Bug Summary

File:llvm/lib/Transforms/Scalar/LICM.cpp
Warning:line 1211, column 33
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LICM.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 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/lib/Transforms/Scalar -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/lib/Transforms/Scalar -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-05-07-005843-9350-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp

/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp

1//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
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 pass performs loop invariant code motion, attempting to remove as much
10// code from the body of a loop as possible. It does this by either hoisting
11// code into the preheader block, or by sinking code to the exit blocks if it is
12// safe. This pass also promotes must-aliased memory locations in the loop to
13// live in registers, thus hoisting and sinking "invariant" loads and stores.
14//
15// Hoisting operations out of loops is a canonicalization transform. It
16// enables and simplifies subsequent optimizations in the middle-end.
17// Rematerialization of hoisted instructions to reduce register pressure is the
18// responsibility of the back-end, which has more accurate information about
19// register pressure and also handles other optimizations than LICM that
20// increase live-ranges.
21//
22// This pass uses alias analysis for two purposes:
23//
24// 1. Moving loop invariant loads and calls out of loops. If we can determine
25// that a load or call inside of a loop never aliases anything stored to,
26// we can hoist it or sink it like any other instruction.
27// 2. Scalar Promotion of Memory - If there is a store instruction inside of
28// the loop, we try to move the store to happen AFTER the loop instead of
29// inside of the loop. This can only happen if a few conditions are true:
30// A. The pointer stored through is loop invariant
31// B. There are no stores or loads in the loop which _may_ alias the
32// pointer. There are no calls in the loop which mod/ref the pointer.
33// If these conditions are true, we can promote the loads and stores in the
34// loop of the pointer to use a temporary alloca'd variable. We then use
35// the SSAUpdater to construct the appropriate SSA form for the value.
36//
37//===----------------------------------------------------------------------===//
38
39#include "llvm/Transforms/Scalar/LICM.h"
40#include "llvm/ADT/SetOperations.h"
41#include "llvm/ADT/Statistic.h"
42#include "llvm/Analysis/AliasAnalysis.h"
43#include "llvm/Analysis/AliasSetTracker.h"
44#include "llvm/Analysis/BasicAliasAnalysis.h"
45#include "llvm/Analysis/BlockFrequencyInfo.h"
46#include "llvm/Analysis/CaptureTracking.h"
47#include "llvm/Analysis/ConstantFolding.h"
48#include "llvm/Analysis/GlobalsModRef.h"
49#include "llvm/Analysis/GuardUtils.h"
50#include "llvm/Analysis/LazyBlockFrequencyInfo.h"
51#include "llvm/Analysis/Loads.h"
52#include "llvm/Analysis/LoopInfo.h"
53#include "llvm/Analysis/LoopIterator.h"
54#include "llvm/Analysis/LoopPass.h"
55#include "llvm/Analysis/MemoryBuiltins.h"
56#include "llvm/Analysis/MemorySSA.h"
57#include "llvm/Analysis/MemorySSAUpdater.h"
58#include "llvm/Analysis/MustExecute.h"
59#include "llvm/Analysis/OptimizationRemarkEmitter.h"
60#include "llvm/Analysis/ScalarEvolution.h"
61#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
62#include "llvm/Analysis/TargetLibraryInfo.h"
63#include "llvm/Analysis/ValueTracking.h"
64#include "llvm/IR/CFG.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfoMetadata.h"
68#include "llvm/IR/DerivedTypes.h"
69#include "llvm/IR/Dominators.h"
70#include "llvm/IR/Instructions.h"
71#include "llvm/IR/IntrinsicInst.h"
72#include "llvm/IR/LLVMContext.h"
73#include "llvm/IR/Metadata.h"
74#include "llvm/IR/PatternMatch.h"
75#include "llvm/IR/PredIteratorCache.h"
76#include "llvm/InitializePasses.h"
77#include "llvm/Support/CommandLine.h"
78#include "llvm/Support/Debug.h"
79#include "llvm/Support/raw_ostream.h"
80#include "llvm/Transforms/Scalar.h"
81#include "llvm/Transforms/Scalar/LoopPassManager.h"
82#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
83#include "llvm/Transforms/Utils/BasicBlockUtils.h"
84#include "llvm/Transforms/Utils/Local.h"
85#include "llvm/Transforms/Utils/LoopUtils.h"
86#include "llvm/Transforms/Utils/SSAUpdater.h"
87#include <algorithm>
88#include <utility>
89using namespace llvm;
90
91#define DEBUG_TYPE"licm" "licm"
92
93STATISTIC(NumCreatedBlocks, "Number of blocks created")static llvm::Statistic NumCreatedBlocks = {"licm", "NumCreatedBlocks"
, "Number of blocks created"}
;
94STATISTIC(NumClonedBranches, "Number of branches cloned")static llvm::Statistic NumClonedBranches = {"licm", "NumClonedBranches"
, "Number of branches cloned"}
;
95STATISTIC(NumSunk, "Number of instructions sunk out of loop")static llvm::Statistic NumSunk = {"licm", "NumSunk", "Number of instructions sunk out of loop"
}
;
96STATISTIC(NumHoisted, "Number of instructions hoisted out of loop")static llvm::Statistic NumHoisted = {"licm", "NumHoisted", "Number of instructions hoisted out of loop"
}
;
97STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk")static llvm::Statistic NumMovedLoads = {"licm", "NumMovedLoads"
, "Number of load insts hoisted or sunk"}
;
98STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk")static llvm::Statistic NumMovedCalls = {"licm", "NumMovedCalls"
, "Number of call insts hoisted or sunk"}
;
99STATISTIC(NumPromoted, "Number of memory locations promoted to registers")static llvm::Statistic NumPromoted = {"licm", "NumPromoted", "Number of memory locations promoted to registers"
}
;
100
101/// Memory promotion is enabled by default.
102static cl::opt<bool>
103 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
104 cl::desc("Disable memory promotion in LICM pass"));
105
106static cl::opt<bool> ControlFlowHoisting(
107 "licm-control-flow-hoisting", cl::Hidden, cl::init(false),
108 cl::desc("Enable control flow (and PHI) hoisting in LICM"));
109
110static cl::opt<unsigned> HoistSinkColdnessThreshold(
111 "licm-coldness-threshold", cl::Hidden, cl::init(4),
112 cl::desc("Relative coldness Threshold of hoisting/sinking destination "
113 "block for LICM to be considered beneficial"));
114
115static cl::opt<uint32_t> MaxNumUsesTraversed(
116 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
117 cl::desc("Max num uses visited for identifying load "
118 "invariance in loop using invariant start (default = 8)"));
119
120// Default value of zero implies we use the regular alias set tracker mechanism
121// instead of the cross product using AA to identify aliasing of the memory
122// location we are interested in.
123static cl::opt<int>
124LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0),
125 cl::desc("How many instruction to cross product using AA"));
126
127// Experimental option to allow imprecision in LICM in pathological cases, in
128// exchange for faster compile. This is to be removed if MemorySSA starts to
129// address the same issue. This flag applies only when LICM uses MemorySSA
130// instead on AliasSetTracker. LICM calls MemorySSAWalker's
131// getClobberingMemoryAccess, up to the value of the Cap, getting perfect
132// accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess,
133// which may not be precise, since optimizeUses is capped. The result is
134// correct, but we may not get as "far up" as possible to get which access is
135// clobbering the one queried.
136cl::opt<unsigned> llvm::SetLicmMssaOptCap(
137 "licm-mssa-optimization-cap", cl::init(100), cl::Hidden,
138 cl::desc("Enable imprecision in LICM in pathological cases, in exchange "
139 "for faster compile. Caps the MemorySSA clobbering calls."));
140
141// Experimentally, memory promotion carries less importance than sinking and
142// hoisting. Limit when we do promotion when using MemorySSA, in order to save
143// compile time.
144cl::opt<unsigned> llvm::SetLicmMssaNoAccForPromotionCap(
145 "licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden,
146 cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no "
147 "effect. When MSSA in LICM is enabled, then this is the maximum "
148 "number of accesses allowed to be present in a loop in order to "
149 "enable memory promotion."));
150
151static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
152static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
153 const LoopSafetyInfo *SafetyInfo,
154 TargetTransformInfo *TTI, bool &FreeInLoop);
155static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
156 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
157 MemorySSAUpdater *MSSAU, ScalarEvolution *SE,
158 OptimizationRemarkEmitter *ORE);
159static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
160 BlockFrequencyInfo *BFI, const Loop *CurLoop,
161 ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU,
162 OptimizationRemarkEmitter *ORE);
163static bool isSafeToExecuteUnconditionally(Instruction &Inst,
164 const DominatorTree *DT,
165 const TargetLibraryInfo *TLI,
166 const Loop *CurLoop,
167 const LoopSafetyInfo *SafetyInfo,
168 OptimizationRemarkEmitter *ORE,
169 const Instruction *CtxI = nullptr);
170static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
171 AliasSetTracker *CurAST, Loop *CurLoop,
172 AAResults *AA);
173static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU,
174 Loop *CurLoop, Instruction &I,
175 SinkAndHoistLICMFlags &Flags);
176static bool pointerInvalidatedByBlockWithMSSA(BasicBlock &BB, MemorySSA &MSSA,
177 MemoryUse &MU);
178static Instruction *cloneInstructionInExitBlock(
179 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
180 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU);
181
182static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
183 AliasSetTracker *AST, MemorySSAUpdater *MSSAU);
184
185static void moveInstructionBefore(Instruction &I, Instruction &Dest,
186 ICFLoopSafetyInfo &SafetyInfo,
187 MemorySSAUpdater *MSSAU, ScalarEvolution *SE);
188
189static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,
190 function_ref<void(Instruction *)> Fn);
191static SmallVector<SmallSetVector<Value *, 8>, 0>
192collectPromotionCandidates(MemorySSA *MSSA, AliasAnalysis *AA, Loop *L,
193 SmallVectorImpl<Instruction *> &MaybePromotable);
194
195namespace {
196struct LoopInvariantCodeMotion {
197 bool runOnLoop(Loop *L, AAResults *AA, LoopInfo *LI, DominatorTree *DT,
198 BlockFrequencyInfo *BFI, TargetLibraryInfo *TLI,
199 TargetTransformInfo *TTI, ScalarEvolution *SE, MemorySSA *MSSA,
200 OptimizationRemarkEmitter *ORE);
201
202 LoopInvariantCodeMotion(unsigned LicmMssaOptCap,
203 unsigned LicmMssaNoAccForPromotionCap)
204 : LicmMssaOptCap(LicmMssaOptCap),
205 LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap) {}
206
207private:
208 unsigned LicmMssaOptCap;
209 unsigned LicmMssaNoAccForPromotionCap;
210
211 std::unique_ptr<AliasSetTracker>
212 collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AAResults *AA);
213};
214
215struct LegacyLICMPass : public LoopPass {
216 static char ID; // Pass identification, replacement for typeid
217 LegacyLICMPass(
218 unsigned LicmMssaOptCap = SetLicmMssaOptCap,
219 unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap)
220 : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap) {
221 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
222 }
223
224 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
225 if (skipLoop(L))
226 return false;
227
228 LLVM_DEBUG(dbgs() << "Perform LICM on Loop with header at block "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Perform LICM on Loop with header at block "
<< L->getHeader()->getNameOrAsOperand() <<
"\n"; } } while (false)
229 << L->getHeader()->getNameOrAsOperand() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Perform LICM on Loop with header at block "
<< L->getHeader()->getNameOrAsOperand() <<
"\n"; } } while (false)
;
230
231 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
232 MemorySSA *MSSA = EnableMSSALoopDependency
233 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
234 : nullptr;
235 bool hasProfileData = L->getHeader()->getParent()->hasProfileData();
236 BlockFrequencyInfo *BFI =
237 hasProfileData ? &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI()
238 : nullptr;
239 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
240 // pass. Function analyses need to be preserved across loop transformations
241 // but ORE cannot be preserved (see comment before the pass definition).
242 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
243 return LICM.runOnLoop(
244 L, &getAnalysis<AAResultsWrapperPass>().getAAResults(),
245 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
246 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), BFI,
247 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
248 *L->getHeader()->getParent()),
249 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
250 *L->getHeader()->getParent()),
251 SE ? &SE->getSE() : nullptr, MSSA, &ORE);
252 }
253
254 /// This transformation requires natural loop information & requires that
255 /// loop preheaders be inserted into the CFG...
256 ///
257 void getAnalysisUsage(AnalysisUsage &AU) const override {
258 AU.addPreserved<DominatorTreeWrapperPass>();
259 AU.addPreserved<LoopInfoWrapperPass>();
260 AU.addRequired<TargetLibraryInfoWrapperPass>();
261 if (EnableMSSALoopDependency) {
262 AU.addRequired<MemorySSAWrapperPass>();
263 AU.addPreserved<MemorySSAWrapperPass>();
264 }
265 AU.addRequired<TargetTransformInfoWrapperPass>();
266 getLoopAnalysisUsage(AU);
267 LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
268 AU.addPreserved<LazyBlockFrequencyInfoPass>();
269 AU.addPreserved<LazyBranchProbabilityInfoPass>();
270 }
271
272private:
273 LoopInvariantCodeMotion LICM;
274};
275} // namespace
276
277PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
278 LoopStandardAnalysisResults &AR, LPMUpdater &) {
279 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
280 // pass. Function analyses need to be preserved across loop transformations
281 // but ORE cannot be preserved (see comment before the pass definition).
282 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
283
284 LoopInvariantCodeMotion LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap);
285 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, AR.BFI, &AR.TLI, &AR.TTI,
286 &AR.SE, AR.MSSA, &ORE))
287 return PreservedAnalyses::all();
288
289 auto PA = getLoopPassPreservedAnalyses();
290
291 PA.preserve<DominatorTreeAnalysis>();
292 PA.preserve<LoopAnalysis>();
293 if (AR.MSSA)
294 PA.preserve<MemorySSAAnalysis>();
295
296 return PA;
297}
298
299char LegacyLICMPass::ID = 0;
300INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",static void *initializeLegacyLICMPassPassOnce(PassRegistry &
Registry) {
301 false, false)static void *initializeLegacyLICMPassPassOnce(PassRegistry &
Registry) {
302INITIALIZE_PASS_DEPENDENCY(LoopPass)initializeLoopPassPass(Registry);
303INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
304INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
305INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)initializeMemorySSAWrapperPassPass(Registry);
306INITIALIZE_PASS_DEPENDENCY(LazyBFIPass)initializeLazyBFIPassPass(Registry);
307INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,PassInfo *PI = new PassInfo( "Loop Invariant Code Motion", "licm"
, &LegacyLICMPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<LegacyLICMPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeLegacyLICMPassPassFlag
; void llvm::initializeLegacyLICMPassPass(PassRegistry &Registry
) { llvm::call_once(InitializeLegacyLICMPassPassFlag, initializeLegacyLICMPassPassOnce
, std::ref(Registry)); }
308 false)PassInfo *PI = new PassInfo( "Loop Invariant Code Motion", "licm"
, &LegacyLICMPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<LegacyLICMPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeLegacyLICMPassPassFlag
; void llvm::initializeLegacyLICMPassPass(PassRegistry &Registry
) { llvm::call_once(InitializeLegacyLICMPassPassFlag, initializeLegacyLICMPassPassOnce
, std::ref(Registry)); }
309
310Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
311Pass *llvm::createLICMPass(unsigned LicmMssaOptCap,
312 unsigned LicmMssaNoAccForPromotionCap) {
313 return new LegacyLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap);
314}
315
316llvm::SinkAndHoistLICMFlags::SinkAndHoistLICMFlags(bool IsSink, Loop *L,
317 MemorySSA *MSSA)
318 : SinkAndHoistLICMFlags(SetLicmMssaOptCap, SetLicmMssaNoAccForPromotionCap,
319 IsSink, L, MSSA) {}
320
321llvm::SinkAndHoistLICMFlags::SinkAndHoistLICMFlags(
322 unsigned LicmMssaOptCap, unsigned LicmMssaNoAccForPromotionCap, bool IsSink,
323 Loop *L, MemorySSA *MSSA)
324 : LicmMssaOptCap(LicmMssaOptCap),
325 LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap),
326 IsSink(IsSink) {
327 assert(((L != nullptr) == (MSSA != nullptr)) &&(static_cast <bool> (((L != nullptr) == (MSSA != nullptr
)) && "Unexpected values for SinkAndHoistLICMFlags") ?
void (0) : __assert_fail ("((L != nullptr) == (MSSA != nullptr)) && \"Unexpected values for SinkAndHoistLICMFlags\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 328, __extension__ __PRETTY_FUNCTION__))
328 "Unexpected values for SinkAndHoistLICMFlags")(static_cast <bool> (((L != nullptr) == (MSSA != nullptr
)) && "Unexpected values for SinkAndHoistLICMFlags") ?
void (0) : __assert_fail ("((L != nullptr) == (MSSA != nullptr)) && \"Unexpected values for SinkAndHoistLICMFlags\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 328, __extension__ __PRETTY_FUNCTION__))
;
329 if (!MSSA)
330 return;
331
332 unsigned AccessCapCount = 0;
333 for (auto *BB : L->getBlocks())
334 if (const auto *Accesses = MSSA->getBlockAccesses(BB))
335 for (const auto &MA : *Accesses) {
336 (void)MA;
337 ++AccessCapCount;
338 if (AccessCapCount > LicmMssaNoAccForPromotionCap) {
339 NoOfMemAccTooLarge = true;
340 return;
341 }
342 }
343}
344
345/// Hoist expressions out of the specified loop. Note, alias info for inner
346/// loop is not preserved so it is not a good idea to run LICM multiple
347/// times on one loop.
348bool LoopInvariantCodeMotion::runOnLoop(
349 Loop *L, AAResults *AA, LoopInfo *LI, DominatorTree *DT,
350 BlockFrequencyInfo *BFI, TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
351 ScalarEvolution *SE, MemorySSA *MSSA, OptimizationRemarkEmitter *ORE) {
352 bool Changed = false;
353
354 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.")(static_cast <bool> (L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."
) ? void (0) : __assert_fail ("L->isLCSSAForm(*DT) && \"Loop is not in LCSSA form.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 354, __extension__ __PRETTY_FUNCTION__))
;
355
356 // If this loop has metadata indicating that LICM is not to be performed then
357 // just exit.
358 if (hasDisableLICMTransformsHint(L)) {
359 return false;
360 }
361
362 std::unique_ptr<AliasSetTracker> CurAST;
363 std::unique_ptr<MemorySSAUpdater> MSSAU;
364 std::unique_ptr<SinkAndHoistLICMFlags> Flags;
365
366 // Don't sink stores from loops with coroutine suspend instructions.
367 // LICM would sink instructions into the default destination of
368 // the coroutine switch. The default destination of the switch is to
369 // handle the case where the coroutine is suspended, by which point the
370 // coroutine frame may have been destroyed. No instruction can be sunk there.
371 // FIXME: This would unfortunately hurt the performance of coroutines, however
372 // there is currently no general solution for this. Similar issues could also
373 // potentially happen in other passes where instructions are being moved
374 // across that edge.
375 bool HasCoroSuspendInst = llvm::any_of(L->getBlocks(), [](BasicBlock *BB) {
376 return llvm::any_of(*BB, [](Instruction &I) {
377 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
378 return II && II->getIntrinsicID() == Intrinsic::coro_suspend;
379 });
380 });
381
382 if (!MSSA) {
383 LLVM_DEBUG(dbgs() << "LICM: Using Alias Set Tracker.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM: Using Alias Set Tracker.\n"
; } } while (false)
;
384 CurAST = collectAliasInfoForLoop(L, LI, AA);
385 Flags = std::make_unique<SinkAndHoistLICMFlags>(
386 LicmMssaOptCap, LicmMssaNoAccForPromotionCap, /*IsSink=*/true);
387 } else {
388 LLVM_DEBUG(dbgs() << "LICM: Using MemorySSA.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM: Using MemorySSA.\n"; } } while
(false)
;
389 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
390 Flags = std::make_unique<SinkAndHoistLICMFlags>(
391 LicmMssaOptCap, LicmMssaNoAccForPromotionCap, /*IsSink=*/true, L, MSSA);
392 }
393
394 // Get the preheader block to move instructions into...
395 BasicBlock *Preheader = L->getLoopPreheader();
396
397 // Compute loop safety information.
398 ICFLoopSafetyInfo SafetyInfo;
399 SafetyInfo.computeLoopSafetyInfo(L);
400
401 // We want to visit all of the instructions in this loop... that are not parts
402 // of our subloops (they have already had their invariants hoisted out of
403 // their loop, into this loop, so there is no need to process the BODIES of
404 // the subloops).
405 //
406 // Traverse the body of the loop in depth first order on the dominator tree so
407 // that we are guaranteed to see definitions before we see uses. This allows
408 // us to sink instructions in one pass, without iteration. After sinking
409 // instructions, we perform another pass to hoist them out of the loop.
410 if (L->hasDedicatedExits())
411 Changed |=
412 sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, BFI, TLI, TTI, L,
413 CurAST.get(), MSSAU.get(), &SafetyInfo, *Flags.get(), ORE);
414 Flags->setIsSink(false);
415 if (Preheader)
416 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, BFI, TLI, L,
417 CurAST.get(), MSSAU.get(), SE, &SafetyInfo,
418 *Flags.get(), ORE);
419
420 // Now that all loop invariants have been removed from the loop, promote any
421 // memory references to scalars that we can.
422 // Don't sink stores from loops without dedicated block exits. Exits
423 // containing indirect branches are not transformed by loop simplify,
424 // make sure we catch that. An additional load may be generated in the
425 // preheader for SSA updater, so also avoid sinking when no preheader
426 // is available.
427 if (!DisablePromotion && Preheader && L->hasDedicatedExits() &&
428 !Flags->tooManyMemoryAccesses() && !HasCoroSuspendInst) {
429 // Figure out the loop exits and their insertion points
430 SmallVector<BasicBlock *, 8> ExitBlocks;
431 L->getUniqueExitBlocks(ExitBlocks);
432
433 // We can't insert into a catchswitch.
434 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
435 return isa<CatchSwitchInst>(Exit->getTerminator());
436 });
437
438 if (!HasCatchSwitch) {
439 SmallVector<Instruction *, 8> InsertPts;
440 SmallVector<MemoryAccess *, 8> MSSAInsertPts;
441 InsertPts.reserve(ExitBlocks.size());
442 if (MSSAU)
443 MSSAInsertPts.reserve(ExitBlocks.size());
444 for (BasicBlock *ExitBlock : ExitBlocks) {
445 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
446 if (MSSAU)
447 MSSAInsertPts.push_back(nullptr);
448 }
449
450 PredIteratorCache PIC;
451
452 bool Promoted = false;
453 if (CurAST.get()) {
454 // Loop over all of the alias sets in the tracker object.
455 for (AliasSet &AS : *CurAST) {
456 // We can promote this alias set if it has a store, if it is a "Must"
457 // alias set, if the pointer is loop invariant, and if we are not
458 // eliminating any volatile loads or stores.
459 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
460 !L->isLoopInvariant(AS.begin()->getValue()))
461 continue;
462
463 assert((static_cast <bool> (!AS.empty() && "Must alias set should have at least one pointer element in it!"
) ? void (0) : __assert_fail ("!AS.empty() && \"Must alias set should have at least one pointer element in it!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 465, __extension__ __PRETTY_FUNCTION__))
464 !AS.empty() &&(static_cast <bool> (!AS.empty() && "Must alias set should have at least one pointer element in it!"
) ? void (0) : __assert_fail ("!AS.empty() && \"Must alias set should have at least one pointer element in it!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 465, __extension__ __PRETTY_FUNCTION__))
465 "Must alias set should have at least one pointer element in it!")(static_cast <bool> (!AS.empty() && "Must alias set should have at least one pointer element in it!"
) ? void (0) : __assert_fail ("!AS.empty() && \"Must alias set should have at least one pointer element in it!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 465, __extension__ __PRETTY_FUNCTION__))
;
466
467 SmallSetVector<Value *, 8> PointerMustAliases;
468 for (const auto &ASI : AS)
469 PointerMustAliases.insert(ASI.getValue());
470
471 Promoted |= promoteLoopAccessesToScalars(
472 PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI,
473 DT, TLI, L, CurAST.get(), MSSAU.get(), &SafetyInfo, ORE);
474 }
475 } else {
476 SmallVector<Instruction *, 16> MaybePromotable;
477 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
478 MaybePromotable.push_back(I);
479 });
480
481 // Promoting one set of accesses may make the pointers for another set
482 // loop invariant, so run this in a loop (with the MaybePromotable set
483 // decreasing in size over time).
484 bool LocalPromoted;
485 do {
486 LocalPromoted = false;
487 for (const SmallSetVector<Value *, 8> &PointerMustAliases :
488 collectPromotionCandidates(MSSA, AA, L, MaybePromotable)) {
489 LocalPromoted |= promoteLoopAccessesToScalars(
490 PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC,
491 LI, DT, TLI, L, /*AST*/nullptr, MSSAU.get(), &SafetyInfo, ORE);
492 }
493 Promoted |= LocalPromoted;
494 } while (LocalPromoted);
495 }
496
497 // Once we have promoted values across the loop body we have to
498 // recursively reform LCSSA as any nested loop may now have values defined
499 // within the loop used in the outer loop.
500 // FIXME: This is really heavy handed. It would be a bit better to use an
501 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
502 // it as it went.
503 if (Promoted)
504 formLCSSARecursively(*L, *DT, LI, SE);
505
506 Changed |= Promoted;
507 }
508 }
509
510 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
511 // specifically moving instructions across the loop boundary and so it is
512 // especially in need of sanity checking here.
513 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!")(static_cast <bool> (L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!"
) ? void (0) : __assert_fail ("L->isLCSSAForm(*DT) && \"Loop not left in LCSSA form after LICM!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 513, __extension__ __PRETTY_FUNCTION__))
;
514 assert((L->isOutermost() || L->getParentLoop()->isLCSSAForm(*DT)) &&(static_cast <bool> ((L->isOutermost() || L->getParentLoop
()->isLCSSAForm(*DT)) && "Parent loop not left in LCSSA form after LICM!"
) ? void (0) : __assert_fail ("(L->isOutermost() || L->getParentLoop()->isLCSSAForm(*DT)) && \"Parent loop not left in LCSSA form after LICM!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 515, __extension__ __PRETTY_FUNCTION__))
515 "Parent loop not left in LCSSA form after LICM!")(static_cast <bool> ((L->isOutermost() || L->getParentLoop
()->isLCSSAForm(*DT)) && "Parent loop not left in LCSSA form after LICM!"
) ? void (0) : __assert_fail ("(L->isOutermost() || L->getParentLoop()->isLCSSAForm(*DT)) && \"Parent loop not left in LCSSA form after LICM!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 515, __extension__ __PRETTY_FUNCTION__))
;
516
517 if (MSSAU.get() && VerifyMemorySSA)
518 MSSAU->getMemorySSA()->verifyMemorySSA();
519
520 if (Changed && SE)
521 SE->forgetLoopDispositions(L);
522 return Changed;
523}
524
525/// Walk the specified region of the CFG (defined by all blocks dominated by
526/// the specified block, and that are in the current loop) in reverse depth
527/// first order w.r.t the DominatorTree. This allows us to visit uses before
528/// definitions, allowing us to sink a loop body in one pass without iteration.
529///
530bool llvm::sinkRegion(DomTreeNode *N, AAResults *AA, LoopInfo *LI,
531 DominatorTree *DT, BlockFrequencyInfo *BFI,
532 TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
533 Loop *CurLoop, AliasSetTracker *CurAST,
534 MemorySSAUpdater *MSSAU, ICFLoopSafetyInfo *SafetyInfo,
535 SinkAndHoistLICMFlags &Flags,
536 OptimizationRemarkEmitter *ORE) {
537
538 // Verify inputs.
539 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&(static_cast <bool> (N != nullptr && AA != nullptr
&& LI != nullptr && DT != nullptr &&
CurLoop != nullptr && SafetyInfo != nullptr &&
"Unexpected input to sinkRegion.") ? void (0) : __assert_fail
("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to sinkRegion.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 541, __extension__ __PRETTY_FUNCTION__))
540 CurLoop != nullptr && SafetyInfo != nullptr &&(static_cast <bool> (N != nullptr && AA != nullptr
&& LI != nullptr && DT != nullptr &&
CurLoop != nullptr && SafetyInfo != nullptr &&
"Unexpected input to sinkRegion.") ? void (0) : __assert_fail
("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to sinkRegion.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 541, __extension__ __PRETTY_FUNCTION__))
541 "Unexpected input to sinkRegion.")(static_cast <bool> (N != nullptr && AA != nullptr
&& LI != nullptr && DT != nullptr &&
CurLoop != nullptr && SafetyInfo != nullptr &&
"Unexpected input to sinkRegion.") ? void (0) : __assert_fail
("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to sinkRegion.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 541, __extension__ __PRETTY_FUNCTION__))
;
542 assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) &&(static_cast <bool> (((CurAST != nullptr) ^ (MSSAU != nullptr
)) && "Either AliasSetTracker or MemorySSA should be initialized."
) ? void (0) : __assert_fail ("((CurAST != nullptr) ^ (MSSAU != nullptr)) && \"Either AliasSetTracker or MemorySSA should be initialized.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 543, __extension__ __PRETTY_FUNCTION__))
543 "Either AliasSetTracker or MemorySSA should be initialized.")(static_cast <bool> (((CurAST != nullptr) ^ (MSSAU != nullptr
)) && "Either AliasSetTracker or MemorySSA should be initialized."
) ? void (0) : __assert_fail ("((CurAST != nullptr) ^ (MSSAU != nullptr)) && \"Either AliasSetTracker or MemorySSA should be initialized.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 543, __extension__ __PRETTY_FUNCTION__))
;
544
545 // We want to visit children before parents. We will enque all the parents
546 // before their children in the worklist and process the worklist in reverse
547 // order.
548 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
549
550 bool Changed = false;
551 for (DomTreeNode *DTN : reverse(Worklist)) {
552 BasicBlock *BB = DTN->getBlock();
553 // Only need to process the contents of this block if it is not part of a
554 // subloop (which would already have been processed).
555 if (inSubLoop(BB, CurLoop, LI))
556 continue;
557
558 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
559 Instruction &I = *--II;
560
561 // The instruction is not used in the loop if it is dead. In this case,
562 // we just delete it instead of sinking it.
563 if (isInstructionTriviallyDead(&I, TLI)) {
564 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM deleting dead inst: " <<
I << '\n'; } } while (false)
;
565 salvageKnowledge(&I);
566 salvageDebugInfo(I);
567 ++II;
568 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
569 Changed = true;
570 continue;
571 }
572
573 // Check to see if we can sink this instruction to the exit blocks
574 // of the loop. We can do this if the all users of the instruction are
575 // outside of the loop. In this case, it doesn't even matter if the
576 // operands of the instruction are loop invariant.
577 //
578 bool FreeInLoop = false;
579 if (!I.mayHaveSideEffects() &&
580 isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) &&
581 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags,
582 ORE)) {
583 if (sink(I, LI, DT, BFI, CurLoop, SafetyInfo, MSSAU, ORE)) {
584 if (!FreeInLoop) {
585 ++II;
586 salvageDebugInfo(I);
587 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
588 }
589 Changed = true;
590 }
591 }
592 }
593 }
594 if (MSSAU && VerifyMemorySSA)
595 MSSAU->getMemorySSA()->verifyMemorySSA();
596 return Changed;
597}
598
599namespace {
600// This is a helper class for hoistRegion to make it able to hoist control flow
601// in order to be able to hoist phis. The way this works is that we initially
602// start hoisting to the loop preheader, and when we see a loop invariant branch
603// we make note of this. When we then come to hoist an instruction that's
604// conditional on such a branch we duplicate the branch and the relevant control
605// flow, then hoist the instruction into the block corresponding to its original
606// block in the duplicated control flow.
607class ControlFlowHoister {
608private:
609 // Information about the loop we are hoisting from
610 LoopInfo *LI;
611 DominatorTree *DT;
612 Loop *CurLoop;
613 MemorySSAUpdater *MSSAU;
614
615 // A map of blocks in the loop to the block their instructions will be hoisted
616 // to.
617 DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap;
618
619 // The branches that we can hoist, mapped to the block that marks a
620 // convergence point of their control flow.
621 DenseMap<BranchInst *, BasicBlock *> HoistableBranches;
622
623public:
624 ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop,
625 MemorySSAUpdater *MSSAU)
626 : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {}
627
628 void registerPossiblyHoistableBranch(BranchInst *BI) {
629 // We can only hoist conditional branches with loop invariant operands.
630 if (!ControlFlowHoisting || !BI->isConditional() ||
631 !CurLoop->hasLoopInvariantOperands(BI))
632 return;
633
634 // The branch destinations need to be in the loop, and we don't gain
635 // anything by duplicating conditional branches with duplicate successors,
636 // as it's essentially the same as an unconditional branch.
637 BasicBlock *TrueDest = BI->getSuccessor(0);
638 BasicBlock *FalseDest = BI->getSuccessor(1);
639 if (!CurLoop->contains(TrueDest) || !CurLoop->contains(FalseDest) ||
640 TrueDest == FalseDest)
641 return;
642
643 // We can hoist BI if one branch destination is the successor of the other,
644 // or both have common successor which we check by seeing if the
645 // intersection of their successors is non-empty.
646 // TODO: This could be expanded to allowing branches where both ends
647 // eventually converge to a single block.
648 SmallPtrSet<BasicBlock *, 4> TrueDestSucc, FalseDestSucc;
649 TrueDestSucc.insert(succ_begin(TrueDest), succ_end(TrueDest));
650 FalseDestSucc.insert(succ_begin(FalseDest), succ_end(FalseDest));
651 BasicBlock *CommonSucc = nullptr;
652 if (TrueDestSucc.count(FalseDest)) {
653 CommonSucc = FalseDest;
654 } else if (FalseDestSucc.count(TrueDest)) {
655 CommonSucc = TrueDest;
656 } else {
657 set_intersect(TrueDestSucc, FalseDestSucc);
658 // If there's one common successor use that.
659 if (TrueDestSucc.size() == 1)
660 CommonSucc = *TrueDestSucc.begin();
661 // If there's more than one pick whichever appears first in the block list
662 // (we can't use the value returned by TrueDestSucc.begin() as it's
663 // unpredicatable which element gets returned).
664 else if (!TrueDestSucc.empty()) {
665 Function *F = TrueDest->getParent();
666 auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); };
667 auto It = llvm::find_if(*F, IsSucc);
668 assert(It != F->end() && "Could not find successor in function")(static_cast <bool> (It != F->end() && "Could not find successor in function"
) ? void (0) : __assert_fail ("It != F->end() && \"Could not find successor in function\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 668, __extension__ __PRETTY_FUNCTION__))
;
669 CommonSucc = &*It;
670 }
671 }
672 // The common successor has to be dominated by the branch, as otherwise
673 // there will be some other path to the successor that will not be
674 // controlled by this branch so any phi we hoist would be controlled by the
675 // wrong condition. This also takes care of avoiding hoisting of loop back
676 // edges.
677 // TODO: In some cases this could be relaxed if the successor is dominated
678 // by another block that's been hoisted and we can guarantee that the
679 // control flow has been replicated exactly.
680 if (CommonSucc && DT->dominates(BI, CommonSucc))
681 HoistableBranches[BI] = CommonSucc;
682 }
683
684 bool canHoistPHI(PHINode *PN) {
685 // The phi must have loop invariant operands.
686 if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(PN))
687 return false;
688 // We can hoist phis if the block they are in is the target of hoistable
689 // branches which cover all of the predecessors of the block.
690 SmallPtrSet<BasicBlock *, 8> PredecessorBlocks;
691 BasicBlock *BB = PN->getParent();
692 for (BasicBlock *PredBB : predecessors(BB))
693 PredecessorBlocks.insert(PredBB);
694 // If we have less predecessor blocks than predecessors then the phi will
695 // have more than one incoming value for the same block which we can't
696 // handle.
697 // TODO: This could be handled be erasing some of the duplicate incoming
698 // values.
699 if (PredecessorBlocks.size() != pred_size(BB))
700 return false;
701 for (auto &Pair : HoistableBranches) {
702 if (Pair.second == BB) {
703 // Which blocks are predecessors via this branch depends on if the
704 // branch is triangle-like or diamond-like.
705 if (Pair.first->getSuccessor(0) == BB) {
706 PredecessorBlocks.erase(Pair.first->getParent());
707 PredecessorBlocks.erase(Pair.first->getSuccessor(1));
708 } else if (Pair.first->getSuccessor(1) == BB) {
709 PredecessorBlocks.erase(Pair.first->getParent());
710 PredecessorBlocks.erase(Pair.first->getSuccessor(0));
711 } else {
712 PredecessorBlocks.erase(Pair.first->getSuccessor(0));
713 PredecessorBlocks.erase(Pair.first->getSuccessor(1));
714 }
715 }
716 }
717 // PredecessorBlocks will now be empty if for every predecessor of BB we
718 // found a hoistable branch source.
719 return PredecessorBlocks.empty();
720 }
721
722 BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) {
723 if (!ControlFlowHoisting)
724 return CurLoop->getLoopPreheader();
725 // If BB has already been hoisted, return that
726 if (HoistDestinationMap.count(BB))
727 return HoistDestinationMap[BB];
728
729 // Check if this block is conditional based on a pending branch
730 auto HasBBAsSuccessor =
731 [&](DenseMap<BranchInst *, BasicBlock *>::value_type &Pair) {
732 return BB != Pair.second && (Pair.first->getSuccessor(0) == BB ||
733 Pair.first->getSuccessor(1) == BB);
734 };
735 auto It = llvm::find_if(HoistableBranches, HasBBAsSuccessor);
736
737 // If not involved in a pending branch, hoist to preheader
738 BasicBlock *InitialPreheader = CurLoop->getLoopPreheader();
739 if (It == HoistableBranches.end()) {
740 LLVM_DEBUG(dbgs() << "LICM using "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM using " << InitialPreheader
->getNameOrAsOperand() << " as hoist destination for "
<< BB->getNameOrAsOperand() << "\n"; } } while
(false)
741 << InitialPreheader->getNameOrAsOperand()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM using " << InitialPreheader
->getNameOrAsOperand() << " as hoist destination for "
<< BB->getNameOrAsOperand() << "\n"; } } while
(false)
742 << " as hoist destination for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM using " << InitialPreheader
->getNameOrAsOperand() << " as hoist destination for "
<< BB->getNameOrAsOperand() << "\n"; } } while
(false)
743 << BB->getNameOrAsOperand() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM using " << InitialPreheader
->getNameOrAsOperand() << " as hoist destination for "
<< BB->getNameOrAsOperand() << "\n"; } } while
(false)
;
744 HoistDestinationMap[BB] = InitialPreheader;
745 return InitialPreheader;
746 }
747 BranchInst *BI = It->first;
748 assert(std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) ==(static_cast <bool> (std::find_if(++It, HoistableBranches
.end(), HasBBAsSuccessor) == HoistableBranches.end() &&
"BB is expected to be the target of at most one branch") ? void
(0) : __assert_fail ("std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) == HoistableBranches.end() && \"BB is expected to be the target of at most one branch\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 750, __extension__ __PRETTY_FUNCTION__))
749 HoistableBranches.end() &&(static_cast <bool> (std::find_if(++It, HoistableBranches
.end(), HasBBAsSuccessor) == HoistableBranches.end() &&
"BB is expected to be the target of at most one branch") ? void
(0) : __assert_fail ("std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) == HoistableBranches.end() && \"BB is expected to be the target of at most one branch\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 750, __extension__ __PRETTY_FUNCTION__))
750 "BB is expected to be the target of at most one branch")(static_cast <bool> (std::find_if(++It, HoistableBranches
.end(), HasBBAsSuccessor) == HoistableBranches.end() &&
"BB is expected to be the target of at most one branch") ? void
(0) : __assert_fail ("std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) == HoistableBranches.end() && \"BB is expected to be the target of at most one branch\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 750, __extension__ __PRETTY_FUNCTION__))
;
751
752 LLVMContext &C = BB->getContext();
753 BasicBlock *TrueDest = BI->getSuccessor(0);
754 BasicBlock *FalseDest = BI->getSuccessor(1);
755 BasicBlock *CommonSucc = HoistableBranches[BI];
756 BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent());
757
758 // Create hoisted versions of blocks that currently don't have them
759 auto CreateHoistedBlock = [&](BasicBlock *Orig) {
760 if (HoistDestinationMap.count(Orig))
761 return HoistDestinationMap[Orig];
762 BasicBlock *New =
763 BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent());
764 HoistDestinationMap[Orig] = New;
765 DT->addNewBlock(New, HoistTarget);
766 if (CurLoop->getParentLoop())
767 CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI);
768 ++NumCreatedBlocks;
769 LLVM_DEBUG(dbgs() << "LICM created " << New->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM created " << New->
getName() << " as hoist destination for " << Orig
->getName() << "\n"; } } while (false)
770 << " as hoist destination for " << Orig->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM created " << New->
getName() << " as hoist destination for " << Orig
->getName() << "\n"; } } while (false)
771 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM created " << New->
getName() << " as hoist destination for " << Orig
->getName() << "\n"; } } while (false)
;
772 return New;
773 };
774 BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest);
775 BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest);
776 BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc);
777
778 // Link up these blocks with branches.
779 if (!HoistCommonSucc->getTerminator()) {
780 // The new common successor we've generated will branch to whatever that
781 // hoist target branched to.
782 BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor();
783 assert(TargetSucc && "Expected hoist target to have a single successor")(static_cast <bool> (TargetSucc && "Expected hoist target to have a single successor"
) ? void (0) : __assert_fail ("TargetSucc && \"Expected hoist target to have a single successor\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 783, __extension__ __PRETTY_FUNCTION__))
;
784 HoistCommonSucc->moveBefore(TargetSucc);
785 BranchInst::Create(TargetSucc, HoistCommonSucc);
786 }
787 if (!HoistTrueDest->getTerminator()) {
788 HoistTrueDest->moveBefore(HoistCommonSucc);
789 BranchInst::Create(HoistCommonSucc, HoistTrueDest);
790 }
791 if (!HoistFalseDest->getTerminator()) {
792 HoistFalseDest->moveBefore(HoistCommonSucc);
793 BranchInst::Create(HoistCommonSucc, HoistFalseDest);
794 }
795
796 // If BI is being cloned to what was originally the preheader then
797 // HoistCommonSucc will now be the new preheader.
798 if (HoistTarget == InitialPreheader) {
799 // Phis in the loop header now need to use the new preheader.
800 InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc);
801 if (MSSAU)
802 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
803 HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget});
804 // The new preheader dominates the loop header.
805 DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc);
806 DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader());
807 DT->changeImmediateDominator(HeaderNode, PreheaderNode);
808 // The preheader hoist destination is now the new preheader, with the
809 // exception of the hoist destination of this branch.
810 for (auto &Pair : HoistDestinationMap)
811 if (Pair.second == InitialPreheader && Pair.first != BI->getParent())
812 Pair.second = HoistCommonSucc;
813 }
814
815 // Now finally clone BI.
816 ReplaceInstWithInst(
817 HoistTarget->getTerminator(),
818 BranchInst::Create(HoistTrueDest, HoistFalseDest, BI->getCondition()));
819 ++NumClonedBranches;
820
821 assert(CurLoop->getLoopPreheader() &&(static_cast <bool> (CurLoop->getLoopPreheader() &&
"Hoisting blocks should not have destroyed preheader") ? void
(0) : __assert_fail ("CurLoop->getLoopPreheader() && \"Hoisting blocks should not have destroyed preheader\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 822, __extension__ __PRETTY_FUNCTION__))
822 "Hoisting blocks should not have destroyed preheader")(static_cast <bool> (CurLoop->getLoopPreheader() &&
"Hoisting blocks should not have destroyed preheader") ? void
(0) : __assert_fail ("CurLoop->getLoopPreheader() && \"Hoisting blocks should not have destroyed preheader\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 822, __extension__ __PRETTY_FUNCTION__))
;
823 return HoistDestinationMap[BB];
824 }
825};
826} // namespace
827
828// Hoisting/sinking instruction out of a loop isn't always beneficial. It's only
829// only worthwhile if the destination block is actually colder than current
830// block.
831static bool worthSinkOrHoistInst(Instruction &I, BasicBlock *DstBlock,
832 OptimizationRemarkEmitter *ORE,
833 BlockFrequencyInfo *BFI) {
834 // Check block frequency only when runtime profile is available
835 // to avoid pathological cases. With static profile, lean towards
836 // hosting because it helps canonicalize the loop for vectorizer.
837 if (!DstBlock->getParent()->hasProfileData())
838 return true;
839
840 if (!HoistSinkColdnessThreshold || !BFI)
841 return true;
842
843 BasicBlock *SrcBlock = I.getParent();
844 if (BFI->getBlockFreq(DstBlock).getFrequency() / HoistSinkColdnessThreshold >
845 BFI->getBlockFreq(SrcBlock).getFrequency()) {
846 ORE->emit([&]() {
847 return OptimizationRemarkMissed(DEBUG_TYPE"licm", "SinkHoistInst", &I)
848 << "failed to sink or hoist instruction because containing block "
849 "has lower frequency than destination block";
850 });
851 return false;
852 }
853
854 return true;
855}
856
857/// Walk the specified region of the CFG (defined by all blocks dominated by
858/// the specified block, and that are in the current loop) in depth first
859/// order w.r.t the DominatorTree. This allows us to visit definitions before
860/// uses, allowing us to hoist a loop body in one pass without iteration.
861///
862bool llvm::hoistRegion(DomTreeNode *N, AAResults *AA, LoopInfo *LI,
863 DominatorTree *DT, BlockFrequencyInfo *BFI,
864 TargetLibraryInfo *TLI, Loop *CurLoop,
865 AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
866 ScalarEvolution *SE, ICFLoopSafetyInfo *SafetyInfo,
867 SinkAndHoistLICMFlags &Flags,
868 OptimizationRemarkEmitter *ORE) {
869 // Verify inputs.
870 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&(static_cast <bool> (N != nullptr && AA != nullptr
&& LI != nullptr && DT != nullptr &&
CurLoop != nullptr && SafetyInfo != nullptr &&
"Unexpected input to hoistRegion.") ? void (0) : __assert_fail
("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to hoistRegion.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 872, __extension__ __PRETTY_FUNCTION__))
871 CurLoop != nullptr && SafetyInfo != nullptr &&(static_cast <bool> (N != nullptr && AA != nullptr
&& LI != nullptr && DT != nullptr &&
CurLoop != nullptr && SafetyInfo != nullptr &&
"Unexpected input to hoistRegion.") ? void (0) : __assert_fail
("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to hoistRegion.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 872, __extension__ __PRETTY_FUNCTION__))
872 "Unexpected input to hoistRegion.")(static_cast <bool> (N != nullptr && AA != nullptr
&& LI != nullptr && DT != nullptr &&
CurLoop != nullptr && SafetyInfo != nullptr &&
"Unexpected input to hoistRegion.") ? void (0) : __assert_fail
("N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected input to hoistRegion.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 872, __extension__ __PRETTY_FUNCTION__))
;
873 assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) &&(static_cast <bool> (((CurAST != nullptr) ^ (MSSAU != nullptr
)) && "Either AliasSetTracker or MemorySSA should be initialized."
) ? void (0) : __assert_fail ("((CurAST != nullptr) ^ (MSSAU != nullptr)) && \"Either AliasSetTracker or MemorySSA should be initialized.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 874, __extension__ __PRETTY_FUNCTION__))
874 "Either AliasSetTracker or MemorySSA should be initialized.")(static_cast <bool> (((CurAST != nullptr) ^ (MSSAU != nullptr
)) && "Either AliasSetTracker or MemorySSA should be initialized."
) ? void (0) : __assert_fail ("((CurAST != nullptr) ^ (MSSAU != nullptr)) && \"Either AliasSetTracker or MemorySSA should be initialized.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 874, __extension__ __PRETTY_FUNCTION__))
;
875
876 ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU);
877
878 // Keep track of instructions that have been hoisted, as they may need to be
879 // re-hoisted if they end up not dominating all of their uses.
880 SmallVector<Instruction *, 16> HoistedInstructions;
881
882 // For PHI hoisting to work we need to hoist blocks before their successors.
883 // We can do this by iterating through the blocks in the loop in reverse
884 // post-order.
885 LoopBlocksRPO Worklist(CurLoop);
886 Worklist.perform(LI);
887 bool Changed = false;
888 for (BasicBlock *BB : Worklist) {
889 // Only need to process the contents of this block if it is not part of a
890 // subloop (which would already have been processed).
891 if (inSubLoop(BB, CurLoop, LI))
892 continue;
893
894 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
895 Instruction &I = *II++;
896 // Try constant folding this instruction. If all the operands are
897 // constants, it is technically hoistable, but it would be better to
898 // just fold it.
899 if (Constant *C = ConstantFoldInstruction(
900 &I, I.getModule()->getDataLayout(), TLI)) {
901 LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM folding inst: " << I <<
" --> " << *C << '\n'; } } while (false)
902 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM folding inst: " << I <<
" --> " << *C << '\n'; } } while (false)
;
903 if (CurAST)
904 CurAST->copyValue(&I, C);
905 // FIXME MSSA: Such replacements may make accesses unoptimized (D51960).
906 I.replaceAllUsesWith(C);
907 if (isInstructionTriviallyDead(&I, TLI))
908 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
909 Changed = true;
910 continue;
911 }
912
913 // Try hoisting the instruction out to the preheader. We can only do
914 // this if all of the operands of the instruction are loop invariant and
915 // if it is safe to hoist the instruction. We also check block frequency
916 // to make sure instruction only gets hoisted into colder blocks.
917 // TODO: It may be safe to hoist if we are hoisting to a conditional block
918 // and we have accurately duplicated the control flow from the loop header
919 // to that block.
920 if (CurLoop->hasLoopInvariantOperands(&I) &&
921 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags,
922 ORE) &&
923 worthSinkOrHoistInst(I, CurLoop->getLoopPreheader(), ORE, BFI) &&
924 isSafeToExecuteUnconditionally(
925 I, DT, TLI, CurLoop, SafetyInfo, ORE,
926 CurLoop->getLoopPreheader()->getTerminator())) {
927 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
928 MSSAU, SE, ORE);
929 HoistedInstructions.push_back(&I);
930 Changed = true;
931 continue;
932 }
933
934 // Attempt to remove floating point division out of the loop by
935 // converting it to a reciprocal multiplication.
936 if (I.getOpcode() == Instruction::FDiv && I.hasAllowReciprocal() &&
937 CurLoop->isLoopInvariant(I.getOperand(1))) {
938 auto Divisor = I.getOperand(1);
939 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
940 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
941 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
942 SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent());
943 ReciprocalDivisor->insertBefore(&I);
944
945 auto Product =
946 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
947 Product->setFastMathFlags(I.getFastMathFlags());
948 SafetyInfo->insertInstructionTo(Product, I.getParent());
949 Product->insertAfter(&I);
950 I.replaceAllUsesWith(Product);
951 eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
952
953 hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB),
954 SafetyInfo, MSSAU, SE, ORE);
955 HoistedInstructions.push_back(ReciprocalDivisor);
956 Changed = true;
957 continue;
958 }
959
960 auto IsInvariantStart = [&](Instruction &I) {
961 using namespace PatternMatch;
962 return I.use_empty() &&
963 match(&I, m_Intrinsic<Intrinsic::invariant_start>());
964 };
965 auto MustExecuteWithoutWritesBefore = [&](Instruction &I) {
966 return SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) &&
967 SafetyInfo->doesNotWriteMemoryBefore(I, CurLoop);
968 };
969 if ((IsInvariantStart(I) || isGuard(&I)) &&
970 CurLoop->hasLoopInvariantOperands(&I) &&
971 MustExecuteWithoutWritesBefore(I)) {
972 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
973 MSSAU, SE, ORE);
974 HoistedInstructions.push_back(&I);
975 Changed = true;
976 continue;
977 }
978
979 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
980 if (CFH.canHoistPHI(PN)) {
981 // Redirect incoming blocks first to ensure that we create hoisted
982 // versions of those blocks before we hoist the phi.
983 for (unsigned int i = 0; i < PN->getNumIncomingValues(); ++i)
984 PN->setIncomingBlock(
985 i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i)));
986 hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
987 MSSAU, SE, ORE);
988 assert(DT->dominates(PN, BB) && "Conditional PHIs not expected")(static_cast <bool> (DT->dominates(PN, BB) &&
"Conditional PHIs not expected") ? void (0) : __assert_fail (
"DT->dominates(PN, BB) && \"Conditional PHIs not expected\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 988, __extension__ __PRETTY_FUNCTION__))
;
989 Changed = true;
990 continue;
991 }
992 }
993
994 // Remember possibly hoistable branches so we can actually hoist them
995 // later if needed.
996 if (BranchInst *BI = dyn_cast<BranchInst>(&I))
997 CFH.registerPossiblyHoistableBranch(BI);
998 }
999 }
1000
1001 // If we hoisted instructions to a conditional block they may not dominate
1002 // their uses that weren't hoisted (such as phis where some operands are not
1003 // loop invariant). If so make them unconditional by moving them to their
1004 // immediate dominator. We iterate through the instructions in reverse order
1005 // which ensures that when we rehoist an instruction we rehoist its operands,
1006 // and also keep track of where in the block we are rehoisting to to make sure
1007 // that we rehoist instructions before the instructions that use them.
1008 Instruction *HoistPoint = nullptr;
1009 if (ControlFlowHoisting) {
1010 for (Instruction *I : reverse(HoistedInstructions)) {
1011 if (!llvm::all_of(I->uses(),
1012 [&](Use &U) { return DT->dominates(I, U); })) {
1013 BasicBlock *Dominator =
1014 DT->getNode(I->getParent())->getIDom()->getBlock();
1015 if (!HoistPoint || !DT->dominates(HoistPoint->getParent(), Dominator)) {
1016 if (HoistPoint)
1017 assert(DT->dominates(Dominator, HoistPoint->getParent()) &&(static_cast <bool> (DT->dominates(Dominator, HoistPoint
->getParent()) && "New hoist point expected to dominate old hoist point"
) ? void (0) : __assert_fail ("DT->dominates(Dominator, HoistPoint->getParent()) && \"New hoist point expected to dominate old hoist point\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1018, __extension__ __PRETTY_FUNCTION__))
1018 "New hoist point expected to dominate old hoist point")(static_cast <bool> (DT->dominates(Dominator, HoistPoint
->getParent()) && "New hoist point expected to dominate old hoist point"
) ? void (0) : __assert_fail ("DT->dominates(Dominator, HoistPoint->getParent()) && \"New hoist point expected to dominate old hoist point\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1018, __extension__ __PRETTY_FUNCTION__))
;
1019 HoistPoint = Dominator->getTerminator();
1020 }
1021 LLVM_DEBUG(dbgs() << "LICM rehoisting to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM rehoisting to " << HoistPoint
->getParent()->getNameOrAsOperand() << ": " <<
*I << "\n"; } } while (false)
1022 << HoistPoint->getParent()->getNameOrAsOperand()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM rehoisting to " << HoistPoint
->getParent()->getNameOrAsOperand() << ": " <<
*I << "\n"; } } while (false)
1023 << ": " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM rehoisting to " << HoistPoint
->getParent()->getNameOrAsOperand() << ": " <<
*I << "\n"; } } while (false)
;
1024 moveInstructionBefore(*I, *HoistPoint, *SafetyInfo, MSSAU, SE);
1025 HoistPoint = I;
1026 Changed = true;
1027 }
1028 }
1029 }
1030 if (MSSAU && VerifyMemorySSA)
1031 MSSAU->getMemorySSA()->verifyMemorySSA();
1032
1033 // Now that we've finished hoisting make sure that LI and DT are still
1034 // valid.
1035#ifdef EXPENSIVE_CHECKS
1036 if (Changed) {
1037 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&(static_cast <bool> (DT->verify(DominatorTree::VerificationLevel
::Fast) && "Dominator tree verification failed") ? void
(0) : __assert_fail ("DT->verify(DominatorTree::VerificationLevel::Fast) && \"Dominator tree verification failed\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1038, __extension__ __PRETTY_FUNCTION__))
1038 "Dominator tree verification failed")(static_cast <bool> (DT->verify(DominatorTree::VerificationLevel
::Fast) && "Dominator tree verification failed") ? void
(0) : __assert_fail ("DT->verify(DominatorTree::VerificationLevel::Fast) && \"Dominator tree verification failed\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1038, __extension__ __PRETTY_FUNCTION__))
;
1039 LI->verify(*DT);
1040 }
1041#endif
1042
1043 return Changed;
1044}
1045
1046// Return true if LI is invariant within scope of the loop. LI is invariant if
1047// CurLoop is dominated by an invariant.start representing the same memory
1048// location and size as the memory location LI loads from, and also the
1049// invariant.start has no uses.
1050static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
1051 Loop *CurLoop) {
1052 Value *Addr = LI->getOperand(0);
1053 const DataLayout &DL = LI->getModule()->getDataLayout();
1054 const TypeSize LocSizeInBits = DL.getTypeSizeInBits(LI->getType());
1055
1056 // It is not currently possible for clang to generate an invariant.start
1057 // intrinsic with scalable vector types because we don't support thread local
1058 // sizeless types and we don't permit sizeless types in structs or classes.
1059 // Furthermore, even if support is added for this in future the intrinsic
1060 // itself is defined to have a size of -1 for variable sized objects. This
1061 // makes it impossible to verify if the intrinsic envelops our region of
1062 // interest. For example, both <vscale x 32 x i8> and <vscale x 16 x i8>
1063 // types would have a -1 parameter, but the former is clearly double the size
1064 // of the latter.
1065 if (LocSizeInBits.isScalable())
30
Calling 'LinearPolySize::isScalable'
33
Returning from 'LinearPolySize::isScalable'
34
Taking true branch
1066 return false;
35
Returning zero, which participates in a condition later
1067
1068 // if the type is i8 addrspace(x)*, we know this is the type of
1069 // llvm.invariant.start operand
1070 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
1071 LI->getPointerAddressSpace());
1072 unsigned BitcastsVisited = 0;
1073 // Look through bitcasts until we reach the i8* type (this is invariant.start
1074 // operand type).
1075 while (Addr->getType() != PtrInt8Ty) {
1076 auto *BC = dyn_cast<BitCastInst>(Addr);
1077 // Avoid traversing high number of bitcast uses.
1078 if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
1079 return false;
1080 Addr = BC->getOperand(0);
1081 }
1082
1083 unsigned UsesVisited = 0;
1084 // Traverse all uses of the load operand value, to see if invariant.start is
1085 // one of the uses, and whether it dominates the load instruction.
1086 for (auto *U : Addr->users()) {
1087 // Avoid traversing for Load operand with high number of users.
1088 if (++UsesVisited > MaxNumUsesTraversed)
1089 return false;
1090 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
1091 // If there are escaping uses of invariant.start instruction, the load maybe
1092 // non-invariant.
1093 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
1094 !II->use_empty())
1095 continue;
1096 ConstantInt *InvariantSize = cast<ConstantInt>(II->getArgOperand(0));
1097 // The intrinsic supports having a -1 argument for variable sized objects
1098 // so we should check for that here.
1099 if (InvariantSize->isNegative())
1100 continue;
1101 uint64_t InvariantSizeInBits = InvariantSize->getSExtValue() * 8;
1102 // Confirm the invariant.start location size contains the load operand size
1103 // in bits. Also, the invariant.start should dominate the load, and we
1104 // should not hoist the load out of a loop that contains this dominating
1105 // invariant.start.
1106 if (LocSizeInBits.getFixedSize() <= InvariantSizeInBits &&
1107 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
1108 return true;
1109 }
1110
1111 return false;
1112}
1113
1114namespace {
1115/// Return true if-and-only-if we know how to (mechanically) both hoist and
1116/// sink a given instruction out of a loop. Does not address legality
1117/// concerns such as aliasing or speculation safety.
1118bool isHoistableAndSinkableInst(Instruction &I) {
1119 // Only these instructions are hoistable/sinkable.
1120 return (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
5
Assuming 'I' is a 'LoadInst'
6
Returning the value 1, which participates in a condition later
1121 isa<FenceInst>(I) || isa<CastInst>(I) || isa<UnaryOperator>(I) ||
1122 isa<BinaryOperator>(I) || isa<SelectInst>(I) ||
1123 isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
1124 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
1125 isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) ||
1126 isa<InsertValueInst>(I) || isa<FreezeInst>(I));
1127}
1128/// Return true if all of the alias sets within this AST are known not to
1129/// contain a Mod, or if MSSA knows there are no MemoryDefs in the loop.
1130bool isReadOnly(AliasSetTracker *CurAST, const MemorySSAUpdater *MSSAU,
1131 const Loop *L) {
1132 if (CurAST) {
1133 for (AliasSet &AS : *CurAST) {
1134 if (!AS.isForwardingAliasSet() && AS.isMod()) {
1135 return false;
1136 }
1137 }
1138 return true;
1139 } else { /*MSSAU*/
1140 for (auto *BB : L->getBlocks())
1141 if (MSSAU->getMemorySSA()->getBlockDefs(BB))
1142 return false;
1143 return true;
1144 }
1145}
1146
1147/// Return true if I is the only Instruction with a MemoryAccess in L.
1148bool isOnlyMemoryAccess(const Instruction *I, const Loop *L,
1149 const MemorySSAUpdater *MSSAU) {
1150 for (auto *BB : L->getBlocks())
1151 if (auto *Accs = MSSAU->getMemorySSA()->getBlockAccesses(BB)) {
1152 int NotAPhi = 0;
1153 for (const auto &Acc : *Accs) {
1154 if (isa<MemoryPhi>(&Acc))
1155 continue;
1156 const auto *MUD = cast<MemoryUseOrDef>(&Acc);
1157 if (MUD->getMemoryInst() != I || NotAPhi++ == 1)
1158 return false;
1159 }
1160 }
1161 return true;
1162}
1163}
1164
1165bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
1166 Loop *CurLoop, AliasSetTracker *CurAST,
1167 MemorySSAUpdater *MSSAU,
1168 bool TargetExecutesOncePerLoop,
1169 SinkAndHoistLICMFlags *Flags,
1170 OptimizationRemarkEmitter *ORE) {
1171 assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) &&(static_cast <bool> (((CurAST != nullptr) ^ (MSSAU != nullptr
)) && "Either AliasSetTracker or MemorySSA should be initialized."
) ? void (0) : __assert_fail ("((CurAST != nullptr) ^ (MSSAU != nullptr)) && \"Either AliasSetTracker or MemorySSA should be initialized.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1172, __extension__ __PRETTY_FUNCTION__))
1
Assuming pointer value is null
2
Assuming the condition is true
3
'?' condition is true
1172 "Either AliasSetTracker or MemorySSA should be initialized.")(static_cast <bool> (((CurAST != nullptr) ^ (MSSAU != nullptr
)) && "Either AliasSetTracker or MemorySSA should be initialized."
) ? void (0) : __assert_fail ("((CurAST != nullptr) ^ (MSSAU != nullptr)) && \"Either AliasSetTracker or MemorySSA should be initialized.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1172, __extension__ __PRETTY_FUNCTION__))
;
1173
1174 // If we don't understand the instruction, bail early.
1175 if (!isHoistableAndSinkableInst(I))
4
Calling 'isHoistableAndSinkableInst'
7
Returning from 'isHoistableAndSinkableInst'
8
Taking false branch
1176 return false;
1177
1178 MemorySSA *MSSA = MSSAU
8.1
'MSSAU' is non-null
8.1
'MSSAU' is non-null
8.1
'MSSAU' is non-null
8.1
'MSSAU' is non-null
? MSSAU->getMemorySSA() : nullptr;
9
'?' condition is true
10
'MSSA' initialized here
1179 if (MSSA)
11
Assuming 'MSSA' is null
12
Taking false branch
1180 assert(Flags != nullptr && "Flags cannot be null.")(static_cast <bool> (Flags != nullptr && "Flags cannot be null."
) ? void (0) : __assert_fail ("Flags != nullptr && \"Flags cannot be null.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1180, __extension__ __PRETTY_FUNCTION__))
;
1181
1182 // Loads have extra constraints we have to verify before we can hoist them.
1183 if (LoadInst *LI
13.1
'LI' is non-null
13.1
'LI' is non-null
13.1
'LI' is non-null
13.1
'LI' is non-null
= dyn_cast<LoadInst>(&I)) {
13
Assuming the object is a 'LoadInst'
14
Taking true branch
1184 if (!LI->isUnordered())
15
Calling 'LoadInst::isUnordered'
19
Returning from 'LoadInst::isUnordered'
20
Taking false branch
1185 return false; // Don't sink/hoist volatile or ordered atomic loads!
1186
1187 // Loads from constant memory are always safe to move, even if they end up
1188 // in the same alias set as something that ends up being modified.
1189 if (AA->pointsToConstantMemory(LI->getOperand(0)))
21
Assuming the condition is false
22
Taking false branch
1190 return true;
1191 if (LI->hasMetadata(LLVMContext::MD_invariant_load))
23
Calling 'Instruction::hasMetadata'
26
Returning from 'Instruction::hasMetadata'
27
Taking false branch
1192 return true;
1193
1194 if (LI->isAtomic() && !TargetExecutesOncePerLoop)
28
Assuming the condition is false
1195 return false; // Don't risk duplicating unordered loads
1196
1197 // This checks for an invariant.start dominating the load.
1198 if (isLoadInvariantInLoop(LI, DT, CurLoop))
29
Calling 'isLoadInvariantInLoop'
36
Returning from 'isLoadInvariantInLoop'
37
Taking false branch
1199 return true;
1200
1201 // Stores with an invariant.group metadata are ok to sink/hoist.
1202 if (LI->hasMetadata(LLVMContext::MD_invariant_group))
38
Calling 'Instruction::hasMetadata'
41
Returning from 'Instruction::hasMetadata'
42
Taking false branch
1203 return true;
1204
1205 bool Invalidated;
1206 if (CurAST
42.1
'CurAST' is null
42.1
'CurAST' is null
42.1
'CurAST' is null
42.1
'CurAST' is null
)
43
Taking false branch
1207 Invalidated = pointerInvalidatedByLoop(MemoryLocation::get(LI), CurAST,
1208 CurLoop, AA);
1209 else
1210 Invalidated = pointerInvalidatedByLoopWithMSSA(
1211 MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(LI)), CurLoop, I, *Flags);
44
Called C++ object pointer is null
1212 // Check loop-invariant address because this may also be a sinkable load
1213 // whose address is not necessarily loop-invariant.
1214 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1215 ORE->emit([&]() {
1216 return OptimizationRemarkMissed(
1217 DEBUG_TYPE"licm", "LoadWithLoopInvariantAddressInvalidated", LI)
1218 << "failed to move load with loop-invariant address "
1219 "because the loop may invalidate its value";
1220 });
1221
1222 return !Invalidated;
1223 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1224 // Don't sink or hoist dbg info; it's legal, but not useful.
1225 if (isa<DbgInfoIntrinsic>(I))
1226 return false;
1227
1228 // Don't sink calls which can throw.
1229 if (CI->mayThrow())
1230 return false;
1231
1232 // Convergent attribute has been used on operations that involve
1233 // inter-thread communication which results are implicitly affected by the
1234 // enclosing control flows. It is not safe to hoist or sink such operations
1235 // across control flow.
1236 if (CI->isConvergent())
1237 return false;
1238
1239 using namespace PatternMatch;
1240 if (match(CI, m_Intrinsic<Intrinsic::assume>()))
1241 // Assumes don't actually alias anything or throw
1242 return true;
1243
1244 if (match(CI, m_Intrinsic<Intrinsic::experimental_widenable_condition>()))
1245 // Widenable conditions don't actually alias anything or throw
1246 return true;
1247
1248 // Handle simple cases by querying alias analysis.
1249 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
1250 if (Behavior == FMRB_DoesNotAccessMemory)
1251 return true;
1252 if (AAResults::onlyReadsMemory(Behavior)) {
1253 // A readonly argmemonly function only reads from memory pointed to by
1254 // it's arguments with arbitrary offsets. If we can prove there are no
1255 // writes to this memory in the loop, we can hoist or sink.
1256 if (AAResults::onlyAccessesArgPointees(Behavior)) {
1257 // TODO: expand to writeable arguments
1258 for (Value *Op : CI->arg_operands())
1259 if (Op->getType()->isPointerTy()) {
1260 bool Invalidated;
1261 if (CurAST)
1262 Invalidated = pointerInvalidatedByLoop(
1263 MemoryLocation::getBeforeOrAfter(Op), CurAST, CurLoop, AA);
1264 else
1265 Invalidated = pointerInvalidatedByLoopWithMSSA(
1266 MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(CI)), CurLoop, I,
1267 *Flags);
1268 if (Invalidated)
1269 return false;
1270 }
1271 return true;
1272 }
1273
1274 // If this call only reads from memory and there are no writes to memory
1275 // in the loop, we can hoist or sink the call as appropriate.
1276 if (isReadOnly(CurAST, MSSAU, CurLoop))
1277 return true;
1278 }
1279
1280 // FIXME: This should use mod/ref information to see if we can hoist or
1281 // sink the call.
1282
1283 return false;
1284 } else if (auto *FI = dyn_cast<FenceInst>(&I)) {
1285 // Fences alias (most) everything to provide ordering. For the moment,
1286 // just give up if there are any other memory operations in the loop.
1287 if (CurAST) {
1288 auto Begin = CurAST->begin();
1289 assert(Begin != CurAST->end() && "must contain FI")(static_cast <bool> (Begin != CurAST->end() &&
"must contain FI") ? void (0) : __assert_fail ("Begin != CurAST->end() && \"must contain FI\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1289, __extension__ __PRETTY_FUNCTION__))
;
1290 if (std::next(Begin) != CurAST->end())
1291 // constant memory for instance, TODO: handle better
1292 return false;
1293 auto *UniqueI = Begin->getUniqueInstruction();
1294 if (!UniqueI)
1295 // other memory op, give up
1296 return false;
1297 (void)FI; // suppress unused variable warning
1298 assert(UniqueI == FI && "AS must contain FI")(static_cast <bool> (UniqueI == FI && "AS must contain FI"
) ? void (0) : __assert_fail ("UniqueI == FI && \"AS must contain FI\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1298, __extension__ __PRETTY_FUNCTION__))
;
1299 return true;
1300 } else // MSSAU
1301 return isOnlyMemoryAccess(FI, CurLoop, MSSAU);
1302 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
1303 if (!SI->isUnordered())
1304 return false; // Don't sink/hoist volatile or ordered atomic store!
1305
1306 // We can only hoist a store that we can prove writes a value which is not
1307 // read or overwritten within the loop. For those cases, we fallback to
1308 // load store promotion instead. TODO: We can extend this to cases where
1309 // there is exactly one write to the location and that write dominates an
1310 // arbitrary number of reads in the loop.
1311 if (CurAST) {
1312 auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI));
1313
1314 if (AS.isRef() || !AS.isMustAlias())
1315 // Quick exit test, handled by the full path below as well.
1316 return false;
1317 auto *UniqueI = AS.getUniqueInstruction();
1318 if (!UniqueI)
1319 // other memory op, give up
1320 return false;
1321 assert(UniqueI == SI && "AS must contain SI")(static_cast <bool> (UniqueI == SI && "AS must contain SI"
) ? void (0) : __assert_fail ("UniqueI == SI && \"AS must contain SI\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1321, __extension__ __PRETTY_FUNCTION__))
;
1322 return true;
1323 } else { // MSSAU
1324 if (isOnlyMemoryAccess(SI, CurLoop, MSSAU))
1325 return true;
1326 // If there are more accesses than the Promotion cap or no "quota" to
1327 // check clobber, then give up as we're not walking a list that long.
1328 if (Flags->tooManyMemoryAccesses() || Flags->tooManyClobberingCalls())
1329 return false;
1330 // If there are interfering Uses (i.e. their defining access is in the
1331 // loop), or ordered loads (stored as Defs!), don't move this store.
1332 // Could do better here, but this is conservatively correct.
1333 // TODO: Cache set of Uses on the first walk in runOnLoop, update when
1334 // moving accesses. Can also extend to dominating uses.
1335 auto *SIMD = MSSA->getMemoryAccess(SI);
1336 for (auto *BB : CurLoop->getBlocks())
1337 if (auto *Accesses = MSSA->getBlockAccesses(BB)) {
1338 for (const auto &MA : *Accesses)
1339 if (const auto *MU = dyn_cast<MemoryUse>(&MA)) {
1340 auto *MD = MU->getDefiningAccess();
1341 if (!MSSA->isLiveOnEntryDef(MD) &&
1342 CurLoop->contains(MD->getBlock()))
1343 return false;
1344 // Disable hoisting past potentially interfering loads. Optimized
1345 // Uses may point to an access outside the loop, as getClobbering
1346 // checks the previous iteration when walking the backedge.
1347 // FIXME: More precise: no Uses that alias SI.
1348 if (!Flags->getIsSink() && !MSSA->dominates(SIMD, MU))
1349 return false;
1350 } else if (const auto *MD = dyn_cast<MemoryDef>(&MA)) {
1351 if (auto *LI = dyn_cast<LoadInst>(MD->getMemoryInst())) {
1352 (void)LI; // Silence warning.
1353 assert(!LI->isUnordered() && "Expected unordered load")(static_cast <bool> (!LI->isUnordered() && "Expected unordered load"
) ? void (0) : __assert_fail ("!LI->isUnordered() && \"Expected unordered load\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1353, __extension__ __PRETTY_FUNCTION__))
;
1354 return false;
1355 }
1356 // Any call, while it may not be clobbering SI, it may be a use.
1357 if (auto *CI = dyn_cast<CallInst>(MD->getMemoryInst())) {
1358 // Check if the call may read from the memory location written
1359 // to by SI. Check CI's attributes and arguments; the number of
1360 // such checks performed is limited above by NoOfMemAccTooLarge.
1361 ModRefInfo MRI = AA->getModRefInfo(CI, MemoryLocation::get(SI));
1362 if (isModOrRefSet(MRI))
1363 return false;
1364 }
1365 }
1366 }
1367 auto *Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(SI);
1368 Flags->incrementClobberingCalls();
1369 // If there are no clobbering Defs in the loop, store is safe to hoist.
1370 return MSSA->isLiveOnEntryDef(Source) ||
1371 !CurLoop->contains(Source->getBlock());
1372 }
1373 }
1374
1375 assert(!I.mayReadOrWriteMemory() && "unhandled aliasing")(static_cast <bool> (!I.mayReadOrWriteMemory() &&
"unhandled aliasing") ? void (0) : __assert_fail ("!I.mayReadOrWriteMemory() && \"unhandled aliasing\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1375, __extension__ __PRETTY_FUNCTION__))
;
1376
1377 // We've established mechanical ability and aliasing, it's up to the caller
1378 // to check fault safety
1379 return true;
1380}
1381
1382/// Returns true if a PHINode is a trivially replaceable with an
1383/// Instruction.
1384/// This is true when all incoming values are that instruction.
1385/// This pattern occurs most often with LCSSA PHI nodes.
1386///
1387static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
1388 for (const Value *IncValue : PN.incoming_values())
1389 if (IncValue != &I)
1390 return false;
1391
1392 return true;
1393}
1394
1395/// Return true if the instruction is free in the loop.
1396static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
1397 const TargetTransformInfo *TTI) {
1398
1399 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1400 if (TTI->getUserCost(GEP, TargetTransformInfo::TCK_SizeAndLatency) !=
1401 TargetTransformInfo::TCC_Free)
1402 return false;
1403 // For a GEP, we cannot simply use getUserCost because currently it
1404 // optimistically assume that a GEP will fold into addressing mode
1405 // regardless of its users.
1406 const BasicBlock *BB = GEP->getParent();
1407 for (const User *U : GEP->users()) {
1408 const Instruction *UI = cast<Instruction>(U);
1409 if (CurLoop->contains(UI) &&
1410 (BB != UI->getParent() ||
1411 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
1412 return false;
1413 }
1414 return true;
1415 } else
1416 return TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
1417 TargetTransformInfo::TCC_Free;
1418}
1419
1420/// Return true if the only users of this instruction are outside of
1421/// the loop. If this is true, we can sink the instruction to the exit
1422/// blocks of the loop.
1423///
1424/// We also return true if the instruction could be folded away in lowering.
1425/// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
1426static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
1427 const LoopSafetyInfo *SafetyInfo,
1428 TargetTransformInfo *TTI, bool &FreeInLoop) {
1429 const auto &BlockColors = SafetyInfo->getBlockColors();
1430 bool IsFree = isFreeInLoop(I, CurLoop, TTI);
1431 for (const User *U : I.users()) {
1432 const Instruction *UI = cast<Instruction>(U);
1433 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
1434 const BasicBlock *BB = PN->getParent();
1435 // We cannot sink uses in catchswitches.
1436 if (isa<CatchSwitchInst>(BB->getTerminator()))
1437 return false;
1438
1439 // We need to sink a callsite to a unique funclet. Avoid sinking if the
1440 // phi use is too muddled.
1441 if (isa<CallInst>(I))
1442 if (!BlockColors.empty() &&
1443 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
1444 return false;
1445 }
1446
1447 if (CurLoop->contains(UI)) {
1448 if (IsFree) {
1449 FreeInLoop = true;
1450 continue;
1451 }
1452 return false;
1453 }
1454 }
1455 return true;
1456}
1457
1458static Instruction *cloneInstructionInExitBlock(
1459 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
1460 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU) {
1461 Instruction *New;
1462 if (auto *CI = dyn_cast<CallInst>(&I)) {
1463 const auto &BlockColors = SafetyInfo->getBlockColors();
1464
1465 // Sinking call-sites need to be handled differently from other
1466 // instructions. The cloned call-site needs a funclet bundle operand
1467 // appropriate for its location in the CFG.
1468 SmallVector<OperandBundleDef, 1> OpBundles;
1469 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
1470 BundleIdx != BundleEnd; ++BundleIdx) {
1471 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
1472 if (Bundle.getTagID() == LLVMContext::OB_funclet)
1473 continue;
1474
1475 OpBundles.emplace_back(Bundle);
1476 }
1477
1478 if (!BlockColors.empty()) {
1479 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
1480 assert(CV.size() == 1 && "non-unique color for exit block!")(static_cast <bool> (CV.size() == 1 && "non-unique color for exit block!"
) ? void (0) : __assert_fail ("CV.size() == 1 && \"non-unique color for exit block!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1480, __extension__ __PRETTY_FUNCTION__))
;
1481 BasicBlock *BBColor = CV.front();
1482 Instruction *EHPad = BBColor->getFirstNonPHI();
1483 if (EHPad->isEHPad())
1484 OpBundles.emplace_back("funclet", EHPad);
1485 }
1486
1487 New = CallInst::Create(CI, OpBundles);
1488 } else {
1489 New = I.clone();
1490 }
1491
1492 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
1493 if (!I.getName().empty())
1494 New->setName(I.getName() + ".le");
1495
1496 if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
1497 // Create a new MemoryAccess and let MemorySSA set its defining access.
1498 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1499 New, nullptr, New->getParent(), MemorySSA::Beginning);
1500 if (NewMemAcc) {
1501 if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
1502 MSSAU->insertDef(MemDef, /*RenameUses=*/true);
1503 else {
1504 auto *MemUse = cast<MemoryUse>(NewMemAcc);
1505 MSSAU->insertUse(MemUse, /*RenameUses=*/true);
1506 }
1507 }
1508 }
1509
1510 // Build LCSSA PHI nodes for any in-loop operands (if legal). Note that
1511 // this is particularly cheap because we can rip off the PHI node that we're
1512 // replacing for the number and blocks of the predecessors.
1513 // OPT: If this shows up in a profile, we can instead finish sinking all
1514 // invariant instructions, and then walk their operands to re-establish
1515 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
1516 // sinking bottom-up.
1517 for (Use &Op : New->operands())
1518 if (LI->wouldBeOutOfLoopUseRequiringLCSSA(Op.get(), PN.getParent())) {
1519 auto *OInst = cast<Instruction>(Op.get());
1520 PHINode *OpPN =
1521 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
1522 OInst->getName() + ".lcssa", &ExitBlock.front());
1523 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1524 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
1525 Op = OpPN;
1526 }
1527 return New;
1528}
1529
1530static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
1531 AliasSetTracker *AST, MemorySSAUpdater *MSSAU) {
1532 if (AST)
1533 AST->deleteValue(&I);
1534 if (MSSAU)
1535 MSSAU->removeMemoryAccess(&I);
1536 SafetyInfo.removeInstruction(&I);
1537 I.eraseFromParent();
1538}
1539
1540static void moveInstructionBefore(Instruction &I, Instruction &Dest,
1541 ICFLoopSafetyInfo &SafetyInfo,
1542 MemorySSAUpdater *MSSAU,
1543 ScalarEvolution *SE) {
1544 SafetyInfo.removeInstruction(&I);
1545 SafetyInfo.insertInstructionTo(&I, Dest.getParent());
1546 I.moveBefore(&Dest);
1547 if (MSSAU)
1548 if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>(
1549 MSSAU->getMemorySSA()->getMemoryAccess(&I)))
1550 MSSAU->moveToPlace(OldMemAcc, Dest.getParent(),
1551 MemorySSA::BeforeTerminator);
1552 if (SE)
1553 SE->forgetValue(&I);
1554}
1555
1556static Instruction *sinkThroughTriviallyReplaceablePHI(
1557 PHINode *TPN, Instruction *I, LoopInfo *LI,
1558 SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
1559 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop,
1560 MemorySSAUpdater *MSSAU) {
1561 assert(isTriviallyReplaceablePHI(*TPN, *I) &&(static_cast <bool> (isTriviallyReplaceablePHI(*TPN, *I
) && "Expect only trivially replaceable PHI") ? void (
0) : __assert_fail ("isTriviallyReplaceablePHI(*TPN, *I) && \"Expect only trivially replaceable PHI\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1562, __extension__ __PRETTY_FUNCTION__))
1562 "Expect only trivially replaceable PHI")(static_cast <bool> (isTriviallyReplaceablePHI(*TPN, *I
) && "Expect only trivially replaceable PHI") ? void (
0) : __assert_fail ("isTriviallyReplaceablePHI(*TPN, *I) && \"Expect only trivially replaceable PHI\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1562, __extension__ __PRETTY_FUNCTION__))
;
1563 BasicBlock *ExitBlock = TPN->getParent();
1564 Instruction *New;
1565 auto It = SunkCopies.find(ExitBlock);
1566 if (It != SunkCopies.end())
1567 New = It->second;
1568 else
1569 New = SunkCopies[ExitBlock] = cloneInstructionInExitBlock(
1570 *I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU);
1571 return New;
1572}
1573
1574static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
1575 BasicBlock *BB = PN->getParent();
1576 if (!BB->canSplitPredecessors())
1577 return false;
1578 // It's not impossible to split EHPad blocks, but if BlockColors already exist
1579 // it require updating BlockColors for all offspring blocks accordingly. By
1580 // skipping such corner case, we can make updating BlockColors after splitting
1581 // predecessor fairly simple.
1582 if (!SafetyInfo->getBlockColors().empty() && BB->getFirstNonPHI()->isEHPad())
1583 return false;
1584 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1585 BasicBlock *BBPred = *PI;
1586 if (isa<IndirectBrInst>(BBPred->getTerminator()) ||
1587 isa<CallBrInst>(BBPred->getTerminator()))
1588 return false;
1589 }
1590 return true;
1591}
1592
1593static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
1594 LoopInfo *LI, const Loop *CurLoop,
1595 LoopSafetyInfo *SafetyInfo,
1596 MemorySSAUpdater *MSSAU) {
1597#ifndef NDEBUG
1598 SmallVector<BasicBlock *, 32> ExitBlocks;
1599 CurLoop->getUniqueExitBlocks(ExitBlocks);
1600 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
1601 ExitBlocks.end());
1602#endif
1603 BasicBlock *ExitBB = PN->getParent();
1604 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.")(static_cast <bool> (ExitBlockSet.count(ExitBB) &&
"Expect the PHI is in an exit block.") ? void (0) : __assert_fail
("ExitBlockSet.count(ExitBB) && \"Expect the PHI is in an exit block.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1604, __extension__ __PRETTY_FUNCTION__))
;
1605
1606 // Split predecessors of the loop exit to make instructions in the loop are
1607 // exposed to exit blocks through trivially replaceable PHIs while keeping the
1608 // loop in the canonical form where each predecessor of each exit block should
1609 // be contained within the loop. For example, this will convert the loop below
1610 // from
1611 //
1612 // LB1:
1613 // %v1 =
1614 // br %LE, %LB2
1615 // LB2:
1616 // %v2 =
1617 // br %LE, %LB1
1618 // LE:
1619 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
1620 //
1621 // to
1622 //
1623 // LB1:
1624 // %v1 =
1625 // br %LE.split, %LB2
1626 // LB2:
1627 // %v2 =
1628 // br %LE.split2, %LB1
1629 // LE.split:
1630 // %p1 = phi [%v1, %LB1] <-- trivially replaceable
1631 // br %LE
1632 // LE.split2:
1633 // %p2 = phi [%v2, %LB2] <-- trivially replaceable
1634 // br %LE
1635 // LE:
1636 // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
1637 //
1638 const auto &BlockColors = SafetyInfo->getBlockColors();
1639 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
1640 while (!PredBBs.empty()) {
1641 BasicBlock *PredBB = *PredBBs.begin();
1642 assert(CurLoop->contains(PredBB) &&(static_cast <bool> (CurLoop->contains(PredBB) &&
"Expect all predecessors are in the loop") ? void (0) : __assert_fail
("CurLoop->contains(PredBB) && \"Expect all predecessors are in the loop\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1643, __extension__ __PRETTY_FUNCTION__))
1643 "Expect all predecessors are in the loop")(static_cast <bool> (CurLoop->contains(PredBB) &&
"Expect all predecessors are in the loop") ? void (0) : __assert_fail
("CurLoop->contains(PredBB) && \"Expect all predecessors are in the loop\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1643, __extension__ __PRETTY_FUNCTION__))
;
1644 if (PN->getBasicBlockIndex(PredBB) >= 0) {
1645 BasicBlock *NewPred = SplitBlockPredecessors(
1646 ExitBB, PredBB, ".split.loop.exit", DT, LI, MSSAU, true);
1647 // Since we do not allow splitting EH-block with BlockColors in
1648 // canSplitPredecessors(), we can simply assign predecessor's color to
1649 // the new block.
1650 if (!BlockColors.empty())
1651 // Grab a reference to the ColorVector to be inserted before getting the
1652 // reference to the vector we are copying because inserting the new
1653 // element in BlockColors might cause the map to be reallocated.
1654 SafetyInfo->copyColors(NewPred, PredBB);
1655 }
1656 PredBBs.remove(PredBB);
1657 }
1658}
1659
1660/// When an instruction is found to only be used outside of the loop, this
1661/// function moves it to the exit blocks and patches up SSA form as needed.
1662/// This method is guaranteed to remove the original instruction from its
1663/// position, and may either delete it or move it to outside of the loop.
1664///
1665static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
1666 BlockFrequencyInfo *BFI, const Loop *CurLoop,
1667 ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU,
1668 OptimizationRemarkEmitter *ORE) {
1669 bool Changed = false;
1670 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM sinking instruction: " <<
I << "\n"; } } while (false)
;
1671
1672 // Iterate over users to be ready for actual sinking. Replace users via
1673 // unreachable blocks with undef and make all user PHIs trivially replaceable.
1674 SmallPtrSet<Instruction *, 8> VisitedUsers;
1675 for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
1676 auto *User = cast<Instruction>(*UI);
1677 Use &U = UI.getUse();
1678 ++UI;
1679
1680 if (VisitedUsers.count(User) || CurLoop->contains(User))
1681 continue;
1682
1683 if (!DT->isReachableFromEntry(User->getParent())) {
1684 U = UndefValue::get(I.getType());
1685 Changed = true;
1686 continue;
1687 }
1688
1689 // The user must be a PHI node.
1690 PHINode *PN = cast<PHINode>(User);
1691
1692 // Surprisingly, instructions can be used outside of loops without any
1693 // exits. This can only happen in PHI nodes if the incoming block is
1694 // unreachable.
1695 BasicBlock *BB = PN->getIncomingBlock(U);
1696 if (!DT->isReachableFromEntry(BB)) {
1697 U = UndefValue::get(I.getType());
1698 Changed = true;
1699 continue;
1700 }
1701
1702 VisitedUsers.insert(PN);
1703 if (isTriviallyReplaceablePHI(*PN, I))
1704 continue;
1705
1706 if (!canSplitPredecessors(PN, SafetyInfo))
1707 return Changed;
1708
1709 // Split predecessors of the PHI so that we can make users trivially
1710 // replaceable.
1711 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, MSSAU);
1712
1713 // Should rebuild the iterators, as they may be invalidated by
1714 // splitPredecessorsOfLoopExit().
1715 UI = I.user_begin();
1716 UE = I.user_end();
1717 }
1718
1719 if (VisitedUsers.empty())
1720 return Changed;
1721
1722 ORE->emit([&]() {
1723 return OptimizationRemark(DEBUG_TYPE"licm", "InstSunk", &I)
1724 << "sinking " << ore::NV("Inst", &I);
1725 });
1726 if (isa<LoadInst>(I))
1727 ++NumMovedLoads;
1728 else if (isa<CallInst>(I))
1729 ++NumMovedCalls;
1730 ++NumSunk;
1731
1732#ifndef NDEBUG
1733 SmallVector<BasicBlock *, 32> ExitBlocks;
1734 CurLoop->getUniqueExitBlocks(ExitBlocks);
1735 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
1736 ExitBlocks.end());
1737#endif
1738
1739 // Clones of this instruction. Don't create more than one per exit block!
1740 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
1741
1742 // If this instruction is only used outside of the loop, then all users are
1743 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1744 // the instruction.
1745 // First check if I is worth sinking for all uses. Sink only when it is worth
1746 // across all uses.
1747 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1748 SmallVector<PHINode *, 8> ExitPNs;
1749 for (auto *UI : Users) {
1750 auto *User = cast<Instruction>(UI);
1751
1752 if (CurLoop->contains(User))
1753 continue;
1754
1755 PHINode *PN = cast<PHINode>(User);
1756 assert(ExitBlockSet.count(PN->getParent()) &&(static_cast <bool> (ExitBlockSet.count(PN->getParent
()) && "The LCSSA PHI is not in an exit block!") ? void
(0) : __assert_fail ("ExitBlockSet.count(PN->getParent()) && \"The LCSSA PHI is not in an exit block!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1757, __extension__ __PRETTY_FUNCTION__))
1757 "The LCSSA PHI is not in an exit block!")(static_cast <bool> (ExitBlockSet.count(PN->getParent
()) && "The LCSSA PHI is not in an exit block!") ? void
(0) : __assert_fail ("ExitBlockSet.count(PN->getParent()) && \"The LCSSA PHI is not in an exit block!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 1757, __extension__ __PRETTY_FUNCTION__))
;
1758 if (!worthSinkOrHoistInst(I, PN->getParent(), ORE, BFI)) {
1759 return Changed;
1760 }
1761
1762 ExitPNs.push_back(PN);
1763 }
1764
1765 for (auto *PN : ExitPNs) {
1766
1767 // The PHI must be trivially replaceable.
1768 Instruction *New = sinkThroughTriviallyReplaceablePHI(
1769 PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU);
1770 PN->replaceAllUsesWith(New);
1771 eraseInstruction(*PN, *SafetyInfo, nullptr, nullptr);
1772 Changed = true;
1773 }
1774 return Changed;
1775}
1776
1777/// When an instruction is found to only use loop invariant operands that
1778/// is safe to hoist, this instruction is called to do the dirty work.
1779///
1780static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
1781 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
1782 MemorySSAUpdater *MSSAU, ScalarEvolution *SE,
1783 OptimizationRemarkEmitter *ORE) {
1784 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getNameOrAsOperand() << ": "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM hoisting to " << Dest
->getNameOrAsOperand() << ": " << I << "\n"
; } } while (false)
1785 << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM hoisting to " << Dest
->getNameOrAsOperand() << ": " << I << "\n"
; } } while (false)
;
1786 ORE->emit([&]() {
1787 return OptimizationRemark(DEBUG_TYPE"licm", "Hoisted", &I) << "hoisting "
1788 << ore::NV("Inst", &I);
1789 });
1790
1791 // Metadata can be dependent on conditions we are hoisting above.
1792 // Conservatively strip all metadata on the instruction unless we were
1793 // guaranteed to execute I if we entered the loop, in which case the metadata
1794 // is valid in the loop preheader.
1795 if (I.hasMetadataOtherThanDebugLoc() &&
1796 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1797 // time in isGuaranteedToExecute if we don't actually have anything to
1798 // drop. It is a compile time optimization, not required for correctness.
1799 !SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop))
1800 I.dropUnknownNonDebugMetadata();
1801
1802 if (isa<PHINode>(I))
1803 // Move the new node to the end of the phi list in the destination block.
1804 moveInstructionBefore(I, *Dest->getFirstNonPHI(), *SafetyInfo, MSSAU, SE);
1805 else
1806 // Move the new node to the destination block, before its terminator.
1807 moveInstructionBefore(I, *Dest->getTerminator(), *SafetyInfo, MSSAU, SE);
1808
1809 I.updateLocationAfterHoist();
1810
1811 if (isa<LoadInst>(I))
1812 ++NumMovedLoads;
1813 else if (isa<CallInst>(I))
1814 ++NumMovedCalls;
1815 ++NumHoisted;
1816}
1817
1818/// Only sink or hoist an instruction if it is not a trapping instruction,
1819/// or if the instruction is known not to trap when moved to the preheader.
1820/// or if it is a trapping instruction and is guaranteed to execute.
1821static bool isSafeToExecuteUnconditionally(Instruction &Inst,
1822 const DominatorTree *DT,
1823 const TargetLibraryInfo *TLI,
1824 const Loop *CurLoop,
1825 const LoopSafetyInfo *SafetyInfo,
1826 OptimizationRemarkEmitter *ORE,
1827 const Instruction *CtxI) {
1828 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI))
1829 return true;
1830
1831 bool GuaranteedToExecute =
1832 SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop);
1833
1834 if (!GuaranteedToExecute) {
1835 auto *LI = dyn_cast<LoadInst>(&Inst);
1836 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1837 ORE->emit([&]() {
1838 return OptimizationRemarkMissed(
1839 DEBUG_TYPE"licm", "LoadWithLoopInvariantAddressCondExecuted", LI)
1840 << "failed to hoist load with loop-invariant address "
1841 "because load is conditionally executed";
1842 });
1843 }
1844
1845 return GuaranteedToExecute;
1846}
1847
1848namespace {
1849class LoopPromoter : public LoadAndStorePromoter {
1850 Value *SomePtr; // Designated pointer to store to.
1851 const SmallSetVector<Value *, 8> &PointerMustAliases;
1852 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1853 SmallVectorImpl<Instruction *> &LoopInsertPts;
1854 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts;
1855 PredIteratorCache &PredCache;
1856 AliasSetTracker *AST;
1857 MemorySSAUpdater *MSSAU;
1858 LoopInfo &LI;
1859 DebugLoc DL;
1860 int Alignment;
1861 bool UnorderedAtomic;
1862 AAMDNodes AATags;
1863 ICFLoopSafetyInfo &SafetyInfo;
1864
1865 // We're about to add a use of V in a loop exit block. Insert an LCSSA phi
1866 // (if legal) if doing so would add an out-of-loop use to an instruction
1867 // defined in-loop.
1868 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1869 if (!LI.wouldBeOutOfLoopUseRequiringLCSSA(V, BB))
1870 return V;
1871
1872 Instruction *I = cast<Instruction>(V);
1873 // We need to create an LCSSA PHI node for the incoming value and
1874 // store that.
1875 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1876 I->getName() + ".lcssa", &BB->front());
1877 for (BasicBlock *Pred : PredCache.get(BB))
1878 PN->addIncoming(I, Pred);
1879 return PN;
1880 }
1881
1882public:
1883 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
1884 const SmallSetVector<Value *, 8> &PMA,
1885 SmallVectorImpl<BasicBlock *> &LEB,
1886 SmallVectorImpl<Instruction *> &LIP,
1887 SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC,
1888 AliasSetTracker *ast, MemorySSAUpdater *MSSAU, LoopInfo &li,
1889 DebugLoc dl, int alignment, bool UnorderedAtomic,
1890 const AAMDNodes &AATags, ICFLoopSafetyInfo &SafetyInfo)
1891 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1892 LoopExitBlocks(LEB), LoopInsertPts(LIP), MSSAInsertPts(MSSAIP),
1893 PredCache(PIC), AST(ast), MSSAU(MSSAU), LI(li), DL(std::move(dl)),
1894 Alignment(alignment), UnorderedAtomic(UnorderedAtomic), AATags(AATags),
1895 SafetyInfo(SafetyInfo) {}
1896
1897 bool isInstInList(Instruction *I,
1898 const SmallVectorImpl<Instruction *> &) const override {
1899 Value *Ptr;
1900 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1901 Ptr = LI->getOperand(0);
1902 else
1903 Ptr = cast<StoreInst>(I)->getPointerOperand();
1904 return PointerMustAliases.count(Ptr);
1905 }
1906
1907 void doExtraRewritesBeforeFinalDeletion() override {
1908 // Insert stores after in the loop exit blocks. Each exit block gets a
1909 // store of the live-out values that feed them. Since we've already told
1910 // the SSA updater about the defs in the loop and the preheader
1911 // definition, it is all set and we can start using it.
1912 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1913 BasicBlock *ExitBlock = LoopExitBlocks[i];
1914 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1915 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1916 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1917 Instruction *InsertPos = LoopInsertPts[i];
1918 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
1919 if (UnorderedAtomic)
1920 NewSI->setOrdering(AtomicOrdering::Unordered);
1921 NewSI->setAlignment(Align(Alignment));
1922 NewSI->setDebugLoc(DL);
1923 if (AATags)
1924 NewSI->setAAMetadata(AATags);
1925
1926 if (MSSAU) {
1927 MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i];
1928 MemoryAccess *NewMemAcc;
1929 if (!MSSAInsertPoint) {
1930 NewMemAcc = MSSAU->createMemoryAccessInBB(
1931 NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning);
1932 } else {
1933 NewMemAcc =
1934 MSSAU->createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint);
1935 }
1936 MSSAInsertPts[i] = NewMemAcc;
1937 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1938 // FIXME: true for safety, false may still be correct.
1939 }
1940 }
1941 }
1942
1943 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1944 // Update alias analysis.
1945 if (AST)
1946 AST->copyValue(LI, V);
1947 }
1948 void instructionDeleted(Instruction *I) const override {
1949 SafetyInfo.removeInstruction(I);
1950 if (AST)
1951 AST->deleteValue(I);
1952 if (MSSAU)
1953 MSSAU->removeMemoryAccess(I);
1954 }
1955};
1956
1957bool isNotCapturedBeforeOrInLoop(const Value *V, const Loop *L,
1958 DominatorTree *DT) {
1959 // We can perform the captured-before check against any instruction in the
1960 // loop header, as the loop header is reachable from any instruction inside
1961 // the loop.
1962 // TODO: ReturnCaptures=true shouldn't be necessary here.
1963 return !PointerMayBeCapturedBefore(V, /* ReturnCaptures */ true,
1964 /* StoreCaptures */ true,
1965 L->getHeader()->getTerminator(), DT);
1966}
1967
1968/// Return true iff we can prove that a caller of this function can not inspect
1969/// the contents of the provided object in a well defined program.
1970bool isKnownNonEscaping(Value *Object, const Loop *L,
1971 const TargetLibraryInfo *TLI, DominatorTree *DT) {
1972 if (isa<AllocaInst>(Object))
1973 // Since the alloca goes out of scope, we know the caller can't retain a
1974 // reference to it and be well defined. Thus, we don't need to check for
1975 // capture.
1976 return true;
1977
1978 // For all other objects we need to know that the caller can't possibly
1979 // have gotten a reference to the object. There are two components of
1980 // that:
1981 // 1) Object can't be escaped by this function. This is what
1982 // PointerMayBeCaptured checks.
1983 // 2) Object can't have been captured at definition site. For this, we
1984 // need to know the return value is noalias. At the moment, we use a
1985 // weaker condition and handle only AllocLikeFunctions (which are
1986 // known to be noalias). TODO
1987 return isAllocLikeFn(Object, TLI) &&
1988 isNotCapturedBeforeOrInLoop(Object, L, DT);
1989}
1990
1991} // namespace
1992
1993/// Try to promote memory values to scalars by sinking stores out of the
1994/// loop and moving loads to before the loop. We do this by looping over
1995/// the stores in the loop, looking for stores to Must pointers which are
1996/// loop invariant.
1997///
1998bool llvm::promoteLoopAccessesToScalars(
1999 const SmallSetVector<Value *, 8> &PointerMustAliases,
2000 SmallVectorImpl<BasicBlock *> &ExitBlocks,
2001 SmallVectorImpl<Instruction *> &InsertPts,
2002 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts, PredIteratorCache &PIC,
2003 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
2004 Loop *CurLoop, AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
2005 ICFLoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE) {
2006 // Verify inputs.
2007 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&(static_cast <bool> (LI != nullptr && DT != nullptr
&& CurLoop != nullptr && SafetyInfo != nullptr
&& "Unexpected Input to promoteLoopAccessesToScalars"
) ? void (0) : __assert_fail ("LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected Input to promoteLoopAccessesToScalars\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 2009, __extension__ __PRETTY_FUNCTION__))
2008 SafetyInfo != nullptr &&(static_cast <bool> (LI != nullptr && DT != nullptr
&& CurLoop != nullptr && SafetyInfo != nullptr
&& "Unexpected Input to promoteLoopAccessesToScalars"
) ? void (0) : __assert_fail ("LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected Input to promoteLoopAccessesToScalars\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 2009, __extension__ __PRETTY_FUNCTION__))
2009 "Unexpected Input to promoteLoopAccessesToScalars")(static_cast <bool> (LI != nullptr && DT != nullptr
&& CurLoop != nullptr && SafetyInfo != nullptr
&& "Unexpected Input to promoteLoopAccessesToScalars"
) ? void (0) : __assert_fail ("LI != nullptr && DT != nullptr && CurLoop != nullptr && SafetyInfo != nullptr && \"Unexpected Input to promoteLoopAccessesToScalars\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 2009, __extension__ __PRETTY_FUNCTION__))
;
2010
2011 Value *SomePtr = *PointerMustAliases.begin();
2012 BasicBlock *Preheader = CurLoop->getLoopPreheader();
2013
2014 // It is not safe to promote a load/store from the loop if the load/store is
2015 // conditional. For example, turning:
2016 //
2017 // for () { if (c) *P += 1; }
2018 //
2019 // into:
2020 //
2021 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
2022 //
2023 // is not safe, because *P may only be valid to access if 'c' is true.
2024 //
2025 // The safety property divides into two parts:
2026 // p1) The memory may not be dereferenceable on entry to the loop. In this
2027 // case, we can't insert the required load in the preheader.
2028 // p2) The memory model does not allow us to insert a store along any dynamic
2029 // path which did not originally have one.
2030 //
2031 // If at least one store is guaranteed to execute, both properties are
2032 // satisfied, and promotion is legal.
2033 //
2034 // This, however, is not a necessary condition. Even if no store/load is
2035 // guaranteed to execute, we can still establish these properties.
2036 // We can establish (p1) by proving that hoisting the load into the preheader
2037 // is safe (i.e. proving dereferenceability on all paths through the loop). We
2038 // can use any access within the alias set to prove dereferenceability,
2039 // since they're all must alias.
2040 //
2041 // There are two ways establish (p2):
2042 // a) Prove the location is thread-local. In this case the memory model
2043 // requirement does not apply, and stores are safe to insert.
2044 // b) Prove a store dominates every exit block. In this case, if an exit
2045 // blocks is reached, the original dynamic path would have taken us through
2046 // the store, so inserting a store into the exit block is safe. Note that this
2047 // is different from the store being guaranteed to execute. For instance,
2048 // if an exception is thrown on the first iteration of the loop, the original
2049 // store is never executed, but the exit blocks are not executed either.
2050
2051 bool DereferenceableInPH = false;
2052 bool SafeToInsertStore = false;
2053
2054 SmallVector<Instruction *, 64> LoopUses;
2055
2056 // We start with an alignment of one and try to find instructions that allow
2057 // us to prove better alignment.
2058 Align Alignment;
2059 // Keep track of which types of access we see
2060 bool SawUnorderedAtomic = false;
2061 bool SawNotAtomic = false;
2062 AAMDNodes AATags;
2063
2064 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
2065
2066 bool IsKnownThreadLocalObject = false;
2067 if (SafetyInfo->anyBlockMayThrow()) {
2068 // If a loop can throw, we have to insert a store along each unwind edge.
2069 // That said, we can't actually make the unwind edge explicit. Therefore,
2070 // we have to prove that the store is dead along the unwind edge. We do
2071 // this by proving that the caller can't have a reference to the object
2072 // after return and thus can't possibly load from the object.
2073 Value *Object = getUnderlyingObject(SomePtr);
2074 if (!isKnownNonEscaping(Object, CurLoop, TLI, DT))
2075 return false;
2076 // Subtlety: Alloca's aren't visible to callers, but *are* potentially
2077 // visible to other threads if captured and used during their lifetimes.
2078 IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
2079 }
2080
2081 // Check that all of the pointers in the alias set have the same type. We
2082 // cannot (yet) promote a memory location that is loaded and stored in
2083 // different sizes. While we are at it, collect alignment and AA info.
2084 for (Value *ASIV : PointerMustAliases) {
2085 // Check that all of the pointers in the alias set have the same type. We
2086 // cannot (yet) promote a memory location that is loaded and stored in
2087 // different sizes.
2088 if (SomePtr->getType() != ASIV->getType())
2089 return false;
2090
2091 for (User *U : ASIV->users()) {
2092 // Ignore instructions that are outside the loop.
2093 Instruction *UI = dyn_cast<Instruction>(U);
2094 if (!UI || !CurLoop->contains(UI))
2095 continue;
2096
2097 // If there is an non-load/store instruction in the loop, we can't promote
2098 // it.
2099 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
2100 if (!Load->isUnordered())
2101 return false;
2102
2103 SawUnorderedAtomic |= Load->isAtomic();
2104 SawNotAtomic |= !Load->isAtomic();
2105
2106 Align InstAlignment = Load->getAlign();
2107
2108 // Note that proving a load safe to speculate requires proving
2109 // sufficient alignment at the target location. Proving it guaranteed
2110 // to execute does as well. Thus we can increase our guaranteed
2111 // alignment as well.
2112 if (!DereferenceableInPH || (InstAlignment > Alignment))
2113 if (isSafeToExecuteUnconditionally(*Load, DT, TLI, CurLoop,
2114 SafetyInfo, ORE,
2115 Preheader->getTerminator())) {
2116 DereferenceableInPH = true;
2117 Alignment = std::max(Alignment, InstAlignment);
2118 }
2119 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
2120 // Stores *of* the pointer are not interesting, only stores *to* the
2121 // pointer.
2122 if (UI->getOperand(1) != ASIV)
2123 continue;
2124 if (!Store->isUnordered())
2125 return false;
2126
2127 SawUnorderedAtomic |= Store->isAtomic();
2128 SawNotAtomic |= !Store->isAtomic();
2129
2130 // If the store is guaranteed to execute, both properties are satisfied.
2131 // We may want to check if a store is guaranteed to execute even if we
2132 // already know that promotion is safe, since it may have higher
2133 // alignment than any other guaranteed stores, in which case we can
2134 // raise the alignment on the promoted store.
2135 Align InstAlignment = Store->getAlign();
2136
2137 if (!DereferenceableInPH || !SafeToInsertStore ||
2138 (InstAlignment > Alignment)) {
2139 if (SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop)) {
2140 DereferenceableInPH = true;
2141 SafeToInsertStore = true;
2142 Alignment = std::max(Alignment, InstAlignment);
2143 }
2144 }
2145
2146 // If a store dominates all exit blocks, it is safe to sink.
2147 // As explained above, if an exit block was executed, a dominating
2148 // store must have been executed at least once, so we are not
2149 // introducing stores on paths that did not have them.
2150 // Note that this only looks at explicit exit blocks. If we ever
2151 // start sinking stores into unwind edges (see above), this will break.
2152 if (!SafeToInsertStore)
2153 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
2154 return DT->dominates(Store->getParent(), Exit);
2155 });
2156
2157 // If the store is not guaranteed to execute, we may still get
2158 // deref info through it.
2159 if (!DereferenceableInPH) {
2160 DereferenceableInPH = isDereferenceableAndAlignedPointer(
2161 Store->getPointerOperand(), Store->getValueOperand()->getType(),
2162 Store->getAlign(), MDL, Preheader->getTerminator(), DT, TLI);
2163 }
2164 } else
2165 return false; // Not a load or store.
2166
2167 // Merge the AA tags.
2168 if (LoopUses.empty()) {
2169 // On the first load/store, just take its AA tags.
2170 UI->getAAMetadata(AATags);
2171 } else if (AATags) {
2172 UI->getAAMetadata(AATags, /* Merge = */ true);
2173 }
2174
2175 LoopUses.push_back(UI);
2176 }
2177 }
2178
2179 // If we found both an unordered atomic instruction and a non-atomic memory
2180 // access, bail. We can't blindly promote non-atomic to atomic since we
2181 // might not be able to lower the result. We can't downgrade since that
2182 // would violate memory model. Also, align 0 is an error for atomics.
2183 if (SawUnorderedAtomic && SawNotAtomic)
2184 return false;
2185
2186 // If we're inserting an atomic load in the preheader, we must be able to
2187 // lower it. We're only guaranteed to be able to lower naturally aligned
2188 // atomics.
2189 auto *SomePtrElemType = SomePtr->getType()->getPointerElementType();
2190 if (SawUnorderedAtomic &&
2191 Alignment < MDL.getTypeStoreSize(SomePtrElemType))
2192 return false;
2193
2194 // If we couldn't prove we can hoist the load, bail.
2195 if (!DereferenceableInPH)
2196 return false;
2197
2198 // We know we can hoist the load, but don't have a guaranteed store.
2199 // Check whether the location is thread-local. If it is, then we can insert
2200 // stores along paths which originally didn't have them without violating the
2201 // memory model.
2202 if (!SafeToInsertStore) {
2203 if (IsKnownThreadLocalObject)
2204 SafeToInsertStore = true;
2205 else {
2206 Value *Object = getUnderlyingObject(SomePtr);
2207 SafeToInsertStore =
2208 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
2209 isNotCapturedBeforeOrInLoop(Object, CurLoop, DT);
2210 }
2211 }
2212
2213 // If we've still failed to prove we can sink the store, give up.
2214 if (!SafeToInsertStore)
2215 return false;
2216
2217 // Otherwise, this is safe to promote, lets do it!
2218 LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtrdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM: Promoting value stored to in loop: "
<< *SomePtr << '\n'; } } while (false)
2219 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "LICM: Promoting value stored to in loop: "
<< *SomePtr << '\n'; } } while (false)
;
2220 ORE->emit([&]() {
2221 return OptimizationRemark(DEBUG_TYPE"licm", "PromoteLoopAccessesToScalar",
2222 LoopUses[0])
2223 << "Moving accesses to memory location out of the loop";
2224 });
2225 ++NumPromoted;
2226
2227 // Look at all the loop uses, and try to merge their locations.
2228 std::vector<const DILocation *> LoopUsesLocs;
2229 for (auto U : LoopUses)
2230 LoopUsesLocs.push_back(U->getDebugLoc().get());
2231 auto DL = DebugLoc(DILocation::getMergedLocations(LoopUsesLocs));
2232
2233 // We use the SSAUpdater interface to insert phi nodes as required.
2234 SmallVector<PHINode *, 16> NewPHIs;
2235 SSAUpdater SSA(&NewPHIs);
2236 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
2237 InsertPts, MSSAInsertPts, PIC, CurAST, MSSAU, *LI, DL,
2238 Alignment.value(), SawUnorderedAtomic, AATags,
2239 *SafetyInfo);
2240
2241 // Set up the preheader to have a definition of the value. It is the live-out
2242 // value from the preheader that uses in the loop will use.
2243 LoadInst *PreheaderLoad = new LoadInst(
2244 SomePtr->getType()->getPointerElementType(), SomePtr,
2245 SomePtr->getName() + ".promoted", Preheader->getTerminator());
2246 if (SawUnorderedAtomic)
2247 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
2248 PreheaderLoad->setAlignment(Alignment);
2249 PreheaderLoad->setDebugLoc(DebugLoc());
2250 if (AATags)
2251 PreheaderLoad->setAAMetadata(AATags);
2252 SSA.AddAvailableValue(Preheader, PreheaderLoad);
2253
2254 if (MSSAU) {
2255 MemoryAccess *PreheaderLoadMemoryAccess = MSSAU->createMemoryAccessInBB(
2256 PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End);
2257 MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess);
2258 MSSAU->insertUse(NewMemUse, /*RenameUses=*/true);
2259 }
2260
2261 if (MSSAU && VerifyMemorySSA)
2262 MSSAU->getMemorySSA()->verifyMemorySSA();
2263 // Rewrite all the loads in the loop and remember all the definitions from
2264 // stores in the loop.
2265 Promoter.run(LoopUses);
2266
2267 if (MSSAU && VerifyMemorySSA)
2268 MSSAU->getMemorySSA()->verifyMemorySSA();
2269 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
2270 if (PreheaderLoad->use_empty())
2271 eraseInstruction(*PreheaderLoad, *SafetyInfo, CurAST, MSSAU);
2272
2273 return true;
2274}
2275
2276static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,
2277 function_ref<void(Instruction *)> Fn) {
2278 for (const BasicBlock *BB : L->blocks())
2279 if (const auto *Accesses = MSSA->getBlockAccesses(BB))
2280 for (const auto &Access : *Accesses)
2281 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(&Access))
2282 Fn(MUD->getMemoryInst());
2283}
2284
2285static SmallVector<SmallSetVector<Value *, 8>, 0>
2286collectPromotionCandidates(MemorySSA *MSSA, AliasAnalysis *AA, Loop *L,
2287 SmallVectorImpl<Instruction *> &MaybePromotable) {
2288 AliasSetTracker AST(*AA);
2289
2290 auto IsPotentiallyPromotable = [L](const Instruction *I) {
2291 if (const auto *SI = dyn_cast<StoreInst>(I))
2292 return L->isLoopInvariant(SI->getPointerOperand());
2293 if (const auto *LI = dyn_cast<LoadInst>(I))
2294 return L->isLoopInvariant(LI->getPointerOperand());
2295 return false;
2296 };
2297
2298 // Populate AST with potentially promotable accesses and remove them from
2299 // MaybePromotable, so they will not be checked again on the next iteration.
2300 SmallPtrSet<Value *, 16> AttemptingPromotion;
2301 llvm::erase_if(MaybePromotable, [&](Instruction *I) {
2302 if (IsPotentiallyPromotable(I)) {
2303 AttemptingPromotion.insert(I);
2304 AST.add(I);
2305 return true;
2306 }
2307 return false;
2308 });
2309
2310 // We're only interested in must-alias sets that contain a mod.
2311 SmallVector<const AliasSet *, 8> Sets;
2312 for (AliasSet &AS : AST)
2313 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias())
2314 Sets.push_back(&AS);
2315
2316 if (Sets.empty())
2317 return {}; // Nothing to promote...
2318
2319 // Discard any sets for which there is an aliasing non-promotable access.
2320 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
2321 if (AttemptingPromotion.contains(I))
2322 return;
2323
2324 llvm::erase_if(Sets, [&](const AliasSet *AS) {
2325 return AS->aliasesUnknownInst(I, *AA);
2326 });
2327 });
2328
2329 SmallVector<SmallSetVector<Value *, 8>, 0> Result;
2330 for (const AliasSet *Set : Sets) {
2331 SmallSetVector<Value *, 8> PointerMustAliases;
2332 for (const auto &ASI : *Set)
2333 PointerMustAliases.insert(ASI.getValue());
2334 Result.push_back(std::move(PointerMustAliases));
2335 }
2336
2337 return Result;
2338}
2339
2340/// Returns an owning pointer to an alias set which incorporates aliasing info
2341/// from L and all subloops of L.
2342std::unique_ptr<AliasSetTracker>
2343LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
2344 AAResults *AA) {
2345 auto CurAST = std::make_unique<AliasSetTracker>(*AA);
2346
2347 // Add everything from all the sub loops.
2348 for (Loop *InnerL : L->getSubLoops())
2349 for (BasicBlock *BB : InnerL->blocks())
2350 CurAST->add(*BB);
2351
2352 // And merge in this loop (without anything from inner loops).
2353 for (BasicBlock *BB : L->blocks())
2354 if (LI->getLoopFor(BB) == L)
2355 CurAST->add(*BB);
2356
2357 return CurAST;
2358}
2359
2360static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
2361 AliasSetTracker *CurAST, Loop *CurLoop,
2362 AAResults *AA) {
2363 // First check to see if any of the basic blocks in CurLoop invalidate *V.
2364 bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod();
2365
2366 if (!isInvalidatedAccordingToAST || !LICMN2Theshold)
2367 return isInvalidatedAccordingToAST;
2368
2369 // Check with a diagnostic analysis if we can refine the information above.
2370 // This is to identify the limitations of using the AST.
2371 // The alias set mechanism used by LICM has a major weakness in that it
2372 // combines all things which may alias into a single set *before* asking
2373 // modref questions. As a result, a single readonly call within a loop will
2374 // collapse all loads and stores into a single alias set and report
2375 // invalidation if the loop contains any store. For example, readonly calls
2376 // with deopt states have this form and create a general alias set with all
2377 // loads and stores. In order to get any LICM in loops containing possible
2378 // deopt states we need a more precise invalidation of checking the mod ref
2379 // info of each instruction within the loop and LI. This has a complexity of
2380 // O(N^2), so currently, it is used only as a diagnostic tool since the
2381 // default value of LICMN2Threshold is zero.
2382
2383 // Don't look at nested loops.
2384 if (CurLoop->begin() != CurLoop->end())
2385 return true;
2386
2387 int N = 0;
2388 for (BasicBlock *BB : CurLoop->getBlocks())
2389 for (Instruction &I : *BB) {
2390 if (N >= LICMN2Theshold) {
2391 LLVM_DEBUG(dbgs() << "Alasing N2 threshold exhausted for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Alasing N2 threshold exhausted for "
<< *(MemLoc.Ptr) << "\n"; } } while (false)
2392 << *(MemLoc.Ptr) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Alasing N2 threshold exhausted for "
<< *(MemLoc.Ptr) << "\n"; } } while (false)
;
2393 return true;
2394 }
2395 N++;
2396 auto Res = AA->getModRefInfo(&I, MemLoc);
2397 if (isModSet(Res)) {
2398 LLVM_DEBUG(dbgs() << "Aliasing failed on " << I << " for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Aliasing failed on " << I <<
" for " << *(MemLoc.Ptr) << "\n"; } } while (false
)
2399 << *(MemLoc.Ptr) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Aliasing failed on " << I <<
" for " << *(MemLoc.Ptr) << "\n"; } } while (false
)
;
2400 return true;
2401 }
2402 }
2403 LLVM_DEBUG(dbgs() << "Aliasing okay for " << *(MemLoc.Ptr) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("licm")) { dbgs() << "Aliasing okay for " << *(MemLoc
.Ptr) << "\n"; } } while (false)
;
2404 return false;
2405}
2406
2407bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU,
2408 Loop *CurLoop, Instruction &I,
2409 SinkAndHoistLICMFlags &Flags) {
2410 // For hoisting, use the walker to determine safety
2411 if (!Flags.getIsSink()) {
2412 MemoryAccess *Source;
2413 // See declaration of SetLicmMssaOptCap for usage details.
2414 if (Flags.tooManyClobberingCalls())
2415 Source = MU->getDefiningAccess();
2416 else {
2417 Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(MU);
2418 Flags.incrementClobberingCalls();
2419 }
2420 return !MSSA->isLiveOnEntryDef(Source) &&
2421 CurLoop->contains(Source->getBlock());
2422 }
2423
2424 // For sinking, we'd need to check all Defs below this use. The getClobbering
2425 // call will look on the backedge of the loop, but will check aliasing with
2426 // the instructions on the previous iteration.
2427 // For example:
2428 // for (i ... )
2429 // load a[i] ( Use (LoE)
2430 // store a[i] ( 1 = Def (2), with 2 = Phi for the loop.
2431 // i++;
2432 // The load sees no clobbering inside the loop, as the backedge alias check
2433 // does phi translation, and will check aliasing against store a[i-1].
2434 // However sinking the load outside the loop, below the store is incorrect.
2435
2436 // For now, only sink if there are no Defs in the loop, and the existing ones
2437 // precede the use and are in the same block.
2438 // FIXME: Increase precision: Safe to sink if Use post dominates the Def;
2439 // needs PostDominatorTreeAnalysis.
2440 // FIXME: More precise: no Defs that alias this Use.
2441 if (Flags.tooManyMemoryAccesses())
2442 return true;
2443 for (auto *BB : CurLoop->getBlocks())
2444 if (pointerInvalidatedByBlockWithMSSA(*BB, *MSSA, *MU))
2445 return true;
2446 // When sinking, the source block may not be part of the loop so check it.
2447 if (!CurLoop->contains(&I))
2448 return pointerInvalidatedByBlockWithMSSA(*I.getParent(), *MSSA, *MU);
2449
2450 return false;
2451}
2452
2453bool pointerInvalidatedByBlockWithMSSA(BasicBlock &BB, MemorySSA &MSSA,
2454 MemoryUse &MU) {
2455 if (const auto *Accesses = MSSA.getBlockDefs(&BB))
2456 for (const auto &MA : *Accesses)
2457 if (const auto *MD = dyn_cast<MemoryDef>(&MA))
2458 if (MU.getBlock() != MD->getBlock() || !MSSA.locallyDominates(MD, &MU))
2459 return true;
2460 return false;
2461}
2462
2463/// Little predicate that returns true if the specified basic block is in
2464/// a subloop of the current one, not the current one itself.
2465///
2466static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
2467 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop")(static_cast <bool> (CurLoop->contains(BB) &&
"Only valid if BB is IN the loop") ? void (0) : __assert_fail
("CurLoop->contains(BB) && \"Only valid if BB is IN the loop\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Transforms/Scalar/LICM.cpp"
, 2467, __extension__ __PRETTY_FUNCTION__))
;
2468 return LI->getLoopFor(BB) != CurLoop;
2469}

/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/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/Bitfields.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/ADT/iterator.h"
26#include "llvm/ADT/iterator_range.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/CallingConv.h"
30#include "llvm/IR/CFG.h"
31#include "llvm/IR/Constant.h"
32#include "llvm/IR/DerivedTypes.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/InstrTypes.h"
35#include "llvm/IR/Instruction.h"
36#include "llvm/IR/OperandTraits.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/Use.h"
39#include "llvm/IR/User.h"
40#include "llvm/IR/Value.h"
41#include "llvm/Support/AtomicOrdering.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/ErrorHandling.h"
44#include <cassert>
45#include <cstddef>
46#include <cstdint>
47#include <iterator>
48
49namespace llvm {
50
51class APInt;
52class ConstantInt;
53class DataLayout;
54class LLVMContext;
55
56//===----------------------------------------------------------------------===//
57// AllocaInst Class
58//===----------------------------------------------------------------------===//
59
60/// an instruction to allocate memory on the stack
61class AllocaInst : public UnaryInstruction {
62 Type *AllocatedType;
63
64 using AlignmentField = AlignmentBitfieldElementT<0>;
65 using UsedWithInAllocaField = BoolBitfieldElementT<AlignmentField::NextBit>;
66 using SwiftErrorField = BoolBitfieldElementT<UsedWithInAllocaField::NextBit>;
67 static_assert(Bitfield::areContiguous<AlignmentField, UsedWithInAllocaField,
68 SwiftErrorField>(),
69 "Bitfields must be contiguous");
70
71protected:
72 // Note: Instruction needs to be a friend here to call cloneImpl.
73 friend class Instruction;
74
75 AllocaInst *cloneImpl() const;
76
77public:
78 explicit AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
79 const Twine &Name, Instruction *InsertBefore);
80 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
81 const Twine &Name, BasicBlock *InsertAtEnd);
82
83 AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
84 Instruction *InsertBefore);
85 AllocaInst(Type *Ty, unsigned AddrSpace,
86 const Twine &Name, BasicBlock *InsertAtEnd);
87
88 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align,
89 const Twine &Name = "", Instruction *InsertBefore = nullptr);
90 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align,
91 const Twine &Name, BasicBlock *InsertAtEnd);
92
93 /// Return true if there is an allocation size parameter to the allocation
94 /// instruction that is not 1.
95 bool isArrayAllocation() const;
96
97 /// Get the number of elements allocated. For a simple allocation of a single
98 /// element, this will return a constant 1 value.
99 const Value *getArraySize() const { return getOperand(0); }
100 Value *getArraySize() { return getOperand(0); }
101
102 /// Overload to return most specific pointer type.
103 PointerType *getType() const {
104 return cast<PointerType>(Instruction::getType());
105 }
106
107 /// Get allocation size in bits. Returns None if size can't be determined,
108 /// e.g. in case of a VLA.
109 Optional<TypeSize> getAllocationSizeInBits(const DataLayout &DL) const;
110
111 /// Return the type that is being allocated by the instruction.
112 Type *getAllocatedType() const { return AllocatedType; }
113 /// for use only in special circumstances that need to generically
114 /// transform a whole instruction (eg: IR linking and vectorization).
115 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
116
117 /// Return the alignment of the memory that is being allocated by the
118 /// instruction.
119 Align getAlign() const {
120 return Align(1ULL << getSubclassData<AlignmentField>());
121 }
122
123 void setAlignment(Align Align) {
124 setSubclassData<AlignmentField>(Log2(Align));
125 }
126
127 // FIXME: Remove this one transition to Align is over.
128 unsigned getAlignment() const { return getAlign().value(); }
129
130 /// Return true if this alloca is in the entry block of the function and is a
131 /// constant size. If so, the code generator will fold it into the
132 /// prolog/epilog code, so it is basically free.
133 bool isStaticAlloca() const;
134
135 /// Return true if this alloca is used as an inalloca argument to a call. Such
136 /// allocas are never considered static even if they are in the entry block.
137 bool isUsedWithInAlloca() const {
138 return getSubclassData<UsedWithInAllocaField>();
139 }
140
141 /// Specify whether this alloca is used to represent the arguments to a call.
142 void setUsedWithInAlloca(bool V) {
143 setSubclassData<UsedWithInAllocaField>(V);
144 }
145
146 /// Return true if this alloca is used as a swifterror argument to a call.
147 bool isSwiftError() const { return getSubclassData<SwiftErrorField>(); }
148 /// Specify whether this alloca is used to represent a swifterror.
149 void setSwiftError(bool V) { setSubclassData<SwiftErrorField>(V); }
150
151 // Methods for support type inquiry through isa, cast, and dyn_cast:
152 static bool classof(const Instruction *I) {
153 return (I->getOpcode() == Instruction::Alloca);
154 }
155 static bool classof(const Value *V) {
156 return isa<Instruction>(V) && classof(cast<Instruction>(V));
157 }
158
159private:
160 // Shadow Instruction::setInstructionSubclassData with a private forwarding
161 // method so that subclasses cannot accidentally use it.
162 template <typename Bitfield>
163 void setSubclassData(typename Bitfield::Type Value) {
164 Instruction::setSubclassData<Bitfield>(Value);
165 }
166};
167
168//===----------------------------------------------------------------------===//
169// LoadInst Class
170//===----------------------------------------------------------------------===//
171
172/// An instruction for reading from memory. This uses the SubclassData field in
173/// Value to store whether or not the load is volatile.
174class LoadInst : public UnaryInstruction {
175 using VolatileField = BoolBitfieldElementT<0>;
176 using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>;
177 using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>;
178 static_assert(
179 Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(),
180 "Bitfields must be contiguous");
181
182 void AssertOK();
183
184protected:
185 // Note: Instruction needs to be a friend here to call cloneImpl.
186 friend class Instruction;
187
188 LoadInst *cloneImpl() const;
189
190public:
191 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr,
192 Instruction *InsertBefore);
193 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
194 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
195 Instruction *InsertBefore);
196 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
197 BasicBlock *InsertAtEnd);
198 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
199 Align Align, Instruction *InsertBefore = nullptr);
200 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
201 Align Align, BasicBlock *InsertAtEnd);
202 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
203 Align Align, AtomicOrdering Order,
204 SyncScope::ID SSID = SyncScope::System,
205 Instruction *InsertBefore = nullptr);
206 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
207 Align Align, AtomicOrdering Order, SyncScope::ID SSID,
208 BasicBlock *InsertAtEnd);
209
210 /// Return true if this is a load from a volatile memory location.
211 bool isVolatile() const { return getSubclassData<VolatileField>(); }
212
213 /// Specify whether this is a volatile load or not.
214 void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
215
216 /// Return the alignment of the access that is being performed.
217 /// FIXME: Remove this function once transition to Align is over.
218 /// Use getAlign() instead.
219 unsigned getAlignment() const { return getAlign().value(); }
220
221 /// Return the alignment of the access that is being performed.
222 Align getAlign() const {
223 return Align(1ULL << (getSubclassData<AlignmentField>()));
224 }
225
226 void setAlignment(Align Align) {
227 setSubclassData<AlignmentField>(Log2(Align));
228 }
229
230 /// Returns the ordering constraint of this load instruction.
231 AtomicOrdering getOrdering() const {
232 return getSubclassData<OrderingField>();
233 }
234 /// Sets the ordering constraint of this load instruction. May not be Release
235 /// or AcquireRelease.
236 void setOrdering(AtomicOrdering Ordering) {
237 setSubclassData<OrderingField>(Ordering);
238 }
239
240 /// Returns the synchronization scope ID of this load instruction.
241 SyncScope::ID getSyncScopeID() const {
242 return SSID;
243 }
244
245 /// Sets the synchronization scope ID of this load instruction.
246 void setSyncScopeID(SyncScope::ID SSID) {
247 this->SSID = SSID;
248 }
249
250 /// Sets the ordering constraint and the synchronization scope ID of this load
251 /// instruction.
252 void setAtomic(AtomicOrdering Ordering,
253 SyncScope::ID SSID = SyncScope::System) {
254 setOrdering(Ordering);
255 setSyncScopeID(SSID);
256 }
257
258 bool isSimple() const { return !isAtomic() && !isVolatile(); }
259
260 bool isUnordered() const {
261 return (getOrdering() == AtomicOrdering::NotAtomic ||
16
Assuming the condition is true
18
Returning the value 1, which participates in a condition later
262 getOrdering() == AtomicOrdering::Unordered) &&
263 !isVolatile();
17
Assuming the condition is true
264 }
265
266 Value *getPointerOperand() { return getOperand(0); }
267 const Value *getPointerOperand() const { return getOperand(0); }
268 static unsigned getPointerOperandIndex() { return 0U; }
269 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
270
271 /// Returns the address space of the pointer operand.
272 unsigned getPointerAddressSpace() const {
273 return getPointerOperandType()->getPointerAddressSpace();
274 }
275
276 // Methods for support type inquiry through isa, cast, and dyn_cast:
277 static bool classof(const Instruction *I) {
278 return I->getOpcode() == Instruction::Load;
279 }
280 static bool classof(const Value *V) {
281 return isa<Instruction>(V) && classof(cast<Instruction>(V));
282 }
283
284private:
285 // Shadow Instruction::setInstructionSubclassData with a private forwarding
286 // method so that subclasses cannot accidentally use it.
287 template <typename Bitfield>
288 void setSubclassData(typename Bitfield::Type Value) {
289 Instruction::setSubclassData<Bitfield>(Value);
290 }
291
292 /// The synchronization scope ID of this load instruction. Not quite enough
293 /// room in SubClassData for everything, so synchronization scope ID gets its
294 /// own field.
295 SyncScope::ID SSID;
296};
297
298//===----------------------------------------------------------------------===//
299// StoreInst Class
300//===----------------------------------------------------------------------===//
301
302/// An instruction for storing to memory.
303class StoreInst : public Instruction {
304 using VolatileField = BoolBitfieldElementT<0>;
305 using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>;
306 using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>;
307 static_assert(
308 Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(),
309 "Bitfields must be contiguous");
310
311 void AssertOK();
312
313protected:
314 // Note: Instruction needs to be a friend here to call cloneImpl.
315 friend class Instruction;
316
317 StoreInst *cloneImpl() const;
318
319public:
320 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
321 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
322 StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore);
323 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
324 StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
325 Instruction *InsertBefore = nullptr);
326 StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
327 BasicBlock *InsertAtEnd);
328 StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
329 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
330 Instruction *InsertBefore = nullptr);
331 StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
332 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd);
333
334 // allocate space for exactly two operands
335 void *operator new(size_t s) {
336 return User::operator new(s, 2);
337 }
338
339 /// Return true if this is a store to a volatile memory location.
340 bool isVolatile() const { return getSubclassData<VolatileField>(); }
341
342 /// Specify whether this is a volatile store or not.
343 void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
344
345 /// Transparently provide more efficient getOperand methods.
346 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
;
347
348 /// Return the alignment of the access that is being performed
349 /// FIXME: Remove this function once transition to Align is over.
350 /// Use getAlign() instead.
351 unsigned getAlignment() const { return getAlign().value(); }
352
353 Align getAlign() const {
354 return Align(1ULL << (getSubclassData<AlignmentField>()));
355 }
356
357 void setAlignment(Align Align) {
358 setSubclassData<AlignmentField>(Log2(Align));
359 }
360
361 /// Returns the ordering constraint of this store instruction.
362 AtomicOrdering getOrdering() const {
363 return getSubclassData<OrderingField>();
364 }
365
366 /// Sets the ordering constraint of this store instruction. May not be
367 /// Acquire or AcquireRelease.
368 void setOrdering(AtomicOrdering Ordering) {
369 setSubclassData<OrderingField>(Ordering);
370 }
371
372 /// Returns the synchronization scope ID of this store instruction.
373 SyncScope::ID getSyncScopeID() const {
374 return SSID;
375 }
376
377 /// Sets the synchronization scope ID of this store instruction.
378 void setSyncScopeID(SyncScope::ID SSID) {
379 this->SSID = SSID;
380 }
381
382 /// Sets the ordering constraint and the synchronization scope ID of this
383 /// store instruction.
384 void setAtomic(AtomicOrdering Ordering,
385 SyncScope::ID SSID = SyncScope::System) {
386 setOrdering(Ordering);
387 setSyncScopeID(SSID);
388 }
389
390 bool isSimple() const { return !isAtomic() && !isVolatile(); }
391
392 bool isUnordered() const {
393 return (getOrdering() == AtomicOrdering::NotAtomic ||
394 getOrdering() == AtomicOrdering::Unordered) &&
395 !isVolatile();
396 }
397
398 Value *getValueOperand() { return getOperand(0); }
399 const Value *getValueOperand() const { return getOperand(0); }
400
401 Value *getPointerOperand() { return getOperand(1); }
402 const Value *getPointerOperand() const { return getOperand(1); }
403 static unsigned getPointerOperandIndex() { return 1U; }
404 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
405
406 /// Returns the address space of the pointer operand.
407 unsigned getPointerAddressSpace() const {
408 return getPointerOperandType()->getPointerAddressSpace();
409 }
410
411 // Methods for support type inquiry through isa, cast, and dyn_cast:
412 static bool classof(const Instruction *I) {
413 return I->getOpcode() == Instruction::Store;
414 }
415 static bool classof(const Value *V) {
416 return isa<Instruction>(V) && classof(cast<Instruction>(V));
417 }
418
419private:
420 // Shadow Instruction::setInstructionSubclassData with a private forwarding
421 // method so that subclasses cannot accidentally use it.
422 template <typename Bitfield>
423 void setSubclassData(typename Bitfield::Type Value) {
424 Instruction::setSubclassData<Bitfield>(Value);
425 }
426
427 /// The synchronization scope ID of this store instruction. Not quite enough
428 /// room in SubClassData for everything, so synchronization scope ID gets its
429 /// own field.
430 SyncScope::ID SSID;
431};
432
433template <>
434struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
435};
436
437DEFINE_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 { (static_cast <bool> (i_nocapture
< OperandTraits<StoreInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 437, __extension__ __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) { (static_cast
<bool> (i_nocapture < OperandTraits<StoreInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 437, __extension__ __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); }
438
439//===----------------------------------------------------------------------===//
440// FenceInst Class
441//===----------------------------------------------------------------------===//
442
443/// An instruction for ordering other memory operations.
444class FenceInst : public Instruction {
445 using OrderingField = AtomicOrderingBitfieldElementT<0>;
446
447 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
448
449protected:
450 // Note: Instruction needs to be a friend here to call cloneImpl.
451 friend class Instruction;
452
453 FenceInst *cloneImpl() const;
454
455public:
456 // Ordering may only be Acquire, Release, AcquireRelease, or
457 // SequentiallyConsistent.
458 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
459 SyncScope::ID SSID = SyncScope::System,
460 Instruction *InsertBefore = nullptr);
461 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
462 BasicBlock *InsertAtEnd);
463
464 // allocate space for exactly zero operands
465 void *operator new(size_t s) {
466 return User::operator new(s, 0);
467 }
468
469 /// Returns the ordering constraint of this fence instruction.
470 AtomicOrdering getOrdering() const {
471 return getSubclassData<OrderingField>();
472 }
473
474 /// Sets the ordering constraint of this fence instruction. May only be
475 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
476 void setOrdering(AtomicOrdering Ordering) {
477 setSubclassData<OrderingField>(Ordering);
478 }
479
480 /// Returns the synchronization scope ID of this fence instruction.
481 SyncScope::ID getSyncScopeID() const {
482 return SSID;
483 }
484
485 /// Sets the synchronization scope ID of this fence instruction.
486 void setSyncScopeID(SyncScope::ID SSID) {
487 this->SSID = SSID;
488 }
489
490 // Methods for support type inquiry through isa, cast, and dyn_cast:
491 static bool classof(const Instruction *I) {
492 return I->getOpcode() == Instruction::Fence;
493 }
494 static bool classof(const Value *V) {
495 return isa<Instruction>(V) && classof(cast<Instruction>(V));
496 }
497
498private:
499 // Shadow Instruction::setInstructionSubclassData with a private forwarding
500 // method so that subclasses cannot accidentally use it.
501 template <typename Bitfield>
502 void setSubclassData(typename Bitfield::Type Value) {
503 Instruction::setSubclassData<Bitfield>(Value);
504 }
505
506 /// The synchronization scope ID of this fence instruction. Not quite enough
507 /// room in SubClassData for everything, so synchronization scope ID gets its
508 /// own field.
509 SyncScope::ID SSID;
510};
511
512//===----------------------------------------------------------------------===//
513// AtomicCmpXchgInst Class
514//===----------------------------------------------------------------------===//
515
516/// An instruction that atomically checks whether a
517/// specified value is in a memory location, and, if it is, stores a new value
518/// there. The value returned by this instruction is a pair containing the
519/// original value as first element, and an i1 indicating success (true) or
520/// failure (false) as second element.
521///
522class AtomicCmpXchgInst : public Instruction {
523 void Init(Value *Ptr, Value *Cmp, Value *NewVal, Align Align,
524 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
525 SyncScope::ID SSID);
526
527 template <unsigned Offset>
528 using AtomicOrderingBitfieldElement =
529 typename Bitfield::Element<AtomicOrdering, Offset, 3,
530 AtomicOrdering::LAST>;
531
532protected:
533 // Note: Instruction needs to be a friend here to call cloneImpl.
534 friend class Instruction;
535
536 AtomicCmpXchgInst *cloneImpl() const;
537
538public:
539 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment,
540 AtomicOrdering SuccessOrdering,
541 AtomicOrdering FailureOrdering, SyncScope::ID SSID,
542 Instruction *InsertBefore = nullptr);
543 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment,
544 AtomicOrdering SuccessOrdering,
545 AtomicOrdering FailureOrdering, SyncScope::ID SSID,
546 BasicBlock *InsertAtEnd);
547
548 // allocate space for exactly three operands
549 void *operator new(size_t s) {
550 return User::operator new(s, 3);
551 }
552
553 using VolatileField = BoolBitfieldElementT<0>;
554 using WeakField = BoolBitfieldElementT<VolatileField::NextBit>;
555 using SuccessOrderingField =
556 AtomicOrderingBitfieldElementT<WeakField::NextBit>;
557 using FailureOrderingField =
558 AtomicOrderingBitfieldElementT<SuccessOrderingField::NextBit>;
559 using AlignmentField =
560 AlignmentBitfieldElementT<FailureOrderingField::NextBit>;
561 static_assert(
562 Bitfield::areContiguous<VolatileField, WeakField, SuccessOrderingField,
563 FailureOrderingField, AlignmentField>(),
564 "Bitfields must be contiguous");
565
566 /// Return the alignment of the memory that is being allocated by the
567 /// instruction.
568 Align getAlign() const {
569 return Align(1ULL << getSubclassData<AlignmentField>());
570 }
571
572 void setAlignment(Align Align) {
573 setSubclassData<AlignmentField>(Log2(Align));
574 }
575
576 /// Return true if this is a cmpxchg from a volatile memory
577 /// location.
578 ///
579 bool isVolatile() const { return getSubclassData<VolatileField>(); }
580
581 /// Specify whether this is a volatile cmpxchg.
582 ///
583 void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
584
585 /// Return true if this cmpxchg may spuriously fail.
586 bool isWeak() const { return getSubclassData<WeakField>(); }
587
588 void setWeak(bool IsWeak) { setSubclassData<WeakField>(IsWeak); }
589
590 /// Transparently provide more efficient getOperand methods.
591 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
;
592
593 /// Returns the success ordering constraint of this cmpxchg instruction.
594 AtomicOrdering getSuccessOrdering() const {
595 return getSubclassData<SuccessOrderingField>();
596 }
597
598 /// Sets the success ordering constraint of this cmpxchg instruction.
599 void setSuccessOrdering(AtomicOrdering Ordering) {
600 assert(Ordering != AtomicOrdering::NotAtomic &&(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "CmpXchg instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 601, __extension__ __PRETTY_FUNCTION__))
601 "CmpXchg instructions can only be atomic.")(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "CmpXchg instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 601, __extension__ __PRETTY_FUNCTION__))
;
602 setSubclassData<SuccessOrderingField>(Ordering);
603 }
604
605 /// Returns the failure ordering constraint of this cmpxchg instruction.
606 AtomicOrdering getFailureOrdering() const {
607 return getSubclassData<FailureOrderingField>();
608 }
609
610 /// Sets the failure ordering constraint of this cmpxchg instruction.
611 void setFailureOrdering(AtomicOrdering Ordering) {
612 assert(Ordering != AtomicOrdering::NotAtomic &&(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "CmpXchg instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 613, __extension__ __PRETTY_FUNCTION__))
613 "CmpXchg instructions can only be atomic.")(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "CmpXchg instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 613, __extension__ __PRETTY_FUNCTION__))
;
614 setSubclassData<FailureOrderingField>(Ordering);
615 }
616
617 /// Returns the synchronization scope ID of this cmpxchg instruction.
618 SyncScope::ID getSyncScopeID() const {
619 return SSID;
620 }
621
622 /// Sets the synchronization scope ID of this cmpxchg instruction.
623 void setSyncScopeID(SyncScope::ID SSID) {
624 this->SSID = SSID;
625 }
626
627 Value *getPointerOperand() { return getOperand(0); }
628 const Value *getPointerOperand() const { return getOperand(0); }
629 static unsigned getPointerOperandIndex() { return 0U; }
630
631 Value *getCompareOperand() { return getOperand(1); }
632 const Value *getCompareOperand() const { return getOperand(1); }
633
634 Value *getNewValOperand() { return getOperand(2); }
635 const Value *getNewValOperand() const { return getOperand(2); }
636
637 /// Returns the address space of the pointer operand.
638 unsigned getPointerAddressSpace() const {
639 return getPointerOperand()->getType()->getPointerAddressSpace();
640 }
641
642 /// Returns the strongest permitted ordering on failure, given the
643 /// desired ordering on success.
644 ///
645 /// If the comparison in a cmpxchg operation fails, there is no atomic store
646 /// so release semantics cannot be provided. So this function drops explicit
647 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
648 /// operation would remain SequentiallyConsistent.
649 static AtomicOrdering
650 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
651 switch (SuccessOrdering) {
652 default:
653 llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 653)
;
654 case AtomicOrdering::Release:
655 case AtomicOrdering::Monotonic:
656 return AtomicOrdering::Monotonic;
657 case AtomicOrdering::AcquireRelease:
658 case AtomicOrdering::Acquire:
659 return AtomicOrdering::Acquire;
660 case AtomicOrdering::SequentiallyConsistent:
661 return AtomicOrdering::SequentiallyConsistent;
662 }
663 }
664
665 // Methods for support type inquiry through isa, cast, and dyn_cast:
666 static bool classof(const Instruction *I) {
667 return I->getOpcode() == Instruction::AtomicCmpXchg;
668 }
669 static bool classof(const Value *V) {
670 return isa<Instruction>(V) && classof(cast<Instruction>(V));
671 }
672
673private:
674 // Shadow Instruction::setInstructionSubclassData with a private forwarding
675 // method so that subclasses cannot accidentally use it.
676 template <typename Bitfield>
677 void setSubclassData(typename Bitfield::Type Value) {
678 Instruction::setSubclassData<Bitfield>(Value);
679 }
680
681 /// The synchronization scope ID of this cmpxchg instruction. Not quite
682 /// enough room in SubClassData for everything, so synchronization scope ID
683 /// gets its own field.
684 SyncScope::ID SSID;
685};
686
687template <>
688struct OperandTraits<AtomicCmpXchgInst> :
689 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
690};
691
692DEFINE_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 { (static_cast <bool> (i_nocapture <
OperandTraits<AtomicCmpXchgInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 692, __extension__ __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) { (static_cast <bool> (i_nocapture
< OperandTraits<AtomicCmpXchgInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 692, __extension__ __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
); }
693
694//===----------------------------------------------------------------------===//
695// AtomicRMWInst Class
696//===----------------------------------------------------------------------===//
697
698/// an instruction that atomically reads a memory location,
699/// combines it with another value, and then stores the result back. Returns
700/// the old value.
701///
702class AtomicRMWInst : public Instruction {
703protected:
704 // Note: Instruction needs to be a friend here to call cloneImpl.
705 friend class Instruction;
706
707 AtomicRMWInst *cloneImpl() const;
708
709public:
710 /// This enumeration lists the possible modifications atomicrmw can make. In
711 /// the descriptions, 'p' is the pointer to the instruction's memory location,
712 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
713 /// instruction. These instructions always return 'old'.
714 enum BinOp : unsigned {
715 /// *p = v
716 Xchg,
717 /// *p = old + v
718 Add,
719 /// *p = old - v
720 Sub,
721 /// *p = old & v
722 And,
723 /// *p = ~(old & v)
724 Nand,
725 /// *p = old | v
726 Or,
727 /// *p = old ^ v
728 Xor,
729 /// *p = old >signed v ? old : v
730 Max,
731 /// *p = old <signed v ? old : v
732 Min,
733 /// *p = old >unsigned v ? old : v
734 UMax,
735 /// *p = old <unsigned v ? old : v
736 UMin,
737
738 /// *p = old + v
739 FAdd,
740
741 /// *p = old - v
742 FSub,
743
744 FIRST_BINOP = Xchg,
745 LAST_BINOP = FSub,
746 BAD_BINOP
747 };
748
749private:
750 template <unsigned Offset>
751 using AtomicOrderingBitfieldElement =
752 typename Bitfield::Element<AtomicOrdering, Offset, 3,
753 AtomicOrdering::LAST>;
754
755 template <unsigned Offset>
756 using BinOpBitfieldElement =
757 typename Bitfield::Element<BinOp, Offset, 4, BinOp::LAST_BINOP>;
758
759public:
760 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment,
761 AtomicOrdering Ordering, SyncScope::ID SSID,
762 Instruction *InsertBefore = nullptr);
763 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment,
764 AtomicOrdering Ordering, SyncScope::ID SSID,
765 BasicBlock *InsertAtEnd);
766
767 // allocate space for exactly two operands
768 void *operator new(size_t s) {
769 return User::operator new(s, 2);
770 }
771
772 using VolatileField = BoolBitfieldElementT<0>;
773 using AtomicOrderingField =
774 AtomicOrderingBitfieldElementT<VolatileField::NextBit>;
775 using OperationField = BinOpBitfieldElement<AtomicOrderingField::NextBit>;
776 using AlignmentField = AlignmentBitfieldElementT<OperationField::NextBit>;
777 static_assert(Bitfield::areContiguous<VolatileField, AtomicOrderingField,
778 OperationField, AlignmentField>(),
779 "Bitfields must be contiguous");
780
781 BinOp getOperation() const { return getSubclassData<OperationField>(); }
782
783 static StringRef getOperationName(BinOp Op);
784
785 static bool isFPOperation(BinOp Op) {
786 switch (Op) {
787 case AtomicRMWInst::FAdd:
788 case AtomicRMWInst::FSub:
789 return true;
790 default:
791 return false;
792 }
793 }
794
795 void setOperation(BinOp Operation) {
796 setSubclassData<OperationField>(Operation);
797 }
798
799 /// Return the alignment of the memory that is being allocated by the
800 /// instruction.
801 Align getAlign() const {
802 return Align(1ULL << getSubclassData<AlignmentField>());
803 }
804
805 void setAlignment(Align Align) {
806 setSubclassData<AlignmentField>(Log2(Align));
807 }
808
809 /// Return true if this is a RMW on a volatile memory location.
810 ///
811 bool isVolatile() const { return getSubclassData<VolatileField>(); }
812
813 /// Specify whether this is a volatile RMW or not.
814 ///
815 void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
816
817 /// Transparently provide more efficient getOperand methods.
818 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
;
819
820 /// Returns the ordering constraint of this rmw instruction.
821 AtomicOrdering getOrdering() const {
822 return getSubclassData<AtomicOrderingField>();
823 }
824
825 /// Sets the ordering constraint of this rmw instruction.
826 void setOrdering(AtomicOrdering Ordering) {
827 assert(Ordering != AtomicOrdering::NotAtomic &&(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "atomicrmw instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 828, __extension__ __PRETTY_FUNCTION__))
828 "atomicrmw instructions can only be atomic.")(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic
&& "atomicrmw instructions can only be atomic.") ? void
(0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 828, __extension__ __PRETTY_FUNCTION__))
;
829 setSubclassData<AtomicOrderingField>(Ordering);
830 }
831
832 /// Returns the synchronization scope ID of this rmw instruction.
833 SyncScope::ID getSyncScopeID() const {
834 return SSID;
835 }
836
837 /// Sets the synchronization scope ID of this rmw instruction.
838 void setSyncScopeID(SyncScope::ID SSID) {
839 this->SSID = SSID;
840 }
841
842 Value *getPointerOperand() { return getOperand(0); }
843 const Value *getPointerOperand() const { return getOperand(0); }
844 static unsigned getPointerOperandIndex() { return 0U; }
845
846 Value *getValOperand() { return getOperand(1); }
847 const Value *getValOperand() const { return getOperand(1); }
848
849 /// Returns the address space of the pointer operand.
850 unsigned getPointerAddressSpace() const {
851 return getPointerOperand()->getType()->getPointerAddressSpace();
852 }
853
854 bool isFloatingPointOperation() const {
855 return isFPOperation(getOperation());
856 }
857
858 // Methods for support type inquiry through isa, cast, and dyn_cast:
859 static bool classof(const Instruction *I) {
860 return I->getOpcode() == Instruction::AtomicRMW;
861 }
862 static bool classof(const Value *V) {
863 return isa<Instruction>(V) && classof(cast<Instruction>(V));
864 }
865
866private:
867 void Init(BinOp Operation, Value *Ptr, Value *Val, Align Align,
868 AtomicOrdering Ordering, SyncScope::ID SSID);
869
870 // Shadow Instruction::setInstructionSubclassData with a private forwarding
871 // method so that subclasses cannot accidentally use it.
872 template <typename Bitfield>
873 void setSubclassData(typename Bitfield::Type Value) {
874 Instruction::setSubclassData<Bitfield>(Value);
875 }
876
877 /// The synchronization scope ID of this rmw instruction. Not quite enough
878 /// room in SubClassData for everything, so synchronization scope ID gets its
879 /// own field.
880 SyncScope::ID SSID;
881};
882
883template <>
884struct OperandTraits<AtomicRMWInst>
885 : public FixedNumOperandTraits<AtomicRMWInst,2> {
886};
887
888DEFINE_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 { (static_cast <bool> (i_nocapture
< OperandTraits<AtomicRMWInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 888, __extension__ __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) { (static_cast
<bool> (i_nocapture < OperandTraits<AtomicRMWInst
>::operands(this) && "setOperand() out of range!")
? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 888, __extension__ __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); }
889
890//===----------------------------------------------------------------------===//
891// GetElementPtrInst Class
892//===----------------------------------------------------------------------===//
893
894// checkGEPType - Simple wrapper function to give a better assertion failure
895// message on bad indexes for a gep instruction.
896//
897inline Type *checkGEPType(Type *Ty) {
898 assert(Ty && "Invalid GetElementPtrInst indices for type!")(static_cast <bool> (Ty && "Invalid GetElementPtrInst indices for type!"
) ? void (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 898, __extension__ __PRETTY_FUNCTION__))
;
899 return Ty;
900}
901
902/// an instruction for type-safe pointer arithmetic to
903/// access elements of arrays and structs
904///
905class GetElementPtrInst : public Instruction {
906 Type *SourceElementType;
907 Type *ResultElementType;
908
909 GetElementPtrInst(const GetElementPtrInst &GEPI);
910
911 /// Constructors - Create a getelementptr instruction with a base pointer an
912 /// list of indices. The first ctor can optionally insert before an existing
913 /// instruction, the second appends the new instruction to the specified
914 /// BasicBlock.
915 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
916 ArrayRef<Value *> IdxList, unsigned Values,
917 const Twine &NameStr, Instruction *InsertBefore);
918 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
919 ArrayRef<Value *> IdxList, unsigned Values,
920 const Twine &NameStr, BasicBlock *InsertAtEnd);
921
922 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
923
924protected:
925 // Note: Instruction needs to be a friend here to call cloneImpl.
926 friend class Instruction;
927
928 GetElementPtrInst *cloneImpl() const;
929
930public:
931 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
932 ArrayRef<Value *> IdxList,
933 const Twine &NameStr = "",
934 Instruction *InsertBefore = nullptr) {
935 unsigned Values = 1 + unsigned(IdxList.size());
936 if (!PointeeType)
937 PointeeType =
938 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
939 else
940 assert((static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 942, __extension__ __PRETTY_FUNCTION__))
941 PointeeType ==(static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 942, __extension__ __PRETTY_FUNCTION__))
942 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())(static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 942, __extension__ __PRETTY_FUNCTION__))
;
943 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
944 NameStr, InsertBefore);
945 }
946
947 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
948 ArrayRef<Value *> IdxList,
949 const Twine &NameStr,
950 BasicBlock *InsertAtEnd) {
951 unsigned Values = 1 + unsigned(IdxList.size());
952 if (!PointeeType)
953 PointeeType =
954 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
955 else
956 assert((static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 958, __extension__ __PRETTY_FUNCTION__))
957 PointeeType ==(static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 958, __extension__ __PRETTY_FUNCTION__))
958 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())(static_cast <bool> (PointeeType == cast<PointerType
>(Ptr->getType()->getScalarType())->getElementType
()) ? void (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 958, __extension__ __PRETTY_FUNCTION__))
;
959 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
960 NameStr, InsertAtEnd);
961 }
962
963 /// Create an "inbounds" getelementptr. See the documentation for the
964 /// "inbounds" flag in LangRef.html for details.
965 static GetElementPtrInst *CreateInBounds(Value *Ptr,
966 ArrayRef<Value *> IdxList,
967 const Twine &NameStr = "",
968 Instruction *InsertBefore = nullptr){
969 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
970 }
971
972 static GetElementPtrInst *
973 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
974 const Twine &NameStr = "",
975 Instruction *InsertBefore = nullptr) {
976 GetElementPtrInst *GEP =
977 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
978 GEP->setIsInBounds(true);
979 return GEP;
980 }
981
982 static GetElementPtrInst *CreateInBounds(Value *Ptr,
983 ArrayRef<Value *> IdxList,
984 const Twine &NameStr,
985 BasicBlock *InsertAtEnd) {
986 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
987 }
988
989 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
990 ArrayRef<Value *> IdxList,
991 const Twine &NameStr,
992 BasicBlock *InsertAtEnd) {
993 GetElementPtrInst *GEP =
994 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
995 GEP->setIsInBounds(true);
996 return GEP;
997 }
998
999 /// Transparently provide more efficient getOperand methods.
1000 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
;
1001
1002 Type *getSourceElementType() const { return SourceElementType; }
1003
1004 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
1005 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
1006
1007 Type *getResultElementType() const {
1008 assert(ResultElementType ==(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1009, __extension__ __PRETTY_FUNCTION__))
1009 cast<PointerType>(getType()->getScalarType())->getElementType())(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1009, __extension__ __PRETTY_FUNCTION__))
;
1010 return ResultElementType;
1011 }
1012
1013 /// Returns the address space of this instruction's pointer type.
1014 unsigned getAddressSpace() const {
1015 // Note that this is always the same as the pointer operand's address space
1016 // and that is cheaper to compute, so cheat here.
1017 return getPointerAddressSpace();
1018 }
1019
1020 /// Returns the result type of a getelementptr with the given source
1021 /// element type and indexes.
1022 ///
1023 /// Null is returned if the indices are invalid for the specified
1024 /// source element type.
1025 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1026 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1027 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1028
1029 /// Return the type of the element at the given index of an indexable
1030 /// type. This is equivalent to "getIndexedType(Agg, {Zero, Idx})".
1031 ///
1032 /// Returns null if the type can't be indexed, or the given index is not
1033 /// legal for the given type.
1034 static Type *getTypeAtIndex(Type *Ty, Value *Idx);
1035 static Type *getTypeAtIndex(Type *Ty, uint64_t Idx);
1036
1037 inline op_iterator idx_begin() { return op_begin()+1; }
1038 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1039 inline op_iterator idx_end() { return op_end(); }
1040 inline const_op_iterator idx_end() const { return op_end(); }
1041
1042 inline iterator_range<op_iterator> indices() {
1043 return make_range(idx_begin(), idx_end());
1044 }
1045
1046 inline iterator_range<const_op_iterator> indices() const {
1047 return make_range(idx_begin(), idx_end());
1048 }
1049
1050 Value *getPointerOperand() {
1051 return getOperand(0);
1052 }
1053 const Value *getPointerOperand() const {
1054 return getOperand(0);
1055 }
1056 static unsigned getPointerOperandIndex() {
1057 return 0U; // get index for modifying correct operand.
1058 }
1059
1060 /// Method to return the pointer operand as a
1061 /// PointerType.
1062 Type *getPointerOperandType() const {
1063 return getPointerOperand()->getType();
1064 }
1065
1066 /// Returns the address space of the pointer operand.
1067 unsigned getPointerAddressSpace() const {
1068 return getPointerOperandType()->getPointerAddressSpace();
1069 }
1070
1071 /// Returns the pointer type returned by the GEP
1072 /// instruction, which may be a vector of pointers.
1073 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1074 ArrayRef<Value *> IdxList) {
1075 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1076 Ptr->getType()->getPointerAddressSpace());
1077 // Vector GEP
1078 if (auto *PtrVTy = dyn_cast<VectorType>(Ptr->getType())) {
1079 ElementCount EltCount = PtrVTy->getElementCount();
1080 return VectorType::get(PtrTy, EltCount);
1081 }
1082 for (Value *Index : IdxList)
1083 if (auto *IndexVTy = dyn_cast<VectorType>(Index->getType())) {
1084 ElementCount EltCount = IndexVTy->getElementCount();
1085 return VectorType::get(PtrTy, EltCount);
1086 }
1087 // Scalar GEP
1088 return PtrTy;
1089 }
1090
1091 unsigned getNumIndices() const { // Note: always non-negative
1092 return getNumOperands() - 1;
1093 }
1094
1095 bool hasIndices() const {
1096 return getNumOperands() > 1;
1097 }
1098
1099 /// Return true if all of the indices of this GEP are
1100 /// zeros. If so, the result pointer and the first operand have the same
1101 /// value, just potentially different types.
1102 bool hasAllZeroIndices() const;
1103
1104 /// Return true if all of the indices of this GEP are
1105 /// constant integers. If so, the result pointer and the first operand have
1106 /// a constant offset between them.
1107 bool hasAllConstantIndices() const;
1108
1109 /// Set or clear the inbounds flag on this GEP instruction.
1110 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1111 void setIsInBounds(bool b = true);
1112
1113 /// Determine whether the GEP has the inbounds flag.
1114 bool isInBounds() const;
1115
1116 /// Accumulate the constant address offset of this GEP if possible.
1117 ///
1118 /// This routine accepts an APInt into which it will accumulate the constant
1119 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1120 /// all-constant, it returns false and the value of the offset APInt is
1121 /// undefined (it is *not* preserved!). The APInt passed into this routine
1122 /// must be at least as wide as the IntPtr type for the address space of
1123 /// the base GEP pointer.
1124 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1125
1126 // Methods for support type inquiry through isa, cast, and dyn_cast:
1127 static bool classof(const Instruction *I) {
1128 return (I->getOpcode() == Instruction::GetElementPtr);
1129 }
1130 static bool classof(const Value *V) {
1131 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1132 }
1133};
1134
1135template <>
1136struct OperandTraits<GetElementPtrInst> :
1137 public VariadicOperandTraits<GetElementPtrInst, 1> {
1138};
1139
1140GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1141 ArrayRef<Value *> IdxList, unsigned Values,
1142 const Twine &NameStr,
1143 Instruction *InsertBefore)
1144 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1145 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1146 Values, InsertBefore),
1147 SourceElementType(PointeeType),
1148 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1149 assert(ResultElementType ==(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1150, __extension__ __PRETTY_FUNCTION__))
1150 cast<PointerType>(getType()->getScalarType())->getElementType())(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1150, __extension__ __PRETTY_FUNCTION__))
;
1151 init(Ptr, IdxList, NameStr);
1152}
1153
1154GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1155 ArrayRef<Value *> IdxList, unsigned Values,
1156 const Twine &NameStr,
1157 BasicBlock *InsertAtEnd)
1158 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1159 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1160 Values, InsertAtEnd),
1161 SourceElementType(PointeeType),
1162 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1163 assert(ResultElementType ==(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1164, __extension__ __PRETTY_FUNCTION__))
1164 cast<PointerType>(getType()->getScalarType())->getElementType())(static_cast <bool> (ResultElementType == cast<PointerType
>(getType()->getScalarType())->getElementType()) ? void
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1164, __extension__ __PRETTY_FUNCTION__))
;
1165 init(Ptr, IdxList, NameStr);
1166}
1167
1168DEFINE_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 { (static_cast <bool> (i_nocapture <
OperandTraits<GetElementPtrInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1168, __extension__ __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) { (static_cast <bool> (i_nocapture
< OperandTraits<GetElementPtrInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1168, __extension__ __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
); }
1169
1170//===----------------------------------------------------------------------===//
1171// ICmpInst Class
1172//===----------------------------------------------------------------------===//
1173
1174/// This instruction compares its operands according to the predicate given
1175/// to the constructor. It only operates on integers or pointers. The operands
1176/// must be identical types.
1177/// Represent an integer comparison operator.
1178class ICmpInst: public CmpInst {
1179 void AssertOK() {
1180 assert(isIntPredicate() &&(static_cast <bool> (isIntPredicate() && "Invalid ICmp predicate value"
) ? void (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1181, __extension__ __PRETTY_FUNCTION__))
1181 "Invalid ICmp predicate value")(static_cast <bool> (isIntPredicate() && "Invalid ICmp predicate value"
) ? void (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1181, __extension__ __PRETTY_FUNCTION__))
;
1182 assert(getOperand(0)->getType() == getOperand(1)->getType() &&(static_cast <bool> (getOperand(0)->getType() == getOperand
(1)->getType() && "Both operands to ICmp instruction are not of the same type!"
) ? 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-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1183, __extension__ __PRETTY_FUNCTION__))
1183 "Both operands to ICmp instruction are not of the same type!")(static_cast <bool> (getOperand(0)->getType() == getOperand
(1)->getType() && "Both operands to ICmp instruction are not of the same type!"
) ? 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-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1183, __extension__ __PRETTY_FUNCTION__))
;
1184 // Check that the operands are the right type
1185 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(static_cast <bool> ((getOperand(0)->getType()->isIntOrIntVectorTy
() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
"Invalid operand types for ICmp instruction") ? void (0) : __assert_fail
("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1187, __extension__ __PRETTY_FUNCTION__))
1186 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(static_cast <bool> ((getOperand(0)->getType()->isIntOrIntVectorTy
() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
"Invalid operand types for ICmp instruction") ? void (0) : __assert_fail
("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1187, __extension__ __PRETTY_FUNCTION__))
1187 "Invalid operand types for ICmp instruction")(static_cast <bool> ((getOperand(0)->getType()->isIntOrIntVectorTy
() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
"Invalid operand types for ICmp instruction") ? void (0) : __assert_fail
("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1187, __extension__ __PRETTY_FUNCTION__))
;
1188 }
1189
1190protected:
1191 // Note: Instruction needs to be a friend here to call cloneImpl.
1192 friend class Instruction;
1193
1194 /// Clone an identical ICmpInst
1195 ICmpInst *cloneImpl() const;
1196
1197public:
1198 /// Constructor with insert-before-instruction semantics.
1199 ICmpInst(
1200 Instruction *InsertBefore, ///< Where to insert
1201 Predicate pred, ///< The predicate to use for the comparison
1202 Value *LHS, ///< The left-hand-side of the expression
1203 Value *RHS, ///< The right-hand-side of the expression
1204 const Twine &NameStr = "" ///< Name of the instruction
1205 ) : CmpInst(makeCmpResultType(LHS->getType()),
1206 Instruction::ICmp, pred, LHS, RHS, NameStr,
1207 InsertBefore) {
1208#ifndef NDEBUG
1209 AssertOK();
1210#endif
1211 }
1212
1213 /// Constructor with insert-at-end semantics.
1214 ICmpInst(
1215 BasicBlock &InsertAtEnd, ///< Block to insert into.
1216 Predicate pred, ///< The predicate to use for the comparison
1217 Value *LHS, ///< The left-hand-side of the expression
1218 Value *RHS, ///< The right-hand-side of the expression
1219 const Twine &NameStr = "" ///< Name of the instruction
1220 ) : CmpInst(makeCmpResultType(LHS->getType()),
1221 Instruction::ICmp, pred, LHS, RHS, NameStr,
1222 &InsertAtEnd) {
1223#ifndef NDEBUG
1224 AssertOK();
1225#endif
1226 }
1227
1228 /// Constructor with no-insertion semantics
1229 ICmpInst(
1230 Predicate pred, ///< The predicate to use for the comparison
1231 Value *LHS, ///< The left-hand-side of the expression
1232 Value *RHS, ///< The right-hand-side of the expression
1233 const Twine &NameStr = "" ///< Name of the instruction
1234 ) : CmpInst(makeCmpResultType(LHS->getType()),
1235 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1236#ifndef NDEBUG
1237 AssertOK();
1238#endif
1239 }
1240
1241 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1242 /// @returns the predicate that would be the result if the operand were
1243 /// regarded as signed.
1244 /// Return the signed version of the predicate
1245 Predicate getSignedPredicate() const {
1246 return getSignedPredicate(getPredicate());
1247 }
1248
1249 /// This is a static version that you can use without an instruction.
1250 /// Return the signed version of the predicate.
1251 static Predicate getSignedPredicate(Predicate pred);
1252
1253 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1254 /// @returns the predicate that would be the result if the operand were
1255 /// regarded as unsigned.
1256 /// Return the unsigned version of the predicate
1257 Predicate getUnsignedPredicate() const {
1258 return getUnsignedPredicate(getPredicate());
1259 }
1260
1261 /// This is a static version that you can use without an instruction.
1262 /// Return the unsigned version of the predicate.
1263 static Predicate getUnsignedPredicate(Predicate pred);
1264
1265 /// Return true if this predicate is either EQ or NE. This also
1266 /// tests for commutativity.
1267 static bool isEquality(Predicate P) {
1268 return P == ICMP_EQ || P == ICMP_NE;
1269 }
1270
1271 /// Return true if this predicate is either EQ or NE. This also
1272 /// tests for commutativity.
1273 bool isEquality() const {
1274 return isEquality(getPredicate());
1275 }
1276
1277 /// @returns true if the predicate of this ICmpInst is commutative
1278 /// Determine if this relation is commutative.
1279 bool isCommutative() const { return isEquality(); }
1280
1281 /// Return true if the predicate is relational (not EQ or NE).
1282 ///
1283 bool isRelational() const {
1284 return !isEquality();
1285 }
1286
1287 /// Return true if the predicate is relational (not EQ or NE).
1288 ///
1289 static bool isRelational(Predicate P) {
1290 return !isEquality(P);
1291 }
1292
1293 /// Return true if the predicate is SGT or UGT.
1294 ///
1295 static bool isGT(Predicate P) {
1296 return P == ICMP_SGT || P == ICMP_UGT;
1297 }
1298
1299 /// Return true if the predicate is SLT or ULT.
1300 ///
1301 static bool isLT(Predicate P) {
1302 return P == ICMP_SLT || P == ICMP_ULT;
1303 }
1304
1305 /// Return true if the predicate is SGE or UGE.
1306 ///
1307 static bool isGE(Predicate P) {
1308 return P == ICMP_SGE || P == ICMP_UGE;
1309 }
1310
1311 /// Return true if the predicate is SLE or ULE.
1312 ///
1313 static bool isLE(Predicate P) {
1314 return P == ICMP_SLE || P == ICMP_ULE;
1315 }
1316
1317 /// Exchange the two operands to this instruction in such a way that it does
1318 /// not modify the semantics of the instruction. The predicate value may be
1319 /// changed to retain the same result if the predicate is order dependent
1320 /// (e.g. ult).
1321 /// Swap operands and adjust predicate.
1322 void swapOperands() {
1323 setPredicate(getSwappedPredicate());
1324 Op<0>().swap(Op<1>());
1325 }
1326
1327 // Methods for support type inquiry through isa, cast, and dyn_cast:
1328 static bool classof(const Instruction *I) {
1329 return I->getOpcode() == Instruction::ICmp;
1330 }
1331 static bool classof(const Value *V) {
1332 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1333 }
1334};
1335
1336//===----------------------------------------------------------------------===//
1337// FCmpInst Class
1338//===----------------------------------------------------------------------===//
1339
1340/// This instruction compares its operands according to the predicate given
1341/// to the constructor. It only operates on floating point values or packed
1342/// vectors of floating point values. The operands must be identical types.
1343/// Represents a floating point comparison operator.
1344class FCmpInst: public CmpInst {
1345 void AssertOK() {
1346 assert(isFPPredicate() && "Invalid FCmp predicate value")(static_cast <bool> (isFPPredicate() && "Invalid FCmp predicate value"
) ? void (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1346, __extension__ __PRETTY_FUNCTION__))
;
1347 assert(getOperand(0)->getType() == getOperand(1)->getType() &&(static_cast <bool> (getOperand(0)->getType() == getOperand
(1)->getType() && "Both operands to FCmp instruction are not of the same type!"
) ? 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-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1348, __extension__ __PRETTY_FUNCTION__))
1348 "Both operands to FCmp instruction are not of the same type!")(static_cast <bool> (getOperand(0)->getType() == getOperand
(1)->getType() && "Both operands to FCmp instruction are not of the same type!"
) ? 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-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1348, __extension__ __PRETTY_FUNCTION__))
;
1349 // Check that the operands are the right type
1350 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&(static_cast <bool> (getOperand(0)->getType()->isFPOrFPVectorTy
() && "Invalid operand types for FCmp instruction") ?
void (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1351, __extension__ __PRETTY_FUNCTION__))
1351 "Invalid operand types for FCmp instruction")(static_cast <bool> (getOperand(0)->getType()->isFPOrFPVectorTy
() && "Invalid operand types for FCmp instruction") ?
void (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1351, __extension__ __PRETTY_FUNCTION__))
;
1352 }
1353
1354protected:
1355 // Note: Instruction needs to be a friend here to call cloneImpl.
1356 friend class Instruction;
1357
1358 /// Clone an identical FCmpInst
1359 FCmpInst *cloneImpl() const;
1360
1361public:
1362 /// Constructor with insert-before-instruction semantics.
1363 FCmpInst(
1364 Instruction *InsertBefore, ///< Where to insert
1365 Predicate pred, ///< The predicate to use for the comparison
1366 Value *LHS, ///< The left-hand-side of the expression
1367 Value *RHS, ///< The right-hand-side of the expression
1368 const Twine &NameStr = "" ///< Name of the instruction
1369 ) : CmpInst(makeCmpResultType(LHS->getType()),
1370 Instruction::FCmp, pred, LHS, RHS, NameStr,
1371 InsertBefore) {
1372 AssertOK();
1373 }
1374
1375 /// Constructor with insert-at-end semantics.
1376 FCmpInst(
1377 BasicBlock &InsertAtEnd, ///< Block to insert into.
1378 Predicate pred, ///< The predicate to use for the comparison
1379 Value *LHS, ///< The left-hand-side of the expression
1380 Value *RHS, ///< The right-hand-side of the expression
1381 const Twine &NameStr = "" ///< Name of the instruction
1382 ) : CmpInst(makeCmpResultType(LHS->getType()),
1383 Instruction::FCmp, pred, LHS, RHS, NameStr,
1384 &InsertAtEnd) {
1385 AssertOK();
1386 }
1387
1388 /// Constructor with no-insertion semantics
1389 FCmpInst(
1390 Predicate Pred, ///< The predicate to use for the comparison
1391 Value *LHS, ///< The left-hand-side of the expression
1392 Value *RHS, ///< The right-hand-side of the expression
1393 const Twine &NameStr = "", ///< Name of the instruction
1394 Instruction *FlagsSource = nullptr
1395 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1396 RHS, NameStr, nullptr, FlagsSource) {
1397 AssertOK();
1398 }
1399
1400 /// @returns true if the predicate of this instruction is EQ or NE.
1401 /// Determine if this is an equality predicate.
1402 static bool isEquality(Predicate Pred) {
1403 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1404 Pred == FCMP_UNE;
1405 }
1406
1407 /// @returns true if the predicate of this instruction is EQ or NE.
1408 /// Determine if this is an equality predicate.
1409 bool isEquality() const { return isEquality(getPredicate()); }
1410
1411 /// @returns true if the predicate of this instruction is commutative.
1412 /// Determine if this is a commutative predicate.
1413 bool isCommutative() const {
1414 return isEquality() ||
1415 getPredicate() == FCMP_FALSE ||
1416 getPredicate() == FCMP_TRUE ||
1417 getPredicate() == FCMP_ORD ||
1418 getPredicate() == FCMP_UNO;
1419 }
1420
1421 /// @returns true if the predicate is relational (not EQ or NE).
1422 /// Determine if this a relational predicate.
1423 bool isRelational() const { return !isEquality(); }
1424
1425 /// Exchange the two operands to this instruction in such a way that it does
1426 /// not modify the semantics of the instruction. The predicate value may be
1427 /// changed to retain the same result if the predicate is order dependent
1428 /// (e.g. ult).
1429 /// Swap operands and adjust predicate.
1430 void swapOperands() {
1431 setPredicate(getSwappedPredicate());
1432 Op<0>().swap(Op<1>());
1433 }
1434
1435 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1436 static bool classof(const Instruction *I) {
1437 return I->getOpcode() == Instruction::FCmp;
1438 }
1439 static bool classof(const Value *V) {
1440 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1441 }
1442};
1443
1444//===----------------------------------------------------------------------===//
1445/// This class represents a function call, abstracting a target
1446/// machine's calling convention. This class uses low bit of the SubClassData
1447/// field to indicate whether or not this is a tail call. The rest of the bits
1448/// hold the calling convention of the call.
1449///
1450class CallInst : public CallBase {
1451 CallInst(const CallInst &CI);
1452
1453 /// Construct a CallInst given a range of arguments.
1454 /// Construct a CallInst from a range of arguments
1455 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1456 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1457 Instruction *InsertBefore);
1458
1459 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1460 const Twine &NameStr, Instruction *InsertBefore)
1461 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1462
1463 /// Construct a CallInst given a range of arguments.
1464 /// Construct a CallInst from a range of arguments
1465 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1466 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1467 BasicBlock *InsertAtEnd);
1468
1469 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1470 Instruction *InsertBefore);
1471
1472 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1473 BasicBlock *InsertAtEnd);
1474
1475 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1476 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1477 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1478
1479 /// Compute the number of operands to allocate.
1480 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1481 // We need one operand for the called function, plus the input operand
1482 // counts provided.
1483 return 1 + NumArgs + NumBundleInputs;
1484 }
1485
1486protected:
1487 // Note: Instruction needs to be a friend here to call cloneImpl.
1488 friend class Instruction;
1489
1490 CallInst *cloneImpl() const;
1491
1492public:
1493 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1494 Instruction *InsertBefore = nullptr) {
1495 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1496 }
1497
1498 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1499 const Twine &NameStr,
1500 Instruction *InsertBefore = nullptr) {
1501 return new (ComputeNumOperands(Args.size()))
1502 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1503 }
1504
1505 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1506 ArrayRef<OperandBundleDef> Bundles = None,
1507 const Twine &NameStr = "",
1508 Instruction *InsertBefore = nullptr) {
1509 const int NumOperands =
1510 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1511 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1512
1513 return new (NumOperands, DescriptorBytes)
1514 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1515 }
1516
1517 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1518 BasicBlock *InsertAtEnd) {
1519 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1520 }
1521
1522 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1523 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1524 return new (ComputeNumOperands(Args.size()))
1525 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1526 }
1527
1528 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1529 ArrayRef<OperandBundleDef> Bundles,
1530 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1531 const int NumOperands =
1532 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1533 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1534
1535 return new (NumOperands, DescriptorBytes)
1536 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1537 }
1538
1539 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1540 Instruction *InsertBefore = nullptr) {
1541 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1542 InsertBefore);
1543 }
1544
1545 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1546 ArrayRef<OperandBundleDef> Bundles = None,
1547 const Twine &NameStr = "",
1548 Instruction *InsertBefore = nullptr) {
1549 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1550 NameStr, InsertBefore);
1551 }
1552
1553 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1554 const Twine &NameStr,
1555 Instruction *InsertBefore = nullptr) {
1556 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1557 InsertBefore);
1558 }
1559
1560 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1561 BasicBlock *InsertAtEnd) {
1562 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1563 InsertAtEnd);
1564 }
1565
1566 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1567 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1568 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1569 InsertAtEnd);
1570 }
1571
1572 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1573 ArrayRef<OperandBundleDef> Bundles,
1574 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1575 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1576 NameStr, InsertAtEnd);
1577 }
1578
1579 /// Create a clone of \p CI with a different set of operand bundles and
1580 /// insert it before \p InsertPt.
1581 ///
1582 /// The returned call instruction is identical \p CI in every way except that
1583 /// the operand bundles for the new instruction are set to the operand bundles
1584 /// in \p Bundles.
1585 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1586 Instruction *InsertPt = nullptr);
1587
1588 /// Generate the IR for a call to malloc:
1589 /// 1. Compute the malloc call's argument as the specified type's size,
1590 /// possibly multiplied by the array size if the array size is not
1591 /// constant 1.
1592 /// 2. Call malloc with that argument.
1593 /// 3. Bitcast the result of the malloc call to the specified type.
1594 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1595 Type *AllocTy, Value *AllocSize,
1596 Value *ArraySize = nullptr,
1597 Function *MallocF = nullptr,
1598 const Twine &Name = "");
1599 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1600 Type *AllocTy, Value *AllocSize,
1601 Value *ArraySize = nullptr,
1602 Function *MallocF = nullptr,
1603 const Twine &Name = "");
1604 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1605 Type *AllocTy, Value *AllocSize,
1606 Value *ArraySize = nullptr,
1607 ArrayRef<OperandBundleDef> Bundles = None,
1608 Function *MallocF = nullptr,
1609 const Twine &Name = "");
1610 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1611 Type *AllocTy, Value *AllocSize,
1612 Value *ArraySize = nullptr,
1613 ArrayRef<OperandBundleDef> Bundles = None,
1614 Function *MallocF = nullptr,
1615 const Twine &Name = "");
1616 /// Generate the IR for a call to the builtin free function.
1617 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1618 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1619 static Instruction *CreateFree(Value *Source,
1620 ArrayRef<OperandBundleDef> Bundles,
1621 Instruction *InsertBefore);
1622 static Instruction *CreateFree(Value *Source,
1623 ArrayRef<OperandBundleDef> Bundles,
1624 BasicBlock *InsertAtEnd);
1625
1626 // Note that 'musttail' implies 'tail'.
1627 enum TailCallKind : unsigned {
1628 TCK_None = 0,
1629 TCK_Tail = 1,
1630 TCK_MustTail = 2,
1631 TCK_NoTail = 3,
1632 TCK_LAST = TCK_NoTail
1633 };
1634
1635 using TailCallKindField = Bitfield::Element<TailCallKind, 0, 2, TCK_LAST>;
1636 static_assert(
1637 Bitfield::areContiguous<TailCallKindField, CallBase::CallingConvField>(),
1638 "Bitfields must be contiguous");
1639
1640 TailCallKind getTailCallKind() const {
1641 return getSubclassData<TailCallKindField>();
1642 }
1643
1644 bool isTailCall() const {
1645 TailCallKind Kind = getTailCallKind();
1646 return Kind == TCK_Tail || Kind == TCK_MustTail;
1647 }
1648
1649 bool isMustTailCall() const { return getTailCallKind() == TCK_MustTail; }
1650
1651 bool isNoTailCall() const { return getTailCallKind() == TCK_NoTail; }
1652
1653 void setTailCallKind(TailCallKind TCK) {
1654 setSubclassData<TailCallKindField>(TCK);
1655 }
1656
1657 void setTailCall(bool IsTc = true) {
1658 setTailCallKind(IsTc ? TCK_Tail : TCK_None);
1659 }
1660
1661 /// Return true if the call can return twice
1662 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1663 void setCanReturnTwice() {
1664 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1665 }
1666
1667 // Methods for support type inquiry through isa, cast, and dyn_cast:
1668 static bool classof(const Instruction *I) {
1669 return I->getOpcode() == Instruction::Call;
1670 }
1671 static bool classof(const Value *V) {
1672 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1673 }
1674
1675 /// Updates profile metadata by scaling it by \p S / \p T.
1676 void updateProfWeight(uint64_t S, uint64_t T);
1677
1678private:
1679 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1680 // method so that subclasses cannot accidentally use it.
1681 template <typename Bitfield>
1682 void setSubclassData(typename Bitfield::Type Value) {
1683 Instruction::setSubclassData<Bitfield>(Value);
1684 }
1685};
1686
1687CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1688 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1689 BasicBlock *InsertAtEnd)
1690 : CallBase(Ty->getReturnType(), Instruction::Call,
1691 OperandTraits<CallBase>::op_end(this) -
1692 (Args.size() + CountBundleInputs(Bundles) + 1),
1693 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1694 InsertAtEnd) {
1695 init(Ty, Func, Args, Bundles, NameStr);
1696}
1697
1698CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1699 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1700 Instruction *InsertBefore)
1701 : CallBase(Ty->getReturnType(), Instruction::Call,
1702 OperandTraits<CallBase>::op_end(this) -
1703 (Args.size() + CountBundleInputs(Bundles) + 1),
1704 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1705 InsertBefore) {
1706 init(Ty, Func, Args, Bundles, NameStr);
1707}
1708
1709//===----------------------------------------------------------------------===//
1710// SelectInst Class
1711//===----------------------------------------------------------------------===//
1712
1713/// This class represents the LLVM 'select' instruction.
1714///
1715class SelectInst : public Instruction {
1716 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1717 Instruction *InsertBefore)
1718 : Instruction(S1->getType(), Instruction::Select,
1719 &Op<0>(), 3, InsertBefore) {
1720 init(C, S1, S2);
1721 setName(NameStr);
1722 }
1723
1724 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1725 BasicBlock *InsertAtEnd)
1726 : Instruction(S1->getType(), Instruction::Select,
1727 &Op<0>(), 3, InsertAtEnd) {
1728 init(C, S1, S2);
1729 setName(NameStr);
1730 }
1731
1732 void init(Value *C, Value *S1, Value *S2) {
1733 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")(static_cast <bool> (!areInvalidOperands(C, S1, S2) &&
"Invalid operands for select") ? void (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1733, __extension__ __PRETTY_FUNCTION__))
;
1734 Op<0>() = C;
1735 Op<1>() = S1;
1736 Op<2>() = S2;
1737 }
1738
1739protected:
1740 // Note: Instruction needs to be a friend here to call cloneImpl.
1741 friend class Instruction;
1742
1743 SelectInst *cloneImpl() const;
1744
1745public:
1746 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1747 const Twine &NameStr = "",
1748 Instruction *InsertBefore = nullptr,
1749 Instruction *MDFrom = nullptr) {
1750 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1751 if (MDFrom)
1752 Sel->copyMetadata(*MDFrom);
1753 return Sel;
1754 }
1755
1756 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1757 const Twine &NameStr,
1758 BasicBlock *InsertAtEnd) {
1759 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1760 }
1761
1762 const Value *getCondition() const { return Op<0>(); }
1763 const Value *getTrueValue() const { return Op<1>(); }
1764 const Value *getFalseValue() const { return Op<2>(); }
1765 Value *getCondition() { return Op<0>(); }
1766 Value *getTrueValue() { return Op<1>(); }
1767 Value *getFalseValue() { return Op<2>(); }
1768
1769 void setCondition(Value *V) { Op<0>() = V; }
1770 void setTrueValue(Value *V) { Op<1>() = V; }
1771 void setFalseValue(Value *V) { Op<2>() = V; }
1772
1773 /// Swap the true and false values of the select instruction.
1774 /// This doesn't swap prof metadata.
1775 void swapValues() { Op<1>().swap(Op<2>()); }
1776
1777 /// Return a string if the specified operands are invalid
1778 /// for a select operation, otherwise return null.
1779 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1780
1781 /// Transparently provide more efficient getOperand methods.
1782 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
;
1783
1784 OtherOps getOpcode() const {
1785 return static_cast<OtherOps>(Instruction::getOpcode());
1786 }
1787
1788 // Methods for support type inquiry through isa, cast, and dyn_cast:
1789 static bool classof(const Instruction *I) {
1790 return I->getOpcode() == Instruction::Select;
1791 }
1792 static bool classof(const Value *V) {
1793 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1794 }
1795};
1796
1797template <>
1798struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1799};
1800
1801DEFINE_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 { (static_cast <bool
> (i_nocapture < OperandTraits<SelectInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1801, __extension__ __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) { (static_cast
<bool> (i_nocapture < OperandTraits<SelectInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1801, __extension__ __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); }
1802
1803//===----------------------------------------------------------------------===//
1804// VAArgInst Class
1805//===----------------------------------------------------------------------===//
1806
1807/// This class represents the va_arg llvm instruction, which returns
1808/// an argument of the specified type given a va_list and increments that list
1809///
1810class VAArgInst : public UnaryInstruction {
1811protected:
1812 // Note: Instruction needs to be a friend here to call cloneImpl.
1813 friend class Instruction;
1814
1815 VAArgInst *cloneImpl() const;
1816
1817public:
1818 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1819 Instruction *InsertBefore = nullptr)
1820 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1821 setName(NameStr);
1822 }
1823
1824 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1825 BasicBlock *InsertAtEnd)
1826 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1827 setName(NameStr);
1828 }
1829
1830 Value *getPointerOperand() { return getOperand(0); }
1831 const Value *getPointerOperand() const { return getOperand(0); }
1832 static unsigned getPointerOperandIndex() { return 0U; }
1833
1834 // Methods for support type inquiry through isa, cast, and dyn_cast:
1835 static bool classof(const Instruction *I) {
1836 return I->getOpcode() == VAArg;
1837 }
1838 static bool classof(const Value *V) {
1839 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1840 }
1841};
1842
1843//===----------------------------------------------------------------------===//
1844// ExtractElementInst Class
1845//===----------------------------------------------------------------------===//
1846
1847/// This instruction extracts a single (scalar)
1848/// element from a VectorType value
1849///
1850class ExtractElementInst : public Instruction {
1851 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1852 Instruction *InsertBefore = nullptr);
1853 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1854 BasicBlock *InsertAtEnd);
1855
1856protected:
1857 // Note: Instruction needs to be a friend here to call cloneImpl.
1858 friend class Instruction;
1859
1860 ExtractElementInst *cloneImpl() const;
1861
1862public:
1863 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1864 const Twine &NameStr = "",
1865 Instruction *InsertBefore = nullptr) {
1866 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1867 }
1868
1869 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1870 const Twine &NameStr,
1871 BasicBlock *InsertAtEnd) {
1872 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1873 }
1874
1875 /// Return true if an extractelement instruction can be
1876 /// formed with the specified operands.
1877 static bool isValidOperands(const Value *Vec, const Value *Idx);
1878
1879 Value *getVectorOperand() { return Op<0>(); }
1880 Value *getIndexOperand() { return Op<1>(); }
1881 const Value *getVectorOperand() const { return Op<0>(); }
1882 const Value *getIndexOperand() const { return Op<1>(); }
1883
1884 VectorType *getVectorOperandType() const {
1885 return cast<VectorType>(getVectorOperand()->getType());
1886 }
1887
1888 /// Transparently provide more efficient getOperand methods.
1889 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
;
1890
1891 // Methods for support type inquiry through isa, cast, and dyn_cast:
1892 static bool classof(const Instruction *I) {
1893 return I->getOpcode() == Instruction::ExtractElement;
1894 }
1895 static bool classof(const Value *V) {
1896 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1897 }
1898};
1899
1900template <>
1901struct OperandTraits<ExtractElementInst> :
1902 public FixedNumOperandTraits<ExtractElementInst, 2> {
1903};
1904
1905DEFINE_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 {
(static_cast <bool> (i_nocapture < OperandTraits<
ExtractElementInst>::operands(this) && "getOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1905, __extension__ __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) { (static_cast <bool> (i_nocapture
< OperandTraits<ExtractElementInst>::operands(this)
&& "setOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1905, __extension__ __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
); }
1906
1907//===----------------------------------------------------------------------===//
1908// InsertElementInst Class
1909//===----------------------------------------------------------------------===//
1910
1911/// This instruction inserts a single (scalar)
1912/// element into a VectorType value
1913///
1914class InsertElementInst : public Instruction {
1915 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1916 const Twine &NameStr = "",
1917 Instruction *InsertBefore = nullptr);
1918 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1919 BasicBlock *InsertAtEnd);
1920
1921protected:
1922 // Note: Instruction needs to be a friend here to call cloneImpl.
1923 friend class Instruction;
1924
1925 InsertElementInst *cloneImpl() const;
1926
1927public:
1928 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1929 const Twine &NameStr = "",
1930 Instruction *InsertBefore = nullptr) {
1931 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1932 }
1933
1934 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1935 const Twine &NameStr,
1936 BasicBlock *InsertAtEnd) {
1937 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1938 }
1939
1940 /// Return true if an insertelement instruction can be
1941 /// formed with the specified operands.
1942 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1943 const Value *Idx);
1944
1945 /// Overload to return most specific vector type.
1946 ///
1947 VectorType *getType() const {
1948 return cast<VectorType>(Instruction::getType());
1949 }
1950
1951 /// Transparently provide more efficient getOperand methods.
1952 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
;
1953
1954 // Methods for support type inquiry through isa, cast, and dyn_cast:
1955 static bool classof(const Instruction *I) {
1956 return I->getOpcode() == Instruction::InsertElement;
1957 }
1958 static bool classof(const Value *V) {
1959 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1960 }
1961};
1962
1963template <>
1964struct OperandTraits<InsertElementInst> :
1965 public FixedNumOperandTraits<InsertElementInst, 3> {
1966};
1967
1968DEFINE_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 { (static_cast <bool> (i_nocapture <
OperandTraits<InsertElementInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1968, __extension__ __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) { (static_cast <bool> (i_nocapture
< OperandTraits<InsertElementInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 1968, __extension__ __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
); }
1969
1970//===----------------------------------------------------------------------===//
1971// ShuffleVectorInst Class
1972//===----------------------------------------------------------------------===//
1973
1974constexpr int UndefMaskElem = -1;
1975
1976/// This instruction constructs a fixed permutation of two
1977/// input vectors.
1978///
1979/// For each element of the result vector, the shuffle mask selects an element
1980/// from one of the input vectors to copy to the result. Non-negative elements
1981/// in the mask represent an index into the concatenated pair of input vectors.
1982/// UndefMaskElem (-1) specifies that the result element is undefined.
1983///
1984/// For scalable vectors, all the elements of the mask must be 0 or -1. This
1985/// requirement may be relaxed in the future.
1986class ShuffleVectorInst : public Instruction {
1987 SmallVector<int, 4> ShuffleMask;
1988 Constant *ShuffleMaskForBitcode;
1989
1990protected:
1991 // Note: Instruction needs to be a friend here to call cloneImpl.
1992 friend class Instruction;
1993
1994 ShuffleVectorInst *cloneImpl() const;
1995
1996public:
1997 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1998 const Twine &NameStr = "",
1999 Instruction *InsertBefor = nullptr);
2000 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2001 const Twine &NameStr, BasicBlock *InsertAtEnd);
2002 ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
2003 const Twine &NameStr = "",
2004 Instruction *InsertBefor = nullptr);
2005 ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
2006 const Twine &NameStr, BasicBlock *InsertAtEnd);
2007
2008 void *operator new(size_t s) { return User::operator new(s, 2); }
2009
2010 /// Swap the operands and adjust the mask to preserve the semantics
2011 /// of the instruction.
2012 void commute();
2013
2014 /// Return true if a shufflevector instruction can be
2015 /// formed with the specified operands.
2016 static bool isValidOperands(const Value *V1, const Value *V2,
2017 const Value *Mask);
2018 static bool isValidOperands(const Value *V1, const Value *V2,
2019 ArrayRef<int> Mask);
2020
2021 /// Overload to return most specific vector type.
2022 ///
2023 VectorType *getType() const {
2024 return cast<VectorType>(Instruction::getType());
2025 }
2026
2027 /// Transparently provide more efficient getOperand methods.
2028 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
;
2029
2030 /// Return the shuffle mask value of this instruction for the given element
2031 /// index. Return UndefMaskElem if the element is undef.
2032 int getMaskValue(unsigned Elt) const { return ShuffleMask[Elt]; }
2033
2034 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2035 /// elements of the mask are returned as UndefMaskElem.
2036 static void getShuffleMask(const Constant *Mask,
2037 SmallVectorImpl<int> &Result);
2038
2039 /// Return the mask for this instruction as a vector of integers. Undefined
2040 /// elements of the mask are returned as UndefMaskElem.
2041 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2042 Result.assign(ShuffleMask.begin(), ShuffleMask.end());
2043 }
2044
2045 /// Return the mask for this instruction, for use in bitcode.
2046 ///
2047 /// TODO: This is temporary until we decide a new bitcode encoding for
2048 /// shufflevector.
2049 Constant *getShuffleMaskForBitcode() const { return ShuffleMaskForBitcode; }
2050
2051 static Constant *convertShuffleMaskForBitcode(ArrayRef<int> Mask,
2052 Type *ResultTy);
2053
2054 void setShuffleMask(ArrayRef<int> Mask);
2055
2056 ArrayRef<int> getShuffleMask() const { return ShuffleMask; }
2057
2058 /// Return true if this shuffle returns a vector with a different number of
2059 /// elements than its source vectors.
2060 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2061 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2062 bool changesLength() const {
2063 unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType())
2064 ->getElementCount()
2065 .getKnownMinValue();
2066 unsigned NumMaskElts = ShuffleMask.size();
2067 return NumSourceElts != NumMaskElts;
2068 }
2069
2070 /// Return true if this shuffle returns a vector with a greater number of
2071 /// elements than its source vectors.
2072 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2073 bool increasesLength() const {
2074 unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType())
2075 ->getElementCount()
2076 .getKnownMinValue();
2077 unsigned NumMaskElts = ShuffleMask.size();
2078 return NumSourceElts < NumMaskElts;
2079 }
2080
2081 /// Return true if this shuffle mask chooses elements from exactly one source
2082 /// vector.
2083 /// Example: <7,5,undef,7>
2084 /// This assumes that vector operands are the same length as the mask.
2085 static bool isSingleSourceMask(ArrayRef<int> Mask);
2086 static bool isSingleSourceMask(const Constant *Mask) {
2087 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy(
) && "Shuffle needs vector constant.") ? void (0) : __assert_fail
("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2087, __extension__ __PRETTY_FUNCTION__))
;
2088 SmallVector<int, 16> MaskAsInts;
2089 getShuffleMask(Mask, MaskAsInts);
2090 return isSingleSourceMask(MaskAsInts);
2091 }
2092
2093 /// Return true if this shuffle chooses elements from exactly one source
2094 /// vector without changing the length of that vector.
2095 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2096 /// TODO: Optionally allow length-changing shuffles.
2097 bool isSingleSource() const {
2098 return !changesLength() && isSingleSourceMask(ShuffleMask);
2099 }
2100
2101 /// Return true if this shuffle mask chooses elements from exactly one source
2102 /// vector without lane crossings. A shuffle using this mask is not
2103 /// necessarily a no-op because it may change the number of elements from its
2104 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2105 /// Example: <undef,undef,2,3>
2106 static bool isIdentityMask(ArrayRef<int> Mask);
2107 static bool isIdentityMask(const Constant *Mask) {
2108 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy(
) && "Shuffle needs vector constant.") ? void (0) : __assert_fail
("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2108, __extension__ __PRETTY_FUNCTION__))
;
2109 SmallVector<int, 16> MaskAsInts;
2110 getShuffleMask(Mask, MaskAsInts);
2111 return isIdentityMask(MaskAsInts);
2112 }
2113
2114 /// Return true if this shuffle chooses elements from exactly one source
2115 /// vector without lane crossings and does not change the number of elements
2116 /// from its input vectors.
2117 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2118 bool isIdentity() const {
2119 return !changesLength() && isIdentityMask(ShuffleMask);
2120 }
2121
2122 /// Return true if this shuffle lengthens exactly one source vector with
2123 /// undefs in the high elements.
2124 bool isIdentityWithPadding() const;
2125
2126 /// Return true if this shuffle extracts the first N elements of exactly one
2127 /// source vector.
2128 bool isIdentityWithExtract() const;
2129
2130 /// Return true if this shuffle concatenates its 2 source vectors. This
2131 /// returns false if either input is undefined. In that case, the shuffle is
2132 /// is better classified as an identity with padding operation.
2133 bool isConcat() const;
2134
2135 /// Return true if this shuffle mask chooses elements from its source vectors
2136 /// without lane crossings. A shuffle using this mask would be
2137 /// equivalent to a vector select with a constant condition operand.
2138 /// Example: <4,1,6,undef>
2139 /// This returns false if the mask does not choose from both input vectors.
2140 /// In that case, the shuffle is better classified as an identity shuffle.
2141 /// This assumes that vector operands are the same length as the mask
2142 /// (a length-changing shuffle can never be equivalent to a vector select).
2143 static bool isSelectMask(ArrayRef<int> Mask);
2144 static bool isSelectMask(const Constant *Mask) {
2145 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy(
) && "Shuffle needs vector constant.") ? void (0) : __assert_fail
("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2145, __extension__ __PRETTY_FUNCTION__))
;
2146 SmallVector<int, 16> MaskAsInts;
2147 getShuffleMask(Mask, MaskAsInts);
2148 return isSelectMask(MaskAsInts);
2149 }
2150
2151 /// Return true if this shuffle chooses elements from its source vectors
2152 /// without lane crossings and all operands have the same number of elements.
2153 /// In other words, this shuffle is equivalent to a vector select with a
2154 /// constant condition operand.
2155 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2156 /// This returns false if the mask does not choose from both input vectors.
2157 /// In that case, the shuffle is better classified as an identity shuffle.
2158 /// TODO: Optionally allow length-changing shuffles.
2159 bool isSelect() const {
2160 return !changesLength() && isSelectMask(ShuffleMask);
2161 }
2162
2163 /// Return true if this shuffle mask swaps the order of elements from exactly
2164 /// one source vector.
2165 /// Example: <7,6,undef,4>
2166 /// This assumes that vector operands are the same length as the mask.
2167 static bool isReverseMask(ArrayRef<int> Mask);
2168 static bool isReverseMask(const Constant *Mask) {
2169 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy(
) && "Shuffle needs vector constant.") ? void (0) : __assert_fail
("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2169, __extension__ __PRETTY_FUNCTION__))
;
2170 SmallVector<int, 16> MaskAsInts;
2171 getShuffleMask(Mask, MaskAsInts);
2172 return isReverseMask(MaskAsInts);
2173 }
2174
2175 /// Return true if this shuffle swaps the order of elements from exactly
2176 /// one source vector.
2177 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2178 /// TODO: Optionally allow length-changing shuffles.
2179 bool isReverse() const {
2180 return !changesLength() && isReverseMask(ShuffleMask);
2181 }
2182
2183 /// Return true if this shuffle mask chooses all elements with the same value
2184 /// as the first element of exactly one source vector.
2185 /// Example: <4,undef,undef,4>
2186 /// This assumes that vector operands are the same length as the mask.
2187 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2188 static bool isZeroEltSplatMask(const Constant *Mask) {
2189 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy(
) && "Shuffle needs vector constant.") ? void (0) : __assert_fail
("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2189, __extension__ __PRETTY_FUNCTION__))
;
2190 SmallVector<int, 16> MaskAsInts;
2191 getShuffleMask(Mask, MaskAsInts);
2192 return isZeroEltSplatMask(MaskAsInts);
2193 }
2194
2195 /// Return true if all elements of this shuffle are the same value as the
2196 /// first element of exactly one source vector without changing the length
2197 /// of that vector.
2198 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2199 /// TODO: Optionally allow length-changing shuffles.
2200 /// TODO: Optionally allow splats from other elements.
2201 bool isZeroEltSplat() const {
2202 return !changesLength() && isZeroEltSplatMask(ShuffleMask);
2203 }
2204
2205 /// Return true if this shuffle mask is a transpose mask.
2206 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2207 /// even- or odd-numbered vector elements from two n-dimensional source
2208 /// vectors and write each result into consecutive elements of an
2209 /// n-dimensional destination vector. Two shuffles are necessary to complete
2210 /// the transpose, one for the even elements and another for the odd elements.
2211 /// This description closely follows how the TRN1 and TRN2 AArch64
2212 /// instructions operate.
2213 ///
2214 /// For example, a simple 2x2 matrix can be transposed with:
2215 ///
2216 /// ; Original matrix
2217 /// m0 = < a, b >
2218 /// m1 = < c, d >
2219 ///
2220 /// ; Transposed matrix
2221 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2222 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2223 ///
2224 /// For matrices having greater than n columns, the resulting nx2 transposed
2225 /// matrix is stored in two result vectors such that one vector contains
2226 /// interleaved elements from all the even-numbered rows and the other vector
2227 /// contains interleaved elements from all the odd-numbered rows. For example,
2228 /// a 2x4 matrix can be transposed with:
2229 ///
2230 /// ; Original matrix
2231 /// m0 = < a, b, c, d >
2232 /// m1 = < e, f, g, h >
2233 ///
2234 /// ; Transposed matrix
2235 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2236 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2237 static bool isTransposeMask(ArrayRef<int> Mask);
2238 static bool isTransposeMask(const Constant *Mask) {
2239 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy(
) && "Shuffle needs vector constant.") ? void (0) : __assert_fail
("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2239, __extension__ __PRETTY_FUNCTION__))
;
2240 SmallVector<int, 16> MaskAsInts;
2241 getShuffleMask(Mask, MaskAsInts);
2242 return isTransposeMask(MaskAsInts);
2243 }
2244
2245 /// Return true if this shuffle transposes the elements of its inputs without
2246 /// changing the length of the vectors. This operation may also be known as a
2247 /// merge or interleave. See the description for isTransposeMask() for the
2248 /// exact specification.
2249 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2250 bool isTranspose() const {
2251 return !changesLength() && isTransposeMask(ShuffleMask);
2252 }
2253
2254 /// Return true if this shuffle mask is an extract subvector mask.
2255 /// A valid extract subvector mask returns a smaller vector from a single
2256 /// source operand. The base extraction index is returned as well.
2257 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2258 int &Index);
2259 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2260 int &Index) {
2261 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy(
) && "Shuffle needs vector constant.") ? void (0) : __assert_fail
("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2261, __extension__ __PRETTY_FUNCTION__))
;
2262 // Not possible to express a shuffle mask for a scalable vector for this
2263 // case.
2264 if (isa<ScalableVectorType>(Mask->getType()))
2265 return false;
2266 SmallVector<int, 16> MaskAsInts;
2267 getShuffleMask(Mask, MaskAsInts);
2268 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2269 }
2270
2271 /// Return true if this shuffle mask is an extract subvector mask.
2272 bool isExtractSubvectorMask(int &Index) const {
2273 // Not possible to express a shuffle mask for a scalable vector for this
2274 // case.
2275 if (isa<ScalableVectorType>(getType()))
2276 return false;
2277
2278 int NumSrcElts =
2279 cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2280 return isExtractSubvectorMask(ShuffleMask, NumSrcElts, Index);
2281 }
2282
2283 /// Change values in a shuffle permute mask assuming the two vector operands
2284 /// of length InVecNumElts have swapped position.
2285 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2286 unsigned InVecNumElts) {
2287 for (int &Idx : Mask) {
2288 if (Idx == -1)
2289 continue;
2290 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2291 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&(static_cast <bool> (Idx >= 0 && Idx < (int
)InVecNumElts * 2 && "shufflevector mask index out of range"
) ? void (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2292, __extension__ __PRETTY_FUNCTION__))
2292 "shufflevector mask index out of range")(static_cast <bool> (Idx >= 0 && Idx < (int
)InVecNumElts * 2 && "shufflevector mask index out of range"
) ? void (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2292, __extension__ __PRETTY_FUNCTION__))
;
2293 }
2294 }
2295
2296 // Methods for support type inquiry through isa, cast, and dyn_cast:
2297 static bool classof(const Instruction *I) {
2298 return I->getOpcode() == Instruction::ShuffleVector;
2299 }
2300 static bool classof(const Value *V) {
2301 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2302 }
2303};
2304
2305template <>
2306struct OperandTraits<ShuffleVectorInst>
2307 : public FixedNumOperandTraits<ShuffleVectorInst, 2> {};
2308
2309DEFINE_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 { (static_cast <bool> (i_nocapture <
OperandTraits<ShuffleVectorInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2309, __extension__ __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) { (static_cast <bool> (i_nocapture
< OperandTraits<ShuffleVectorInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2309, __extension__ __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
); }
2310
2311//===----------------------------------------------------------------------===//
2312// ExtractValueInst Class
2313//===----------------------------------------------------------------------===//
2314
2315/// This instruction extracts a struct member or array
2316/// element value from an aggregate value.
2317///
2318class ExtractValueInst : public UnaryInstruction {
2319 SmallVector<unsigned, 4> Indices;
2320
2321 ExtractValueInst(const ExtractValueInst &EVI);
2322
2323 /// Constructors - Create a extractvalue instruction with a base aggregate
2324 /// value and a list of indices. The first ctor can optionally insert before
2325 /// an existing instruction, the second appends the new instruction to the
2326 /// specified BasicBlock.
2327 inline ExtractValueInst(Value *Agg,
2328 ArrayRef<unsigned> Idxs,
2329 const Twine &NameStr,
2330 Instruction *InsertBefore);
2331 inline ExtractValueInst(Value *Agg,
2332 ArrayRef<unsigned> Idxs,
2333 const Twine &NameStr, BasicBlock *InsertAtEnd);
2334
2335 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2336
2337protected:
2338 // Note: Instruction needs to be a friend here to call cloneImpl.
2339 friend class Instruction;
2340
2341 ExtractValueInst *cloneImpl() const;
2342
2343public:
2344 static ExtractValueInst *Create(Value *Agg,
2345 ArrayRef<unsigned> Idxs,
2346 const Twine &NameStr = "",
2347 Instruction *InsertBefore = nullptr) {
2348 return new
2349 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2350 }
2351
2352 static ExtractValueInst *Create(Value *Agg,
2353 ArrayRef<unsigned> Idxs,
2354 const Twine &NameStr,
2355 BasicBlock *InsertAtEnd) {
2356 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2357 }
2358
2359 /// Returns the type of the element that would be extracted
2360 /// with an extractvalue instruction with the specified parameters.
2361 ///
2362 /// Null is returned if the indices are invalid for the specified type.
2363 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2364
2365 using idx_iterator = const unsigned*;
2366
2367 inline idx_iterator idx_begin() const { return Indices.begin(); }
2368 inline idx_iterator idx_end() const { return Indices.end(); }
2369 inline iterator_range<idx_iterator> indices() const {
2370 return make_range(idx_begin(), idx_end());
2371 }
2372
2373 Value *getAggregateOperand() {
2374 return getOperand(0);
2375 }
2376 const Value *getAggregateOperand() const {
2377 return getOperand(0);
2378 }
2379 static unsigned getAggregateOperandIndex() {
2380 return 0U; // get index for modifying correct operand
2381 }
2382
2383 ArrayRef<unsigned> getIndices() const {
2384 return Indices;
2385 }
2386
2387 unsigned getNumIndices() const {
2388 return (unsigned)Indices.size();
2389 }
2390
2391 bool hasIndices() const {
2392 return true;
2393 }
2394
2395 // Methods for support type inquiry through isa, cast, and dyn_cast:
2396 static bool classof(const Instruction *I) {
2397 return I->getOpcode() == Instruction::ExtractValue;
2398 }
2399 static bool classof(const Value *V) {
2400 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2401 }
2402};
2403
2404ExtractValueInst::ExtractValueInst(Value *Agg,
2405 ArrayRef<unsigned> Idxs,
2406 const Twine &NameStr,
2407 Instruction *InsertBefore)
2408 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2409 ExtractValue, Agg, InsertBefore) {
2410 init(Idxs, NameStr);
2411}
2412
2413ExtractValueInst::ExtractValueInst(Value *Agg,
2414 ArrayRef<unsigned> Idxs,
2415 const Twine &NameStr,
2416 BasicBlock *InsertAtEnd)
2417 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2418 ExtractValue, Agg, InsertAtEnd) {
2419 init(Idxs, NameStr);
2420}
2421
2422//===----------------------------------------------------------------------===//
2423// InsertValueInst Class
2424//===----------------------------------------------------------------------===//
2425
2426/// This instruction inserts a struct field of array element
2427/// value into an aggregate value.
2428///
2429class InsertValueInst : public Instruction {
2430 SmallVector<unsigned, 4> Indices;
2431
2432 InsertValueInst(const InsertValueInst &IVI);
2433
2434 /// Constructors - Create a insertvalue instruction with a base aggregate
2435 /// value, a value to insert, and a list of indices. The first ctor can
2436 /// optionally insert before an existing instruction, the second appends
2437 /// the new instruction to the specified BasicBlock.
2438 inline InsertValueInst(Value *Agg, Value *Val,
2439 ArrayRef<unsigned> Idxs,
2440 const Twine &NameStr,
2441 Instruction *InsertBefore);
2442 inline InsertValueInst(Value *Agg, Value *Val,
2443 ArrayRef<unsigned> Idxs,
2444 const Twine &NameStr, BasicBlock *InsertAtEnd);
2445
2446 /// Constructors - These two constructors are convenience methods because one
2447 /// and two index insertvalue instructions are so common.
2448 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2449 const Twine &NameStr = "",
2450 Instruction *InsertBefore = nullptr);
2451 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2452 BasicBlock *InsertAtEnd);
2453
2454 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2455 const Twine &NameStr);
2456
2457protected:
2458 // Note: Instruction needs to be a friend here to call cloneImpl.
2459 friend class Instruction;
2460
2461 InsertValueInst *cloneImpl() const;
2462
2463public:
2464 // allocate space for exactly two operands
2465 void *operator new(size_t s) {
2466 return User::operator new(s, 2);
2467 }
2468
2469 static InsertValueInst *Create(Value *Agg, Value *Val,
2470 ArrayRef<unsigned> Idxs,
2471 const Twine &NameStr = "",
2472 Instruction *InsertBefore = nullptr) {
2473 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2474 }
2475
2476 static InsertValueInst *Create(Value *Agg, Value *Val,
2477 ArrayRef<unsigned> Idxs,
2478 const Twine &NameStr,
2479 BasicBlock *InsertAtEnd) {
2480 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2481 }
2482
2483 /// Transparently provide more efficient getOperand methods.
2484 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
;
2485
2486 using idx_iterator = const unsigned*;
2487
2488 inline idx_iterator idx_begin() const { return Indices.begin(); }
2489 inline idx_iterator idx_end() const { return Indices.end(); }
2490 inline iterator_range<idx_iterator> indices() const {
2491 return make_range(idx_begin(), idx_end());
2492 }
2493
2494 Value *getAggregateOperand() {
2495 return getOperand(0);
2496 }
2497 const Value *getAggregateOperand() const {
2498 return getOperand(0);
2499 }
2500 static unsigned getAggregateOperandIndex() {
2501 return 0U; // get index for modifying correct operand
2502 }
2503
2504 Value *getInsertedValueOperand() {
2505 return getOperand(1);
2506 }
2507 const Value *getInsertedValueOperand() const {
2508 return getOperand(1);
2509 }
2510 static unsigned getInsertedValueOperandIndex() {
2511 return 1U; // get index for modifying correct operand
2512 }
2513
2514 ArrayRef<unsigned> getIndices() const {
2515 return Indices;
2516 }
2517
2518 unsigned getNumIndices() const {
2519 return (unsigned)Indices.size();
2520 }
2521
2522 bool hasIndices() const {
2523 return true;
2524 }
2525
2526 // Methods for support type inquiry through isa, cast, and dyn_cast:
2527 static bool classof(const Instruction *I) {
2528 return I->getOpcode() == Instruction::InsertValue;
2529 }
2530 static bool classof(const Value *V) {
2531 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2532 }
2533};
2534
2535template <>
2536struct OperandTraits<InsertValueInst> :
2537 public FixedNumOperandTraits<InsertValueInst, 2> {
2538};
2539
2540InsertValueInst::InsertValueInst(Value *Agg,
2541 Value *Val,
2542 ArrayRef<unsigned> Idxs,
2543 const Twine &NameStr,
2544 Instruction *InsertBefore)
2545 : Instruction(Agg->getType(), InsertValue,
2546 OperandTraits<InsertValueInst>::op_begin(this),
2547 2, InsertBefore) {
2548 init(Agg, Val, Idxs, NameStr);
2549}
2550
2551InsertValueInst::InsertValueInst(Value *Agg,
2552 Value *Val,
2553 ArrayRef<unsigned> Idxs,
2554 const Twine &NameStr,
2555 BasicBlock *InsertAtEnd)
2556 : Instruction(Agg->getType(), InsertValue,
2557 OperandTraits<InsertValueInst>::op_begin(this),
2558 2, InsertAtEnd) {
2559 init(Agg, Val, Idxs, NameStr);
2560}
2561
2562DEFINE_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 { (static_cast <bool
> (i_nocapture < OperandTraits<InsertValueInst>::
operands(this) && "getOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2562, __extension__ __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) { (static_cast <bool> (i_nocapture <
OperandTraits<InsertValueInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2562, __extension__ __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); }
2563
2564//===----------------------------------------------------------------------===//
2565// PHINode Class
2566//===----------------------------------------------------------------------===//
2567
2568// PHINode - The PHINode class is used to represent the magical mystical PHI
2569// node, that can not exist in nature, but can be synthesized in a computer
2570// scientist's overactive imagination.
2571//
2572class PHINode : public Instruction {
2573 /// The number of operands actually allocated. NumOperands is
2574 /// the number actually in use.
2575 unsigned ReservedSpace;
2576
2577 PHINode(const PHINode &PN);
2578
2579 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2580 const Twine &NameStr = "",
2581 Instruction *InsertBefore = nullptr)
2582 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2583 ReservedSpace(NumReservedValues) {
2584 assert(!Ty->isTokenTy() && "PHI nodes cannot have token type!")(static_cast <bool> (!Ty->isTokenTy() && "PHI nodes cannot have token type!"
) ? void (0) : __assert_fail ("!Ty->isTokenTy() && \"PHI nodes cannot have token type!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2584, __extension__ __PRETTY_FUNCTION__))
;
2585 setName(NameStr);
2586 allocHungoffUses(ReservedSpace);
2587 }
2588
2589 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2590 BasicBlock *InsertAtEnd)
2591 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2592 ReservedSpace(NumReservedValues) {
2593 assert(!Ty->isTokenTy() && "PHI nodes cannot have token type!")(static_cast <bool> (!Ty->isTokenTy() && "PHI nodes cannot have token type!"
) ? void (0) : __assert_fail ("!Ty->isTokenTy() && \"PHI nodes cannot have token type!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2593, __extension__ __PRETTY_FUNCTION__))
;
2594 setName(NameStr);
2595 allocHungoffUses(ReservedSpace);
2596 }
2597
2598protected:
2599 // Note: Instruction needs to be a friend here to call cloneImpl.
2600 friend class Instruction;
2601
2602 PHINode *cloneImpl() const;
2603
2604 // allocHungoffUses - this is more complicated than the generic
2605 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2606 // values and pointers to the incoming blocks, all in one allocation.
2607 void allocHungoffUses(unsigned N) {
2608 User::allocHungoffUses(N, /* IsPhi */ true);
2609 }
2610
2611public:
2612 /// Constructors - NumReservedValues is a hint for the number of incoming
2613 /// edges that this phi node will have (use 0 if you really have no idea).
2614 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2615 const Twine &NameStr = "",
2616 Instruction *InsertBefore = nullptr) {
2617 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2618 }
2619
2620 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2621 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2622 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2623 }
2624
2625 /// Provide fast operand accessors
2626 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
;
2627
2628 // Block iterator interface. This provides access to the list of incoming
2629 // basic blocks, which parallels the list of incoming values.
2630
2631 using block_iterator = BasicBlock **;
2632 using const_block_iterator = BasicBlock * const *;
2633
2634 block_iterator block_begin() {
2635 return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
2636 }
2637
2638 const_block_iterator block_begin() const {
2639 return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
2640 }
2641
2642 block_iterator block_end() {
2643 return block_begin() + getNumOperands();
2644 }
2645
2646 const_block_iterator block_end() const {
2647 return block_begin() + getNumOperands();
2648 }
2649
2650 iterator_range<block_iterator> blocks() {
2651 return make_range(block_begin(), block_end());
2652 }
2653
2654 iterator_range<const_block_iterator> blocks() const {
2655 return make_range(block_begin(), block_end());
2656 }
2657
2658 op_range incoming_values() { return operands(); }
2659
2660 const_op_range incoming_values() const { return operands(); }
2661
2662 /// Return the number of incoming edges
2663 ///
2664 unsigned getNumIncomingValues() const { return getNumOperands(); }
2665
2666 /// Return incoming value number x
2667 ///
2668 Value *getIncomingValue(unsigned i) const {
2669 return getOperand(i);
2670 }
2671 void setIncomingValue(unsigned i, Value *V) {
2672 assert(V && "PHI node got a null value!")(static_cast <bool> (V && "PHI node got a null value!"
) ? void (0) : __assert_fail ("V && \"PHI node got a null value!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2672, __extension__ __PRETTY_FUNCTION__))
;
2673 assert(getType() == V->getType() &&(static_cast <bool> (getType() == V->getType() &&
"All operands to PHI node must be the same type as the PHI node!"
) ? 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-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2674, __extension__ __PRETTY_FUNCTION__))
2674 "All operands to PHI node must be the same type as the PHI node!")(static_cast <bool> (getType() == V->getType() &&
"All operands to PHI node must be the same type as the PHI node!"
) ? 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-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2674, __extension__ __PRETTY_FUNCTION__))
;
2675 setOperand(i, V);
2676 }
2677
2678 static unsigned getOperandNumForIncomingValue(unsigned i) {
2679 return i;
2680 }
2681
2682 static unsigned getIncomingValueNumForOperand(unsigned i) {
2683 return i;
2684 }
2685
2686 /// Return incoming basic block number @p i.
2687 ///
2688 BasicBlock *getIncomingBlock(unsigned i) const {
2689 return block_begin()[i];
2690 }
2691
2692 /// Return incoming basic block corresponding
2693 /// to an operand of the PHI.
2694 ///
2695 BasicBlock *getIncomingBlock(const Use &U) const {
2696 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")(static_cast <bool> (this == U.getUser() && "Iterator doesn't point to PHI's Uses?"
) ? void (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2696, __extension__ __PRETTY_FUNCTION__))
;
2697 return getIncomingBlock(unsigned(&U - op_begin()));
2698 }
2699
2700 /// Return incoming basic block corresponding
2701 /// to value use iterator.
2702 ///
2703 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2704 return getIncomingBlock(I.getUse());
2705 }
2706
2707 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2708 assert(BB && "PHI node got a null basic block!")(static_cast <bool> (BB && "PHI node got a null basic block!"
) ? void (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2708, __extension__ __PRETTY_FUNCTION__))
;
2709 block_begin()[i] = BB;
2710 }
2711
2712 /// Replace every incoming basic block \p Old to basic block \p New.
2713 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
2714 assert(New && Old && "PHI node got a null basic block!")(static_cast <bool> (New && Old && "PHI node got a null basic block!"
) ? void (0) : __assert_fail ("New && Old && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2714, __extension__ __PRETTY_FUNCTION__))
;
2715 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2716 if (getIncomingBlock(Op) == Old)
2717 setIncomingBlock(Op, New);
2718 }
2719
2720 /// Add an incoming value to the end of the PHI list
2721 ///
2722 void addIncoming(Value *V, BasicBlock *BB) {
2723 if (getNumOperands() == ReservedSpace)
2724 growOperands(); // Get more space!
2725 // Initialize some new operands.
2726 setNumHungOffUseOperands(getNumOperands() + 1);
2727 setIncomingValue(getNumOperands() - 1, V);
2728 setIncomingBlock(getNumOperands() - 1, BB);
2729 }
2730
2731 /// Remove an incoming value. This is useful if a
2732 /// predecessor basic block is deleted. The value removed is returned.
2733 ///
2734 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2735 /// is true), the PHI node is destroyed and any uses of it are replaced with
2736 /// dummy values. The only time there should be zero incoming values to a PHI
2737 /// node is when the block is dead, so this strategy is sound.
2738 ///
2739 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2740
2741 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2742 int Idx = getBasicBlockIndex(BB);
2743 assert(Idx >= 0 && "Invalid basic block argument to remove!")(static_cast <bool> (Idx >= 0 && "Invalid basic block argument to remove!"
) ? void (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument to remove!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2743, __extension__ __PRETTY_FUNCTION__))
;
2744 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2745 }
2746
2747 /// Return the first index of the specified basic
2748 /// block in the value list for this PHI. Returns -1 if no instance.
2749 ///
2750 int getBasicBlockIndex(const BasicBlock *BB) const {
2751 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2752 if (block_begin()[i] == BB)
2753 return i;
2754 return -1;
2755 }
2756
2757 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2758 int Idx = getBasicBlockIndex(BB);
2759 assert(Idx >= 0 && "Invalid basic block argument!")(static_cast <bool> (Idx >= 0 && "Invalid basic block argument!"
) ? void (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2759, __extension__ __PRETTY_FUNCTION__))
;
2760 return getIncomingValue(Idx);
2761 }
2762
2763 /// Set every incoming value(s) for block \p BB to \p V.
2764 void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
2765 assert(BB && "PHI node got a null basic block!")(static_cast <bool> (BB && "PHI node got a null basic block!"
) ? void (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2765, __extension__ __PRETTY_FUNCTION__))
;
2766 bool Found = false;
2767 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2768 if (getIncomingBlock(Op) == BB) {
2769 Found = true;
2770 setIncomingValue(Op, V);
2771 }
2772 (void)Found;
2773 assert(Found && "Invalid basic block argument to set!")(static_cast <bool> (Found && "Invalid basic block argument to set!"
) ? void (0) : __assert_fail ("Found && \"Invalid basic block argument to set!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2773, __extension__ __PRETTY_FUNCTION__))
;
2774 }
2775
2776 /// If the specified PHI node always merges together the
2777 /// same value, return the value, otherwise return null.
2778 Value *hasConstantValue() const;
2779
2780 /// Whether the specified PHI node always merges
2781 /// together the same value, assuming undefs are equal to a unique
2782 /// non-undef value.
2783 bool hasConstantOrUndefValue() const;
2784
2785 /// If the PHI node is complete which means all of its parent's predecessors
2786 /// have incoming value in this PHI, return true, otherwise return false.
2787 bool isComplete() const {
2788 return llvm::all_of(predecessors(getParent()),
2789 [this](const BasicBlock *Pred) {
2790 return getBasicBlockIndex(Pred) >= 0;
2791 });
2792 }
2793
2794 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2795 static bool classof(const Instruction *I) {
2796 return I->getOpcode() == Instruction::PHI;
2797 }
2798 static bool classof(const Value *V) {
2799 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2800 }
2801
2802private:
2803 void growOperands();
2804};
2805
2806template <>
2807struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2808};
2809
2810DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)PHINode::op_iterator PHINode::op_begin() { return OperandTraits
<PHINode>::op_begin(this); } PHINode::const_op_iterator
PHINode::op_begin() const { return OperandTraits<PHINode>
::op_begin(const_cast<PHINode*>(this)); } PHINode::op_iterator
PHINode::op_end() { return OperandTraits<PHINode>::op_end
(this); } PHINode::const_op_iterator PHINode::op_end() const {
return OperandTraits<PHINode>::op_end(const_cast<PHINode
*>(this)); } Value *PHINode::getOperand(unsigned i_nocapture
) const { (static_cast <bool> (i_nocapture < OperandTraits
<PHINode>::operands(this) && "getOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2810, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<PHINode>::op_begin(const_cast
<PHINode*>(this))[i_nocapture].get()); } void PHINode::
setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<PHINode>::
operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2810, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
PHINode>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
PHINode::getNumOperands() const { return OperandTraits<PHINode
>::operands(this); } template <int Idx_nocapture> Use
&PHINode::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
PHINode::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
2811
2812//===----------------------------------------------------------------------===//
2813// LandingPadInst Class
2814//===----------------------------------------------------------------------===//
2815
2816//===---------------------------------------------------------------------------
2817/// The landingpad instruction holds all of the information
2818/// necessary to generate correct exception handling. The landingpad instruction
2819/// cannot be moved from the top of a landing pad block, which itself is
2820/// accessible only from the 'unwind' edge of an invoke. This uses the
2821/// SubclassData field in Value to store whether or not the landingpad is a
2822/// cleanup.
2823///
2824class LandingPadInst : public Instruction {
2825 using CleanupField = BoolBitfieldElementT<0>;
2826
2827 /// The number of operands actually allocated. NumOperands is
2828 /// the number actually in use.
2829 unsigned ReservedSpace;
2830
2831 LandingPadInst(const LandingPadInst &LP);
2832
2833public:
2834 enum ClauseType { Catch, Filter };
2835
2836private:
2837 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2838 const Twine &NameStr, Instruction *InsertBefore);
2839 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2840 const Twine &NameStr, BasicBlock *InsertAtEnd);
2841
2842 // Allocate space for exactly zero operands.
2843 void *operator new(size_t s) {
2844 return User::operator new(s);
2845 }
2846
2847 void growOperands(unsigned Size);
2848 void init(unsigned NumReservedValues, const Twine &NameStr);
2849
2850protected:
2851 // Note: Instruction needs to be a friend here to call cloneImpl.
2852 friend class Instruction;
2853
2854 LandingPadInst *cloneImpl() const;
2855
2856public:
2857 /// Constructors - NumReservedClauses is a hint for the number of incoming
2858 /// clauses that this landingpad will have (use 0 if you really have no idea).
2859 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2860 const Twine &NameStr = "",
2861 Instruction *InsertBefore = nullptr);
2862 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2863 const Twine &NameStr, BasicBlock *InsertAtEnd);
2864
2865 /// Provide fast operand accessors
2866 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
;
2867
2868 /// Return 'true' if this landingpad instruction is a
2869 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2870 /// doesn't catch the exception.
2871 bool isCleanup() const { return getSubclassData<CleanupField>(); }
2872
2873 /// Indicate that this landingpad instruction is a cleanup.
2874 void setCleanup(bool V) { setSubclassData<CleanupField>(V); }
2875
2876 /// Add a catch or filter clause to the landing pad.
2877 void addClause(Constant *ClauseVal);
2878
2879 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2880 /// determine what type of clause this is.
2881 Constant *getClause(unsigned Idx) const {
2882 return cast<Constant>(getOperandList()[Idx]);
2883 }
2884
2885 /// Return 'true' if the clause and index Idx is a catch clause.
2886 bool isCatch(unsigned Idx) const {
2887 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2888 }
2889
2890 /// Return 'true' if the clause and index Idx is a filter clause.
2891 bool isFilter(unsigned Idx) const {
2892 return isa<ArrayType>(getOperandList()[Idx]->getType());
2893 }
2894
2895 /// Get the number of clauses for this landing pad.
2896 unsigned getNumClauses() const { return getNumOperands(); }
2897
2898 /// Grow the size of the operand list to accommodate the new
2899 /// number of clauses.
2900 void reserveClauses(unsigned Size) { growOperands(Size); }
2901
2902 // Methods for support type inquiry through isa, cast, and dyn_cast:
2903 static bool classof(const Instruction *I) {
2904 return I->getOpcode() == Instruction::LandingPad;
2905 }
2906 static bool classof(const Value *V) {
2907 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2908 }
2909};
2910
2911template <>
2912struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2913};
2914
2915DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)LandingPadInst::op_iterator LandingPadInst::op_begin() { return
OperandTraits<LandingPadInst>::op_begin(this); } LandingPadInst
::const_op_iterator LandingPadInst::op_begin() const { return
OperandTraits<LandingPadInst>::op_begin(const_cast<
LandingPadInst*>(this)); } LandingPadInst::op_iterator LandingPadInst
::op_end() { return OperandTraits<LandingPadInst>::op_end
(this); } LandingPadInst::const_op_iterator LandingPadInst::op_end
() const { return OperandTraits<LandingPadInst>::op_end
(const_cast<LandingPadInst*>(this)); } Value *LandingPadInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<LandingPadInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2915, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<LandingPadInst>::op_begin(
const_cast<LandingPadInst*>(this))[i_nocapture].get());
} void LandingPadInst::setOperand(unsigned i_nocapture, Value
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<LandingPadInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2915, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
LandingPadInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned LandingPadInst::getNumOperands() const { return OperandTraits
<LandingPadInst>::operands(this); } template <int Idx_nocapture
> Use &LandingPadInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &LandingPadInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
2916
2917//===----------------------------------------------------------------------===//
2918// ReturnInst Class
2919//===----------------------------------------------------------------------===//
2920
2921//===---------------------------------------------------------------------------
2922/// Return a value (possibly void), from a function. Execution
2923/// does not continue in this function any longer.
2924///
2925class ReturnInst : public Instruction {
2926 ReturnInst(const ReturnInst &RI);
2927
2928private:
2929 // ReturnInst constructors:
2930 // ReturnInst() - 'ret void' instruction
2931 // ReturnInst( null) - 'ret void' instruction
2932 // ReturnInst(Value* X) - 'ret X' instruction
2933 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2934 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2935 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2936 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2937 //
2938 // NOTE: If the Value* passed is of type void then the constructor behaves as
2939 // if it was passed NULL.
2940 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2941 Instruction *InsertBefore = nullptr);
2942 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2943 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2944
2945protected:
2946 // Note: Instruction needs to be a friend here to call cloneImpl.
2947 friend class Instruction;
2948
2949 ReturnInst *cloneImpl() const;
2950
2951public:
2952 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2953 Instruction *InsertBefore = nullptr) {
2954 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2955 }
2956
2957 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2958 BasicBlock *InsertAtEnd) {
2959 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2960 }
2961
2962 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2963 return new(0) ReturnInst(C, InsertAtEnd);
2964 }
2965
2966 /// Provide fast operand accessors
2967 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
;
2968
2969 /// Convenience accessor. Returns null if there is no return value.
2970 Value *getReturnValue() const {
2971 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2972 }
2973
2974 unsigned getNumSuccessors() const { return 0; }
2975
2976 // Methods for support type inquiry through isa, cast, and dyn_cast:
2977 static bool classof(const Instruction *I) {
2978 return (I->getOpcode() == Instruction::Ret);
2979 }
2980 static bool classof(const Value *V) {
2981 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2982 }
2983
2984private:
2985 BasicBlock *getSuccessor(unsigned idx) const {
2986 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2986)
;
2987 }
2988
2989 void setSuccessor(unsigned idx, BasicBlock *B) {
2990 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2990)
;
2991 }
2992};
2993
2994template <>
2995struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2996};
2997
2998DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)ReturnInst::op_iterator ReturnInst::op_begin() { return OperandTraits
<ReturnInst>::op_begin(this); } ReturnInst::const_op_iterator
ReturnInst::op_begin() const { return OperandTraits<ReturnInst
>::op_begin(const_cast<ReturnInst*>(this)); } ReturnInst
::op_iterator ReturnInst::op_end() { return OperandTraits<
ReturnInst>::op_end(this); } ReturnInst::const_op_iterator
ReturnInst::op_end() const { return OperandTraits<ReturnInst
>::op_end(const_cast<ReturnInst*>(this)); } Value *ReturnInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<ReturnInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2998, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<ReturnInst>::op_begin(const_cast
<ReturnInst*>(this))[i_nocapture].get()); } void ReturnInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<ReturnInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 2998, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
ReturnInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned ReturnInst::getNumOperands() const { return OperandTraits
<ReturnInst>::operands(this); } template <int Idx_nocapture
> Use &ReturnInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
ReturnInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
2999
3000//===----------------------------------------------------------------------===//
3001// BranchInst Class
3002//===----------------------------------------------------------------------===//
3003
3004//===---------------------------------------------------------------------------
3005/// Conditional or Unconditional Branch instruction.
3006///
3007class BranchInst : public Instruction {
3008 /// Ops list - Branches are strange. The operands are ordered:
3009 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
3010 /// they don't have to check for cond/uncond branchness. These are mostly
3011 /// accessed relative from op_end().
3012 BranchInst(const BranchInst &BI);
3013 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
3014 // BranchInst(BB *B) - 'br B'
3015 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
3016 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
3017 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
3018 // BranchInst(BB* B, BB *I) - 'br B' insert at end
3019 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
3020 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
3021 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3022 Instruction *InsertBefore = nullptr);
3023 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
3024 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3025 BasicBlock *InsertAtEnd);
3026
3027 void AssertOK();
3028
3029protected:
3030 // Note: Instruction needs to be a friend here to call cloneImpl.
3031 friend class Instruction;
3032
3033 BranchInst *cloneImpl() const;
3034
3035public:
3036 /// Iterator type that casts an operand to a basic block.
3037 ///
3038 /// This only makes sense because the successors are stored as adjacent
3039 /// operands for branch instructions.
3040 struct succ_op_iterator
3041 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3042 std::random_access_iterator_tag, BasicBlock *,
3043 ptrdiff_t, BasicBlock *, BasicBlock *> {
3044 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3045
3046 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3047 BasicBlock *operator->() const { return operator*(); }
3048 };
3049
3050 /// The const version of `succ_op_iterator`.
3051 struct const_succ_op_iterator
3052 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3053 std::random_access_iterator_tag,
3054 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3055 const BasicBlock *> {
3056 explicit const_succ_op_iterator(const_value_op_iterator I)
3057 : iterator_adaptor_base(I) {}
3058
3059 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3060 const BasicBlock *operator->() const { return operator*(); }
3061 };
3062
3063 static BranchInst *Create(BasicBlock *IfTrue,
3064 Instruction *InsertBefore = nullptr) {
3065 return new(1) BranchInst(IfTrue, InsertBefore);
3066 }
3067
3068 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3069 Value *Cond, Instruction *InsertBefore = nullptr) {
3070 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3071 }
3072
3073 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3074 return new(1) BranchInst(IfTrue, InsertAtEnd);
3075 }
3076
3077 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3078 Value *Cond, BasicBlock *InsertAtEnd) {
3079 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3080 }
3081
3082 /// Transparently provide more efficient getOperand methods.
3083 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
;
3084
3085 bool isUnconditional() const { return getNumOperands() == 1; }
3086 bool isConditional() const { return getNumOperands() == 3; }
3087
3088 Value *getCondition() const {
3089 assert(isConditional() && "Cannot get condition of an uncond branch!")(static_cast <bool> (isConditional() && "Cannot get condition of an uncond branch!"
) ? void (0) : __assert_fail ("isConditional() && \"Cannot get condition of an uncond branch!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3089, __extension__ __PRETTY_FUNCTION__))
;
3090 return Op<-3>();
3091 }
3092
3093 void setCondition(Value *V) {
3094 assert(isConditional() && "Cannot set condition of unconditional branch!")(static_cast <bool> (isConditional() && "Cannot set condition of unconditional branch!"
) ? void (0) : __assert_fail ("isConditional() && \"Cannot set condition of unconditional branch!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3094, __extension__ __PRETTY_FUNCTION__))
;
3095 Op<-3>() = V;
3096 }
3097
3098 unsigned getNumSuccessors() const { return 1+isConditional(); }
3099
3100 BasicBlock *getSuccessor(unsigned i) const {
3101 assert(i < getNumSuccessors() && "Successor # out of range for Branch!")(static_cast <bool> (i < getNumSuccessors() &&
"Successor # out of range for Branch!") ? void (0) : __assert_fail
("i < getNumSuccessors() && \"Successor # out of range for Branch!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3101, __extension__ __PRETTY_FUNCTION__))
;
3102 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3103 }
3104
3105 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3106 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!")(static_cast <bool> (idx < getNumSuccessors() &&
"Successor # out of range for Branch!") ? void (0) : __assert_fail
("idx < getNumSuccessors() && \"Successor # out of range for Branch!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3106, __extension__ __PRETTY_FUNCTION__))
;
3107 *(&Op<-1>() - idx) = NewSucc;
3108 }
3109
3110 /// Swap the successors of this branch instruction.
3111 ///
3112 /// Swaps the successors of the branch instruction. This also swaps any
3113 /// branch weight metadata associated with the instruction so that it
3114 /// continues to map correctly to each operand.
3115 void swapSuccessors();
3116
3117 iterator_range<succ_op_iterator> successors() {
3118 return make_range(
3119 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3120 succ_op_iterator(value_op_end()));
3121 }
3122
3123 iterator_range<const_succ_op_iterator> successors() const {
3124 return make_range(const_succ_op_iterator(
3125 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3126 const_succ_op_iterator(value_op_end()));
3127 }
3128
3129 // Methods for support type inquiry through isa, cast, and dyn_cast:
3130 static bool classof(const Instruction *I) {
3131 return (I->getOpcode() == Instruction::Br);
3132 }
3133 static bool classof(const Value *V) {
3134 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3135 }
3136};
3137
3138template <>
3139struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3140};
3141
3142DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)BranchInst::op_iterator BranchInst::op_begin() { return OperandTraits
<BranchInst>::op_begin(this); } BranchInst::const_op_iterator
BranchInst::op_begin() const { return OperandTraits<BranchInst
>::op_begin(const_cast<BranchInst*>(this)); } BranchInst
::op_iterator BranchInst::op_end() { return OperandTraits<
BranchInst>::op_end(this); } BranchInst::const_op_iterator
BranchInst::op_end() const { return OperandTraits<BranchInst
>::op_end(const_cast<BranchInst*>(this)); } Value *BranchInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<BranchInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3142, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<BranchInst>::op_begin(const_cast
<BranchInst*>(this))[i_nocapture].get()); } void BranchInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<BranchInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3142, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
BranchInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned BranchInst::getNumOperands() const { return OperandTraits
<BranchInst>::operands(this); } template <int Idx_nocapture
> Use &BranchInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
BranchInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
3143
3144//===----------------------------------------------------------------------===//
3145// SwitchInst Class
3146//===----------------------------------------------------------------------===//
3147
3148//===---------------------------------------------------------------------------
3149/// Multiway switch
3150///
3151class SwitchInst : public Instruction {
3152 unsigned ReservedSpace;
3153
3154 // Operand[0] = Value to switch on
3155 // Operand[1] = Default basic block destination
3156 // Operand[2n ] = Value to match
3157 // Operand[2n+1] = BasicBlock to go to on match
3158 SwitchInst(const SwitchInst &SI);
3159
3160 /// Create a new switch instruction, specifying a value to switch on and a
3161 /// default destination. The number of additional cases can be specified here
3162 /// to make memory allocation more efficient. This constructor can also
3163 /// auto-insert before another instruction.
3164 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3165 Instruction *InsertBefore);
3166
3167 /// Create a new switch instruction, specifying a value to switch on and a
3168 /// default destination. The number of additional cases can be specified here
3169 /// to make memory allocation more efficient. This constructor also
3170 /// auto-inserts at the end of the specified BasicBlock.
3171 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3172 BasicBlock *InsertAtEnd);
3173
3174 // allocate space for exactly zero operands
3175 void *operator new(size_t s) {
3176 return User::operator new(s);
3177 }
3178
3179 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3180 void growOperands();
3181
3182protected:
3183 // Note: Instruction needs to be a friend here to call cloneImpl.
3184 friend class Instruction;
3185
3186 SwitchInst *cloneImpl() const;
3187
3188public:
3189 // -2
3190 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3191
3192 template <typename CaseHandleT> class CaseIteratorImpl;
3193
3194 /// A handle to a particular switch case. It exposes a convenient interface
3195 /// to both the case value and the successor block.
3196 ///
3197 /// We define this as a template and instantiate it to form both a const and
3198 /// non-const handle.
3199 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3200 class CaseHandleImpl {
3201 // Directly befriend both const and non-const iterators.
3202 friend class SwitchInst::CaseIteratorImpl<
3203 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3204
3205 protected:
3206 // Expose the switch type we're parameterized with to the iterator.
3207 using SwitchInstType = SwitchInstT;
3208
3209 SwitchInstT *SI;
3210 ptrdiff_t Index;
3211
3212 CaseHandleImpl() = default;
3213 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3214
3215 public:
3216 /// Resolves case value for current case.
3217 ConstantIntT *getCaseValue() const {
3218 assert((unsigned)Index < SI->getNumCases() &&(static_cast <bool> ((unsigned)Index < SI->getNumCases
() && "Index out the number of cases.") ? void (0) : __assert_fail
("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3219, __extension__ __PRETTY_FUNCTION__))
3219 "Index out the number of cases.")(static_cast <bool> ((unsigned)Index < SI->getNumCases
() && "Index out the number of cases.") ? void (0) : __assert_fail
("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3219, __extension__ __PRETTY_FUNCTION__))
;
3220 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3221 }
3222
3223 /// Resolves successor for current case.
3224 BasicBlockT *getCaseSuccessor() const {
3225 assert(((unsigned)Index < SI->getNumCases() ||(static_cast <bool> (((unsigned)Index < SI->getNumCases
() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3227, __extension__ __PRETTY_FUNCTION__))
3226 (unsigned)Index == DefaultPseudoIndex) &&(static_cast <bool> (((unsigned)Index < SI->getNumCases
() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3227, __extension__ __PRETTY_FUNCTION__))
3227 "Index out the number of cases.")(static_cast <bool> (((unsigned)Index < SI->getNumCases
() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3227, __extension__ __PRETTY_FUNCTION__))
;
3228 return SI->getSuccessor(getSuccessorIndex());
3229 }
3230
3231 /// Returns number of current case.
3232 unsigned getCaseIndex() const { return Index; }
3233
3234 /// Returns successor index for current case successor.
3235 unsigned getSuccessorIndex() const {
3236 assert(((unsigned)Index == DefaultPseudoIndex ||(static_cast <bool> (((unsigned)Index == DefaultPseudoIndex
|| (unsigned)Index < SI->getNumCases()) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3238, __extension__ __PRETTY_FUNCTION__))
3237 (unsigned)Index < SI->getNumCases()) &&(static_cast <bool> (((unsigned)Index == DefaultPseudoIndex
|| (unsigned)Index < SI->getNumCases()) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3238, __extension__ __PRETTY_FUNCTION__))
3238 "Index out the number of cases.")(static_cast <bool> (((unsigned)Index == DefaultPseudoIndex
|| (unsigned)Index < SI->getNumCases()) && "Index out the number of cases."
) ? void (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3238, __extension__ __PRETTY_FUNCTION__))
;
3239 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3240 }
3241
3242 bool operator==(const CaseHandleImpl &RHS) const {
3243 assert(SI == RHS.SI && "Incompatible operators.")(static_cast <bool> (SI == RHS.SI && "Incompatible operators."
) ? void (0) : __assert_fail ("SI == RHS.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3243, __extension__ __PRETTY_FUNCTION__))
;
3244 return Index == RHS.Index;
3245 }
3246 };
3247
3248 using ConstCaseHandle =
3249 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3250
3251 class CaseHandle
3252 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3253 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3254
3255 public:
3256 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3257
3258 /// Sets the new value for current case.
3259 void setValue(ConstantInt *V) {
3260 assert((unsigned)Index < SI->getNumCases() &&(static_cast <bool> ((unsigned)Index < SI->getNumCases
() && "Index out the number of cases.") ? void (0) : __assert_fail
("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3261, __extension__ __PRETTY_FUNCTION__))
3261 "Index out the number of cases.")(static_cast <bool> ((unsigned)Index < SI->getNumCases
() && "Index out the number of cases.") ? void (0) : __assert_fail
("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3261, __extension__ __PRETTY_FUNCTION__))
;
3262 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3263 }
3264
3265 /// Sets the new successor for current case.
3266 void setSuccessor(BasicBlock *S) {
3267 SI->setSuccessor(getSuccessorIndex(), S);
3268 }
3269 };
3270
3271 template <typename CaseHandleT>
3272 class CaseIteratorImpl
3273 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3274 std::random_access_iterator_tag,
3275 CaseHandleT> {
3276 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3277
3278 CaseHandleT Case;
3279
3280 public:
3281 /// Default constructed iterator is in an invalid state until assigned to
3282 /// a case for a particular switch.
3283 CaseIteratorImpl() = default;
3284
3285 /// Initializes case iterator for given SwitchInst and for given
3286 /// case number.
3287 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3288
3289 /// Initializes case iterator for given SwitchInst and for given
3290 /// successor index.
3291 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3292 unsigned SuccessorIndex) {
3293 assert(SuccessorIndex < SI->getNumSuccessors() &&(static_cast <bool> (SuccessorIndex < SI->getNumSuccessors
() && "Successor index # out of range!") ? void (0) :
__assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3294, __extension__ __PRETTY_FUNCTION__))
3294 "Successor index # out of range!")(static_cast <bool> (SuccessorIndex < SI->getNumSuccessors
() && "Successor index # out of range!") ? void (0) :
__assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3294, __extension__ __PRETTY_FUNCTION__))
;
3295 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3296 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3297 }
3298
3299 /// Support converting to the const variant. This will be a no-op for const
3300 /// variant.
3301 operator CaseIteratorImpl<ConstCaseHandle>() const {
3302 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3303 }
3304
3305 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3306 // Check index correctness after addition.
3307 // Note: Index == getNumCases() means end().
3308 assert(Case.Index + N >= 0 &&(static_cast <bool> (Case.Index + N >= 0 && (
unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3310, __extension__ __PRETTY_FUNCTION__))
3309 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&(static_cast <bool> (Case.Index + N >= 0 && (
unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3310, __extension__ __PRETTY_FUNCTION__))
3310 "Case.Index out the number of cases.")(static_cast <bool> (Case.Index + N >= 0 && (
unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3310, __extension__ __PRETTY_FUNCTION__))
;
3311 Case.Index += N;
3312 return *this;
3313 }
3314 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3315 // Check index correctness after subtraction.
3316 // Note: Case.Index == getNumCases() means end().
3317 assert(Case.Index - N >= 0 &&(static_cast <bool> (Case.Index - N >= 0 && (
unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3319, __extension__ __PRETTY_FUNCTION__))
3318 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&(static_cast <bool> (Case.Index - N >= 0 && (
unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3319, __extension__ __PRETTY_FUNCTION__))
3319 "Case.Index out the number of cases.")(static_cast <bool> (Case.Index - N >= 0 && (
unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
"Case.Index out the number of cases.") ? void (0) : __assert_fail
("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3319, __extension__ __PRETTY_FUNCTION__))
;
3320 Case.Index -= N;
3321 return *this;
3322 }
3323 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3324 assert(Case.SI == RHS.Case.SI && "Incompatible operators.")(static_cast <bool> (Case.SI == RHS.Case.SI && "Incompatible operators."
) ? void (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3324, __extension__ __PRETTY_FUNCTION__))
;
3325 return Case.Index - RHS.Case.Index;
3326 }
3327 bool operator==(const CaseIteratorImpl &RHS) const {
3328 return Case == RHS.Case;
3329 }
3330 bool operator<(const CaseIteratorImpl &RHS) const {
3331 assert(Case.SI == RHS.Case.SI && "Incompatible operators.")(static_cast <bool> (Case.SI == RHS.Case.SI && "Incompatible operators."
) ? void (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3331, __extension__ __PRETTY_FUNCTION__))
;
3332 return Case.Index < RHS.Case.Index;
3333 }
3334 CaseHandleT &operator*() { return Case; }
3335 const CaseHandleT &operator*() const { return Case; }
3336 };
3337
3338 using CaseIt = CaseIteratorImpl<CaseHandle>;
3339 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3340
3341 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3342 unsigned NumCases,
3343 Instruction *InsertBefore = nullptr) {
3344 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3345 }
3346
3347 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3348 unsigned NumCases, BasicBlock *InsertAtEnd) {
3349 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3350 }
3351
3352 /// Provide fast operand accessors
3353 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
;
3354
3355 // Accessor Methods for Switch stmt
3356 Value *getCondition() const { return getOperand(0); }
3357 void setCondition(Value *V) { setOperand(0, V); }
3358
3359 BasicBlock *getDefaultDest() const {
3360 return cast<BasicBlock>(getOperand(1));
3361 }
3362
3363 void setDefaultDest(BasicBlock *DefaultCase) {
3364 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3365 }
3366
3367 /// Return the number of 'cases' in this switch instruction, excluding the
3368 /// default case.
3369 unsigned getNumCases() const {
3370 return getNumOperands()/2 - 1;
3371 }
3372
3373 /// Returns a read/write iterator that points to the first case in the
3374 /// SwitchInst.
3375 CaseIt case_begin() {
3376 return CaseIt(this, 0);
3377 }
3378
3379 /// Returns a read-only iterator that points to the first case in the
3380 /// SwitchInst.
3381 ConstCaseIt case_begin() const {
3382 return ConstCaseIt(this, 0);
3383 }
3384
3385 /// Returns a read/write iterator that points one past the last in the
3386 /// SwitchInst.
3387 CaseIt case_end() {
3388 return CaseIt(this, getNumCases());
3389 }
3390
3391 /// Returns a read-only iterator that points one past the last in the
3392 /// SwitchInst.
3393 ConstCaseIt case_end() const {
3394 return ConstCaseIt(this, getNumCases());
3395 }
3396
3397 /// Iteration adapter for range-for loops.
3398 iterator_range<CaseIt> cases() {
3399 return make_range(case_begin(), case_end());
3400 }
3401
3402 /// Constant iteration adapter for range-for loops.
3403 iterator_range<ConstCaseIt> cases() const {
3404 return make_range(case_begin(), case_end());
3405 }
3406
3407 /// Returns an iterator that points to the default case.
3408 /// Note: this iterator allows to resolve successor only. Attempt
3409 /// to resolve case value causes an assertion.
3410 /// Also note, that increment and decrement also causes an assertion and
3411 /// makes iterator invalid.
3412 CaseIt case_default() {
3413 return CaseIt(this, DefaultPseudoIndex);
3414 }
3415 ConstCaseIt case_default() const {
3416 return ConstCaseIt(this, DefaultPseudoIndex);
3417 }
3418
3419 /// Search all of the case values for the specified constant. If it is
3420 /// explicitly handled, return the case iterator of it, otherwise return
3421 /// default case iterator to indicate that it is handled by the default
3422 /// handler.
3423 CaseIt findCaseValue(const ConstantInt *C) {
3424 CaseIt I = llvm::find_if(
3425 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3426 if (I != case_end())
3427 return I;
3428
3429 return case_default();
3430 }
3431 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3432 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3433 return Case.getCaseValue() == C;
3434 });
3435 if (I != case_end())
3436 return I;
3437
3438 return case_default();
3439 }
3440
3441 /// Finds the unique case value for a given successor. Returns null if the
3442 /// successor is not found, not unique, or is the default case.
3443 ConstantInt *findCaseDest(BasicBlock *BB) {
3444 if (BB == getDefaultDest())
3445 return nullptr;
3446
3447 ConstantInt *CI = nullptr;
3448 for (auto Case : cases()) {
3449 if (Case.getCaseSuccessor() != BB)
3450 continue;
3451
3452 if (CI)
3453 return nullptr; // Multiple cases lead to BB.
3454
3455 CI = Case.getCaseValue();
3456 }
3457
3458 return CI;
3459 }
3460
3461 /// Add an entry to the switch instruction.
3462 /// Note:
3463 /// This action invalidates case_end(). Old case_end() iterator will
3464 /// point to the added case.
3465 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3466
3467 /// This method removes the specified case and its successor from the switch
3468 /// instruction. Note that this operation may reorder the remaining cases at
3469 /// index idx and above.
3470 /// Note:
3471 /// This action invalidates iterators for all cases following the one removed,
3472 /// including the case_end() iterator. It returns an iterator for the next
3473 /// case.
3474 CaseIt removeCase(CaseIt I);
3475
3476 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3477 BasicBlock *getSuccessor(unsigned idx) const {
3478 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!")(static_cast <bool> (idx < getNumSuccessors() &&
"Successor idx out of range for switch!") ? void (0) : __assert_fail
("idx < getNumSuccessors() &&\"Successor idx out of range for switch!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3478, __extension__ __PRETTY_FUNCTION__))
;
3479 return cast<BasicBlock>(getOperand(idx*2+1));
3480 }
3481 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3482 assert(idx < getNumSuccessors() && "Successor # out of range for switch!")(static_cast <bool> (idx < getNumSuccessors() &&
"Successor # out of range for switch!") ? void (0) : __assert_fail
("idx < getNumSuccessors() && \"Successor # out of range for switch!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3482, __extension__ __PRETTY_FUNCTION__))
;
3483 setOperand(idx * 2 + 1, NewSucc);
3484 }
3485
3486 // Methods for support type inquiry through isa, cast, and dyn_cast:
3487 static bool classof(const Instruction *I) {
3488 return I->getOpcode() == Instruction::Switch;
3489 }
3490 static bool classof(const Value *V) {
3491 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3492 }
3493};
3494
3495/// A wrapper class to simplify modification of SwitchInst cases along with
3496/// their prof branch_weights metadata.
3497class SwitchInstProfUpdateWrapper {
3498 SwitchInst &SI;
3499 Optional<SmallVector<uint32_t, 8> > Weights = None;
3500 bool Changed = false;
3501
3502protected:
3503 static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
3504
3505 MDNode *buildProfBranchWeightsMD();
3506
3507 void init();
3508
3509public:
3510 using CaseWeightOpt = Optional<uint32_t>;
3511 SwitchInst *operator->() { return &SI; }
3512 SwitchInst &operator*() { return SI; }
3513 operator SwitchInst *() { return &SI; }
3514
3515 SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); }
3516
3517 ~SwitchInstProfUpdateWrapper() {
3518 if (Changed)
3519 SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
3520 }
3521
3522 /// Delegate the call to the underlying SwitchInst::removeCase() and remove
3523 /// correspondent branch weight.
3524 SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
3525
3526 /// Delegate the call to the underlying SwitchInst::addCase() and set the
3527 /// specified branch weight for the added case.
3528 void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
3529
3530 /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
3531 /// this object to not touch the underlying SwitchInst in destructor.
3532 SymbolTableList<Instruction>::iterator eraseFromParent();
3533
3534 void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
3535 CaseWeightOpt getSuccessorWeight(unsigned idx);
3536
3537 static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
3538};
3539
3540template <>
3541struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3542};
3543
3544DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)SwitchInst::op_iterator SwitchInst::op_begin() { return OperandTraits
<SwitchInst>::op_begin(this); } SwitchInst::const_op_iterator
SwitchInst::op_begin() const { return OperandTraits<SwitchInst
>::op_begin(const_cast<SwitchInst*>(this)); } SwitchInst
::op_iterator SwitchInst::op_end() { return OperandTraits<
SwitchInst>::op_end(this); } SwitchInst::const_op_iterator
SwitchInst::op_end() const { return OperandTraits<SwitchInst
>::op_end(const_cast<SwitchInst*>(this)); } Value *SwitchInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<SwitchInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3544, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<SwitchInst>::op_begin(const_cast
<SwitchInst*>(this))[i_nocapture].get()); } void SwitchInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<SwitchInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3544, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
SwitchInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned SwitchInst::getNumOperands() const { return OperandTraits
<SwitchInst>::operands(this); } template <int Idx_nocapture
> Use &SwitchInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
SwitchInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
3545
3546//===----------------------------------------------------------------------===//
3547// IndirectBrInst Class
3548//===----------------------------------------------------------------------===//
3549
3550//===---------------------------------------------------------------------------
3551/// Indirect Branch Instruction.
3552///
3553class IndirectBrInst : public Instruction {
3554 unsigned ReservedSpace;
3555
3556 // Operand[0] = Address to jump to
3557 // Operand[n+1] = n-th destination
3558 IndirectBrInst(const IndirectBrInst &IBI);
3559
3560 /// Create a new indirectbr instruction, specifying an
3561 /// Address to jump to. The number of expected destinations can be specified
3562 /// here to make memory allocation more efficient. This constructor can also
3563 /// autoinsert before another instruction.
3564 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3565
3566 /// Create a new indirectbr instruction, specifying an
3567 /// Address to jump to. The number of expected destinations can be specified
3568 /// here to make memory allocation more efficient. This constructor also
3569 /// autoinserts at the end of the specified BasicBlock.
3570 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3571
3572 // allocate space for exactly zero operands
3573 void *operator new(size_t s) {
3574 return User::operator new(s);
3575 }
3576
3577 void init(Value *Address, unsigned NumDests);
3578 void growOperands();
3579
3580protected:
3581 // Note: Instruction needs to be a friend here to call cloneImpl.
3582 friend class Instruction;
3583
3584 IndirectBrInst *cloneImpl() const;
3585
3586public:
3587 /// Iterator type that casts an operand to a basic block.
3588 ///
3589 /// This only makes sense because the successors are stored as adjacent
3590 /// operands for indirectbr instructions.
3591 struct succ_op_iterator
3592 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3593 std::random_access_iterator_tag, BasicBlock *,
3594 ptrdiff_t, BasicBlock *, BasicBlock *> {
3595 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3596
3597 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3598 BasicBlock *operator->() const { return operator*(); }
3599 };
3600
3601 /// The const version of `succ_op_iterator`.
3602 struct const_succ_op_iterator
3603 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3604 std::random_access_iterator_tag,
3605 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3606 const BasicBlock *> {
3607 explicit const_succ_op_iterator(const_value_op_iterator I)
3608 : iterator_adaptor_base(I) {}
3609
3610 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3611 const BasicBlock *operator->() const { return operator*(); }
3612 };
3613
3614 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3615 Instruction *InsertBefore = nullptr) {
3616 return new IndirectBrInst(Address, NumDests, InsertBefore);
3617 }
3618
3619 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3620 BasicBlock *InsertAtEnd) {
3621 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3622 }
3623
3624 /// Provide fast operand accessors.
3625 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
;
3626
3627 // Accessor Methods for IndirectBrInst instruction.
3628 Value *getAddress() { return getOperand(0); }
3629 const Value *getAddress() const { return getOperand(0); }
3630 void setAddress(Value *V) { setOperand(0, V); }
3631
3632 /// return the number of possible destinations in this
3633 /// indirectbr instruction.
3634 unsigned getNumDestinations() const { return getNumOperands()-1; }
3635
3636 /// Return the specified destination.
3637 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3638 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3639
3640 /// Add a destination.
3641 ///
3642 void addDestination(BasicBlock *Dest);
3643
3644 /// This method removes the specified successor from the
3645 /// indirectbr instruction.
3646 void removeDestination(unsigned i);
3647
3648 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3649 BasicBlock *getSuccessor(unsigned i) const {
3650 return cast<BasicBlock>(getOperand(i+1));
3651 }
3652 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3653 setOperand(i + 1, NewSucc);
3654 }
3655
3656 iterator_range<succ_op_iterator> successors() {
3657 return make_range(succ_op_iterator(std::next(value_op_begin())),
3658 succ_op_iterator(value_op_end()));
3659 }
3660
3661 iterator_range<const_succ_op_iterator> successors() const {
3662 return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3663 const_succ_op_iterator(value_op_end()));
3664 }
3665
3666 // Methods for support type inquiry through isa, cast, and dyn_cast:
3667 static bool classof(const Instruction *I) {
3668 return I->getOpcode() == Instruction::IndirectBr;
3669 }
3670 static bool classof(const Value *V) {
3671 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3672 }
3673};
3674
3675template <>
3676struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3677};
3678
3679DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)IndirectBrInst::op_iterator IndirectBrInst::op_begin() { return
OperandTraits<IndirectBrInst>::op_begin(this); } IndirectBrInst
::const_op_iterator IndirectBrInst::op_begin() const { return
OperandTraits<IndirectBrInst>::op_begin(const_cast<
IndirectBrInst*>(this)); } IndirectBrInst::op_iterator IndirectBrInst
::op_end() { return OperandTraits<IndirectBrInst>::op_end
(this); } IndirectBrInst::const_op_iterator IndirectBrInst::op_end
() const { return OperandTraits<IndirectBrInst>::op_end
(const_cast<IndirectBrInst*>(this)); } Value *IndirectBrInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<IndirectBrInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3679, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<IndirectBrInst>::op_begin(
const_cast<IndirectBrInst*>(this))[i_nocapture].get());
} void IndirectBrInst::setOperand(unsigned i_nocapture, Value
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<IndirectBrInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3679, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
IndirectBrInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned IndirectBrInst::getNumOperands() const { return OperandTraits
<IndirectBrInst>::operands(this); } template <int Idx_nocapture
> Use &IndirectBrInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &IndirectBrInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
3680
3681//===----------------------------------------------------------------------===//
3682// InvokeInst Class
3683//===----------------------------------------------------------------------===//
3684
3685/// Invoke instruction. The SubclassData field is used to hold the
3686/// calling convention of the call.
3687///
3688class InvokeInst : public CallBase {
3689 /// The number of operands for this call beyond the called function,
3690 /// arguments, and operand bundles.
3691 static constexpr int NumExtraOperands = 2;
3692
3693 /// The index from the end of the operand array to the normal destination.
3694 static constexpr int NormalDestOpEndIdx = -3;
3695
3696 /// The index from the end of the operand array to the unwind destination.
3697 static constexpr int UnwindDestOpEndIdx = -2;
3698
3699 InvokeInst(const InvokeInst &BI);
3700
3701 /// Construct an InvokeInst given a range of arguments.
3702 ///
3703 /// Construct an InvokeInst from a range of arguments
3704 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3705 BasicBlock *IfException, ArrayRef<Value *> Args,
3706 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3707 const Twine &NameStr, Instruction *InsertBefore);
3708
3709 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3710 BasicBlock *IfException, ArrayRef<Value *> Args,
3711 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3712 const Twine &NameStr, BasicBlock *InsertAtEnd);
3713
3714 void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3715 BasicBlock *IfException, ArrayRef<Value *> Args,
3716 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3717
3718 /// Compute the number of operands to allocate.
3719 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3720 // We need one operand for the called function, plus our extra operands and
3721 // the input operand counts provided.
3722 return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3723 }
3724
3725protected:
3726 // Note: Instruction needs to be a friend here to call cloneImpl.
3727 friend class Instruction;
3728
3729 InvokeInst *cloneImpl() const;
3730
3731public:
3732 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3733 BasicBlock *IfException, ArrayRef<Value *> Args,
3734 const Twine &NameStr,
3735 Instruction *InsertBefore = nullptr) {
3736 int NumOperands = ComputeNumOperands(Args.size());
3737 return new (NumOperands)
3738 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3739 NameStr, InsertBefore);
3740 }
3741
3742 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3743 BasicBlock *IfException, ArrayRef<Value *> Args,
3744 ArrayRef<OperandBundleDef> Bundles = None,
3745 const Twine &NameStr = "",
3746 Instruction *InsertBefore = nullptr) {
3747 int NumOperands =
3748 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3749 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3750
3751 return new (NumOperands, DescriptorBytes)
3752 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3753 NameStr, InsertBefore);
3754 }
3755
3756 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3757 BasicBlock *IfException, ArrayRef<Value *> Args,
3758 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3759 int NumOperands = ComputeNumOperands(Args.size());
3760 return new (NumOperands)
3761 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3762 NameStr, InsertAtEnd);
3763 }
3764
3765 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3766 BasicBlock *IfException, ArrayRef<Value *> Args,
3767 ArrayRef<OperandBundleDef> Bundles,
3768 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3769 int NumOperands =
3770 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3771 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3772
3773 return new (NumOperands, DescriptorBytes)
3774 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3775 NameStr, InsertAtEnd);
3776 }
3777
3778 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3779 BasicBlock *IfException, ArrayRef<Value *> Args,
3780 const Twine &NameStr,
3781 Instruction *InsertBefore = nullptr) {
3782 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3783 IfException, Args, None, NameStr, InsertBefore);
3784 }
3785
3786 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3787 BasicBlock *IfException, ArrayRef<Value *> Args,
3788 ArrayRef<OperandBundleDef> Bundles = None,
3789 const Twine &NameStr = "",
3790 Instruction *InsertBefore = nullptr) {
3791 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3792 IfException, Args, Bundles, NameStr, InsertBefore);
3793 }
3794
3795 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3796 BasicBlock *IfException, ArrayRef<Value *> Args,
3797 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3798 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3799 IfException, Args, NameStr, InsertAtEnd);
3800 }
3801
3802 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3803 BasicBlock *IfException, ArrayRef<Value *> Args,
3804 ArrayRef<OperandBundleDef> Bundles,
3805 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3806 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3807 IfException, Args, Bundles, NameStr, InsertAtEnd);
3808 }
3809
3810 /// Create a clone of \p II with a different set of operand bundles and
3811 /// insert it before \p InsertPt.
3812 ///
3813 /// The returned invoke instruction is identical to \p II in every way except
3814 /// that the operand bundles for the new instruction are set to the operand
3815 /// bundles in \p Bundles.
3816 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3817 Instruction *InsertPt = nullptr);
3818
3819 // get*Dest - Return the destination basic blocks...
3820 BasicBlock *getNormalDest() const {
3821 return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3822 }
3823 BasicBlock *getUnwindDest() const {
3824 return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3825 }
3826 void setNormalDest(BasicBlock *B) {
3827 Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3828 }
3829 void setUnwindDest(BasicBlock *B) {
3830 Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3831 }
3832
3833 /// Get the landingpad instruction from the landing pad
3834 /// block (the unwind destination).
3835 LandingPadInst *getLandingPadInst() const;
3836
3837 BasicBlock *getSuccessor(unsigned i) const {
3838 assert(i < 2 && "Successor # out of range for invoke!")(static_cast <bool> (i < 2 && "Successor # out of range for invoke!"
) ? void (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3838, __extension__ __PRETTY_FUNCTION__))
;
3839 return i == 0 ? getNormalDest() : getUnwindDest();
3840 }
3841
3842 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3843 assert(i < 2 && "Successor # out of range for invoke!")(static_cast <bool> (i < 2 && "Successor # out of range for invoke!"
) ? void (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 3843, __extension__ __PRETTY_FUNCTION__))
;
3844 if (i == 0)
3845 setNormalDest(NewSucc);
3846 else
3847 setUnwindDest(NewSucc);
3848 }
3849
3850 unsigned getNumSuccessors() const { return 2; }
3851
3852 // Methods for support type inquiry through isa, cast, and dyn_cast:
3853 static bool classof(const Instruction *I) {
3854 return (I->getOpcode() == Instruction::Invoke);
3855 }
3856 static bool classof(const Value *V) {
3857 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3858 }
3859
3860private:
3861 // Shadow Instruction::setInstructionSubclassData with a private forwarding
3862 // method so that subclasses cannot accidentally use it.
3863 template <typename Bitfield>
3864 void setSubclassData(typename Bitfield::Type Value) {
3865 Instruction::setSubclassData<Bitfield>(Value);
3866 }
3867};
3868
3869InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3870 BasicBlock *IfException, ArrayRef<Value *> Args,
3871 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3872 const Twine &NameStr, Instruction *InsertBefore)
3873 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3874 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3875 InsertBefore) {
3876 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3877}
3878
3879InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3880 BasicBlock *IfException, ArrayRef<Value *> Args,
3881 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3882 const Twine &NameStr, BasicBlock *InsertAtEnd)
3883 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3884 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3885 InsertAtEnd) {
3886 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3887}
3888
3889//===----------------------------------------------------------------------===//
3890// CallBrInst Class
3891//===----------------------------------------------------------------------===//
3892
3893/// CallBr instruction, tracking function calls that may not return control but
3894/// instead transfer it to a third location. The SubclassData field is used to
3895/// hold the calling convention of the call.
3896///
3897class CallBrInst : public CallBase {
3898
3899 unsigned NumIndirectDests;
3900
3901 CallBrInst(const CallBrInst &BI);
3902
3903 /// Construct a CallBrInst given a range of arguments.
3904 ///
3905 /// Construct a CallBrInst from a range of arguments
3906 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3907 ArrayRef<BasicBlock *> IndirectDests,
3908 ArrayRef<Value *> Args,
3909 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3910 const Twine &NameStr, Instruction *InsertBefore);
3911
3912 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3913 ArrayRef<BasicBlock *> IndirectDests,
3914 ArrayRef<Value *> Args,
3915 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3916 const Twine &NameStr, BasicBlock *InsertAtEnd);
3917
3918 void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3919 ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3920 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3921
3922 /// Should the Indirect Destinations change, scan + update the Arg list.
3923 void updateArgBlockAddresses(unsigned i, BasicBlock *B);
3924
3925 /// Compute the number of operands to allocate.
3926 static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3927 int NumBundleInputs = 0) {
3928 // We need one operand for the called function, plus our extra operands and
3929 // the input operand counts provided.
3930 return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3931 }
3932
3933protected:
3934 // Note: Instruction needs to be a friend here to call cloneImpl.
3935 friend class Instruction;
3936
3937 CallBrInst *cloneImpl() const;
3938
3939public:
3940 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3941 BasicBlock *DefaultDest,
3942 ArrayRef<BasicBlock *> IndirectDests,
3943 ArrayRef<Value *> Args, const Twine &NameStr,
3944 Instruction *InsertBefore = nullptr) {
3945 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3946 return new (NumOperands)
3947 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3948 NumOperands, NameStr, InsertBefore);
3949 }
3950
3951 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3952 BasicBlock *DefaultDest,
3953 ArrayRef<BasicBlock *> IndirectDests,
3954 ArrayRef<Value *> Args,
3955 ArrayRef<OperandBundleDef> Bundles = None,
3956 const Twine &NameStr = "",
3957 Instruction *InsertBefore = nullptr) {
3958 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3959 CountBundleInputs(Bundles));
3960 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3961
3962 return new (NumOperands, DescriptorBytes)
3963 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3964 NumOperands, NameStr, InsertBefore);
3965 }
3966
3967 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3968 BasicBlock *DefaultDest,
3969 ArrayRef<BasicBlock *> IndirectDests,
3970 ArrayRef<Value *> Args, const Twine &NameStr,
3971 BasicBlock *InsertAtEnd) {
3972 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3973 return new (NumOperands)
3974 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3975 NumOperands, NameStr, InsertAtEnd);
3976 }
3977
3978 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3979 BasicBlock *DefaultDest,
3980 ArrayRef<BasicBlock *> IndirectDests,
3981 ArrayRef<Value *> Args,
3982 ArrayRef<OperandBundleDef> Bundles,
3983 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3984 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3985 CountBundleInputs(Bundles));
3986 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3987
3988 return new (NumOperands, DescriptorBytes)
3989 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3990 NumOperands, NameStr, InsertAtEnd);
3991 }
3992
3993 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
3994 ArrayRef<BasicBlock *> IndirectDests,
3995 ArrayRef<Value *> Args, const Twine &NameStr,
3996 Instruction *InsertBefore = nullptr) {
3997 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
3998 IndirectDests, Args, NameStr, InsertBefore);
3999 }
4000
4001 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4002 ArrayRef<BasicBlock *> IndirectDests,
4003 ArrayRef<Value *> Args,
4004 ArrayRef<OperandBundleDef> Bundles = None,
4005 const Twine &NameStr = "",
4006 Instruction *InsertBefore = nullptr) {
4007 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4008 IndirectDests, Args, Bundles, NameStr, InsertBefore);
4009 }
4010
4011 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4012 ArrayRef<BasicBlock *> IndirectDests,
4013 ArrayRef<Value *> Args, const Twine &NameStr,
4014 BasicBlock *InsertAtEnd) {
4015 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4016 IndirectDests, Args, NameStr, InsertAtEnd);
4017 }
4018
4019 static CallBrInst *Create(FunctionCallee Func,
4020 BasicBlock *DefaultDest,
4021 ArrayRef<BasicBlock *> IndirectDests,
4022 ArrayRef<Value *> Args,
4023 ArrayRef<OperandBundleDef> Bundles,
4024 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4025 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4026 IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4027 }
4028
4029 /// Create a clone of \p CBI with a different set of operand bundles and
4030 /// insert it before \p InsertPt.
4031 ///
4032 /// The returned callbr instruction is identical to \p CBI in every way
4033 /// except that the operand bundles for the new instruction are set to the
4034 /// operand bundles in \p Bundles.
4035 static CallBrInst *Create(CallBrInst *CBI,
4036 ArrayRef<OperandBundleDef> Bundles,
4037 Instruction *InsertPt = nullptr);
4038
4039 /// Return the number of callbr indirect dest labels.
4040 ///
4041 unsigned getNumIndirectDests() const { return NumIndirectDests; }
4042
4043 /// getIndirectDestLabel - Return the i-th indirect dest label.
4044 ///
4045 Value *getIndirectDestLabel(unsigned i) const {
4046 assert(i < getNumIndirectDests() && "Out of bounds!")(static_cast <bool> (i < getNumIndirectDests() &&
"Out of bounds!") ? void (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4046, __extension__ __PRETTY_FUNCTION__))
;
4047 return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4048 1);
4049 }
4050
4051 Value *getIndirectDestLabelUse(unsigned i) const {
4052 assert(i < getNumIndirectDests() && "Out of bounds!")(static_cast <bool> (i < getNumIndirectDests() &&
"Out of bounds!") ? void (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4052, __extension__ __PRETTY_FUNCTION__))
;
4053 return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4054 1);
4055 }
4056
4057 // Return the destination basic blocks...
4058 BasicBlock *getDefaultDest() const {
4059 return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4060 }
4061 BasicBlock *getIndirectDest(unsigned i) const {
4062 return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4063 }
4064 SmallVector<BasicBlock *, 16> getIndirectDests() const {
4065 SmallVector<BasicBlock *, 16> IndirectDests;
4066 for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4067 IndirectDests.push_back(getIndirectDest(i));
4068 return IndirectDests;
4069 }
4070 void setDefaultDest(BasicBlock *B) {
4071 *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4072 }
4073 void setIndirectDest(unsigned i, BasicBlock *B) {
4074 updateArgBlockAddresses(i, B);
4075 *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4076 }
4077
4078 BasicBlock *getSuccessor(unsigned i) const {
4079 assert(i < getNumSuccessors() + 1 &&(static_cast <bool> (i < getNumSuccessors() + 1 &&
"Successor # out of range for callbr!") ? void (0) : __assert_fail
("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4080, __extension__ __PRETTY_FUNCTION__))
4080 "Successor # out of range for callbr!")(static_cast <bool> (i < getNumSuccessors() + 1 &&
"Successor # out of range for callbr!") ? void (0) : __assert_fail
("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4080, __extension__ __PRETTY_FUNCTION__))
;
4081 return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4082 }
4083
4084 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
4085 assert(i < getNumIndirectDests() + 1 &&(static_cast <bool> (i < getNumIndirectDests() + 1 &&
"Successor # out of range for callbr!") ? void (0) : __assert_fail
("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4086, __extension__ __PRETTY_FUNCTION__))
4086 "Successor # out of range for callbr!")(static_cast <bool> (i < getNumIndirectDests() + 1 &&
"Successor # out of range for callbr!") ? void (0) : __assert_fail
("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4086, __extension__ __PRETTY_FUNCTION__))
;
4087 return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
4088 }
4089
4090 unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4091
4092 // Methods for support type inquiry through isa, cast, and dyn_cast:
4093 static bool classof(const Instruction *I) {
4094 return (I->getOpcode() == Instruction::CallBr);
4095 }
4096 static bool classof(const Value *V) {
4097 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4098 }
4099
4100private:
4101 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4102 // method so that subclasses cannot accidentally use it.
4103 template <typename Bitfield>
4104 void setSubclassData(typename Bitfield::Type Value) {
4105 Instruction::setSubclassData<Bitfield>(Value);
4106 }
4107};
4108
4109CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4110 ArrayRef<BasicBlock *> IndirectDests,
4111 ArrayRef<Value *> Args,
4112 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4113 const Twine &NameStr, Instruction *InsertBefore)
4114 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4115 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4116 InsertBefore) {
4117 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4118}
4119
4120CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4121 ArrayRef<BasicBlock *> IndirectDests,
4122 ArrayRef<Value *> Args,
4123 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4124 const Twine &NameStr, BasicBlock *InsertAtEnd)
4125 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4126 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4127 InsertAtEnd) {
4128 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4129}
4130
4131//===----------------------------------------------------------------------===//
4132// ResumeInst Class
4133//===----------------------------------------------------------------------===//
4134
4135//===---------------------------------------------------------------------------
4136/// Resume the propagation of an exception.
4137///
4138class ResumeInst : public Instruction {
4139 ResumeInst(const ResumeInst &RI);
4140
4141 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4142 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4143
4144protected:
4145 // Note: Instruction needs to be a friend here to call cloneImpl.
4146 friend class Instruction;
4147
4148 ResumeInst *cloneImpl() const;
4149
4150public:
4151 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4152 return new(1) ResumeInst(Exn, InsertBefore);
4153 }
4154
4155 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4156 return new(1) ResumeInst(Exn, InsertAtEnd);
4157 }
4158
4159 /// Provide fast operand accessors
4160 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
;
4161
4162 /// Convenience accessor.
4163 Value *getValue() const { return Op<0>(); }
4164
4165 unsigned getNumSuccessors() const { return 0; }
4166
4167 // Methods for support type inquiry through isa, cast, and dyn_cast:
4168 static bool classof(const Instruction *I) {
4169 return I->getOpcode() == Instruction::Resume;
4170 }
4171 static bool classof(const Value *V) {
4172 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4173 }
4174
4175private:
4176 BasicBlock *getSuccessor(unsigned idx) const {
4177 llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4177)
;
4178 }
4179
4180 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4181 llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4181)
;
4182 }
4183};
4184
4185template <>
4186struct OperandTraits<ResumeInst> :
4187 public FixedNumOperandTraits<ResumeInst, 1> {
4188};
4189
4190DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)ResumeInst::op_iterator ResumeInst::op_begin() { return OperandTraits
<ResumeInst>::op_begin(this); } ResumeInst::const_op_iterator
ResumeInst::op_begin() const { return OperandTraits<ResumeInst
>::op_begin(const_cast<ResumeInst*>(this)); } ResumeInst
::op_iterator ResumeInst::op_end() { return OperandTraits<
ResumeInst>::op_end(this); } ResumeInst::const_op_iterator
ResumeInst::op_end() const { return OperandTraits<ResumeInst
>::op_end(const_cast<ResumeInst*>(this)); } Value *ResumeInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<ResumeInst>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4190, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<ResumeInst>::op_begin(const_cast
<ResumeInst*>(this))[i_nocapture].get()); } void ResumeInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast
<bool> (i_nocapture < OperandTraits<ResumeInst>
::operands(this) && "setOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4190, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
ResumeInst>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned ResumeInst::getNumOperands() const { return OperandTraits
<ResumeInst>::operands(this); } template <int Idx_nocapture
> Use &ResumeInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
ResumeInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
4191
4192//===----------------------------------------------------------------------===//
4193// CatchSwitchInst Class
4194//===----------------------------------------------------------------------===//
4195class CatchSwitchInst : public Instruction {
4196 using UnwindDestField = BoolBitfieldElementT<0>;
4197
4198 /// The number of operands actually allocated. NumOperands is
4199 /// the number actually in use.
4200 unsigned ReservedSpace;
4201
4202 // Operand[0] = Outer scope
4203 // Operand[1] = Unwind block destination
4204 // Operand[n] = BasicBlock to go to on match
4205 CatchSwitchInst(const CatchSwitchInst &CSI);
4206
4207 /// Create a new switch instruction, specifying a
4208 /// default destination. The number of additional handlers can be specified
4209 /// here to make memory allocation more efficient.
4210 /// This constructor can also autoinsert before another instruction.
4211 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4212 unsigned NumHandlers, const Twine &NameStr,
4213 Instruction *InsertBefore);
4214
4215 /// Create a new switch instruction, specifying a
4216 /// default destination. The number of additional handlers can be specified
4217 /// here to make memory allocation more efficient.
4218 /// This constructor also autoinserts at the end of the specified BasicBlock.
4219 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4220 unsigned NumHandlers, const Twine &NameStr,
4221 BasicBlock *InsertAtEnd);
4222
4223 // allocate space for exactly zero operands
4224 void *operator new(size_t s) { return User::operator new(s); }
4225
4226 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4227 void growOperands(unsigned Size);
4228
4229protected:
4230 // Note: Instruction needs to be a friend here to call cloneImpl.
4231 friend class Instruction;
4232
4233 CatchSwitchInst *cloneImpl() const;
4234
4235public:
4236 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4237 unsigned NumHandlers,
4238 const Twine &NameStr = "",
4239 Instruction *InsertBefore = nullptr) {
4240 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4241 InsertBefore);
4242 }
4243
4244 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4245 unsigned NumHandlers, const Twine &NameStr,
4246 BasicBlock *InsertAtEnd) {
4247 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4248 InsertAtEnd);
4249 }
4250
4251 /// Provide fast operand accessors
4252 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
;
4253
4254 // Accessor Methods for CatchSwitch stmt
4255 Value *getParentPad() const { return getOperand(0); }
4256 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4257
4258 // Accessor Methods for CatchSwitch stmt
4259 bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); }
4260 bool unwindsToCaller() const { return !hasUnwindDest(); }
4261 BasicBlock *getUnwindDest() const {
4262 if (hasUnwindDest())
4263 return cast<BasicBlock>(getOperand(1));
4264 return nullptr;
4265 }
4266 void setUnwindDest(BasicBlock *UnwindDest) {
4267 assert(UnwindDest)(static_cast <bool> (UnwindDest) ? void (0) : __assert_fail
("UnwindDest", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4267, __extension__ __PRETTY_FUNCTION__))
;
4268 assert(hasUnwindDest())(static_cast <bool> (hasUnwindDest()) ? void (0) : __assert_fail
("hasUnwindDest()", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4268, __extension__ __PRETTY_FUNCTION__))
;
4269 setOperand(1, UnwindDest);
4270 }
4271
4272 /// return the number of 'handlers' in this catchswitch
4273 /// instruction, except the default handler
4274 unsigned getNumHandlers() const {
4275 if (hasUnwindDest())
4276 return getNumOperands() - 2;
4277 return getNumOperands() - 1;
4278 }
4279
4280private:
4281 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4282 static const BasicBlock *handler_helper(const Value *V) {
4283 return cast<BasicBlock>(V);
4284 }
4285
4286public:
4287 using DerefFnTy = BasicBlock *(*)(Value *);
4288 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4289 using handler_range = iterator_range<handler_iterator>;
4290 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4291 using const_handler_iterator =
4292 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4293 using const_handler_range = iterator_range<const_handler_iterator>;
4294
4295 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4296 handler_iterator handler_begin() {
4297 op_iterator It = op_begin() + 1;
4298 if (hasUnwindDest())
4299 ++It;
4300 return handler_iterator(It, DerefFnTy(handler_helper));
4301 }
4302
4303 /// Returns an iterator that points to the first handler in the
4304 /// CatchSwitchInst.
4305 const_handler_iterator handler_begin() const {
4306 const_op_iterator It = op_begin() + 1;
4307 if (hasUnwindDest())
4308 ++It;
4309 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4310 }
4311
4312 /// Returns a read-only iterator that points one past the last
4313 /// handler in the CatchSwitchInst.
4314 handler_iterator handler_end() {
4315 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4316 }
4317
4318 /// Returns an iterator that points one past the last handler in the
4319 /// CatchSwitchInst.
4320 const_handler_iterator handler_end() const {
4321 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4322 }
4323
4324 /// iteration adapter for range-for loops.
4325 handler_range handlers() {
4326 return make_range(handler_begin(), handler_end());
4327 }
4328
4329 /// iteration adapter for range-for loops.
4330 const_handler_range handlers() const {
4331 return make_range(handler_begin(), handler_end());
4332 }
4333
4334 /// Add an entry to the switch instruction...
4335 /// Note:
4336 /// This action invalidates handler_end(). Old handler_end() iterator will
4337 /// point to the added handler.
4338 void addHandler(BasicBlock *Dest);
4339
4340 void removeHandler(handler_iterator HI);
4341
4342 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4343 BasicBlock *getSuccessor(unsigned Idx) const {
4344 assert(Idx < getNumSuccessors() &&(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchswitch!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4345, __extension__ __PRETTY_FUNCTION__))
4345 "Successor # out of range for catchswitch!")(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchswitch!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4345, __extension__ __PRETTY_FUNCTION__))
;
4346 return cast<BasicBlock>(getOperand(Idx + 1));
4347 }
4348 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4349 assert(Idx < getNumSuccessors() &&(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchswitch!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4350, __extension__ __PRETTY_FUNCTION__))
4350 "Successor # out of range for catchswitch!")(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchswitch!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4350, __extension__ __PRETTY_FUNCTION__))
;
4351 setOperand(Idx + 1, NewSucc);
4352 }
4353
4354 // Methods for support type inquiry through isa, cast, and dyn_cast:
4355 static bool classof(const Instruction *I) {
4356 return I->getOpcode() == Instruction::CatchSwitch;
4357 }
4358 static bool classof(const Value *V) {
4359 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4360 }
4361};
4362
4363template <>
4364struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4365
4366DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)CatchSwitchInst::op_iterator CatchSwitchInst::op_begin() { return
OperandTraits<CatchSwitchInst>::op_begin(this); } CatchSwitchInst
::const_op_iterator CatchSwitchInst::op_begin() const { return
OperandTraits<CatchSwitchInst>::op_begin(const_cast<
CatchSwitchInst*>(this)); } CatchSwitchInst::op_iterator CatchSwitchInst
::op_end() { return OperandTraits<CatchSwitchInst>::op_end
(this); } CatchSwitchInst::const_op_iterator CatchSwitchInst::
op_end() const { return OperandTraits<CatchSwitchInst>::
op_end(const_cast<CatchSwitchInst*>(this)); } Value *CatchSwitchInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<CatchSwitchInst>::
operands(this) && "getOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4366, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<CatchSwitchInst>::op_begin
(const_cast<CatchSwitchInst*>(this))[i_nocapture].get()
); } void CatchSwitchInst::setOperand(unsigned i_nocapture, Value
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<CatchSwitchInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4366, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
CatchSwitchInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned CatchSwitchInst::getNumOperands() const { return
OperandTraits<CatchSwitchInst>::operands(this); } template
<int Idx_nocapture> Use &CatchSwitchInst::Op() { return
this->OpFrom<Idx_nocapture>(this); } template <int
Idx_nocapture> const Use &CatchSwitchInst::Op() const
{ return this->OpFrom<Idx_nocapture>(this); }
4367
4368//===----------------------------------------------------------------------===//
4369// CleanupPadInst Class
4370//===----------------------------------------------------------------------===//
4371class CleanupPadInst : public FuncletPadInst {
4372private:
4373 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4374 unsigned Values, const Twine &NameStr,
4375 Instruction *InsertBefore)
4376 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4377 NameStr, InsertBefore) {}
4378 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4379 unsigned Values, const Twine &NameStr,
4380 BasicBlock *InsertAtEnd)
4381 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4382 NameStr, InsertAtEnd) {}
4383
4384public:
4385 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4386 const Twine &NameStr = "",
4387 Instruction *InsertBefore = nullptr) {
4388 unsigned Values = 1 + Args.size();
4389 return new (Values)
4390 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4391 }
4392
4393 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4394 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4395 unsigned Values = 1 + Args.size();
4396 return new (Values)
4397 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4398 }
4399
4400 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4401 static bool classof(const Instruction *I) {
4402 return I->getOpcode() == Instruction::CleanupPad;
4403 }
4404 static bool classof(const Value *V) {
4405 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4406 }
4407};
4408
4409//===----------------------------------------------------------------------===//
4410// CatchPadInst Class
4411//===----------------------------------------------------------------------===//
4412class CatchPadInst : public FuncletPadInst {
4413private:
4414 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4415 unsigned Values, const Twine &NameStr,
4416 Instruction *InsertBefore)
4417 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4418 NameStr, InsertBefore) {}
4419 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4420 unsigned Values, const Twine &NameStr,
4421 BasicBlock *InsertAtEnd)
4422 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4423 NameStr, InsertAtEnd) {}
4424
4425public:
4426 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4427 const Twine &NameStr = "",
4428 Instruction *InsertBefore = nullptr) {
4429 unsigned Values = 1 + Args.size();
4430 return new (Values)
4431 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4432 }
4433
4434 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4435 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4436 unsigned Values = 1 + Args.size();
4437 return new (Values)
4438 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4439 }
4440
4441 /// Convenience accessors
4442 CatchSwitchInst *getCatchSwitch() const {
4443 return cast<CatchSwitchInst>(Op<-1>());
4444 }
4445 void setCatchSwitch(Value *CatchSwitch) {
4446 assert(CatchSwitch)(static_cast <bool> (CatchSwitch) ? void (0) : __assert_fail
("CatchSwitch", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4446, __extension__ __PRETTY_FUNCTION__))
;
4447 Op<-1>() = CatchSwitch;
4448 }
4449
4450 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4451 static bool classof(const Instruction *I) {
4452 return I->getOpcode() == Instruction::CatchPad;
4453 }
4454 static bool classof(const Value *V) {
4455 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4456 }
4457};
4458
4459//===----------------------------------------------------------------------===//
4460// CatchReturnInst Class
4461//===----------------------------------------------------------------------===//
4462
4463class CatchReturnInst : public Instruction {
4464 CatchReturnInst(const CatchReturnInst &RI);
4465 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4466 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4467
4468 void init(Value *CatchPad, BasicBlock *BB);
4469
4470protected:
4471 // Note: Instruction needs to be a friend here to call cloneImpl.
4472 friend class Instruction;
4473
4474 CatchReturnInst *cloneImpl() const;
4475
4476public:
4477 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4478 Instruction *InsertBefore = nullptr) {
4479 assert(CatchPad)(static_cast <bool> (CatchPad) ? void (0) : __assert_fail
("CatchPad", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4479, __extension__ __PRETTY_FUNCTION__))
;
4480 assert(BB)(static_cast <bool> (BB) ? void (0) : __assert_fail ("BB"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4480, __extension__ __PRETTY_FUNCTION__))
;
4481 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4482 }
4483
4484 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4485 BasicBlock *InsertAtEnd) {
4486 assert(CatchPad)(static_cast <bool> (CatchPad) ? void (0) : __assert_fail
("CatchPad", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4486, __extension__ __PRETTY_FUNCTION__))
;
4487 assert(BB)(static_cast <bool> (BB) ? void (0) : __assert_fail ("BB"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4487, __extension__ __PRETTY_FUNCTION__))
;
4488 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4489 }
4490
4491 /// Provide fast operand accessors
4492 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
;
4493
4494 /// Convenience accessors.
4495 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4496 void setCatchPad(CatchPadInst *CatchPad) {
4497 assert(CatchPad)(static_cast <bool> (CatchPad) ? void (0) : __assert_fail
("CatchPad", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4497, __extension__ __PRETTY_FUNCTION__))
;
4498 Op<0>() = CatchPad;
4499 }
4500
4501 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4502 void setSuccessor(BasicBlock *NewSucc) {
4503 assert(NewSucc)(static_cast <bool> (NewSucc) ? void (0) : __assert_fail
("NewSucc", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4503, __extension__ __PRETTY_FUNCTION__))
;
4504 Op<1>() = NewSucc;
4505 }
4506 unsigned getNumSuccessors() const { return 1; }
4507
4508 /// Get the parentPad of this catchret's catchpad's catchswitch.
4509 /// The successor block is implicitly a member of this funclet.
4510 Value *getCatchSwitchParentPad() const {
4511 return getCatchPad()->getCatchSwitch()->getParentPad();
4512 }
4513
4514 // Methods for support type inquiry through isa, cast, and dyn_cast:
4515 static bool classof(const Instruction *I) {
4516 return (I->getOpcode() == Instruction::CatchRet);
4517 }
4518 static bool classof(const Value *V) {
4519 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4520 }
4521
4522private:
4523 BasicBlock *getSuccessor(unsigned Idx) const {
4524 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchret!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4524, __extension__ __PRETTY_FUNCTION__))
;
4525 return getSuccessor();
4526 }
4527
4528 void setSuccessor(unsigned Idx, BasicBlock *B) {
4529 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")(static_cast <bool> (Idx < getNumSuccessors() &&
"Successor # out of range for catchret!") ? void (0) : __assert_fail
("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4529, __extension__ __PRETTY_FUNCTION__))
;
4530 setSuccessor(B);
4531 }
4532};
4533
4534template <>
4535struct OperandTraits<CatchReturnInst>
4536 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4537
4538DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)CatchReturnInst::op_iterator CatchReturnInst::op_begin() { return
OperandTraits<CatchReturnInst>::op_begin(this); } CatchReturnInst
::const_op_iterator CatchReturnInst::op_begin() const { return
OperandTraits<CatchReturnInst>::op_begin(const_cast<
CatchReturnInst*>(this)); } CatchReturnInst::op_iterator CatchReturnInst
::op_end() { return OperandTraits<CatchReturnInst>::op_end
(this); } CatchReturnInst::const_op_iterator CatchReturnInst::
op_end() const { return OperandTraits<CatchReturnInst>::
op_end(const_cast<CatchReturnInst*>(this)); } Value *CatchReturnInst
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<CatchReturnInst>::
operands(this) && "getOperand() out of range!") ? void
(0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4538, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<CatchReturnInst>::op_begin
(const_cast<CatchReturnInst*>(this))[i_nocapture].get()
); } void CatchReturnInst::setOperand(unsigned i_nocapture, Value
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<CatchReturnInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4538, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
CatchReturnInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned CatchReturnInst::getNumOperands() const { return
OperandTraits<CatchReturnInst>::operands(this); } template
<int Idx_nocapture> Use &CatchReturnInst::Op() { return
this->OpFrom<Idx_nocapture>(this); } template <int
Idx_nocapture> const Use &CatchReturnInst::Op() const
{ return this->OpFrom<Idx_nocapture>(this); }
4539
4540//===----------------------------------------------------------------------===//
4541// CleanupReturnInst Class
4542//===----------------------------------------------------------------------===//
4543
4544class CleanupReturnInst : public Instruction {
4545 using UnwindDestField = BoolBitfieldElementT<0>;
4546
4547private:
4548 CleanupReturnInst(const CleanupReturnInst &RI);
4549 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4550 Instruction *InsertBefore = nullptr);
4551 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4552 BasicBlock *InsertAtEnd);
4553
4554 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4555
4556protected:
4557 // Note: Instruction needs to be a friend here to call cloneImpl.
4558 friend class Instruction;
4559
4560 CleanupReturnInst *cloneImpl() const;
4561
4562public:
4563 static CleanupReturnInst *Create(Value *CleanupPad,
4564 BasicBlock *UnwindBB = nullptr,
4565 Instruction *InsertBefore = nullptr) {
4566 assert(CleanupPad)(static_cast <bool> (CleanupPad) ? void (0) : __assert_fail
("CleanupPad", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4566, __extension__ __PRETTY_FUNCTION__))
;
4567 unsigned Values = 1;
4568 if (UnwindBB)
4569 ++Values;
4570 return new (Values)
4571 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4572 }
4573
4574 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4575 BasicBlock *InsertAtEnd) {
4576 assert(CleanupPad)(static_cast <bool> (CleanupPad) ? void (0) : __assert_fail
("CleanupPad", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4576, __extension__ __PRETTY_FUNCTION__))
;
4577 unsigned Values = 1;
4578 if (UnwindBB)
4579 ++Values;
4580 return new (Values)
4581 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4582 }
4583
4584 /// Provide fast operand accessors
4585 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
;
4586
4587 bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); }
4588 bool unwindsToCaller() const { return !hasUnwindDest(); }
4589
4590 /// Convenience accessor.
4591 CleanupPadInst *getCleanupPad() const {
4592 return cast<CleanupPadInst>(Op<0>());
4593 }
4594 void setCleanupPad(CleanupPadInst *CleanupPad) {
4595 assert(CleanupPad)(static_cast <bool> (CleanupPad) ? void (0) : __assert_fail
("CleanupPad", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4595, __extension__ __PRETTY_FUNCTION__))
;
4596 Op<0>() = CleanupPad;
4597 }
4598
4599 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4600
4601 BasicBlock *getUnwindDest() const {
4602 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4603 }
4604 void setUnwindDest(BasicBlock *NewDest) {
4605 assert(NewDest)(static_cast <bool> (NewDest) ? void (0) : __assert_fail
("NewDest", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4605, __extension__ __PRETTY_FUNCTION__))
;
4606 assert(hasUnwindDest())(static_cast <bool> (hasUnwindDest()) ? void (0) : __assert_fail
("hasUnwindDest()", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4606, __extension__ __PRETTY_FUNCTION__))
;
4607 Op<1>() = NewDest;
4608 }
4609
4610 // Methods for support type inquiry through isa, cast, and dyn_cast:
4611 static bool classof(const Instruction *I) {
4612 return (I->getOpcode() == Instruction::CleanupRet);
4613 }
4614 static bool classof(const Value *V) {
4615 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4616 }
4617
4618private:
4619 BasicBlock *getSuccessor(unsigned Idx) const {
4620 assert(Idx == 0)(static_cast <bool> (Idx == 0) ? void (0) : __assert_fail
("Idx == 0", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4620, __extension__ __PRETTY_FUNCTION__))
;
4621 return getUnwindDest();
4622 }
4623
4624 void setSuccessor(unsigned Idx, BasicBlock *B) {
4625 assert(Idx == 0)(static_cast <bool> (Idx == 0) ? void (0) : __assert_fail
("Idx == 0", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4625, __extension__ __PRETTY_FUNCTION__))
;
4626 setUnwindDest(B);
4627 }
4628
4629 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4630 // method so that subclasses cannot accidentally use it.
4631 template <typename Bitfield>
4632 void setSubclassData(typename Bitfield::Type Value) {
4633 Instruction::setSubclassData<Bitfield>(Value);
4634 }
4635};
4636
4637template <>
4638struct OperandTraits<CleanupReturnInst>
4639 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4640
4641DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)CleanupReturnInst::op_iterator CleanupReturnInst::op_begin() {
return OperandTraits<CleanupReturnInst>::op_begin(this
); } CleanupReturnInst::const_op_iterator CleanupReturnInst::
op_begin() const { return OperandTraits<CleanupReturnInst>
::op_begin(const_cast<CleanupReturnInst*>(this)); } CleanupReturnInst
::op_iterator CleanupReturnInst::op_end() { return OperandTraits
<CleanupReturnInst>::op_end(this); } CleanupReturnInst::
const_op_iterator CleanupReturnInst::op_end() const { return OperandTraits
<CleanupReturnInst>::op_end(const_cast<CleanupReturnInst
*>(this)); } Value *CleanupReturnInst::getOperand(unsigned
i_nocapture) const { (static_cast <bool> (i_nocapture <
OperandTraits<CleanupReturnInst>::operands(this) &&
"getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4641, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<Value>( OperandTraits<CleanupReturnInst>::op_begin
(const_cast<CleanupReturnInst*>(this))[i_nocapture].get
()); } void CleanupReturnInst::setOperand(unsigned i_nocapture
, Value *Val_nocapture) { (static_cast <bool> (i_nocapture
< OperandTraits<CleanupReturnInst>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4641, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
CleanupReturnInst>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned CleanupReturnInst::getNumOperands() const { return
OperandTraits<CleanupReturnInst>::operands(this); } template
<int Idx_nocapture> Use &CleanupReturnInst::Op() {
return this->OpFrom<Idx_nocapture>(this); } template
<int Idx_nocapture> const Use &CleanupReturnInst::
Op() const { return this->OpFrom<Idx_nocapture>(this
); }
4642
4643//===----------------------------------------------------------------------===//
4644// UnreachableInst Class
4645//===----------------------------------------------------------------------===//
4646
4647//===---------------------------------------------------------------------------
4648/// This function has undefined behavior. In particular, the
4649/// presence of this instruction indicates some higher level knowledge that the
4650/// end of the block cannot be reached.
4651///
4652class UnreachableInst : public Instruction {
4653protected:
4654 // Note: Instruction needs to be a friend here to call cloneImpl.
4655 friend class Instruction;
4656
4657 UnreachableInst *cloneImpl() const;
4658
4659public:
4660 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4661 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4662
4663 // allocate space for exactly zero operands
4664 void *operator new(size_t s) {
4665 return User::operator new(s, 0);
4666 }
4667
4668 unsigned getNumSuccessors() const { return 0; }
4669
4670 // Methods for support type inquiry through isa, cast, and dyn_cast:
4671 static bool classof(const Instruction *I) {
4672 return I->getOpcode() == Instruction::Unreachable;
4673 }
4674 static bool classof(const Value *V) {
4675 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4676 }
4677
4678private:
4679 BasicBlock *getSuccessor(unsigned idx) const {
4680 llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4680)
;
4681 }
4682
4683 void setSuccessor(unsigned idx, BasicBlock *B) {
4684 llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 4684)
;
4685 }
4686};
4687
4688//===----------------------------------------------------------------------===//
4689// TruncInst Class
4690//===----------------------------------------------------------------------===//
4691
4692/// This class represents a truncation of integer types.
4693class TruncInst : public CastInst {
4694protected:
4695 // Note: Instruction needs to be a friend here to call cloneImpl.
4696 friend class Instruction;
4697
4698 /// Clone an identical TruncInst
4699 TruncInst *cloneImpl() const;
4700
4701public:
4702 /// Constructor with insert-before-instruction semantics
4703 TruncInst(
4704 Value *S, ///< The value to be truncated
4705 Type *Ty, ///< The (smaller) type to truncate to
4706 const Twine &NameStr = "", ///< A name for the new instruction
4707 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4708 );
4709
4710 /// Constructor with insert-at-end-of-block semantics
4711 TruncInst(
4712 Value *S, ///< The value to be truncated
4713 Type *Ty, ///< The (smaller) type to truncate to
4714 const Twine &NameStr, ///< A name for the new instruction
4715 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4716 );
4717
4718 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4719 static bool classof(const Instruction *I) {
4720 return I->getOpcode() == Trunc;
4721 }
4722 static bool classof(const Value *V) {
4723 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4724 }
4725};
4726
4727//===----------------------------------------------------------------------===//
4728// ZExtInst Class
4729//===----------------------------------------------------------------------===//
4730
4731/// This class represents zero extension of integer types.
4732class ZExtInst : public CastInst {
4733protected:
4734 // Note: Instruction needs to be a friend here to call cloneImpl.
4735 friend class Instruction;
4736
4737 /// Clone an identical ZExtInst
4738 ZExtInst *cloneImpl() const;
4739
4740public:
4741 /// Constructor with insert-before-instruction semantics
4742 ZExtInst(
4743 Value *S, ///< The value to be zero extended
4744 Type *Ty, ///< The type to zero extend to
4745 const Twine &NameStr = "", ///< A name for the new instruction
4746 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4747 );
4748
4749 /// Constructor with insert-at-end semantics.
4750 ZExtInst(
4751 Value *S, ///< The value to be zero extended
4752 Type *Ty, ///< The type to zero extend to
4753 const Twine &NameStr, ///< A name for the new instruction
4754 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4755 );
4756
4757 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4758 static bool classof(const Instruction *I) {
4759 return I->getOpcode() == ZExt;
4760 }
4761 static bool classof(const Value *V) {
4762 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4763 }
4764};
4765
4766//===----------------------------------------------------------------------===//
4767// SExtInst Class
4768//===----------------------------------------------------------------------===//
4769
4770/// This class represents a sign extension of integer types.
4771class SExtInst : public CastInst {
4772protected:
4773 // Note: Instruction needs to be a friend here to call cloneImpl.
4774 friend class Instruction;
4775
4776 /// Clone an identical SExtInst
4777 SExtInst *cloneImpl() const;
4778
4779public:
4780 /// Constructor with insert-before-instruction semantics
4781 SExtInst(
4782 Value *S, ///< The value to be sign extended
4783 Type *Ty, ///< The type to sign extend to
4784 const Twine &NameStr = "", ///< A name for the new instruction
4785 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4786 );
4787
4788 /// Constructor with insert-at-end-of-block semantics
4789 SExtInst(
4790 Value *S, ///< The value to be sign extended
4791 Type *Ty, ///< The type to sign extend to
4792 const Twine &NameStr, ///< A name for the new instruction
4793 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4794 );
4795
4796 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4797 static bool classof(const Instruction *I) {
4798 return I->getOpcode() == SExt;
4799 }
4800 static bool classof(const Value *V) {
4801 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4802 }
4803};
4804
4805//===----------------------------------------------------------------------===//
4806// FPTruncInst Class
4807//===----------------------------------------------------------------------===//
4808
4809/// This class represents a truncation of floating point types.
4810class FPTruncInst : public CastInst {
4811protected:
4812 // Note: Instruction needs to be a friend here to call cloneImpl.
4813 friend class Instruction;
4814
4815 /// Clone an identical FPTruncInst
4816 FPTruncInst *cloneImpl() const;
4817
4818public:
4819 /// Constructor with insert-before-instruction semantics
4820 FPTruncInst(
4821 Value *S, ///< The value to be truncated
4822 Type *Ty, ///< The type to truncate to
4823 const Twine &NameStr = "", ///< A name for the new instruction
4824 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4825 );
4826
4827 /// Constructor with insert-before-instruction semantics
4828 FPTruncInst(
4829 Value *S, ///< The value to be truncated
4830 Type *Ty, ///< The type to truncate to
4831 const Twine &NameStr, ///< A name for the new instruction
4832 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4833 );
4834
4835 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4836 static bool classof(const Instruction *I) {
4837 return I->getOpcode() == FPTrunc;
4838 }
4839 static bool classof(const Value *V) {
4840 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4841 }
4842};
4843
4844//===----------------------------------------------------------------------===//
4845// FPExtInst Class
4846//===----------------------------------------------------------------------===//
4847
4848/// This class represents an extension of floating point types.
4849class FPExtInst : public CastInst {
4850protected:
4851 // Note: Instruction needs to be a friend here to call cloneImpl.
4852 friend class Instruction;
4853
4854 /// Clone an identical FPExtInst
4855 FPExtInst *cloneImpl() const;
4856
4857public:
4858 /// Constructor with insert-before-instruction semantics
4859 FPExtInst(
4860 Value *S, ///< The value to be extended
4861 Type *Ty, ///< The type to extend to
4862 const Twine &NameStr = "", ///< A name for the new instruction
4863 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4864 );
4865
4866 /// Constructor with insert-at-end-of-block semantics
4867 FPExtInst(
4868 Value *S, ///< The value to be extended
4869 Type *Ty, ///< The type to extend to
4870 const Twine &NameStr, ///< A name for the new instruction
4871 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4872 );
4873
4874 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4875 static bool classof(const Instruction *I) {
4876 return I->getOpcode() == FPExt;
4877 }
4878 static bool classof(const Value *V) {
4879 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4880 }
4881};
4882
4883//===----------------------------------------------------------------------===//
4884// UIToFPInst Class
4885//===----------------------------------------------------------------------===//
4886
4887/// This class represents a cast unsigned integer to floating point.
4888class UIToFPInst : public CastInst {
4889protected:
4890 // Note: Instruction needs to be a friend here to call cloneImpl.
4891 friend class Instruction;
4892
4893 /// Clone an identical UIToFPInst
4894 UIToFPInst *cloneImpl() const;
4895
4896public:
4897 /// Constructor with insert-before-instruction semantics
4898 UIToFPInst(
4899 Value *S, ///< The value to be converted
4900 Type *Ty, ///< The type to convert to
4901 const Twine &NameStr = "", ///< A name for the new instruction
4902 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4903 );
4904
4905 /// Constructor with insert-at-end-of-block semantics
4906 UIToFPInst(
4907 Value *S, ///< The value to be converted
4908 Type *Ty, ///< The type to convert to
4909 const Twine &NameStr, ///< A name for the new instruction
4910 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4911 );
4912
4913 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4914 static bool classof(const Instruction *I) {
4915 return I->getOpcode() == UIToFP;
4916 }
4917 static bool classof(const Value *V) {
4918 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4919 }
4920};
4921
4922//===----------------------------------------------------------------------===//
4923// SIToFPInst Class
4924//===----------------------------------------------------------------------===//
4925
4926/// This class represents a cast from signed integer to floating point.
4927class SIToFPInst : public CastInst {
4928protected:
4929 // Note: Instruction needs to be a friend here to call cloneImpl.
4930 friend class Instruction;
4931
4932 /// Clone an identical SIToFPInst
4933 SIToFPInst *cloneImpl() const;
4934
4935public:
4936 /// Constructor with insert-before-instruction semantics
4937 SIToFPInst(
4938 Value *S, ///< The value to be converted
4939 Type *Ty, ///< The type to convert to
4940 const Twine &NameStr = "", ///< A name for the new instruction
4941 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4942 );
4943
4944 /// Constructor with insert-at-end-of-block semantics
4945 SIToFPInst(
4946 Value *S, ///< The value to be converted
4947 Type *Ty, ///< The type to convert to
4948 const Twine &NameStr, ///< A name for the new instruction
4949 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4950 );
4951
4952 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4953 static bool classof(const Instruction *I) {
4954 return I->getOpcode() == SIToFP;
4955 }
4956 static bool classof(const Value *V) {
4957 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4958 }
4959};
4960
4961//===----------------------------------------------------------------------===//
4962// FPToUIInst Class
4963//===----------------------------------------------------------------------===//
4964
4965/// This class represents a cast from floating point to unsigned integer
4966class FPToUIInst : public CastInst {
4967protected:
4968 // Note: Instruction needs to be a friend here to call cloneImpl.
4969 friend class Instruction;
4970
4971 /// Clone an identical FPToUIInst
4972 FPToUIInst *cloneImpl() const;
4973
4974public:
4975 /// Constructor with insert-before-instruction semantics
4976 FPToUIInst(
4977 Value *S, ///< The value to be converted
4978 Type *Ty, ///< The type to convert to
4979 const Twine &NameStr = "", ///< A name for the new instruction
4980 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4981 );
4982
4983 /// Constructor with insert-at-end-of-block semantics
4984 FPToUIInst(
4985 Value *S, ///< The value to be converted
4986 Type *Ty, ///< The type to convert to
4987 const Twine &NameStr, ///< A name for the new instruction
4988 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
4989 );
4990
4991 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4992 static bool classof(const Instruction *I) {
4993 return I->getOpcode() == FPToUI;
4994 }
4995 static bool classof(const Value *V) {
4996 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4997 }
4998};
4999
5000//===----------------------------------------------------------------------===//
5001// FPToSIInst Class
5002//===----------------------------------------------------------------------===//
5003
5004/// This class represents a cast from floating point to signed integer.
5005class FPToSIInst : public CastInst {
5006protected:
5007 // Note: Instruction needs to be a friend here to call cloneImpl.
5008 friend class Instruction;
5009
5010 /// Clone an identical FPToSIInst
5011 FPToSIInst *cloneImpl() const;
5012
5013public:
5014 /// Constructor with insert-before-instruction semantics
5015 FPToSIInst(
5016 Value *S, ///< The value to be converted
5017 Type *Ty, ///< The type to convert to
5018 const Twine &NameStr = "", ///< A name for the new instruction
5019 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5020 );
5021
5022 /// Constructor with insert-at-end-of-block semantics
5023 FPToSIInst(
5024 Value *S, ///< The value to be converted
5025 Type *Ty, ///< The type to convert to
5026 const Twine &NameStr, ///< A name for the new instruction
5027 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5028 );
5029
5030 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5031 static bool classof(const Instruction *I) {
5032 return I->getOpcode() == FPToSI;
5033 }
5034 static bool classof(const Value *V) {
5035 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5036 }
5037};
5038
5039//===----------------------------------------------------------------------===//
5040// IntToPtrInst Class
5041//===----------------------------------------------------------------------===//
5042
5043/// This class represents a cast from an integer to a pointer.
5044class IntToPtrInst : public CastInst {
5045public:
5046 // Note: Instruction needs to be a friend here to call cloneImpl.
5047 friend class Instruction;
5048
5049 /// Constructor with insert-before-instruction semantics
5050 IntToPtrInst(
5051 Value *S, ///< The value to be converted
5052 Type *Ty, ///< The type to convert to
5053 const Twine &NameStr = "", ///< A name for the new instruction
5054 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5055 );
5056
5057 /// Constructor with insert-at-end-of-block semantics
5058 IntToPtrInst(
5059 Value *S, ///< The value to be converted
5060 Type *Ty, ///< The type to convert to
5061 const Twine &NameStr, ///< A name for the new instruction
5062 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5063 );
5064
5065 /// Clone an identical IntToPtrInst.
5066 IntToPtrInst *cloneImpl() const;
5067
5068 /// Returns the address space of this instruction's pointer type.
5069 unsigned getAddressSpace() const {
5070 return getType()->getPointerAddressSpace();
5071 }
5072
5073 // Methods for support type inquiry through isa, cast, and dyn_cast:
5074 static bool classof(const Instruction *I) {
5075 return I->getOpcode() == IntToPtr;
5076 }
5077 static bool classof(const Value *V) {
5078 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5079 }
5080};
5081
5082//===----------------------------------------------------------------------===//
5083// PtrToIntInst Class
5084//===----------------------------------------------------------------------===//
5085
5086/// This class represents a cast from a pointer to an integer.
5087class PtrToIntInst : public CastInst {
5088protected:
5089 // Note: Instruction needs to be a friend here to call cloneImpl.
5090 friend class Instruction;
5091
5092 /// Clone an identical PtrToIntInst.
5093 PtrToIntInst *cloneImpl() const;
5094
5095public:
5096 /// Constructor with insert-before-instruction semantics
5097 PtrToIntInst(
5098 Value *S, ///< The value to be converted
5099 Type *Ty, ///< The type to convert to
5100 const Twine &NameStr = "", ///< A name for the new instruction
5101 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5102 );
5103
5104 /// Constructor with insert-at-end-of-block semantics
5105 PtrToIntInst(
5106 Value *S, ///< The value to be converted
5107 Type *Ty, ///< The type to convert to
5108 const Twine &NameStr, ///< A name for the new instruction
5109 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5110 );
5111
5112 /// Gets the pointer operand.
5113 Value *getPointerOperand() { return getOperand(0); }
5114 /// Gets the pointer operand.
5115 const Value *getPointerOperand() const { return getOperand(0); }
5116 /// Gets the operand index of the pointer operand.
5117 static unsigned getPointerOperandIndex() { return 0U; }
5118
5119 /// Returns the address space of the pointer operand.
5120 unsigned getPointerAddressSpace() const {
5121 return getPointerOperand()->getType()->getPointerAddressSpace();
5122 }
5123
5124 // Methods for support type inquiry through isa, cast, and dyn_cast:
5125 static bool classof(const Instruction *I) {
5126 return I->getOpcode() == PtrToInt;
5127 }
5128 static bool classof(const Value *V) {
5129 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5130 }
5131};
5132
5133//===----------------------------------------------------------------------===//
5134// BitCastInst Class
5135//===----------------------------------------------------------------------===//
5136
5137/// This class represents a no-op cast from one type to another.
5138class BitCastInst : public CastInst {
5139protected:
5140 // Note: Instruction needs to be a friend here to call cloneImpl.
5141 friend class Instruction;
5142
5143 /// Clone an identical BitCastInst.
5144 BitCastInst *cloneImpl() const;
5145
5146public:
5147 /// Constructor with insert-before-instruction semantics
5148 BitCastInst(
5149 Value *S, ///< The value to be casted
5150 Type *Ty, ///< The type to casted to
5151 const Twine &NameStr = "", ///< A name for the new instruction
5152 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5153 );
5154
5155 /// Constructor with insert-at-end-of-block semantics
5156 BitCastInst(
5157 Value *S, ///< The value to be casted
5158 Type *Ty, ///< The type to casted to
5159 const Twine &NameStr, ///< A name for the new instruction
5160 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5161 );
5162
5163 // Methods for support type inquiry through isa, cast, and dyn_cast:
5164 static bool classof(const Instruction *I) {
5165 return I->getOpcode() == BitCast;
5166 }
5167 static bool classof(const Value *V) {
5168 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5169 }
5170};
5171
5172//===----------------------------------------------------------------------===//
5173// AddrSpaceCastInst Class
5174//===----------------------------------------------------------------------===//
5175
5176/// This class represents a conversion between pointers from one address space
5177/// to another.
5178class AddrSpaceCastInst : public CastInst {
5179protected:
5180 // Note: Instruction needs to be a friend here to call cloneImpl.
5181 friend class Instruction;
5182
5183 /// Clone an identical AddrSpaceCastInst.
5184 AddrSpaceCastInst *cloneImpl() const;
5185
5186public:
5187 /// Constructor with insert-before-instruction semantics
5188 AddrSpaceCastInst(
5189 Value *S, ///< The value to be casted
5190 Type *Ty, ///< The type to casted to
5191 const Twine &NameStr = "", ///< A name for the new instruction
5192 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5193 );
5194
5195 /// Constructor with insert-at-end-of-block semantics
5196 AddrSpaceCastInst(
5197 Value *S, ///< The value to be casted
5198 Type *Ty, ///< The type to casted to
5199 const Twine &NameStr, ///< A name for the new instruction
5200 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5201 );
5202
5203 // Methods for support type inquiry through isa, cast, and dyn_cast:
5204 static bool classof(const Instruction *I) {
5205 return I->getOpcode() == AddrSpaceCast;
5206 }
5207 static bool classof(const Value *V) {
5208 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5209 }
5210
5211 /// Gets the pointer operand.
5212 Value *getPointerOperand() {
5213 return getOperand(0);
5214 }
5215
5216 /// Gets the pointer operand.
5217 const Value *getPointerOperand() const {
5218 return getOperand(0);
5219 }
5220
5221 /// Gets the operand index of the pointer operand.
5222 static unsigned getPointerOperandIndex() {
5223 return 0U;
5224 }
5225
5226 /// Returns the address space of the pointer operand.
5227 unsigned getSrcAddressSpace() const {
5228 return getPointerOperand()->getType()->getPointerAddressSpace();
5229 }
5230
5231 /// Returns the address space of the result.
5232 unsigned getDestAddressSpace() const {
5233 return getType()->getPointerAddressSpace();
5234 }
5235};
5236
5237/// A helper function that returns the pointer operand of a load or store
5238/// instruction. Returns nullptr if not load or store.
5239inline const Value *getLoadStorePointerOperand(const Value *V) {
5240 if (auto *Load = dyn_cast<LoadInst>(V))
5241 return Load->getPointerOperand();
5242 if (auto *Store = dyn_cast<StoreInst>(V))
5243 return Store->getPointerOperand();
5244 return nullptr;
5245}
5246inline Value *getLoadStorePointerOperand(Value *V) {
5247 return const_cast<Value *>(
5248 getLoadStorePointerOperand(static_cast<const Value *>(V)));
5249}
5250
5251/// A helper function that returns the pointer operand of a load, store
5252/// or GEP instruction. Returns nullptr if not load, store, or GEP.
5253inline const Value *getPointerOperand(const Value *V) {
5254 if (auto *Ptr = getLoadStorePointerOperand(V))
5255 return Ptr;
5256 if (auto *Gep = dyn_cast<GetElementPtrInst>(V))
5257 return Gep->getPointerOperand();
5258 return nullptr;
5259}
5260inline Value *getPointerOperand(Value *V) {
5261 return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V)));
5262}
5263
5264/// A helper function that returns the alignment of load or store instruction.
5265inline Align getLoadStoreAlignment(Value *I) {
5266 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 5267, __extension__ __PRETTY_FUNCTION__))
5267 "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 5267, __extension__ __PRETTY_FUNCTION__))
;
5268 if (auto *LI = dyn_cast<LoadInst>(I))
5269 return LI->getAlign();
5270 return cast<StoreInst>(I)->getAlign();
5271}
5272
5273/// A helper function that returns the address space of the pointer operand of
5274/// load or store instruction.
5275inline unsigned getLoadStoreAddressSpace(Value *I) {
5276 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 5277, __extension__ __PRETTY_FUNCTION__))
5277 "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instructions.h"
, 5277, __extension__ __PRETTY_FUNCTION__))
;
5278 if (auto *LI = dyn_cast<LoadInst>(I))
5279 return LI->getPointerAddressSpace();
5280 return cast<StoreInst>(I)->getPointerAddressSpace();
5281}
5282
5283//===----------------------------------------------------------------------===//
5284// FreezeInst Class
5285//===----------------------------------------------------------------------===//
5286
5287/// This class represents a freeze function that returns random concrete
5288/// value if an operand is either a poison value or an undef value
5289class FreezeInst : public UnaryInstruction {
5290protected:
5291 // Note: Instruction needs to be a friend here to call cloneImpl.
5292 friend class Instruction;
5293
5294 /// Clone an identical FreezeInst
5295 FreezeInst *cloneImpl() const;
5296
5297public:
5298 explicit FreezeInst(Value *S,
5299 const Twine &NameStr = "",
5300 Instruction *InsertBefore = nullptr);
5301 FreezeInst(Value *S, const Twine &NameStr, BasicBlock *InsertAtEnd);
5302
5303 // Methods for support type inquiry through isa, cast, and dyn_cast:
5304 static inline bool classof(const Instruction *I) {
5305 return I->getOpcode() == Freeze;
5306 }
5307 static inline bool classof(const Value *V) {
5308 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5309 }
5310};
5311
5312} // end namespace llvm
5313
5314#endif // LLVM_IR_INSTRUCTIONS_H

/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/IR/Instruction.h

1//===-- llvm/Instruction.h - Instruction class definition -------*- 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 contains the declaration of the Instruction class, which is the
10// base class for all of the LLVM instructions.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_IR_INSTRUCTION_H
15#define LLVM_IR_INSTRUCTION_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/Bitfields.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/ilist_node.h"
22#include "llvm/IR/DebugLoc.h"
23#include "llvm/IR/SymbolTableListTraits.h"
24#include "llvm/IR/User.h"
25#include "llvm/IR/Value.h"
26#include "llvm/Support/AtomicOrdering.h"
27#include "llvm/Support/Casting.h"
28#include <algorithm>
29#include <cassert>
30#include <cstdint>
31#include <utility>
32
33namespace llvm {
34
35class BasicBlock;
36class FastMathFlags;
37class MDNode;
38class Module;
39struct AAMDNodes;
40
41template <> struct ilist_alloc_traits<Instruction> {
42 static inline void deleteNode(Instruction *V);
43};
44
45class Instruction : public User,
46 public ilist_node_with_parent<Instruction, BasicBlock> {
47 BasicBlock *Parent;
48 DebugLoc DbgLoc; // 'dbg' Metadata cache.
49
50 /// Relative order of this instruction in its parent basic block. Used for
51 /// O(1) local dominance checks between instructions.
52 mutable unsigned Order = 0;
53
54protected:
55 // The 15 first bits of `Value::SubclassData` are available for subclasses of
56 // `Instruction` to use.
57 using OpaqueField = Bitfield::Element<uint16_t, 0, 15>;
58
59 // Template alias so that all Instruction storing alignment use the same
60 // definiton.
61 // Valid alignments are powers of two from 2^0 to 2^MaxAlignmentExponent =
62 // 2^29. We store them as Log2(Alignment), so we need 5 bits to encode the 30
63 // possible values.
64 template <unsigned Offset>
65 using AlignmentBitfieldElementT =
66 typename Bitfield::Element<unsigned, Offset, 5,
67 Value::MaxAlignmentExponent>;
68
69 template <unsigned Offset>
70 using BoolBitfieldElementT = typename Bitfield::Element<bool, Offset, 1>;
71
72 template <unsigned Offset>
73 using AtomicOrderingBitfieldElementT =
74 typename Bitfield::Element<AtomicOrdering, Offset, 3,
75 AtomicOrdering::LAST>;
76
77private:
78 // The last bit is used to store whether the instruction has metadata attached
79 // or not.
80 using HasMetadataField = Bitfield::Element<bool, 15, 1>;
81
82protected:
83 ~Instruction(); // Use deleteValue() to delete a generic Instruction.
84
85public:
86 Instruction(const Instruction &) = delete;
87 Instruction &operator=(const Instruction &) = delete;
88
89 /// Specialize the methods defined in Value, as we know that an instruction
90 /// can only be used by other instructions.
91 Instruction *user_back() { return cast<Instruction>(*user_begin());}
92 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
93
94 inline const BasicBlock *getParent() const { return Parent; }
95 inline BasicBlock *getParent() { return Parent; }
96
97 /// Return the module owning the function this instruction belongs to
98 /// or nullptr it the function does not have a module.
99 ///
100 /// Note: this is undefined behavior if the instruction does not have a
101 /// parent, or the parent basic block does not have a parent function.
102 const Module *getModule() const;
103 Module *getModule() {
104 return const_cast<Module *>(
105 static_cast<const Instruction *>(this)->getModule());
106 }
107
108 /// Return the function this instruction belongs to.
109 ///
110 /// Note: it is undefined behavior to call this on an instruction not
111 /// currently inserted into a function.
112 const Function *getFunction() const;
113 Function *getFunction() {
114 return const_cast<Function *>(
115 static_cast<const Instruction *>(this)->getFunction());
116 }
117
118 /// This method unlinks 'this' from the containing basic block, but does not
119 /// delete it.
120 void removeFromParent();
121
122 /// This method unlinks 'this' from the containing basic block and deletes it.
123 ///
124 /// \returns an iterator pointing to the element after the erased one
125 SymbolTableList<Instruction>::iterator eraseFromParent();
126
127 /// Insert an unlinked instruction into a basic block immediately before
128 /// the specified instruction.
129 void insertBefore(Instruction *InsertPos);
130
131 /// Insert an unlinked instruction into a basic block immediately after the
132 /// specified instruction.
133 void insertAfter(Instruction *InsertPos);
134
135 /// Unlink this instruction from its current basic block and insert it into
136 /// the basic block that MovePos lives in, right before MovePos.
137 void moveBefore(Instruction *MovePos);
138
139 /// Unlink this instruction and insert into BB before I.
140 ///
141 /// \pre I is a valid iterator into BB.
142 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I);
143
144 /// Unlink this instruction from its current basic block and insert it into
145 /// the basic block that MovePos lives in, right after MovePos.
146 void moveAfter(Instruction *MovePos);
147
148 /// Given an instruction Other in the same basic block as this instruction,
149 /// return true if this instruction comes before Other. In this worst case,
150 /// this takes linear time in the number of instructions in the block. The
151 /// results are cached, so in common cases when the block remains unmodified,
152 /// it takes constant time.
153 bool comesBefore(const Instruction *Other) const;
154
155 //===--------------------------------------------------------------------===//
156 // Subclass classification.
157 //===--------------------------------------------------------------------===//
158
159 /// Returns a member of one of the enums like Instruction::Add.
160 unsigned getOpcode() const { return getValueID() - InstructionVal; }
161
162 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
163 bool isTerminator() const { return isTerminator(getOpcode()); }
164 bool isUnaryOp() const { return isUnaryOp(getOpcode()); }
165 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
166 bool isIntDivRem() const { return isIntDivRem(getOpcode()); }
167 bool isShift() const { return isShift(getOpcode()); }
168 bool isCast() const { return isCast(getOpcode()); }
169 bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
170 bool isExceptionalTerminator() const {
171 return isExceptionalTerminator(getOpcode());
172 }
173 bool isIndirectTerminator() const {
174 return isIndirectTerminator(getOpcode());
175 }
176
177 static const char* getOpcodeName(unsigned OpCode);
178
179 static inline bool isTerminator(unsigned OpCode) {
180 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
181 }
182
183 static inline bool isUnaryOp(unsigned Opcode) {
184 return Opcode >= UnaryOpsBegin && Opcode < UnaryOpsEnd;
185 }
186 static inline bool isBinaryOp(unsigned Opcode) {
187 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
188 }
189
190 static inline bool isIntDivRem(unsigned Opcode) {
191 return Opcode == UDiv || Opcode == SDiv || Opcode == URem || Opcode == SRem;
192 }
193
194 /// Determine if the Opcode is one of the shift instructions.
195 static inline bool isShift(unsigned Opcode) {
196 return Opcode >= Shl && Opcode <= AShr;
197 }
198
199 /// Return true if this is a logical shift left or a logical shift right.
200 inline bool isLogicalShift() const {
201 return getOpcode() == Shl || getOpcode() == LShr;
202 }
203
204 /// Return true if this is an arithmetic shift right.
205 inline bool isArithmeticShift() const {
206 return getOpcode() == AShr;
207 }
208
209 /// Determine if the Opcode is and/or/xor.
210 static inline bool isBitwiseLogicOp(unsigned Opcode) {
211 return Opcode == And || Opcode == Or || Opcode == Xor;
212 }
213
214 /// Return true if this is and/or/xor.
215 inline bool isBitwiseLogicOp() const {
216 return isBitwiseLogicOp(getOpcode());
217 }
218
219 /// Determine if the OpCode is one of the CastInst instructions.
220 static inline bool isCast(unsigned OpCode) {
221 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
222 }
223
224 /// Determine if the OpCode is one of the FuncletPadInst instructions.
225 static inline bool isFuncletPad(unsigned OpCode) {
226 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
227 }
228
229 /// Returns true if the OpCode is a terminator related to exception handling.
230 static inline bool isExceptionalTerminator(unsigned OpCode) {
231 switch (OpCode) {
232 case Instruction::CatchSwitch:
233 case Instruction::CatchRet:
234 case Instruction::CleanupRet:
235 case Instruction::Invoke:
236 case Instruction::Resume:
237 return true;
238 default:
239 return false;
240 }
241 }
242
243 /// Returns true if the OpCode is a terminator with indirect targets.
244 static inline bool isIndirectTerminator(unsigned OpCode) {
245 switch (OpCode) {
246 case Instruction::IndirectBr:
247 case Instruction::CallBr:
248 return true;
249 default:
250 return false;
251 }
252 }
253
254 //===--------------------------------------------------------------------===//
255 // Metadata manipulation.
256 //===--------------------------------------------------------------------===//
257
258 /// Return true if this instruction has any metadata attached to it.
259 bool hasMetadata() const { return DbgLoc || Value::hasMetadata(); }
260
261 /// Return true if this instruction has metadata attached to it other than a
262 /// debug location.
263 bool hasMetadataOtherThanDebugLoc() const { return Value::hasMetadata(); }
264
265 /// Return true if this instruction has the given type of metadata attached.
266 bool hasMetadata(unsigned KindID) const {
267 return getMetadata(KindID) != nullptr;
24
Assuming the condition is false
25
Returning zero, which participates in a condition later
39
Assuming the condition is false
40
Returning zero, which participates in a condition later
268 }
269
270 /// Return true if this instruction has the given type of metadata attached.
271 bool hasMetadata(StringRef Kind) const {
272 return getMetadata(Kind) != nullptr;
273 }
274
275 /// Get the metadata of given kind attached to this Instruction.
276 /// If the metadata is not found then return null.
277 MDNode *getMetadata(unsigned KindID) const {
278 if (!hasMetadata()) return nullptr;
279 return getMetadataImpl(KindID);
280 }
281
282 /// Get the metadata of given kind attached to this Instruction.
283 /// If the metadata is not found then return null.
284 MDNode *getMetadata(StringRef Kind) const {
285 if (!hasMetadata()) return nullptr;
286 return getMetadataImpl(Kind);
287 }
288
289 /// Get all metadata attached to this Instruction. The first element of each
290 /// pair returned is the KindID, the second element is the metadata value.
291 /// This list is returned sorted by the KindID.
292 void
293 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
294 if (hasMetadata())
295 getAllMetadataImpl(MDs);
296 }
297
298 /// This does the same thing as getAllMetadata, except that it filters out the
299 /// debug location.
300 void getAllMetadataOtherThanDebugLoc(
301 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
302 Value::getAllMetadata(MDs);
303 }
304
305 /// Fills the AAMDNodes structure with AA metadata from this instruction.
306 /// When Merge is true, the existing AA metadata is merged with that from this
307 /// instruction providing the most-general result.
308 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
309
310 /// Set the metadata of the specified kind to the specified node. This updates
311 /// or replaces metadata if already present, or removes it if Node is null.
312 void setMetadata(unsigned KindID, MDNode *Node);
313 void setMetadata(StringRef Kind, MDNode *Node);
314
315 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
316 /// specifies the list of meta data that needs to be copied. If \p WL is
317 /// empty, all meta data will be copied.
318 void copyMetadata(const Instruction &SrcInst,
319 ArrayRef<unsigned> WL = ArrayRef<unsigned>());
320
321 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
322 /// has three operands (including name string), swap the order of the
323 /// metadata.
324 void swapProfMetadata();
325
326 /// Drop all unknown metadata except for debug locations.
327 /// @{
328 /// Passes are required to drop metadata they don't understand. This is a
329 /// convenience method for passes to do so.
330 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
331 void dropUnknownNonDebugMetadata() {
332 return dropUnknownNonDebugMetadata(None);
333 }
334 void dropUnknownNonDebugMetadata(unsigned ID1) {
335 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
336 }
337 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
338 unsigned IDs[] = {ID1, ID2};
339 return dropUnknownNonDebugMetadata(IDs);
340 }
341 /// @}
342
343 /// Adds an !annotation metadata node with \p Annotation to this instruction.
344 /// If this instruction already has !annotation metadata, append \p Annotation
345 /// to the existing node.
346 void addAnnotationMetadata(StringRef Annotation);
347
348 /// Sets the metadata on this instruction from the AAMDNodes structure.
349 void setAAMetadata(const AAMDNodes &N);
350
351 /// Retrieve the raw weight values of a conditional branch or select.
352 /// Returns true on success with profile weights filled in.
353 /// Returns false if no metadata or invalid metadata was found.
354 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const;
355
356 /// Retrieve total raw weight values of a branch.
357 /// Returns true on success with profile total weights filled in.
358 /// Returns false if no metadata was found.
359 bool extractProfTotalWeight(uint64_t &TotalVal) const;
360
361 /// Set the debug location information for this instruction.
362 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
363
364 /// Return the debug location for this node as a DebugLoc.
365 const DebugLoc &getDebugLoc() const { return DbgLoc; }
366
367 /// Set or clear the nuw flag on this instruction, which must be an operator
368 /// which supports this flag. See LangRef.html for the meaning of this flag.
369 void setHasNoUnsignedWrap(bool b = true);
370
371 /// Set or clear the nsw flag on this instruction, which must be an operator
372 /// which supports this flag. See LangRef.html for the meaning of this flag.
373 void setHasNoSignedWrap(bool b = true);
374
375 /// Set or clear the exact flag on this instruction, which must be an operator
376 /// which supports this flag. See LangRef.html for the meaning of this flag.
377 void setIsExact(bool b = true);
378
379 /// Determine whether the no unsigned wrap flag is set.
380 bool hasNoUnsignedWrap() const;
381
382 /// Determine whether the no signed wrap flag is set.
383 bool hasNoSignedWrap() const;
384
385 /// Drops flags that may cause this instruction to evaluate to poison despite
386 /// having non-poison inputs.
387 void dropPoisonGeneratingFlags();
388
389 /// Determine whether the exact flag is set.
390 bool isExact() const;
391
392 /// Set or clear all fast-math-flags on this instruction, which must be an
393 /// operator which supports this flag. See LangRef.html for the meaning of
394 /// this flag.
395 void setFast(bool B);
396
397 /// Set or clear the reassociation flag on this instruction, which must be
398 /// an operator which supports this flag. See LangRef.html for the meaning of
399 /// this flag.
400 void setHasAllowReassoc(bool B);
401
402 /// Set or clear the no-nans flag on this instruction, which must be an
403 /// operator which supports this flag. See LangRef.html for the meaning of
404 /// this flag.
405 void setHasNoNaNs(bool B);
406
407 /// Set or clear the no-infs flag on this instruction, which must be an
408 /// operator which supports this flag. See LangRef.html for the meaning of
409 /// this flag.
410 void setHasNoInfs(bool B);
411
412 /// Set or clear the no-signed-zeros flag on this instruction, which must be
413 /// an operator which supports this flag. See LangRef.html for the meaning of
414 /// this flag.
415 void setHasNoSignedZeros(bool B);
416
417 /// Set or clear the allow-reciprocal flag on this instruction, which must be
418 /// an operator which supports this flag. See LangRef.html for the meaning of
419 /// this flag.
420 void setHasAllowReciprocal(bool B);
421
422 /// Set or clear the allow-contract flag on this instruction, which must be
423 /// an operator which supports this flag. See LangRef.html for the meaning of
424 /// this flag.
425 void setHasAllowContract(bool B);
426
427 /// Set or clear the approximate-math-functions flag on this instruction,
428 /// which must be an operator which supports this flag. See LangRef.html for
429 /// the meaning of this flag.
430 void setHasApproxFunc(bool B);
431
432 /// Convenience function for setting multiple fast-math flags on this
433 /// instruction, which must be an operator which supports these flags. See
434 /// LangRef.html for the meaning of these flags.
435 void setFastMathFlags(FastMathFlags FMF);
436
437 /// Convenience function for transferring all fast-math flag values to this
438 /// instruction, which must be an operator which supports these flags. See
439 /// LangRef.html for the meaning of these flags.
440 void copyFastMathFlags(FastMathFlags FMF);
441
442 /// Determine whether all fast-math-flags are set.
443 bool isFast() const;
444
445 /// Determine whether the allow-reassociation flag is set.
446 bool hasAllowReassoc() const;
447
448 /// Determine whether the no-NaNs flag is set.
449 bool hasNoNaNs() const;
450
451 /// Determine whether the no-infs flag is set.
452 bool hasNoInfs() const;
453
454 /// Determine whether the no-signed-zeros flag is set.
455 bool hasNoSignedZeros() const;
456
457 /// Determine whether the allow-reciprocal flag is set.
458 bool hasAllowReciprocal() const;
459
460 /// Determine whether the allow-contract flag is set.
461 bool hasAllowContract() const;
462
463 /// Determine whether the approximate-math-functions flag is set.
464 bool hasApproxFunc() const;
465
466 /// Convenience function for getting all the fast-math flags, which must be an
467 /// operator which supports these flags. See LangRef.html for the meaning of
468 /// these flags.
469 FastMathFlags getFastMathFlags() const;
470
471 /// Copy I's fast-math flags
472 void copyFastMathFlags(const Instruction *I);
473
474 /// Convenience method to copy supported exact, fast-math, and (optionally)
475 /// wrapping flags from V to this instruction.
476 void copyIRFlags(const Value *V, bool IncludeWrapFlags = true);
477
478 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
479 /// V and this instruction.
480 void andIRFlags(const Value *V);
481
482 /// Merge 2 debug locations and apply it to the Instruction. If the
483 /// instruction is a CallIns, we need to traverse the inline chain to find
484 /// the common scope. This is not efficient for N-way merging as each time
485 /// you merge 2 iterations, you need to rebuild the hashmap to find the
486 /// common scope. However, we still choose this API because:
487 /// 1) Simplicity: it takes 2 locations instead of a list of locations.
488 /// 2) In worst case, it increases the complexity from O(N*I) to
489 /// O(2*N*I), where N is # of Instructions to merge, and I is the
490 /// maximum level of inline stack. So it is still linear.
491 /// 3) Merging of call instructions should be extremely rare in real
492 /// applications, thus the N-way merging should be in code path.
493 /// The DebugLoc attached to this instruction will be overwritten by the
494 /// merged DebugLoc.
495 void applyMergedLocation(const DILocation *LocA, const DILocation *LocB);
496
497 /// Updates the debug location given that the instruction has been hoisted
498 /// from a block to a predecessor of that block.
499 /// Note: it is undefined behavior to call this on an instruction not
500 /// currently inserted into a function.
501 void updateLocationAfterHoist();
502
503 /// Drop the instruction's debug location. This does not guarantee removal
504 /// of the !dbg source location attachment, as it must set a line 0 location
505 /// with scope information attached on call instructions. To guarantee
506 /// removal of the !dbg attachment, use the \ref setDebugLoc() API.
507 /// Note: it is undefined behavior to call this on an instruction not
508 /// currently inserted into a function.
509 void dropLocation();
510
511private:
512 // These are all implemented in Metadata.cpp.
513 MDNode *getMetadataImpl(unsigned KindID) const;
514 MDNode *getMetadataImpl(StringRef Kind) const;
515 void
516 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
517
518public:
519 //===--------------------------------------------------------------------===//
520 // Predicates and helper methods.
521 //===--------------------------------------------------------------------===//
522
523 /// Return true if the instruction is associative:
524 ///
525 /// Associative operators satisfy: x op (y op z) === (x op y) op z
526 ///
527 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
528 ///
529 bool isAssociative() const LLVM_READONLY__attribute__((__pure__));
530 static bool isAssociative(unsigned Opcode) {
531 return Opcode == And || Opcode == Or || Opcode == Xor ||
532 Opcode == Add || Opcode == Mul;
533 }
534
535 /// Return true if the instruction is commutative:
536 ///
537 /// Commutative operators satisfy: (x op y) === (y op x)
538 ///
539 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when
540 /// applied to any type.
541 ///
542 bool isCommutative() const LLVM_READONLY__attribute__((__pure__));
543 static bool isCommutative(unsigned Opcode) {
544 switch (Opcode) {
545 case Add: case FAdd:
546 case Mul: case FMul:
547 case And: case Or: case Xor:
548 return true;
549 default:
550 return false;
551 }
552 }
553
554 /// Return true if the instruction is idempotent:
555 ///
556 /// Idempotent operators satisfy: x op x === x
557 ///
558 /// In LLVM, the And and Or operators are idempotent.
559 ///
560 bool isIdempotent() const { return isIdempotent(getOpcode()); }
561 static bool isIdempotent(unsigned Opcode) {
562 return Opcode == And || Opcode == Or;
563 }
564
565 /// Return true if the instruction is nilpotent:
566 ///
567 /// Nilpotent operators satisfy: x op x === Id,
568 ///
569 /// where Id is the identity for the operator, i.e. a constant such that
570 /// x op Id === x and Id op x === x for all x.
571 ///
572 /// In LLVM, the Xor operator is nilpotent.
573 ///
574 bool isNilpotent() const { return isNilpotent(getOpcode()); }
575 static bool isNilpotent(unsigned Opcode) {
576 return Opcode == Xor;
577 }
578
579 /// Return true if this instruction may modify memory.
580 bool mayWriteToMemory() const;
581
582 /// Return true if this instruction may read memory.
583 bool mayReadFromMemory() const;
584
585 /// Return true if this instruction may read or write memory.
586 bool mayReadOrWriteMemory() const {
587 return mayReadFromMemory() || mayWriteToMemory();
588 }
589
590 /// Return true if this instruction has an AtomicOrdering of unordered or
591 /// higher.
592 bool isAtomic() const;
593
594 /// Return true if this atomic instruction loads from memory.
595 bool hasAtomicLoad() const;
596
597 /// Return true if this atomic instruction stores to memory.
598 bool hasAtomicStore() const;
599
600 /// Return true if this instruction has a volatile memory access.
601 bool isVolatile() const;
602
603 /// Return true if this instruction may throw an exception.
604 bool mayThrow() const;
605
606 /// Return true if this instruction behaves like a memory fence: it can load
607 /// or store to memory location without being given a memory location.
608 bool isFenceLike() const {
609 switch (getOpcode()) {
610 default:
611 return false;
612 // This list should be kept in sync with the list in mayWriteToMemory for
613 // all opcodes which don't have a memory location.
614 case Instruction::Fence:
615 case Instruction::CatchPad:
616 case Instruction::CatchRet:
617 case Instruction::Call:
618 case Instruction::Invoke:
619 return true;
620 }
621 }
622
623 /// Return true if the instruction may have side effects.
624 ///
625 /// Note that this does not consider malloc and alloca to have side
626 /// effects because the newly allocated memory is completely invisible to
627 /// instructions which don't use the returned value. For cases where this
628 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
629 bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
630
631 /// Return true if the instruction can be removed if the result is unused.
632 ///
633 /// When constant folding some instructions cannot be removed even if their
634 /// results are unused. Specifically terminator instructions and calls that
635 /// may have side effects cannot be removed without semantically changing the
636 /// generated program.
637 bool isSafeToRemove() const;
638
639 /// Return true if the instruction will return (unwinding is considered as
640 /// a form of returning control flow here).
641 bool willReturn() const;
642
643 /// Return true if the instruction is a variety of EH-block.
644 bool isEHPad() const {
645 switch (getOpcode()) {
646 case Instruction::CatchSwitch:
647 case Instruction::CatchPad:
648 case Instruction::CleanupPad:
649 case Instruction::LandingPad:
650 return true;
651 default:
652 return false;
653 }
654 }
655
656 /// Return true if the instruction is a llvm.lifetime.start or
657 /// llvm.lifetime.end marker.
658 bool isLifetimeStartOrEnd() const;
659
660 /// Return true if the instruction is a llvm.launder.invariant.group or
661 /// llvm.strip.invariant.group.
662 bool isLaunderOrStripInvariantGroup() const;
663
664 /// Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
665 bool isDebugOrPseudoInst() const;
666
667 /// Return a pointer to the next non-debug instruction in the same basic
668 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo
669 /// operations if \c SkipPseudoOp is true.
670 const Instruction *
671 getNextNonDebugInstruction(bool SkipPseudoOp = false) const;
672 Instruction *getNextNonDebugInstruction(bool SkipPseudoOp = false) {
673 return const_cast<Instruction *>(
674 static_cast<const Instruction *>(this)->getNextNonDebugInstruction(
675 SkipPseudoOp));
676 }
677
678 /// Return a pointer to the previous non-debug instruction in the same basic
679 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo
680 /// operations if \c SkipPseudoOp is true.
681 const Instruction *
682 getPrevNonDebugInstruction(bool SkipPseudoOp = false) const;
683 Instruction *getPrevNonDebugInstruction(bool SkipPseudoOp = false) {
684 return const_cast<Instruction *>(
685 static_cast<const Instruction *>(this)->getPrevNonDebugInstruction(
686 SkipPseudoOp));
687 }
688
689 /// Create a copy of 'this' instruction that is identical in all ways except
690 /// the following:
691 /// * The instruction has no parent
692 /// * The instruction has no name
693 ///
694 Instruction *clone() const;
695
696 /// Return true if the specified instruction is exactly identical to the
697 /// current one. This means that all operands match and any extra information
698 /// (e.g. load is volatile) agree.
699 bool isIdenticalTo(const Instruction *I) const;
700
701 /// This is like isIdenticalTo, except that it ignores the
702 /// SubclassOptionalData flags, which may specify conditions under which the
703 /// instruction's result is undefined.
704 bool isIdenticalToWhenDefined(const Instruction *I) const;
705
706 /// When checking for operation equivalence (using isSameOperationAs) it is
707 /// sometimes useful to ignore certain attributes.
708 enum OperationEquivalenceFlags {
709 /// Check for equivalence ignoring load/store alignment.
710 CompareIgnoringAlignment = 1<<0,
711 /// Check for equivalence treating a type and a vector of that type
712 /// as equivalent.
713 CompareUsingScalarTypes = 1<<1
714 };
715
716 /// This function determines if the specified instruction executes the same
717 /// operation as the current one. This means that the opcodes, type, operand
718 /// types and any other factors affecting the operation must be the same. This
719 /// is similar to isIdenticalTo except the operands themselves don't have to
720 /// be identical.
721 /// @returns true if the specified instruction is the same operation as
722 /// the current one.
723 /// Determine if one instruction is the same operation as another.
724 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
725
726 /// Return true if there are any uses of this instruction in blocks other than
727 /// the specified block. Note that PHI nodes are considered to evaluate their
728 /// operands in the corresponding predecessor block.
729 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
730
731 /// Return the number of successors that this instruction has. The instruction
732 /// must be a terminator.
733 unsigned getNumSuccessors() const;
734
735 /// Return the specified successor. This instruction must be a terminator.
736 BasicBlock *getSuccessor(unsigned Idx) const;
737
738 /// Update the specified successor to point at the provided block. This
739 /// instruction must be a terminator.
740 void setSuccessor(unsigned Idx, BasicBlock *BB);
741
742 /// Replace specified successor OldBB to point at the provided block.
743 /// This instruction must be a terminator.
744 void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB);
745
746 /// Methods for support type inquiry through isa, cast, and dyn_cast:
747 static bool classof(const Value *V) {
748 return V->getValueID() >= Value::InstructionVal;
749 }
750
751 //----------------------------------------------------------------------
752 // Exported enumerations.
753 //
754 enum TermOps { // These terminate basic blocks
755#define FIRST_TERM_INST(N) TermOpsBegin = N,
756#define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
757#define LAST_TERM_INST(N) TermOpsEnd = N+1
758#include "llvm/IR/Instruction.def"
759 };
760
761 enum UnaryOps {
762#define FIRST_UNARY_INST(N) UnaryOpsBegin = N,
763#define HANDLE_UNARY_INST(N, OPC, CLASS) OPC = N,
764#define LAST_UNARY_INST(N) UnaryOpsEnd = N+1
765#include "llvm/IR/Instruction.def"
766 };
767
768 enum BinaryOps {
769#define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
770#define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
771#define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
772#include "llvm/IR/Instruction.def"
773 };
774
775 enum MemoryOps {
776#define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
777#define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
778#define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
779#include "llvm/IR/Instruction.def"
780 };
781
782 enum CastOps {
783#define FIRST_CAST_INST(N) CastOpsBegin = N,
784#define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
785#define LAST_CAST_INST(N) CastOpsEnd = N+1
786#include "llvm/IR/Instruction.def"
787 };
788
789 enum FuncletPadOps {
790#define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
791#define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
792#define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
793#include "llvm/IR/Instruction.def"
794 };
795
796 enum OtherOps {
797#define FIRST_OTHER_INST(N) OtherOpsBegin = N,
798#define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
799#define LAST_OTHER_INST(N) OtherOpsEnd = N+1
800#include "llvm/IR/Instruction.def"
801 };
802
803private:
804 friend class SymbolTableListTraits<Instruction>;
805 friend class BasicBlock; // For renumbering.
806
807 // Shadow Value::setValueSubclassData with a private forwarding method so that
808 // subclasses cannot accidentally use it.
809 void setValueSubclassData(unsigned short D) {
810 Value::setValueSubclassData(D);
811 }
812
813 unsigned short getSubclassDataFromValue() const {
814 return Value::getSubclassDataFromValue();
815 }
816
817 void setParent(BasicBlock *P);
818
819protected:
820 // Instruction subclasses can stick up to 15 bits of stuff into the
821 // SubclassData field of instruction with these members.
822
823 template <typename BitfieldElement>
824 typename BitfieldElement::Type getSubclassData() const {
825 static_assert(
826 std::is_same<BitfieldElement, HasMetadataField>::value ||
827 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(),
828 "Must not overlap with the metadata bit");
829 return Bitfield::get<BitfieldElement>(getSubclassDataFromValue());
830 }
831
832 template <typename BitfieldElement>
833 void setSubclassData(typename BitfieldElement::Type Value) {
834 static_assert(
835 std::is_same<BitfieldElement, HasMetadataField>::value ||
836 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(),
837 "Must not overlap with the metadata bit");
838 auto Storage = getSubclassDataFromValue();
839 Bitfield::set<BitfieldElement>(Storage, Value);
840 setValueSubclassData(Storage);
841 }
842
843 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
844 Instruction *InsertBefore = nullptr);
845 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
846 BasicBlock *InsertAtEnd);
847
848private:
849 /// Create a copy of this instruction.
850 Instruction *cloneImpl() const;
851};
852
853inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) {
854 V->deleteValue();
855}
856
857} // end namespace llvm
858
859#endif // LLVM_IR_INSTRUCTION_H

/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/Support/TypeSize.h

1//===- TypeSize.h - Wrapper around type sizes -------------------*- 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 provides a struct that can be used to query the size of IR types
10// which may be scalable vectors. It provides convenience operators so that
11// it can be used in much the same way as a single scalar value.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_TYPESIZE_H
16#define LLVM_SUPPORT_TYPESIZE_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Support/WithColor.h"
21
22#include <algorithm>
23#include <array>
24#include <cassert>
25#include <cstdint>
26#include <type_traits>
27
28namespace llvm {
29
30/// Reports a diagnostic message to indicate an invalid size request has been
31/// done on a scalable vector. This function may not return.
32void reportInvalidSizeRequest(const char *Msg);
33
34template <typename LeafTy> struct LinearPolyBaseTypeTraits {};
35
36//===----------------------------------------------------------------------===//
37// LinearPolyBase - a base class for linear polynomials with multiple
38// dimensions. This can e.g. be used to describe offsets that are have both a
39// fixed and scalable component.
40//===----------------------------------------------------------------------===//
41
42/// LinearPolyBase describes a linear polynomial:
43/// c0 * scale0 + c1 * scale1 + ... + cK * scaleK
44/// where the scale is implicit, so only the coefficients are encoded.
45template <typename LeafTy>
46class LinearPolyBase {
47public:
48 using ScalarTy = typename LinearPolyBaseTypeTraits<LeafTy>::ScalarTy;
49 static constexpr auto Dimensions = LinearPolyBaseTypeTraits<LeafTy>::Dimensions;
50 static_assert(Dimensions != std::numeric_limits<unsigned>::max(),
51 "Dimensions out of range");
52
53private:
54 std::array<ScalarTy, Dimensions> Coefficients;
55
56protected:
57 LinearPolyBase(ArrayRef<ScalarTy> Values) {
58 std::copy(Values.begin(), Values.end(), Coefficients.begin());
59 }
60
61public:
62 friend LeafTy &operator+=(LeafTy &LHS, const LeafTy &RHS) {
63 for (unsigned I=0; I<Dimensions; ++I)
64 LHS.Coefficients[I] += RHS.Coefficients[I];
65 return LHS;
66 }
67
68 friend LeafTy &operator-=(LeafTy &LHS, const LeafTy &RHS) {
69 for (unsigned I=0; I<Dimensions; ++I)
70 LHS.Coefficients[I] -= RHS.Coefficients[I];
71 return LHS;
72 }
73
74 friend LeafTy &operator*=(LeafTy &LHS, ScalarTy RHS) {
75 for (auto &C : LHS.Coefficients)
76 C *= RHS;
77 return LHS;
78 }
79
80 friend LeafTy operator+(const LeafTy &LHS, const LeafTy &RHS) {
81 LeafTy Copy = LHS;
82 return Copy += RHS;
83 }
84
85 friend LeafTy operator-(const LeafTy &LHS, const LeafTy &RHS) {
86 LeafTy Copy = LHS;
87 return Copy -= RHS;
88 }
89
90 friend LeafTy operator*(const LeafTy &LHS, ScalarTy RHS) {
91 LeafTy Copy = LHS;
92 return Copy *= RHS;
93 }
94
95 template <typename U = ScalarTy>
96 friend typename std::enable_if_t<std::is_signed<U>::value, LeafTy>
97 operator-(const LeafTy &LHS) {
98 LeafTy Copy = LHS;
99 return Copy *= -1;
100 }
101
102 bool operator==(const LinearPolyBase &RHS) const {
103 return std::equal(Coefficients.begin(), Coefficients.end(),
104 RHS.Coefficients.begin());
105 }
106
107 bool operator!=(const LinearPolyBase &RHS) const {
108 return !(*this == RHS);
109 }
110
111 bool isZero() const {
112 return all_of(Coefficients, [](const ScalarTy &C) { return C == 0; });
113 }
114 bool isNonZero() const { return !isZero(); }
115 explicit operator bool() const { return isNonZero(); }
116
117 ScalarTy getValue(unsigned Dim) const { return Coefficients[Dim]; }
118};
119
120//===----------------------------------------------------------------------===//
121// StackOffset - Represent an offset with named fixed and scalable components.
122//===----------------------------------------------------------------------===//
123
124class StackOffset;
125template <> struct LinearPolyBaseTypeTraits<StackOffset> {
126 using ScalarTy = int64_t;
127 static constexpr unsigned Dimensions = 2;
128};
129
130/// StackOffset is a class to represent an offset with 2 dimensions,
131/// named fixed and scalable, respectively. This class allows a value for both
132/// dimensions to depict e.g. "8 bytes and 16 scalable bytes", which is needed
133/// to represent stack offsets.
134class StackOffset : public LinearPolyBase<StackOffset> {
135protected:
136 StackOffset(ScalarTy Fixed, ScalarTy Scalable)
137 : LinearPolyBase<StackOffset>({Fixed, Scalable}) {}
138
139public:
140 StackOffset() : StackOffset({0, 0}) {}
141 StackOffset(const LinearPolyBase<StackOffset> &Other)
142 : LinearPolyBase<StackOffset>(Other) {}
143 static StackOffset getFixed(ScalarTy Fixed) { return {Fixed, 0}; }
144 static StackOffset getScalable(ScalarTy Scalable) { return {0, Scalable}; }
145 static StackOffset get(ScalarTy Fixed, ScalarTy Scalable) {
146 return {Fixed, Scalable};
147 }
148
149 ScalarTy getFixed() const { return this->getValue(0); }
150 ScalarTy getScalable() const { return this->getValue(1); }
151};
152
153//===----------------------------------------------------------------------===//
154// UnivariateLinearPolyBase - a base class for linear polynomials with multiple
155// dimensions, but where only one dimension can be set at any time.
156// This can e.g. be used to describe sizes that are either fixed or scalable.
157//===----------------------------------------------------------------------===//
158
159/// UnivariateLinearPolyBase is a base class for ElementCount and TypeSize.
160/// Like LinearPolyBase it tries to represent a linear polynomial
161/// where only one dimension can be set at any time, e.g.
162/// 0 * scale0 + 0 * scale1 + ... + cJ * scaleJ + ... + 0 * scaleK
163/// The dimension that is set is the univariate dimension.
164template <typename LeafTy>
165class UnivariateLinearPolyBase {
166public:
167 using ScalarTy = typename LinearPolyBaseTypeTraits<LeafTy>::ScalarTy;
168 static constexpr auto Dimensions = LinearPolyBaseTypeTraits<LeafTy>::Dimensions;
169 static_assert(Dimensions != std::numeric_limits<unsigned>::max(),
170 "Dimensions out of range");
171
172protected:
173 ScalarTy Value; // The value at the univeriate dimension.
174 unsigned UnivariateDim; // The univeriate dimension.
175
176 UnivariateLinearPolyBase(ScalarTy Val, unsigned UnivariateDim)
177 : Value(Val), UnivariateDim(UnivariateDim) {
178 assert(UnivariateDim < Dimensions && "Dimension out of range")(static_cast <bool> (UnivariateDim < Dimensions &&
"Dimension out of range") ? void (0) : __assert_fail ("UnivariateDim < Dimensions && \"Dimension out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/Support/TypeSize.h"
, 178, __extension__ __PRETTY_FUNCTION__))
;
179 }
180
181 friend LeafTy &operator+=(LeafTy &LHS, const LeafTy &RHS) {
182 assert(LHS.UnivariateDim == RHS.UnivariateDim && "Invalid dimensions")(static_cast <bool> (LHS.UnivariateDim == RHS.UnivariateDim
&& "Invalid dimensions") ? void (0) : __assert_fail (
"LHS.UnivariateDim == RHS.UnivariateDim && \"Invalid dimensions\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/Support/TypeSize.h"
, 182, __extension__ __PRETTY_FUNCTION__))
;
183 LHS.Value += RHS.Value;
184 return LHS;
185 }
186
187 friend LeafTy &operator-=(LeafTy &LHS, const LeafTy &RHS) {
188 assert(LHS.UnivariateDim == RHS.UnivariateDim && "Invalid dimensions")(static_cast <bool> (LHS.UnivariateDim == RHS.UnivariateDim
&& "Invalid dimensions") ? void (0) : __assert_fail (
"LHS.UnivariateDim == RHS.UnivariateDim && \"Invalid dimensions\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/Support/TypeSize.h"
, 188, __extension__ __PRETTY_FUNCTION__))
;
189 LHS.Value -= RHS.Value;
190 return LHS;
191 }
192
193 friend LeafTy &operator*=(LeafTy &LHS, ScalarTy RHS) {
194 LHS.Value *= RHS;
195 return LHS;
196 }
197
198 friend LeafTy operator+(const LeafTy &LHS, const LeafTy &RHS) {
199 LeafTy Copy = LHS;
200 return Copy += RHS;
201 }
202
203 friend LeafTy operator-(const LeafTy &LHS, const LeafTy &RHS) {
204 LeafTy Copy = LHS;
205 return Copy -= RHS;
206 }
207
208 friend LeafTy operator*(const LeafTy &LHS, ScalarTy RHS) {
209 LeafTy Copy = LHS;
210 return Copy *= RHS;
211 }
212
213 template <typename U = ScalarTy>
214 friend typename std::enable_if<std::is_signed<U>::value, LeafTy>::type
215 operator-(const LeafTy &LHS) {
216 LeafTy Copy = LHS;
217 return Copy *= -1;
218 }
219
220public:
221 bool operator==(const UnivariateLinearPolyBase &RHS) const {
222 return Value == RHS.Value && UnivariateDim == RHS.UnivariateDim;
223 }
224
225 bool operator!=(const UnivariateLinearPolyBase &RHS) const {
226 return !(*this == RHS);
227 }
228
229 bool isZero() const { return !Value; }
230 bool isNonZero() const { return !isZero(); }
231 explicit operator bool() const { return isNonZero(); }
232 ScalarTy getValue() const { return Value; }
233 ScalarTy getValue(unsigned Dim) const {
234 return Dim == UnivariateDim ? Value : 0;
235 }
236
237 /// Add \p RHS to the value at the univariate dimension.
238 LeafTy getWithIncrement(ScalarTy RHS) const {
239 return static_cast<LeafTy>(
240 UnivariateLinearPolyBase(Value + RHS, UnivariateDim));
241 }
242
243 /// Subtract \p RHS from the value at the univariate dimension.
244 LeafTy getWithDecrement(ScalarTy RHS) const {
245 return static_cast<LeafTy>(
246 UnivariateLinearPolyBase(Value - RHS, UnivariateDim));
247 }
248};
249
250
251//===----------------------------------------------------------------------===//
252// LinearPolySize - base class for fixed- or scalable sizes.
253// ^ ^
254// | |
255// | +----- ElementCount - Leaf class to represent an element count
256// | (vscale x unsigned)
257// |
258// +-------- TypeSize - Leaf class to represent a type size
259// (vscale x uint64_t)
260//===----------------------------------------------------------------------===//
261
262/// LinearPolySize is a base class to represent sizes. It is either
263/// fixed-sized or it is scalable-sized, but it cannot be both.
264template <typename LeafTy>
265class LinearPolySize : public UnivariateLinearPolyBase<LeafTy> {
266 // Make the parent class a friend, so that it can access the protected
267 // conversion/copy-constructor for UnivariatePolyBase<LeafTy> ->
268 // LinearPolySize<LeafTy>.
269 friend class UnivariateLinearPolyBase<LeafTy>;
270
271public:
272 using ScalarTy = typename UnivariateLinearPolyBase<LeafTy>::ScalarTy;
273 enum Dims : unsigned { FixedDim = 0, ScalableDim = 1 };
274
275protected:
276 LinearPolySize(ScalarTy MinVal, Dims D)
277 : UnivariateLinearPolyBase<LeafTy>(MinVal, D) {}
278
279 LinearPolySize(const UnivariateLinearPolyBase<LeafTy> &V)
280 : UnivariateLinearPolyBase<LeafTy>(V) {}
281
282public:
283
284 static LeafTy getFixed(ScalarTy MinVal) {
285 return static_cast<LeafTy>(LinearPolySize(MinVal, FixedDim));
286 }
287 static LeafTy getScalable(ScalarTy MinVal) {
288 return static_cast<LeafTy>(LinearPolySize(MinVal, ScalableDim));
289 }
290 static LeafTy get(ScalarTy MinVal, bool Scalable) {
291 return static_cast<LeafTy>(
292 LinearPolySize(MinVal, Scalable ? ScalableDim : FixedDim));
293 }
294 static LeafTy getNull() { return get(0, false); }
295
296 /// Returns the minimum value this size can represent.
297 ScalarTy getKnownMinValue() const { return this->getValue(); }
298 /// Returns whether the size is scaled by a runtime quantity (vscale).
299 bool isScalable() const { return this->UnivariateDim == ScalableDim; }
31
Assuming field 'UnivariateDim' is equal to ScalableDim
32
Returning the value 1, which participates in a condition later
300 /// A return value of true indicates we know at compile time that the number
301 /// of elements (vscale * Min) is definitely even. However, returning false
302 /// does not guarantee that the total number of elements is odd.
303 bool isKnownEven() const { return (getKnownMinValue() & 0x1) == 0; }
304 /// This function tells the caller whether the element count is known at
305 /// compile time to be a multiple of the scalar value RHS.
306 bool isKnownMultipleOf(ScalarTy RHS) const {
307 return getKnownMinValue() % RHS == 0;
308 }
309
310 // Return the minimum value with the assumption that the count is exact.
311 // Use in places where a scalable count doesn't make sense (e.g. non-vector
312 // types, or vectors in backends which don't support scalable vectors).
313 ScalarTy getFixedValue() const {
314 assert(!isScalable() &&(static_cast <bool> (!isScalable() && "Request for a fixed element count on a scalable object"
) ? void (0) : __assert_fail ("!isScalable() && \"Request for a fixed element count on a scalable object\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/Support/TypeSize.h"
, 315, __extension__ __PRETTY_FUNCTION__))
315 "Request for a fixed element count on a scalable object")(static_cast <bool> (!isScalable() && "Request for a fixed element count on a scalable object"
) ? void (0) : __assert_fail ("!isScalable() && \"Request for a fixed element count on a scalable object\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/Support/TypeSize.h"
, 315, __extension__ __PRETTY_FUNCTION__))
;
316 return getKnownMinValue();
317 }
318
319 // For some cases, size ordering between scalable and fixed size types cannot
320 // be determined at compile time, so such comparisons aren't allowed.
321 //
322 // e.g. <vscale x 2 x i16> could be bigger than <4 x i32> with a runtime
323 // vscale >= 5, equal sized with a vscale of 4, and smaller with
324 // a vscale <= 3.
325 //
326 // All the functions below make use of the fact vscale is always >= 1, which
327 // means that <vscale x 4 x i32> is guaranteed to be >= <4 x i32>, etc.
328
329 static bool isKnownLT(const LinearPolySize &LHS, const LinearPolySize &RHS) {
330 if (!LHS.isScalable() || RHS.isScalable())
331 return LHS.getKnownMinValue() < RHS.getKnownMinValue();
332 return false;
333 }
334
335 static bool isKnownGT(const LinearPolySize &LHS, const LinearPolySize &RHS) {
336 if (LHS.isScalable() || !RHS.isScalable())
337 return LHS.getKnownMinValue() > RHS.getKnownMinValue();
338 return false;
339 }
340
341 static bool isKnownLE(const LinearPolySize &LHS, const LinearPolySize &RHS) {
342 if (!LHS.isScalable() || RHS.isScalable())
343 return LHS.getKnownMinValue() <= RHS.getKnownMinValue();
344 return false;
345 }
346
347 static bool isKnownGE(const LinearPolySize &LHS, const LinearPolySize &RHS) {
348 if (LHS.isScalable() || !RHS.isScalable())
349 return LHS.getKnownMinValue() >= RHS.getKnownMinValue();
350 return false;
351 }
352
353 /// We do not provide the '/' operator here because division for polynomial
354 /// types does not work in the same way as for normal integer types. We can
355 /// only divide the minimum value (or coefficient) by RHS, which is not the
356 /// same as
357 /// (Min * Vscale) / RHS
358 /// The caller is recommended to use this function in combination with
359 /// isKnownMultipleOf(RHS), which lets the caller know if it's possible to
360 /// perform a lossless divide by RHS.
361 LeafTy divideCoefficientBy(ScalarTy RHS) const {
362 return static_cast<LeafTy>(
363 LinearPolySize::get(getKnownMinValue() / RHS, isScalable()));
364 }
365
366 LeafTy coefficientNextPowerOf2() const {
367 return static_cast<LeafTy>(LinearPolySize::get(
368 static_cast<ScalarTy>(llvm::NextPowerOf2(getKnownMinValue())),
369 isScalable()));
370 }
371
372 /// Printing function.
373 void print(raw_ostream &OS) const {
374 if (isScalable())
375 OS << "vscale x ";
376 OS << getKnownMinValue();
377 }
378};
379
380class ElementCount;
381template <> struct LinearPolyBaseTypeTraits<ElementCount> {
382 using ScalarTy = unsigned;
383 static constexpr unsigned Dimensions = 2;
384};
385
386class ElementCount : public LinearPolySize<ElementCount> {
387public:
388 ElementCount() : LinearPolySize(LinearPolySize::getNull()) {}
389
390 ElementCount(const LinearPolySize<ElementCount> &V) : LinearPolySize(V) {}
391
392 /// Counting predicates.
393 ///
394 ///@{ Number of elements..
395 /// Exactly one element.
396 bool isScalar() const { return !isScalable() && getKnownMinValue() == 1; }
397 /// One or more elements.
398 bool isVector() const {
399 return (isScalable() && getKnownMinValue() != 0) || getKnownMinValue() > 1;
400 }
401 ///@}
402};
403
404// This class is used to represent the size of types. If the type is of fixed
405class TypeSize;
406template <> struct LinearPolyBaseTypeTraits<TypeSize> {
407 using ScalarTy = uint64_t;
408 static constexpr unsigned Dimensions = 2;
409};
410
411// TODO: Most functionality in this class will gradually be phased out
412// so it will resemble LinearPolySize as much as possible.
413//
414// TypeSize is used to represent the size of types. If the type is of fixed
415// size, it will represent the exact size. If the type is a scalable vector,
416// it will represent the known minimum size.
417class TypeSize : public LinearPolySize<TypeSize> {
418public:
419 TypeSize(const LinearPolySize<TypeSize> &V) : LinearPolySize(V) {}
420 TypeSize(ScalarTy MinVal, bool IsScalable)
421 : LinearPolySize(LinearPolySize::get(MinVal, IsScalable)) {}
422
423 static TypeSize Fixed(ScalarTy MinVal) { return TypeSize(MinVal, false); }
424 static TypeSize Scalable(ScalarTy MinVal) { return TypeSize(MinVal, true); }
425
426 ScalarTy getFixedSize() const { return getFixedValue(); }
427 ScalarTy getKnownMinSize() const { return getKnownMinValue(); }
428
429 // All code for this class below this point is needed because of the
430 // temporary implicit conversion to uint64_t. The operator overloads are
431 // needed because otherwise the conversion of the parent class
432 // UnivariateLinearPolyBase -> TypeSize is ambiguous.
433 // TODO: Remove the implicit conversion.
434
435 // Casts to a uint64_t if this is a fixed-width size.
436 //
437 // This interface is deprecated and will be removed in a future version
438 // of LLVM in favour of upgrading uses that rely on this implicit conversion
439 // to uint64_t. Calls to functions that return a TypeSize should use the
440 // proper interfaces to TypeSize.
441 // In practice this is mostly calls to MVT/EVT::getSizeInBits().
442 //
443 // To determine how to upgrade the code:
444 //
445 // if (<algorithm works for both scalable and fixed-width vectors>)
446 // use getKnownMinValue()
447 // else if (<algorithm works only for fixed-width vectors>) {
448 // if <algorithm can be adapted for both scalable and fixed-width vectors>
449 // update the algorithm and use getKnownMinValue()
450 // else
451 // bail out early for scalable vectors and use getFixedValue()
452 // }
453 operator ScalarTy() const;
454
455 // Additional operators needed to avoid ambiguous parses
456 // because of the implicit conversion hack.
457 friend TypeSize operator*(const TypeSize &LHS, const int RHS) {
458 return LHS * (ScalarTy)RHS;
459 }
460 friend TypeSize operator*(const TypeSize &LHS, const unsigned RHS) {
461 return LHS * (ScalarTy)RHS;
462 }
463 friend TypeSize operator*(const TypeSize &LHS, const int64_t RHS) {
464 return LHS * (ScalarTy)RHS;
465 }
466 friend TypeSize operator*(const int LHS, const TypeSize &RHS) {
467 return RHS * LHS;
468 }
469 friend TypeSize operator*(const unsigned LHS, const TypeSize &RHS) {
470 return RHS * LHS;
471 }
472 friend TypeSize operator*(const int64_t LHS, const TypeSize &RHS) {
473 return RHS * LHS;
474 }
475 friend TypeSize operator*(const uint64_t LHS, const TypeSize &RHS) {
476 return RHS * LHS;
477 }
478};
479
480//===----------------------------------------------------------------------===//
481// Utilities
482//===----------------------------------------------------------------------===//
483
484/// Returns a TypeSize with a known minimum size that is the next integer
485/// (mod 2**64) that is greater than or equal to \p Value and is a multiple
486/// of \p Align. \p Align must be non-zero.
487///
488/// Similar to the alignTo functions in MathExtras.h
489inline TypeSize alignTo(TypeSize Size, uint64_t Align) {
490 assert(Align != 0u && "Align must be non-zero")(static_cast <bool> (Align != 0u && "Align must be non-zero"
) ? void (0) : __assert_fail ("Align != 0u && \"Align must be non-zero\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/Support/TypeSize.h"
, 490, __extension__ __PRETTY_FUNCTION__))
;
491 return {(Size.getKnownMinValue() + Align - 1) / Align * Align,
492 Size.isScalable()};
493}
494
495/// Stream operator function for `LinearPolySize`.
496template <typename LeafTy>
497inline raw_ostream &operator<<(raw_ostream &OS,
498 const LinearPolySize<LeafTy> &PS) {
499 PS.print(OS);
500 return OS;
501}
502
503template <typename T> struct DenseMapInfo;
504template <> struct DenseMapInfo<ElementCount> {
505 static inline ElementCount getEmptyKey() {
506 return ElementCount::getScalable(~0U);
507 }
508 static inline ElementCount getTombstoneKey() {
509 return ElementCount::getFixed(~0U - 1);
510 }
511 static unsigned getHashValue(const ElementCount &EltCnt) {
512 unsigned HashVal = EltCnt.getKnownMinValue() * 37U;
513 if (EltCnt.isScalable())
514 return (HashVal - 1U);
515
516 return HashVal;
517 }
518
519 static bool isEqual(const ElementCount &LHS, const ElementCount &RHS) {
520 return LHS == RHS;
521 }
522};
523
524} // end namespace llvm
525
526#endif // LLVM_SUPPORT_TYPESIZE_H