Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LICM.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/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-12/lib/clang/12.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-12~++20210114111115+2b1e25befefc/build-llvm/lib/Transforms/Scalar -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-15-025533-4418-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/llvm/lib/Transforms/Scalar/LICM.cpp

/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/llvm/lib/Transforms/Scalar/LICM.cpp

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

/build/llvm-toolchain-snapshot-12~++20210114111115+2b1e25befefc/llvm/include/llvm/IR/Instructions.h

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