1009b1c42SEd Schouten //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements the Jump Threading pass.
10009b1c42SEd Schouten //
11009b1c42SEd Schouten //===----------------------------------------------------------------------===//
12009b1c42SEd Schouten
1301095a5dSDimitry Andric #include "llvm/Transforms/Scalar/JumpThreading.h"
144a16efa3SDimitry Andric #include "llvm/ADT/DenseMap.h"
154a16efa3SDimitry Andric #include "llvm/ADT/DenseSet.h"
16cfca06d7SDimitry Andric #include "llvm/ADT/MapVector.h"
174a16efa3SDimitry Andric #include "llvm/ADT/STLExtras.h"
18044eb2f6SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
19044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
204a16efa3SDimitry Andric #include "llvm/ADT/Statistic.h"
2171d5a254SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
22044eb2f6SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
23044eb2f6SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
247ab83427SDimitry Andric #include "llvm/Analysis/CFG.h"
256b943ff3SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
267ab83427SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
27d8e91e46SDimitry Andric #include "llvm/Analysis/GuardUtils.h"
28907da171SRoman Divacky #include "llvm/Analysis/InstructionSimplify.h"
29044eb2f6SDimitry Andric #include "llvm/Analysis/LazyValueInfo.h"
3066e41e3cSRoman Divacky #include "llvm/Analysis/Loads.h"
31dd58ef01SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
32344a3780SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
337fa27ce4SDimitry Andric #include "llvm/Analysis/PostDominators.h"
34044eb2f6SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
35b60736ecSDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
36dd58ef01SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
37044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
38044eb2f6SDimitry Andric #include "llvm/IR/CFG.h"
39044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
4008bbd35aSDimitry Andric #include "llvm/IR/ConstantRange.h"
41044eb2f6SDimitry Andric #include "llvm/IR/Constants.h"
424a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
437fa27ce4SDimitry Andric #include "llvm/IR/DebugInfo.h"
44044eb2f6SDimitry Andric #include "llvm/IR/Dominators.h"
45044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
46044eb2f6SDimitry Andric #include "llvm/IR/InstrTypes.h"
47044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
48044eb2f6SDimitry Andric #include "llvm/IR/Instructions.h"
494a16efa3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
50044eb2f6SDimitry Andric #include "llvm/IR/Intrinsics.h"
514a16efa3SDimitry Andric #include "llvm/IR/LLVMContext.h"
52dd58ef01SDimitry Andric #include "llvm/IR/MDBuilder.h"
5367c32a98SDimitry Andric #include "llvm/IR/Metadata.h"
54044eb2f6SDimitry Andric #include "llvm/IR/Module.h"
55044eb2f6SDimitry Andric #include "llvm/IR/PassManager.h"
5671d5a254SDimitry Andric #include "llvm/IR/PatternMatch.h"
57e3b55780SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
58044eb2f6SDimitry Andric #include "llvm/IR/Type.h"
59044eb2f6SDimitry Andric #include "llvm/IR/Use.h"
60044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
61044eb2f6SDimitry Andric #include "llvm/Support/BlockFrequency.h"
62044eb2f6SDimitry Andric #include "llvm/Support/BranchProbability.h"
63044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
64009b1c42SEd Schouten #include "llvm/Support/CommandLine.h"
65009b1c42SEd Schouten #include "llvm/Support/Debug.h"
6659850d08SRoman Divacky #include "llvm/Support/raw_ostream.h"
674a16efa3SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
6871d5a254SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
69d8e91e46SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
704a16efa3SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdater.h"
71044eb2f6SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
72dd58ef01SDimitry Andric #include <algorithm>
73044eb2f6SDimitry Andric #include <cassert>
74044eb2f6SDimitry Andric #include <cstdint>
75044eb2f6SDimitry Andric #include <iterator>
76dd58ef01SDimitry Andric #include <memory>
77044eb2f6SDimitry Andric #include <utility>
78044eb2f6SDimitry Andric
79009b1c42SEd Schouten using namespace llvm;
8001095a5dSDimitry Andric using namespace jumpthreading;
81009b1c42SEd Schouten
825ca98fd9SDimitry Andric #define DEBUG_TYPE "jump-threading"
835ca98fd9SDimitry Andric
84009b1c42SEd Schouten STATISTIC(NumThreads, "Number of jumps threaded");
85009b1c42SEd Schouten STATISTIC(NumFolds, "Number of terminators folded");
8659850d08SRoman Divacky STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
87009b1c42SEd Schouten
88009b1c42SEd Schouten static cl::opt<unsigned>
8967c32a98SDimitry Andric BBDuplicateThreshold("jump-threading-threshold",
90009b1c42SEd Schouten cl::desc("Max block size to duplicate for jump threading"),
91009b1c42SEd Schouten cl::init(6), cl::Hidden);
92009b1c42SEd Schouten
93dd58ef01SDimitry Andric static cl::opt<unsigned>
94dd58ef01SDimitry Andric ImplicationSearchThreshold(
95dd58ef01SDimitry Andric "jump-threading-implication-search-threshold",
96dd58ef01SDimitry Andric cl::desc("The number of predecessors to search for a stronger "
97dd58ef01SDimitry Andric "condition to use to thread over a weaker condition"),
98dd58ef01SDimitry Andric cl::init(3), cl::Hidden);
99dd58ef01SDimitry Andric
100e3b55780SDimitry Andric static cl::opt<unsigned> PhiDuplicateThreshold(
101e3b55780SDimitry Andric "jump-threading-phi-threshold",
102e3b55780SDimitry Andric cl::desc("Max PHIs in BB to duplicate for jump threading"), cl::init(76),
103e3b55780SDimitry Andric cl::Hidden);
104e3b55780SDimitry Andric
105e6d15924SDimitry Andric static cl::opt<bool> ThreadAcrossLoopHeaders(
106e6d15924SDimitry Andric "jump-threading-across-loop-headers",
107e6d15924SDimitry Andric cl::desc("Allow JumpThreading to thread across loop headers, for testing"),
108e6d15924SDimitry Andric cl::init(false), cl::Hidden);
109e6d15924SDimitry Andric
JumpThreadingPass(int T)110145449b1SDimitry Andric JumpThreadingPass::JumpThreadingPass(int T) {
111cfca06d7SDimitry Andric DefaultBBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
11201095a5dSDimitry Andric }
11301095a5dSDimitry Andric
114044eb2f6SDimitry Andric // Update branch probability information according to conditional
115eb11fae6SDimitry Andric // branch probability. This is usually made possible for cloned branches
116044eb2f6SDimitry Andric // in inline instances by the context specific profile in the caller.
117044eb2f6SDimitry Andric // For instance,
118044eb2f6SDimitry Andric //
119044eb2f6SDimitry Andric // [Block PredBB]
120044eb2f6SDimitry Andric // [Branch PredBr]
121044eb2f6SDimitry Andric // if (t) {
122044eb2f6SDimitry Andric // Block A;
123044eb2f6SDimitry Andric // } else {
124044eb2f6SDimitry Andric // Block B;
125044eb2f6SDimitry Andric // }
126044eb2f6SDimitry Andric //
127044eb2f6SDimitry Andric // [Block BB]
128044eb2f6SDimitry Andric // cond = PN([true, %A], [..., %B]); // PHI node
129044eb2f6SDimitry Andric // [Branch CondBr]
130044eb2f6SDimitry Andric // if (cond) {
131044eb2f6SDimitry Andric // ... // P(cond == true) = 1%
132044eb2f6SDimitry Andric // }
133044eb2f6SDimitry Andric //
134044eb2f6SDimitry Andric // Here we know that when block A is taken, cond must be true, which means
135044eb2f6SDimitry Andric // P(cond == true | A) = 1
136044eb2f6SDimitry Andric //
137044eb2f6SDimitry Andric // Given that P(cond == true) = P(cond == true | A) * P(A) +
138044eb2f6SDimitry Andric // P(cond == true | B) * P(B)
139044eb2f6SDimitry Andric // we get:
140044eb2f6SDimitry Andric // P(cond == true ) = P(A) + P(cond == true | B) * P(B)
141044eb2f6SDimitry Andric //
142044eb2f6SDimitry Andric // which gives us:
143044eb2f6SDimitry Andric // P(A) is less than P(cond == true), i.e.
144044eb2f6SDimitry Andric // P(t == true) <= P(cond == true)
145044eb2f6SDimitry Andric //
146044eb2f6SDimitry Andric // In other words, if we know P(cond == true) is unlikely, we know
147044eb2f6SDimitry Andric // that P(t == true) is also unlikely.
148044eb2f6SDimitry Andric //
updatePredecessorProfileMetadata(PHINode * PN,BasicBlock * BB)149044eb2f6SDimitry Andric static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) {
150044eb2f6SDimitry Andric BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
151044eb2f6SDimitry Andric if (!CondBr)
152044eb2f6SDimitry Andric return;
153044eb2f6SDimitry Andric
154044eb2f6SDimitry Andric uint64_t TrueWeight, FalseWeight;
155e3b55780SDimitry Andric if (!extractBranchWeights(*CondBr, TrueWeight, FalseWeight))
156044eb2f6SDimitry Andric return;
157044eb2f6SDimitry Andric
158cfca06d7SDimitry Andric if (TrueWeight + FalseWeight == 0)
159cfca06d7SDimitry Andric // Zero branch_weights do not give a hint for getting branch probabilities.
160cfca06d7SDimitry Andric // Technically it would result in division by zero denominator, which is
161cfca06d7SDimitry Andric // TrueWeight + FalseWeight.
162cfca06d7SDimitry Andric return;
163cfca06d7SDimitry Andric
164044eb2f6SDimitry Andric // Returns the outgoing edge of the dominating predecessor block
165044eb2f6SDimitry Andric // that leads to the PhiNode's incoming block:
166044eb2f6SDimitry Andric auto GetPredOutEdge =
167044eb2f6SDimitry Andric [](BasicBlock *IncomingBB,
168044eb2f6SDimitry Andric BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
169044eb2f6SDimitry Andric auto *PredBB = IncomingBB;
170044eb2f6SDimitry Andric auto *SuccBB = PhiBB;
1711d5ae102SDimitry Andric SmallPtrSet<BasicBlock *, 16> Visited;
172044eb2f6SDimitry Andric while (true) {
173044eb2f6SDimitry Andric BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
174044eb2f6SDimitry Andric if (PredBr && PredBr->isConditional())
175044eb2f6SDimitry Andric return {PredBB, SuccBB};
1761d5ae102SDimitry Andric Visited.insert(PredBB);
177044eb2f6SDimitry Andric auto *SinglePredBB = PredBB->getSinglePredecessor();
178044eb2f6SDimitry Andric if (!SinglePredBB)
179044eb2f6SDimitry Andric return {nullptr, nullptr};
1801d5ae102SDimitry Andric
1811d5ae102SDimitry Andric // Stop searching when SinglePredBB has been visited. It means we see
1821d5ae102SDimitry Andric // an unreachable loop.
1831d5ae102SDimitry Andric if (Visited.count(SinglePredBB))
1841d5ae102SDimitry Andric return {nullptr, nullptr};
1851d5ae102SDimitry Andric
186044eb2f6SDimitry Andric SuccBB = PredBB;
187044eb2f6SDimitry Andric PredBB = SinglePredBB;
188044eb2f6SDimitry Andric }
189044eb2f6SDimitry Andric };
190044eb2f6SDimitry Andric
191044eb2f6SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
192044eb2f6SDimitry Andric Value *PhiOpnd = PN->getIncomingValue(i);
193044eb2f6SDimitry Andric ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
194044eb2f6SDimitry Andric
195044eb2f6SDimitry Andric if (!CI || !CI->getType()->isIntegerTy(1))
196044eb2f6SDimitry Andric continue;
197044eb2f6SDimitry Andric
198cfca06d7SDimitry Andric BranchProbability BP =
199cfca06d7SDimitry Andric (CI->isOne() ? BranchProbability::getBranchProbability(
200044eb2f6SDimitry Andric TrueWeight, TrueWeight + FalseWeight)
201044eb2f6SDimitry Andric : BranchProbability::getBranchProbability(
202044eb2f6SDimitry Andric FalseWeight, TrueWeight + FalseWeight));
203044eb2f6SDimitry Andric
204044eb2f6SDimitry Andric auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB);
205044eb2f6SDimitry Andric if (!PredOutEdge.first)
206044eb2f6SDimitry Andric return;
207044eb2f6SDimitry Andric
208044eb2f6SDimitry Andric BasicBlock *PredBB = PredOutEdge.first;
2091d5ae102SDimitry Andric BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
2101d5ae102SDimitry Andric if (!PredBr)
2111d5ae102SDimitry Andric return;
212044eb2f6SDimitry Andric
213044eb2f6SDimitry Andric uint64_t PredTrueWeight, PredFalseWeight;
214044eb2f6SDimitry Andric // FIXME: We currently only set the profile data when it is missing.
215044eb2f6SDimitry Andric // With PGO, this can be used to refine even existing profile data with
216044eb2f6SDimitry Andric // context information. This needs to be done after more performance
217044eb2f6SDimitry Andric // testing.
218e3b55780SDimitry Andric if (extractBranchWeights(*PredBr, PredTrueWeight, PredFalseWeight))
219044eb2f6SDimitry Andric continue;
220044eb2f6SDimitry Andric
221044eb2f6SDimitry Andric // We can not infer anything useful when BP >= 50%, because BP is the
222044eb2f6SDimitry Andric // upper bound probability value.
223044eb2f6SDimitry Andric if (BP >= BranchProbability(50, 100))
224044eb2f6SDimitry Andric continue;
225044eb2f6SDimitry Andric
226b1c73532SDimitry Andric uint32_t Weights[2];
227044eb2f6SDimitry Andric if (PredBr->getSuccessor(0) == PredOutEdge.second) {
228b1c73532SDimitry Andric Weights[0] = BP.getNumerator();
229b1c73532SDimitry Andric Weights[1] = BP.getCompl().getNumerator();
230044eb2f6SDimitry Andric } else {
231b1c73532SDimitry Andric Weights[0] = BP.getCompl().getNumerator();
232b1c73532SDimitry Andric Weights[1] = BP.getNumerator();
233044eb2f6SDimitry Andric }
234ac9a064cSDimitry Andric setBranchWeights(*PredBr, Weights, hasBranchWeightOrigin(*PredBr));
235044eb2f6SDimitry Andric }
236044eb2f6SDimitry Andric }
237044eb2f6SDimitry Andric
run(Function & F,FunctionAnalysisManager & AM)23801095a5dSDimitry Andric PreservedAnalyses JumpThreadingPass::run(Function &F,
239b915e9e0SDimitry Andric FunctionAnalysisManager &AM) {
240b60736ecSDimitry Andric auto &TTI = AM.getResult<TargetIRAnalysis>(F);
241b60736ecSDimitry Andric // Jump Threading has no sense for the targets with divergent CF
2427fa27ce4SDimitry Andric if (TTI.hasBranchDivergence(&F))
243b60736ecSDimitry Andric return PreservedAnalyses::all();
24401095a5dSDimitry Andric auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
24501095a5dSDimitry Andric auto &LVI = AM.getResult<LazyValueAnalysis>(F);
24671d5a254SDimitry Andric auto &AA = AM.getResult<AAManager>(F);
2477fa27ce4SDimitry Andric auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
24871d5a254SDimitry Andric
2497fa27ce4SDimitry Andric bool Changed =
2507fa27ce4SDimitry Andric runImpl(F, &AM, &TLI, &TTI, &LVI, &AA,
2517fa27ce4SDimitry Andric std::make_unique<DomTreeUpdater>(
2527fa27ce4SDimitry Andric &DT, nullptr, DomTreeUpdater::UpdateStrategy::Lazy),
2537fa27ce4SDimitry Andric std::nullopt, std::nullopt);
25401095a5dSDimitry Andric
25501095a5dSDimitry Andric if (!Changed)
25601095a5dSDimitry Andric return PreservedAnalyses::all();
2577fa27ce4SDimitry Andric
2587fa27ce4SDimitry Andric
2597fa27ce4SDimitry Andric getDomTreeUpdater()->flush();
2607fa27ce4SDimitry Andric
2617fa27ce4SDimitry Andric #if defined(EXPENSIVE_CHECKS)
2627fa27ce4SDimitry Andric assert(getDomTreeUpdater()->getDomTree().verify(
2637fa27ce4SDimitry Andric DominatorTree::VerificationLevel::Full) &&
2647fa27ce4SDimitry Andric "DT broken after JumpThreading");
2657fa27ce4SDimitry Andric assert((!getDomTreeUpdater()->hasPostDomTree() ||
2667fa27ce4SDimitry Andric getDomTreeUpdater()->getPostDomTree().verify(
2677fa27ce4SDimitry Andric PostDominatorTree::VerificationLevel::Full)) &&
2687fa27ce4SDimitry Andric "PDT broken after JumpThreading");
2697fa27ce4SDimitry Andric #else
2707fa27ce4SDimitry Andric assert(getDomTreeUpdater()->getDomTree().verify(
2717fa27ce4SDimitry Andric DominatorTree::VerificationLevel::Fast) &&
2727fa27ce4SDimitry Andric "DT broken after JumpThreading");
2737fa27ce4SDimitry Andric assert((!getDomTreeUpdater()->hasPostDomTree() ||
2747fa27ce4SDimitry Andric getDomTreeUpdater()->getPostDomTree().verify(
2757fa27ce4SDimitry Andric PostDominatorTree::VerificationLevel::Fast)) &&
2767fa27ce4SDimitry Andric "PDT broken after JumpThreading");
2777fa27ce4SDimitry Andric #endif
2787fa27ce4SDimitry Andric
2797fa27ce4SDimitry Andric return getPreservedAnalysis();
28001095a5dSDimitry Andric }
28101095a5dSDimitry Andric
runImpl(Function & F_,FunctionAnalysisManager * FAM_,TargetLibraryInfo * TLI_,TargetTransformInfo * TTI_,LazyValueInfo * LVI_,AliasAnalysis * AA_,std::unique_ptr<DomTreeUpdater> DTU_,std::optional<BlockFrequencyInfo * > BFI_,std::optional<BranchProbabilityInfo * > BPI_)2827fa27ce4SDimitry Andric bool JumpThreadingPass::runImpl(Function &F_, FunctionAnalysisManager *FAM_,
2837fa27ce4SDimitry Andric TargetLibraryInfo *TLI_,
284c0981da4SDimitry Andric TargetTransformInfo *TTI_, LazyValueInfo *LVI_,
2857fa27ce4SDimitry Andric AliasAnalysis *AA_,
2867fa27ce4SDimitry Andric std::unique_ptr<DomTreeUpdater> DTU_,
2877fa27ce4SDimitry Andric std::optional<BlockFrequencyInfo *> BFI_,
2887fa27ce4SDimitry Andric std::optional<BranchProbabilityInfo *> BPI_) {
2897fa27ce4SDimitry Andric LLVM_DEBUG(dbgs() << "Jump threading on function '" << F_.getName() << "'\n");
2907fa27ce4SDimitry Andric F = &F_;
2917fa27ce4SDimitry Andric FAM = FAM_;
29201095a5dSDimitry Andric TLI = TLI_;
293c0981da4SDimitry Andric TTI = TTI_;
29401095a5dSDimitry Andric LVI = LVI_;
29571d5a254SDimitry Andric AA = AA_;
2967fa27ce4SDimitry Andric DTU = std::move(DTU_);
2977fa27ce4SDimitry Andric BFI = BFI_;
2987fa27ce4SDimitry Andric BPI = BPI_;
2997fa27ce4SDimitry Andric auto *GuardDecl = F->getParent()->getFunction(
30071d5a254SDimitry Andric Intrinsic::getName(Intrinsic::experimental_guard));
30171d5a254SDimitry Andric HasGuards = GuardDecl && !GuardDecl->use_empty();
302009b1c42SEd Schouten
303cfca06d7SDimitry Andric // Reduce the number of instructions duplicated when optimizing strictly for
304cfca06d7SDimitry Andric // size.
305cfca06d7SDimitry Andric if (BBDuplicateThreshold.getNumOccurrences())
306cfca06d7SDimitry Andric BBDupThreshold = BBDuplicateThreshold;
3077fa27ce4SDimitry Andric else if (F->hasFnAttribute(Attribute::MinSize))
308cfca06d7SDimitry Andric BBDupThreshold = 3;
309cfca06d7SDimitry Andric else
310cfca06d7SDimitry Andric BBDupThreshold = DefaultBBDupThreshold;
311cfca06d7SDimitry Andric
312eb11fae6SDimitry Andric // JumpThreading must not processes blocks unreachable from entry. It's a
313eb11fae6SDimitry Andric // waste of compute time and can potentially lead to hangs.
314eb11fae6SDimitry Andric SmallPtrSet<BasicBlock *, 16> Unreachable;
315d8e91e46SDimitry Andric assert(DTU && "DTU isn't passed into JumpThreading before using it.");
316d8e91e46SDimitry Andric assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed.");
317d8e91e46SDimitry Andric DominatorTree &DT = DTU->getDomTree();
3187fa27ce4SDimitry Andric for (auto &BB : *F)
319eb11fae6SDimitry Andric if (!DT.isReachableFromEntry(&BB))
320eb11fae6SDimitry Andric Unreachable.insert(&BB);
3215ca98fd9SDimitry Andric
322e6d15924SDimitry Andric if (!ThreadAcrossLoopHeaders)
3237fa27ce4SDimitry Andric findLoopHeaders(*F);
324009b1c42SEd Schouten
325eb11fae6SDimitry Andric bool EverChanged = false;
326050e163aSDimitry Andric bool Changed;
327829000e0SRoman Divacky do {
328829000e0SRoman Divacky Changed = false;
3297fa27ce4SDimitry Andric for (auto &BB : *F) {
330eb11fae6SDimitry Andric if (Unreachable.count(&BB))
331eb11fae6SDimitry Andric continue;
332b60736ecSDimitry Andric while (processBlock(&BB)) // Thread all of the branches we can over BB.
3337fa27ce4SDimitry Andric Changed = ChangedSinceLastAnalysisUpdate = true;
334cfca06d7SDimitry Andric
335cfca06d7SDimitry Andric // Jump threading may have introduced redundant debug values into BB
336cfca06d7SDimitry Andric // which should be removed.
337cfca06d7SDimitry Andric if (Changed)
338cfca06d7SDimitry Andric RemoveRedundantDbgInstrs(&BB);
339cfca06d7SDimitry Andric
340eb11fae6SDimitry Andric // Stop processing BB if it's the entry or is now deleted. The following
341eb11fae6SDimitry Andric // routines attempt to eliminate BB and locating a suitable replacement
342eb11fae6SDimitry Andric // for the entry is non-trivial.
3437fa27ce4SDimitry Andric if (&BB == &F->getEntryBlock() || DTU->isBBPendingDeletion(&BB))
344eb11fae6SDimitry Andric continue;
345009b1c42SEd Schouten
346eb11fae6SDimitry Andric if (pred_empty(&BB)) {
347b60736ecSDimitry Andric // When processBlock makes BB unreachable it doesn't bother to fix up
348eb11fae6SDimitry Andric // the instructions in it. We must remove BB to prevent invalid IR.
349eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName()
350eb11fae6SDimitry Andric << "' with terminator: " << *BB.getTerminator()
351eb11fae6SDimitry Andric << '\n');
352eb11fae6SDimitry Andric LoopHeaders.erase(&BB);
353eb11fae6SDimitry Andric LVI->eraseBlock(&BB);
3547fa27ce4SDimitry Andric DeleteDeadBlock(&BB, DTU.get());
3557fa27ce4SDimitry Andric Changed = ChangedSinceLastAnalysisUpdate = true;
356cf099d11SDimitry Andric continue;
357cf099d11SDimitry Andric }
358cf099d11SDimitry Andric
359b60736ecSDimitry Andric // processBlock doesn't thread BBs with unconditional TIs. However, if BB
360eb11fae6SDimitry Andric // is "almost empty", we attempt to merge BB with its sole successor.
361eb11fae6SDimitry Andric auto *BI = dyn_cast<BranchInst>(BB.getTerminator());
362cfca06d7SDimitry Andric if (BI && BI->isUnconditional()) {
363cfca06d7SDimitry Andric BasicBlock *Succ = BI->getSuccessor(0);
364cfca06d7SDimitry Andric if (
365eb11fae6SDimitry Andric // The terminator must be the only non-phi instruction in BB.
366344a3780SDimitry Andric BB.getFirstNonPHIOrDbg(true)->isTerminator() &&
367eb11fae6SDimitry Andric // Don't alter Loop headers and latches to ensure another pass can
368eb11fae6SDimitry Andric // detect and transform nested loops later.
369cfca06d7SDimitry Andric !LoopHeaders.count(&BB) && !LoopHeaders.count(Succ) &&
3707fa27ce4SDimitry Andric TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU.get())) {
371cfca06d7SDimitry Andric RemoveRedundantDbgInstrs(Succ);
372d8e91e46SDimitry Andric // BB is valid for cleanup here because we passed in DTU. F remains
373d8e91e46SDimitry Andric // BB's parent until a DTU->getDomTree() event.
374eb11fae6SDimitry Andric LVI->eraseBlock(&BB);
3757fa27ce4SDimitry Andric Changed = ChangedSinceLastAnalysisUpdate = true;
376907da171SRoman Divacky }
377907da171SRoman Divacky }
378cfca06d7SDimitry Andric }
379009b1c42SEd Schouten EverChanged |= Changed;
380829000e0SRoman Divacky } while (Changed);
381009b1c42SEd Schouten
382009b1c42SEd Schouten LoopHeaders.clear();
383009b1c42SEd Schouten return EverChanged;
384009b1c42SEd Schouten }
385009b1c42SEd Schouten
386ab44ce3dSDimitry Andric // Replace uses of Cond with ToVal when safe to do so. If all uses are
387ab44ce3dSDimitry Andric // replaced, we can remove Cond. We cannot blindly replace all uses of Cond
388ab44ce3dSDimitry Andric // because we may incorrectly replace uses when guards/assumes are uses of
389ab44ce3dSDimitry Andric // of `Cond` and we used the guards/assume to reason about the `Cond` value
390ab44ce3dSDimitry Andric // at the end of block. RAUW unconditionally replaces all uses
391ab44ce3dSDimitry Andric // including the guards/assumes themselves and the uses before the
392ab44ce3dSDimitry Andric // guard/assume.
replaceFoldableUses(Instruction * Cond,Value * ToVal,BasicBlock * KnownAtEndOfBB)393145449b1SDimitry Andric static bool replaceFoldableUses(Instruction *Cond, Value *ToVal,
394145449b1SDimitry Andric BasicBlock *KnownAtEndOfBB) {
395145449b1SDimitry Andric bool Changed = false;
396ab44ce3dSDimitry Andric assert(Cond->getType() == ToVal->getType());
397ab44ce3dSDimitry Andric // We can unconditionally replace all uses in non-local blocks (i.e. uses
398ab44ce3dSDimitry Andric // strictly dominated by BB), since LVI information is true from the
399ab44ce3dSDimitry Andric // terminator of BB.
400145449b1SDimitry Andric if (Cond->getParent() == KnownAtEndOfBB)
401145449b1SDimitry Andric Changed |= replaceNonLocalUsesWith(Cond, ToVal);
402145449b1SDimitry Andric for (Instruction &I : reverse(*KnownAtEndOfBB)) {
403b1c73532SDimitry Andric // Replace any debug-info record users of Cond with ToVal.
404ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
405ac9a064cSDimitry Andric DVR.replaceVariableLocationOp(Cond, ToVal, true);
406b1c73532SDimitry Andric
407ab44ce3dSDimitry Andric // Reached the Cond whose uses we are trying to replace, so there are no
408ab44ce3dSDimitry Andric // more uses.
409ab44ce3dSDimitry Andric if (&I == Cond)
410ab44ce3dSDimitry Andric break;
411ab44ce3dSDimitry Andric // We only replace uses in instructions that are guaranteed to reach the end
412ab44ce3dSDimitry Andric // of BB, where we know Cond is ToVal.
413ab44ce3dSDimitry Andric if (!isGuaranteedToTransferExecutionToSuccessor(&I))
414ab44ce3dSDimitry Andric break;
415145449b1SDimitry Andric Changed |= I.replaceUsesOfWith(Cond, ToVal);
416ab44ce3dSDimitry Andric }
417145449b1SDimitry Andric if (Cond->use_empty() && !Cond->mayHaveSideEffects()) {
418ab44ce3dSDimitry Andric Cond->eraseFromParent();
419145449b1SDimitry Andric Changed = true;
420145449b1SDimitry Andric }
421145449b1SDimitry Andric return Changed;
422ab44ce3dSDimitry Andric }
423ab44ce3dSDimitry Andric
42471d5a254SDimitry Andric /// Return the cost of duplicating a piece of this block from first non-phi
42571d5a254SDimitry Andric /// and before StopAt instruction to thread across it. Stop scanning the block
42671d5a254SDimitry Andric /// when exceeding the threshold. If duplication is impossible, returns ~0U.
getJumpThreadDuplicationCost(const TargetTransformInfo * TTI,BasicBlock * BB,Instruction * StopAt,unsigned Threshold)427c0981da4SDimitry Andric static unsigned getJumpThreadDuplicationCost(const TargetTransformInfo *TTI,
428c0981da4SDimitry Andric BasicBlock *BB,
42971d5a254SDimitry Andric Instruction *StopAt,
4304a16efa3SDimitry Andric unsigned Threshold) {
43171d5a254SDimitry Andric assert(StopAt->getParent() == BB && "Not an instruction from proper BB?");
432e3b55780SDimitry Andric
433e3b55780SDimitry Andric // Do not duplicate the BB if it has a lot of PHI nodes.
434e3b55780SDimitry Andric // If a threadable chain is too long then the number of PHI nodes can add up,
435e3b55780SDimitry Andric // leading to a substantial increase in compile time when rewriting the SSA.
436e3b55780SDimitry Andric unsigned PhiCount = 0;
437e3b55780SDimitry Andric Instruction *FirstNonPHI = nullptr;
438e3b55780SDimitry Andric for (Instruction &I : *BB) {
439e3b55780SDimitry Andric if (!isa<PHINode>(&I)) {
440e3b55780SDimitry Andric FirstNonPHI = &I;
441e3b55780SDimitry Andric break;
442e3b55780SDimitry Andric }
443e3b55780SDimitry Andric if (++PhiCount > PhiDuplicateThreshold)
444e3b55780SDimitry Andric return ~0U;
445e3b55780SDimitry Andric }
446e3b55780SDimitry Andric
44759850d08SRoman Divacky /// Ignore PHI nodes, these will be flattened when duplication happens.
448e3b55780SDimitry Andric BasicBlock::const_iterator I(FirstNonPHI);
44959850d08SRoman Divacky
450907da171SRoman Divacky // FIXME: THREADING will delete values that are just used to compute the
451907da171SRoman Divacky // branch, so they shouldn't count against the duplication cost.
452907da171SRoman Divacky
453dd58ef01SDimitry Andric unsigned Bonus = 0;
45471d5a254SDimitry Andric if (BB->getTerminator() == StopAt) {
455dd58ef01SDimitry Andric // Threading through a switch statement is particularly profitable. If this
45671d5a254SDimitry Andric // block ends in a switch, decrease its cost to make it more likely to
45771d5a254SDimitry Andric // happen.
45871d5a254SDimitry Andric if (isa<SwitchInst>(StopAt))
459dd58ef01SDimitry Andric Bonus = 6;
460dd58ef01SDimitry Andric
461dd58ef01SDimitry Andric // The same holds for indirect branches, but slightly more so.
46271d5a254SDimitry Andric if (isa<IndirectBrInst>(StopAt))
463dd58ef01SDimitry Andric Bonus = 8;
46471d5a254SDimitry Andric }
465dd58ef01SDimitry Andric
466dd58ef01SDimitry Andric // Bump the threshold up so the early exit from the loop doesn't skip the
467dd58ef01SDimitry Andric // terminator-based Size adjustment at the end.
468dd58ef01SDimitry Andric Threshold += Bonus;
469dd58ef01SDimitry Andric
47059850d08SRoman Divacky // Sum up the cost of each instruction until we get to the terminator. Don't
47159850d08SRoman Divacky // include the terminator because the copy won't include it.
47259850d08SRoman Divacky unsigned Size = 0;
47371d5a254SDimitry Andric for (; &*I != StopAt; ++I) {
4744a16efa3SDimitry Andric
4754a16efa3SDimitry Andric // Stop scanning the block if we've reached the threshold.
4764a16efa3SDimitry Andric if (Size > Threshold)
4774a16efa3SDimitry Andric return Size;
4784a16efa3SDimitry Andric
479dd58ef01SDimitry Andric // Bail out if this instruction gives back a token type, it is not possible
480dd58ef01SDimitry Andric // to duplicate it if it is used outside this BB.
481dd58ef01SDimitry Andric if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
482dd58ef01SDimitry Andric return ~0U;
483dd58ef01SDimitry Andric
484c0981da4SDimitry Andric // Blocks with NoDuplicate are modelled as having infinite cost, so they
485c0981da4SDimitry Andric // are never duplicated.
486c0981da4SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(I))
487c0981da4SDimitry Andric if (CI->cannotDuplicate() || CI->isConvergent())
488c0981da4SDimitry Andric return ~0U;
489c0981da4SDimitry Andric
490e3b55780SDimitry Andric if (TTI->getInstructionCost(&*I, TargetTransformInfo::TCK_SizeAndLatency) ==
491e3b55780SDimitry Andric TargetTransformInfo::TCC_Free)
492c0981da4SDimitry Andric continue;
493c0981da4SDimitry Andric
49459850d08SRoman Divacky // All other instructions count for at least one unit.
49559850d08SRoman Divacky ++Size;
49659850d08SRoman Divacky
49759850d08SRoman Divacky // Calls are more expensive. If they are non-intrinsic calls, we model them
49859850d08SRoman Divacky // as having cost of 4. If they are a non-vector intrinsic, we model them
49959850d08SRoman Divacky // as having cost of 2 total, and if they are a vector intrinsic, we model
50059850d08SRoman Divacky // them as having cost 1.
50159850d08SRoman Divacky if (const CallInst *CI = dyn_cast<CallInst>(I)) {
502c0981da4SDimitry Andric if (!isa<IntrinsicInst>(CI))
50359850d08SRoman Divacky Size += 3;
50467a71b31SRoman Divacky else if (!CI->getType()->isVectorTy())
50559850d08SRoman Divacky Size += 1;
50659850d08SRoman Divacky }
50759850d08SRoman Divacky }
50859850d08SRoman Divacky
509dd58ef01SDimitry Andric return Size > Bonus ? Size - Bonus : 0;
51059850d08SRoman Divacky }
51159850d08SRoman Divacky
512b60736ecSDimitry Andric /// findLoopHeaders - We do not want jump threading to turn proper loop
513009b1c42SEd Schouten /// structures into irreducible loops. Doing this breaks up the loop nesting
514009b1c42SEd Schouten /// hierarchy and pessimizes later transformations. To prevent this from
515009b1c42SEd Schouten /// happening, we first have to find the loop headers. Here we approximate this
516009b1c42SEd Schouten /// by finding targets of backedges in the CFG.
517009b1c42SEd Schouten ///
518009b1c42SEd Schouten /// Note that there definitely are cases when we want to allow threading of
519009b1c42SEd Schouten /// edges across a loop header. For example, threading a jump from outside the
520009b1c42SEd Schouten /// loop (the preheader) to an exit block of the loop is definitely profitable.
521009b1c42SEd Schouten /// It is also almost always profitable to thread backedges from within the loop
522009b1c42SEd Schouten /// to exit blocks, and is often profitable to thread backedges to other blocks
523009b1c42SEd Schouten /// within the loop (forming a nested loop). This simple analysis is not rich
524009b1c42SEd Schouten /// enough to track all of these properties and keep it up-to-date as the CFG
525009b1c42SEd Schouten /// mutates, so we don't allow any of these transformations.
findLoopHeaders(Function & F)526b60736ecSDimitry Andric void JumpThreadingPass::findLoopHeaders(Function &F) {
527009b1c42SEd Schouten SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
528009b1c42SEd Schouten FindFunctionBackedges(F, Edges);
529009b1c42SEd Schouten
530050e163aSDimitry Andric for (const auto &Edge : Edges)
531050e163aSDimitry Andric LoopHeaders.insert(Edge.second);
532009b1c42SEd Schouten }
533009b1c42SEd Schouten
534cf099d11SDimitry Andric /// getKnownConstant - Helper method to determine if we can thread over a
535cf099d11SDimitry Andric /// terminator with the given value as its condition, and if so what value to
536cf099d11SDimitry Andric /// use for that. What kind of value this is depends on whether we want an
537cf099d11SDimitry Andric /// integer or a block address, but an undef is always accepted.
538cf099d11SDimitry Andric /// Returns null if Val is null or not an appropriate constant.
getKnownConstant(Value * Val,ConstantPreference Preference)539cf099d11SDimitry Andric static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
540cf099d11SDimitry Andric if (!Val)
5415ca98fd9SDimitry Andric return nullptr;
542cf099d11SDimitry Andric
543cf099d11SDimitry Andric // Undef is "known" enough.
544cf099d11SDimitry Andric if (UndefValue *U = dyn_cast<UndefValue>(Val))
545cf099d11SDimitry Andric return U;
546cf099d11SDimitry Andric
547cf099d11SDimitry Andric if (Preference == WantBlockAddress)
548cf099d11SDimitry Andric return dyn_cast<BlockAddress>(Val->stripPointerCasts());
549cf099d11SDimitry Andric
550cf099d11SDimitry Andric return dyn_cast<ConstantInt>(Val);
551d39c594dSDimitry Andric }
552d39c594dSDimitry Andric
553b60736ecSDimitry Andric /// computeValueKnownInPredecessors - Given a basic block BB and a value V, see
554cf099d11SDimitry Andric /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
555cf099d11SDimitry Andric /// in any of our predecessors. If so, return the known list of value and pred
556cf099d11SDimitry Andric /// BB in the result vector.
557009b1c42SEd Schouten ///
558907da171SRoman Divacky /// This returns true if there were any known values.
computeValueKnownInPredecessorsImpl(Value * V,BasicBlock * BB,PredValueInfo & Result,ConstantPreference Preference,SmallPtrSet<Value *,4> & RecursionSet,Instruction * CxtI)559b60736ecSDimitry Andric bool JumpThreadingPass::computeValueKnownInPredecessorsImpl(
56001095a5dSDimitry Andric Value *V, BasicBlock *BB, PredValueInfo &Result,
561ac9a064cSDimitry Andric ConstantPreference Preference, SmallPtrSet<Value *, 4> &RecursionSet,
562d8e91e46SDimitry Andric Instruction *CxtI) {
563ac9a064cSDimitry Andric const DataLayout &DL = BB->getDataLayout();
564b1c73532SDimitry Andric
565d39c594dSDimitry Andric // This method walks up use-def chains recursively. Because of this, we could
566d39c594dSDimitry Andric // get into an infinite loop going around loops in the use-def chain. To
567d39c594dSDimitry Andric // prevent this, keep track of what (value, block) pairs we've already visited
568d39c594dSDimitry Andric // and terminate the search if we loop back to them
569cfca06d7SDimitry Andric if (!RecursionSet.insert(V).second)
570d39c594dSDimitry Andric return false;
571d39c594dSDimitry Andric
572cf099d11SDimitry Andric // If V is a constant, then it is known in all predecessors.
573cf099d11SDimitry Andric if (Constant *KC = getKnownConstant(V, Preference)) {
574050e163aSDimitry Andric for (BasicBlock *Pred : predecessors(BB))
575cfca06d7SDimitry Andric Result.emplace_back(KC, Pred);
576d39c594dSDimitry Andric
57701095a5dSDimitry Andric return !Result.empty();
578009b1c42SEd Schouten }
579009b1c42SEd Schouten
580907da171SRoman Divacky // If V is a non-instruction value, or an instruction in a different block,
581907da171SRoman Divacky // then it can't be derived from a PHI.
582907da171SRoman Divacky Instruction *I = dyn_cast<Instruction>(V);
5835ca98fd9SDimitry Andric if (!I || I->getParent() != BB) {
584907da171SRoman Divacky
585e3b55780SDimitry Andric // Okay, if this is a live-in value, see if it has a known value at the any
586e3b55780SDimitry Andric // edge from our predecessors.
587050e163aSDimitry Andric for (BasicBlock *P : predecessors(BB)) {
588e3b55780SDimitry Andric using namespace PatternMatch;
589907da171SRoman Divacky // If the value is known by LazyValueInfo to be a constant in a
590907da171SRoman Divacky // predecessor, use that information to try to thread this block.
59167c32a98SDimitry Andric Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
592e3b55780SDimitry Andric // If I is a non-local compare-with-constant instruction, use more-rich
593e3b55780SDimitry Andric // 'getPredicateOnEdge' method. This would be able to handle value
594e3b55780SDimitry Andric // inequalities better, for example if the compare is "X < 4" and "X < 3"
595e3b55780SDimitry Andric // is known true but "X < 4" itself is not available.
596e3b55780SDimitry Andric CmpInst::Predicate Pred;
597e3b55780SDimitry Andric Value *Val;
598e3b55780SDimitry Andric Constant *Cst;
599ac9a064cSDimitry Andric if (!PredCst && match(V, m_Cmp(Pred, m_Value(Val), m_Constant(Cst))))
600ac9a064cSDimitry Andric PredCst = LVI->getPredicateOnEdge(Pred, Val, Cst, P, BB, CxtI);
601cf099d11SDimitry Andric if (Constant *KC = getKnownConstant(PredCst, Preference))
602cfca06d7SDimitry Andric Result.emplace_back(KC, P);
603907da171SRoman Divacky }
604907da171SRoman Divacky
605907da171SRoman Divacky return !Result.empty();
606907da171SRoman Divacky }
607907da171SRoman Divacky
608907da171SRoman Divacky /// If I is a PHI node, then we know the incoming values for any constants.
609907da171SRoman Divacky if (PHINode *PN = dyn_cast<PHINode>(I)) {
610907da171SRoman Divacky for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
611907da171SRoman Divacky Value *InVal = PN->getIncomingValue(i);
612cf099d11SDimitry Andric if (Constant *KC = getKnownConstant(InVal, Preference)) {
613cfca06d7SDimitry Andric Result.emplace_back(KC, PN->getIncomingBlock(i));
614cf099d11SDimitry Andric } else {
615d39c594dSDimitry Andric Constant *CI = LVI->getConstantOnEdge(InVal,
61667c32a98SDimitry Andric PN->getIncomingBlock(i),
61767c32a98SDimitry Andric BB, CxtI);
618cf099d11SDimitry Andric if (Constant *KC = getKnownConstant(CI, Preference))
619cfca06d7SDimitry Andric Result.emplace_back(KC, PN->getIncomingBlock(i));
620907da171SRoman Divacky }
621907da171SRoman Divacky }
622d39c594dSDimitry Andric
623907da171SRoman Divacky return !Result.empty();
624907da171SRoman Divacky }
625907da171SRoman Divacky
626b60736ecSDimitry Andric // Handle Cast instructions.
62701095a5dSDimitry Andric if (CastInst *CI = dyn_cast<CastInst>(I)) {
62801095a5dSDimitry Andric Value *Source = CI->getOperand(0);
629b1c73532SDimitry Andric PredValueInfoTy Vals;
630b1c73532SDimitry Andric computeValueKnownInPredecessorsImpl(Source, BB, Vals, Preference,
631d8e91e46SDimitry Andric RecursionSet, CxtI);
632b1c73532SDimitry Andric if (Vals.empty())
63301095a5dSDimitry Andric return false;
63401095a5dSDimitry Andric
63501095a5dSDimitry Andric // Convert the known values.
636b1c73532SDimitry Andric for (auto &Val : Vals)
637b1c73532SDimitry Andric if (Constant *Folded = ConstantFoldCastOperand(CI->getOpcode(), Val.first,
638b1c73532SDimitry Andric CI->getType(), DL))
639b1c73532SDimitry Andric Result.emplace_back(Folded, Val.second);
64001095a5dSDimitry Andric
641b1c73532SDimitry Andric return !Result.empty();
64201095a5dSDimitry Andric }
64301095a5dSDimitry Andric
644b60736ecSDimitry Andric if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
645b60736ecSDimitry Andric Value *Source = FI->getOperand(0);
646b60736ecSDimitry Andric computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
647b60736ecSDimitry Andric RecursionSet, CxtI);
648b60736ecSDimitry Andric
649b60736ecSDimitry Andric erase_if(Result, [](auto &Pair) {
650b60736ecSDimitry Andric return !isGuaranteedNotToBeUndefOrPoison(Pair.first);
651b60736ecSDimitry Andric });
652b60736ecSDimitry Andric
653b60736ecSDimitry Andric return !Result.empty();
654b60736ecSDimitry Andric }
655b60736ecSDimitry Andric
656907da171SRoman Divacky // Handle some boolean conditions.
657907da171SRoman Divacky if (I->getType()->getPrimitiveSizeInBits() == 1) {
658344a3780SDimitry Andric using namespace PatternMatch;
6596f8fc217SDimitry Andric if (Preference != WantInteger)
6606f8fc217SDimitry Andric return false;
661907da171SRoman Divacky // X | true -> true
662907da171SRoman Divacky // X & false -> false
663344a3780SDimitry Andric Value *Op0, *Op1;
664344a3780SDimitry Andric if (match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
665344a3780SDimitry Andric match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
666044eb2f6SDimitry Andric PredValueInfoTy LHSVals, RHSVals;
667044eb2f6SDimitry Andric
668344a3780SDimitry Andric computeValueKnownInPredecessorsImpl(Op0, BB, LHSVals, WantInteger,
669344a3780SDimitry Andric RecursionSet, CxtI);
670344a3780SDimitry Andric computeValueKnownInPredecessorsImpl(Op1, BB, RHSVals, WantInteger,
671344a3780SDimitry Andric RecursionSet, CxtI);
672907da171SRoman Divacky
673907da171SRoman Divacky if (LHSVals.empty() && RHSVals.empty())
674907da171SRoman Divacky return false;
675907da171SRoman Divacky
676907da171SRoman Divacky ConstantInt *InterestingVal;
677344a3780SDimitry Andric if (match(I, m_LogicalOr()))
678907da171SRoman Divacky InterestingVal = ConstantInt::getTrue(I->getContext());
679907da171SRoman Divacky else
680907da171SRoman Divacky InterestingVal = ConstantInt::getFalse(I->getContext());
681907da171SRoman Divacky
682d39c594dSDimitry Andric SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
683d39c594dSDimitry Andric
6846fe5c7aaSRoman Divacky // Scan for the sentinel. If we find an undef, force it to the
6856fe5c7aaSRoman Divacky // interesting value: x|undef -> true and x&undef -> false.
686050e163aSDimitry Andric for (const auto &LHSVal : LHSVals)
687050e163aSDimitry Andric if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
688050e163aSDimitry Andric Result.emplace_back(InterestingVal, LHSVal.second);
689050e163aSDimitry Andric LHSKnownBBs.insert(LHSVal.second);
6906fe5c7aaSRoman Divacky }
691050e163aSDimitry Andric for (const auto &RHSVal : RHSVals)
692050e163aSDimitry Andric if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
69366e41e3cSRoman Divacky // If we already inferred a value for this block on the LHS, don't
69466e41e3cSRoman Divacky // re-add it.
695050e163aSDimitry Andric if (!LHSKnownBBs.count(RHSVal.second))
696050e163aSDimitry Andric Result.emplace_back(InterestingVal, RHSVal.second);
69766e41e3cSRoman Divacky }
698d39c594dSDimitry Andric
699907da171SRoman Divacky return !Result.empty();
700907da171SRoman Divacky }
701907da171SRoman Divacky
702907da171SRoman Divacky // Handle the NOT form of XOR.
703907da171SRoman Divacky if (I->getOpcode() == Instruction::Xor &&
704907da171SRoman Divacky isa<ConstantInt>(I->getOperand(1)) &&
705907da171SRoman Divacky cast<ConstantInt>(I->getOperand(1))->isOne()) {
706b60736ecSDimitry Andric computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result,
707d8e91e46SDimitry Andric WantInteger, RecursionSet, CxtI);
708907da171SRoman Divacky if (Result.empty())
709907da171SRoman Divacky return false;
710907da171SRoman Divacky
711907da171SRoman Divacky // Invert the known values.
712050e163aSDimitry Andric for (auto &R : Result)
713050e163aSDimitry Andric R.first = ConstantExpr::getNot(R.first);
714d39c594dSDimitry Andric
715907da171SRoman Divacky return true;
716907da171SRoman Divacky }
717d39c594dSDimitry Andric
718d39c594dSDimitry Andric // Try to simplify some other binary operator values.
719d39c594dSDimitry Andric } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
7206f8fc217SDimitry Andric if (Preference != WantInteger)
7216f8fc217SDimitry Andric return false;
722d39c594dSDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
723cf099d11SDimitry Andric PredValueInfoTy LHSVals;
724b60736ecSDimitry Andric computeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
725d8e91e46SDimitry Andric WantInteger, RecursionSet, CxtI);
726d39c594dSDimitry Andric
727d39c594dSDimitry Andric // Try to use constant folding to simplify the binary operator.
728050e163aSDimitry Andric for (const auto &LHSVal : LHSVals) {
729050e163aSDimitry Andric Constant *V = LHSVal.first;
730145449b1SDimitry Andric Constant *Folded =
731145449b1SDimitry Andric ConstantFoldBinaryOpOperands(BO->getOpcode(), V, CI, DL);
732d39c594dSDimitry Andric
733cf099d11SDimitry Andric if (Constant *KC = getKnownConstant(Folded, WantInteger))
734cfca06d7SDimitry Andric Result.emplace_back(KC, LHSVal.second);
735d39c594dSDimitry Andric }
736d39c594dSDimitry Andric }
737d39c594dSDimitry Andric
738d39c594dSDimitry Andric return !Result.empty();
739907da171SRoman Divacky }
740907da171SRoman Divacky
741907da171SRoman Divacky // Handle compare with phi operand, where the PHI is defined in this block.
742907da171SRoman Divacky if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
7436f8fc217SDimitry Andric if (Preference != WantInteger)
7446f8fc217SDimitry Andric return false;
74508bbd35aSDimitry Andric Type *CmpType = Cmp->getType();
74608bbd35aSDimitry Andric Value *CmpLHS = Cmp->getOperand(0);
74708bbd35aSDimitry Andric Value *CmpRHS = Cmp->getOperand(1);
74808bbd35aSDimitry Andric CmpInst::Predicate Pred = Cmp->getPredicate();
74908bbd35aSDimitry Andric
75008bbd35aSDimitry Andric PHINode *PN = dyn_cast<PHINode>(CmpLHS);
751eb11fae6SDimitry Andric if (!PN)
752eb11fae6SDimitry Andric PN = dyn_cast<PHINode>(CmpRHS);
753b1c73532SDimitry Andric // Do not perform phi translation across a loop header phi, because this
754b1c73532SDimitry Andric // may result in comparison of values from two different loop iterations.
755b1c73532SDimitry Andric // FIXME: This check is broken if LoopHeaders is not populated.
756b1c73532SDimitry Andric if (PN && PN->getParent() == BB && !LoopHeaders.contains(BB)) {
757ac9a064cSDimitry Andric const DataLayout &DL = PN->getDataLayout();
758907da171SRoman Divacky // We can do this simplification if any comparisons fold to true or false.
759907da171SRoman Divacky // See if any do.
760907da171SRoman Divacky for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
761907da171SRoman Divacky BasicBlock *PredBB = PN->getIncomingBlock(i);
762eb11fae6SDimitry Andric Value *LHS, *RHS;
763eb11fae6SDimitry Andric if (PN == CmpLHS) {
764eb11fae6SDimitry Andric LHS = PN->getIncomingValue(i);
765eb11fae6SDimitry Andric RHS = CmpRHS->DoPHITranslation(BB, PredBB);
766eb11fae6SDimitry Andric } else {
767eb11fae6SDimitry Andric LHS = CmpLHS->DoPHITranslation(BB, PredBB);
768eb11fae6SDimitry Andric RHS = PN->getIncomingValue(i);
769eb11fae6SDimitry Andric }
770145449b1SDimitry Andric Value *Res = simplifyCmpInst(Pred, LHS, RHS, {DL});
7715ca98fd9SDimitry Andric if (!Res) {
772cf099d11SDimitry Andric if (!isa<Constant>(RHS))
773907da171SRoman Divacky continue;
774907da171SRoman Divacky
775eb11fae6SDimitry Andric // getPredicateOnEdge call will make no sense if LHS is defined in BB.
776eb11fae6SDimitry Andric auto LHSInst = dyn_cast<Instruction>(LHS);
777eb11fae6SDimitry Andric if (LHSInst && LHSInst->getParent() == BB)
778eb11fae6SDimitry Andric continue;
779eb11fae6SDimitry Andric
780ac9a064cSDimitry Andric Res = LVI->getPredicateOnEdge(Pred, LHS, cast<Constant>(RHS), PredBB,
781ac9a064cSDimitry Andric BB, CxtI ? CxtI : Cmp);
782907da171SRoman Divacky }
783907da171SRoman Divacky
784cf099d11SDimitry Andric if (Constant *KC = getKnownConstant(Res, WantInteger))
785cfca06d7SDimitry Andric Result.emplace_back(KC, PredBB);
786907da171SRoman Divacky }
787907da171SRoman Divacky
788907da171SRoman Divacky return !Result.empty();
789907da171SRoman Divacky }
790907da171SRoman Divacky
791907da171SRoman Divacky // If comparing a live-in value against a constant, see if we know the
792907da171SRoman Divacky // live-in value on any predecessors.
79308bbd35aSDimitry Andric if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) {
79408bbd35aSDimitry Andric Constant *CmpConst = cast<Constant>(CmpRHS);
795c46e6a59SDimitry Andric
79608bbd35aSDimitry Andric if (!isa<Instruction>(CmpLHS) ||
79708bbd35aSDimitry Andric cast<Instruction>(CmpLHS)->getParent() != BB) {
798050e163aSDimitry Andric for (BasicBlock *P : predecessors(BB)) {
799907da171SRoman Divacky // If the value is known by LazyValueInfo to be a constant in a
800907da171SRoman Divacky // predecessor, use that information to try to thread this block.
801ac9a064cSDimitry Andric Constant *Res = LVI->getPredicateOnEdge(Pred, CmpLHS, CmpConst, P, BB,
802ac9a064cSDimitry Andric CxtI ? CxtI : Cmp);
803ac9a064cSDimitry Andric if (Constant *KC = getKnownConstant(Res, WantInteger))
804ac9a064cSDimitry Andric Result.emplace_back(KC, P);
805907da171SRoman Divacky }
806907da171SRoman Divacky
807907da171SRoman Divacky return !Result.empty();
808907da171SRoman Divacky }
809d39c594dSDimitry Andric
81008bbd35aSDimitry Andric // InstCombine can fold some forms of constant range checks into
81108bbd35aSDimitry Andric // (icmp (add (x, C1)), C2). See if we have we have such a thing with
81208bbd35aSDimitry Andric // x as a live-in.
81308bbd35aSDimitry Andric {
81408bbd35aSDimitry Andric using namespace PatternMatch;
815044eb2f6SDimitry Andric
81608bbd35aSDimitry Andric Value *AddLHS;
81708bbd35aSDimitry Andric ConstantInt *AddConst;
81808bbd35aSDimitry Andric if (isa<ConstantInt>(CmpConst) &&
81908bbd35aSDimitry Andric match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) {
82008bbd35aSDimitry Andric if (!isa<Instruction>(AddLHS) ||
82108bbd35aSDimitry Andric cast<Instruction>(AddLHS)->getParent() != BB) {
82208bbd35aSDimitry Andric for (BasicBlock *P : predecessors(BB)) {
82308bbd35aSDimitry Andric // If the value is known by LazyValueInfo to be a ConstantRange in
82408bbd35aSDimitry Andric // a predecessor, use that information to try to thread this
82508bbd35aSDimitry Andric // block.
82608bbd35aSDimitry Andric ConstantRange CR = LVI->getConstantRangeOnEdge(
82708bbd35aSDimitry Andric AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
82808bbd35aSDimitry Andric // Propagate the range through the addition.
82908bbd35aSDimitry Andric CR = CR.add(AddConst->getValue());
83008bbd35aSDimitry Andric
83108bbd35aSDimitry Andric // Get the range where the compare returns true.
83208bbd35aSDimitry Andric ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(
83308bbd35aSDimitry Andric Pred, cast<ConstantInt>(CmpConst)->getValue());
83408bbd35aSDimitry Andric
83508bbd35aSDimitry Andric Constant *ResC;
83608bbd35aSDimitry Andric if (CmpRange.contains(CR))
83708bbd35aSDimitry Andric ResC = ConstantInt::getTrue(CmpType);
83808bbd35aSDimitry Andric else if (CmpRange.inverse().contains(CR))
83908bbd35aSDimitry Andric ResC = ConstantInt::getFalse(CmpType);
84008bbd35aSDimitry Andric else
84108bbd35aSDimitry Andric continue;
84208bbd35aSDimitry Andric
843cfca06d7SDimitry Andric Result.emplace_back(ResC, P);
84408bbd35aSDimitry Andric }
84508bbd35aSDimitry Andric
84608bbd35aSDimitry Andric return !Result.empty();
84708bbd35aSDimitry Andric }
84808bbd35aSDimitry Andric }
84908bbd35aSDimitry Andric }
85008bbd35aSDimitry Andric
851d39c594dSDimitry Andric // Try to find a constant value for the LHS of a comparison,
852d39c594dSDimitry Andric // and evaluate it statically if we can.
853cf099d11SDimitry Andric PredValueInfoTy LHSVals;
854b60736ecSDimitry Andric computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals,
855d8e91e46SDimitry Andric WantInteger, RecursionSet, CxtI);
856d39c594dSDimitry Andric
857050e163aSDimitry Andric for (const auto &LHSVal : LHSVals) {
858050e163aSDimitry Andric Constant *V = LHSVal.first;
859ac9a064cSDimitry Andric Constant *Folded =
860ac9a064cSDimitry Andric ConstantFoldCompareInstOperands(Pred, V, CmpConst, DL);
861cf099d11SDimitry Andric if (Constant *KC = getKnownConstant(Folded, WantInteger))
862cfca06d7SDimitry Andric Result.emplace_back(KC, LHSVal.second);
863907da171SRoman Divacky }
864d39c594dSDimitry Andric
865d39c594dSDimitry Andric return !Result.empty();
866d39c594dSDimitry Andric }
867d39c594dSDimitry Andric }
868d39c594dSDimitry Andric
869cf099d11SDimitry Andric if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
870cf099d11SDimitry Andric // Handle select instructions where at least one operand is a known constant
871cf099d11SDimitry Andric // and we can figure out the condition value for any predecessor block.
872cf099d11SDimitry Andric Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
873cf099d11SDimitry Andric Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
874cf099d11SDimitry Andric PredValueInfoTy Conds;
875cf099d11SDimitry Andric if ((TrueVal || FalseVal) &&
876b60736ecSDimitry Andric computeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds,
877d8e91e46SDimitry Andric WantInteger, RecursionSet, CxtI)) {
878050e163aSDimitry Andric for (auto &C : Conds) {
879050e163aSDimitry Andric Constant *Cond = C.first;
880cf099d11SDimitry Andric
881cf099d11SDimitry Andric // Figure out what value to use for the condition.
882cf099d11SDimitry Andric bool KnownCond;
883cf099d11SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
884cf099d11SDimitry Andric // A known boolean.
885cf099d11SDimitry Andric KnownCond = CI->isOne();
886cf099d11SDimitry Andric } else {
887cf099d11SDimitry Andric assert(isa<UndefValue>(Cond) && "Unexpected condition value");
888cf099d11SDimitry Andric // Either operand will do, so be sure to pick the one that's a known
889cf099d11SDimitry Andric // constant.
890cf099d11SDimitry Andric // FIXME: Do this more cleverly if both values are known constants?
8915ca98fd9SDimitry Andric KnownCond = (TrueVal != nullptr);
892cf099d11SDimitry Andric }
893cf099d11SDimitry Andric
894cf099d11SDimitry Andric // See if the select has a known constant value for this predecessor.
895cf099d11SDimitry Andric if (Constant *Val = KnownCond ? TrueVal : FalseVal)
896cfca06d7SDimitry Andric Result.emplace_back(Val, C.second);
897cf099d11SDimitry Andric }
898cf099d11SDimitry Andric
899cf099d11SDimitry Andric return !Result.empty();
900cf099d11SDimitry Andric }
901cf099d11SDimitry Andric }
902cf099d11SDimitry Andric
903d39c594dSDimitry Andric // If all else fails, see if LVI can figure out a constant value for us.
904b60736ecSDimitry Andric assert(CxtI->getParent() == BB && "CxtI should be in BB");
905b60736ecSDimitry Andric Constant *CI = LVI->getConstant(V, CxtI);
906cf099d11SDimitry Andric if (Constant *KC = getKnownConstant(CI, Preference)) {
907050e163aSDimitry Andric for (BasicBlock *Pred : predecessors(BB))
908cfca06d7SDimitry Andric Result.emplace_back(KC, Pred);
909d39c594dSDimitry Andric }
910d39c594dSDimitry Andric
911d39c594dSDimitry Andric return !Result.empty();
912d39c594dSDimitry Andric }
913d39c594dSDimitry Andric
91459850d08SRoman Divacky /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
91559850d08SRoman Divacky /// in an undefined jump, decide which block is best to revector to.
91659850d08SRoman Divacky ///
91759850d08SRoman Divacky /// Since we can pick an arbitrary destination, we pick the successor with the
91859850d08SRoman Divacky /// fewest predecessors. This should reduce the in-degree of the others.
getBestDestForJumpOnUndef(BasicBlock * BB)919b60736ecSDimitry Andric static unsigned getBestDestForJumpOnUndef(BasicBlock *BB) {
920d8e91e46SDimitry Andric Instruction *BBTerm = BB->getTerminator();
92159850d08SRoman Divacky unsigned MinSucc = 0;
92259850d08SRoman Divacky BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
92359850d08SRoman Divacky // Compute the successor with the minimum number of predecessors.
924eb11fae6SDimitry Andric unsigned MinNumPreds = pred_size(TestBB);
92559850d08SRoman Divacky for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
92659850d08SRoman Divacky TestBB = BBTerm->getSuccessor(i);
927eb11fae6SDimitry Andric unsigned NumPreds = pred_size(TestBB);
928411bd29eSDimitry Andric if (NumPreds < MinNumPreds) {
92959850d08SRoman Divacky MinSucc = i;
930411bd29eSDimitry Andric MinNumPreds = NumPreds;
931411bd29eSDimitry Andric }
932009b1c42SEd Schouten }
933009b1c42SEd Schouten
93459850d08SRoman Divacky return MinSucc;
935009b1c42SEd Schouten }
936009b1c42SEd Schouten
hasAddressTakenAndUsed(BasicBlock * BB)937cf099d11SDimitry Andric static bool hasAddressTakenAndUsed(BasicBlock *BB) {
938cf099d11SDimitry Andric if (!BB->hasAddressTaken()) return false;
939cf099d11SDimitry Andric
940cf099d11SDimitry Andric // If the block has its address taken, it may be a tree of dead constants
941cf099d11SDimitry Andric // hanging off of it. These shouldn't keep the block alive.
942cf099d11SDimitry Andric BlockAddress *BA = BlockAddress::get(BB);
943cf099d11SDimitry Andric BA->removeDeadConstantUsers();
944cf099d11SDimitry Andric return !BA->use_empty();
945cf099d11SDimitry Andric }
946cf099d11SDimitry Andric
947b60736ecSDimitry Andric /// processBlock - If there are any predecessors whose control can be threaded
948009b1c42SEd Schouten /// through to a successor, transform them now.
processBlock(BasicBlock * BB)949b60736ecSDimitry Andric bool JumpThreadingPass::processBlock(BasicBlock *BB) {
9506fe5c7aaSRoman Divacky // If the block is trivially dead, just return and let the caller nuke it.
9516fe5c7aaSRoman Divacky // This simplifies other transformations.
952d8e91e46SDimitry Andric if (DTU->isBBPendingDeletion(BB) ||
953eb11fae6SDimitry Andric (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()))
9546fe5c7aaSRoman Divacky return false;
9556fe5c7aaSRoman Divacky
956009b1c42SEd Schouten // If this block has a single predecessor, and if that pred has a single
957009b1c42SEd Schouten // successor, merge the blocks. This encourages recursive jump threading
958009b1c42SEd Schouten // because now the condition in this block can be threaded through
959009b1c42SEd Schouten // predecessors of our predecessor block.
960b60736ecSDimitry Andric if (maybeMergeBasicBlockIntoOnlyPred(BB))
961009b1c42SEd Schouten return true;
962009b1c42SEd Schouten
963b60736ecSDimitry Andric if (tryToUnfoldSelectInCurrBB(BB))
964050e163aSDimitry Andric return true;
965050e163aSDimitry Andric
96671d5a254SDimitry Andric // Look if we can propagate guards to predecessors.
967b60736ecSDimitry Andric if (HasGuards && processGuards(BB))
96871d5a254SDimitry Andric return true;
96971d5a254SDimitry Andric
970cf099d11SDimitry Andric // What kind of constant we're looking for.
971cf099d11SDimitry Andric ConstantPreference Preference = WantInteger;
972cf099d11SDimitry Andric
973cf099d11SDimitry Andric // Look to see if the terminator is a conditional branch, switch or indirect
974cf099d11SDimitry Andric // branch, if not we can't thread it.
975009b1c42SEd Schouten Value *Condition;
976cf099d11SDimitry Andric Instruction *Terminator = BB->getTerminator();
977cf099d11SDimitry Andric if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
978009b1c42SEd Schouten // Can't thread an unconditional jump.
979009b1c42SEd Schouten if (BI->isUnconditional()) return false;
980009b1c42SEd Schouten Condition = BI->getCondition();
981cf099d11SDimitry Andric } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
982009b1c42SEd Schouten Condition = SI->getCondition();
983cf099d11SDimitry Andric } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
98458b69754SDimitry Andric // Can't thread indirect branch with no successors.
98558b69754SDimitry Andric if (IB->getNumSuccessors() == 0) return false;
986cf099d11SDimitry Andric Condition = IB->getAddress()->stripPointerCasts();
987cf099d11SDimitry Andric Preference = WantBlockAddress;
988cf099d11SDimitry Andric } else {
989e6d15924SDimitry Andric return false; // Must be an invoke or callbr.
990009b1c42SEd Schouten }
991009b1c42SEd Schouten
992b60736ecSDimitry Andric // Keep track if we constant folded the condition in this invocation.
993b60736ecSDimitry Andric bool ConstantFolded = false;
994b60736ecSDimitry Andric
9956b943ff3SDimitry Andric // Run constant folding to see if we can reduce the condition to a simple
9966b943ff3SDimitry Andric // constant.
9976b943ff3SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(Condition)) {
9985a5ac124SDimitry Andric Value *SimpleVal =
999ac9a064cSDimitry Andric ConstantFoldInstruction(I, BB->getDataLayout(), TLI);
10006b943ff3SDimitry Andric if (SimpleVal) {
10016b943ff3SDimitry Andric I->replaceAllUsesWith(SimpleVal);
1002a7fe922bSDimitry Andric if (isInstructionTriviallyDead(I, TLI))
10036b943ff3SDimitry Andric I->eraseFromParent();
10046b943ff3SDimitry Andric Condition = SimpleVal;
1005b60736ecSDimitry Andric ConstantFolded = true;
10066b943ff3SDimitry Andric }
10076b943ff3SDimitry Andric }
10086b943ff3SDimitry Andric
1009b60736ecSDimitry Andric // If the terminator is branching on an undef or freeze undef, we can pick any
1010b60736ecSDimitry Andric // of the successors to branch to. Let getBestDestForJumpOnUndef decide.
1011b60736ecSDimitry Andric auto *FI = dyn_cast<FreezeInst>(Condition);
1012b60736ecSDimitry Andric if (isa<UndefValue>(Condition) ||
1013b60736ecSDimitry Andric (FI && isa<UndefValue>(FI->getOperand(0)) && FI->hasOneUse())) {
1014b60736ecSDimitry Andric unsigned BestSucc = getBestDestForJumpOnUndef(BB);
1015eb11fae6SDimitry Andric std::vector<DominatorTree::UpdateType> Updates;
1016009b1c42SEd Schouten
1017009b1c42SEd Schouten // Fold the branch/switch.
1018d8e91e46SDimitry Andric Instruction *BBTerm = BB->getTerminator();
1019eb11fae6SDimitry Andric Updates.reserve(BBTerm->getNumSuccessors());
1020009b1c42SEd Schouten for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
102159850d08SRoman Divacky if (i == BestSucc) continue;
1022eb11fae6SDimitry Andric BasicBlock *Succ = BBTerm->getSuccessor(i);
1023eb11fae6SDimitry Andric Succ->removePredecessor(BB, true);
1024eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Delete, BB, Succ});
1025009b1c42SEd Schouten }
1026009b1c42SEd Schouten
1027eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
102859850d08SRoman Divacky << "' folding undef terminator: " << *BBTerm << '\n');
1029ac9a064cSDimitry Andric Instruction *NewBI = BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm->getIterator());
1030ac9a064cSDimitry Andric NewBI->setDebugLoc(BBTerm->getDebugLoc());
1031344a3780SDimitry Andric ++NumFolds;
1032009b1c42SEd Schouten BBTerm->eraseFromParent();
1033e6d15924SDimitry Andric DTU->applyUpdatesPermissive(Updates);
1034b60736ecSDimitry Andric if (FI)
1035b60736ecSDimitry Andric FI->eraseFromParent();
1036009b1c42SEd Schouten return true;
1037009b1c42SEd Schouten }
1038009b1c42SEd Schouten
1039cf099d11SDimitry Andric // If the terminator of this block is branching on a constant, simplify the
1040cf099d11SDimitry Andric // terminator to an unconditional branch. This can occur due to threading in
1041cf099d11SDimitry Andric // other blocks.
1042cf099d11SDimitry Andric if (getKnownConstant(Condition, Preference)) {
1043eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
1044eb11fae6SDimitry Andric << "' folding terminator: " << *BB->getTerminator()
1045eb11fae6SDimitry Andric << '\n');
1046cf099d11SDimitry Andric ++NumFolds;
10477fa27ce4SDimitry Andric ConstantFoldTerminator(BB, true, nullptr, DTU.get());
10487fa27ce4SDimitry Andric if (auto *BPI = getBPI())
1049b60736ecSDimitry Andric BPI->eraseBlock(BB);
1050cf099d11SDimitry Andric return true;
1051cf099d11SDimitry Andric }
1052009b1c42SEd Schouten
1053cf099d11SDimitry Andric Instruction *CondInst = dyn_cast<Instruction>(Condition);
1054009b1c42SEd Schouten
1055009b1c42SEd Schouten // All the rest of our checks depend on the condition being an instruction.
10565ca98fd9SDimitry Andric if (!CondInst) {
1057907da171SRoman Divacky // FIXME: Unify this with code below.
1058b60736ecSDimitry Andric if (processThreadableEdges(Condition, BB, Preference, Terminator))
1059907da171SRoman Divacky return true;
1060b60736ecSDimitry Andric return ConstantFolded;
1061907da171SRoman Divacky }
1062907da171SRoman Divacky
1063145449b1SDimitry Andric // Some of the following optimization can safely work on the unfrozen cond.
1064145449b1SDimitry Andric Value *CondWithoutFreeze = CondInst;
1065145449b1SDimitry Andric if (auto *FI = dyn_cast<FreezeInst>(CondInst))
1066145449b1SDimitry Andric CondWithoutFreeze = FI->getOperand(0);
1067145449b1SDimitry Andric
1068145449b1SDimitry Andric if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondWithoutFreeze)) {
10693a0822f0SDimitry Andric // If we're branching on a conditional, LVI might be able to determine
10703a0822f0SDimitry Andric // it's value at the branch instruction. We only handle comparisons
10713a0822f0SDimitry Andric // against a constant at this time.
1072145449b1SDimitry Andric if (Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1))) {
1073ac9a064cSDimitry Andric Constant *Res =
10743a0822f0SDimitry Andric LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
1075145449b1SDimitry Andric CondConst, BB->getTerminator(),
1076145449b1SDimitry Andric /*UseBlockValue=*/false);
1077ac9a064cSDimitry Andric if (Res) {
1078ab44ce3dSDimitry Andric // We can safely replace *some* uses of the CondInst if it has
1079b5630dbaSDimitry Andric // exactly one value as returned by LVI. RAUW is incorrect in the
1080b5630dbaSDimitry Andric // presence of guards and assumes, that have the `Cond` as the use. This
1081b5630dbaSDimitry Andric // is because we use the guards/assume to reason about the `Cond` value
1082b5630dbaSDimitry Andric // at the end of block, but RAUW unconditionally replaces all uses
1083b5630dbaSDimitry Andric // including the guards/assumes themselves and the uses before the
1084b5630dbaSDimitry Andric // guard/assume.
1085ac9a064cSDimitry Andric if (replaceFoldableUses(CondCmp, Res, BB))
1086d39c594dSDimitry Andric return true;
1087d39c594dSDimitry Andric }
1088f8af5cf6SDimitry Andric
108971d5a254SDimitry Andric // We did not manage to simplify this branch, try to see whether
109071d5a254SDimitry Andric // CondCmp depends on a known phi-select pattern.
1091b60736ecSDimitry Andric if (tryToUnfoldSelect(CondCmp, BB))
1092f8af5cf6SDimitry Andric return true;
109366e41e3cSRoman Divacky }
109471d5a254SDimitry Andric }
1095009b1c42SEd Schouten
1096d8e91e46SDimitry Andric if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
1097b60736ecSDimitry Andric if (tryToUnfoldSelect(SI, BB))
1098e6d15924SDimitry Andric return true;
1099d8e91e46SDimitry Andric
1100009b1c42SEd Schouten // Check for some cases that are worth simplifying. Right now we want to look
1101009b1c42SEd Schouten // for loads that are used by a switch or by the condition for the branch. If
1102009b1c42SEd Schouten // we see one, check to see if it's partially redundant. If so, insert a PHI
1103009b1c42SEd Schouten // which can then be used to thread the values.
1104145449b1SDimitry Andric Value *SimplifyValue = CondWithoutFreeze;
1105b60736ecSDimitry Andric
1106009b1c42SEd Schouten if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
1107009b1c42SEd Schouten if (isa<Constant>(CondCmp->getOperand(1)))
1108009b1c42SEd Schouten SimplifyValue = CondCmp->getOperand(0);
1109009b1c42SEd Schouten
1110907da171SRoman Divacky // TODO: There are other places where load PRE would be profitable, such as
1111907da171SRoman Divacky // more complex comparisons.
1112eb11fae6SDimitry Andric if (LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue))
1113b60736ecSDimitry Andric if (simplifyPartiallyRedundantLoad(LoadI))
1114009b1c42SEd Schouten return true;
1115009b1c42SEd Schouten
1116044eb2f6SDimitry Andric // Before threading, try to propagate profile data backwards:
1117044eb2f6SDimitry Andric if (PHINode *PN = dyn_cast<PHINode>(CondInst))
1118044eb2f6SDimitry Andric if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1119044eb2f6SDimitry Andric updatePredecessorProfileMetadata(PN, BB);
1120044eb2f6SDimitry Andric
1121907da171SRoman Divacky // Handle a variety of cases where we are branching on something derived from
1122907da171SRoman Divacky // a PHI node in the current block. If we can prove that any predecessors
1123907da171SRoman Divacky // compute a predictable value based on a PHI node, thread those predecessors.
1124b60736ecSDimitry Andric if (processThreadableEdges(CondInst, BB, Preference, Terminator))
1125907da171SRoman Divacky return true;
1126907da171SRoman Divacky
1127b60736ecSDimitry Andric // If this is an otherwise-unfoldable branch on a phi node or freeze(phi) in
1128b60736ecSDimitry Andric // the current block, see if we can simplify.
1129145449b1SDimitry Andric PHINode *PN = dyn_cast<PHINode>(CondWithoutFreeze);
1130b60736ecSDimitry Andric if (PN && PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1131b60736ecSDimitry Andric return processBranchOnPHI(PN);
1132829000e0SRoman Divacky
1133829000e0SRoman Divacky // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
1134829000e0SRoman Divacky if (CondInst->getOpcode() == Instruction::Xor &&
1135829000e0SRoman Divacky CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1136b60736ecSDimitry Andric return processBranchOnXOR(cast<BinaryOperator>(CondInst));
1137829000e0SRoman Divacky
1138dd58ef01SDimitry Andric // Search for a stronger dominating condition that can be used to simplify a
1139dd58ef01SDimitry Andric // conditional branch leaving BB.
1140b60736ecSDimitry Andric if (processImpliedCondition(BB))
1141dd58ef01SDimitry Andric return true;
1142907da171SRoman Divacky
1143dd58ef01SDimitry Andric return false;
1144dd58ef01SDimitry Andric }
1145dd58ef01SDimitry Andric
processImpliedCondition(BasicBlock * BB)1146b60736ecSDimitry Andric bool JumpThreadingPass::processImpliedCondition(BasicBlock *BB) {
1147dd58ef01SDimitry Andric auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
1148dd58ef01SDimitry Andric if (!BI || !BI->isConditional())
1149dd58ef01SDimitry Andric return false;
1150dd58ef01SDimitry Andric
1151dd58ef01SDimitry Andric Value *Cond = BI->getCondition();
1152145449b1SDimitry Andric // Assuming that predecessor's branch was taken, if pred's branch condition
1153145449b1SDimitry Andric // (V) implies Cond, Cond can be either true, undef, or poison. In this case,
1154145449b1SDimitry Andric // freeze(Cond) is either true or a nondeterministic value.
1155145449b1SDimitry Andric // If freeze(Cond) has only one use, we can freely fold freeze(Cond) to true
1156145449b1SDimitry Andric // without affecting other instructions.
1157145449b1SDimitry Andric auto *FICond = dyn_cast<FreezeInst>(Cond);
1158145449b1SDimitry Andric if (FICond && FICond->hasOneUse())
1159145449b1SDimitry Andric Cond = FICond->getOperand(0);
1160145449b1SDimitry Andric else
1161145449b1SDimitry Andric FICond = nullptr;
1162145449b1SDimitry Andric
1163dd58ef01SDimitry Andric BasicBlock *CurrentBB = BB;
1164dd58ef01SDimitry Andric BasicBlock *CurrentPred = BB->getSinglePredecessor();
1165dd58ef01SDimitry Andric unsigned Iter = 0;
1166dd58ef01SDimitry Andric
1167ac9a064cSDimitry Andric auto &DL = BB->getDataLayout();
1168dd58ef01SDimitry Andric
1169dd58ef01SDimitry Andric while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
1170dd58ef01SDimitry Andric auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
117101095a5dSDimitry Andric if (!PBI || !PBI->isConditional())
117201095a5dSDimitry Andric return false;
117301095a5dSDimitry Andric if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1174dd58ef01SDimitry Andric return false;
1175dd58ef01SDimitry Andric
1176044eb2f6SDimitry Andric bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB;
1177e3b55780SDimitry Andric std::optional<bool> Implication =
1178044eb2f6SDimitry Andric isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue);
1179145449b1SDimitry Andric
1180145449b1SDimitry Andric // If the branch condition of BB (which is Cond) and CurrentPred are
1181145449b1SDimitry Andric // exactly the same freeze instruction, Cond can be folded into CondIsTrue.
1182145449b1SDimitry Andric if (!Implication && FICond && isa<FreezeInst>(PBI->getCondition())) {
1183145449b1SDimitry Andric if (cast<FreezeInst>(PBI->getCondition())->getOperand(0) ==
1184145449b1SDimitry Andric FICond->getOperand(0))
1185145449b1SDimitry Andric Implication = CondIsTrue;
1186145449b1SDimitry Andric }
1187145449b1SDimitry Andric
118801095a5dSDimitry Andric if (Implication) {
1189eb11fae6SDimitry Andric BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
1190eb11fae6SDimitry Andric BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
1191eb11fae6SDimitry Andric RemoveSucc->removePredecessor(BB);
1192ac9a064cSDimitry Andric BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI->getIterator());
1193e6d15924SDimitry Andric UncondBI->setDebugLoc(BI->getDebugLoc());
1194344a3780SDimitry Andric ++NumFolds;
1195dd58ef01SDimitry Andric BI->eraseFromParent();
1196145449b1SDimitry Andric if (FICond)
1197145449b1SDimitry Andric FICond->eraseFromParent();
1198145449b1SDimitry Andric
1199e6d15924SDimitry Andric DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}});
12007fa27ce4SDimitry Andric if (auto *BPI = getBPI())
1201b60736ecSDimitry Andric BPI->eraseBlock(BB);
1202dd58ef01SDimitry Andric return true;
1203dd58ef01SDimitry Andric }
1204dd58ef01SDimitry Andric CurrentBB = CurrentPred;
1205dd58ef01SDimitry Andric CurrentPred = CurrentBB->getSinglePredecessor();
1206dd58ef01SDimitry Andric }
1207009b1c42SEd Schouten
1208009b1c42SEd Schouten return false;
1209009b1c42SEd Schouten }
1210009b1c42SEd Schouten
121171d5a254SDimitry Andric /// Return true if Op is an instruction defined in the given block.
isOpDefinedInBlock(Value * Op,BasicBlock * BB)121271d5a254SDimitry Andric static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
121371d5a254SDimitry Andric if (Instruction *OpInst = dyn_cast<Instruction>(Op))
121471d5a254SDimitry Andric if (OpInst->getParent() == BB)
121571d5a254SDimitry Andric return true;
121671d5a254SDimitry Andric return false;
121771d5a254SDimitry Andric }
121871d5a254SDimitry Andric
1219b60736ecSDimitry Andric /// simplifyPartiallyRedundantLoad - If LoadI is an obviously partially
1220eb11fae6SDimitry Andric /// redundant load instruction, eliminate it by replacing it with a PHI node.
1221eb11fae6SDimitry Andric /// This is an important optimization that encourages jump threading, and needs
1222eb11fae6SDimitry Andric /// to be run interlaced with other jump threading tasks.
simplifyPartiallyRedundantLoad(LoadInst * LoadI)1223b60736ecSDimitry Andric bool JumpThreadingPass::simplifyPartiallyRedundantLoad(LoadInst *LoadI) {
122401095a5dSDimitry Andric // Don't hack volatile and ordered loads.
1225eb11fae6SDimitry Andric if (!LoadI->isUnordered()) return false;
1226009b1c42SEd Schouten
1227009b1c42SEd Schouten // If the load is defined in a block with exactly one predecessor, it can't be
1228009b1c42SEd Schouten // partially redundant.
1229eb11fae6SDimitry Andric BasicBlock *LoadBB = LoadI->getParent();
1230009b1c42SEd Schouten if (LoadBB->getSinglePredecessor())
1231009b1c42SEd Schouten return false;
1232009b1c42SEd Schouten
1233dd58ef01SDimitry Andric // If the load is defined in an EH pad, it can't be partially redundant,
1234dd58ef01SDimitry Andric // because the edges between the invoke and the EH pad cannot have other
1235f8af5cf6SDimitry Andric // instructions between them.
1236dd58ef01SDimitry Andric if (LoadBB->isEHPad())
1237f8af5cf6SDimitry Andric return false;
1238f8af5cf6SDimitry Andric
1239eb11fae6SDimitry Andric Value *LoadedPtr = LoadI->getOperand(0);
1240009b1c42SEd Schouten
124171d5a254SDimitry Andric // If the loaded operand is defined in the LoadBB and its not a phi,
124271d5a254SDimitry Andric // it can't be available in predecessors.
124371d5a254SDimitry Andric if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr))
1244009b1c42SEd Schouten return false;
1245009b1c42SEd Schouten
1246009b1c42SEd Schouten // Scan a few instructions up from the load, to see if it is obviously live at
1247009b1c42SEd Schouten // the entry to its block.
1248eb11fae6SDimitry Andric BasicBlock::iterator BBIt(LoadI);
1249b915e9e0SDimitry Andric bool IsLoadCSE;
1250ac9a064cSDimitry Andric BatchAAResults BatchAA(*AA);
1251ac9a064cSDimitry Andric // The dominator tree is updated lazily and may not be valid at this point.
1252ac9a064cSDimitry Andric BatchAA.disableDominatorTree();
125371d5a254SDimitry Andric if (Value *AvailableVal = FindAvailableLoadedValue(
1254ac9a064cSDimitry Andric LoadI, LoadBB, BBIt, DefMaxInstsToScan, &BatchAA, &IsLoadCSE)) {
1255dd58ef01SDimitry Andric // If the value of the load is locally available within the block, just use
1256009b1c42SEd Schouten // it. This frequently occurs for reg2mem'd allocas.
1257009b1c42SEd Schouten
1258b915e9e0SDimitry Andric if (IsLoadCSE) {
1259eb11fae6SDimitry Andric LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
1260d8e91e46SDimitry Andric combineMetadataForCSE(NLoadI, LoadI, false);
1261b1c73532SDimitry Andric LVI->forgetValue(NLoadI);
1262b915e9e0SDimitry Andric };
1263b915e9e0SDimitry Andric
1264145449b1SDimitry Andric // If the returned value is the load itself, replace with poison. This can
1265009b1c42SEd Schouten // only happen in dead loops.
1266eb11fae6SDimitry Andric if (AvailableVal == LoadI)
1267145449b1SDimitry Andric AvailableVal = PoisonValue::get(LoadI->getType());
1268ac9a064cSDimitry Andric if (AvailableVal->getType() != LoadI->getType()) {
1269eb11fae6SDimitry Andric AvailableVal = CastInst::CreateBitOrPointerCast(
1270ac9a064cSDimitry Andric AvailableVal, LoadI->getType(), "", LoadI->getIterator());
1271ac9a064cSDimitry Andric cast<Instruction>(AvailableVal)->setDebugLoc(LoadI->getDebugLoc());
1272ac9a064cSDimitry Andric }
1273eb11fae6SDimitry Andric LoadI->replaceAllUsesWith(AvailableVal);
1274eb11fae6SDimitry Andric LoadI->eraseFromParent();
1275009b1c42SEd Schouten return true;
1276009b1c42SEd Schouten }
1277009b1c42SEd Schouten
1278009b1c42SEd Schouten // Otherwise, if we scanned the whole block and got to the top of the block,
1279009b1c42SEd Schouten // we know the block is locally transparent to the load. If not, something
1280009b1c42SEd Schouten // might clobber its value.
1281009b1c42SEd Schouten if (BBIt != LoadBB->begin())
1282009b1c42SEd Schouten return false;
1283009b1c42SEd Schouten
128467c32a98SDimitry Andric // If all of the loads and stores that feed the value have the same AA tags,
128567c32a98SDimitry Andric // then we can propagate them onto any newly inserted loads.
1286c0981da4SDimitry Andric AAMDNodes AATags = LoadI->getAAMetadata();
1287009b1c42SEd Schouten
1288009b1c42SEd Schouten SmallPtrSet<BasicBlock*, 8> PredsScanned;
1289044eb2f6SDimitry Andric
1290044eb2f6SDimitry Andric using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>;
1291044eb2f6SDimitry Andric
1292009b1c42SEd Schouten AvailablePredsTy AvailablePreds;
12935ca98fd9SDimitry Andric BasicBlock *OneUnavailablePred = nullptr;
1294b915e9e0SDimitry Andric SmallVector<LoadInst*, 8> CSELoads;
1295009b1c42SEd Schouten
1296009b1c42SEd Schouten // If we got here, the loaded value is transparent through to the start of the
1297009b1c42SEd Schouten // block. Check to see if it is available in any of the predecessor blocks.
1298050e163aSDimitry Andric for (BasicBlock *PredBB : predecessors(LoadBB)) {
1299009b1c42SEd Schouten // If we already scanned this predecessor, skip it.
130067c32a98SDimitry Andric if (!PredsScanned.insert(PredBB).second)
1301009b1c42SEd Schouten continue;
1302009b1c42SEd Schouten
1303009b1c42SEd Schouten BBIt = PredBB->end();
130471d5a254SDimitry Andric unsigned NumScanedInst = 0;
130571d5a254SDimitry Andric Value *PredAvailable = nullptr;
130671d5a254SDimitry Andric // NOTE: We don't CSE load that is volatile or anything stronger than
130771d5a254SDimitry Andric // unordered, that should have been checked when we entered the function.
1308eb11fae6SDimitry Andric assert(LoadI->isUnordered() &&
1309eb11fae6SDimitry Andric "Attempting to CSE volatile or atomic loads");
131071d5a254SDimitry Andric // If this is a load on a phi pointer, phi-translate it and search
131171d5a254SDimitry Andric // for available load/store to the pointer in predecessors.
1312344a3780SDimitry Andric Type *AccessTy = LoadI->getType();
1313ac9a064cSDimitry Andric const auto &DL = LoadI->getDataLayout();
1314344a3780SDimitry Andric MemoryLocation Loc(LoadedPtr->DoPHITranslation(LoadBB, PredBB),
1315344a3780SDimitry Andric LocationSize::precise(DL.getTypeStoreSize(AccessTy)),
1316344a3780SDimitry Andric AATags);
1317ac9a064cSDimitry Andric PredAvailable = findAvailablePtrLoadStore(
1318ac9a064cSDimitry Andric Loc, AccessTy, LoadI->isAtomic(), PredBB, BBIt, DefMaxInstsToScan,
1319ac9a064cSDimitry Andric &BatchAA, &IsLoadCSE, &NumScanedInst);
132071d5a254SDimitry Andric
132171d5a254SDimitry Andric // If PredBB has a single predecessor, continue scanning through the
1322eb11fae6SDimitry Andric // single predecessor.
132371d5a254SDimitry Andric BasicBlock *SinglePredBB = PredBB;
132471d5a254SDimitry Andric while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
132571d5a254SDimitry Andric NumScanedInst < DefMaxInstsToScan) {
132671d5a254SDimitry Andric SinglePredBB = SinglePredBB->getSinglePredecessor();
132771d5a254SDimitry Andric if (SinglePredBB) {
132871d5a254SDimitry Andric BBIt = SinglePredBB->end();
1329344a3780SDimitry Andric PredAvailable = findAvailablePtrLoadStore(
1330344a3780SDimitry Andric Loc, AccessTy, LoadI->isAtomic(), SinglePredBB, BBIt,
1331ac9a064cSDimitry Andric (DefMaxInstsToScan - NumScanedInst), &BatchAA, &IsLoadCSE,
133271d5a254SDimitry Andric &NumScanedInst);
133371d5a254SDimitry Andric }
133471d5a254SDimitry Andric }
133571d5a254SDimitry Andric
1336009b1c42SEd Schouten if (!PredAvailable) {
1337009b1c42SEd Schouten OneUnavailablePred = PredBB;
1338009b1c42SEd Schouten continue;
1339009b1c42SEd Schouten }
1340009b1c42SEd Schouten
1341b915e9e0SDimitry Andric if (IsLoadCSE)
1342b915e9e0SDimitry Andric CSELoads.push_back(cast<LoadInst>(PredAvailable));
134363faed5bSDimitry Andric
1344009b1c42SEd Schouten // If so, this load is partially redundant. Remember this info so that we
1345009b1c42SEd Schouten // can create a PHI node.
1346cfca06d7SDimitry Andric AvailablePreds.emplace_back(PredBB, PredAvailable);
1347009b1c42SEd Schouten }
1348009b1c42SEd Schouten
1349009b1c42SEd Schouten // If the loaded value isn't available in any predecessor, it isn't partially
1350009b1c42SEd Schouten // redundant.
1351009b1c42SEd Schouten if (AvailablePreds.empty()) return false;
1352009b1c42SEd Schouten
1353009b1c42SEd Schouten // Okay, the loaded value is available in at least one (and maybe all!)
1354009b1c42SEd Schouten // predecessors. If the value is unavailable in more than one unique
1355009b1c42SEd Schouten // predecessor, we want to insert a merge block for those common predecessors.
1356009b1c42SEd Schouten // This ensures that we only have to insert one reload, thus not increasing
1357009b1c42SEd Schouten // code size.
13585ca98fd9SDimitry Andric BasicBlock *UnavailablePred = nullptr;
1359009b1c42SEd Schouten
1360c7dac04cSDimitry Andric // If the value is unavailable in one of predecessors, we will end up
1361c7dac04cSDimitry Andric // inserting a new instruction into them. It is only valid if all the
1362eb11fae6SDimitry Andric // instructions before LoadI are guaranteed to pass execution to its
1363eb11fae6SDimitry Andric // successor, or if LoadI is safe to speculate.
1364c7dac04cSDimitry Andric // TODO: If this logic becomes more complex, and we will perform PRE insertion
1365c7dac04cSDimitry Andric // farther than to a predecessor, we need to reuse the code from GVN's PRE.
1366c7dac04cSDimitry Andric // It requires domination tree analysis, so for this simple case it is an
1367c7dac04cSDimitry Andric // overkill.
1368c7dac04cSDimitry Andric if (PredsScanned.size() != AvailablePreds.size() &&
1369eb11fae6SDimitry Andric !isSafeToSpeculativelyExecute(LoadI))
1370eb11fae6SDimitry Andric for (auto I = LoadBB->begin(); &*I != LoadI; ++I)
1371c7dac04cSDimitry Andric if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
1372c7dac04cSDimitry Andric return false;
1373c7dac04cSDimitry Andric
1374009b1c42SEd Schouten // If there is exactly one predecessor where the value is unavailable, the
1375009b1c42SEd Schouten // already computed 'OneUnavailablePred' block is it. If it ends in an
1376009b1c42SEd Schouten // unconditional branch, we know that it isn't a critical edge.
1377009b1c42SEd Schouten if (PredsScanned.size() == AvailablePreds.size()+1 &&
1378009b1c42SEd Schouten OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
1379009b1c42SEd Schouten UnavailablePred = OneUnavailablePred;
1380009b1c42SEd Schouten } else if (PredsScanned.size() != AvailablePreds.size()) {
1381009b1c42SEd Schouten // Otherwise, we had multiple unavailable predecessors or we had a critical
1382009b1c42SEd Schouten // edge from the one.
1383009b1c42SEd Schouten SmallVector<BasicBlock*, 8> PredsToSplit;
1384009b1c42SEd Schouten SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
1385009b1c42SEd Schouten
1386050e163aSDimitry Andric for (const auto &AvailablePred : AvailablePreds)
1387050e163aSDimitry Andric AvailablePredSet.insert(AvailablePred.first);
1388009b1c42SEd Schouten
1389009b1c42SEd Schouten // Add all the unavailable predecessors to the PredsToSplit list.
1390050e163aSDimitry Andric for (BasicBlock *P : predecessors(LoadBB)) {
139166e41e3cSRoman Divacky // If the predecessor is an indirect goto, we can't split the edge.
13921f917f69SDimitry Andric if (isa<IndirectBrInst>(P->getTerminator()))
139366e41e3cSRoman Divacky return false;
139466e41e3cSRoman Divacky
139566e41e3cSRoman Divacky if (!AvailablePredSet.count(P))
139666e41e3cSRoman Divacky PredsToSplit.push_back(P);
139766e41e3cSRoman Divacky }
1398009b1c42SEd Schouten
1399009b1c42SEd Schouten // Split them out to their own block.
1400b60736ecSDimitry Andric UnavailablePred = splitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
1401009b1c42SEd Schouten }
1402009b1c42SEd Schouten
1403009b1c42SEd Schouten // If the value isn't available in all predecessors, then there will be
1404009b1c42SEd Schouten // exactly one where it isn't available. Insert a load on that edge and add
1405009b1c42SEd Schouten // it to the AvailablePreds list.
1406009b1c42SEd Schouten if (UnavailablePred) {
1407009b1c42SEd Schouten assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
1408009b1c42SEd Schouten "Can't handle critical edge here!");
1409e6d15924SDimitry Andric LoadInst *NewVal = new LoadInst(
1410e6d15924SDimitry Andric LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred),
1411cfca06d7SDimitry Andric LoadI->getName() + ".pr", false, LoadI->getAlign(),
1412eb11fae6SDimitry Andric LoadI->getOrdering(), LoadI->getSyncScopeID(),
1413ac9a064cSDimitry Andric UnavailablePred->getTerminator()->getIterator());
1414eb11fae6SDimitry Andric NewVal->setDebugLoc(LoadI->getDebugLoc());
141567c32a98SDimitry Andric if (AATags)
141667c32a98SDimitry Andric NewVal->setAAMetadata(AATags);
141763faed5bSDimitry Andric
1418cfca06d7SDimitry Andric AvailablePreds.emplace_back(UnavailablePred, NewVal);
1419009b1c42SEd Schouten }
1420009b1c42SEd Schouten
1421009b1c42SEd Schouten // Now we know that each predecessor of this block has a value in
1422009b1c42SEd Schouten // AvailablePreds, sort them for efficient access as we're walking the preds.
1423009b1c42SEd Schouten array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
1424009b1c42SEd Schouten
1425009b1c42SEd Schouten // Create a PHI node at the start of the block for the PRE'd load value.
1426ac9a064cSDimitry Andric PHINode *PN = PHINode::Create(LoadI->getType(), pred_size(LoadBB), "");
1427b1c73532SDimitry Andric PN->insertBefore(LoadBB->begin());
1428eb11fae6SDimitry Andric PN->takeName(LoadI);
1429eb11fae6SDimitry Andric PN->setDebugLoc(LoadI->getDebugLoc());
1430009b1c42SEd Schouten
1431009b1c42SEd Schouten // Insert new entries into the PHI for each predecessor. A single block may
1432009b1c42SEd Schouten // have multiple entries here.
1433ac9a064cSDimitry Andric for (BasicBlock *P : predecessors(LoadBB)) {
1434009b1c42SEd Schouten AvailablePredsTy::iterator I =
1435e6d15924SDimitry Andric llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr));
1436009b1c42SEd Schouten
143766e41e3cSRoman Divacky assert(I != AvailablePreds.end() && I->first == P &&
1438009b1c42SEd Schouten "Didn't find entry for predecessor!");
1439009b1c42SEd Schouten
144067c32a98SDimitry Andric // If we have an available predecessor but it requires casting, insert the
144167c32a98SDimitry Andric // cast in the predecessor and use the cast. Note that we have to update the
144267c32a98SDimitry Andric // AvailablePreds vector as we go so that all of the PHI entries for this
144367c32a98SDimitry Andric // predecessor use the same bitcast.
144467c32a98SDimitry Andric Value *&PredV = I->second;
1445eb11fae6SDimitry Andric if (PredV->getType() != LoadI->getType())
1446ac9a064cSDimitry Andric PredV = CastInst::CreateBitOrPointerCast(
1447ac9a064cSDimitry Andric PredV, LoadI->getType(), "", P->getTerminator()->getIterator());
144867c32a98SDimitry Andric
144967c32a98SDimitry Andric PN->addIncoming(PredV, I->first);
1450009b1c42SEd Schouten }
1451009b1c42SEd Schouten
1452eb11fae6SDimitry Andric for (LoadInst *PredLoadI : CSELoads) {
1453d8e91e46SDimitry Andric combineMetadataForCSE(PredLoadI, LoadI, true);
1454b1c73532SDimitry Andric LVI->forgetValue(PredLoadI);
1455b915e9e0SDimitry Andric }
1456b915e9e0SDimitry Andric
1457eb11fae6SDimitry Andric LoadI->replaceAllUsesWith(PN);
1458eb11fae6SDimitry Andric LoadI->eraseFromParent();
1459009b1c42SEd Schouten
1460009b1c42SEd Schouten return true;
1461009b1c42SEd Schouten }
1462009b1c42SEd Schouten
1463b60736ecSDimitry Andric /// findMostPopularDest - The specified list contains multiple possible
1464907da171SRoman Divacky /// threadable destinations. Pick the one that occurs the most frequently in
1465907da171SRoman Divacky /// the list.
1466907da171SRoman Divacky static BasicBlock *
findMostPopularDest(BasicBlock * BB,const SmallVectorImpl<std::pair<BasicBlock *,BasicBlock * >> & PredToDestList)1467b60736ecSDimitry Andric findMostPopularDest(BasicBlock *BB,
1468907da171SRoman Divacky const SmallVectorImpl<std::pair<BasicBlock *,
1469907da171SRoman Divacky BasicBlock *>> &PredToDestList) {
1470907da171SRoman Divacky assert(!PredToDestList.empty());
1471907da171SRoman Divacky
1472907da171SRoman Divacky // Determine popularity. If there are multiple possible destinations, we
1473907da171SRoman Divacky // explicitly choose to ignore 'undef' destinations. We prefer to thread
1474907da171SRoman Divacky // blocks with known and real destinations to threading undef. We'll handle
1475907da171SRoman Divacky // them later if interesting.
1476cfca06d7SDimitry Andric MapVector<BasicBlock *, unsigned> DestPopularity;
1477cfca06d7SDimitry Andric
1478cfca06d7SDimitry Andric // Populate DestPopularity with the successors in the order they appear in the
1479cfca06d7SDimitry Andric // successor list. This way, we ensure determinism by iterating it in the
1480ac9a064cSDimitry Andric // same order in llvm::max_element below. We map nullptr to 0 so that we can
1481cfca06d7SDimitry Andric // return nullptr when PredToDestList contains nullptr only.
1482cfca06d7SDimitry Andric DestPopularity[nullptr] = 0;
1483cfca06d7SDimitry Andric for (auto *SuccBB : successors(BB))
1484cfca06d7SDimitry Andric DestPopularity[SuccBB] = 0;
1485cfca06d7SDimitry Andric
1486050e163aSDimitry Andric for (const auto &PredToDest : PredToDestList)
1487050e163aSDimitry Andric if (PredToDest.second)
1488050e163aSDimitry Andric DestPopularity[PredToDest.second]++;
1489907da171SRoman Divacky
1490907da171SRoman Divacky // Find the most popular dest.
1491ac9a064cSDimitry Andric auto MostPopular = llvm::max_element(DestPopularity, llvm::less_second());
1492907da171SRoman Divacky
1493907da171SRoman Divacky // Okay, we have finally picked the most popular destination.
1494cfca06d7SDimitry Andric return MostPopular->first;
1495cfca06d7SDimitry Andric }
1496cfca06d7SDimitry Andric
1497cfca06d7SDimitry Andric // Try to evaluate the value of V when the control flows from PredPredBB to
1498cfca06d7SDimitry Andric // BB->getSinglePredecessor() and then on to BB.
evaluateOnPredecessorEdge(BasicBlock * BB,BasicBlock * PredPredBB,Value * V,const DataLayout & DL)1499b60736ecSDimitry Andric Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB,
1500cfca06d7SDimitry Andric BasicBlock *PredPredBB,
1501ac9a064cSDimitry Andric Value *V,
1502ac9a064cSDimitry Andric const DataLayout &DL) {
1503cfca06d7SDimitry Andric BasicBlock *PredBB = BB->getSinglePredecessor();
1504cfca06d7SDimitry Andric assert(PredBB && "Expected a single predecessor");
1505cfca06d7SDimitry Andric
1506cfca06d7SDimitry Andric if (Constant *Cst = dyn_cast<Constant>(V)) {
1507cfca06d7SDimitry Andric return Cst;
1508cfca06d7SDimitry Andric }
1509cfca06d7SDimitry Andric
1510cfca06d7SDimitry Andric // Consult LVI if V is not an instruction in BB or PredBB.
1511cfca06d7SDimitry Andric Instruction *I = dyn_cast<Instruction>(V);
1512cfca06d7SDimitry Andric if (!I || (I->getParent() != BB && I->getParent() != PredBB)) {
1513cfca06d7SDimitry Andric return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr);
1514cfca06d7SDimitry Andric }
1515cfca06d7SDimitry Andric
1516cfca06d7SDimitry Andric // Look into a PHI argument.
1517cfca06d7SDimitry Andric if (PHINode *PHI = dyn_cast<PHINode>(V)) {
1518cfca06d7SDimitry Andric if (PHI->getParent() == PredBB)
1519cfca06d7SDimitry Andric return dyn_cast<Constant>(PHI->getIncomingValueForBlock(PredPredBB));
1520cfca06d7SDimitry Andric return nullptr;
1521cfca06d7SDimitry Andric }
1522cfca06d7SDimitry Andric
1523cfca06d7SDimitry Andric // If we have a CmpInst, try to fold it for each incoming edge into PredBB.
1524cfca06d7SDimitry Andric if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) {
1525cfca06d7SDimitry Andric if (CondCmp->getParent() == BB) {
1526cfca06d7SDimitry Andric Constant *Op0 =
1527ac9a064cSDimitry Andric evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0), DL);
1528cfca06d7SDimitry Andric Constant *Op1 =
1529ac9a064cSDimitry Andric evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1), DL);
1530cfca06d7SDimitry Andric if (Op0 && Op1) {
1531ac9a064cSDimitry Andric return ConstantFoldCompareInstOperands(CondCmp->getPredicate(), Op0,
1532ac9a064cSDimitry Andric Op1, DL);
1533cfca06d7SDimitry Andric }
1534cfca06d7SDimitry Andric }
1535cfca06d7SDimitry Andric return nullptr;
1536cfca06d7SDimitry Andric }
1537cfca06d7SDimitry Andric
1538cfca06d7SDimitry Andric return nullptr;
1539907da171SRoman Divacky }
1540907da171SRoman Divacky
processThreadableEdges(Value * Cond,BasicBlock * BB,ConstantPreference Preference,Instruction * CxtI)1541b60736ecSDimitry Andric bool JumpThreadingPass::processThreadableEdges(Value *Cond, BasicBlock *BB,
154267c32a98SDimitry Andric ConstantPreference Preference,
154367c32a98SDimitry Andric Instruction *CxtI) {
1544907da171SRoman Divacky // If threading this would thread across a loop header, don't even try to
1545907da171SRoman Divacky // thread the edge.
1546907da171SRoman Divacky if (LoopHeaders.count(BB))
1547907da171SRoman Divacky return false;
1548907da171SRoman Divacky
1549cf099d11SDimitry Andric PredValueInfoTy PredValues;
1550b60736ecSDimitry Andric if (!computeValueKnownInPredecessors(Cond, BB, PredValues, Preference,
1551cfca06d7SDimitry Andric CxtI)) {
1552cfca06d7SDimitry Andric // We don't have known values in predecessors. See if we can thread through
1553cfca06d7SDimitry Andric // BB and its sole predecessor.
1554b60736ecSDimitry Andric return maybethreadThroughTwoBasicBlocks(BB, Cond);
1555cfca06d7SDimitry Andric }
1556d39c594dSDimitry Andric
1557907da171SRoman Divacky assert(!PredValues.empty() &&
1558b60736ecSDimitry Andric "computeValueKnownInPredecessors returned true with no values");
1559907da171SRoman Divacky
1560eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "IN BB: " << *BB;
1561050e163aSDimitry Andric for (const auto &PredValue : PredValues) {
1562eb11fae6SDimitry Andric dbgs() << " BB '" << BB->getName()
1563eb11fae6SDimitry Andric << "': FOUND condition = " << *PredValue.first
1564050e163aSDimitry Andric << " for pred '" << PredValue.second->getName() << "'.\n";
1565907da171SRoman Divacky });
1566907da171SRoman Divacky
1567907da171SRoman Divacky // Decide what we want to thread through. Convert our list of known values to
1568907da171SRoman Divacky // a list of known destinations for each pred. This also discards duplicate
1569907da171SRoman Divacky // predecessors and keeps track of the undefined inputs (which are represented
1570907da171SRoman Divacky // as a null dest in the PredToDestList).
1571907da171SRoman Divacky SmallPtrSet<BasicBlock*, 16> SeenPreds;
1572907da171SRoman Divacky SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1573907da171SRoman Divacky
15745ca98fd9SDimitry Andric BasicBlock *OnlyDest = nullptr;
1575907da171SRoman Divacky BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1576a303c417SDimitry Andric Constant *OnlyVal = nullptr;
1577a303c417SDimitry Andric Constant *MultipleVal = (Constant *)(intptr_t)~0ULL;
1578907da171SRoman Divacky
1579050e163aSDimitry Andric for (const auto &PredValue : PredValues) {
1580050e163aSDimitry Andric BasicBlock *Pred = PredValue.second;
158167c32a98SDimitry Andric if (!SeenPreds.insert(Pred).second)
1582907da171SRoman Divacky continue; // Duplicate predecessor entry.
1583907da171SRoman Divacky
1584050e163aSDimitry Andric Constant *Val = PredValue.first;
1585907da171SRoman Divacky
1586907da171SRoman Divacky BasicBlock *DestBB;
1587cf099d11SDimitry Andric if (isa<UndefValue>(Val))
15885ca98fd9SDimitry Andric DestBB = nullptr;
1589a303c417SDimitry Andric else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1590a303c417SDimitry Andric assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1591cf099d11SDimitry Andric DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
1592a303c417SDimitry Andric } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1593a303c417SDimitry Andric assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
159471d5a254SDimitry Andric DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
159563faed5bSDimitry Andric } else {
1596cf099d11SDimitry Andric assert(isa<IndirectBrInst>(BB->getTerminator())
1597cf099d11SDimitry Andric && "Unexpected terminator");
1598a303c417SDimitry Andric assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress");
1599cf099d11SDimitry Andric DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1600907da171SRoman Divacky }
1601907da171SRoman Divacky
1602907da171SRoman Divacky // If we have exactly one destination, remember it for efficiency below.
1603a303c417SDimitry Andric if (PredToDestList.empty()) {
1604907da171SRoman Divacky OnlyDest = DestBB;
1605a303c417SDimitry Andric OnlyVal = Val;
1606a303c417SDimitry Andric } else {
1607a303c417SDimitry Andric if (OnlyDest != DestBB)
1608907da171SRoman Divacky OnlyDest = MultipleDestSentinel;
1609a303c417SDimitry Andric // It possible we have same destination, but different value, e.g. default
1610a303c417SDimitry Andric // case in switchinst.
1611a303c417SDimitry Andric if (Val != OnlyVal)
1612a303c417SDimitry Andric OnlyVal = MultipleVal;
1613a303c417SDimitry Andric }
1614a303c417SDimitry Andric
1615a303c417SDimitry Andric // If the predecessor ends with an indirect goto, we can't change its
16161f917f69SDimitry Andric // destination.
16171f917f69SDimitry Andric if (isa<IndirectBrInst>(Pred->getTerminator()))
1618a303c417SDimitry Andric continue;
1619907da171SRoman Divacky
1620cfca06d7SDimitry Andric PredToDestList.emplace_back(Pred, DestBB);
1621907da171SRoman Divacky }
1622907da171SRoman Divacky
1623907da171SRoman Divacky // If all edges were unthreadable, we fail.
1624907da171SRoman Divacky if (PredToDestList.empty())
1625907da171SRoman Divacky return false;
1626907da171SRoman Divacky
162712f3ca4cSDimitry Andric // If all the predecessors go to a single known successor, we want to fold,
162812f3ca4cSDimitry Andric // not thread. By doing so, we do not need to duplicate the current block and
162912f3ca4cSDimitry Andric // also miss potential opportunities in case we dont/cant duplicate.
163012f3ca4cSDimitry Andric if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1631e6d15924SDimitry Andric if (BB->hasNPredecessors(PredToDestList.size())) {
163212f3ca4cSDimitry Andric bool SeenFirstBranchToOnlyDest = false;
1633eb11fae6SDimitry Andric std::vector <DominatorTree::UpdateType> Updates;
1634eb11fae6SDimitry Andric Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1);
163512f3ca4cSDimitry Andric for (BasicBlock *SuccBB : successors(BB)) {
1636eb11fae6SDimitry Andric if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
163712f3ca4cSDimitry Andric SeenFirstBranchToOnlyDest = true; // Don't modify the first branch.
1638eb11fae6SDimitry Andric } else {
163912f3ca4cSDimitry Andric SuccBB->removePredecessor(BB, true); // This is unreachable successor.
1640eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Delete, BB, SuccBB});
1641eb11fae6SDimitry Andric }
164212f3ca4cSDimitry Andric }
164312f3ca4cSDimitry Andric
164412f3ca4cSDimitry Andric // Finally update the terminator.
1645d8e91e46SDimitry Andric Instruction *Term = BB->getTerminator();
1646ac9a064cSDimitry Andric Instruction *NewBI = BranchInst::Create(OnlyDest, Term->getIterator());
1647ac9a064cSDimitry Andric NewBI->setDebugLoc(Term->getDebugLoc());
1648344a3780SDimitry Andric ++NumFolds;
164912f3ca4cSDimitry Andric Term->eraseFromParent();
1650e6d15924SDimitry Andric DTU->applyUpdatesPermissive(Updates);
16517fa27ce4SDimitry Andric if (auto *BPI = getBPI())
1652b60736ecSDimitry Andric BPI->eraseBlock(BB);
165312f3ca4cSDimitry Andric
165412f3ca4cSDimitry Andric // If the condition is now dead due to the removal of the old terminator,
165512f3ca4cSDimitry Andric // erase it.
1656a303c417SDimitry Andric if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
1657a303c417SDimitry Andric if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
165812f3ca4cSDimitry Andric CondInst->eraseFromParent();
1659ab44ce3dSDimitry Andric // We can safely replace *some* uses of the CondInst if it has
1660b5630dbaSDimitry Andric // exactly one value as returned by LVI. RAUW is incorrect in the
1661b5630dbaSDimitry Andric // presence of guards and assumes, that have the `Cond` as the use. This
1662b5630dbaSDimitry Andric // is because we use the guards/assume to reason about the `Cond` value
1663b5630dbaSDimitry Andric // at the end of block, but RAUW unconditionally replaces all uses
1664b5630dbaSDimitry Andric // including the guards/assumes themselves and the uses before the
1665b5630dbaSDimitry Andric // guard/assume.
1666145449b1SDimitry Andric else if (OnlyVal && OnlyVal != MultipleVal)
1667145449b1SDimitry Andric replaceFoldableUses(CondInst, OnlyVal, BB);
1668a303c417SDimitry Andric }
166912f3ca4cSDimitry Andric return true;
167012f3ca4cSDimitry Andric }
167112f3ca4cSDimitry Andric }
167212f3ca4cSDimitry Andric
1673907da171SRoman Divacky // Determine which is the most common successor. If we have many inputs and
1674907da171SRoman Divacky // this block is a switch, we want to start by threading the batch that goes
1675907da171SRoman Divacky // to the most popular destination first. If we only know about one
1676907da171SRoman Divacky // threadable destination (the common case) we can avoid this.
1677907da171SRoman Divacky BasicBlock *MostPopularDest = OnlyDest;
1678907da171SRoman Divacky
1679eb11fae6SDimitry Andric if (MostPopularDest == MultipleDestSentinel) {
1680b60736ecSDimitry Andric // Remove any loop headers from the Dest list, threadEdge conservatively
1681eb11fae6SDimitry Andric // won't process them, but we might have other destination that are eligible
1682eb11fae6SDimitry Andric // and we still want to process.
1683eb11fae6SDimitry Andric erase_if(PredToDestList,
1684eb11fae6SDimitry Andric [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1685b60736ecSDimitry Andric return LoopHeaders.contains(PredToDest.second);
1686eb11fae6SDimitry Andric });
1687eb11fae6SDimitry Andric
1688eb11fae6SDimitry Andric if (PredToDestList.empty())
1689eb11fae6SDimitry Andric return false;
1690eb11fae6SDimitry Andric
1691b60736ecSDimitry Andric MostPopularDest = findMostPopularDest(BB, PredToDestList);
1692eb11fae6SDimitry Andric }
1693907da171SRoman Divacky
1694907da171SRoman Divacky // Now that we know what the most popular destination is, factor all
1695907da171SRoman Divacky // predecessors that will jump to it into a single predecessor.
1696907da171SRoman Divacky SmallVector<BasicBlock*, 16> PredsToFactor;
1697050e163aSDimitry Andric for (const auto &PredToDest : PredToDestList)
1698050e163aSDimitry Andric if (PredToDest.second == MostPopularDest) {
1699050e163aSDimitry Andric BasicBlock *Pred = PredToDest.first;
1700907da171SRoman Divacky
1701907da171SRoman Divacky // This predecessor may be a switch or something else that has multiple
1702907da171SRoman Divacky // edges to the block. Factor each of these edges by listing them
1703907da171SRoman Divacky // according to # occurrences in PredsToFactor.
1704050e163aSDimitry Andric for (BasicBlock *Succ : successors(Pred))
1705050e163aSDimitry Andric if (Succ == BB)
1706907da171SRoman Divacky PredsToFactor.push_back(Pred);
1707907da171SRoman Divacky }
1708907da171SRoman Divacky
1709907da171SRoman Divacky // If the threadable edges are branching on an undefined value, we get to pick
1710907da171SRoman Divacky // the destination that these predecessors should get to.
17115ca98fd9SDimitry Andric if (!MostPopularDest)
1712907da171SRoman Divacky MostPopularDest = BB->getTerminator()->
1713b60736ecSDimitry Andric getSuccessor(getBestDestForJumpOnUndef(BB));
1714907da171SRoman Divacky
1715907da171SRoman Divacky // Ok, try to thread it!
1716b60736ecSDimitry Andric return tryThreadEdge(BB, PredsToFactor, MostPopularDest);
1717907da171SRoman Divacky }
1718009b1c42SEd Schouten
1719b60736ecSDimitry Andric /// processBranchOnPHI - We have an otherwise unthreadable conditional branch on
1720b60736ecSDimitry Andric /// a PHI node (or freeze PHI) in the current block. See if there are any
1721b60736ecSDimitry Andric /// simplifications we can do based on inputs to the phi node.
processBranchOnPHI(PHINode * PN)1722b60736ecSDimitry Andric bool JumpThreadingPass::processBranchOnPHI(PHINode *PN) {
1723009b1c42SEd Schouten BasicBlock *BB = PN->getParent();
1724009b1c42SEd Schouten
1725829000e0SRoman Divacky // TODO: We could make use of this to do it once for blocks with common PHI
1726829000e0SRoman Divacky // values.
1727829000e0SRoman Divacky SmallVector<BasicBlock*, 1> PredBBs;
1728829000e0SRoman Divacky PredBBs.resize(1);
1729829000e0SRoman Divacky
1730907da171SRoman Divacky // If any of the predecessor blocks end in an unconditional branch, we can
1731829000e0SRoman Divacky // *duplicate* the conditional branch into that block in order to further
1732829000e0SRoman Divacky // encourage jump threading and to eliminate cases where we have branch on a
1733829000e0SRoman Divacky // phi of an icmp (branch on icmp is much better).
1734b60736ecSDimitry Andric // This is still beneficial when a frozen phi is used as the branch condition
1735b60736ecSDimitry Andric // because it allows CodeGenPrepare to further canonicalize br(freeze(icmp))
1736b60736ecSDimitry Andric // to br(icmp(freeze ...)).
173759850d08SRoman Divacky for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
173859850d08SRoman Divacky BasicBlock *PredBB = PN->getIncomingBlock(i);
173959850d08SRoman Divacky if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1740829000e0SRoman Divacky if (PredBr->isUnconditional()) {
1741829000e0SRoman Divacky PredBBs[0] = PredBB;
174259850d08SRoman Divacky // Try to duplicate BB into PredBB.
1743b60736ecSDimitry Andric if (duplicateCondBranchOnPHIIntoPred(BB, PredBBs))
174459850d08SRoman Divacky return true;
174559850d08SRoman Divacky }
1746829000e0SRoman Divacky }
174759850d08SRoman Divacky
174859850d08SRoman Divacky return false;
174959850d08SRoman Divacky }
175059850d08SRoman Divacky
1751b60736ecSDimitry Andric /// processBranchOnXOR - We have an otherwise unthreadable conditional branch on
1752829000e0SRoman Divacky /// a xor instruction in the current block. See if there are any
1753829000e0SRoman Divacky /// simplifications we can do based on inputs to the xor.
processBranchOnXOR(BinaryOperator * BO)1754b60736ecSDimitry Andric bool JumpThreadingPass::processBranchOnXOR(BinaryOperator *BO) {
1755829000e0SRoman Divacky BasicBlock *BB = BO->getParent();
1756829000e0SRoman Divacky
1757829000e0SRoman Divacky // If either the LHS or RHS of the xor is a constant, don't do this
1758829000e0SRoman Divacky // optimization.
1759829000e0SRoman Divacky if (isa<ConstantInt>(BO->getOperand(0)) ||
1760829000e0SRoman Divacky isa<ConstantInt>(BO->getOperand(1)))
1761829000e0SRoman Divacky return false;
1762829000e0SRoman Divacky
17636fe5c7aaSRoman Divacky // If the first instruction in BB isn't a phi, we won't be able to infer
17646fe5c7aaSRoman Divacky // anything special about any particular predecessor.
17656fe5c7aaSRoman Divacky if (!isa<PHINode>(BB->front()))
17666fe5c7aaSRoman Divacky return false;
17676fe5c7aaSRoman Divacky
17686449741fSDimitry Andric // If this BB is a landing pad, we won't be able to split the edge into it.
17696449741fSDimitry Andric if (BB->isEHPad())
17706449741fSDimitry Andric return false;
17716449741fSDimitry Andric
1772829000e0SRoman Divacky // If we have a xor as the branch input to this block, and we know that the
1773829000e0SRoman Divacky // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1774829000e0SRoman Divacky // the condition into the predecessor and fix that value to true, saving some
1775829000e0SRoman Divacky // logical ops on that path and encouraging other paths to simplify.
1776829000e0SRoman Divacky //
1777829000e0SRoman Divacky // This copies something like this:
1778829000e0SRoman Divacky //
1779829000e0SRoman Divacky // BB:
1780829000e0SRoman Divacky // %X = phi i1 [1], [%X']
1781829000e0SRoman Divacky // %Y = icmp eq i32 %A, %B
1782829000e0SRoman Divacky // %Z = xor i1 %X, %Y
1783829000e0SRoman Divacky // br i1 %Z, ...
1784829000e0SRoman Divacky //
1785829000e0SRoman Divacky // Into:
1786829000e0SRoman Divacky // BB':
1787829000e0SRoman Divacky // %Y = icmp ne i32 %A, %B
1788dd58ef01SDimitry Andric // br i1 %Y, ...
1789829000e0SRoman Divacky
1790cf099d11SDimitry Andric PredValueInfoTy XorOpValues;
1791829000e0SRoman Divacky bool isLHS = true;
1792b60736ecSDimitry Andric if (!computeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
179367c32a98SDimitry Andric WantInteger, BO)) {
1794829000e0SRoman Divacky assert(XorOpValues.empty());
1795b60736ecSDimitry Andric if (!computeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
179667c32a98SDimitry Andric WantInteger, BO))
1797829000e0SRoman Divacky return false;
1798829000e0SRoman Divacky isLHS = false;
1799829000e0SRoman Divacky }
1800829000e0SRoman Divacky
1801829000e0SRoman Divacky assert(!XorOpValues.empty() &&
1802b60736ecSDimitry Andric "computeValueKnownInPredecessors returned true with no values");
1803829000e0SRoman Divacky
1804829000e0SRoman Divacky // Scan the information to see which is most popular: true or false. The
1805829000e0SRoman Divacky // predecessors can be of the set true, false, or undef.
1806829000e0SRoman Divacky unsigned NumTrue = 0, NumFalse = 0;
1807050e163aSDimitry Andric for (const auto &XorOpValue : XorOpValues) {
1808050e163aSDimitry Andric if (isa<UndefValue>(XorOpValue.first))
1809cf099d11SDimitry Andric // Ignore undefs for the count.
1810cf099d11SDimitry Andric continue;
1811050e163aSDimitry Andric if (cast<ConstantInt>(XorOpValue.first)->isZero())
1812829000e0SRoman Divacky ++NumFalse;
1813829000e0SRoman Divacky else
1814829000e0SRoman Divacky ++NumTrue;
1815829000e0SRoman Divacky }
1816829000e0SRoman Divacky
1817829000e0SRoman Divacky // Determine which value to split on, true, false, or undef if neither.
18185ca98fd9SDimitry Andric ConstantInt *SplitVal = nullptr;
1819829000e0SRoman Divacky if (NumTrue > NumFalse)
1820829000e0SRoman Divacky SplitVal = ConstantInt::getTrue(BB->getContext());
1821829000e0SRoman Divacky else if (NumTrue != 0 || NumFalse != 0)
1822829000e0SRoman Divacky SplitVal = ConstantInt::getFalse(BB->getContext());
1823829000e0SRoman Divacky
1824829000e0SRoman Divacky // Collect all of the blocks that this can be folded into so that we can
1825829000e0SRoman Divacky // factor this once and clone it once.
1826829000e0SRoman Divacky SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1827050e163aSDimitry Andric for (const auto &XorOpValue : XorOpValues) {
1828050e163aSDimitry Andric if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1829cf099d11SDimitry Andric continue;
1830829000e0SRoman Divacky
1831050e163aSDimitry Andric BlocksToFoldInto.push_back(XorOpValue.second);
1832829000e0SRoman Divacky }
1833829000e0SRoman Divacky
18346fe5c7aaSRoman Divacky // If we inferred a value for all of the predecessors, then duplication won't
18356fe5c7aaSRoman Divacky // help us. However, we can just replace the LHS or RHS with the constant.
18366fe5c7aaSRoman Divacky if (BlocksToFoldInto.size() ==
18376fe5c7aaSRoman Divacky cast<PHINode>(BB->front()).getNumIncomingValues()) {
18385ca98fd9SDimitry Andric if (!SplitVal) {
18396fe5c7aaSRoman Divacky // If all preds provide undef, just nuke the xor, because it is undef too.
18406fe5c7aaSRoman Divacky BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
18416fe5c7aaSRoman Divacky BO->eraseFromParent();
1842e3b55780SDimitry Andric } else if (SplitVal->isZero() && BO != BO->getOperand(isLHS)) {
18436fe5c7aaSRoman Divacky // If all preds provide 0, replace the xor with the other input.
18446fe5c7aaSRoman Divacky BO->replaceAllUsesWith(BO->getOperand(isLHS));
18456fe5c7aaSRoman Divacky BO->eraseFromParent();
18466fe5c7aaSRoman Divacky } else {
18476fe5c7aaSRoman Divacky // If all preds provide 1, set the computed value to 1.
18486fe5c7aaSRoman Divacky BO->setOperand(!isLHS, SplitVal);
18496fe5c7aaSRoman Divacky }
18506fe5c7aaSRoman Divacky
18516fe5c7aaSRoman Divacky return true;
18526fe5c7aaSRoman Divacky }
18536fe5c7aaSRoman Divacky
1854b60736ecSDimitry Andric // If any of predecessors end with an indirect goto, we can't change its
18551f917f69SDimitry Andric // destination.
1856b60736ecSDimitry Andric if (any_of(BlocksToFoldInto, [](BasicBlock *Pred) {
18571f917f69SDimitry Andric return isa<IndirectBrInst>(Pred->getTerminator());
1858b60736ecSDimitry Andric }))
1859b60736ecSDimitry Andric return false;
1860b60736ecSDimitry Andric
1861829000e0SRoman Divacky // Try to duplicate BB into PredBB.
1862b60736ecSDimitry Andric return duplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1863829000e0SRoman Divacky }
1864829000e0SRoman Divacky
1865b60736ecSDimitry Andric /// addPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
186659850d08SRoman Divacky /// predecessor to the PHIBB block. If it has PHI nodes, add entries for
186759850d08SRoman Divacky /// NewPred using the entries from OldPred (suitably mapped).
addPHINodeEntriesForMappedBlock(BasicBlock * PHIBB,BasicBlock * OldPred,BasicBlock * NewPred,ValueToValueMapTy & ValueMap)1868b60736ecSDimitry Andric static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
186959850d08SRoman Divacky BasicBlock *OldPred,
187059850d08SRoman Divacky BasicBlock *NewPred,
1871ac9a064cSDimitry Andric ValueToValueMapTy &ValueMap) {
1872eb11fae6SDimitry Andric for (PHINode &PN : PHIBB->phis()) {
187359850d08SRoman Divacky // Ok, we have a PHI node. Figure out what the incoming value was for the
187459850d08SRoman Divacky // DestBlock.
1875eb11fae6SDimitry Andric Value *IV = PN.getIncomingValueForBlock(OldPred);
187659850d08SRoman Divacky
187759850d08SRoman Divacky // Remap the value if necessary.
187859850d08SRoman Divacky if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1879ac9a064cSDimitry Andric ValueToValueMapTy::iterator I = ValueMap.find(Inst);
188059850d08SRoman Divacky if (I != ValueMap.end())
188159850d08SRoman Divacky IV = I->second;
188259850d08SRoman Divacky }
188359850d08SRoman Divacky
1884eb11fae6SDimitry Andric PN.addIncoming(IV, NewPred);
188559850d08SRoman Divacky }
188659850d08SRoman Divacky }
188759850d08SRoman Divacky
1888706b4fc4SDimitry Andric /// Merge basic block BB into its sole predecessor if possible.
maybeMergeBasicBlockIntoOnlyPred(BasicBlock * BB)1889b60736ecSDimitry Andric bool JumpThreadingPass::maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) {
1890706b4fc4SDimitry Andric BasicBlock *SinglePred = BB->getSinglePredecessor();
1891706b4fc4SDimitry Andric if (!SinglePred)
1892706b4fc4SDimitry Andric return false;
1893706b4fc4SDimitry Andric
1894706b4fc4SDimitry Andric const Instruction *TI = SinglePred->getTerminator();
1895b1c73532SDimitry Andric if (TI->isSpecialTerminator() || TI->getNumSuccessors() != 1 ||
1896706b4fc4SDimitry Andric SinglePred == BB || hasAddressTakenAndUsed(BB))
1897706b4fc4SDimitry Andric return false;
1898706b4fc4SDimitry Andric
1899706b4fc4SDimitry Andric // If SinglePred was a loop header, BB becomes one.
1900706b4fc4SDimitry Andric if (LoopHeaders.erase(SinglePred))
1901706b4fc4SDimitry Andric LoopHeaders.insert(BB);
1902706b4fc4SDimitry Andric
1903706b4fc4SDimitry Andric LVI->eraseBlock(SinglePred);
19047fa27ce4SDimitry Andric MergeBasicBlockIntoOnlyPred(BB, DTU.get());
1905706b4fc4SDimitry Andric
1906706b4fc4SDimitry Andric // Now that BB is merged into SinglePred (i.e. SinglePred code followed by
1907706b4fc4SDimitry Andric // BB code within one basic block `BB`), we need to invalidate the LVI
1908706b4fc4SDimitry Andric // information associated with BB, because the LVI information need not be
1909706b4fc4SDimitry Andric // true for all of BB after the merge. For example,
1910706b4fc4SDimitry Andric // Before the merge, LVI info and code is as follows:
1911706b4fc4SDimitry Andric // SinglePred: <LVI info1 for %p val>
1912706b4fc4SDimitry Andric // %y = use of %p
1913706b4fc4SDimitry Andric // call @exit() // need not transfer execution to successor.
1914706b4fc4SDimitry Andric // assume(%p) // from this point on %p is true
1915706b4fc4SDimitry Andric // br label %BB
1916706b4fc4SDimitry Andric // BB: <LVI info2 for %p val, i.e. %p is true>
1917706b4fc4SDimitry Andric // %x = use of %p
1918706b4fc4SDimitry Andric // br label exit
1919706b4fc4SDimitry Andric //
1920706b4fc4SDimitry Andric // Note that this LVI info for blocks BB and SinglPred is correct for %p
1921706b4fc4SDimitry Andric // (info2 and info1 respectively). After the merge and the deletion of the
1922706b4fc4SDimitry Andric // LVI info1 for SinglePred. We have the following code:
1923706b4fc4SDimitry Andric // BB: <LVI info2 for %p val>
1924706b4fc4SDimitry Andric // %y = use of %p
1925706b4fc4SDimitry Andric // call @exit()
1926706b4fc4SDimitry Andric // assume(%p)
1927706b4fc4SDimitry Andric // %x = use of %p <-- LVI info2 is correct from here onwards.
1928706b4fc4SDimitry Andric // br label exit
1929706b4fc4SDimitry Andric // LVI info2 for BB is incorrect at the beginning of BB.
1930706b4fc4SDimitry Andric
1931706b4fc4SDimitry Andric // Invalidate LVI information for BB if the LVI is not provably true for
1932706b4fc4SDimitry Andric // all of BB.
1933706b4fc4SDimitry Andric if (!isGuaranteedToTransferExecutionToSuccessor(BB))
1934706b4fc4SDimitry Andric LVI->eraseBlock(BB);
1935706b4fc4SDimitry Andric return true;
1936706b4fc4SDimitry Andric }
1937706b4fc4SDimitry Andric
1938706b4fc4SDimitry Andric /// Update the SSA form. NewBB contains instructions that are copied from BB.
1939706b4fc4SDimitry Andric /// ValueMapping maps old values in BB to new ones in NewBB.
updateSSA(BasicBlock * BB,BasicBlock * NewBB,ValueToValueMapTy & ValueMapping)1940ac9a064cSDimitry Andric void JumpThreadingPass::updateSSA(BasicBlock *BB, BasicBlock *NewBB,
1941ac9a064cSDimitry Andric ValueToValueMapTy &ValueMapping) {
1942706b4fc4SDimitry Andric // If there were values defined in BB that are used outside the block, then we
1943706b4fc4SDimitry Andric // now have to update all uses of the value to use either the original value,
1944706b4fc4SDimitry Andric // the cloned value, or some PHI derived value. This can require arbitrary
1945706b4fc4SDimitry Andric // PHI insertion, of which we are prepared to do, clean these up now.
1946706b4fc4SDimitry Andric SSAUpdater SSAUpdate;
1947706b4fc4SDimitry Andric SmallVector<Use *, 16> UsesToRename;
19487fa27ce4SDimitry Andric SmallVector<DbgValueInst *, 4> DbgValues;
1949ac9a064cSDimitry Andric SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;
1950706b4fc4SDimitry Andric
1951706b4fc4SDimitry Andric for (Instruction &I : *BB) {
1952706b4fc4SDimitry Andric // Scan all uses of this instruction to see if it is used outside of its
1953706b4fc4SDimitry Andric // block, and if so, record them in UsesToRename.
1954706b4fc4SDimitry Andric for (Use &U : I.uses()) {
1955706b4fc4SDimitry Andric Instruction *User = cast<Instruction>(U.getUser());
1956706b4fc4SDimitry Andric if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1957706b4fc4SDimitry Andric if (UserPN->getIncomingBlock(U) == BB)
1958706b4fc4SDimitry Andric continue;
1959706b4fc4SDimitry Andric } else if (User->getParent() == BB)
1960706b4fc4SDimitry Andric continue;
1961706b4fc4SDimitry Andric
1962706b4fc4SDimitry Andric UsesToRename.push_back(&U);
1963706b4fc4SDimitry Andric }
1964706b4fc4SDimitry Andric
19657fa27ce4SDimitry Andric // Find debug values outside of the block
1966ac9a064cSDimitry Andric findDbgValues(DbgValues, &I, &DbgVariableRecords);
1967b1c73532SDimitry Andric llvm::erase_if(DbgValues, [&](const DbgValueInst *DbgVal) {
19687fa27ce4SDimitry Andric return DbgVal->getParent() == BB;
1969b1c73532SDimitry Andric });
1970ac9a064cSDimitry Andric llvm::erase_if(DbgVariableRecords, [&](const DbgVariableRecord *DbgVarRec) {
1971ac9a064cSDimitry Andric return DbgVarRec->getParent() == BB;
1972b1c73532SDimitry Andric });
19737fa27ce4SDimitry Andric
1974706b4fc4SDimitry Andric // If there are no uses outside the block, we're done with this instruction.
1975ac9a064cSDimitry Andric if (UsesToRename.empty() && DbgValues.empty() && DbgVariableRecords.empty())
1976706b4fc4SDimitry Andric continue;
1977706b4fc4SDimitry Andric LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
1978706b4fc4SDimitry Andric
1979706b4fc4SDimitry Andric // We found a use of I outside of BB. Rename all uses of I that are outside
1980706b4fc4SDimitry Andric // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1981706b4fc4SDimitry Andric // with the two values we know.
1982706b4fc4SDimitry Andric SSAUpdate.Initialize(I.getType(), I.getName());
1983706b4fc4SDimitry Andric SSAUpdate.AddAvailableValue(BB, &I);
1984706b4fc4SDimitry Andric SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
1985706b4fc4SDimitry Andric
1986706b4fc4SDimitry Andric while (!UsesToRename.empty())
1987706b4fc4SDimitry Andric SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1988ac9a064cSDimitry Andric if (!DbgValues.empty() || !DbgVariableRecords.empty()) {
19897fa27ce4SDimitry Andric SSAUpdate.UpdateDebugValues(&I, DbgValues);
1990ac9a064cSDimitry Andric SSAUpdate.UpdateDebugValues(&I, DbgVariableRecords);
19917fa27ce4SDimitry Andric DbgValues.clear();
1992ac9a064cSDimitry Andric DbgVariableRecords.clear();
19937fa27ce4SDimitry Andric }
19947fa27ce4SDimitry Andric
1995706b4fc4SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
1996706b4fc4SDimitry Andric }
1997706b4fc4SDimitry Andric }
1998706b4fc4SDimitry Andric
1999706b4fc4SDimitry Andric /// Clone instructions in range [BI, BE) to NewBB. For PHI nodes, we only clone
2000706b4fc4SDimitry Andric /// arguments that come from PredBB. Return the map from the variables in the
2001706b4fc4SDimitry Andric /// source basic block to the variables in the newly created basic block.
2002ac9a064cSDimitry Andric
cloneInstructions(ValueToValueMapTy & ValueMapping,BasicBlock::iterator BI,BasicBlock::iterator BE,BasicBlock * NewBB,BasicBlock * PredBB)2003ac9a064cSDimitry Andric void JumpThreadingPass::cloneInstructions(ValueToValueMapTy &ValueMapping,
2004ac9a064cSDimitry Andric BasicBlock::iterator BI,
2005ac9a064cSDimitry Andric BasicBlock::iterator BE,
2006ac9a064cSDimitry Andric BasicBlock *NewBB,
2007706b4fc4SDimitry Andric BasicBlock *PredBB) {
2008706b4fc4SDimitry Andric // We are going to have to map operands from the source basic block to the new
2009706b4fc4SDimitry Andric // copy of the block 'NewBB'. If there are PHI nodes in the source basic
2010706b4fc4SDimitry Andric // block, evaluate them to account for entry from PredBB.
2011706b4fc4SDimitry Andric
2012e3b55780SDimitry Andric // Retargets llvm.dbg.value to any renamed variables.
2013e3b55780SDimitry Andric auto RetargetDbgValueIfPossible = [&](Instruction *NewInst) -> bool {
2014e3b55780SDimitry Andric auto DbgInstruction = dyn_cast<DbgValueInst>(NewInst);
2015e3b55780SDimitry Andric if (!DbgInstruction)
2016e3b55780SDimitry Andric return false;
2017e3b55780SDimitry Andric
2018e3b55780SDimitry Andric SmallSet<std::pair<Value *, Value *>, 16> OperandsToRemap;
2019e3b55780SDimitry Andric for (auto DbgOperand : DbgInstruction->location_ops()) {
2020e3b55780SDimitry Andric auto DbgOperandInstruction = dyn_cast<Instruction>(DbgOperand);
2021e3b55780SDimitry Andric if (!DbgOperandInstruction)
2022e3b55780SDimitry Andric continue;
2023e3b55780SDimitry Andric
2024e3b55780SDimitry Andric auto I = ValueMapping.find(DbgOperandInstruction);
2025e3b55780SDimitry Andric if (I != ValueMapping.end()) {
2026e3b55780SDimitry Andric OperandsToRemap.insert(
2027e3b55780SDimitry Andric std::pair<Value *, Value *>(DbgOperand, I->second));
2028e3b55780SDimitry Andric }
2029e3b55780SDimitry Andric }
2030e3b55780SDimitry Andric
2031e3b55780SDimitry Andric for (auto &[OldOp, MappedOp] : OperandsToRemap)
2032e3b55780SDimitry Andric DbgInstruction->replaceVariableLocationOp(OldOp, MappedOp);
2033e3b55780SDimitry Andric return true;
2034e3b55780SDimitry Andric };
2035e3b55780SDimitry Andric
2036ac9a064cSDimitry Andric // Duplicate implementation of the above dbg.value code, using
2037ac9a064cSDimitry Andric // DbgVariableRecords instead.
2038ac9a064cSDimitry Andric auto RetargetDbgVariableRecordIfPossible = [&](DbgVariableRecord *DVR) {
2039b1c73532SDimitry Andric SmallSet<std::pair<Value *, Value *>, 16> OperandsToRemap;
2040ac9a064cSDimitry Andric for (auto *Op : DVR->location_ops()) {
2041b1c73532SDimitry Andric Instruction *OpInst = dyn_cast<Instruction>(Op);
2042b1c73532SDimitry Andric if (!OpInst)
2043b1c73532SDimitry Andric continue;
2044b1c73532SDimitry Andric
2045b1c73532SDimitry Andric auto I = ValueMapping.find(OpInst);
2046b1c73532SDimitry Andric if (I != ValueMapping.end())
2047b1c73532SDimitry Andric OperandsToRemap.insert({OpInst, I->second});
2048b1c73532SDimitry Andric }
2049b1c73532SDimitry Andric
2050b1c73532SDimitry Andric for (auto &[OldOp, MappedOp] : OperandsToRemap)
2051ac9a064cSDimitry Andric DVR->replaceVariableLocationOp(OldOp, MappedOp);
2052b1c73532SDimitry Andric };
2053b1c73532SDimitry Andric
2054b1c73532SDimitry Andric BasicBlock *RangeBB = BI->getParent();
2055b1c73532SDimitry Andric
2056706b4fc4SDimitry Andric // Clone the phi nodes of the source basic block into NewBB. The resulting
2057706b4fc4SDimitry Andric // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater
2058706b4fc4SDimitry Andric // might need to rewrite the operand of the cloned phi.
2059706b4fc4SDimitry Andric for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2060706b4fc4SDimitry Andric PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB);
2061706b4fc4SDimitry Andric NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB);
2062706b4fc4SDimitry Andric ValueMapping[PN] = NewPN;
2063706b4fc4SDimitry Andric }
2064706b4fc4SDimitry Andric
2065344a3780SDimitry Andric // Clone noalias scope declarations in the threaded block. When threading a
2066344a3780SDimitry Andric // loop exit, we would otherwise end up with two idential scope declarations
2067344a3780SDimitry Andric // visible at the same time.
2068344a3780SDimitry Andric SmallVector<MDNode *> NoAliasScopes;
2069344a3780SDimitry Andric DenseMap<MDNode *, MDNode *> ClonedScopes;
2070344a3780SDimitry Andric LLVMContext &Context = PredBB->getContext();
2071344a3780SDimitry Andric identifyNoAliasScopesToClone(BI, BE, NoAliasScopes);
2072344a3780SDimitry Andric cloneNoAliasScopes(NoAliasScopes, ClonedScopes, "thread", Context);
2073344a3780SDimitry Andric
2074b1c73532SDimitry Andric auto CloneAndRemapDbgInfo = [&](Instruction *NewInst, Instruction *From) {
2075ac9a064cSDimitry Andric auto DVRRange = NewInst->cloneDebugInfoFrom(From);
2076ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(DVRRange))
2077ac9a064cSDimitry Andric RetargetDbgVariableRecordIfPossible(&DVR);
2078b1c73532SDimitry Andric };
2079b1c73532SDimitry Andric
2080706b4fc4SDimitry Andric // Clone the non-phi instructions of the source basic block into NewBB,
2081706b4fc4SDimitry Andric // keeping track of the mapping and using it to remap operands in the cloned
2082706b4fc4SDimitry Andric // instructions.
2083706b4fc4SDimitry Andric for (; BI != BE; ++BI) {
2084706b4fc4SDimitry Andric Instruction *New = BI->clone();
2085706b4fc4SDimitry Andric New->setName(BI->getName());
2086e3b55780SDimitry Andric New->insertInto(NewBB, NewBB->end());
2087706b4fc4SDimitry Andric ValueMapping[&*BI] = New;
2088344a3780SDimitry Andric adaptNoAliasScopes(New, ClonedScopes, Context);
2089706b4fc4SDimitry Andric
2090b1c73532SDimitry Andric CloneAndRemapDbgInfo(New, &*BI);
2091b1c73532SDimitry Andric
2092e3b55780SDimitry Andric if (RetargetDbgValueIfPossible(New))
2093e3b55780SDimitry Andric continue;
2094e3b55780SDimitry Andric
2095706b4fc4SDimitry Andric // Remap operands to patch up intra-block references.
2096706b4fc4SDimitry Andric for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2097706b4fc4SDimitry Andric if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2098ac9a064cSDimitry Andric ValueToValueMapTy::iterator I = ValueMapping.find(Inst);
2099706b4fc4SDimitry Andric if (I != ValueMapping.end())
2100706b4fc4SDimitry Andric New->setOperand(i, I->second);
2101706b4fc4SDimitry Andric }
2102706b4fc4SDimitry Andric }
2103706b4fc4SDimitry Andric
2104ac9a064cSDimitry Andric // There may be DbgVariableRecords on the terminator, clone directly from
2105ac9a064cSDimitry Andric // marker to marker as there isn't an instruction there.
2106ac9a064cSDimitry Andric if (BE != RangeBB->end() && BE->hasDbgRecords()) {
2107b1c73532SDimitry Andric // Dump them at the end.
2108ac9a064cSDimitry Andric DbgMarker *Marker = RangeBB->getMarker(BE);
2109ac9a064cSDimitry Andric DbgMarker *EndMarker = NewBB->createMarker(NewBB->end());
2110ac9a064cSDimitry Andric auto DVRRange = EndMarker->cloneDebugInfoFrom(Marker, std::nullopt);
2111ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(DVRRange))
2112ac9a064cSDimitry Andric RetargetDbgVariableRecordIfPossible(&DVR);
2113b1c73532SDimitry Andric }
2114b1c73532SDimitry Andric
2115ac9a064cSDimitry Andric return;
2116706b4fc4SDimitry Andric }
2117706b4fc4SDimitry Andric
2118cfca06d7SDimitry Andric /// Attempt to thread through two successive basic blocks.
maybethreadThroughTwoBasicBlocks(BasicBlock * BB,Value * Cond)2119b60736ecSDimitry Andric bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB,
2120cfca06d7SDimitry Andric Value *Cond) {
2121cfca06d7SDimitry Andric // Consider:
2122cfca06d7SDimitry Andric //
2123cfca06d7SDimitry Andric // PredBB:
2124cfca06d7SDimitry Andric // %var = phi i32* [ null, %bb1 ], [ @a, %bb2 ]
2125cfca06d7SDimitry Andric // %tobool = icmp eq i32 %cond, 0
2126cfca06d7SDimitry Andric // br i1 %tobool, label %BB, label ...
2127cfca06d7SDimitry Andric //
2128cfca06d7SDimitry Andric // BB:
2129cfca06d7SDimitry Andric // %cmp = icmp eq i32* %var, null
2130cfca06d7SDimitry Andric // br i1 %cmp, label ..., label ...
2131cfca06d7SDimitry Andric //
2132cfca06d7SDimitry Andric // We don't know the value of %var at BB even if we know which incoming edge
2133cfca06d7SDimitry Andric // we take to BB. However, once we duplicate PredBB for each of its incoming
2134cfca06d7SDimitry Andric // edges (say, PredBB1 and PredBB2), we know the value of %var in each copy of
2135cfca06d7SDimitry Andric // PredBB. Then we can thread edges PredBB1->BB and PredBB2->BB through BB.
2136cfca06d7SDimitry Andric
2137cfca06d7SDimitry Andric // Require that BB end with a Branch for simplicity.
2138cfca06d7SDimitry Andric BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2139cfca06d7SDimitry Andric if (!CondBr)
2140cfca06d7SDimitry Andric return false;
2141cfca06d7SDimitry Andric
2142cfca06d7SDimitry Andric // BB must have exactly one predecessor.
2143cfca06d7SDimitry Andric BasicBlock *PredBB = BB->getSinglePredecessor();
2144cfca06d7SDimitry Andric if (!PredBB)
2145cfca06d7SDimitry Andric return false;
2146cfca06d7SDimitry Andric
2147cfca06d7SDimitry Andric // Require that PredBB end with a conditional Branch. If PredBB ends with an
2148cfca06d7SDimitry Andric // unconditional branch, we should be merging PredBB and BB instead. For
2149cfca06d7SDimitry Andric // simplicity, we don't deal with a switch.
2150cfca06d7SDimitry Andric BranchInst *PredBBBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2151cfca06d7SDimitry Andric if (!PredBBBranch || PredBBBranch->isUnconditional())
2152cfca06d7SDimitry Andric return false;
2153cfca06d7SDimitry Andric
2154cfca06d7SDimitry Andric // If PredBB has exactly one incoming edge, we don't gain anything by copying
2155cfca06d7SDimitry Andric // PredBB.
2156cfca06d7SDimitry Andric if (PredBB->getSinglePredecessor())
2157cfca06d7SDimitry Andric return false;
2158cfca06d7SDimitry Andric
2159cfca06d7SDimitry Andric // Don't thread through PredBB if it contains a successor edge to itself, in
2160cfca06d7SDimitry Andric // which case we would infinite loop. Suppose we are threading an edge from
2161cfca06d7SDimitry Andric // PredPredBB through PredBB and BB to SuccBB with PredBB containing a
2162cfca06d7SDimitry Andric // successor edge to itself. If we allowed jump threading in this case, we
2163cfca06d7SDimitry Andric // could duplicate PredBB and BB as, say, PredBB.thread and BB.thread. Since
2164cfca06d7SDimitry Andric // PredBB.thread has a successor edge to PredBB, we would immediately come up
2165cfca06d7SDimitry Andric // with another jump threading opportunity from PredBB.thread through PredBB
2166cfca06d7SDimitry Andric // and BB to SuccBB. This jump threading would repeatedly occur. That is, we
2167cfca06d7SDimitry Andric // would keep peeling one iteration from PredBB.
2168cfca06d7SDimitry Andric if (llvm::is_contained(successors(PredBB), PredBB))
2169cfca06d7SDimitry Andric return false;
2170cfca06d7SDimitry Andric
2171cfca06d7SDimitry Andric // Don't thread across a loop header.
2172cfca06d7SDimitry Andric if (LoopHeaders.count(PredBB))
2173cfca06d7SDimitry Andric return false;
2174cfca06d7SDimitry Andric
2175cfca06d7SDimitry Andric // Avoid complication with duplicating EH pads.
2176cfca06d7SDimitry Andric if (PredBB->isEHPad())
2177cfca06d7SDimitry Andric return false;
2178cfca06d7SDimitry Andric
2179cfca06d7SDimitry Andric // Find a predecessor that we can thread. For simplicity, we only consider a
2180cfca06d7SDimitry Andric // successor edge out of BB to which we thread exactly one incoming edge into
2181cfca06d7SDimitry Andric // PredBB.
2182cfca06d7SDimitry Andric unsigned ZeroCount = 0;
2183cfca06d7SDimitry Andric unsigned OneCount = 0;
2184cfca06d7SDimitry Andric BasicBlock *ZeroPred = nullptr;
2185cfca06d7SDimitry Andric BasicBlock *OnePred = nullptr;
2186ac9a064cSDimitry Andric const DataLayout &DL = BB->getDataLayout();
2187cfca06d7SDimitry Andric for (BasicBlock *P : predecessors(PredBB)) {
21881f917f69SDimitry Andric // If PredPred ends with IndirectBrInst, we can't handle it.
21891f917f69SDimitry Andric if (isa<IndirectBrInst>(P->getTerminator()))
21901f917f69SDimitry Andric continue;
2191cfca06d7SDimitry Andric if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(
2192ac9a064cSDimitry Andric evaluateOnPredecessorEdge(BB, P, Cond, DL))) {
2193cfca06d7SDimitry Andric if (CI->isZero()) {
2194cfca06d7SDimitry Andric ZeroCount++;
2195cfca06d7SDimitry Andric ZeroPred = P;
2196cfca06d7SDimitry Andric } else if (CI->isOne()) {
2197cfca06d7SDimitry Andric OneCount++;
2198cfca06d7SDimitry Andric OnePred = P;
2199cfca06d7SDimitry Andric }
2200cfca06d7SDimitry Andric }
2201cfca06d7SDimitry Andric }
2202cfca06d7SDimitry Andric
2203cfca06d7SDimitry Andric // Disregard complicated cases where we have to thread multiple edges.
2204cfca06d7SDimitry Andric BasicBlock *PredPredBB;
2205cfca06d7SDimitry Andric if (ZeroCount == 1) {
2206cfca06d7SDimitry Andric PredPredBB = ZeroPred;
2207cfca06d7SDimitry Andric } else if (OneCount == 1) {
2208cfca06d7SDimitry Andric PredPredBB = OnePred;
2209cfca06d7SDimitry Andric } else {
2210cfca06d7SDimitry Andric return false;
2211cfca06d7SDimitry Andric }
2212cfca06d7SDimitry Andric
2213cfca06d7SDimitry Andric BasicBlock *SuccBB = CondBr->getSuccessor(PredPredBB == ZeroPred);
2214cfca06d7SDimitry Andric
2215cfca06d7SDimitry Andric // If threading to the same block as we come from, we would infinite loop.
2216cfca06d7SDimitry Andric if (SuccBB == BB) {
2217cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
2218cfca06d7SDimitry Andric << "' - would thread to self!\n");
2219cfca06d7SDimitry Andric return false;
2220cfca06d7SDimitry Andric }
2221cfca06d7SDimitry Andric
2222cfca06d7SDimitry Andric // If threading this would thread across a loop header, don't thread the edge.
2223b60736ecSDimitry Andric // See the comments above findLoopHeaders for justifications and caveats.
2224cfca06d7SDimitry Andric if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2225cfca06d7SDimitry Andric LLVM_DEBUG({
2226cfca06d7SDimitry Andric bool BBIsHeader = LoopHeaders.count(BB);
2227cfca06d7SDimitry Andric bool SuccIsHeader = LoopHeaders.count(SuccBB);
2228cfca06d7SDimitry Andric dbgs() << " Not threading across "
2229cfca06d7SDimitry Andric << (BBIsHeader ? "loop header BB '" : "block BB '")
2230cfca06d7SDimitry Andric << BB->getName() << "' to dest "
2231cfca06d7SDimitry Andric << (SuccIsHeader ? "loop header BB '" : "block BB '")
2232cfca06d7SDimitry Andric << SuccBB->getName()
2233cfca06d7SDimitry Andric << "' - it might create an irreducible loop!\n";
2234cfca06d7SDimitry Andric });
2235cfca06d7SDimitry Andric return false;
2236cfca06d7SDimitry Andric }
2237cfca06d7SDimitry Andric
2238cfca06d7SDimitry Andric // Compute the cost of duplicating BB and PredBB.
2239c0981da4SDimitry Andric unsigned BBCost = getJumpThreadDuplicationCost(
2240c0981da4SDimitry Andric TTI, BB, BB->getTerminator(), BBDupThreshold);
2241cfca06d7SDimitry Andric unsigned PredBBCost = getJumpThreadDuplicationCost(
2242c0981da4SDimitry Andric TTI, PredBB, PredBB->getTerminator(), BBDupThreshold);
2243cfca06d7SDimitry Andric
2244cfca06d7SDimitry Andric // Give up if costs are too high. We need to check BBCost and PredBBCost
2245cfca06d7SDimitry Andric // individually before checking their sum because getJumpThreadDuplicationCost
2246cfca06d7SDimitry Andric // return (unsigned)~0 for those basic blocks that cannot be duplicated.
2247cfca06d7SDimitry Andric if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold ||
2248cfca06d7SDimitry Andric BBCost + PredBBCost > BBDupThreshold) {
2249cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()
2250cfca06d7SDimitry Andric << "' - Cost is too high: " << PredBBCost
2251cfca06d7SDimitry Andric << " for PredBB, " << BBCost << "for BB\n");
2252cfca06d7SDimitry Andric return false;
2253cfca06d7SDimitry Andric }
2254cfca06d7SDimitry Andric
2255cfca06d7SDimitry Andric // Now we are ready to duplicate PredBB.
2256b60736ecSDimitry Andric threadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB);
2257cfca06d7SDimitry Andric return true;
2258cfca06d7SDimitry Andric }
2259cfca06d7SDimitry Andric
threadThroughTwoBasicBlocks(BasicBlock * PredPredBB,BasicBlock * PredBB,BasicBlock * BB,BasicBlock * SuccBB)2260b60736ecSDimitry Andric void JumpThreadingPass::threadThroughTwoBasicBlocks(BasicBlock *PredPredBB,
2261cfca06d7SDimitry Andric BasicBlock *PredBB,
2262cfca06d7SDimitry Andric BasicBlock *BB,
2263cfca06d7SDimitry Andric BasicBlock *SuccBB) {
2264cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << " Threading through '" << PredBB->getName() << "' and '"
2265cfca06d7SDimitry Andric << BB->getName() << "'\n");
2266cfca06d7SDimitry Andric
22677fa27ce4SDimitry Andric // Build BPI/BFI before any changes are made to IR.
22687fa27ce4SDimitry Andric bool HasProfile = doesBlockHaveProfileData(BB);
22697fa27ce4SDimitry Andric auto *BFI = getOrCreateBFI(HasProfile);
22707fa27ce4SDimitry Andric auto *BPI = getOrCreateBPI(BFI != nullptr);
22717fa27ce4SDimitry Andric
2272cfca06d7SDimitry Andric BranchInst *CondBr = cast<BranchInst>(BB->getTerminator());
2273cfca06d7SDimitry Andric BranchInst *PredBBBranch = cast<BranchInst>(PredBB->getTerminator());
2274cfca06d7SDimitry Andric
2275cfca06d7SDimitry Andric BasicBlock *NewBB =
2276cfca06d7SDimitry Andric BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread",
2277cfca06d7SDimitry Andric PredBB->getParent(), PredBB);
2278cfca06d7SDimitry Andric NewBB->moveAfter(PredBB);
2279cfca06d7SDimitry Andric
2280cfca06d7SDimitry Andric // Set the block frequency of NewBB.
22817fa27ce4SDimitry Andric if (BFI) {
22827fa27ce4SDimitry Andric assert(BPI && "It's expected BPI to exist along with BFI");
2283cfca06d7SDimitry Andric auto NewBBFreq = BFI->getBlockFreq(PredPredBB) *
2284cfca06d7SDimitry Andric BPI->getEdgeProbability(PredPredBB, PredBB);
2285b1c73532SDimitry Andric BFI->setBlockFreq(NewBB, NewBBFreq);
2286cfca06d7SDimitry Andric }
2287cfca06d7SDimitry Andric
2288cfca06d7SDimitry Andric // We are going to have to map operands from the original BB block to the new
2289cfca06d7SDimitry Andric // copy of the block 'NewBB'. If there are PHI nodes in PredBB, evaluate them
2290cfca06d7SDimitry Andric // to account for entry from PredPredBB.
2291ac9a064cSDimitry Andric ValueToValueMapTy ValueMapping;
2292ac9a064cSDimitry Andric cloneInstructions(ValueMapping, PredBB->begin(), PredBB->end(), NewBB,
2293ac9a064cSDimitry Andric PredPredBB);
2294b60736ecSDimitry Andric
2295b60736ecSDimitry Andric // Copy the edge probabilities from PredBB to NewBB.
22967fa27ce4SDimitry Andric if (BPI)
2297b60736ecSDimitry Andric BPI->copyEdgeProbabilities(PredBB, NewBB);
2298cfca06d7SDimitry Andric
2299cfca06d7SDimitry Andric // Update the terminator of PredPredBB to jump to NewBB instead of PredBB.
2300cfca06d7SDimitry Andric // This eliminates predecessors from PredPredBB, which requires us to simplify
2301cfca06d7SDimitry Andric // any PHI nodes in PredBB.
2302cfca06d7SDimitry Andric Instruction *PredPredTerm = PredPredBB->getTerminator();
2303cfca06d7SDimitry Andric for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i)
2304cfca06d7SDimitry Andric if (PredPredTerm->getSuccessor(i) == PredBB) {
2305cfca06d7SDimitry Andric PredBB->removePredecessor(PredPredBB, true);
2306cfca06d7SDimitry Andric PredPredTerm->setSuccessor(i, NewBB);
2307cfca06d7SDimitry Andric }
2308cfca06d7SDimitry Andric
2309b60736ecSDimitry Andric addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB,
2310cfca06d7SDimitry Andric ValueMapping);
2311b60736ecSDimitry Andric addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB,
2312cfca06d7SDimitry Andric ValueMapping);
2313cfca06d7SDimitry Andric
2314cfca06d7SDimitry Andric DTU->applyUpdatesPermissive(
2315cfca06d7SDimitry Andric {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)},
2316cfca06d7SDimitry Andric {DominatorTree::Insert, NewBB, CondBr->getSuccessor(1)},
2317cfca06d7SDimitry Andric {DominatorTree::Insert, PredPredBB, NewBB},
2318cfca06d7SDimitry Andric {DominatorTree::Delete, PredPredBB, PredBB}});
2319cfca06d7SDimitry Andric
2320b60736ecSDimitry Andric updateSSA(PredBB, NewBB, ValueMapping);
2321cfca06d7SDimitry Andric
2322cfca06d7SDimitry Andric // Clean up things like PHI nodes with single operands, dead instructions,
2323cfca06d7SDimitry Andric // etc.
2324cfca06d7SDimitry Andric SimplifyInstructionsInBlock(NewBB, TLI);
2325cfca06d7SDimitry Andric SimplifyInstructionsInBlock(PredBB, TLI);
2326cfca06d7SDimitry Andric
2327cfca06d7SDimitry Andric SmallVector<BasicBlock *, 1> PredsToFactor;
2328cfca06d7SDimitry Andric PredsToFactor.push_back(NewBB);
2329b60736ecSDimitry Andric threadEdge(BB, PredsToFactor, SuccBB);
2330cfca06d7SDimitry Andric }
2331cfca06d7SDimitry Andric
2332b60736ecSDimitry Andric /// tryThreadEdge - Thread an edge if it's safe and profitable to do so.
tryThreadEdge(BasicBlock * BB,const SmallVectorImpl<BasicBlock * > & PredBBs,BasicBlock * SuccBB)2333b60736ecSDimitry Andric bool JumpThreadingPass::tryThreadEdge(
2334706b4fc4SDimitry Andric BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs,
233559850d08SRoman Divacky BasicBlock *SuccBB) {
2336009b1c42SEd Schouten // If threading to the same block as we come from, we would infinite loop.
2337009b1c42SEd Schouten if (SuccBB == BB) {
2338eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
233959850d08SRoman Divacky << "' - would thread to self!\n");
2340009b1c42SEd Schouten return false;
2341009b1c42SEd Schouten }
2342009b1c42SEd Schouten
2343009b1c42SEd Schouten // If threading this would thread across a loop header, don't thread the edge.
2344b60736ecSDimitry Andric // See the comments above findLoopHeaders for justifications and caveats.
2345044eb2f6SDimitry Andric if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2346eb11fae6SDimitry Andric LLVM_DEBUG({
2347044eb2f6SDimitry Andric bool BBIsHeader = LoopHeaders.count(BB);
2348044eb2f6SDimitry Andric bool SuccIsHeader = LoopHeaders.count(SuccBB);
2349044eb2f6SDimitry Andric dbgs() << " Not threading across "
2350044eb2f6SDimitry Andric << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName()
2351044eb2f6SDimitry Andric << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '")
2352044eb2f6SDimitry Andric << SuccBB->getName() << "' - it might create an irreducible loop!\n";
2353044eb2f6SDimitry Andric });
235459850d08SRoman Divacky return false;
235559850d08SRoman Divacky }
235659850d08SRoman Divacky
2357c0981da4SDimitry Andric unsigned JumpThreadCost = getJumpThreadDuplicationCost(
2358c0981da4SDimitry Andric TTI, BB, BB->getTerminator(), BBDupThreshold);
235967c32a98SDimitry Andric if (JumpThreadCost > BBDupThreshold) {
2360eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()
236159850d08SRoman Divacky << "' - Cost is too high: " << JumpThreadCost << "\n");
2362009b1c42SEd Schouten return false;
2363009b1c42SEd Schouten }
2364009b1c42SEd Schouten
2365b60736ecSDimitry Andric threadEdge(BB, PredBBs, SuccBB);
2366706b4fc4SDimitry Andric return true;
2367706b4fc4SDimitry Andric }
2368706b4fc4SDimitry Andric
2369b60736ecSDimitry Andric /// threadEdge - We have decided that it is safe and profitable to factor the
2370706b4fc4SDimitry Andric /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
2371706b4fc4SDimitry Andric /// across BB. Transform the IR to reflect this change.
threadEdge(BasicBlock * BB,const SmallVectorImpl<BasicBlock * > & PredBBs,BasicBlock * SuccBB)2372b60736ecSDimitry Andric void JumpThreadingPass::threadEdge(BasicBlock *BB,
2373706b4fc4SDimitry Andric const SmallVectorImpl<BasicBlock *> &PredBBs,
2374706b4fc4SDimitry Andric BasicBlock *SuccBB) {
2375706b4fc4SDimitry Andric assert(SuccBB != BB && "Don't create an infinite loop");
2376706b4fc4SDimitry Andric
2377706b4fc4SDimitry Andric assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) &&
2378706b4fc4SDimitry Andric "Don't thread across loop headers");
2379706b4fc4SDimitry Andric
23807fa27ce4SDimitry Andric // Build BPI/BFI before any changes are made to IR.
23817fa27ce4SDimitry Andric bool HasProfile = doesBlockHaveProfileData(BB);
23827fa27ce4SDimitry Andric auto *BFI = getOrCreateBFI(HasProfile);
23837fa27ce4SDimitry Andric auto *BPI = getOrCreateBPI(BFI != nullptr);
23847fa27ce4SDimitry Andric
2385dd58ef01SDimitry Andric // And finally, do it! Start by factoring the predecessors if needed.
2386907da171SRoman Divacky BasicBlock *PredBB;
2387907da171SRoman Divacky if (PredBBs.size() == 1)
2388907da171SRoman Divacky PredBB = PredBBs[0];
2389907da171SRoman Divacky else {
2390eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()
2391907da171SRoman Divacky << " common predecessors.\n");
2392b60736ecSDimitry Andric PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
2393907da171SRoman Divacky }
2394907da171SRoman Divacky
2395009b1c42SEd Schouten // And finally, do it!
2396eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName()
2397eb11fae6SDimitry Andric << "' to '" << SuccBB->getName()
2398eb11fae6SDimitry Andric << ", across block:\n " << *BB << "\n");
2399009b1c42SEd Schouten
2400d39c594dSDimitry Andric LVI->threadEdge(PredBB, BB, SuccBB);
2401d39c594dSDimitry Andric
240259850d08SRoman Divacky BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
240359850d08SRoman Divacky BB->getName()+".thread",
240459850d08SRoman Divacky BB->getParent(), BB);
2405009b1c42SEd Schouten NewBB->moveAfter(PredBB);
2406009b1c42SEd Schouten
2407dd58ef01SDimitry Andric // Set the block frequency of NewBB.
24087fa27ce4SDimitry Andric if (BFI) {
24097fa27ce4SDimitry Andric assert(BPI && "It's expected BPI to exist along with BFI");
2410dd58ef01SDimitry Andric auto NewBBFreq =
2411dd58ef01SDimitry Andric BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
2412b1c73532SDimitry Andric BFI->setBlockFreq(NewBB, NewBBFreq);
2413dd58ef01SDimitry Andric }
2414dd58ef01SDimitry Andric
2415706b4fc4SDimitry Andric // Copy all the instructions from BB to NewBB except the terminator.
2416ac9a064cSDimitry Andric ValueToValueMapTy ValueMapping;
2417ac9a064cSDimitry Andric cloneInstructions(ValueMapping, BB->begin(), std::prev(BB->end()), NewBB,
2418ac9a064cSDimitry Andric PredBB);
2419009b1c42SEd Schouten
2420009b1c42SEd Schouten // We didn't copy the terminator from BB over to NewBB, because there is now
2421009b1c42SEd Schouten // an unconditional jump to SuccBB. Insert the unconditional jump.
242256fe8f14SDimitry Andric BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
242356fe8f14SDimitry Andric NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
2424009b1c42SEd Schouten
2425009b1c42SEd Schouten // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
2426009b1c42SEd Schouten // PHI nodes for NewBB now.
2427b60736ecSDimitry Andric addPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
2428009b1c42SEd Schouten
2429eb11fae6SDimitry Andric // Update the terminator of PredBB to jump to NewBB instead of BB. This
2430eb11fae6SDimitry Andric // eliminates predecessors from BB, which requires us to simplify any PHI
2431eb11fae6SDimitry Andric // nodes in BB.
2432d8e91e46SDimitry Andric Instruction *PredTerm = PredBB->getTerminator();
2433eb11fae6SDimitry Andric for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
2434eb11fae6SDimitry Andric if (PredTerm->getSuccessor(i) == BB) {
2435eb11fae6SDimitry Andric BB->removePredecessor(PredBB, true);
2436eb11fae6SDimitry Andric PredTerm->setSuccessor(i, NewBB);
2437eb11fae6SDimitry Andric }
2438eb11fae6SDimitry Andric
2439eb11fae6SDimitry Andric // Enqueue required DT updates.
2440e6d15924SDimitry Andric DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB},
2441eb11fae6SDimitry Andric {DominatorTree::Insert, PredBB, NewBB},
2442eb11fae6SDimitry Andric {DominatorTree::Delete, PredBB, BB}});
2443eb11fae6SDimitry Andric
2444b60736ecSDimitry Andric updateSSA(BB, NewBB, ValueMapping);
2445009b1c42SEd Schouten
2446009b1c42SEd Schouten // At this point, the IR is fully up to date and consistent. Do a quick scan
2447009b1c42SEd Schouten // over the new instructions and zap any that are constants or dead. This
2448009b1c42SEd Schouten // frequently happens because of phi translation.
24495a5ac124SDimitry Andric SimplifyInstructionsInBlock(NewBB, TLI);
2450009b1c42SEd Schouten
2451dd58ef01SDimitry Andric // Update the edge weight from BB to SuccBB, which should be less than before.
24527fa27ce4SDimitry Andric updateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB, BFI, BPI, HasProfile);
2453dd58ef01SDimitry Andric
2454009b1c42SEd Schouten // Threaded an edge!
2455009b1c42SEd Schouten ++NumThreads;
2456009b1c42SEd Schouten }
245759850d08SRoman Divacky
2458dd58ef01SDimitry Andric /// Create a new basic block that will be the predecessor of BB and successor of
2459b915e9e0SDimitry Andric /// all blocks in Preds. When profile data is available, update the frequency of
2460dd58ef01SDimitry Andric /// this new block.
splitBlockPreds(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix)2461b60736ecSDimitry Andric BasicBlock *JumpThreadingPass::splitBlockPreds(BasicBlock *BB,
2462dd58ef01SDimitry Andric ArrayRef<BasicBlock *> Preds,
2463dd58ef01SDimitry Andric const char *Suffix) {
2464eb11fae6SDimitry Andric SmallVector<BasicBlock *, 2> NewBBs;
2465eb11fae6SDimitry Andric
2466dd58ef01SDimitry Andric // Collect the frequencies of all predecessors of BB, which will be used to
2467eb11fae6SDimitry Andric // update the edge weight of the result of splitting predecessors.
2468eb11fae6SDimitry Andric DenseMap<BasicBlock *, BlockFrequency> FreqMap;
24697fa27ce4SDimitry Andric auto *BFI = getBFI();
24707fa27ce4SDimitry Andric if (BFI) {
24717fa27ce4SDimitry Andric auto *BPI = getOrCreateBPI(true);
2472e3b55780SDimitry Andric for (auto *Pred : Preds)
2473eb11fae6SDimitry Andric FreqMap.insert(std::make_pair(
2474eb11fae6SDimitry Andric Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
24757fa27ce4SDimitry Andric }
2476dd58ef01SDimitry Andric
2477eb11fae6SDimitry Andric // In the case when BB is a LandingPad block we create 2 new predecessors
2478eb11fae6SDimitry Andric // instead of just one.
2479eb11fae6SDimitry Andric if (BB->isLandingPad()) {
2480eb11fae6SDimitry Andric std::string NewName = std::string(Suffix) + ".split-lp";
2481eb11fae6SDimitry Andric SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs);
2482eb11fae6SDimitry Andric } else {
2483eb11fae6SDimitry Andric NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix));
2484eb11fae6SDimitry Andric }
2485dd58ef01SDimitry Andric
2486eb11fae6SDimitry Andric std::vector<DominatorTree::UpdateType> Updates;
2487eb11fae6SDimitry Andric Updates.reserve((2 * Preds.size()) + NewBBs.size());
2488e3b55780SDimitry Andric for (auto *NewBB : NewBBs) {
2489eb11fae6SDimitry Andric BlockFrequency NewBBFreq(0);
2490eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Insert, NewBB, BB});
2491e3b55780SDimitry Andric for (auto *Pred : predecessors(NewBB)) {
2492eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Delete, Pred, BB});
2493eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Insert, Pred, NewBB});
24947fa27ce4SDimitry Andric if (BFI) // Update frequencies between Pred -> NewBB.
2495eb11fae6SDimitry Andric NewBBFreq += FreqMap.lookup(Pred);
2496eb11fae6SDimitry Andric }
24977fa27ce4SDimitry Andric if (BFI) // Apply the summed frequency to NewBB.
2498b1c73532SDimitry Andric BFI->setBlockFreq(NewBB, NewBBFreq);
2499eb11fae6SDimitry Andric }
2500eb11fae6SDimitry Andric
2501e6d15924SDimitry Andric DTU->applyUpdatesPermissive(Updates);
2502eb11fae6SDimitry Andric return NewBBs[0];
2503dd58ef01SDimitry Andric }
2504dd58ef01SDimitry Andric
doesBlockHaveProfileData(BasicBlock * BB)2505b915e9e0SDimitry Andric bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
2506d8e91e46SDimitry Andric const Instruction *TI = BB->getTerminator();
25077fa27ce4SDimitry Andric if (!TI || TI->getNumSuccessors() < 2)
25087fa27ce4SDimitry Andric return false;
25097fa27ce4SDimitry Andric
2510e3b55780SDimitry Andric return hasValidBranchWeightMD(*TI);
2511b915e9e0SDimitry Andric }
2512b915e9e0SDimitry Andric
2513dd58ef01SDimitry Andric /// Update the block frequency of BB and branch weight and the metadata on the
2514dd58ef01SDimitry Andric /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
2515dd58ef01SDimitry Andric /// Freq(PredBB->BB) / Freq(BB->SuccBB).
updateBlockFreqAndEdgeWeight(BasicBlock * PredBB,BasicBlock * BB,BasicBlock * NewBB,BasicBlock * SuccBB,BlockFrequencyInfo * BFI,BranchProbabilityInfo * BPI,bool HasProfile)2516b60736ecSDimitry Andric void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
2517dd58ef01SDimitry Andric BasicBlock *BB,
2518dd58ef01SDimitry Andric BasicBlock *NewBB,
25197fa27ce4SDimitry Andric BasicBlock *SuccBB,
25207fa27ce4SDimitry Andric BlockFrequencyInfo *BFI,
25217fa27ce4SDimitry Andric BranchProbabilityInfo *BPI,
25227fa27ce4SDimitry Andric bool HasProfile) {
25237fa27ce4SDimitry Andric assert(((BFI && BPI) || (!BFI && !BFI)) &&
25247fa27ce4SDimitry Andric "Both BFI & BPI should either be set or unset");
2525dd58ef01SDimitry Andric
25267fa27ce4SDimitry Andric if (!BFI) {
25277fa27ce4SDimitry Andric assert(!HasProfile &&
25287fa27ce4SDimitry Andric "It's expected to have BFI/BPI when profile info exists");
25297fa27ce4SDimitry Andric return;
25307fa27ce4SDimitry Andric }
2531dd58ef01SDimitry Andric
2532dd58ef01SDimitry Andric // As the edge from PredBB to BB is deleted, we have to update the block
2533dd58ef01SDimitry Andric // frequency of BB.
2534dd58ef01SDimitry Andric auto BBOrigFreq = BFI->getBlockFreq(BB);
2535dd58ef01SDimitry Andric auto NewBBFreq = BFI->getBlockFreq(NewBB);
2536dd58ef01SDimitry Andric auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
2537dd58ef01SDimitry Andric auto BBNewFreq = BBOrigFreq - NewBBFreq;
2538b1c73532SDimitry Andric BFI->setBlockFreq(BB, BBNewFreq);
2539dd58ef01SDimitry Andric
2540dd58ef01SDimitry Andric // Collect updated outgoing edges' frequencies from BB and use them to update
2541dd58ef01SDimitry Andric // edge probabilities.
2542dd58ef01SDimitry Andric SmallVector<uint64_t, 4> BBSuccFreq;
2543050e163aSDimitry Andric for (BasicBlock *Succ : successors(BB)) {
2544050e163aSDimitry Andric auto SuccFreq = (Succ == SuccBB)
2545dd58ef01SDimitry Andric ? BB2SuccBBFreq - NewBBFreq
2546050e163aSDimitry Andric : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
2547dd58ef01SDimitry Andric BBSuccFreq.push_back(SuccFreq.getFrequency());
2548dd58ef01SDimitry Andric }
2549dd58ef01SDimitry Andric
2550ac9a064cSDimitry Andric uint64_t MaxBBSuccFreq = *llvm::max_element(BBSuccFreq);
2551dd58ef01SDimitry Andric
2552dd58ef01SDimitry Andric SmallVector<BranchProbability, 4> BBSuccProbs;
2553dd58ef01SDimitry Andric if (MaxBBSuccFreq == 0)
2554dd58ef01SDimitry Andric BBSuccProbs.assign(BBSuccFreq.size(),
2555dd58ef01SDimitry Andric {1, static_cast<unsigned>(BBSuccFreq.size())});
2556dd58ef01SDimitry Andric else {
2557dd58ef01SDimitry Andric for (uint64_t Freq : BBSuccFreq)
2558dd58ef01SDimitry Andric BBSuccProbs.push_back(
2559dd58ef01SDimitry Andric BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
2560dd58ef01SDimitry Andric // Normalize edge probabilities so that they sum up to one.
2561dd58ef01SDimitry Andric BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
2562dd58ef01SDimitry Andric BBSuccProbs.end());
2563dd58ef01SDimitry Andric }
2564dd58ef01SDimitry Andric
2565dd58ef01SDimitry Andric // Update edge probabilities in BPI.
2566cfca06d7SDimitry Andric BPI->setEdgeProbability(BB, BBSuccProbs);
2567dd58ef01SDimitry Andric
2568b915e9e0SDimitry Andric // Update the profile metadata as well.
2569b915e9e0SDimitry Andric //
2570b915e9e0SDimitry Andric // Don't do this if the profile of the transformed blocks was statically
2571b915e9e0SDimitry Andric // estimated. (This could occur despite the function having an entry
2572b915e9e0SDimitry Andric // frequency in completely cold parts of the CFG.)
2573b915e9e0SDimitry Andric //
2574b915e9e0SDimitry Andric // In this case we don't want to suggest to subsequent passes that the
2575b915e9e0SDimitry Andric // calculated weights are fully consistent. Consider this graph:
2576b915e9e0SDimitry Andric //
2577b915e9e0SDimitry Andric // check_1
2578b915e9e0SDimitry Andric // 50% / |
2579b915e9e0SDimitry Andric // eq_1 | 50%
2580b915e9e0SDimitry Andric // \ |
2581b915e9e0SDimitry Andric // check_2
2582b915e9e0SDimitry Andric // 50% / |
2583b915e9e0SDimitry Andric // eq_2 | 50%
2584b915e9e0SDimitry Andric // \ |
2585b915e9e0SDimitry Andric // check_3
2586b915e9e0SDimitry Andric // 50% / |
2587b915e9e0SDimitry Andric // eq_3 | 50%
2588b915e9e0SDimitry Andric // \ |
2589b915e9e0SDimitry Andric //
2590b915e9e0SDimitry Andric // Assuming the blocks check_* all compare the same value against 1, 2 and 3,
2591b915e9e0SDimitry Andric // the overall probabilities are inconsistent; the total probability that the
2592b915e9e0SDimitry Andric // value is either 1, 2 or 3 is 150%.
2593b915e9e0SDimitry Andric //
2594b915e9e0SDimitry Andric // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3
2595b915e9e0SDimitry Andric // becomes 0%. This is even worse if the edge whose probability becomes 0% is
2596b915e9e0SDimitry Andric // the loop exit edge. Then based solely on static estimation we would assume
2597b915e9e0SDimitry Andric // the loop was extremely hot.
2598b915e9e0SDimitry Andric //
2599b915e9e0SDimitry Andric // FIXME this locally as well so that BPI and BFI are consistent as well. We
2600b915e9e0SDimitry Andric // shouldn't make edges extremely likely or unlikely based solely on static
2601b915e9e0SDimitry Andric // estimation.
26027fa27ce4SDimitry Andric if (BBSuccProbs.size() >= 2 && HasProfile) {
2603dd58ef01SDimitry Andric SmallVector<uint32_t, 4> Weights;
2604dd58ef01SDimitry Andric for (auto Prob : BBSuccProbs)
2605dd58ef01SDimitry Andric Weights.push_back(Prob.getNumerator());
2606dd58ef01SDimitry Andric
2607dd58ef01SDimitry Andric auto TI = BB->getTerminator();
2608ac9a064cSDimitry Andric setBranchWeights(*TI, Weights, hasBranchWeightOrigin(*TI));
2609dd58ef01SDimitry Andric }
2610dd58ef01SDimitry Andric }
2611dd58ef01SDimitry Andric
2612b60736ecSDimitry Andric /// duplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
261359850d08SRoman Divacky /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
261459850d08SRoman Divacky /// If we can duplicate the contents of BB up into PredBB do so now, this
261559850d08SRoman Divacky /// improves the odds that the branch will be on an analyzable instruction like
261659850d08SRoman Divacky /// a compare.
duplicateCondBranchOnPHIIntoPred(BasicBlock * BB,const SmallVectorImpl<BasicBlock * > & PredBBs)2617b60736ecSDimitry Andric bool JumpThreadingPass::duplicateCondBranchOnPHIIntoPred(
261801095a5dSDimitry Andric BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
2619829000e0SRoman Divacky assert(!PredBBs.empty() && "Can't handle an empty set");
2620829000e0SRoman Divacky
262159850d08SRoman Divacky // If BB is a loop header, then duplicating this block outside the loop would
262259850d08SRoman Divacky // cause us to transform this into an irreducible loop, don't do this.
2623b60736ecSDimitry Andric // See the comments above findLoopHeaders for justifications and caveats.
262459850d08SRoman Divacky if (LoopHeaders.count(BB)) {
2625eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
2626829000e0SRoman Divacky << "' into predecessor block '" << PredBBs[0]->getName()
262759850d08SRoman Divacky << "' - it might create an irreducible loop!\n");
262859850d08SRoman Divacky return false;
262959850d08SRoman Divacky }
263059850d08SRoman Divacky
2631c0981da4SDimitry Andric unsigned DuplicationCost = getJumpThreadDuplicationCost(
2632c0981da4SDimitry Andric TTI, BB, BB->getTerminator(), BBDupThreshold);
263367c32a98SDimitry Andric if (DuplicationCost > BBDupThreshold) {
2634eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
263559850d08SRoman Divacky << "' - Cost is too high: " << DuplicationCost << "\n");
263659850d08SRoman Divacky return false;
263759850d08SRoman Divacky }
263859850d08SRoman Divacky
2639dd58ef01SDimitry Andric // And finally, do it! Start by factoring the predecessors if needed.
2640eb11fae6SDimitry Andric std::vector<DominatorTree::UpdateType> Updates;
2641829000e0SRoman Divacky BasicBlock *PredBB;
2642829000e0SRoman Divacky if (PredBBs.size() == 1)
2643829000e0SRoman Divacky PredBB = PredBBs[0];
2644829000e0SRoman Divacky else {
2645eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()
2646829000e0SRoman Divacky << " common predecessors.\n");
2647b60736ecSDimitry Andric PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
2648829000e0SRoman Divacky }
2649eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Delete, PredBB, BB});
2650829000e0SRoman Divacky
265159850d08SRoman Divacky // Okay, we decided to do this! Clone all the instructions in BB onto the end
265259850d08SRoman Divacky // of PredBB.
2653eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName()
2654eb11fae6SDimitry Andric << "' into end of '" << PredBB->getName()
2655eb11fae6SDimitry Andric << "' to eliminate branch on phi. Cost: "
265659850d08SRoman Divacky << DuplicationCost << " block is:" << *BB << "\n");
265759850d08SRoman Divacky
2658829000e0SRoman Divacky // Unless PredBB ends with an unconditional branch, split the edge so that we
2659829000e0SRoman Divacky // can just clone the bits from BB into the end of the new PredBB.
26606fe5c7aaSRoman Divacky BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2661829000e0SRoman Divacky
26625ca98fd9SDimitry Andric if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
2663eb11fae6SDimitry Andric BasicBlock *OldPredBB = PredBB;
2664eb11fae6SDimitry Andric PredBB = SplitEdge(OldPredBB, BB);
2665eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB});
2666eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Insert, PredBB, BB});
2667eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Delete, OldPredBB, BB});
2668829000e0SRoman Divacky OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
2669829000e0SRoman Divacky }
2670829000e0SRoman Divacky
267159850d08SRoman Divacky // We are going to have to map operands from the original BB block into the
267259850d08SRoman Divacky // PredBB block. Evaluate PHI nodes in BB.
2673ac9a064cSDimitry Andric ValueToValueMapTy ValueMapping;
267459850d08SRoman Divacky
267559850d08SRoman Divacky BasicBlock::iterator BI = BB->begin();
267659850d08SRoman Divacky for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
267759850d08SRoman Divacky ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
267859850d08SRoman Divacky // Clone the non-phi instructions of BB into PredBB, keeping track of the
267959850d08SRoman Divacky // mapping and using it to remap operands in the cloned instructions.
268059850d08SRoman Divacky for (; BI != BB->end(); ++BI) {
268159850d08SRoman Divacky Instruction *New = BI->clone();
26827fa27ce4SDimitry Andric New->insertInto(PredBB, OldPredBranch->getIterator());
268359850d08SRoman Divacky
268459850d08SRoman Divacky // Remap operands to patch up intra-block references.
268559850d08SRoman Divacky for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
268659850d08SRoman Divacky if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2687ac9a064cSDimitry Andric ValueToValueMapTy::iterator I = ValueMapping.find(Inst);
268859850d08SRoman Divacky if (I != ValueMapping.end())
268959850d08SRoman Divacky New->setOperand(i, I->second);
269059850d08SRoman Divacky }
2691829000e0SRoman Divacky
2692ac9a064cSDimitry Andric // Remap debug variable operands.
2693ac9a064cSDimitry Andric remapDebugVariable(ValueMapping, New);
2694ac9a064cSDimitry Andric
2695829000e0SRoman Divacky // If this instruction can be simplified after the operands are updated,
2696829000e0SRoman Divacky // just use the simplified value instead. This frequently happens due to
2697829000e0SRoman Divacky // phi translation.
2698145449b1SDimitry Andric if (Value *IV = simplifyInstruction(
2699a303c417SDimitry Andric New,
2700ac9a064cSDimitry Andric {BB->getDataLayout(), TLI, nullptr, nullptr, New})) {
2701dd58ef01SDimitry Andric ValueMapping[&*BI] = IV;
270201095a5dSDimitry Andric if (!New->mayHaveSideEffects()) {
27037fa27ce4SDimitry Andric New->eraseFromParent();
270401095a5dSDimitry Andric New = nullptr;
2705b1c73532SDimitry Andric // Clone debug-info on the elided instruction to the destination
2706b1c73532SDimitry Andric // position.
2707b1c73532SDimitry Andric OldPredBranch->cloneDebugInfoFrom(&*BI, std::nullopt, true);
270801095a5dSDimitry Andric }
2709829000e0SRoman Divacky } else {
271001095a5dSDimitry Andric ValueMapping[&*BI] = New;
271101095a5dSDimitry Andric }
271201095a5dSDimitry Andric if (New) {
2713829000e0SRoman Divacky // Otherwise, insert the new instruction into the block.
2714829000e0SRoman Divacky New->setName(BI->getName());
2715b1c73532SDimitry Andric // Clone across any debug-info attached to the old instruction.
2716b1c73532SDimitry Andric New->cloneDebugInfoFrom(&*BI);
2717eb11fae6SDimitry Andric // Update Dominance from simplified New instruction operands.
2718eb11fae6SDimitry Andric for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2719eb11fae6SDimitry Andric if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i)))
2720eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Insert, PredBB, SuccBB});
2721829000e0SRoman Divacky }
272259850d08SRoman Divacky }
272359850d08SRoman Divacky
272459850d08SRoman Divacky // Check to see if the targets of the branch had PHI nodes. If so, we need to
272559850d08SRoman Divacky // add entries to the PHI nodes for branch from PredBB now.
272659850d08SRoman Divacky BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
2727b60736ecSDimitry Andric addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
272859850d08SRoman Divacky ValueMapping);
2729b60736ecSDimitry Andric addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
273059850d08SRoman Divacky ValueMapping);
273159850d08SRoman Divacky
2732b60736ecSDimitry Andric updateSSA(BB, PredBB, ValueMapping);
273359850d08SRoman Divacky
273459850d08SRoman Divacky // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
273559850d08SRoman Divacky // that we nuked.
2736cf099d11SDimitry Andric BB->removePredecessor(PredBB, true);
273759850d08SRoman Divacky
273859850d08SRoman Divacky // Remove the unconditional branch at the end of the PredBB block.
273959850d08SRoman Divacky OldPredBranch->eraseFromParent();
27407fa27ce4SDimitry Andric if (auto *BPI = getBPI())
2741b60736ecSDimitry Andric BPI->copyEdgeProbabilities(BB, PredBB);
2742e6d15924SDimitry Andric DTU->applyUpdatesPermissive(Updates);
274359850d08SRoman Divacky
274459850d08SRoman Divacky ++NumDupes;
274559850d08SRoman Divacky return true;
274659850d08SRoman Divacky }
274759850d08SRoman Divacky
2748d8e91e46SDimitry Andric // Pred is a predecessor of BB with an unconditional branch to BB. SI is
2749d8e91e46SDimitry Andric // a Select instruction in Pred. BB has other predecessors and SI is used in
2750d8e91e46SDimitry Andric // a PHI node in BB. SI has no other use.
2751d8e91e46SDimitry Andric // A new basic block, NewBB, is created and SI is converted to compare and
2752d8e91e46SDimitry Andric // conditional branch. SI is erased from parent.
unfoldSelectInstr(BasicBlock * Pred,BasicBlock * BB,SelectInst * SI,PHINode * SIUse,unsigned Idx)2753b60736ecSDimitry Andric void JumpThreadingPass::unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB,
2754d8e91e46SDimitry Andric SelectInst *SI, PHINode *SIUse,
2755d8e91e46SDimitry Andric unsigned Idx) {
2756d8e91e46SDimitry Andric // Expand the select.
2757d8e91e46SDimitry Andric //
2758d8e91e46SDimitry Andric // Pred --
2759d8e91e46SDimitry Andric // | v
2760d8e91e46SDimitry Andric // | NewBB
2761d8e91e46SDimitry Andric // | |
2762d8e91e46SDimitry Andric // |-----
2763d8e91e46SDimitry Andric // v
2764d8e91e46SDimitry Andric // BB
27651d5ae102SDimitry Andric BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator());
2766d8e91e46SDimitry Andric BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
2767d8e91e46SDimitry Andric BB->getParent(), BB);
2768d8e91e46SDimitry Andric // Move the unconditional branch to NewBB.
2769d8e91e46SDimitry Andric PredTerm->removeFromParent();
2770e3b55780SDimitry Andric PredTerm->insertInto(NewBB, NewBB->end());
2771d8e91e46SDimitry Andric // Create a conditional branch and update PHI nodes.
2772344a3780SDimitry Andric auto *BI = BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
2773344a3780SDimitry Andric BI->applyMergedLocation(PredTerm->getDebugLoc(), SI->getDebugLoc());
2774e3b55780SDimitry Andric BI->copyMetadata(*SI, {LLVMContext::MD_prof});
2775d8e91e46SDimitry Andric SIUse->setIncomingValue(Idx, SI->getFalseValue());
2776d8e91e46SDimitry Andric SIUse->addIncoming(SI->getTrueValue(), NewBB);
27777fa27ce4SDimitry Andric
27787fa27ce4SDimitry Andric uint64_t TrueWeight = 1;
27797fa27ce4SDimitry Andric uint64_t FalseWeight = 1;
27807fa27ce4SDimitry Andric // Copy probabilities from 'SI' to created conditional branch in 'Pred'.
2781e3b55780SDimitry Andric if (extractBranchWeights(*SI, TrueWeight, FalseWeight) &&
2782e3b55780SDimitry Andric (TrueWeight + FalseWeight) != 0) {
2783e3b55780SDimitry Andric SmallVector<BranchProbability, 2> BP;
2784e3b55780SDimitry Andric BP.emplace_back(BranchProbability::getBranchProbability(
2785e3b55780SDimitry Andric TrueWeight, TrueWeight + FalseWeight));
2786e3b55780SDimitry Andric BP.emplace_back(BranchProbability::getBranchProbability(
2787e3b55780SDimitry Andric FalseWeight, TrueWeight + FalseWeight));
27887fa27ce4SDimitry Andric // Update BPI if exists.
27897fa27ce4SDimitry Andric if (auto *BPI = getBPI())
2790e3b55780SDimitry Andric BPI->setEdgeProbability(Pred, BP);
2791e3b55780SDimitry Andric }
27927fa27ce4SDimitry Andric // Set the block frequency of NewBB.
27937fa27ce4SDimitry Andric if (auto *BFI = getBFI()) {
27947fa27ce4SDimitry Andric if ((TrueWeight + FalseWeight) == 0) {
27957fa27ce4SDimitry Andric TrueWeight = 1;
27967fa27ce4SDimitry Andric FalseWeight = 1;
27977fa27ce4SDimitry Andric }
27987fa27ce4SDimitry Andric BranchProbability PredToNewBBProb = BranchProbability::getBranchProbability(
27997fa27ce4SDimitry Andric TrueWeight, TrueWeight + FalseWeight);
28007fa27ce4SDimitry Andric auto NewBBFreq = BFI->getBlockFreq(Pred) * PredToNewBBProb;
2801b1c73532SDimitry Andric BFI->setBlockFreq(NewBB, NewBBFreq);
2802e3b55780SDimitry Andric }
2803d8e91e46SDimitry Andric
2804d8e91e46SDimitry Andric // The select is now dead.
2805d8e91e46SDimitry Andric SI->eraseFromParent();
2806e6d15924SDimitry Andric DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB},
2807d8e91e46SDimitry Andric {DominatorTree::Insert, Pred, NewBB}});
2808d8e91e46SDimitry Andric
2809d8e91e46SDimitry Andric // Update any other PHI nodes in BB.
2810d8e91e46SDimitry Andric for (BasicBlock::iterator BI = BB->begin();
2811d8e91e46SDimitry Andric PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
2812d8e91e46SDimitry Andric if (Phi != SIUse)
2813d8e91e46SDimitry Andric Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
2814d8e91e46SDimitry Andric }
2815d8e91e46SDimitry Andric
tryToUnfoldSelect(SwitchInst * SI,BasicBlock * BB)2816b60736ecSDimitry Andric bool JumpThreadingPass::tryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) {
2817d8e91e46SDimitry Andric PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition());
2818d8e91e46SDimitry Andric
2819d8e91e46SDimitry Andric if (!CondPHI || CondPHI->getParent() != BB)
2820d8e91e46SDimitry Andric return false;
2821d8e91e46SDimitry Andric
2822d8e91e46SDimitry Andric for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) {
2823d8e91e46SDimitry Andric BasicBlock *Pred = CondPHI->getIncomingBlock(I);
2824d8e91e46SDimitry Andric SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I));
2825d8e91e46SDimitry Andric
2826d8e91e46SDimitry Andric // The second and third condition can be potentially relaxed. Currently
2827d8e91e46SDimitry Andric // the conditions help to simplify the code and allow us to reuse existing
2828b60736ecSDimitry Andric // code, developed for tryToUnfoldSelect(CmpInst *, BasicBlock *)
2829d8e91e46SDimitry Andric if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse())
2830d8e91e46SDimitry Andric continue;
2831d8e91e46SDimitry Andric
2832d8e91e46SDimitry Andric BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2833d8e91e46SDimitry Andric if (!PredTerm || !PredTerm->isUnconditional())
2834d8e91e46SDimitry Andric continue;
2835d8e91e46SDimitry Andric
2836b60736ecSDimitry Andric unfoldSelectInstr(Pred, BB, PredSI, CondPHI, I);
2837d8e91e46SDimitry Andric return true;
2838d8e91e46SDimitry Andric }
2839d8e91e46SDimitry Andric return false;
2840d8e91e46SDimitry Andric }
2841d8e91e46SDimitry Andric
2842b60736ecSDimitry Andric /// tryToUnfoldSelect - Look for blocks of the form
2843f8af5cf6SDimitry Andric /// bb1:
2844f8af5cf6SDimitry Andric /// %a = select
284571d5a254SDimitry Andric /// br bb2
2846f8af5cf6SDimitry Andric ///
2847f8af5cf6SDimitry Andric /// bb2:
284871d5a254SDimitry Andric /// %p = phi [%a, %bb1] ...
2849f8af5cf6SDimitry Andric /// %c = icmp %p
2850f8af5cf6SDimitry Andric /// br i1 %c
2851f8af5cf6SDimitry Andric ///
2852f8af5cf6SDimitry Andric /// And expand the select into a branch structure if one of its arms allows %c
2853f8af5cf6SDimitry Andric /// to be folded. This later enables threading from bb1 over bb2.
tryToUnfoldSelect(CmpInst * CondCmp,BasicBlock * BB)2854b60736ecSDimitry Andric bool JumpThreadingPass::tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
2855f8af5cf6SDimitry Andric BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2856f8af5cf6SDimitry Andric PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
2857f8af5cf6SDimitry Andric Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
285859850d08SRoman Divacky
2859f8af5cf6SDimitry Andric if (!CondBr || !CondBr->isConditional() || !CondLHS ||
2860f8af5cf6SDimitry Andric CondLHS->getParent() != BB)
2861f8af5cf6SDimitry Andric return false;
2862f8af5cf6SDimitry Andric
2863f8af5cf6SDimitry Andric for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
2864f8af5cf6SDimitry Andric BasicBlock *Pred = CondLHS->getIncomingBlock(I);
2865f8af5cf6SDimitry Andric SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
2866f8af5cf6SDimitry Andric
2867f8af5cf6SDimitry Andric // Look if one of the incoming values is a select in the corresponding
2868f8af5cf6SDimitry Andric // predecessor.
2869f8af5cf6SDimitry Andric if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
2870f8af5cf6SDimitry Andric continue;
2871f8af5cf6SDimitry Andric
2872f8af5cf6SDimitry Andric BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2873f8af5cf6SDimitry Andric if (!PredTerm || !PredTerm->isUnconditional())
2874f8af5cf6SDimitry Andric continue;
2875f8af5cf6SDimitry Andric
2876f8af5cf6SDimitry Andric // Now check if one of the select values would allow us to constant fold the
2877f8af5cf6SDimitry Andric // terminator in BB. We don't do the transform if both sides fold, those
2878f8af5cf6SDimitry Andric // cases will be threaded in any case.
2879ac9a064cSDimitry Andric Constant *LHSRes =
2880f8af5cf6SDimitry Andric LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
288167c32a98SDimitry Andric CondRHS, Pred, BB, CondCmp);
2882ac9a064cSDimitry Andric Constant *RHSRes =
2883f8af5cf6SDimitry Andric LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
288467c32a98SDimitry Andric CondRHS, Pred, BB, CondCmp);
2885ac9a064cSDimitry Andric if ((LHSRes || RHSRes) && LHSRes != RHSRes) {
2886b60736ecSDimitry Andric unfoldSelectInstr(Pred, BB, SI, CondLHS, I);
2887f8af5cf6SDimitry Andric return true;
2888f8af5cf6SDimitry Andric }
2889f8af5cf6SDimitry Andric }
2890f8af5cf6SDimitry Andric return false;
2891f8af5cf6SDimitry Andric }
2892050e163aSDimitry Andric
2893b60736ecSDimitry Andric /// tryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the
289493c91e39SDimitry Andric /// same BB in the form
2895050e163aSDimitry Andric /// bb:
2896050e163aSDimitry Andric /// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
289793c91e39SDimitry Andric /// %s = select %p, trueval, falseval
2898050e163aSDimitry Andric ///
289993c91e39SDimitry Andric /// or
290093c91e39SDimitry Andric ///
290193c91e39SDimitry Andric /// bb:
290293c91e39SDimitry Andric /// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ...
290393c91e39SDimitry Andric /// %c = cmp %p, 0
290493c91e39SDimitry Andric /// %s = select %c, trueval, falseval
2905044eb2f6SDimitry Andric ///
2906050e163aSDimitry Andric /// And expand the select into a branch structure. This later enables
2907050e163aSDimitry Andric /// jump-threading over bb in this pass.
2908050e163aSDimitry Andric ///
2909050e163aSDimitry Andric /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
2910050e163aSDimitry Andric /// select if the associated PHI has at least one constant. If the unfolded
2911050e163aSDimitry Andric /// select is not jump-threaded, it will be folded again in the later
2912050e163aSDimitry Andric /// optimizations.
tryToUnfoldSelectInCurrBB(BasicBlock * BB)2913b60736ecSDimitry Andric bool JumpThreadingPass::tryToUnfoldSelectInCurrBB(BasicBlock *BB) {
2914b60736ecSDimitry Andric // This transform would reduce the quality of msan diagnostics.
2915cfca06d7SDimitry Andric // Disable this transform under MemorySanitizer.
2916cfca06d7SDimitry Andric if (BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory))
2917cfca06d7SDimitry Andric return false;
2918cfca06d7SDimitry Andric
2919050e163aSDimitry Andric // If threading this would thread across a loop header, don't thread the edge.
2920b60736ecSDimitry Andric // See the comments above findLoopHeaders for justifications and caveats.
2921050e163aSDimitry Andric if (LoopHeaders.count(BB))
2922050e163aSDimitry Andric return false;
2923050e163aSDimitry Andric
2924050e163aSDimitry Andric for (BasicBlock::iterator BI = BB->begin();
2925050e163aSDimitry Andric PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
292693c91e39SDimitry Andric // Look for a Phi having at least one constant incoming value.
292793c91e39SDimitry Andric if (llvm::all_of(PN->incoming_values(),
292893c91e39SDimitry Andric [](Value *V) { return !isa<ConstantInt>(V); }))
2929050e163aSDimitry Andric continue;
2930050e163aSDimitry Andric
293193c91e39SDimitry Andric auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) {
2932344a3780SDimitry Andric using namespace PatternMatch;
2933344a3780SDimitry Andric
293493c91e39SDimitry Andric // Check if SI is in BB and use V as condition.
293593c91e39SDimitry Andric if (SI->getParent() != BB)
2936050e163aSDimitry Andric return false;
293793c91e39SDimitry Andric Value *Cond = SI->getCondition();
2938344a3780SDimitry Andric bool IsAndOr = match(SI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()));
2939344a3780SDimitry Andric return Cond && Cond == V && Cond->getType()->isIntegerTy(1) && !IsAndOr;
294093c91e39SDimitry Andric };
294193c91e39SDimitry Andric
294293c91e39SDimitry Andric SelectInst *SI = nullptr;
294393c91e39SDimitry Andric for (Use &U : PN->uses()) {
294493c91e39SDimitry Andric if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
294593c91e39SDimitry Andric // Look for a ICmp in BB that compares PN with a constant and is the
294693c91e39SDimitry Andric // condition of a Select.
294793c91e39SDimitry Andric if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
294893c91e39SDimitry Andric isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
294993c91e39SDimitry Andric if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
295093c91e39SDimitry Andric if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
295193c91e39SDimitry Andric SI = SelectI;
295293c91e39SDimitry Andric break;
295393c91e39SDimitry Andric }
295493c91e39SDimitry Andric } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
2955eb11fae6SDimitry Andric // Look for a Select in BB that uses PN as condition.
295693c91e39SDimitry Andric if (isUnfoldCandidate(SelectI, U.get())) {
295793c91e39SDimitry Andric SI = SelectI;
295893c91e39SDimitry Andric break;
295993c91e39SDimitry Andric }
296093c91e39SDimitry Andric }
2961050e163aSDimitry Andric }
2962050e163aSDimitry Andric
296393c91e39SDimitry Andric if (!SI)
296493c91e39SDimitry Andric continue;
2965050e163aSDimitry Andric // Expand the select.
2966b60736ecSDimitry Andric Value *Cond = SI->getCondition();
2967145449b1SDimitry Andric if (!isGuaranteedNotToBeUndefOrPoison(Cond, nullptr, SI))
2968ac9a064cSDimitry Andric Cond = new FreezeInst(Cond, "cond.fr", SI->getIterator());
2969b1c73532SDimitry Andric MDNode *BranchWeights = getBranchWeightMDNode(*SI);
2970b1c73532SDimitry Andric Instruction *Term =
2971b1c73532SDimitry Andric SplitBlockAndInsertIfThen(Cond, SI, false, BranchWeights);
2972eb11fae6SDimitry Andric BasicBlock *SplitBB = SI->getParent();
2973eb11fae6SDimitry Andric BasicBlock *NewBB = Term->getParent();
2974ac9a064cSDimitry Andric PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI->getIterator());
2975050e163aSDimitry Andric NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
2976050e163aSDimitry Andric NewPN->addIncoming(SI->getFalseValue(), BB);
2977ac9a064cSDimitry Andric NewPN->setDebugLoc(SI->getDebugLoc());
2978050e163aSDimitry Andric SI->replaceAllUsesWith(NewPN);
2979050e163aSDimitry Andric SI->eraseFromParent();
2980eb11fae6SDimitry Andric // NewBB and SplitBB are newly created blocks which require insertion.
2981eb11fae6SDimitry Andric std::vector<DominatorTree::UpdateType> Updates;
2982eb11fae6SDimitry Andric Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
2983eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Insert, BB, SplitBB});
2984eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Insert, BB, NewBB});
2985eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Insert, NewBB, SplitBB});
2986d8e91e46SDimitry Andric // BB's successors were moved to SplitBB, update DTU accordingly.
2987eb11fae6SDimitry Andric for (auto *Succ : successors(SplitBB)) {
2988eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Delete, BB, Succ});
2989eb11fae6SDimitry Andric Updates.push_back({DominatorTree::Insert, SplitBB, Succ});
2990eb11fae6SDimitry Andric }
2991e6d15924SDimitry Andric DTU->applyUpdatesPermissive(Updates);
2992050e163aSDimitry Andric return true;
2993050e163aSDimitry Andric }
2994050e163aSDimitry Andric return false;
2995050e163aSDimitry Andric }
299671d5a254SDimitry Andric
299771d5a254SDimitry Andric /// Try to propagate a guard from the current BB into one of its predecessors
299871d5a254SDimitry Andric /// in case if another branch of execution implies that the condition of this
299971d5a254SDimitry Andric /// guard is always true. Currently we only process the simplest case that
300071d5a254SDimitry Andric /// looks like:
300171d5a254SDimitry Andric ///
300271d5a254SDimitry Andric /// Start:
300371d5a254SDimitry Andric /// %cond = ...
300471d5a254SDimitry Andric /// br i1 %cond, label %T1, label %F1
300571d5a254SDimitry Andric /// T1:
300671d5a254SDimitry Andric /// br label %Merge
300771d5a254SDimitry Andric /// F1:
300871d5a254SDimitry Andric /// br label %Merge
300971d5a254SDimitry Andric /// Merge:
301071d5a254SDimitry Andric /// %condGuard = ...
301171d5a254SDimitry Andric /// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ]
301271d5a254SDimitry Andric ///
301371d5a254SDimitry Andric /// And cond either implies condGuard or !condGuard. In this case all the
301471d5a254SDimitry Andric /// instructions before the guard can be duplicated in both branches, and the
301571d5a254SDimitry Andric /// guard is then threaded to one of them.
processGuards(BasicBlock * BB)3016b60736ecSDimitry Andric bool JumpThreadingPass::processGuards(BasicBlock *BB) {
301771d5a254SDimitry Andric using namespace PatternMatch;
3018044eb2f6SDimitry Andric
301971d5a254SDimitry Andric // We only want to deal with two predecessors.
302071d5a254SDimitry Andric BasicBlock *Pred1, *Pred2;
302171d5a254SDimitry Andric auto PI = pred_begin(BB), PE = pred_end(BB);
302271d5a254SDimitry Andric if (PI == PE)
302371d5a254SDimitry Andric return false;
302471d5a254SDimitry Andric Pred1 = *PI++;
302571d5a254SDimitry Andric if (PI == PE)
302671d5a254SDimitry Andric return false;
302771d5a254SDimitry Andric Pred2 = *PI++;
302871d5a254SDimitry Andric if (PI != PE)
302971d5a254SDimitry Andric return false;
303071d5a254SDimitry Andric if (Pred1 == Pred2)
303171d5a254SDimitry Andric return false;
303271d5a254SDimitry Andric
303371d5a254SDimitry Andric // Try to thread one of the guards of the block.
303471d5a254SDimitry Andric // TODO: Look up deeper than to immediate predecessor?
303571d5a254SDimitry Andric auto *Parent = Pred1->getSinglePredecessor();
303671d5a254SDimitry Andric if (!Parent || Parent != Pred2->getSinglePredecessor())
303771d5a254SDimitry Andric return false;
303871d5a254SDimitry Andric
303971d5a254SDimitry Andric if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
304071d5a254SDimitry Andric for (auto &I : *BB)
3041b60736ecSDimitry Andric if (isGuard(&I) && threadGuard(BB, cast<IntrinsicInst>(&I), BI))
304271d5a254SDimitry Andric return true;
304371d5a254SDimitry Andric
304471d5a254SDimitry Andric return false;
304571d5a254SDimitry Andric }
304671d5a254SDimitry Andric
304771d5a254SDimitry Andric /// Try to propagate the guard from BB which is the lower block of a diamond
304871d5a254SDimitry Andric /// to one of its branches, in case if diamond's condition implies guard's
304971d5a254SDimitry Andric /// condition.
threadGuard(BasicBlock * BB,IntrinsicInst * Guard,BranchInst * BI)3050b60736ecSDimitry Andric bool JumpThreadingPass::threadGuard(BasicBlock *BB, IntrinsicInst *Guard,
305171d5a254SDimitry Andric BranchInst *BI) {
305271d5a254SDimitry Andric assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?");
305371d5a254SDimitry Andric assert(BI->isConditional() && "Unconditional branch has 2 successors?");
305471d5a254SDimitry Andric Value *GuardCond = Guard->getArgOperand(0);
305571d5a254SDimitry Andric Value *BranchCond = BI->getCondition();
305671d5a254SDimitry Andric BasicBlock *TrueDest = BI->getSuccessor(0);
305771d5a254SDimitry Andric BasicBlock *FalseDest = BI->getSuccessor(1);
305871d5a254SDimitry Andric
3059ac9a064cSDimitry Andric auto &DL = BB->getDataLayout();
306071d5a254SDimitry Andric bool TrueDestIsSafe = false;
306171d5a254SDimitry Andric bool FalseDestIsSafe = false;
306271d5a254SDimitry Andric
306371d5a254SDimitry Andric // True dest is safe if BranchCond => GuardCond.
306471d5a254SDimitry Andric auto Impl = isImpliedCondition(BranchCond, GuardCond, DL);
306571d5a254SDimitry Andric if (Impl && *Impl)
306671d5a254SDimitry Andric TrueDestIsSafe = true;
306771d5a254SDimitry Andric else {
306871d5a254SDimitry Andric // False dest is safe if !BranchCond => GuardCond.
3069044eb2f6SDimitry Andric Impl = isImpliedCondition(BranchCond, GuardCond, DL, /* LHSIsTrue */ false);
307071d5a254SDimitry Andric if (Impl && *Impl)
307171d5a254SDimitry Andric FalseDestIsSafe = true;
307271d5a254SDimitry Andric }
307371d5a254SDimitry Andric
307471d5a254SDimitry Andric if (!TrueDestIsSafe && !FalseDestIsSafe)
307571d5a254SDimitry Andric return false;
307671d5a254SDimitry Andric
3077eb11fae6SDimitry Andric BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
3078eb11fae6SDimitry Andric BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
307971d5a254SDimitry Andric
308071d5a254SDimitry Andric ValueToValueMapTy UnguardedMapping, GuardedMapping;
308171d5a254SDimitry Andric Instruction *AfterGuard = Guard->getNextNode();
3082c0981da4SDimitry Andric unsigned Cost =
3083c0981da4SDimitry Andric getJumpThreadDuplicationCost(TTI, BB, AfterGuard, BBDupThreshold);
308471d5a254SDimitry Andric if (Cost > BBDupThreshold)
308571d5a254SDimitry Andric return false;
308671d5a254SDimitry Andric // Duplicate all instructions before the guard and the guard itself to the
308771d5a254SDimitry Andric // branch where implication is not proved.
3088eb11fae6SDimitry Andric BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween(
3089d8e91e46SDimitry Andric BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU);
309071d5a254SDimitry Andric assert(GuardedBlock && "Could not create the guarded block?");
309171d5a254SDimitry Andric // Duplicate all instructions before the guard in the unguarded branch.
309271d5a254SDimitry Andric // Since we have successfully duplicated the guarded block and this block
309371d5a254SDimitry Andric // has fewer instructions, we expect it to succeed.
3094eb11fae6SDimitry Andric BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween(
3095d8e91e46SDimitry Andric BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU);
309671d5a254SDimitry Andric assert(UnguardedBlock && "Could not create the unguarded block?");
3097eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block "
309871d5a254SDimitry Andric << GuardedBlock->getName() << "\n");
309971d5a254SDimitry Andric // Some instructions before the guard may still have uses. For them, we need
310071d5a254SDimitry Andric // to create Phi nodes merging their copies in both guarded and unguarded
310171d5a254SDimitry Andric // branches. Those instructions that have no uses can be just removed.
310271d5a254SDimitry Andric SmallVector<Instruction *, 4> ToRemove;
310371d5a254SDimitry Andric for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
310471d5a254SDimitry Andric if (!isa<PHINode>(&*BI))
310571d5a254SDimitry Andric ToRemove.push_back(&*BI);
310671d5a254SDimitry Andric
3107b1c73532SDimitry Andric BasicBlock::iterator InsertionPoint = BB->getFirstInsertionPt();
3108b1c73532SDimitry Andric assert(InsertionPoint != BB->end() && "Empty block?");
310971d5a254SDimitry Andric // Substitute with Phis & remove.
311071d5a254SDimitry Andric for (auto *Inst : reverse(ToRemove)) {
311171d5a254SDimitry Andric if (!Inst->use_empty()) {
311271d5a254SDimitry Andric PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
311371d5a254SDimitry Andric NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
311471d5a254SDimitry Andric NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
3115ac9a064cSDimitry Andric NewPN->setDebugLoc(Inst->getDebugLoc());
311671d5a254SDimitry Andric NewPN->insertBefore(InsertionPoint);
311771d5a254SDimitry Andric Inst->replaceAllUsesWith(NewPN);
311871d5a254SDimitry Andric }
3119ac9a064cSDimitry Andric Inst->dropDbgRecords();
312071d5a254SDimitry Andric Inst->eraseFromParent();
312171d5a254SDimitry Andric }
312271d5a254SDimitry Andric return true;
312371d5a254SDimitry Andric }
31247fa27ce4SDimitry Andric
getPreservedAnalysis() const31257fa27ce4SDimitry Andric PreservedAnalyses JumpThreadingPass::getPreservedAnalysis() const {
31267fa27ce4SDimitry Andric PreservedAnalyses PA;
31277fa27ce4SDimitry Andric PA.preserve<LazyValueAnalysis>();
31287fa27ce4SDimitry Andric PA.preserve<DominatorTreeAnalysis>();
31297fa27ce4SDimitry Andric
31307fa27ce4SDimitry Andric // TODO: We would like to preserve BPI/BFI. Enable once all paths update them.
31317fa27ce4SDimitry Andric // TODO: Would be nice to verify BPI/BFI consistency as well.
31327fa27ce4SDimitry Andric return PA;
31337fa27ce4SDimitry Andric }
31347fa27ce4SDimitry Andric
31357fa27ce4SDimitry Andric template <typename AnalysisT>
runExternalAnalysis()31367fa27ce4SDimitry Andric typename AnalysisT::Result *JumpThreadingPass::runExternalAnalysis() {
31377fa27ce4SDimitry Andric assert(FAM && "Can't run external analysis without FunctionAnalysisManager");
31387fa27ce4SDimitry Andric
31397fa27ce4SDimitry Andric // If there were no changes since last call to 'runExternalAnalysis' then all
31407fa27ce4SDimitry Andric // analysis is either up to date or explicitly invalidated. Just go ahead and
31417fa27ce4SDimitry Andric // run the "external" analysis.
31427fa27ce4SDimitry Andric if (!ChangedSinceLastAnalysisUpdate) {
31437fa27ce4SDimitry Andric assert(!DTU->hasPendingUpdates() &&
31447fa27ce4SDimitry Andric "Lost update of 'ChangedSinceLastAnalysisUpdate'?");
31457fa27ce4SDimitry Andric // Run the "external" analysis.
31467fa27ce4SDimitry Andric return &FAM->getResult<AnalysisT>(*F);
31477fa27ce4SDimitry Andric }
31487fa27ce4SDimitry Andric ChangedSinceLastAnalysisUpdate = false;
31497fa27ce4SDimitry Andric
31507fa27ce4SDimitry Andric auto PA = getPreservedAnalysis();
31517fa27ce4SDimitry Andric // TODO: This shouldn't be needed once 'getPreservedAnalysis' reports BPI/BFI
31527fa27ce4SDimitry Andric // as preserved.
31537fa27ce4SDimitry Andric PA.preserve<BranchProbabilityAnalysis>();
31547fa27ce4SDimitry Andric PA.preserve<BlockFrequencyAnalysis>();
31557fa27ce4SDimitry Andric // Report everything except explicitly preserved as invalid.
31567fa27ce4SDimitry Andric FAM->invalidate(*F, PA);
31577fa27ce4SDimitry Andric // Update DT/PDT.
31587fa27ce4SDimitry Andric DTU->flush();
31597fa27ce4SDimitry Andric // Make sure DT/PDT are valid before running "external" analysis.
31607fa27ce4SDimitry Andric assert(DTU->getDomTree().verify(DominatorTree::VerificationLevel::Fast));
31617fa27ce4SDimitry Andric assert((!DTU->hasPostDomTree() ||
31627fa27ce4SDimitry Andric DTU->getPostDomTree().verify(
31637fa27ce4SDimitry Andric PostDominatorTree::VerificationLevel::Fast)));
31647fa27ce4SDimitry Andric // Run the "external" analysis.
31657fa27ce4SDimitry Andric auto *Result = &FAM->getResult<AnalysisT>(*F);
31667fa27ce4SDimitry Andric // Update analysis JumpThreading depends on and not explicitly preserved.
31677fa27ce4SDimitry Andric TTI = &FAM->getResult<TargetIRAnalysis>(*F);
31687fa27ce4SDimitry Andric TLI = &FAM->getResult<TargetLibraryAnalysis>(*F);
31697fa27ce4SDimitry Andric AA = &FAM->getResult<AAManager>(*F);
31707fa27ce4SDimitry Andric
31717fa27ce4SDimitry Andric return Result;
31727fa27ce4SDimitry Andric }
31737fa27ce4SDimitry Andric
getBPI()31747fa27ce4SDimitry Andric BranchProbabilityInfo *JumpThreadingPass::getBPI() {
31757fa27ce4SDimitry Andric if (!BPI) {
31767fa27ce4SDimitry Andric assert(FAM && "Can't create BPI without FunctionAnalysisManager");
31777fa27ce4SDimitry Andric BPI = FAM->getCachedResult<BranchProbabilityAnalysis>(*F);
31787fa27ce4SDimitry Andric }
31797fa27ce4SDimitry Andric return *BPI;
31807fa27ce4SDimitry Andric }
31817fa27ce4SDimitry Andric
getBFI()31827fa27ce4SDimitry Andric BlockFrequencyInfo *JumpThreadingPass::getBFI() {
31837fa27ce4SDimitry Andric if (!BFI) {
31847fa27ce4SDimitry Andric assert(FAM && "Can't create BFI without FunctionAnalysisManager");
31857fa27ce4SDimitry Andric BFI = FAM->getCachedResult<BlockFrequencyAnalysis>(*F);
31867fa27ce4SDimitry Andric }
31877fa27ce4SDimitry Andric return *BFI;
31887fa27ce4SDimitry Andric }
31897fa27ce4SDimitry Andric
31907fa27ce4SDimitry Andric // Important note on validity of BPI/BFI. JumpThreading tries to preserve
31917fa27ce4SDimitry Andric // BPI/BFI as it goes. Thus if cached instance exists it will be updated.
31927fa27ce4SDimitry Andric // Otherwise, new instance of BPI/BFI is created (up to date by definition).
getOrCreateBPI(bool Force)31937fa27ce4SDimitry Andric BranchProbabilityInfo *JumpThreadingPass::getOrCreateBPI(bool Force) {
31947fa27ce4SDimitry Andric auto *Res = getBPI();
31957fa27ce4SDimitry Andric if (Res)
31967fa27ce4SDimitry Andric return Res;
31977fa27ce4SDimitry Andric
31987fa27ce4SDimitry Andric if (Force)
31997fa27ce4SDimitry Andric BPI = runExternalAnalysis<BranchProbabilityAnalysis>();
32007fa27ce4SDimitry Andric
32017fa27ce4SDimitry Andric return *BPI;
32027fa27ce4SDimitry Andric }
32037fa27ce4SDimitry Andric
getOrCreateBFI(bool Force)32047fa27ce4SDimitry Andric BlockFrequencyInfo *JumpThreadingPass::getOrCreateBFI(bool Force) {
32057fa27ce4SDimitry Andric auto *Res = getBFI();
32067fa27ce4SDimitry Andric if (Res)
32077fa27ce4SDimitry Andric return Res;
32087fa27ce4SDimitry Andric
32097fa27ce4SDimitry Andric if (Force)
32107fa27ce4SDimitry Andric BFI = runExternalAnalysis<BlockFrequencyAnalysis>();
32117fa27ce4SDimitry Andric
32127fa27ce4SDimitry Andric return *BFI;
32137fa27ce4SDimitry Andric }
3214