Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/Transforms/Scalar/JumpThreading.cpp
Warning:line 1452, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name JumpThreading.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/Transforms/Scalar -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/Transforms/Scalar/JumpThreading.cpp
1//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Jump Threading pass.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Transforms/Scalar/JumpThreading.h"
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/Optional.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
25#include "llvm/Analysis/CFG.h"
26#include "llvm/Analysis/ConstantFolding.h"
27#include "llvm/Analysis/DomTreeUpdater.h"
28#include "llvm/Analysis/GlobalsModRef.h"
29#include "llvm/Analysis/GuardUtils.h"
30#include "llvm/Analysis/InstructionSimplify.h"
31#include "llvm/Analysis/LazyValueInfo.h"
32#include "llvm/Analysis/Loads.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/Analysis/MemoryLocation.h"
35#include "llvm/Analysis/TargetLibraryInfo.h"
36#include "llvm/Analysis/TargetTransformInfo.h"
37#include "llvm/Analysis/ValueTracking.h"
38#include "llvm/IR/BasicBlock.h"
39#include "llvm/IR/CFG.h"
40#include "llvm/IR/Constant.h"
41#include "llvm/IR/ConstantRange.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/Dominators.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/InstrTypes.h"
47#include "llvm/IR/Instruction.h"
48#include "llvm/IR/Instructions.h"
49#include "llvm/IR/IntrinsicInst.h"
50#include "llvm/IR/Intrinsics.h"
51#include "llvm/IR/LLVMContext.h"
52#include "llvm/IR/MDBuilder.h"
53#include "llvm/IR/Metadata.h"
54#include "llvm/IR/Module.h"
55#include "llvm/IR/PassManager.h"
56#include "llvm/IR/PatternMatch.h"
57#include "llvm/IR/ProfDataUtils.h"
58#include "llvm/IR/Type.h"
59#include "llvm/IR/Use.h"
60#include "llvm/IR/Value.h"
61#include "llvm/InitializePasses.h"
62#include "llvm/Pass.h"
63#include "llvm/Support/BlockFrequency.h"
64#include "llvm/Support/BranchProbability.h"
65#include "llvm/Support/Casting.h"
66#include "llvm/Support/CommandLine.h"
67#include "llvm/Support/Debug.h"
68#include "llvm/Support/raw_ostream.h"
69#include "llvm/Transforms/Scalar.h"
70#include "llvm/Transforms/Utils/BasicBlockUtils.h"
71#include "llvm/Transforms/Utils/Cloning.h"
72#include "llvm/Transforms/Utils/Local.h"
73#include "llvm/Transforms/Utils/SSAUpdater.h"
74#include "llvm/Transforms/Utils/ValueMapper.h"
75#include <algorithm>
76#include <cassert>
77#include <cstdint>
78#include <iterator>
79#include <memory>
80#include <utility>
81
82using namespace llvm;
83using namespace jumpthreading;
84
85#define DEBUG_TYPE"jump-threading" "jump-threading"
86
87STATISTIC(NumThreads, "Number of jumps threaded")static llvm::Statistic NumThreads = {"jump-threading", "NumThreads"
, "Number of jumps threaded"}
;
88STATISTIC(NumFolds, "Number of terminators folded")static llvm::Statistic NumFolds = {"jump-threading", "NumFolds"
, "Number of terminators folded"}
;
89STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi")static llvm::Statistic NumDupes = {"jump-threading", "NumDupes"
, "Number of branch blocks duplicated to eliminate phi"}
;
90
91static cl::opt<unsigned>
92BBDuplicateThreshold("jump-threading-threshold",
93 cl::desc("Max block size to duplicate for jump threading"),
94 cl::init(6), cl::Hidden);
95
96static cl::opt<unsigned>
97ImplicationSearchThreshold(
98 "jump-threading-implication-search-threshold",
99 cl::desc("The number of predecessors to search for a stronger "
100 "condition to use to thread over a weaker condition"),
101 cl::init(3), cl::Hidden);
102
103static cl::opt<bool> PrintLVIAfterJumpThreading(
104 "print-lvi-after-jump-threading",
105 cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false),
106 cl::Hidden);
107
108static cl::opt<bool> ThreadAcrossLoopHeaders(
109 "jump-threading-across-loop-headers",
110 cl::desc("Allow JumpThreading to thread across loop headers, for testing"),
111 cl::init(false), cl::Hidden);
112
113
114namespace {
115
116 /// This pass performs 'jump threading', which looks at blocks that have
117 /// multiple predecessors and multiple successors. If one or more of the
118 /// predecessors of the block can be proven to always jump to one of the
119 /// successors, we forward the edge from the predecessor to the successor by
120 /// duplicating the contents of this block.
121 ///
122 /// An example of when this can occur is code like this:
123 ///
124 /// if () { ...
125 /// X = 4;
126 /// }
127 /// if (X < 3) {
128 ///
129 /// In this case, the unconditional branch at the end of the first if can be
130 /// revectored to the false side of the second if.
131 class JumpThreading : public FunctionPass {
132 JumpThreadingPass Impl;
133
134 public:
135 static char ID; // Pass identification
136
137 JumpThreading(int T = -1) : FunctionPass(ID), Impl(T) {
138 initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
139 }
140
141 bool runOnFunction(Function &F) override;
142
143 void getAnalysisUsage(AnalysisUsage &AU) const override {
144 AU.addRequired<DominatorTreeWrapperPass>();
145 AU.addPreserved<DominatorTreeWrapperPass>();
146 AU.addRequired<AAResultsWrapperPass>();
147 AU.addRequired<LazyValueInfoWrapperPass>();
148 AU.addPreserved<LazyValueInfoWrapperPass>();
149 AU.addPreserved<GlobalsAAWrapperPass>();
150 AU.addRequired<TargetLibraryInfoWrapperPass>();
151 AU.addRequired<TargetTransformInfoWrapperPass>();
152 }
153
154 void releaseMemory() override { Impl.releaseMemory(); }
155 };
156
157} // end anonymous namespace
158
159char JumpThreading::ID = 0;
160
161INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",static void *initializeJumpThreadingPassOnce(PassRegistry &
Registry) {
162 "Jump Threading", false, false)static void *initializeJumpThreadingPassOnce(PassRegistry &
Registry) {
163INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
164INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)initializeLazyValueInfoWrapperPassPass(Registry);
165INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
166INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry);
167INITIALIZE_PASS_END(JumpThreading, "jump-threading",PassInfo *PI = new PassInfo( "Jump Threading", "jump-threading"
, &JumpThreading::ID, PassInfo::NormalCtor_t(callDefaultCtor
<JumpThreading>), false, false); Registry.registerPass(
*PI, true); return PI; } static llvm::once_flag InitializeJumpThreadingPassFlag
; void llvm::initializeJumpThreadingPass(PassRegistry &Registry
) { llvm::call_once(InitializeJumpThreadingPassFlag, initializeJumpThreadingPassOnce
, std::ref(Registry)); }
168 "Jump Threading", false, false)PassInfo *PI = new PassInfo( "Jump Threading", "jump-threading"
, &JumpThreading::ID, PassInfo::NormalCtor_t(callDefaultCtor
<JumpThreading>), false, false); Registry.registerPass(
*PI, true); return PI; } static llvm::once_flag InitializeJumpThreadingPassFlag
; void llvm::initializeJumpThreadingPass(PassRegistry &Registry
) { llvm::call_once(InitializeJumpThreadingPassFlag, initializeJumpThreadingPassOnce
, std::ref(Registry)); }
169
170// Public interface to the Jump Threading pass
171FunctionPass *llvm::createJumpThreadingPass(int Threshold) {
172 return new JumpThreading(Threshold);
173}
174
175JumpThreadingPass::JumpThreadingPass(int T) {
176 DefaultBBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
177}
178
179// Update branch probability information according to conditional
180// branch probability. This is usually made possible for cloned branches
181// in inline instances by the context specific profile in the caller.
182// For instance,
183//
184// [Block PredBB]
185// [Branch PredBr]
186// if (t) {
187// Block A;
188// } else {
189// Block B;
190// }
191//
192// [Block BB]
193// cond = PN([true, %A], [..., %B]); // PHI node
194// [Branch CondBr]
195// if (cond) {
196// ... // P(cond == true) = 1%
197// }
198//
199// Here we know that when block A is taken, cond must be true, which means
200// P(cond == true | A) = 1
201//
202// Given that P(cond == true) = P(cond == true | A) * P(A) +
203// P(cond == true | B) * P(B)
204// we get:
205// P(cond == true ) = P(A) + P(cond == true | B) * P(B)
206//
207// which gives us:
208// P(A) is less than P(cond == true), i.e.
209// P(t == true) <= P(cond == true)
210//
211// In other words, if we know P(cond == true) is unlikely, we know
212// that P(t == true) is also unlikely.
213//
214static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) {
215 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
216 if (!CondBr)
217 return;
218
219 uint64_t TrueWeight, FalseWeight;
220 if (!extractBranchWeights(*CondBr, TrueWeight, FalseWeight))
221 return;
222
223 if (TrueWeight + FalseWeight == 0)
224 // Zero branch_weights do not give a hint for getting branch probabilities.
225 // Technically it would result in division by zero denominator, which is
226 // TrueWeight + FalseWeight.
227 return;
228
229 // Returns the outgoing edge of the dominating predecessor block
230 // that leads to the PhiNode's incoming block:
231 auto GetPredOutEdge =
232 [](BasicBlock *IncomingBB,
233 BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
234 auto *PredBB = IncomingBB;
235 auto *SuccBB = PhiBB;
236 SmallPtrSet<BasicBlock *, 16> Visited;
237 while (true) {
238 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
239 if (PredBr && PredBr->isConditional())
240 return {PredBB, SuccBB};
241 Visited.insert(PredBB);
242 auto *SinglePredBB = PredBB->getSinglePredecessor();
243 if (!SinglePredBB)
244 return {nullptr, nullptr};
245
246 // Stop searching when SinglePredBB has been visited. It means we see
247 // an unreachable loop.
248 if (Visited.count(SinglePredBB))
249 return {nullptr, nullptr};
250
251 SuccBB = PredBB;
252 PredBB = SinglePredBB;
253 }
254 };
255
256 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
257 Value *PhiOpnd = PN->getIncomingValue(i);
258 ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
259
260 if (!CI || !CI->getType()->isIntegerTy(1))
261 continue;
262
263 BranchProbability BP =
264 (CI->isOne() ? BranchProbability::getBranchProbability(
265 TrueWeight, TrueWeight + FalseWeight)
266 : BranchProbability::getBranchProbability(
267 FalseWeight, TrueWeight + FalseWeight));
268
269 auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB);
270 if (!PredOutEdge.first)
271 return;
272
273 BasicBlock *PredBB = PredOutEdge.first;
274 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
275 if (!PredBr)
276 return;
277
278 uint64_t PredTrueWeight, PredFalseWeight;
279 // FIXME: We currently only set the profile data when it is missing.
280 // With PGO, this can be used to refine even existing profile data with
281 // context information. This needs to be done after more performance
282 // testing.
283 if (extractBranchWeights(*PredBr, PredTrueWeight, PredFalseWeight))
284 continue;
285
286 // We can not infer anything useful when BP >= 50%, because BP is the
287 // upper bound probability value.
288 if (BP >= BranchProbability(50, 100))
289 continue;
290
291 SmallVector<uint32_t, 2> Weights;
292 if (PredBr->getSuccessor(0) == PredOutEdge.second) {
293 Weights.push_back(BP.getNumerator());
294 Weights.push_back(BP.getCompl().getNumerator());
295 } else {
296 Weights.push_back(BP.getCompl().getNumerator());
297 Weights.push_back(BP.getNumerator());
298 }
299 PredBr->setMetadata(LLVMContext::MD_prof,
300 MDBuilder(PredBr->getParent()->getContext())
301 .createBranchWeights(Weights));
302 }
303}
304
305/// runOnFunction - Toplevel algorithm.
306bool JumpThreading::runOnFunction(Function &F) {
307 if (skipFunction(F))
308 return false;
309 auto TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
310 // Jump Threading has no sense for the targets with divergent CF
311 if (TTI->hasBranchDivergence())
312 return false;
313 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
314 auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
315 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
316 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
317 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
318 std::unique_ptr<BlockFrequencyInfo> BFI;
319 std::unique_ptr<BranchProbabilityInfo> BPI;
320 if (F.hasProfileData()) {
321 LoopInfo LI{*DT};
322 BPI.reset(new BranchProbabilityInfo(F, LI, TLI));
323 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
324 }
325
326 bool Changed = Impl.runImpl(F, TLI, TTI, LVI, AA, &DTU, F.hasProfileData(),
327 std::move(BFI), std::move(BPI));
328 if (PrintLVIAfterJumpThreading) {
329 dbgs() << "LVI for function '" << F.getName() << "':\n";
330 LVI->printLVI(F, DTU.getDomTree(), dbgs());
331 }
332 return Changed;
333}
334
335PreservedAnalyses JumpThreadingPass::run(Function &F,
336 FunctionAnalysisManager &AM) {
337 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
338 // Jump Threading has no sense for the targets with divergent CF
339 if (TTI.hasBranchDivergence())
340 return PreservedAnalyses::all();
341 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
342 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
343 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
344 auto &AA = AM.getResult<AAManager>(F);
345 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
346
347 std::unique_ptr<BlockFrequencyInfo> BFI;
348 std::unique_ptr<BranchProbabilityInfo> BPI;
349 if (F.hasProfileData()) {
350 LoopInfo LI{DominatorTree(F)};
351 BPI.reset(new BranchProbabilityInfo(F, LI, &TLI));
352 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
353 }
354
355 bool Changed = runImpl(F, &TLI, &TTI, &LVI, &AA, &DTU, F.hasProfileData(),
356 std::move(BFI), std::move(BPI));
357
358 if (PrintLVIAfterJumpThreading) {
359 dbgs() << "LVI for function '" << F.getName() << "':\n";
360 LVI.printLVI(F, DTU.getDomTree(), dbgs());
361 }
362
363 if (!Changed)
364 return PreservedAnalyses::all();
365 PreservedAnalyses PA;
366 PA.preserve<DominatorTreeAnalysis>();
367 PA.preserve<LazyValueAnalysis>();
368 return PA;
369}
370
371bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
372 TargetTransformInfo *TTI_, LazyValueInfo *LVI_,
373 AliasAnalysis *AA_, DomTreeUpdater *DTU_,
374 bool HasProfileData_,
375 std::unique_ptr<BlockFrequencyInfo> BFI_,
376 std::unique_ptr<BranchProbabilityInfo> BPI_) {
377 LLVM_DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "Jump threading on function '"
<< F.getName() << "'\n"; } } while (false)
;
378 TLI = TLI_;
379 TTI = TTI_;
380 LVI = LVI_;
381 AA = AA_;
382 DTU = DTU_;
383 BFI.reset();
384 BPI.reset();
385 // When profile data is available, we need to update edge weights after
386 // successful jump threading, which requires both BPI and BFI being available.
387 HasProfileData = HasProfileData_;
388 auto *GuardDecl = F.getParent()->getFunction(
389 Intrinsic::getName(Intrinsic::experimental_guard));
390 HasGuards = GuardDecl && !GuardDecl->use_empty();
391 if (HasProfileData) {
392 BPI = std::move(BPI_);
393 BFI = std::move(BFI_);
394 }
395
396 // Reduce the number of instructions duplicated when optimizing strictly for
397 // size.
398 if (BBDuplicateThreshold.getNumOccurrences())
399 BBDupThreshold = BBDuplicateThreshold;
400 else if (F.hasFnAttribute(Attribute::MinSize))
401 BBDupThreshold = 3;
402 else
403 BBDupThreshold = DefaultBBDupThreshold;
404
405 // JumpThreading must not processes blocks unreachable from entry. It's a
406 // waste of compute time and can potentially lead to hangs.
407 SmallPtrSet<BasicBlock *, 16> Unreachable;
408 assert(DTU && "DTU isn't passed into JumpThreading before using it.")(static_cast <bool> (DTU && "DTU isn't passed into JumpThreading before using it."
) ? void (0) : __assert_fail ("DTU && \"DTU isn't passed into JumpThreading before using it.\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 408, __extension__
__PRETTY_FUNCTION__))
;
409 assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed.")(static_cast <bool> (DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed."
) ? void (0) : __assert_fail ("DTU->hasDomTree() && \"JumpThreading relies on DomTree to proceed.\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 409, __extension__
__PRETTY_FUNCTION__))
;
410 DominatorTree &DT = DTU->getDomTree();
411 for (auto &BB : F)
412 if (!DT.isReachableFromEntry(&BB))
413 Unreachable.insert(&BB);
414
415 if (!ThreadAcrossLoopHeaders)
416 findLoopHeaders(F);
417
418 bool EverChanged = false;
419 bool Changed;
420 do {
421 Changed = false;
422 for (auto &BB : F) {
423 if (Unreachable.count(&BB))
424 continue;
425 while (processBlock(&BB)) // Thread all of the branches we can over BB.
426 Changed = true;
427
428 // Jump threading may have introduced redundant debug values into BB
429 // which should be removed.
430 if (Changed)
431 RemoveRedundantDbgInstrs(&BB);
432
433 // Stop processing BB if it's the entry or is now deleted. The following
434 // routines attempt to eliminate BB and locating a suitable replacement
435 // for the entry is non-trivial.
436 if (&BB == &F.getEntryBlock() || DTU->isBBPendingDeletion(&BB))
437 continue;
438
439 if (pred_empty(&BB)) {
440 // When processBlock makes BB unreachable it doesn't bother to fix up
441 // the instructions in it. We must remove BB to prevent invalid IR.
442 LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " JT: Deleting dead block '"
<< BB.getName() << "' with terminator: " <<
*BB.getTerminator() << '\n'; } } while (false)
443 << "' with terminator: " << *BB.getTerminator()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " JT: Deleting dead block '"
<< BB.getName() << "' with terminator: " <<
*BB.getTerminator() << '\n'; } } while (false)
444 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " JT: Deleting dead block '"
<< BB.getName() << "' with terminator: " <<
*BB.getTerminator() << '\n'; } } while (false)
;
445 LoopHeaders.erase(&BB);
446 LVI->eraseBlock(&BB);
447 DeleteDeadBlock(&BB, DTU);
448 Changed = true;
449 continue;
450 }
451
452 // processBlock doesn't thread BBs with unconditional TIs. However, if BB
453 // is "almost empty", we attempt to merge BB with its sole successor.
454 auto *BI = dyn_cast<BranchInst>(BB.getTerminator());
455 if (BI && BI->isUnconditional()) {
456 BasicBlock *Succ = BI->getSuccessor(0);
457 if (
458 // The terminator must be the only non-phi instruction in BB.
459 BB.getFirstNonPHIOrDbg(true)->isTerminator() &&
460 // Don't alter Loop headers and latches to ensure another pass can
461 // detect and transform nested loops later.
462 !LoopHeaders.count(&BB) && !LoopHeaders.count(Succ) &&
463 TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU)) {
464 RemoveRedundantDbgInstrs(Succ);
465 // BB is valid for cleanup here because we passed in DTU. F remains
466 // BB's parent until a DTU->getDomTree() event.
467 LVI->eraseBlock(&BB);
468 Changed = true;
469 }
470 }
471 }
472 EverChanged |= Changed;
473 } while (Changed);
474
475 LoopHeaders.clear();
476 return EverChanged;
477}
478
479// Replace uses of Cond with ToVal when safe to do so. If all uses are
480// replaced, we can remove Cond. We cannot blindly replace all uses of Cond
481// because we may incorrectly replace uses when guards/assumes are uses of
482// of `Cond` and we used the guards/assume to reason about the `Cond` value
483// at the end of block. RAUW unconditionally replaces all uses
484// including the guards/assumes themselves and the uses before the
485// guard/assume.
486static bool replaceFoldableUses(Instruction *Cond, Value *ToVal,
487 BasicBlock *KnownAtEndOfBB) {
488 bool Changed = false;
489 assert(Cond->getType() == ToVal->getType())(static_cast <bool> (Cond->getType() == ToVal->getType
()) ? void (0) : __assert_fail ("Cond->getType() == ToVal->getType()"
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 489, __extension__
__PRETTY_FUNCTION__))
;
490 // We can unconditionally replace all uses in non-local blocks (i.e. uses
491 // strictly dominated by BB), since LVI information is true from the
492 // terminator of BB.
493 if (Cond->getParent() == KnownAtEndOfBB)
494 Changed |= replaceNonLocalUsesWith(Cond, ToVal);
495 for (Instruction &I : reverse(*KnownAtEndOfBB)) {
496 // Reached the Cond whose uses we are trying to replace, so there are no
497 // more uses.
498 if (&I == Cond)
499 break;
500 // We only replace uses in instructions that are guaranteed to reach the end
501 // of BB, where we know Cond is ToVal.
502 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
503 break;
504 Changed |= I.replaceUsesOfWith(Cond, ToVal);
505 }
506 if (Cond->use_empty() && !Cond->mayHaveSideEffects()) {
507 Cond->eraseFromParent();
508 Changed = true;
509 }
510 return Changed;
511}
512
513/// Return the cost of duplicating a piece of this block from first non-phi
514/// and before StopAt instruction to thread across it. Stop scanning the block
515/// when exceeding the threshold. If duplication is impossible, returns ~0U.
516static unsigned getJumpThreadDuplicationCost(const TargetTransformInfo *TTI,
517 BasicBlock *BB,
518 Instruction *StopAt,
519 unsigned Threshold) {
520 assert(StopAt->getParent() == BB && "Not an instruction from proper BB?")(static_cast <bool> (StopAt->getParent() == BB &&
"Not an instruction from proper BB?") ? void (0) : __assert_fail
("StopAt->getParent() == BB && \"Not an instruction from proper BB?\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 520, __extension__
__PRETTY_FUNCTION__))
;
521 /// Ignore PHI nodes, these will be flattened when duplication happens.
522 BasicBlock::const_iterator I(BB->getFirstNonPHI());
523
524 // FIXME: THREADING will delete values that are just used to compute the
525 // branch, so they shouldn't count against the duplication cost.
526
527 unsigned Bonus = 0;
528 if (BB->getTerminator() == StopAt) {
529 // Threading through a switch statement is particularly profitable. If this
530 // block ends in a switch, decrease its cost to make it more likely to
531 // happen.
532 if (isa<SwitchInst>(StopAt))
533 Bonus = 6;
534
535 // The same holds for indirect branches, but slightly more so.
536 if (isa<IndirectBrInst>(StopAt))
537 Bonus = 8;
538 }
539
540 // Bump the threshold up so the early exit from the loop doesn't skip the
541 // terminator-based Size adjustment at the end.
542 Threshold += Bonus;
543
544 // Sum up the cost of each instruction until we get to the terminator. Don't
545 // include the terminator because the copy won't include it.
546 unsigned Size = 0;
547 for (; &*I != StopAt; ++I) {
548
549 // Stop scanning the block if we've reached the threshold.
550 if (Size > Threshold)
551 return Size;
552
553 // Bail out if this instruction gives back a token type, it is not possible
554 // to duplicate it if it is used outside this BB.
555 if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
556 return ~0U;
557
558 // Blocks with NoDuplicate are modelled as having infinite cost, so they
559 // are never duplicated.
560 if (const CallInst *CI = dyn_cast<CallInst>(I))
561 if (CI->cannotDuplicate() || CI->isConvergent())
562 return ~0U;
563
564 if (TTI->getInstructionCost(&*I, TargetTransformInfo::TCK_SizeAndLatency) ==
565 TargetTransformInfo::TCC_Free)
566 continue;
567
568 // All other instructions count for at least one unit.
569 ++Size;
570
571 // Calls are more expensive. If they are non-intrinsic calls, we model them
572 // as having cost of 4. If they are a non-vector intrinsic, we model them
573 // as having cost of 2 total, and if they are a vector intrinsic, we model
574 // them as having cost 1.
575 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
576 if (!isa<IntrinsicInst>(CI))
577 Size += 3;
578 else if (!CI->getType()->isVectorTy())
579 Size += 1;
580 }
581 }
582
583 return Size > Bonus ? Size - Bonus : 0;
584}
585
586/// findLoopHeaders - We do not want jump threading to turn proper loop
587/// structures into irreducible loops. Doing this breaks up the loop nesting
588/// hierarchy and pessimizes later transformations. To prevent this from
589/// happening, we first have to find the loop headers. Here we approximate this
590/// by finding targets of backedges in the CFG.
591///
592/// Note that there definitely are cases when we want to allow threading of
593/// edges across a loop header. For example, threading a jump from outside the
594/// loop (the preheader) to an exit block of the loop is definitely profitable.
595/// It is also almost always profitable to thread backedges from within the loop
596/// to exit blocks, and is often profitable to thread backedges to other blocks
597/// within the loop (forming a nested loop). This simple analysis is not rich
598/// enough to track all of these properties and keep it up-to-date as the CFG
599/// mutates, so we don't allow any of these transformations.
600void JumpThreadingPass::findLoopHeaders(Function &F) {
601 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
602 FindFunctionBackedges(F, Edges);
603
604 for (const auto &Edge : Edges)
605 LoopHeaders.insert(Edge.second);
606}
607
608/// getKnownConstant - Helper method to determine if we can thread over a
609/// terminator with the given value as its condition, and if so what value to
610/// use for that. What kind of value this is depends on whether we want an
611/// integer or a block address, but an undef is always accepted.
612/// Returns null if Val is null or not an appropriate constant.
613static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
614 if (!Val)
615 return nullptr;
616
617 // Undef is "known" enough.
618 if (UndefValue *U = dyn_cast<UndefValue>(Val))
619 return U;
620
621 if (Preference == WantBlockAddress)
622 return dyn_cast<BlockAddress>(Val->stripPointerCasts());
623
624 return dyn_cast<ConstantInt>(Val);
625}
626
627/// computeValueKnownInPredecessors - Given a basic block BB and a value V, see
628/// if we can infer that the value is a known ConstantInt/BlockAddress or undef
629/// in any of our predecessors. If so, return the known list of value and pred
630/// BB in the result vector.
631///
632/// This returns true if there were any known values.
633bool JumpThreadingPass::computeValueKnownInPredecessorsImpl(
634 Value *V, BasicBlock *BB, PredValueInfo &Result,
635 ConstantPreference Preference, DenseSet<Value *> &RecursionSet,
636 Instruction *CxtI) {
637 // This method walks up use-def chains recursively. Because of this, we could
638 // get into an infinite loop going around loops in the use-def chain. To
639 // prevent this, keep track of what (value, block) pairs we've already visited
640 // and terminate the search if we loop back to them
641 if (!RecursionSet.insert(V).second)
642 return false;
643
644 // If V is a constant, then it is known in all predecessors.
645 if (Constant *KC = getKnownConstant(V, Preference)) {
646 for (BasicBlock *Pred : predecessors(BB))
647 Result.emplace_back(KC, Pred);
648
649 return !Result.empty();
650 }
651
652 // If V is a non-instruction value, or an instruction in a different block,
653 // then it can't be derived from a PHI.
654 Instruction *I = dyn_cast<Instruction>(V);
655 if (!I || I->getParent() != BB) {
656
657 // Okay, if this is a live-in value, see if it has a known value at the any
658 // edge from our predecessors.
659 for (BasicBlock *P : predecessors(BB)) {
660 using namespace PatternMatch;
661 // If the value is known by LazyValueInfo to be a constant in a
662 // predecessor, use that information to try to thread this block.
663 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
664 // If I is a non-local compare-with-constant instruction, use more-rich
665 // 'getPredicateOnEdge' method. This would be able to handle value
666 // inequalities better, for example if the compare is "X < 4" and "X < 3"
667 // is known true but "X < 4" itself is not available.
668 CmpInst::Predicate Pred;
669 Value *Val;
670 Constant *Cst;
671 if (!PredCst && match(V, m_Cmp(Pred, m_Value(Val), m_Constant(Cst)))) {
672 auto Res = LVI->getPredicateOnEdge(Pred, Val, Cst, P, BB, CxtI);
673 if (Res != LazyValueInfo::Unknown)
674 PredCst = ConstantInt::getBool(V->getContext(), Res);
675 }
676 if (Constant *KC = getKnownConstant(PredCst, Preference))
677 Result.emplace_back(KC, P);
678 }
679
680 return !Result.empty();
681 }
682
683 /// If I is a PHI node, then we know the incoming values for any constants.
684 if (PHINode *PN = dyn_cast<PHINode>(I)) {
685 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
686 Value *InVal = PN->getIncomingValue(i);
687 if (Constant *KC = getKnownConstant(InVal, Preference)) {
688 Result.emplace_back(KC, PN->getIncomingBlock(i));
689 } else {
690 Constant *CI = LVI->getConstantOnEdge(InVal,
691 PN->getIncomingBlock(i),
692 BB, CxtI);
693 if (Constant *KC = getKnownConstant(CI, Preference))
694 Result.emplace_back(KC, PN->getIncomingBlock(i));
695 }
696 }
697
698 return !Result.empty();
699 }
700
701 // Handle Cast instructions.
702 if (CastInst *CI = dyn_cast<CastInst>(I)) {
703 Value *Source = CI->getOperand(0);
704 computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
705 RecursionSet, CxtI);
706 if (Result.empty())
707 return false;
708
709 // Convert the known values.
710 for (auto &R : Result)
711 R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType());
712
713 return true;
714 }
715
716 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
717 Value *Source = FI->getOperand(0);
718 computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
719 RecursionSet, CxtI);
720
721 erase_if(Result, [](auto &Pair) {
722 return !isGuaranteedNotToBeUndefOrPoison(Pair.first);
723 });
724
725 return !Result.empty();
726 }
727
728 // Handle some boolean conditions.
729 if (I->getType()->getPrimitiveSizeInBits() == 1) {
730 using namespace PatternMatch;
731 if (Preference != WantInteger)
732 return false;
733 // X | true -> true
734 // X & false -> false
735 Value *Op0, *Op1;
736 if (match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
737 match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
738 PredValueInfoTy LHSVals, RHSVals;
739
740 computeValueKnownInPredecessorsImpl(Op0, BB, LHSVals, WantInteger,
741 RecursionSet, CxtI);
742 computeValueKnownInPredecessorsImpl(Op1, BB, RHSVals, WantInteger,
743 RecursionSet, CxtI);
744
745 if (LHSVals.empty() && RHSVals.empty())
746 return false;
747
748 ConstantInt *InterestingVal;
749 if (match(I, m_LogicalOr()))
750 InterestingVal = ConstantInt::getTrue(I->getContext());
751 else
752 InterestingVal = ConstantInt::getFalse(I->getContext());
753
754 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
755
756 // Scan for the sentinel. If we find an undef, force it to the
757 // interesting value: x|undef -> true and x&undef -> false.
758 for (const auto &LHSVal : LHSVals)
759 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
760 Result.emplace_back(InterestingVal, LHSVal.second);
761 LHSKnownBBs.insert(LHSVal.second);
762 }
763 for (const auto &RHSVal : RHSVals)
764 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
765 // If we already inferred a value for this block on the LHS, don't
766 // re-add it.
767 if (!LHSKnownBBs.count(RHSVal.second))
768 Result.emplace_back(InterestingVal, RHSVal.second);
769 }
770
771 return !Result.empty();
772 }
773
774 // Handle the NOT form of XOR.
775 if (I->getOpcode() == Instruction::Xor &&
776 isa<ConstantInt>(I->getOperand(1)) &&
777 cast<ConstantInt>(I->getOperand(1))->isOne()) {
778 computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result,
779 WantInteger, RecursionSet, CxtI);
780 if (Result.empty())
781 return false;
782
783 // Invert the known values.
784 for (auto &R : Result)
785 R.first = ConstantExpr::getNot(R.first);
786
787 return true;
788 }
789
790 // Try to simplify some other binary operator values.
791 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
792 if (Preference != WantInteger)
793 return false;
794 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
795 const DataLayout &DL = BO->getModule()->getDataLayout();
796 PredValueInfoTy LHSVals;
797 computeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
798 WantInteger, RecursionSet, CxtI);
799
800 // Try to use constant folding to simplify the binary operator.
801 for (const auto &LHSVal : LHSVals) {
802 Constant *V = LHSVal.first;
803 Constant *Folded =
804 ConstantFoldBinaryOpOperands(BO->getOpcode(), V, CI, DL);
805
806 if (Constant *KC = getKnownConstant(Folded, WantInteger))
807 Result.emplace_back(KC, LHSVal.second);
808 }
809 }
810
811 return !Result.empty();
812 }
813
814 // Handle compare with phi operand, where the PHI is defined in this block.
815 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
816 if (Preference != WantInteger)
817 return false;
818 Type *CmpType = Cmp->getType();
819 Value *CmpLHS = Cmp->getOperand(0);
820 Value *CmpRHS = Cmp->getOperand(1);
821 CmpInst::Predicate Pred = Cmp->getPredicate();
822
823 PHINode *PN = dyn_cast<PHINode>(CmpLHS);
824 if (!PN)
825 PN = dyn_cast<PHINode>(CmpRHS);
826 if (PN && PN->getParent() == BB) {
827 const DataLayout &DL = PN->getModule()->getDataLayout();
828 // We can do this simplification if any comparisons fold to true or false.
829 // See if any do.
830 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
831 BasicBlock *PredBB = PN->getIncomingBlock(i);
832 Value *LHS, *RHS;
833 if (PN == CmpLHS) {
834 LHS = PN->getIncomingValue(i);
835 RHS = CmpRHS->DoPHITranslation(BB, PredBB);
836 } else {
837 LHS = CmpLHS->DoPHITranslation(BB, PredBB);
838 RHS = PN->getIncomingValue(i);
839 }
840 Value *Res = simplifyCmpInst(Pred, LHS, RHS, {DL});
841 if (!Res) {
842 if (!isa<Constant>(RHS))
843 continue;
844
845 // getPredicateOnEdge call will make no sense if LHS is defined in BB.
846 auto LHSInst = dyn_cast<Instruction>(LHS);
847 if (LHSInst && LHSInst->getParent() == BB)
848 continue;
849
850 LazyValueInfo::Tristate
851 ResT = LVI->getPredicateOnEdge(Pred, LHS,
852 cast<Constant>(RHS), PredBB, BB,
853 CxtI ? CxtI : Cmp);
854 if (ResT == LazyValueInfo::Unknown)
855 continue;
856 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
857 }
858
859 if (Constant *KC = getKnownConstant(Res, WantInteger))
860 Result.emplace_back(KC, PredBB);
861 }
862
863 return !Result.empty();
864 }
865
866 // If comparing a live-in value against a constant, see if we know the
867 // live-in value on any predecessors.
868 if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) {
869 Constant *CmpConst = cast<Constant>(CmpRHS);
870
871 if (!isa<Instruction>(CmpLHS) ||
872 cast<Instruction>(CmpLHS)->getParent() != BB) {
873 for (BasicBlock *P : predecessors(BB)) {
874 // If the value is known by LazyValueInfo to be a constant in a
875 // predecessor, use that information to try to thread this block.
876 LazyValueInfo::Tristate Res =
877 LVI->getPredicateOnEdge(Pred, CmpLHS,
878 CmpConst, P, BB, CxtI ? CxtI : Cmp);
879 if (Res == LazyValueInfo::Unknown)
880 continue;
881
882 Constant *ResC = ConstantInt::get(CmpType, Res);
883 Result.emplace_back(ResC, P);
884 }
885
886 return !Result.empty();
887 }
888
889 // InstCombine can fold some forms of constant range checks into
890 // (icmp (add (x, C1)), C2). See if we have we have such a thing with
891 // x as a live-in.
892 {
893 using namespace PatternMatch;
894
895 Value *AddLHS;
896 ConstantInt *AddConst;
897 if (isa<ConstantInt>(CmpConst) &&
898 match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) {
899 if (!isa<Instruction>(AddLHS) ||
900 cast<Instruction>(AddLHS)->getParent() != BB) {
901 for (BasicBlock *P : predecessors(BB)) {
902 // If the value is known by LazyValueInfo to be a ConstantRange in
903 // a predecessor, use that information to try to thread this
904 // block.
905 ConstantRange CR = LVI->getConstantRangeOnEdge(
906 AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
907 // Propagate the range through the addition.
908 CR = CR.add(AddConst->getValue());
909
910 // Get the range where the compare returns true.
911 ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(
912 Pred, cast<ConstantInt>(CmpConst)->getValue());
913
914 Constant *ResC;
915 if (CmpRange.contains(CR))
916 ResC = ConstantInt::getTrue(CmpType);
917 else if (CmpRange.inverse().contains(CR))
918 ResC = ConstantInt::getFalse(CmpType);
919 else
920 continue;
921
922 Result.emplace_back(ResC, P);
923 }
924
925 return !Result.empty();
926 }
927 }
928 }
929
930 // Try to find a constant value for the LHS of a comparison,
931 // and evaluate it statically if we can.
932 PredValueInfoTy LHSVals;
933 computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals,
934 WantInteger, RecursionSet, CxtI);
935
936 for (const auto &LHSVal : LHSVals) {
937 Constant *V = LHSVal.first;
938 Constant *Folded = ConstantExpr::getCompare(Pred, V, CmpConst);
939 if (Constant *KC = getKnownConstant(Folded, WantInteger))
940 Result.emplace_back(KC, LHSVal.second);
941 }
942
943 return !Result.empty();
944 }
945 }
946
947 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
948 // Handle select instructions where at least one operand is a known constant
949 // and we can figure out the condition value for any predecessor block.
950 Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
951 Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
952 PredValueInfoTy Conds;
953 if ((TrueVal || FalseVal) &&
954 computeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds,
955 WantInteger, RecursionSet, CxtI)) {
956 for (auto &C : Conds) {
957 Constant *Cond = C.first;
958
959 // Figure out what value to use for the condition.
960 bool KnownCond;
961 if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
962 // A known boolean.
963 KnownCond = CI->isOne();
964 } else {
965 assert(isa<UndefValue>(Cond) && "Unexpected condition value")(static_cast <bool> (isa<UndefValue>(Cond) &&
"Unexpected condition value") ? void (0) : __assert_fail ("isa<UndefValue>(Cond) && \"Unexpected condition value\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 965, __extension__
__PRETTY_FUNCTION__))
;
966 // Either operand will do, so be sure to pick the one that's a known
967 // constant.
968 // FIXME: Do this more cleverly if both values are known constants?
969 KnownCond = (TrueVal != nullptr);
970 }
971
972 // See if the select has a known constant value for this predecessor.
973 if (Constant *Val = KnownCond ? TrueVal : FalseVal)
974 Result.emplace_back(Val, C.second);
975 }
976
977 return !Result.empty();
978 }
979 }
980
981 // If all else fails, see if LVI can figure out a constant value for us.
982 assert(CxtI->getParent() == BB && "CxtI should be in BB")(static_cast <bool> (CxtI->getParent() == BB &&
"CxtI should be in BB") ? void (0) : __assert_fail ("CxtI->getParent() == BB && \"CxtI should be in BB\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 982, __extension__
__PRETTY_FUNCTION__))
;
983 Constant *CI = LVI->getConstant(V, CxtI);
984 if (Constant *KC = getKnownConstant(CI, Preference)) {
985 for (BasicBlock *Pred : predecessors(BB))
986 Result.emplace_back(KC, Pred);
987 }
988
989 return !Result.empty();
990}
991
992/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
993/// in an undefined jump, decide which block is best to revector to.
994///
995/// Since we can pick an arbitrary destination, we pick the successor with the
996/// fewest predecessors. This should reduce the in-degree of the others.
997static unsigned getBestDestForJumpOnUndef(BasicBlock *BB) {
998 Instruction *BBTerm = BB->getTerminator();
999 unsigned MinSucc = 0;
1000 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
1001 // Compute the successor with the minimum number of predecessors.
1002 unsigned MinNumPreds = pred_size(TestBB);
1003 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
1004 TestBB = BBTerm->getSuccessor(i);
1005 unsigned NumPreds = pred_size(TestBB);
1006 if (NumPreds < MinNumPreds) {
1007 MinSucc = i;
1008 MinNumPreds = NumPreds;
1009 }
1010 }
1011
1012 return MinSucc;
1013}
1014
1015static bool hasAddressTakenAndUsed(BasicBlock *BB) {
1016 if (!BB->hasAddressTaken()) return false;
1017
1018 // If the block has its address taken, it may be a tree of dead constants
1019 // hanging off of it. These shouldn't keep the block alive.
1020 BlockAddress *BA = BlockAddress::get(BB);
1021 BA->removeDeadConstantUsers();
1022 return !BA->use_empty();
1023}
1024
1025/// processBlock - If there are any predecessors whose control can be threaded
1026/// through to a successor, transform them now.
1027bool JumpThreadingPass::processBlock(BasicBlock *BB) {
1028 // If the block is trivially dead, just return and let the caller nuke it.
1029 // This simplifies other transformations.
1030 if (DTU->isBBPendingDeletion(BB) ||
1031 (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()))
1032 return false;
1033
1034 // If this block has a single predecessor, and if that pred has a single
1035 // successor, merge the blocks. This encourages recursive jump threading
1036 // because now the condition in this block can be threaded through
1037 // predecessors of our predecessor block.
1038 if (maybeMergeBasicBlockIntoOnlyPred(BB))
1039 return true;
1040
1041 if (tryToUnfoldSelectInCurrBB(BB))
1042 return true;
1043
1044 // Look if we can propagate guards to predecessors.
1045 if (HasGuards && processGuards(BB))
1046 return true;
1047
1048 // What kind of constant we're looking for.
1049 ConstantPreference Preference = WantInteger;
1050
1051 // Look to see if the terminator is a conditional branch, switch or indirect
1052 // branch, if not we can't thread it.
1053 Value *Condition;
1054 Instruction *Terminator = BB->getTerminator();
1055 if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
1056 // Can't thread an unconditional jump.
1057 if (BI->isUnconditional()) return false;
1058 Condition = BI->getCondition();
1059 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
1060 Condition = SI->getCondition();
1061 } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
1062 // Can't thread indirect branch with no successors.
1063 if (IB->getNumSuccessors() == 0) return false;
1064 Condition = IB->getAddress()->stripPointerCasts();
1065 Preference = WantBlockAddress;
1066 } else {
1067 return false; // Must be an invoke or callbr.
1068 }
1069
1070 // Keep track if we constant folded the condition in this invocation.
1071 bool ConstantFolded = false;
1072
1073 // Run constant folding to see if we can reduce the condition to a simple
1074 // constant.
1075 if (Instruction *I = dyn_cast<Instruction>(Condition)) {
1076 Value *SimpleVal =
1077 ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
1078 if (SimpleVal) {
1079 I->replaceAllUsesWith(SimpleVal);
1080 if (isInstructionTriviallyDead(I, TLI))
1081 I->eraseFromParent();
1082 Condition = SimpleVal;
1083 ConstantFolded = true;
1084 }
1085 }
1086
1087 // If the terminator is branching on an undef or freeze undef, we can pick any
1088 // of the successors to branch to. Let getBestDestForJumpOnUndef decide.
1089 auto *FI = dyn_cast<FreezeInst>(Condition);
1090 if (isa<UndefValue>(Condition) ||
1091 (FI && isa<UndefValue>(FI->getOperand(0)) && FI->hasOneUse())) {
1092 unsigned BestSucc = getBestDestForJumpOnUndef(BB);
1093 std::vector<DominatorTree::UpdateType> Updates;
1094
1095 // Fold the branch/switch.
1096 Instruction *BBTerm = BB->getTerminator();
1097 Updates.reserve(BBTerm->getNumSuccessors());
1098 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
1099 if (i == BestSucc) continue;
1100 BasicBlock *Succ = BBTerm->getSuccessor(i);
1101 Succ->removePredecessor(BB, true);
1102 Updates.push_back({DominatorTree::Delete, BB, Succ});
1103 }
1104
1105 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding undef terminator: " <<
*BBTerm << '\n'; } } while (false)
1106 << "' folding undef terminator: " << *BBTerm << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding undef terminator: " <<
*BBTerm << '\n'; } } while (false)
;
1107 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
1108 ++NumFolds;
1109 BBTerm->eraseFromParent();
1110 DTU->applyUpdatesPermissive(Updates);
1111 if (FI)
1112 FI->eraseFromParent();
1113 return true;
1114 }
1115
1116 // If the terminator of this block is branching on a constant, simplify the
1117 // terminator to an unconditional branch. This can occur due to threading in
1118 // other blocks.
1119 if (getKnownConstant(Condition, Preference)) {
1120 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding terminator: " << *
BB->getTerminator() << '\n'; } } while (false)
1121 << "' folding terminator: " << *BB->getTerminator()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding terminator: " << *
BB->getTerminator() << '\n'; } } while (false)
1122 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding terminator: " << *
BB->getTerminator() << '\n'; } } while (false)
;
1123 ++NumFolds;
1124 ConstantFoldTerminator(BB, true, nullptr, DTU);
1125 if (HasProfileData)
1126 BPI->eraseBlock(BB);
1127 return true;
1128 }
1129
1130 Instruction *CondInst = dyn_cast<Instruction>(Condition);
1131
1132 // All the rest of our checks depend on the condition being an instruction.
1133 if (!CondInst) {
1134 // FIXME: Unify this with code below.
1135 if (processThreadableEdges(Condition, BB, Preference, Terminator))
1136 return true;
1137 return ConstantFolded;
1138 }
1139
1140 // Some of the following optimization can safely work on the unfrozen cond.
1141 Value *CondWithoutFreeze = CondInst;
1142 if (auto *FI = dyn_cast<FreezeInst>(CondInst))
1143 CondWithoutFreeze = FI->getOperand(0);
1144
1145 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondWithoutFreeze)) {
1146 // If we're branching on a conditional, LVI might be able to determine
1147 // it's value at the branch instruction. We only handle comparisons
1148 // against a constant at this time.
1149 if (Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1))) {
1150 LazyValueInfo::Tristate Ret =
1151 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
1152 CondConst, BB->getTerminator(),
1153 /*UseBlockValue=*/false);
1154 if (Ret != LazyValueInfo::Unknown) {
1155 // We can safely replace *some* uses of the CondInst if it has
1156 // exactly one value as returned by LVI. RAUW is incorrect in the
1157 // presence of guards and assumes, that have the `Cond` as the use. This
1158 // is because we use the guards/assume to reason about the `Cond` value
1159 // at the end of block, but RAUW unconditionally replaces all uses
1160 // including the guards/assumes themselves and the uses before the
1161 // guard/assume.
1162 auto *CI = Ret == LazyValueInfo::True ?
1163 ConstantInt::getTrue(CondCmp->getType()) :
1164 ConstantInt::getFalse(CondCmp->getType());
1165 if (replaceFoldableUses(CondCmp, CI, BB))
1166 return true;
1167 }
1168
1169 // We did not manage to simplify this branch, try to see whether
1170 // CondCmp depends on a known phi-select pattern.
1171 if (tryToUnfoldSelect(CondCmp, BB))
1172 return true;
1173 }
1174 }
1175
1176 if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
1177 if (tryToUnfoldSelect(SI, BB))
1178 return true;
1179
1180 // Check for some cases that are worth simplifying. Right now we want to look
1181 // for loads that are used by a switch or by the condition for the branch. If
1182 // we see one, check to see if it's partially redundant. If so, insert a PHI
1183 // which can then be used to thread the values.
1184 Value *SimplifyValue = CondWithoutFreeze;
1185
1186 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
1187 if (isa<Constant>(CondCmp->getOperand(1)))
1188 SimplifyValue = CondCmp->getOperand(0);
1189
1190 // TODO: There are other places where load PRE would be profitable, such as
1191 // more complex comparisons.
1192 if (LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue))
1193 if (simplifyPartiallyRedundantLoad(LoadI))
1194 return true;
1195
1196 // Before threading, try to propagate profile data backwards:
1197 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
1198 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1199 updatePredecessorProfileMetadata(PN, BB);
1200
1201 // Handle a variety of cases where we are branching on something derived from
1202 // a PHI node in the current block. If we can prove that any predecessors
1203 // compute a predictable value based on a PHI node, thread those predecessors.
1204 if (processThreadableEdges(CondInst, BB, Preference, Terminator))
1205 return true;
1206
1207 // If this is an otherwise-unfoldable branch on a phi node or freeze(phi) in
1208 // the current block, see if we can simplify.
1209 PHINode *PN = dyn_cast<PHINode>(CondWithoutFreeze);
1210 if (PN && PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1211 return processBranchOnPHI(PN);
1212
1213 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
1214 if (CondInst->getOpcode() == Instruction::Xor &&
1215 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1216 return processBranchOnXOR(cast<BinaryOperator>(CondInst));
1217
1218 // Search for a stronger dominating condition that can be used to simplify a
1219 // conditional branch leaving BB.
1220 if (processImpliedCondition(BB))
1221 return true;
1222
1223 return false;
1224}
1225
1226bool JumpThreadingPass::processImpliedCondition(BasicBlock *BB) {
1227 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
1228 if (!BI || !BI->isConditional())
1229 return false;
1230
1231 Value *Cond = BI->getCondition();
1232 // Assuming that predecessor's branch was taken, if pred's branch condition
1233 // (V) implies Cond, Cond can be either true, undef, or poison. In this case,
1234 // freeze(Cond) is either true or a nondeterministic value.
1235 // If freeze(Cond) has only one use, we can freely fold freeze(Cond) to true
1236 // without affecting other instructions.
1237 auto *FICond = dyn_cast<FreezeInst>(Cond);
1238 if (FICond && FICond->hasOneUse())
1239 Cond = FICond->getOperand(0);
1240 else
1241 FICond = nullptr;
1242
1243 BasicBlock *CurrentBB = BB;
1244 BasicBlock *CurrentPred = BB->getSinglePredecessor();
1245 unsigned Iter = 0;
1246
1247 auto &DL = BB->getModule()->getDataLayout();
1248
1249 while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
1250 auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
1251 if (!PBI || !PBI->isConditional())
1252 return false;
1253 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1254 return false;
1255
1256 bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB;
1257 Optional<bool> Implication =
1258 isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue);
1259
1260 // If the branch condition of BB (which is Cond) and CurrentPred are
1261 // exactly the same freeze instruction, Cond can be folded into CondIsTrue.
1262 if (!Implication && FICond && isa<FreezeInst>(PBI->getCondition())) {
1263 if (cast<FreezeInst>(PBI->getCondition())->getOperand(0) ==
1264 FICond->getOperand(0))
1265 Implication = CondIsTrue;
1266 }
1267
1268 if (Implication) {
1269 BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
1270 BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
1271 RemoveSucc->removePredecessor(BB);
1272 BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI);
1273 UncondBI->setDebugLoc(BI->getDebugLoc());
1274 ++NumFolds;
1275 BI->eraseFromParent();
1276 if (FICond)
1277 FICond->eraseFromParent();
1278
1279 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}});
1280 if (HasProfileData)
1281 BPI->eraseBlock(BB);
1282 return true;
1283 }
1284 CurrentBB = CurrentPred;
1285 CurrentPred = CurrentBB->getSinglePredecessor();
1286 }
1287
1288 return false;
1289}
1290
1291/// Return true if Op is an instruction defined in the given block.
1292static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
1293 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1294 if (OpInst->getParent() == BB)
1295 return true;
1296 return false;
1297}
1298
1299/// simplifyPartiallyRedundantLoad - If LoadI is an obviously partially
1300/// redundant load instruction, eliminate it by replacing it with a PHI node.
1301/// This is an important optimization that encourages jump threading, and needs
1302/// to be run interlaced with other jump threading tasks.
1303bool JumpThreadingPass::simplifyPartiallyRedundantLoad(LoadInst *LoadI) {
1304 // Don't hack volatile and ordered loads.
1305 if (!LoadI->isUnordered()) return false;
1
Taking false branch
1306
1307 // If the load is defined in a block with exactly one predecessor, it can't be
1308 // partially redundant.
1309 BasicBlock *LoadBB = LoadI->getParent();
1310 if (LoadBB->getSinglePredecessor())
2
Assuming the condition is false
3
Taking false branch
1311 return false;
1312
1313 // If the load is defined in an EH pad, it can't be partially redundant,
1314 // because the edges between the invoke and the EH pad cannot have other
1315 // instructions between them.
1316 if (LoadBB->isEHPad())
4
Assuming the condition is false
5
Taking false branch
1317 return false;
1318
1319 Value *LoadedPtr = LoadI->getOperand(0);
1320
1321 // If the loaded operand is defined in the LoadBB and its not a phi,
1322 // it can't be available in predecessors.
1323 if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr))
1324 return false;
1325
1326 // Scan a few instructions up from the load, to see if it is obviously live at
1327 // the entry to its block.
1328 BasicBlock::iterator BBIt(LoadI);
1329 bool IsLoadCSE;
1330 if (Value *AvailableVal = FindAvailableLoadedValue(
6
Assuming 'AvailableVal' is null
7
Taking false branch
1331 LoadI, LoadBB, BBIt, DefMaxInstsToScan, AA, &IsLoadCSE)) {
1332 // If the value of the load is locally available within the block, just use
1333 // it. This frequently occurs for reg2mem'd allocas.
1334
1335 if (IsLoadCSE) {
1336 LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
1337 combineMetadataForCSE(NLoadI, LoadI, false);
1338 };
1339
1340 // If the returned value is the load itself, replace with poison. This can
1341 // only happen in dead loops.
1342 if (AvailableVal == LoadI)
1343 AvailableVal = PoisonValue::get(LoadI->getType());
1344 if (AvailableVal->getType() != LoadI->getType())
1345 AvailableVal = CastInst::CreateBitOrPointerCast(
1346 AvailableVal, LoadI->getType(), "", LoadI);
1347 LoadI->replaceAllUsesWith(AvailableVal);
1348 LoadI->eraseFromParent();
1349 return true;
1350 }
1351
1352 // Otherwise, if we scanned the whole block and got to the top of the block,
1353 // we know the block is locally transparent to the load. If not, something
1354 // might clobber its value.
1355 if (BBIt != LoadBB->begin())
8
Taking false branch
1356 return false;
1357
1358 // If all of the loads and stores that feed the value have the same AA tags,
1359 // then we can propagate them onto any newly inserted loads.
1360 AAMDNodes AATags = LoadI->getAAMetadata();
1361
1362 SmallPtrSet<BasicBlock*, 8> PredsScanned;
1363
1364 using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>;
1365
1366 AvailablePredsTy AvailablePreds;
1367 BasicBlock *OneUnavailablePred = nullptr;
9
'OneUnavailablePred' initialized to a null pointer value
1368 SmallVector<LoadInst*, 8> CSELoads;
1369
1370 // If we got here, the loaded value is transparent through to the start of the
1371 // block. Check to see if it is available in any of the predecessor blocks.
1372 for (BasicBlock *PredBB : predecessors(LoadBB)) {
1373 // If we already scanned this predecessor, skip it.
1374 if (!PredsScanned.insert(PredBB).second)
1375 continue;
1376
1377 BBIt = PredBB->end();
1378 unsigned NumScanedInst = 0;
1379 Value *PredAvailable = nullptr;
1380 // NOTE: We don't CSE load that is volatile or anything stronger than
1381 // unordered, that should have been checked when we entered the function.
1382 assert(LoadI->isUnordered() &&(static_cast <bool> (LoadI->isUnordered() &&
"Attempting to CSE volatile or atomic loads") ? void (0) : __assert_fail
("LoadI->isUnordered() && \"Attempting to CSE volatile or atomic loads\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1383, __extension__
__PRETTY_FUNCTION__))
1383 "Attempting to CSE volatile or atomic loads")(static_cast <bool> (LoadI->isUnordered() &&
"Attempting to CSE volatile or atomic loads") ? void (0) : __assert_fail
("LoadI->isUnordered() && \"Attempting to CSE volatile or atomic loads\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1383, __extension__
__PRETTY_FUNCTION__))
;
1384 // If this is a load on a phi pointer, phi-translate it and search
1385 // for available load/store to the pointer in predecessors.
1386 Type *AccessTy = LoadI->getType();
1387 const auto &DL = LoadI->getModule()->getDataLayout();
1388 MemoryLocation Loc(LoadedPtr->DoPHITranslation(LoadBB, PredBB),
1389 LocationSize::precise(DL.getTypeStoreSize(AccessTy)),
1390 AATags);
1391 PredAvailable = findAvailablePtrLoadStore(Loc, AccessTy, LoadI->isAtomic(),
1392 PredBB, BBIt, DefMaxInstsToScan,
1393 AA, &IsLoadCSE, &NumScanedInst);
1394
1395 // If PredBB has a single predecessor, continue scanning through the
1396 // single predecessor.
1397 BasicBlock *SinglePredBB = PredBB;
1398 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
1399 NumScanedInst < DefMaxInstsToScan) {
1400 SinglePredBB = SinglePredBB->getSinglePredecessor();
1401 if (SinglePredBB) {
1402 BBIt = SinglePredBB->end();
1403 PredAvailable = findAvailablePtrLoadStore(
1404 Loc, AccessTy, LoadI->isAtomic(), SinglePredBB, BBIt,
1405 (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
1406 &NumScanedInst);
1407 }
1408 }
1409
1410 if (!PredAvailable) {
1411 OneUnavailablePred = PredBB;
1412 continue;
1413 }
1414
1415 if (IsLoadCSE)
1416 CSELoads.push_back(cast<LoadInst>(PredAvailable));
1417
1418 // If so, this load is partially redundant. Remember this info so that we
1419 // can create a PHI node.
1420 AvailablePreds.emplace_back(PredBB, PredAvailable);
1421 }
1422
1423 // If the loaded value isn't available in any predecessor, it isn't partially
1424 // redundant.
1425 if (AvailablePreds.empty()) return false;
10
Taking false branch
1426
1427 // Okay, the loaded value is available in at least one (and maybe all!)
1428 // predecessors. If the value is unavailable in more than one unique
1429 // predecessor, we want to insert a merge block for those common predecessors.
1430 // This ensures that we only have to insert one reload, thus not increasing
1431 // code size.
1432 BasicBlock *UnavailablePred = nullptr;
1433
1434 // If the value is unavailable in one of predecessors, we will end up
1435 // inserting a new instruction into them. It is only valid if all the
1436 // instructions before LoadI are guaranteed to pass execution to its
1437 // successor, or if LoadI is safe to speculate.
1438 // TODO: If this logic becomes more complex, and we will perform PRE insertion
1439 // farther than to a predecessor, we need to reuse the code from GVN's PRE.
1440 // It requires domination tree analysis, so for this simple case it is an
1441 // overkill.
1442 if (PredsScanned.size() != AvailablePreds.size() &&
11
Assuming the condition is false
1443 !isSafeToSpeculativelyExecute(LoadI))
1444 for (auto I = LoadBB->begin(); &*I != LoadI; ++I)
1445 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
1446 return false;
1447
1448 // If there is exactly one predecessor where the value is unavailable, the
1449 // already computed 'OneUnavailablePred' block is it. If it ends in an
1450 // unconditional branch, we know that it isn't a critical edge.
1451 if (PredsScanned.size() == AvailablePreds.size()+1 &&
12
Assuming the condition is true
1452 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
13
Called C++ object pointer is null
1453 UnavailablePred = OneUnavailablePred;
1454 } else if (PredsScanned.size() != AvailablePreds.size()) {
1455 // Otherwise, we had multiple unavailable predecessors or we had a critical
1456 // edge from the one.
1457 SmallVector<BasicBlock*, 8> PredsToSplit;
1458 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
1459
1460 for (const auto &AvailablePred : AvailablePreds)
1461 AvailablePredSet.insert(AvailablePred.first);
1462
1463 // Add all the unavailable predecessors to the PredsToSplit list.
1464 for (BasicBlock *P : predecessors(LoadBB)) {
1465 // If the predecessor is an indirect goto, we can't split the edge.
1466 if (isa<IndirectBrInst>(P->getTerminator()))
1467 return false;
1468
1469 if (!AvailablePredSet.count(P))
1470 PredsToSplit.push_back(P);
1471 }
1472
1473 // Split them out to their own block.
1474 UnavailablePred = splitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
1475 }
1476
1477 // If the value isn't available in all predecessors, then there will be
1478 // exactly one where it isn't available. Insert a load on that edge and add
1479 // it to the AvailablePreds list.
1480 if (UnavailablePred) {
1481 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&(static_cast <bool> (UnavailablePred->getTerminator(
)->getNumSuccessors() == 1 && "Can't handle critical edge here!"
) ? void (0) : __assert_fail ("UnavailablePred->getTerminator()->getNumSuccessors() == 1 && \"Can't handle critical edge here!\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1482, __extension__
__PRETTY_FUNCTION__))
1482 "Can't handle critical edge here!")(static_cast <bool> (UnavailablePred->getTerminator(
)->getNumSuccessors() == 1 && "Can't handle critical edge here!"
) ? void (0) : __assert_fail ("UnavailablePred->getTerminator()->getNumSuccessors() == 1 && \"Can't handle critical edge here!\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1482, __extension__
__PRETTY_FUNCTION__))
;
1483 LoadInst *NewVal = new LoadInst(
1484 LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred),
1485 LoadI->getName() + ".pr", false, LoadI->getAlign(),
1486 LoadI->getOrdering(), LoadI->getSyncScopeID(),
1487 UnavailablePred->getTerminator());
1488 NewVal->setDebugLoc(LoadI->getDebugLoc());
1489 if (AATags)
1490 NewVal->setAAMetadata(AATags);
1491
1492 AvailablePreds.emplace_back(UnavailablePred, NewVal);
1493 }
1494
1495 // Now we know that each predecessor of this block has a value in
1496 // AvailablePreds, sort them for efficient access as we're walking the preds.
1497 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
1498
1499 // Create a PHI node at the start of the block for the PRE'd load value.
1500 pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
1501 PHINode *PN = PHINode::Create(LoadI->getType(), std::distance(PB, PE), "",
1502 &LoadBB->front());
1503 PN->takeName(LoadI);
1504 PN->setDebugLoc(LoadI->getDebugLoc());
1505
1506 // Insert new entries into the PHI for each predecessor. A single block may
1507 // have multiple entries here.
1508 for (pred_iterator PI = PB; PI != PE; ++PI) {
1509 BasicBlock *P = *PI;
1510 AvailablePredsTy::iterator I =
1511 llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr));
1512
1513 assert(I != AvailablePreds.end() && I->first == P &&(static_cast <bool> (I != AvailablePreds.end() &&
I->first == P && "Didn't find entry for predecessor!"
) ? void (0) : __assert_fail ("I != AvailablePreds.end() && I->first == P && \"Didn't find entry for predecessor!\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1514, __extension__
__PRETTY_FUNCTION__))
1514 "Didn't find entry for predecessor!")(static_cast <bool> (I != AvailablePreds.end() &&
I->first == P && "Didn't find entry for predecessor!"
) ? void (0) : __assert_fail ("I != AvailablePreds.end() && I->first == P && \"Didn't find entry for predecessor!\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1514, __extension__
__PRETTY_FUNCTION__))
;
1515
1516 // If we have an available predecessor but it requires casting, insert the
1517 // cast in the predecessor and use the cast. Note that we have to update the
1518 // AvailablePreds vector as we go so that all of the PHI entries for this
1519 // predecessor use the same bitcast.
1520 Value *&PredV = I->second;
1521 if (PredV->getType() != LoadI->getType())
1522 PredV = CastInst::CreateBitOrPointerCast(PredV, LoadI->getType(), "",
1523 P->getTerminator());
1524
1525 PN->addIncoming(PredV, I->first);
1526 }
1527
1528 for (LoadInst *PredLoadI : CSELoads) {
1529 combineMetadataForCSE(PredLoadI, LoadI, true);
1530 }
1531
1532 LoadI->replaceAllUsesWith(PN);
1533 LoadI->eraseFromParent();
1534
1535 return true;
1536}
1537
1538/// findMostPopularDest - The specified list contains multiple possible
1539/// threadable destinations. Pick the one that occurs the most frequently in
1540/// the list.
1541static BasicBlock *
1542findMostPopularDest(BasicBlock *BB,
1543 const SmallVectorImpl<std::pair<BasicBlock *,
1544 BasicBlock *>> &PredToDestList) {
1545 assert(!PredToDestList.empty())(static_cast <bool> (!PredToDestList.empty()) ? void (0
) : __assert_fail ("!PredToDestList.empty()", "llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1545, __extension__ __PRETTY_FUNCTION__))
;
1546
1547 // Determine popularity. If there are multiple possible destinations, we
1548 // explicitly choose to ignore 'undef' destinations. We prefer to thread
1549 // blocks with known and real destinations to threading undef. We'll handle
1550 // them later if interesting.
1551 MapVector<BasicBlock *, unsigned> DestPopularity;
1552
1553 // Populate DestPopularity with the successors in the order they appear in the
1554 // successor list. This way, we ensure determinism by iterating it in the
1555 // same order in std::max_element below. We map nullptr to 0 so that we can
1556 // return nullptr when PredToDestList contains nullptr only.
1557 DestPopularity[nullptr] = 0;
1558 for (auto *SuccBB : successors(BB))
1559 DestPopularity[SuccBB] = 0;
1560
1561 for (const auto &PredToDest : PredToDestList)
1562 if (PredToDest.second)
1563 DestPopularity[PredToDest.second]++;
1564
1565 // Find the most popular dest.
1566 auto MostPopular = std::max_element(
1567 DestPopularity.begin(), DestPopularity.end(), llvm::less_second());
1568
1569 // Okay, we have finally picked the most popular destination.
1570 return MostPopular->first;
1571}
1572
1573// Try to evaluate the value of V when the control flows from PredPredBB to
1574// BB->getSinglePredecessor() and then on to BB.
1575Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB,
1576 BasicBlock *PredPredBB,
1577 Value *V) {
1578 BasicBlock *PredBB = BB->getSinglePredecessor();
1579 assert(PredBB && "Expected a single predecessor")(static_cast <bool> (PredBB && "Expected a single predecessor"
) ? void (0) : __assert_fail ("PredBB && \"Expected a single predecessor\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1579, __extension__
__PRETTY_FUNCTION__))
;
1580
1581 if (Constant *Cst = dyn_cast<Constant>(V)) {
1582 return Cst;
1583 }
1584
1585 // Consult LVI if V is not an instruction in BB or PredBB.
1586 Instruction *I = dyn_cast<Instruction>(V);
1587 if (!I || (I->getParent() != BB && I->getParent() != PredBB)) {
1588 return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr);
1589 }
1590
1591 // Look into a PHI argument.
1592 if (PHINode *PHI = dyn_cast<PHINode>(V)) {
1593 if (PHI->getParent() == PredBB)
1594 return dyn_cast<Constant>(PHI->getIncomingValueForBlock(PredPredBB));
1595 return nullptr;
1596 }
1597
1598 // If we have a CmpInst, try to fold it for each incoming edge into PredBB.
1599 if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) {
1600 if (CondCmp->getParent() == BB) {
1601 Constant *Op0 =
1602 evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0));
1603 Constant *Op1 =
1604 evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1));
1605 if (Op0 && Op1) {
1606 return ConstantExpr::getCompare(CondCmp->getPredicate(), Op0, Op1);
1607 }
1608 }
1609 return nullptr;
1610 }
1611
1612 return nullptr;
1613}
1614
1615bool JumpThreadingPass::processThreadableEdges(Value *Cond, BasicBlock *BB,
1616 ConstantPreference Preference,
1617 Instruction *CxtI) {
1618 // If threading this would thread across a loop header, don't even try to
1619 // thread the edge.
1620 if (LoopHeaders.count(BB))
1621 return false;
1622
1623 PredValueInfoTy PredValues;
1624 if (!computeValueKnownInPredecessors(Cond, BB, PredValues, Preference,
1625 CxtI)) {
1626 // We don't have known values in predecessors. See if we can thread through
1627 // BB and its sole predecessor.
1628 return maybethreadThroughTwoBasicBlocks(BB, Cond);
1629 }
1630
1631 assert(!PredValues.empty() &&(static_cast <bool> (!PredValues.empty() && "computeValueKnownInPredecessors returned true with no values"
) ? void (0) : __assert_fail ("!PredValues.empty() && \"computeValueKnownInPredecessors returned true with no values\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1632, __extension__
__PRETTY_FUNCTION__))
1632 "computeValueKnownInPredecessors returned true with no values")(static_cast <bool> (!PredValues.empty() && "computeValueKnownInPredecessors returned true with no values"
) ? void (0) : __assert_fail ("!PredValues.empty() && \"computeValueKnownInPredecessors returned true with no values\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1632, __extension__
__PRETTY_FUNCTION__))
;
1633
1634 LLVM_DEBUG(dbgs() << "IN BB: " << *BB;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1635 for (const auto &PredValue : PredValues) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1636 dbgs() << " BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1637 << "': FOUND condition = " << *PredValue.firstdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1638 << " for pred '" << PredValue.second->getName() << "'.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1639 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
;
1640
1641 // Decide what we want to thread through. Convert our list of known values to
1642 // a list of known destinations for each pred. This also discards duplicate
1643 // predecessors and keeps track of the undefined inputs (which are represented
1644 // as a null dest in the PredToDestList).
1645 SmallPtrSet<BasicBlock*, 16> SeenPreds;
1646 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1647
1648 BasicBlock *OnlyDest = nullptr;
1649 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1650 Constant *OnlyVal = nullptr;
1651 Constant *MultipleVal = (Constant *)(intptr_t)~0ULL;
1652
1653 for (const auto &PredValue : PredValues) {
1654 BasicBlock *Pred = PredValue.second;
1655 if (!SeenPreds.insert(Pred).second)
1656 continue; // Duplicate predecessor entry.
1657
1658 Constant *Val = PredValue.first;
1659
1660 BasicBlock *DestBB;
1661 if (isa<UndefValue>(Val))
1662 DestBB = nullptr;
1663 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1664 assert(isa<ConstantInt>(Val) && "Expecting a constant integer")(static_cast <bool> (isa<ConstantInt>(Val) &&
"Expecting a constant integer") ? void (0) : __assert_fail (
"isa<ConstantInt>(Val) && \"Expecting a constant integer\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1664, __extension__
__PRETTY_FUNCTION__))
;
1665 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
1666 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1667 assert(isa<ConstantInt>(Val) && "Expecting a constant integer")(static_cast <bool> (isa<ConstantInt>(Val) &&
"Expecting a constant integer") ? void (0) : __assert_fail (
"isa<ConstantInt>(Val) && \"Expecting a constant integer\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1667, __extension__
__PRETTY_FUNCTION__))
;
1668 DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
1669 } else {
1670 assert(isa<IndirectBrInst>(BB->getTerminator())(static_cast <bool> (isa<IndirectBrInst>(BB->getTerminator
()) && "Unexpected terminator") ? void (0) : __assert_fail
("isa<IndirectBrInst>(BB->getTerminator()) && \"Unexpected terminator\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1671, __extension__
__PRETTY_FUNCTION__))
1671 && "Unexpected terminator")(static_cast <bool> (isa<IndirectBrInst>(BB->getTerminator
()) && "Unexpected terminator") ? void (0) : __assert_fail
("isa<IndirectBrInst>(BB->getTerminator()) && \"Unexpected terminator\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1671, __extension__
__PRETTY_FUNCTION__))
;
1672 assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress")(static_cast <bool> (isa<BlockAddress>(Val) &&
"Expecting a constant blockaddress") ? void (0) : __assert_fail
("isa<BlockAddress>(Val) && \"Expecting a constant blockaddress\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1672, __extension__
__PRETTY_FUNCTION__))
;
1673 DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1674 }
1675
1676 // If we have exactly one destination, remember it for efficiency below.
1677 if (PredToDestList.empty()) {
1678 OnlyDest = DestBB;
1679 OnlyVal = Val;
1680 } else {
1681 if (OnlyDest != DestBB)
1682 OnlyDest = MultipleDestSentinel;
1683 // It possible we have same destination, but different value, e.g. default
1684 // case in switchinst.
1685 if (Val != OnlyVal)
1686 OnlyVal = MultipleVal;
1687 }
1688
1689 // If the predecessor ends with an indirect goto, we can't change its
1690 // destination.
1691 if (isa<IndirectBrInst>(Pred->getTerminator()))
1692 continue;
1693
1694 PredToDestList.emplace_back(Pred, DestBB);
1695 }
1696
1697 // If all edges were unthreadable, we fail.
1698 if (PredToDestList.empty())
1699 return false;
1700
1701 // If all the predecessors go to a single known successor, we want to fold,
1702 // not thread. By doing so, we do not need to duplicate the current block and
1703 // also miss potential opportunities in case we dont/cant duplicate.
1704 if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1705 if (BB->hasNPredecessors(PredToDestList.size())) {
1706 bool SeenFirstBranchToOnlyDest = false;
1707 std::vector <DominatorTree::UpdateType> Updates;
1708 Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1);
1709 for (BasicBlock *SuccBB : successors(BB)) {
1710 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
1711 SeenFirstBranchToOnlyDest = true; // Don't modify the first branch.
1712 } else {
1713 SuccBB->removePredecessor(BB, true); // This is unreachable successor.
1714 Updates.push_back({DominatorTree::Delete, BB, SuccBB});
1715 }
1716 }
1717
1718 // Finally update the terminator.
1719 Instruction *Term = BB->getTerminator();
1720 BranchInst::Create(OnlyDest, Term);
1721 ++NumFolds;
1722 Term->eraseFromParent();
1723 DTU->applyUpdatesPermissive(Updates);
1724 if (HasProfileData)
1725 BPI->eraseBlock(BB);
1726
1727 // If the condition is now dead due to the removal of the old terminator,
1728 // erase it.
1729 if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
1730 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
1731 CondInst->eraseFromParent();
1732 // We can safely replace *some* uses of the CondInst if it has
1733 // exactly one value as returned by LVI. RAUW is incorrect in the
1734 // presence of guards and assumes, that have the `Cond` as the use. This
1735 // is because we use the guards/assume to reason about the `Cond` value
1736 // at the end of block, but RAUW unconditionally replaces all uses
1737 // including the guards/assumes themselves and the uses before the
1738 // guard/assume.
1739 else if (OnlyVal && OnlyVal != MultipleVal)
1740 replaceFoldableUses(CondInst, OnlyVal, BB);
1741 }
1742 return true;
1743 }
1744 }
1745
1746 // Determine which is the most common successor. If we have many inputs and
1747 // this block is a switch, we want to start by threading the batch that goes
1748 // to the most popular destination first. If we only know about one
1749 // threadable destination (the common case) we can avoid this.
1750 BasicBlock *MostPopularDest = OnlyDest;
1751
1752 if (MostPopularDest == MultipleDestSentinel) {
1753 // Remove any loop headers from the Dest list, threadEdge conservatively
1754 // won't process them, but we might have other destination that are eligible
1755 // and we still want to process.
1756 erase_if(PredToDestList,
1757 [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1758 return LoopHeaders.contains(PredToDest.second);
1759 });
1760
1761 if (PredToDestList.empty())
1762 return false;
1763
1764 MostPopularDest = findMostPopularDest(BB, PredToDestList);
1765 }
1766
1767 // Now that we know what the most popular destination is, factor all
1768 // predecessors that will jump to it into a single predecessor.
1769 SmallVector<BasicBlock*, 16> PredsToFactor;
1770 for (const auto &PredToDest : PredToDestList)
1771 if (PredToDest.second == MostPopularDest) {
1772 BasicBlock *Pred = PredToDest.first;
1773
1774 // This predecessor may be a switch or something else that has multiple
1775 // edges to the block. Factor each of these edges by listing them
1776 // according to # occurrences in PredsToFactor.
1777 for (BasicBlock *Succ : successors(Pred))
1778 if (Succ == BB)
1779 PredsToFactor.push_back(Pred);
1780 }
1781
1782 // If the threadable edges are branching on an undefined value, we get to pick
1783 // the destination that these predecessors should get to.
1784 if (!MostPopularDest)
1785 MostPopularDest = BB->getTerminator()->
1786 getSuccessor(getBestDestForJumpOnUndef(BB));
1787
1788 // Ok, try to thread it!
1789 return tryThreadEdge(BB, PredsToFactor, MostPopularDest);
1790}
1791
1792/// processBranchOnPHI - We have an otherwise unthreadable conditional branch on
1793/// a PHI node (or freeze PHI) in the current block. See if there are any
1794/// simplifications we can do based on inputs to the phi node.
1795bool JumpThreadingPass::processBranchOnPHI(PHINode *PN) {
1796 BasicBlock *BB = PN->getParent();
1797
1798 // TODO: We could make use of this to do it once for blocks with common PHI
1799 // values.
1800 SmallVector<BasicBlock*, 1> PredBBs;
1801 PredBBs.resize(1);
1802
1803 // If any of the predecessor blocks end in an unconditional branch, we can
1804 // *duplicate* the conditional branch into that block in order to further
1805 // encourage jump threading and to eliminate cases where we have branch on a
1806 // phi of an icmp (branch on icmp is much better).
1807 // This is still beneficial when a frozen phi is used as the branch condition
1808 // because it allows CodeGenPrepare to further canonicalize br(freeze(icmp))
1809 // to br(icmp(freeze ...)).
1810 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1811 BasicBlock *PredBB = PN->getIncomingBlock(i);
1812 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1813 if (PredBr->isUnconditional()) {
1814 PredBBs[0] = PredBB;
1815 // Try to duplicate BB into PredBB.
1816 if (duplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1817 return true;
1818 }
1819 }
1820
1821 return false;
1822}
1823
1824/// processBranchOnXOR - We have an otherwise unthreadable conditional branch on
1825/// a xor instruction in the current block. See if there are any
1826/// simplifications we can do based on inputs to the xor.
1827bool JumpThreadingPass::processBranchOnXOR(BinaryOperator *BO) {
1828 BasicBlock *BB = BO->getParent();
1829
1830 // If either the LHS or RHS of the xor is a constant, don't do this
1831 // optimization.
1832 if (isa<ConstantInt>(BO->getOperand(0)) ||
1833 isa<ConstantInt>(BO->getOperand(1)))
1834 return false;
1835
1836 // If the first instruction in BB isn't a phi, we won't be able to infer
1837 // anything special about any particular predecessor.
1838 if (!isa<PHINode>(BB->front()))
1839 return false;
1840
1841 // If this BB is a landing pad, we won't be able to split the edge into it.
1842 if (BB->isEHPad())
1843 return false;
1844
1845 // If we have a xor as the branch input to this block, and we know that the
1846 // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1847 // the condition into the predecessor and fix that value to true, saving some
1848 // logical ops on that path and encouraging other paths to simplify.
1849 //
1850 // This copies something like this:
1851 //
1852 // BB:
1853 // %X = phi i1 [1], [%X']
1854 // %Y = icmp eq i32 %A, %B
1855 // %Z = xor i1 %X, %Y
1856 // br i1 %Z, ...
1857 //
1858 // Into:
1859 // BB':
1860 // %Y = icmp ne i32 %A, %B
1861 // br i1 %Y, ...
1862
1863 PredValueInfoTy XorOpValues;
1864 bool isLHS = true;
1865 if (!computeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
1866 WantInteger, BO)) {
1867 assert(XorOpValues.empty())(static_cast <bool> (XorOpValues.empty()) ? void (0) : __assert_fail
("XorOpValues.empty()", "llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1867, __extension__ __PRETTY_FUNCTION__))
;
1868 if (!computeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
1869 WantInteger, BO))
1870 return false;
1871 isLHS = false;
1872 }
1873
1874 assert(!XorOpValues.empty() &&(static_cast <bool> (!XorOpValues.empty() && "computeValueKnownInPredecessors returned true with no values"
) ? void (0) : __assert_fail ("!XorOpValues.empty() && \"computeValueKnownInPredecessors returned true with no values\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1875, __extension__
__PRETTY_FUNCTION__))
1875 "computeValueKnownInPredecessors returned true with no values")(static_cast <bool> (!XorOpValues.empty() && "computeValueKnownInPredecessors returned true with no values"
) ? void (0) : __assert_fail ("!XorOpValues.empty() && \"computeValueKnownInPredecessors returned true with no values\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 1875, __extension__
__PRETTY_FUNCTION__))
;
1876
1877 // Scan the information to see which is most popular: true or false. The
1878 // predecessors can be of the set true, false, or undef.
1879 unsigned NumTrue = 0, NumFalse = 0;
1880 for (const auto &XorOpValue : XorOpValues) {
1881 if (isa<UndefValue>(XorOpValue.first))
1882 // Ignore undefs for the count.
1883 continue;
1884 if (cast<ConstantInt>(XorOpValue.first)->isZero())
1885 ++NumFalse;
1886 else
1887 ++NumTrue;
1888 }
1889
1890 // Determine which value to split on, true, false, or undef if neither.
1891 ConstantInt *SplitVal = nullptr;
1892 if (NumTrue > NumFalse)
1893 SplitVal = ConstantInt::getTrue(BB->getContext());
1894 else if (NumTrue != 0 || NumFalse != 0)
1895 SplitVal = ConstantInt::getFalse(BB->getContext());
1896
1897 // Collect all of the blocks that this can be folded into so that we can
1898 // factor this once and clone it once.
1899 SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1900 for (const auto &XorOpValue : XorOpValues) {
1901 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1902 continue;
1903
1904 BlocksToFoldInto.push_back(XorOpValue.second);
1905 }
1906
1907 // If we inferred a value for all of the predecessors, then duplication won't
1908 // help us. However, we can just replace the LHS or RHS with the constant.
1909 if (BlocksToFoldInto.size() ==
1910 cast<PHINode>(BB->front()).getNumIncomingValues()) {
1911 if (!SplitVal) {
1912 // If all preds provide undef, just nuke the xor, because it is undef too.
1913 BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1914 BO->eraseFromParent();
1915 } else if (SplitVal->isZero()) {
1916 // If all preds provide 0, replace the xor with the other input.
1917 BO->replaceAllUsesWith(BO->getOperand(isLHS));
1918 BO->eraseFromParent();
1919 } else {
1920 // If all preds provide 1, set the computed value to 1.
1921 BO->setOperand(!isLHS, SplitVal);
1922 }
1923
1924 return true;
1925 }
1926
1927 // If any of predecessors end with an indirect goto, we can't change its
1928 // destination.
1929 if (any_of(BlocksToFoldInto, [](BasicBlock *Pred) {
1930 return isa<IndirectBrInst>(Pred->getTerminator());
1931 }))
1932 return false;
1933
1934 // Try to duplicate BB into PredBB.
1935 return duplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1936}
1937
1938/// addPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1939/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1940/// NewPred using the entries from OldPred (suitably mapped).
1941static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1942 BasicBlock *OldPred,
1943 BasicBlock *NewPred,
1944 DenseMap<Instruction*, Value*> &ValueMap) {
1945 for (PHINode &PN : PHIBB->phis()) {
1946 // Ok, we have a PHI node. Figure out what the incoming value was for the
1947 // DestBlock.
1948 Value *IV = PN.getIncomingValueForBlock(OldPred);
1949
1950 // Remap the value if necessary.
1951 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1952 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1953 if (I != ValueMap.end())
1954 IV = I->second;
1955 }
1956
1957 PN.addIncoming(IV, NewPred);
1958 }
1959}
1960
1961/// Merge basic block BB into its sole predecessor if possible.
1962bool JumpThreadingPass::maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) {
1963 BasicBlock *SinglePred = BB->getSinglePredecessor();
1964 if (!SinglePred)
1965 return false;
1966
1967 const Instruction *TI = SinglePred->getTerminator();
1968 if (TI->isExceptionalTerminator() || TI->getNumSuccessors() != 1 ||
1969 SinglePred == BB || hasAddressTakenAndUsed(BB))
1970 return false;
1971
1972 // If SinglePred was a loop header, BB becomes one.
1973 if (LoopHeaders.erase(SinglePred))
1974 LoopHeaders.insert(BB);
1975
1976 LVI->eraseBlock(SinglePred);
1977 MergeBasicBlockIntoOnlyPred(BB, DTU);
1978
1979 // Now that BB is merged into SinglePred (i.e. SinglePred code followed by
1980 // BB code within one basic block `BB`), we need to invalidate the LVI
1981 // information associated with BB, because the LVI information need not be
1982 // true for all of BB after the merge. For example,
1983 // Before the merge, LVI info and code is as follows:
1984 // SinglePred: <LVI info1 for %p val>
1985 // %y = use of %p
1986 // call @exit() // need not transfer execution to successor.
1987 // assume(%p) // from this point on %p is true
1988 // br label %BB
1989 // BB: <LVI info2 for %p val, i.e. %p is true>
1990 // %x = use of %p
1991 // br label exit
1992 //
1993 // Note that this LVI info for blocks BB and SinglPred is correct for %p
1994 // (info2 and info1 respectively). After the merge and the deletion of the
1995 // LVI info1 for SinglePred. We have the following code:
1996 // BB: <LVI info2 for %p val>
1997 // %y = use of %p
1998 // call @exit()
1999 // assume(%p)
2000 // %x = use of %p <-- LVI info2 is correct from here onwards.
2001 // br label exit
2002 // LVI info2 for BB is incorrect at the beginning of BB.
2003
2004 // Invalidate LVI information for BB if the LVI is not provably true for
2005 // all of BB.
2006 if (!isGuaranteedToTransferExecutionToSuccessor(BB))
2007 LVI->eraseBlock(BB);
2008 return true;
2009}
2010
2011/// Update the SSA form. NewBB contains instructions that are copied from BB.
2012/// ValueMapping maps old values in BB to new ones in NewBB.
2013void JumpThreadingPass::updateSSA(
2014 BasicBlock *BB, BasicBlock *NewBB,
2015 DenseMap<Instruction *, Value *> &ValueMapping) {
2016 // If there were values defined in BB that are used outside the block, then we
2017 // now have to update all uses of the value to use either the original value,
2018 // the cloned value, or some PHI derived value. This can require arbitrary
2019 // PHI insertion, of which we are prepared to do, clean these up now.
2020 SSAUpdater SSAUpdate;
2021 SmallVector<Use *, 16> UsesToRename;
2022
2023 for (Instruction &I : *BB) {
2024 // Scan all uses of this instruction to see if it is used outside of its
2025 // block, and if so, record them in UsesToRename.
2026 for (Use &U : I.uses()) {
2027 Instruction *User = cast<Instruction>(U.getUser());
2028 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
2029 if (UserPN->getIncomingBlock(U) == BB)
2030 continue;
2031 } else if (User->getParent() == BB)
2032 continue;
2033
2034 UsesToRename.push_back(&U);
2035 }
2036
2037 // If there are no uses outside the block, we're done with this instruction.
2038 if (UsesToRename.empty())
2039 continue;
2040 LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "JT: Renaming non-local uses of: "
<< I << "\n"; } } while (false)
;
2041
2042 // We found a use of I outside of BB. Rename all uses of I that are outside
2043 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
2044 // with the two values we know.
2045 SSAUpdate.Initialize(I.getType(), I.getName());
2046 SSAUpdate.AddAvailableValue(BB, &I);
2047 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
2048
2049 while (!UsesToRename.empty())
2050 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
2051 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "\n"; } } while (false)
;
2052 }
2053}
2054
2055/// Clone instructions in range [BI, BE) to NewBB. For PHI nodes, we only clone
2056/// arguments that come from PredBB. Return the map from the variables in the
2057/// source basic block to the variables in the newly created basic block.
2058DenseMap<Instruction *, Value *>
2059JumpThreadingPass::cloneInstructions(BasicBlock::iterator BI,
2060 BasicBlock::iterator BE, BasicBlock *NewBB,
2061 BasicBlock *PredBB) {
2062 // We are going to have to map operands from the source basic block to the new
2063 // copy of the block 'NewBB'. If there are PHI nodes in the source basic
2064 // block, evaluate them to account for entry from PredBB.
2065 DenseMap<Instruction *, Value *> ValueMapping;
2066
2067 // Clone the phi nodes of the source basic block into NewBB. The resulting
2068 // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater
2069 // might need to rewrite the operand of the cloned phi.
2070 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2071 PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB);
2072 NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB);
2073 ValueMapping[PN] = NewPN;
2074 }
2075
2076 // Clone noalias scope declarations in the threaded block. When threading a
2077 // loop exit, we would otherwise end up with two idential scope declarations
2078 // visible at the same time.
2079 SmallVector<MDNode *> NoAliasScopes;
2080 DenseMap<MDNode *, MDNode *> ClonedScopes;
2081 LLVMContext &Context = PredBB->getContext();
2082 identifyNoAliasScopesToClone(BI, BE, NoAliasScopes);
2083 cloneNoAliasScopes(NoAliasScopes, ClonedScopes, "thread", Context);
2084
2085 // Clone the non-phi instructions of the source basic block into NewBB,
2086 // keeping track of the mapping and using it to remap operands in the cloned
2087 // instructions.
2088 for (; BI != BE; ++BI) {
2089 Instruction *New = BI->clone();
2090 New->setName(BI->getName());
2091 NewBB->getInstList().push_back(New);
2092 ValueMapping[&*BI] = New;
2093 adaptNoAliasScopes(New, ClonedScopes, Context);
2094
2095 // Remap operands to patch up intra-block references.
2096 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2097 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2098 DenseMap<Instruction *, Value *>::iterator I = ValueMapping.find(Inst);
2099 if (I != ValueMapping.end())
2100 New->setOperand(i, I->second);
2101 }
2102 }
2103
2104 return ValueMapping;
2105}
2106
2107/// Attempt to thread through two successive basic blocks.
2108bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB,
2109 Value *Cond) {
2110 // Consider:
2111 //
2112 // PredBB:
2113 // %var = phi i32* [ null, %bb1 ], [ @a, %bb2 ]
2114 // %tobool = icmp eq i32 %cond, 0
2115 // br i1 %tobool, label %BB, label ...
2116 //
2117 // BB:
2118 // %cmp = icmp eq i32* %var, null
2119 // br i1 %cmp, label ..., label ...
2120 //
2121 // We don't know the value of %var at BB even if we know which incoming edge
2122 // we take to BB. However, once we duplicate PredBB for each of its incoming
2123 // edges (say, PredBB1 and PredBB2), we know the value of %var in each copy of
2124 // PredBB. Then we can thread edges PredBB1->BB and PredBB2->BB through BB.
2125
2126 // Require that BB end with a Branch for simplicity.
2127 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2128 if (!CondBr)
2129 return false;
2130
2131 // BB must have exactly one predecessor.
2132 BasicBlock *PredBB = BB->getSinglePredecessor();
2133 if (!PredBB)
2134 return false;
2135
2136 // Require that PredBB end with a conditional Branch. If PredBB ends with an
2137 // unconditional branch, we should be merging PredBB and BB instead. For
2138 // simplicity, we don't deal with a switch.
2139 BranchInst *PredBBBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2140 if (!PredBBBranch || PredBBBranch->isUnconditional())
2141 return false;
2142
2143 // If PredBB has exactly one incoming edge, we don't gain anything by copying
2144 // PredBB.
2145 if (PredBB->getSinglePredecessor())
2146 return false;
2147
2148 // Don't thread through PredBB if it contains a successor edge to itself, in
2149 // which case we would infinite loop. Suppose we are threading an edge from
2150 // PredPredBB through PredBB and BB to SuccBB with PredBB containing a
2151 // successor edge to itself. If we allowed jump threading in this case, we
2152 // could duplicate PredBB and BB as, say, PredBB.thread and BB.thread. Since
2153 // PredBB.thread has a successor edge to PredBB, we would immediately come up
2154 // with another jump threading opportunity from PredBB.thread through PredBB
2155 // and BB to SuccBB. This jump threading would repeatedly occur. That is, we
2156 // would keep peeling one iteration from PredBB.
2157 if (llvm::is_contained(successors(PredBB), PredBB))
2158 return false;
2159
2160 // Don't thread across a loop header.
2161 if (LoopHeaders.count(PredBB))
2162 return false;
2163
2164 // Avoid complication with duplicating EH pads.
2165 if (PredBB->isEHPad())
2166 return false;
2167
2168 // Find a predecessor that we can thread. For simplicity, we only consider a
2169 // successor edge out of BB to which we thread exactly one incoming edge into
2170 // PredBB.
2171 unsigned ZeroCount = 0;
2172 unsigned OneCount = 0;
2173 BasicBlock *ZeroPred = nullptr;
2174 BasicBlock *OnePred = nullptr;
2175 for (BasicBlock *P : predecessors(PredBB)) {
2176 // If PredPred ends with IndirectBrInst, we can't handle it.
2177 if (isa<IndirectBrInst>(P->getTerminator()))
2178 continue;
2179 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(
2180 evaluateOnPredecessorEdge(BB, P, Cond))) {
2181 if (CI->isZero()) {
2182 ZeroCount++;
2183 ZeroPred = P;
2184 } else if (CI->isOne()) {
2185 OneCount++;
2186 OnePred = P;
2187 }
2188 }
2189 }
2190
2191 // Disregard complicated cases where we have to thread multiple edges.
2192 BasicBlock *PredPredBB;
2193 if (ZeroCount == 1) {
2194 PredPredBB = ZeroPred;
2195 } else if (OneCount == 1) {
2196 PredPredBB = OnePred;
2197 } else {
2198 return false;
2199 }
2200
2201 BasicBlock *SuccBB = CondBr->getSuccessor(PredPredBB == ZeroPred);
2202
2203 // If threading to the same block as we come from, we would infinite loop.
2204 if (SuccBB == BB) {
2205 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading across BB '"
<< BB->getName() << "' - would thread to self!\n"
; } } while (false)
2206 << "' - would thread to self!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading across BB '"
<< BB->getName() << "' - would thread to self!\n"
; } } while (false)
;
2207 return false;
2208 }
2209
2210 // If threading this would thread across a loop header, don't thread the edge.
2211 // See the comments above findLoopHeaders for justifications and caveats.
2212 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2213 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2214 bool BBIsHeader = LoopHeaders.count(BB);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2215 bool SuccIsHeader = LoopHeaders.count(SuccBB);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2216 dbgs() << " Not threading across "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2217 << (BBIsHeader ? "loop header BB '" : "block BB '")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2218 << BB->getName() << "' to dest "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2219 << (SuccIsHeader ? "loop header BB '" : "block BB '")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2220 << SuccBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2221 << "' - it might create an irreducible loop!\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2222 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
;
2223 return false;
2224 }
2225
2226 // Compute the cost of duplicating BB and PredBB.
2227 unsigned BBCost = getJumpThreadDuplicationCost(
2228 TTI, BB, BB->getTerminator(), BBDupThreshold);
2229 unsigned PredBBCost = getJumpThreadDuplicationCost(
2230 TTI, PredBB, PredBB->getTerminator(), BBDupThreshold);
2231
2232 // Give up if costs are too high. We need to check BBCost and PredBBCost
2233 // individually before checking their sum because getJumpThreadDuplicationCost
2234 // return (unsigned)~0 for those basic blocks that cannot be duplicated.
2235 if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold ||
2236 BBCost + PredBBCost > BBDupThreshold) {
2237 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << PredBBCost
<< " for PredBB, " << BBCost << "for BB\n"
; } } while (false)
2238 << "' - Cost is too high: " << PredBBCostdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << PredBBCost
<< " for PredBB, " << BBCost << "for BB\n"
; } } while (false)
2239 << " for PredBB, " << BBCost << "for BB\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << PredBBCost
<< " for PredBB, " << BBCost << "for BB\n"
; } } while (false)
;
2240 return false;
2241 }
2242
2243 // Now we are ready to duplicate PredBB.
2244 threadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB);
2245 return true;
2246}
2247
2248void JumpThreadingPass::threadThroughTwoBasicBlocks(BasicBlock *PredPredBB,
2249 BasicBlock *PredBB,
2250 BasicBlock *BB,
2251 BasicBlock *SuccBB) {
2252 LLVM_DEBUG(dbgs() << " Threading through '" << PredBB->getName() << "' and '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading through '"
<< PredBB->getName() << "' and '" << BB
->getName() << "'\n"; } } while (false)
2253 << BB->getName() << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading through '"
<< PredBB->getName() << "' and '" << BB
->getName() << "'\n"; } } while (false)
;
2254
2255 BranchInst *CondBr = cast<BranchInst>(BB->getTerminator());
2256 BranchInst *PredBBBranch = cast<BranchInst>(PredBB->getTerminator());
2257
2258 BasicBlock *NewBB =
2259 BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread",
2260 PredBB->getParent(), PredBB);
2261 NewBB->moveAfter(PredBB);
2262
2263 // Set the block frequency of NewBB.
2264 if (HasProfileData) {
2265 auto NewBBFreq = BFI->getBlockFreq(PredPredBB) *
2266 BPI->getEdgeProbability(PredPredBB, PredBB);
2267 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2268 }
2269
2270 // We are going to have to map operands from the original BB block to the new
2271 // copy of the block 'NewBB'. If there are PHI nodes in PredBB, evaluate them
2272 // to account for entry from PredPredBB.
2273 DenseMap<Instruction *, Value *> ValueMapping =
2274 cloneInstructions(PredBB->begin(), PredBB->end(), NewBB, PredPredBB);
2275
2276 // Copy the edge probabilities from PredBB to NewBB.
2277 if (HasProfileData)
2278 BPI->copyEdgeProbabilities(PredBB, NewBB);
2279
2280 // Update the terminator of PredPredBB to jump to NewBB instead of PredBB.
2281 // This eliminates predecessors from PredPredBB, which requires us to simplify
2282 // any PHI nodes in PredBB.
2283 Instruction *PredPredTerm = PredPredBB->getTerminator();
2284 for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i)
2285 if (PredPredTerm->getSuccessor(i) == PredBB) {
2286 PredBB->removePredecessor(PredPredBB, true);
2287 PredPredTerm->setSuccessor(i, NewBB);
2288 }
2289
2290 addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB,
2291 ValueMapping);
2292 addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB,
2293 ValueMapping);
2294
2295 DTU->applyUpdatesPermissive(
2296 {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)},
2297 {DominatorTree::Insert, NewBB, CondBr->getSuccessor(1)},
2298 {DominatorTree::Insert, PredPredBB, NewBB},
2299 {DominatorTree::Delete, PredPredBB, PredBB}});
2300
2301 updateSSA(PredBB, NewBB, ValueMapping);
2302
2303 // Clean up things like PHI nodes with single operands, dead instructions,
2304 // etc.
2305 SimplifyInstructionsInBlock(NewBB, TLI);
2306 SimplifyInstructionsInBlock(PredBB, TLI);
2307
2308 SmallVector<BasicBlock *, 1> PredsToFactor;
2309 PredsToFactor.push_back(NewBB);
2310 threadEdge(BB, PredsToFactor, SuccBB);
2311}
2312
2313/// tryThreadEdge - Thread an edge if it's safe and profitable to do so.
2314bool JumpThreadingPass::tryThreadEdge(
2315 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs,
2316 BasicBlock *SuccBB) {
2317 // If threading to the same block as we come from, we would infinite loop.
2318 if (SuccBB == BB) {
2319 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading across BB '"
<< BB->getName() << "' - would thread to self!\n"
; } } while (false)
2320 << "' - would thread to self!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading across BB '"
<< BB->getName() << "' - would thread to self!\n"
; } } while (false)
;
2321 return false;
2322 }
2323
2324 // If threading this would thread across a loop header, don't thread the edge.
2325 // See the comments above findLoopHeaders for justifications and caveats.
2326 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2327 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2328 bool BBIsHeader = LoopHeaders.count(BB);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2329 bool SuccIsHeader = LoopHeaders.count(SuccBB);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2330 dbgs() << " Not threading across "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2331 << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2332 << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2333 << SuccBB->getName() << "' - it might create an irreducible loop!\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2334 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
;
2335 return false;
2336 }
2337
2338 unsigned JumpThreadCost = getJumpThreadDuplicationCost(
2339 TTI, BB, BB->getTerminator(), BBDupThreshold);
2340 if (JumpThreadCost > BBDupThreshold) {
2341 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << JumpThreadCost
<< "\n"; } } while (false)
2342 << "' - Cost is too high: " << JumpThreadCost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << JumpThreadCost
<< "\n"; } } while (false)
;
2343 return false;
2344 }
2345
2346 threadEdge(BB, PredBBs, SuccBB);
2347 return true;
2348}
2349
2350/// threadEdge - We have decided that it is safe and profitable to factor the
2351/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
2352/// across BB. Transform the IR to reflect this change.
2353void JumpThreadingPass::threadEdge(BasicBlock *BB,
2354 const SmallVectorImpl<BasicBlock *> &PredBBs,
2355 BasicBlock *SuccBB) {
2356 assert(SuccBB != BB && "Don't create an infinite loop")(static_cast <bool> (SuccBB != BB && "Don't create an infinite loop"
) ? void (0) : __assert_fail ("SuccBB != BB && \"Don't create an infinite loop\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 2356, __extension__
__PRETTY_FUNCTION__))
;
2357
2358 assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) &&(static_cast <bool> (!LoopHeaders.count(BB) && !
LoopHeaders.count(SuccBB) && "Don't thread across loop headers"
) ? void (0) : __assert_fail ("!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) && \"Don't thread across loop headers\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 2359, __extension__
__PRETTY_FUNCTION__))
2359 "Don't thread across loop headers")(static_cast <bool> (!LoopHeaders.count(BB) && !
LoopHeaders.count(SuccBB) && "Don't thread across loop headers"
) ? void (0) : __assert_fail ("!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) && \"Don't thread across loop headers\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 2359, __extension__
__PRETTY_FUNCTION__))
;
2360
2361 // And finally, do it! Start by factoring the predecessors if needed.
2362 BasicBlock *PredBB;
2363 if (PredBBs.size() == 1)
2364 PredBB = PredBBs[0];
2365 else {
2366 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
2367 << " common predecessors.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
;
2368 PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
2369 }
2370
2371 // And finally, do it!
2372 LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading edge from '"
<< PredBB->getName() << "' to '" << SuccBB
->getName() << ", across block:\n " << *BB <<
"\n"; } } while (false)
2373 << "' to '" << SuccBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading edge from '"
<< PredBB->getName() << "' to '" << SuccBB
->getName() << ", across block:\n " << *BB <<
"\n"; } } while (false)
2374 << ", across block:\n " << *BB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading edge from '"
<< PredBB->getName() << "' to '" << SuccBB
->getName() << ", across block:\n " << *BB <<
"\n"; } } while (false)
;
2375
2376 LVI->threadEdge(PredBB, BB, SuccBB);
2377
2378 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
2379 BB->getName()+".thread",
2380 BB->getParent(), BB);
2381 NewBB->moveAfter(PredBB);
2382
2383 // Set the block frequency of NewBB.
2384 if (HasProfileData) {
2385 auto NewBBFreq =
2386 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
2387 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2388 }
2389
2390 // Copy all the instructions from BB to NewBB except the terminator.
2391 DenseMap<Instruction *, Value *> ValueMapping =
2392 cloneInstructions(BB->begin(), std::prev(BB->end()), NewBB, PredBB);
2393
2394 // We didn't copy the terminator from BB over to NewBB, because there is now
2395 // an unconditional jump to SuccBB. Insert the unconditional jump.
2396 BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
2397 NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
2398
2399 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
2400 // PHI nodes for NewBB now.
2401 addPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
2402
2403 // Update the terminator of PredBB to jump to NewBB instead of BB. This
2404 // eliminates predecessors from BB, which requires us to simplify any PHI
2405 // nodes in BB.
2406 Instruction *PredTerm = PredBB->getTerminator();
2407 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
2408 if (PredTerm->getSuccessor(i) == BB) {
2409 BB->removePredecessor(PredBB, true);
2410 PredTerm->setSuccessor(i, NewBB);
2411 }
2412
2413 // Enqueue required DT updates.
2414 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB},
2415 {DominatorTree::Insert, PredBB, NewBB},
2416 {DominatorTree::Delete, PredBB, BB}});
2417
2418 updateSSA(BB, NewBB, ValueMapping);
2419
2420 // At this point, the IR is fully up to date and consistent. Do a quick scan
2421 // over the new instructions and zap any that are constants or dead. This
2422 // frequently happens because of phi translation.
2423 SimplifyInstructionsInBlock(NewBB, TLI);
2424
2425 // Update the edge weight from BB to SuccBB, which should be less than before.
2426 updateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
2427
2428 // Threaded an edge!
2429 ++NumThreads;
2430}
2431
2432/// Create a new basic block that will be the predecessor of BB and successor of
2433/// all blocks in Preds. When profile data is available, update the frequency of
2434/// this new block.
2435BasicBlock *JumpThreadingPass::splitBlockPreds(BasicBlock *BB,
2436 ArrayRef<BasicBlock *> Preds,
2437 const char *Suffix) {
2438 SmallVector<BasicBlock *, 2> NewBBs;
2439
2440 // Collect the frequencies of all predecessors of BB, which will be used to
2441 // update the edge weight of the result of splitting predecessors.
2442 DenseMap<BasicBlock *, BlockFrequency> FreqMap;
2443 if (HasProfileData)
2444 for (auto *Pred : Preds)
2445 FreqMap.insert(std::make_pair(
2446 Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
2447
2448 // In the case when BB is a LandingPad block we create 2 new predecessors
2449 // instead of just one.
2450 if (BB->isLandingPad()) {
2451 std::string NewName = std::string(Suffix) + ".split-lp";
2452 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs);
2453 } else {
2454 NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix));
2455 }
2456
2457 std::vector<DominatorTree::UpdateType> Updates;
2458 Updates.reserve((2 * Preds.size()) + NewBBs.size());
2459 for (auto *NewBB : NewBBs) {
2460 BlockFrequency NewBBFreq(0);
2461 Updates.push_back({DominatorTree::Insert, NewBB, BB});
2462 for (auto *Pred : predecessors(NewBB)) {
2463 Updates.push_back({DominatorTree::Delete, Pred, BB});
2464 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
2465 if (HasProfileData) // Update frequencies between Pred -> NewBB.
2466 NewBBFreq += FreqMap.lookup(Pred);
2467 }
2468 if (HasProfileData) // Apply the summed frequency to NewBB.
2469 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2470 }
2471
2472 DTU->applyUpdatesPermissive(Updates);
2473 return NewBBs[0];
2474}
2475
2476bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
2477 const Instruction *TI = BB->getTerminator();
2478 assert(TI->getNumSuccessors() > 1 && "not a split")(static_cast <bool> (TI->getNumSuccessors() > 1 &&
"not a split") ? void (0) : __assert_fail ("TI->getNumSuccessors() > 1 && \"not a split\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 2478, __extension__
__PRETTY_FUNCTION__))
;
2479
2480 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
2481 if (!WeightsNode)
2482 return false;
2483
2484 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
2485 if (MDName->getString() != "branch_weights")
2486 return false;
2487
2488 // Ensure there are weights for all of the successors. Note that the first
2489 // operand to the metadata node is a name, not a weight.
2490 return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1;
2491}
2492
2493/// Update the block frequency of BB and branch weight and the metadata on the
2494/// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
2495/// Freq(PredBB->BB) / Freq(BB->SuccBB).
2496void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
2497 BasicBlock *BB,
2498 BasicBlock *NewBB,
2499 BasicBlock *SuccBB) {
2500 if (!HasProfileData)
2501 return;
2502
2503 assert(BFI && BPI && "BFI & BPI should have been created here")(static_cast <bool> (BFI && BPI && "BFI & BPI should have been created here"
) ? void (0) : __assert_fail ("BFI && BPI && \"BFI & BPI should have been created here\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 2503, __extension__
__PRETTY_FUNCTION__))
;
2504
2505 // As the edge from PredBB to BB is deleted, we have to update the block
2506 // frequency of BB.
2507 auto BBOrigFreq = BFI->getBlockFreq(BB);
2508 auto NewBBFreq = BFI->getBlockFreq(NewBB);
2509 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
2510 auto BBNewFreq = BBOrigFreq - NewBBFreq;
2511 BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
2512
2513 // Collect updated outgoing edges' frequencies from BB and use them to update
2514 // edge probabilities.
2515 SmallVector<uint64_t, 4> BBSuccFreq;
2516 for (BasicBlock *Succ : successors(BB)) {
2517 auto SuccFreq = (Succ == SuccBB)
2518 ? BB2SuccBBFreq - NewBBFreq
2519 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
2520 BBSuccFreq.push_back(SuccFreq.getFrequency());
2521 }
2522
2523 uint64_t MaxBBSuccFreq =
2524 *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
2525
2526 SmallVector<BranchProbability, 4> BBSuccProbs;
2527 if (MaxBBSuccFreq == 0)
2528 BBSuccProbs.assign(BBSuccFreq.size(),
2529 {1, static_cast<unsigned>(BBSuccFreq.size())});
2530 else {
2531 for (uint64_t Freq : BBSuccFreq)
2532 BBSuccProbs.push_back(
2533 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
2534 // Normalize edge probabilities so that they sum up to one.
2535 BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
2536 BBSuccProbs.end());
2537 }
2538
2539 // Update edge probabilities in BPI.
2540 BPI->setEdgeProbability(BB, BBSuccProbs);
2541
2542 // Update the profile metadata as well.
2543 //
2544 // Don't do this if the profile of the transformed blocks was statically
2545 // estimated. (This could occur despite the function having an entry
2546 // frequency in completely cold parts of the CFG.)
2547 //
2548 // In this case we don't want to suggest to subsequent passes that the
2549 // calculated weights are fully consistent. Consider this graph:
2550 //
2551 // check_1
2552 // 50% / |
2553 // eq_1 | 50%
2554 // \ |
2555 // check_2
2556 // 50% / |
2557 // eq_2 | 50%
2558 // \ |
2559 // check_3
2560 // 50% / |
2561 // eq_3 | 50%
2562 // \ |
2563 //
2564 // Assuming the blocks check_* all compare the same value against 1, 2 and 3,
2565 // the overall probabilities are inconsistent; the total probability that the
2566 // value is either 1, 2 or 3 is 150%.
2567 //
2568 // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3
2569 // becomes 0%. This is even worse if the edge whose probability becomes 0% is
2570 // the loop exit edge. Then based solely on static estimation we would assume
2571 // the loop was extremely hot.
2572 //
2573 // FIXME this locally as well so that BPI and BFI are consistent as well. We
2574 // shouldn't make edges extremely likely or unlikely based solely on static
2575 // estimation.
2576 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) {
2577 SmallVector<uint32_t, 4> Weights;
2578 for (auto Prob : BBSuccProbs)
2579 Weights.push_back(Prob.getNumerator());
2580
2581 auto TI = BB->getTerminator();
2582 TI->setMetadata(
2583 LLVMContext::MD_prof,
2584 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
2585 }
2586}
2587
2588/// duplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
2589/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
2590/// If we can duplicate the contents of BB up into PredBB do so now, this
2591/// improves the odds that the branch will be on an analyzable instruction like
2592/// a compare.
2593bool JumpThreadingPass::duplicateCondBranchOnPHIIntoPred(
2594 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
2595 assert(!PredBBs.empty() && "Can't handle an empty set")(static_cast <bool> (!PredBBs.empty() && "Can't handle an empty set"
) ? void (0) : __assert_fail ("!PredBBs.empty() && \"Can't handle an empty set\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 2595, __extension__
__PRETTY_FUNCTION__))
;
2596
2597 // If BB is a loop header, then duplicating this block outside the loop would
2598 // cause us to transform this into an irreducible loop, don't do this.
2599 // See the comments above findLoopHeaders for justifications and caveats.
2600 if (LoopHeaders.count(BB)) {
2601 LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating loop header '"
<< BB->getName() << "' into predecessor block '"
<< PredBBs[0]->getName() << "' - it might create an irreducible loop!\n"
; } } while (false)
2602 << "' into predecessor block '" << PredBBs[0]->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating loop header '"
<< BB->getName() << "' into predecessor block '"
<< PredBBs[0]->getName() << "' - it might create an irreducible loop!\n"
; } } while (false)
2603 << "' - it might create an irreducible loop!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating loop header '"
<< BB->getName() << "' into predecessor block '"
<< PredBBs[0]->getName() << "' - it might create an irreducible loop!\n"
; } } while (false)
;
2604 return false;
2605 }
2606
2607 unsigned DuplicationCost = getJumpThreadDuplicationCost(
2608 TTI, BB, BB->getTerminator(), BBDupThreshold);
2609 if (DuplicationCost > BBDupThreshold) {
2610 LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating BB '"
<< BB->getName() << "' - Cost is too high: " <<
DuplicationCost << "\n"; } } while (false)
2611 << "' - Cost is too high: " << DuplicationCost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating BB '"
<< BB->getName() << "' - Cost is too high: " <<
DuplicationCost << "\n"; } } while (false)
;
2612 return false;
2613 }
2614
2615 // And finally, do it! Start by factoring the predecessors if needed.
2616 std::vector<DominatorTree::UpdateType> Updates;
2617 BasicBlock *PredBB;
2618 if (PredBBs.size() == 1)
2619 PredBB = PredBBs[0];
2620 else {
2621 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
2622 << " common predecessors.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
;
2623 PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
2624 }
2625 Updates.push_back({DominatorTree::Delete, PredBB, BB});
2626
2627 // Okay, we decided to do this! Clone all the instructions in BB onto the end
2628 // of PredBB.
2629 LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
2630 << "' into end of '" << PredBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
2631 << "' to eliminate branch on phi. Cost: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
2632 << DuplicationCost << " block is:" << *BB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
;
2633
2634 // Unless PredBB ends with an unconditional branch, split the edge so that we
2635 // can just clone the bits from BB into the end of the new PredBB.
2636 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2637
2638 if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
2639 BasicBlock *OldPredBB = PredBB;
2640 PredBB = SplitEdge(OldPredBB, BB);
2641 Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB});
2642 Updates.push_back({DominatorTree::Insert, PredBB, BB});
2643 Updates.push_back({DominatorTree::Delete, OldPredBB, BB});
2644 OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
2645 }
2646
2647 // We are going to have to map operands from the original BB block into the
2648 // PredBB block. Evaluate PHI nodes in BB.
2649 DenseMap<Instruction*, Value*> ValueMapping;
2650
2651 BasicBlock::iterator BI = BB->begin();
2652 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
2653 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
2654 // Clone the non-phi instructions of BB into PredBB, keeping track of the
2655 // mapping and using it to remap operands in the cloned instructions.
2656 for (; BI != BB->end(); ++BI) {
2657 Instruction *New = BI->clone();
2658
2659 // Remap operands to patch up intra-block references.
2660 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2661 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2662 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
2663 if (I != ValueMapping.end())
2664 New->setOperand(i, I->second);
2665 }
2666
2667 // If this instruction can be simplified after the operands are updated,
2668 // just use the simplified value instead. This frequently happens due to
2669 // phi translation.
2670 if (Value *IV = simplifyInstruction(
2671 New,
2672 {BB->getModule()->getDataLayout(), TLI, nullptr, nullptr, New})) {
2673 ValueMapping[&*BI] = IV;
2674 if (!New->mayHaveSideEffects()) {
2675 New->deleteValue();
2676 New = nullptr;
2677 }
2678 } else {
2679 ValueMapping[&*BI] = New;
2680 }
2681 if (New) {
2682 // Otherwise, insert the new instruction into the block.
2683 New->setName(BI->getName());
2684 PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
2685 // Update Dominance from simplified New instruction operands.
2686 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2687 if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i)))
2688 Updates.push_back({DominatorTree::Insert, PredBB, SuccBB});
2689 }
2690 }
2691
2692 // Check to see if the targets of the branch had PHI nodes. If so, we need to
2693 // add entries to the PHI nodes for branch from PredBB now.
2694 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
2695 addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
2696 ValueMapping);
2697 addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
2698 ValueMapping);
2699
2700 updateSSA(BB, PredBB, ValueMapping);
2701
2702 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
2703 // that we nuked.
2704 BB->removePredecessor(PredBB, true);
2705
2706 // Remove the unconditional branch at the end of the PredBB block.
2707 OldPredBranch->eraseFromParent();
2708 if (HasProfileData)
2709 BPI->copyEdgeProbabilities(BB, PredBB);
2710 DTU->applyUpdatesPermissive(Updates);
2711
2712 ++NumDupes;
2713 return true;
2714}
2715
2716// Pred is a predecessor of BB with an unconditional branch to BB. SI is
2717// a Select instruction in Pred. BB has other predecessors and SI is used in
2718// a PHI node in BB. SI has no other use.
2719// A new basic block, NewBB, is created and SI is converted to compare and
2720// conditional branch. SI is erased from parent.
2721void JumpThreadingPass::unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB,
2722 SelectInst *SI, PHINode *SIUse,
2723 unsigned Idx) {
2724 // Expand the select.
2725 //
2726 // Pred --
2727 // | v
2728 // | NewBB
2729 // | |
2730 // |-----
2731 // v
2732 // BB
2733 BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator());
2734 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
2735 BB->getParent(), BB);
2736 // Move the unconditional branch to NewBB.
2737 PredTerm->removeFromParent();
2738 NewBB->getInstList().insert(NewBB->end(), PredTerm);
2739 // Create a conditional branch and update PHI nodes.
2740 auto *BI = BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
2741 BI->applyMergedLocation(PredTerm->getDebugLoc(), SI->getDebugLoc());
2742 SIUse->setIncomingValue(Idx, SI->getFalseValue());
2743 SIUse->addIncoming(SI->getTrueValue(), NewBB);
2744
2745 // The select is now dead.
2746 SI->eraseFromParent();
2747 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB},
2748 {DominatorTree::Insert, Pred, NewBB}});
2749
2750 // Update any other PHI nodes in BB.
2751 for (BasicBlock::iterator BI = BB->begin();
2752 PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
2753 if (Phi != SIUse)
2754 Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
2755}
2756
2757bool JumpThreadingPass::tryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) {
2758 PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition());
2759
2760 if (!CondPHI || CondPHI->getParent() != BB)
2761 return false;
2762
2763 for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) {
2764 BasicBlock *Pred = CondPHI->getIncomingBlock(I);
2765 SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I));
2766
2767 // The second and third condition can be potentially relaxed. Currently
2768 // the conditions help to simplify the code and allow us to reuse existing
2769 // code, developed for tryToUnfoldSelect(CmpInst *, BasicBlock *)
2770 if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse())
2771 continue;
2772
2773 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2774 if (!PredTerm || !PredTerm->isUnconditional())
2775 continue;
2776
2777 unfoldSelectInstr(Pred, BB, PredSI, CondPHI, I);
2778 return true;
2779 }
2780 return false;
2781}
2782
2783/// tryToUnfoldSelect - Look for blocks of the form
2784/// bb1:
2785/// %a = select
2786/// br bb2
2787///
2788/// bb2:
2789/// %p = phi [%a, %bb1] ...
2790/// %c = icmp %p
2791/// br i1 %c
2792///
2793/// And expand the select into a branch structure if one of its arms allows %c
2794/// to be folded. This later enables threading from bb1 over bb2.
2795bool JumpThreadingPass::tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
2796 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2797 PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
2798 Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
2799
2800 if (!CondBr || !CondBr->isConditional() || !CondLHS ||
2801 CondLHS->getParent() != BB)
2802 return false;
2803
2804 for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
2805 BasicBlock *Pred = CondLHS->getIncomingBlock(I);
2806 SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
2807
2808 // Look if one of the incoming values is a select in the corresponding
2809 // predecessor.
2810 if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
2811 continue;
2812
2813 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2814 if (!PredTerm || !PredTerm->isUnconditional())
2815 continue;
2816
2817 // Now check if one of the select values would allow us to constant fold the
2818 // terminator in BB. We don't do the transform if both sides fold, those
2819 // cases will be threaded in any case.
2820 LazyValueInfo::Tristate LHSFolds =
2821 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
2822 CondRHS, Pred, BB, CondCmp);
2823 LazyValueInfo::Tristate RHSFolds =
2824 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
2825 CondRHS, Pred, BB, CondCmp);
2826 if ((LHSFolds != LazyValueInfo::Unknown ||
2827 RHSFolds != LazyValueInfo::Unknown) &&
2828 LHSFolds != RHSFolds) {
2829 unfoldSelectInstr(Pred, BB, SI, CondLHS, I);
2830 return true;
2831 }
2832 }
2833 return false;
2834}
2835
2836/// tryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the
2837/// same BB in the form
2838/// bb:
2839/// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
2840/// %s = select %p, trueval, falseval
2841///
2842/// or
2843///
2844/// bb:
2845/// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ...
2846/// %c = cmp %p, 0
2847/// %s = select %c, trueval, falseval
2848///
2849/// And expand the select into a branch structure. This later enables
2850/// jump-threading over bb in this pass.
2851///
2852/// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
2853/// select if the associated PHI has at least one constant. If the unfolded
2854/// select is not jump-threaded, it will be folded again in the later
2855/// optimizations.
2856bool JumpThreadingPass::tryToUnfoldSelectInCurrBB(BasicBlock *BB) {
2857 // This transform would reduce the quality of msan diagnostics.
2858 // Disable this transform under MemorySanitizer.
2859 if (BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory))
2860 return false;
2861
2862 // If threading this would thread across a loop header, don't thread the edge.
2863 // See the comments above findLoopHeaders for justifications and caveats.
2864 if (LoopHeaders.count(BB))
2865 return false;
2866
2867 for (BasicBlock::iterator BI = BB->begin();
2868 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2869 // Look for a Phi having at least one constant incoming value.
2870 if (llvm::all_of(PN->incoming_values(),
2871 [](Value *V) { return !isa<ConstantInt>(V); }))
2872 continue;
2873
2874 auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) {
2875 using namespace PatternMatch;
2876
2877 // Check if SI is in BB and use V as condition.
2878 if (SI->getParent() != BB)
2879 return false;
2880 Value *Cond = SI->getCondition();
2881 bool IsAndOr = match(SI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()));
2882 return Cond && Cond == V && Cond->getType()->isIntegerTy(1) && !IsAndOr;
2883 };
2884
2885 SelectInst *SI = nullptr;
2886 for (Use &U : PN->uses()) {
2887 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
2888 // Look for a ICmp in BB that compares PN with a constant and is the
2889 // condition of a Select.
2890 if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
2891 isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
2892 if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
2893 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
2894 SI = SelectI;
2895 break;
2896 }
2897 } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
2898 // Look for a Select in BB that uses PN as condition.
2899 if (isUnfoldCandidate(SelectI, U.get())) {
2900 SI = SelectI;
2901 break;
2902 }
2903 }
2904 }
2905
2906 if (!SI)
2907 continue;
2908 // Expand the select.
2909 Value *Cond = SI->getCondition();
2910 if (!isGuaranteedNotToBeUndefOrPoison(Cond, nullptr, SI))
2911 Cond = new FreezeInst(Cond, "cond.fr", SI);
2912 Instruction *Term = SplitBlockAndInsertIfThen(Cond, SI, false);
2913 BasicBlock *SplitBB = SI->getParent();
2914 BasicBlock *NewBB = Term->getParent();
2915 PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI);
2916 NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
2917 NewPN->addIncoming(SI->getFalseValue(), BB);
2918 SI->replaceAllUsesWith(NewPN);
2919 SI->eraseFromParent();
2920 // NewBB and SplitBB are newly created blocks which require insertion.
2921 std::vector<DominatorTree::UpdateType> Updates;
2922 Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
2923 Updates.push_back({DominatorTree::Insert, BB, SplitBB});
2924 Updates.push_back({DominatorTree::Insert, BB, NewBB});
2925 Updates.push_back({DominatorTree::Insert, NewBB, SplitBB});
2926 // BB's successors were moved to SplitBB, update DTU accordingly.
2927 for (auto *Succ : successors(SplitBB)) {
2928 Updates.push_back({DominatorTree::Delete, BB, Succ});
2929 Updates.push_back({DominatorTree::Insert, SplitBB, Succ});
2930 }
2931 DTU->applyUpdatesPermissive(Updates);
2932 return true;
2933 }
2934 return false;
2935}
2936
2937/// Try to propagate a guard from the current BB into one of its predecessors
2938/// in case if another branch of execution implies that the condition of this
2939/// guard is always true. Currently we only process the simplest case that
2940/// looks like:
2941///
2942/// Start:
2943/// %cond = ...
2944/// br i1 %cond, label %T1, label %F1
2945/// T1:
2946/// br label %Merge
2947/// F1:
2948/// br label %Merge
2949/// Merge:
2950/// %condGuard = ...
2951/// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ]
2952///
2953/// And cond either implies condGuard or !condGuard. In this case all the
2954/// instructions before the guard can be duplicated in both branches, and the
2955/// guard is then threaded to one of them.
2956bool JumpThreadingPass::processGuards(BasicBlock *BB) {
2957 using namespace PatternMatch;
2958
2959 // We only want to deal with two predecessors.
2960 BasicBlock *Pred1, *Pred2;
2961 auto PI = pred_begin(BB), PE = pred_end(BB);
2962 if (PI == PE)
2963 return false;
2964 Pred1 = *PI++;
2965 if (PI == PE)
2966 return false;
2967 Pred2 = *PI++;
2968 if (PI != PE)
2969 return false;
2970 if (Pred1 == Pred2)
2971 return false;
2972
2973 // Try to thread one of the guards of the block.
2974 // TODO: Look up deeper than to immediate predecessor?
2975 auto *Parent = Pred1->getSinglePredecessor();
2976 if (!Parent || Parent != Pred2->getSinglePredecessor())
2977 return false;
2978
2979 if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
2980 for (auto &I : *BB)
2981 if (isGuard(&I) && threadGuard(BB, cast<IntrinsicInst>(&I), BI))
2982 return true;
2983
2984 return false;
2985}
2986
2987/// Try to propagate the guard from BB which is the lower block of a diamond
2988/// to one of its branches, in case if diamond's condition implies guard's
2989/// condition.
2990bool JumpThreadingPass::threadGuard(BasicBlock *BB, IntrinsicInst *Guard,
2991 BranchInst *BI) {
2992 assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?")(static_cast <bool> (BI->getNumSuccessors() == 2 &&
"Wrong number of successors?") ? void (0) : __assert_fail ("BI->getNumSuccessors() == 2 && \"Wrong number of successors?\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 2992, __extension__
__PRETTY_FUNCTION__))
;
2993 assert(BI->isConditional() && "Unconditional branch has 2 successors?")(static_cast <bool> (BI->isConditional() && "Unconditional branch has 2 successors?"
) ? void (0) : __assert_fail ("BI->isConditional() && \"Unconditional branch has 2 successors?\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 2993, __extension__
__PRETTY_FUNCTION__))
;
2994 Value *GuardCond = Guard->getArgOperand(0);
2995 Value *BranchCond = BI->getCondition();
2996 BasicBlock *TrueDest = BI->getSuccessor(0);
2997 BasicBlock *FalseDest = BI->getSuccessor(1);
2998
2999 auto &DL = BB->getModule()->getDataLayout();
3000 bool TrueDestIsSafe = false;
3001 bool FalseDestIsSafe = false;
3002
3003 // True dest is safe if BranchCond => GuardCond.
3004 auto Impl = isImpliedCondition(BranchCond, GuardCond, DL);
3005 if (Impl && *Impl)
3006 TrueDestIsSafe = true;
3007 else {
3008 // False dest is safe if !BranchCond => GuardCond.
3009 Impl = isImpliedCondition(BranchCond, GuardCond, DL, /* LHSIsTrue */ false);
3010 if (Impl && *Impl)
3011 FalseDestIsSafe = true;
3012 }
3013
3014 if (!TrueDestIsSafe && !FalseDestIsSafe)
3015 return false;
3016
3017 BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
3018 BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
3019
3020 ValueToValueMapTy UnguardedMapping, GuardedMapping;
3021 Instruction *AfterGuard = Guard->getNextNode();
3022 unsigned Cost =
3023 getJumpThreadDuplicationCost(TTI, BB, AfterGuard, BBDupThreshold);
3024 if (Cost > BBDupThreshold)
3025 return false;
3026 // Duplicate all instructions before the guard and the guard itself to the
3027 // branch where implication is not proved.
3028 BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween(
3029 BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU);
3030 assert(GuardedBlock && "Could not create the guarded block?")(static_cast <bool> (GuardedBlock && "Could not create the guarded block?"
) ? void (0) : __assert_fail ("GuardedBlock && \"Could not create the guarded block?\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 3030, __extension__
__PRETTY_FUNCTION__))
;
3031 // Duplicate all instructions before the guard in the unguarded branch.
3032 // Since we have successfully duplicated the guarded block and this block
3033 // has fewer instructions, we expect it to succeed.
3034 BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween(
3035 BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU);
3036 assert(UnguardedBlock && "Could not create the unguarded block?")(static_cast <bool> (UnguardedBlock && "Could not create the unguarded block?"
) ? void (0) : __assert_fail ("UnguardedBlock && \"Could not create the unguarded block?\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 3036, __extension__
__PRETTY_FUNCTION__))
;
3037 LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "Moved guard " <<
*Guard << " to block " << GuardedBlock->getName
() << "\n"; } } while (false)
3038 << GuardedBlock->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "Moved guard " <<
*Guard << " to block " << GuardedBlock->getName
() << "\n"; } } while (false)
;
3039 // Some instructions before the guard may still have uses. For them, we need
3040 // to create Phi nodes merging their copies in both guarded and unguarded
3041 // branches. Those instructions that have no uses can be just removed.
3042 SmallVector<Instruction *, 4> ToRemove;
3043 for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
3044 if (!isa<PHINode>(&*BI))
3045 ToRemove.push_back(&*BI);
3046
3047 Instruction *InsertionPoint = &*BB->getFirstInsertionPt();
3048 assert(InsertionPoint && "Empty block?")(static_cast <bool> (InsertionPoint && "Empty block?"
) ? void (0) : __assert_fail ("InsertionPoint && \"Empty block?\""
, "llvm/lib/Transforms/Scalar/JumpThreading.cpp", 3048, __extension__
__PRETTY_FUNCTION__))
;
3049 // Substitute with Phis & remove.
3050 for (auto *Inst : reverse(ToRemove)) {
3051 if (!Inst->use_empty()) {
3052 PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
3053 NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
3054 NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
3055 NewPN->insertBefore(InsertionPoint);
3056 Inst->replaceAllUsesWith(NewPN);
3057 }
3058 Inst->eraseFromParent();
3059 }
3060 return true;
3061}