1 //===-- llvm/InstrTypes.h - Important Instruction subclasses ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines various meta classes of instructions that exist in the VM
11 // representation. Specific concrete subclasses of these may be found in the
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_IR_INSTRTYPES_H
17 #define LLVM_IR_INSTRTYPES_H
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/IR/Attributes.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/OperandTraits.h"
31 //===----------------------------------------------------------------------===//
32 // TerminatorInst Class
33 //===----------------------------------------------------------------------===//
35 /// Subclasses of this class are all able to terminate a basic
36 /// block. Thus, these are all the flow control type of operations.
38 class TerminatorInst : public Instruction {
40 TerminatorInst(Type *Ty, Instruction::TermOps iType,
41 Use *Ops, unsigned NumOps,
42 Instruction *InsertBefore = nullptr)
43 : Instruction(Ty, iType, Ops, NumOps, InsertBefore) {}
45 TerminatorInst(Type *Ty, Instruction::TermOps iType,
46 Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd)
47 : Instruction(Ty, iType, Ops, NumOps, InsertAtEnd) {}
49 // Out of line virtual method, so the vtable, etc has a home.
50 ~TerminatorInst() override;
52 /// Virtual methods - Terminators should overload these and provide inline
53 /// overrides of non-V methods.
54 virtual BasicBlock *getSuccessorV(unsigned idx) const = 0;
55 virtual unsigned getNumSuccessorsV() const = 0;
56 virtual void setSuccessorV(unsigned idx, BasicBlock *B) = 0;
59 /// Return the number of successors that this terminator has.
60 unsigned getNumSuccessors() const {
61 return getNumSuccessorsV();
64 /// Return the specified successor.
65 BasicBlock *getSuccessor(unsigned idx) const {
66 return getSuccessorV(idx);
69 /// Update the specified successor to point at the provided block.
70 void setSuccessor(unsigned idx, BasicBlock *B) {
71 setSuccessorV(idx, B);
74 // Methods for support type inquiry through isa, cast, and dyn_cast:
75 static inline bool classof(const Instruction *I) {
76 return I->isTerminator();
78 static inline bool classof(const Value *V) {
79 return isa<Instruction>(V) && classof(cast<Instruction>(V));
82 // \brief Returns true if this terminator relates to exception handling.
83 bool isExceptional() const {
84 switch (getOpcode()) {
85 case Instruction::CatchPad:
86 case Instruction::CatchEndPad:
87 case Instruction::CatchRet:
88 case Instruction::CleanupEndPad:
89 case Instruction::CleanupRet:
90 case Instruction::Invoke:
91 case Instruction::Resume:
92 case Instruction::TerminatePad:
99 //===--------------------------------------------------------------------===//
100 // succ_iterator definition
101 //===--------------------------------------------------------------------===//
103 template <class Term, class BB> // Successor Iterator
104 class SuccIterator : public std::iterator<std::random_access_iterator_tag, BB,
106 typedef std::iterator<std::random_access_iterator_tag, BB, int, BB *, BB *>
110 typedef typename super::pointer pointer;
111 typedef typename super::reference reference;
116 typedef SuccIterator<Term, BB> Self;
118 inline bool index_is_valid(unsigned idx) {
119 return idx < TermInst->getNumSuccessors();
122 /// \brief Proxy object to allow write access in operator[]
123 class SuccessorProxy {
127 explicit SuccessorProxy(const Self &it) : it(it) {}
129 SuccessorProxy(const SuccessorProxy &) = default;
131 SuccessorProxy &operator=(SuccessorProxy r) {
132 *this = reference(r);
136 SuccessorProxy &operator=(reference r) {
137 it.TermInst->setSuccessor(it.idx, r);
141 operator reference() const { return *it; }
146 explicit inline SuccIterator(Term T) : TermInst(T), idx(0) {}
148 inline SuccIterator(Term T, bool) : TermInst(T) {
150 idx = TermInst->getNumSuccessors();
152 // Term == NULL happens, if a basic block is not fully constructed and
153 // consequently getTerminator() returns NULL. In this case we construct
154 // a SuccIterator which describes a basic block that has zero
156 // Defining SuccIterator for incomplete and malformed CFGs is especially
157 // useful for debugging.
161 /// This is used to interface between code that wants to
162 /// operate on terminator instructions directly.
163 unsigned getSuccessorIndex() const { return idx; }
165 inline bool operator==(const Self &x) const { return idx == x.idx; }
166 inline bool operator!=(const Self &x) const { return !operator==(x); }
168 inline reference operator*() const { return TermInst->getSuccessor(idx); }
169 inline pointer operator->() const { return operator*(); }
171 inline Self &operator++() {
176 inline Self operator++(int) { // Postincrement
182 inline Self &operator--() {
186 inline Self operator--(int) { // Postdecrement
192 inline bool operator<(const Self &x) const {
193 assert(TermInst == x.TermInst &&
194 "Cannot compare iterators of different blocks!");
198 inline bool operator<=(const Self &x) const {
199 assert(TermInst == x.TermInst &&
200 "Cannot compare iterators of different blocks!");
203 inline bool operator>=(const Self &x) const {
204 assert(TermInst == x.TermInst &&
205 "Cannot compare iterators of different blocks!");
209 inline bool operator>(const Self &x) const {
210 assert(TermInst == x.TermInst &&
211 "Cannot compare iterators of different blocks!");
215 inline Self &operator+=(int Right) {
216 unsigned new_idx = idx + Right;
217 assert(index_is_valid(new_idx) && "Iterator index out of bound");
222 inline Self operator+(int Right) const {
228 inline Self &operator-=(int Right) { return operator+=(-Right); }
230 inline Self operator-(int Right) const { return operator+(-Right); }
232 inline int operator-(const Self &x) const {
233 assert(TermInst == x.TermInst &&
234 "Cannot work on iterators of different blocks!");
235 int distance = idx - x.idx;
239 inline SuccessorProxy operator[](int offset) {
242 return SuccessorProxy(tmp);
245 /// Get the source BB of this iterator.
246 inline BB *getSource() {
247 assert(TermInst && "Source not available, if basic block was malformed");
248 return TermInst->getParent();
252 typedef SuccIterator<TerminatorInst *, BasicBlock> succ_iterator;
253 typedef SuccIterator<const TerminatorInst *, const BasicBlock>
255 typedef llvm::iterator_range<succ_iterator> succ_range;
256 typedef llvm::iterator_range<succ_const_iterator> succ_const_range;
259 inline succ_iterator succ_begin() { return succ_iterator(this); }
260 inline succ_const_iterator succ_begin() const {
261 return succ_const_iterator(this);
263 inline succ_iterator succ_end() { return succ_iterator(this, true); }
264 inline succ_const_iterator succ_end() const {
265 return succ_const_iterator(this, true);
269 inline succ_range successors() {
270 return succ_range(succ_begin(), succ_end());
272 inline succ_const_range successors() const {
273 return succ_const_range(succ_begin(), succ_end());
277 //===----------------------------------------------------------------------===//
278 // UnaryInstruction Class
279 //===----------------------------------------------------------------------===//
281 class UnaryInstruction : public Instruction {
282 void *operator new(size_t, unsigned) = delete;
285 UnaryInstruction(Type *Ty, unsigned iType, Value *V,
286 Instruction *IB = nullptr)
287 : Instruction(Ty, iType, &Op<0>(), 1, IB) {
290 UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
291 : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
296 // allocate space for exactly one operand
297 void *operator new(size_t s) {
298 return User::operator new(s, 1);
301 // Out of line virtual method, so the vtable, etc has a home.
302 ~UnaryInstruction() override;
304 /// Transparently provide more efficient getOperand methods.
305 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
307 // Methods for support type inquiry through isa, cast, and dyn_cast:
308 static inline bool classof(const Instruction *I) {
309 return I->getOpcode() == Instruction::Alloca ||
310 I->getOpcode() == Instruction::Load ||
311 I->getOpcode() == Instruction::VAArg ||
312 I->getOpcode() == Instruction::ExtractValue ||
313 (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
315 static inline bool classof(const Value *V) {
316 return isa<Instruction>(V) && classof(cast<Instruction>(V));
321 struct OperandTraits<UnaryInstruction> :
322 public FixedNumOperandTraits<UnaryInstruction, 1> {
325 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
327 //===----------------------------------------------------------------------===//
328 // BinaryOperator Class
329 //===----------------------------------------------------------------------===//
331 class BinaryOperator : public Instruction {
332 void *operator new(size_t, unsigned) = delete;
335 void init(BinaryOps iType);
336 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
337 const Twine &Name, Instruction *InsertBefore);
338 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
339 const Twine &Name, BasicBlock *InsertAtEnd);
341 // Note: Instruction needs to be a friend here to call cloneImpl.
342 friend class Instruction;
343 BinaryOperator *cloneImpl() const;
346 // allocate space for exactly two operands
347 void *operator new(size_t s) {
348 return User::operator new(s, 2);
351 /// Transparently provide more efficient getOperand methods.
352 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
354 /// Construct a binary instruction, given the opcode and the two
355 /// operands. Optionally (if InstBefore is specified) insert the instruction
356 /// into a BasicBlock right before the specified instruction. The specified
357 /// Instruction is allowed to be a dereferenced end iterator.
359 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
360 const Twine &Name = Twine(),
361 Instruction *InsertBefore = nullptr);
363 /// Construct a binary instruction, given the opcode and the two
364 /// operands. Also automatically insert this instruction to the end of the
365 /// BasicBlock specified.
367 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
368 const Twine &Name, BasicBlock *InsertAtEnd);
370 /// These methods just forward to Create, and are useful when you
371 /// statically know what type of instruction you're going to create. These
372 /// helpers just save some typing.
373 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
374 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
375 const Twine &Name = "") {\
376 return Create(Instruction::OPC, V1, V2, Name);\
378 #include "llvm/IR/Instruction.def"
379 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
380 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
381 const Twine &Name, BasicBlock *BB) {\
382 return Create(Instruction::OPC, V1, V2, Name, BB);\
384 #include "llvm/IR/Instruction.def"
385 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
386 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
387 const Twine &Name, Instruction *I) {\
388 return Create(Instruction::OPC, V1, V2, Name, I);\
390 #include "llvm/IR/Instruction.def"
392 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
393 const Twine &Name = "") {
394 BinaryOperator *BO = Create(Opc, V1, V2, Name);
395 BO->setHasNoSignedWrap(true);
398 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
399 const Twine &Name, BasicBlock *BB) {
400 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
401 BO->setHasNoSignedWrap(true);
404 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
405 const Twine &Name, Instruction *I) {
406 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
407 BO->setHasNoSignedWrap(true);
411 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
412 const Twine &Name = "") {
413 BinaryOperator *BO = Create(Opc, V1, V2, Name);
414 BO->setHasNoUnsignedWrap(true);
417 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
418 const Twine &Name, BasicBlock *BB) {
419 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
420 BO->setHasNoUnsignedWrap(true);
423 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
424 const Twine &Name, Instruction *I) {
425 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
426 BO->setHasNoUnsignedWrap(true);
430 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
431 const Twine &Name = "") {
432 BinaryOperator *BO = Create(Opc, V1, V2, Name);
433 BO->setIsExact(true);
436 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
437 const Twine &Name, BasicBlock *BB) {
438 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
439 BO->setIsExact(true);
442 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
443 const Twine &Name, Instruction *I) {
444 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
445 BO->setIsExact(true);
449 #define DEFINE_HELPERS(OPC, NUWNSWEXACT) \
450 static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2, \
451 const Twine &Name = "") { \
452 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \
454 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
455 Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) { \
456 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB); \
458 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
459 Value *V1, Value *V2, const Twine &Name, Instruction *I) { \
460 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I); \
463 DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
464 DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
465 DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
466 DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
467 DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
468 DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
469 DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
470 DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
472 DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv
473 DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv
474 DEFINE_HELPERS(AShr, Exact) // CreateExactAShr
475 DEFINE_HELPERS(LShr, Exact) // CreateExactLShr
477 #undef DEFINE_HELPERS
479 /// Helper functions to construct and inspect unary operations (NEG and NOT)
480 /// via binary operators SUB and XOR:
482 /// Create the NEG and NOT instructions out of SUB and XOR instructions.
484 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
485 Instruction *InsertBefore = nullptr);
486 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
487 BasicBlock *InsertAtEnd);
488 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
489 Instruction *InsertBefore = nullptr);
490 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
491 BasicBlock *InsertAtEnd);
492 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
493 Instruction *InsertBefore = nullptr);
494 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
495 BasicBlock *InsertAtEnd);
496 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
497 Instruction *InsertBefore = nullptr);
498 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
499 BasicBlock *InsertAtEnd);
500 static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
501 Instruction *InsertBefore = nullptr);
502 static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
503 BasicBlock *InsertAtEnd);
505 /// Check if the given Value is a NEG, FNeg, or NOT instruction.
507 static bool isNeg(const Value *V);
508 static bool isFNeg(const Value *V, bool IgnoreZeroSign=false);
509 static bool isNot(const Value *V);
511 /// Helper functions to extract the unary argument of a NEG, FNEG or NOT
512 /// operation implemented via Sub, FSub, or Xor.
514 static const Value *getNegArgument(const Value *BinOp);
515 static Value *getNegArgument( Value *BinOp);
516 static const Value *getFNegArgument(const Value *BinOp);
517 static Value *getFNegArgument( Value *BinOp);
518 static const Value *getNotArgument(const Value *BinOp);
519 static Value *getNotArgument( Value *BinOp);
521 BinaryOps getOpcode() const {
522 return static_cast<BinaryOps>(Instruction::getOpcode());
525 /// Exchange the two operands to this instruction.
526 /// This instruction is safe to use on any binary instruction and
527 /// does not modify the semantics of the instruction. If the instruction
528 /// cannot be reversed (ie, it's a Div), then return true.
532 /// Set or clear the nsw flag on this instruction, which must be an operator
533 /// which supports this flag. See LangRef.html for the meaning of this flag.
534 void setHasNoUnsignedWrap(bool b = true);
536 /// Set or clear the nsw flag on this instruction, which must be an operator
537 /// which supports this flag. See LangRef.html for the meaning of this flag.
538 void setHasNoSignedWrap(bool b = true);
540 /// Set or clear the exact flag on this instruction, which must be an operator
541 /// which supports this flag. See LangRef.html for the meaning of this flag.
542 void setIsExact(bool b = true);
544 /// Determine whether the no unsigned wrap flag is set.
545 bool hasNoUnsignedWrap() const;
547 /// Determine whether the no signed wrap flag is set.
548 bool hasNoSignedWrap() const;
550 /// Determine whether the exact flag is set.
551 bool isExact() const;
553 /// Convenience method to copy supported wrapping, exact, and fast-math flags
554 /// from V to this instruction.
555 void copyIRFlags(const Value *V);
557 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
558 /// V and this instruction.
559 void andIRFlags(const Value *V);
561 // Methods for support type inquiry through isa, cast, and dyn_cast:
562 static inline bool classof(const Instruction *I) {
563 return I->isBinaryOp();
565 static inline bool classof(const Value *V) {
566 return isa<Instruction>(V) && classof(cast<Instruction>(V));
571 struct OperandTraits<BinaryOperator> :
572 public FixedNumOperandTraits<BinaryOperator, 2> {
575 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
577 //===----------------------------------------------------------------------===//
579 //===----------------------------------------------------------------------===//
581 /// This is the base class for all instructions that perform data
582 /// casts. It is simply provided so that instruction category testing
583 /// can be performed with code like:
585 /// if (isa<CastInst>(Instr)) { ... }
586 /// @brief Base class of casting instructions.
587 class CastInst : public UnaryInstruction {
588 void anchor() override;
591 /// @brief Constructor with insert-before-instruction semantics for subclasses
592 CastInst(Type *Ty, unsigned iType, Value *S,
593 const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
594 : UnaryInstruction(Ty, iType, S, InsertBefore) {
597 /// @brief Constructor with insert-at-end-of-block semantics for subclasses
598 CastInst(Type *Ty, unsigned iType, Value *S,
599 const Twine &NameStr, BasicBlock *InsertAtEnd)
600 : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
605 /// Provides a way to construct any of the CastInst subclasses using an
606 /// opcode instead of the subclass's constructor. The opcode must be in the
607 /// CastOps category (Instruction::isCast(opcode) returns true). This
608 /// constructor has insert-before-instruction semantics to automatically
609 /// insert the new CastInst before InsertBefore (if it is non-null).
610 /// @brief Construct any of the CastInst subclasses
611 static CastInst *Create(
612 Instruction::CastOps, ///< The opcode of the cast instruction
613 Value *S, ///< The value to be casted (operand 0)
614 Type *Ty, ///< The type to which cast should be made
615 const Twine &Name = "", ///< Name for the instruction
616 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
618 /// Provides a way to construct any of the CastInst subclasses using an
619 /// opcode instead of the subclass's constructor. The opcode must be in the
620 /// CastOps category. This constructor has insert-at-end-of-block semantics
621 /// to automatically insert the new CastInst at the end of InsertAtEnd (if
623 /// @brief Construct any of the CastInst subclasses
624 static CastInst *Create(
625 Instruction::CastOps, ///< The opcode for the cast instruction
626 Value *S, ///< The value to be casted (operand 0)
627 Type *Ty, ///< The type to which operand is casted
628 const Twine &Name, ///< The name for the instruction
629 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
632 /// @brief Create a ZExt or BitCast cast instruction
633 static CastInst *CreateZExtOrBitCast(
634 Value *S, ///< The value to be casted (operand 0)
635 Type *Ty, ///< The type to which cast should be made
636 const Twine &Name = "", ///< Name for the instruction
637 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
640 /// @brief Create a ZExt or BitCast cast instruction
641 static CastInst *CreateZExtOrBitCast(
642 Value *S, ///< The value to be casted (operand 0)
643 Type *Ty, ///< The type to which operand is casted
644 const Twine &Name, ///< The name for the instruction
645 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
648 /// @brief Create a SExt or BitCast cast instruction
649 static CastInst *CreateSExtOrBitCast(
650 Value *S, ///< The value to be casted (operand 0)
651 Type *Ty, ///< The type to which cast should be made
652 const Twine &Name = "", ///< Name for the instruction
653 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
656 /// @brief Create a SExt or BitCast cast instruction
657 static CastInst *CreateSExtOrBitCast(
658 Value *S, ///< The value to be casted (operand 0)
659 Type *Ty, ///< The type to which operand is casted
660 const Twine &Name, ///< The name for the instruction
661 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
664 /// @brief Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
665 static CastInst *CreatePointerCast(
666 Value *S, ///< The pointer value to be casted (operand 0)
667 Type *Ty, ///< The type to which operand is casted
668 const Twine &Name, ///< The name for the instruction
669 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
672 /// @brief Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
673 static CastInst *CreatePointerCast(
674 Value *S, ///< The pointer value to be casted (operand 0)
675 Type *Ty, ///< The type to which cast should be made
676 const Twine &Name = "", ///< Name for the instruction
677 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
680 /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
681 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
682 Value *S, ///< The pointer value to be casted (operand 0)
683 Type *Ty, ///< The type to which operand is casted
684 const Twine &Name, ///< The name for the instruction
685 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
688 /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
689 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
690 Value *S, ///< The pointer value to be casted (operand 0)
691 Type *Ty, ///< The type to which cast should be made
692 const Twine &Name = "", ///< Name for the instruction
693 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
696 /// @brief Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
698 /// If the value is a pointer type and the destination an integer type,
699 /// creates a PtrToInt cast. If the value is an integer type and the
700 /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
702 static CastInst *CreateBitOrPointerCast(
703 Value *S, ///< The pointer value to be casted (operand 0)
704 Type *Ty, ///< The type to which cast should be made
705 const Twine &Name = "", ///< Name for the instruction
706 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
709 /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
710 static CastInst *CreateIntegerCast(
711 Value *S, ///< The pointer value to be casted (operand 0)
712 Type *Ty, ///< The type to which cast should be made
713 bool isSigned, ///< Whether to regard S as signed or not
714 const Twine &Name = "", ///< Name for the instruction
715 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
718 /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
719 static CastInst *CreateIntegerCast(
720 Value *S, ///< The integer value to be casted (operand 0)
721 Type *Ty, ///< The integer type to which operand is casted
722 bool isSigned, ///< Whether to regard S as signed or not
723 const Twine &Name, ///< The name for the instruction
724 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
727 /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
728 static CastInst *CreateFPCast(
729 Value *S, ///< The floating point value to be casted
730 Type *Ty, ///< The floating point type to cast to
731 const Twine &Name = "", ///< Name for the instruction
732 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
735 /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
736 static CastInst *CreateFPCast(
737 Value *S, ///< The floating point value to be casted
738 Type *Ty, ///< The floating point type to cast to
739 const Twine &Name, ///< The name for the instruction
740 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
743 /// @brief Create a Trunc or BitCast cast instruction
744 static CastInst *CreateTruncOrBitCast(
745 Value *S, ///< The value to be casted (operand 0)
746 Type *Ty, ///< The type to which cast should be made
747 const Twine &Name = "", ///< Name for the instruction
748 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
751 /// @brief Create a Trunc or BitCast cast instruction
752 static CastInst *CreateTruncOrBitCast(
753 Value *S, ///< The value to be casted (operand 0)
754 Type *Ty, ///< The type to which operand is casted
755 const Twine &Name, ///< The name for the instruction
756 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
759 /// @brief Check whether it is valid to call getCastOpcode for these types.
760 static bool isCastable(
761 Type *SrcTy, ///< The Type from which the value should be cast.
762 Type *DestTy ///< The Type to which the value should be cast.
765 /// @brief Check whether a bitcast between these types is valid
766 static bool isBitCastable(
767 Type *SrcTy, ///< The Type from which the value should be cast.
768 Type *DestTy ///< The Type to which the value should be cast.
771 /// @brief Check whether a bitcast, inttoptr, or ptrtoint cast between these
772 /// types is valid and a no-op.
774 /// This ensures that any pointer<->integer cast has enough bits in the
775 /// integer and any other cast is a bitcast.
776 static bool isBitOrNoopPointerCastable(
777 Type *SrcTy, ///< The Type from which the value should be cast.
778 Type *DestTy, ///< The Type to which the value should be cast.
779 const DataLayout &DL);
781 /// Returns the opcode necessary to cast Val into Ty using usual casting
783 /// @brief Infer the opcode for cast operand and type
784 static Instruction::CastOps getCastOpcode(
785 const Value *Val, ///< The value to cast
786 bool SrcIsSigned, ///< Whether to treat the source as signed
787 Type *Ty, ///< The Type to which the value should be casted
788 bool DstIsSigned ///< Whether to treate the dest. as signed
791 /// There are several places where we need to know if a cast instruction
792 /// only deals with integer source and destination types. To simplify that
793 /// logic, this method is provided.
794 /// @returns true iff the cast has only integral typed operand and dest type.
795 /// @brief Determine if this is an integer-only cast.
796 bool isIntegerCast() const;
798 /// A lossless cast is one that does not alter the basic value. It implies
799 /// a no-op cast but is more stringent, preventing things like int->float,
800 /// long->double, or int->ptr.
801 /// @returns true iff the cast is lossless.
802 /// @brief Determine if this is a lossless cast.
803 bool isLosslessCast() const;
805 /// A no-op cast is one that can be effected without changing any bits.
806 /// It implies that the source and destination types are the same size. The
807 /// IntPtrTy argument is used to make accurate determinations for casts
808 /// involving Integer and Pointer types. They are no-op casts if the integer
809 /// is the same size as the pointer. However, pointer size varies with
810 /// platform. Generally, the result of DataLayout::getIntPtrType() should be
811 /// passed in. If that's not available, use Type::Int64Ty, which will make
812 /// the isNoopCast call conservative.
813 /// @brief Determine if the described cast is a no-op cast.
814 static bool isNoopCast(
815 Instruction::CastOps Opcode, ///< Opcode of cast
816 Type *SrcTy, ///< SrcTy of cast
817 Type *DstTy, ///< DstTy of cast
818 Type *IntPtrTy ///< Integer type corresponding to Ptr types
821 /// @brief Determine if this cast is a no-op cast.
823 Type *IntPtrTy ///< Integer type corresponding to pointer
826 /// @brief Determine if this cast is a no-op cast.
828 /// \param DL is the DataLayout to get the Int Ptr type from.
829 bool isNoopCast(const DataLayout &DL) const;
831 /// Determine how a pair of casts can be eliminated, if they can be at all.
832 /// This is a helper function for both CastInst and ConstantExpr.
833 /// @returns 0 if the CastInst pair can't be eliminated, otherwise
834 /// returns Instruction::CastOps value for a cast that can replace
835 /// the pair, casting SrcTy to DstTy.
836 /// @brief Determine if a cast pair is eliminable
837 static unsigned isEliminableCastPair(
838 Instruction::CastOps firstOpcode, ///< Opcode of first cast
839 Instruction::CastOps secondOpcode, ///< Opcode of second cast
840 Type *SrcTy, ///< SrcTy of 1st cast
841 Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
842 Type *DstTy, ///< DstTy of 2nd cast
843 Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
844 Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
845 Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null
848 /// @brief Return the opcode of this CastInst
849 Instruction::CastOps getOpcode() const {
850 return Instruction::CastOps(Instruction::getOpcode());
853 /// @brief Return the source type, as a convenience
854 Type* getSrcTy() const { return getOperand(0)->getType(); }
855 /// @brief Return the destination type, as a convenience
856 Type* getDestTy() const { return getType(); }
858 /// This method can be used to determine if a cast from S to DstTy using
859 /// Opcode op is valid or not.
860 /// @returns true iff the proposed cast is valid.
861 /// @brief Determine if a cast is valid without creating one.
862 static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
864 /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
865 static inline bool classof(const Instruction *I) {
868 static inline bool classof(const Value *V) {
869 return isa<Instruction>(V) && classof(cast<Instruction>(V));
873 //===----------------------------------------------------------------------===//
875 //===----------------------------------------------------------------------===//
877 /// This class is the base class for the comparison instructions.
878 /// @brief Abstract base class of comparison instructions.
879 class CmpInst : public Instruction {
880 void *operator new(size_t, unsigned) = delete;
884 CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
885 Value *LHS, Value *RHS, const Twine &Name = "",
886 Instruction *InsertBefore = nullptr);
888 CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
889 Value *LHS, Value *RHS, const Twine &Name,
890 BasicBlock *InsertAtEnd);
892 void anchor() override; // Out of line virtual method.
895 /// This enumeration lists the possible predicates for CmpInst subclasses.
896 /// Values in the range 0-31 are reserved for FCmpInst, while values in the
897 /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
898 /// predicate values are not overlapping between the classes.
900 // Opcode U L G E Intuitive operation
901 FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded)
902 FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal
903 FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than
904 FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal
905 FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than
906 FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal
907 FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal
908 FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans)
909 FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y)
910 FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal
911 FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than
912 FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal
913 FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than
914 FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal
915 FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal
916 FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded)
917 FIRST_FCMP_PREDICATE = FCMP_FALSE,
918 LAST_FCMP_PREDICATE = FCMP_TRUE,
919 BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
920 ICMP_EQ = 32, ///< equal
921 ICMP_NE = 33, ///< not equal
922 ICMP_UGT = 34, ///< unsigned greater than
923 ICMP_UGE = 35, ///< unsigned greater or equal
924 ICMP_ULT = 36, ///< unsigned less than
925 ICMP_ULE = 37, ///< unsigned less or equal
926 ICMP_SGT = 38, ///< signed greater than
927 ICMP_SGE = 39, ///< signed greater or equal
928 ICMP_SLT = 40, ///< signed less than
929 ICMP_SLE = 41, ///< signed less or equal
930 FIRST_ICMP_PREDICATE = ICMP_EQ,
931 LAST_ICMP_PREDICATE = ICMP_SLE,
932 BAD_ICMP_PREDICATE = ICMP_SLE + 1
935 // allocate space for exactly two operands
936 void *operator new(size_t s) {
937 return User::operator new(s, 2);
939 /// Construct a compare instruction, given the opcode, the predicate and
940 /// the two operands. Optionally (if InstBefore is specified) insert the
941 /// instruction into a BasicBlock right before the specified instruction.
942 /// The specified Instruction is allowed to be a dereferenced end iterator.
943 /// @brief Create a CmpInst
944 static CmpInst *Create(OtherOps Op,
945 unsigned short predicate, Value *S1,
946 Value *S2, const Twine &Name = "",
947 Instruction *InsertBefore = nullptr);
949 /// Construct a compare instruction, given the opcode, the predicate and the
950 /// two operands. Also automatically insert this instruction to the end of
951 /// the BasicBlock specified.
952 /// @brief Create a CmpInst
953 static CmpInst *Create(OtherOps Op, unsigned short predicate, Value *S1,
954 Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
956 /// @brief Get the opcode casted to the right type
957 OtherOps getOpcode() const {
958 return static_cast<OtherOps>(Instruction::getOpcode());
961 /// @brief Return the predicate for this instruction.
962 Predicate getPredicate() const {
963 return Predicate(getSubclassDataFromInstruction());
966 /// @brief Set the predicate for this instruction to the specified value.
967 void setPredicate(Predicate P) { setInstructionSubclassData(P); }
969 static bool isFPPredicate(Predicate P) {
970 return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
973 static bool isIntPredicate(Predicate P) {
974 return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
977 bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
978 bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
980 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
981 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
982 /// @returns the inverse predicate for the instruction's current predicate.
983 /// @brief Return the inverse of the instruction's predicate.
984 Predicate getInversePredicate() const {
985 return getInversePredicate(getPredicate());
988 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
989 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
990 /// @returns the inverse predicate for predicate provided in \p pred.
991 /// @brief Return the inverse of a given predicate
992 static Predicate getInversePredicate(Predicate pred);
994 /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
995 /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
996 /// @returns the predicate that would be the result of exchanging the two
997 /// operands of the CmpInst instruction without changing the result
999 /// @brief Return the predicate as if the operands were swapped
1000 Predicate getSwappedPredicate() const {
1001 return getSwappedPredicate(getPredicate());
1004 /// This is a static version that you can use without an instruction
1006 /// @brief Return the predicate as if the operands were swapped.
1007 static Predicate getSwappedPredicate(Predicate pred);
1009 /// @brief Provide more efficient getOperand methods.
1010 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1012 /// This is just a convenience that dispatches to the subclasses.
1013 /// @brief Swap the operands and adjust predicate accordingly to retain
1014 /// the same comparison.
1015 void swapOperands();
1017 /// This is just a convenience that dispatches to the subclasses.
1018 /// @brief Determine if this CmpInst is commutative.
1019 bool isCommutative() const;
1021 /// This is just a convenience that dispatches to the subclasses.
1022 /// @brief Determine if this is an equals/not equals predicate.
1023 bool isEquality() const;
1025 /// @returns true if the comparison is signed, false otherwise.
1026 /// @brief Determine if this instruction is using a signed comparison.
1027 bool isSigned() const {
1028 return isSigned(getPredicate());
1031 /// @returns true if the comparison is unsigned, false otherwise.
1032 /// @brief Determine if this instruction is using an unsigned comparison.
1033 bool isUnsigned() const {
1034 return isUnsigned(getPredicate());
1037 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1038 /// @returns the signed version of the unsigned predicate pred.
1039 /// @brief return the signed version of a predicate
1040 static Predicate getSignedPredicate(Predicate pred);
1042 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1043 /// @returns the signed version of the predicate for this instruction (which
1044 /// has to be an unsigned predicate).
1045 /// @brief return the signed version of a predicate
1046 Predicate getSignedPredicate() {
1047 return getSignedPredicate(getPredicate());
1050 /// This is just a convenience.
1051 /// @brief Determine if this is true when both operands are the same.
1052 bool isTrueWhenEqual() const {
1053 return isTrueWhenEqual(getPredicate());
1056 /// This is just a convenience.
1057 /// @brief Determine if this is false when both operands are the same.
1058 bool isFalseWhenEqual() const {
1059 return isFalseWhenEqual(getPredicate());
1062 /// @returns true if the predicate is unsigned, false otherwise.
1063 /// @brief Determine if the predicate is an unsigned operation.
1064 static bool isUnsigned(unsigned short predicate);
1066 /// @returns true if the predicate is signed, false otherwise.
1067 /// @brief Determine if the predicate is an signed operation.
1068 static bool isSigned(unsigned short predicate);
1070 /// @brief Determine if the predicate is an ordered operation.
1071 static bool isOrdered(unsigned short predicate);
1073 /// @brief Determine if the predicate is an unordered operation.
1074 static bool isUnordered(unsigned short predicate);
1076 /// Determine if the predicate is true when comparing a value with itself.
1077 static bool isTrueWhenEqual(unsigned short predicate);
1079 /// Determine if the predicate is false when comparing a value with itself.
1080 static bool isFalseWhenEqual(unsigned short predicate);
1082 /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
1083 static inline bool classof(const Instruction *I) {
1084 return I->getOpcode() == Instruction::ICmp ||
1085 I->getOpcode() == Instruction::FCmp;
1087 static inline bool classof(const Value *V) {
1088 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1091 /// @brief Create a result type for fcmp/icmp
1092 static Type* makeCmpResultType(Type* opnd_type) {
1093 if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
1094 return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
1095 vt->getNumElements());
1097 return Type::getInt1Ty(opnd_type->getContext());
1101 // Shadow Value::setValueSubclassData with a private forwarding method so that
1102 // subclasses cannot accidentally use it.
1103 void setValueSubclassData(unsigned short D) {
1104 Value::setValueSubclassData(D);
1108 // FIXME: these are redundant if CmpInst < BinaryOperator
1110 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
1113 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
1115 /// \brief A lightweight accessor for an operand bundle meant to be passed
1116 /// around by value.
1117 struct OperandBundleUse {
1118 ArrayRef<Use> Inputs;
1120 OperandBundleUse() {}
1121 explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
1122 : Inputs(Inputs), Tag(Tag) {}
1124 /// \brief Return true if all the operands in this operand bundle have the
1127 /// Currently there is no way to have attributes on operand bundles differ on
1128 /// a per operand granularity.
1129 bool operandsHaveAttr(Attribute::AttrKind A) const {
1130 if (isDeoptOperandBundle())
1131 return A == Attribute::ReadOnly || A == Attribute::NoCapture;
1133 // Conservative answer: no operands have any attributes.
1137 /// \brief Return the tag of this operand bundle as a string.
1138 StringRef getTagName() const {
1139 return Tag->getKey();
1142 /// \brief Return the tag of this operand bundle as an integer.
1144 /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
1145 /// and this function returns the unique integer getOrInsertBundleTag
1146 /// associated the tag of this operand bundle to.
1147 uint32_t getTagID() const {
1148 return Tag->getValue();
1151 /// \brief Return true if this is a "deopt" operand bundle.
1152 bool isDeoptOperandBundle() const {
1153 return getTagID() == LLVMContext::OB_deopt;
1157 /// \brief Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1158 StringMapEntry<uint32_t> *Tag;
1161 /// \brief A container for an operand bundle being viewed as a set of values
1162 /// rather than a set of uses.
1164 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1165 /// so it is possible to create and pass around "self-contained" instances of
1166 /// OperandBundleDef and ConstOperandBundleDef.
1167 template <typename InputTy> class OperandBundleDefT {
1169 std::vector<InputTy> Inputs;
1172 explicit OperandBundleDefT(StringRef Tag, std::vector<InputTy> Inputs)
1173 : Tag(Tag), Inputs(std::move(Inputs)) {}
1175 explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1176 : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1178 explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1179 Tag = OBU.getTagName();
1180 Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
1183 ArrayRef<InputTy> inputs() const { return Inputs; }
1185 typedef typename std::vector<InputTy>::const_iterator input_iterator;
1186 size_t input_size() const { return Inputs.size(); }
1187 input_iterator input_begin() const { return Inputs.begin(); }
1188 input_iterator input_end() const { return Inputs.end(); }
1190 StringRef getTag() const { return Tag; }
1193 typedef OperandBundleDefT<Value *> OperandBundleDef;
1194 typedef OperandBundleDefT<const Value *> ConstOperandBundleDef;
1196 /// \brief A mixin to add operand bundle functionality to llvm instruction
1199 /// OperandBundleUser uses the descriptor area co-allocated with the host User
1200 /// to store some meta information about which operands are "normal" operands,
1201 /// and which ones belong to some operand bundle.
1203 /// The layout of an operand bundle user is
1205 /// +-----------uint32_t End-------------------------------------+
1207 /// | +--------uint32_t Begin--------------------+ |
1210 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1211 /// | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
1212 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1215 /// | +--------uint32_t Begin------------+ |
1217 /// +-----------uint32_t End-----------------------------+
1220 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use list.
1221 /// These descriptions are installed and managed by this class, and they're all
1222 /// instances of OperandBundleUser<T>::BundleOpInfo.
1224 /// DU is an additional descriptor installed by User's 'operator new' to keep
1225 /// track of the 'BOI0 ... BOIN' co-allocation. OperandBundleUser does not
1226 /// access or modify DU in any way, it's an implementation detail private to
1229 /// The regular Use& vector for the User starts at U0. The operand bundle uses
1230 /// are part of the Use& vector, just like normal uses. In the diagram above,
1231 /// the operand bundle uses start at BOI0_U0. Each instance of BundleOpInfo has
1232 /// information about a contiguous set of uses constituting an operand bundle,
1233 /// and the total set of operand bundle uses themselves form a contiguous set of
1234 /// uses (i.e. there are no gaps between uses corresponding to individual
1235 /// operand bundles).
1237 /// This class does not know the location of the set of operand bundle uses
1238 /// within the use list -- that is decided by the User using this class via the
1239 /// BeginIdx argument in populateBundleOperandInfos.
1241 /// Currently operand bundle users with hung-off operands are not supported.
1242 template <typename InstrTy, typename OpIteratorTy> class OperandBundleUser {
1244 /// \brief Return the number of operand bundles associated with this User.
1245 unsigned getNumOperandBundles() const {
1246 return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1249 /// \brief Return true if this User has any operand bundles.
1250 bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1252 /// \brief Return the index of the first bundle operand in the Use array.
1253 unsigned getBundleOperandsStartIndex() const {
1254 assert(hasOperandBundles() && "Don't call otherwise!");
1255 return bundle_op_info_begin()->Begin;
1258 /// \brief Return the index of the last bundle operand in the Use array.
1259 unsigned getBundleOperandsEndIndex() const {
1260 assert(hasOperandBundles() && "Don't call otherwise!");
1261 return bundle_op_info_end()[-1].End;
1264 /// \brief Return the total number operands (not operand bundles) used by
1265 /// every operand bundle in this OperandBundleUser.
1266 unsigned getNumTotalBundleOperands() const {
1267 if (!hasOperandBundles())
1270 unsigned Begin = getBundleOperandsStartIndex();
1271 unsigned End = getBundleOperandsEndIndex();
1273 assert(Begin <= End && "Should be!");
1277 /// \brief Return the operand bundle at a specific index.
1278 OperandBundleUse getOperandBundleAt(unsigned Index) const {
1279 assert(Index < getNumOperandBundles() && "Index out of bounds!");
1280 return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1283 /// \brief Return the number of operand bundles with the tag Name attached to
1284 /// this instruction.
1285 unsigned countOperandBundlesOfType(StringRef Name) const {
1287 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1288 if (getOperandBundleAt(i).getTagName() == Name)
1294 /// \brief Return the number of operand bundles with the tag ID attached to
1295 /// this instruction.
1296 unsigned countOperandBundlesOfType(uint32_t ID) const {
1298 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1299 if (getOperandBundleAt(i).getTagID() == ID)
1305 /// \brief Return an operand bundle by name, if present.
1307 /// It is an error to call this for operand bundle types that may have
1308 /// multiple instances of them on the same instruction.
1309 Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1310 assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
1312 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1313 OperandBundleUse U = getOperandBundleAt(i);
1314 if (U.getTagName() == Name)
1321 /// \brief Return an operand bundle by tag ID, if present.
1323 /// It is an error to call this for operand bundle types that may have
1324 /// multiple instances of them on the same instruction.
1325 Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1326 assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
1328 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1329 OperandBundleUse U = getOperandBundleAt(i);
1330 if (U.getTagID() == ID)
1337 /// \brief Return the list of operand bundles attached to this instruction as
1338 /// a vector of OperandBundleDefs.
1340 /// This function copies the OperandBundeUse instances associated with this
1341 /// OperandBundleUser to a vector of OperandBundleDefs. Note:
1342 /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1343 /// representations of operand bundles (see documentation above).
1344 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
1345 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1346 Defs.emplace_back(getOperandBundleAt(i));
1349 /// \brief Return the operand bundle for the operand at index OpIdx.
1351 /// It is an error to call this with an OpIdx that does not correspond to an
1353 OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1354 for (auto &BOI : bundle_op_infos())
1355 if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
1356 return operandBundleFromBundleOpInfo(BOI);
1358 llvm_unreachable("Did not find operand bundle for operand!");
1361 /// \brief Return true if this operand bundle user has operand bundles that
1362 /// may read from the heap.
1363 bool hasReadingOperandBundles() const {
1364 // Implementation note: this is a conservative implementation of operand
1365 // bundle semantics, where *any* operand bundle forces a callsite to be at
1367 return hasOperandBundles();
1370 /// \brief Return true if this operand bundle user has operand bundles that
1371 /// may write to the heap.
1372 bool hasClobberingOperandBundles() const {
1373 for (auto &BOI : bundle_op_infos()) {
1374 if (BOI.Tag->second == LLVMContext::OB_deopt)
1377 // This instruction has an operand bundle that is not a "deopt" operand
1378 // bundle. Assume the worst.
1386 /// \brief Is the function attribute S disallowed by some operand bundle on
1387 /// this operand bundle user?
1388 bool isFnAttrDisallowedByOpBundle(StringRef S) const {
1389 // Operand bundles only possibly disallow readnone, readonly and argmenonly
1390 // attributes. All String attributes are fine.
1394 /// \brief Is the function attribute A disallowed by some operand bundle on
1395 /// this operand bundle user?
1396 bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
1401 case Attribute::ArgMemOnly:
1402 return hasReadingOperandBundles();
1404 case Attribute::ReadNone:
1405 return hasReadingOperandBundles();
1407 case Attribute::ReadOnly:
1408 return hasClobberingOperandBundles();
1411 llvm_unreachable("switch has a default case!");
1414 /// \brief Used to keep track of an operand bundle. See the main comment on
1415 /// OperandBundleUser above.
1416 struct BundleOpInfo {
1417 /// \brief The operand bundle tag, interned by
1418 /// LLVMContextImpl::getOrInsertBundleTag.
1419 StringMapEntry<uint32_t> *Tag;
1421 /// \brief The index in the Use& vector where operands for this operand
1425 /// \brief The index in the Use& vector where operands for this operand
1430 /// \brief Simple helper function to map a BundleOpInfo to an
1431 /// OperandBundleUse.
1433 operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
1434 auto op_begin = static_cast<const InstrTy *>(this)->op_begin();
1435 ArrayRef<Use> Inputs(op_begin + BOI.Begin, op_begin + BOI.End);
1436 return OperandBundleUse(BOI.Tag, Inputs);
1439 typedef BundleOpInfo *bundle_op_iterator;
1440 typedef const BundleOpInfo *const_bundle_op_iterator;
1442 /// \brief Return the start of the list of BundleOpInfo instances associated
1443 /// with this OperandBundleUser.
1444 bundle_op_iterator bundle_op_info_begin() {
1445 if (!static_cast<InstrTy *>(this)->hasDescriptor())
1448 uint8_t *BytesBegin = static_cast<InstrTy *>(this)->getDescriptor().begin();
1449 return reinterpret_cast<bundle_op_iterator>(BytesBegin);
1452 /// \brief Return the start of the list of BundleOpInfo instances associated
1453 /// with this OperandBundleUser.
1454 const_bundle_op_iterator bundle_op_info_begin() const {
1455 auto *NonConstThis =
1456 const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1457 return NonConstThis->bundle_op_info_begin();
1460 /// \brief Return the end of the list of BundleOpInfo instances associated
1461 /// with this OperandBundleUser.
1462 bundle_op_iterator bundle_op_info_end() {
1463 if (!static_cast<InstrTy *>(this)->hasDescriptor())
1466 uint8_t *BytesEnd = static_cast<InstrTy *>(this)->getDescriptor().end();
1467 return reinterpret_cast<bundle_op_iterator>(BytesEnd);
1470 /// \brief Return the end of the list of BundleOpInfo instances associated
1471 /// with this OperandBundleUser.
1472 const_bundle_op_iterator bundle_op_info_end() const {
1473 auto *NonConstThis =
1474 const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1475 return NonConstThis->bundle_op_info_end();
1478 /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1479 iterator_range<bundle_op_iterator> bundle_op_infos() {
1480 return iterator_range<bundle_op_iterator>(bundle_op_info_begin(),
1481 bundle_op_info_end());
1484 /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1485 iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
1486 return iterator_range<const_bundle_op_iterator>(bundle_op_info_begin(),
1487 bundle_op_info_end());
1490 /// \brief Populate the BundleOpInfo instances and the Use& vector from \p
1491 /// Bundles. Return the op_iterator pointing to the Use& one past the last
1492 /// last bundle operand use.
1494 /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
1495 /// instance allocated in this User's descriptor.
1496 OpIteratorTy populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
1497 const unsigned BeginIndex) {
1498 auto It = static_cast<InstrTy *>(this)->op_begin() + BeginIndex;
1499 for (auto &B : Bundles)
1500 It = std::copy(B.input_begin(), B.input_end(), It);
1502 auto *ContextImpl = static_cast<InstrTy *>(this)->getContext().pImpl;
1503 auto BI = Bundles.begin();
1504 unsigned CurrentIndex = BeginIndex;
1506 for (auto &BOI : bundle_op_infos()) {
1507 assert(BI != Bundles.end() && "Incorrect allocation?");
1509 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
1510 BOI.Begin = CurrentIndex;
1511 BOI.End = CurrentIndex + BI->input_size();
1512 CurrentIndex = BOI.End;
1516 assert(BI == Bundles.end() && "Incorrect allocation?");
1521 /// \brief Return the total number of values used in \p Bundles.
1522 static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
1524 for (auto &B : Bundles)
1525 Total += B.input_size();
1530 } // end llvm namespace
1532 #endif // LLVM_IR_INSTRTYPES_H