Bug Summary

File:llvm/lib/Transforms/Scalar/JumpThreading.cpp
Warning:line 1417, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name JumpThreading.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Transforms/Scalar -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/Scalar/JumpThreading.cpp

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

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h

1//===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
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 exposes the class definitions of all of the subclasses of the
10// Instruction class. This is meant to be an easy way to get access to all
11// instruction subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_INSTRUCTIONS_H
16#define LLVM_IR_INSTRUCTIONS_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
24#include "llvm/ADT/iterator.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/CallingConv.h"
29#include "llvm/IR/Constant.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/OperandTraits.h"
35#include "llvm/IR/Type.h"
36#include "llvm/IR/Use.h"
37#include "llvm/IR/User.h"
38#include "llvm/IR/Value.h"
39#include "llvm/Support/AtomicOrdering.h"
40#include "llvm/Support/Casting.h"
41#include "llvm/Support/ErrorHandling.h"
42#include <cassert>
43#include <cstddef>
44#include <cstdint>
45#include <iterator>
46
47namespace llvm {
48
49class APInt;
50class ConstantInt;
51class DataLayout;
52class LLVMContext;
53
54//===----------------------------------------------------------------------===//
55// AllocaInst Class
56//===----------------------------------------------------------------------===//
57
58/// an instruction to allocate memory on the stack
59class AllocaInst : public UnaryInstruction {
60 Type *AllocatedType;
61
62protected:
63 // Note: Instruction needs to be a friend here to call cloneImpl.
64 friend class Instruction;
65
66 AllocaInst *cloneImpl() const;
67
68public:
69 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
70 Value *ArraySize = nullptr,
71 const Twine &Name = "",
72 Instruction *InsertBefore = nullptr);
73 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
74 const Twine &Name, BasicBlock *InsertAtEnd);
75
76 AllocaInst(Type *Ty, unsigned AddrSpace,
77 const Twine &Name, Instruction *InsertBefore = nullptr);
78 AllocaInst(Type *Ty, unsigned AddrSpace,
79 const Twine &Name, BasicBlock *InsertAtEnd);
80
81 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, MaybeAlign Align,
82 const Twine &Name = "", Instruction *InsertBefore = nullptr);
83 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, MaybeAlign Align,
84 const Twine &Name, BasicBlock *InsertAtEnd);
85
86 /// Return true if there is an allocation size parameter to the allocation
87 /// instruction that is not 1.
88 bool isArrayAllocation() const;
89
90 /// Get the number of elements allocated. For a simple allocation of a single
91 /// element, this will return a constant 1 value.
92 const Value *getArraySize() const { return getOperand(0); }
93 Value *getArraySize() { return getOperand(0); }
94
95 /// Overload to return most specific pointer type.
96 PointerType *getType() const {
97 return cast<PointerType>(Instruction::getType());
98 }
99
100 /// Get allocation size in bits. Returns None if size can't be determined,
101 /// e.g. in case of a VLA.
102 Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const;
103
104 /// Return the type that is being allocated by the instruction.
105 Type *getAllocatedType() const { return AllocatedType; }
106 /// for use only in special circumstances that need to generically
107 /// transform a whole instruction (eg: IR linking and vectorization).
108 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
109
110 /// Return the alignment of the memory that is being allocated by the
111 /// instruction.
112 MaybeAlign getAlign() const {
113 return decodeMaybeAlign(getSubclassDataFromInstruction() & 31);
114 }
115 // FIXME: Remove this one transition to Align is over.
116 unsigned getAlignment() const {
117 if (const auto MA = getAlign())
118 return MA->value();
119 return 0;
120 }
121 void setAlignment(MaybeAlign Align);
122
123 /// Return true if this alloca is in the entry block of the function and is a
124 /// constant size. If so, the code generator will fold it into the
125 /// prolog/epilog code, so it is basically free.
126 bool isStaticAlloca() const;
127
128 /// Return true if this alloca is used as an inalloca argument to a call. Such
129 /// allocas are never considered static even if they are in the entry block.
130 bool isUsedWithInAlloca() const {
131 return getSubclassDataFromInstruction() & 32;
132 }
133
134 /// Specify whether this alloca is used to represent the arguments to a call.
135 void setUsedWithInAlloca(bool V) {
136 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
137 (V ? 32 : 0));
138 }
139
140 /// Return true if this alloca is used as a swifterror argument to a call.
141 bool isSwiftError() const {
142 return getSubclassDataFromInstruction() & 64;
143 }
144
145 /// Specify whether this alloca is used to represent a swifterror.
146 void setSwiftError(bool V) {
147 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
148 (V ? 64 : 0));
149 }
150
151 // Methods for support type inquiry through isa, cast, and dyn_cast:
152 static bool classof(const Instruction *I) {
153 return (I->getOpcode() == Instruction::Alloca);
154 }
155 static bool classof(const Value *V) {
156 return isa<Instruction>(V) && classof(cast<Instruction>(V));
157 }
158
159private:
160 // Shadow Instruction::setInstructionSubclassData with a private forwarding
161 // method so that subclasses cannot accidentally use it.
162 void setInstructionSubclassData(unsigned short D) {
163 Instruction::setInstructionSubclassData(D);
164 }
165};
166
167//===----------------------------------------------------------------------===//
168// LoadInst Class
169//===----------------------------------------------------------------------===//
170
171/// An instruction for reading from memory. This uses the SubclassData field in
172/// Value to store whether or not the load is volatile.
173class LoadInst : public UnaryInstruction {
174 void AssertOK();
175
176protected:
177 // Note: Instruction needs to be a friend here to call cloneImpl.
178 friend class Instruction;
179
180 LoadInst *cloneImpl() const;
181
182public:
183 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
184 Instruction *InsertBefore = nullptr);
185 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
186 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187 Instruction *InsertBefore = nullptr);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 BasicBlock *InsertAtEnd);
190 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
191 MaybeAlign Align, Instruction *InsertBefore = nullptr);
192 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
193 MaybeAlign Align, BasicBlock *InsertAtEnd);
194 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
195 MaybeAlign Align, AtomicOrdering Order,
196 SyncScope::ID SSID = SyncScope::System,
197 Instruction *InsertBefore = nullptr);
198 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
199 MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID,
200 BasicBlock *InsertAtEnd);
201
202 // Deprecated [opaque pointer types]
203 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
204 Instruction *InsertBefore = nullptr)
205 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
206 InsertBefore) {}
207 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
208 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
209 InsertAtEnd) {}
210 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
211 Instruction *InsertBefore = nullptr)
212 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
213 isVolatile, InsertBefore) {}
214 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
215 BasicBlock *InsertAtEnd)
216 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
217 isVolatile, InsertAtEnd) {}
218 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
219 Instruction *InsertBefore = nullptr)
220 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
221 isVolatile, Align, InsertBefore) {}
222 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
223 BasicBlock *InsertAtEnd)
224 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
225 isVolatile, Align, InsertAtEnd) {}
226 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
227 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
228 Instruction *InsertBefore = nullptr)
229 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
230 isVolatile, Align, Order, SSID, InsertBefore) {}
231 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
232 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
233 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
234 isVolatile, Align, Order, SSID, InsertAtEnd) {}
235
236 /// Return true if this is a load from a volatile memory location.
237 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
238
239 /// Specify whether this is a volatile load or not.
240 void setVolatile(bool V) {
241 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
242 (V ? 1 : 0));
243 }
244
245 /// Return the alignment of the access that is being performed.
246 /// FIXME: Remove this function once transition to Align is over.
247 /// Use getAlign() instead.
248 unsigned getAlignment() const {
249 if (const auto MA = getAlign())
250 return MA->value();
251 return 0;
252 }
253
254 /// Return the alignment of the access that is being performed.
255 MaybeAlign getAlign() const {
256 return decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31);
257 }
258
259 void setAlignment(MaybeAlign Alignment);
260
261 /// Returns the ordering constraint of this load instruction.
262 AtomicOrdering getOrdering() const {
263 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
264 }
265
266 /// Sets the ordering constraint of this load instruction. May not be Release
267 /// or AcquireRelease.
268 void setOrdering(AtomicOrdering Ordering) {
269 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
270 ((unsigned)Ordering << 7));
271 }
272
273 /// Returns the synchronization scope ID of this load instruction.
274 SyncScope::ID getSyncScopeID() const {
275 return SSID;
276 }
277
278 /// Sets the synchronization scope ID of this load instruction.
279 void setSyncScopeID(SyncScope::ID SSID) {
280 this->SSID = SSID;
281 }
282
283 /// Sets the ordering constraint and the synchronization scope ID of this load
284 /// instruction.
285 void setAtomic(AtomicOrdering Ordering,
286 SyncScope::ID SSID = SyncScope::System) {
287 setOrdering(Ordering);
288 setSyncScopeID(SSID);
289 }
290
291 bool isSimple() const { return !isAtomic() && !isVolatile(); }
292
293 bool isUnordered() const {
294 return (getOrdering() == AtomicOrdering::NotAtomic ||
33
Assuming the condition is false
36
Returning the value 1, which participates in a condition later
295 getOrdering() == AtomicOrdering::Unordered) &&
34
Assuming the condition is true
296 !isVolatile();
35
Assuming the condition is true
297 }
298
299 Value *getPointerOperand() { return getOperand(0); }
300 const Value *getPointerOperand() const { return getOperand(0); }
301 static unsigned getPointerOperandIndex() { return 0U; }
302 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
303
304 /// Returns the address space of the pointer operand.
305 unsigned getPointerAddressSpace() const {
306 return getPointerOperandType()->getPointerAddressSpace();
307 }
308
309 // Methods for support type inquiry through isa, cast, and dyn_cast:
310 static bool classof(const Instruction *I) {
311 return I->getOpcode() == Instruction::Load;
312 }
313 static bool classof(const Value *V) {
314 return isa<Instruction>(V) && classof(cast<Instruction>(V));
315 }
316
317private:
318 // Shadow Instruction::setInstructionSubclassData with a private forwarding
319 // method so that subclasses cannot accidentally use it.
320 void setInstructionSubclassData(unsigned short D) {
321 Instruction::setInstructionSubclassData(D);
322 }
323
324 /// The synchronization scope ID of this load instruction. Not quite enough
325 /// room in SubClassData for everything, so synchronization scope ID gets its
326 /// own field.
327 SyncScope::ID SSID;
328};
329
330//===----------------------------------------------------------------------===//
331// StoreInst Class
332//===----------------------------------------------------------------------===//
333
334/// An instruction for storing to memory.
335class StoreInst : public Instruction {
336 void AssertOK();
337
338protected:
339 // Note: Instruction needs to be a friend here to call cloneImpl.
340 friend class Instruction;
341
342 StoreInst *cloneImpl() const;
343
344public:
345 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
346 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
347 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
348 Instruction *InsertBefore = nullptr);
349 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
350 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
351 Instruction *InsertBefore = nullptr);
352 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
353 BasicBlock *InsertAtEnd);
354 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
355 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
356 Instruction *InsertBefore = nullptr);
357 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
358 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd);
359
360 // allocate space for exactly two operands
361 void *operator new(size_t s) {
362 return User::operator new(s, 2);
363 }
364
365 /// Return true if this is a store to a volatile memory location.
366 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
367
368 /// Specify whether this is a volatile store or not.
369 void setVolatile(bool V) {
370 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
371 (V ? 1 : 0));
372 }
373
374 /// Transparently provide more efficient getOperand methods.
375 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
376
377 /// Return the alignment of the access that is being performed
378 /// FIXME: Remove this function once transition to Align is over.
379 /// Use getAlign() instead.
380 unsigned getAlignment() const {
381 if (const auto MA = getAlign())
382 return MA->value();
383 return 0;
384 }
385
386 MaybeAlign getAlign() const {
387 return decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31);
388 }
389
390 void setAlignment(MaybeAlign Alignment);
391
392 /// Returns the ordering constraint of this store instruction.
393 AtomicOrdering getOrdering() const {
394 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
395 }
396
397 /// Sets the ordering constraint of this store instruction. May not be
398 /// Acquire or AcquireRelease.
399 void setOrdering(AtomicOrdering Ordering) {
400 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
401 ((unsigned)Ordering << 7));
402 }
403
404 /// Returns the synchronization scope ID of this store instruction.
405 SyncScope::ID getSyncScopeID() const {
406 return SSID;
407 }
408
409 /// Sets the synchronization scope ID of this store instruction.
410 void setSyncScopeID(SyncScope::ID SSID) {
411 this->SSID = SSID;
412 }
413
414 /// Sets the ordering constraint and the synchronization scope ID of this
415 /// store instruction.
416 void setAtomic(AtomicOrdering Ordering,
417 SyncScope::ID SSID = SyncScope::System) {
418 setOrdering(Ordering);
419 setSyncScopeID(SSID);
420 }
421
422 bool isSimple() const { return !isAtomic() && !isVolatile(); }
423
424 bool isUnordered() const {
425 return (getOrdering() == AtomicOrdering::NotAtomic ||
426 getOrdering() == AtomicOrdering::Unordered) &&
427 !isVolatile();
428 }
429
430 Value *getValueOperand() { return getOperand(0); }
431 const Value *getValueOperand() const { return getOperand(0); }
432
433 Value *getPointerOperand() { return getOperand(1); }
434 const Value *getPointerOperand() const { return getOperand(1); }
435 static unsigned getPointerOperandIndex() { return 1U; }
436 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
437
438 /// Returns the address space of the pointer operand.
439 unsigned getPointerAddressSpace() const {
440 return getPointerOperandType()->getPointerAddressSpace();
441 }
442
443 // Methods for support type inquiry through isa, cast, and dyn_cast:
444 static bool classof(const Instruction *I) {
445 return I->getOpcode() == Instruction::Store;
446 }
447 static bool classof(const Value *V) {
448 return isa<Instruction>(V) && classof(cast<Instruction>(V));
449 }
450
451private:
452 // Shadow Instruction::setInstructionSubclassData with a private forwarding
453 // method so that subclasses cannot accidentally use it.
454 void setInstructionSubclassData(unsigned short D) {
455 Instruction::setInstructionSubclassData(D);
456 }
457
458 /// The synchronization scope ID of this store instruction. Not quite enough
459 /// room in SubClassData for everything, so synchronization scope ID gets its
460 /// own field.
461 SyncScope::ID SSID;
462};
463
464template <>
465struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
466};
467
468DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)StoreInst::op_iterator StoreInst::op_begin() { return OperandTraits
<StoreInst>::op_begin(this); } StoreInst::const_op_iterator
StoreInst::op_begin() const { return OperandTraits<StoreInst
>::op_begin(const_cast<StoreInst*>(this)); } StoreInst
::op_iterator StoreInst::op_end() { return OperandTraits<StoreInst
>::op_end(this); } StoreInst::const_op_iterator StoreInst::
op_end() const { return OperandTraits<StoreInst>::op_end
(const_cast<StoreInst*>(this)); } Value *StoreInst::getOperand
(unsigned i_nocapture) const { ((i_nocapture < OperandTraits
<StoreInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 468, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<StoreInst>::op_begin(const_cast<StoreInst
*>(this))[i_nocapture].get()); } void StoreInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<StoreInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 468, __PRETTY_FUNCTION__)); OperandTraits<StoreInst>::
op_begin(this)[i_nocapture] = Val_nocapture; } unsigned StoreInst
::getNumOperands() const { return OperandTraits<StoreInst>
::operands(this); } template <int Idx_nocapture> Use &
StoreInst::Op() { return this->OpFrom<Idx_nocapture>
(this); } template <int Idx_nocapture> const Use &StoreInst
::Op() const { return this->OpFrom<Idx_nocapture>(this
); }
469
470//===----------------------------------------------------------------------===//
471// FenceInst Class
472//===----------------------------------------------------------------------===//
473
474/// An instruction for ordering other memory operations.
475class FenceInst : public Instruction {
476 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
477
478protected:
479 // Note: Instruction needs to be a friend here to call cloneImpl.
480 friend class Instruction;
481
482 FenceInst *cloneImpl() const;
483
484public:
485 // Ordering may only be Acquire, Release, AcquireRelease, or
486 // SequentiallyConsistent.
487 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
488 SyncScope::ID SSID = SyncScope::System,
489 Instruction *InsertBefore = nullptr);
490 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
491 BasicBlock *InsertAtEnd);
492
493 // allocate space for exactly zero operands
494 void *operator new(size_t s) {
495 return User::operator new(s, 0);
496 }
497
498 /// Returns the ordering constraint of this fence instruction.
499 AtomicOrdering getOrdering() const {
500 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
501 }
502
503 /// Sets the ordering constraint of this fence instruction. May only be
504 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
505 void setOrdering(AtomicOrdering Ordering) {
506 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
507 ((unsigned)Ordering << 1));
508 }
509
510 /// Returns the synchronization scope ID of this fence instruction.
511 SyncScope::ID getSyncScopeID() const {
512 return SSID;
513 }
514
515 /// Sets the synchronization scope ID of this fence instruction.
516 void setSyncScopeID(SyncScope::ID SSID) {
517 this->SSID = SSID;
518 }
519
520 // Methods for support type inquiry through isa, cast, and dyn_cast:
521 static bool classof(const Instruction *I) {
522 return I->getOpcode() == Instruction::Fence;
523 }
524 static bool classof(const Value *V) {
525 return isa<Instruction>(V) && classof(cast<Instruction>(V));
526 }
527
528private:
529 // Shadow Instruction::setInstructionSubclassData with a private forwarding
530 // method so that subclasses cannot accidentally use it.
531 void setInstructionSubclassData(unsigned short D) {
532 Instruction::setInstructionSubclassData(D);
533 }
534
535 /// The synchronization scope ID of this fence instruction. Not quite enough
536 /// room in SubClassData for everything, so synchronization scope ID gets its
537 /// own field.
538 SyncScope::ID SSID;
539};
540
541//===----------------------------------------------------------------------===//
542// AtomicCmpXchgInst Class
543//===----------------------------------------------------------------------===//
544
545/// An instruction that atomically checks whether a
546/// specified value is in a memory location, and, if it is, stores a new value
547/// there. The value returned by this instruction is a pair containing the
548/// original value as first element, and an i1 indicating success (true) or
549/// failure (false) as second element.
550///
551class AtomicCmpXchgInst : public Instruction {
552 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
553 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
554 SyncScope::ID SSID);
555
556protected:
557 // Note: Instruction needs to be a friend here to call cloneImpl.
558 friend class Instruction;
559
560 AtomicCmpXchgInst *cloneImpl() const;
561
562public:
563 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
564 AtomicOrdering SuccessOrdering,
565 AtomicOrdering FailureOrdering,
566 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
567 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
568 AtomicOrdering SuccessOrdering,
569 AtomicOrdering FailureOrdering,
570 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
571
572 // allocate space for exactly three operands
573 void *operator new(size_t s) {
574 return User::operator new(s, 3);
575 }
576
577 /// Return true if this is a cmpxchg from a volatile memory
578 /// location.
579 ///
580 bool isVolatile() const {
581 return getSubclassDataFromInstruction() & 1;
582 }
583
584 /// Specify whether this is a volatile cmpxchg.
585 ///
586 void setVolatile(bool V) {
587 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
588 (unsigned)V);
589 }
590
591 /// Return true if this cmpxchg may spuriously fail.
592 bool isWeak() const {
593 return getSubclassDataFromInstruction() & 0x100;
594 }
595
596 void setWeak(bool IsWeak) {
597 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
598 (IsWeak << 8));
599 }
600
601 /// Transparently provide more efficient getOperand methods.
602 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
603
604 /// Returns the success ordering constraint of this cmpxchg instruction.
605 AtomicOrdering getSuccessOrdering() const {
606 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
607 }
608
609 /// Sets the success ordering constraint of this cmpxchg instruction.
610 void setSuccessOrdering(AtomicOrdering Ordering) {
611 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 612, __PRETTY_FUNCTION__))
612 "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 612, __PRETTY_FUNCTION__))
;
613 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
614 ((unsigned)Ordering << 2));
615 }
616
617 /// Returns the failure ordering constraint of this cmpxchg instruction.
618 AtomicOrdering getFailureOrdering() const {
619 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
620 }
621
622 /// Sets the failure ordering constraint of this cmpxchg instruction.
623 void setFailureOrdering(AtomicOrdering Ordering) {
624 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 625, __PRETTY_FUNCTION__))
625 "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 625, __PRETTY_FUNCTION__))
;
626 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
627 ((unsigned)Ordering << 5));
628 }
629
630 /// Returns the synchronization scope ID of this cmpxchg instruction.
631 SyncScope::ID getSyncScopeID() const {
632 return SSID;
633 }
634
635 /// Sets the synchronization scope ID of this cmpxchg instruction.
636 void setSyncScopeID(SyncScope::ID SSID) {
637 this->SSID = SSID;
638 }
639
640 Value *getPointerOperand() { return getOperand(0); }
641 const Value *getPointerOperand() const { return getOperand(0); }
642 static unsigned getPointerOperandIndex() { return 0U; }
643
644 Value *getCompareOperand() { return getOperand(1); }
645 const Value *getCompareOperand() const { return getOperand(1); }
646
647 Value *getNewValOperand() { return getOperand(2); }
648 const Value *getNewValOperand() const { return getOperand(2); }
649
650 /// Returns the address space of the pointer operand.
651 unsigned getPointerAddressSpace() const {
652 return getPointerOperand()->getType()->getPointerAddressSpace();
653 }
654
655 /// Returns the strongest permitted ordering on failure, given the
656 /// desired ordering on success.
657 ///
658 /// If the comparison in a cmpxchg operation fails, there is no atomic store
659 /// so release semantics cannot be provided. So this function drops explicit
660 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
661 /// operation would remain SequentiallyConsistent.
662 static AtomicOrdering
663 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
664 switch (SuccessOrdering) {
665 default:
666 llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 666)
;
667 case AtomicOrdering::Release:
668 case AtomicOrdering::Monotonic:
669 return AtomicOrdering::Monotonic;
670 case AtomicOrdering::AcquireRelease:
671 case AtomicOrdering::Acquire:
672 return AtomicOrdering::Acquire;
673 case AtomicOrdering::SequentiallyConsistent:
674 return AtomicOrdering::SequentiallyConsistent;
675 }
676 }
677
678 // Methods for support type inquiry through isa, cast, and dyn_cast:
679 static bool classof(const Instruction *I) {
680 return I->getOpcode() == Instruction::AtomicCmpXchg;
681 }
682 static bool classof(const Value *V) {
683 return isa<Instruction>(V) && classof(cast<Instruction>(V));
684 }
685
686private:
687 // Shadow Instruction::setInstructionSubclassData with a private forwarding
688 // method so that subclasses cannot accidentally use it.
689 void setInstructionSubclassData(unsigned short D) {
690 Instruction::setInstructionSubclassData(D);
691 }
692
693 /// The synchronization scope ID of this cmpxchg instruction. Not quite
694 /// enough room in SubClassData for everything, so synchronization scope ID
695 /// gets its own field.
696 SyncScope::ID SSID;
697};
698
699template <>
700struct OperandTraits<AtomicCmpXchgInst> :
701 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
702};
703
704DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)AtomicCmpXchgInst::op_iterator AtomicCmpXchgInst::op_begin() {
return OperandTraits<AtomicCmpXchgInst>::op_begin(this
); } AtomicCmpXchgInst::const_op_iterator AtomicCmpXchgInst::
op_begin() const { return OperandTraits<AtomicCmpXchgInst>
::op_begin(const_cast<AtomicCmpXchgInst*>(this)); } AtomicCmpXchgInst
::op_iterator AtomicCmpXchgInst::op_end() { return OperandTraits
<AtomicCmpXchgInst>::op_end(this); } AtomicCmpXchgInst::
const_op_iterator AtomicCmpXchgInst::op_end() const { return OperandTraits
<AtomicCmpXchgInst>::op_end(const_cast<AtomicCmpXchgInst
*>(this)); } Value *AtomicCmpXchgInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<AtomicCmpXchgInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 704, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<AtomicCmpXchgInst>::op_begin(const_cast
<AtomicCmpXchgInst*>(this))[i_nocapture].get()); } void
AtomicCmpXchgInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<AtomicCmpXchgInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 704, __PRETTY_FUNCTION__)); OperandTraits<AtomicCmpXchgInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
AtomicCmpXchgInst::getNumOperands() const { return OperandTraits
<AtomicCmpXchgInst>::operands(this); } template <int
Idx_nocapture> Use &AtomicCmpXchgInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &AtomicCmpXchgInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
705
706//===----------------------------------------------------------------------===//
707// AtomicRMWInst Class
708//===----------------------------------------------------------------------===//
709
710/// an instruction that atomically reads a memory location,
711/// combines it with another value, and then stores the result back. Returns
712/// the old value.
713///
714class AtomicRMWInst : public Instruction {
715protected:
716 // Note: Instruction needs to be a friend here to call cloneImpl.
717 friend class Instruction;
718
719 AtomicRMWInst *cloneImpl() const;
720
721public:
722 /// This enumeration lists the possible modifications atomicrmw can make. In
723 /// the descriptions, 'p' is the pointer to the instruction's memory location,
724 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
725 /// instruction. These instructions always return 'old'.
726 enum BinOp {
727 /// *p = v
728 Xchg,
729 /// *p = old + v
730 Add,
731 /// *p = old - v
732 Sub,
733 /// *p = old & v
734 And,
735 /// *p = ~(old & v)
736 Nand,
737 /// *p = old | v
738 Or,
739 /// *p = old ^ v
740 Xor,
741 /// *p = old >signed v ? old : v
742 Max,
743 /// *p = old <signed v ? old : v
744 Min,
745 /// *p = old >unsigned v ? old : v
746 UMax,
747 /// *p = old <unsigned v ? old : v
748 UMin,
749
750 /// *p = old + v
751 FAdd,
752
753 /// *p = old - v
754 FSub,
755
756 FIRST_BINOP = Xchg,
757 LAST_BINOP = FSub,
758 BAD_BINOP
759 };
760
761 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
762 AtomicOrdering Ordering, SyncScope::ID SSID,
763 Instruction *InsertBefore = nullptr);
764 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
765 AtomicOrdering Ordering, SyncScope::ID SSID,
766 BasicBlock *InsertAtEnd);
767
768 // allocate space for exactly two operands
769 void *operator new(size_t s) {
770 return User::operator new(s, 2);
771 }
772
773 BinOp getOperation() const {
774 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
775 }
776
777 static StringRef getOperationName(BinOp Op);
778
779 static bool isFPOperation(BinOp Op) {
780 switch (Op) {
781 case AtomicRMWInst::FAdd:
782 case AtomicRMWInst::FSub:
783 return true;
784 default:
785 return false;
786 }
787 }
788
789 void setOperation(BinOp Operation) {
790 unsigned short SubclassData = getSubclassDataFromInstruction();
791 setInstructionSubclassData((SubclassData & 31) |
792 (Operation << 5));
793 }
794
795 /// Return true if this is a RMW on a volatile memory location.
796 ///
797 bool isVolatile() const {
798 return getSubclassDataFromInstruction() & 1;
799 }
800
801 /// Specify whether this is a volatile RMW or not.
802 ///
803 void setVolatile(bool V) {
804 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
805 (unsigned)V);
806 }
807
808 /// Transparently provide more efficient getOperand methods.
809 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
810
811 /// Returns the ordering constraint of this rmw instruction.
812 AtomicOrdering getOrdering() const {
813 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
814 }
815
816 /// Sets the ordering constraint of this rmw instruction.
817 void setOrdering(AtomicOrdering Ordering) {
818 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 819, __PRETTY_FUNCTION__))
819 "atomicrmw instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 819, __PRETTY_FUNCTION__))
;
820 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
821 ((unsigned)Ordering << 2));
822 }
823
824 /// Returns the synchronization scope ID of this rmw instruction.
825 SyncScope::ID getSyncScopeID() const {
826 return SSID;
827 }
828
829 /// Sets the synchronization scope ID of this rmw instruction.
830 void setSyncScopeID(SyncScope::ID SSID) {
831 this->SSID = SSID;
832 }
833
834 Value *getPointerOperand() { return getOperand(0); }
835 const Value *getPointerOperand() const { return getOperand(0); }
836 static unsigned getPointerOperandIndex() { return 0U; }
837
838 Value *getValOperand() { return getOperand(1); }
839 const Value *getValOperand() const { return getOperand(1); }
840
841 /// Returns the address space of the pointer operand.
842 unsigned getPointerAddressSpace() const {
843 return getPointerOperand()->getType()->getPointerAddressSpace();
844 }
845
846 bool isFloatingPointOperation() const {
847 return isFPOperation(getOperation());
848 }
849
850 // Methods for support type inquiry through isa, cast, and dyn_cast:
851 static bool classof(const Instruction *I) {
852 return I->getOpcode() == Instruction::AtomicRMW;
853 }
854 static bool classof(const Value *V) {
855 return isa<Instruction>(V) && classof(cast<Instruction>(V));
856 }
857
858private:
859 void Init(BinOp Operation, Value *Ptr, Value *Val,
860 AtomicOrdering Ordering, SyncScope::ID SSID);
861
862 // Shadow Instruction::setInstructionSubclassData with a private forwarding
863 // method so that subclasses cannot accidentally use it.
864 void setInstructionSubclassData(unsigned short D) {
865 Instruction::setInstructionSubclassData(D);
866 }
867
868 /// The synchronization scope ID of this rmw instruction. Not quite enough
869 /// room in SubClassData for everything, so synchronization scope ID gets its
870 /// own field.
871 SyncScope::ID SSID;
872};
873
874template <>
875struct OperandTraits<AtomicRMWInst>
876 : public FixedNumOperandTraits<AtomicRMWInst,2> {
877};
878
879DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)AtomicRMWInst::op_iterator AtomicRMWInst::op_begin() { return
OperandTraits<AtomicRMWInst>::op_begin(this); } AtomicRMWInst
::const_op_iterator AtomicRMWInst::op_begin() const { return OperandTraits
<AtomicRMWInst>::op_begin(const_cast<AtomicRMWInst*>
(this)); } AtomicRMWInst::op_iterator AtomicRMWInst::op_end()
{ return OperandTraits<AtomicRMWInst>::op_end(this); }
AtomicRMWInst::const_op_iterator AtomicRMWInst::op_end() const
{ return OperandTraits<AtomicRMWInst>::op_end(const_cast
<AtomicRMWInst*>(this)); } Value *AtomicRMWInst::getOperand
(unsigned i_nocapture) const { ((i_nocapture < OperandTraits
<AtomicRMWInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 879, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<AtomicRMWInst>::op_begin(const_cast<
AtomicRMWInst*>(this))[i_nocapture].get()); } void AtomicRMWInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<AtomicRMWInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 879, __PRETTY_FUNCTION__)); OperandTraits<AtomicRMWInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned AtomicRMWInst
::getNumOperands() const { return OperandTraits<AtomicRMWInst
>::operands(this); } template <int Idx_nocapture> Use
&AtomicRMWInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
AtomicRMWInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
880
881//===----------------------------------------------------------------------===//
882// GetElementPtrInst Class
883//===----------------------------------------------------------------------===//
884
885// checkGEPType - Simple wrapper function to give a better assertion failure
886// message on bad indexes for a gep instruction.
887//
888inline Type *checkGEPType(Type *Ty) {
889 assert(Ty && "Invalid GetElementPtrInst indices for type!")((Ty && "Invalid GetElementPtrInst indices for type!"
) ? static_cast<void> (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 889, __PRETTY_FUNCTION__))
;
890 return Ty;
891}
892
893/// an instruction for type-safe pointer arithmetic to
894/// access elements of arrays and structs
895///
896class GetElementPtrInst : public Instruction {
897 Type *SourceElementType;
898 Type *ResultElementType;
899
900 GetElementPtrInst(const GetElementPtrInst &GEPI);
901
902 /// Constructors - Create a getelementptr instruction with a base pointer an
903 /// list of indices. The first ctor can optionally insert before an existing
904 /// instruction, the second appends the new instruction to the specified
905 /// BasicBlock.
906 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
907 ArrayRef<Value *> IdxList, unsigned Values,
908 const Twine &NameStr, Instruction *InsertBefore);
909 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
910 ArrayRef<Value *> IdxList, unsigned Values,
911 const Twine &NameStr, BasicBlock *InsertAtEnd);
912
913 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
914
915protected:
916 // Note: Instruction needs to be a friend here to call cloneImpl.
917 friend class Instruction;
918
919 GetElementPtrInst *cloneImpl() const;
920
921public:
922 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
923 ArrayRef<Value *> IdxList,
924 const Twine &NameStr = "",
925 Instruction *InsertBefore = nullptr) {
926 unsigned Values = 1 + unsigned(IdxList.size());
927 if (!PointeeType)
928 PointeeType =
929 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
930 else
931 assert(((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 933, __PRETTY_FUNCTION__))
932 PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 933, __PRETTY_FUNCTION__))
933 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 933, __PRETTY_FUNCTION__))
;
934 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
935 NameStr, InsertBefore);
936 }
937
938 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
939 ArrayRef<Value *> IdxList,
940 const Twine &NameStr,
941 BasicBlock *InsertAtEnd) {
942 unsigned Values = 1 + unsigned(IdxList.size());
943 if (!PointeeType)
944 PointeeType =
945 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
946 else
947 assert(((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 949, __PRETTY_FUNCTION__))
948 PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 949, __PRETTY_FUNCTION__))
949 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 949, __PRETTY_FUNCTION__))
;
950 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
951 NameStr, InsertAtEnd);
952 }
953
954 /// Create an "inbounds" getelementptr. See the documentation for the
955 /// "inbounds" flag in LangRef.html for details.
956 static GetElementPtrInst *CreateInBounds(Value *Ptr,
957 ArrayRef<Value *> IdxList,
958 const Twine &NameStr = "",
959 Instruction *InsertBefore = nullptr){
960 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
961 }
962
963 static GetElementPtrInst *
964 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
965 const Twine &NameStr = "",
966 Instruction *InsertBefore = nullptr) {
967 GetElementPtrInst *GEP =
968 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
969 GEP->setIsInBounds(true);
970 return GEP;
971 }
972
973 static GetElementPtrInst *CreateInBounds(Value *Ptr,
974 ArrayRef<Value *> IdxList,
975 const Twine &NameStr,
976 BasicBlock *InsertAtEnd) {
977 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
978 }
979
980 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
981 ArrayRef<Value *> IdxList,
982 const Twine &NameStr,
983 BasicBlock *InsertAtEnd) {
984 GetElementPtrInst *GEP =
985 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
986 GEP->setIsInBounds(true);
987 return GEP;
988 }
989
990 /// Transparently provide more efficient getOperand methods.
991 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
992
993 Type *getSourceElementType() const { return SourceElementType; }
994
995 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
996 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
997
998 Type *getResultElementType() const {
999 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1000, __PRETTY_FUNCTION__))
1000 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1000, __PRETTY_FUNCTION__))
;
1001 return ResultElementType;
1002 }
1003
1004 /// Returns the address space of this instruction's pointer type.
1005 unsigned getAddressSpace() const {
1006 // Note that this is always the same as the pointer operand's address space
1007 // and that is cheaper to compute, so cheat here.
1008 return getPointerAddressSpace();
1009 }
1010
1011 /// Returns the type of the element that would be loaded with
1012 /// a load instruction with the specified parameters.
1013 ///
1014 /// Null is returned if the indices are invalid for the specified
1015 /// pointer type.
1016 ///
1017 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1018 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1019 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1020
1021 inline op_iterator idx_begin() { return op_begin()+1; }
1022 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1023 inline op_iterator idx_end() { return op_end(); }
1024 inline const_op_iterator idx_end() const { return op_end(); }
1025
1026 inline iterator_range<op_iterator> indices() {
1027 return make_range(idx_begin(), idx_end());
1028 }
1029
1030 inline iterator_range<const_op_iterator> indices() const {
1031 return make_range(idx_begin(), idx_end());
1032 }
1033
1034 Value *getPointerOperand() {
1035 return getOperand(0);
1036 }
1037 const Value *getPointerOperand() const {
1038 return getOperand(0);
1039 }
1040 static unsigned getPointerOperandIndex() {
1041 return 0U; // get index for modifying correct operand.
1042 }
1043
1044 /// Method to return the pointer operand as a
1045 /// PointerType.
1046 Type *getPointerOperandType() const {
1047 return getPointerOperand()->getType();
1048 }
1049
1050 /// Returns the address space of the pointer operand.
1051 unsigned getPointerAddressSpace() const {
1052 return getPointerOperandType()->getPointerAddressSpace();
1053 }
1054
1055 /// Returns the pointer type returned by the GEP
1056 /// instruction, which may be a vector of pointers.
1057 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1058 ArrayRef<Value *> IdxList) {
1059 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1060 Ptr->getType()->getPointerAddressSpace());
1061 // Vector GEP
1062 if (Ptr->getType()->isVectorTy()) {
1063 ElementCount EltCount = Ptr->getType()->getVectorElementCount();
1064 return VectorType::get(PtrTy, EltCount);
1065 }
1066 for (Value *Index : IdxList)
1067 if (Index->getType()->isVectorTy()) {
1068 ElementCount EltCount = Index->getType()->getVectorElementCount();
1069 return VectorType::get(PtrTy, EltCount);
1070 }
1071 // Scalar GEP
1072 return PtrTy;
1073 }
1074
1075 unsigned getNumIndices() const { // Note: always non-negative
1076 return getNumOperands() - 1;
1077 }
1078
1079 bool hasIndices() const {
1080 return getNumOperands() > 1;
1081 }
1082
1083 /// Return true if all of the indices of this GEP are
1084 /// zeros. If so, the result pointer and the first operand have the same
1085 /// value, just potentially different types.
1086 bool hasAllZeroIndices() const;
1087
1088 /// Return true if all of the indices of this GEP are
1089 /// constant integers. If so, the result pointer and the first operand have
1090 /// a constant offset between them.
1091 bool hasAllConstantIndices() const;
1092
1093 /// Set or clear the inbounds flag on this GEP instruction.
1094 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1095 void setIsInBounds(bool b = true);
1096
1097 /// Determine whether the GEP has the inbounds flag.
1098 bool isInBounds() const;
1099
1100 /// Accumulate the constant address offset of this GEP if possible.
1101 ///
1102 /// This routine accepts an APInt into which it will accumulate the constant
1103 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1104 /// all-constant, it returns false and the value of the offset APInt is
1105 /// undefined (it is *not* preserved!). The APInt passed into this routine
1106 /// must be at least as wide as the IntPtr type for the address space of
1107 /// the base GEP pointer.
1108 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1109
1110 // Methods for support type inquiry through isa, cast, and dyn_cast:
1111 static bool classof(const Instruction *I) {
1112 return (I->getOpcode() == Instruction::GetElementPtr);
1113 }
1114 static bool classof(const Value *V) {
1115 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1116 }
1117};
1118
1119template <>
1120struct OperandTraits<GetElementPtrInst> :
1121 public VariadicOperandTraits<GetElementPtrInst, 1> {
1122};
1123
1124GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1125 ArrayRef<Value *> IdxList, unsigned Values,
1126 const Twine &NameStr,
1127 Instruction *InsertBefore)
1128 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1129 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1130 Values, InsertBefore),
1131 SourceElementType(PointeeType),
1132 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1133 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1134, __PRETTY_FUNCTION__))
1134 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1134, __PRETTY_FUNCTION__))
;
1135 init(Ptr, IdxList, NameStr);
1136}
1137
1138GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1139 ArrayRef<Value *> IdxList, unsigned Values,
1140 const Twine &NameStr,
1141 BasicBlock *InsertAtEnd)
1142 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1143 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1144 Values, InsertAtEnd),
1145 SourceElementType(PointeeType),
1146 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1147 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1148, __PRETTY_FUNCTION__))
1148 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1148, __PRETTY_FUNCTION__))
;
1149 init(Ptr, IdxList, NameStr);
1150}
1151
1152DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)GetElementPtrInst::op_iterator GetElementPtrInst::op_begin() {
return OperandTraits<GetElementPtrInst>::op_begin(this
); } GetElementPtrInst::const_op_iterator GetElementPtrInst::
op_begin() const { return OperandTraits<GetElementPtrInst>
::op_begin(const_cast<GetElementPtrInst*>(this)); } GetElementPtrInst
::op_iterator GetElementPtrInst::op_end() { return OperandTraits
<GetElementPtrInst>::op_end(this); } GetElementPtrInst::
const_op_iterator GetElementPtrInst::op_end() const { return OperandTraits
<GetElementPtrInst>::op_end(const_cast<GetElementPtrInst
*>(this)); } Value *GetElementPtrInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<GetElementPtrInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1152, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<GetElementPtrInst>::op_begin(const_cast
<GetElementPtrInst*>(this))[i_nocapture].get()); } void
GetElementPtrInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<GetElementPtrInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1152, __PRETTY_FUNCTION__)); OperandTraits<GetElementPtrInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
GetElementPtrInst::getNumOperands() const { return OperandTraits
<GetElementPtrInst>::operands(this); } template <int
Idx_nocapture> Use &GetElementPtrInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &GetElementPtrInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
1153
1154//===----------------------------------------------------------------------===//
1155// ICmpInst Class
1156//===----------------------------------------------------------------------===//
1157
1158/// This instruction compares its operands according to the predicate given
1159/// to the constructor. It only operates on integers or pointers. The operands
1160/// must be identical types.
1161/// Represent an integer comparison operator.
1162class ICmpInst: public CmpInst {
1163 void AssertOK() {
1164 assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1165, __PRETTY_FUNCTION__))
1165 "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1165, __PRETTY_FUNCTION__))
;
1166 assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to ICmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1167, __PRETTY_FUNCTION__))
1167 "Both operands to ICmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to ICmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1167, __PRETTY_FUNCTION__))
;
1168 // Check that the operands are the right type
1169 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1171, __PRETTY_FUNCTION__))
1170 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1171, __PRETTY_FUNCTION__))
1171 "Invalid operand types for ICmp instruction")(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1171, __PRETTY_FUNCTION__))
;
1172 }
1173
1174protected:
1175 // Note: Instruction needs to be a friend here to call cloneImpl.
1176 friend class Instruction;
1177
1178 /// Clone an identical ICmpInst
1179 ICmpInst *cloneImpl() const;
1180
1181public:
1182 /// Constructor with insert-before-instruction semantics.
1183 ICmpInst(
1184 Instruction *InsertBefore, ///< Where to insert
1185 Predicate pred, ///< The predicate to use for the comparison
1186 Value *LHS, ///< The left-hand-side of the expression
1187 Value *RHS, ///< The right-hand-side of the expression
1188 const Twine &NameStr = "" ///< Name of the instruction
1189 ) : CmpInst(makeCmpResultType(LHS->getType()),
1190 Instruction::ICmp, pred, LHS, RHS, NameStr,
1191 InsertBefore) {
1192#ifndef NDEBUG
1193 AssertOK();
1194#endif
1195 }
1196
1197 /// Constructor with insert-at-end semantics.
1198 ICmpInst(
1199 BasicBlock &InsertAtEnd, ///< Block to insert into.
1200 Predicate pred, ///< The predicate to use for the comparison
1201 Value *LHS, ///< The left-hand-side of the expression
1202 Value *RHS, ///< The right-hand-side of the expression
1203 const Twine &NameStr = "" ///< Name of the instruction
1204 ) : CmpInst(makeCmpResultType(LHS->getType()),
1205 Instruction::ICmp, pred, LHS, RHS, NameStr,
1206 &InsertAtEnd) {
1207#ifndef NDEBUG
1208 AssertOK();
1209#endif
1210 }
1211
1212 /// Constructor with no-insertion semantics
1213 ICmpInst(
1214 Predicate pred, ///< The predicate to use for the comparison
1215 Value *LHS, ///< The left-hand-side of the expression
1216 Value *RHS, ///< The right-hand-side of the expression
1217 const Twine &NameStr = "" ///< Name of the instruction
1218 ) : CmpInst(makeCmpResultType(LHS->getType()),
1219 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1220#ifndef NDEBUG
1221 AssertOK();
1222#endif
1223 }
1224
1225 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1226 /// @returns the predicate that would be the result if the operand were
1227 /// regarded as signed.
1228 /// Return the signed version of the predicate
1229 Predicate getSignedPredicate() const {
1230 return getSignedPredicate(getPredicate());
1231 }
1232
1233 /// This is a static version that you can use without an instruction.
1234 /// Return the signed version of the predicate.
1235 static Predicate getSignedPredicate(Predicate pred);
1236
1237 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1238 /// @returns the predicate that would be the result if the operand were
1239 /// regarded as unsigned.
1240 /// Return the unsigned version of the predicate
1241 Predicate getUnsignedPredicate() const {
1242 return getUnsignedPredicate(getPredicate());
1243 }
1244
1245 /// This is a static version that you can use without an instruction.
1246 /// Return the unsigned version of the predicate.
1247 static Predicate getUnsignedPredicate(Predicate pred);
1248
1249 /// Return true if this predicate is either EQ or NE. This also
1250 /// tests for commutativity.
1251 static bool isEquality(Predicate P) {
1252 return P == ICMP_EQ || P == ICMP_NE;
1253 }
1254
1255 /// Return true if this predicate is either EQ or NE. This also
1256 /// tests for commutativity.
1257 bool isEquality() const {
1258 return isEquality(getPredicate());
1259 }
1260
1261 /// @returns true if the predicate of this ICmpInst is commutative
1262 /// Determine if this relation is commutative.
1263 bool isCommutative() const { return isEquality(); }
1264
1265 /// Return true if the predicate is relational (not EQ or NE).
1266 ///
1267 bool isRelational() const {
1268 return !isEquality();
1269 }
1270
1271 /// Return true if the predicate is relational (not EQ or NE).
1272 ///
1273 static bool isRelational(Predicate P) {
1274 return !isEquality(P);
1275 }
1276
1277 /// Exchange the two operands to this instruction in such a way that it does
1278 /// not modify the semantics of the instruction. The predicate value may be
1279 /// changed to retain the same result if the predicate is order dependent
1280 /// (e.g. ult).
1281 /// Swap operands and adjust predicate.
1282 void swapOperands() {
1283 setPredicate(getSwappedPredicate());
1284 Op<0>().swap(Op<1>());
1285 }
1286
1287 // Methods for support type inquiry through isa, cast, and dyn_cast:
1288 static bool classof(const Instruction *I) {
1289 return I->getOpcode() == Instruction::ICmp;
1290 }
1291 static bool classof(const Value *V) {
1292 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1293 }
1294};
1295
1296//===----------------------------------------------------------------------===//
1297// FCmpInst Class
1298//===----------------------------------------------------------------------===//
1299
1300/// This instruction compares its operands according to the predicate given
1301/// to the constructor. It only operates on floating point values or packed
1302/// vectors of floating point values. The operands must be identical types.
1303/// Represents a floating point comparison operator.
1304class FCmpInst: public CmpInst {
1305 void AssertOK() {
1306 assert(isFPPredicate() && "Invalid FCmp predicate value")((isFPPredicate() && "Invalid FCmp predicate value") ?
static_cast<void> (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1306, __PRETTY_FUNCTION__))
;
1307 assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to FCmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1308, __PRETTY_FUNCTION__))
1308 "Both operands to FCmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to FCmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1308, __PRETTY_FUNCTION__))
;
1309 // Check that the operands are the right type
1310 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&((getOperand(0)->getType()->isFPOrFPVectorTy() &&
"Invalid operand types for FCmp instruction") ? static_cast<
void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1311, __PRETTY_FUNCTION__))
1311 "Invalid operand types for FCmp instruction")((getOperand(0)->getType()->isFPOrFPVectorTy() &&
"Invalid operand types for FCmp instruction") ? static_cast<
void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1311, __PRETTY_FUNCTION__))
;
1312 }
1313
1314protected:
1315 // Note: Instruction needs to be a friend here to call cloneImpl.
1316 friend class Instruction;
1317
1318 /// Clone an identical FCmpInst
1319 FCmpInst *cloneImpl() const;
1320
1321public:
1322 /// Constructor with insert-before-instruction semantics.
1323 FCmpInst(
1324 Instruction *InsertBefore, ///< Where to insert
1325 Predicate pred, ///< The predicate to use for the comparison
1326 Value *LHS, ///< The left-hand-side of the expression
1327 Value *RHS, ///< The right-hand-side of the expression
1328 const Twine &NameStr = "" ///< Name of the instruction
1329 ) : CmpInst(makeCmpResultType(LHS->getType()),
1330 Instruction::FCmp, pred, LHS, RHS, NameStr,
1331 InsertBefore) {
1332 AssertOK();
1333 }
1334
1335 /// Constructor with insert-at-end semantics.
1336 FCmpInst(
1337 BasicBlock &InsertAtEnd, ///< Block to insert into.
1338 Predicate pred, ///< The predicate to use for the comparison
1339 Value *LHS, ///< The left-hand-side of the expression
1340 Value *RHS, ///< The right-hand-side of the expression
1341 const Twine &NameStr = "" ///< Name of the instruction
1342 ) : CmpInst(makeCmpResultType(LHS->getType()),
1343 Instruction::FCmp, pred, LHS, RHS, NameStr,
1344 &InsertAtEnd) {
1345 AssertOK();
1346 }
1347
1348 /// Constructor with no-insertion semantics
1349 FCmpInst(
1350 Predicate Pred, ///< The predicate to use for the comparison
1351 Value *LHS, ///< The left-hand-side of the expression
1352 Value *RHS, ///< The right-hand-side of the expression
1353 const Twine &NameStr = "", ///< Name of the instruction
1354 Instruction *FlagsSource = nullptr
1355 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1356 RHS, NameStr, nullptr, FlagsSource) {
1357 AssertOK();
1358 }
1359
1360 /// @returns true if the predicate of this instruction is EQ or NE.
1361 /// Determine if this is an equality predicate.
1362 static bool isEquality(Predicate Pred) {
1363 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1364 Pred == FCMP_UNE;
1365 }
1366
1367 /// @returns true if the predicate of this instruction is EQ or NE.
1368 /// Determine if this is an equality predicate.
1369 bool isEquality() const { return isEquality(getPredicate()); }
1370
1371 /// @returns true if the predicate of this instruction is commutative.
1372 /// Determine if this is a commutative predicate.
1373 bool isCommutative() const {
1374 return isEquality() ||
1375 getPredicate() == FCMP_FALSE ||
1376 getPredicate() == FCMP_TRUE ||
1377 getPredicate() == FCMP_ORD ||
1378 getPredicate() == FCMP_UNO;
1379 }
1380
1381 /// @returns true if the predicate is relational (not EQ or NE).
1382 /// Determine if this a relational predicate.
1383 bool isRelational() const { return !isEquality(); }
1384
1385 /// Exchange the two operands to this instruction in such a way that it does
1386 /// not modify the semantics of the instruction. The predicate value may be
1387 /// changed to retain the same result if the predicate is order dependent
1388 /// (e.g. ult).
1389 /// Swap operands and adjust predicate.
1390 void swapOperands() {
1391 setPredicate(getSwappedPredicate());
1392 Op<0>().swap(Op<1>());
1393 }
1394
1395 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1396 static bool classof(const Instruction *I) {
1397 return I->getOpcode() == Instruction::FCmp;
1398 }
1399 static bool classof(const Value *V) {
1400 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1401 }
1402};
1403
1404//===----------------------------------------------------------------------===//
1405/// This class represents a function call, abstracting a target
1406/// machine's calling convention. This class uses low bit of the SubClassData
1407/// field to indicate whether or not this is a tail call. The rest of the bits
1408/// hold the calling convention of the call.
1409///
1410class CallInst : public CallBase {
1411 CallInst(const CallInst &CI);
1412
1413 /// Construct a CallInst given a range of arguments.
1414 /// Construct a CallInst from a range of arguments
1415 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1416 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1417 Instruction *InsertBefore);
1418
1419 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1420 const Twine &NameStr, Instruction *InsertBefore)
1421 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1422
1423 /// Construct a CallInst given a range of arguments.
1424 /// Construct a CallInst from a range of arguments
1425 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1426 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1427 BasicBlock *InsertAtEnd);
1428
1429 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1430 Instruction *InsertBefore);
1431
1432 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1433 BasicBlock *InsertAtEnd);
1434
1435 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1436 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1437 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1438
1439 /// Compute the number of operands to allocate.
1440 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1441 // We need one operand for the called function, plus the input operand
1442 // counts provided.
1443 return 1 + NumArgs + NumBundleInputs;
1444 }
1445
1446protected:
1447 // Note: Instruction needs to be a friend here to call cloneImpl.
1448 friend class Instruction;
1449
1450 CallInst *cloneImpl() const;
1451
1452public:
1453 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1454 Instruction *InsertBefore = nullptr) {
1455 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1456 }
1457
1458 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1459 const Twine &NameStr,
1460 Instruction *InsertBefore = nullptr) {
1461 return new (ComputeNumOperands(Args.size()))
1462 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1463 }
1464
1465 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1466 ArrayRef<OperandBundleDef> Bundles = None,
1467 const Twine &NameStr = "",
1468 Instruction *InsertBefore = nullptr) {
1469 const int NumOperands =
1470 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1471 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1472
1473 return new (NumOperands, DescriptorBytes)
1474 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1475 }
1476
1477 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1478 BasicBlock *InsertAtEnd) {
1479 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1480 }
1481
1482 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1483 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1484 return new (ComputeNumOperands(Args.size()))
1485 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1486 }
1487
1488 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1489 ArrayRef<OperandBundleDef> Bundles,
1490 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1491 const int NumOperands =
1492 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1493 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1494
1495 return new (NumOperands, DescriptorBytes)
1496 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1497 }
1498
1499 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1500 Instruction *InsertBefore = nullptr) {
1501 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1502 InsertBefore);
1503 }
1504
1505 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1506 ArrayRef<OperandBundleDef> Bundles = None,
1507 const Twine &NameStr = "",
1508 Instruction *InsertBefore = nullptr) {
1509 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1510 NameStr, InsertBefore);
1511 }
1512
1513 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1514 const Twine &NameStr,
1515 Instruction *InsertBefore = nullptr) {
1516 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1517 InsertBefore);
1518 }
1519
1520 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1521 BasicBlock *InsertAtEnd) {
1522 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1523 InsertAtEnd);
1524 }
1525
1526 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1527 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1528 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1529 InsertAtEnd);
1530 }
1531
1532 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1533 ArrayRef<OperandBundleDef> Bundles,
1534 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1535 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1536 NameStr, InsertAtEnd);
1537 }
1538
1539 // Deprecated [opaque pointer types]
1540 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1541 Instruction *InsertBefore = nullptr) {
1542 return Create(cast<FunctionType>(
1543 cast<PointerType>(Func->getType())->getElementType()),
1544 Func, NameStr, InsertBefore);
1545 }
1546
1547 // Deprecated [opaque pointer types]
1548 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1549 const Twine &NameStr,
1550 Instruction *InsertBefore = nullptr) {
1551 return Create(cast<FunctionType>(
1552 cast<PointerType>(Func->getType())->getElementType()),
1553 Func, Args, NameStr, InsertBefore);
1554 }
1555
1556 // Deprecated [opaque pointer types]
1557 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1558 ArrayRef<OperandBundleDef> Bundles = None,
1559 const Twine &NameStr = "",
1560 Instruction *InsertBefore = nullptr) {
1561 return Create(cast<FunctionType>(
1562 cast<PointerType>(Func->getType())->getElementType()),
1563 Func, Args, Bundles, NameStr, InsertBefore);
1564 }
1565
1566 // Deprecated [opaque pointer types]
1567 static CallInst *Create(Value *Func, const Twine &NameStr,
1568 BasicBlock *InsertAtEnd) {
1569 return Create(cast<FunctionType>(
1570 cast<PointerType>(Func->getType())->getElementType()),
1571 Func, NameStr, InsertAtEnd);
1572 }
1573
1574 // Deprecated [opaque pointer types]
1575 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1576 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1577 return Create(cast<FunctionType>(
1578 cast<PointerType>(Func->getType())->getElementType()),
1579 Func, Args, NameStr, InsertAtEnd);
1580 }
1581
1582 // Deprecated [opaque pointer types]
1583 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1584 ArrayRef<OperandBundleDef> Bundles,
1585 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1586 return Create(cast<FunctionType>(
1587 cast<PointerType>(Func->getType())->getElementType()),
1588 Func, Args, Bundles, NameStr, InsertAtEnd);
1589 }
1590
1591 /// Create a clone of \p CI with a different set of operand bundles and
1592 /// insert it before \p InsertPt.
1593 ///
1594 /// The returned call instruction is identical \p CI in every way except that
1595 /// the operand bundles for the new instruction are set to the operand bundles
1596 /// in \p Bundles.
1597 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1598 Instruction *InsertPt = nullptr);
1599
1600 /// Generate the IR for a call to malloc:
1601 /// 1. Compute the malloc call's argument as the specified type's size,
1602 /// possibly multiplied by the array size if the array size is not
1603 /// constant 1.
1604 /// 2. Call malloc with that argument.
1605 /// 3. Bitcast the result of the malloc call to the specified type.
1606 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1607 Type *AllocTy, Value *AllocSize,
1608 Value *ArraySize = nullptr,
1609 Function *MallocF = nullptr,
1610 const Twine &Name = "");
1611 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1612 Type *AllocTy, Value *AllocSize,
1613 Value *ArraySize = nullptr,
1614 Function *MallocF = nullptr,
1615 const Twine &Name = "");
1616 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1617 Type *AllocTy, Value *AllocSize,
1618 Value *ArraySize = nullptr,
1619 ArrayRef<OperandBundleDef> Bundles = None,
1620 Function *MallocF = nullptr,
1621 const Twine &Name = "");
1622 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1623 Type *AllocTy, Value *AllocSize,
1624 Value *ArraySize = nullptr,
1625 ArrayRef<OperandBundleDef> Bundles = None,
1626 Function *MallocF = nullptr,
1627 const Twine &Name = "");
1628 /// Generate the IR for a call to the builtin free function.
1629 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1630 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1631 static Instruction *CreateFree(Value *Source,
1632 ArrayRef<OperandBundleDef> Bundles,
1633 Instruction *InsertBefore);
1634 static Instruction *CreateFree(Value *Source,
1635 ArrayRef<OperandBundleDef> Bundles,
1636 BasicBlock *InsertAtEnd);
1637
1638 // Note that 'musttail' implies 'tail'.
1639 enum TailCallKind {
1640 TCK_None = 0,
1641 TCK_Tail = 1,
1642 TCK_MustTail = 2,
1643 TCK_NoTail = 3
1644 };
1645 TailCallKind getTailCallKind() const {
1646 return TailCallKind(getSubclassDataFromInstruction() & 3);
1647 }
1648
1649 bool isTailCall() const {
1650 unsigned Kind = getSubclassDataFromInstruction() & 3;
1651 return Kind == TCK_Tail || Kind == TCK_MustTail;
1652 }
1653
1654 bool isMustTailCall() const {
1655 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1656 }
1657
1658 bool isNoTailCall() const {
1659 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1660 }
1661
1662 void setTailCall(bool isTC = true) {
1663 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1664 unsigned(isTC ? TCK_Tail : TCK_None));
1665 }
1666
1667 void setTailCallKind(TailCallKind TCK) {
1668 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1669 unsigned(TCK));
1670 }
1671
1672 /// Return true if the call can return twice
1673 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1674 void setCanReturnTwice() {
1675 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1676 }
1677
1678 // Methods for support type inquiry through isa, cast, and dyn_cast:
1679 static bool classof(const Instruction *I) {
1680 return I->getOpcode() == Instruction::Call;
1681 }
1682 static bool classof(const Value *V) {
1683 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1684 }
1685
1686 /// Updates profile metadata by scaling it by \p S / \p T.
1687 void updateProfWeight(uint64_t S, uint64_t T);
1688
1689private:
1690 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1691 // method so that subclasses cannot accidentally use it.
1692 void setInstructionSubclassData(unsigned short D) {
1693 Instruction::setInstructionSubclassData(D);
1694 }
1695};
1696
1697CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1698 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1699 BasicBlock *InsertAtEnd)
1700 : CallBase(Ty->getReturnType(), Instruction::Call,
1701 OperandTraits<CallBase>::op_end(this) -
1702 (Args.size() + CountBundleInputs(Bundles) + 1),
1703 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1704 InsertAtEnd) {
1705 init(Ty, Func, Args, Bundles, NameStr);
1706}
1707
1708CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1709 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1710 Instruction *InsertBefore)
1711 : CallBase(Ty->getReturnType(), Instruction::Call,
1712 OperandTraits<CallBase>::op_end(this) -
1713 (Args.size() + CountBundleInputs(Bundles) + 1),
1714 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1715 InsertBefore) {
1716 init(Ty, Func, Args, Bundles, NameStr);
1717}
1718
1719//===----------------------------------------------------------------------===//
1720// SelectInst Class
1721//===----------------------------------------------------------------------===//
1722
1723/// This class represents the LLVM 'select' instruction.
1724///
1725class SelectInst : public Instruction {
1726 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1727 Instruction *InsertBefore)
1728 : Instruction(S1->getType(), Instruction::Select,
1729 &Op<0>(), 3, InsertBefore) {
1730 init(C, S1, S2);
1731 setName(NameStr);
1732 }
1733
1734 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1735 BasicBlock *InsertAtEnd)
1736 : Instruction(S1->getType(), Instruction::Select,
1737 &Op<0>(), 3, InsertAtEnd) {
1738 init(C, S1, S2);
1739 setName(NameStr);
1740 }
1741
1742 void init(Value *C, Value *S1, Value *S2) {
1743 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")((!areInvalidOperands(C, S1, S2) && "Invalid operands for select"
) ? static_cast<void> (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1743, __PRETTY_FUNCTION__))
;
1744 Op<0>() = C;
1745 Op<1>() = S1;
1746 Op<2>() = S2;
1747 }
1748
1749protected:
1750 // Note: Instruction needs to be a friend here to call cloneImpl.
1751 friend class Instruction;
1752
1753 SelectInst *cloneImpl() const;
1754
1755public:
1756 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1757 const Twine &NameStr = "",
1758 Instruction *InsertBefore = nullptr,
1759 Instruction *MDFrom = nullptr) {
1760 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1761 if (MDFrom)
1762 Sel->copyMetadata(*MDFrom);
1763 return Sel;
1764 }
1765
1766 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1767 const Twine &NameStr,
1768 BasicBlock *InsertAtEnd) {
1769 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1770 }
1771
1772 const Value *getCondition() const { return Op<0>(); }
1773 const Value *getTrueValue() const { return Op<1>(); }
1774 const Value *getFalseValue() const { return Op<2>(); }
1775 Value *getCondition() { return Op<0>(); }
1776 Value *getTrueValue() { return Op<1>(); }
1777 Value *getFalseValue() { return Op<2>(); }
1778
1779 void setCondition(Value *V) { Op<0>() = V; }
1780 void setTrueValue(Value *V) { Op<1>() = V; }
1781 void setFalseValue(Value *V) { Op<2>() = V; }
1782
1783 /// Swap the true and false values of the select instruction.
1784 /// This doesn't swap prof metadata.
1785 void swapValues() { Op<1>().swap(Op<2>()); }
1786
1787 /// Return a string if the specified operands are invalid
1788 /// for a select operation, otherwise return null.
1789 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1790
1791 /// Transparently provide more efficient getOperand methods.
1792 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1793
1794 OtherOps getOpcode() const {
1795 return static_cast<OtherOps>(Instruction::getOpcode());
1796 }
1797
1798 // Methods for support type inquiry through isa, cast, and dyn_cast:
1799 static bool classof(const Instruction *I) {
1800 return I->getOpcode() == Instruction::Select;
1801 }
1802 static bool classof(const Value *V) {
1803 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1804 }
1805};
1806
1807template <>
1808struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1809};
1810
1811DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)SelectInst::op_iterator SelectInst::op_begin() { return OperandTraits
<SelectInst>::op_begin(this); } SelectInst::const_op_iterator
SelectInst::op_begin() const { return OperandTraits<SelectInst
>::op_begin(const_cast<SelectInst*>(this)); } SelectInst
::op_iterator SelectInst::op_end() { return OperandTraits<
SelectInst>::op_end(this); } SelectInst::const_op_iterator
SelectInst::op_end() const { return OperandTraits<SelectInst
>::op_end(const_cast<SelectInst*>(this)); } Value *SelectInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<SelectInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1811, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<SelectInst>::op_begin(const_cast<SelectInst
*>(this))[i_nocapture].get()); } void SelectInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<SelectInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1811, __PRETTY_FUNCTION__)); OperandTraits<SelectInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SelectInst
::getNumOperands() const { return OperandTraits<SelectInst
>::operands(this); } template <int Idx_nocapture> Use
&SelectInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
SelectInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
1812
1813//===----------------------------------------------------------------------===//
1814// VAArgInst Class
1815//===----------------------------------------------------------------------===//
1816
1817/// This class represents the va_arg llvm instruction, which returns
1818/// an argument of the specified type given a va_list and increments that list
1819///
1820class VAArgInst : public UnaryInstruction {
1821protected:
1822 // Note: Instruction needs to be a friend here to call cloneImpl.
1823 friend class Instruction;
1824
1825 VAArgInst *cloneImpl() const;
1826
1827public:
1828 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1829 Instruction *InsertBefore = nullptr)
1830 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1831 setName(NameStr);
1832 }
1833
1834 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1835 BasicBlock *InsertAtEnd)
1836 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1837 setName(NameStr);
1838 }
1839
1840 Value *getPointerOperand() { return getOperand(0); }
1841 const Value *getPointerOperand() const { return getOperand(0); }
1842 static unsigned getPointerOperandIndex() { return 0U; }
1843
1844 // Methods for support type inquiry through isa, cast, and dyn_cast:
1845 static bool classof(const Instruction *I) {
1846 return I->getOpcode() == VAArg;
1847 }
1848 static bool classof(const Value *V) {
1849 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1850 }
1851};
1852
1853//===----------------------------------------------------------------------===//
1854// ExtractElementInst Class
1855//===----------------------------------------------------------------------===//
1856
1857/// This instruction extracts a single (scalar)
1858/// element from a VectorType value
1859///
1860class ExtractElementInst : public Instruction {
1861 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1862 Instruction *InsertBefore = nullptr);
1863 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1864 BasicBlock *InsertAtEnd);
1865
1866protected:
1867 // Note: Instruction needs to be a friend here to call cloneImpl.
1868 friend class Instruction;
1869
1870 ExtractElementInst *cloneImpl() const;
1871
1872public:
1873 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1874 const Twine &NameStr = "",
1875 Instruction *InsertBefore = nullptr) {
1876 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1877 }
1878
1879 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1880 const Twine &NameStr,
1881 BasicBlock *InsertAtEnd) {
1882 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1883 }
1884
1885 /// Return true if an extractelement instruction can be
1886 /// formed with the specified operands.
1887 static bool isValidOperands(const Value *Vec, const Value *Idx);
1888
1889 Value *getVectorOperand() { return Op<0>(); }
1890 Value *getIndexOperand() { return Op<1>(); }
1891 const Value *getVectorOperand() const { return Op<0>(); }
1892 const Value *getIndexOperand() const { return Op<1>(); }
1893
1894 VectorType *getVectorOperandType() const {
1895 return cast<VectorType>(getVectorOperand()->getType());
1896 }
1897
1898 /// Transparently provide more efficient getOperand methods.
1899 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1900
1901 // Methods for support type inquiry through isa, cast, and dyn_cast:
1902 static bool classof(const Instruction *I) {
1903 return I->getOpcode() == Instruction::ExtractElement;
1904 }
1905 static bool classof(const Value *V) {
1906 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1907 }
1908};
1909
1910template <>
1911struct OperandTraits<ExtractElementInst> :
1912 public FixedNumOperandTraits<ExtractElementInst, 2> {
1913};
1914
1915DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)ExtractElementInst::op_iterator ExtractElementInst::op_begin(
) { return OperandTraits<ExtractElementInst>::op_begin(
this); } ExtractElementInst::const_op_iterator ExtractElementInst
::op_begin() const { return OperandTraits<ExtractElementInst
>::op_begin(const_cast<ExtractElementInst*>(this)); }
ExtractElementInst::op_iterator ExtractElementInst::op_end()
{ return OperandTraits<ExtractElementInst>::op_end(this
); } ExtractElementInst::const_op_iterator ExtractElementInst
::op_end() const { return OperandTraits<ExtractElementInst
>::op_end(const_cast<ExtractElementInst*>(this)); } Value
*ExtractElementInst::getOperand(unsigned i_nocapture) const {
((i_nocapture < OperandTraits<ExtractElementInst>::
operands(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1915, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ExtractElementInst>::op_begin(const_cast
<ExtractElementInst*>(this))[i_nocapture].get()); } void
ExtractElementInst::setOperand(unsigned i_nocapture, Value *
Val_nocapture) { ((i_nocapture < OperandTraits<ExtractElementInst
>::operands(this) && "setOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1915, __PRETTY_FUNCTION__)); OperandTraits<ExtractElementInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
ExtractElementInst::getNumOperands() const { return OperandTraits
<ExtractElementInst>::operands(this); } template <int
Idx_nocapture> Use &ExtractElementInst::Op() { return
this->OpFrom<Idx_nocapture>(this); } template <int
Idx_nocapture> const Use &ExtractElementInst::Op() const
{ return this->OpFrom<Idx_nocapture>(this); }
1916
1917//===----------------------------------------------------------------------===//
1918// InsertElementInst Class
1919//===----------------------------------------------------------------------===//
1920
1921/// This instruction inserts a single (scalar)
1922/// element into a VectorType value
1923///
1924class InsertElementInst : public Instruction {
1925 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1926 const Twine &NameStr = "",
1927 Instruction *InsertBefore = nullptr);
1928 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1929 BasicBlock *InsertAtEnd);
1930
1931protected:
1932 // Note: Instruction needs to be a friend here to call cloneImpl.
1933 friend class Instruction;
1934
1935 InsertElementInst *cloneImpl() const;
1936
1937public:
1938 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1939 const Twine &NameStr = "",
1940 Instruction *InsertBefore = nullptr) {
1941 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1942 }
1943
1944 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1945 const Twine &NameStr,
1946 BasicBlock *InsertAtEnd) {
1947 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1948 }
1949
1950 /// Return true if an insertelement instruction can be
1951 /// formed with the specified operands.
1952 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1953 const Value *Idx);
1954
1955 /// Overload to return most specific vector type.
1956 ///
1957 VectorType *getType() const {
1958 return cast<VectorType>(Instruction::getType());
1959 }
1960
1961 /// Transparently provide more efficient getOperand methods.
1962 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1963
1964 // Methods for support type inquiry through isa, cast, and dyn_cast:
1965 static bool classof(const Instruction *I) {
1966 return I->getOpcode() == Instruction::InsertElement;
1967 }
1968 static bool classof(const Value *V) {
1969 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1970 }
1971};
1972
1973template <>
1974struct OperandTraits<InsertElementInst> :
1975 public FixedNumOperandTraits<InsertElementInst, 3> {
1976};
1977
1978DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)InsertElementInst::op_iterator InsertElementInst::op_begin() {
return OperandTraits<InsertElementInst>::op_begin(this
); } InsertElementInst::const_op_iterator InsertElementInst::
op_begin() const { return OperandTraits<InsertElementInst>
::op_begin(const_cast<InsertElementInst*>(this)); } InsertElementInst
::op_iterator InsertElementInst::op_end() { return OperandTraits
<InsertElementInst>::op_end(this); } InsertElementInst::
const_op_iterator InsertElementInst::op_end() const { return OperandTraits
<InsertElementInst>::op_end(const_cast<InsertElementInst
*>(this)); } Value *InsertElementInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<InsertElementInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1978, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<InsertElementInst>::op_begin(const_cast
<InsertElementInst*>(this))[i_nocapture].get()); } void
InsertElementInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<InsertElementInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 1978, __PRETTY_FUNCTION__)); OperandTraits<InsertElementInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
InsertElementInst::getNumOperands() const { return OperandTraits
<InsertElementInst>::operands(this); } template <int
Idx_nocapture> Use &InsertElementInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &InsertElementInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
1979
1980//===----------------------------------------------------------------------===//
1981// ShuffleVectorInst Class
1982//===----------------------------------------------------------------------===//
1983
1984/// This instruction constructs a fixed permutation of two
1985/// input vectors.
1986///
1987class ShuffleVectorInst : public Instruction {
1988protected:
1989 // Note: Instruction needs to be a friend here to call cloneImpl.
1990 friend class Instruction;
1991
1992 ShuffleVectorInst *cloneImpl() const;
1993
1994public:
1995 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1996 const Twine &NameStr = "",
1997 Instruction *InsertBefor = nullptr);
1998 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1999 const Twine &NameStr, BasicBlock *InsertAtEnd);
2000
2001 // allocate space for exactly three operands
2002 void *operator new(size_t s) {
2003 return User::operator new(s, 3);
2004 }
2005
2006 /// Swap the first 2 operands and adjust the mask to preserve the semantics
2007 /// of the instruction.
2008 void commute();
2009
2010 /// Return true if a shufflevector instruction can be
2011 /// formed with the specified operands.
2012 static bool isValidOperands(const Value *V1, const Value *V2,
2013 const Value *Mask);
2014
2015 /// Overload to return most specific vector type.
2016 ///
2017 VectorType *getType() const {
2018 return cast<VectorType>(Instruction::getType());
2019 }
2020
2021 /// Transparently provide more efficient getOperand methods.
2022 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2023
2024 Constant *getMask() const {
2025 return cast<Constant>(getOperand(2));
2026 }
2027
2028 /// Return the shuffle mask value for the specified element of the mask.
2029 /// Return -1 if the element is undef.
2030 static int getMaskValue(const Constant *Mask, unsigned Elt);
2031
2032 /// Return the shuffle mask value of this instruction for the given element
2033 /// index. Return -1 if the element is undef.
2034 int getMaskValue(unsigned Elt) const {
2035 return getMaskValue(getMask(), Elt);
2036 }
2037
2038 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2039 /// elements of the mask are returned as -1.
2040 static void getShuffleMask(const Constant *Mask,
2041 SmallVectorImpl<int> &Result);
2042
2043 /// Return the mask for this instruction as a vector of integers. Undefined
2044 /// elements of the mask are returned as -1.
2045 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2046 return getShuffleMask(getMask(), Result);
2047 }
2048
2049 SmallVector<int, 16> getShuffleMask() const {
2050 SmallVector<int, 16> Mask;
2051 getShuffleMask(Mask);
2052 return Mask;
2053 }
2054
2055 /// Return true if this shuffle returns a vector with a different number of
2056 /// elements than its source vectors.
2057 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2058 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2059 bool changesLength() const {
2060 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2061 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2062 return NumSourceElts != NumMaskElts;
2063 }
2064
2065 /// Return true if this shuffle returns a vector with a greater number of
2066 /// elements than its source vectors.
2067 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2068 bool increasesLength() const {
2069 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2070 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2071 return NumSourceElts < NumMaskElts;
2072 }
2073
2074 /// Return true if this shuffle mask chooses elements from exactly one source
2075 /// vector.
2076 /// Example: <7,5,undef,7>
2077 /// This assumes that vector operands are the same length as the mask.
2078 static bool isSingleSourceMask(ArrayRef<int> Mask);
2079 static bool isSingleSourceMask(const Constant *Mask) {
2080 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2080, __PRETTY_FUNCTION__))
;
2081 SmallVector<int, 16> MaskAsInts;
2082 getShuffleMask(Mask, MaskAsInts);
2083 return isSingleSourceMask(MaskAsInts);
2084 }
2085
2086 /// Return true if this shuffle chooses elements from exactly one source
2087 /// vector without changing the length of that vector.
2088 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2089 /// TODO: Optionally allow length-changing shuffles.
2090 bool isSingleSource() const {
2091 return !changesLength() && isSingleSourceMask(getMask());
2092 }
2093
2094 /// Return true if this shuffle mask chooses elements from exactly one source
2095 /// vector without lane crossings. A shuffle using this mask is not
2096 /// necessarily a no-op because it may change the number of elements from its
2097 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2098 /// Example: <undef,undef,2,3>
2099 static bool isIdentityMask(ArrayRef<int> Mask);
2100 static bool isIdentityMask(const Constant *Mask) {
2101 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2101, __PRETTY_FUNCTION__))
;
2102 SmallVector<int, 16> MaskAsInts;
2103 getShuffleMask(Mask, MaskAsInts);
2104 return isIdentityMask(MaskAsInts);
2105 }
2106
2107 /// Return true if this shuffle chooses elements from exactly one source
2108 /// vector without lane crossings and does not change the number of elements
2109 /// from its input vectors.
2110 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2111 bool isIdentity() const {
2112 return !changesLength() && isIdentityMask(getShuffleMask());
2113 }
2114
2115 /// Return true if this shuffle lengthens exactly one source vector with
2116 /// undefs in the high elements.
2117 bool isIdentityWithPadding() const;
2118
2119 /// Return true if this shuffle extracts the first N elements of exactly one
2120 /// source vector.
2121 bool isIdentityWithExtract() const;
2122
2123 /// Return true if this shuffle concatenates its 2 source vectors. This
2124 /// returns false if either input is undefined. In that case, the shuffle is
2125 /// is better classified as an identity with padding operation.
2126 bool isConcat() const;
2127
2128 /// Return true if this shuffle mask chooses elements from its source vectors
2129 /// without lane crossings. A shuffle using this mask would be
2130 /// equivalent to a vector select with a constant condition operand.
2131 /// Example: <4,1,6,undef>
2132 /// This returns false if the mask does not choose from both input vectors.
2133 /// In that case, the shuffle is better classified as an identity shuffle.
2134 /// This assumes that vector operands are the same length as the mask
2135 /// (a length-changing shuffle can never be equivalent to a vector select).
2136 static bool isSelectMask(ArrayRef<int> Mask);
2137 static bool isSelectMask(const Constant *Mask) {
2138 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2138, __PRETTY_FUNCTION__))
;
2139 SmallVector<int, 16> MaskAsInts;
2140 getShuffleMask(Mask, MaskAsInts);
2141 return isSelectMask(MaskAsInts);
2142 }
2143
2144 /// Return true if this shuffle chooses elements from its source vectors
2145 /// without lane crossings and all operands have the same number of elements.
2146 /// In other words, this shuffle is equivalent to a vector select with a
2147 /// constant condition operand.
2148 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2149 /// This returns false if the mask does not choose from both input vectors.
2150 /// In that case, the shuffle is better classified as an identity shuffle.
2151 /// TODO: Optionally allow length-changing shuffles.
2152 bool isSelect() const {
2153 return !changesLength() && isSelectMask(getMask());
2154 }
2155
2156 /// Return true if this shuffle mask swaps the order of elements from exactly
2157 /// one source vector.
2158 /// Example: <7,6,undef,4>
2159 /// This assumes that vector operands are the same length as the mask.
2160 static bool isReverseMask(ArrayRef<int> Mask);
2161 static bool isReverseMask(const Constant *Mask) {
2162 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2162, __PRETTY_FUNCTION__))
;
2163 SmallVector<int, 16> MaskAsInts;
2164 getShuffleMask(Mask, MaskAsInts);
2165 return isReverseMask(MaskAsInts);
2166 }
2167
2168 /// Return true if this shuffle swaps the order of elements from exactly
2169 /// one source vector.
2170 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2171 /// TODO: Optionally allow length-changing shuffles.
2172 bool isReverse() const {
2173 return !changesLength() && isReverseMask(getMask());
2174 }
2175
2176 /// Return true if this shuffle mask chooses all elements with the same value
2177 /// as the first element of exactly one source vector.
2178 /// Example: <4,undef,undef,4>
2179 /// This assumes that vector operands are the same length as the mask.
2180 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2181 static bool isZeroEltSplatMask(const Constant *Mask) {
2182 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2182, __PRETTY_FUNCTION__))
;
2183 SmallVector<int, 16> MaskAsInts;
2184 getShuffleMask(Mask, MaskAsInts);
2185 return isZeroEltSplatMask(MaskAsInts);
2186 }
2187
2188 /// Return true if all elements of this shuffle are the same value as the
2189 /// first element of exactly one source vector without changing the length
2190 /// of that vector.
2191 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2192 /// TODO: Optionally allow length-changing shuffles.
2193 /// TODO: Optionally allow splats from other elements.
2194 bool isZeroEltSplat() const {
2195 return !changesLength() && isZeroEltSplatMask(getMask());
2196 }
2197
2198 /// Return true if this shuffle mask is a transpose mask.
2199 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2200 /// even- or odd-numbered vector elements from two n-dimensional source
2201 /// vectors and write each result into consecutive elements of an
2202 /// n-dimensional destination vector. Two shuffles are necessary to complete
2203 /// the transpose, one for the even elements and another for the odd elements.
2204 /// This description closely follows how the TRN1 and TRN2 AArch64
2205 /// instructions operate.
2206 ///
2207 /// For example, a simple 2x2 matrix can be transposed with:
2208 ///
2209 /// ; Original matrix
2210 /// m0 = < a, b >
2211 /// m1 = < c, d >
2212 ///
2213 /// ; Transposed matrix
2214 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2215 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2216 ///
2217 /// For matrices having greater than n columns, the resulting nx2 transposed
2218 /// matrix is stored in two result vectors such that one vector contains
2219 /// interleaved elements from all the even-numbered rows and the other vector
2220 /// contains interleaved elements from all the odd-numbered rows. For example,
2221 /// a 2x4 matrix can be transposed with:
2222 ///
2223 /// ; Original matrix
2224 /// m0 = < a, b, c, d >
2225 /// m1 = < e, f, g, h >
2226 ///
2227 /// ; Transposed matrix
2228 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2229 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2230 static bool isTransposeMask(ArrayRef<int> Mask);
2231 static bool isTransposeMask(const Constant *Mask) {
2232 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2232, __PRETTY_FUNCTION__))
;
2233 SmallVector<int, 16> MaskAsInts;
2234 getShuffleMask(Mask, MaskAsInts);
2235 return isTransposeMask(MaskAsInts);
2236 }
2237
2238 /// Return true if this shuffle transposes the elements of its inputs without
2239 /// changing the length of the vectors. This operation may also be known as a
2240 /// merge or interleave. See the description for isTransposeMask() for the
2241 /// exact specification.
2242 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2243 bool isTranspose() const {
2244 return !changesLength() && isTransposeMask(getMask());
2245 }
2246
2247 /// Return true if this shuffle mask is an extract subvector mask.
2248 /// A valid extract subvector mask returns a smaller vector from a single
2249 /// source operand. The base extraction index is returned as well.
2250 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2251 int &Index);
2252 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2253 int &Index) {
2254 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2254, __PRETTY_FUNCTION__))
;
2255 SmallVector<int, 16> MaskAsInts;
2256 getShuffleMask(Mask, MaskAsInts);
2257 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2258 }
2259
2260 /// Return true if this shuffle mask is an extract subvector mask.
2261 bool isExtractSubvectorMask(int &Index) const {
2262 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2263 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2264 }
2265
2266 /// Change values in a shuffle permute mask assuming the two vector operands
2267 /// of length InVecNumElts have swapped position.
2268 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2269 unsigned InVecNumElts) {
2270 for (int &Idx : Mask) {
2271 if (Idx == -1)
2272 continue;
2273 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2274 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&((Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
"shufflevector mask index out of range") ? static_cast<void
> (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2275, __PRETTY_FUNCTION__))
2275 "shufflevector mask index out of range")((Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
"shufflevector mask index out of range") ? static_cast<void
> (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2275, __PRETTY_FUNCTION__))
;
2276 }
2277 }
2278
2279 // Methods for support type inquiry through isa, cast, and dyn_cast:
2280 static bool classof(const Instruction *I) {
2281 return I->getOpcode() == Instruction::ShuffleVector;
2282 }
2283 static bool classof(const Value *V) {
2284 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2285 }
2286};
2287
2288template <>
2289struct OperandTraits<ShuffleVectorInst> :
2290 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2291};
2292
2293DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)ShuffleVectorInst::op_iterator ShuffleVectorInst::op_begin() {
return OperandTraits<ShuffleVectorInst>::op_begin(this
); } ShuffleVectorInst::const_op_iterator ShuffleVectorInst::
op_begin() const { return OperandTraits<ShuffleVectorInst>
::op_begin(const_cast<ShuffleVectorInst*>(this)); } ShuffleVectorInst
::op_iterator ShuffleVectorInst::op_end() { return OperandTraits
<ShuffleVectorInst>::op_end(this); } ShuffleVectorInst::
const_op_iterator ShuffleVectorInst::op_end() const { return OperandTraits
<ShuffleVectorInst>::op_end(const_cast<ShuffleVectorInst
*>(this)); } Value *ShuffleVectorInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<ShuffleVectorInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2293, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ShuffleVectorInst>::op_begin(const_cast
<ShuffleVectorInst*>(this))[i_nocapture].get()); } void
ShuffleVectorInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<ShuffleVectorInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/Instructions.h"
, 2293, __PRETTY_FUNCTION__)); OperandTraits<ShuffleVectorInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
ShuffleVectorInst::getNumOperands() const { return OperandTraits
<ShuffleVectorInst>::operands(this); } template <int
Idx_nocapture> Use &ShuffleVectorInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &ShuffleVectorInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
2294
2295//===----------------------------------------------------------------------===//
2296// ExtractValueInst Class
2297//===----------------------------------------------------------------------===//
2298
2299/// This instruction extracts a struct member or array
2300/// element value from an aggregate value.
2301///
2302class ExtractValueInst : public UnaryInstruction {
2303 SmallVector<unsigned, 4> Indices;
2304
2305 ExtractValueInst(const ExtractValueInst &EVI);
2306
2307 /// Constructors - Create a extractvalue instruction with a base aggregate
2308 /// value and a list of indices. The first ctor can optionally insert before
2309 /// an existing instruction, the second appends the new instruction to the
2310 /// specified BasicBlock.
2311 inline ExtractValueInst(Value *Agg,
2312 ArrayRef<unsigned> Idxs,
2313 const Twine &NameStr,
2314 Instruction *InsertBefore);
2315 inline ExtractValueInst(Value *Agg,
2316 ArrayRef<unsigned> Idxs,
2317 const Twine &NameStr, BasicBlock *InsertAtEnd);
2318
2319 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2320
2321protected:
2322 // Note: Instruction needs to be a friend here to call cloneImpl.
2323 friend class Instruction;
2324
2325 ExtractValueInst *cloneImpl() const;
2326
2327public:
2328 static ExtractValueInst *Create(Value *Agg,
2329 ArrayRef<unsigned> Idxs,
2330 const Twine &NameStr = "",
2331 Instruction *InsertBefore = nullptr) {
2332 return new
2333 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2334 }
2335
2336 static ExtractValueInst *Create(Value *Agg,
2337 ArrayRef<unsigned> Idxs,
2338 const Twine &NameStr,
2339 BasicBlock *InsertAtEnd) {
2340 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2341 }
2342
2343 /// Returns the type of the element that would be extracted
2344 /// with an extractvalue instruction with the specified parameters.
2345 ///
2346 /// Null is returned if the indices are invalid for the specified type.
2347 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2348
2349 using idx_iterator = const unsigned*;
2350
2351 inline idx_iterator idx_begin() const { return Indices.begin(); }
2352 inline idx_iterator idx_end() const { return Indices.end(); }
2353 inline iterator_range<idx_iterator> indices() const {
2354 return make_range(idx_begin(), idx_end());
2355 }
2356
2357 Value *getAggregateOperand() {
2358 return getOperand(0);
2359 }
2360 const Value *getAggregateOperand() const {
2361 return getOperand(0);
2362 }
2363 static unsigned getAggregateOperandIndex() {
2364 return 0U; // get index for modifying correct operand
2365 }
2366
2367 ArrayRef<unsigned> getIndices() const {
2368 return Indices;
2369 }
2370
2371 unsigned getNumIndices() const {
2372 return (unsigned)Indices.size();
2373 }
2374
2375 bool hasIndices() const {
2376 return true;
2377 }
2378
2379 // Methods for support type inquiry through isa, cast, and dyn_cast:
2380 static bool classof(const Instruction *I) {
2381 return I->getOpcode() == Instruction::ExtractValue;
2382 }
2383 static bool classof(const Value *V) {
2384 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2385 }
2386};
2387
2388ExtractValueInst::ExtractValueInst(Value *Agg,
2389 ArrayRef<unsigned> Idxs,
2390 const Twine &NameStr,
2391 Instruction *InsertBefore)
2392 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2393 ExtractValue, Agg, InsertBefore) {
2394 init(Idxs, NameStr);
2395}
2396
2397ExtractValueInst::ExtractValueInst(Value *Agg,
2398 ArrayRef<unsigned> Idxs,
2399 const Twine &NameStr,
2400 BasicBlock *InsertAtEnd)
2401 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2402 ExtractValue, Agg, InsertAtEnd) {
2403 init(Idxs, NameStr);
2404}
2405
2406//===----------------------------------------------------------------------===//
2407// InsertValueInst Class