Bug Summary

File:llvm/lib/Transforms/Scalar/JumpThreading.cpp
Warning:line 1398, 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 -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/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-10/lib/clang/10.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-10~+201911111502510600c19528f1809/build-llvm/lib/Transforms/Scalar -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -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-2019-12-05-225554-32688-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/Scalar/JumpThreading.cpp

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

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