Bug Summary

File:llvm/lib/Target/X86/X86PartialReduction.cpp
Warning:line 238, column 26
Division by zero

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 X86PartialReduction.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 -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~++20201129111111+e987fbdd85d/build-llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/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~++20201129111111+e987fbdd85d/build-llvm/lib/Target/X86 -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d=. -ferror-limit 19 -fvisibility hidden -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-2020-11-29-190409-37574-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/Target/X86/X86PartialReduction.cpp

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/Target/X86/X86PartialReduction.cpp

1//===-- X86PartialReduction.cpp -------------------------------------------===//
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 looks for add instructions used by a horizontal reduction to see
10// if we might be able to use pmaddwd or psadbw. Some cases of this require
11// cross basic block knowledge and can't be done in SelectionDAG.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86.h"
16#include "llvm/Analysis/ValueTracking.h"
17#include "llvm/CodeGen/TargetPassConfig.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/Instructions.h"
20#include "llvm/IR/IntrinsicsX86.h"
21#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/Operator.h"
23#include "llvm/Pass.h"
24#include "X86TargetMachine.h"
25
26using namespace llvm;
27
28#define DEBUG_TYPE"x86-partial-reduction" "x86-partial-reduction"
29
30namespace {
31
32class X86PartialReduction : public FunctionPass {
33 const DataLayout *DL;
34 const X86Subtarget *ST;
35
36public:
37 static char ID; // Pass identification, replacement for typeid.
38
39 X86PartialReduction() : FunctionPass(ID) { }
40
41 bool runOnFunction(Function &Fn) override;
42
43 void getAnalysisUsage(AnalysisUsage &AU) const override {
44 AU.setPreservesCFG();
45 }
46
47 StringRef getPassName() const override {
48 return "X86 Partial Reduction";
49 }
50
51private:
52 bool tryMAddReplacement(Instruction *Op);
53 bool trySADReplacement(Instruction *Op);
54};
55}
56
57FunctionPass *llvm::createX86PartialReductionPass() {
58 return new X86PartialReduction();
59}
60
61char X86PartialReduction::ID = 0;
62
63INITIALIZE_PASS(X86PartialReduction, DEBUG_TYPE,static void *initializeX86PartialReductionPassOnce(PassRegistry
&Registry) { PassInfo *PI = new PassInfo( "X86 Partial Reduction"
, "x86-partial-reduction", &X86PartialReduction::ID, PassInfo
::NormalCtor_t(callDefaultCtor<X86PartialReduction>), false
, false); Registry.registerPass(*PI, true); return PI; } static
llvm::once_flag InitializeX86PartialReductionPassFlag; void llvm
::initializeX86PartialReductionPass(PassRegistry &Registry
) { llvm::call_once(InitializeX86PartialReductionPassFlag, initializeX86PartialReductionPassOnce
, std::ref(Registry)); }
64 "X86 Partial Reduction", false, false)static void *initializeX86PartialReductionPassOnce(PassRegistry
&Registry) { PassInfo *PI = new PassInfo( "X86 Partial Reduction"
, "x86-partial-reduction", &X86PartialReduction::ID, PassInfo
::NormalCtor_t(callDefaultCtor<X86PartialReduction>), false
, false); Registry.registerPass(*PI, true); return PI; } static
llvm::once_flag InitializeX86PartialReductionPassFlag; void llvm
::initializeX86PartialReductionPass(PassRegistry &Registry
) { llvm::call_once(InitializeX86PartialReductionPassFlag, initializeX86PartialReductionPassOnce
, std::ref(Registry)); }
65
66bool X86PartialReduction::tryMAddReplacement(Instruction *Op) {
67 if (!ST->hasSSE2())
68 return false;
69
70 // Need at least 8 elements.
71 if (cast<FixedVectorType>(Op->getType())->getNumElements() < 8)
72 return false;
73
74 // Element type should be i32.
75 if (!cast<VectorType>(Op->getType())->getElementType()->isIntegerTy(32))
76 return false;
77
78 auto *Mul = dyn_cast<BinaryOperator>(Op);
79 if (!Mul || Mul->getOpcode() != Instruction::Mul)
80 return false;
81
82 Value *LHS = Mul->getOperand(0);
83 Value *RHS = Mul->getOperand(1);
84
85 // LHS and RHS should be only used once or if they are the same then only
86 // used twice. Only check this when SSE4.1 is enabled and we have zext/sext
87 // instructions, otherwise we use punpck to emulate zero extend in stages. The
88 // trunc/ we need to do likely won't introduce new instructions in that case.
89 if (ST->hasSSE41()) {
90 if (LHS == RHS) {
91 if (!isa<Constant>(LHS) && !LHS->hasNUses(2))
92 return false;
93 } else {
94 if (!isa<Constant>(LHS) && !LHS->hasOneUse())
95 return false;
96 if (!isa<Constant>(RHS) && !RHS->hasOneUse())
97 return false;
98 }
99 }
100
101 auto CanShrinkOp = [&](Value *Op) {
102 auto IsFreeTruncation = [&](Value *Op) {
103 if (auto *Cast = dyn_cast<CastInst>(Op)) {
104 if (Cast->getParent() == Mul->getParent() &&
105 (Cast->getOpcode() == Instruction::SExt ||
106 Cast->getOpcode() == Instruction::ZExt) &&
107 Cast->getOperand(0)->getType()->getScalarSizeInBits() <= 16)
108 return true;
109 }
110
111 return isa<Constant>(Op);
112 };
113
114 // If the operation can be freely truncated and has enough sign bits we
115 // can shrink.
116 if (IsFreeTruncation(Op) &&
117 ComputeNumSignBits(Op, *DL, 0, nullptr, Mul) > 16)
118 return true;
119
120 // SelectionDAG has limited support for truncating through an add or sub if
121 // the inputs are freely truncatable.
122 if (auto *BO = dyn_cast<BinaryOperator>(Op)) {
123 if (BO->getParent() == Mul->getParent() &&
124 IsFreeTruncation(BO->getOperand(0)) &&
125 IsFreeTruncation(BO->getOperand(1)) &&
126 ComputeNumSignBits(Op, *DL, 0, nullptr, Mul) > 16)
127 return true;
128 }
129
130 return false;
131 };
132
133 // Both Ops need to be shrinkable.
134 if (!CanShrinkOp(LHS) && !CanShrinkOp(RHS))
135 return false;
136
137 IRBuilder<> Builder(Mul);
138
139 auto *MulTy = cast<FixedVectorType>(Op->getType());
140 unsigned NumElts = MulTy->getNumElements();
141
142 // Extract even elements and odd elements and add them together. This will
143 // be pattern matched by SelectionDAG to pmaddwd. This instruction will be
144 // half the original width.
145 SmallVector<int, 16> EvenMask(NumElts / 2);
146 SmallVector<int, 16> OddMask(NumElts / 2);
147 for (int i = 0, e = NumElts / 2; i != e; ++i) {
148 EvenMask[i] = i * 2;
149 OddMask[i] = i * 2 + 1;
150 }
151 // Creating a new mul so the replaceAllUsesWith below doesn't replace the
152 // uses in the shuffles we're creating.
153 Value *NewMul = Builder.CreateMul(Mul->getOperand(0), Mul->getOperand(1));
154 Value *EvenElts = Builder.CreateShuffleVector(NewMul, NewMul, EvenMask);
155 Value *OddElts = Builder.CreateShuffleVector(NewMul, NewMul, OddMask);
156 Value *MAdd = Builder.CreateAdd(EvenElts, OddElts);
157
158 // Concatenate zeroes to extend back to the original type.
159 SmallVector<int, 32> ConcatMask(NumElts);
160 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
161 Value *Zero = Constant::getNullValue(MAdd->getType());
162 Value *Concat = Builder.CreateShuffleVector(MAdd, Zero, ConcatMask);
163
164 Mul->replaceAllUsesWith(Concat);
165 Mul->eraseFromParent();
166
167 return true;
168}
169
170bool X86PartialReduction::trySADReplacement(Instruction *Op) {
171 if (!ST->hasSSE2())
12
Calling 'X86Subtarget::hasSSE2'
14
Returning from 'X86Subtarget::hasSSE2'
15
Taking false branch
172 return false;
173
174 // TODO: There's nothing special about i32, any integer type above i16 should
175 // work just as well.
176 if (!cast<VectorType>(Op->getType())->getElementType()->isIntegerTy(32))
16
The object is a 'VectorType'
17
Assuming the condition is false
18
Taking false branch
177 return false;
178
179 // Operand should be a select.
180 auto *SI = dyn_cast<SelectInst>(Op);
19
Assuming 'Op' is a 'SelectInst'
181 if (!SI
19.1
'SI' is non-null
19.1
'SI' is non-null
19.1
'SI' is non-null
)
20
Taking false branch
182 return false;
183
184 // Select needs to implement absolute value.
185 Value *LHS, *RHS;
186 auto SPR = matchSelectPattern(SI, LHS, RHS);
187 if (SPR.Flavor != SPF_ABS)
21
Assuming field 'Flavor' is equal to SPF_ABS
22
Taking false branch
188 return false;
189
190 // Need a subtract of two values.
191 auto *Sub = dyn_cast<BinaryOperator>(LHS);
23
Assuming 'LHS' is a 'BinaryOperator'
192 if (!Sub
23.1
'Sub' is non-null
23.1
'Sub' is non-null
23.1
'Sub' is non-null
|| Sub->getOpcode() != Instruction::Sub)
24
Assuming the condition is false
25
Taking false branch
193 return false;
194
195 // Look for zero extend from i8.
196 auto getZeroExtendedVal = [](Value *Op) -> Value * {
197 if (auto *ZExt = dyn_cast<ZExtInst>(Op))
27
Assuming 'ZExt' is non-null
28
Taking true branch
40
Assuming 'ZExt' is non-null
41
Taking true branch
198 if (cast<VectorType>(ZExt->getOperand(0)->getType())
29
The object is a 'VectorType'
30
Assuming the condition is true
31
Taking true branch
42
The object is a 'VectorType'
43
Assuming the condition is true
44
Taking true branch
199 ->getElementType()
200 ->isIntegerTy(8))
201 return ZExt->getOperand(0);
32
Calling 'UnaryInstruction::getOperand'
36
Returning from 'UnaryInstruction::getOperand'
37
Returning pointer, which participates in a condition later
45
Calling 'UnaryInstruction::getOperand'
49
Returning from 'UnaryInstruction::getOperand'
50
Returning pointer, which participates in a condition later
202
203 return nullptr;
204 };
205
206 // Both operands of the subtract should be extends from vXi8.
207 Value *Op0 = getZeroExtendedVal(Sub->getOperand(0));
26
Calling 'operator()'
38
Returning from 'operator()'
208 Value *Op1 = getZeroExtendedVal(Sub->getOperand(1));
39
Calling 'operator()'
51
Returning from 'operator()'
209 if (!Op0
51.1
'Op0' is non-null
51.1
'Op0' is non-null
51.1
'Op0' is non-null
|| !Op1
51.2
'Op1' is non-null
51.2
'Op1' is non-null
51.2
'Op1' is non-null
)
52
Taking false branch
210 return false;
211
212 IRBuilder<> Builder(SI);
213
214 auto *OpTy = cast<FixedVectorType>(Op->getType());
53
The object is a 'FixedVectorType'
215 unsigned NumElts = OpTy->getNumElements();
54
'NumElts' initialized here
216
217 unsigned IntrinsicNumElts;
218 Intrinsic::ID IID;
219 if (ST->hasBWI() && NumElts >= 64) {
55
Assuming the condition is false
220 IID = Intrinsic::x86_avx512_psad_bw_512;
221 IntrinsicNumElts = 64;
222 } else if (ST->hasAVX2() && NumElts >= 32) {
223 IID = Intrinsic::x86_avx2_psad_bw;
224 IntrinsicNumElts = 32;
225 } else {
226 IID = Intrinsic::x86_sse2_psad_bw;
227 IntrinsicNumElts = 16;
228 }
229
230 Function *PSADBWFn = Intrinsic::getDeclaration(SI->getModule(), IID);
231
232 if (NumElts < 16) {
56
Assuming 'NumElts' is < 16
57
Taking true branch
233 // Pad input with zeroes.
234 SmallVector<int, 32> ConcatMask(16);
235 for (unsigned i = 0; i != NumElts; ++i)
58
Assuming 'i' is equal to 'NumElts'
59
Loop condition is false. Execution continues on line 237
236 ConcatMask[i] = i;
237 for (unsigned i = NumElts; i != 16; ++i)
60
Loop condition is true. Entering loop body
238 ConcatMask[i] = (i % NumElts) + NumElts;
61
Division by zero
239
240 Value *Zero = Constant::getNullValue(Op0->getType());
241 Op0 = Builder.CreateShuffleVector(Op0, Zero, ConcatMask);
242 Op1 = Builder.CreateShuffleVector(Op1, Zero, ConcatMask);
243 NumElts = 16;
244 }
245
246 // Intrinsics produce vXi64 and need to be casted to vXi32.
247 auto *I32Ty =
248 FixedVectorType::get(Builder.getInt32Ty(), IntrinsicNumElts / 4);
249
250 assert(NumElts % IntrinsicNumElts == 0 && "Unexpected number of elements!")((NumElts % IntrinsicNumElts == 0 && "Unexpected number of elements!"
) ? static_cast<void> (0) : __assert_fail ("NumElts % IntrinsicNumElts == 0 && \"Unexpected number of elements!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/Target/X86/X86PartialReduction.cpp"
, 250, __PRETTY_FUNCTION__))
;
251 unsigned NumSplits = NumElts / IntrinsicNumElts;
252
253 // First collect the pieces we need.
254 SmallVector<Value *, 4> Ops(NumSplits);
255 for (unsigned i = 0; i != NumSplits; ++i) {
256 SmallVector<int, 64> ExtractMask(IntrinsicNumElts);
257 std::iota(ExtractMask.begin(), ExtractMask.end(), i * IntrinsicNumElts);
258 Value *ExtractOp0 = Builder.CreateShuffleVector(Op0, Op0, ExtractMask);
259 Value *ExtractOp1 = Builder.CreateShuffleVector(Op1, Op0, ExtractMask);
260 Ops[i] = Builder.CreateCall(PSADBWFn, {ExtractOp0, ExtractOp1});
261 Ops[i] = Builder.CreateBitCast(Ops[i], I32Ty);
262 }
263
264 assert(isPowerOf2_32(NumSplits) && "Expected power of 2 splits")((isPowerOf2_32(NumSplits) && "Expected power of 2 splits"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(NumSplits) && \"Expected power of 2 splits\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/Target/X86/X86PartialReduction.cpp"
, 264, __PRETTY_FUNCTION__))
;
265 unsigned Stages = Log2_32(NumSplits);
266 for (unsigned s = Stages; s > 0; --s) {
267 unsigned NumConcatElts =
268 cast<FixedVectorType>(Ops[0]->getType())->getNumElements() * 2;
269 for (unsigned i = 0; i != 1U << (s - 1); ++i) {
270 SmallVector<int, 64> ConcatMask(NumConcatElts);
271 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
272 Ops[i] = Builder.CreateShuffleVector(Ops[i*2], Ops[i*2+1], ConcatMask);
273 }
274 }
275
276 // At this point the final value should be in Ops[0]. Now we need to adjust
277 // it to the final original type.
278 NumElts = cast<FixedVectorType>(OpTy)->getNumElements();
279 if (NumElts == 2) {
280 // Extract down to 2 elements.
281 Ops[0] = Builder.CreateShuffleVector(Ops[0], Ops[0], ArrayRef<int>{0, 1});
282 } else if (NumElts >= 8) {
283 SmallVector<int, 32> ConcatMask(NumElts);
284 unsigned SubElts =
285 cast<FixedVectorType>(Ops[0]->getType())->getNumElements();
286 for (unsigned i = 0; i != SubElts; ++i)
287 ConcatMask[i] = i;
288 for (unsigned i = SubElts; i != NumElts; ++i)
289 ConcatMask[i] = (i % SubElts) + SubElts;
290
291 Value *Zero = Constant::getNullValue(Ops[0]->getType());
292 Ops[0] = Builder.CreateShuffleVector(Ops[0], Zero, ConcatMask);
293 }
294
295 SI->replaceAllUsesWith(Ops[0]);
296 SI->eraseFromParent();
297
298 return true;
299}
300
301// Walk backwards from the ExtractElementInst and determine if it is the end of
302// a horizontal reduction. Return the input to the reduction if we find one.
303static Value *matchAddReduction(const ExtractElementInst &EE) {
304 // Make sure we're extracting index 0.
305 auto *Index = dyn_cast<ConstantInt>(EE.getIndexOperand());
306 if (!Index || !Index->isNullValue())
307 return nullptr;
308
309 const auto *BO = dyn_cast<BinaryOperator>(EE.getVectorOperand());
310 if (!BO || BO->getOpcode() != Instruction::Add || !BO->hasOneUse())
311 return nullptr;
312
313 unsigned NumElems = cast<FixedVectorType>(BO->getType())->getNumElements();
314 // Ensure the reduction size is a power of 2.
315 if (!isPowerOf2_32(NumElems))
316 return nullptr;
317
318 const Value *Op = BO;
319 unsigned Stages = Log2_32(NumElems);
320 for (unsigned i = 0; i != Stages; ++i) {
321 const auto *BO = dyn_cast<BinaryOperator>(Op);
322 if (!BO || BO->getOpcode() != Instruction::Add)
323 return nullptr;
324
325 // If this isn't the first add, then it should only have 2 users, the
326 // shuffle and another add which we checked in the previous iteration.
327 if (i != 0 && !BO->hasNUses(2))
328 return nullptr;
329
330 Value *LHS = BO->getOperand(0);
331 Value *RHS = BO->getOperand(1);
332
333 auto *Shuffle = dyn_cast<ShuffleVectorInst>(LHS);
334 if (Shuffle) {
335 Op = RHS;
336 } else {
337 Shuffle = dyn_cast<ShuffleVectorInst>(RHS);
338 Op = LHS;
339 }
340
341 // The first operand of the shuffle should be the same as the other operand
342 // of the bin op.
343 if (!Shuffle || Shuffle->getOperand(0) != Op)
344 return nullptr;
345
346 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
347 unsigned MaskEnd = 1 << i;
348 for (unsigned Index = 0; Index < MaskEnd; ++Index)
349 if (Shuffle->getMaskValue(Index) != (int)(MaskEnd + Index))
350 return nullptr;
351 }
352
353 return const_cast<Value *>(Op);
354}
355
356// See if this BO is reachable from this Phi by walking forward through single
357// use BinaryOperators with the same opcode. If we get back then we know we've
358// found a loop and it is safe to step through this Add to find more leaves.
359static bool isReachableFromPHI(PHINode *Phi, BinaryOperator *BO) {
360 // The PHI itself should only have one use.
361 if (!Phi->hasOneUse())
362 return false;
363
364 Instruction *U = cast<Instruction>(*Phi->user_begin());
365 if (U == BO)
366 return true;
367
368 while (U->hasOneUse() && U->getOpcode() == BO->getOpcode())
369 U = cast<Instruction>(*U->user_begin());
370
371 return U == BO;
372}
373
374// Collect all the leaves of the tree of adds that feeds into the horizontal
375// reduction. Root is the Value that is used by the horizontal reduction.
376// We look through single use phis, single use adds, or adds that are used by
377// a phi that forms a loop with the add.
378static void collectLeaves(Value *Root, SmallVectorImpl<Instruction *> &Leaves) {
379 SmallPtrSet<Value *, 8> Visited;
380 SmallVector<Value *, 8> Worklist;
381 Worklist.push_back(Root);
382
383 while (!Worklist.empty()) {
384 Value *V = Worklist.pop_back_val();
385 if (!Visited.insert(V).second)
386 continue;
387
388 if (auto *PN = dyn_cast<PHINode>(V)) {
389 // PHI node should have single use unless it is the root node, then it
390 // has 2 uses.
391 if (!PN->hasNUses(PN == Root ? 2 : 1))
392 break;
393
394 // Push incoming values to the worklist.
395 for (Value *InV : PN->incoming_values())
396 Worklist.push_back(InV);
397
398 continue;
399 }
400
401 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
402 if (BO->getOpcode() == Instruction::Add) {
403 // Simple case. Single use, just push its operands to the worklist.
404 if (BO->hasNUses(BO == Root ? 2 : 1)) {
405 for (Value *Op : BO->operands())
406 Worklist.push_back(Op);
407 continue;
408 }
409
410 // If there is additional use, make sure it is an unvisited phi that
411 // gets us back to this node.
412 if (BO->hasNUses(BO == Root ? 3 : 2)) {
413 PHINode *PN = nullptr;
414 for (auto *U : Root->users())
415 if (auto *P = dyn_cast<PHINode>(U))
416 if (!Visited.count(P))
417 PN = P;
418
419 // If we didn't find a 2-input PHI then this isn't a case we can
420 // handle.
421 if (!PN || PN->getNumIncomingValues() != 2)
422 continue;
423
424 // Walk forward from this phi to see if it reaches back to this add.
425 if (!isReachableFromPHI(PN, BO))
426 continue;
427
428 // The phi forms a loop with this Add, push its operands.
429 for (Value *Op : BO->operands())
430 Worklist.push_back(Op);
431 }
432 }
433 }
434
435 // Not an add or phi, make it a leaf.
436 if (auto *I = dyn_cast<Instruction>(V)) {
437 if (!V->hasNUses(I == Root ? 2 : 1))
438 continue;
439
440 // Add this as a leaf.
441 Leaves.push_back(I);
442 }
443 }
444}
445
446bool X86PartialReduction::runOnFunction(Function &F) {
447 if (skipFunction(F))
1
Assuming the condition is false
2
Taking false branch
448 return false;
449
450 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
451 if (!TPC)
3
Assuming 'TPC' is non-null
4
Taking false branch
452 return false;
453
454 auto &TM = TPC->getTM<X86TargetMachine>();
455 ST = TM.getSubtargetImpl(F);
456
457 DL = &F.getParent()->getDataLayout();
458
459 bool MadeChange = false;
460 for (auto &BB : F) {
461 for (auto &I : BB) {
462 auto *EE = dyn_cast<ExtractElementInst>(&I);
5
Assuming the object is a 'ExtractElementInst'
463 if (!EE
5.1
'EE' is non-null
5.1
'EE' is non-null
5.1
'EE' is non-null
)
6
Taking false branch
464 continue;
465
466 // First find a reduction tree.
467 // FIXME: Do we need to handle other opcodes than Add?
468 Value *Root = matchAddReduction(*EE);
469 if (!Root
6.1
'Root' is non-null
6.1
'Root' is non-null
6.1
'Root' is non-null
)
7
Taking false branch
470 continue;
471
472 SmallVector<Instruction *, 8> Leaves;
473 collectLeaves(Root, Leaves);
474
475 for (Instruction *I : Leaves) {
8
Assuming '__begin3' is not equal to '__end3'
476 if (tryMAddReplacement(I)) {
9
Taking false branch
477 MadeChange = true;
478 continue;
479 }
480
481 // Don't do SAD matching on the root node. SelectionDAG already
482 // has support for that and currently generates better code.
483 if (I != Root && trySADReplacement(I))
10
Assuming 'I' is not equal to 'Root'
11
Calling 'X86PartialReduction::trySADReplacement'
484 MadeChange = true;
485 }
486 }
487 }
488
489 return MadeChange;
490}

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/Target/X86/X86Subtarget.h

1//===-- X86Subtarget.h - Define Subtarget for the X86 ----------*- 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 declares the X86 specific subclass of TargetSubtargetInfo.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_LIB_TARGET_X86_X86SUBTARGET_H
14#define LLVM_LIB_TARGET_X86_X86SUBTARGET_H
15
16#include "X86FrameLowering.h"
17#include "X86ISelLowering.h"
18#include "X86InstrInfo.h"
19#include "X86SelectionDAGInfo.h"
20#include "llvm/ADT/Triple.h"
21#include "llvm/CodeGen/TargetSubtargetInfo.h"
22#include "llvm/IR/CallingConv.h"
23#include <climits>
24#include <memory>
25
26#define GET_SUBTARGETINFO_HEADER
27#include "X86GenSubtargetInfo.inc"
28
29namespace llvm {
30
31class CallLowering;
32class GlobalValue;
33class InstructionSelector;
34class LegalizerInfo;
35class RegisterBankInfo;
36class StringRef;
37class TargetMachine;
38
39/// The X86 backend supports a number of different styles of PIC.
40///
41namespace PICStyles {
42
43enum class Style {
44 StubPIC, // Used on i386-darwin in pic mode.
45 GOT, // Used on 32 bit elf on when in pic mode.
46 RIPRel, // Used on X86-64 when in pic mode.
47 None // Set when not in pic mode.
48};
49
50} // end namespace PICStyles
51
52class X86Subtarget final : public X86GenSubtargetInfo {
53 // NOTE: Do not add anything new to this list. Coarse, CPU name based flags
54 // are not a good idea. We should be migrating away from these.
55 enum X86ProcFamilyEnum {
56 Others,
57 IntelAtom,
58 IntelSLM
59 };
60
61 enum X86SSEEnum {
62 NoSSE, SSE1, SSE2, SSE3, SSSE3, SSE41, SSE42, AVX, AVX2, AVX512F
63 };
64
65 enum X863DNowEnum {
66 NoThreeDNow, MMX, ThreeDNow, ThreeDNowA
67 };
68
69 /// X86 processor family: Intel Atom, and others
70 X86ProcFamilyEnum X86ProcFamily = Others;
71
72 /// Which PIC style to use
73 PICStyles::Style PICStyle;
74
75 const TargetMachine &TM;
76
77 /// SSE1, SSE2, SSE3, SSSE3, SSE41, SSE42, or none supported.
78 X86SSEEnum X86SSELevel = NoSSE;
79
80 /// MMX, 3DNow, 3DNow Athlon, or none supported.
81 X863DNowEnum X863DNowLevel = NoThreeDNow;
82
83 /// True if the processor supports X87 instructions.
84 bool HasX87 = false;
85
86 /// True if the processor supports CMPXCHG8B.
87 bool HasCmpxchg8b = false;
88
89 /// True if this processor has NOPL instruction
90 /// (generally pentium pro+).
91 bool HasNOPL = false;
92
93 /// True if this processor has conditional move instructions
94 /// (generally pentium pro+).
95 bool HasCMov = false;
96
97 /// True if the processor supports X86-64 instructions.
98 bool HasX86_64 = false;
99
100 /// True if the processor supports POPCNT.
101 bool HasPOPCNT = false;
102
103 /// True if the processor supports SSE4A instructions.
104 bool HasSSE4A = false;
105
106 /// Target has AES instructions
107 bool HasAES = false;
108 bool HasVAES = false;
109
110 /// Target has FXSAVE/FXRESTOR instructions
111 bool HasFXSR = false;
112
113 /// Target has XSAVE instructions
114 bool HasXSAVE = false;
115
116 /// Target has XSAVEOPT instructions
117 bool HasXSAVEOPT = false;
118
119 /// Target has XSAVEC instructions
120 bool HasXSAVEC = false;
121
122 /// Target has XSAVES instructions
123 bool HasXSAVES = false;
124
125 /// Target has carry-less multiplication
126 bool HasPCLMUL = false;
127 bool HasVPCLMULQDQ = false;
128
129 /// Target has Galois Field Arithmetic instructions
130 bool HasGFNI = false;
131
132 /// Target has 3-operand fused multiply-add
133 bool HasFMA = false;
134
135 /// Target has 4-operand fused multiply-add
136 bool HasFMA4 = false;
137
138 /// Target has XOP instructions
139 bool HasXOP = false;
140
141 /// Target has TBM instructions.
142 bool HasTBM = false;
143
144 /// Target has LWP instructions
145 bool HasLWP = false;
146
147 /// True if the processor has the MOVBE instruction.
148 bool HasMOVBE = false;
149
150 /// True if the processor has the RDRAND instruction.
151 bool HasRDRAND = false;
152
153 /// Processor has 16-bit floating point conversion instructions.
154 bool HasF16C = false;
155
156 /// Processor has FS/GS base insturctions.
157 bool HasFSGSBase = false;
158
159 /// Processor has LZCNT instruction.
160 bool HasLZCNT = false;
161
162 /// Processor has BMI1 instructions.
163 bool HasBMI = false;
164
165 /// Processor has BMI2 instructions.
166 bool HasBMI2 = false;
167
168 /// Processor has VBMI instructions.
169 bool HasVBMI = false;
170
171 /// Processor has VBMI2 instructions.
172 bool HasVBMI2 = false;
173
174 /// Processor has Integer Fused Multiply Add
175 bool HasIFMA = false;
176
177 /// Processor has RTM instructions.
178 bool HasRTM = false;
179
180 /// Processor has ADX instructions.
181 bool HasADX = false;
182
183 /// Processor has SHA instructions.
184 bool HasSHA = false;
185
186 /// Processor has PRFCHW instructions.
187 bool HasPRFCHW = false;
188
189 /// Processor has RDSEED instructions.
190 bool HasRDSEED = false;
191
192 /// Processor has LAHF/SAHF instructions in 64-bit mode.
193 bool HasLAHFSAHF64 = false;
194
195 /// Processor has MONITORX/MWAITX instructions.
196 bool HasMWAITX = false;
197
198 /// Processor has Cache Line Zero instruction
199 bool HasCLZERO = false;
200
201 /// Processor has Cache Line Demote instruction
202 bool HasCLDEMOTE = false;
203
204 /// Processor has MOVDIRI instruction (direct store integer).
205 bool HasMOVDIRI = false;
206
207 /// Processor has MOVDIR64B instruction (direct store 64 bytes).
208 bool HasMOVDIR64B = false;
209
210 /// Processor has ptwrite instruction.
211 bool HasPTWRITE = false;
212
213 /// Processor has Prefetch with intent to Write instruction
214 bool HasPREFETCHWT1 = false;
215
216 /// True if SHLD instructions are slow.
217 bool IsSHLDSlow = false;
218
219 /// True if the PMULLD instruction is slow compared to PMULLW/PMULHW and
220 // PMULUDQ.
221 bool IsPMULLDSlow = false;
222
223 /// True if the PMADDWD instruction is slow compared to PMULLD.
224 bool IsPMADDWDSlow = false;
225
226 /// True if unaligned memory accesses of 16-bytes are slow.
227 bool IsUAMem16Slow = false;
228
229 /// True if unaligned memory accesses of 32-bytes are slow.
230 bool IsUAMem32Slow = false;
231
232 /// True if SSE operations can have unaligned memory operands.
233 /// This may require setting a configuration bit in the processor.
234 bool HasSSEUnalignedMem = false;
235
236 /// True if this processor has the CMPXCHG16B instruction;
237 /// this is true for most x86-64 chips, but not the first AMD chips.
238 bool HasCmpxchg16b = false;
239
240 /// True if the LEA instruction should be used for adjusting
241 /// the stack pointer. This is an optimization for Intel Atom processors.
242 bool UseLeaForSP = false;
243
244 /// True if POPCNT instruction has a false dependency on the destination register.
245 bool HasPOPCNTFalseDeps = false;
246
247 /// True if LZCNT/TZCNT instructions have a false dependency on the destination register.
248 bool HasLZCNTFalseDeps = false;
249
250 /// True if its preferable to combine to a single shuffle using a variable
251 /// mask over multiple fixed shuffles.
252 bool HasFastVariableShuffle = false;
253
254 /// True if vzeroupper instructions should be inserted after code that uses
255 /// ymm or zmm registers.
256 bool InsertVZEROUPPER = false;
257
258 /// True if there is no performance penalty for writing NOPs with up to
259 /// 7 bytes.
260 bool HasFast7ByteNOP = false;
261
262 /// True if there is no performance penalty for writing NOPs with up to
263 /// 11 bytes.
264 bool HasFast11ByteNOP = false;
265
266 /// True if there is no performance penalty for writing NOPs with up to
267 /// 15 bytes.
268 bool HasFast15ByteNOP = false;
269
270 /// True if gather is reasonably fast. This is true for Skylake client and
271 /// all AVX-512 CPUs.
272 bool HasFastGather = false;
273
274 /// True if hardware SQRTSS instruction is at least as fast (latency) as
275 /// RSQRTSS followed by a Newton-Raphson iteration.
276 bool HasFastScalarFSQRT = false;
277
278 /// True if hardware SQRTPS/VSQRTPS instructions are at least as fast
279 /// (throughput) as RSQRTPS/VRSQRTPS followed by a Newton-Raphson iteration.
280 bool HasFastVectorFSQRT = false;
281
282 /// True if 8-bit divisions are significantly faster than
283 /// 32-bit divisions and should be used when possible.
284 bool HasSlowDivide32 = false;
285
286 /// True if 32-bit divides are significantly faster than
287 /// 64-bit divisions and should be used when possible.
288 bool HasSlowDivide64 = false;
289
290 /// True if LZCNT instruction is fast.
291 bool HasFastLZCNT = false;
292
293 /// True if SHLD based rotate is fast.
294 bool HasFastSHLDRotate = false;
295
296 /// True if the processor supports macrofusion.
297 bool HasMacroFusion = false;
298
299 /// True if the processor supports branch fusion.
300 bool HasBranchFusion = false;
301
302 /// True if the processor has enhanced REP MOVSB/STOSB.
303 bool HasERMSB = false;
304
305 /// True if the processor has fast short REP MOV.
306 bool HasFSRM = false;
307
308 /// True if the short functions should be padded to prevent
309 /// a stall when returning too early.
310 bool PadShortFunctions = false;
311
312 /// True if two memory operand instructions should use a temporary register
313 /// instead.
314 bool SlowTwoMemOps = false;
315
316 /// True if the LEA instruction inputs have to be ready at address generation
317 /// (AG) time.
318 bool LEAUsesAG = false;
319
320 /// True if the LEA instruction with certain arguments is slow
321 bool SlowLEA = false;
322
323 /// True if the LEA instruction has all three source operands: base, index,
324 /// and offset or if the LEA instruction uses base and index registers where
325 /// the base is EBP, RBP,or R13
326 bool Slow3OpsLEA = false;
327
328 /// True if INC and DEC instructions are slow when writing to flags
329 bool SlowIncDec = false;
330
331 /// Processor has AVX-512 PreFetch Instructions
332 bool HasPFI = false;
333
334 /// Processor has AVX-512 Exponential and Reciprocal Instructions
335 bool HasERI = false;
336
337 /// Processor has AVX-512 Conflict Detection Instructions
338 bool HasCDI = false;
339
340 /// Processor has AVX-512 population count Instructions
341 bool HasVPOPCNTDQ = false;
342
343 /// Processor has AVX-512 Doubleword and Quadword instructions
344 bool HasDQI = false;
345
346 /// Processor has AVX-512 Byte and Word instructions
347 bool HasBWI = false;
348
349 /// Processor has AVX-512 Vector Length eXtenstions
350 bool HasVLX = false;
351
352 /// Processor has PKU extenstions
353 bool HasPKU = false;
354
355 /// Processor has AVX-512 Vector Neural Network Instructions
356 bool HasVNNI = false;
357
358 /// Processor has AVX Vector Neural Network Instructions
359 bool HasAVXVNNI = false;
360
361 /// Processor has AVX-512 bfloat16 floating-point extensions
362 bool HasBF16 = false;
363
364 /// Processor supports ENQCMD instructions
365 bool HasENQCMD = false;
366
367 /// Processor has AVX-512 Bit Algorithms instructions
368 bool HasBITALG = false;
369
370 /// Processor has AVX-512 vp2intersect instructions
371 bool HasVP2INTERSECT = false;
372
373 /// Processor supports CET SHSTK - Control-Flow Enforcement Technology
374 /// using Shadow Stack
375 bool HasSHSTK = false;
376
377 /// Processor supports Invalidate Process-Context Identifier
378 bool HasINVPCID = false;
379
380 /// Processor has Software Guard Extensions
381 bool HasSGX = false;
382
383 /// Processor supports Flush Cache Line instruction
384 bool HasCLFLUSHOPT = false;
385
386 /// Processor supports Cache Line Write Back instruction
387 bool HasCLWB = false;
388
389 /// Processor supports Write Back No Invalidate instruction
390 bool HasWBNOINVD = false;
391
392 /// Processor support RDPID instruction
393 bool HasRDPID = false;
394
395 /// Processor supports WaitPKG instructions
396 bool HasWAITPKG = false;
397
398 /// Processor supports PCONFIG instruction
399 bool HasPCONFIG = false;
400
401 /// Processor support key locker instructions
402 bool HasKL = false;
403
404 /// Processor support key locker wide instructions
405 bool HasWIDEKL = false;
406
407 /// Processor supports HRESET instruction
408 bool HasHRESET = false;
409
410 /// Processor supports SERIALIZE instruction
411 bool HasSERIALIZE = false;
412
413 /// Processor supports TSXLDTRK instruction
414 bool HasTSXLDTRK = false;
415
416 /// Processor has AMX support
417 bool HasAMXTILE = false;
418 bool HasAMXBF16 = false;
419 bool HasAMXINT8 = false;
420
421 /// Processor supports User Level Interrupt instructions
422 bool HasUINTR = false;
423
424 /// Processor has a single uop BEXTR implementation.
425 bool HasFastBEXTR = false;
426
427 /// Try harder to combine to horizontal vector ops if they are fast.
428 bool HasFastHorizontalOps = false;
429
430 /// Prefer a left/right scalar logical shifts pair over a shift+and pair.
431 bool HasFastScalarShiftMasks = false;
432
433 /// Prefer a left/right vector logical shifts pair over a shift+and pair.
434 bool HasFastVectorShiftMasks = false;
435
436 /// Use a retpoline thunk rather than indirect calls to block speculative
437 /// execution.
438 bool UseRetpolineIndirectCalls = false;
439
440 /// Use a retpoline thunk or remove any indirect branch to block speculative
441 /// execution.
442 bool UseRetpolineIndirectBranches = false;
443
444 /// Deprecated flag, query `UseRetpolineIndirectCalls` and
445 /// `UseRetpolineIndirectBranches` instead.
446 bool DeprecatedUseRetpoline = false;
447
448 /// When using a retpoline thunk, call an externally provided thunk rather
449 /// than emitting one inside the compiler.
450 bool UseRetpolineExternalThunk = false;
451
452 /// Prevent generation of indirect call/branch instructions from memory,
453 /// and force all indirect call/branch instructions from a register to be
454 /// preceded by an LFENCE. Also decompose RET instructions into a
455 /// POP+LFENCE+JMP sequence.
456 bool UseLVIControlFlowIntegrity = false;
457
458 /// Enable Speculative Execution Side Effect Suppression
459 bool UseSpeculativeExecutionSideEffectSuppression = false;
460
461 /// Insert LFENCE instructions to prevent data speculatively injected into
462 /// loads from being used maliciously.
463 bool UseLVILoadHardening = false;
464
465 /// Use software floating point for code generation.
466 bool UseSoftFloat = false;
467
468 /// Use alias analysis during code generation.
469 bool UseAA = false;
470
471 /// The minimum alignment known to hold of the stack frame on
472 /// entry to the function and which must be maintained by every function.
473 Align stackAlignment = Align(4);
474
475 /// Max. memset / memcpy size that is turned into rep/movs, rep/stos ops.
476 ///
477 // FIXME: this is a known good value for Yonah. How about others?
478 unsigned MaxInlineSizeThreshold = 128;
479
480 /// Indicates target prefers 128 bit instructions.
481 bool Prefer128Bit = false;
482
483 /// Indicates target prefers 256 bit instructions.
484 bool Prefer256Bit = false;
485
486 /// Indicates target prefers AVX512 mask registers.
487 bool PreferMaskRegisters = false;
488
489 /// Use Goldmont specific floating point div/sqrt costs.
490 bool UseGLMDivSqrtCosts = false;
491
492 /// What processor and OS we're targeting.
493 Triple TargetTriple;
494
495 /// GlobalISel related APIs.
496 std::unique_ptr<CallLowering> CallLoweringInfo;
497 std::unique_ptr<LegalizerInfo> Legalizer;
498 std::unique_ptr<RegisterBankInfo> RegBankInfo;
499 std::unique_ptr<InstructionSelector> InstSelector;
500
501private:
502 /// Override the stack alignment.
503 MaybeAlign StackAlignOverride;
504
505 /// Preferred vector width from function attribute.
506 unsigned PreferVectorWidthOverride;
507
508 /// Resolved preferred vector width from function attribute and subtarget
509 /// features.
510 unsigned PreferVectorWidth = UINT32_MAX(4294967295U);
511
512 /// Required vector width from function attribute.
513 unsigned RequiredVectorWidth;
514
515 /// True if compiling for 64-bit, false for 16-bit or 32-bit.
516 bool In64BitMode = false;
517
518 /// True if compiling for 32-bit, false for 16-bit or 64-bit.
519 bool In32BitMode = false;
520
521 /// True if compiling for 16-bit, false for 32-bit or 64-bit.
522 bool In16BitMode = false;
523
524 X86SelectionDAGInfo TSInfo;
525 // Ordering here is important. X86InstrInfo initializes X86RegisterInfo which
526 // X86TargetLowering needs.
527 X86InstrInfo InstrInfo;
528 X86TargetLowering TLInfo;
529 X86FrameLowering FrameLowering;
530
531public:
532 /// This constructor initializes the data members to match that
533 /// of the specified triple.
534 ///
535 X86Subtarget(const Triple &TT, StringRef CPU, StringRef TuneCPU, StringRef FS,
536 const X86TargetMachine &TM, MaybeAlign StackAlignOverride,
537 unsigned PreferVectorWidthOverride,
538 unsigned RequiredVectorWidth);
539
540 const X86TargetLowering *getTargetLowering() const override {
541 return &TLInfo;
542 }
543
544 const X86InstrInfo *getInstrInfo() const override { return &InstrInfo; }
545
546 const X86FrameLowering *getFrameLowering() const override {
547 return &FrameLowering;
548 }
549
550 const X86SelectionDAGInfo *getSelectionDAGInfo() const override {
551 return &TSInfo;
552 }
553
554 const X86RegisterInfo *getRegisterInfo() const override {
555 return &getInstrInfo()->getRegisterInfo();
556 }
557
558 /// Returns the minimum alignment known to hold of the
559 /// stack frame on entry to the function and which must be maintained by every
560 /// function for this subtarget.
561 Align getStackAlignment() const { return stackAlignment; }
562
563 /// Returns the maximum memset / memcpy size
564 /// that still makes it profitable to inline the call.
565 unsigned getMaxInlineSizeThreshold() const { return MaxInlineSizeThreshold; }
566
567 /// ParseSubtargetFeatures - Parses features string setting specified
568 /// subtarget options. Definition of function is auto generated by tblgen.
569 void ParseSubtargetFeatures(StringRef CPU, StringRef TuneCPU, StringRef FS);
570
571 /// Methods used by Global ISel
572 const CallLowering *getCallLowering() const override;
573 InstructionSelector *getInstructionSelector() const override;
574 const LegalizerInfo *getLegalizerInfo() const override;
575 const RegisterBankInfo *getRegBankInfo() const override;
576
577private:
578 /// Initialize the full set of dependencies so we can use an initializer
579 /// list for X86Subtarget.
580 X86Subtarget &initializeSubtargetDependencies(StringRef CPU,
581 StringRef TuneCPU,
582 StringRef FS);
583 void initSubtargetFeatures(StringRef CPU, StringRef TuneCPU, StringRef FS);
584
585public:
586 /// Is this x86_64? (disregarding specific ABI / programming model)
587 bool is64Bit() const {
588 return In64BitMode;
589 }
590
591 bool is32Bit() const {
592 return In32BitMode;
593 }
594
595 bool is16Bit() const {
596 return In16BitMode;
597 }
598
599 /// Is this x86_64 with the ILP32 programming model (x32 ABI)?
600 bool isTarget64BitILP32() const {
601 return In64BitMode && (TargetTriple.getEnvironment() == Triple::GNUX32 ||
602 TargetTriple.isOSNaCl());
603 }
604
605 /// Is this x86_64 with the LP64 programming model (standard AMD64, no x32)?
606 bool isTarget64BitLP64() const {
607 return In64BitMode && (TargetTriple.getEnvironment() != Triple::GNUX32 &&
608 !TargetTriple.isOSNaCl());
609 }
610
611 PICStyles::Style getPICStyle() const { return PICStyle; }
612 void setPICStyle(PICStyles::Style Style) { PICStyle = Style; }
613
614 bool hasX87() const { return HasX87; }
615 bool hasCmpxchg8b() const { return HasCmpxchg8b; }
616 bool hasNOPL() const { return HasNOPL; }
617 // SSE codegen depends on cmovs, and all SSE1+ processors support them.
618 // All 64-bit processors support cmov.
619 bool hasCMov() const { return HasCMov || X86SSELevel >= SSE1 || is64Bit(); }
620 bool hasSSE1() const { return X86SSELevel >= SSE1; }
621 bool hasSSE2() const { return X86SSELevel
12.1
Field 'X86SSELevel' is >= SSE2
12.1
Field 'X86SSELevel' is >= SSE2
12.1
Field 'X86SSELevel' is >= SSE2
>= SSE2
; }
13
Returning the value 1, which participates in a condition later
622 bool hasSSE3() const { return X86SSELevel >= SSE3; }
623 bool hasSSSE3() const { return X86SSELevel >= SSSE3; }
624 bool hasSSE41() const { return X86SSELevel >= SSE41; }
625 bool hasSSE42() const { return X86SSELevel >= SSE42; }
626 bool hasAVX() const { return X86SSELevel >= AVX; }
627 bool hasAVX2() const { return X86SSELevel >= AVX2; }
628 bool hasAVX512() const { return X86SSELevel >= AVX512F; }
629 bool hasInt256() const { return hasAVX2(); }
630 bool hasSSE4A() const { return HasSSE4A; }
631 bool hasMMX() const { return X863DNowLevel >= MMX; }
632 bool has3DNow() const { return X863DNowLevel >= ThreeDNow; }
633 bool has3DNowA() const { return X863DNowLevel >= ThreeDNowA; }
634 bool hasPOPCNT() const { return HasPOPCNT; }
635 bool hasAES() const { return HasAES; }
636 bool hasVAES() const { return HasVAES; }
637 bool hasFXSR() const { return HasFXSR; }
638 bool hasXSAVE() const { return HasXSAVE; }
639 bool hasXSAVEOPT() const { return HasXSAVEOPT; }
640 bool hasXSAVEC() const { return HasXSAVEC; }
641 bool hasXSAVES() const { return HasXSAVES; }
642 bool hasPCLMUL() const { return HasPCLMUL; }
643 bool hasVPCLMULQDQ() const { return HasVPCLMULQDQ; }
644 bool hasGFNI() const { return HasGFNI; }
645 // Prefer FMA4 to FMA - its better for commutation/memory folding and
646 // has equal or better performance on all supported targets.
647 bool hasFMA() const { return HasFMA; }
648 bool hasFMA4() const { return HasFMA4; }
649 bool hasAnyFMA() const { return hasFMA() || hasFMA4(); }
650 bool hasXOP() const { return HasXOP; }
651 bool hasTBM() const { return HasTBM; }
652 bool hasLWP() const { return HasLWP; }
653 bool hasMOVBE() const { return HasMOVBE; }
654 bool hasRDRAND() const { return HasRDRAND; }
655 bool hasF16C() const { return HasF16C; }
656 bool hasFSGSBase() const { return HasFSGSBase; }
657 bool hasLZCNT() const { return HasLZCNT; }
658 bool hasBMI() const { return HasBMI; }
659 bool hasBMI2() const { return HasBMI2; }
660 bool hasVBMI() const { return HasVBMI; }
661 bool hasVBMI2() const { return HasVBMI2; }
662 bool hasIFMA() const { return HasIFMA; }
663 bool hasRTM() const { return HasRTM; }
664 bool hasADX() const { return HasADX; }
665 bool hasSHA() const { return HasSHA; }
666 bool hasPRFCHW() const { return HasPRFCHW; }
667 bool hasPREFETCHWT1() const { return HasPREFETCHWT1; }
668 bool hasPrefetchW() const {
669 // The PREFETCHW instruction was added with 3DNow but later CPUs gave it
670 // its own CPUID bit as part of deprecating 3DNow. Intel eventually added
671 // it and KNL has another that prefetches to L2 cache. We assume the
672 // L1 version exists if the L2 version does.
673 return has3DNow() || hasPRFCHW() || hasPREFETCHWT1();
674 }
675 bool hasSSEPrefetch() const {
676 // We implicitly enable these when we have a write prefix supporting cache
677 // level OR if we have prfchw, but don't already have a read prefetch from
678 // 3dnow.
679 return hasSSE1() || (hasPRFCHW() && !has3DNow()) || hasPREFETCHWT1();
680 }
681 bool hasRDSEED() const { return HasRDSEED; }
682 bool hasLAHFSAHF() const { return HasLAHFSAHF64 || !is64Bit(); }
683 bool hasMWAITX() const { return HasMWAITX; }
684 bool hasCLZERO() const { return HasCLZERO; }
685 bool hasCLDEMOTE() const { return HasCLDEMOTE; }
686 bool hasMOVDIRI() const { return HasMOVDIRI; }
687 bool hasMOVDIR64B() const { return HasMOVDIR64B; }
688 bool hasPTWRITE() const { return HasPTWRITE; }
689 bool isSHLDSlow() const { return IsSHLDSlow; }
690 bool isPMULLDSlow() const { return IsPMULLDSlow; }
691 bool isPMADDWDSlow() const { return IsPMADDWDSlow; }
692 bool isUnalignedMem16Slow() const { return IsUAMem16Slow; }
693 bool isUnalignedMem32Slow() const { return IsUAMem32Slow; }
694 bool hasSSEUnalignedMem() const { return HasSSEUnalignedMem; }
695 bool hasCmpxchg16b() const { return HasCmpxchg16b && is64Bit(); }
696 bool useLeaForSP() const { return UseLeaForSP; }
697 bool hasPOPCNTFalseDeps() const { return HasPOPCNTFalseDeps; }
698 bool hasLZCNTFalseDeps() const { return HasLZCNTFalseDeps; }
699 bool hasFastVariableShuffle() const {
700 return HasFastVariableShuffle;
701 }
702 bool insertVZEROUPPER() const { return InsertVZEROUPPER; }
703 bool hasFastGather() const { return HasFastGather; }
704 bool hasFastScalarFSQRT() const { return HasFastScalarFSQRT; }
705 bool hasFastVectorFSQRT() const { return HasFastVectorFSQRT; }
706 bool hasFastLZCNT() const { return HasFastLZCNT; }
707 bool hasFastSHLDRotate() const { return HasFastSHLDRotate; }
708 bool hasFastBEXTR() const { return HasFastBEXTR; }
709 bool hasFastHorizontalOps() const { return HasFastHorizontalOps; }
710 bool hasFastScalarShiftMasks() const { return HasFastScalarShiftMasks; }
711 bool hasFastVectorShiftMasks() const { return HasFastVectorShiftMasks; }
712 bool hasMacroFusion() const { return HasMacroFusion; }
713 bool hasBranchFusion() const { return HasBranchFusion; }
714 bool hasERMSB() const { return HasERMSB; }
715 bool hasFSRM() const { return HasFSRM; }
716 bool hasSlowDivide32() const { return HasSlowDivide32; }
717 bool hasSlowDivide64() const { return HasSlowDivide64; }
718 bool padShortFunctions() const { return PadShortFunctions; }
719 bool slowTwoMemOps() const { return SlowTwoMemOps; }
720 bool LEAusesAG() const { return LEAUsesAG; }
721 bool slowLEA() const { return SlowLEA; }
722 bool slow3OpsLEA() const { return Slow3OpsLEA; }
723 bool slowIncDec() const { return SlowIncDec; }
724 bool hasCDI() const { return HasCDI; }
725 bool hasVPOPCNTDQ() const { return HasVPOPCNTDQ; }
726 bool hasPFI() const { return HasPFI; }
727 bool hasERI() const { return HasERI; }
728 bool hasDQI() const { return HasDQI; }
729 bool hasBWI() const { return HasBWI; }
730 bool hasVLX() const { return HasVLX; }
731 bool hasPKU() const { return HasPKU; }
732 bool hasVNNI() const { return HasVNNI; }
733 bool hasBF16() const { return HasBF16; }
734 bool hasVP2INTERSECT() const { return HasVP2INTERSECT; }
735 bool hasBITALG() const { return HasBITALG; }
736 bool hasSHSTK() const { return HasSHSTK; }
737 bool hasCLFLUSHOPT() const { return HasCLFLUSHOPT; }
738 bool hasCLWB() const { return HasCLWB; }
739 bool hasWBNOINVD() const { return HasWBNOINVD; }
740 bool hasRDPID() const { return HasRDPID; }
741 bool hasWAITPKG() const { return HasWAITPKG; }
742 bool hasPCONFIG() const { return HasPCONFIG; }
743 bool hasSGX() const { return HasSGX; }
744 bool hasINVPCID() const { return HasINVPCID; }
745 bool hasENQCMD() const { return HasENQCMD; }
746 bool hasKL() const { return HasKL; }
747 bool hasWIDEKL() const { return HasWIDEKL; }
748 bool hasHRESET() const { return HasHRESET; }
749 bool hasSERIALIZE() const { return HasSERIALIZE; }
750 bool hasTSXLDTRK() const { return HasTSXLDTRK; }
751 bool hasUINTR() const { return HasUINTR; }
752 bool useRetpolineIndirectCalls() const { return UseRetpolineIndirectCalls; }
753 bool useRetpolineIndirectBranches() const {
754 return UseRetpolineIndirectBranches;
755 }
756 bool hasAVXVNNI() const { return HasAVXVNNI; }
757 bool hasAMXTILE() const { return HasAMXTILE; }
758 bool hasAMXBF16() const { return HasAMXBF16; }
759 bool hasAMXINT8() const { return HasAMXINT8; }
760 bool useRetpolineExternalThunk() const { return UseRetpolineExternalThunk; }
761
762 // These are generic getters that OR together all of the thunk types
763 // supported by the subtarget. Therefore useIndirectThunk*() will return true
764 // if any respective thunk feature is enabled.
765 bool useIndirectThunkCalls() const {
766 return useRetpolineIndirectCalls() || useLVIControlFlowIntegrity();
767 }
768 bool useIndirectThunkBranches() const {
769 return useRetpolineIndirectBranches() || useLVIControlFlowIntegrity();
770 }
771
772 bool preferMaskRegisters() const { return PreferMaskRegisters; }
773 bool useGLMDivSqrtCosts() const { return UseGLMDivSqrtCosts; }
774 bool useLVIControlFlowIntegrity() const { return UseLVIControlFlowIntegrity; }
775 bool useLVILoadHardening() const { return UseLVILoadHardening; }
776 bool useSpeculativeExecutionSideEffectSuppression() const {
777 return UseSpeculativeExecutionSideEffectSuppression;
778 }
779
780 unsigned getPreferVectorWidth() const { return PreferVectorWidth; }
781 unsigned getRequiredVectorWidth() const { return RequiredVectorWidth; }
782
783 // Helper functions to determine when we should allow widening to 512-bit
784 // during codegen.
785 // TODO: Currently we're always allowing widening on CPUs without VLX,
786 // because for many cases we don't have a better option.
787 bool canExtendTo512DQ() const {
788 return hasAVX512() && (!hasVLX() || getPreferVectorWidth() >= 512);
789 }
790 bool canExtendTo512BW() const {
791 return hasBWI() && canExtendTo512DQ();
792 }
793
794 // If there are no 512-bit vectors and we prefer not to use 512-bit registers,
795 // disable them in the legalizer.
796 bool useAVX512Regs() const {
797 return hasAVX512() && (canExtendTo512DQ() || RequiredVectorWidth > 256);
798 }
799
800 bool useBWIRegs() const {
801 return hasBWI() && useAVX512Regs();
802 }
803
804 bool isXRaySupported() const override { return is64Bit(); }
805
806 /// TODO: to be removed later and replaced with suitable properties
807 bool isAtom() const { return X86ProcFamily == IntelAtom; }
808 bool isSLM() const { return X86ProcFamily == IntelSLM; }
809 bool useSoftFloat() const { return UseSoftFloat; }
810 bool useAA() const override { return UseAA; }
811
812 /// Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
813 /// no-sse2). There isn't any reason to disable it if the target processor
814 /// supports it.
815 bool hasMFence() const { return hasSSE2() || is64Bit(); }
816
817 const Triple &getTargetTriple() const { return TargetTriple; }
818
819 bool isTargetDarwin() const { return TargetTriple.isOSDarwin(); }
820 bool isTargetFreeBSD() const { return TargetTriple.isOSFreeBSD(); }
821 bool isTargetDragonFly() const { return TargetTriple.isOSDragonFly(); }
822 bool isTargetSolaris() const { return TargetTriple.isOSSolaris(); }
823 bool isTargetPS4() const { return TargetTriple.isPS4CPU(); }
824
825 bool isTargetELF() const { return TargetTriple.isOSBinFormatELF(); }
826 bool isTargetCOFF() const { return TargetTriple.isOSBinFormatCOFF(); }
827 bool isTargetMachO() const { return TargetTriple.isOSBinFormatMachO(); }
828
829 bool isTargetLinux() const { return TargetTriple.isOSLinux(); }
830 bool isTargetKFreeBSD() const { return TargetTriple.isOSKFreeBSD(); }
831 bool isTargetGlibc() const { return TargetTriple.isOSGlibc(); }
832 bool isTargetAndroid() const { return TargetTriple.isAndroid(); }
833 bool isTargetNaCl() const { return TargetTriple.isOSNaCl(); }
834 bool isTargetNaCl32() const { return isTargetNaCl() && !is64Bit(); }
835 bool isTargetNaCl64() const { return isTargetNaCl() && is64Bit(); }
836 bool isTargetMCU() const { return TargetTriple.isOSIAMCU(); }
837 bool isTargetFuchsia() const { return TargetTriple.isOSFuchsia(); }
838
839 bool isTargetWindowsMSVC() const {
840 return TargetTriple.isWindowsMSVCEnvironment();
841 }
842
843 bool isTargetWindowsCoreCLR() const {
844 return TargetTriple.isWindowsCoreCLREnvironment();
845 }
846
847 bool isTargetWindowsCygwin() const {
848 return TargetTriple.isWindowsCygwinEnvironment();
849 }
850
851 bool isTargetWindowsGNU() const {
852 return TargetTriple.isWindowsGNUEnvironment();
853 }
854
855 bool isTargetWindowsItanium() const {
856 return TargetTriple.isWindowsItaniumEnvironment();
857 }
858
859 bool isTargetCygMing() const { return TargetTriple.isOSCygMing(); }
860
861 bool isOSWindows() const { return TargetTriple.isOSWindows(); }
862
863 bool isTargetWin64() const { return In64BitMode && isOSWindows(); }
864
865 bool isTargetWin32() const { return !In64BitMode && isOSWindows(); }
866
867 bool isPICStyleGOT() const { return PICStyle == PICStyles::Style::GOT; }
868 bool isPICStyleRIPRel() const { return PICStyle == PICStyles::Style::RIPRel; }
869
870 bool isPICStyleStubPIC() const {
871 return PICStyle == PICStyles::Style::StubPIC;
872 }
873
874 bool isPositionIndependent() const;
875
876 bool isCallingConvWin64(CallingConv::ID CC) const {
877 switch (CC) {
878 // On Win64, all these conventions just use the default convention.
879 case CallingConv::C:
880 case CallingConv::Fast:
881 case CallingConv::Tail:
882 case CallingConv::Swift:
883 case CallingConv::X86_FastCall:
884 case CallingConv::X86_StdCall:
885 case CallingConv::X86_ThisCall:
886 case CallingConv::X86_VectorCall:
887 case CallingConv::Intel_OCL_BI:
888 return isTargetWin64();
889 // This convention allows using the Win64 convention on other targets.
890 case CallingConv::Win64:
891 return true;
892 // This convention allows using the SysV convention on Windows targets.
893 case CallingConv::X86_64_SysV:
894 return false;
895 // Otherwise, who knows what this is.
896 default:
897 return false;
898 }
899 }
900
901 /// Classify a global variable reference for the current subtarget according
902 /// to how we should reference it in a non-pcrel context.
903 unsigned char classifyLocalReference(const GlobalValue *GV) const;
904
905 unsigned char classifyGlobalReference(const GlobalValue *GV,
906 const Module &M) const;
907 unsigned char classifyGlobalReference(const GlobalValue *GV) const;
908
909 /// Classify a global function reference for the current subtarget.
910 unsigned char classifyGlobalFunctionReference(const GlobalValue *GV,
911 const Module &M) const;
912 unsigned char classifyGlobalFunctionReference(const GlobalValue *GV) const;
913
914 /// Classify a blockaddress reference for the current subtarget according to
915 /// how we should reference it in a non-pcrel context.
916 unsigned char classifyBlockAddressReference() const;
917
918 /// Return true if the subtarget allows calls to immediate address.
919 bool isLegalToCallImmediateAddr() const;
920
921 /// If we are using indirect thunks, we need to expand indirectbr to avoid it
922 /// lowering to an actual indirect jump.
923 bool enableIndirectBrExpand() const override {
924 return useIndirectThunkBranches();
925 }
926
927 /// Enable the MachineScheduler pass for all X86 subtargets.
928 bool enableMachineScheduler() const override { return true; }
929
930 bool enableEarlyIfConversion() const override;
931
932 void getPostRAMutations(std::vector<std::unique_ptr<ScheduleDAGMutation>>
933 &Mutations) const override;
934
935 AntiDepBreakMode getAntiDepBreakMode() const override {
936 return TargetSubtargetInfo::ANTIDEP_CRITICAL;
937 }
938
939 bool enableAdvancedRASplitCost() const override { return true; }
940};
941
942} // end namespace llvm
943
944#endif // LLVM_LIB_TARGET_X86_X86SUBTARGET_H

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h

1//===- llvm/InstrTypes.h - Important Instruction subclasses -----*- 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 defines various meta classes of instructions that exist in the VM
10// representation. Specific concrete subclasses of these may be found in the
11// i*.h files...
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_INSTRTYPES_H
16#define LLVM_IR_INSTRTYPES_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/CallingConv.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/Instruction.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/OperandTraits.h"
34#include "llvm/IR/Type.h"
35#include "llvm/IR/User.h"
36#include "llvm/IR/Value.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/ErrorHandling.h"
39#include <algorithm>
40#include <cassert>
41#include <cstddef>
42#include <cstdint>
43#include <iterator>
44#include <string>
45#include <vector>
46
47namespace llvm {
48
49namespace Intrinsic {
50typedef unsigned ID;
51}
52
53//===----------------------------------------------------------------------===//
54// UnaryInstruction Class
55//===----------------------------------------------------------------------===//
56
57class UnaryInstruction : public Instruction {
58protected:
59 UnaryInstruction(Type *Ty, unsigned iType, Value *V,
60 Instruction *IB = nullptr)
61 : Instruction(Ty, iType, &Op<0>(), 1, IB) {
62 Op<0>() = V;
63 }
64 UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
65 : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
66 Op<0>() = V;
67 }
68
69public:
70 // allocate space for exactly one operand
71 void *operator new(size_t s) {
72 return User::operator new(s, 1);
73 }
74
75 /// Transparently provide more efficient getOperand methods.
76 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
;
77
78 // Methods for support type inquiry through isa, cast, and dyn_cast:
79 static bool classof(const Instruction *I) {
80 return I->isUnaryOp() ||
81 I->getOpcode() == Instruction::Alloca ||
82 I->getOpcode() == Instruction::Load ||
83 I->getOpcode() == Instruction::VAArg ||
84 I->getOpcode() == Instruction::ExtractValue ||
85 (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
86 }
87 static bool classof(const Value *V) {
88 return isa<Instruction>(V) && classof(cast<Instruction>(V));
89 }
90};
91
92template <>
93struct OperandTraits<UnaryInstruction> :
94 public FixedNumOperandTraits<UnaryInstruction, 1> {
95};
96
97DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)UnaryInstruction::op_iterator UnaryInstruction::op_begin() { return
OperandTraits<UnaryInstruction>::op_begin(this); } UnaryInstruction
::const_op_iterator UnaryInstruction::op_begin() const { return
OperandTraits<UnaryInstruction>::op_begin(const_cast<
UnaryInstruction*>(this)); } UnaryInstruction::op_iterator
UnaryInstruction::op_end() { return OperandTraits<UnaryInstruction
>::op_end(this); } UnaryInstruction::const_op_iterator UnaryInstruction
::op_end() const { return OperandTraits<UnaryInstruction>
::op_end(const_cast<UnaryInstruction*>(this)); } Value *
UnaryInstruction::getOperand(unsigned i_nocapture) const { ((
i_nocapture < OperandTraits<UnaryInstruction>::operands
(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<UnaryInstruction>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 97, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<UnaryInstruction>::op_begin(const_cast<
UnaryInstruction*>(this))[i_nocapture].get()); } void UnaryInstruction
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<UnaryInstruction>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<UnaryInstruction>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 97, __PRETTY_FUNCTION__)); OperandTraits<UnaryInstruction
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
UnaryInstruction::getNumOperands() const { return OperandTraits
<UnaryInstruction>::operands(this); } template <int Idx_nocapture
> Use &UnaryInstruction::Op() { return this->OpFrom
<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &UnaryInstruction::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
33
'?' condition is true
34
The object is a 'Value'
35
Returning pointer, which participates in a condition later
46
'?' condition is true
47
The object is a 'Value'
48
Returning pointer, which participates in a condition later
98
99//===----------------------------------------------------------------------===//
100// UnaryOperator Class
101//===----------------------------------------------------------------------===//
102
103class UnaryOperator : public UnaryInstruction {
104 void AssertOK();
105
106protected:
107 UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
108 const Twine &Name, Instruction *InsertBefore);
109 UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
110 const Twine &Name, BasicBlock *InsertAtEnd);
111
112 // Note: Instruction needs to be a friend here to call cloneImpl.
113 friend class Instruction;
114
115 UnaryOperator *cloneImpl() const;
116
117public:
118
119 /// Construct a unary instruction, given the opcode and an operand.
120 /// Optionally (if InstBefore is specified) insert the instruction
121 /// into a BasicBlock right before the specified instruction. The specified
122 /// Instruction is allowed to be a dereferenced end iterator.
123 ///
124 static UnaryOperator *Create(UnaryOps Op, Value *S,
125 const Twine &Name = Twine(),
126 Instruction *InsertBefore = nullptr);
127
128 /// Construct a unary instruction, given the opcode and an operand.
129 /// Also automatically insert this instruction to the end of the
130 /// BasicBlock specified.
131 ///
132 static UnaryOperator *Create(UnaryOps Op, Value *S,
133 const Twine &Name,
134 BasicBlock *InsertAtEnd);
135
136 /// These methods just forward to Create, and are useful when you
137 /// statically know what type of instruction you're going to create. These
138 /// helpers just save some typing.
139#define HANDLE_UNARY_INST(N, OPC, CLASS) \
140 static UnaryOperator *Create##OPC(Value *V, const Twine &Name = "") {\
141 return Create(Instruction::OPC, V, Name);\
142 }
143#include "llvm/IR/Instruction.def"
144#define HANDLE_UNARY_INST(N, OPC, CLASS) \
145 static UnaryOperator *Create##OPC(Value *V, const Twine &Name, \
146 BasicBlock *BB) {\
147 return Create(Instruction::OPC, V, Name, BB);\
148 }
149#include "llvm/IR/Instruction.def"
150#define HANDLE_UNARY_INST(N, OPC, CLASS) \
151 static UnaryOperator *Create##OPC(Value *V, const Twine &Name, \
152 Instruction *I) {\
153 return Create(Instruction::OPC, V, Name, I);\
154 }
155#include "llvm/IR/Instruction.def"
156
157 static UnaryOperator *
158 CreateWithCopiedFlags(UnaryOps Opc, Value *V, Instruction *CopyO,
159 const Twine &Name = "",
160 Instruction *InsertBefore = nullptr) {
161 UnaryOperator *UO = Create(Opc, V, Name, InsertBefore);
162 UO->copyIRFlags(CopyO);
163 return UO;
164 }
165
166 static UnaryOperator *CreateFNegFMF(Value *Op, Instruction *FMFSource,
167 const Twine &Name = "",
168 Instruction *InsertBefore = nullptr) {
169 return CreateWithCopiedFlags(Instruction::FNeg, Op, FMFSource, Name,
170 InsertBefore);
171 }
172
173 UnaryOps getOpcode() const {
174 return static_cast<UnaryOps>(Instruction::getOpcode());
175 }
176
177 // Methods for support type inquiry through isa, cast, and dyn_cast:
178 static bool classof(const Instruction *I) {
179 return I->isUnaryOp();
180 }
181 static bool classof(const Value *V) {
182 return isa<Instruction>(V) && classof(cast<Instruction>(V));
183 }
184};
185
186//===----------------------------------------------------------------------===//
187// BinaryOperator Class
188//===----------------------------------------------------------------------===//
189
190class BinaryOperator : public Instruction {
191 void AssertOK();
192
193protected:
194 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
195 const Twine &Name, Instruction *InsertBefore);
196 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
197 const Twine &Name, BasicBlock *InsertAtEnd);
198
199 // Note: Instruction needs to be a friend here to call cloneImpl.
200 friend class Instruction;
201
202 BinaryOperator *cloneImpl() const;
203
204public:
205 // allocate space for exactly two operands
206 void *operator new(size_t s) {
207 return User::operator new(s, 2);
208 }
209
210 /// Transparently provide more efficient getOperand methods.
211 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
;
212
213 /// Construct a binary instruction, given the opcode and the two
214 /// operands. Optionally (if InstBefore is specified) insert the instruction
215 /// into a BasicBlock right before the specified instruction. The specified
216 /// Instruction is allowed to be a dereferenced end iterator.
217 ///
218 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
219 const Twine &Name = Twine(),
220 Instruction *InsertBefore = nullptr);
221
222 /// Construct a binary instruction, given the opcode and the two
223 /// operands. Also automatically insert this instruction to the end of the
224 /// BasicBlock specified.
225 ///
226 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
227 const Twine &Name, BasicBlock *InsertAtEnd);
228
229 /// These methods just forward to Create, and are useful when you
230 /// statically know what type of instruction you're going to create. These
231 /// helpers just save some typing.
232#define HANDLE_BINARY_INST(N, OPC, CLASS) \
233 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
234 const Twine &Name = "") {\
235 return Create(Instruction::OPC, V1, V2, Name);\
236 }
237#include "llvm/IR/Instruction.def"
238#define HANDLE_BINARY_INST(N, OPC, CLASS) \
239 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
240 const Twine &Name, BasicBlock *BB) {\
241 return Create(Instruction::OPC, V1, V2, Name, BB);\
242 }
243#include "llvm/IR/Instruction.def"
244#define HANDLE_BINARY_INST(N, OPC, CLASS) \
245 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
246 const Twine &Name, Instruction *I) {\
247 return Create(Instruction::OPC, V1, V2, Name, I);\
248 }
249#include "llvm/IR/Instruction.def"
250
251 static BinaryOperator *CreateWithCopiedFlags(BinaryOps Opc,
252 Value *V1, Value *V2,
253 Instruction *CopyO,
254 const Twine &Name = "") {
255 BinaryOperator *BO = Create(Opc, V1, V2, Name);
256 BO->copyIRFlags(CopyO);
257 return BO;
258 }
259
260 static BinaryOperator *CreateFAddFMF(Value *V1, Value *V2,
261 Instruction *FMFSource,
262 const Twine &Name = "") {
263 return CreateWithCopiedFlags(Instruction::FAdd, V1, V2, FMFSource, Name);
264 }
265 static BinaryOperator *CreateFSubFMF(Value *V1, Value *V2,
266 Instruction *FMFSource,
267 const Twine &Name = "") {
268 return CreateWithCopiedFlags(Instruction::FSub, V1, V2, FMFSource, Name);
269 }
270 static BinaryOperator *CreateFMulFMF(Value *V1, Value *V2,
271 Instruction *FMFSource,
272 const Twine &Name = "") {
273 return CreateWithCopiedFlags(Instruction::FMul, V1, V2, FMFSource, Name);
274 }
275 static BinaryOperator *CreateFDivFMF(Value *V1, Value *V2,
276 Instruction *FMFSource,
277 const Twine &Name = "") {
278 return CreateWithCopiedFlags(Instruction::FDiv, V1, V2, FMFSource, Name);
279 }
280 static BinaryOperator *CreateFRemFMF(Value *V1, Value *V2,
281 Instruction *FMFSource,
282 const Twine &Name = "") {
283 return CreateWithCopiedFlags(Instruction::FRem, V1, V2, FMFSource, Name);
284 }
285
286 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
287 const Twine &Name = "") {
288 BinaryOperator *BO = Create(Opc, V1, V2, Name);
289 BO->setHasNoSignedWrap(true);
290 return BO;
291 }
292 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
293 const Twine &Name, BasicBlock *BB) {
294 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
295 BO->setHasNoSignedWrap(true);
296 return BO;
297 }
298 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
299 const Twine &Name, Instruction *I) {
300 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
301 BO->setHasNoSignedWrap(true);
302 return BO;
303 }
304
305 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
306 const Twine &Name = "") {
307 BinaryOperator *BO = Create(Opc, V1, V2, Name);
308 BO->setHasNoUnsignedWrap(true);
309 return BO;
310 }
311 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
312 const Twine &Name, BasicBlock *BB) {
313 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
314 BO->setHasNoUnsignedWrap(true);
315 return BO;
316 }
317 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
318 const Twine &Name, Instruction *I) {
319 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
320 BO->setHasNoUnsignedWrap(true);
321 return BO;
322 }
323
324 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
325 const Twine &Name = "") {
326 BinaryOperator *BO = Create(Opc, V1, V2, Name);
327 BO->setIsExact(true);
328 return BO;
329 }
330 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
331 const Twine &Name, BasicBlock *BB) {
332 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
333 BO->setIsExact(true);
334 return BO;
335 }
336 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
337 const Twine &Name, Instruction *I) {
338 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
339 BO->setIsExact(true);
340 return BO;
341 }
342
343#define DEFINE_HELPERS(OPC, NUWNSWEXACT) \
344 static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2, \
345 const Twine &Name = "") { \
346 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \
347 } \
348 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
349 Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) { \
350 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB); \
351 } \
352 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
353 Value *V1, Value *V2, const Twine &Name, Instruction *I) { \
354 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I); \
355 }
356
357 DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
358 DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
359 DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
360 DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
361 DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
362 DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
363 DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
364 DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
365
366 DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv
367 DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv
368 DEFINE_HELPERS(AShr, Exact) // CreateExactAShr
369 DEFINE_HELPERS(LShr, Exact) // CreateExactLShr
370
371#undef DEFINE_HELPERS
372
373 /// Helper functions to construct and inspect unary operations (NEG and NOT)
374 /// via binary operators SUB and XOR:
375 ///
376 /// Create the NEG and NOT instructions out of SUB and XOR instructions.
377 ///
378 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
379 Instruction *InsertBefore = nullptr);
380 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
381 BasicBlock *InsertAtEnd);
382 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
383 Instruction *InsertBefore = nullptr);
384 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
385 BasicBlock *InsertAtEnd);
386 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
387 Instruction *InsertBefore = nullptr);
388 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
389 BasicBlock *InsertAtEnd);
390 static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
391 Instruction *InsertBefore = nullptr);
392 static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
393 BasicBlock *InsertAtEnd);
394
395 BinaryOps getOpcode() const {
396 return static_cast<BinaryOps>(Instruction::getOpcode());
397 }
398
399 /// Exchange the two operands to this instruction.
400 /// This instruction is safe to use on any binary instruction and
401 /// does not modify the semantics of the instruction. If the instruction
402 /// cannot be reversed (ie, it's a Div), then return true.
403 ///
404 bool swapOperands();
405
406 // Methods for support type inquiry through isa, cast, and dyn_cast:
407 static bool classof(const Instruction *I) {
408 return I->isBinaryOp();
409 }
410 static bool classof(const Value *V) {
411 return isa<Instruction>(V) && classof(cast<Instruction>(V));
412 }
413};
414
415template <>
416struct OperandTraits<BinaryOperator> :
417 public FixedNumOperandTraits<BinaryOperator, 2> {
418};
419
420DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)BinaryOperator::op_iterator BinaryOperator::op_begin() { return
OperandTraits<BinaryOperator>::op_begin(this); } BinaryOperator
::const_op_iterator BinaryOperator::op_begin() const { return
OperandTraits<BinaryOperator>::op_begin(const_cast<
BinaryOperator*>(this)); } BinaryOperator::op_iterator BinaryOperator
::op_end() { return OperandTraits<BinaryOperator>::op_end
(this); } BinaryOperator::const_op_iterator BinaryOperator::op_end
() const { return OperandTraits<BinaryOperator>::op_end
(const_cast<BinaryOperator*>(this)); } Value *BinaryOperator
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<BinaryOperator>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<BinaryOperator>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 420, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<BinaryOperator>::op_begin(const_cast<
BinaryOperator*>(this))[i_nocapture].get()); } void BinaryOperator
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<BinaryOperator>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BinaryOperator>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 420, __PRETTY_FUNCTION__)); OperandTraits<BinaryOperator
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
BinaryOperator::getNumOperands() const { return OperandTraits
<BinaryOperator>::operands(this); } template <int Idx_nocapture
> Use &BinaryOperator::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &BinaryOperator::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
421
422//===----------------------------------------------------------------------===//
423// CastInst Class
424//===----------------------------------------------------------------------===//
425
426/// This is the base class for all instructions that perform data
427/// casts. It is simply provided so that instruction category testing
428/// can be performed with code like:
429///
430/// if (isa<CastInst>(Instr)) { ... }
431/// Base class of casting instructions.
432class CastInst : public UnaryInstruction {
433protected:
434 /// Constructor with insert-before-instruction semantics for subclasses
435 CastInst(Type *Ty, unsigned iType, Value *S,
436 const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
437 : UnaryInstruction(Ty, iType, S, InsertBefore) {
438 setName(NameStr);
439 }
440 /// Constructor with insert-at-end-of-block semantics for subclasses
441 CastInst(Type *Ty, unsigned iType, Value *S,
442 const Twine &NameStr, BasicBlock *InsertAtEnd)
443 : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
444 setName(NameStr);
445 }
446
447public:
448 /// Provides a way to construct any of the CastInst subclasses using an
449 /// opcode instead of the subclass's constructor. The opcode must be in the
450 /// CastOps category (Instruction::isCast(opcode) returns true). This
451 /// constructor has insert-before-instruction semantics to automatically
452 /// insert the new CastInst before InsertBefore (if it is non-null).
453 /// Construct any of the CastInst subclasses
454 static CastInst *Create(
455 Instruction::CastOps, ///< The opcode of the cast instruction
456 Value *S, ///< The value to be casted (operand 0)
457 Type *Ty, ///< The type to which cast should be made
458 const Twine &Name = "", ///< Name for the instruction
459 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
460 );
461 /// Provides a way to construct any of the CastInst subclasses using an
462 /// opcode instead of the subclass's constructor. The opcode must be in the
463 /// CastOps category. This constructor has insert-at-end-of-block semantics
464 /// to automatically insert the new CastInst at the end of InsertAtEnd (if
465 /// its non-null).
466 /// Construct any of the CastInst subclasses
467 static CastInst *Create(
468 Instruction::CastOps, ///< The opcode for the cast instruction
469 Value *S, ///< The value to be casted (operand 0)
470 Type *Ty, ///< The type to which operand is casted
471 const Twine &Name, ///< The name for the instruction
472 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
473 );
474
475 /// Create a ZExt or BitCast cast instruction
476 static CastInst *CreateZExtOrBitCast(
477 Value *S, ///< The value to be casted (operand 0)
478 Type *Ty, ///< The type to which cast should be made
479 const Twine &Name = "", ///< Name for the instruction
480 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
481 );
482
483 /// Create a ZExt or BitCast cast instruction
484 static CastInst *CreateZExtOrBitCast(
485 Value *S, ///< The value to be casted (operand 0)
486 Type *Ty, ///< The type to which operand is casted
487 const Twine &Name, ///< The name for the instruction
488 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
489 );
490
491 /// Create a SExt or BitCast cast instruction
492 static CastInst *CreateSExtOrBitCast(
493 Value *S, ///< The value to be casted (operand 0)
494 Type *Ty, ///< The type to which cast should be made
495 const Twine &Name = "", ///< Name for the instruction
496 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
497 );
498
499 /// Create a SExt or BitCast cast instruction
500 static CastInst *CreateSExtOrBitCast(
501 Value *S, ///< The value to be casted (operand 0)
502 Type *Ty, ///< The type to which operand is casted
503 const Twine &Name, ///< The name for the instruction
504 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
505 );
506
507 /// Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
508 static CastInst *CreatePointerCast(
509 Value *S, ///< The pointer value to be casted (operand 0)
510 Type *Ty, ///< The type to which operand is casted
511 const Twine &Name, ///< The name for the instruction
512 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
513 );
514
515 /// Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
516 static CastInst *CreatePointerCast(
517 Value *S, ///< The pointer value to be casted (operand 0)
518 Type *Ty, ///< The type to which cast should be made
519 const Twine &Name = "", ///< Name for the instruction
520 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
521 );
522
523 /// Create a BitCast or an AddrSpaceCast cast instruction.
524 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
525 Value *S, ///< The pointer value to be casted (operand 0)
526 Type *Ty, ///< The type to which operand is casted
527 const Twine &Name, ///< The name for the instruction
528 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
529 );
530
531 /// Create a BitCast or an AddrSpaceCast cast instruction.
532 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
533 Value *S, ///< The pointer value to be casted (operand 0)
534 Type *Ty, ///< The type to which cast should be made
535 const Twine &Name = "", ///< Name for the instruction
536 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
537 );
538
539 /// Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
540 ///
541 /// If the value is a pointer type and the destination an integer type,
542 /// creates a PtrToInt cast. If the value is an integer type and the
543 /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
544 /// a bitcast.
545 static CastInst *CreateBitOrPointerCast(
546 Value *S, ///< The pointer value to be casted (operand 0)
547 Type *Ty, ///< The type to which cast should be made
548 const Twine &Name = "", ///< Name for the instruction
549 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
550 );
551
552 /// Create a ZExt, BitCast, or Trunc for int -> int casts.
553 static CastInst *CreateIntegerCast(
554 Value *S, ///< The pointer value to be casted (operand 0)
555 Type *Ty, ///< The type to which cast should be made
556 bool isSigned, ///< Whether to regard S as signed or not
557 const Twine &Name = "", ///< Name for the instruction
558 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
559 );
560
561 /// Create a ZExt, BitCast, or Trunc for int -> int casts.
562 static CastInst *CreateIntegerCast(
563 Value *S, ///< The integer value to be casted (operand 0)
564 Type *Ty, ///< The integer type to which operand is casted
565 bool isSigned, ///< Whether to regard S as signed or not
566 const Twine &Name, ///< The name for the instruction
567 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
568 );
569
570 /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
571 static CastInst *CreateFPCast(
572 Value *S, ///< The floating point value to be casted
573 Type *Ty, ///< The floating point type to cast to
574 const Twine &Name = "", ///< Name for the instruction
575 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
576 );
577
578 /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
579 static CastInst *CreateFPCast(
580 Value *S, ///< The floating point value to be casted
581 Type *Ty, ///< The floating point type to cast to
582 const Twine &Name, ///< The name for the instruction
583 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
584 );
585
586 /// Create a Trunc or BitCast cast instruction
587 static CastInst *CreateTruncOrBitCast(
588 Value *S, ///< The value to be casted (operand 0)
589 Type *Ty, ///< The type to which cast should be made
590 const Twine &Name = "", ///< Name for the instruction
591 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
592 );
593
594 /// Create a Trunc or BitCast cast instruction
595 static CastInst *CreateTruncOrBitCast(
596 Value *S, ///< The value to be casted (operand 0)
597 Type *Ty, ///< The type to which operand is casted
598 const Twine &Name, ///< The name for the instruction
599 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
600 );
601
602 /// Check whether it is valid to call getCastOpcode for these types.
603 static bool isCastable(
604 Type *SrcTy, ///< The Type from which the value should be cast.
605 Type *DestTy ///< The Type to which the value should be cast.
606 );
607
608 /// Check whether a bitcast between these types is valid
609 static bool isBitCastable(
610 Type *SrcTy, ///< The Type from which the value should be cast.
611 Type *DestTy ///< The Type to which the value should be cast.
612 );
613
614 /// Check whether a bitcast, inttoptr, or ptrtoint cast between these
615 /// types is valid and a no-op.
616 ///
617 /// This ensures that any pointer<->integer cast has enough bits in the
618 /// integer and any other cast is a bitcast.
619 static bool isBitOrNoopPointerCastable(
620 Type *SrcTy, ///< The Type from which the value should be cast.
621 Type *DestTy, ///< The Type to which the value should be cast.
622 const DataLayout &DL);
623
624 /// Returns the opcode necessary to cast Val into Ty using usual casting
625 /// rules.
626 /// Infer the opcode for cast operand and type
627 static Instruction::CastOps getCastOpcode(
628 const Value *Val, ///< The value to cast
629 bool SrcIsSigned, ///< Whether to treat the source as signed
630 Type *Ty, ///< The Type to which the value should be casted
631 bool DstIsSigned ///< Whether to treate the dest. as signed
632 );
633
634 /// There are several places where we need to know if a cast instruction
635 /// only deals with integer source and destination types. To simplify that
636 /// logic, this method is provided.
637 /// @returns true iff the cast has only integral typed operand and dest type.
638 /// Determine if this is an integer-only cast.
639 bool isIntegerCast() const;
640
641 /// A lossless cast is one that does not alter the basic value. It implies
642 /// a no-op cast but is more stringent, preventing things like int->float,
643 /// long->double, or int->ptr.
644 /// @returns true iff the cast is lossless.
645 /// Determine if this is a lossless cast.
646 bool isLosslessCast() const;
647
648 /// A no-op cast is one that can be effected without changing any bits.
649 /// It implies that the source and destination types are the same size. The
650 /// DataLayout argument is to determine the pointer size when examining casts
651 /// involving Integer and Pointer types. They are no-op casts if the integer
652 /// is the same size as the pointer. However, pointer size varies with
653 /// platform. Note that a precondition of this method is that the cast is
654 /// legal - i.e. the instruction formed with these operands would verify.
655 static bool isNoopCast(
656 Instruction::CastOps Opcode, ///< Opcode of cast
657 Type *SrcTy, ///< SrcTy of cast
658 Type *DstTy, ///< DstTy of cast
659 const DataLayout &DL ///< DataLayout to get the Int Ptr type from.
660 );
661
662 /// Determine if this cast is a no-op cast.
663 ///
664 /// \param DL is the DataLayout to determine pointer size.
665 bool isNoopCast(const DataLayout &DL) const;
666
667 /// Determine how a pair of casts can be eliminated, if they can be at all.
668 /// This is a helper function for both CastInst and ConstantExpr.
669 /// @returns 0 if the CastInst pair can't be eliminated, otherwise
670 /// returns Instruction::CastOps value for a cast that can replace
671 /// the pair, casting SrcTy to DstTy.
672 /// Determine if a cast pair is eliminable
673 static unsigned isEliminableCastPair(
674 Instruction::CastOps firstOpcode, ///< Opcode of first cast
675 Instruction::CastOps secondOpcode, ///< Opcode of second cast
676 Type *SrcTy, ///< SrcTy of 1st cast
677 Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
678 Type *DstTy, ///< DstTy of 2nd cast
679 Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
680 Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
681 Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null
682 );
683
684 /// Return the opcode of this CastInst
685 Instruction::CastOps getOpcode() const {
686 return Instruction::CastOps(Instruction::getOpcode());
687 }
688
689 /// Return the source type, as a convenience
690 Type* getSrcTy() const { return getOperand(0)->getType(); }
691 /// Return the destination type, as a convenience
692 Type* getDestTy() const { return getType(); }
693
694 /// This method can be used to determine if a cast from SrcTy to DstTy using
695 /// Opcode op is valid or not.
696 /// @returns true iff the proposed cast is valid.
697 /// Determine if a cast is valid without creating one.
698 static bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy);
699 static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
700 return castIsValid(op, S->getType(), DstTy);
701 }
702
703 /// Methods for support type inquiry through isa, cast, and dyn_cast:
704 static bool classof(const Instruction *I) {
705 return I->isCast();
706 }
707 static bool classof(const Value *V) {
708 return isa<Instruction>(V) && classof(cast<Instruction>(V));
709 }
710};
711
712//===----------------------------------------------------------------------===//
713// CmpInst Class
714//===----------------------------------------------------------------------===//
715
716/// This class is the base class for the comparison instructions.
717/// Abstract base class of comparison instructions.
718class CmpInst : public Instruction {
719public:
720 /// This enumeration lists the possible predicates for CmpInst subclasses.
721 /// Values in the range 0-31 are reserved for FCmpInst, while values in the
722 /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
723 /// predicate values are not overlapping between the classes.
724 ///
725 /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of
726 /// FCMP_* values. Changing the bit patterns requires a potential change to
727 /// those passes.
728 enum Predicate : unsigned {
729 // Opcode U L G E Intuitive operation
730 FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded)
731 FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal
732 FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than
733 FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal
734 FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than
735 FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal
736 FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal
737 FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans)
738 FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y)
739 FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal
740 FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than
741 FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal
742 FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than
743 FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal
744 FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal
745 FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded)
746 FIRST_FCMP_PREDICATE = FCMP_FALSE,
747 LAST_FCMP_PREDICATE = FCMP_TRUE,
748 BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
749 ICMP_EQ = 32, ///< equal
750 ICMP_NE = 33, ///< not equal
751 ICMP_UGT = 34, ///< unsigned greater than
752 ICMP_UGE = 35, ///< unsigned greater or equal
753 ICMP_ULT = 36, ///< unsigned less than
754 ICMP_ULE = 37, ///< unsigned less or equal
755 ICMP_SGT = 38, ///< signed greater than
756 ICMP_SGE = 39, ///< signed greater or equal
757 ICMP_SLT = 40, ///< signed less than
758 ICMP_SLE = 41, ///< signed less or equal
759 FIRST_ICMP_PREDICATE = ICMP_EQ,
760 LAST_ICMP_PREDICATE = ICMP_SLE,
761 BAD_ICMP_PREDICATE = ICMP_SLE + 1
762 };
763 using PredicateField =
764 Bitfield::Element<Predicate, 0, 6, LAST_ICMP_PREDICATE>;
765
766protected:
767 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
768 Value *LHS, Value *RHS, const Twine &Name = "",
769 Instruction *InsertBefore = nullptr,
770 Instruction *FlagsSource = nullptr);
771
772 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
773 Value *LHS, Value *RHS, const Twine &Name,
774 BasicBlock *InsertAtEnd);
775
776public:
777 // allocate space for exactly two operands
778 void *operator new(size_t s) {
779 return User::operator new(s, 2);
780 }
781
782 /// Construct a compare instruction, given the opcode, the predicate and
783 /// the two operands. Optionally (if InstBefore is specified) insert the
784 /// instruction into a BasicBlock right before the specified instruction.
785 /// The specified Instruction is allowed to be a dereferenced end iterator.
786 /// Create a CmpInst
787 static CmpInst *Create(OtherOps Op,
788 Predicate predicate, Value *S1,
789 Value *S2, const Twine &Name = "",
790 Instruction *InsertBefore = nullptr);
791
792 /// Construct a compare instruction, given the opcode, the predicate and the
793 /// two operands. Also automatically insert this instruction to the end of
794 /// the BasicBlock specified.
795 /// Create a CmpInst
796 static CmpInst *Create(OtherOps Op, Predicate predicate, Value *S1,
797 Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
798
799 /// Get the opcode casted to the right type
800 OtherOps getOpcode() const {
801 return static_cast<OtherOps>(Instruction::getOpcode());
802 }
803
804 /// Return the predicate for this instruction.
805 Predicate getPredicate() const { return getSubclassData<PredicateField>(); }
806
807 /// Set the predicate for this instruction to the specified value.
808 void setPredicate(Predicate P) { setSubclassData<PredicateField>(P); }
809
810 static bool isFPPredicate(Predicate P) {
811 assert(FIRST_FCMP_PREDICATE == 0 &&((FIRST_FCMP_PREDICATE == 0 && "FIRST_FCMP_PREDICATE is required to be 0"
) ? static_cast<void> (0) : __assert_fail ("FIRST_FCMP_PREDICATE == 0 && \"FIRST_FCMP_PREDICATE is required to be 0\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 812, __PRETTY_FUNCTION__))
812 "FIRST_FCMP_PREDICATE is required to be 0")((FIRST_FCMP_PREDICATE == 0 && "FIRST_FCMP_PREDICATE is required to be 0"
) ? static_cast<void> (0) : __assert_fail ("FIRST_FCMP_PREDICATE == 0 && \"FIRST_FCMP_PREDICATE is required to be 0\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 812, __PRETTY_FUNCTION__))
;
813 return P <= LAST_FCMP_PREDICATE;
814 }
815
816 static bool isIntPredicate(Predicate P) {
817 return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
818 }
819
820 static StringRef getPredicateName(Predicate P);
821
822 bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
823 bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
824
825 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
826 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
827 /// @returns the inverse predicate for the instruction's current predicate.
828 /// Return the inverse of the instruction's predicate.
829 Predicate getInversePredicate() const {
830 return getInversePredicate(getPredicate());
831 }
832
833 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
834 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
835 /// @returns the inverse predicate for predicate provided in \p pred.
836 /// Return the inverse of a given predicate
837 static Predicate getInversePredicate(Predicate pred);
838
839 /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
840 /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
841 /// @returns the predicate that would be the result of exchanging the two
842 /// operands of the CmpInst instruction without changing the result
843 /// produced.
844 /// Return the predicate as if the operands were swapped
845 Predicate getSwappedPredicate() const {
846 return getSwappedPredicate(getPredicate());
847 }
848
849 /// This is a static version that you can use without an instruction
850 /// available.
851 /// Return the predicate as if the operands were swapped.
852 static Predicate getSwappedPredicate(Predicate pred);
853
854 /// For predicate of kind "is X or equal to 0" returns the predicate "is X".
855 /// For predicate of kind "is X" returns the predicate "is X or equal to 0".
856 /// does not support other kind of predicates.
857 /// @returns the predicate that does not contains is equal to zero if
858 /// it had and vice versa.
859 /// Return the flipped strictness of predicate
860 Predicate getFlippedStrictnessPredicate() const {
861 return getFlippedStrictnessPredicate(getPredicate());
862 }
863
864 /// This is a static version that you can use without an instruction
865 /// available.
866 /// Return the flipped strictness of predicate
867 static Predicate getFlippedStrictnessPredicate(Predicate pred);
868
869 /// For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
870 /// Returns the non-strict version of strict comparisons.
871 Predicate getNonStrictPredicate() const {
872 return getNonStrictPredicate(getPredicate());
873 }
874
875 /// This is a static version that you can use without an instruction
876 /// available.
877 /// @returns the non-strict version of comparison provided in \p pred.
878 /// If \p pred is not a strict comparison predicate, returns \p pred.
879 /// Returns the non-strict version of strict comparisons.
880 static Predicate getNonStrictPredicate(Predicate pred);
881
882 /// Provide more efficient getOperand methods.
883 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
;
884
885 /// This is just a convenience that dispatches to the subclasses.
886 /// Swap the operands and adjust predicate accordingly to retain
887 /// the same comparison.
888 void swapOperands();
889
890 /// This is just a convenience that dispatches to the subclasses.
891 /// Determine if this CmpInst is commutative.
892 bool isCommutative() const;
893
894 /// Determine if this is an equals/not equals predicate.
895 /// This is a static version that you can use without an instruction
896 /// available.
897 static bool isEquality(Predicate pred);
898
899 /// Determine if this is an equals/not equals predicate.
900 bool isEquality() const { return isEquality(getPredicate()); }
901
902 /// Return true if the predicate is relational (not EQ or NE).
903 static bool isRelational(Predicate P) { return !isEquality(P); }
904
905 /// Return true if the predicate is relational (not EQ or NE).
906 bool isRelational() const { return !isEquality(); }
907
908 /// @returns true if the comparison is signed, false otherwise.
909 /// Determine if this instruction is using a signed comparison.
910 bool isSigned() const {
911 return isSigned(getPredicate());
912 }
913
914 /// @returns true if the comparison is unsigned, false otherwise.
915 /// Determine if this instruction is using an unsigned comparison.
916 bool isUnsigned() const {
917 return isUnsigned(getPredicate());
918 }
919
920 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
921 /// @returns the signed version of the unsigned predicate pred.
922 /// return the signed version of a predicate
923 static Predicate getSignedPredicate(Predicate pred);
924
925 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
926 /// @returns the signed version of the predicate for this instruction (which
927 /// has to be an unsigned predicate).
928 /// return the signed version of a predicate
929 Predicate getSignedPredicate() {
930 return getSignedPredicate(getPredicate());
931 }
932
933 /// For example, SLT->ULT, SLE->ULE, SGT->UGT, SGE->UGE, ULT->Failed assert
934 /// @returns the unsigned version of the signed predicate pred.
935 static Predicate getUnsignedPredicate(Predicate pred);
936
937 /// For example, SLT->ULT, SLE->ULE, SGT->UGT, SGE->UGE, ULT->Failed assert
938 /// @returns the unsigned version of the predicate for this instruction (which
939 /// has to be an signed predicate).
940 /// return the unsigned version of a predicate
941 Predicate getUnsignedPredicate() {
942 return getUnsignedPredicate(getPredicate());
943 }
944
945 /// For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->Failed assert
946 /// @returns the unsigned version of the signed predicate pred or
947 /// the signed version of the signed predicate pred.
948 static Predicate getFlippedSignednessPredicate(Predicate pred);
949
950 /// For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->Failed assert
951 /// @returns the unsigned version of the signed predicate pred or
952 /// the signed version of the signed predicate pred.
953 Predicate getFlippedSignednessPredicate() {
954 return getFlippedSignednessPredicate(getPredicate());
955 }
956
957 /// This is just a convenience.
958 /// Determine if this is true when both operands are the same.
959 bool isTrueWhenEqual() const {
960 return isTrueWhenEqual(getPredicate());
961 }
962
963 /// This is just a convenience.
964 /// Determine if this is false when both operands are the same.
965 bool isFalseWhenEqual() const {
966 return isFalseWhenEqual(getPredicate());
967 }
968
969 /// @returns true if the predicate is unsigned, false otherwise.
970 /// Determine if the predicate is an unsigned operation.
971 static bool isUnsigned(Predicate predicate);
972
973 /// @returns true if the predicate is signed, false otherwise.
974 /// Determine if the predicate is an signed operation.
975 static bool isSigned(Predicate predicate);
976
977 /// Determine if the predicate is an ordered operation.
978 static bool isOrdered(Predicate predicate);
979
980 /// Determine if the predicate is an unordered operation.
981 static bool isUnordered(Predicate predicate);
982
983 /// Determine if the predicate is true when comparing a value with itself.
984 static bool isTrueWhenEqual(Predicate predicate);
985
986 /// Determine if the predicate is false when comparing a value with itself.
987 static bool isFalseWhenEqual(Predicate predicate);
988
989 /// Determine if Pred1 implies Pred2 is true when two compares have matching
990 /// operands.
991 static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2);
992
993 /// Determine if Pred1 implies Pred2 is false when two compares have matching
994 /// operands.
995 static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2);
996
997 /// Methods for support type inquiry through isa, cast, and dyn_cast:
998 static bool classof(const Instruction *I) {
999 return I->getOpcode() == Instruction::ICmp ||
1000 I->getOpcode() == Instruction::FCmp;
1001 }
1002 static bool classof(const Value *V) {
1003 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1004 }
1005
1006 /// Create a result type for fcmp/icmp
1007 static Type* makeCmpResultType(Type* opnd_type) {
1008 if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
1009 return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
1010 vt->getElementCount());
1011 }
1012 return Type::getInt1Ty(opnd_type->getContext());
1013 }
1014
1015private:
1016 // Shadow Value::setValueSubclassData with a private forwarding method so that
1017 // subclasses cannot accidentally use it.
1018 void setValueSubclassData(unsigned short D) {
1019 Value::setValueSubclassData(D);
1020 }
1021};
1022
1023// FIXME: these are redundant if CmpInst < BinaryOperator
1024template <>
1025struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
1026};
1027
1028DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)CmpInst::op_iterator CmpInst::op_begin() { return OperandTraits
<CmpInst>::op_begin(this); } CmpInst::const_op_iterator
CmpInst::op_begin() const { return OperandTraits<CmpInst>
::op_begin(const_cast<CmpInst*>(this)); } CmpInst::op_iterator
CmpInst::op_end() { return OperandTraits<CmpInst>::op_end
(this); } CmpInst::const_op_iterator CmpInst::op_end() const {
return OperandTraits<CmpInst>::op_end(const_cast<CmpInst
*>(this)); } Value *CmpInst::getOperand(unsigned i_nocapture
) const { ((i_nocapture < OperandTraits<CmpInst>::operands
(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CmpInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1028, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<CmpInst>::op_begin(const_cast<CmpInst
*>(this))[i_nocapture].get()); } void CmpInst::setOperand(
unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<CmpInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CmpInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1028, __PRETTY_FUNCTION__)); OperandTraits<CmpInst>::
op_begin(this)[i_nocapture] = Val_nocapture; } unsigned CmpInst
::getNumOperands() const { return OperandTraits<CmpInst>
::operands(this); } template <int Idx_nocapture> Use &
CmpInst::Op() { return this->OpFrom<Idx_nocapture>(this
); } template <int Idx_nocapture> const Use &CmpInst
::Op() const { return this->OpFrom<Idx_nocapture>(this
); }
1029
1030/// A lightweight accessor for an operand bundle meant to be passed
1031/// around by value.
1032struct OperandBundleUse {
1033 ArrayRef<Use> Inputs;
1034
1035 OperandBundleUse() = default;
1036 explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
1037 : Inputs(Inputs), Tag(Tag) {}
1038
1039 /// Return true if the operand at index \p Idx in this operand bundle
1040 /// has the attribute A.
1041 bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const {
1042 if (isDeoptOperandBundle())
1043 if (A == Attribute::ReadOnly || A == Attribute::NoCapture)
1044 return Inputs[Idx]->getType()->isPointerTy();
1045
1046 // Conservative answer: no operands have any attributes.
1047 return false;
1048 }
1049
1050 /// Return the tag of this operand bundle as a string.
1051 StringRef getTagName() const {
1052 return Tag->getKey();
1053 }
1054
1055 /// Return the tag of this operand bundle as an integer.
1056 ///
1057 /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
1058 /// and this function returns the unique integer getOrInsertBundleTag
1059 /// associated the tag of this operand bundle to.
1060 uint32_t getTagID() const {
1061 return Tag->getValue();
1062 }
1063
1064 /// Return true if this is a "deopt" operand bundle.
1065 bool isDeoptOperandBundle() const {
1066 return getTagID() == LLVMContext::OB_deopt;
1067 }
1068
1069 /// Return true if this is a "funclet" operand bundle.
1070 bool isFuncletOperandBundle() const {
1071 return getTagID() == LLVMContext::OB_funclet;
1072 }
1073
1074 /// Return true if this is a "cfguardtarget" operand bundle.
1075 bool isCFGuardTargetOperandBundle() const {
1076 return getTagID() == LLVMContext::OB_cfguardtarget;
1077 }
1078
1079private:
1080 /// Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1081 StringMapEntry<uint32_t> *Tag;
1082};
1083
1084/// A container for an operand bundle being viewed as a set of values
1085/// rather than a set of uses.
1086///
1087/// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1088/// so it is possible to create and pass around "self-contained" instances of
1089/// OperandBundleDef and ConstOperandBundleDef.
1090template <typename InputTy> class OperandBundleDefT {
1091 std::string Tag;
1092 std::vector<InputTy> Inputs;
1093
1094public:
1095 explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1096 : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1097 explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs)
1098 : Tag(std::move(Tag)), Inputs(Inputs) {}
1099
1100 explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1101 Tag = std::string(OBU.getTagName());
1102 Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
1103 }
1104
1105 ArrayRef<InputTy> inputs() const { return Inputs; }
1106
1107 using input_iterator = typename std::vector<InputTy>::const_iterator;
1108
1109 size_t input_size() const { return Inputs.size(); }
1110 input_iterator input_begin() const { return Inputs.begin(); }
1111 input_iterator input_end() const { return Inputs.end(); }
1112
1113 StringRef getTag() const { return Tag; }
1114};
1115
1116using OperandBundleDef = OperandBundleDefT<Value *>;
1117using ConstOperandBundleDef = OperandBundleDefT<const Value *>;
1118
1119//===----------------------------------------------------------------------===//
1120// CallBase Class
1121//===----------------------------------------------------------------------===//
1122
1123/// Base class for all callable instructions (InvokeInst and CallInst)
1124/// Holds everything related to calling a function.
1125///
1126/// All call-like instructions are required to use a common operand layout:
1127/// - Zero or more arguments to the call,
1128/// - Zero or more operand bundles with zero or more operand inputs each
1129/// bundle,
1130/// - Zero or more subclass controlled operands
1131/// - The called function.
1132///
1133/// This allows this base class to easily access the called function and the
1134/// start of the arguments without knowing how many other operands a particular
1135/// subclass requires. Note that accessing the end of the argument list isn't
1136/// as cheap as most other operations on the base class.
1137class CallBase : public Instruction {
1138protected:
1139 // The first two bits are reserved by CallInst for fast retrieval,
1140 using CallInstReservedField = Bitfield::Element<unsigned, 0, 2>;
1141 using CallingConvField =
1142 Bitfield::Element<CallingConv::ID, CallInstReservedField::NextBit, 10,
1143 CallingConv::MaxID>;
1144 static_assert(
1145 Bitfield::areContiguous<CallInstReservedField, CallingConvField>(),
1146 "Bitfields must be contiguous");
1147
1148 /// The last operand is the called operand.
1149 static constexpr int CalledOperandOpEndIdx = -1;
1150
1151 AttributeList Attrs; ///< parameter attributes for callable
1152 FunctionType *FTy;
1153
1154 template <class... ArgsTy>
1155 CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args)
1156 : Instruction(std::forward<ArgsTy>(Args)...), Attrs(A), FTy(FT) {}
1157
1158 using Instruction::Instruction;
1159
1160 bool hasDescriptor() const { return Value::HasDescriptor; }
1161
1162 unsigned getNumSubclassExtraOperands() const {
1163 switch (getOpcode()) {
1164 case Instruction::Call:
1165 return 0;
1166 case Instruction::Invoke:
1167 return 2;
1168 case Instruction::CallBr:
1169 return getNumSubclassExtraOperandsDynamic();
1170 }
1171 llvm_unreachable("Invalid opcode!")::llvm::llvm_unreachable_internal("Invalid opcode!", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1171)
;
1172 }
1173
1174 /// Get the number of extra operands for instructions that don't have a fixed
1175 /// number of extra operands.
1176 unsigned getNumSubclassExtraOperandsDynamic() const;
1177
1178public:
1179 using Instruction::getContext;
1180
1181 /// Create a clone of \p CB with a different set of operand bundles and
1182 /// insert it before \p InsertPt.
1183 ///
1184 /// The returned call instruction is identical \p CB in every way except that
1185 /// the operand bundles for the new instruction are set to the operand bundles
1186 /// in \p Bundles.
1187 static CallBase *Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles,
1188 Instruction *InsertPt = nullptr);
1189
1190 static bool classof(const Instruction *I) {
1191 return I->getOpcode() == Instruction::Call ||
1192 I->getOpcode() == Instruction::Invoke ||
1193 I->getOpcode() == Instruction::CallBr;
1194 }
1195 static bool classof(const Value *V) {
1196 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1197 }
1198
1199 FunctionType *getFunctionType() const { return FTy; }
1200
1201 void mutateFunctionType(FunctionType *FTy) {
1202 Value::mutateType(FTy->getReturnType());
1203 this->FTy = FTy;
1204 }
1205
1206 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
;
1207
1208 /// data_operands_begin/data_operands_end - Return iterators iterating over
1209 /// the call / invoke argument list and bundle operands. For invokes, this is
1210 /// the set of instruction operands except the invoke target and the two
1211 /// successor blocks; and for calls this is the set of instruction operands
1212 /// except the call target.
1213 User::op_iterator data_operands_begin() { return op_begin(); }
1214 User::const_op_iterator data_operands_begin() const {
1215 return const_cast<CallBase *>(this)->data_operands_begin();
1216 }
1217 User::op_iterator data_operands_end() {
1218 // Walk from the end of the operands over the called operand and any
1219 // subclass operands.
1220 return op_end() - getNumSubclassExtraOperands() - 1;
1221 }
1222 User::const_op_iterator data_operands_end() const {
1223 return const_cast<CallBase *>(this)->data_operands_end();
1224 }
1225 iterator_range<User::op_iterator> data_ops() {
1226 return make_range(data_operands_begin(), data_operands_end());
1227 }
1228 iterator_range<User::const_op_iterator> data_ops() const {
1229 return make_range(data_operands_begin(), data_operands_end());
1230 }
1231 bool data_operands_empty() const {
1232 return data_operands_end() == data_operands_begin();
1233 }
1234 unsigned data_operands_size() const {
1235 return std::distance(data_operands_begin(), data_operands_end());
1236 }
1237
1238 bool isDataOperand(const Use *U) const {
1239 assert(this == U->getUser() &&((this == U->getUser() && "Only valid to query with a use of this instruction!"
) ? static_cast<void> (0) : __assert_fail ("this == U->getUser() && \"Only valid to query with a use of this instruction!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1240, __PRETTY_FUNCTION__))
1240 "Only valid to query with a use of this instruction!")((this == U->getUser() && "Only valid to query with a use of this instruction!"
) ? static_cast<void> (0) : __assert_fail ("this == U->getUser() && \"Only valid to query with a use of this instruction!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1240, __PRETTY_FUNCTION__))
;
1241 return data_operands_begin() <= U && U < data_operands_end();
1242 }
1243 bool isDataOperand(Value::const_user_iterator UI) const {
1244 return isDataOperand(&UI.getUse());
1245 }
1246
1247 /// Given a value use iterator, return the data operand corresponding to it.
1248 /// Iterator must actually correspond to a data operand.
1249 unsigned getDataOperandNo(Value::const_user_iterator UI) const {
1250 return getDataOperandNo(&UI.getUse());
1251 }
1252
1253 /// Given a use for a data operand, get the data operand number that
1254 /// corresponds to it.
1255 unsigned getDataOperandNo(const Use *U) const {
1256 assert(isDataOperand(U) && "Data operand # out of range!")((isDataOperand(U) && "Data operand # out of range!")
? static_cast<void> (0) : __assert_fail ("isDataOperand(U) && \"Data operand # out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1256, __PRETTY_FUNCTION__))
;
1257 return U - data_operands_begin();
1258 }
1259
1260 /// Return the iterator pointing to the beginning of the argument list.
1261 User::op_iterator arg_begin() { return op_begin(); }
1262 User::const_op_iterator arg_begin() const {
1263 return const_cast<CallBase *>(this)->arg_begin();
1264 }
1265
1266 /// Return the iterator pointing to the end of the argument list.
1267 User::op_iterator arg_end() {
1268 // From the end of the data operands, walk backwards past the bundle
1269 // operands.
1270 return data_operands_end() - getNumTotalBundleOperands();
1271 }
1272 User::const_op_iterator arg_end() const {
1273 return const_cast<CallBase *>(this)->arg_end();
1274 }
1275
1276 /// Iteration adapter for range-for loops.
1277 iterator_range<User::op_iterator> args() {
1278 return make_range(arg_begin(), arg_end());
1279 }
1280 iterator_range<User::const_op_iterator> args() const {
1281 return make_range(arg_begin(), arg_end());
1282 }
1283 bool arg_empty() const { return arg_end() == arg_begin(); }
1284 unsigned arg_size() const { return arg_end() - arg_begin(); }
1285
1286 // Legacy API names that duplicate the above and will be removed once users
1287 // are migrated.
1288 iterator_range<User::op_iterator> arg_operands() {
1289 return make_range(arg_begin(), arg_end());
1290 }
1291 iterator_range<User::const_op_iterator> arg_operands() const {
1292 return make_range(arg_begin(), arg_end());
1293 }
1294 unsigned getNumArgOperands() const { return arg_size(); }
1295
1296 Value *getArgOperand(unsigned i) const {
1297 assert(i < getNumArgOperands() && "Out of bounds!")((i < getNumArgOperands() && "Out of bounds!") ? static_cast
<void> (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1297, __PRETTY_FUNCTION__))
;
1298 return getOperand(i);
1299 }
1300
1301 void setArgOperand(unsigned i, Value *v) {
1302 assert(i < getNumArgOperands() && "Out of bounds!")((i < getNumArgOperands() && "Out of bounds!") ? static_cast
<void> (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1302, __PRETTY_FUNCTION__))
;
1303 setOperand(i, v);
1304 }
1305
1306 /// Wrappers for getting the \c Use of a call argument.
1307 const Use &getArgOperandUse(unsigned i) const {
1308 assert(i < getNumArgOperands() && "Out of bounds!")((i < getNumArgOperands() && "Out of bounds!") ? static_cast
<void> (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1308, __PRETTY_FUNCTION__))
;
1309 return User::getOperandUse(i);
1310 }
1311 Use &getArgOperandUse(unsigned i) {
1312 assert(i < getNumArgOperands() && "Out of bounds!")((i < getNumArgOperands() && "Out of bounds!") ? static_cast
<void> (0) : __assert_fail ("i < getNumArgOperands() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1312, __PRETTY_FUNCTION__))
;
1313 return User::getOperandUse(i);
1314 }
1315
1316 bool isArgOperand(const Use *U) const {
1317 assert(this == U->getUser() &&((this == U->getUser() && "Only valid to query with a use of this instruction!"
) ? static_cast<void> (0) : __assert_fail ("this == U->getUser() && \"Only valid to query with a use of this instruction!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1318, __PRETTY_FUNCTION__))
1318 "Only valid to query with a use of this instruction!")((this == U->getUser() && "Only valid to query with a use of this instruction!"
) ? static_cast<void> (0) : __assert_fail ("this == U->getUser() && \"Only valid to query with a use of this instruction!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1318, __PRETTY_FUNCTION__))
;
1319 return arg_begin() <= U && U < arg_end();
1320 }
1321 bool isArgOperand(Value::const_user_iterator UI) const {
1322 return isArgOperand(&UI.getUse());
1323 }
1324
1325 /// Given a use for a arg operand, get the arg operand number that
1326 /// corresponds to it.
1327 unsigned getArgOperandNo(const Use *U) const {
1328 assert(isArgOperand(U) && "Arg operand # out of range!")((isArgOperand(U) && "Arg operand # out of range!") ?
static_cast<void> (0) : __assert_fail ("isArgOperand(U) && \"Arg operand # out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1328, __PRETTY_FUNCTION__))
;
1329 return U - arg_begin();
1330 }
1331
1332 /// Given a value use iterator, return the arg operand number corresponding to
1333 /// it. Iterator must actually correspond to a data operand.
1334 unsigned getArgOperandNo(Value::const_user_iterator UI) const {
1335 return getArgOperandNo(&UI.getUse());
1336 }
1337
1338 /// Returns true if this CallSite passes the given Value* as an argument to
1339 /// the called function.
1340 bool hasArgument(const Value *V) const {
1341 return llvm::is_contained(args(), V);
1342 }
1343
1344 Value *getCalledOperand() const { return Op<CalledOperandOpEndIdx>(); }
1345
1346 const Use &getCalledOperandUse() const { return Op<CalledOperandOpEndIdx>(); }
1347 Use &getCalledOperandUse() { return Op<CalledOperandOpEndIdx>(); }
1348
1349 /// Returns the function called, or null if this is an
1350 /// indirect function invocation.
1351 Function *getCalledFunction() const {
1352 return dyn_cast_or_null<Function>(getCalledOperand());
1353 }
1354
1355 /// Return true if the callsite is an indirect call.
1356 bool isIndirectCall() const;
1357
1358 /// Determine whether the passed iterator points to the callee operand's Use.
1359 bool isCallee(Value::const_user_iterator UI) const {
1360 return isCallee(&UI.getUse());
1361 }
1362
1363 /// Determine whether this Use is the callee operand's Use.
1364 bool isCallee(const Use *U) const { return &getCalledOperandUse() == U; }
1365
1366 /// Helper to get the caller (the parent function).
1367 Function *getCaller();
1368 const Function *getCaller() const {
1369 return const_cast<CallBase *>(this)->getCaller();
1370 }
1371
1372 /// Tests if this call site must be tail call optimized. Only a CallInst can
1373 /// be tail call optimized.
1374 bool isMustTailCall() const;
1375
1376 /// Tests if this call site is marked as a tail call.
1377 bool isTailCall() const;
1378
1379 /// Returns the intrinsic ID of the intrinsic called or
1380 /// Intrinsic::not_intrinsic if the called function is not an intrinsic, or if
1381 /// this is an indirect call.
1382 Intrinsic::ID getIntrinsicID() const;
1383
1384 void setCalledOperand(Value *V) { Op<CalledOperandOpEndIdx>() = V; }
1385
1386 /// Sets the function called, including updating the function type.
1387 void setCalledFunction(Function *Fn) {
1388 setCalledFunction(Fn->getFunctionType(), Fn);
1389 }
1390
1391 /// Sets the function called, including updating the function type.
1392 void setCalledFunction(FunctionCallee Fn) {
1393 setCalledFunction(Fn.getFunctionType(), Fn.getCallee());
1394 }
1395
1396 /// Sets the function called, including updating to the specified function
1397 /// type.
1398 void setCalledFunction(FunctionType *FTy, Value *Fn) {
1399 this->FTy = FTy;
1400 assert(FTy == cast<FunctionType>(((FTy == cast<FunctionType>( cast<PointerType>(Fn
->getType())->getElementType())) ? static_cast<void>
(0) : __assert_fail ("FTy == cast<FunctionType>( cast<PointerType>(Fn->getType())->getElementType())"
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1401, __PRETTY_FUNCTION__))
1401 cast<PointerType>(Fn->getType())->getElementType()))((FTy == cast<FunctionType>( cast<PointerType>(Fn
->getType())->getElementType())) ? static_cast<void>
(0) : __assert_fail ("FTy == cast<FunctionType>( cast<PointerType>(Fn->getType())->getElementType())"
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1401, __PRETTY_FUNCTION__))
;
1402 // This function doesn't mutate the return type, only the function
1403 // type. Seems broken, but I'm just gonna stick an assert in for now.
1404 assert(getType() == FTy->getReturnType())((getType() == FTy->getReturnType()) ? static_cast<void
> (0) : __assert_fail ("getType() == FTy->getReturnType()"
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1404, __PRETTY_FUNCTION__))
;
1405 setCalledOperand(Fn);
1406 }
1407
1408 CallingConv::ID getCallingConv() const {
1409 return getSubclassData<CallingConvField>();
1410 }
1411
1412 void setCallingConv(CallingConv::ID CC) {
1413 setSubclassData<CallingConvField>(CC);
1414 }
1415
1416 /// Check if this call is an inline asm statement.
1417 bool isInlineAsm() const { return isa<InlineAsm>(getCalledOperand()); }
1418
1419 /// \name Attribute API
1420 ///
1421 /// These methods access and modify attributes on this call (including
1422 /// looking through to the attributes on the called function when necessary).
1423 ///@{
1424
1425 /// Return the parameter attributes for this call.
1426 ///
1427 AttributeList getAttributes() const { return Attrs; }
1428
1429 /// Set the parameter attributes for this call.
1430 ///
1431 void setAttributes(AttributeList A) { Attrs = A; }
1432
1433 /// Determine whether this call has the given attribute. If it does not
1434 /// then determine if the called function has the attribute, but only if
1435 /// the attribute is allowed for the call.
1436 bool hasFnAttr(Attribute::AttrKind Kind) const {
1437 assert(Kind != Attribute::NoBuiltin &&((Kind != Attribute::NoBuiltin && "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin"
) ? static_cast<void> (0) : __assert_fail ("Kind != Attribute::NoBuiltin && \"Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1438, __PRETTY_FUNCTION__))
1438 "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin")((Kind != Attribute::NoBuiltin && "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin"
) ? static_cast<void> (0) : __assert_fail ("Kind != Attribute::NoBuiltin && \"Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1438, __PRETTY_FUNCTION__))
;
1439 return hasFnAttrImpl(Kind);
1440 }
1441
1442 /// Determine whether this call has the given attribute. If it does not
1443 /// then determine if the called function has the attribute, but only if
1444 /// the attribute is allowed for the call.
1445 bool hasFnAttr(StringRef Kind) const { return hasFnAttrImpl(Kind); }
1446
1447 /// adds the attribute to the list of attributes.
1448 void addAttribute(unsigned i, Attribute::AttrKind Kind) {
1449 AttributeList PAL = getAttributes();
1450 PAL = PAL.addAttribute(getContext(), i, Kind);
1451 setAttributes(PAL);
1452 }
1453
1454 /// adds the attribute to the list of attributes.
1455 void addAttribute(unsigned i, Attribute Attr) {
1456 AttributeList PAL = getAttributes();
1457 PAL = PAL.addAttribute(getContext(), i, Attr);
1458 setAttributes(PAL);
1459 }
1460
1461 /// Adds the attribute to the indicated argument
1462 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1463 assert(ArgNo < getNumArgOperands() && "Out of bounds")((ArgNo < getNumArgOperands() && "Out of bounds") ?
static_cast<void> (0) : __assert_fail ("ArgNo < getNumArgOperands() && \"Out of bounds\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1463, __PRETTY_FUNCTION__))
;
1464 AttributeList PAL = getAttributes();
1465 PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
1466 setAttributes(PAL);
1467 }
1468
1469 /// Adds the attribute to the indicated argument
1470 void addParamAttr(unsigned ArgNo, Attribute Attr) {
1471 assert(ArgNo < getNumArgOperands() && "Out of bounds")((ArgNo < getNumArgOperands() && "Out of bounds") ?
static_cast<void> (0) : __assert_fail ("ArgNo < getNumArgOperands() && \"Out of bounds\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1471, __PRETTY_FUNCTION__))
;
1472 AttributeList PAL = getAttributes();
1473 PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
1474 setAttributes(PAL);
1475 }
1476
1477 /// removes the attribute from the list of attributes.
1478 void removeAttribute(unsigned i, Attribute::AttrKind Kind) {
1479 AttributeList PAL = getAttributes();
1480 PAL = PAL.removeAttribute(getContext(), i, Kind);
1481 setAttributes(PAL);
1482 }
1483
1484 /// removes the attribute from the list of attributes.
1485 void removeAttribute(unsigned i, StringRef Kind) {
1486 AttributeList PAL = getAttributes();
1487 PAL = PAL.removeAttribute(getContext(), i, Kind);
1488 setAttributes(PAL);
1489 }
1490
1491 void removeAttributes(unsigned i, const AttrBuilder &Attrs) {
1492 AttributeList PAL = getAttributes();
1493 PAL = PAL.removeAttributes(getContext(), i, Attrs);
1494 setAttributes(PAL);
1495 }
1496
1497 /// Removes the attribute from the given argument
1498 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1499 assert(ArgNo < getNumArgOperands() && "Out of bounds")((ArgNo < getNumArgOperands() && "Out of bounds") ?
static_cast<void> (0) : __assert_fail ("ArgNo < getNumArgOperands() && \"Out of bounds\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1499, __PRETTY_FUNCTION__))
;
1500 AttributeList PAL = getAttributes();
1501 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1502 setAttributes(PAL);
1503 }
1504
1505 /// Removes the attribute from the given argument
1506 void removeParamAttr(unsigned ArgNo, StringRef Kind) {
1507 assert(ArgNo < getNumArgOperands() && "Out of bounds")((ArgNo < getNumArgOperands() && "Out of bounds") ?
static_cast<void> (0) : __assert_fail ("ArgNo < getNumArgOperands() && \"Out of bounds\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1507, __PRETTY_FUNCTION__))
;
1508 AttributeList PAL = getAttributes();
1509 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1510 setAttributes(PAL);
1511 }
1512
1513 /// adds the dereferenceable attribute to the list of attributes.
1514 void addDereferenceableAttr(unsigned i, uint64_t Bytes) {
1515 AttributeList PAL = getAttributes();
1516 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
1517 setAttributes(PAL);
1518 }
1519
1520 /// adds the dereferenceable_or_null attribute to the list of
1521 /// attributes.
1522 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
1523 AttributeList PAL = getAttributes();
1524 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
1525 setAttributes(PAL);
1526 }
1527
1528 /// Determine whether the return value has the given attribute.
1529 bool hasRetAttr(Attribute::AttrKind Kind) const;
1530
1531 /// Determine whether the argument or parameter has the given attribute.
1532 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1533
1534 /// Get the attribute of a given kind at a position.
1535 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
1536 return getAttributes().getAttribute(i, Kind);
1537 }
1538
1539 /// Get the attribute of a given kind at a position.
1540 Attribute getAttribute(unsigned i, StringRef Kind) const {
1541 return getAttributes().getAttribute(i, Kind);
1542 }
1543
1544 /// Get the attribute of a given kind from a given arg
1545 Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1546 assert(ArgNo < getNumArgOperands() && "Out of bounds")((ArgNo < getNumArgOperands() && "Out of bounds") ?
static_cast<void> (0) : __assert_fail ("ArgNo < getNumArgOperands() && \"Out of bounds\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1546, __PRETTY_FUNCTION__))
;
1547 return getAttributes().getParamAttr(ArgNo, Kind);
1548 }
1549
1550 /// Get the attribute of a given kind from a given arg
1551 Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1552 assert(ArgNo < getNumArgOperands() && "Out of bounds")((ArgNo < getNumArgOperands() && "Out of bounds") ?
static_cast<void> (0) : __assert_fail ("ArgNo < getNumArgOperands() && \"Out of bounds\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1552, __PRETTY_FUNCTION__))
;
1553 return getAttributes().getParamAttr(ArgNo, Kind);
1554 }
1555
1556 /// Return true if the data operand at index \p i has the attribute \p
1557 /// A.
1558 ///
1559 /// Data operands include call arguments and values used in operand bundles,
1560 /// but does not include the callee operand. This routine dispatches to the
1561 /// underlying AttributeList or the OperandBundleUser as appropriate.
1562 ///
1563 /// The index \p i is interpreted as
1564 ///
1565 /// \p i == Attribute::ReturnIndex -> the return value
1566 /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
1567 /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1568 /// (\p i - 1) in the operand list.
1569 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const {
1570 // Note that we have to add one because `i` isn't zero-indexed.
1571 assert(i < (getNumArgOperands() + getNumTotalBundleOperands() + 1) &&((i < (getNumArgOperands() + getNumTotalBundleOperands() +
1) && "Data operand index out of bounds!") ? static_cast
<void> (0) : __assert_fail ("i < (getNumArgOperands() + getNumTotalBundleOperands() + 1) && \"Data operand index out of bounds!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1572, __PRETTY_FUNCTION__))
1572 "Data operand index out of bounds!")((i < (getNumArgOperands() + getNumTotalBundleOperands() +
1) && "Data operand index out of bounds!") ? static_cast
<void> (0) : __assert_fail ("i < (getNumArgOperands() + getNumTotalBundleOperands() + 1) && \"Data operand index out of bounds!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1572, __PRETTY_FUNCTION__))
;
1573
1574 // The attribute A can either be directly specified, if the operand in
1575 // question is a call argument; or be indirectly implied by the kind of its
1576 // containing operand bundle, if the operand is a bundle operand.
1577
1578 if (i == AttributeList::ReturnIndex)
1579 return hasRetAttr(Kind);
1580
1581 // FIXME: Avoid these i - 1 calculations and update the API to use
1582 // zero-based indices.
1583 if (i < (getNumArgOperands() + 1))
1584 return paramHasAttr(i - 1, Kind);
1585
1586 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&((hasOperandBundles() && i >= (getBundleOperandsStartIndex
() + 1) && "Must be either a call argument or an operand bundle!"
) ? static_cast<void> (0) : __assert_fail ("hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) && \"Must be either a call argument or an operand bundle!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1587, __PRETTY_FUNCTION__))
1587 "Must be either a call argument or an operand bundle!")((hasOperandBundles() && i >= (getBundleOperandsStartIndex
() + 1) && "Must be either a call argument or an operand bundle!"
) ? static_cast<void> (0) : __assert_fail ("hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) && \"Must be either a call argument or an operand bundle!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1587, __PRETTY_FUNCTION__))
;
1588 return bundleOperandHasAttr(i - 1, Kind);
1589 }
1590
1591 /// Determine whether this data operand is not captured.
1592 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1593 // better indicate that this may return a conservative answer.
1594 bool doesNotCapture(unsigned OpNo) const {
1595 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::NoCapture);
1596 }
1597
1598 /// Determine whether this argument is passed by value.
1599 bool isByValArgument(unsigned ArgNo) const {
1600 return paramHasAttr(ArgNo, Attribute::ByVal);
1601 }
1602
1603 /// Determine whether this argument is passed in an alloca.
1604 bool isInAllocaArgument(unsigned ArgNo) const {
1605 return paramHasAttr(ArgNo, Attribute::InAlloca);
1606 }
1607
1608 /// Determine whether this argument is passed by value, in an alloca, or is
1609 /// preallocated.
1610 bool isPassPointeeByValueArgument(unsigned ArgNo) const {
1611 return paramHasAttr(ArgNo, Attribute::ByVal) ||
1612 paramHasAttr(ArgNo, Attribute::InAlloca) ||
1613 paramHasAttr(ArgNo, Attribute::Preallocated);
1614 }
1615
1616 /// Determine if there are is an inalloca argument. Only the last argument can
1617 /// have the inalloca attribute.
1618 bool hasInAllocaArgument() const {
1619 return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca);
1620 }
1621
1622 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1623 // better indicate that this may return a conservative answer.
1624 bool doesNotAccessMemory(unsigned OpNo) const {
1625 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1626 }
1627
1628 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1629 // better indicate that this may return a conservative answer.
1630 bool onlyReadsMemory(unsigned OpNo) const {
1631 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadOnly) ||
1632 dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1633 }
1634
1635 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1636 // better indicate that this may return a conservative answer.
1637 bool doesNotReadMemory(unsigned OpNo) const {
1638 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::WriteOnly) ||
1639 dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1640 }
1641
1642 LLVM_ATTRIBUTE_DEPRECATED(unsigned getRetAlignment() const,unsigned getRetAlignment() const __attribute__((deprecated("Use getRetAlign() instead"
)))
1643 "Use getRetAlign() instead")unsigned getRetAlignment() const __attribute__((deprecated("Use getRetAlign() instead"
)))
{
1644 if (const auto MA = Attrs.getRetAlignment())
1645 return MA->value();
1646 return 0;
1647 }
1648
1649 /// Extract the alignment of the return value.
1650 MaybeAlign getRetAlign() const { return Attrs.getRetAlignment(); }
1651
1652 /// Extract the alignment for a call or parameter (0=unknown).
1653 LLVM_ATTRIBUTE_DEPRECATED(unsigned getParamAlignment(unsigned ArgNo) const,unsigned getParamAlignment(unsigned ArgNo) const __attribute__
((deprecated("Use getParamAlign() instead")))
1654 "Use getParamAlign() instead")unsigned getParamAlignment(unsigned ArgNo) const __attribute__
((deprecated("Use getParamAlign() instead")))
{
1655 if (const auto MA = Attrs.getParamAlignment(ArgNo))
1656 return MA->value();
1657 return 0;
1658 }
1659
1660 /// Extract the alignment for a call or parameter (0=unknown).
1661 MaybeAlign getParamAlign(unsigned ArgNo) const {
1662 return Attrs.getParamAlignment(ArgNo);
1663 }
1664
1665 /// Extract the byval type for a call or parameter.
1666 Type *getParamByValType(unsigned ArgNo) const {
1667 Type *Ty = Attrs.getParamByValType(ArgNo);
1668 return Ty ? Ty : getArgOperand(ArgNo)->getType()->getPointerElementType();
1669 }
1670
1671 /// Extract the preallocated type for a call or parameter.
1672 Type *getParamPreallocatedType(unsigned ArgNo) const {
1673 Type *Ty = Attrs.getParamPreallocatedType(ArgNo);
1674 return Ty ? Ty : getArgOperand(ArgNo)->getType()->getPointerElementType();
1675 }
1676
1677 /// Extract the number of dereferenceable bytes for a call or
1678 /// parameter (0=unknown).
1679 uint64_t getDereferenceableBytes(unsigned i) const {
1680 return Attrs.getDereferenceableBytes(i);
1681 }
1682
1683 /// Extract the number of dereferenceable_or_null bytes for a call or
1684 /// parameter (0=unknown).
1685 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1686 return Attrs.getDereferenceableOrNullBytes(i);
1687 }
1688
1689 /// Return true if the return value is known to be not null.
1690 /// This may be because it has the nonnull attribute, or because at least
1691 /// one byte is dereferenceable and the pointer is in addrspace(0).
1692 bool isReturnNonNull() const;
1693
1694 /// Determine if the return value is marked with NoAlias attribute.
1695 bool returnDoesNotAlias() const {
1696 return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1697 }
1698
1699 /// If one of the arguments has the 'returned' attribute, returns its
1700 /// operand value. Otherwise, return nullptr.
1701 Value *getReturnedArgOperand() const;
1702
1703 /// Return true if the call should not be treated as a call to a
1704 /// builtin.
1705 bool isNoBuiltin() const {
1706 return hasFnAttrImpl(Attribute::NoBuiltin) &&
1707 !hasFnAttrImpl(Attribute::Builtin);
1708 }
1709
1710 /// Determine if the call requires strict floating point semantics.
1711 bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1712
1713 /// Return true if the call should not be inlined.
1714 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1715 void setIsNoInline() {
1716 addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1717 }
1718 /// Determine if the call does not access memory.
1719 bool doesNotAccessMemory() const { return hasFnAttr(Attribute::ReadNone); }
1720 void setDoesNotAccessMemory() {
1721 addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1722 }
1723
1724 /// Determine if the call does not access or only reads memory.
1725 bool onlyReadsMemory() const {
1726 return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1727 }
1728 void setOnlyReadsMemory() {
1729 addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1730 }
1731
1732 /// Determine if the call does not access or only writes memory.
1733 bool doesNotReadMemory() const {
1734 return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1735 }
1736 void setDoesNotReadMemory() {
1737 addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1738 }
1739
1740 /// Determine if the call can access memmory only using pointers based
1741 /// on its arguments.
1742 bool onlyAccessesArgMemory() const {
1743 return hasFnAttr(Attribute::ArgMemOnly);
1744 }
1745 void setOnlyAccessesArgMemory() {
1746 addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1747 }
1748
1749 /// Determine if the function may only access memory that is
1750 /// inaccessible from the IR.
1751 bool onlyAccessesInaccessibleMemory() const {
1752 return hasFnAttr(Attribute::InaccessibleMemOnly);
1753 }
1754 void setOnlyAccessesInaccessibleMemory() {
1755 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOnly);
1756 }
1757
1758 /// Determine if the function may only access memory that is
1759 /// either inaccessible from the IR or pointed to by its arguments.
1760 bool onlyAccessesInaccessibleMemOrArgMem() const {
1761 return hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
1762 }
1763 void setOnlyAccessesInaccessibleMemOrArgMem() {
1764 addAttribute(AttributeList::FunctionIndex,
1765 Attribute::InaccessibleMemOrArgMemOnly);
1766 }
1767 /// Determine if the call cannot return.
1768 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1769 void setDoesNotReturn() {
1770 addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1771 }
1772
1773 /// Determine if the call should not perform indirect branch tracking.
1774 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
1775
1776 /// Determine if the call cannot unwind.
1777 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1778 void setDoesNotThrow() {
1779 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1780 }
1781
1782 /// Determine if the invoke cannot be duplicated.
1783 bool cannotDuplicate() const { return hasFnAttr(Attribute::NoDuplicate); }
1784 void setCannotDuplicate() {
1785 addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1786 }
1787
1788 /// Determine if the call cannot be tail merged.
1789 bool cannotMerge() const { return hasFnAttr(Attribute::NoMerge); }
1790 void setCannotMerge() {
1791 addAttribute(AttributeList::FunctionIndex, Attribute::NoMerge);
1792 }
1793
1794 /// Determine if the invoke is convergent
1795 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1796 void setConvergent() {
1797 addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1798 }
1799 void setNotConvergent() {
1800 removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1801 }
1802
1803 /// Determine if the call returns a structure through first
1804 /// pointer argument.
1805 bool hasStructRetAttr() const {
1806 if (getNumArgOperands() == 0)
1807 return false;
1808
1809 // Be friendly and also check the callee.
1810 return paramHasAttr(0, Attribute::StructRet);
1811 }
1812
1813 /// Determine if any call argument is an aggregate passed by value.
1814 bool hasByValArgument() const {
1815 return Attrs.hasAttrSomewhere(Attribute::ByVal);
1816 }
1817
1818 ///@{
1819 // End of attribute API.
1820
1821 /// \name Operand Bundle API
1822 ///
1823 /// This group of methods provides the API to access and manipulate operand
1824 /// bundles on this call.
1825 /// @{
1826
1827 /// Return the number of operand bundles associated with this User.
1828 unsigned getNumOperandBundles() const {
1829 return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1830 }
1831
1832 /// Return true if this User has any operand bundles.
1833 bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1834
1835 /// Return the index of the first bundle operand in the Use array.
1836 unsigned getBundleOperandsStartIndex() const {
1837 assert(hasOperandBundles() && "Don't call otherwise!")((hasOperandBundles() && "Don't call otherwise!") ? static_cast
<void> (0) : __assert_fail ("hasOperandBundles() && \"Don't call otherwise!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1837, __PRETTY_FUNCTION__))
;
1838 return bundle_op_info_begin()->Begin;
1839 }
1840
1841 /// Return the index of the last bundle operand in the Use array.
1842 unsigned getBundleOperandsEndIndex() const {
1843 assert(hasOperandBundles() && "Don't call otherwise!")((hasOperandBundles() && "Don't call otherwise!") ? static_cast
<void> (0) : __assert_fail ("hasOperandBundles() && \"Don't call otherwise!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1843, __PRETTY_FUNCTION__))
;
1844 return bundle_op_info_end()[-1].End;
1845 }
1846
1847 /// Return true if the operand at index \p Idx is a bundle operand.
1848 bool isBundleOperand(unsigned Idx) const {
1849 return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() &&
1850 Idx < getBundleOperandsEndIndex();
1851 }
1852
1853 /// Returns true if the use is a bundle operand.
1854 bool isBundleOperand(const Use *U) const {
1855 assert(this == U->getUser() &&((this == U->getUser() && "Only valid to query with a use of this instruction!"
) ? static_cast<void> (0) : __assert_fail ("this == U->getUser() && \"Only valid to query with a use of this instruction!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1856, __PRETTY_FUNCTION__))
1856 "Only valid to query with a use of this instruction!")((this == U->getUser() && "Only valid to query with a use of this instruction!"
) ? static_cast<void> (0) : __assert_fail ("this == U->getUser() && \"Only valid to query with a use of this instruction!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1856, __PRETTY_FUNCTION__))
;
1857 return hasOperandBundles() && isBundleOperand(U - op_begin());
1858 }
1859 bool isBundleOperand(Value::const_user_iterator UI) const {
1860 return isBundleOperand(&UI.getUse());
1861 }
1862
1863 /// Return the total number operands (not operand bundles) used by
1864 /// every operand bundle in this OperandBundleUser.
1865 unsigned getNumTotalBundleOperands() const {
1866 if (!hasOperandBundles())
1867 return 0;
1868
1869 unsigned Begin = getBundleOperandsStartIndex();
1870 unsigned End = getBundleOperandsEndIndex();
1871
1872 assert(Begin <= End && "Should be!")((Begin <= End && "Should be!") ? static_cast<void
> (0) : __assert_fail ("Begin <= End && \"Should be!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1872, __PRETTY_FUNCTION__))
;
1873 return End - Begin;
1874 }
1875
1876 /// Return the operand bundle at a specific index.
1877 OperandBundleUse getOperandBundleAt(unsigned Index) const {
1878 assert(Index < getNumOperandBundles() && "Index out of bounds!")((Index < getNumOperandBundles() && "Index out of bounds!"
) ? static_cast<void> (0) : __assert_fail ("Index < getNumOperandBundles() && \"Index out of bounds!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1878, __PRETTY_FUNCTION__))
;
1879 return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1880 }
1881
1882 /// Return the number of operand bundles with the tag Name attached to
1883 /// this instruction.
1884 unsigned countOperandBundlesOfType(StringRef Name) const {
1885 unsigned Count = 0;
1886 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1887 if (getOperandBundleAt(i).getTagName() == Name)
1888 Count++;
1889
1890 return Count;
1891 }
1892
1893 /// Return the number of operand bundles with the tag ID attached to
1894 /// this instruction.
1895 unsigned countOperandBundlesOfType(uint32_t ID) const {
1896 unsigned Count = 0;
1897 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1898 if (getOperandBundleAt(i).getTagID() == ID)
1899 Count++;
1900
1901 return Count;
1902 }
1903
1904 /// Return an operand bundle by name, if present.
1905 ///
1906 /// It is an error to call this for operand bundle types that may have
1907 /// multiple instances of them on the same instruction.
1908 Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1909 assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!")((countOperandBundlesOfType(Name) < 2 && "Precondition violated!"
) ? static_cast<void> (0) : __assert_fail ("countOperandBundlesOfType(Name) < 2 && \"Precondition violated!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1909, __PRETTY_FUNCTION__))
;
1910
1911 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1912 OperandBundleUse U = getOperandBundleAt(i);
1913 if (U.getTagName() == Name)
1914 return U;
1915 }
1916
1917 return None;
1918 }
1919
1920 /// Return an operand bundle by tag ID, if present.
1921 ///
1922 /// It is an error to call this for operand bundle types that may have
1923 /// multiple instances of them on the same instruction.
1924 Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1925 assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!")((countOperandBundlesOfType(ID) < 2 && "Precondition violated!"
) ? static_cast<void> (0) : __assert_fail ("countOperandBundlesOfType(ID) < 2 && \"Precondition violated!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 1925, __PRETTY_FUNCTION__))
;
1926
1927 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1928 OperandBundleUse U = getOperandBundleAt(i);
1929 if (U.getTagID() == ID)
1930 return U;
1931 }
1932
1933 return None;
1934 }
1935
1936 /// Return the list of operand bundles attached to this instruction as
1937 /// a vector of OperandBundleDefs.
1938 ///
1939 /// This function copies the OperandBundeUse instances associated with this
1940 /// OperandBundleUser to a vector of OperandBundleDefs. Note:
1941 /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1942 /// representations of operand bundles (see documentation above).
1943 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const;
1944
1945 /// Return the operand bundle for the operand at index OpIdx.
1946 ///
1947 /// It is an error to call this with an OpIdx that does not correspond to an
1948 /// bundle operand.
1949 OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1950 return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
1951 }
1952
1953 /// Return true if this operand bundle user has operand bundles that
1954 /// may read from the heap.
1955 bool hasReadingOperandBundles() const {
1956 // Implementation note: this is a conservative implementation of operand
1957 // bundle semantics, where *any* operand bundle forces a callsite to be at
1958 // least readonly.
1959 return hasOperandBundles();
1960 }
1961
1962 /// Return true if this operand bundle user has operand bundles that
1963 /// may write to the heap.
1964 bool hasClobberingOperandBundles() const {
1965 for (auto &BOI : bundle_op_infos()) {
1966 if (BOI.Tag->second == LLVMContext::OB_deopt ||
1967 BOI.Tag->second == LLVMContext::OB_funclet)
1968 continue;
1969
1970 // This instruction has an operand bundle that is not known to us.
1971 // Assume the worst.
1972 return true;
1973 }
1974
1975 return false;
1976 }
1977
1978 /// Return true if the bundle operand at index \p OpIdx has the
1979 /// attribute \p A.
1980 bool bundleOperandHasAttr(unsigned OpIdx, Attribute::AttrKind A) const {
1981 auto &BOI = getBundleOpInfoForOperand(OpIdx);
1982 auto OBU = operandBundleFromBundleOpInfo(BOI);
1983 return OBU.operandHasAttr(OpIdx - BOI.Begin, A);
1984 }
1985
1986 /// Return true if \p Other has the same sequence of operand bundle
1987 /// tags with the same number of operands on each one of them as this
1988 /// OperandBundleUser.
1989 bool hasIdenticalOperandBundleSchema(const CallBase &Other) const {
1990 if (getNumOperandBundles() != Other.getNumOperandBundles())
1991 return false;
1992
1993 return std::equal(bundle_op_info_begin(), bundle_op_info_end(),
1994 Other.bundle_op_info_begin());
1995 }
1996
1997 /// Return true if this operand bundle user contains operand bundles
1998 /// with tags other than those specified in \p IDs.
1999 bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const {
2000 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
2001 uint32_t ID = getOperandBundleAt(i).getTagID();
2002 if (!is_contained(IDs, ID))
2003 return true;
2004 }
2005 return false;
2006 }
2007
2008 /// Is the function attribute S disallowed by some operand bundle on
2009 /// this operand bundle user?
2010 bool isFnAttrDisallowedByOpBundle(StringRef S) const {
2011 // Operand bundles only possibly disallow readnone, readonly and argmemonly
2012 // attributes. All String attributes are fine.
2013 return false;
2014 }
2015
2016 /// Is the function attribute A disallowed by some operand bundle on
2017 /// this operand bundle user?
2018 bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
2019 switch (A) {
2020 default:
2021 return false;
2022
2023 case Attribute::InaccessibleMemOrArgMemOnly:
2024 return hasReadingOperandBundles();
2025
2026 case Attribute::InaccessibleMemOnly:
2027 return hasReadingOperandBundles();
2028
2029 case Attribute::ArgMemOnly:
2030 return hasReadingOperandBundles();
2031
2032 case Attribute::ReadNone:
2033 return hasReadingOperandBundles();
2034
2035 case Attribute::ReadOnly:
2036 return hasClobberingOperandBundles();
2037 }
2038
2039 llvm_unreachable("switch has a default case!")::llvm::llvm_unreachable_internal("switch has a default case!"
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 2039)
;
2040 }
2041
2042 /// Used to keep track of an operand bundle. See the main comment on
2043 /// OperandBundleUser above.
2044 struct BundleOpInfo {
2045 /// The operand bundle tag, interned by
2046 /// LLVMContextImpl::getOrInsertBundleTag.
2047 StringMapEntry<uint32_t> *Tag;
2048
2049 /// The index in the Use& vector where operands for this operand
2050 /// bundle starts.
2051 uint32_t Begin;
2052
2053 /// The index in the Use& vector where operands for this operand
2054 /// bundle ends.
2055 uint32_t End;
2056
2057 bool operator==(const BundleOpInfo &Other) const {
2058 return Tag == Other.Tag && Begin == Other.Begin && End == Other.End;
2059 }
2060 };
2061
2062 /// Simple helper function to map a BundleOpInfo to an
2063 /// OperandBundleUse.
2064 OperandBundleUse
2065 operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
2066 auto begin = op_begin();
2067 ArrayRef<Use> Inputs(begin + BOI.Begin, begin + BOI.End);
2068 return OperandBundleUse(BOI.Tag, Inputs);
2069 }
2070
2071 using bundle_op_iterator = BundleOpInfo *;
2072 using const_bundle_op_iterator = const BundleOpInfo *;
2073
2074 /// Return the start of the list of BundleOpInfo instances associated
2075 /// with this OperandBundleUser.
2076 ///
2077 /// OperandBundleUser uses the descriptor area co-allocated with the host User
2078 /// to store some meta information about which operands are "normal" operands,
2079 /// and which ones belong to some operand bundle.
2080 ///
2081 /// The layout of an operand bundle user is
2082 ///
2083 /// +-----------uint32_t End-------------------------------------+
2084 /// | |
2085 /// | +--------uint32_t Begin--------------------+ |
2086 /// | | | |
2087 /// ^ ^ v v
2088 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
2089 /// | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
2090 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
2091 /// v v ^ ^
2092 /// | | | |
2093 /// | +--------uint32_t Begin------------+ |
2094 /// | |
2095 /// +-----------uint32_t End-----------------------------+
2096 ///
2097 ///
2098 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use
2099 /// list. These descriptions are installed and managed by this class, and
2100 /// they're all instances of OperandBundleUser<T>::BundleOpInfo.
2101 ///
2102 /// DU is an additional descriptor installed by User's 'operator new' to keep
2103 /// track of the 'BOI0 ... BOIN' co-allocation. OperandBundleUser does not
2104 /// access or modify DU in any way, it's an implementation detail private to
2105 /// User.
2106 ///
2107 /// The regular Use& vector for the User starts at U0. The operand bundle
2108 /// uses are part of the Use& vector, just like normal uses. In the diagram
2109 /// above, the operand bundle uses start at BOI0_U0. Each instance of
2110 /// BundleOpInfo has information about a contiguous set of uses constituting
2111 /// an operand bundle, and the total set of operand bundle uses themselves
2112 /// form a contiguous set of uses (i.e. there are no gaps between uses
2113 /// corresponding to individual operand bundles).
2114 ///
2115 /// This class does not know the location of the set of operand bundle uses
2116 /// within the use list -- that is decided by the User using this class via
2117 /// the BeginIdx argument in populateBundleOperandInfos.
2118 ///
2119 /// Currently operand bundle users with hung-off operands are not supported.
2120 bundle_op_iterator bundle_op_info_begin() {
2121 if (!hasDescriptor())
2122 return nullptr;
2123
2124 uint8_t *BytesBegin = getDescriptor().begin();
2125 return reinterpret_cast<bundle_op_iterator>(BytesBegin);
2126 }
2127
2128 /// Return the start of the list of BundleOpInfo instances associated
2129 /// with this OperandBundleUser.
2130 const_bundle_op_iterator bundle_op_info_begin() const {
2131 auto *NonConstThis = const_cast<CallBase *>(this);
2132 return NonConstThis->bundle_op_info_begin();
2133 }
2134
2135 /// Return the end of the list of BundleOpInfo instances associated
2136 /// with this OperandBundleUser.
2137 bundle_op_iterator bundle_op_info_end() {
2138 if (!hasDescriptor())
2139 return nullptr;
2140
2141 uint8_t *BytesEnd = getDescriptor().end();
2142 return reinterpret_cast<bundle_op_iterator>(BytesEnd);
2143 }
2144
2145 /// Return the end of the list of BundleOpInfo instances associated
2146 /// with this OperandBundleUser.
2147 const_bundle_op_iterator bundle_op_info_end() const {
2148 auto *NonConstThis = const_cast<CallBase *>(this);
2149 return NonConstThis->bundle_op_info_end();
2150 }
2151
2152 /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
2153 iterator_range<bundle_op_iterator> bundle_op_infos() {
2154 return make_range(bundle_op_info_begin(), bundle_op_info_end());
2155 }
2156
2157 /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
2158 iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
2159 return make_range(bundle_op_info_begin(), bundle_op_info_end());
2160 }
2161
2162 /// Populate the BundleOpInfo instances and the Use& vector from \p
2163 /// Bundles. Return the op_iterator pointing to the Use& one past the last
2164 /// last bundle operand use.
2165 ///
2166 /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
2167 /// instance allocated in this User's descriptor.
2168 op_iterator populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
2169 const unsigned BeginIndex);
2170
2171public:
2172 /// Return the BundleOpInfo for the operand at index OpIdx.
2173 ///
2174 /// It is an error to call this with an OpIdx that does not correspond to an
2175 /// bundle operand.
2176 BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx);
2177 const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
2178 return const_cast<CallBase *>(this)->getBundleOpInfoForOperand(OpIdx);
2179 }
2180
2181protected:
2182 /// Return the total number of values used in \p Bundles.
2183 static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
2184 unsigned Total = 0;
2185 for (auto &B : Bundles)
2186 Total += B.input_size();
2187 return Total;
2188 }
2189
2190 /// @}
2191 // End of operand bundle API.
2192
2193private:
2194 bool hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
2195 bool hasFnAttrOnCalledFunction(StringRef Kind) const;
2196
2197 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
2198 if (Attrs.hasFnAttribute(Kind))
2199 return true;
2200
2201 // Operand bundles override attributes on the called function, but don't
2202 // override attributes directly present on the call instruction.
2203 if (isFnAttrDisallowedByOpBundle(Kind))
2204 return false;
2205
2206 return hasFnAttrOnCalledFunction(Kind);
2207 }
2208};
2209
2210template <>
2211struct OperandTraits<CallBase> : public VariadicOperandTraits<CallBase, 1> {};
2212
2213DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallBase, Value)CallBase::op_iterator CallBase::op_begin() { return OperandTraits
<CallBase>::op_begin(this); } CallBase::const_op_iterator
CallBase::op_begin() const { return OperandTraits<CallBase
>::op_begin(const_cast<CallBase*>(this)); } CallBase
::op_iterator CallBase::op_end() { return OperandTraits<CallBase
>::op_end(this); } CallBase::const_op_iterator CallBase::op_end
() const { return OperandTraits<CallBase>::op_end(const_cast
<CallBase*>(this)); } Value *CallBase::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<CallBase
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CallBase>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 2213, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<CallBase>::op_begin(const_cast<CallBase
*>(this))[i_nocapture].get()); } void CallBase::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<CallBase>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CallBase>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 2213, __PRETTY_FUNCTION__)); OperandTraits<CallBase>::
op_begin(this)[i_nocapture] = Val_nocapture; } unsigned CallBase
::getNumOperands() const { return OperandTraits<CallBase>
::operands(this); } template <int Idx_nocapture> Use &
CallBase::Op() { return this->OpFrom<Idx_nocapture>(
this); } template <int Idx_nocapture> const Use &CallBase
::Op() const { return this->OpFrom<Idx_nocapture>(this
); }
2214
2215//===----------------------------------------------------------------------===//
2216// FuncletPadInst Class
2217//===----------------------------------------------------------------------===//
2218class FuncletPadInst : public Instruction {
2219private:
2220 FuncletPadInst(const FuncletPadInst &CPI);
2221
2222 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2223 ArrayRef<Value *> Args, unsigned Values,
2224 const Twine &NameStr, Instruction *InsertBefore);
2225 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2226 ArrayRef<Value *> Args, unsigned Values,
2227 const Twine &NameStr, BasicBlock *InsertAtEnd);
2228
2229 void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
2230
2231protected:
2232 // Note: Instruction needs to be a friend here to call cloneImpl.
2233 friend class Instruction;
2234 friend class CatchPadInst;
2235 friend class CleanupPadInst;
2236
2237 FuncletPadInst *cloneImpl() const;
2238
2239public:
2240 /// Provide fast operand accessors
2241 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
;
2242
2243 /// getNumArgOperands - Return the number of funcletpad arguments.
2244 ///
2245 unsigned getNumArgOperands() const { return getNumOperands() - 1; }
2246
2247 /// Convenience accessors
2248
2249 /// Return the outer EH-pad this funclet is nested within.
2250 ///
2251 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
2252 /// is a CatchPadInst.
2253 Value *getParentPad() const { return Op<-1>(); }
2254 void setParentPad(Value *ParentPad) {
2255 assert(ParentPad)((ParentPad) ? static_cast<void> (0) : __assert_fail ("ParentPad"
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 2255, __PRETTY_FUNCTION__))
;
2256 Op<-1>() = ParentPad;
2257 }
2258
2259 /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
2260 ///
2261 Value *getArgOperand(unsigned i) const { return getOperand(i); }
2262 void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
2263
2264 /// arg_operands - iteration adapter for range-for loops.
2265 op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
2266
2267 /// arg_operands - iteration adapter for range-for loops.
2268 const_op_range arg_operands() const {
2269 return const_op_range(op_begin(), op_end() - 1);
2270 }
2271
2272 // Methods for support type inquiry through isa, cast, and dyn_cast:
2273 static bool classof(const Instruction *I) { return I->isFuncletPad(); }
2274 static bool classof(const Value *V) {
2275 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2276 }
2277};
2278
2279template <>
2280struct OperandTraits<FuncletPadInst>
2281 : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {};
2282
2283DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)FuncletPadInst::op_iterator FuncletPadInst::op_begin() { return
OperandTraits<FuncletPadInst>::op_begin(this); } FuncletPadInst
::const_op_iterator FuncletPadInst::op_begin() const { return
OperandTraits<FuncletPadInst>::op_begin(const_cast<
FuncletPadInst*>(this)); } FuncletPadInst::op_iterator FuncletPadInst
::op_end() { return OperandTraits<FuncletPadInst>::op_end
(this); } FuncletPadInst::const_op_iterator FuncletPadInst::op_end
() const { return OperandTraits<FuncletPadInst>::op_end
(const_cast<FuncletPadInst*>(this)); } Value *FuncletPadInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<FuncletPadInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<FuncletPadInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 2283, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<FuncletPadInst>::op_begin(const_cast<
FuncletPadInst*>(this))[i_nocapture].get()); } void FuncletPadInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<FuncletPadInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<FuncletPadInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/IR/InstrTypes.h"
, 2283, __PRETTY_FUNCTION__)); OperandTraits<FuncletPadInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
FuncletPadInst::getNumOperands() const { return OperandTraits
<FuncletPadInst>::operands(this); } template <int Idx_nocapture
> Use &FuncletPadInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &FuncletPadInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
2284
2285} // end namespace llvm
2286
2287#endif // LLVM_IR_INSTRTYPES_H