10b57cec5SDimitry Andric //===- JumpThreading.cpp - Thread control through conditional blocks ------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file implements the Jump Threading pass. 100b57cec5SDimitry Andric // 110b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 120b57cec5SDimitry Andric 130b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/JumpThreading.h" 140b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 150b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h" 165ffd83dbSDimitry Andric #include "llvm/ADT/MapVector.h" 170b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 180b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 190b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 200b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 210b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 220b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h" 230b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h" 240b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h" 250b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h" 260b57cec5SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h" 270b57cec5SDimitry Andric #include "llvm/Analysis/GuardUtils.h" 280b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h" 290b57cec5SDimitry Andric #include "llvm/Analysis/LazyValueInfo.h" 300b57cec5SDimitry Andric #include "llvm/Analysis/Loads.h" 310b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 32fe6060f1SDimitry Andric #include "llvm/Analysis/MemoryLocation.h" 3306c3fb27SDimitry Andric #include "llvm/Analysis/PostDominators.h" 340b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 35e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h" 360b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 370b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h" 380b57cec5SDimitry Andric #include "llvm/IR/CFG.h" 390b57cec5SDimitry Andric #include "llvm/IR/Constant.h" 400b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h" 410b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 420b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 4306c3fb27SDimitry Andric #include "llvm/IR/DebugInfo.h" 440b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 450b57cec5SDimitry Andric #include "llvm/IR/Function.h" 460b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 470b57cec5SDimitry Andric #include "llvm/IR/Instruction.h" 480b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 490b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 500b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 510b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 520b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h" 530b57cec5SDimitry Andric #include "llvm/IR/Metadata.h" 540b57cec5SDimitry Andric #include "llvm/IR/Module.h" 550b57cec5SDimitry Andric #include "llvm/IR/PassManager.h" 560b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h" 57bdd1243dSDimitry Andric #include "llvm/IR/ProfDataUtils.h" 580b57cec5SDimitry Andric #include "llvm/IR/Type.h" 590b57cec5SDimitry Andric #include "llvm/IR/Use.h" 600b57cec5SDimitry Andric #include "llvm/IR/Value.h" 610b57cec5SDimitry Andric #include "llvm/Support/BlockFrequency.h" 620b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h" 630b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 640b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 650b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 660b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 670b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h" 680b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h" 690b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h" 700b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdater.h" 710b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h" 720b57cec5SDimitry Andric #include <algorithm> 730b57cec5SDimitry Andric #include <cassert> 740b57cec5SDimitry Andric #include <cstdint> 750b57cec5SDimitry Andric #include <iterator> 760b57cec5SDimitry Andric #include <memory> 770b57cec5SDimitry Andric #include <utility> 780b57cec5SDimitry Andric 790b57cec5SDimitry Andric using namespace llvm; 800b57cec5SDimitry Andric using namespace jumpthreading; 810b57cec5SDimitry Andric 820b57cec5SDimitry Andric #define DEBUG_TYPE "jump-threading" 830b57cec5SDimitry Andric 840b57cec5SDimitry Andric STATISTIC(NumThreads, "Number of jumps threaded"); 850b57cec5SDimitry Andric STATISTIC(NumFolds, "Number of terminators folded"); 860b57cec5SDimitry Andric STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi"); 870b57cec5SDimitry Andric 880b57cec5SDimitry Andric static cl::opt<unsigned> 890b57cec5SDimitry Andric BBDuplicateThreshold("jump-threading-threshold", 900b57cec5SDimitry Andric cl::desc("Max block size to duplicate for jump threading"), 910b57cec5SDimitry Andric cl::init(6), cl::Hidden); 920b57cec5SDimitry Andric 930b57cec5SDimitry Andric static cl::opt<unsigned> 940b57cec5SDimitry Andric ImplicationSearchThreshold( 950b57cec5SDimitry Andric "jump-threading-implication-search-threshold", 960b57cec5SDimitry Andric cl::desc("The number of predecessors to search for a stronger " 970b57cec5SDimitry Andric "condition to use to thread over a weaker condition"), 980b57cec5SDimitry Andric cl::init(3), cl::Hidden); 990b57cec5SDimitry Andric 100bdd1243dSDimitry Andric static cl::opt<unsigned> PhiDuplicateThreshold( 101bdd1243dSDimitry Andric "jump-threading-phi-threshold", 102bdd1243dSDimitry Andric cl::desc("Max PHIs in BB to duplicate for jump threading"), cl::init(76), 103bdd1243dSDimitry Andric cl::Hidden); 104bdd1243dSDimitry Andric 1050b57cec5SDimitry Andric static cl::opt<bool> ThreadAcrossLoopHeaders( 1060b57cec5SDimitry Andric "jump-threading-across-loop-headers", 1070b57cec5SDimitry Andric cl::desc("Allow JumpThreading to thread across loop headers, for testing"), 1080b57cec5SDimitry Andric cl::init(false), cl::Hidden); 1090b57cec5SDimitry Andric 11081ad6265SDimitry Andric JumpThreadingPass::JumpThreadingPass(int T) { 1115ffd83dbSDimitry Andric DefaultBBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T); 1120b57cec5SDimitry Andric } 1130b57cec5SDimitry Andric 1140b57cec5SDimitry Andric // Update branch probability information according to conditional 1150b57cec5SDimitry Andric // branch probability. This is usually made possible for cloned branches 1160b57cec5SDimitry Andric // in inline instances by the context specific profile in the caller. 1170b57cec5SDimitry Andric // For instance, 1180b57cec5SDimitry Andric // 1190b57cec5SDimitry Andric // [Block PredBB] 1200b57cec5SDimitry Andric // [Branch PredBr] 1210b57cec5SDimitry Andric // if (t) { 1220b57cec5SDimitry Andric // Block A; 1230b57cec5SDimitry Andric // } else { 1240b57cec5SDimitry Andric // Block B; 1250b57cec5SDimitry Andric // } 1260b57cec5SDimitry Andric // 1270b57cec5SDimitry Andric // [Block BB] 1280b57cec5SDimitry Andric // cond = PN([true, %A], [..., %B]); // PHI node 1290b57cec5SDimitry Andric // [Branch CondBr] 1300b57cec5SDimitry Andric // if (cond) { 1310b57cec5SDimitry Andric // ... // P(cond == true) = 1% 1320b57cec5SDimitry Andric // } 1330b57cec5SDimitry Andric // 1340b57cec5SDimitry Andric // Here we know that when block A is taken, cond must be true, which means 1350b57cec5SDimitry Andric // P(cond == true | A) = 1 1360b57cec5SDimitry Andric // 1370b57cec5SDimitry Andric // Given that P(cond == true) = P(cond == true | A) * P(A) + 1380b57cec5SDimitry Andric // P(cond == true | B) * P(B) 1390b57cec5SDimitry Andric // we get: 1400b57cec5SDimitry Andric // P(cond == true ) = P(A) + P(cond == true | B) * P(B) 1410b57cec5SDimitry Andric // 1420b57cec5SDimitry Andric // which gives us: 1430b57cec5SDimitry Andric // P(A) is less than P(cond == true), i.e. 1440b57cec5SDimitry Andric // P(t == true) <= P(cond == true) 1450b57cec5SDimitry Andric // 1460b57cec5SDimitry Andric // In other words, if we know P(cond == true) is unlikely, we know 1470b57cec5SDimitry Andric // that P(t == true) is also unlikely. 1480b57cec5SDimitry Andric // 1490b57cec5SDimitry Andric static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) { 1500b57cec5SDimitry Andric BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 1510b57cec5SDimitry Andric if (!CondBr) 1520b57cec5SDimitry Andric return; 1530b57cec5SDimitry Andric 1540b57cec5SDimitry Andric uint64_t TrueWeight, FalseWeight; 155bdd1243dSDimitry Andric if (!extractBranchWeights(*CondBr, TrueWeight, FalseWeight)) 1560b57cec5SDimitry Andric return; 1570b57cec5SDimitry Andric 1585ffd83dbSDimitry Andric if (TrueWeight + FalseWeight == 0) 1595ffd83dbSDimitry Andric // Zero branch_weights do not give a hint for getting branch probabilities. 1605ffd83dbSDimitry Andric // Technically it would result in division by zero denominator, which is 1615ffd83dbSDimitry Andric // TrueWeight + FalseWeight. 1625ffd83dbSDimitry Andric return; 1635ffd83dbSDimitry Andric 1640b57cec5SDimitry Andric // Returns the outgoing edge of the dominating predecessor block 1650b57cec5SDimitry Andric // that leads to the PhiNode's incoming block: 1660b57cec5SDimitry Andric auto GetPredOutEdge = 1670b57cec5SDimitry Andric [](BasicBlock *IncomingBB, 1680b57cec5SDimitry Andric BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> { 1690b57cec5SDimitry Andric auto *PredBB = IncomingBB; 1700b57cec5SDimitry Andric auto *SuccBB = PhiBB; 1718bcb0991SDimitry Andric SmallPtrSet<BasicBlock *, 16> Visited; 1720b57cec5SDimitry Andric while (true) { 1730b57cec5SDimitry Andric BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()); 1740b57cec5SDimitry Andric if (PredBr && PredBr->isConditional()) 1750b57cec5SDimitry Andric return {PredBB, SuccBB}; 1768bcb0991SDimitry Andric Visited.insert(PredBB); 1770b57cec5SDimitry Andric auto *SinglePredBB = PredBB->getSinglePredecessor(); 1780b57cec5SDimitry Andric if (!SinglePredBB) 1790b57cec5SDimitry Andric return {nullptr, nullptr}; 1808bcb0991SDimitry Andric 1818bcb0991SDimitry Andric // Stop searching when SinglePredBB has been visited. It means we see 1828bcb0991SDimitry Andric // an unreachable loop. 1838bcb0991SDimitry Andric if (Visited.count(SinglePredBB)) 1848bcb0991SDimitry Andric return {nullptr, nullptr}; 1858bcb0991SDimitry Andric 1860b57cec5SDimitry Andric SuccBB = PredBB; 1870b57cec5SDimitry Andric PredBB = SinglePredBB; 1880b57cec5SDimitry Andric } 1890b57cec5SDimitry Andric }; 1900b57cec5SDimitry Andric 1910b57cec5SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1920b57cec5SDimitry Andric Value *PhiOpnd = PN->getIncomingValue(i); 1930b57cec5SDimitry Andric ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd); 1940b57cec5SDimitry Andric 1950b57cec5SDimitry Andric if (!CI || !CI->getType()->isIntegerTy(1)) 1960b57cec5SDimitry Andric continue; 1970b57cec5SDimitry Andric 1985ffd83dbSDimitry Andric BranchProbability BP = 1995ffd83dbSDimitry Andric (CI->isOne() ? BranchProbability::getBranchProbability( 2000b57cec5SDimitry Andric TrueWeight, TrueWeight + FalseWeight) 2010b57cec5SDimitry Andric : BranchProbability::getBranchProbability( 2020b57cec5SDimitry Andric FalseWeight, TrueWeight + FalseWeight)); 2030b57cec5SDimitry Andric 2040b57cec5SDimitry Andric auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB); 2050b57cec5SDimitry Andric if (!PredOutEdge.first) 2060b57cec5SDimitry Andric return; 2070b57cec5SDimitry Andric 2080b57cec5SDimitry Andric BasicBlock *PredBB = PredOutEdge.first; 2098bcb0991SDimitry Andric BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()); 2108bcb0991SDimitry Andric if (!PredBr) 2118bcb0991SDimitry Andric return; 2120b57cec5SDimitry Andric 2130b57cec5SDimitry Andric uint64_t PredTrueWeight, PredFalseWeight; 2140b57cec5SDimitry Andric // FIXME: We currently only set the profile data when it is missing. 2150b57cec5SDimitry Andric // With PGO, this can be used to refine even existing profile data with 2160b57cec5SDimitry Andric // context information. This needs to be done after more performance 2170b57cec5SDimitry Andric // testing. 218bdd1243dSDimitry Andric if (extractBranchWeights(*PredBr, PredTrueWeight, PredFalseWeight)) 2190b57cec5SDimitry Andric continue; 2200b57cec5SDimitry Andric 2210b57cec5SDimitry Andric // We can not infer anything useful when BP >= 50%, because BP is the 2220b57cec5SDimitry Andric // upper bound probability value. 2230b57cec5SDimitry Andric if (BP >= BranchProbability(50, 100)) 2240b57cec5SDimitry Andric continue; 2250b57cec5SDimitry Andric 2265f757f3fSDimitry Andric uint32_t Weights[2]; 2270b57cec5SDimitry Andric if (PredBr->getSuccessor(0) == PredOutEdge.second) { 2285f757f3fSDimitry Andric Weights[0] = BP.getNumerator(); 2295f757f3fSDimitry Andric Weights[1] = BP.getCompl().getNumerator(); 2300b57cec5SDimitry Andric } else { 2315f757f3fSDimitry Andric Weights[0] = BP.getCompl().getNumerator(); 2325f757f3fSDimitry Andric Weights[1] = BP.getNumerator(); 2330b57cec5SDimitry Andric } 234*0fca6ea1SDimitry Andric setBranchWeights(*PredBr, Weights, hasBranchWeightOrigin(*PredBr)); 2350b57cec5SDimitry Andric } 2360b57cec5SDimitry Andric } 2370b57cec5SDimitry Andric 2380b57cec5SDimitry Andric PreservedAnalyses JumpThreadingPass::run(Function &F, 2390b57cec5SDimitry Andric FunctionAnalysisManager &AM) { 240e8d8bef9SDimitry Andric auto &TTI = AM.getResult<TargetIRAnalysis>(F); 241e8d8bef9SDimitry Andric // Jump Threading has no sense for the targets with divergent CF 24206c3fb27SDimitry Andric if (TTI.hasBranchDivergence(&F)) 243e8d8bef9SDimitry Andric return PreservedAnalyses::all(); 2440b57cec5SDimitry Andric auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 2450b57cec5SDimitry Andric auto &LVI = AM.getResult<LazyValueAnalysis>(F); 2460b57cec5SDimitry Andric auto &AA = AM.getResult<AAManager>(F); 24706c3fb27SDimitry Andric auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 2480b57cec5SDimitry Andric 24906c3fb27SDimitry Andric bool Changed = 25006c3fb27SDimitry Andric runImpl(F, &AM, &TLI, &TTI, &LVI, &AA, 25106c3fb27SDimitry Andric std::make_unique<DomTreeUpdater>( 25206c3fb27SDimitry Andric &DT, nullptr, DomTreeUpdater::UpdateStrategy::Lazy), 25306c3fb27SDimitry Andric std::nullopt, std::nullopt); 2540b57cec5SDimitry Andric 2550b57cec5SDimitry Andric if (!Changed) 2560b57cec5SDimitry Andric return PreservedAnalyses::all(); 25706c3fb27SDimitry Andric 25806c3fb27SDimitry Andric 25906c3fb27SDimitry Andric getDomTreeUpdater()->flush(); 26006c3fb27SDimitry Andric 26106c3fb27SDimitry Andric #if defined(EXPENSIVE_CHECKS) 26206c3fb27SDimitry Andric assert(getDomTreeUpdater()->getDomTree().verify( 26306c3fb27SDimitry Andric DominatorTree::VerificationLevel::Full) && 26406c3fb27SDimitry Andric "DT broken after JumpThreading"); 26506c3fb27SDimitry Andric assert((!getDomTreeUpdater()->hasPostDomTree() || 26606c3fb27SDimitry Andric getDomTreeUpdater()->getPostDomTree().verify( 26706c3fb27SDimitry Andric PostDominatorTree::VerificationLevel::Full)) && 26806c3fb27SDimitry Andric "PDT broken after JumpThreading"); 26906c3fb27SDimitry Andric #else 27006c3fb27SDimitry Andric assert(getDomTreeUpdater()->getDomTree().verify( 27106c3fb27SDimitry Andric DominatorTree::VerificationLevel::Fast) && 27206c3fb27SDimitry Andric "DT broken after JumpThreading"); 27306c3fb27SDimitry Andric assert((!getDomTreeUpdater()->hasPostDomTree() || 27406c3fb27SDimitry Andric getDomTreeUpdater()->getPostDomTree().verify( 27506c3fb27SDimitry Andric PostDominatorTree::VerificationLevel::Fast)) && 27606c3fb27SDimitry Andric "PDT broken after JumpThreading"); 27706c3fb27SDimitry Andric #endif 27806c3fb27SDimitry Andric 27906c3fb27SDimitry Andric return getPreservedAnalysis(); 2800b57cec5SDimitry Andric } 2810b57cec5SDimitry Andric 28206c3fb27SDimitry Andric bool JumpThreadingPass::runImpl(Function &F_, FunctionAnalysisManager *FAM_, 28306c3fb27SDimitry Andric TargetLibraryInfo *TLI_, 284349cc55cSDimitry Andric TargetTransformInfo *TTI_, LazyValueInfo *LVI_, 28506c3fb27SDimitry Andric AliasAnalysis *AA_, 28606c3fb27SDimitry Andric std::unique_ptr<DomTreeUpdater> DTU_, 28706c3fb27SDimitry Andric std::optional<BlockFrequencyInfo *> BFI_, 28806c3fb27SDimitry Andric std::optional<BranchProbabilityInfo *> BPI_) { 28906c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "Jump threading on function '" << F_.getName() << "'\n"); 29006c3fb27SDimitry Andric F = &F_; 29106c3fb27SDimitry Andric FAM = FAM_; 2920b57cec5SDimitry Andric TLI = TLI_; 293349cc55cSDimitry Andric TTI = TTI_; 2940b57cec5SDimitry Andric LVI = LVI_; 2950b57cec5SDimitry Andric AA = AA_; 29606c3fb27SDimitry Andric DTU = std::move(DTU_); 29706c3fb27SDimitry Andric BFI = BFI_; 29806c3fb27SDimitry Andric BPI = BPI_; 29906c3fb27SDimitry Andric auto *GuardDecl = F->getParent()->getFunction( 3000b57cec5SDimitry Andric Intrinsic::getName(Intrinsic::experimental_guard)); 3010b57cec5SDimitry Andric HasGuards = GuardDecl && !GuardDecl->use_empty(); 3020b57cec5SDimitry Andric 3035ffd83dbSDimitry Andric // Reduce the number of instructions duplicated when optimizing strictly for 3045ffd83dbSDimitry Andric // size. 3055ffd83dbSDimitry Andric if (BBDuplicateThreshold.getNumOccurrences()) 3065ffd83dbSDimitry Andric BBDupThreshold = BBDuplicateThreshold; 30706c3fb27SDimitry Andric else if (F->hasFnAttribute(Attribute::MinSize)) 3085ffd83dbSDimitry Andric BBDupThreshold = 3; 3095ffd83dbSDimitry Andric else 3105ffd83dbSDimitry Andric BBDupThreshold = DefaultBBDupThreshold; 3115ffd83dbSDimitry Andric 3120b57cec5SDimitry Andric // JumpThreading must not processes blocks unreachable from entry. It's a 3130b57cec5SDimitry Andric // waste of compute time and can potentially lead to hangs. 3140b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 16> Unreachable; 3150b57cec5SDimitry Andric assert(DTU && "DTU isn't passed into JumpThreading before using it."); 3160b57cec5SDimitry Andric assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed."); 3170b57cec5SDimitry Andric DominatorTree &DT = DTU->getDomTree(); 31806c3fb27SDimitry Andric for (auto &BB : *F) 3190b57cec5SDimitry Andric if (!DT.isReachableFromEntry(&BB)) 3200b57cec5SDimitry Andric Unreachable.insert(&BB); 3210b57cec5SDimitry Andric 3220b57cec5SDimitry Andric if (!ThreadAcrossLoopHeaders) 32306c3fb27SDimitry Andric findLoopHeaders(*F); 3240b57cec5SDimitry Andric 3250b57cec5SDimitry Andric bool EverChanged = false; 3260b57cec5SDimitry Andric bool Changed; 3270b57cec5SDimitry Andric do { 3280b57cec5SDimitry Andric Changed = false; 32906c3fb27SDimitry Andric for (auto &BB : *F) { 3300b57cec5SDimitry Andric if (Unreachable.count(&BB)) 3310b57cec5SDimitry Andric continue; 332e8d8bef9SDimitry Andric while (processBlock(&BB)) // Thread all of the branches we can over BB. 33306c3fb27SDimitry Andric Changed = ChangedSinceLastAnalysisUpdate = true; 3345ffd83dbSDimitry Andric 3355ffd83dbSDimitry Andric // Jump threading may have introduced redundant debug values into BB 3365ffd83dbSDimitry Andric // which should be removed. 3375ffd83dbSDimitry Andric if (Changed) 3385ffd83dbSDimitry Andric RemoveRedundantDbgInstrs(&BB); 3395ffd83dbSDimitry Andric 3400b57cec5SDimitry Andric // Stop processing BB if it's the entry or is now deleted. The following 3410b57cec5SDimitry Andric // routines attempt to eliminate BB and locating a suitable replacement 3420b57cec5SDimitry Andric // for the entry is non-trivial. 34306c3fb27SDimitry Andric if (&BB == &F->getEntryBlock() || DTU->isBBPendingDeletion(&BB)) 3440b57cec5SDimitry Andric continue; 3450b57cec5SDimitry Andric 3460b57cec5SDimitry Andric if (pred_empty(&BB)) { 347e8d8bef9SDimitry Andric // When processBlock makes BB unreachable it doesn't bother to fix up 3480b57cec5SDimitry Andric // the instructions in it. We must remove BB to prevent invalid IR. 3490b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName() 3500b57cec5SDimitry Andric << "' with terminator: " << *BB.getTerminator() 3510b57cec5SDimitry Andric << '\n'); 3520b57cec5SDimitry Andric LoopHeaders.erase(&BB); 3530b57cec5SDimitry Andric LVI->eraseBlock(&BB); 35406c3fb27SDimitry Andric DeleteDeadBlock(&BB, DTU.get()); 35506c3fb27SDimitry Andric Changed = ChangedSinceLastAnalysisUpdate = true; 3560b57cec5SDimitry Andric continue; 3570b57cec5SDimitry Andric } 3580b57cec5SDimitry Andric 359e8d8bef9SDimitry Andric // processBlock doesn't thread BBs with unconditional TIs. However, if BB 3600b57cec5SDimitry Andric // is "almost empty", we attempt to merge BB with its sole successor. 3610b57cec5SDimitry Andric auto *BI = dyn_cast<BranchInst>(BB.getTerminator()); 3625ffd83dbSDimitry Andric if (BI && BI->isUnconditional()) { 3635ffd83dbSDimitry Andric BasicBlock *Succ = BI->getSuccessor(0); 3645ffd83dbSDimitry Andric if ( 3650b57cec5SDimitry Andric // The terminator must be the only non-phi instruction in BB. 366fe6060f1SDimitry Andric BB.getFirstNonPHIOrDbg(true)->isTerminator() && 3670b57cec5SDimitry Andric // Don't alter Loop headers and latches to ensure another pass can 3680b57cec5SDimitry Andric // detect and transform nested loops later. 3695ffd83dbSDimitry Andric !LoopHeaders.count(&BB) && !LoopHeaders.count(Succ) && 37006c3fb27SDimitry Andric TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU.get())) { 3715ffd83dbSDimitry Andric RemoveRedundantDbgInstrs(Succ); 3720b57cec5SDimitry Andric // BB is valid for cleanup here because we passed in DTU. F remains 3730b57cec5SDimitry Andric // BB's parent until a DTU->getDomTree() event. 3740b57cec5SDimitry Andric LVI->eraseBlock(&BB); 37506c3fb27SDimitry Andric Changed = ChangedSinceLastAnalysisUpdate = true; 3760b57cec5SDimitry Andric } 3770b57cec5SDimitry Andric } 3785ffd83dbSDimitry Andric } 3790b57cec5SDimitry Andric EverChanged |= Changed; 3800b57cec5SDimitry Andric } while (Changed); 3810b57cec5SDimitry Andric 3820b57cec5SDimitry Andric LoopHeaders.clear(); 3830b57cec5SDimitry Andric return EverChanged; 3840b57cec5SDimitry Andric } 3850b57cec5SDimitry Andric 3860b57cec5SDimitry Andric // Replace uses of Cond with ToVal when safe to do so. If all uses are 3870b57cec5SDimitry Andric // replaced, we can remove Cond. We cannot blindly replace all uses of Cond 3880b57cec5SDimitry Andric // because we may incorrectly replace uses when guards/assumes are uses of 3890b57cec5SDimitry Andric // of `Cond` and we used the guards/assume to reason about the `Cond` value 3900b57cec5SDimitry Andric // at the end of block. RAUW unconditionally replaces all uses 3910b57cec5SDimitry Andric // including the guards/assumes themselves and the uses before the 3920b57cec5SDimitry Andric // guard/assume. 39381ad6265SDimitry Andric static bool replaceFoldableUses(Instruction *Cond, Value *ToVal, 39481ad6265SDimitry Andric BasicBlock *KnownAtEndOfBB) { 39581ad6265SDimitry Andric bool Changed = false; 3960b57cec5SDimitry Andric assert(Cond->getType() == ToVal->getType()); 3970b57cec5SDimitry Andric // We can unconditionally replace all uses in non-local blocks (i.e. uses 3980b57cec5SDimitry Andric // strictly dominated by BB), since LVI information is true from the 3990b57cec5SDimitry Andric // terminator of BB. 40081ad6265SDimitry Andric if (Cond->getParent() == KnownAtEndOfBB) 40181ad6265SDimitry Andric Changed |= replaceNonLocalUsesWith(Cond, ToVal); 40281ad6265SDimitry Andric for (Instruction &I : reverse(*KnownAtEndOfBB)) { 4035f757f3fSDimitry Andric // Replace any debug-info record users of Cond with ToVal. 404*0fca6ea1SDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) 405*0fca6ea1SDimitry Andric DVR.replaceVariableLocationOp(Cond, ToVal, true); 4065f757f3fSDimitry Andric 4070b57cec5SDimitry Andric // Reached the Cond whose uses we are trying to replace, so there are no 4080b57cec5SDimitry Andric // more uses. 4090b57cec5SDimitry Andric if (&I == Cond) 4100b57cec5SDimitry Andric break; 4110b57cec5SDimitry Andric // We only replace uses in instructions that are guaranteed to reach the end 4120b57cec5SDimitry Andric // of BB, where we know Cond is ToVal. 4130b57cec5SDimitry Andric if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 4140b57cec5SDimitry Andric break; 41581ad6265SDimitry Andric Changed |= I.replaceUsesOfWith(Cond, ToVal); 4160b57cec5SDimitry Andric } 41781ad6265SDimitry Andric if (Cond->use_empty() && !Cond->mayHaveSideEffects()) { 4180b57cec5SDimitry Andric Cond->eraseFromParent(); 41981ad6265SDimitry Andric Changed = true; 42081ad6265SDimitry Andric } 42181ad6265SDimitry Andric return Changed; 4220b57cec5SDimitry Andric } 4230b57cec5SDimitry Andric 4240b57cec5SDimitry Andric /// Return the cost of duplicating a piece of this block from first non-phi 4250b57cec5SDimitry Andric /// and before StopAt instruction to thread across it. Stop scanning the block 4260b57cec5SDimitry Andric /// when exceeding the threshold. If duplication is impossible, returns ~0U. 427349cc55cSDimitry Andric static unsigned getJumpThreadDuplicationCost(const TargetTransformInfo *TTI, 428349cc55cSDimitry Andric BasicBlock *BB, 4290b57cec5SDimitry Andric Instruction *StopAt, 4300b57cec5SDimitry Andric unsigned Threshold) { 4310b57cec5SDimitry Andric assert(StopAt->getParent() == BB && "Not an instruction from proper BB?"); 432bdd1243dSDimitry Andric 433bdd1243dSDimitry Andric // Do not duplicate the BB if it has a lot of PHI nodes. 434bdd1243dSDimitry Andric // If a threadable chain is too long then the number of PHI nodes can add up, 435bdd1243dSDimitry Andric // leading to a substantial increase in compile time when rewriting the SSA. 436bdd1243dSDimitry Andric unsigned PhiCount = 0; 437bdd1243dSDimitry Andric Instruction *FirstNonPHI = nullptr; 438bdd1243dSDimitry Andric for (Instruction &I : *BB) { 439bdd1243dSDimitry Andric if (!isa<PHINode>(&I)) { 440bdd1243dSDimitry Andric FirstNonPHI = &I; 441bdd1243dSDimitry Andric break; 442bdd1243dSDimitry Andric } 443bdd1243dSDimitry Andric if (++PhiCount > PhiDuplicateThreshold) 444bdd1243dSDimitry Andric return ~0U; 445bdd1243dSDimitry Andric } 446bdd1243dSDimitry Andric 4470b57cec5SDimitry Andric /// Ignore PHI nodes, these will be flattened when duplication happens. 448bdd1243dSDimitry Andric BasicBlock::const_iterator I(FirstNonPHI); 4490b57cec5SDimitry Andric 4500b57cec5SDimitry Andric // FIXME: THREADING will delete values that are just used to compute the 4510b57cec5SDimitry Andric // branch, so they shouldn't count against the duplication cost. 4520b57cec5SDimitry Andric 4530b57cec5SDimitry Andric unsigned Bonus = 0; 4540b57cec5SDimitry Andric if (BB->getTerminator() == StopAt) { 4550b57cec5SDimitry Andric // Threading through a switch statement is particularly profitable. If this 4560b57cec5SDimitry Andric // block ends in a switch, decrease its cost to make it more likely to 4570b57cec5SDimitry Andric // happen. 4580b57cec5SDimitry Andric if (isa<SwitchInst>(StopAt)) 4590b57cec5SDimitry Andric Bonus = 6; 4600b57cec5SDimitry Andric 4610b57cec5SDimitry Andric // The same holds for indirect branches, but slightly more so. 4620b57cec5SDimitry Andric if (isa<IndirectBrInst>(StopAt)) 4630b57cec5SDimitry Andric Bonus = 8; 4640b57cec5SDimitry Andric } 4650b57cec5SDimitry Andric 4660b57cec5SDimitry Andric // Bump the threshold up so the early exit from the loop doesn't skip the 4670b57cec5SDimitry Andric // terminator-based Size adjustment at the end. 4680b57cec5SDimitry Andric Threshold += Bonus; 4690b57cec5SDimitry Andric 4700b57cec5SDimitry Andric // Sum up the cost of each instruction until we get to the terminator. Don't 4710b57cec5SDimitry Andric // include the terminator because the copy won't include it. 4720b57cec5SDimitry Andric unsigned Size = 0; 4730b57cec5SDimitry Andric for (; &*I != StopAt; ++I) { 4740b57cec5SDimitry Andric 4750b57cec5SDimitry Andric // Stop scanning the block if we've reached the threshold. 4760b57cec5SDimitry Andric if (Size > Threshold) 4770b57cec5SDimitry Andric return Size; 4780b57cec5SDimitry Andric 4790b57cec5SDimitry Andric // Bail out if this instruction gives back a token type, it is not possible 4800b57cec5SDimitry Andric // to duplicate it if it is used outside this BB. 4810b57cec5SDimitry Andric if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB)) 4820b57cec5SDimitry Andric return ~0U; 4830b57cec5SDimitry Andric 484349cc55cSDimitry Andric // Blocks with NoDuplicate are modelled as having infinite cost, so they 485349cc55cSDimitry Andric // are never duplicated. 486349cc55cSDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(I)) 487349cc55cSDimitry Andric if (CI->cannotDuplicate() || CI->isConvergent()) 488349cc55cSDimitry Andric return ~0U; 489349cc55cSDimitry Andric 490bdd1243dSDimitry Andric if (TTI->getInstructionCost(&*I, TargetTransformInfo::TCK_SizeAndLatency) == 491bdd1243dSDimitry Andric TargetTransformInfo::TCC_Free) 492349cc55cSDimitry Andric continue; 493349cc55cSDimitry Andric 4940b57cec5SDimitry Andric // All other instructions count for at least one unit. 4950b57cec5SDimitry Andric ++Size; 4960b57cec5SDimitry Andric 4970b57cec5SDimitry Andric // Calls are more expensive. If they are non-intrinsic calls, we model them 4980b57cec5SDimitry Andric // as having cost of 4. If they are a non-vector intrinsic, we model them 4990b57cec5SDimitry Andric // as having cost of 2 total, and if they are a vector intrinsic, we model 5000b57cec5SDimitry Andric // them as having cost 1. 5010b57cec5SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(I)) { 502349cc55cSDimitry Andric if (!isa<IntrinsicInst>(CI)) 5030b57cec5SDimitry Andric Size += 3; 5040b57cec5SDimitry Andric else if (!CI->getType()->isVectorTy()) 5050b57cec5SDimitry Andric Size += 1; 5060b57cec5SDimitry Andric } 5070b57cec5SDimitry Andric } 5080b57cec5SDimitry Andric 5090b57cec5SDimitry Andric return Size > Bonus ? Size - Bonus : 0; 5100b57cec5SDimitry Andric } 5110b57cec5SDimitry Andric 512e8d8bef9SDimitry Andric /// findLoopHeaders - We do not want jump threading to turn proper loop 5130b57cec5SDimitry Andric /// structures into irreducible loops. Doing this breaks up the loop nesting 5140b57cec5SDimitry Andric /// hierarchy and pessimizes later transformations. To prevent this from 5150b57cec5SDimitry Andric /// happening, we first have to find the loop headers. Here we approximate this 5160b57cec5SDimitry Andric /// by finding targets of backedges in the CFG. 5170b57cec5SDimitry Andric /// 5180b57cec5SDimitry Andric /// Note that there definitely are cases when we want to allow threading of 5190b57cec5SDimitry Andric /// edges across a loop header. For example, threading a jump from outside the 5200b57cec5SDimitry Andric /// loop (the preheader) to an exit block of the loop is definitely profitable. 5210b57cec5SDimitry Andric /// It is also almost always profitable to thread backedges from within the loop 5220b57cec5SDimitry Andric /// to exit blocks, and is often profitable to thread backedges to other blocks 5230b57cec5SDimitry Andric /// within the loop (forming a nested loop). This simple analysis is not rich 5240b57cec5SDimitry Andric /// enough to track all of these properties and keep it up-to-date as the CFG 5250b57cec5SDimitry Andric /// mutates, so we don't allow any of these transformations. 526e8d8bef9SDimitry Andric void JumpThreadingPass::findLoopHeaders(Function &F) { 5270b57cec5SDimitry Andric SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges; 5280b57cec5SDimitry Andric FindFunctionBackedges(F, Edges); 5290b57cec5SDimitry Andric 5300b57cec5SDimitry Andric for (const auto &Edge : Edges) 5310b57cec5SDimitry Andric LoopHeaders.insert(Edge.second); 5320b57cec5SDimitry Andric } 5330b57cec5SDimitry Andric 5340b57cec5SDimitry Andric /// getKnownConstant - Helper method to determine if we can thread over a 5350b57cec5SDimitry Andric /// terminator with the given value as its condition, and if so what value to 5360b57cec5SDimitry Andric /// use for that. What kind of value this is depends on whether we want an 5370b57cec5SDimitry Andric /// integer or a block address, but an undef is always accepted. 5380b57cec5SDimitry Andric /// Returns null if Val is null or not an appropriate constant. 5390b57cec5SDimitry Andric static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) { 5400b57cec5SDimitry Andric if (!Val) 5410b57cec5SDimitry Andric return nullptr; 5420b57cec5SDimitry Andric 5430b57cec5SDimitry Andric // Undef is "known" enough. 5440b57cec5SDimitry Andric if (UndefValue *U = dyn_cast<UndefValue>(Val)) 5450b57cec5SDimitry Andric return U; 5460b57cec5SDimitry Andric 5470b57cec5SDimitry Andric if (Preference == WantBlockAddress) 5480b57cec5SDimitry Andric return dyn_cast<BlockAddress>(Val->stripPointerCasts()); 5490b57cec5SDimitry Andric 5500b57cec5SDimitry Andric return dyn_cast<ConstantInt>(Val); 5510b57cec5SDimitry Andric } 5520b57cec5SDimitry Andric 553e8d8bef9SDimitry Andric /// computeValueKnownInPredecessors - Given a basic block BB and a value V, see 5540b57cec5SDimitry Andric /// if we can infer that the value is a known ConstantInt/BlockAddress or undef 5550b57cec5SDimitry Andric /// in any of our predecessors. If so, return the known list of value and pred 5560b57cec5SDimitry Andric /// BB in the result vector. 5570b57cec5SDimitry Andric /// 5580b57cec5SDimitry Andric /// This returns true if there were any known values. 559e8d8bef9SDimitry Andric bool JumpThreadingPass::computeValueKnownInPredecessorsImpl( 5600b57cec5SDimitry Andric Value *V, BasicBlock *BB, PredValueInfo &Result, 561*0fca6ea1SDimitry Andric ConstantPreference Preference, SmallPtrSet<Value *, 4> &RecursionSet, 5620b57cec5SDimitry Andric Instruction *CxtI) { 563*0fca6ea1SDimitry Andric const DataLayout &DL = BB->getDataLayout(); 5645f757f3fSDimitry Andric 5650b57cec5SDimitry Andric // This method walks up use-def chains recursively. Because of this, we could 5660b57cec5SDimitry Andric // get into an infinite loop going around loops in the use-def chain. To 5670b57cec5SDimitry Andric // prevent this, keep track of what (value, block) pairs we've already visited 5680b57cec5SDimitry Andric // and terminate the search if we loop back to them 5695ffd83dbSDimitry Andric if (!RecursionSet.insert(V).second) 5700b57cec5SDimitry Andric return false; 5710b57cec5SDimitry Andric 5720b57cec5SDimitry Andric // If V is a constant, then it is known in all predecessors. 5730b57cec5SDimitry Andric if (Constant *KC = getKnownConstant(V, Preference)) { 5740b57cec5SDimitry Andric for (BasicBlock *Pred : predecessors(BB)) 5755ffd83dbSDimitry Andric Result.emplace_back(KC, Pred); 5760b57cec5SDimitry Andric 5770b57cec5SDimitry Andric return !Result.empty(); 5780b57cec5SDimitry Andric } 5790b57cec5SDimitry Andric 5800b57cec5SDimitry Andric // If V is a non-instruction value, or an instruction in a different block, 5810b57cec5SDimitry Andric // then it can't be derived from a PHI. 5820b57cec5SDimitry Andric Instruction *I = dyn_cast<Instruction>(V); 5830b57cec5SDimitry Andric if (!I || I->getParent() != BB) { 5840b57cec5SDimitry Andric 585bdd1243dSDimitry Andric // Okay, if this is a live-in value, see if it has a known value at the any 586bdd1243dSDimitry Andric // edge from our predecessors. 5870b57cec5SDimitry Andric for (BasicBlock *P : predecessors(BB)) { 588bdd1243dSDimitry Andric using namespace PatternMatch; 5890b57cec5SDimitry Andric // If the value is known by LazyValueInfo to be a constant in a 5900b57cec5SDimitry Andric // predecessor, use that information to try to thread this block. 5910b57cec5SDimitry Andric Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI); 592bdd1243dSDimitry Andric // If I is a non-local compare-with-constant instruction, use more-rich 593bdd1243dSDimitry Andric // 'getPredicateOnEdge' method. This would be able to handle value 594bdd1243dSDimitry Andric // inequalities better, for example if the compare is "X < 4" and "X < 3" 595bdd1243dSDimitry Andric // is known true but "X < 4" itself is not available. 596bdd1243dSDimitry Andric CmpInst::Predicate Pred; 597bdd1243dSDimitry Andric Value *Val; 598bdd1243dSDimitry Andric Constant *Cst; 599*0fca6ea1SDimitry Andric if (!PredCst && match(V, m_Cmp(Pred, m_Value(Val), m_Constant(Cst)))) 600*0fca6ea1SDimitry Andric PredCst = LVI->getPredicateOnEdge(Pred, Val, Cst, P, BB, CxtI); 6010b57cec5SDimitry Andric if (Constant *KC = getKnownConstant(PredCst, Preference)) 6025ffd83dbSDimitry Andric Result.emplace_back(KC, P); 6030b57cec5SDimitry Andric } 6040b57cec5SDimitry Andric 6050b57cec5SDimitry Andric return !Result.empty(); 6060b57cec5SDimitry Andric } 6070b57cec5SDimitry Andric 6080b57cec5SDimitry Andric /// If I is a PHI node, then we know the incoming values for any constants. 6090b57cec5SDimitry Andric if (PHINode *PN = dyn_cast<PHINode>(I)) { 6100b57cec5SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6110b57cec5SDimitry Andric Value *InVal = PN->getIncomingValue(i); 6120b57cec5SDimitry Andric if (Constant *KC = getKnownConstant(InVal, Preference)) { 6135ffd83dbSDimitry Andric Result.emplace_back(KC, PN->getIncomingBlock(i)); 6140b57cec5SDimitry Andric } else { 6150b57cec5SDimitry Andric Constant *CI = LVI->getConstantOnEdge(InVal, 6160b57cec5SDimitry Andric PN->getIncomingBlock(i), 6170b57cec5SDimitry Andric BB, CxtI); 6180b57cec5SDimitry Andric if (Constant *KC = getKnownConstant(CI, Preference)) 6195ffd83dbSDimitry Andric Result.emplace_back(KC, PN->getIncomingBlock(i)); 6200b57cec5SDimitry Andric } 6210b57cec5SDimitry Andric } 6220b57cec5SDimitry Andric 6230b57cec5SDimitry Andric return !Result.empty(); 6240b57cec5SDimitry Andric } 6250b57cec5SDimitry Andric 626e8d8bef9SDimitry Andric // Handle Cast instructions. 6270b57cec5SDimitry Andric if (CastInst *CI = dyn_cast<CastInst>(I)) { 6280b57cec5SDimitry Andric Value *Source = CI->getOperand(0); 6295f757f3fSDimitry Andric PredValueInfoTy Vals; 6305f757f3fSDimitry Andric computeValueKnownInPredecessorsImpl(Source, BB, Vals, Preference, 6310b57cec5SDimitry Andric RecursionSet, CxtI); 6325f757f3fSDimitry Andric if (Vals.empty()) 6330b57cec5SDimitry Andric return false; 6340b57cec5SDimitry Andric 6350b57cec5SDimitry Andric // Convert the known values. 6365f757f3fSDimitry Andric for (auto &Val : Vals) 6375f757f3fSDimitry Andric if (Constant *Folded = ConstantFoldCastOperand(CI->getOpcode(), Val.first, 6385f757f3fSDimitry Andric CI->getType(), DL)) 6395f757f3fSDimitry Andric Result.emplace_back(Folded, Val.second); 6400b57cec5SDimitry Andric 6415f757f3fSDimitry Andric return !Result.empty(); 6420b57cec5SDimitry Andric } 6430b57cec5SDimitry Andric 644e8d8bef9SDimitry Andric if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) { 645e8d8bef9SDimitry Andric Value *Source = FI->getOperand(0); 646e8d8bef9SDimitry Andric computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference, 647e8d8bef9SDimitry Andric RecursionSet, CxtI); 648e8d8bef9SDimitry Andric 649e8d8bef9SDimitry Andric erase_if(Result, [](auto &Pair) { 650e8d8bef9SDimitry Andric return !isGuaranteedNotToBeUndefOrPoison(Pair.first); 651e8d8bef9SDimitry Andric }); 652e8d8bef9SDimitry Andric 653e8d8bef9SDimitry Andric return !Result.empty(); 654e8d8bef9SDimitry Andric } 655e8d8bef9SDimitry Andric 6560b57cec5SDimitry Andric // Handle some boolean conditions. 6570b57cec5SDimitry Andric if (I->getType()->getPrimitiveSizeInBits() == 1) { 658fe6060f1SDimitry Andric using namespace PatternMatch; 65904eeddc0SDimitry Andric if (Preference != WantInteger) 66004eeddc0SDimitry Andric return false; 6610b57cec5SDimitry Andric // X | true -> true 6620b57cec5SDimitry Andric // X & false -> false 663fe6060f1SDimitry Andric Value *Op0, *Op1; 664fe6060f1SDimitry Andric if (match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))) || 665fe6060f1SDimitry Andric match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 6660b57cec5SDimitry Andric PredValueInfoTy LHSVals, RHSVals; 6670b57cec5SDimitry Andric 668fe6060f1SDimitry Andric computeValueKnownInPredecessorsImpl(Op0, BB, LHSVals, WantInteger, 669fe6060f1SDimitry Andric RecursionSet, CxtI); 670fe6060f1SDimitry Andric computeValueKnownInPredecessorsImpl(Op1, BB, RHSVals, WantInteger, 671fe6060f1SDimitry Andric RecursionSet, CxtI); 6720b57cec5SDimitry Andric 6730b57cec5SDimitry Andric if (LHSVals.empty() && RHSVals.empty()) 6740b57cec5SDimitry Andric return false; 6750b57cec5SDimitry Andric 6760b57cec5SDimitry Andric ConstantInt *InterestingVal; 677fe6060f1SDimitry Andric if (match(I, m_LogicalOr())) 6780b57cec5SDimitry Andric InterestingVal = ConstantInt::getTrue(I->getContext()); 6790b57cec5SDimitry Andric else 6800b57cec5SDimitry Andric InterestingVal = ConstantInt::getFalse(I->getContext()); 6810b57cec5SDimitry Andric 6820b57cec5SDimitry Andric SmallPtrSet<BasicBlock*, 4> LHSKnownBBs; 6830b57cec5SDimitry Andric 6840b57cec5SDimitry Andric // Scan for the sentinel. If we find an undef, force it to the 6850b57cec5SDimitry Andric // interesting value: x|undef -> true and x&undef -> false. 6860b57cec5SDimitry Andric for (const auto &LHSVal : LHSVals) 6870b57cec5SDimitry Andric if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) { 6880b57cec5SDimitry Andric Result.emplace_back(InterestingVal, LHSVal.second); 6890b57cec5SDimitry Andric LHSKnownBBs.insert(LHSVal.second); 6900b57cec5SDimitry Andric } 6910b57cec5SDimitry Andric for (const auto &RHSVal : RHSVals) 6920b57cec5SDimitry Andric if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) { 6930b57cec5SDimitry Andric // If we already inferred a value for this block on the LHS, don't 6940b57cec5SDimitry Andric // re-add it. 6950b57cec5SDimitry Andric if (!LHSKnownBBs.count(RHSVal.second)) 6960b57cec5SDimitry Andric Result.emplace_back(InterestingVal, RHSVal.second); 6970b57cec5SDimitry Andric } 6980b57cec5SDimitry Andric 6990b57cec5SDimitry Andric return !Result.empty(); 7000b57cec5SDimitry Andric } 7010b57cec5SDimitry Andric 7020b57cec5SDimitry Andric // Handle the NOT form of XOR. 7030b57cec5SDimitry Andric if (I->getOpcode() == Instruction::Xor && 7040b57cec5SDimitry Andric isa<ConstantInt>(I->getOperand(1)) && 7050b57cec5SDimitry Andric cast<ConstantInt>(I->getOperand(1))->isOne()) { 706e8d8bef9SDimitry Andric computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result, 7070b57cec5SDimitry Andric WantInteger, RecursionSet, CxtI); 7080b57cec5SDimitry Andric if (Result.empty()) 7090b57cec5SDimitry Andric return false; 7100b57cec5SDimitry Andric 7110b57cec5SDimitry Andric // Invert the known values. 7120b57cec5SDimitry Andric for (auto &R : Result) 7130b57cec5SDimitry Andric R.first = ConstantExpr::getNot(R.first); 7140b57cec5SDimitry Andric 7150b57cec5SDimitry Andric return true; 7160b57cec5SDimitry Andric } 7170b57cec5SDimitry Andric 7180b57cec5SDimitry Andric // Try to simplify some other binary operator values. 7190b57cec5SDimitry Andric } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 72004eeddc0SDimitry Andric if (Preference != WantInteger) 72104eeddc0SDimitry Andric return false; 7220b57cec5SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) { 7230b57cec5SDimitry Andric PredValueInfoTy LHSVals; 724e8d8bef9SDimitry Andric computeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals, 7250b57cec5SDimitry Andric WantInteger, RecursionSet, CxtI); 7260b57cec5SDimitry Andric 7270b57cec5SDimitry Andric // Try to use constant folding to simplify the binary operator. 7280b57cec5SDimitry Andric for (const auto &LHSVal : LHSVals) { 7290b57cec5SDimitry Andric Constant *V = LHSVal.first; 73081ad6265SDimitry Andric Constant *Folded = 73181ad6265SDimitry Andric ConstantFoldBinaryOpOperands(BO->getOpcode(), V, CI, DL); 7320b57cec5SDimitry Andric 7330b57cec5SDimitry Andric if (Constant *KC = getKnownConstant(Folded, WantInteger)) 7345ffd83dbSDimitry Andric Result.emplace_back(KC, LHSVal.second); 7350b57cec5SDimitry Andric } 7360b57cec5SDimitry Andric } 7370b57cec5SDimitry Andric 7380b57cec5SDimitry Andric return !Result.empty(); 7390b57cec5SDimitry Andric } 7400b57cec5SDimitry Andric 7410b57cec5SDimitry Andric // Handle compare with phi operand, where the PHI is defined in this block. 7420b57cec5SDimitry Andric if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 74304eeddc0SDimitry Andric if (Preference != WantInteger) 74404eeddc0SDimitry Andric return false; 7450b57cec5SDimitry Andric Type *CmpType = Cmp->getType(); 7460b57cec5SDimitry Andric Value *CmpLHS = Cmp->getOperand(0); 7470b57cec5SDimitry Andric Value *CmpRHS = Cmp->getOperand(1); 7480b57cec5SDimitry Andric CmpInst::Predicate Pred = Cmp->getPredicate(); 7490b57cec5SDimitry Andric 7500b57cec5SDimitry Andric PHINode *PN = dyn_cast<PHINode>(CmpLHS); 7510b57cec5SDimitry Andric if (!PN) 7520b57cec5SDimitry Andric PN = dyn_cast<PHINode>(CmpRHS); 7535f757f3fSDimitry Andric // Do not perform phi translation across a loop header phi, because this 7545f757f3fSDimitry Andric // may result in comparison of values from two different loop iterations. 7555f757f3fSDimitry Andric // FIXME: This check is broken if LoopHeaders is not populated. 7565f757f3fSDimitry Andric if (PN && PN->getParent() == BB && !LoopHeaders.contains(BB)) { 757*0fca6ea1SDimitry Andric const DataLayout &DL = PN->getDataLayout(); 7580b57cec5SDimitry Andric // We can do this simplification if any comparisons fold to true or false. 7590b57cec5SDimitry Andric // See if any do. 7600b57cec5SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7610b57cec5SDimitry Andric BasicBlock *PredBB = PN->getIncomingBlock(i); 7620b57cec5SDimitry Andric Value *LHS, *RHS; 7630b57cec5SDimitry Andric if (PN == CmpLHS) { 7640b57cec5SDimitry Andric LHS = PN->getIncomingValue(i); 7650b57cec5SDimitry Andric RHS = CmpRHS->DoPHITranslation(BB, PredBB); 7660b57cec5SDimitry Andric } else { 7670b57cec5SDimitry Andric LHS = CmpLHS->DoPHITranslation(BB, PredBB); 7680b57cec5SDimitry Andric RHS = PN->getIncomingValue(i); 7690b57cec5SDimitry Andric } 77081ad6265SDimitry Andric Value *Res = simplifyCmpInst(Pred, LHS, RHS, {DL}); 7710b57cec5SDimitry Andric if (!Res) { 7720b57cec5SDimitry Andric if (!isa<Constant>(RHS)) 7730b57cec5SDimitry Andric continue; 7740b57cec5SDimitry Andric 7750b57cec5SDimitry Andric // getPredicateOnEdge call will make no sense if LHS is defined in BB. 7760b57cec5SDimitry Andric auto LHSInst = dyn_cast<Instruction>(LHS); 7770b57cec5SDimitry Andric if (LHSInst && LHSInst->getParent() == BB) 7780b57cec5SDimitry Andric continue; 7790b57cec5SDimitry Andric 780*0fca6ea1SDimitry Andric Res = LVI->getPredicateOnEdge(Pred, LHS, cast<Constant>(RHS), PredBB, 781*0fca6ea1SDimitry Andric BB, CxtI ? CxtI : Cmp); 7820b57cec5SDimitry Andric } 7830b57cec5SDimitry Andric 7840b57cec5SDimitry Andric if (Constant *KC = getKnownConstant(Res, WantInteger)) 7855ffd83dbSDimitry Andric Result.emplace_back(KC, PredBB); 7860b57cec5SDimitry Andric } 7870b57cec5SDimitry Andric 7880b57cec5SDimitry Andric return !Result.empty(); 7890b57cec5SDimitry Andric } 7900b57cec5SDimitry Andric 7910b57cec5SDimitry Andric // If comparing a live-in value against a constant, see if we know the 7920b57cec5SDimitry Andric // live-in value on any predecessors. 7930b57cec5SDimitry Andric if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) { 7940b57cec5SDimitry Andric Constant *CmpConst = cast<Constant>(CmpRHS); 7950b57cec5SDimitry Andric 7960b57cec5SDimitry Andric if (!isa<Instruction>(CmpLHS) || 7970b57cec5SDimitry Andric cast<Instruction>(CmpLHS)->getParent() != BB) { 7980b57cec5SDimitry Andric for (BasicBlock *P : predecessors(BB)) { 7990b57cec5SDimitry Andric // If the value is known by LazyValueInfo to be a constant in a 8000b57cec5SDimitry Andric // predecessor, use that information to try to thread this block. 801*0fca6ea1SDimitry Andric Constant *Res = LVI->getPredicateOnEdge(Pred, CmpLHS, CmpConst, P, BB, 802*0fca6ea1SDimitry Andric CxtI ? CxtI : Cmp); 803*0fca6ea1SDimitry Andric if (Constant *KC = getKnownConstant(Res, WantInteger)) 804*0fca6ea1SDimitry Andric Result.emplace_back(KC, P); 8050b57cec5SDimitry Andric } 8060b57cec5SDimitry Andric 8070b57cec5SDimitry Andric return !Result.empty(); 8080b57cec5SDimitry Andric } 8090b57cec5SDimitry Andric 8100b57cec5SDimitry Andric // InstCombine can fold some forms of constant range checks into 8110b57cec5SDimitry Andric // (icmp (add (x, C1)), C2). See if we have we have such a thing with 8120b57cec5SDimitry Andric // x as a live-in. 8130b57cec5SDimitry Andric { 8140b57cec5SDimitry Andric using namespace PatternMatch; 8150b57cec5SDimitry Andric 8160b57cec5SDimitry Andric Value *AddLHS; 8170b57cec5SDimitry Andric ConstantInt *AddConst; 8180b57cec5SDimitry Andric if (isa<ConstantInt>(CmpConst) && 8190b57cec5SDimitry Andric match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) { 8200b57cec5SDimitry Andric if (!isa<Instruction>(AddLHS) || 8210b57cec5SDimitry Andric cast<Instruction>(AddLHS)->getParent() != BB) { 8220b57cec5SDimitry Andric for (BasicBlock *P : predecessors(BB)) { 8230b57cec5SDimitry Andric // If the value is known by LazyValueInfo to be a ConstantRange in 8240b57cec5SDimitry Andric // a predecessor, use that information to try to thread this 8250b57cec5SDimitry Andric // block. 8260b57cec5SDimitry Andric ConstantRange CR = LVI->getConstantRangeOnEdge( 8270b57cec5SDimitry Andric AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS)); 8280b57cec5SDimitry Andric // Propagate the range through the addition. 8290b57cec5SDimitry Andric CR = CR.add(AddConst->getValue()); 8300b57cec5SDimitry Andric 8310b57cec5SDimitry Andric // Get the range where the compare returns true. 8320b57cec5SDimitry Andric ConstantRange CmpRange = ConstantRange::makeExactICmpRegion( 8330b57cec5SDimitry Andric Pred, cast<ConstantInt>(CmpConst)->getValue()); 8340b57cec5SDimitry Andric 8350b57cec5SDimitry Andric Constant *ResC; 8360b57cec5SDimitry Andric if (CmpRange.contains(CR)) 8370b57cec5SDimitry Andric ResC = ConstantInt::getTrue(CmpType); 8380b57cec5SDimitry Andric else if (CmpRange.inverse().contains(CR)) 8390b57cec5SDimitry Andric ResC = ConstantInt::getFalse(CmpType); 8400b57cec5SDimitry Andric else 8410b57cec5SDimitry Andric continue; 8420b57cec5SDimitry Andric 8435ffd83dbSDimitry Andric Result.emplace_back(ResC, P); 8440b57cec5SDimitry Andric } 8450b57cec5SDimitry Andric 8460b57cec5SDimitry Andric return !Result.empty(); 8470b57cec5SDimitry Andric } 8480b57cec5SDimitry Andric } 8490b57cec5SDimitry Andric } 8500b57cec5SDimitry Andric 8510b57cec5SDimitry Andric // Try to find a constant value for the LHS of a comparison, 8520b57cec5SDimitry Andric // and evaluate it statically if we can. 8530b57cec5SDimitry Andric PredValueInfoTy LHSVals; 854e8d8bef9SDimitry Andric computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals, 8550b57cec5SDimitry Andric WantInteger, RecursionSet, CxtI); 8560b57cec5SDimitry Andric 8570b57cec5SDimitry Andric for (const auto &LHSVal : LHSVals) { 8580b57cec5SDimitry Andric Constant *V = LHSVal.first; 859*0fca6ea1SDimitry Andric Constant *Folded = 860*0fca6ea1SDimitry Andric ConstantFoldCompareInstOperands(Pred, V, CmpConst, DL); 8610b57cec5SDimitry Andric if (Constant *KC = getKnownConstant(Folded, WantInteger)) 8625ffd83dbSDimitry Andric Result.emplace_back(KC, LHSVal.second); 8630b57cec5SDimitry Andric } 8640b57cec5SDimitry Andric 8650b57cec5SDimitry Andric return !Result.empty(); 8660b57cec5SDimitry Andric } 8670b57cec5SDimitry Andric } 8680b57cec5SDimitry Andric 8690b57cec5SDimitry Andric if (SelectInst *SI = dyn_cast<SelectInst>(I)) { 8700b57cec5SDimitry Andric // Handle select instructions where at least one operand is a known constant 8710b57cec5SDimitry Andric // and we can figure out the condition value for any predecessor block. 8720b57cec5SDimitry Andric Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference); 8730b57cec5SDimitry Andric Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference); 8740b57cec5SDimitry Andric PredValueInfoTy Conds; 8750b57cec5SDimitry Andric if ((TrueVal || FalseVal) && 876e8d8bef9SDimitry Andric computeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds, 8770b57cec5SDimitry Andric WantInteger, RecursionSet, CxtI)) { 8780b57cec5SDimitry Andric for (auto &C : Conds) { 8790b57cec5SDimitry Andric Constant *Cond = C.first; 8800b57cec5SDimitry Andric 8810b57cec5SDimitry Andric // Figure out what value to use for the condition. 8820b57cec5SDimitry Andric bool KnownCond; 8830b57cec5SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) { 8840b57cec5SDimitry Andric // A known boolean. 8850b57cec5SDimitry Andric KnownCond = CI->isOne(); 8860b57cec5SDimitry Andric } else { 8870b57cec5SDimitry Andric assert(isa<UndefValue>(Cond) && "Unexpected condition value"); 8880b57cec5SDimitry Andric // Either operand will do, so be sure to pick the one that's a known 8890b57cec5SDimitry Andric // constant. 8900b57cec5SDimitry Andric // FIXME: Do this more cleverly if both values are known constants? 8910b57cec5SDimitry Andric KnownCond = (TrueVal != nullptr); 8920b57cec5SDimitry Andric } 8930b57cec5SDimitry Andric 8940b57cec5SDimitry Andric // See if the select has a known constant value for this predecessor. 8950b57cec5SDimitry Andric if (Constant *Val = KnownCond ? TrueVal : FalseVal) 8965ffd83dbSDimitry Andric Result.emplace_back(Val, C.second); 8970b57cec5SDimitry Andric } 8980b57cec5SDimitry Andric 8990b57cec5SDimitry Andric return !Result.empty(); 9000b57cec5SDimitry Andric } 9010b57cec5SDimitry Andric } 9020b57cec5SDimitry Andric 9030b57cec5SDimitry Andric // If all else fails, see if LVI can figure out a constant value for us. 904e8d8bef9SDimitry Andric assert(CxtI->getParent() == BB && "CxtI should be in BB"); 905e8d8bef9SDimitry Andric Constant *CI = LVI->getConstant(V, CxtI); 9060b57cec5SDimitry Andric if (Constant *KC = getKnownConstant(CI, Preference)) { 9070b57cec5SDimitry Andric for (BasicBlock *Pred : predecessors(BB)) 9085ffd83dbSDimitry Andric Result.emplace_back(KC, Pred); 9090b57cec5SDimitry Andric } 9100b57cec5SDimitry Andric 9110b57cec5SDimitry Andric return !Result.empty(); 9120b57cec5SDimitry Andric } 9130b57cec5SDimitry Andric 9140b57cec5SDimitry Andric /// GetBestDestForBranchOnUndef - If we determine that the specified block ends 9150b57cec5SDimitry Andric /// in an undefined jump, decide which block is best to revector to. 9160b57cec5SDimitry Andric /// 9170b57cec5SDimitry Andric /// Since we can pick an arbitrary destination, we pick the successor with the 9180b57cec5SDimitry Andric /// fewest predecessors. This should reduce the in-degree of the others. 919e8d8bef9SDimitry Andric static unsigned getBestDestForJumpOnUndef(BasicBlock *BB) { 9200b57cec5SDimitry Andric Instruction *BBTerm = BB->getTerminator(); 9210b57cec5SDimitry Andric unsigned MinSucc = 0; 9220b57cec5SDimitry Andric BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc); 9230b57cec5SDimitry Andric // Compute the successor with the minimum number of predecessors. 9240b57cec5SDimitry Andric unsigned MinNumPreds = pred_size(TestBB); 9250b57cec5SDimitry Andric for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) { 9260b57cec5SDimitry Andric TestBB = BBTerm->getSuccessor(i); 9270b57cec5SDimitry Andric unsigned NumPreds = pred_size(TestBB); 9280b57cec5SDimitry Andric if (NumPreds < MinNumPreds) { 9290b57cec5SDimitry Andric MinSucc = i; 9300b57cec5SDimitry Andric MinNumPreds = NumPreds; 9310b57cec5SDimitry Andric } 9320b57cec5SDimitry Andric } 9330b57cec5SDimitry Andric 9340b57cec5SDimitry Andric return MinSucc; 9350b57cec5SDimitry Andric } 9360b57cec5SDimitry Andric 9370b57cec5SDimitry Andric static bool hasAddressTakenAndUsed(BasicBlock *BB) { 9380b57cec5SDimitry Andric if (!BB->hasAddressTaken()) return false; 9390b57cec5SDimitry Andric 9400b57cec5SDimitry Andric // If the block has its address taken, it may be a tree of dead constants 9410b57cec5SDimitry Andric // hanging off of it. These shouldn't keep the block alive. 9420b57cec5SDimitry Andric BlockAddress *BA = BlockAddress::get(BB); 9430b57cec5SDimitry Andric BA->removeDeadConstantUsers(); 9440b57cec5SDimitry Andric return !BA->use_empty(); 9450b57cec5SDimitry Andric } 9460b57cec5SDimitry Andric 947e8d8bef9SDimitry Andric /// processBlock - If there are any predecessors whose control can be threaded 9480b57cec5SDimitry Andric /// through to a successor, transform them now. 949e8d8bef9SDimitry Andric bool JumpThreadingPass::processBlock(BasicBlock *BB) { 9500b57cec5SDimitry Andric // If the block is trivially dead, just return and let the caller nuke it. 9510b57cec5SDimitry Andric // This simplifies other transformations. 9520b57cec5SDimitry Andric if (DTU->isBBPendingDeletion(BB) || 9530b57cec5SDimitry Andric (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock())) 9540b57cec5SDimitry Andric return false; 9550b57cec5SDimitry Andric 9560b57cec5SDimitry Andric // If this block has a single predecessor, and if that pred has a single 9570b57cec5SDimitry Andric // successor, merge the blocks. This encourages recursive jump threading 9580b57cec5SDimitry Andric // because now the condition in this block can be threaded through 9590b57cec5SDimitry Andric // predecessors of our predecessor block. 960e8d8bef9SDimitry Andric if (maybeMergeBasicBlockIntoOnlyPred(BB)) 9610b57cec5SDimitry Andric return true; 9620b57cec5SDimitry Andric 963e8d8bef9SDimitry Andric if (tryToUnfoldSelectInCurrBB(BB)) 9640b57cec5SDimitry Andric return true; 9650b57cec5SDimitry Andric 9660b57cec5SDimitry Andric // Look if we can propagate guards to predecessors. 967e8d8bef9SDimitry Andric if (HasGuards && processGuards(BB)) 9680b57cec5SDimitry Andric return true; 9690b57cec5SDimitry Andric 9700b57cec5SDimitry Andric // What kind of constant we're looking for. 9710b57cec5SDimitry Andric ConstantPreference Preference = WantInteger; 9720b57cec5SDimitry Andric 9730b57cec5SDimitry Andric // Look to see if the terminator is a conditional branch, switch or indirect 9740b57cec5SDimitry Andric // branch, if not we can't thread it. 9750b57cec5SDimitry Andric Value *Condition; 9760b57cec5SDimitry Andric Instruction *Terminator = BB->getTerminator(); 9770b57cec5SDimitry Andric if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) { 9780b57cec5SDimitry Andric // Can't thread an unconditional jump. 9790b57cec5SDimitry Andric if (BI->isUnconditional()) return false; 9800b57cec5SDimitry Andric Condition = BI->getCondition(); 9810b57cec5SDimitry Andric } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) { 9820b57cec5SDimitry Andric Condition = SI->getCondition(); 9830b57cec5SDimitry Andric } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) { 9840b57cec5SDimitry Andric // Can't thread indirect branch with no successors. 9850b57cec5SDimitry Andric if (IB->getNumSuccessors() == 0) return false; 9860b57cec5SDimitry Andric Condition = IB->getAddress()->stripPointerCasts(); 9870b57cec5SDimitry Andric Preference = WantBlockAddress; 9880b57cec5SDimitry Andric } else { 9890b57cec5SDimitry Andric return false; // Must be an invoke or callbr. 9900b57cec5SDimitry Andric } 9910b57cec5SDimitry Andric 992e8d8bef9SDimitry Andric // Keep track if we constant folded the condition in this invocation. 993e8d8bef9SDimitry Andric bool ConstantFolded = false; 994e8d8bef9SDimitry Andric 9950b57cec5SDimitry Andric // Run constant folding to see if we can reduce the condition to a simple 9960b57cec5SDimitry Andric // constant. 9970b57cec5SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(Condition)) { 9980b57cec5SDimitry Andric Value *SimpleVal = 999*0fca6ea1SDimitry Andric ConstantFoldInstruction(I, BB->getDataLayout(), TLI); 10000b57cec5SDimitry Andric if (SimpleVal) { 10010b57cec5SDimitry Andric I->replaceAllUsesWith(SimpleVal); 10020b57cec5SDimitry Andric if (isInstructionTriviallyDead(I, TLI)) 10030b57cec5SDimitry Andric I->eraseFromParent(); 10040b57cec5SDimitry Andric Condition = SimpleVal; 1005e8d8bef9SDimitry Andric ConstantFolded = true; 10060b57cec5SDimitry Andric } 10070b57cec5SDimitry Andric } 10080b57cec5SDimitry Andric 1009e8d8bef9SDimitry Andric // If the terminator is branching on an undef or freeze undef, we can pick any 1010e8d8bef9SDimitry Andric // of the successors to branch to. Let getBestDestForJumpOnUndef decide. 1011e8d8bef9SDimitry Andric auto *FI = dyn_cast<FreezeInst>(Condition); 1012e8d8bef9SDimitry Andric if (isa<UndefValue>(Condition) || 1013e8d8bef9SDimitry Andric (FI && isa<UndefValue>(FI->getOperand(0)) && FI->hasOneUse())) { 1014e8d8bef9SDimitry Andric unsigned BestSucc = getBestDestForJumpOnUndef(BB); 10150b57cec5SDimitry Andric std::vector<DominatorTree::UpdateType> Updates; 10160b57cec5SDimitry Andric 10170b57cec5SDimitry Andric // Fold the branch/switch. 10180b57cec5SDimitry Andric Instruction *BBTerm = BB->getTerminator(); 10190b57cec5SDimitry Andric Updates.reserve(BBTerm->getNumSuccessors()); 10200b57cec5SDimitry Andric for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) { 10210b57cec5SDimitry Andric if (i == BestSucc) continue; 10220b57cec5SDimitry Andric BasicBlock *Succ = BBTerm->getSuccessor(i); 10230b57cec5SDimitry Andric Succ->removePredecessor(BB, true); 10240b57cec5SDimitry Andric Updates.push_back({DominatorTree::Delete, BB, Succ}); 10250b57cec5SDimitry Andric } 10260b57cec5SDimitry Andric 10270b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " In block '" << BB->getName() 10280b57cec5SDimitry Andric << "' folding undef terminator: " << *BBTerm << '\n'); 1029*0fca6ea1SDimitry Andric Instruction *NewBI = BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm->getIterator()); 1030*0fca6ea1SDimitry Andric NewBI->setDebugLoc(BBTerm->getDebugLoc()); 1031fe6060f1SDimitry Andric ++NumFolds; 10320b57cec5SDimitry Andric BBTerm->eraseFromParent(); 10330b57cec5SDimitry Andric DTU->applyUpdatesPermissive(Updates); 1034e8d8bef9SDimitry Andric if (FI) 1035e8d8bef9SDimitry Andric FI->eraseFromParent(); 10360b57cec5SDimitry Andric return true; 10370b57cec5SDimitry Andric } 10380b57cec5SDimitry Andric 10390b57cec5SDimitry Andric // If the terminator of this block is branching on a constant, simplify the 10400b57cec5SDimitry Andric // terminator to an unconditional branch. This can occur due to threading in 10410b57cec5SDimitry Andric // other blocks. 10420b57cec5SDimitry Andric if (getKnownConstant(Condition, Preference)) { 10430b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " In block '" << BB->getName() 10440b57cec5SDimitry Andric << "' folding terminator: " << *BB->getTerminator() 10450b57cec5SDimitry Andric << '\n'); 10460b57cec5SDimitry Andric ++NumFolds; 104706c3fb27SDimitry Andric ConstantFoldTerminator(BB, true, nullptr, DTU.get()); 104806c3fb27SDimitry Andric if (auto *BPI = getBPI()) 1049e8d8bef9SDimitry Andric BPI->eraseBlock(BB); 10500b57cec5SDimitry Andric return true; 10510b57cec5SDimitry Andric } 10520b57cec5SDimitry Andric 10530b57cec5SDimitry Andric Instruction *CondInst = dyn_cast<Instruction>(Condition); 10540b57cec5SDimitry Andric 10550b57cec5SDimitry Andric // All the rest of our checks depend on the condition being an instruction. 10560b57cec5SDimitry Andric if (!CondInst) { 10570b57cec5SDimitry Andric // FIXME: Unify this with code below. 1058e8d8bef9SDimitry Andric if (processThreadableEdges(Condition, BB, Preference, Terminator)) 10590b57cec5SDimitry Andric return true; 1060e8d8bef9SDimitry Andric return ConstantFolded; 10610b57cec5SDimitry Andric } 10620b57cec5SDimitry Andric 106381ad6265SDimitry Andric // Some of the following optimization can safely work on the unfrozen cond. 106481ad6265SDimitry Andric Value *CondWithoutFreeze = CondInst; 106581ad6265SDimitry Andric if (auto *FI = dyn_cast<FreezeInst>(CondInst)) 106681ad6265SDimitry Andric CondWithoutFreeze = FI->getOperand(0); 106781ad6265SDimitry Andric 106881ad6265SDimitry Andric if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondWithoutFreeze)) { 10690b57cec5SDimitry Andric // If we're branching on a conditional, LVI might be able to determine 10700b57cec5SDimitry Andric // it's value at the branch instruction. We only handle comparisons 10710b57cec5SDimitry Andric // against a constant at this time. 107281ad6265SDimitry Andric if (Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1))) { 1073*0fca6ea1SDimitry Andric Constant *Res = 10740b57cec5SDimitry Andric LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0), 107581ad6265SDimitry Andric CondConst, BB->getTerminator(), 107681ad6265SDimitry Andric /*UseBlockValue=*/false); 1077*0fca6ea1SDimitry Andric if (Res) { 10780b57cec5SDimitry Andric // We can safely replace *some* uses of the CondInst if it has 10790b57cec5SDimitry Andric // exactly one value as returned by LVI. RAUW is incorrect in the 10800b57cec5SDimitry Andric // presence of guards and assumes, that have the `Cond` as the use. This 10810b57cec5SDimitry Andric // is because we use the guards/assume to reason about the `Cond` value 10820b57cec5SDimitry Andric // at the end of block, but RAUW unconditionally replaces all uses 10830b57cec5SDimitry Andric // including the guards/assumes themselves and the uses before the 10840b57cec5SDimitry Andric // guard/assume. 1085*0fca6ea1SDimitry Andric if (replaceFoldableUses(CondCmp, Res, BB)) 10860b57cec5SDimitry Andric return true; 10870b57cec5SDimitry Andric } 10880b57cec5SDimitry Andric 10890b57cec5SDimitry Andric // We did not manage to simplify this branch, try to see whether 10900b57cec5SDimitry Andric // CondCmp depends on a known phi-select pattern. 1091e8d8bef9SDimitry Andric if (tryToUnfoldSelect(CondCmp, BB)) 10920b57cec5SDimitry Andric return true; 10930b57cec5SDimitry Andric } 10940b57cec5SDimitry Andric } 10950b57cec5SDimitry Andric 10960b57cec5SDimitry Andric if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) 1097e8d8bef9SDimitry Andric if (tryToUnfoldSelect(SI, BB)) 10980b57cec5SDimitry Andric return true; 10990b57cec5SDimitry Andric 11000b57cec5SDimitry Andric // Check for some cases that are worth simplifying. Right now we want to look 11010b57cec5SDimitry Andric // for loads that are used by a switch or by the condition for the branch. If 11020b57cec5SDimitry Andric // we see one, check to see if it's partially redundant. If so, insert a PHI 11030b57cec5SDimitry Andric // which can then be used to thread the values. 110481ad6265SDimitry Andric Value *SimplifyValue = CondWithoutFreeze; 1105e8d8bef9SDimitry Andric 11060b57cec5SDimitry Andric if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue)) 11070b57cec5SDimitry Andric if (isa<Constant>(CondCmp->getOperand(1))) 11080b57cec5SDimitry Andric SimplifyValue = CondCmp->getOperand(0); 11090b57cec5SDimitry Andric 11100b57cec5SDimitry Andric // TODO: There are other places where load PRE would be profitable, such as 11110b57cec5SDimitry Andric // more complex comparisons. 11120b57cec5SDimitry Andric if (LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue)) 1113e8d8bef9SDimitry Andric if (simplifyPartiallyRedundantLoad(LoadI)) 11140b57cec5SDimitry Andric return true; 11150b57cec5SDimitry Andric 11160b57cec5SDimitry Andric // Before threading, try to propagate profile data backwards: 11170b57cec5SDimitry Andric if (PHINode *PN = dyn_cast<PHINode>(CondInst)) 11180b57cec5SDimitry Andric if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 11190b57cec5SDimitry Andric updatePredecessorProfileMetadata(PN, BB); 11200b57cec5SDimitry Andric 11210b57cec5SDimitry Andric // Handle a variety of cases where we are branching on something derived from 11220b57cec5SDimitry Andric // a PHI node in the current block. If we can prove that any predecessors 11230b57cec5SDimitry Andric // compute a predictable value based on a PHI node, thread those predecessors. 1124e8d8bef9SDimitry Andric if (processThreadableEdges(CondInst, BB, Preference, Terminator)) 11250b57cec5SDimitry Andric return true; 11260b57cec5SDimitry Andric 1127e8d8bef9SDimitry Andric // If this is an otherwise-unfoldable branch on a phi node or freeze(phi) in 1128e8d8bef9SDimitry Andric // the current block, see if we can simplify. 112981ad6265SDimitry Andric PHINode *PN = dyn_cast<PHINode>(CondWithoutFreeze); 1130e8d8bef9SDimitry Andric if (PN && PN->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 1131e8d8bef9SDimitry Andric return processBranchOnPHI(PN); 11320b57cec5SDimitry Andric 11330b57cec5SDimitry Andric // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify. 11340b57cec5SDimitry Andric if (CondInst->getOpcode() == Instruction::Xor && 11350b57cec5SDimitry Andric CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 1136e8d8bef9SDimitry Andric return processBranchOnXOR(cast<BinaryOperator>(CondInst)); 11370b57cec5SDimitry Andric 11380b57cec5SDimitry Andric // Search for a stronger dominating condition that can be used to simplify a 11390b57cec5SDimitry Andric // conditional branch leaving BB. 1140e8d8bef9SDimitry Andric if (processImpliedCondition(BB)) 11410b57cec5SDimitry Andric return true; 11420b57cec5SDimitry Andric 11430b57cec5SDimitry Andric return false; 11440b57cec5SDimitry Andric } 11450b57cec5SDimitry Andric 1146e8d8bef9SDimitry Andric bool JumpThreadingPass::processImpliedCondition(BasicBlock *BB) { 11470b57cec5SDimitry Andric auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 11480b57cec5SDimitry Andric if (!BI || !BI->isConditional()) 11490b57cec5SDimitry Andric return false; 11500b57cec5SDimitry Andric 11510b57cec5SDimitry Andric Value *Cond = BI->getCondition(); 115281ad6265SDimitry Andric // Assuming that predecessor's branch was taken, if pred's branch condition 115381ad6265SDimitry Andric // (V) implies Cond, Cond can be either true, undef, or poison. In this case, 115481ad6265SDimitry Andric // freeze(Cond) is either true or a nondeterministic value. 115581ad6265SDimitry Andric // If freeze(Cond) has only one use, we can freely fold freeze(Cond) to true 115681ad6265SDimitry Andric // without affecting other instructions. 115781ad6265SDimitry Andric auto *FICond = dyn_cast<FreezeInst>(Cond); 115881ad6265SDimitry Andric if (FICond && FICond->hasOneUse()) 115981ad6265SDimitry Andric Cond = FICond->getOperand(0); 116081ad6265SDimitry Andric else 116181ad6265SDimitry Andric FICond = nullptr; 116281ad6265SDimitry Andric 11630b57cec5SDimitry Andric BasicBlock *CurrentBB = BB; 11640b57cec5SDimitry Andric BasicBlock *CurrentPred = BB->getSinglePredecessor(); 11650b57cec5SDimitry Andric unsigned Iter = 0; 11660b57cec5SDimitry Andric 1167*0fca6ea1SDimitry Andric auto &DL = BB->getDataLayout(); 11680b57cec5SDimitry Andric 11690b57cec5SDimitry Andric while (CurrentPred && Iter++ < ImplicationSearchThreshold) { 11700b57cec5SDimitry Andric auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator()); 11710b57cec5SDimitry Andric if (!PBI || !PBI->isConditional()) 11720b57cec5SDimitry Andric return false; 11730b57cec5SDimitry Andric if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB) 11740b57cec5SDimitry Andric return false; 11750b57cec5SDimitry Andric 11760b57cec5SDimitry Andric bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB; 1177bdd1243dSDimitry Andric std::optional<bool> Implication = 11780b57cec5SDimitry Andric isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue); 117981ad6265SDimitry Andric 118081ad6265SDimitry Andric // If the branch condition of BB (which is Cond) and CurrentPred are 118181ad6265SDimitry Andric // exactly the same freeze instruction, Cond can be folded into CondIsTrue. 118281ad6265SDimitry Andric if (!Implication && FICond && isa<FreezeInst>(PBI->getCondition())) { 118381ad6265SDimitry Andric if (cast<FreezeInst>(PBI->getCondition())->getOperand(0) == 118481ad6265SDimitry Andric FICond->getOperand(0)) 118581ad6265SDimitry Andric Implication = CondIsTrue; 118681ad6265SDimitry Andric } 118781ad6265SDimitry Andric 11880b57cec5SDimitry Andric if (Implication) { 11890b57cec5SDimitry Andric BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1); 11900b57cec5SDimitry Andric BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0); 11910b57cec5SDimitry Andric RemoveSucc->removePredecessor(BB); 1192*0fca6ea1SDimitry Andric BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI->getIterator()); 11930b57cec5SDimitry Andric UncondBI->setDebugLoc(BI->getDebugLoc()); 1194fe6060f1SDimitry Andric ++NumFolds; 11950b57cec5SDimitry Andric BI->eraseFromParent(); 119681ad6265SDimitry Andric if (FICond) 119781ad6265SDimitry Andric FICond->eraseFromParent(); 119881ad6265SDimitry Andric 11990b57cec5SDimitry Andric DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}}); 120006c3fb27SDimitry Andric if (auto *BPI = getBPI()) 1201e8d8bef9SDimitry Andric BPI->eraseBlock(BB); 12020b57cec5SDimitry Andric return true; 12030b57cec5SDimitry Andric } 12040b57cec5SDimitry Andric CurrentBB = CurrentPred; 12050b57cec5SDimitry Andric CurrentPred = CurrentBB->getSinglePredecessor(); 12060b57cec5SDimitry Andric } 12070b57cec5SDimitry Andric 12080b57cec5SDimitry Andric return false; 12090b57cec5SDimitry Andric } 12100b57cec5SDimitry Andric 12110b57cec5SDimitry Andric /// Return true if Op is an instruction defined in the given block. 12120b57cec5SDimitry Andric static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) { 12130b57cec5SDimitry Andric if (Instruction *OpInst = dyn_cast<Instruction>(Op)) 12140b57cec5SDimitry Andric if (OpInst->getParent() == BB) 12150b57cec5SDimitry Andric return true; 12160b57cec5SDimitry Andric return false; 12170b57cec5SDimitry Andric } 12180b57cec5SDimitry Andric 1219e8d8bef9SDimitry Andric /// simplifyPartiallyRedundantLoad - If LoadI is an obviously partially 12200b57cec5SDimitry Andric /// redundant load instruction, eliminate it by replacing it with a PHI node. 12210b57cec5SDimitry Andric /// This is an important optimization that encourages jump threading, and needs 12220b57cec5SDimitry Andric /// to be run interlaced with other jump threading tasks. 1223e8d8bef9SDimitry Andric bool JumpThreadingPass::simplifyPartiallyRedundantLoad(LoadInst *LoadI) { 12240b57cec5SDimitry Andric // Don't hack volatile and ordered loads. 12250b57cec5SDimitry Andric if (!LoadI->isUnordered()) return false; 12260b57cec5SDimitry Andric 12270b57cec5SDimitry Andric // If the load is defined in a block with exactly one predecessor, it can't be 12280b57cec5SDimitry Andric // partially redundant. 12290b57cec5SDimitry Andric BasicBlock *LoadBB = LoadI->getParent(); 12300b57cec5SDimitry Andric if (LoadBB->getSinglePredecessor()) 12310b57cec5SDimitry Andric return false; 12320b57cec5SDimitry Andric 12330b57cec5SDimitry Andric // If the load is defined in an EH pad, it can't be partially redundant, 12340b57cec5SDimitry Andric // because the edges between the invoke and the EH pad cannot have other 12350b57cec5SDimitry Andric // instructions between them. 12360b57cec5SDimitry Andric if (LoadBB->isEHPad()) 12370b57cec5SDimitry Andric return false; 12380b57cec5SDimitry Andric 12390b57cec5SDimitry Andric Value *LoadedPtr = LoadI->getOperand(0); 12400b57cec5SDimitry Andric 12410b57cec5SDimitry Andric // If the loaded operand is defined in the LoadBB and its not a phi, 12420b57cec5SDimitry Andric // it can't be available in predecessors. 12430b57cec5SDimitry Andric if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr)) 12440b57cec5SDimitry Andric return false; 12450b57cec5SDimitry Andric 12460b57cec5SDimitry Andric // Scan a few instructions up from the load, to see if it is obviously live at 12470b57cec5SDimitry Andric // the entry to its block. 12480b57cec5SDimitry Andric BasicBlock::iterator BBIt(LoadI); 12490b57cec5SDimitry Andric bool IsLoadCSE; 1250b3edf446SDimitry Andric BatchAAResults BatchAA(*AA); 1251b3edf446SDimitry Andric // The dominator tree is updated lazily and may not be valid at this point. 1252b3edf446SDimitry Andric BatchAA.disableDominatorTree(); 12530b57cec5SDimitry Andric if (Value *AvailableVal = FindAvailableLoadedValue( 1254b3edf446SDimitry Andric LoadI, LoadBB, BBIt, DefMaxInstsToScan, &BatchAA, &IsLoadCSE)) { 12550b57cec5SDimitry Andric // If the value of the load is locally available within the block, just use 12560b57cec5SDimitry Andric // it. This frequently occurs for reg2mem'd allocas. 12570b57cec5SDimitry Andric 12580b57cec5SDimitry Andric if (IsLoadCSE) { 12590b57cec5SDimitry Andric LoadInst *NLoadI = cast<LoadInst>(AvailableVal); 12600b57cec5SDimitry Andric combineMetadataForCSE(NLoadI, LoadI, false); 12618a4dda33SDimitry Andric LVI->forgetValue(NLoadI); 12620b57cec5SDimitry Andric }; 12630b57cec5SDimitry Andric 126481ad6265SDimitry Andric // If the returned value is the load itself, replace with poison. This can 12650b57cec5SDimitry Andric // only happen in dead loops. 12660b57cec5SDimitry Andric if (AvailableVal == LoadI) 126781ad6265SDimitry Andric AvailableVal = PoisonValue::get(LoadI->getType()); 1268*0fca6ea1SDimitry Andric if (AvailableVal->getType() != LoadI->getType()) { 12690b57cec5SDimitry Andric AvailableVal = CastInst::CreateBitOrPointerCast( 1270*0fca6ea1SDimitry Andric AvailableVal, LoadI->getType(), "", LoadI->getIterator()); 1271*0fca6ea1SDimitry Andric cast<Instruction>(AvailableVal)->setDebugLoc(LoadI->getDebugLoc()); 1272*0fca6ea1SDimitry Andric } 12730b57cec5SDimitry Andric LoadI->replaceAllUsesWith(AvailableVal); 12740b57cec5SDimitry Andric LoadI->eraseFromParent(); 12750b57cec5SDimitry Andric return true; 12760b57cec5SDimitry Andric } 12770b57cec5SDimitry Andric 12780b57cec5SDimitry Andric // Otherwise, if we scanned the whole block and got to the top of the block, 12790b57cec5SDimitry Andric // we know the block is locally transparent to the load. If not, something 12800b57cec5SDimitry Andric // might clobber its value. 12810b57cec5SDimitry Andric if (BBIt != LoadBB->begin()) 12820b57cec5SDimitry Andric return false; 12830b57cec5SDimitry Andric 12840b57cec5SDimitry Andric // If all of the loads and stores that feed the value have the same AA tags, 12850b57cec5SDimitry Andric // then we can propagate them onto any newly inserted loads. 1286349cc55cSDimitry Andric AAMDNodes AATags = LoadI->getAAMetadata(); 12870b57cec5SDimitry Andric 12880b57cec5SDimitry Andric SmallPtrSet<BasicBlock*, 8> PredsScanned; 12890b57cec5SDimitry Andric 12900b57cec5SDimitry Andric using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>; 12910b57cec5SDimitry Andric 12920b57cec5SDimitry Andric AvailablePredsTy AvailablePreds; 12930b57cec5SDimitry Andric BasicBlock *OneUnavailablePred = nullptr; 12940b57cec5SDimitry Andric SmallVector<LoadInst*, 8> CSELoads; 12950b57cec5SDimitry Andric 12960b57cec5SDimitry Andric // If we got here, the loaded value is transparent through to the start of the 12970b57cec5SDimitry Andric // block. Check to see if it is available in any of the predecessor blocks. 12980b57cec5SDimitry Andric for (BasicBlock *PredBB : predecessors(LoadBB)) { 12990b57cec5SDimitry Andric // If we already scanned this predecessor, skip it. 13000b57cec5SDimitry Andric if (!PredsScanned.insert(PredBB).second) 13010b57cec5SDimitry Andric continue; 13020b57cec5SDimitry Andric 13030b57cec5SDimitry Andric BBIt = PredBB->end(); 13040b57cec5SDimitry Andric unsigned NumScanedInst = 0; 13050b57cec5SDimitry Andric Value *PredAvailable = nullptr; 13060b57cec5SDimitry Andric // NOTE: We don't CSE load that is volatile or anything stronger than 13070b57cec5SDimitry Andric // unordered, that should have been checked when we entered the function. 13080b57cec5SDimitry Andric assert(LoadI->isUnordered() && 13090b57cec5SDimitry Andric "Attempting to CSE volatile or atomic loads"); 13100b57cec5SDimitry Andric // If this is a load on a phi pointer, phi-translate it and search 13110b57cec5SDimitry Andric // for available load/store to the pointer in predecessors. 1312fe6060f1SDimitry Andric Type *AccessTy = LoadI->getType(); 1313*0fca6ea1SDimitry Andric const auto &DL = LoadI->getDataLayout(); 1314fe6060f1SDimitry Andric MemoryLocation Loc(LoadedPtr->DoPHITranslation(LoadBB, PredBB), 1315fe6060f1SDimitry Andric LocationSize::precise(DL.getTypeStoreSize(AccessTy)), 1316fe6060f1SDimitry Andric AATags); 1317b3edf446SDimitry Andric PredAvailable = findAvailablePtrLoadStore( 1318b3edf446SDimitry Andric Loc, AccessTy, LoadI->isAtomic(), PredBB, BBIt, DefMaxInstsToScan, 1319b3edf446SDimitry Andric &BatchAA, &IsLoadCSE, &NumScanedInst); 13200b57cec5SDimitry Andric 13210b57cec5SDimitry Andric // If PredBB has a single predecessor, continue scanning through the 13220b57cec5SDimitry Andric // single predecessor. 13230b57cec5SDimitry Andric BasicBlock *SinglePredBB = PredBB; 13240b57cec5SDimitry Andric while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() && 13250b57cec5SDimitry Andric NumScanedInst < DefMaxInstsToScan) { 13260b57cec5SDimitry Andric SinglePredBB = SinglePredBB->getSinglePredecessor(); 13270b57cec5SDimitry Andric if (SinglePredBB) { 13280b57cec5SDimitry Andric BBIt = SinglePredBB->end(); 1329fe6060f1SDimitry Andric PredAvailable = findAvailablePtrLoadStore( 1330fe6060f1SDimitry Andric Loc, AccessTy, LoadI->isAtomic(), SinglePredBB, BBIt, 1331b3edf446SDimitry Andric (DefMaxInstsToScan - NumScanedInst), &BatchAA, &IsLoadCSE, 13320b57cec5SDimitry Andric &NumScanedInst); 13330b57cec5SDimitry Andric } 13340b57cec5SDimitry Andric } 13350b57cec5SDimitry Andric 13360b57cec5SDimitry Andric if (!PredAvailable) { 13370b57cec5SDimitry Andric OneUnavailablePred = PredBB; 13380b57cec5SDimitry Andric continue; 13390b57cec5SDimitry Andric } 13400b57cec5SDimitry Andric 13410b57cec5SDimitry Andric if (IsLoadCSE) 13420b57cec5SDimitry Andric CSELoads.push_back(cast<LoadInst>(PredAvailable)); 13430b57cec5SDimitry Andric 13440b57cec5SDimitry Andric // If so, this load is partially redundant. Remember this info so that we 13450b57cec5SDimitry Andric // can create a PHI node. 13465ffd83dbSDimitry Andric AvailablePreds.emplace_back(PredBB, PredAvailable); 13470b57cec5SDimitry Andric } 13480b57cec5SDimitry Andric 13490b57cec5SDimitry Andric // If the loaded value isn't available in any predecessor, it isn't partially 13500b57cec5SDimitry Andric // redundant. 13510b57cec5SDimitry Andric if (AvailablePreds.empty()) return false; 13520b57cec5SDimitry Andric 13530b57cec5SDimitry Andric // Okay, the loaded value is available in at least one (and maybe all!) 13540b57cec5SDimitry Andric // predecessors. If the value is unavailable in more than one unique 13550b57cec5SDimitry Andric // predecessor, we want to insert a merge block for those common predecessors. 13560b57cec5SDimitry Andric // This ensures that we only have to insert one reload, thus not increasing 13570b57cec5SDimitry Andric // code size. 13580b57cec5SDimitry Andric BasicBlock *UnavailablePred = nullptr; 13590b57cec5SDimitry Andric 13600b57cec5SDimitry Andric // If the value is unavailable in one of predecessors, we will end up 13610b57cec5SDimitry Andric // inserting a new instruction into them. It is only valid if all the 13620b57cec5SDimitry Andric // instructions before LoadI are guaranteed to pass execution to its 13630b57cec5SDimitry Andric // successor, or if LoadI is safe to speculate. 13640b57cec5SDimitry Andric // TODO: If this logic becomes more complex, and we will perform PRE insertion 13650b57cec5SDimitry Andric // farther than to a predecessor, we need to reuse the code from GVN's PRE. 13660b57cec5SDimitry Andric // It requires domination tree analysis, so for this simple case it is an 13670b57cec5SDimitry Andric // overkill. 13680b57cec5SDimitry Andric if (PredsScanned.size() != AvailablePreds.size() && 13690b57cec5SDimitry Andric !isSafeToSpeculativelyExecute(LoadI)) 13700b57cec5SDimitry Andric for (auto I = LoadBB->begin(); &*I != LoadI; ++I) 13710b57cec5SDimitry Andric if (!isGuaranteedToTransferExecutionToSuccessor(&*I)) 13720b57cec5SDimitry Andric return false; 13730b57cec5SDimitry Andric 13740b57cec5SDimitry Andric // If there is exactly one predecessor where the value is unavailable, the 13750b57cec5SDimitry Andric // already computed 'OneUnavailablePred' block is it. If it ends in an 13760b57cec5SDimitry Andric // unconditional branch, we know that it isn't a critical edge. 13770b57cec5SDimitry Andric if (PredsScanned.size() == AvailablePreds.size()+1 && 13780b57cec5SDimitry Andric OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) { 13790b57cec5SDimitry Andric UnavailablePred = OneUnavailablePred; 13800b57cec5SDimitry Andric } else if (PredsScanned.size() != AvailablePreds.size()) { 13810b57cec5SDimitry Andric // Otherwise, we had multiple unavailable predecessors or we had a critical 13820b57cec5SDimitry Andric // edge from the one. 13830b57cec5SDimitry Andric SmallVector<BasicBlock*, 8> PredsToSplit; 13840b57cec5SDimitry Andric SmallPtrSet<BasicBlock*, 8> AvailablePredSet; 13850b57cec5SDimitry Andric 13860b57cec5SDimitry Andric for (const auto &AvailablePred : AvailablePreds) 13870b57cec5SDimitry Andric AvailablePredSet.insert(AvailablePred.first); 13880b57cec5SDimitry Andric 13890b57cec5SDimitry Andric // Add all the unavailable predecessors to the PredsToSplit list. 13900b57cec5SDimitry Andric for (BasicBlock *P : predecessors(LoadBB)) { 13910b57cec5SDimitry Andric // If the predecessor is an indirect goto, we can't split the edge. 1392753f127fSDimitry Andric if (isa<IndirectBrInst>(P->getTerminator())) 13930b57cec5SDimitry Andric return false; 13940b57cec5SDimitry Andric 13950b57cec5SDimitry Andric if (!AvailablePredSet.count(P)) 13960b57cec5SDimitry Andric PredsToSplit.push_back(P); 13970b57cec5SDimitry Andric } 13980b57cec5SDimitry Andric 13990b57cec5SDimitry Andric // Split them out to their own block. 1400e8d8bef9SDimitry Andric UnavailablePred = splitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split"); 14010b57cec5SDimitry Andric } 14020b57cec5SDimitry Andric 14030b57cec5SDimitry Andric // If the value isn't available in all predecessors, then there will be 14040b57cec5SDimitry Andric // exactly one where it isn't available. Insert a load on that edge and add 14050b57cec5SDimitry Andric // it to the AvailablePreds list. 14060b57cec5SDimitry Andric if (UnavailablePred) { 14070b57cec5SDimitry Andric assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 && 14080b57cec5SDimitry Andric "Can't handle critical edge here!"); 14090b57cec5SDimitry Andric LoadInst *NewVal = new LoadInst( 14100b57cec5SDimitry Andric LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred), 14115ffd83dbSDimitry Andric LoadI->getName() + ".pr", false, LoadI->getAlign(), 14120b57cec5SDimitry Andric LoadI->getOrdering(), LoadI->getSyncScopeID(), 1413*0fca6ea1SDimitry Andric UnavailablePred->getTerminator()->getIterator()); 14140b57cec5SDimitry Andric NewVal->setDebugLoc(LoadI->getDebugLoc()); 14150b57cec5SDimitry Andric if (AATags) 14160b57cec5SDimitry Andric NewVal->setAAMetadata(AATags); 14170b57cec5SDimitry Andric 14185ffd83dbSDimitry Andric AvailablePreds.emplace_back(UnavailablePred, NewVal); 14190b57cec5SDimitry Andric } 14200b57cec5SDimitry Andric 14210b57cec5SDimitry Andric // Now we know that each predecessor of this block has a value in 14220b57cec5SDimitry Andric // AvailablePreds, sort them for efficient access as we're walking the preds. 14230b57cec5SDimitry Andric array_pod_sort(AvailablePreds.begin(), AvailablePreds.end()); 14240b57cec5SDimitry Andric 14250b57cec5SDimitry Andric // Create a PHI node at the start of the block for the PRE'd load value. 1426*0fca6ea1SDimitry Andric PHINode *PN = PHINode::Create(LoadI->getType(), pred_size(LoadBB), ""); 14275f757f3fSDimitry Andric PN->insertBefore(LoadBB->begin()); 14280b57cec5SDimitry Andric PN->takeName(LoadI); 14290b57cec5SDimitry Andric PN->setDebugLoc(LoadI->getDebugLoc()); 14300b57cec5SDimitry Andric 14310b57cec5SDimitry Andric // Insert new entries into the PHI for each predecessor. A single block may 14320b57cec5SDimitry Andric // have multiple entries here. 1433*0fca6ea1SDimitry Andric for (BasicBlock *P : predecessors(LoadBB)) { 14340b57cec5SDimitry Andric AvailablePredsTy::iterator I = 14350b57cec5SDimitry Andric llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr)); 14360b57cec5SDimitry Andric 14370b57cec5SDimitry Andric assert(I != AvailablePreds.end() && I->first == P && 14380b57cec5SDimitry Andric "Didn't find entry for predecessor!"); 14390b57cec5SDimitry Andric 14400b57cec5SDimitry Andric // If we have an available predecessor but it requires casting, insert the 14410b57cec5SDimitry Andric // cast in the predecessor and use the cast. Note that we have to update the 14420b57cec5SDimitry Andric // AvailablePreds vector as we go so that all of the PHI entries for this 14430b57cec5SDimitry Andric // predecessor use the same bitcast. 14440b57cec5SDimitry Andric Value *&PredV = I->second; 14450b57cec5SDimitry Andric if (PredV->getType() != LoadI->getType()) 1446*0fca6ea1SDimitry Andric PredV = CastInst::CreateBitOrPointerCast( 1447*0fca6ea1SDimitry Andric PredV, LoadI->getType(), "", P->getTerminator()->getIterator()); 14480b57cec5SDimitry Andric 14490b57cec5SDimitry Andric PN->addIncoming(PredV, I->first); 14500b57cec5SDimitry Andric } 14510b57cec5SDimitry Andric 14520b57cec5SDimitry Andric for (LoadInst *PredLoadI : CSELoads) { 14530b57cec5SDimitry Andric combineMetadataForCSE(PredLoadI, LoadI, true); 14548a4dda33SDimitry Andric LVI->forgetValue(PredLoadI); 14550b57cec5SDimitry Andric } 14560b57cec5SDimitry Andric 14570b57cec5SDimitry Andric LoadI->replaceAllUsesWith(PN); 14580b57cec5SDimitry Andric LoadI->eraseFromParent(); 14590b57cec5SDimitry Andric 14600b57cec5SDimitry Andric return true; 14610b57cec5SDimitry Andric } 14620b57cec5SDimitry Andric 1463e8d8bef9SDimitry Andric /// findMostPopularDest - The specified list contains multiple possible 14640b57cec5SDimitry Andric /// threadable destinations. Pick the one that occurs the most frequently in 14650b57cec5SDimitry Andric /// the list. 14660b57cec5SDimitry Andric static BasicBlock * 1467e8d8bef9SDimitry Andric findMostPopularDest(BasicBlock *BB, 14680b57cec5SDimitry Andric const SmallVectorImpl<std::pair<BasicBlock *, 14690b57cec5SDimitry Andric BasicBlock *>> &PredToDestList) { 14700b57cec5SDimitry Andric assert(!PredToDestList.empty()); 14710b57cec5SDimitry Andric 14720b57cec5SDimitry Andric // Determine popularity. If there are multiple possible destinations, we 14730b57cec5SDimitry Andric // explicitly choose to ignore 'undef' destinations. We prefer to thread 14740b57cec5SDimitry Andric // blocks with known and real destinations to threading undef. We'll handle 14750b57cec5SDimitry Andric // them later if interesting. 14765ffd83dbSDimitry Andric MapVector<BasicBlock *, unsigned> DestPopularity; 14775ffd83dbSDimitry Andric 14785ffd83dbSDimitry Andric // Populate DestPopularity with the successors in the order they appear in the 14795ffd83dbSDimitry Andric // successor list. This way, we ensure determinism by iterating it in the 1480*0fca6ea1SDimitry Andric // same order in llvm::max_element below. We map nullptr to 0 so that we can 14815ffd83dbSDimitry Andric // return nullptr when PredToDestList contains nullptr only. 14825ffd83dbSDimitry Andric DestPopularity[nullptr] = 0; 14835ffd83dbSDimitry Andric for (auto *SuccBB : successors(BB)) 14845ffd83dbSDimitry Andric DestPopularity[SuccBB] = 0; 14855ffd83dbSDimitry Andric 14860b57cec5SDimitry Andric for (const auto &PredToDest : PredToDestList) 14870b57cec5SDimitry Andric if (PredToDest.second) 14880b57cec5SDimitry Andric DestPopularity[PredToDest.second]++; 14890b57cec5SDimitry Andric 14900b57cec5SDimitry Andric // Find the most popular dest. 1491*0fca6ea1SDimitry Andric auto MostPopular = llvm::max_element(DestPopularity, llvm::less_second()); 14920b57cec5SDimitry Andric 14930b57cec5SDimitry Andric // Okay, we have finally picked the most popular destination. 14945ffd83dbSDimitry Andric return MostPopular->first; 14955ffd83dbSDimitry Andric } 14965ffd83dbSDimitry Andric 14975ffd83dbSDimitry Andric // Try to evaluate the value of V when the control flows from PredPredBB to 14985ffd83dbSDimitry Andric // BB->getSinglePredecessor() and then on to BB. 1499e8d8bef9SDimitry Andric Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB, 15005ffd83dbSDimitry Andric BasicBlock *PredPredBB, 1501*0fca6ea1SDimitry Andric Value *V, 1502*0fca6ea1SDimitry Andric const DataLayout &DL) { 15035ffd83dbSDimitry Andric BasicBlock *PredBB = BB->getSinglePredecessor(); 15045ffd83dbSDimitry Andric assert(PredBB && "Expected a single predecessor"); 15055ffd83dbSDimitry Andric 15065ffd83dbSDimitry Andric if (Constant *Cst = dyn_cast<Constant>(V)) { 15075ffd83dbSDimitry Andric return Cst; 15085ffd83dbSDimitry Andric } 15095ffd83dbSDimitry Andric 15105ffd83dbSDimitry Andric // Consult LVI if V is not an instruction in BB or PredBB. 15115ffd83dbSDimitry Andric Instruction *I = dyn_cast<Instruction>(V); 15125ffd83dbSDimitry Andric if (!I || (I->getParent() != BB && I->getParent() != PredBB)) { 15135ffd83dbSDimitry Andric return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr); 15145ffd83dbSDimitry Andric } 15155ffd83dbSDimitry Andric 15165ffd83dbSDimitry Andric // Look into a PHI argument. 15175ffd83dbSDimitry Andric if (PHINode *PHI = dyn_cast<PHINode>(V)) { 15185ffd83dbSDimitry Andric if (PHI->getParent() == PredBB) 15195ffd83dbSDimitry Andric return dyn_cast<Constant>(PHI->getIncomingValueForBlock(PredPredBB)); 15205ffd83dbSDimitry Andric return nullptr; 15215ffd83dbSDimitry Andric } 15225ffd83dbSDimitry Andric 15235ffd83dbSDimitry Andric // If we have a CmpInst, try to fold it for each incoming edge into PredBB. 15245ffd83dbSDimitry Andric if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) { 15255ffd83dbSDimitry Andric if (CondCmp->getParent() == BB) { 15265ffd83dbSDimitry Andric Constant *Op0 = 1527*0fca6ea1SDimitry Andric evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0), DL); 15285ffd83dbSDimitry Andric Constant *Op1 = 1529*0fca6ea1SDimitry Andric evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1), DL); 15305ffd83dbSDimitry Andric if (Op0 && Op1) { 1531*0fca6ea1SDimitry Andric return ConstantFoldCompareInstOperands(CondCmp->getPredicate(), Op0, 1532*0fca6ea1SDimitry Andric Op1, DL); 15335ffd83dbSDimitry Andric } 15345ffd83dbSDimitry Andric } 15355ffd83dbSDimitry Andric return nullptr; 15365ffd83dbSDimitry Andric } 15375ffd83dbSDimitry Andric 15385ffd83dbSDimitry Andric return nullptr; 15390b57cec5SDimitry Andric } 15400b57cec5SDimitry Andric 1541e8d8bef9SDimitry Andric bool JumpThreadingPass::processThreadableEdges(Value *Cond, BasicBlock *BB, 15420b57cec5SDimitry Andric ConstantPreference Preference, 15430b57cec5SDimitry Andric Instruction *CxtI) { 15440b57cec5SDimitry Andric // If threading this would thread across a loop header, don't even try to 15450b57cec5SDimitry Andric // thread the edge. 15460b57cec5SDimitry Andric if (LoopHeaders.count(BB)) 15470b57cec5SDimitry Andric return false; 15480b57cec5SDimitry Andric 15490b57cec5SDimitry Andric PredValueInfoTy PredValues; 1550e8d8bef9SDimitry Andric if (!computeValueKnownInPredecessors(Cond, BB, PredValues, Preference, 15515ffd83dbSDimitry Andric CxtI)) { 15525ffd83dbSDimitry Andric // We don't have known values in predecessors. See if we can thread through 15535ffd83dbSDimitry Andric // BB and its sole predecessor. 1554e8d8bef9SDimitry Andric return maybethreadThroughTwoBasicBlocks(BB, Cond); 15555ffd83dbSDimitry Andric } 15560b57cec5SDimitry Andric 15570b57cec5SDimitry Andric assert(!PredValues.empty() && 1558e8d8bef9SDimitry Andric "computeValueKnownInPredecessors returned true with no values"); 15590b57cec5SDimitry Andric 15600b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "IN BB: " << *BB; 15610b57cec5SDimitry Andric for (const auto &PredValue : PredValues) { 15620b57cec5SDimitry Andric dbgs() << " BB '" << BB->getName() 15630b57cec5SDimitry Andric << "': FOUND condition = " << *PredValue.first 15640b57cec5SDimitry Andric << " for pred '" << PredValue.second->getName() << "'.\n"; 15650b57cec5SDimitry Andric }); 15660b57cec5SDimitry Andric 15670b57cec5SDimitry Andric // Decide what we want to thread through. Convert our list of known values to 15680b57cec5SDimitry Andric // a list of known destinations for each pred. This also discards duplicate 15690b57cec5SDimitry Andric // predecessors and keeps track of the undefined inputs (which are represented 15700b57cec5SDimitry Andric // as a null dest in the PredToDestList). 15710b57cec5SDimitry Andric SmallPtrSet<BasicBlock*, 16> SeenPreds; 15720b57cec5SDimitry Andric SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList; 15730b57cec5SDimitry Andric 15740b57cec5SDimitry Andric BasicBlock *OnlyDest = nullptr; 15750b57cec5SDimitry Andric BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL; 15760b57cec5SDimitry Andric Constant *OnlyVal = nullptr; 15770b57cec5SDimitry Andric Constant *MultipleVal = (Constant *)(intptr_t)~0ULL; 15780b57cec5SDimitry Andric 15790b57cec5SDimitry Andric for (const auto &PredValue : PredValues) { 15800b57cec5SDimitry Andric BasicBlock *Pred = PredValue.second; 15810b57cec5SDimitry Andric if (!SeenPreds.insert(Pred).second) 15820b57cec5SDimitry Andric continue; // Duplicate predecessor entry. 15830b57cec5SDimitry Andric 15840b57cec5SDimitry Andric Constant *Val = PredValue.first; 15850b57cec5SDimitry Andric 15860b57cec5SDimitry Andric BasicBlock *DestBB; 15870b57cec5SDimitry Andric if (isa<UndefValue>(Val)) 15880b57cec5SDimitry Andric DestBB = nullptr; 15890b57cec5SDimitry Andric else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 15900b57cec5SDimitry Andric assert(isa<ConstantInt>(Val) && "Expecting a constant integer"); 15910b57cec5SDimitry Andric DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero()); 15920b57cec5SDimitry Andric } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 15930b57cec5SDimitry Andric assert(isa<ConstantInt>(Val) && "Expecting a constant integer"); 15940b57cec5SDimitry Andric DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor(); 15950b57cec5SDimitry Andric } else { 15960b57cec5SDimitry Andric assert(isa<IndirectBrInst>(BB->getTerminator()) 15970b57cec5SDimitry Andric && "Unexpected terminator"); 15980b57cec5SDimitry Andric assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress"); 15990b57cec5SDimitry Andric DestBB = cast<BlockAddress>(Val)->getBasicBlock(); 16000b57cec5SDimitry Andric } 16010b57cec5SDimitry Andric 16020b57cec5SDimitry Andric // If we have exactly one destination, remember it for efficiency below. 16030b57cec5SDimitry Andric if (PredToDestList.empty()) { 16040b57cec5SDimitry Andric OnlyDest = DestBB; 16050b57cec5SDimitry Andric OnlyVal = Val; 16060b57cec5SDimitry Andric } else { 16070b57cec5SDimitry Andric if (OnlyDest != DestBB) 16080b57cec5SDimitry Andric OnlyDest = MultipleDestSentinel; 16090b57cec5SDimitry Andric // It possible we have same destination, but different value, e.g. default 16100b57cec5SDimitry Andric // case in switchinst. 16110b57cec5SDimitry Andric if (Val != OnlyVal) 16120b57cec5SDimitry Andric OnlyVal = MultipleVal; 16130b57cec5SDimitry Andric } 16140b57cec5SDimitry Andric 16150b57cec5SDimitry Andric // If the predecessor ends with an indirect goto, we can't change its 1616753f127fSDimitry Andric // destination. 1617753f127fSDimitry Andric if (isa<IndirectBrInst>(Pred->getTerminator())) 16180b57cec5SDimitry Andric continue; 16190b57cec5SDimitry Andric 16205ffd83dbSDimitry Andric PredToDestList.emplace_back(Pred, DestBB); 16210b57cec5SDimitry Andric } 16220b57cec5SDimitry Andric 16230b57cec5SDimitry Andric // If all edges were unthreadable, we fail. 16240b57cec5SDimitry Andric if (PredToDestList.empty()) 16250b57cec5SDimitry Andric return false; 16260b57cec5SDimitry Andric 16270b57cec5SDimitry Andric // If all the predecessors go to a single known successor, we want to fold, 16280b57cec5SDimitry Andric // not thread. By doing so, we do not need to duplicate the current block and 16290b57cec5SDimitry Andric // also miss potential opportunities in case we dont/cant duplicate. 16300b57cec5SDimitry Andric if (OnlyDest && OnlyDest != MultipleDestSentinel) { 16310b57cec5SDimitry Andric if (BB->hasNPredecessors(PredToDestList.size())) { 16320b57cec5SDimitry Andric bool SeenFirstBranchToOnlyDest = false; 16330b57cec5SDimitry Andric std::vector <DominatorTree::UpdateType> Updates; 16340b57cec5SDimitry Andric Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1); 16350b57cec5SDimitry Andric for (BasicBlock *SuccBB : successors(BB)) { 16360b57cec5SDimitry Andric if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) { 16370b57cec5SDimitry Andric SeenFirstBranchToOnlyDest = true; // Don't modify the first branch. 16380b57cec5SDimitry Andric } else { 16390b57cec5SDimitry Andric SuccBB->removePredecessor(BB, true); // This is unreachable successor. 16400b57cec5SDimitry Andric Updates.push_back({DominatorTree::Delete, BB, SuccBB}); 16410b57cec5SDimitry Andric } 16420b57cec5SDimitry Andric } 16430b57cec5SDimitry Andric 16440b57cec5SDimitry Andric // Finally update the terminator. 16450b57cec5SDimitry Andric Instruction *Term = BB->getTerminator(); 1646*0fca6ea1SDimitry Andric Instruction *NewBI = BranchInst::Create(OnlyDest, Term->getIterator()); 1647*0fca6ea1SDimitry Andric NewBI->setDebugLoc(Term->getDebugLoc()); 1648fe6060f1SDimitry Andric ++NumFolds; 16490b57cec5SDimitry Andric Term->eraseFromParent(); 16500b57cec5SDimitry Andric DTU->applyUpdatesPermissive(Updates); 165106c3fb27SDimitry Andric if (auto *BPI = getBPI()) 1652e8d8bef9SDimitry Andric BPI->eraseBlock(BB); 16530b57cec5SDimitry Andric 16540b57cec5SDimitry Andric // If the condition is now dead due to the removal of the old terminator, 16550b57cec5SDimitry Andric // erase it. 16560b57cec5SDimitry Andric if (auto *CondInst = dyn_cast<Instruction>(Cond)) { 16570b57cec5SDimitry Andric if (CondInst->use_empty() && !CondInst->mayHaveSideEffects()) 16580b57cec5SDimitry Andric CondInst->eraseFromParent(); 16590b57cec5SDimitry Andric // We can safely replace *some* uses of the CondInst if it has 16600b57cec5SDimitry Andric // exactly one value as returned by LVI. RAUW is incorrect in the 16610b57cec5SDimitry Andric // presence of guards and assumes, that have the `Cond` as the use. This 16620b57cec5SDimitry Andric // is because we use the guards/assume to reason about the `Cond` value 16630b57cec5SDimitry Andric // at the end of block, but RAUW unconditionally replaces all uses 16640b57cec5SDimitry Andric // including the guards/assumes themselves and the uses before the 16650b57cec5SDimitry Andric // guard/assume. 166681ad6265SDimitry Andric else if (OnlyVal && OnlyVal != MultipleVal) 166781ad6265SDimitry Andric replaceFoldableUses(CondInst, OnlyVal, BB); 16680b57cec5SDimitry Andric } 16690b57cec5SDimitry Andric return true; 16700b57cec5SDimitry Andric } 16710b57cec5SDimitry Andric } 16720b57cec5SDimitry Andric 16730b57cec5SDimitry Andric // Determine which is the most common successor. If we have many inputs and 16740b57cec5SDimitry Andric // this block is a switch, we want to start by threading the batch that goes 16750b57cec5SDimitry Andric // to the most popular destination first. If we only know about one 16760b57cec5SDimitry Andric // threadable destination (the common case) we can avoid this. 16770b57cec5SDimitry Andric BasicBlock *MostPopularDest = OnlyDest; 16780b57cec5SDimitry Andric 16790b57cec5SDimitry Andric if (MostPopularDest == MultipleDestSentinel) { 1680e8d8bef9SDimitry Andric // Remove any loop headers from the Dest list, threadEdge conservatively 16810b57cec5SDimitry Andric // won't process them, but we might have other destination that are eligible 16820b57cec5SDimitry Andric // and we still want to process. 16830b57cec5SDimitry Andric erase_if(PredToDestList, 16840b57cec5SDimitry Andric [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) { 1685e8d8bef9SDimitry Andric return LoopHeaders.contains(PredToDest.second); 16860b57cec5SDimitry Andric }); 16870b57cec5SDimitry Andric 16880b57cec5SDimitry Andric if (PredToDestList.empty()) 16890b57cec5SDimitry Andric return false; 16900b57cec5SDimitry Andric 1691e8d8bef9SDimitry Andric MostPopularDest = findMostPopularDest(BB, PredToDestList); 16920b57cec5SDimitry Andric } 16930b57cec5SDimitry Andric 16940b57cec5SDimitry Andric // Now that we know what the most popular destination is, factor all 16950b57cec5SDimitry Andric // predecessors that will jump to it into a single predecessor. 16960b57cec5SDimitry Andric SmallVector<BasicBlock*, 16> PredsToFactor; 16970b57cec5SDimitry Andric for (const auto &PredToDest : PredToDestList) 16980b57cec5SDimitry Andric if (PredToDest.second == MostPopularDest) { 16990b57cec5SDimitry Andric BasicBlock *Pred = PredToDest.first; 17000b57cec5SDimitry Andric 17010b57cec5SDimitry Andric // This predecessor may be a switch or something else that has multiple 17020b57cec5SDimitry Andric // edges to the block. Factor each of these edges by listing them 17030b57cec5SDimitry Andric // according to # occurrences in PredsToFactor. 17040b57cec5SDimitry Andric for (BasicBlock *Succ : successors(Pred)) 17050b57cec5SDimitry Andric if (Succ == BB) 17060b57cec5SDimitry Andric PredsToFactor.push_back(Pred); 17070b57cec5SDimitry Andric } 17080b57cec5SDimitry Andric 17090b57cec5SDimitry Andric // If the threadable edges are branching on an undefined value, we get to pick 17100b57cec5SDimitry Andric // the destination that these predecessors should get to. 17110b57cec5SDimitry Andric if (!MostPopularDest) 17120b57cec5SDimitry Andric MostPopularDest = BB->getTerminator()-> 1713e8d8bef9SDimitry Andric getSuccessor(getBestDestForJumpOnUndef(BB)); 17140b57cec5SDimitry Andric 17150b57cec5SDimitry Andric // Ok, try to thread it! 1716e8d8bef9SDimitry Andric return tryThreadEdge(BB, PredsToFactor, MostPopularDest); 17170b57cec5SDimitry Andric } 17180b57cec5SDimitry Andric 1719e8d8bef9SDimitry Andric /// processBranchOnPHI - We have an otherwise unthreadable conditional branch on 1720e8d8bef9SDimitry Andric /// a PHI node (or freeze PHI) in the current block. See if there are any 1721e8d8bef9SDimitry Andric /// simplifications we can do based on inputs to the phi node. 1722e8d8bef9SDimitry Andric bool JumpThreadingPass::processBranchOnPHI(PHINode *PN) { 17230b57cec5SDimitry Andric BasicBlock *BB = PN->getParent(); 17240b57cec5SDimitry Andric 17250b57cec5SDimitry Andric // TODO: We could make use of this to do it once for blocks with common PHI 17260b57cec5SDimitry Andric // values. 17270b57cec5SDimitry Andric SmallVector<BasicBlock*, 1> PredBBs; 17280b57cec5SDimitry Andric PredBBs.resize(1); 17290b57cec5SDimitry Andric 17300b57cec5SDimitry Andric // If any of the predecessor blocks end in an unconditional branch, we can 17310b57cec5SDimitry Andric // *duplicate* the conditional branch into that block in order to further 17320b57cec5SDimitry Andric // encourage jump threading and to eliminate cases where we have branch on a 17330b57cec5SDimitry Andric // phi of an icmp (branch on icmp is much better). 1734e8d8bef9SDimitry Andric // This is still beneficial when a frozen phi is used as the branch condition 1735e8d8bef9SDimitry Andric // because it allows CodeGenPrepare to further canonicalize br(freeze(icmp)) 1736e8d8bef9SDimitry Andric // to br(icmp(freeze ...)). 17370b57cec5SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 17380b57cec5SDimitry Andric BasicBlock *PredBB = PN->getIncomingBlock(i); 17390b57cec5SDimitry Andric if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator())) 17400b57cec5SDimitry Andric if (PredBr->isUnconditional()) { 17410b57cec5SDimitry Andric PredBBs[0] = PredBB; 17420b57cec5SDimitry Andric // Try to duplicate BB into PredBB. 1743e8d8bef9SDimitry Andric if (duplicateCondBranchOnPHIIntoPred(BB, PredBBs)) 17440b57cec5SDimitry Andric return true; 17450b57cec5SDimitry Andric } 17460b57cec5SDimitry Andric } 17470b57cec5SDimitry Andric 17480b57cec5SDimitry Andric return false; 17490b57cec5SDimitry Andric } 17500b57cec5SDimitry Andric 1751e8d8bef9SDimitry Andric /// processBranchOnXOR - We have an otherwise unthreadable conditional branch on 17520b57cec5SDimitry Andric /// a xor instruction in the current block. See if there are any 17530b57cec5SDimitry Andric /// simplifications we can do based on inputs to the xor. 1754e8d8bef9SDimitry Andric bool JumpThreadingPass::processBranchOnXOR(BinaryOperator *BO) { 17550b57cec5SDimitry Andric BasicBlock *BB = BO->getParent(); 17560b57cec5SDimitry Andric 17570b57cec5SDimitry Andric // If either the LHS or RHS of the xor is a constant, don't do this 17580b57cec5SDimitry Andric // optimization. 17590b57cec5SDimitry Andric if (isa<ConstantInt>(BO->getOperand(0)) || 17600b57cec5SDimitry Andric isa<ConstantInt>(BO->getOperand(1))) 17610b57cec5SDimitry Andric return false; 17620b57cec5SDimitry Andric 17630b57cec5SDimitry Andric // If the first instruction in BB isn't a phi, we won't be able to infer 17640b57cec5SDimitry Andric // anything special about any particular predecessor. 17650b57cec5SDimitry Andric if (!isa<PHINode>(BB->front())) 17660b57cec5SDimitry Andric return false; 17670b57cec5SDimitry Andric 17680b57cec5SDimitry Andric // If this BB is a landing pad, we won't be able to split the edge into it. 17690b57cec5SDimitry Andric if (BB->isEHPad()) 17700b57cec5SDimitry Andric return false; 17710b57cec5SDimitry Andric 17720b57cec5SDimitry Andric // If we have a xor as the branch input to this block, and we know that the 17730b57cec5SDimitry Andric // LHS or RHS of the xor in any predecessor is true/false, then we can clone 17740b57cec5SDimitry Andric // the condition into the predecessor and fix that value to true, saving some 17750b57cec5SDimitry Andric // logical ops on that path and encouraging other paths to simplify. 17760b57cec5SDimitry Andric // 17770b57cec5SDimitry Andric // This copies something like this: 17780b57cec5SDimitry Andric // 17790b57cec5SDimitry Andric // BB: 17800b57cec5SDimitry Andric // %X = phi i1 [1], [%X'] 17810b57cec5SDimitry Andric // %Y = icmp eq i32 %A, %B 17820b57cec5SDimitry Andric // %Z = xor i1 %X, %Y 17830b57cec5SDimitry Andric // br i1 %Z, ... 17840b57cec5SDimitry Andric // 17850b57cec5SDimitry Andric // Into: 17860b57cec5SDimitry Andric // BB': 17870b57cec5SDimitry Andric // %Y = icmp ne i32 %A, %B 17880b57cec5SDimitry Andric // br i1 %Y, ... 17890b57cec5SDimitry Andric 17900b57cec5SDimitry Andric PredValueInfoTy XorOpValues; 17910b57cec5SDimitry Andric bool isLHS = true; 1792e8d8bef9SDimitry Andric if (!computeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues, 17930b57cec5SDimitry Andric WantInteger, BO)) { 17940b57cec5SDimitry Andric assert(XorOpValues.empty()); 1795e8d8bef9SDimitry Andric if (!computeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues, 17960b57cec5SDimitry Andric WantInteger, BO)) 17970b57cec5SDimitry Andric return false; 17980b57cec5SDimitry Andric isLHS = false; 17990b57cec5SDimitry Andric } 18000b57cec5SDimitry Andric 18010b57cec5SDimitry Andric assert(!XorOpValues.empty() && 1802e8d8bef9SDimitry Andric "computeValueKnownInPredecessors returned true with no values"); 18030b57cec5SDimitry Andric 18040b57cec5SDimitry Andric // Scan the information to see which is most popular: true or false. The 18050b57cec5SDimitry Andric // predecessors can be of the set true, false, or undef. 18060b57cec5SDimitry Andric unsigned NumTrue = 0, NumFalse = 0; 18070b57cec5SDimitry Andric for (const auto &XorOpValue : XorOpValues) { 18080b57cec5SDimitry Andric if (isa<UndefValue>(XorOpValue.first)) 18090b57cec5SDimitry Andric // Ignore undefs for the count. 18100b57cec5SDimitry Andric continue; 18110b57cec5SDimitry Andric if (cast<ConstantInt>(XorOpValue.first)->isZero()) 18120b57cec5SDimitry Andric ++NumFalse; 18130b57cec5SDimitry Andric else 18140b57cec5SDimitry Andric ++NumTrue; 18150b57cec5SDimitry Andric } 18160b57cec5SDimitry Andric 18170b57cec5SDimitry Andric // Determine which value to split on, true, false, or undef if neither. 18180b57cec5SDimitry Andric ConstantInt *SplitVal = nullptr; 18190b57cec5SDimitry Andric if (NumTrue > NumFalse) 18200b57cec5SDimitry Andric SplitVal = ConstantInt::getTrue(BB->getContext()); 18210b57cec5SDimitry Andric else if (NumTrue != 0 || NumFalse != 0) 18220b57cec5SDimitry Andric SplitVal = ConstantInt::getFalse(BB->getContext()); 18230b57cec5SDimitry Andric 18240b57cec5SDimitry Andric // Collect all of the blocks that this can be folded into so that we can 18250b57cec5SDimitry Andric // factor this once and clone it once. 18260b57cec5SDimitry Andric SmallVector<BasicBlock*, 8> BlocksToFoldInto; 18270b57cec5SDimitry Andric for (const auto &XorOpValue : XorOpValues) { 18280b57cec5SDimitry Andric if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first)) 18290b57cec5SDimitry Andric continue; 18300b57cec5SDimitry Andric 18310b57cec5SDimitry Andric BlocksToFoldInto.push_back(XorOpValue.second); 18320b57cec5SDimitry Andric } 18330b57cec5SDimitry Andric 18340b57cec5SDimitry Andric // If we inferred a value for all of the predecessors, then duplication won't 18350b57cec5SDimitry Andric // help us. However, we can just replace the LHS or RHS with the constant. 18360b57cec5SDimitry Andric if (BlocksToFoldInto.size() == 18370b57cec5SDimitry Andric cast<PHINode>(BB->front()).getNumIncomingValues()) { 18380b57cec5SDimitry Andric if (!SplitVal) { 18390b57cec5SDimitry Andric // If all preds provide undef, just nuke the xor, because it is undef too. 18400b57cec5SDimitry Andric BO->replaceAllUsesWith(UndefValue::get(BO->getType())); 18410b57cec5SDimitry Andric BO->eraseFromParent(); 1842bdd1243dSDimitry Andric } else if (SplitVal->isZero() && BO != BO->getOperand(isLHS)) { 18430b57cec5SDimitry Andric // If all preds provide 0, replace the xor with the other input. 18440b57cec5SDimitry Andric BO->replaceAllUsesWith(BO->getOperand(isLHS)); 18450b57cec5SDimitry Andric BO->eraseFromParent(); 18460b57cec5SDimitry Andric } else { 18470b57cec5SDimitry Andric // If all preds provide 1, set the computed value to 1. 18480b57cec5SDimitry Andric BO->setOperand(!isLHS, SplitVal); 18490b57cec5SDimitry Andric } 18500b57cec5SDimitry Andric 18510b57cec5SDimitry Andric return true; 18520b57cec5SDimitry Andric } 18530b57cec5SDimitry Andric 1854979e22ffSDimitry Andric // If any of predecessors end with an indirect goto, we can't change its 1855753f127fSDimitry Andric // destination. 1856979e22ffSDimitry Andric if (any_of(BlocksToFoldInto, [](BasicBlock *Pred) { 1857753f127fSDimitry Andric return isa<IndirectBrInst>(Pred->getTerminator()); 1858979e22ffSDimitry Andric })) 1859979e22ffSDimitry Andric return false; 1860979e22ffSDimitry Andric 18610b57cec5SDimitry Andric // Try to duplicate BB into PredBB. 1862e8d8bef9SDimitry Andric return duplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto); 18630b57cec5SDimitry Andric } 18640b57cec5SDimitry Andric 1865e8d8bef9SDimitry Andric /// addPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new 18660b57cec5SDimitry Andric /// predecessor to the PHIBB block. If it has PHI nodes, add entries for 18670b57cec5SDimitry Andric /// NewPred using the entries from OldPred (suitably mapped). 1868e8d8bef9SDimitry Andric static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, 18690b57cec5SDimitry Andric BasicBlock *OldPred, 18700b57cec5SDimitry Andric BasicBlock *NewPred, 1871*0fca6ea1SDimitry Andric ValueToValueMapTy &ValueMap) { 18720b57cec5SDimitry Andric for (PHINode &PN : PHIBB->phis()) { 18730b57cec5SDimitry Andric // Ok, we have a PHI node. Figure out what the incoming value was for the 18740b57cec5SDimitry Andric // DestBlock. 18750b57cec5SDimitry Andric Value *IV = PN.getIncomingValueForBlock(OldPred); 18760b57cec5SDimitry Andric 18770b57cec5SDimitry Andric // Remap the value if necessary. 18780b57cec5SDimitry Andric if (Instruction *Inst = dyn_cast<Instruction>(IV)) { 1879*0fca6ea1SDimitry Andric ValueToValueMapTy::iterator I = ValueMap.find(Inst); 18800b57cec5SDimitry Andric if (I != ValueMap.end()) 18810b57cec5SDimitry Andric IV = I->second; 18820b57cec5SDimitry Andric } 18830b57cec5SDimitry Andric 18840b57cec5SDimitry Andric PN.addIncoming(IV, NewPred); 18850b57cec5SDimitry Andric } 18860b57cec5SDimitry Andric } 18870b57cec5SDimitry Andric 1888480093f4SDimitry Andric /// Merge basic block BB into its sole predecessor if possible. 1889e8d8bef9SDimitry Andric bool JumpThreadingPass::maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) { 1890480093f4SDimitry Andric BasicBlock *SinglePred = BB->getSinglePredecessor(); 1891480093f4SDimitry Andric if (!SinglePred) 1892480093f4SDimitry Andric return false; 1893480093f4SDimitry Andric 1894480093f4SDimitry Andric const Instruction *TI = SinglePred->getTerminator(); 18955f757f3fSDimitry Andric if (TI->isSpecialTerminator() || TI->getNumSuccessors() != 1 || 1896480093f4SDimitry Andric SinglePred == BB || hasAddressTakenAndUsed(BB)) 1897480093f4SDimitry Andric return false; 1898480093f4SDimitry Andric 1899480093f4SDimitry Andric // If SinglePred was a loop header, BB becomes one. 1900480093f4SDimitry Andric if (LoopHeaders.erase(SinglePred)) 1901480093f4SDimitry Andric LoopHeaders.insert(BB); 1902480093f4SDimitry Andric 1903480093f4SDimitry Andric LVI->eraseBlock(SinglePred); 190406c3fb27SDimitry Andric MergeBasicBlockIntoOnlyPred(BB, DTU.get()); 1905480093f4SDimitry Andric 1906480093f4SDimitry Andric // Now that BB is merged into SinglePred (i.e. SinglePred code followed by 1907480093f4SDimitry Andric // BB code within one basic block `BB`), we need to invalidate the LVI 1908480093f4SDimitry Andric // information associated with BB, because the LVI information need not be 1909480093f4SDimitry Andric // true for all of BB after the merge. For example, 1910480093f4SDimitry Andric // Before the merge, LVI info and code is as follows: 1911480093f4SDimitry Andric // SinglePred: <LVI info1 for %p val> 1912480093f4SDimitry Andric // %y = use of %p 1913480093f4SDimitry Andric // call @exit() // need not transfer execution to successor. 1914480093f4SDimitry Andric // assume(%p) // from this point on %p is true 1915480093f4SDimitry Andric // br label %BB 1916480093f4SDimitry Andric // BB: <LVI info2 for %p val, i.e. %p is true> 1917480093f4SDimitry Andric // %x = use of %p 1918480093f4SDimitry Andric // br label exit 1919480093f4SDimitry Andric // 1920480093f4SDimitry Andric // Note that this LVI info for blocks BB and SinglPred is correct for %p 1921480093f4SDimitry Andric // (info2 and info1 respectively). After the merge and the deletion of the 1922480093f4SDimitry Andric // LVI info1 for SinglePred. We have the following code: 1923480093f4SDimitry Andric // BB: <LVI info2 for %p val> 1924480093f4SDimitry Andric // %y = use of %p 1925480093f4SDimitry Andric // call @exit() 1926480093f4SDimitry Andric // assume(%p) 1927480093f4SDimitry Andric // %x = use of %p <-- LVI info2 is correct from here onwards. 1928480093f4SDimitry Andric // br label exit 1929480093f4SDimitry Andric // LVI info2 for BB is incorrect at the beginning of BB. 1930480093f4SDimitry Andric 1931480093f4SDimitry Andric // Invalidate LVI information for BB if the LVI is not provably true for 1932480093f4SDimitry Andric // all of BB. 1933480093f4SDimitry Andric if (!isGuaranteedToTransferExecutionToSuccessor(BB)) 1934480093f4SDimitry Andric LVI->eraseBlock(BB); 1935480093f4SDimitry Andric return true; 1936480093f4SDimitry Andric } 1937480093f4SDimitry Andric 1938480093f4SDimitry Andric /// Update the SSA form. NewBB contains instructions that are copied from BB. 1939480093f4SDimitry Andric /// ValueMapping maps old values in BB to new ones in NewBB. 1940*0fca6ea1SDimitry Andric void JumpThreadingPass::updateSSA(BasicBlock *BB, BasicBlock *NewBB, 1941*0fca6ea1SDimitry Andric ValueToValueMapTy &ValueMapping) { 1942480093f4SDimitry Andric // If there were values defined in BB that are used outside the block, then we 1943480093f4SDimitry Andric // now have to update all uses of the value to use either the original value, 1944480093f4SDimitry Andric // the cloned value, or some PHI derived value. This can require arbitrary 1945480093f4SDimitry Andric // PHI insertion, of which we are prepared to do, clean these up now. 1946480093f4SDimitry Andric SSAUpdater SSAUpdate; 1947480093f4SDimitry Andric SmallVector<Use *, 16> UsesToRename; 194806c3fb27SDimitry Andric SmallVector<DbgValueInst *, 4> DbgValues; 1949*0fca6ea1SDimitry Andric SmallVector<DbgVariableRecord *, 4> DbgVariableRecords; 1950480093f4SDimitry Andric 1951480093f4SDimitry Andric for (Instruction &I : *BB) { 1952480093f4SDimitry Andric // Scan all uses of this instruction to see if it is used outside of its 1953480093f4SDimitry Andric // block, and if so, record them in UsesToRename. 1954480093f4SDimitry Andric for (Use &U : I.uses()) { 1955480093f4SDimitry Andric Instruction *User = cast<Instruction>(U.getUser()); 1956480093f4SDimitry Andric if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 1957480093f4SDimitry Andric if (UserPN->getIncomingBlock(U) == BB) 1958480093f4SDimitry Andric continue; 1959480093f4SDimitry Andric } else if (User->getParent() == BB) 1960480093f4SDimitry Andric continue; 1961480093f4SDimitry Andric 1962480093f4SDimitry Andric UsesToRename.push_back(&U); 1963480093f4SDimitry Andric } 1964480093f4SDimitry Andric 196506c3fb27SDimitry Andric // Find debug values outside of the block 1966*0fca6ea1SDimitry Andric findDbgValues(DbgValues, &I, &DbgVariableRecords); 19675f757f3fSDimitry Andric llvm::erase_if(DbgValues, [&](const DbgValueInst *DbgVal) { 196806c3fb27SDimitry Andric return DbgVal->getParent() == BB; 19695f757f3fSDimitry Andric }); 1970*0fca6ea1SDimitry Andric llvm::erase_if(DbgVariableRecords, [&](const DbgVariableRecord *DbgVarRec) { 1971*0fca6ea1SDimitry Andric return DbgVarRec->getParent() == BB; 19725f757f3fSDimitry Andric }); 197306c3fb27SDimitry Andric 1974480093f4SDimitry Andric // If there are no uses outside the block, we're done with this instruction. 1975*0fca6ea1SDimitry Andric if (UsesToRename.empty() && DbgValues.empty() && DbgVariableRecords.empty()) 1976480093f4SDimitry Andric continue; 1977480093f4SDimitry Andric LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n"); 1978480093f4SDimitry Andric 1979480093f4SDimitry Andric // We found a use of I outside of BB. Rename all uses of I that are outside 1980480093f4SDimitry Andric // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 1981480093f4SDimitry Andric // with the two values we know. 1982480093f4SDimitry Andric SSAUpdate.Initialize(I.getType(), I.getName()); 1983480093f4SDimitry Andric SSAUpdate.AddAvailableValue(BB, &I); 1984480093f4SDimitry Andric SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]); 1985480093f4SDimitry Andric 1986480093f4SDimitry Andric while (!UsesToRename.empty()) 1987480093f4SDimitry Andric SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 1988*0fca6ea1SDimitry Andric if (!DbgValues.empty() || !DbgVariableRecords.empty()) { 198906c3fb27SDimitry Andric SSAUpdate.UpdateDebugValues(&I, DbgValues); 1990*0fca6ea1SDimitry Andric SSAUpdate.UpdateDebugValues(&I, DbgVariableRecords); 199106c3fb27SDimitry Andric DbgValues.clear(); 1992*0fca6ea1SDimitry Andric DbgVariableRecords.clear(); 199306c3fb27SDimitry Andric } 199406c3fb27SDimitry Andric 1995480093f4SDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 1996480093f4SDimitry Andric } 1997480093f4SDimitry Andric } 1998480093f4SDimitry Andric 1999480093f4SDimitry Andric /// Clone instructions in range [BI, BE) to NewBB. For PHI nodes, we only clone 2000480093f4SDimitry Andric /// arguments that come from PredBB. Return the map from the variables in the 2001480093f4SDimitry Andric /// source basic block to the variables in the newly created basic block. 2002*0fca6ea1SDimitry Andric 2003*0fca6ea1SDimitry Andric void JumpThreadingPass::cloneInstructions(ValueToValueMapTy &ValueMapping, 2004*0fca6ea1SDimitry Andric BasicBlock::iterator BI, 2005*0fca6ea1SDimitry Andric BasicBlock::iterator BE, 2006*0fca6ea1SDimitry Andric BasicBlock *NewBB, 2007480093f4SDimitry Andric BasicBlock *PredBB) { 2008480093f4SDimitry Andric // We are going to have to map operands from the source basic block to the new 2009480093f4SDimitry Andric // copy of the block 'NewBB'. If there are PHI nodes in the source basic 2010480093f4SDimitry Andric // block, evaluate them to account for entry from PredBB. 2011480093f4SDimitry Andric 2012bdd1243dSDimitry Andric // Retargets llvm.dbg.value to any renamed variables. 2013bdd1243dSDimitry Andric auto RetargetDbgValueIfPossible = [&](Instruction *NewInst) -> bool { 2014bdd1243dSDimitry Andric auto DbgInstruction = dyn_cast<DbgValueInst>(NewInst); 2015bdd1243dSDimitry Andric if (!DbgInstruction) 2016bdd1243dSDimitry Andric return false; 2017bdd1243dSDimitry Andric 2018bdd1243dSDimitry Andric SmallSet<std::pair<Value *, Value *>, 16> OperandsToRemap; 2019bdd1243dSDimitry Andric for (auto DbgOperand : DbgInstruction->location_ops()) { 2020bdd1243dSDimitry Andric auto DbgOperandInstruction = dyn_cast<Instruction>(DbgOperand); 2021bdd1243dSDimitry Andric if (!DbgOperandInstruction) 2022bdd1243dSDimitry Andric continue; 2023bdd1243dSDimitry Andric 2024bdd1243dSDimitry Andric auto I = ValueMapping.find(DbgOperandInstruction); 2025bdd1243dSDimitry Andric if (I != ValueMapping.end()) { 2026bdd1243dSDimitry Andric OperandsToRemap.insert( 2027bdd1243dSDimitry Andric std::pair<Value *, Value *>(DbgOperand, I->second)); 2028bdd1243dSDimitry Andric } 2029bdd1243dSDimitry Andric } 2030bdd1243dSDimitry Andric 2031bdd1243dSDimitry Andric for (auto &[OldOp, MappedOp] : OperandsToRemap) 2032bdd1243dSDimitry Andric DbgInstruction->replaceVariableLocationOp(OldOp, MappedOp); 2033bdd1243dSDimitry Andric return true; 2034bdd1243dSDimitry Andric }; 2035bdd1243dSDimitry Andric 2036*0fca6ea1SDimitry Andric // Duplicate implementation of the above dbg.value code, using 2037*0fca6ea1SDimitry Andric // DbgVariableRecords instead. 2038*0fca6ea1SDimitry Andric auto RetargetDbgVariableRecordIfPossible = [&](DbgVariableRecord *DVR) { 20395f757f3fSDimitry Andric SmallSet<std::pair<Value *, Value *>, 16> OperandsToRemap; 2040*0fca6ea1SDimitry Andric for (auto *Op : DVR->location_ops()) { 20415f757f3fSDimitry Andric Instruction *OpInst = dyn_cast<Instruction>(Op); 20425f757f3fSDimitry Andric if (!OpInst) 20435f757f3fSDimitry Andric continue; 20445f757f3fSDimitry Andric 20455f757f3fSDimitry Andric auto I = ValueMapping.find(OpInst); 20465f757f3fSDimitry Andric if (I != ValueMapping.end()) 20475f757f3fSDimitry Andric OperandsToRemap.insert({OpInst, I->second}); 20485f757f3fSDimitry Andric } 20495f757f3fSDimitry Andric 20505f757f3fSDimitry Andric for (auto &[OldOp, MappedOp] : OperandsToRemap) 2051*0fca6ea1SDimitry Andric DVR->replaceVariableLocationOp(OldOp, MappedOp); 20525f757f3fSDimitry Andric }; 20535f757f3fSDimitry Andric 20545f757f3fSDimitry Andric BasicBlock *RangeBB = BI->getParent(); 20555f757f3fSDimitry Andric 2056480093f4SDimitry Andric // Clone the phi nodes of the source basic block into NewBB. The resulting 2057480093f4SDimitry Andric // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater 2058480093f4SDimitry Andric // might need to rewrite the operand of the cloned phi. 2059480093f4SDimitry Andric for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) { 2060480093f4SDimitry Andric PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB); 2061480093f4SDimitry Andric NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB); 2062480093f4SDimitry Andric ValueMapping[PN] = NewPN; 2063480093f4SDimitry Andric } 2064480093f4SDimitry Andric 2065d409305fSDimitry Andric // Clone noalias scope declarations in the threaded block. When threading a 2066d409305fSDimitry Andric // loop exit, we would otherwise end up with two idential scope declarations 2067d409305fSDimitry Andric // visible at the same time. 2068d409305fSDimitry Andric SmallVector<MDNode *> NoAliasScopes; 2069d409305fSDimitry Andric DenseMap<MDNode *, MDNode *> ClonedScopes; 2070d409305fSDimitry Andric LLVMContext &Context = PredBB->getContext(); 2071d409305fSDimitry Andric identifyNoAliasScopesToClone(BI, BE, NoAliasScopes); 2072d409305fSDimitry Andric cloneNoAliasScopes(NoAliasScopes, ClonedScopes, "thread", Context); 2073d409305fSDimitry Andric 20745f757f3fSDimitry Andric auto CloneAndRemapDbgInfo = [&](Instruction *NewInst, Instruction *From) { 2075*0fca6ea1SDimitry Andric auto DVRRange = NewInst->cloneDebugInfoFrom(From); 2076*0fca6ea1SDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(DVRRange)) 2077*0fca6ea1SDimitry Andric RetargetDbgVariableRecordIfPossible(&DVR); 20785f757f3fSDimitry Andric }; 20795f757f3fSDimitry Andric 2080480093f4SDimitry Andric // Clone the non-phi instructions of the source basic block into NewBB, 2081480093f4SDimitry Andric // keeping track of the mapping and using it to remap operands in the cloned 2082480093f4SDimitry Andric // instructions. 2083480093f4SDimitry Andric for (; BI != BE; ++BI) { 2084480093f4SDimitry Andric Instruction *New = BI->clone(); 2085480093f4SDimitry Andric New->setName(BI->getName()); 2086bdd1243dSDimitry Andric New->insertInto(NewBB, NewBB->end()); 2087480093f4SDimitry Andric ValueMapping[&*BI] = New; 2088d409305fSDimitry Andric adaptNoAliasScopes(New, ClonedScopes, Context); 2089480093f4SDimitry Andric 20905f757f3fSDimitry Andric CloneAndRemapDbgInfo(New, &*BI); 20915f757f3fSDimitry Andric 2092bdd1243dSDimitry Andric if (RetargetDbgValueIfPossible(New)) 2093bdd1243dSDimitry Andric continue; 2094bdd1243dSDimitry Andric 2095480093f4SDimitry Andric // Remap operands to patch up intra-block references. 2096480093f4SDimitry Andric for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 2097480093f4SDimitry Andric if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 2098*0fca6ea1SDimitry Andric ValueToValueMapTy::iterator I = ValueMapping.find(Inst); 2099480093f4SDimitry Andric if (I != ValueMapping.end()) 2100480093f4SDimitry Andric New->setOperand(i, I->second); 2101480093f4SDimitry Andric } 2102480093f4SDimitry Andric } 2103480093f4SDimitry Andric 2104*0fca6ea1SDimitry Andric // There may be DbgVariableRecords on the terminator, clone directly from 2105*0fca6ea1SDimitry Andric // marker to marker as there isn't an instruction there. 2106*0fca6ea1SDimitry Andric if (BE != RangeBB->end() && BE->hasDbgRecords()) { 21075f757f3fSDimitry Andric // Dump them at the end. 2108*0fca6ea1SDimitry Andric DbgMarker *Marker = RangeBB->getMarker(BE); 2109*0fca6ea1SDimitry Andric DbgMarker *EndMarker = NewBB->createMarker(NewBB->end()); 2110*0fca6ea1SDimitry Andric auto DVRRange = EndMarker->cloneDebugInfoFrom(Marker, std::nullopt); 2111*0fca6ea1SDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(DVRRange)) 2112*0fca6ea1SDimitry Andric RetargetDbgVariableRecordIfPossible(&DVR); 21135f757f3fSDimitry Andric } 21145f757f3fSDimitry Andric 2115*0fca6ea1SDimitry Andric return; 2116480093f4SDimitry Andric } 2117480093f4SDimitry Andric 21185ffd83dbSDimitry Andric /// Attempt to thread through two successive basic blocks. 2119e8d8bef9SDimitry Andric bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB, 21205ffd83dbSDimitry Andric Value *Cond) { 21215ffd83dbSDimitry Andric // Consider: 21225ffd83dbSDimitry Andric // 21235ffd83dbSDimitry Andric // PredBB: 21245ffd83dbSDimitry Andric // %var = phi i32* [ null, %bb1 ], [ @a, %bb2 ] 21255ffd83dbSDimitry Andric // %tobool = icmp eq i32 %cond, 0 21265ffd83dbSDimitry Andric // br i1 %tobool, label %BB, label ... 21275ffd83dbSDimitry Andric // 21285ffd83dbSDimitry Andric // BB: 21295ffd83dbSDimitry Andric // %cmp = icmp eq i32* %var, null 21305ffd83dbSDimitry Andric // br i1 %cmp, label ..., label ... 21315ffd83dbSDimitry Andric // 21325ffd83dbSDimitry Andric // We don't know the value of %var at BB even if we know which incoming edge 21335ffd83dbSDimitry Andric // we take to BB. However, once we duplicate PredBB for each of its incoming 21345ffd83dbSDimitry Andric // edges (say, PredBB1 and PredBB2), we know the value of %var in each copy of 21355ffd83dbSDimitry Andric // PredBB. Then we can thread edges PredBB1->BB and PredBB2->BB through BB. 21365ffd83dbSDimitry Andric 21375ffd83dbSDimitry Andric // Require that BB end with a Branch for simplicity. 21385ffd83dbSDimitry Andric BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 21395ffd83dbSDimitry Andric if (!CondBr) 21405ffd83dbSDimitry Andric return false; 21415ffd83dbSDimitry Andric 21425ffd83dbSDimitry Andric // BB must have exactly one predecessor. 21435ffd83dbSDimitry Andric BasicBlock *PredBB = BB->getSinglePredecessor(); 21445ffd83dbSDimitry Andric if (!PredBB) 21455ffd83dbSDimitry Andric return false; 21465ffd83dbSDimitry Andric 21475ffd83dbSDimitry Andric // Require that PredBB end with a conditional Branch. If PredBB ends with an 21485ffd83dbSDimitry Andric // unconditional branch, we should be merging PredBB and BB instead. For 21495ffd83dbSDimitry Andric // simplicity, we don't deal with a switch. 21505ffd83dbSDimitry Andric BranchInst *PredBBBranch = dyn_cast<BranchInst>(PredBB->getTerminator()); 21515ffd83dbSDimitry Andric if (!PredBBBranch || PredBBBranch->isUnconditional()) 21525ffd83dbSDimitry Andric return false; 21535ffd83dbSDimitry Andric 21545ffd83dbSDimitry Andric // If PredBB has exactly one incoming edge, we don't gain anything by copying 21555ffd83dbSDimitry Andric // PredBB. 21565ffd83dbSDimitry Andric if (PredBB->getSinglePredecessor()) 21575ffd83dbSDimitry Andric return false; 21585ffd83dbSDimitry Andric 21595ffd83dbSDimitry Andric // Don't thread through PredBB if it contains a successor edge to itself, in 21605ffd83dbSDimitry Andric // which case we would infinite loop. Suppose we are threading an edge from 21615ffd83dbSDimitry Andric // PredPredBB through PredBB and BB to SuccBB with PredBB containing a 21625ffd83dbSDimitry Andric // successor edge to itself. If we allowed jump threading in this case, we 21635ffd83dbSDimitry Andric // could duplicate PredBB and BB as, say, PredBB.thread and BB.thread. Since 21645ffd83dbSDimitry Andric // PredBB.thread has a successor edge to PredBB, we would immediately come up 21655ffd83dbSDimitry Andric // with another jump threading opportunity from PredBB.thread through PredBB 21665ffd83dbSDimitry Andric // and BB to SuccBB. This jump threading would repeatedly occur. That is, we 21675ffd83dbSDimitry Andric // would keep peeling one iteration from PredBB. 21685ffd83dbSDimitry Andric if (llvm::is_contained(successors(PredBB), PredBB)) 21695ffd83dbSDimitry Andric return false; 21705ffd83dbSDimitry Andric 21715ffd83dbSDimitry Andric // Don't thread across a loop header. 21725ffd83dbSDimitry Andric if (LoopHeaders.count(PredBB)) 21735ffd83dbSDimitry Andric return false; 21745ffd83dbSDimitry Andric 21755ffd83dbSDimitry Andric // Avoid complication with duplicating EH pads. 21765ffd83dbSDimitry Andric if (PredBB->isEHPad()) 21775ffd83dbSDimitry Andric return false; 21785ffd83dbSDimitry Andric 21795ffd83dbSDimitry Andric // Find a predecessor that we can thread. For simplicity, we only consider a 21805ffd83dbSDimitry Andric // successor edge out of BB to which we thread exactly one incoming edge into 21815ffd83dbSDimitry Andric // PredBB. 21825ffd83dbSDimitry Andric unsigned ZeroCount = 0; 21835ffd83dbSDimitry Andric unsigned OneCount = 0; 21845ffd83dbSDimitry Andric BasicBlock *ZeroPred = nullptr; 21855ffd83dbSDimitry Andric BasicBlock *OnePred = nullptr; 2186*0fca6ea1SDimitry Andric const DataLayout &DL = BB->getDataLayout(); 21875ffd83dbSDimitry Andric for (BasicBlock *P : predecessors(PredBB)) { 2188753f127fSDimitry Andric // If PredPred ends with IndirectBrInst, we can't handle it. 2189753f127fSDimitry Andric if (isa<IndirectBrInst>(P->getTerminator())) 2190753f127fSDimitry Andric continue; 21915ffd83dbSDimitry Andric if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>( 2192*0fca6ea1SDimitry Andric evaluateOnPredecessorEdge(BB, P, Cond, DL))) { 21935ffd83dbSDimitry Andric if (CI->isZero()) { 21945ffd83dbSDimitry Andric ZeroCount++; 21955ffd83dbSDimitry Andric ZeroPred = P; 21965ffd83dbSDimitry Andric } else if (CI->isOne()) { 21975ffd83dbSDimitry Andric OneCount++; 21985ffd83dbSDimitry Andric OnePred = P; 21995ffd83dbSDimitry Andric } 22005ffd83dbSDimitry Andric } 22015ffd83dbSDimitry Andric } 22025ffd83dbSDimitry Andric 22035ffd83dbSDimitry Andric // Disregard complicated cases where we have to thread multiple edges. 22045ffd83dbSDimitry Andric BasicBlock *PredPredBB; 22055ffd83dbSDimitry Andric if (ZeroCount == 1) { 22065ffd83dbSDimitry Andric PredPredBB = ZeroPred; 22075ffd83dbSDimitry Andric } else if (OneCount == 1) { 22085ffd83dbSDimitry Andric PredPredBB = OnePred; 22095ffd83dbSDimitry Andric } else { 22105ffd83dbSDimitry Andric return false; 22115ffd83dbSDimitry Andric } 22125ffd83dbSDimitry Andric 22135ffd83dbSDimitry Andric BasicBlock *SuccBB = CondBr->getSuccessor(PredPredBB == ZeroPred); 22145ffd83dbSDimitry Andric 22155ffd83dbSDimitry Andric // If threading to the same block as we come from, we would infinite loop. 22165ffd83dbSDimitry Andric if (SuccBB == BB) { 22175ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName() 22185ffd83dbSDimitry Andric << "' - would thread to self!\n"); 22195ffd83dbSDimitry Andric return false; 22205ffd83dbSDimitry Andric } 22215ffd83dbSDimitry Andric 22225ffd83dbSDimitry Andric // If threading this would thread across a loop header, don't thread the edge. 2223e8d8bef9SDimitry Andric // See the comments above findLoopHeaders for justifications and caveats. 22245ffd83dbSDimitry Andric if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) { 22255ffd83dbSDimitry Andric LLVM_DEBUG({ 22265ffd83dbSDimitry Andric bool BBIsHeader = LoopHeaders.count(BB); 22275ffd83dbSDimitry Andric bool SuccIsHeader = LoopHeaders.count(SuccBB); 22285ffd83dbSDimitry Andric dbgs() << " Not threading across " 22295ffd83dbSDimitry Andric << (BBIsHeader ? "loop header BB '" : "block BB '") 22305ffd83dbSDimitry Andric << BB->getName() << "' to dest " 22315ffd83dbSDimitry Andric << (SuccIsHeader ? "loop header BB '" : "block BB '") 22325ffd83dbSDimitry Andric << SuccBB->getName() 22335ffd83dbSDimitry Andric << "' - it might create an irreducible loop!\n"; 22345ffd83dbSDimitry Andric }); 22355ffd83dbSDimitry Andric return false; 22365ffd83dbSDimitry Andric } 22375ffd83dbSDimitry Andric 22385ffd83dbSDimitry Andric // Compute the cost of duplicating BB and PredBB. 2239349cc55cSDimitry Andric unsigned BBCost = getJumpThreadDuplicationCost( 2240349cc55cSDimitry Andric TTI, BB, BB->getTerminator(), BBDupThreshold); 22415ffd83dbSDimitry Andric unsigned PredBBCost = getJumpThreadDuplicationCost( 2242349cc55cSDimitry Andric TTI, PredBB, PredBB->getTerminator(), BBDupThreshold); 22435ffd83dbSDimitry Andric 22445ffd83dbSDimitry Andric // Give up if costs are too high. We need to check BBCost and PredBBCost 22455ffd83dbSDimitry Andric // individually before checking their sum because getJumpThreadDuplicationCost 22465ffd83dbSDimitry Andric // return (unsigned)~0 for those basic blocks that cannot be duplicated. 22475ffd83dbSDimitry Andric if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold || 22485ffd83dbSDimitry Andric BBCost + PredBBCost > BBDupThreshold) { 22495ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName() 22505ffd83dbSDimitry Andric << "' - Cost is too high: " << PredBBCost 22515ffd83dbSDimitry Andric << " for PredBB, " << BBCost << "for BB\n"); 22525ffd83dbSDimitry Andric return false; 22535ffd83dbSDimitry Andric } 22545ffd83dbSDimitry Andric 22555ffd83dbSDimitry Andric // Now we are ready to duplicate PredBB. 2256e8d8bef9SDimitry Andric threadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB); 22575ffd83dbSDimitry Andric return true; 22585ffd83dbSDimitry Andric } 22595ffd83dbSDimitry Andric 2260e8d8bef9SDimitry Andric void JumpThreadingPass::threadThroughTwoBasicBlocks(BasicBlock *PredPredBB, 22615ffd83dbSDimitry Andric BasicBlock *PredBB, 22625ffd83dbSDimitry Andric BasicBlock *BB, 22635ffd83dbSDimitry Andric BasicBlock *SuccBB) { 22645ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << " Threading through '" << PredBB->getName() << "' and '" 22655ffd83dbSDimitry Andric << BB->getName() << "'\n"); 22665ffd83dbSDimitry Andric 226706c3fb27SDimitry Andric // Build BPI/BFI before any changes are made to IR. 226806c3fb27SDimitry Andric bool HasProfile = doesBlockHaveProfileData(BB); 226906c3fb27SDimitry Andric auto *BFI = getOrCreateBFI(HasProfile); 227006c3fb27SDimitry Andric auto *BPI = getOrCreateBPI(BFI != nullptr); 227106c3fb27SDimitry Andric 22725ffd83dbSDimitry Andric BranchInst *CondBr = cast<BranchInst>(BB->getTerminator()); 22735ffd83dbSDimitry Andric BranchInst *PredBBBranch = cast<BranchInst>(PredBB->getTerminator()); 22745ffd83dbSDimitry Andric 22755ffd83dbSDimitry Andric BasicBlock *NewBB = 22765ffd83dbSDimitry Andric BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread", 22775ffd83dbSDimitry Andric PredBB->getParent(), PredBB); 22785ffd83dbSDimitry Andric NewBB->moveAfter(PredBB); 22795ffd83dbSDimitry Andric 22805ffd83dbSDimitry Andric // Set the block frequency of NewBB. 228106c3fb27SDimitry Andric if (BFI) { 228206c3fb27SDimitry Andric assert(BPI && "It's expected BPI to exist along with BFI"); 22835ffd83dbSDimitry Andric auto NewBBFreq = BFI->getBlockFreq(PredPredBB) * 22845ffd83dbSDimitry Andric BPI->getEdgeProbability(PredPredBB, PredBB); 22855f757f3fSDimitry Andric BFI->setBlockFreq(NewBB, NewBBFreq); 22865ffd83dbSDimitry Andric } 22875ffd83dbSDimitry Andric 22885ffd83dbSDimitry Andric // We are going to have to map operands from the original BB block to the new 22895ffd83dbSDimitry Andric // copy of the block 'NewBB'. If there are PHI nodes in PredBB, evaluate them 22905ffd83dbSDimitry Andric // to account for entry from PredPredBB. 2291*0fca6ea1SDimitry Andric ValueToValueMapTy ValueMapping; 2292*0fca6ea1SDimitry Andric cloneInstructions(ValueMapping, PredBB->begin(), PredBB->end(), NewBB, 2293*0fca6ea1SDimitry Andric PredPredBB); 2294e8d8bef9SDimitry Andric 2295e8d8bef9SDimitry Andric // Copy the edge probabilities from PredBB to NewBB. 229606c3fb27SDimitry Andric if (BPI) 2297e8d8bef9SDimitry Andric BPI->copyEdgeProbabilities(PredBB, NewBB); 22985ffd83dbSDimitry Andric 22995ffd83dbSDimitry Andric // Update the terminator of PredPredBB to jump to NewBB instead of PredBB. 23005ffd83dbSDimitry Andric // This eliminates predecessors from PredPredBB, which requires us to simplify 23015ffd83dbSDimitry Andric // any PHI nodes in PredBB. 23025ffd83dbSDimitry Andric Instruction *PredPredTerm = PredPredBB->getTerminator(); 23035ffd83dbSDimitry Andric for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i) 23045ffd83dbSDimitry Andric if (PredPredTerm->getSuccessor(i) == PredBB) { 23055ffd83dbSDimitry Andric PredBB->removePredecessor(PredPredBB, true); 23065ffd83dbSDimitry Andric PredPredTerm->setSuccessor(i, NewBB); 23075ffd83dbSDimitry Andric } 23085ffd83dbSDimitry Andric 2309e8d8bef9SDimitry Andric addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB, 23105ffd83dbSDimitry Andric ValueMapping); 2311e8d8bef9SDimitry Andric addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB, 23125ffd83dbSDimitry Andric ValueMapping); 23135ffd83dbSDimitry Andric 23145ffd83dbSDimitry Andric DTU->applyUpdatesPermissive( 23155ffd83dbSDimitry Andric {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)}, 23165ffd83dbSDimitry Andric {DominatorTree::Insert, NewBB, CondBr->getSuccessor(1)}, 23175ffd83dbSDimitry Andric {DominatorTree::Insert, PredPredBB, NewBB}, 23185ffd83dbSDimitry Andric {DominatorTree::Delete, PredPredBB, PredBB}}); 23195ffd83dbSDimitry Andric 2320e8d8bef9SDimitry Andric updateSSA(PredBB, NewBB, ValueMapping); 23215ffd83dbSDimitry Andric 23225ffd83dbSDimitry Andric // Clean up things like PHI nodes with single operands, dead instructions, 23235ffd83dbSDimitry Andric // etc. 23245ffd83dbSDimitry Andric SimplifyInstructionsInBlock(NewBB, TLI); 23255ffd83dbSDimitry Andric SimplifyInstructionsInBlock(PredBB, TLI); 23265ffd83dbSDimitry Andric 23275ffd83dbSDimitry Andric SmallVector<BasicBlock *, 1> PredsToFactor; 23285ffd83dbSDimitry Andric PredsToFactor.push_back(NewBB); 2329e8d8bef9SDimitry Andric threadEdge(BB, PredsToFactor, SuccBB); 23305ffd83dbSDimitry Andric } 23315ffd83dbSDimitry Andric 2332e8d8bef9SDimitry Andric /// tryThreadEdge - Thread an edge if it's safe and profitable to do so. 2333e8d8bef9SDimitry Andric bool JumpThreadingPass::tryThreadEdge( 2334480093f4SDimitry Andric BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs, 23350b57cec5SDimitry Andric BasicBlock *SuccBB) { 23360b57cec5SDimitry Andric // If threading to the same block as we come from, we would infinite loop. 23370b57cec5SDimitry Andric if (SuccBB == BB) { 23380b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName() 23390b57cec5SDimitry Andric << "' - would thread to self!\n"); 23400b57cec5SDimitry Andric return false; 23410b57cec5SDimitry Andric } 23420b57cec5SDimitry Andric 23430b57cec5SDimitry Andric // If threading this would thread across a loop header, don't thread the edge. 2344e8d8bef9SDimitry Andric // See the comments above findLoopHeaders for justifications and caveats. 23450b57cec5SDimitry Andric if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) { 23460b57cec5SDimitry Andric LLVM_DEBUG({ 23470b57cec5SDimitry Andric bool BBIsHeader = LoopHeaders.count(BB); 23480b57cec5SDimitry Andric bool SuccIsHeader = LoopHeaders.count(SuccBB); 23490b57cec5SDimitry Andric dbgs() << " Not threading across " 23500b57cec5SDimitry Andric << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName() 23510b57cec5SDimitry Andric << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '") 23520b57cec5SDimitry Andric << SuccBB->getName() << "' - it might create an irreducible loop!\n"; 23530b57cec5SDimitry Andric }); 23540b57cec5SDimitry Andric return false; 23550b57cec5SDimitry Andric } 23560b57cec5SDimitry Andric 2357349cc55cSDimitry Andric unsigned JumpThreadCost = getJumpThreadDuplicationCost( 2358349cc55cSDimitry Andric TTI, BB, BB->getTerminator(), BBDupThreshold); 23590b57cec5SDimitry Andric if (JumpThreadCost > BBDupThreshold) { 23600b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName() 23610b57cec5SDimitry Andric << "' - Cost is too high: " << JumpThreadCost << "\n"); 23620b57cec5SDimitry Andric return false; 23630b57cec5SDimitry Andric } 23640b57cec5SDimitry Andric 2365e8d8bef9SDimitry Andric threadEdge(BB, PredBBs, SuccBB); 2366480093f4SDimitry Andric return true; 2367480093f4SDimitry Andric } 2368480093f4SDimitry Andric 2369e8d8bef9SDimitry Andric /// threadEdge - We have decided that it is safe and profitable to factor the 2370480093f4SDimitry Andric /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB 2371480093f4SDimitry Andric /// across BB. Transform the IR to reflect this change. 2372e8d8bef9SDimitry Andric void JumpThreadingPass::threadEdge(BasicBlock *BB, 2373480093f4SDimitry Andric const SmallVectorImpl<BasicBlock *> &PredBBs, 2374480093f4SDimitry Andric BasicBlock *SuccBB) { 2375480093f4SDimitry Andric assert(SuccBB != BB && "Don't create an infinite loop"); 2376480093f4SDimitry Andric 2377480093f4SDimitry Andric assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) && 2378480093f4SDimitry Andric "Don't thread across loop headers"); 2379480093f4SDimitry Andric 238006c3fb27SDimitry Andric // Build BPI/BFI before any changes are made to IR. 238106c3fb27SDimitry Andric bool HasProfile = doesBlockHaveProfileData(BB); 238206c3fb27SDimitry Andric auto *BFI = getOrCreateBFI(HasProfile); 238306c3fb27SDimitry Andric auto *BPI = getOrCreateBPI(BFI != nullptr); 238406c3fb27SDimitry Andric 23850b57cec5SDimitry Andric // And finally, do it! Start by factoring the predecessors if needed. 23860b57cec5SDimitry Andric BasicBlock *PredBB; 23870b57cec5SDimitry Andric if (PredBBs.size() == 1) 23880b57cec5SDimitry Andric PredBB = PredBBs[0]; 23890b57cec5SDimitry Andric else { 23900b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size() 23910b57cec5SDimitry Andric << " common predecessors.\n"); 2392e8d8bef9SDimitry Andric PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm"); 23930b57cec5SDimitry Andric } 23940b57cec5SDimitry Andric 23950b57cec5SDimitry Andric // And finally, do it! 23960b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() 23970b57cec5SDimitry Andric << "' to '" << SuccBB->getName() 23980b57cec5SDimitry Andric << ", across block:\n " << *BB << "\n"); 23990b57cec5SDimitry Andric 24000b57cec5SDimitry Andric LVI->threadEdge(PredBB, BB, SuccBB); 24010b57cec5SDimitry Andric 24020b57cec5SDimitry Andric BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), 24030b57cec5SDimitry Andric BB->getName()+".thread", 24040b57cec5SDimitry Andric BB->getParent(), BB); 24050b57cec5SDimitry Andric NewBB->moveAfter(PredBB); 24060b57cec5SDimitry Andric 24070b57cec5SDimitry Andric // Set the block frequency of NewBB. 240806c3fb27SDimitry Andric if (BFI) { 240906c3fb27SDimitry Andric assert(BPI && "It's expected BPI to exist along with BFI"); 24100b57cec5SDimitry Andric auto NewBBFreq = 24110b57cec5SDimitry Andric BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB); 24125f757f3fSDimitry Andric BFI->setBlockFreq(NewBB, NewBBFreq); 24130b57cec5SDimitry Andric } 24140b57cec5SDimitry Andric 2415480093f4SDimitry Andric // Copy all the instructions from BB to NewBB except the terminator. 2416*0fca6ea1SDimitry Andric ValueToValueMapTy ValueMapping; 2417*0fca6ea1SDimitry Andric cloneInstructions(ValueMapping, BB->begin(), std::prev(BB->end()), NewBB, 2418*0fca6ea1SDimitry Andric PredBB); 24190b57cec5SDimitry Andric 24200b57cec5SDimitry Andric // We didn't copy the terminator from BB over to NewBB, because there is now 24210b57cec5SDimitry Andric // an unconditional jump to SuccBB. Insert the unconditional jump. 24220b57cec5SDimitry Andric BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB); 24230b57cec5SDimitry Andric NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc()); 24240b57cec5SDimitry Andric 24250b57cec5SDimitry Andric // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the 24260b57cec5SDimitry Andric // PHI nodes for NewBB now. 2427e8d8bef9SDimitry Andric addPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping); 24280b57cec5SDimitry Andric 24290b57cec5SDimitry Andric // Update the terminator of PredBB to jump to NewBB instead of BB. This 24300b57cec5SDimitry Andric // eliminates predecessors from BB, which requires us to simplify any PHI 24310b57cec5SDimitry Andric // nodes in BB. 24320b57cec5SDimitry Andric Instruction *PredTerm = PredBB->getTerminator(); 24330b57cec5SDimitry Andric for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) 24340b57cec5SDimitry Andric if (PredTerm->getSuccessor(i) == BB) { 24350b57cec5SDimitry Andric BB->removePredecessor(PredBB, true); 24360b57cec5SDimitry Andric PredTerm->setSuccessor(i, NewBB); 24370b57cec5SDimitry Andric } 24380b57cec5SDimitry Andric 24390b57cec5SDimitry Andric // Enqueue required DT updates. 24400b57cec5SDimitry Andric DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB}, 24410b57cec5SDimitry Andric {DominatorTree::Insert, PredBB, NewBB}, 24420b57cec5SDimitry Andric {DominatorTree::Delete, PredBB, BB}}); 24430b57cec5SDimitry Andric 2444e8d8bef9SDimitry Andric updateSSA(BB, NewBB, ValueMapping); 24450b57cec5SDimitry Andric 24460b57cec5SDimitry Andric // At this point, the IR is fully up to date and consistent. Do a quick scan 24470b57cec5SDimitry Andric // over the new instructions and zap any that are constants or dead. This 24480b57cec5SDimitry Andric // frequently happens because of phi translation. 24490b57cec5SDimitry Andric SimplifyInstructionsInBlock(NewBB, TLI); 24500b57cec5SDimitry Andric 24510b57cec5SDimitry Andric // Update the edge weight from BB to SuccBB, which should be less than before. 245206c3fb27SDimitry Andric updateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB, BFI, BPI, HasProfile); 24530b57cec5SDimitry Andric 24540b57cec5SDimitry Andric // Threaded an edge! 24550b57cec5SDimitry Andric ++NumThreads; 24560b57cec5SDimitry Andric } 24570b57cec5SDimitry Andric 24580b57cec5SDimitry Andric /// Create a new basic block that will be the predecessor of BB and successor of 24590b57cec5SDimitry Andric /// all blocks in Preds. When profile data is available, update the frequency of 24600b57cec5SDimitry Andric /// this new block. 2461e8d8bef9SDimitry Andric BasicBlock *JumpThreadingPass::splitBlockPreds(BasicBlock *BB, 24620b57cec5SDimitry Andric ArrayRef<BasicBlock *> Preds, 24630b57cec5SDimitry Andric const char *Suffix) { 24640b57cec5SDimitry Andric SmallVector<BasicBlock *, 2> NewBBs; 24650b57cec5SDimitry Andric 24660b57cec5SDimitry Andric // Collect the frequencies of all predecessors of BB, which will be used to 24670b57cec5SDimitry Andric // update the edge weight of the result of splitting predecessors. 24680b57cec5SDimitry Andric DenseMap<BasicBlock *, BlockFrequency> FreqMap; 246906c3fb27SDimitry Andric auto *BFI = getBFI(); 247006c3fb27SDimitry Andric if (BFI) { 247106c3fb27SDimitry Andric auto *BPI = getOrCreateBPI(true); 2472bdd1243dSDimitry Andric for (auto *Pred : Preds) 24730b57cec5SDimitry Andric FreqMap.insert(std::make_pair( 24740b57cec5SDimitry Andric Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB))); 247506c3fb27SDimitry Andric } 24760b57cec5SDimitry Andric 24770b57cec5SDimitry Andric // In the case when BB is a LandingPad block we create 2 new predecessors 24780b57cec5SDimitry Andric // instead of just one. 24790b57cec5SDimitry Andric if (BB->isLandingPad()) { 24800b57cec5SDimitry Andric std::string NewName = std::string(Suffix) + ".split-lp"; 24810b57cec5SDimitry Andric SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs); 24820b57cec5SDimitry Andric } else { 24830b57cec5SDimitry Andric NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix)); 24840b57cec5SDimitry Andric } 24850b57cec5SDimitry Andric 24860b57cec5SDimitry Andric std::vector<DominatorTree::UpdateType> Updates; 24870b57cec5SDimitry Andric Updates.reserve((2 * Preds.size()) + NewBBs.size()); 2488bdd1243dSDimitry Andric for (auto *NewBB : NewBBs) { 24890b57cec5SDimitry Andric BlockFrequency NewBBFreq(0); 24900b57cec5SDimitry Andric Updates.push_back({DominatorTree::Insert, NewBB, BB}); 2491bdd1243dSDimitry Andric for (auto *Pred : predecessors(NewBB)) { 24920b57cec5SDimitry Andric Updates.push_back({DominatorTree::Delete, Pred, BB}); 24930b57cec5SDimitry Andric Updates.push_back({DominatorTree::Insert, Pred, NewBB}); 249406c3fb27SDimitry Andric if (BFI) // Update frequencies between Pred -> NewBB. 24950b57cec5SDimitry Andric NewBBFreq += FreqMap.lookup(Pred); 24960b57cec5SDimitry Andric } 249706c3fb27SDimitry Andric if (BFI) // Apply the summed frequency to NewBB. 24985f757f3fSDimitry Andric BFI->setBlockFreq(NewBB, NewBBFreq); 24990b57cec5SDimitry Andric } 25000b57cec5SDimitry Andric 25010b57cec5SDimitry Andric DTU->applyUpdatesPermissive(Updates); 25020b57cec5SDimitry Andric return NewBBs[0]; 25030b57cec5SDimitry Andric } 25040b57cec5SDimitry Andric 25050b57cec5SDimitry Andric bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) { 25060b57cec5SDimitry Andric const Instruction *TI = BB->getTerminator(); 250706c3fb27SDimitry Andric if (!TI || TI->getNumSuccessors() < 2) 250806c3fb27SDimitry Andric return false; 250906c3fb27SDimitry Andric 2510bdd1243dSDimitry Andric return hasValidBranchWeightMD(*TI); 25110b57cec5SDimitry Andric } 25120b57cec5SDimitry Andric 25130b57cec5SDimitry Andric /// Update the block frequency of BB and branch weight and the metadata on the 25140b57cec5SDimitry Andric /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 - 25150b57cec5SDimitry Andric /// Freq(PredBB->BB) / Freq(BB->SuccBB). 2516e8d8bef9SDimitry Andric void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB, 25170b57cec5SDimitry Andric BasicBlock *BB, 25180b57cec5SDimitry Andric BasicBlock *NewBB, 251906c3fb27SDimitry Andric BasicBlock *SuccBB, 252006c3fb27SDimitry Andric BlockFrequencyInfo *BFI, 252106c3fb27SDimitry Andric BranchProbabilityInfo *BPI, 252206c3fb27SDimitry Andric bool HasProfile) { 252306c3fb27SDimitry Andric assert(((BFI && BPI) || (!BFI && !BFI)) && 252406c3fb27SDimitry Andric "Both BFI & BPI should either be set or unset"); 25250b57cec5SDimitry Andric 252606c3fb27SDimitry Andric if (!BFI) { 252706c3fb27SDimitry Andric assert(!HasProfile && 252806c3fb27SDimitry Andric "It's expected to have BFI/BPI when profile info exists"); 252906c3fb27SDimitry Andric return; 253006c3fb27SDimitry Andric } 25310b57cec5SDimitry Andric 25320b57cec5SDimitry Andric // As the edge from PredBB to BB is deleted, we have to update the block 25330b57cec5SDimitry Andric // frequency of BB. 25340b57cec5SDimitry Andric auto BBOrigFreq = BFI->getBlockFreq(BB); 25350b57cec5SDimitry Andric auto NewBBFreq = BFI->getBlockFreq(NewBB); 25360b57cec5SDimitry Andric auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB); 25370b57cec5SDimitry Andric auto BBNewFreq = BBOrigFreq - NewBBFreq; 25385f757f3fSDimitry Andric BFI->setBlockFreq(BB, BBNewFreq); 25390b57cec5SDimitry Andric 25400b57cec5SDimitry Andric // Collect updated outgoing edges' frequencies from BB and use them to update 25410b57cec5SDimitry Andric // edge probabilities. 25420b57cec5SDimitry Andric SmallVector<uint64_t, 4> BBSuccFreq; 25430b57cec5SDimitry Andric for (BasicBlock *Succ : successors(BB)) { 25440b57cec5SDimitry Andric auto SuccFreq = (Succ == SuccBB) 25450b57cec5SDimitry Andric ? BB2SuccBBFreq - NewBBFreq 25460b57cec5SDimitry Andric : BBOrigFreq * BPI->getEdgeProbability(BB, Succ); 25470b57cec5SDimitry Andric BBSuccFreq.push_back(SuccFreq.getFrequency()); 25480b57cec5SDimitry Andric } 25490b57cec5SDimitry Andric 2550*0fca6ea1SDimitry Andric uint64_t MaxBBSuccFreq = *llvm::max_element(BBSuccFreq); 25510b57cec5SDimitry Andric 25520b57cec5SDimitry Andric SmallVector<BranchProbability, 4> BBSuccProbs; 25530b57cec5SDimitry Andric if (MaxBBSuccFreq == 0) 25540b57cec5SDimitry Andric BBSuccProbs.assign(BBSuccFreq.size(), 25550b57cec5SDimitry Andric {1, static_cast<unsigned>(BBSuccFreq.size())}); 25560b57cec5SDimitry Andric else { 25570b57cec5SDimitry Andric for (uint64_t Freq : BBSuccFreq) 25580b57cec5SDimitry Andric BBSuccProbs.push_back( 25590b57cec5SDimitry Andric BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq)); 25600b57cec5SDimitry Andric // Normalize edge probabilities so that they sum up to one. 25610b57cec5SDimitry Andric BranchProbability::normalizeProbabilities(BBSuccProbs.begin(), 25620b57cec5SDimitry Andric BBSuccProbs.end()); 25630b57cec5SDimitry Andric } 25640b57cec5SDimitry Andric 25650b57cec5SDimitry Andric // Update edge probabilities in BPI. 25665ffd83dbSDimitry Andric BPI->setEdgeProbability(BB, BBSuccProbs); 25670b57cec5SDimitry Andric 25680b57cec5SDimitry Andric // Update the profile metadata as well. 25690b57cec5SDimitry Andric // 25700b57cec5SDimitry Andric // Don't do this if the profile of the transformed blocks was statically 25710b57cec5SDimitry Andric // estimated. (This could occur despite the function having an entry 25720b57cec5SDimitry Andric // frequency in completely cold parts of the CFG.) 25730b57cec5SDimitry Andric // 25740b57cec5SDimitry Andric // In this case we don't want to suggest to subsequent passes that the 25750b57cec5SDimitry Andric // calculated weights are fully consistent. Consider this graph: 25760b57cec5SDimitry Andric // 25770b57cec5SDimitry Andric // check_1 25780b57cec5SDimitry Andric // 50% / | 25790b57cec5SDimitry Andric // eq_1 | 50% 25800b57cec5SDimitry Andric // \ | 25810b57cec5SDimitry Andric // check_2 25820b57cec5SDimitry Andric // 50% / | 25830b57cec5SDimitry Andric // eq_2 | 50% 25840b57cec5SDimitry Andric // \ | 25850b57cec5SDimitry Andric // check_3 25860b57cec5SDimitry Andric // 50% / | 25870b57cec5SDimitry Andric // eq_3 | 50% 25880b57cec5SDimitry Andric // \ | 25890b57cec5SDimitry Andric // 25900b57cec5SDimitry Andric // Assuming the blocks check_* all compare the same value against 1, 2 and 3, 25910b57cec5SDimitry Andric // the overall probabilities are inconsistent; the total probability that the 25920b57cec5SDimitry Andric // value is either 1, 2 or 3 is 150%. 25930b57cec5SDimitry Andric // 25940b57cec5SDimitry Andric // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3 25950b57cec5SDimitry Andric // becomes 0%. This is even worse if the edge whose probability becomes 0% is 25960b57cec5SDimitry Andric // the loop exit edge. Then based solely on static estimation we would assume 25970b57cec5SDimitry Andric // the loop was extremely hot. 25980b57cec5SDimitry Andric // 25990b57cec5SDimitry Andric // FIXME this locally as well so that BPI and BFI are consistent as well. We 26000b57cec5SDimitry Andric // shouldn't make edges extremely likely or unlikely based solely on static 26010b57cec5SDimitry Andric // estimation. 260206c3fb27SDimitry Andric if (BBSuccProbs.size() >= 2 && HasProfile) { 26030b57cec5SDimitry Andric SmallVector<uint32_t, 4> Weights; 26040b57cec5SDimitry Andric for (auto Prob : BBSuccProbs) 26050b57cec5SDimitry Andric Weights.push_back(Prob.getNumerator()); 26060b57cec5SDimitry Andric 26070b57cec5SDimitry Andric auto TI = BB->getTerminator(); 2608*0fca6ea1SDimitry Andric setBranchWeights(*TI, Weights, hasBranchWeightOrigin(*TI)); 26090b57cec5SDimitry Andric } 26100b57cec5SDimitry Andric } 26110b57cec5SDimitry Andric 2612e8d8bef9SDimitry Andric /// duplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch 26130b57cec5SDimitry Andric /// to BB which contains an i1 PHI node and a conditional branch on that PHI. 26140b57cec5SDimitry Andric /// If we can duplicate the contents of BB up into PredBB do so now, this 26150b57cec5SDimitry Andric /// improves the odds that the branch will be on an analyzable instruction like 26160b57cec5SDimitry Andric /// a compare. 2617e8d8bef9SDimitry Andric bool JumpThreadingPass::duplicateCondBranchOnPHIIntoPred( 26180b57cec5SDimitry Andric BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) { 26190b57cec5SDimitry Andric assert(!PredBBs.empty() && "Can't handle an empty set"); 26200b57cec5SDimitry Andric 26210b57cec5SDimitry Andric // If BB is a loop header, then duplicating this block outside the loop would 26220b57cec5SDimitry Andric // cause us to transform this into an irreducible loop, don't do this. 2623e8d8bef9SDimitry Andric // See the comments above findLoopHeaders for justifications and caveats. 26240b57cec5SDimitry Andric if (LoopHeaders.count(BB)) { 26250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName() 26260b57cec5SDimitry Andric << "' into predecessor block '" << PredBBs[0]->getName() 26270b57cec5SDimitry Andric << "' - it might create an irreducible loop!\n"); 26280b57cec5SDimitry Andric return false; 26290b57cec5SDimitry Andric } 26300b57cec5SDimitry Andric 2631349cc55cSDimitry Andric unsigned DuplicationCost = getJumpThreadDuplicationCost( 2632349cc55cSDimitry Andric TTI, BB, BB->getTerminator(), BBDupThreshold); 26330b57cec5SDimitry Andric if (DuplicationCost > BBDupThreshold) { 26340b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName() 26350b57cec5SDimitry Andric << "' - Cost is too high: " << DuplicationCost << "\n"); 26360b57cec5SDimitry Andric return false; 26370b57cec5SDimitry Andric } 26380b57cec5SDimitry Andric 26390b57cec5SDimitry Andric // And finally, do it! Start by factoring the predecessors if needed. 26400b57cec5SDimitry Andric std::vector<DominatorTree::UpdateType> Updates; 26410b57cec5SDimitry Andric BasicBlock *PredBB; 26420b57cec5SDimitry Andric if (PredBBs.size() == 1) 26430b57cec5SDimitry Andric PredBB = PredBBs[0]; 26440b57cec5SDimitry Andric else { 26450b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size() 26460b57cec5SDimitry Andric << " common predecessors.\n"); 2647e8d8bef9SDimitry Andric PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm"); 26480b57cec5SDimitry Andric } 26490b57cec5SDimitry Andric Updates.push_back({DominatorTree::Delete, PredBB, BB}); 26500b57cec5SDimitry Andric 26510b57cec5SDimitry Andric // Okay, we decided to do this! Clone all the instructions in BB onto the end 26520b57cec5SDimitry Andric // of PredBB. 26530b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName() 26540b57cec5SDimitry Andric << "' into end of '" << PredBB->getName() 26550b57cec5SDimitry Andric << "' to eliminate branch on phi. Cost: " 26560b57cec5SDimitry Andric << DuplicationCost << " block is:" << *BB << "\n"); 26570b57cec5SDimitry Andric 26580b57cec5SDimitry Andric // Unless PredBB ends with an unconditional branch, split the edge so that we 26590b57cec5SDimitry Andric // can just clone the bits from BB into the end of the new PredBB. 26600b57cec5SDimitry Andric BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator()); 26610b57cec5SDimitry Andric 26620b57cec5SDimitry Andric if (!OldPredBranch || !OldPredBranch->isUnconditional()) { 26630b57cec5SDimitry Andric BasicBlock *OldPredBB = PredBB; 26640b57cec5SDimitry Andric PredBB = SplitEdge(OldPredBB, BB); 26650b57cec5SDimitry Andric Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB}); 26660b57cec5SDimitry Andric Updates.push_back({DominatorTree::Insert, PredBB, BB}); 26670b57cec5SDimitry Andric Updates.push_back({DominatorTree::Delete, OldPredBB, BB}); 26680b57cec5SDimitry Andric OldPredBranch = cast<BranchInst>(PredBB->getTerminator()); 26690b57cec5SDimitry Andric } 26700b57cec5SDimitry Andric 26710b57cec5SDimitry Andric // We are going to have to map operands from the original BB block into the 26720b57cec5SDimitry Andric // PredBB block. Evaluate PHI nodes in BB. 2673*0fca6ea1SDimitry Andric ValueToValueMapTy ValueMapping; 26740b57cec5SDimitry Andric 26750b57cec5SDimitry Andric BasicBlock::iterator BI = BB->begin(); 26760b57cec5SDimitry Andric for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 26770b57cec5SDimitry Andric ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 26780b57cec5SDimitry Andric // Clone the non-phi instructions of BB into PredBB, keeping track of the 26790b57cec5SDimitry Andric // mapping and using it to remap operands in the cloned instructions. 26800b57cec5SDimitry Andric for (; BI != BB->end(); ++BI) { 26810b57cec5SDimitry Andric Instruction *New = BI->clone(); 268206c3fb27SDimitry Andric New->insertInto(PredBB, OldPredBranch->getIterator()); 26830b57cec5SDimitry Andric 26840b57cec5SDimitry Andric // Remap operands to patch up intra-block references. 26850b57cec5SDimitry Andric for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 26860b57cec5SDimitry Andric if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 2687*0fca6ea1SDimitry Andric ValueToValueMapTy::iterator I = ValueMapping.find(Inst); 26880b57cec5SDimitry Andric if (I != ValueMapping.end()) 26890b57cec5SDimitry Andric New->setOperand(i, I->second); 26900b57cec5SDimitry Andric } 26910b57cec5SDimitry Andric 2692*0fca6ea1SDimitry Andric // Remap debug variable operands. 2693*0fca6ea1SDimitry Andric remapDebugVariable(ValueMapping, New); 2694*0fca6ea1SDimitry Andric 26950b57cec5SDimitry Andric // If this instruction can be simplified after the operands are updated, 26960b57cec5SDimitry Andric // just use the simplified value instead. This frequently happens due to 26970b57cec5SDimitry Andric // phi translation. 269881ad6265SDimitry Andric if (Value *IV = simplifyInstruction( 26990b57cec5SDimitry Andric New, 2700*0fca6ea1SDimitry Andric {BB->getDataLayout(), TLI, nullptr, nullptr, New})) { 27010b57cec5SDimitry Andric ValueMapping[&*BI] = IV; 27020b57cec5SDimitry Andric if (!New->mayHaveSideEffects()) { 270306c3fb27SDimitry Andric New->eraseFromParent(); 27040b57cec5SDimitry Andric New = nullptr; 27055f757f3fSDimitry Andric // Clone debug-info on the elided instruction to the destination 27065f757f3fSDimitry Andric // position. 27075f757f3fSDimitry Andric OldPredBranch->cloneDebugInfoFrom(&*BI, std::nullopt, true); 27080b57cec5SDimitry Andric } 27090b57cec5SDimitry Andric } else { 27100b57cec5SDimitry Andric ValueMapping[&*BI] = New; 27110b57cec5SDimitry Andric } 27120b57cec5SDimitry Andric if (New) { 27130b57cec5SDimitry Andric // Otherwise, insert the new instruction into the block. 27140b57cec5SDimitry Andric New->setName(BI->getName()); 27155f757f3fSDimitry Andric // Clone across any debug-info attached to the old instruction. 27165f757f3fSDimitry Andric New->cloneDebugInfoFrom(&*BI); 27170b57cec5SDimitry Andric // Update Dominance from simplified New instruction operands. 27180b57cec5SDimitry Andric for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 27190b57cec5SDimitry Andric if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i))) 27200b57cec5SDimitry Andric Updates.push_back({DominatorTree::Insert, PredBB, SuccBB}); 27210b57cec5SDimitry Andric } 27220b57cec5SDimitry Andric } 27230b57cec5SDimitry Andric 27240b57cec5SDimitry Andric // Check to see if the targets of the branch had PHI nodes. If so, we need to 27250b57cec5SDimitry Andric // add entries to the PHI nodes for branch from PredBB now. 27260b57cec5SDimitry Andric BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator()); 2727e8d8bef9SDimitry Andric addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB, 27280b57cec5SDimitry Andric ValueMapping); 2729e8d8bef9SDimitry Andric addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB, 27300b57cec5SDimitry Andric ValueMapping); 27310b57cec5SDimitry Andric 2732e8d8bef9SDimitry Andric updateSSA(BB, PredBB, ValueMapping); 27330b57cec5SDimitry Andric 27340b57cec5SDimitry Andric // PredBB no longer jumps to BB, remove entries in the PHI node for the edge 27350b57cec5SDimitry Andric // that we nuked. 27360b57cec5SDimitry Andric BB->removePredecessor(PredBB, true); 27370b57cec5SDimitry Andric 27380b57cec5SDimitry Andric // Remove the unconditional branch at the end of the PredBB block. 27390b57cec5SDimitry Andric OldPredBranch->eraseFromParent(); 274006c3fb27SDimitry Andric if (auto *BPI = getBPI()) 2741e8d8bef9SDimitry Andric BPI->copyEdgeProbabilities(BB, PredBB); 27420b57cec5SDimitry Andric DTU->applyUpdatesPermissive(Updates); 27430b57cec5SDimitry Andric 27440b57cec5SDimitry Andric ++NumDupes; 27450b57cec5SDimitry Andric return true; 27460b57cec5SDimitry Andric } 27470b57cec5SDimitry Andric 27480b57cec5SDimitry Andric // Pred is a predecessor of BB with an unconditional branch to BB. SI is 27490b57cec5SDimitry Andric // a Select instruction in Pred. BB has other predecessors and SI is used in 27500b57cec5SDimitry Andric // a PHI node in BB. SI has no other use. 27510b57cec5SDimitry Andric // A new basic block, NewBB, is created and SI is converted to compare and 27520b57cec5SDimitry Andric // conditional branch. SI is erased from parent. 2753e8d8bef9SDimitry Andric void JumpThreadingPass::unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB, 27540b57cec5SDimitry Andric SelectInst *SI, PHINode *SIUse, 27550b57cec5SDimitry Andric unsigned Idx) { 27560b57cec5SDimitry Andric // Expand the select. 27570b57cec5SDimitry Andric // 27580b57cec5SDimitry Andric // Pred -- 27590b57cec5SDimitry Andric // | v 27600b57cec5SDimitry Andric // | NewBB 27610b57cec5SDimitry Andric // | | 27620b57cec5SDimitry Andric // |----- 27630b57cec5SDimitry Andric // v 27640b57cec5SDimitry Andric // BB 27658bcb0991SDimitry Andric BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator()); 27660b57cec5SDimitry Andric BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold", 27670b57cec5SDimitry Andric BB->getParent(), BB); 27680b57cec5SDimitry Andric // Move the unconditional branch to NewBB. 27690b57cec5SDimitry Andric PredTerm->removeFromParent(); 2770bdd1243dSDimitry Andric PredTerm->insertInto(NewBB, NewBB->end()); 27710b57cec5SDimitry Andric // Create a conditional branch and update PHI nodes. 2772fe6060f1SDimitry Andric auto *BI = BranchInst::Create(NewBB, BB, SI->getCondition(), Pred); 2773fe6060f1SDimitry Andric BI->applyMergedLocation(PredTerm->getDebugLoc(), SI->getDebugLoc()); 2774bdd1243dSDimitry Andric BI->copyMetadata(*SI, {LLVMContext::MD_prof}); 27750b57cec5SDimitry Andric SIUse->setIncomingValue(Idx, SI->getFalseValue()); 27760b57cec5SDimitry Andric SIUse->addIncoming(SI->getTrueValue(), NewBB); 277706c3fb27SDimitry Andric 277806c3fb27SDimitry Andric uint64_t TrueWeight = 1; 277906c3fb27SDimitry Andric uint64_t FalseWeight = 1; 278006c3fb27SDimitry Andric // Copy probabilities from 'SI' to created conditional branch in 'Pred'. 2781bdd1243dSDimitry Andric if (extractBranchWeights(*SI, TrueWeight, FalseWeight) && 2782bdd1243dSDimitry Andric (TrueWeight + FalseWeight) != 0) { 2783bdd1243dSDimitry Andric SmallVector<BranchProbability, 2> BP; 2784bdd1243dSDimitry Andric BP.emplace_back(BranchProbability::getBranchProbability( 2785bdd1243dSDimitry Andric TrueWeight, TrueWeight + FalseWeight)); 2786bdd1243dSDimitry Andric BP.emplace_back(BranchProbability::getBranchProbability( 2787bdd1243dSDimitry Andric FalseWeight, TrueWeight + FalseWeight)); 278806c3fb27SDimitry Andric // Update BPI if exists. 278906c3fb27SDimitry Andric if (auto *BPI = getBPI()) 2790bdd1243dSDimitry Andric BPI->setEdgeProbability(Pred, BP); 2791bdd1243dSDimitry Andric } 279206c3fb27SDimitry Andric // Set the block frequency of NewBB. 279306c3fb27SDimitry Andric if (auto *BFI = getBFI()) { 279406c3fb27SDimitry Andric if ((TrueWeight + FalseWeight) == 0) { 279506c3fb27SDimitry Andric TrueWeight = 1; 279606c3fb27SDimitry Andric FalseWeight = 1; 279706c3fb27SDimitry Andric } 279806c3fb27SDimitry Andric BranchProbability PredToNewBBProb = BranchProbability::getBranchProbability( 279906c3fb27SDimitry Andric TrueWeight, TrueWeight + FalseWeight); 280006c3fb27SDimitry Andric auto NewBBFreq = BFI->getBlockFreq(Pred) * PredToNewBBProb; 28015f757f3fSDimitry Andric BFI->setBlockFreq(NewBB, NewBBFreq); 2802bdd1243dSDimitry Andric } 28030b57cec5SDimitry Andric 28040b57cec5SDimitry Andric // The select is now dead. 28050b57cec5SDimitry Andric SI->eraseFromParent(); 28060b57cec5SDimitry Andric DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB}, 28070b57cec5SDimitry Andric {DominatorTree::Insert, Pred, NewBB}}); 28080b57cec5SDimitry Andric 28090b57cec5SDimitry Andric // Update any other PHI nodes in BB. 28100b57cec5SDimitry Andric for (BasicBlock::iterator BI = BB->begin(); 28110b57cec5SDimitry Andric PHINode *Phi = dyn_cast<PHINode>(BI); ++BI) 28120b57cec5SDimitry Andric if (Phi != SIUse) 28130b57cec5SDimitry Andric Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB); 28140b57cec5SDimitry Andric } 28150b57cec5SDimitry Andric 2816e8d8bef9SDimitry Andric bool JumpThreadingPass::tryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) { 28170b57cec5SDimitry Andric PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition()); 28180b57cec5SDimitry Andric 28190b57cec5SDimitry Andric if (!CondPHI || CondPHI->getParent() != BB) 28200b57cec5SDimitry Andric return false; 28210b57cec5SDimitry Andric 28220b57cec5SDimitry Andric for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) { 28230b57cec5SDimitry Andric BasicBlock *Pred = CondPHI->getIncomingBlock(I); 28240b57cec5SDimitry Andric SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I)); 28250b57cec5SDimitry Andric 28260b57cec5SDimitry Andric // The second and third condition can be potentially relaxed. Currently 28270b57cec5SDimitry Andric // the conditions help to simplify the code and allow us to reuse existing 2828e8d8bef9SDimitry Andric // code, developed for tryToUnfoldSelect(CmpInst *, BasicBlock *) 28290b57cec5SDimitry Andric if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse()) 28300b57cec5SDimitry Andric continue; 28310b57cec5SDimitry Andric 28320b57cec5SDimitry Andric BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator()); 28330b57cec5SDimitry Andric if (!PredTerm || !PredTerm->isUnconditional()) 28340b57cec5SDimitry Andric continue; 28350b57cec5SDimitry Andric 2836e8d8bef9SDimitry Andric unfoldSelectInstr(Pred, BB, PredSI, CondPHI, I); 28370b57cec5SDimitry Andric return true; 28380b57cec5SDimitry Andric } 28390b57cec5SDimitry Andric return false; 28400b57cec5SDimitry Andric } 28410b57cec5SDimitry Andric 2842e8d8bef9SDimitry Andric /// tryToUnfoldSelect - Look for blocks of the form 28430b57cec5SDimitry Andric /// bb1: 28440b57cec5SDimitry Andric /// %a = select 28450b57cec5SDimitry Andric /// br bb2 28460b57cec5SDimitry Andric /// 28470b57cec5SDimitry Andric /// bb2: 28480b57cec5SDimitry Andric /// %p = phi [%a, %bb1] ... 28490b57cec5SDimitry Andric /// %c = icmp %p 28500b57cec5SDimitry Andric /// br i1 %c 28510b57cec5SDimitry Andric /// 28520b57cec5SDimitry Andric /// And expand the select into a branch structure if one of its arms allows %c 28530b57cec5SDimitry Andric /// to be folded. This later enables threading from bb1 over bb2. 2854e8d8bef9SDimitry Andric bool JumpThreadingPass::tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) { 28550b57cec5SDimitry Andric BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 28560b57cec5SDimitry Andric PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0)); 28570b57cec5SDimitry Andric Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1)); 28580b57cec5SDimitry Andric 28590b57cec5SDimitry Andric if (!CondBr || !CondBr->isConditional() || !CondLHS || 28600b57cec5SDimitry Andric CondLHS->getParent() != BB) 28610b57cec5SDimitry Andric return false; 28620b57cec5SDimitry Andric 28630b57cec5SDimitry Andric for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) { 28640b57cec5SDimitry Andric BasicBlock *Pred = CondLHS->getIncomingBlock(I); 28650b57cec5SDimitry Andric SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I)); 28660b57cec5SDimitry Andric 28670b57cec5SDimitry Andric // Look if one of the incoming values is a select in the corresponding 28680b57cec5SDimitry Andric // predecessor. 28690b57cec5SDimitry Andric if (!SI || SI->getParent() != Pred || !SI->hasOneUse()) 28700b57cec5SDimitry Andric continue; 28710b57cec5SDimitry Andric 28720b57cec5SDimitry Andric BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator()); 28730b57cec5SDimitry Andric if (!PredTerm || !PredTerm->isUnconditional()) 28740b57cec5SDimitry Andric continue; 28750b57cec5SDimitry Andric 28760b57cec5SDimitry Andric // Now check if one of the select values would allow us to constant fold the 28770b57cec5SDimitry Andric // terminator in BB. We don't do the transform if both sides fold, those 28780b57cec5SDimitry Andric // cases will be threaded in any case. 2879*0fca6ea1SDimitry Andric Constant *LHSRes = 28800b57cec5SDimitry Andric LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1), 28810b57cec5SDimitry Andric CondRHS, Pred, BB, CondCmp); 2882*0fca6ea1SDimitry Andric Constant *RHSRes = 28830b57cec5SDimitry Andric LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2), 28840b57cec5SDimitry Andric CondRHS, Pred, BB, CondCmp); 2885*0fca6ea1SDimitry Andric if ((LHSRes || RHSRes) && LHSRes != RHSRes) { 2886e8d8bef9SDimitry Andric unfoldSelectInstr(Pred, BB, SI, CondLHS, I); 28870b57cec5SDimitry Andric return true; 28880b57cec5SDimitry Andric } 28890b57cec5SDimitry Andric } 28900b57cec5SDimitry Andric return false; 28910b57cec5SDimitry Andric } 28920b57cec5SDimitry Andric 2893e8d8bef9SDimitry Andric /// tryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the 28940b57cec5SDimitry Andric /// same BB in the form 28950b57cec5SDimitry Andric /// bb: 28960b57cec5SDimitry Andric /// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ... 28970b57cec5SDimitry Andric /// %s = select %p, trueval, falseval 28980b57cec5SDimitry Andric /// 28990b57cec5SDimitry Andric /// or 29000b57cec5SDimitry Andric /// 29010b57cec5SDimitry Andric /// bb: 29020b57cec5SDimitry Andric /// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ... 29030b57cec5SDimitry Andric /// %c = cmp %p, 0 29040b57cec5SDimitry Andric /// %s = select %c, trueval, falseval 29050b57cec5SDimitry Andric /// 29060b57cec5SDimitry Andric /// And expand the select into a branch structure. This later enables 29070b57cec5SDimitry Andric /// jump-threading over bb in this pass. 29080b57cec5SDimitry Andric /// 29090b57cec5SDimitry Andric /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold 29100b57cec5SDimitry Andric /// select if the associated PHI has at least one constant. If the unfolded 29110b57cec5SDimitry Andric /// select is not jump-threaded, it will be folded again in the later 29120b57cec5SDimitry Andric /// optimizations. 2913e8d8bef9SDimitry Andric bool JumpThreadingPass::tryToUnfoldSelectInCurrBB(BasicBlock *BB) { 2914e8d8bef9SDimitry Andric // This transform would reduce the quality of msan diagnostics. 29155ffd83dbSDimitry Andric // Disable this transform under MemorySanitizer. 29165ffd83dbSDimitry Andric if (BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory)) 29175ffd83dbSDimitry Andric return false; 29185ffd83dbSDimitry Andric 29190b57cec5SDimitry Andric // If threading this would thread across a loop header, don't thread the edge. 2920e8d8bef9SDimitry Andric // See the comments above findLoopHeaders for justifications and caveats. 29210b57cec5SDimitry Andric if (LoopHeaders.count(BB)) 29220b57cec5SDimitry Andric return false; 29230b57cec5SDimitry Andric 29240b57cec5SDimitry Andric for (BasicBlock::iterator BI = BB->begin(); 29250b57cec5SDimitry Andric PHINode *PN = dyn_cast<PHINode>(BI); ++BI) { 29260b57cec5SDimitry Andric // Look for a Phi having at least one constant incoming value. 29270b57cec5SDimitry Andric if (llvm::all_of(PN->incoming_values(), 29280b57cec5SDimitry Andric [](Value *V) { return !isa<ConstantInt>(V); })) 29290b57cec5SDimitry Andric continue; 29300b57cec5SDimitry Andric 29310b57cec5SDimitry Andric auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) { 2932fe6060f1SDimitry Andric using namespace PatternMatch; 2933fe6060f1SDimitry Andric 29340b57cec5SDimitry Andric // Check if SI is in BB and use V as condition. 29350b57cec5SDimitry Andric if (SI->getParent() != BB) 29360b57cec5SDimitry Andric return false; 29370b57cec5SDimitry Andric Value *Cond = SI->getCondition(); 2938fe6060f1SDimitry Andric bool IsAndOr = match(SI, m_CombineOr(m_LogicalAnd(), m_LogicalOr())); 2939fe6060f1SDimitry Andric return Cond && Cond == V && Cond->getType()->isIntegerTy(1) && !IsAndOr; 29400b57cec5SDimitry Andric }; 29410b57cec5SDimitry Andric 29420b57cec5SDimitry Andric SelectInst *SI = nullptr; 29430b57cec5SDimitry Andric for (Use &U : PN->uses()) { 29440b57cec5SDimitry Andric if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) { 29450b57cec5SDimitry Andric // Look for a ICmp in BB that compares PN with a constant and is the 29460b57cec5SDimitry Andric // condition of a Select. 29470b57cec5SDimitry Andric if (Cmp->getParent() == BB && Cmp->hasOneUse() && 29480b57cec5SDimitry Andric isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo()))) 29490b57cec5SDimitry Andric if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back())) 29500b57cec5SDimitry Andric if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) { 29510b57cec5SDimitry Andric SI = SelectI; 29520b57cec5SDimitry Andric break; 29530b57cec5SDimitry Andric } 29540b57cec5SDimitry Andric } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) { 29550b57cec5SDimitry Andric // Look for a Select in BB that uses PN as condition. 29560b57cec5SDimitry Andric if (isUnfoldCandidate(SelectI, U.get())) { 29570b57cec5SDimitry Andric SI = SelectI; 29580b57cec5SDimitry Andric break; 29590b57cec5SDimitry Andric } 29600b57cec5SDimitry Andric } 29610b57cec5SDimitry Andric } 29620b57cec5SDimitry Andric 29630b57cec5SDimitry Andric if (!SI) 29640b57cec5SDimitry Andric continue; 29650b57cec5SDimitry Andric // Expand the select. 2966e8d8bef9SDimitry Andric Value *Cond = SI->getCondition(); 296781ad6265SDimitry Andric if (!isGuaranteedNotToBeUndefOrPoison(Cond, nullptr, SI)) 2968*0fca6ea1SDimitry Andric Cond = new FreezeInst(Cond, "cond.fr", SI->getIterator()); 29695f757f3fSDimitry Andric MDNode *BranchWeights = getBranchWeightMDNode(*SI); 29705f757f3fSDimitry Andric Instruction *Term = 29715f757f3fSDimitry Andric SplitBlockAndInsertIfThen(Cond, SI, false, BranchWeights); 29720b57cec5SDimitry Andric BasicBlock *SplitBB = SI->getParent(); 29730b57cec5SDimitry Andric BasicBlock *NewBB = Term->getParent(); 2974*0fca6ea1SDimitry Andric PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI->getIterator()); 29750b57cec5SDimitry Andric NewPN->addIncoming(SI->getTrueValue(), Term->getParent()); 29760b57cec5SDimitry Andric NewPN->addIncoming(SI->getFalseValue(), BB); 2977*0fca6ea1SDimitry Andric NewPN->setDebugLoc(SI->getDebugLoc()); 29780b57cec5SDimitry Andric SI->replaceAllUsesWith(NewPN); 29790b57cec5SDimitry Andric SI->eraseFromParent(); 29800b57cec5SDimitry Andric // NewBB and SplitBB are newly created blocks which require insertion. 29810b57cec5SDimitry Andric std::vector<DominatorTree::UpdateType> Updates; 29820b57cec5SDimitry Andric Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3); 29830b57cec5SDimitry Andric Updates.push_back({DominatorTree::Insert, BB, SplitBB}); 29840b57cec5SDimitry Andric Updates.push_back({DominatorTree::Insert, BB, NewBB}); 29850b57cec5SDimitry Andric Updates.push_back({DominatorTree::Insert, NewBB, SplitBB}); 29860b57cec5SDimitry Andric // BB's successors were moved to SplitBB, update DTU accordingly. 29870b57cec5SDimitry Andric for (auto *Succ : successors(SplitBB)) { 29880b57cec5SDimitry Andric Updates.push_back({DominatorTree::Delete, BB, Succ}); 29890b57cec5SDimitry Andric Updates.push_back({DominatorTree::Insert, SplitBB, Succ}); 29900b57cec5SDimitry Andric } 29910b57cec5SDimitry Andric DTU->applyUpdatesPermissive(Updates); 29920b57cec5SDimitry Andric return true; 29930b57cec5SDimitry Andric } 29940b57cec5SDimitry Andric return false; 29950b57cec5SDimitry Andric } 29960b57cec5SDimitry Andric 29970b57cec5SDimitry Andric /// Try to propagate a guard from the current BB into one of its predecessors 29980b57cec5SDimitry Andric /// in case if another branch of execution implies that the condition of this 29990b57cec5SDimitry Andric /// guard is always true. Currently we only process the simplest case that 30000b57cec5SDimitry Andric /// looks like: 30010b57cec5SDimitry Andric /// 30020b57cec5SDimitry Andric /// Start: 30030b57cec5SDimitry Andric /// %cond = ... 30040b57cec5SDimitry Andric /// br i1 %cond, label %T1, label %F1 30050b57cec5SDimitry Andric /// T1: 30060b57cec5SDimitry Andric /// br label %Merge 30070b57cec5SDimitry Andric /// F1: 30080b57cec5SDimitry Andric /// br label %Merge 30090b57cec5SDimitry Andric /// Merge: 30100b57cec5SDimitry Andric /// %condGuard = ... 30110b57cec5SDimitry Andric /// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ] 30120b57cec5SDimitry Andric /// 30130b57cec5SDimitry Andric /// And cond either implies condGuard or !condGuard. In this case all the 30140b57cec5SDimitry Andric /// instructions before the guard can be duplicated in both branches, and the 30150b57cec5SDimitry Andric /// guard is then threaded to one of them. 3016e8d8bef9SDimitry Andric bool JumpThreadingPass::processGuards(BasicBlock *BB) { 30170b57cec5SDimitry Andric using namespace PatternMatch; 30180b57cec5SDimitry Andric 30190b57cec5SDimitry Andric // We only want to deal with two predecessors. 30200b57cec5SDimitry Andric BasicBlock *Pred1, *Pred2; 30210b57cec5SDimitry Andric auto PI = pred_begin(BB), PE = pred_end(BB); 30220b57cec5SDimitry Andric if (PI == PE) 30230b57cec5SDimitry Andric return false; 30240b57cec5SDimitry Andric Pred1 = *PI++; 30250b57cec5SDimitry Andric if (PI == PE) 30260b57cec5SDimitry Andric return false; 30270b57cec5SDimitry Andric Pred2 = *PI++; 30280b57cec5SDimitry Andric if (PI != PE) 30290b57cec5SDimitry Andric return false; 30300b57cec5SDimitry Andric if (Pred1 == Pred2) 30310b57cec5SDimitry Andric return false; 30320b57cec5SDimitry Andric 30330b57cec5SDimitry Andric // Try to thread one of the guards of the block. 30340b57cec5SDimitry Andric // TODO: Look up deeper than to immediate predecessor? 30350b57cec5SDimitry Andric auto *Parent = Pred1->getSinglePredecessor(); 30360b57cec5SDimitry Andric if (!Parent || Parent != Pred2->getSinglePredecessor()) 30370b57cec5SDimitry Andric return false; 30380b57cec5SDimitry Andric 30390b57cec5SDimitry Andric if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator())) 30400b57cec5SDimitry Andric for (auto &I : *BB) 3041e8d8bef9SDimitry Andric if (isGuard(&I) && threadGuard(BB, cast<IntrinsicInst>(&I), BI)) 30420b57cec5SDimitry Andric return true; 30430b57cec5SDimitry Andric 30440b57cec5SDimitry Andric return false; 30450b57cec5SDimitry Andric } 30460b57cec5SDimitry Andric 30470b57cec5SDimitry Andric /// Try to propagate the guard from BB which is the lower block of a diamond 30480b57cec5SDimitry Andric /// to one of its branches, in case if diamond's condition implies guard's 30490b57cec5SDimitry Andric /// condition. 3050e8d8bef9SDimitry Andric bool JumpThreadingPass::threadGuard(BasicBlock *BB, IntrinsicInst *Guard, 30510b57cec5SDimitry Andric BranchInst *BI) { 30520b57cec5SDimitry Andric assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?"); 30530b57cec5SDimitry Andric assert(BI->isConditional() && "Unconditional branch has 2 successors?"); 30540b57cec5SDimitry Andric Value *GuardCond = Guard->getArgOperand(0); 30550b57cec5SDimitry Andric Value *BranchCond = BI->getCondition(); 30560b57cec5SDimitry Andric BasicBlock *TrueDest = BI->getSuccessor(0); 30570b57cec5SDimitry Andric BasicBlock *FalseDest = BI->getSuccessor(1); 30580b57cec5SDimitry Andric 3059*0fca6ea1SDimitry Andric auto &DL = BB->getDataLayout(); 30600b57cec5SDimitry Andric bool TrueDestIsSafe = false; 30610b57cec5SDimitry Andric bool FalseDestIsSafe = false; 30620b57cec5SDimitry Andric 30630b57cec5SDimitry Andric // True dest is safe if BranchCond => GuardCond. 30640b57cec5SDimitry Andric auto Impl = isImpliedCondition(BranchCond, GuardCond, DL); 30650b57cec5SDimitry Andric if (Impl && *Impl) 30660b57cec5SDimitry Andric TrueDestIsSafe = true; 30670b57cec5SDimitry Andric else { 30680b57cec5SDimitry Andric // False dest is safe if !BranchCond => GuardCond. 30690b57cec5SDimitry Andric Impl = isImpliedCondition(BranchCond, GuardCond, DL, /* LHSIsTrue */ false); 30700b57cec5SDimitry Andric if (Impl && *Impl) 30710b57cec5SDimitry Andric FalseDestIsSafe = true; 30720b57cec5SDimitry Andric } 30730b57cec5SDimitry Andric 30740b57cec5SDimitry Andric if (!TrueDestIsSafe && !FalseDestIsSafe) 30750b57cec5SDimitry Andric return false; 30760b57cec5SDimitry Andric 30770b57cec5SDimitry Andric BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest; 30780b57cec5SDimitry Andric BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest; 30790b57cec5SDimitry Andric 30800b57cec5SDimitry Andric ValueToValueMapTy UnguardedMapping, GuardedMapping; 30810b57cec5SDimitry Andric Instruction *AfterGuard = Guard->getNextNode(); 3082349cc55cSDimitry Andric unsigned Cost = 3083349cc55cSDimitry Andric getJumpThreadDuplicationCost(TTI, BB, AfterGuard, BBDupThreshold); 30840b57cec5SDimitry Andric if (Cost > BBDupThreshold) 30850b57cec5SDimitry Andric return false; 30860b57cec5SDimitry Andric // Duplicate all instructions before the guard and the guard itself to the 30870b57cec5SDimitry Andric // branch where implication is not proved. 30880b57cec5SDimitry Andric BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween( 30890b57cec5SDimitry Andric BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU); 30900b57cec5SDimitry Andric assert(GuardedBlock && "Could not create the guarded block?"); 30910b57cec5SDimitry Andric // Duplicate all instructions before the guard in the unguarded branch. 30920b57cec5SDimitry Andric // Since we have successfully duplicated the guarded block and this block 30930b57cec5SDimitry Andric // has fewer instructions, we expect it to succeed. 30940b57cec5SDimitry Andric BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween( 30950b57cec5SDimitry Andric BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU); 30960b57cec5SDimitry Andric assert(UnguardedBlock && "Could not create the unguarded block?"); 30970b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block " 30980b57cec5SDimitry Andric << GuardedBlock->getName() << "\n"); 30990b57cec5SDimitry Andric // Some instructions before the guard may still have uses. For them, we need 31000b57cec5SDimitry Andric // to create Phi nodes merging their copies in both guarded and unguarded 31010b57cec5SDimitry Andric // branches. Those instructions that have no uses can be just removed. 31020b57cec5SDimitry Andric SmallVector<Instruction *, 4> ToRemove; 31030b57cec5SDimitry Andric for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI) 31040b57cec5SDimitry Andric if (!isa<PHINode>(&*BI)) 31050b57cec5SDimitry Andric ToRemove.push_back(&*BI); 31060b57cec5SDimitry Andric 31075f757f3fSDimitry Andric BasicBlock::iterator InsertionPoint = BB->getFirstInsertionPt(); 31085f757f3fSDimitry Andric assert(InsertionPoint != BB->end() && "Empty block?"); 31090b57cec5SDimitry Andric // Substitute with Phis & remove. 31100b57cec5SDimitry Andric for (auto *Inst : reverse(ToRemove)) { 31110b57cec5SDimitry Andric if (!Inst->use_empty()) { 31120b57cec5SDimitry Andric PHINode *NewPN = PHINode::Create(Inst->getType(), 2); 31130b57cec5SDimitry Andric NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock); 31140b57cec5SDimitry Andric NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock); 3115*0fca6ea1SDimitry Andric NewPN->setDebugLoc(Inst->getDebugLoc()); 31160b57cec5SDimitry Andric NewPN->insertBefore(InsertionPoint); 31170b57cec5SDimitry Andric Inst->replaceAllUsesWith(NewPN); 31180b57cec5SDimitry Andric } 3119*0fca6ea1SDimitry Andric Inst->dropDbgRecords(); 31200b57cec5SDimitry Andric Inst->eraseFromParent(); 31210b57cec5SDimitry Andric } 31220b57cec5SDimitry Andric return true; 31230b57cec5SDimitry Andric } 312406c3fb27SDimitry Andric 312506c3fb27SDimitry Andric PreservedAnalyses JumpThreadingPass::getPreservedAnalysis() const { 312606c3fb27SDimitry Andric PreservedAnalyses PA; 312706c3fb27SDimitry Andric PA.preserve<LazyValueAnalysis>(); 312806c3fb27SDimitry Andric PA.preserve<DominatorTreeAnalysis>(); 312906c3fb27SDimitry Andric 313006c3fb27SDimitry Andric // TODO: We would like to preserve BPI/BFI. Enable once all paths update them. 313106c3fb27SDimitry Andric // TODO: Would be nice to verify BPI/BFI consistency as well. 313206c3fb27SDimitry Andric return PA; 313306c3fb27SDimitry Andric } 313406c3fb27SDimitry Andric 313506c3fb27SDimitry Andric template <typename AnalysisT> 313606c3fb27SDimitry Andric typename AnalysisT::Result *JumpThreadingPass::runExternalAnalysis() { 313706c3fb27SDimitry Andric assert(FAM && "Can't run external analysis without FunctionAnalysisManager"); 313806c3fb27SDimitry Andric 313906c3fb27SDimitry Andric // If there were no changes since last call to 'runExternalAnalysis' then all 314006c3fb27SDimitry Andric // analysis is either up to date or explicitly invalidated. Just go ahead and 314106c3fb27SDimitry Andric // run the "external" analysis. 314206c3fb27SDimitry Andric if (!ChangedSinceLastAnalysisUpdate) { 314306c3fb27SDimitry Andric assert(!DTU->hasPendingUpdates() && 314406c3fb27SDimitry Andric "Lost update of 'ChangedSinceLastAnalysisUpdate'?"); 314506c3fb27SDimitry Andric // Run the "external" analysis. 314606c3fb27SDimitry Andric return &FAM->getResult<AnalysisT>(*F); 314706c3fb27SDimitry Andric } 314806c3fb27SDimitry Andric ChangedSinceLastAnalysisUpdate = false; 314906c3fb27SDimitry Andric 315006c3fb27SDimitry Andric auto PA = getPreservedAnalysis(); 315106c3fb27SDimitry Andric // TODO: This shouldn't be needed once 'getPreservedAnalysis' reports BPI/BFI 315206c3fb27SDimitry Andric // as preserved. 315306c3fb27SDimitry Andric PA.preserve<BranchProbabilityAnalysis>(); 315406c3fb27SDimitry Andric PA.preserve<BlockFrequencyAnalysis>(); 315506c3fb27SDimitry Andric // Report everything except explicitly preserved as invalid. 315606c3fb27SDimitry Andric FAM->invalidate(*F, PA); 315706c3fb27SDimitry Andric // Update DT/PDT. 315806c3fb27SDimitry Andric DTU->flush(); 315906c3fb27SDimitry Andric // Make sure DT/PDT are valid before running "external" analysis. 316006c3fb27SDimitry Andric assert(DTU->getDomTree().verify(DominatorTree::VerificationLevel::Fast)); 316106c3fb27SDimitry Andric assert((!DTU->hasPostDomTree() || 316206c3fb27SDimitry Andric DTU->getPostDomTree().verify( 316306c3fb27SDimitry Andric PostDominatorTree::VerificationLevel::Fast))); 316406c3fb27SDimitry Andric // Run the "external" analysis. 316506c3fb27SDimitry Andric auto *Result = &FAM->getResult<AnalysisT>(*F); 316606c3fb27SDimitry Andric // Update analysis JumpThreading depends on and not explicitly preserved. 316706c3fb27SDimitry Andric TTI = &FAM->getResult<TargetIRAnalysis>(*F); 316806c3fb27SDimitry Andric TLI = &FAM->getResult<TargetLibraryAnalysis>(*F); 316906c3fb27SDimitry Andric AA = &FAM->getResult<AAManager>(*F); 317006c3fb27SDimitry Andric 317106c3fb27SDimitry Andric return Result; 317206c3fb27SDimitry Andric } 317306c3fb27SDimitry Andric 317406c3fb27SDimitry Andric BranchProbabilityInfo *JumpThreadingPass::getBPI() { 317506c3fb27SDimitry Andric if (!BPI) { 317606c3fb27SDimitry Andric assert(FAM && "Can't create BPI without FunctionAnalysisManager"); 317706c3fb27SDimitry Andric BPI = FAM->getCachedResult<BranchProbabilityAnalysis>(*F); 317806c3fb27SDimitry Andric } 317906c3fb27SDimitry Andric return *BPI; 318006c3fb27SDimitry Andric } 318106c3fb27SDimitry Andric 318206c3fb27SDimitry Andric BlockFrequencyInfo *JumpThreadingPass::getBFI() { 318306c3fb27SDimitry Andric if (!BFI) { 318406c3fb27SDimitry Andric assert(FAM && "Can't create BFI without FunctionAnalysisManager"); 318506c3fb27SDimitry Andric BFI = FAM->getCachedResult<BlockFrequencyAnalysis>(*F); 318606c3fb27SDimitry Andric } 318706c3fb27SDimitry Andric return *BFI; 318806c3fb27SDimitry Andric } 318906c3fb27SDimitry Andric 319006c3fb27SDimitry Andric // Important note on validity of BPI/BFI. JumpThreading tries to preserve 319106c3fb27SDimitry Andric // BPI/BFI as it goes. Thus if cached instance exists it will be updated. 319206c3fb27SDimitry Andric // Otherwise, new instance of BPI/BFI is created (up to date by definition). 319306c3fb27SDimitry Andric BranchProbabilityInfo *JumpThreadingPass::getOrCreateBPI(bool Force) { 319406c3fb27SDimitry Andric auto *Res = getBPI(); 319506c3fb27SDimitry Andric if (Res) 319606c3fb27SDimitry Andric return Res; 319706c3fb27SDimitry Andric 319806c3fb27SDimitry Andric if (Force) 319906c3fb27SDimitry Andric BPI = runExternalAnalysis<BranchProbabilityAnalysis>(); 320006c3fb27SDimitry Andric 320106c3fb27SDimitry Andric return *BPI; 320206c3fb27SDimitry Andric } 320306c3fb27SDimitry Andric 320406c3fb27SDimitry Andric BlockFrequencyInfo *JumpThreadingPass::getOrCreateBFI(bool Force) { 320506c3fb27SDimitry Andric auto *Res = getBFI(); 320606c3fb27SDimitry Andric if (Res) 320706c3fb27SDimitry Andric return Res; 320806c3fb27SDimitry Andric 320906c3fb27SDimitry Andric if (Force) 321006c3fb27SDimitry Andric BFI = runExternalAnalysis<BlockFrequencyAnalysis>(); 321106c3fb27SDimitry Andric 321206c3fb27SDimitry Andric return *BFI; 321306c3fb27SDimitry Andric } 3214