[InstCombine] Signed saturation patterns
[llvm-complete.git] / include / llvm / IR / InstrTypes.h
blob7fb94e9d8c22c73e7096be8f3fdbaa2aa2e703e5
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...
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_INSTRTYPES_H
16 #define LLVM_IR_INSTRTYPES_H
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>
47 namespace llvm {
49 namespace Intrinsic {
50 enum ID : unsigned;
53 //===----------------------------------------------------------------------===//
54 // UnaryInstruction Class
55 //===----------------------------------------------------------------------===//
57 class UnaryInstruction : public Instruction {
58 protected:
59 UnaryInstruction(Type *Ty, unsigned iType, Value *V,
60 Instruction *IB = nullptr)
61 : Instruction(Ty, iType, &Op<0>(), 1, IB) {
62 Op<0>() = V;
64 UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
65 : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
66 Op<0>() = V;
69 public:
70 // allocate space for exactly one operand
71 void *operator new(size_t s) {
72 return User::operator new(s, 1);
75 /// Transparently provide more efficient getOperand methods.
76 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
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);
87 static bool classof(const Value *V) {
88 return isa<Instruction>(V) && classof(cast<Instruction>(V));
92 template <>
93 struct OperandTraits<UnaryInstruction> :
94 public FixedNumOperandTraits<UnaryInstruction, 1> {
97 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
99 //===----------------------------------------------------------------------===//
100 // UnaryOperator Class
101 //===----------------------------------------------------------------------===//
103 class UnaryOperator : public UnaryInstruction {
104 void AssertOK();
106 protected:
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);
112 // Note: Instruction needs to be a friend here to call cloneImpl.
113 friend class Instruction;
115 UnaryOperator *cloneImpl() const;
117 public:
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.
124 static UnaryOperator *Create(UnaryOps Op, Value *S,
125 const Twine &Name = Twine(),
126 Instruction *InsertBefore = nullptr);
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.
132 static UnaryOperator *Create(UnaryOps Op, Value *S,
133 const Twine &Name,
134 BasicBlock *InsertAtEnd);
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);\
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);\
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);\
155 #include "llvm/IR/Instruction.def"
157 static UnaryOperator *CreateWithCopiedFlags(UnaryOps Opc,
158 Value *V,
159 Instruction *CopyO,
160 const Twine &Name = "") {
161 UnaryOperator *UO = Create(Opc, V, Name);
162 UO->copyIRFlags(CopyO);
163 return UO;
166 static UnaryOperator *CreateFNegFMF(Value *Op, Instruction *FMFSource,
167 const Twine &Name = "") {
168 return CreateWithCopiedFlags(Instruction::FNeg, Op, FMFSource, Name);
171 UnaryOps getOpcode() const {
172 return static_cast<UnaryOps>(Instruction::getOpcode());
175 // Methods for support type inquiry through isa, cast, and dyn_cast:
176 static bool classof(const Instruction *I) {
177 return I->isUnaryOp();
179 static bool classof(const Value *V) {
180 return isa<Instruction>(V) && classof(cast<Instruction>(V));
184 //===----------------------------------------------------------------------===//
185 // BinaryOperator Class
186 //===----------------------------------------------------------------------===//
188 class BinaryOperator : public Instruction {
189 void AssertOK();
191 protected:
192 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
193 const Twine &Name, Instruction *InsertBefore);
194 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
195 const Twine &Name, BasicBlock *InsertAtEnd);
197 // Note: Instruction needs to be a friend here to call cloneImpl.
198 friend class Instruction;
200 BinaryOperator *cloneImpl() const;
202 public:
203 // allocate space for exactly two operands
204 void *operator new(size_t s) {
205 return User::operator new(s, 2);
208 /// Transparently provide more efficient getOperand methods.
209 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
211 /// Construct a binary instruction, given the opcode and the two
212 /// operands. Optionally (if InstBefore is specified) insert the instruction
213 /// into a BasicBlock right before the specified instruction. The specified
214 /// Instruction is allowed to be a dereferenced end iterator.
216 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
217 const Twine &Name = Twine(),
218 Instruction *InsertBefore = nullptr);
220 /// Construct a binary instruction, given the opcode and the two
221 /// operands. Also automatically insert this instruction to the end of the
222 /// BasicBlock specified.
224 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
225 const Twine &Name, BasicBlock *InsertAtEnd);
227 /// These methods just forward to Create, and are useful when you
228 /// statically know what type of instruction you're going to create. These
229 /// helpers just save some typing.
230 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
231 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
232 const Twine &Name = "") {\
233 return Create(Instruction::OPC, V1, V2, Name);\
235 #include "llvm/IR/Instruction.def"
236 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
237 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
238 const Twine &Name, BasicBlock *BB) {\
239 return Create(Instruction::OPC, V1, V2, Name, BB);\
241 #include "llvm/IR/Instruction.def"
242 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
243 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
244 const Twine &Name, Instruction *I) {\
245 return Create(Instruction::OPC, V1, V2, Name, I);\
247 #include "llvm/IR/Instruction.def"
249 static BinaryOperator *CreateWithCopiedFlags(BinaryOps Opc,
250 Value *V1, Value *V2,
251 Instruction *CopyO,
252 const Twine &Name = "") {
253 BinaryOperator *BO = Create(Opc, V1, V2, Name);
254 BO->copyIRFlags(CopyO);
255 return BO;
258 static BinaryOperator *CreateFAddFMF(Value *V1, Value *V2,
259 Instruction *FMFSource,
260 const Twine &Name = "") {
261 return CreateWithCopiedFlags(Instruction::FAdd, V1, V2, FMFSource, Name);
263 static BinaryOperator *CreateFSubFMF(Value *V1, Value *V2,
264 Instruction *FMFSource,
265 const Twine &Name = "") {
266 return CreateWithCopiedFlags(Instruction::FSub, V1, V2, FMFSource, Name);
268 static BinaryOperator *CreateFMulFMF(Value *V1, Value *V2,
269 Instruction *FMFSource,
270 const Twine &Name = "") {
271 return CreateWithCopiedFlags(Instruction::FMul, V1, V2, FMFSource, Name);
273 static BinaryOperator *CreateFDivFMF(Value *V1, Value *V2,
274 Instruction *FMFSource,
275 const Twine &Name = "") {
276 return CreateWithCopiedFlags(Instruction::FDiv, V1, V2, FMFSource, Name);
278 static BinaryOperator *CreateFRemFMF(Value *V1, Value *V2,
279 Instruction *FMFSource,
280 const Twine &Name = "") {
281 return CreateWithCopiedFlags(Instruction::FRem, V1, V2, FMFSource, Name);
283 static BinaryOperator *CreateFNegFMF(Value *Op, Instruction *FMFSource,
284 const Twine &Name = "") {
285 Value *Zero = ConstantFP::getNegativeZero(Op->getType());
286 return CreateWithCopiedFlags(Instruction::FSub, Zero, Op, FMFSource, Name);
289 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
290 const Twine &Name = "") {
291 BinaryOperator *BO = Create(Opc, V1, V2, Name);
292 BO->setHasNoSignedWrap(true);
293 return BO;
295 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
296 const Twine &Name, BasicBlock *BB) {
297 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
298 BO->setHasNoSignedWrap(true);
299 return BO;
301 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
302 const Twine &Name, Instruction *I) {
303 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
304 BO->setHasNoSignedWrap(true);
305 return BO;
308 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
309 const Twine &Name = "") {
310 BinaryOperator *BO = Create(Opc, V1, V2, Name);
311 BO->setHasNoUnsignedWrap(true);
312 return BO;
314 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
315 const Twine &Name, BasicBlock *BB) {
316 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
317 BO->setHasNoUnsignedWrap(true);
318 return BO;
320 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
321 const Twine &Name, Instruction *I) {
322 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
323 BO->setHasNoUnsignedWrap(true);
324 return BO;
327 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
328 const Twine &Name = "") {
329 BinaryOperator *BO = Create(Opc, V1, V2, Name);
330 BO->setIsExact(true);
331 return BO;
333 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
334 const Twine &Name, BasicBlock *BB) {
335 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
336 BO->setIsExact(true);
337 return BO;
339 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
340 const Twine &Name, Instruction *I) {
341 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
342 BO->setIsExact(true);
343 return BO;
346 #define DEFINE_HELPERS(OPC, NUWNSWEXACT) \
347 static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2, \
348 const Twine &Name = "") { \
349 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \
351 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
352 Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) { \
353 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB); \
355 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
356 Value *V1, Value *V2, const Twine &Name, Instruction *I) { \
357 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I); \
360 DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
361 DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
362 DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
363 DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
364 DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
365 DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
366 DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
367 DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
369 DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv
370 DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv
371 DEFINE_HELPERS(AShr, Exact) // CreateExactAShr
372 DEFINE_HELPERS(LShr, Exact) // CreateExactLShr
374 #undef DEFINE_HELPERS
376 /// Helper functions to construct and inspect unary operations (NEG and NOT)
377 /// via binary operators SUB and XOR:
379 /// Create the NEG and NOT instructions out of SUB and XOR instructions.
381 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
382 Instruction *InsertBefore = nullptr);
383 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
384 BasicBlock *InsertAtEnd);
385 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
386 Instruction *InsertBefore = nullptr);
387 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
388 BasicBlock *InsertAtEnd);
389 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
390 Instruction *InsertBefore = nullptr);
391 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
392 BasicBlock *InsertAtEnd);
393 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
394 Instruction *InsertBefore = nullptr);
395 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
396 BasicBlock *InsertAtEnd);
397 static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
398 Instruction *InsertBefore = nullptr);
399 static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
400 BasicBlock *InsertAtEnd);
402 BinaryOps getOpcode() const {
403 return static_cast<BinaryOps>(Instruction::getOpcode());
406 /// Exchange the two operands to this instruction.
407 /// This instruction is safe to use on any binary instruction and
408 /// does not modify the semantics of the instruction. If the instruction
409 /// cannot be reversed (ie, it's a Div), then return true.
411 bool swapOperands();
413 // Methods for support type inquiry through isa, cast, and dyn_cast:
414 static bool classof(const Instruction *I) {
415 return I->isBinaryOp();
417 static bool classof(const Value *V) {
418 return isa<Instruction>(V) && classof(cast<Instruction>(V));
422 template <>
423 struct OperandTraits<BinaryOperator> :
424 public FixedNumOperandTraits<BinaryOperator, 2> {
427 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
429 //===----------------------------------------------------------------------===//
430 // CastInst Class
431 //===----------------------------------------------------------------------===//
433 /// This is the base class for all instructions that perform data
434 /// casts. It is simply provided so that instruction category testing
435 /// can be performed with code like:
437 /// if (isa<CastInst>(Instr)) { ... }
438 /// Base class of casting instructions.
439 class CastInst : public UnaryInstruction {
440 protected:
441 /// Constructor with insert-before-instruction semantics for subclasses
442 CastInst(Type *Ty, unsigned iType, Value *S,
443 const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
444 : UnaryInstruction(Ty, iType, S, InsertBefore) {
445 setName(NameStr);
447 /// Constructor with insert-at-end-of-block semantics for subclasses
448 CastInst(Type *Ty, unsigned iType, Value *S,
449 const Twine &NameStr, BasicBlock *InsertAtEnd)
450 : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
451 setName(NameStr);
454 public:
455 /// Provides a way to construct any of the CastInst subclasses using an
456 /// opcode instead of the subclass's constructor. The opcode must be in the
457 /// CastOps category (Instruction::isCast(opcode) returns true). This
458 /// constructor has insert-before-instruction semantics to automatically
459 /// insert the new CastInst before InsertBefore (if it is non-null).
460 /// Construct any of the CastInst subclasses
461 static CastInst *Create(
462 Instruction::CastOps, ///< The opcode of the cast instruction
463 Value *S, ///< The value to be casted (operand 0)
464 Type *Ty, ///< The type to which cast should be made
465 const Twine &Name = "", ///< Name for the instruction
466 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
468 /// Provides a way to construct any of the CastInst subclasses using an
469 /// opcode instead of the subclass's constructor. The opcode must be in the
470 /// CastOps category. This constructor has insert-at-end-of-block semantics
471 /// to automatically insert the new CastInst at the end of InsertAtEnd (if
472 /// its non-null).
473 /// Construct any of the CastInst subclasses
474 static CastInst *Create(
475 Instruction::CastOps, ///< The opcode for the cast instruction
476 Value *S, ///< The value to be casted (operand 0)
477 Type *Ty, ///< The type to which operand is casted
478 const Twine &Name, ///< The name for the instruction
479 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
482 /// Create a ZExt or BitCast cast instruction
483 static CastInst *CreateZExtOrBitCast(
484 Value *S, ///< The value to be casted (operand 0)
485 Type *Ty, ///< The type to which cast should be made
486 const Twine &Name = "", ///< Name for the instruction
487 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
490 /// Create a ZExt or BitCast cast instruction
491 static CastInst *CreateZExtOrBitCast(
492 Value *S, ///< The value to be casted (operand 0)
493 Type *Ty, ///< The type to which operand is casted
494 const Twine &Name, ///< The name for the instruction
495 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
498 /// Create a SExt or BitCast cast instruction
499 static CastInst *CreateSExtOrBitCast(
500 Value *S, ///< The value to be casted (operand 0)
501 Type *Ty, ///< The type to which cast should be made
502 const Twine &Name = "", ///< Name for the instruction
503 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
506 /// Create a SExt or BitCast cast instruction
507 static CastInst *CreateSExtOrBitCast(
508 Value *S, ///< The value to be casted (operand 0)
509 Type *Ty, ///< The type to which operand is casted
510 const Twine &Name, ///< The name for the instruction
511 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
514 /// Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
515 static CastInst *CreatePointerCast(
516 Value *S, ///< The pointer value to be casted (operand 0)
517 Type *Ty, ///< The type to which operand is casted
518 const Twine &Name, ///< The name for the instruction
519 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
522 /// Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
523 static CastInst *CreatePointerCast(
524 Value *S, ///< The pointer value to be casted (operand 0)
525 Type *Ty, ///< The type to which cast should be made
526 const Twine &Name = "", ///< Name for the instruction
527 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
530 /// Create a BitCast or an AddrSpaceCast cast instruction.
531 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
532 Value *S, ///< The pointer value to be casted (operand 0)
533 Type *Ty, ///< The type to which operand is casted
534 const Twine &Name, ///< The name for the instruction
535 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
538 /// Create a BitCast or an AddrSpaceCast cast instruction.
539 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
540 Value *S, ///< The pointer value to be casted (operand 0)
541 Type *Ty, ///< The type to which cast should be made
542 const Twine &Name = "", ///< Name for the instruction
543 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
546 /// Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
548 /// If the value is a pointer type and the destination an integer type,
549 /// creates a PtrToInt cast. If the value is an integer type and the
550 /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
551 /// a bitcast.
552 static CastInst *CreateBitOrPointerCast(
553 Value *S, ///< The pointer value to be casted (operand 0)
554 Type *Ty, ///< The type to which cast should be made
555 const Twine &Name = "", ///< Name for the instruction
556 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
559 /// Create a ZExt, BitCast, or Trunc for int -> int casts.
560 static CastInst *CreateIntegerCast(
561 Value *S, ///< The pointer value to be casted (operand 0)
562 Type *Ty, ///< The type to which cast should be made
563 bool isSigned, ///< Whether to regard S as signed or not
564 const Twine &Name = "", ///< Name for the instruction
565 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
568 /// Create a ZExt, BitCast, or Trunc for int -> int casts.
569 static CastInst *CreateIntegerCast(
570 Value *S, ///< The integer value to be casted (operand 0)
571 Type *Ty, ///< The integer type to which operand is casted
572 bool isSigned, ///< Whether to regard S as signed or not
573 const Twine &Name, ///< The name for the instruction
574 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
577 /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
578 static CastInst *CreateFPCast(
579 Value *S, ///< The floating point value to be casted
580 Type *Ty, ///< The floating point type to cast to
581 const Twine &Name = "", ///< Name for the instruction
582 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
585 /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
586 static CastInst *CreateFPCast(
587 Value *S, ///< The floating point value to be casted
588 Type *Ty, ///< The floating point type to cast to
589 const Twine &Name, ///< The name for the instruction
590 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
593 /// Create a Trunc or BitCast cast instruction
594 static CastInst *CreateTruncOrBitCast(
595 Value *S, ///< The value to be casted (operand 0)
596 Type *Ty, ///< The type to which cast should be made
597 const Twine &Name = "", ///< Name for the instruction
598 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
601 /// Create a Trunc or BitCast cast instruction
602 static CastInst *CreateTruncOrBitCast(
603 Value *S, ///< The value to be casted (operand 0)
604 Type *Ty, ///< The type to which operand is casted
605 const Twine &Name, ///< The name for the instruction
606 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
609 /// Check whether it is valid to call getCastOpcode for these types.
610 static bool isCastable(
611 Type *SrcTy, ///< The Type from which the value should be cast.
612 Type *DestTy ///< The Type to which the value should be cast.
615 /// Check whether a bitcast between these types is valid
616 static bool isBitCastable(
617 Type *SrcTy, ///< The Type from which the value should be cast.
618 Type *DestTy ///< The Type to which the value should be cast.
621 /// Check whether a bitcast, inttoptr, or ptrtoint cast between these
622 /// types is valid and a no-op.
624 /// This ensures that any pointer<->integer cast has enough bits in the
625 /// integer and any other cast is a bitcast.
626 static bool isBitOrNoopPointerCastable(
627 Type *SrcTy, ///< The Type from which the value should be cast.
628 Type *DestTy, ///< The Type to which the value should be cast.
629 const DataLayout &DL);
631 /// Returns the opcode necessary to cast Val into Ty using usual casting
632 /// rules.
633 /// Infer the opcode for cast operand and type
634 static Instruction::CastOps getCastOpcode(
635 const Value *Val, ///< The value to cast
636 bool SrcIsSigned, ///< Whether to treat the source as signed
637 Type *Ty, ///< The Type to which the value should be casted
638 bool DstIsSigned ///< Whether to treate the dest. as signed
641 /// There are several places where we need to know if a cast instruction
642 /// only deals with integer source and destination types. To simplify that
643 /// logic, this method is provided.
644 /// @returns true iff the cast has only integral typed operand and dest type.
645 /// Determine if this is an integer-only cast.
646 bool isIntegerCast() const;
648 /// A lossless cast is one that does not alter the basic value. It implies
649 /// a no-op cast but is more stringent, preventing things like int->float,
650 /// long->double, or int->ptr.
651 /// @returns true iff the cast is lossless.
652 /// Determine if this is a lossless cast.
653 bool isLosslessCast() const;
655 /// A no-op cast is one that can be effected without changing any bits.
656 /// It implies that the source and destination types are the same size. The
657 /// DataLayout argument is to determine the pointer size when examining casts
658 /// involving Integer and Pointer types. They are no-op casts if the integer
659 /// is the same size as the pointer. However, pointer size varies with
660 /// platform.
661 /// Determine if the described cast is a no-op cast.
662 static bool isNoopCast(
663 Instruction::CastOps Opcode, ///< Opcode of cast
664 Type *SrcTy, ///< SrcTy of cast
665 Type *DstTy, ///< DstTy of cast
666 const DataLayout &DL ///< DataLayout to get the Int Ptr type from.
669 /// Determine if this cast is a no-op cast.
671 /// \param DL is the DataLayout to determine pointer size.
672 bool isNoopCast(const DataLayout &DL) const;
674 /// Determine how a pair of casts can be eliminated, if they can be at all.
675 /// This is a helper function for both CastInst and ConstantExpr.
676 /// @returns 0 if the CastInst pair can't be eliminated, otherwise
677 /// returns Instruction::CastOps value for a cast that can replace
678 /// the pair, casting SrcTy to DstTy.
679 /// Determine if a cast pair is eliminable
680 static unsigned isEliminableCastPair(
681 Instruction::CastOps firstOpcode, ///< Opcode of first cast
682 Instruction::CastOps secondOpcode, ///< Opcode of second cast
683 Type *SrcTy, ///< SrcTy of 1st cast
684 Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
685 Type *DstTy, ///< DstTy of 2nd cast
686 Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
687 Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
688 Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null
691 /// Return the opcode of this CastInst
692 Instruction::CastOps getOpcode() const {
693 return Instruction::CastOps(Instruction::getOpcode());
696 /// Return the source type, as a convenience
697 Type* getSrcTy() const { return getOperand(0)->getType(); }
698 /// Return the destination type, as a convenience
699 Type* getDestTy() const { return getType(); }
701 /// This method can be used to determine if a cast from S to DstTy using
702 /// Opcode op is valid or not.
703 /// @returns true iff the proposed cast is valid.
704 /// Determine if a cast is valid without creating one.
705 static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
707 /// Methods for support type inquiry through isa, cast, and dyn_cast:
708 static bool classof(const Instruction *I) {
709 return I->isCast();
711 static bool classof(const Value *V) {
712 return isa<Instruction>(V) && classof(cast<Instruction>(V));
716 //===----------------------------------------------------------------------===//
717 // CmpInst Class
718 //===----------------------------------------------------------------------===//
720 /// This class is the base class for the comparison instructions.
721 /// Abstract base class of comparison instructions.
722 class CmpInst : public Instruction {
723 public:
724 /// This enumeration lists the possible predicates for CmpInst subclasses.
725 /// Values in the range 0-31 are reserved for FCmpInst, while values in the
726 /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
727 /// predicate values are not overlapping between the classes.
729 /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of
730 /// FCMP_* values. Changing the bit patterns requires a potential change to
731 /// those passes.
732 enum Predicate {
733 // Opcode U L G E Intuitive operation
734 FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded)
735 FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal
736 FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than
737 FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal
738 FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than
739 FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal
740 FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal
741 FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans)
742 FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y)
743 FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal
744 FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than
745 FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal
746 FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than
747 FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal
748 FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal
749 FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded)
750 FIRST_FCMP_PREDICATE = FCMP_FALSE,
751 LAST_FCMP_PREDICATE = FCMP_TRUE,
752 BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
753 ICMP_EQ = 32, ///< equal
754 ICMP_NE = 33, ///< not equal
755 ICMP_UGT = 34, ///< unsigned greater than
756 ICMP_UGE = 35, ///< unsigned greater or equal
757 ICMP_ULT = 36, ///< unsigned less than
758 ICMP_ULE = 37, ///< unsigned less or equal
759 ICMP_SGT = 38, ///< signed greater than
760 ICMP_SGE = 39, ///< signed greater or equal
761 ICMP_SLT = 40, ///< signed less than
762 ICMP_SLE = 41, ///< signed less or equal
763 FIRST_ICMP_PREDICATE = ICMP_EQ,
764 LAST_ICMP_PREDICATE = ICMP_SLE,
765 BAD_ICMP_PREDICATE = ICMP_SLE + 1
768 protected:
769 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
770 Value *LHS, Value *RHS, const Twine &Name = "",
771 Instruction *InsertBefore = nullptr,
772 Instruction *FlagsSource = nullptr);
774 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
775 Value *LHS, Value *RHS, const Twine &Name,
776 BasicBlock *InsertAtEnd);
778 public:
779 // allocate space for exactly two operands
780 void *operator new(size_t s) {
781 return User::operator new(s, 2);
784 /// Construct a compare instruction, given the opcode, the predicate and
785 /// the two operands. Optionally (if InstBefore is specified) insert the
786 /// instruction into a BasicBlock right before the specified instruction.
787 /// The specified Instruction is allowed to be a dereferenced end iterator.
788 /// Create a CmpInst
789 static CmpInst *Create(OtherOps Op,
790 Predicate predicate, Value *S1,
791 Value *S2, const Twine &Name = "",
792 Instruction *InsertBefore = nullptr);
794 /// Construct a compare instruction, given the opcode, the predicate and the
795 /// two operands. Also automatically insert this instruction to the end of
796 /// the BasicBlock specified.
797 /// Create a CmpInst
798 static CmpInst *Create(OtherOps Op, Predicate predicate, Value *S1,
799 Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
801 /// Get the opcode casted to the right type
802 OtherOps getOpcode() const {
803 return static_cast<OtherOps>(Instruction::getOpcode());
806 /// Return the predicate for this instruction.
807 Predicate getPredicate() const {
808 return Predicate(getSubclassDataFromInstruction());
811 /// Set the predicate for this instruction to the specified value.
812 void setPredicate(Predicate P) { setInstructionSubclassData(P); }
814 static bool isFPPredicate(Predicate P) {
815 return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
818 static bool isIntPredicate(Predicate P) {
819 return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
822 static StringRef getPredicateName(Predicate P);
824 bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
825 bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
827 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
828 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
829 /// @returns the inverse predicate for the instruction's current predicate.
830 /// Return the inverse of the instruction's predicate.
831 Predicate getInversePredicate() const {
832 return getInversePredicate(getPredicate());
835 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
836 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
837 /// @returns the inverse predicate for predicate provided in \p pred.
838 /// Return the inverse of a given predicate
839 static Predicate getInversePredicate(Predicate pred);
841 /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
842 /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
843 /// @returns the predicate that would be the result of exchanging the two
844 /// operands of the CmpInst instruction without changing the result
845 /// produced.
846 /// Return the predicate as if the operands were swapped
847 Predicate getSwappedPredicate() const {
848 return getSwappedPredicate(getPredicate());
851 /// This is a static version that you can use without an instruction
852 /// available.
853 /// Return the predicate as if the operands were swapped.
854 static Predicate getSwappedPredicate(Predicate pred);
856 /// For predicate of kind "is X or equal to 0" returns the predicate "is X".
857 /// For predicate of kind "is X" returns the predicate "is X or equal to 0".
858 /// does not support other kind of predicates.
859 /// @returns the predicate that does not contains is equal to zero if
860 /// it had and vice versa.
861 /// Return the flipped strictness of predicate
862 Predicate getFlippedStrictnessPredicate() const {
863 return getFlippedStrictnessPredicate(getPredicate());
866 /// This is a static version that you can use without an instruction
867 /// available.
868 /// Return the flipped strictness of predicate
869 static Predicate getFlippedStrictnessPredicate(Predicate pred);
871 /// For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
872 /// Returns the non-strict version of strict comparisons.
873 Predicate getNonStrictPredicate() const {
874 return getNonStrictPredicate(getPredicate());
877 /// This is a static version that you can use without an instruction
878 /// available.
879 /// @returns the non-strict version of comparison provided in \p pred.
880 /// If \p pred is not a strict comparison predicate, returns \p pred.
881 /// Returns the non-strict version of strict comparisons.
882 static Predicate getNonStrictPredicate(Predicate pred);
884 /// Provide more efficient getOperand methods.
885 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
887 /// This is just a convenience that dispatches to the subclasses.
888 /// Swap the operands and adjust predicate accordingly to retain
889 /// the same comparison.
890 void swapOperands();
892 /// This is just a convenience that dispatches to the subclasses.
893 /// Determine if this CmpInst is commutative.
894 bool isCommutative() const;
896 /// This is just a convenience that dispatches to the subclasses.
897 /// Determine if this is an equals/not equals predicate.
898 bool isEquality() const;
900 /// @returns true if the comparison is signed, false otherwise.
901 /// Determine if this instruction is using a signed comparison.
902 bool isSigned() const {
903 return isSigned(getPredicate());
906 /// @returns true if the comparison is unsigned, false otherwise.
907 /// Determine if this instruction is using an unsigned comparison.
908 bool isUnsigned() const {
909 return isUnsigned(getPredicate());
912 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
913 /// @returns the signed version of the unsigned predicate pred.
914 /// return the signed version of a predicate
915 static Predicate getSignedPredicate(Predicate pred);
917 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
918 /// @returns the signed version of the predicate for this instruction (which
919 /// has to be an unsigned predicate).
920 /// return the signed version of a predicate
921 Predicate getSignedPredicate() {
922 return getSignedPredicate(getPredicate());
925 /// This is just a convenience.
926 /// Determine if this is true when both operands are the same.
927 bool isTrueWhenEqual() const {
928 return isTrueWhenEqual(getPredicate());
931 /// This is just a convenience.
932 /// Determine if this is false when both operands are the same.
933 bool isFalseWhenEqual() const {
934 return isFalseWhenEqual(getPredicate());
937 /// @returns true if the predicate is unsigned, false otherwise.
938 /// Determine if the predicate is an unsigned operation.
939 static bool isUnsigned(Predicate predicate);
941 /// @returns true if the predicate is signed, false otherwise.
942 /// Determine if the predicate is an signed operation.
943 static bool isSigned(Predicate predicate);
945 /// Determine if the predicate is an ordered operation.
946 static bool isOrdered(Predicate predicate);
948 /// Determine if the predicate is an unordered operation.
949 static bool isUnordered(Predicate predicate);
951 /// Determine if the predicate is true when comparing a value with itself.
952 static bool isTrueWhenEqual(Predicate predicate);
954 /// Determine if the predicate is false when comparing a value with itself.
955 static bool isFalseWhenEqual(Predicate predicate);
957 /// Determine if Pred1 implies Pred2 is true when two compares have matching
958 /// operands.
959 static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2);
961 /// Determine if Pred1 implies Pred2 is false when two compares have matching
962 /// operands.
963 static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2);
965 /// Methods for support type inquiry through isa, cast, and dyn_cast:
966 static bool classof(const Instruction *I) {
967 return I->getOpcode() == Instruction::ICmp ||
968 I->getOpcode() == Instruction::FCmp;
970 static bool classof(const Value *V) {
971 return isa<Instruction>(V) && classof(cast<Instruction>(V));
974 /// Create a result type for fcmp/icmp
975 static Type* makeCmpResultType(Type* opnd_type) {
976 if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
977 return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
978 vt->getElementCount());
980 return Type::getInt1Ty(opnd_type->getContext());
983 private:
984 // Shadow Value::setValueSubclassData with a private forwarding method so that
985 // subclasses cannot accidentally use it.
986 void setValueSubclassData(unsigned short D) {
987 Value::setValueSubclassData(D);
991 // FIXME: these are redundant if CmpInst < BinaryOperator
992 template <>
993 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
996 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
998 /// A lightweight accessor for an operand bundle meant to be passed
999 /// around by value.
1000 struct OperandBundleUse {
1001 ArrayRef<Use> Inputs;
1003 OperandBundleUse() = default;
1004 explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
1005 : Inputs(Inputs), Tag(Tag) {}
1007 /// Return true if the operand at index \p Idx in this operand bundle
1008 /// has the attribute A.
1009 bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const {
1010 if (isDeoptOperandBundle())
1011 if (A == Attribute::ReadOnly || A == Attribute::NoCapture)
1012 return Inputs[Idx]->getType()->isPointerTy();
1014 // Conservative answer: no operands have any attributes.
1015 return false;
1018 /// Return the tag of this operand bundle as a string.
1019 StringRef getTagName() const {
1020 return Tag->getKey();
1023 /// Return the tag of this operand bundle as an integer.
1025 /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
1026 /// and this function returns the unique integer getOrInsertBundleTag
1027 /// associated the tag of this operand bundle to.
1028 uint32_t getTagID() const {
1029 return Tag->getValue();
1032 /// Return true if this is a "deopt" operand bundle.
1033 bool isDeoptOperandBundle() const {
1034 return getTagID() == LLVMContext::OB_deopt;
1037 /// Return true if this is a "funclet" operand bundle.
1038 bool isFuncletOperandBundle() const {
1039 return getTagID() == LLVMContext::OB_funclet;
1042 private:
1043 /// Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1044 StringMapEntry<uint32_t> *Tag;
1047 /// A container for an operand bundle being viewed as a set of values
1048 /// rather than a set of uses.
1050 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1051 /// so it is possible to create and pass around "self-contained" instances of
1052 /// OperandBundleDef and ConstOperandBundleDef.
1053 template <typename InputTy> class OperandBundleDefT {
1054 std::string Tag;
1055 std::vector<InputTy> Inputs;
1057 public:
1058 explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1059 : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1060 explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs)
1061 : Tag(std::move(Tag)), Inputs(Inputs) {}
1063 explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1064 Tag = OBU.getTagName();
1065 Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
1068 ArrayRef<InputTy> inputs() const { return Inputs; }
1070 using input_iterator = typename std::vector<InputTy>::const_iterator;
1072 size_t input_size() const { return Inputs.size(); }
1073 input_iterator input_begin() const { return Inputs.begin(); }
1074 input_iterator input_end() const { return Inputs.end(); }
1076 StringRef getTag() const { return Tag; }
1079 using OperandBundleDef = OperandBundleDefT<Value *>;
1080 using ConstOperandBundleDef = OperandBundleDefT<const Value *>;
1082 //===----------------------------------------------------------------------===//
1083 // CallBase Class
1084 //===----------------------------------------------------------------------===//
1086 /// Base class for all callable instructions (InvokeInst and CallInst)
1087 /// Holds everything related to calling a function.
1089 /// All call-like instructions are required to use a common operand layout:
1090 /// - Zero or more arguments to the call,
1091 /// - Zero or more operand bundles with zero or more operand inputs each
1092 /// bundle,
1093 /// - Zero or more subclass controlled operands
1094 /// - The called function.
1096 /// This allows this base class to easily access the called function and the
1097 /// start of the arguments without knowing how many other operands a particular
1098 /// subclass requires. Note that accessing the end of the argument list isn't
1099 /// as cheap as most other operations on the base class.
1100 class CallBase : public Instruction {
1101 protected:
1102 /// The last operand is the called operand.
1103 static constexpr int CalledOperandOpEndIdx = -1;
1105 AttributeList Attrs; ///< parameter attributes for callable
1106 FunctionType *FTy;
1108 template <class... ArgsTy>
1109 CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args)
1110 : Instruction(std::forward<ArgsTy>(Args)...), Attrs(A), FTy(FT) {}
1112 using Instruction::Instruction;
1114 bool hasDescriptor() const { return Value::HasDescriptor; }
1116 unsigned getNumSubclassExtraOperands() const {
1117 switch (getOpcode()) {
1118 case Instruction::Call:
1119 return 0;
1120 case Instruction::Invoke:
1121 return 2;
1122 case Instruction::CallBr:
1123 return getNumSubclassExtraOperandsDynamic();
1125 llvm_unreachable("Invalid opcode!");
1128 /// Get the number of extra operands for instructions that don't have a fixed
1129 /// number of extra operands.
1130 unsigned getNumSubclassExtraOperandsDynamic() const;
1132 public:
1133 using Instruction::getContext;
1135 static bool classof(const Instruction *I) {
1136 return I->getOpcode() == Instruction::Call ||
1137 I->getOpcode() == Instruction::Invoke ||
1138 I->getOpcode() == Instruction::CallBr;
1140 static bool classof(const Value *V) {
1141 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1144 FunctionType *getFunctionType() const { return FTy; }
1146 void mutateFunctionType(FunctionType *FTy) {
1147 Value::mutateType(FTy->getReturnType());
1148 this->FTy = FTy;
1151 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1153 /// data_operands_begin/data_operands_end - Return iterators iterating over
1154 /// the call / invoke argument list and bundle operands. For invokes, this is
1155 /// the set of instruction operands except the invoke target and the two
1156 /// successor blocks; and for calls this is the set of instruction operands
1157 /// except the call target.
1158 User::op_iterator data_operands_begin() { return op_begin(); }
1159 User::const_op_iterator data_operands_begin() const {
1160 return const_cast<CallBase *>(this)->data_operands_begin();
1162 User::op_iterator data_operands_end() {
1163 // Walk from the end of the operands over the called operand and any
1164 // subclass operands.
1165 return op_end() - getNumSubclassExtraOperands() - 1;
1167 User::const_op_iterator data_operands_end() const {
1168 return const_cast<CallBase *>(this)->data_operands_end();
1170 iterator_range<User::op_iterator> data_ops() {
1171 return make_range(data_operands_begin(), data_operands_end());
1173 iterator_range<User::const_op_iterator> data_ops() const {
1174 return make_range(data_operands_begin(), data_operands_end());
1176 bool data_operands_empty() const {
1177 return data_operands_end() == data_operands_begin();
1179 unsigned data_operands_size() const {
1180 return std::distance(data_operands_begin(), data_operands_end());
1183 bool isDataOperand(const Use *U) const {
1184 assert(this == U->getUser() &&
1185 "Only valid to query with a use of this instruction!");
1186 return data_operands_begin() <= U && U < data_operands_end();
1188 bool isDataOperand(Value::const_user_iterator UI) const {
1189 return isDataOperand(&UI.getUse());
1192 /// Given a value use iterator, return the data operand corresponding to it.
1193 /// Iterator must actually correspond to a data operand.
1194 unsigned getDataOperandNo(Value::const_user_iterator UI) const {
1195 return getDataOperandNo(&UI.getUse());
1198 /// Given a use for a data operand, get the data operand number that
1199 /// corresponds to it.
1200 unsigned getDataOperandNo(const Use *U) const {
1201 assert(isDataOperand(U) && "Data operand # out of range!");
1202 return U - data_operands_begin();
1205 /// Return the iterator pointing to the beginning of the argument list.
1206 User::op_iterator arg_begin() { return op_begin(); }
1207 User::const_op_iterator arg_begin() const {
1208 return const_cast<CallBase *>(this)->arg_begin();
1211 /// Return the iterator pointing to the end of the argument list.
1212 User::op_iterator arg_end() {
1213 // From the end of the data operands, walk backwards past the bundle
1214 // operands.
1215 return data_operands_end() - getNumTotalBundleOperands();
1217 User::const_op_iterator arg_end() const {
1218 return const_cast<CallBase *>(this)->arg_end();
1221 /// Iteration adapter for range-for loops.
1222 iterator_range<User::op_iterator> args() {
1223 return make_range(arg_begin(), arg_end());
1225 iterator_range<User::const_op_iterator> args() const {
1226 return make_range(arg_begin(), arg_end());
1228 bool arg_empty() const { return arg_end() == arg_begin(); }
1229 unsigned arg_size() const { return arg_end() - arg_begin(); }
1231 // Legacy API names that duplicate the above and will be removed once users
1232 // are migrated.
1233 iterator_range<User::op_iterator> arg_operands() {
1234 return make_range(arg_begin(), arg_end());
1236 iterator_range<User::const_op_iterator> arg_operands() const {
1237 return make_range(arg_begin(), arg_end());
1239 unsigned getNumArgOperands() const { return arg_size(); }
1241 Value *getArgOperand(unsigned i) const {
1242 assert(i < getNumArgOperands() && "Out of bounds!");
1243 return getOperand(i);
1246 void setArgOperand(unsigned i, Value *v) {
1247 assert(i < getNumArgOperands() && "Out of bounds!");
1248 setOperand(i, v);
1251 /// Wrappers for getting the \c Use of a call argument.
1252 const Use &getArgOperandUse(unsigned i) const {
1253 assert(i < getNumArgOperands() && "Out of bounds!");
1254 return User::getOperandUse(i);
1256 Use &getArgOperandUse(unsigned i) {
1257 assert(i < getNumArgOperands() && "Out of bounds!");
1258 return User::getOperandUse(i);
1261 bool isArgOperand(const Use *U) const {
1262 assert(this == U->getUser() &&
1263 "Only valid to query with a use of this instruction!");
1264 return arg_begin() <= U && U < arg_end();
1266 bool isArgOperand(Value::const_user_iterator UI) const {
1267 return isArgOperand(&UI.getUse());
1270 /// Returns true if this CallSite passes the given Value* as an argument to
1271 /// the called function.
1272 bool hasArgument(const Value *V) const {
1273 return llvm::any_of(args(), [V](const Value *Arg) { return Arg == V; });
1276 Value *getCalledOperand() const { return Op<CalledOperandOpEndIdx>(); }
1278 // DEPRECATED: This routine will be removed in favor of `getCalledOperand` in
1279 // the near future.
1280 Value *getCalledValue() const { return getCalledOperand(); }
1282 const Use &getCalledOperandUse() const { return Op<CalledOperandOpEndIdx>(); }
1283 Use &getCalledOperandUse() { return Op<CalledOperandOpEndIdx>(); }
1285 /// Returns the function called, or null if this is an
1286 /// indirect function invocation.
1287 Function *getCalledFunction() const {
1288 return dyn_cast_or_null<Function>(getCalledOperand());
1291 /// Return true if the callsite is an indirect call.
1292 bool isIndirectCall() const;
1294 /// Determine whether the passed iterator points to the callee operand's Use.
1295 bool isCallee(Value::const_user_iterator UI) const {
1296 return isCallee(&UI.getUse());
1299 /// Determine whether this Use is the callee operand's Use.
1300 bool isCallee(const Use *U) const { return &getCalledOperandUse() == U; }
1302 /// Helper to get the caller (the parent function).
1303 Function *getCaller();
1304 const Function *getCaller() const {
1305 return const_cast<CallBase *>(this)->getCaller();
1308 /// Tests if this call site must be tail call optimized. Only a CallInst can
1309 /// be tail call optimized.
1310 bool isMustTailCall() const;
1312 /// Tests if this call site is marked as a tail call.
1313 bool isTailCall() const;
1315 /// Returns the intrinsic ID of the intrinsic called or
1316 /// Intrinsic::not_intrinsic if the called function is not an intrinsic, or if
1317 /// this is an indirect call.
1318 Intrinsic::ID getIntrinsicID() const;
1320 void setCalledOperand(Value *V) { Op<CalledOperandOpEndIdx>() = V; }
1322 /// Sets the function called, including updating the function type.
1323 void setCalledFunction(Function *Fn) {
1324 setCalledFunction(Fn->getFunctionType(), Fn);
1327 /// Sets the function called, including updating the function type.
1328 void setCalledFunction(FunctionCallee Fn) {
1329 setCalledFunction(Fn.getFunctionType(), Fn.getCallee());
1332 /// Sets the function called, including updating to the specified function
1333 /// type.
1334 void setCalledFunction(FunctionType *FTy, Value *Fn) {
1335 this->FTy = FTy;
1336 assert(FTy == cast<FunctionType>(
1337 cast<PointerType>(Fn->getType())->getElementType()));
1338 // This function doesn't mutate the return type, only the function
1339 // type. Seems broken, but I'm just gonna stick an assert in for now.
1340 assert(getType() == FTy->getReturnType());
1341 setCalledOperand(Fn);
1344 CallingConv::ID getCallingConv() const {
1345 return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1348 void setCallingConv(CallingConv::ID CC) {
1349 auto ID = static_cast<unsigned>(CC);
1350 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1351 setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1352 (ID << 2));
1355 /// Check if this call is an inline asm statement.
1356 bool isInlineAsm() const { return isa<InlineAsm>(getCalledOperand()); }
1358 /// \name Attribute API
1360 /// These methods access and modify attributes on this call (including
1361 /// looking through to the attributes on the called function when necessary).
1362 ///@{
1364 /// Return the parameter attributes for this call.
1366 AttributeList getAttributes() const { return Attrs; }
1368 /// Set the parameter attributes for this call.
1370 void setAttributes(AttributeList A) { Attrs = A; }
1372 /// Determine whether this call has the given attribute.
1373 bool hasFnAttr(Attribute::AttrKind Kind) const {
1374 assert(Kind != Attribute::NoBuiltin &&
1375 "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin");
1376 return hasFnAttrImpl(Kind);
1379 /// Determine whether this call has the given attribute.
1380 bool hasFnAttr(StringRef Kind) const { return hasFnAttrImpl(Kind); }
1382 /// adds the attribute to the list of attributes.
1383 void addAttribute(unsigned i, Attribute::AttrKind Kind) {
1384 AttributeList PAL = getAttributes();
1385 PAL = PAL.addAttribute(getContext(), i, Kind);
1386 setAttributes(PAL);
1389 /// adds the attribute to the list of attributes.
1390 void addAttribute(unsigned i, Attribute Attr) {
1391 AttributeList PAL = getAttributes();
1392 PAL = PAL.addAttribute(getContext(), i, Attr);
1393 setAttributes(PAL);
1396 /// Adds the attribute to the indicated argument
1397 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1398 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1399 AttributeList PAL = getAttributes();
1400 PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
1401 setAttributes(PAL);
1404 /// Adds the attribute to the indicated argument
1405 void addParamAttr(unsigned ArgNo, Attribute Attr) {
1406 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1407 AttributeList PAL = getAttributes();
1408 PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
1409 setAttributes(PAL);
1412 /// removes the attribute from the list of attributes.
1413 void removeAttribute(unsigned i, Attribute::AttrKind Kind) {
1414 AttributeList PAL = getAttributes();
1415 PAL = PAL.removeAttribute(getContext(), i, Kind);
1416 setAttributes(PAL);
1419 /// removes the attribute from the list of attributes.
1420 void removeAttribute(unsigned i, StringRef Kind) {
1421 AttributeList PAL = getAttributes();
1422 PAL = PAL.removeAttribute(getContext(), i, Kind);
1423 setAttributes(PAL);
1426 /// Removes the attribute from the given argument
1427 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1428 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1429 AttributeList PAL = getAttributes();
1430 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1431 setAttributes(PAL);
1434 /// Removes the attribute from the given argument
1435 void removeParamAttr(unsigned ArgNo, StringRef Kind) {
1436 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1437 AttributeList PAL = getAttributes();
1438 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1439 setAttributes(PAL);
1442 /// adds the dereferenceable attribute to the list of attributes.
1443 void addDereferenceableAttr(unsigned i, uint64_t Bytes) {
1444 AttributeList PAL = getAttributes();
1445 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
1446 setAttributes(PAL);
1449 /// adds the dereferenceable_or_null attribute to the list of
1450 /// attributes.
1451 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
1452 AttributeList PAL = getAttributes();
1453 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
1454 setAttributes(PAL);
1457 /// Determine whether the return value has the given attribute.
1458 bool hasRetAttr(Attribute::AttrKind Kind) const;
1460 /// Determine whether the argument or parameter has the given attribute.
1461 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1463 /// Get the attribute of a given kind at a position.
1464 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
1465 return getAttributes().getAttribute(i, Kind);
1468 /// Get the attribute of a given kind at a position.
1469 Attribute getAttribute(unsigned i, StringRef Kind) const {
1470 return getAttributes().getAttribute(i, Kind);
1473 /// Get the attribute of a given kind from a given arg
1474 Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1475 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1476 return getAttributes().getParamAttr(ArgNo, Kind);
1479 /// Get the attribute of a given kind from a given arg
1480 Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1481 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1482 return getAttributes().getParamAttr(ArgNo, Kind);
1485 /// Return true if the data operand at index \p i has the attribute \p
1486 /// A.
1488 /// Data operands include call arguments and values used in operand bundles,
1489 /// but does not include the callee operand. This routine dispatches to the
1490 /// underlying AttributeList or the OperandBundleUser as appropriate.
1492 /// The index \p i is interpreted as
1494 /// \p i == Attribute::ReturnIndex -> the return value
1495 /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
1496 /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1497 /// (\p i - 1) in the operand list.
1498 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const {
1499 // Note that we have to add one because `i` isn't zero-indexed.
1500 assert(i < (getNumArgOperands() + getNumTotalBundleOperands() + 1) &&
1501 "Data operand index out of bounds!");
1503 // The attribute A can either be directly specified, if the operand in
1504 // question is a call argument; or be indirectly implied by the kind of its
1505 // containing operand bundle, if the operand is a bundle operand.
1507 if (i == AttributeList::ReturnIndex)
1508 return hasRetAttr(Kind);
1510 // FIXME: Avoid these i - 1 calculations and update the API to use
1511 // zero-based indices.
1512 if (i < (getNumArgOperands() + 1))
1513 return paramHasAttr(i - 1, Kind);
1515 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
1516 "Must be either a call argument or an operand bundle!");
1517 return bundleOperandHasAttr(i - 1, Kind);
1520 /// Determine whether this data operand is not captured.
1521 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1522 // better indicate that this may return a conservative answer.
1523 bool doesNotCapture(unsigned OpNo) const {
1524 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::NoCapture);
1527 /// Determine whether this argument is passed by value.
1528 bool isByValArgument(unsigned ArgNo) const {
1529 return paramHasAttr(ArgNo, Attribute::ByVal);
1532 /// Determine whether this argument is passed in an alloca.
1533 bool isInAllocaArgument(unsigned ArgNo) const {
1534 return paramHasAttr(ArgNo, Attribute::InAlloca);
1537 /// Determine whether this argument is passed by value or in an alloca.
1538 bool isByValOrInAllocaArgument(unsigned ArgNo) const {
1539 return paramHasAttr(ArgNo, Attribute::ByVal) ||
1540 paramHasAttr(ArgNo, Attribute::InAlloca);
1543 /// Determine if there are is an inalloca argument. Only the last argument can
1544 /// have the inalloca attribute.
1545 bool hasInAllocaArgument() const {
1546 return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca);
1549 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1550 // better indicate that this may return a conservative answer.
1551 bool doesNotAccessMemory(unsigned OpNo) const {
1552 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1555 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1556 // better indicate that this may return a conservative answer.
1557 bool onlyReadsMemory(unsigned OpNo) const {
1558 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadOnly) ||
1559 dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1562 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1563 // better indicate that this may return a conservative answer.
1564 bool doesNotReadMemory(unsigned OpNo) const {
1565 return dataOperandHasImpliedAttr(OpNo + 1, Attribute::WriteOnly) ||
1566 dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1569 /// Extract the alignment of the return value.
1570 unsigned getRetAlignment() const {
1571 if (const auto MA = Attrs.getRetAlignment())
1572 return MA->value();
1573 return 0;
1576 /// Extract the alignment for a call or parameter (0=unknown).
1577 unsigned getParamAlignment(unsigned ArgNo) const {
1578 if (const auto MA = Attrs.getParamAlignment(ArgNo))
1579 return MA->value();
1580 return 0;
1583 /// Extract the byval type for a call or parameter.
1584 Type *getParamByValType(unsigned ArgNo) const {
1585 Type *Ty = Attrs.getParamByValType(ArgNo);
1586 return Ty ? Ty : getArgOperand(ArgNo)->getType()->getPointerElementType();
1589 /// Extract the number of dereferenceable bytes for a call or
1590 /// parameter (0=unknown).
1591 uint64_t getDereferenceableBytes(unsigned i) const {
1592 return Attrs.getDereferenceableBytes(i);
1595 /// Extract the number of dereferenceable_or_null bytes for a call or
1596 /// parameter (0=unknown).
1597 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1598 return Attrs.getDereferenceableOrNullBytes(i);
1601 /// Return true if the return value is known to be not null.
1602 /// This may be because it has the nonnull attribute, or because at least
1603 /// one byte is dereferenceable and the pointer is in addrspace(0).
1604 bool isReturnNonNull() const;
1606 /// Determine if the return value is marked with NoAlias attribute.
1607 bool returnDoesNotAlias() const {
1608 return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1611 /// If one of the arguments has the 'returned' attribute, returns its
1612 /// operand value. Otherwise, return nullptr.
1613 Value *getReturnedArgOperand() const;
1615 /// Return true if the call should not be treated as a call to a
1616 /// builtin.
1617 bool isNoBuiltin() const {
1618 return hasFnAttrImpl(Attribute::NoBuiltin) &&
1619 !hasFnAttrImpl(Attribute::Builtin);
1622 /// Determine if the call requires strict floating point semantics.
1623 bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1625 /// Return true if the call should not be inlined.
1626 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1627 void setIsNoInline() {
1628 addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1630 /// Determine if the call does not access memory.
1631 bool doesNotAccessMemory() const { return hasFnAttr(Attribute::ReadNone); }
1632 void setDoesNotAccessMemory() {
1633 addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1636 /// Determine if the call does not access or only reads memory.
1637 bool onlyReadsMemory() const {
1638 return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1640 void setOnlyReadsMemory() {
1641 addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1644 /// Determine if the call does not access or only writes memory.
1645 bool doesNotReadMemory() const {
1646 return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1648 void setDoesNotReadMemory() {
1649 addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1652 /// Determine if the call can access memmory only using pointers based
1653 /// on its arguments.
1654 bool onlyAccessesArgMemory() const {
1655 return hasFnAttr(Attribute::ArgMemOnly);
1657 void setOnlyAccessesArgMemory() {
1658 addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1661 /// Determine if the function may only access memory that is
1662 /// inaccessible from the IR.
1663 bool onlyAccessesInaccessibleMemory() const {
1664 return hasFnAttr(Attribute::InaccessibleMemOnly);
1666 void setOnlyAccessesInaccessibleMemory() {
1667 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOnly);
1670 /// Determine if the function may only access memory that is
1671 /// either inaccessible from the IR or pointed to by its arguments.
1672 bool onlyAccessesInaccessibleMemOrArgMem() const {
1673 return hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
1675 void setOnlyAccessesInaccessibleMemOrArgMem() {
1676 addAttribute(AttributeList::FunctionIndex,
1677 Attribute::InaccessibleMemOrArgMemOnly);
1679 /// Determine if the call cannot return.
1680 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1681 void setDoesNotReturn() {
1682 addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1685 /// Determine if the call should not perform indirect branch tracking.
1686 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
1688 /// Determine if the call cannot unwind.
1689 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1690 void setDoesNotThrow() {
1691 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1694 /// Determine if the invoke cannot be duplicated.
1695 bool cannotDuplicate() const { return hasFnAttr(Attribute::NoDuplicate); }
1696 void setCannotDuplicate() {
1697 addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1700 /// Determine if the invoke is convergent
1701 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1702 void setConvergent() {
1703 addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1705 void setNotConvergent() {
1706 removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1709 /// Determine if the call returns a structure through first
1710 /// pointer argument.
1711 bool hasStructRetAttr() const {
1712 if (getNumArgOperands() == 0)
1713 return false;
1715 // Be friendly and also check the callee.
1716 return paramHasAttr(0, Attribute::StructRet);
1719 /// Determine if any call argument is an aggregate passed by value.
1720 bool hasByValArgument() const {
1721 return Attrs.hasAttrSomewhere(Attribute::ByVal);
1724 ///@{
1725 // End of attribute API.
1727 /// \name Operand Bundle API
1729 /// This group of methods provides the API to access and manipulate operand
1730 /// bundles on this call.
1731 /// @{
1733 /// Return the number of operand bundles associated with this User.
1734 unsigned getNumOperandBundles() const {
1735 return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1738 /// Return true if this User has any operand bundles.
1739 bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1741 /// Return the index of the first bundle operand in the Use array.
1742 unsigned getBundleOperandsStartIndex() const {
1743 assert(hasOperandBundles() && "Don't call otherwise!");
1744 return bundle_op_info_begin()->Begin;
1747 /// Return the index of the last bundle operand in the Use array.
1748 unsigned getBundleOperandsEndIndex() const {
1749 assert(hasOperandBundles() && "Don't call otherwise!");
1750 return bundle_op_info_end()[-1].End;
1753 /// Return true if the operand at index \p Idx is a bundle operand.
1754 bool isBundleOperand(unsigned Idx) const {
1755 return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() &&
1756 Idx < getBundleOperandsEndIndex();
1759 /// Returns true if the use is a bundle operand.
1760 bool isBundleOperand(const Use *U) const {
1761 assert(this == U->getUser() &&
1762 "Only valid to query with a use of this instruction!");
1763 return hasOperandBundles() && isBundleOperand(U - op_begin());
1765 bool isBundleOperand(Value::const_user_iterator UI) const {
1766 return isBundleOperand(&UI.getUse());
1769 /// Return the total number operands (not operand bundles) used by
1770 /// every operand bundle in this OperandBundleUser.
1771 unsigned getNumTotalBundleOperands() const {
1772 if (!hasOperandBundles())
1773 return 0;
1775 unsigned Begin = getBundleOperandsStartIndex();
1776 unsigned End = getBundleOperandsEndIndex();
1778 assert(Begin <= End && "Should be!");
1779 return End - Begin;
1782 /// Return the operand bundle at a specific index.
1783 OperandBundleUse getOperandBundleAt(unsigned Index) const {
1784 assert(Index < getNumOperandBundles() && "Index out of bounds!");
1785 return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1788 /// Return the number of operand bundles with the tag Name attached to
1789 /// this instruction.
1790 unsigned countOperandBundlesOfType(StringRef Name) const {
1791 unsigned Count = 0;
1792 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1793 if (getOperandBundleAt(i).getTagName() == Name)
1794 Count++;
1796 return Count;
1799 /// Return the number of operand bundles with the tag ID attached to
1800 /// this instruction.
1801 unsigned countOperandBundlesOfType(uint32_t ID) const {
1802 unsigned Count = 0;
1803 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1804 if (getOperandBundleAt(i).getTagID() == ID)
1805 Count++;
1807 return Count;
1810 /// Return an operand bundle by name, if present.
1812 /// It is an error to call this for operand bundle types that may have
1813 /// multiple instances of them on the same instruction.
1814 Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1815 assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
1817 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1818 OperandBundleUse U = getOperandBundleAt(i);
1819 if (U.getTagName() == Name)
1820 return U;
1823 return None;
1826 /// Return an operand bundle by tag ID, if present.
1828 /// It is an error to call this for operand bundle types that may have
1829 /// multiple instances of them on the same instruction.
1830 Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1831 assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
1833 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1834 OperandBundleUse U = getOperandBundleAt(i);
1835 if (U.getTagID() == ID)
1836 return U;
1839 return None;
1842 /// Return the list of operand bundles attached to this instruction as
1843 /// a vector of OperandBundleDefs.
1845 /// This function copies the OperandBundeUse instances associated with this
1846 /// OperandBundleUser to a vector of OperandBundleDefs. Note:
1847 /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1848 /// representations of operand bundles (see documentation above).
1849 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
1850 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1851 Defs.emplace_back(getOperandBundleAt(i));
1854 /// Return the operand bundle for the operand at index OpIdx.
1856 /// It is an error to call this with an OpIdx that does not correspond to an
1857 /// bundle operand.
1858 OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1859 return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
1862 /// Return true if this operand bundle user has operand bundles that
1863 /// may read from the heap.
1864 bool hasReadingOperandBundles() const {
1865 // Implementation note: this is a conservative implementation of operand
1866 // bundle semantics, where *any* operand bundle forces a callsite to be at
1867 // least readonly.
1868 return hasOperandBundles();
1871 /// Return true if this operand bundle user has operand bundles that
1872 /// may write to the heap.
1873 bool hasClobberingOperandBundles() const {
1874 for (auto &BOI : bundle_op_infos()) {
1875 if (BOI.Tag->second == LLVMContext::OB_deopt ||
1876 BOI.Tag->second == LLVMContext::OB_funclet)
1877 continue;
1879 // This instruction has an operand bundle that is not known to us.
1880 // Assume the worst.
1881 return true;
1884 return false;
1887 /// Return true if the bundle operand at index \p OpIdx has the
1888 /// attribute \p A.
1889 bool bundleOperandHasAttr(unsigned OpIdx, Attribute::AttrKind A) const {
1890 auto &BOI = getBundleOpInfoForOperand(OpIdx);
1891 auto OBU = operandBundleFromBundleOpInfo(BOI);
1892 return OBU.operandHasAttr(OpIdx - BOI.Begin, A);
1895 /// Return true if \p Other has the same sequence of operand bundle
1896 /// tags with the same number of operands on each one of them as this
1897 /// OperandBundleUser.
1898 bool hasIdenticalOperandBundleSchema(const CallBase &Other) const {
1899 if (getNumOperandBundles() != Other.getNumOperandBundles())
1900 return false;
1902 return std::equal(bundle_op_info_begin(), bundle_op_info_end(),
1903 Other.bundle_op_info_begin());
1906 /// Return true if this operand bundle user contains operand bundles
1907 /// with tags other than those specified in \p IDs.
1908 bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const {
1909 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1910 uint32_t ID = getOperandBundleAt(i).getTagID();
1911 if (!is_contained(IDs, ID))
1912 return true;
1914 return false;
1917 /// Is the function attribute S disallowed by some operand bundle on
1918 /// this operand bundle user?
1919 bool isFnAttrDisallowedByOpBundle(StringRef S) const {
1920 // Operand bundles only possibly disallow readnone, readonly and argmenonly
1921 // attributes. All String attributes are fine.
1922 return false;
1925 /// Is the function attribute A disallowed by some operand bundle on
1926 /// this operand bundle user?
1927 bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
1928 switch (A) {
1929 default:
1930 return false;
1932 case Attribute::InaccessibleMemOrArgMemOnly:
1933 return hasReadingOperandBundles();
1935 case Attribute::InaccessibleMemOnly:
1936 return hasReadingOperandBundles();
1938 case Attribute::ArgMemOnly:
1939 return hasReadingOperandBundles();
1941 case Attribute::ReadNone:
1942 return hasReadingOperandBundles();
1944 case Attribute::ReadOnly:
1945 return hasClobberingOperandBundles();
1948 llvm_unreachable("switch has a default case!");
1951 /// Used to keep track of an operand bundle. See the main comment on
1952 /// OperandBundleUser above.
1953 struct BundleOpInfo {
1954 /// The operand bundle tag, interned by
1955 /// LLVMContextImpl::getOrInsertBundleTag.
1956 StringMapEntry<uint32_t> *Tag;
1958 /// The index in the Use& vector where operands for this operand
1959 /// bundle starts.
1960 uint32_t Begin;
1962 /// The index in the Use& vector where operands for this operand
1963 /// bundle ends.
1964 uint32_t End;
1966 bool operator==(const BundleOpInfo &Other) const {
1967 return Tag == Other.Tag && Begin == Other.Begin && End == Other.End;
1971 /// Simple helper function to map a BundleOpInfo to an
1972 /// OperandBundleUse.
1973 OperandBundleUse
1974 operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
1975 auto begin = op_begin();
1976 ArrayRef<Use> Inputs(begin + BOI.Begin, begin + BOI.End);
1977 return OperandBundleUse(BOI.Tag, Inputs);
1980 using bundle_op_iterator = BundleOpInfo *;
1981 using const_bundle_op_iterator = const BundleOpInfo *;
1983 /// Return the start of the list of BundleOpInfo instances associated
1984 /// with this OperandBundleUser.
1986 /// OperandBundleUser uses the descriptor area co-allocated with the host User
1987 /// to store some meta information about which operands are "normal" operands,
1988 /// and which ones belong to some operand bundle.
1990 /// The layout of an operand bundle user is
1992 /// +-----------uint32_t End-------------------------------------+
1993 /// | |
1994 /// | +--------uint32_t Begin--------------------+ |
1995 /// | | | |
1996 /// ^ ^ v v
1997 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1998 /// | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
1999 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
2000 /// v v ^ ^
2001 /// | | | |
2002 /// | +--------uint32_t Begin------------+ |
2003 /// | |
2004 /// +-----------uint32_t End-----------------------------+
2007 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use
2008 /// list. These descriptions are installed and managed by this class, and
2009 /// they're all instances of OperandBundleUser<T>::BundleOpInfo.
2011 /// DU is an additional descriptor installed by User's 'operator new' to keep
2012 /// track of the 'BOI0 ... BOIN' co-allocation. OperandBundleUser does not
2013 /// access or modify DU in any way, it's an implementation detail private to
2014 /// User.
2016 /// The regular Use& vector for the User starts at U0. The operand bundle
2017 /// uses are part of the Use& vector, just like normal uses. In the diagram
2018 /// above, the operand bundle uses start at BOI0_U0. Each instance of
2019 /// BundleOpInfo has information about a contiguous set of uses constituting
2020 /// an operand bundle, and the total set of operand bundle uses themselves
2021 /// form a contiguous set of uses (i.e. there are no gaps between uses
2022 /// corresponding to individual operand bundles).
2024 /// This class does not know the location of the set of operand bundle uses
2025 /// within the use list -- that is decided by the User using this class via
2026 /// the BeginIdx argument in populateBundleOperandInfos.
2028 /// Currently operand bundle users with hung-off operands are not supported.
2029 bundle_op_iterator bundle_op_info_begin() {
2030 if (!hasDescriptor())
2031 return nullptr;
2033 uint8_t *BytesBegin = getDescriptor().begin();
2034 return reinterpret_cast<bundle_op_iterator>(BytesBegin);
2037 /// Return the start of the list of BundleOpInfo instances associated
2038 /// with this OperandBundleUser.
2039 const_bundle_op_iterator bundle_op_info_begin() const {
2040 auto *NonConstThis = const_cast<CallBase *>(this);
2041 return NonConstThis->bundle_op_info_begin();
2044 /// Return the end of the list of BundleOpInfo instances associated
2045 /// with this OperandBundleUser.
2046 bundle_op_iterator bundle_op_info_end() {
2047 if (!hasDescriptor())
2048 return nullptr;
2050 uint8_t *BytesEnd = getDescriptor().end();
2051 return reinterpret_cast<bundle_op_iterator>(BytesEnd);
2054 /// Return the end of the list of BundleOpInfo instances associated
2055 /// with this OperandBundleUser.
2056 const_bundle_op_iterator bundle_op_info_end() const {
2057 auto *NonConstThis = const_cast<CallBase *>(this);
2058 return NonConstThis->bundle_op_info_end();
2061 /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
2062 iterator_range<bundle_op_iterator> bundle_op_infos() {
2063 return make_range(bundle_op_info_begin(), bundle_op_info_end());
2066 /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
2067 iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
2068 return make_range(bundle_op_info_begin(), bundle_op_info_end());
2071 /// Populate the BundleOpInfo instances and the Use& vector from \p
2072 /// Bundles. Return the op_iterator pointing to the Use& one past the last
2073 /// last bundle operand use.
2075 /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
2076 /// instance allocated in this User's descriptor.
2077 op_iterator populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
2078 const unsigned BeginIndex);
2080 /// Return the BundleOpInfo for the operand at index OpIdx.
2082 /// It is an error to call this with an OpIdx that does not correspond to an
2083 /// bundle operand.
2084 const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
2085 for (auto &BOI : bundle_op_infos())
2086 if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
2087 return BOI;
2089 llvm_unreachable("Did not find operand bundle for operand!");
2092 protected:
2093 /// Return the total number of values used in \p Bundles.
2094 static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
2095 unsigned Total = 0;
2096 for (auto &B : Bundles)
2097 Total += B.input_size();
2098 return Total;
2101 /// @}
2102 // End of operand bundle API.
2104 private:
2105 bool hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
2106 bool hasFnAttrOnCalledFunction(StringRef Kind) const;
2108 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
2109 if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
2110 return true;
2112 // Operand bundles override attributes on the called function, but don't
2113 // override attributes directly present on the call instruction.
2114 if (isFnAttrDisallowedByOpBundle(Kind))
2115 return false;
2117 return hasFnAttrOnCalledFunction(Kind);
2121 template <>
2122 struct OperandTraits<CallBase> : public VariadicOperandTraits<CallBase, 1> {};
2124 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallBase, Value)
2126 //===----------------------------------------------------------------------===//
2127 // FuncletPadInst Class
2128 //===----------------------------------------------------------------------===//
2129 class FuncletPadInst : public Instruction {
2130 private:
2131 FuncletPadInst(const FuncletPadInst &CPI);
2133 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2134 ArrayRef<Value *> Args, unsigned Values,
2135 const Twine &NameStr, Instruction *InsertBefore);
2136 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2137 ArrayRef<Value *> Args, unsigned Values,
2138 const Twine &NameStr, BasicBlock *InsertAtEnd);
2140 void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
2142 protected:
2143 // Note: Instruction needs to be a friend here to call cloneImpl.
2144 friend class Instruction;
2145 friend class CatchPadInst;
2146 friend class CleanupPadInst;
2148 FuncletPadInst *cloneImpl() const;
2150 public:
2151 /// Provide fast operand accessors
2152 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2154 /// getNumArgOperands - Return the number of funcletpad arguments.
2156 unsigned getNumArgOperands() const { return getNumOperands() - 1; }
2158 /// Convenience accessors
2160 /// Return the outer EH-pad this funclet is nested within.
2162 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
2163 /// is a CatchPadInst.
2164 Value *getParentPad() const { return Op<-1>(); }
2165 void setParentPad(Value *ParentPad) {
2166 assert(ParentPad);
2167 Op<-1>() = ParentPad;
2170 /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
2172 Value *getArgOperand(unsigned i) const { return getOperand(i); }
2173 void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
2175 /// arg_operands - iteration adapter for range-for loops.
2176 op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
2178 /// arg_operands - iteration adapter for range-for loops.
2179 const_op_range arg_operands() const {
2180 return const_op_range(op_begin(), op_end() - 1);
2183 // Methods for support type inquiry through isa, cast, and dyn_cast:
2184 static bool classof(const Instruction *I) { return I->isFuncletPad(); }
2185 static bool classof(const Value *V) {
2186 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2190 template <>
2191 struct OperandTraits<FuncletPadInst>
2192 : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {};
2194 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)
2196 } // end namespace llvm
2198 #endif // LLVM_IR_INSTRTYPES_H