Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

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

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h

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