1 //===-- llvm/Instructions.h - Instruction subclass definitions --*- 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 exposes the class definitions of all of the subclasses of the
11 // Instruction class. This is meant to be an easy way to get access to all
12 // instruction subclasses.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_IR_INSTRUCTIONS_H
17 #define LLVM_IR_INSTRUCTIONS_H
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/IR/Attributes.h"
23 #include "llvm/IR/CallingConv.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/InstrTypes.h"
27 #include "llvm/Support/ErrorHandling.h"
42 // Consume = 3, // Not specified yet.
46 SequentiallyConsistent = 7
49 enum SynchronizationScope {
54 /// Returns true if the ordering is at least as strong as acquire
55 /// (i.e. acquire, acq_rel or seq_cst)
56 inline bool isAtLeastAcquire(AtomicOrdering Ord) {
57 return (Ord == Acquire ||
58 Ord == AcquireRelease ||
59 Ord == SequentiallyConsistent);
62 /// Returns true if the ordering is at least as strong as release
63 /// (i.e. release, acq_rel or seq_cst)
64 inline bool isAtLeastRelease(AtomicOrdering Ord) {
65 return (Ord == Release ||
66 Ord == AcquireRelease ||
67 Ord == SequentiallyConsistent);
70 //===----------------------------------------------------------------------===//
72 //===----------------------------------------------------------------------===//
74 /// AllocaInst - an instruction to allocate memory on the stack
76 class AllocaInst : public UnaryInstruction {
80 // Note: Instruction needs to be a friend here to call cloneImpl.
81 friend class Instruction;
82 AllocaInst *cloneImpl() const;
85 explicit AllocaInst(Type *Ty, Value *ArraySize = nullptr,
86 const Twine &Name = "",
87 Instruction *InsertBefore = nullptr);
88 AllocaInst(Type *Ty, Value *ArraySize,
89 const Twine &Name, BasicBlock *InsertAtEnd);
91 AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore = nullptr);
92 AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd);
94 AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
95 const Twine &Name = "", Instruction *InsertBefore = nullptr);
96 AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
97 const Twine &Name, BasicBlock *InsertAtEnd);
99 // Out of line virtual method, so the vtable, etc. has a home.
100 ~AllocaInst() override;
102 /// isArrayAllocation - Return true if there is an allocation size parameter
103 /// to the allocation instruction that is not 1.
105 bool isArrayAllocation() const;
107 /// getArraySize - Get the number of elements allocated. For a simple
108 /// allocation of a single element, this will return a constant 1 value.
110 const Value *getArraySize() const { return getOperand(0); }
111 Value *getArraySize() { return getOperand(0); }
113 /// getType - Overload to return most specific pointer type
115 PointerType *getType() const {
116 return cast<PointerType>(Instruction::getType());
119 /// getAllocatedType - Return the type that is being allocated by the
122 Type *getAllocatedType() const { return AllocatedType; }
123 /// \brief for use only in special circumstances that need to generically
124 /// transform a whole instruction (eg: IR linking and vectorization).
125 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
127 /// getAlignment - Return the alignment of the memory that is being allocated
128 /// by the instruction.
130 unsigned getAlignment() const {
131 return (1u << (getSubclassDataFromInstruction() & 31)) >> 1;
133 void setAlignment(unsigned Align);
135 /// isStaticAlloca - Return true if this alloca is in the entry block of the
136 /// function and is a constant size. If so, the code generator will fold it
137 /// into the prolog/epilog code, so it is basically free.
138 bool isStaticAlloca() const;
140 /// \brief Return true if this alloca is used as an inalloca argument to a
141 /// call. Such allocas are never considered static even if they are in the
143 bool isUsedWithInAlloca() const {
144 return getSubclassDataFromInstruction() & 32;
147 /// \brief Specify whether this alloca is used to represent the arguments to
149 void setUsedWithInAlloca(bool V) {
150 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
154 // Methods for support type inquiry through isa, cast, and dyn_cast:
155 static inline bool classof(const Instruction *I) {
156 return (I->getOpcode() == Instruction::Alloca);
158 static inline bool classof(const Value *V) {
159 return isa<Instruction>(V) && classof(cast<Instruction>(V));
163 // Shadow Instruction::setInstructionSubclassData with a private forwarding
164 // method so that subclasses cannot accidentally use it.
165 void setInstructionSubclassData(unsigned short D) {
166 Instruction::setInstructionSubclassData(D);
170 //===----------------------------------------------------------------------===//
172 //===----------------------------------------------------------------------===//
174 /// LoadInst - an instruction for reading from memory. This uses the
175 /// SubclassData field in Value to store whether or not the load is volatile.
177 class LoadInst : public UnaryInstruction {
181 // Note: Instruction needs to be a friend here to call cloneImpl.
182 friend class Instruction;
183 LoadInst *cloneImpl() const;
186 LoadInst(Value *Ptr, const Twine &NameStr, Instruction *InsertBefore);
187 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile = false,
189 Instruction *InsertBefore = nullptr);
190 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile = false,
191 Instruction *InsertBefore = nullptr)
192 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
193 NameStr, isVolatile, InsertBefore) {}
194 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
195 BasicBlock *InsertAtEnd);
196 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
197 Instruction *InsertBefore = nullptr)
198 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
199 NameStr, isVolatile, Align, InsertBefore) {}
200 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
201 unsigned Align, Instruction *InsertBefore = nullptr);
202 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
203 unsigned Align, BasicBlock *InsertAtEnd);
204 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
205 AtomicOrdering Order, SynchronizationScope SynchScope = CrossThread,
206 Instruction *InsertBefore = nullptr)
207 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
208 NameStr, isVolatile, Align, Order, SynchScope, InsertBefore) {}
209 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
210 unsigned Align, AtomicOrdering Order,
211 SynchronizationScope SynchScope = CrossThread,
212 Instruction *InsertBefore = nullptr);
213 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
214 unsigned Align, AtomicOrdering Order,
215 SynchronizationScope SynchScope,
216 BasicBlock *InsertAtEnd);
218 LoadInst(Value *Ptr, const char *NameStr, Instruction *InsertBefore);
219 LoadInst(Value *Ptr, const char *NameStr, BasicBlock *InsertAtEnd);
220 LoadInst(Type *Ty, Value *Ptr, const char *NameStr = nullptr,
221 bool isVolatile = false, Instruction *InsertBefore = nullptr);
222 explicit LoadInst(Value *Ptr, const char *NameStr = nullptr,
223 bool isVolatile = false,
224 Instruction *InsertBefore = nullptr)
225 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
226 NameStr, isVolatile, InsertBefore) {}
227 LoadInst(Value *Ptr, const char *NameStr, bool isVolatile,
228 BasicBlock *InsertAtEnd);
230 /// isVolatile - Return true if this is a load from a volatile memory
233 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
235 /// setVolatile - Specify whether this is a volatile load or not.
237 void setVolatile(bool V) {
238 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
242 /// getAlignment - Return the alignment of the access that is being performed
244 unsigned getAlignment() const {
245 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
248 void setAlignment(unsigned Align);
250 /// Returns the ordering effect of this fence.
251 AtomicOrdering getOrdering() const {
252 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
255 /// Set the ordering constraint on this load. May not be Release or
257 void setOrdering(AtomicOrdering Ordering) {
258 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
262 SynchronizationScope getSynchScope() const {
263 return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
266 /// Specify whether this load is ordered with respect to all
267 /// concurrently executing threads, or only with respect to signal handlers
268 /// executing in the same thread.
269 void setSynchScope(SynchronizationScope xthread) {
270 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
274 void setAtomic(AtomicOrdering Ordering,
275 SynchronizationScope SynchScope = CrossThread) {
276 setOrdering(Ordering);
277 setSynchScope(SynchScope);
280 bool isSimple() const { return !isAtomic() && !isVolatile(); }
281 bool isUnordered() const {
282 return getOrdering() <= Unordered && !isVolatile();
285 Value *getPointerOperand() { return getOperand(0); }
286 const Value *getPointerOperand() const { return getOperand(0); }
287 static unsigned getPointerOperandIndex() { return 0U; }
289 /// \brief Returns the address space of the pointer operand.
290 unsigned getPointerAddressSpace() const {
291 return getPointerOperand()->getType()->getPointerAddressSpace();
294 // Methods for support type inquiry through isa, cast, and dyn_cast:
295 static inline bool classof(const Instruction *I) {
296 return I->getOpcode() == Instruction::Load;
298 static inline bool classof(const Value *V) {
299 return isa<Instruction>(V) && classof(cast<Instruction>(V));
303 // Shadow Instruction::setInstructionSubclassData with a private forwarding
304 // method so that subclasses cannot accidentally use it.
305 void setInstructionSubclassData(unsigned short D) {
306 Instruction::setInstructionSubclassData(D);
310 //===----------------------------------------------------------------------===//
312 //===----------------------------------------------------------------------===//
314 /// StoreInst - an instruction for storing to memory
316 class StoreInst : public Instruction {
317 void *operator new(size_t, unsigned) = delete;
321 // Note: Instruction needs to be a friend here to call cloneImpl.
322 friend class Instruction;
323 StoreInst *cloneImpl() const;
326 // allocate space for exactly two operands
327 void *operator new(size_t s) {
328 return User::operator new(s, 2);
330 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
331 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
332 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
333 Instruction *InsertBefore = nullptr);
334 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
335 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
336 unsigned Align, Instruction *InsertBefore = nullptr);
337 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
338 unsigned Align, BasicBlock *InsertAtEnd);
339 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
340 unsigned Align, AtomicOrdering Order,
341 SynchronizationScope SynchScope = CrossThread,
342 Instruction *InsertBefore = nullptr);
343 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
344 unsigned Align, AtomicOrdering Order,
345 SynchronizationScope SynchScope,
346 BasicBlock *InsertAtEnd);
348 /// isVolatile - Return true if this is a store to a volatile memory
351 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
353 /// setVolatile - Specify whether this is a volatile store or not.
355 void setVolatile(bool V) {
356 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
360 /// Transparently provide more efficient getOperand methods.
361 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
363 /// getAlignment - Return the alignment of the access that is being performed
365 unsigned getAlignment() const {
366 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
369 void setAlignment(unsigned Align);
371 /// Returns the ordering effect of this store.
372 AtomicOrdering getOrdering() const {
373 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
376 /// Set the ordering constraint on this store. May not be Acquire or
378 void setOrdering(AtomicOrdering Ordering) {
379 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
383 SynchronizationScope getSynchScope() const {
384 return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
387 /// Specify whether this store instruction is ordered with respect to all
388 /// concurrently executing threads, or only with respect to signal handlers
389 /// executing in the same thread.
390 void setSynchScope(SynchronizationScope xthread) {
391 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
395 void setAtomic(AtomicOrdering Ordering,
396 SynchronizationScope SynchScope = CrossThread) {
397 setOrdering(Ordering);
398 setSynchScope(SynchScope);
401 bool isSimple() const { return !isAtomic() && !isVolatile(); }
402 bool isUnordered() const {
403 return getOrdering() <= Unordered && !isVolatile();
406 Value *getValueOperand() { return getOperand(0); }
407 const Value *getValueOperand() const { return getOperand(0); }
409 Value *getPointerOperand() { return getOperand(1); }
410 const Value *getPointerOperand() const { return getOperand(1); }
411 static unsigned getPointerOperandIndex() { return 1U; }
413 /// \brief Returns the address space of the pointer operand.
414 unsigned getPointerAddressSpace() const {
415 return getPointerOperand()->getType()->getPointerAddressSpace();
418 // Methods for support type inquiry through isa, cast, and dyn_cast:
419 static inline bool classof(const Instruction *I) {
420 return I->getOpcode() == Instruction::Store;
422 static inline bool classof(const Value *V) {
423 return isa<Instruction>(V) && classof(cast<Instruction>(V));
427 // Shadow Instruction::setInstructionSubclassData with a private forwarding
428 // method so that subclasses cannot accidentally use it.
429 void setInstructionSubclassData(unsigned short D) {
430 Instruction::setInstructionSubclassData(D);
435 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
438 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
440 //===----------------------------------------------------------------------===//
442 //===----------------------------------------------------------------------===//
444 /// FenceInst - an instruction for ordering other memory operations
446 class FenceInst : public Instruction {
447 void *operator new(size_t, unsigned) = delete;
448 void Init(AtomicOrdering Ordering, SynchronizationScope SynchScope);
451 // Note: Instruction needs to be a friend here to call cloneImpl.
452 friend class Instruction;
453 FenceInst *cloneImpl() const;
456 // allocate space for exactly zero operands
457 void *operator new(size_t s) {
458 return User::operator new(s, 0);
461 // Ordering may only be Acquire, Release, AcquireRelease, or
462 // SequentiallyConsistent.
463 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
464 SynchronizationScope SynchScope = CrossThread,
465 Instruction *InsertBefore = nullptr);
466 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
467 SynchronizationScope SynchScope,
468 BasicBlock *InsertAtEnd);
470 /// Returns the ordering effect of this fence.
471 AtomicOrdering getOrdering() const {
472 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
475 /// Set the ordering constraint on this fence. May only be Acquire, Release,
476 /// AcquireRelease, or SequentiallyConsistent.
477 void setOrdering(AtomicOrdering Ordering) {
478 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
482 SynchronizationScope getSynchScope() const {
483 return SynchronizationScope(getSubclassDataFromInstruction() & 1);
486 /// Specify whether this fence orders other operations with respect to all
487 /// concurrently executing threads, or only with respect to signal handlers
488 /// executing in the same thread.
489 void setSynchScope(SynchronizationScope xthread) {
490 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
494 // Methods for support type inquiry through isa, cast, and dyn_cast:
495 static inline bool classof(const Instruction *I) {
496 return I->getOpcode() == Instruction::Fence;
498 static inline bool classof(const Value *V) {
499 return isa<Instruction>(V) && classof(cast<Instruction>(V));
503 // Shadow Instruction::setInstructionSubclassData with a private forwarding
504 // method so that subclasses cannot accidentally use it.
505 void setInstructionSubclassData(unsigned short D) {
506 Instruction::setInstructionSubclassData(D);
510 //===----------------------------------------------------------------------===//
511 // AtomicCmpXchgInst Class
512 //===----------------------------------------------------------------------===//
514 /// AtomicCmpXchgInst - an instruction that atomically checks whether a
515 /// specified value is in a memory location, and, if it is, stores a new value
516 /// there. Returns the value that was loaded.
518 class AtomicCmpXchgInst : public Instruction {
519 void *operator new(size_t, unsigned) = delete;
520 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
521 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
522 SynchronizationScope SynchScope);
525 // Note: Instruction needs to be a friend here to call cloneImpl.
526 friend class Instruction;
527 AtomicCmpXchgInst *cloneImpl() const;
530 // allocate space for exactly three operands
531 void *operator new(size_t s) {
532 return User::operator new(s, 3);
534 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
535 AtomicOrdering SuccessOrdering,
536 AtomicOrdering FailureOrdering,
537 SynchronizationScope SynchScope,
538 Instruction *InsertBefore = nullptr);
539 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
540 AtomicOrdering SuccessOrdering,
541 AtomicOrdering FailureOrdering,
542 SynchronizationScope SynchScope,
543 BasicBlock *InsertAtEnd);
545 /// isVolatile - Return true if this is a cmpxchg from a volatile memory
548 bool isVolatile() const {
549 return getSubclassDataFromInstruction() & 1;
552 /// setVolatile - Specify whether this is a volatile cmpxchg.
554 void setVolatile(bool V) {
555 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
559 /// Return true if this cmpxchg may spuriously fail.
560 bool isWeak() const {
561 return getSubclassDataFromInstruction() & 0x100;
564 void setWeak(bool IsWeak) {
565 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
569 /// Transparently provide more efficient getOperand methods.
570 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
572 /// Set the ordering constraint on this cmpxchg.
573 void setSuccessOrdering(AtomicOrdering Ordering) {
574 assert(Ordering != NotAtomic &&
575 "CmpXchg instructions can only be atomic.");
576 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
580 void setFailureOrdering(AtomicOrdering Ordering) {
581 assert(Ordering != NotAtomic &&
582 "CmpXchg instructions can only be atomic.");
583 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
587 /// Specify whether this cmpxchg is atomic and orders other operations with
588 /// respect to all concurrently executing threads, or only with respect to
589 /// signal handlers executing in the same thread.
590 void setSynchScope(SynchronizationScope SynchScope) {
591 setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
595 /// Returns the ordering constraint on this cmpxchg.
596 AtomicOrdering getSuccessOrdering() const {
597 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
600 /// Returns the ordering constraint on this cmpxchg.
601 AtomicOrdering getFailureOrdering() const {
602 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
605 /// Returns whether this cmpxchg is atomic between threads or only within a
607 SynchronizationScope getSynchScope() const {
608 return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
611 Value *getPointerOperand() { return getOperand(0); }
612 const Value *getPointerOperand() const { return getOperand(0); }
613 static unsigned getPointerOperandIndex() { return 0U; }
615 Value *getCompareOperand() { return getOperand(1); }
616 const Value *getCompareOperand() const { return getOperand(1); }
618 Value *getNewValOperand() { return getOperand(2); }
619 const Value *getNewValOperand() const { return getOperand(2); }
621 /// \brief Returns the address space of the pointer operand.
622 unsigned getPointerAddressSpace() const {
623 return getPointerOperand()->getType()->getPointerAddressSpace();
626 /// \brief Returns the strongest permitted ordering on failure, given the
627 /// desired ordering on success.
629 /// If the comparison in a cmpxchg operation fails, there is no atomic store
630 /// so release semantics cannot be provided. So this function drops explicit
631 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
632 /// operation would remain SequentiallyConsistent.
633 static AtomicOrdering
634 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
635 switch (SuccessOrdering) {
636 default: llvm_unreachable("invalid cmpxchg success ordering");
643 case SequentiallyConsistent:
644 return SequentiallyConsistent;
648 // Methods for support type inquiry through isa, cast, and dyn_cast:
649 static inline bool classof(const Instruction *I) {
650 return I->getOpcode() == Instruction::AtomicCmpXchg;
652 static inline bool classof(const Value *V) {
653 return isa<Instruction>(V) && classof(cast<Instruction>(V));
657 // Shadow Instruction::setInstructionSubclassData with a private forwarding
658 // method so that subclasses cannot accidentally use it.
659 void setInstructionSubclassData(unsigned short D) {
660 Instruction::setInstructionSubclassData(D);
665 struct OperandTraits<AtomicCmpXchgInst> :
666 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
669 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
671 //===----------------------------------------------------------------------===//
672 // AtomicRMWInst Class
673 //===----------------------------------------------------------------------===//
675 /// AtomicRMWInst - an instruction that atomically reads a memory location,
676 /// combines it with another value, and then stores the result back. Returns
679 class AtomicRMWInst : public Instruction {
680 void *operator new(size_t, unsigned) = delete;
683 // Note: Instruction needs to be a friend here to call cloneImpl.
684 friend class Instruction;
685 AtomicRMWInst *cloneImpl() const;
688 /// This enumeration lists the possible modifications atomicrmw can make. In
689 /// the descriptions, 'p' is the pointer to the instruction's memory location,
690 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
691 /// instruction. These instructions always return 'old'.
707 /// *p = old >signed v ? old : v
709 /// *p = old <signed v ? old : v
711 /// *p = old >unsigned v ? old : v
713 /// *p = old <unsigned v ? old : v
721 // allocate space for exactly two operands
722 void *operator new(size_t s) {
723 return User::operator new(s, 2);
725 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
726 AtomicOrdering Ordering, SynchronizationScope SynchScope,
727 Instruction *InsertBefore = nullptr);
728 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
729 AtomicOrdering Ordering, SynchronizationScope SynchScope,
730 BasicBlock *InsertAtEnd);
732 BinOp getOperation() const {
733 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
736 void setOperation(BinOp Operation) {
737 unsigned short SubclassData = getSubclassDataFromInstruction();
738 setInstructionSubclassData((SubclassData & 31) |
742 /// isVolatile - Return true if this is a RMW on a volatile memory location.
744 bool isVolatile() const {
745 return getSubclassDataFromInstruction() & 1;
748 /// setVolatile - Specify whether this is a volatile RMW or not.
750 void setVolatile(bool V) {
751 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
755 /// Transparently provide more efficient getOperand methods.
756 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
758 /// Set the ordering constraint on this RMW.
759 void setOrdering(AtomicOrdering Ordering) {
760 assert(Ordering != NotAtomic &&
761 "atomicrmw instructions can only be atomic.");
762 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
766 /// Specify whether this RMW orders other operations with respect to all
767 /// concurrently executing threads, or only with respect to signal handlers
768 /// executing in the same thread.
769 void setSynchScope(SynchronizationScope SynchScope) {
770 setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
774 /// Returns the ordering constraint on this RMW.
775 AtomicOrdering getOrdering() const {
776 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
779 /// Returns whether this RMW is atomic between threads or only within a
781 SynchronizationScope getSynchScope() const {
782 return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
785 Value *getPointerOperand() { return getOperand(0); }
786 const Value *getPointerOperand() const { return getOperand(0); }
787 static unsigned getPointerOperandIndex() { return 0U; }
789 Value *getValOperand() { return getOperand(1); }
790 const Value *getValOperand() const { return getOperand(1); }
792 /// \brief Returns the address space of the pointer operand.
793 unsigned getPointerAddressSpace() const {
794 return getPointerOperand()->getType()->getPointerAddressSpace();
797 // Methods for support type inquiry through isa, cast, and dyn_cast:
798 static inline bool classof(const Instruction *I) {
799 return I->getOpcode() == Instruction::AtomicRMW;
801 static inline bool classof(const Value *V) {
802 return isa<Instruction>(V) && classof(cast<Instruction>(V));
806 void Init(BinOp Operation, Value *Ptr, Value *Val,
807 AtomicOrdering Ordering, SynchronizationScope SynchScope);
808 // Shadow Instruction::setInstructionSubclassData with a private forwarding
809 // method so that subclasses cannot accidentally use it.
810 void setInstructionSubclassData(unsigned short D) {
811 Instruction::setInstructionSubclassData(D);
816 struct OperandTraits<AtomicRMWInst>
817 : public FixedNumOperandTraits<AtomicRMWInst,2> {
820 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
822 //===----------------------------------------------------------------------===//
823 // GetElementPtrInst Class
824 //===----------------------------------------------------------------------===//
826 // checkGEPType - Simple wrapper function to give a better assertion failure
827 // message on bad indexes for a gep instruction.
829 inline Type *checkGEPType(Type *Ty) {
830 assert(Ty && "Invalid GetElementPtrInst indices for type!");
834 /// GetElementPtrInst - an instruction for type-safe pointer arithmetic to
835 /// access elements of arrays and structs
837 class GetElementPtrInst : public Instruction {
838 Type *SourceElementType;
839 Type *ResultElementType;
841 GetElementPtrInst(const GetElementPtrInst &GEPI);
842 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
844 /// Constructors - Create a getelementptr instruction with a base pointer an
845 /// list of indices. The first ctor can optionally insert before an existing
846 /// instruction, the second appends the new instruction to the specified
848 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
849 ArrayRef<Value *> IdxList, unsigned Values,
850 const Twine &NameStr, Instruction *InsertBefore);
851 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
852 ArrayRef<Value *> IdxList, unsigned Values,
853 const Twine &NameStr, BasicBlock *InsertAtEnd);
856 // Note: Instruction needs to be a friend here to call cloneImpl.
857 friend class Instruction;
858 GetElementPtrInst *cloneImpl() const;
861 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
862 ArrayRef<Value *> IdxList,
863 const Twine &NameStr = "",
864 Instruction *InsertBefore = nullptr) {
865 unsigned Values = 1 + unsigned(IdxList.size());
868 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
872 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
873 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
874 NameStr, InsertBefore);
876 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
877 ArrayRef<Value *> IdxList,
878 const Twine &NameStr,
879 BasicBlock *InsertAtEnd) {
880 unsigned Values = 1 + unsigned(IdxList.size());
883 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
887 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
888 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
889 NameStr, InsertAtEnd);
892 /// Create an "inbounds" getelementptr. See the documentation for the
893 /// "inbounds" flag in LangRef.html for details.
894 static GetElementPtrInst *CreateInBounds(Value *Ptr,
895 ArrayRef<Value *> IdxList,
896 const Twine &NameStr = "",
897 Instruction *InsertBefore = nullptr){
898 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
900 static GetElementPtrInst *
901 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
902 const Twine &NameStr = "",
903 Instruction *InsertBefore = nullptr) {
904 GetElementPtrInst *GEP =
905 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
906 GEP->setIsInBounds(true);
909 static GetElementPtrInst *CreateInBounds(Value *Ptr,
910 ArrayRef<Value *> IdxList,
911 const Twine &NameStr,
912 BasicBlock *InsertAtEnd) {
913 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
915 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
916 ArrayRef<Value *> IdxList,
917 const Twine &NameStr,
918 BasicBlock *InsertAtEnd) {
919 GetElementPtrInst *GEP =
920 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
921 GEP->setIsInBounds(true);
925 /// Transparently provide more efficient getOperand methods.
926 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
928 // getType - Overload to return most specific sequential type.
929 SequentialType *getType() const {
930 return cast<SequentialType>(Instruction::getType());
933 Type *getSourceElementType() const { return SourceElementType; }
935 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
936 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
938 Type *getResultElementType() const {
939 assert(ResultElementType ==
940 cast<PointerType>(getType()->getScalarType())->getElementType());
941 return ResultElementType;
944 /// \brief Returns the address space of this instruction's pointer type.
945 unsigned getAddressSpace() const {
946 // Note that this is always the same as the pointer operand's address space
947 // and that is cheaper to compute, so cheat here.
948 return getPointerAddressSpace();
951 /// getIndexedType - Returns the type of the element that would be loaded with
952 /// a load instruction with the specified parameters.
954 /// Null is returned if the indices are invalid for the specified
957 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
958 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
959 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
961 inline op_iterator idx_begin() { return op_begin()+1; }
962 inline const_op_iterator idx_begin() const { return op_begin()+1; }
963 inline op_iterator idx_end() { return op_end(); }
964 inline const_op_iterator idx_end() const { return op_end(); }
966 Value *getPointerOperand() {
967 return getOperand(0);
969 const Value *getPointerOperand() const {
970 return getOperand(0);
972 static unsigned getPointerOperandIndex() {
973 return 0U; // get index for modifying correct operand.
976 /// getPointerOperandType - Method to return the pointer operand as a
978 Type *getPointerOperandType() const {
979 return getPointerOperand()->getType();
982 /// \brief Returns the address space of the pointer operand.
983 unsigned getPointerAddressSpace() const {
984 return getPointerOperandType()->getPointerAddressSpace();
987 /// GetGEPReturnType - Returns the pointer type returned by the GEP
988 /// instruction, which may be a vector of pointers.
989 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
990 return getGEPReturnType(
991 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
994 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
995 ArrayRef<Value *> IdxList) {
996 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
997 Ptr->getType()->getPointerAddressSpace());
999 if (Ptr->getType()->isVectorTy()) {
1000 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1001 return VectorType::get(PtrTy, NumElem);
1003 for (Value *Index : IdxList)
1004 if (Index->getType()->isVectorTy()) {
1005 unsigned NumElem = Index->getType()->getVectorNumElements();
1006 return VectorType::get(PtrTy, NumElem);
1012 unsigned getNumIndices() const { // Note: always non-negative
1013 return getNumOperands() - 1;
1016 bool hasIndices() const {
1017 return getNumOperands() > 1;
1020 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1021 /// zeros. If so, the result pointer and the first operand have the same
1022 /// value, just potentially different types.
1023 bool hasAllZeroIndices() const;
1025 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1026 /// constant integers. If so, the result pointer and the first operand have
1027 /// a constant offset between them.
1028 bool hasAllConstantIndices() const;
1030 /// setIsInBounds - Set or clear the inbounds flag on this GEP instruction.
1031 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1032 void setIsInBounds(bool b = true);
1034 /// isInBounds - Determine whether the GEP has the inbounds flag.
1035 bool isInBounds() const;
1037 /// \brief Accumulate the constant address offset of this GEP if possible.
1039 /// This routine accepts an APInt into which it will accumulate the constant
1040 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1041 /// all-constant, it returns false and the value of the offset APInt is
1042 /// undefined (it is *not* preserved!). The APInt passed into this routine
1043 /// must be at least as wide as the IntPtr type for the address space of
1044 /// the base GEP pointer.
1045 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1047 // Methods for support type inquiry through isa, cast, and dyn_cast:
1048 static inline bool classof(const Instruction *I) {
1049 return (I->getOpcode() == Instruction::GetElementPtr);
1051 static inline bool classof(const Value *V) {
1052 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1057 struct OperandTraits<GetElementPtrInst> :
1058 public VariadicOperandTraits<GetElementPtrInst, 1> {
1061 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1062 ArrayRef<Value *> IdxList, unsigned Values,
1063 const Twine &NameStr,
1064 Instruction *InsertBefore)
1065 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1066 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1067 Values, InsertBefore),
1068 SourceElementType(PointeeType),
1069 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1070 assert(ResultElementType ==
1071 cast<PointerType>(getType()->getScalarType())->getElementType());
1072 init(Ptr, IdxList, NameStr);
1074 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1075 ArrayRef<Value *> IdxList, unsigned Values,
1076 const Twine &NameStr,
1077 BasicBlock *InsertAtEnd)
1078 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1079 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1080 Values, InsertAtEnd),
1081 SourceElementType(PointeeType),
1082 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1083 assert(ResultElementType ==
1084 cast<PointerType>(getType()->getScalarType())->getElementType());
1085 init(Ptr, IdxList, NameStr);
1088 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1090 //===----------------------------------------------------------------------===//
1092 //===----------------------------------------------------------------------===//
1094 /// This instruction compares its operands according to the predicate given
1095 /// to the constructor. It only operates on integers or pointers. The operands
1096 /// must be identical types.
1097 /// \brief Represent an integer comparison operator.
1098 class ICmpInst: public CmpInst {
1100 assert(getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1101 getPredicate() <= CmpInst::LAST_ICMP_PREDICATE &&
1102 "Invalid ICmp predicate value");
1103 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1104 "Both operands to ICmp instruction are not of the same type!");
1105 // Check that the operands are the right type
1106 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1107 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1108 "Invalid operand types for ICmp instruction");
1112 // Note: Instruction needs to be a friend here to call cloneImpl.
1113 friend class Instruction;
1114 /// \brief Clone an identical ICmpInst
1115 ICmpInst *cloneImpl() const;
1118 /// \brief Constructor with insert-before-instruction semantics.
1120 Instruction *InsertBefore, ///< Where to insert
1121 Predicate pred, ///< The predicate to use for the comparison
1122 Value *LHS, ///< The left-hand-side of the expression
1123 Value *RHS, ///< The right-hand-side of the expression
1124 const Twine &NameStr = "" ///< Name of the instruction
1125 ) : CmpInst(makeCmpResultType(LHS->getType()),
1126 Instruction::ICmp, pred, LHS, RHS, NameStr,
1133 /// \brief Constructor with insert-at-end semantics.
1135 BasicBlock &InsertAtEnd, ///< Block to insert into.
1136 Predicate pred, ///< The predicate to use for the comparison
1137 Value *LHS, ///< The left-hand-side of the expression
1138 Value *RHS, ///< The right-hand-side of the expression
1139 const Twine &NameStr = "" ///< Name of the instruction
1140 ) : CmpInst(makeCmpResultType(LHS->getType()),
1141 Instruction::ICmp, pred, LHS, RHS, NameStr,
1148 /// \brief Constructor with no-insertion semantics
1150 Predicate pred, ///< The predicate to use for the comparison
1151 Value *LHS, ///< The left-hand-side of the expression
1152 Value *RHS, ///< The right-hand-side of the expression
1153 const Twine &NameStr = "" ///< Name of the instruction
1154 ) : CmpInst(makeCmpResultType(LHS->getType()),
1155 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1161 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1162 /// @returns the predicate that would be the result if the operand were
1163 /// regarded as signed.
1164 /// \brief Return the signed version of the predicate
1165 Predicate getSignedPredicate() const {
1166 return getSignedPredicate(getPredicate());
1169 /// This is a static version that you can use without an instruction.
1170 /// \brief Return the signed version of the predicate.
1171 static Predicate getSignedPredicate(Predicate pred);
1173 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1174 /// @returns the predicate that would be the result if the operand were
1175 /// regarded as unsigned.
1176 /// \brief Return the unsigned version of the predicate
1177 Predicate getUnsignedPredicate() const {
1178 return getUnsignedPredicate(getPredicate());
1181 /// This is a static version that you can use without an instruction.
1182 /// \brief Return the unsigned version of the predicate.
1183 static Predicate getUnsignedPredicate(Predicate pred);
1185 /// isEquality - Return true if this predicate is either EQ or NE. This also
1186 /// tests for commutativity.
1187 static bool isEquality(Predicate P) {
1188 return P == ICMP_EQ || P == ICMP_NE;
1191 /// isEquality - Return true if this predicate is either EQ or NE. This also
1192 /// tests for commutativity.
1193 bool isEquality() const {
1194 return isEquality(getPredicate());
1197 /// @returns true if the predicate of this ICmpInst is commutative
1198 /// \brief Determine if this relation is commutative.
1199 bool isCommutative() const { return isEquality(); }
1201 /// isRelational - Return true if the predicate is relational (not EQ or NE).
1203 bool isRelational() const {
1204 return !isEquality();
1207 /// isRelational - Return true if the predicate is relational (not EQ or NE).
1209 static bool isRelational(Predicate P) {
1210 return !isEquality(P);
1213 /// Initialize a set of values that all satisfy the predicate with C.
1214 /// \brief Make a ConstantRange for a relation with a constant value.
1215 static ConstantRange makeConstantRange(Predicate pred, const APInt &C);
1217 /// Exchange the two operands to this instruction in such a way that it does
1218 /// not modify the semantics of the instruction. The predicate value may be
1219 /// changed to retain the same result if the predicate is order dependent
1221 /// \brief Swap operands and adjust predicate.
1222 void swapOperands() {
1223 setPredicate(getSwappedPredicate());
1224 Op<0>().swap(Op<1>());
1227 // Methods for support type inquiry through isa, cast, and dyn_cast:
1228 static inline bool classof(const Instruction *I) {
1229 return I->getOpcode() == Instruction::ICmp;
1231 static inline bool classof(const Value *V) {
1232 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1236 //===----------------------------------------------------------------------===//
1238 //===----------------------------------------------------------------------===//
1240 /// This instruction compares its operands according to the predicate given
1241 /// to the constructor. It only operates on floating point values or packed
1242 /// vectors of floating point values. The operands must be identical types.
1243 /// \brief Represents a floating point comparison operator.
1244 class FCmpInst: public CmpInst {
1246 // Note: Instruction needs to be a friend here to call cloneImpl.
1247 friend class Instruction;
1248 /// \brief Clone an identical FCmpInst
1249 FCmpInst *cloneImpl() const;
1252 /// \brief Constructor with insert-before-instruction semantics.
1254 Instruction *InsertBefore, ///< Where to insert
1255 Predicate pred, ///< The predicate to use for the comparison
1256 Value *LHS, ///< The left-hand-side of the expression
1257 Value *RHS, ///< The right-hand-side of the expression
1258 const Twine &NameStr = "" ///< Name of the instruction
1259 ) : CmpInst(makeCmpResultType(LHS->getType()),
1260 Instruction::FCmp, pred, LHS, RHS, NameStr,
1262 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1263 "Invalid FCmp predicate value");
1264 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1265 "Both operands to FCmp instruction are not of the same type!");
1266 // Check that the operands are the right type
1267 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1268 "Invalid operand types for FCmp instruction");
1271 /// \brief Constructor with insert-at-end semantics.
1273 BasicBlock &InsertAtEnd, ///< Block to insert into.
1274 Predicate pred, ///< The predicate to use for the comparison
1275 Value *LHS, ///< The left-hand-side of the expression
1276 Value *RHS, ///< The right-hand-side of the expression
1277 const Twine &NameStr = "" ///< Name of the instruction
1278 ) : CmpInst(makeCmpResultType(LHS->getType()),
1279 Instruction::FCmp, pred, LHS, RHS, NameStr,
1281 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1282 "Invalid FCmp predicate value");
1283 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1284 "Both operands to FCmp instruction are not of the same type!");
1285 // Check that the operands are the right type
1286 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1287 "Invalid operand types for FCmp instruction");
1290 /// \brief Constructor with no-insertion semantics
1292 Predicate pred, ///< The predicate to use for the comparison
1293 Value *LHS, ///< The left-hand-side of the expression
1294 Value *RHS, ///< The right-hand-side of the expression
1295 const Twine &NameStr = "" ///< Name of the instruction
1296 ) : CmpInst(makeCmpResultType(LHS->getType()),
1297 Instruction::FCmp, pred, LHS, RHS, NameStr) {
1298 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1299 "Invalid FCmp predicate value");
1300 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1301 "Both operands to FCmp instruction are not of the same type!");
1302 // Check that the operands are the right type
1303 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1304 "Invalid operand types for FCmp instruction");
1307 /// @returns true if the predicate of this instruction is EQ or NE.
1308 /// \brief Determine if this is an equality predicate.
1309 static bool isEquality(Predicate Pred) {
1310 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1314 /// @returns true if the predicate of this instruction is EQ or NE.
1315 /// \brief Determine if this is an equality predicate.
1316 bool isEquality() const { return isEquality(getPredicate()); }
1318 /// @returns true if the predicate of this instruction is commutative.
1319 /// \brief Determine if this is a commutative predicate.
1320 bool isCommutative() const {
1321 return isEquality() ||
1322 getPredicate() == FCMP_FALSE ||
1323 getPredicate() == FCMP_TRUE ||
1324 getPredicate() == FCMP_ORD ||
1325 getPredicate() == FCMP_UNO;
1328 /// @returns true if the predicate is relational (not EQ or NE).
1329 /// \brief Determine if this a relational predicate.
1330 bool isRelational() const { return !isEquality(); }
1332 /// Exchange the two operands to this instruction in such a way that it does
1333 /// not modify the semantics of the instruction. The predicate value may be
1334 /// changed to retain the same result if the predicate is order dependent
1336 /// \brief Swap operands and adjust predicate.
1337 void swapOperands() {
1338 setPredicate(getSwappedPredicate());
1339 Op<0>().swap(Op<1>());
1342 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
1343 static inline bool classof(const Instruction *I) {
1344 return I->getOpcode() == Instruction::FCmp;
1346 static inline bool classof(const Value *V) {
1347 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1351 //===----------------------------------------------------------------------===//
1352 /// CallInst - This class represents a function call, abstracting a target
1353 /// machine's calling convention. This class uses low bit of the SubClassData
1354 /// field to indicate whether or not this is a tail call. The rest of the bits
1355 /// hold the calling convention of the call.
1357 class CallInst : public Instruction,
1358 public OperandBundleUser<CallInst, User::op_iterator> {
1359 AttributeSet AttributeList; ///< parameter attributes for call
1361 CallInst(const CallInst &CI);
1362 void init(Value *Func, ArrayRef<Value *> Args,
1363 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
1364 init(cast<FunctionType>(
1365 cast<PointerType>(Func->getType())->getElementType()),
1366 Func, Args, Bundles, NameStr);
1368 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1369 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1370 void init(Value *Func, const Twine &NameStr);
1372 /// Construct a CallInst given a range of arguments.
1373 /// \brief Construct a CallInst from a range of arguments
1374 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1375 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1376 Instruction *InsertBefore);
1377 inline CallInst(Value *Func, ArrayRef<Value *> Args,
1378 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1379 Instruction *InsertBefore)
1380 : CallInst(cast<FunctionType>(
1381 cast<PointerType>(Func->getType())->getElementType()),
1382 Func, Args, Bundles, NameStr, InsertBefore) {}
1384 inline CallInst(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr,
1385 Instruction *InsertBefore)
1386 : CallInst(Func, Args, None, NameStr, InsertBefore) {}
1388 /// Construct a CallInst given a range of arguments.
1389 /// \brief Construct a CallInst from a range of arguments
1390 inline CallInst(Value *Func, ArrayRef<Value *> Args,
1391 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1392 BasicBlock *InsertAtEnd);
1394 explicit CallInst(Value *F, const Twine &NameStr,
1395 Instruction *InsertBefore);
1396 CallInst(Value *F, const Twine &NameStr, BasicBlock *InsertAtEnd);
1398 friend class OperandBundleUser<CallInst, User::op_iterator>;
1399 bool hasDescriptor() const { return HasDescriptor; }
1402 // Note: Instruction needs to be a friend here to call cloneImpl.
1403 friend class Instruction;
1404 CallInst *cloneImpl() const;
1407 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1408 ArrayRef<OperandBundleDef> Bundles = None,
1409 const Twine &NameStr = "",
1410 Instruction *InsertBefore = nullptr) {
1411 return Create(cast<FunctionType>(
1412 cast<PointerType>(Func->getType())->getElementType()),
1413 Func, Args, Bundles, NameStr, InsertBefore);
1415 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1416 const Twine &NameStr,
1417 Instruction *InsertBefore = nullptr) {
1418 return Create(cast<FunctionType>(
1419 cast<PointerType>(Func->getType())->getElementType()),
1420 Func, Args, None, NameStr, InsertBefore);
1422 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1423 const Twine &NameStr,
1424 Instruction *InsertBefore = nullptr) {
1425 return new (unsigned(Args.size() + 1))
1426 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1428 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1429 ArrayRef<OperandBundleDef> Bundles = None,
1430 const Twine &NameStr = "",
1431 Instruction *InsertBefore = nullptr) {
1432 const unsigned TotalOps =
1433 unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1434 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1436 return new (TotalOps, DescriptorBytes)
1437 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1439 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1440 ArrayRef<OperandBundleDef> Bundles,
1441 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1442 const unsigned TotalOps =
1443 unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1444 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1446 return new (TotalOps, DescriptorBytes)
1447 CallInst(Func, Args, Bundles, NameStr, InsertAtEnd);
1449 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1450 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1451 return new (unsigned(Args.size() + 1))
1452 CallInst(Func, Args, None, NameStr, InsertAtEnd);
1454 static CallInst *Create(Value *F, const Twine &NameStr = "",
1455 Instruction *InsertBefore = nullptr) {
1456 return new(1) CallInst(F, NameStr, InsertBefore);
1458 static CallInst *Create(Value *F, const Twine &NameStr,
1459 BasicBlock *InsertAtEnd) {
1460 return new(1) CallInst(F, NameStr, InsertAtEnd);
1462 /// CreateMalloc - Generate the IR for a call to malloc:
1463 /// 1. Compute the malloc call's argument as the specified type's size,
1464 /// possibly multiplied by the array size if the array size is not
1466 /// 2. Call malloc with that argument.
1467 /// 3. Bitcast the result of the malloc call to the specified type.
1468 static Instruction *CreateMalloc(Instruction *InsertBefore,
1469 Type *IntPtrTy, Type *AllocTy,
1470 Value *AllocSize, Value *ArraySize = nullptr,
1471 Function* MallocF = nullptr,
1472 const Twine &Name = "");
1473 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1474 Type *IntPtrTy, Type *AllocTy,
1475 Value *AllocSize, Value *ArraySize = nullptr,
1476 Function* MallocF = nullptr,
1477 const Twine &Name = "");
1478 /// CreateFree - Generate the IR for a call to the builtin free function.
1479 static Instruction* CreateFree(Value* Source, Instruction *InsertBefore);
1480 static Instruction* CreateFree(Value* Source, BasicBlock *InsertAtEnd);
1482 ~CallInst() override;
1484 FunctionType *getFunctionType() const { return FTy; }
1486 void mutateFunctionType(FunctionType *FTy) {
1487 mutateType(FTy->getReturnType());
1491 // Note that 'musttail' implies 'tail'.
1492 enum TailCallKind { TCK_None = 0, TCK_Tail = 1, TCK_MustTail = 2 };
1493 TailCallKind getTailCallKind() const {
1494 return TailCallKind(getSubclassDataFromInstruction() & 3);
1496 bool isTailCall() const {
1497 return (getSubclassDataFromInstruction() & 3) != TCK_None;
1499 bool isMustTailCall() const {
1500 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1502 void setTailCall(bool isTC = true) {
1503 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1504 unsigned(isTC ? TCK_Tail : TCK_None));
1506 void setTailCallKind(TailCallKind TCK) {
1507 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1511 /// Provide fast operand accessors
1512 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1514 /// getNumArgOperands - Return the number of call arguments.
1516 unsigned getNumArgOperands() const {
1517 return getNumOperands() - getNumTotalBundleOperands() - 1;
1520 /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1522 Value *getArgOperand(unsigned i) const {
1523 assert(i < getNumArgOperands() && "Out of bounds!");
1524 return getOperand(i);
1526 void setArgOperand(unsigned i, Value *v) {
1527 assert(i < getNumArgOperands() && "Out of bounds!");
1531 /// arg_operands - iteration adapter for range-for loops.
1532 iterator_range<op_iterator> arg_operands() {
1533 // The last operand in the op list is the callee - it's not one of the args
1534 // so we don't want to iterate over it.
1535 return iterator_range<op_iterator>(
1536 op_begin(), op_end() - getNumTotalBundleOperands() - 1);
1539 /// arg_operands - iteration adapter for range-for loops.
1540 iterator_range<const_op_iterator> arg_operands() const {
1541 return iterator_range<const_op_iterator>(
1542 op_begin(), op_end() - getNumTotalBundleOperands() - 1);
1545 /// \brief Wrappers for getting the \c Use of a call argument.
1546 const Use &getArgOperandUse(unsigned i) const {
1547 assert(i < getNumArgOperands() && "Out of bounds!");
1548 return getOperandUse(i);
1550 Use &getArgOperandUse(unsigned i) {
1551 assert(i < getNumArgOperands() && "Out of bounds!");
1552 return getOperandUse(i);
1555 /// getCallingConv/setCallingConv - Get or set the calling convention of this
1557 CallingConv::ID getCallingConv() const {
1558 return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1560 void setCallingConv(CallingConv::ID CC) {
1561 auto ID = static_cast<unsigned>(CC);
1562 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1563 setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1567 /// getAttributes - Return the parameter attributes for this call.
1569 const AttributeSet &getAttributes() const { return AttributeList; }
1571 /// setAttributes - Set the parameter attributes for this call.
1573 void setAttributes(const AttributeSet &Attrs) { AttributeList = Attrs; }
1575 /// addAttribute - adds the attribute to the list of attributes.
1576 void addAttribute(unsigned i, Attribute::AttrKind attr);
1578 /// addAttribute - adds the attribute to the list of attributes.
1579 void addAttribute(unsigned i, StringRef Kind, StringRef Value);
1581 /// removeAttribute - removes the attribute from the list of attributes.
1582 void removeAttribute(unsigned i, Attribute attr);
1584 /// \brief adds the dereferenceable attribute to the list of attributes.
1585 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
1587 /// \brief adds the dereferenceable_or_null attribute to the list of
1589 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
1591 /// \brief Determine whether this call has the given attribute.
1592 bool hasFnAttr(Attribute::AttrKind A) const {
1593 assert(A != Attribute::NoBuiltin &&
1594 "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
1595 return hasFnAttrImpl(A);
1598 /// \brief Determine whether this call has the given attribute.
1599 bool hasFnAttr(StringRef A) const {
1600 return hasFnAttrImpl(A);
1603 /// \brief Determine whether the call or the callee has the given attributes.
1604 bool paramHasAttr(unsigned i, Attribute::AttrKind A) const;
1606 /// \brief Extract the alignment for a call or parameter (0=unknown).
1607 unsigned getParamAlignment(unsigned i) const {
1608 return AttributeList.getParamAlignment(i);
1611 /// \brief Extract the number of dereferenceable bytes for a call or
1612 /// parameter (0=unknown).
1613 uint64_t getDereferenceableBytes(unsigned i) const {
1614 return AttributeList.getDereferenceableBytes(i);
1617 /// \brief Extract the number of dereferenceable_or_null bytes for a call or
1618 /// parameter (0=unknown).
1619 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1620 return AttributeList.getDereferenceableOrNullBytes(i);
1623 /// @brief Determine if the parameter or return value is marked with NoAlias
1625 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
1626 bool doesNotAlias(unsigned n) const {
1627 return AttributeList.hasAttribute(n, Attribute::NoAlias);
1630 /// \brief Return true if the call should not be treated as a call to a
1632 bool isNoBuiltin() const {
1633 return hasFnAttrImpl(Attribute::NoBuiltin) &&
1634 !hasFnAttrImpl(Attribute::Builtin);
1637 /// \brief Return true if the call should not be inlined.
1638 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1639 void setIsNoInline() {
1640 addAttribute(AttributeSet::FunctionIndex, Attribute::NoInline);
1643 /// \brief Return true if the call can return twice
1644 bool canReturnTwice() const {
1645 return hasFnAttr(Attribute::ReturnsTwice);
1647 void setCanReturnTwice() {
1648 addAttribute(AttributeSet::FunctionIndex, Attribute::ReturnsTwice);
1651 /// \brief Determine if the call does not access memory.
1652 bool doesNotAccessMemory() const {
1653 return hasFnAttr(Attribute::ReadNone);
1655 void setDoesNotAccessMemory() {
1656 addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
1659 /// \brief Determine if the call does not access or only reads memory.
1660 bool onlyReadsMemory() const {
1661 return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1663 void setOnlyReadsMemory() {
1664 addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
1667 /// @brief Determine if the call can access memmory only using pointers based
1668 /// on its arguments.
1669 bool onlyAccessesArgMemory() const {
1670 return hasFnAttr(Attribute::ArgMemOnly);
1672 void setOnlyAccessesArgMemory() {
1673 addAttribute(AttributeSet::FunctionIndex, Attribute::ArgMemOnly);
1676 /// \brief Determine if the call cannot return.
1677 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1678 void setDoesNotReturn() {
1679 addAttribute(AttributeSet::FunctionIndex, Attribute::NoReturn);
1682 /// \brief Determine if the call cannot unwind.
1683 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1684 void setDoesNotThrow() {
1685 addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
1688 /// \brief Determine if the call cannot be duplicated.
1689 bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1690 void setCannotDuplicate() {
1691 addAttribute(AttributeSet::FunctionIndex, Attribute::NoDuplicate);
1694 /// \brief Determine if the call is convergent
1695 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1696 void setConvergent() {
1697 addAttribute(AttributeSet::FunctionIndex, Attribute::Convergent);
1700 /// \brief Determine if the call returns a structure through first
1701 /// pointer argument.
1702 bool hasStructRetAttr() const {
1703 // Be friendly and also check the callee.
1704 return paramHasAttr(1, Attribute::StructRet);
1707 /// \brief Determine if any call argument is an aggregate passed by value.
1708 bool hasByValArgument() const {
1709 return AttributeList.hasAttrSomewhere(Attribute::ByVal);
1712 /// getCalledFunction - Return the function called, or null if this is an
1713 /// indirect function invocation.
1715 Function *getCalledFunction() const {
1716 return dyn_cast<Function>(Op<-1>());
1719 /// getCalledValue - Get a pointer to the function that is invoked by this
1721 const Value *getCalledValue() const { return Op<-1>(); }
1722 Value *getCalledValue() { return Op<-1>(); }
1724 /// setCalledFunction - Set the function called.
1725 void setCalledFunction(Value* Fn) {
1727 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1730 void setCalledFunction(FunctionType *FTy, Value *Fn) {
1732 assert(FTy == cast<FunctionType>(
1733 cast<PointerType>(Fn->getType())->getElementType()));
1737 /// isInlineAsm - Check if this call is an inline asm statement.
1738 bool isInlineAsm() const {
1739 return isa<InlineAsm>(Op<-1>());
1742 // Methods for support type inquiry through isa, cast, and dyn_cast:
1743 static inline bool classof(const Instruction *I) {
1744 return I->getOpcode() == Instruction::Call;
1746 static inline bool classof(const Value *V) {
1747 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1751 template <typename AttrKind> bool hasFnAttrImpl(AttrKind A) const {
1752 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
1755 // Operand bundles override attributes on the called function, but don't
1756 // override attributes directly present on the call instruction.
1757 if (isFnAttrDisallowedByOpBundle(A))
1760 if (const Function *F = getCalledFunction())
1761 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
1765 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1766 // method so that subclasses cannot accidentally use it.
1767 void setInstructionSubclassData(unsigned short D) {
1768 Instruction::setInstructionSubclassData(D);
1773 struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1776 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1777 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1778 BasicBlock *InsertAtEnd)
1780 cast<FunctionType>(cast<PointerType>(Func->getType())
1781 ->getElementType())->getReturnType(),
1782 Instruction::Call, OperandTraits<CallInst>::op_end(this) -
1783 (Args.size() + CountBundleInputs(Bundles) + 1),
1784 unsigned(Args.size() + CountBundleInputs(Bundles) + 1), InsertAtEnd) {
1785 init(Func, Args, Bundles, NameStr);
1788 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1789 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1790 Instruction *InsertBefore)
1791 : Instruction(Ty->getReturnType(), Instruction::Call,
1792 OperandTraits<CallInst>::op_end(this) -
1793 (Args.size() + CountBundleInputs(Bundles) + 1),
1794 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1796 init(Ty, Func, Args, Bundles, NameStr);
1799 // Note: if you get compile errors about private methods then
1800 // please update your code to use the high-level operand
1801 // interfaces. See line 943 above.
1802 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
1804 //===----------------------------------------------------------------------===//
1806 //===----------------------------------------------------------------------===//
1808 /// SelectInst - This class represents the LLVM 'select' instruction.
1810 class SelectInst : public Instruction {
1811 void init(Value *C, Value *S1, Value *S2) {
1812 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1818 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1819 Instruction *InsertBefore)
1820 : Instruction(S1->getType(), Instruction::Select,
1821 &Op<0>(), 3, InsertBefore) {
1825 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1826 BasicBlock *InsertAtEnd)
1827 : Instruction(S1->getType(), Instruction::Select,
1828 &Op<0>(), 3, InsertAtEnd) {
1834 // Note: Instruction needs to be a friend here to call cloneImpl.
1835 friend class Instruction;
1836 SelectInst *cloneImpl() const;
1839 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1840 const Twine &NameStr = "",
1841 Instruction *InsertBefore = nullptr) {
1842 return new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1844 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1845 const Twine &NameStr,
1846 BasicBlock *InsertAtEnd) {
1847 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1850 const Value *getCondition() const { return Op<0>(); }
1851 const Value *getTrueValue() const { return Op<1>(); }
1852 const Value *getFalseValue() const { return Op<2>(); }
1853 Value *getCondition() { return Op<0>(); }
1854 Value *getTrueValue() { return Op<1>(); }
1855 Value *getFalseValue() { return Op<2>(); }
1857 /// areInvalidOperands - Return a string if the specified operands are invalid
1858 /// for a select operation, otherwise return null.
1859 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1861 /// Transparently provide more efficient getOperand methods.
1862 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1864 OtherOps getOpcode() const {
1865 return static_cast<OtherOps>(Instruction::getOpcode());
1868 // Methods for support type inquiry through isa, cast, and dyn_cast:
1869 static inline bool classof(const Instruction *I) {
1870 return I->getOpcode() == Instruction::Select;
1872 static inline bool classof(const Value *V) {
1873 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1878 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1881 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1883 //===----------------------------------------------------------------------===//
1885 //===----------------------------------------------------------------------===//
1887 /// VAArgInst - This class represents the va_arg llvm instruction, which returns
1888 /// an argument of the specified type given a va_list and increments that list
1890 class VAArgInst : public UnaryInstruction {
1892 // Note: Instruction needs to be a friend here to call cloneImpl.
1893 friend class Instruction;
1894 VAArgInst *cloneImpl() const;
1897 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1898 Instruction *InsertBefore = nullptr)
1899 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1902 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1903 BasicBlock *InsertAtEnd)
1904 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1908 Value *getPointerOperand() { return getOperand(0); }
1909 const Value *getPointerOperand() const { return getOperand(0); }
1910 static unsigned getPointerOperandIndex() { return 0U; }
1912 // Methods for support type inquiry through isa, cast, and dyn_cast:
1913 static inline bool classof(const Instruction *I) {
1914 return I->getOpcode() == VAArg;
1916 static inline bool classof(const Value *V) {
1917 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1921 //===----------------------------------------------------------------------===//
1922 // ExtractElementInst Class
1923 //===----------------------------------------------------------------------===//
1925 /// ExtractElementInst - This instruction extracts a single (scalar)
1926 /// element from a VectorType value
1928 class ExtractElementInst : public Instruction {
1929 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1930 Instruction *InsertBefore = nullptr);
1931 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1932 BasicBlock *InsertAtEnd);
1935 // Note: Instruction needs to be a friend here to call cloneImpl.
1936 friend class Instruction;
1937 ExtractElementInst *cloneImpl() const;
1940 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1941 const Twine &NameStr = "",
1942 Instruction *InsertBefore = nullptr) {
1943 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1945 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1946 const Twine &NameStr,
1947 BasicBlock *InsertAtEnd) {
1948 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1951 /// isValidOperands - Return true if an extractelement instruction can be
1952 /// formed with the specified operands.
1953 static bool isValidOperands(const Value *Vec, const Value *Idx);
1955 Value *getVectorOperand() { return Op<0>(); }
1956 Value *getIndexOperand() { return Op<1>(); }
1957 const Value *getVectorOperand() const { return Op<0>(); }
1958 const Value *getIndexOperand() const { return Op<1>(); }
1960 VectorType *getVectorOperandType() const {
1961 return cast<VectorType>(getVectorOperand()->getType());
1964 /// Transparently provide more efficient getOperand methods.
1965 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1967 // Methods for support type inquiry through isa, cast, and dyn_cast:
1968 static inline bool classof(const Instruction *I) {
1969 return I->getOpcode() == Instruction::ExtractElement;
1971 static inline bool classof(const Value *V) {
1972 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1977 struct OperandTraits<ExtractElementInst> :
1978 public FixedNumOperandTraits<ExtractElementInst, 2> {
1981 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1983 //===----------------------------------------------------------------------===//
1984 // InsertElementInst Class
1985 //===----------------------------------------------------------------------===//
1987 /// InsertElementInst - This instruction inserts a single (scalar)
1988 /// element into a VectorType value
1990 class InsertElementInst : public Instruction {
1991 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1992 const Twine &NameStr = "",
1993 Instruction *InsertBefore = nullptr);
1994 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1995 BasicBlock *InsertAtEnd);
1998 // Note: Instruction needs to be a friend here to call cloneImpl.
1999 friend class Instruction;
2000 InsertElementInst *cloneImpl() const;
2003 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2004 const Twine &NameStr = "",
2005 Instruction *InsertBefore = nullptr) {
2006 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
2008 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2009 const Twine &NameStr,
2010 BasicBlock *InsertAtEnd) {
2011 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
2014 /// isValidOperands - Return true if an insertelement instruction can be
2015 /// formed with the specified operands.
2016 static bool isValidOperands(const Value *Vec, const Value *NewElt,
2019 /// getType - Overload to return most specific vector type.
2021 VectorType *getType() const {
2022 return cast<VectorType>(Instruction::getType());
2025 /// Transparently provide more efficient getOperand methods.
2026 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2028 // Methods for support type inquiry through isa, cast, and dyn_cast:
2029 static inline bool classof(const Instruction *I) {
2030 return I->getOpcode() == Instruction::InsertElement;
2032 static inline bool classof(const Value *V) {
2033 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2038 struct OperandTraits<InsertElementInst> :
2039 public FixedNumOperandTraits<InsertElementInst, 3> {
2042 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2044 //===----------------------------------------------------------------------===//
2045 // ShuffleVectorInst Class
2046 //===----------------------------------------------------------------------===//
2048 /// ShuffleVectorInst - This instruction constructs a fixed permutation of two
2051 class ShuffleVectorInst : public Instruction {
2053 // Note: Instruction needs to be a friend here to call cloneImpl.
2054 friend class Instruction;
2055 ShuffleVectorInst *cloneImpl() const;
2058 // allocate space for exactly three operands
2059 void *operator new(size_t s) {
2060 return User::operator new(s, 3);
2062 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2063 const Twine &NameStr = "",
2064 Instruction *InsertBefor = nullptr);
2065 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2066 const Twine &NameStr, BasicBlock *InsertAtEnd);
2068 /// isValidOperands - Return true if a shufflevector instruction can be
2069 /// formed with the specified operands.
2070 static bool isValidOperands(const Value *V1, const Value *V2,
2073 /// getType - Overload to return most specific vector type.
2075 VectorType *getType() const {
2076 return cast<VectorType>(Instruction::getType());
2079 /// Transparently provide more efficient getOperand methods.
2080 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2082 Constant *getMask() const {
2083 return cast<Constant>(getOperand(2));
2086 /// getMaskValue - Return the index from the shuffle mask for the specified
2087 /// output result. This is either -1 if the element is undef or a number less
2088 /// than 2*numelements.
2089 static int getMaskValue(Constant *Mask, unsigned i);
2091 int getMaskValue(unsigned i) const {
2092 return getMaskValue(getMask(), i);
2095 /// getShuffleMask - Return the full mask for this instruction, where each
2096 /// element is the element number and undef's are returned as -1.
2097 static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
2099 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2100 return getShuffleMask(getMask(), Result);
2103 SmallVector<int, 16> getShuffleMask() const {
2104 SmallVector<int, 16> Mask;
2105 getShuffleMask(Mask);
2109 // Methods for support type inquiry through isa, cast, and dyn_cast:
2110 static inline bool classof(const Instruction *I) {
2111 return I->getOpcode() == Instruction::ShuffleVector;
2113 static inline bool classof(const Value *V) {
2114 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2119 struct OperandTraits<ShuffleVectorInst> :
2120 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2123 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2125 //===----------------------------------------------------------------------===//
2126 // ExtractValueInst Class
2127 //===----------------------------------------------------------------------===//
2129 /// ExtractValueInst - This instruction extracts a struct member or array
2130 /// element value from an aggregate value.
2132 class ExtractValueInst : public UnaryInstruction {
2133 SmallVector<unsigned, 4> Indices;
2135 ExtractValueInst(const ExtractValueInst &EVI);
2136 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2138 /// Constructors - Create a extractvalue instruction with a base aggregate
2139 /// value and a list of indices. The first ctor can optionally insert before
2140 /// an existing instruction, the second appends the new instruction to the
2141 /// specified BasicBlock.
2142 inline ExtractValueInst(Value *Agg,
2143 ArrayRef<unsigned> Idxs,
2144 const Twine &NameStr,
2145 Instruction *InsertBefore);
2146 inline ExtractValueInst(Value *Agg,
2147 ArrayRef<unsigned> Idxs,
2148 const Twine &NameStr, BasicBlock *InsertAtEnd);
2150 // allocate space for exactly one operand
2151 void *operator new(size_t s) { return User::operator new(s, 1); }
2154 // Note: Instruction needs to be a friend here to call cloneImpl.
2155 friend class Instruction;
2156 ExtractValueInst *cloneImpl() const;
2159 static ExtractValueInst *Create(Value *Agg,
2160 ArrayRef<unsigned> Idxs,
2161 const Twine &NameStr = "",
2162 Instruction *InsertBefore = nullptr) {
2164 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2166 static ExtractValueInst *Create(Value *Agg,
2167 ArrayRef<unsigned> Idxs,
2168 const Twine &NameStr,
2169 BasicBlock *InsertAtEnd) {
2170 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2173 /// getIndexedType - Returns the type of the element that would be extracted
2174 /// with an extractvalue instruction with the specified parameters.
2176 /// Null is returned if the indices are invalid for the specified type.
2177 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2179 typedef const unsigned* idx_iterator;
2180 inline idx_iterator idx_begin() const { return Indices.begin(); }
2181 inline idx_iterator idx_end() const { return Indices.end(); }
2182 inline iterator_range<idx_iterator> indices() const {
2183 return iterator_range<idx_iterator>(idx_begin(), idx_end());
2186 Value *getAggregateOperand() {
2187 return getOperand(0);
2189 const Value *getAggregateOperand() const {
2190 return getOperand(0);
2192 static unsigned getAggregateOperandIndex() {
2193 return 0U; // get index for modifying correct operand
2196 ArrayRef<unsigned> getIndices() const {
2200 unsigned getNumIndices() const {
2201 return (unsigned)Indices.size();
2204 bool hasIndices() const {
2208 // Methods for support type inquiry through isa, cast, and dyn_cast:
2209 static inline bool classof(const Instruction *I) {
2210 return I->getOpcode() == Instruction::ExtractValue;
2212 static inline bool classof(const Value *V) {
2213 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2217 ExtractValueInst::ExtractValueInst(Value *Agg,
2218 ArrayRef<unsigned> Idxs,
2219 const Twine &NameStr,
2220 Instruction *InsertBefore)
2221 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2222 ExtractValue, Agg, InsertBefore) {
2223 init(Idxs, NameStr);
2225 ExtractValueInst::ExtractValueInst(Value *Agg,
2226 ArrayRef<unsigned> Idxs,
2227 const Twine &NameStr,
2228 BasicBlock *InsertAtEnd)
2229 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2230 ExtractValue, Agg, InsertAtEnd) {
2231 init(Idxs, NameStr);
2234 //===----------------------------------------------------------------------===//
2235 // InsertValueInst Class
2236 //===----------------------------------------------------------------------===//
2238 /// InsertValueInst - This instruction inserts a struct field of array element
2239 /// value into an aggregate value.
2241 class InsertValueInst : public Instruction {
2242 SmallVector<unsigned, 4> Indices;
2244 void *operator new(size_t, unsigned) = delete;
2245 InsertValueInst(const InsertValueInst &IVI);
2246 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2247 const Twine &NameStr);
2249 /// Constructors - Create a insertvalue instruction with a base aggregate
2250 /// value, a value to insert, and a list of indices. The first ctor can
2251 /// optionally insert before an existing instruction, the second appends
2252 /// the new instruction to the specified BasicBlock.
2253 inline InsertValueInst(Value *Agg, Value *Val,
2254 ArrayRef<unsigned> Idxs,
2255 const Twine &NameStr,
2256 Instruction *InsertBefore);
2257 inline InsertValueInst(Value *Agg, Value *Val,
2258 ArrayRef<unsigned> Idxs,
2259 const Twine &NameStr, BasicBlock *InsertAtEnd);
2261 /// Constructors - These two constructors are convenience methods because one
2262 /// and two index insertvalue instructions are so common.
2263 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2264 const Twine &NameStr = "",
2265 Instruction *InsertBefore = nullptr);
2266 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2267 BasicBlock *InsertAtEnd);
2270 // Note: Instruction needs to be a friend here to call cloneImpl.
2271 friend class Instruction;
2272 InsertValueInst *cloneImpl() const;
2275 // allocate space for exactly two operands
2276 void *operator new(size_t s) {
2277 return User::operator new(s, 2);
2280 static InsertValueInst *Create(Value *Agg, Value *Val,
2281 ArrayRef<unsigned> Idxs,
2282 const Twine &NameStr = "",
2283 Instruction *InsertBefore = nullptr) {
2284 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2286 static InsertValueInst *Create(Value *Agg, Value *Val,
2287 ArrayRef<unsigned> Idxs,
2288 const Twine &NameStr,
2289 BasicBlock *InsertAtEnd) {
2290 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2293 /// Transparently provide more efficient getOperand methods.
2294 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2296 typedef const unsigned* idx_iterator;
2297 inline idx_iterator idx_begin() const { return Indices.begin(); }
2298 inline idx_iterator idx_end() const { return Indices.end(); }
2299 inline iterator_range<idx_iterator> indices() const {
2300 return iterator_range<idx_iterator>(idx_begin(), idx_end());
2303 Value *getAggregateOperand() {
2304 return getOperand(0);
2306 const Value *getAggregateOperand() const {
2307 return getOperand(0);
2309 static unsigned getAggregateOperandIndex() {
2310 return 0U; // get index for modifying correct operand
2313 Value *getInsertedValueOperand() {
2314 return getOperand(1);
2316 const Value *getInsertedValueOperand() const {
2317 return getOperand(1);
2319 static unsigned getInsertedValueOperandIndex() {
2320 return 1U; // get index for modifying correct operand
2323 ArrayRef<unsigned> getIndices() const {
2327 unsigned getNumIndices() const {
2328 return (unsigned)Indices.size();
2331 bool hasIndices() const {
2335 // Methods for support type inquiry through isa, cast, and dyn_cast:
2336 static inline bool classof(const Instruction *I) {
2337 return I->getOpcode() == Instruction::InsertValue;
2339 static inline bool classof(const Value *V) {
2340 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2345 struct OperandTraits<InsertValueInst> :
2346 public FixedNumOperandTraits<InsertValueInst, 2> {
2349 InsertValueInst::InsertValueInst(Value *Agg,
2351 ArrayRef<unsigned> Idxs,
2352 const Twine &NameStr,
2353 Instruction *InsertBefore)
2354 : Instruction(Agg->getType(), InsertValue,
2355 OperandTraits<InsertValueInst>::op_begin(this),
2357 init(Agg, Val, Idxs, NameStr);
2359 InsertValueInst::InsertValueInst(Value *Agg,
2361 ArrayRef<unsigned> Idxs,
2362 const Twine &NameStr,
2363 BasicBlock *InsertAtEnd)
2364 : Instruction(Agg->getType(), InsertValue,
2365 OperandTraits<InsertValueInst>::op_begin(this),
2367 init(Agg, Val, Idxs, NameStr);
2370 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2372 //===----------------------------------------------------------------------===//
2374 //===----------------------------------------------------------------------===//
2376 // PHINode - The PHINode class is used to represent the magical mystical PHI
2377 // node, that can not exist in nature, but can be synthesized in a computer
2378 // scientist's overactive imagination.
2380 class PHINode : public Instruction {
2381 void *operator new(size_t, unsigned) = delete;
2382 /// ReservedSpace - The number of operands actually allocated. NumOperands is
2383 /// the number actually in use.
2384 unsigned ReservedSpace;
2385 PHINode(const PHINode &PN);
2386 // allocate space for exactly zero operands
2387 void *operator new(size_t s) {
2388 return User::operator new(s);
2390 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2391 const Twine &NameStr = "",
2392 Instruction *InsertBefore = nullptr)
2393 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2394 ReservedSpace(NumReservedValues) {
2396 allocHungoffUses(ReservedSpace);
2399 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2400 BasicBlock *InsertAtEnd)
2401 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2402 ReservedSpace(NumReservedValues) {
2404 allocHungoffUses(ReservedSpace);
2408 // allocHungoffUses - this is more complicated than the generic
2409 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2410 // values and pointers to the incoming blocks, all in one allocation.
2411 void allocHungoffUses(unsigned N) {
2412 User::allocHungoffUses(N, /* IsPhi */ true);
2415 // Note: Instruction needs to be a friend here to call cloneImpl.
2416 friend class Instruction;
2417 PHINode *cloneImpl() const;
2420 /// Constructors - NumReservedValues is a hint for the number of incoming
2421 /// edges that this phi node will have (use 0 if you really have no idea).
2422 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2423 const Twine &NameStr = "",
2424 Instruction *InsertBefore = nullptr) {
2425 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2427 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2428 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2429 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2432 /// Provide fast operand accessors
2433 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2435 // Block iterator interface. This provides access to the list of incoming
2436 // basic blocks, which parallels the list of incoming values.
2438 typedef BasicBlock **block_iterator;
2439 typedef BasicBlock * const *const_block_iterator;
2441 block_iterator block_begin() {
2443 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2444 return reinterpret_cast<block_iterator>(ref + 1);
2447 const_block_iterator block_begin() const {
2448 const Use::UserRef *ref =
2449 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2450 return reinterpret_cast<const_block_iterator>(ref + 1);
2453 block_iterator block_end() {
2454 return block_begin() + getNumOperands();
2457 const_block_iterator block_end() const {
2458 return block_begin() + getNumOperands();
2461 op_range incoming_values() { return operands(); }
2463 const_op_range incoming_values() const { return operands(); }
2465 /// getNumIncomingValues - Return the number of incoming edges
2467 unsigned getNumIncomingValues() const { return getNumOperands(); }
2469 /// getIncomingValue - Return incoming value number x
2471 Value *getIncomingValue(unsigned i) const {
2472 return getOperand(i);
2474 void setIncomingValue(unsigned i, Value *V) {
2475 assert(V && "PHI node got a null value!");
2476 assert(getType() == V->getType() &&
2477 "All operands to PHI node must be the same type as the PHI node!");
2480 static unsigned getOperandNumForIncomingValue(unsigned i) {
2483 static unsigned getIncomingValueNumForOperand(unsigned i) {
2487 /// getIncomingBlock - Return incoming basic block number @p i.
2489 BasicBlock *getIncomingBlock(unsigned i) const {
2490 return block_begin()[i];
2493 /// getIncomingBlock - Return incoming basic block corresponding
2494 /// to an operand of the PHI.
2496 BasicBlock *getIncomingBlock(const Use &U) const {
2497 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2498 return getIncomingBlock(unsigned(&U - op_begin()));
2501 /// getIncomingBlock - Return incoming basic block corresponding
2502 /// to value use iterator.
2504 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2505 return getIncomingBlock(I.getUse());
2508 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2509 assert(BB && "PHI node got a null basic block!");
2510 block_begin()[i] = BB;
2513 /// addIncoming - Add an incoming value to the end of the PHI list
2515 void addIncoming(Value *V, BasicBlock *BB) {
2516 if (getNumOperands() == ReservedSpace)
2517 growOperands(); // Get more space!
2518 // Initialize some new operands.
2519 setNumHungOffUseOperands(getNumOperands() + 1);
2520 setIncomingValue(getNumOperands() - 1, V);
2521 setIncomingBlock(getNumOperands() - 1, BB);
2524 /// removeIncomingValue - Remove an incoming value. This is useful if a
2525 /// predecessor basic block is deleted. The value removed is returned.
2527 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2528 /// is true), the PHI node is destroyed and any uses of it are replaced with
2529 /// dummy values. The only time there should be zero incoming values to a PHI
2530 /// node is when the block is dead, so this strategy is sound.
2532 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2534 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2535 int Idx = getBasicBlockIndex(BB);
2536 assert(Idx >= 0 && "Invalid basic block argument to remove!");
2537 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2540 /// getBasicBlockIndex - Return the first index of the specified basic
2541 /// block in the value list for this PHI. Returns -1 if no instance.
2543 int getBasicBlockIndex(const BasicBlock *BB) const {
2544 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2545 if (block_begin()[i] == BB)
2550 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2551 int Idx = getBasicBlockIndex(BB);
2552 assert(Idx >= 0 && "Invalid basic block argument!");
2553 return getIncomingValue(Idx);
2556 /// hasConstantValue - If the specified PHI node always merges together the
2557 /// same value, return the value, otherwise return null.
2558 Value *hasConstantValue() const;
2560 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2561 static inline bool classof(const Instruction *I) {
2562 return I->getOpcode() == Instruction::PHI;
2564 static inline bool classof(const Value *V) {
2565 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2569 void growOperands();
2573 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2576 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2578 //===----------------------------------------------------------------------===//
2579 // LandingPadInst Class
2580 //===----------------------------------------------------------------------===//
2582 //===---------------------------------------------------------------------------
2583 /// LandingPadInst - The landingpad instruction holds all of the information
2584 /// necessary to generate correct exception handling. The landingpad instruction
2585 /// cannot be moved from the top of a landing pad block, which itself is
2586 /// accessible only from the 'unwind' edge of an invoke. This uses the
2587 /// SubclassData field in Value to store whether or not the landingpad is a
2590 class LandingPadInst : public Instruction {
2591 /// ReservedSpace - The number of operands actually allocated. NumOperands is
2592 /// the number actually in use.
2593 unsigned ReservedSpace;
2594 LandingPadInst(const LandingPadInst &LP);
2597 enum ClauseType { Catch, Filter };
2600 void *operator new(size_t, unsigned) = delete;
2601 // Allocate space for exactly zero operands.
2602 void *operator new(size_t s) {
2603 return User::operator new(s);
2605 void growOperands(unsigned Size);
2606 void init(unsigned NumReservedValues, const Twine &NameStr);
2608 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2609 const Twine &NameStr, Instruction *InsertBefore);
2610 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2611 const Twine &NameStr, BasicBlock *InsertAtEnd);
2614 // Note: Instruction needs to be a friend here to call cloneImpl.
2615 friend class Instruction;
2616 LandingPadInst *cloneImpl() const;
2619 /// Constructors - NumReservedClauses is a hint for the number of incoming
2620 /// clauses that this landingpad will have (use 0 if you really have no idea).
2621 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2622 const Twine &NameStr = "",
2623 Instruction *InsertBefore = nullptr);
2624 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2625 const Twine &NameStr, BasicBlock *InsertAtEnd);
2627 /// Provide fast operand accessors
2628 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2630 /// isCleanup - Return 'true' if this landingpad instruction is a
2631 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2632 /// doesn't catch the exception.
2633 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2635 /// setCleanup - Indicate that this landingpad instruction is a cleanup.
2636 void setCleanup(bool V) {
2637 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2641 /// Add a catch or filter clause to the landing pad.
2642 void addClause(Constant *ClauseVal);
2644 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2645 /// determine what type of clause this is.
2646 Constant *getClause(unsigned Idx) const {
2647 return cast<Constant>(getOperandList()[Idx]);
2650 /// isCatch - Return 'true' if the clause and index Idx is a catch clause.
2651 bool isCatch(unsigned Idx) const {
2652 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2655 /// isFilter - Return 'true' if the clause and index Idx is a filter clause.
2656 bool isFilter(unsigned Idx) const {
2657 return isa<ArrayType>(getOperandList()[Idx]->getType());
2660 /// getNumClauses - Get the number of clauses for this landing pad.
2661 unsigned getNumClauses() const { return getNumOperands(); }
2663 /// reserveClauses - Grow the size of the operand list to accommodate the new
2664 /// number of clauses.
2665 void reserveClauses(unsigned Size) { growOperands(Size); }
2667 // Methods for support type inquiry through isa, cast, and dyn_cast:
2668 static inline bool classof(const Instruction *I) {
2669 return I->getOpcode() == Instruction::LandingPad;
2671 static inline bool classof(const Value *V) {
2672 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2677 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2680 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2682 //===----------------------------------------------------------------------===//
2684 //===----------------------------------------------------------------------===//
2686 //===---------------------------------------------------------------------------
2687 /// ReturnInst - Return a value (possibly void), from a function. Execution
2688 /// does not continue in this function any longer.
2690 class ReturnInst : public TerminatorInst {
2691 ReturnInst(const ReturnInst &RI);
2694 // ReturnInst constructors:
2695 // ReturnInst() - 'ret void' instruction
2696 // ReturnInst( null) - 'ret void' instruction
2697 // ReturnInst(Value* X) - 'ret X' instruction
2698 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2699 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2700 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2701 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2703 // NOTE: If the Value* passed is of type void then the constructor behaves as
2704 // if it was passed NULL.
2705 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2706 Instruction *InsertBefore = nullptr);
2707 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2708 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2711 // Note: Instruction needs to be a friend here to call cloneImpl.
2712 friend class Instruction;
2713 ReturnInst *cloneImpl() const;
2716 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2717 Instruction *InsertBefore = nullptr) {
2718 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2720 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2721 BasicBlock *InsertAtEnd) {
2722 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2724 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2725 return new(0) ReturnInst(C, InsertAtEnd);
2727 ~ReturnInst() override;
2729 /// Provide fast operand accessors
2730 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2732 /// Convenience accessor. Returns null if there is no return value.
2733 Value *getReturnValue() const {
2734 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2737 unsigned getNumSuccessors() const { return 0; }
2739 // Methods for support type inquiry through isa, cast, and dyn_cast:
2740 static inline bool classof(const Instruction *I) {
2741 return (I->getOpcode() == Instruction::Ret);
2743 static inline bool classof(const Value *V) {
2744 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2748 BasicBlock *getSuccessorV(unsigned idx) const override;
2749 unsigned getNumSuccessorsV() const override;
2750 void setSuccessorV(unsigned idx, BasicBlock *B) override;
2754 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2757 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2759 //===----------------------------------------------------------------------===//
2761 //===----------------------------------------------------------------------===//
2763 //===---------------------------------------------------------------------------
2764 /// BranchInst - Conditional or Unconditional Branch instruction.
2766 class BranchInst : public TerminatorInst {
2767 /// Ops list - Branches are strange. The operands are ordered:
2768 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2769 /// they don't have to check for cond/uncond branchness. These are mostly
2770 /// accessed relative from op_end().
2771 BranchInst(const BranchInst &BI);
2773 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2774 // BranchInst(BB *B) - 'br B'
2775 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2776 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2777 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2778 // BranchInst(BB* B, BB *I) - 'br B' insert at end
2779 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2780 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2781 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2782 Instruction *InsertBefore = nullptr);
2783 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2784 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2785 BasicBlock *InsertAtEnd);
2788 // Note: Instruction needs to be a friend here to call cloneImpl.
2789 friend class Instruction;
2790 BranchInst *cloneImpl() const;
2793 static BranchInst *Create(BasicBlock *IfTrue,
2794 Instruction *InsertBefore = nullptr) {
2795 return new(1) BranchInst(IfTrue, InsertBefore);
2797 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2798 Value *Cond, Instruction *InsertBefore = nullptr) {
2799 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
2801 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
2802 return new(1) BranchInst(IfTrue, InsertAtEnd);
2804 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2805 Value *Cond, BasicBlock *InsertAtEnd) {
2806 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
2809 /// Transparently provide more efficient getOperand methods.
2810 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2812 bool isUnconditional() const { return getNumOperands() == 1; }
2813 bool isConditional() const { return getNumOperands() == 3; }
2815 Value *getCondition() const {
2816 assert(isConditional() && "Cannot get condition of an uncond branch!");
2820 void setCondition(Value *V) {
2821 assert(isConditional() && "Cannot set condition of unconditional branch!");
2825 unsigned getNumSuccessors() const { return 1+isConditional(); }
2827 BasicBlock *getSuccessor(unsigned i) const {
2828 assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
2829 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
2832 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
2833 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
2834 *(&Op<-1>() - idx) = NewSucc;
2837 /// \brief Swap the successors of this branch instruction.
2839 /// Swaps the successors of the branch instruction. This also swaps any
2840 /// branch weight metadata associated with the instruction so that it
2841 /// continues to map correctly to each operand.
2842 void swapSuccessors();
2844 // Methods for support type inquiry through isa, cast, and dyn_cast:
2845 static inline bool classof(const Instruction *I) {
2846 return (I->getOpcode() == Instruction::Br);
2848 static inline bool classof(const Value *V) {
2849 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2853 BasicBlock *getSuccessorV(unsigned idx) const override;
2854 unsigned getNumSuccessorsV() const override;
2855 void setSuccessorV(unsigned idx, BasicBlock *B) override;
2859 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
2862 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
2864 //===----------------------------------------------------------------------===//
2866 //===----------------------------------------------------------------------===//
2868 //===---------------------------------------------------------------------------
2869 /// SwitchInst - Multiway switch
2871 class SwitchInst : public TerminatorInst {
2872 void *operator new(size_t, unsigned) = delete;
2873 unsigned ReservedSpace;
2874 // Operand[0] = Value to switch on
2875 // Operand[1] = Default basic block destination
2876 // Operand[2n ] = Value to match
2877 // Operand[2n+1] = BasicBlock to go to on match
2878 SwitchInst(const SwitchInst &SI);
2879 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
2880 void growOperands();
2881 // allocate space for exactly zero operands
2882 void *operator new(size_t s) {
2883 return User::operator new(s);
2885 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2886 /// switch on and a default destination. The number of additional cases can
2887 /// be specified here to make memory allocation more efficient. This
2888 /// constructor can also autoinsert before another instruction.
2889 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2890 Instruction *InsertBefore);
2892 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2893 /// switch on and a default destination. The number of additional cases can
2894 /// be specified here to make memory allocation more efficient. This
2895 /// constructor also autoinserts at the end of the specified BasicBlock.
2896 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2897 BasicBlock *InsertAtEnd);
2900 // Note: Instruction needs to be a friend here to call cloneImpl.
2901 friend class Instruction;
2902 SwitchInst *cloneImpl() const;
2906 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
2908 template <class SwitchInstTy, class ConstantIntTy, class BasicBlockTy>
2909 class CaseIteratorT {
2915 typedef CaseIteratorT<SwitchInstTy, ConstantIntTy, BasicBlockTy> Self;
2917 /// Initializes case iterator for given SwitchInst and for given
2919 CaseIteratorT(SwitchInstTy *SI, unsigned CaseNum) {
2924 /// Initializes case iterator for given SwitchInst and for given
2925 /// TerminatorInst's successor index.
2926 static Self fromSuccessorIndex(SwitchInstTy *SI, unsigned SuccessorIndex) {
2927 assert(SuccessorIndex < SI->getNumSuccessors() &&
2928 "Successor index # out of range!");
2929 return SuccessorIndex != 0 ?
2930 Self(SI, SuccessorIndex - 1) :
2931 Self(SI, DefaultPseudoIndex);
2934 /// Resolves case value for current case.
2935 ConstantIntTy *getCaseValue() {
2936 assert(Index < SI->getNumCases() && "Index out the number of cases.");
2937 return reinterpret_cast<ConstantIntTy*>(SI->getOperand(2 + Index*2));
2940 /// Resolves successor for current case.
2941 BasicBlockTy *getCaseSuccessor() {
2942 assert((Index < SI->getNumCases() ||
2943 Index == DefaultPseudoIndex) &&
2944 "Index out the number of cases.");
2945 return SI->getSuccessor(getSuccessorIndex());
2948 /// Returns number of current case.
2949 unsigned getCaseIndex() const { return Index; }
2951 /// Returns TerminatorInst's successor index for current case successor.
2952 unsigned getSuccessorIndex() const {
2953 assert((Index == DefaultPseudoIndex || Index < SI->getNumCases()) &&
2954 "Index out the number of cases.");
2955 return Index != DefaultPseudoIndex ? Index + 1 : 0;
2959 // Check index correctness after increment.
2960 // Note: Index == getNumCases() means end().
2961 assert(Index+1 <= SI->getNumCases() && "Index out the number of cases.");
2965 Self operator++(int) {
2971 // Check index correctness after decrement.
2972 // Note: Index == getNumCases() means end().
2973 // Also allow "-1" iterator here. That will became valid after ++.
2974 assert((Index == 0 || Index-1 <= SI->getNumCases()) &&
2975 "Index out the number of cases.");
2979 Self operator--(int) {
2984 bool operator==(const Self& RHS) const {
2985 assert(RHS.SI == SI && "Incompatible operators.");
2986 return RHS.Index == Index;
2988 bool operator!=(const Self& RHS) const {
2989 assert(RHS.SI == SI && "Incompatible operators.");
2990 return RHS.Index != Index;
2997 typedef CaseIteratorT<const SwitchInst, const ConstantInt, const BasicBlock>
3000 class CaseIt : public CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> {
3002 typedef CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> ParentTy;
3005 CaseIt(const ParentTy &Src) : ParentTy(Src) {}
3006 CaseIt(SwitchInst *SI, unsigned CaseNum) : ParentTy(SI, CaseNum) {}
3008 /// Sets the new value for current case.
3009 void setValue(ConstantInt *V) {
3010 assert(Index < SI->getNumCases() && "Index out the number of cases.");
3011 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3014 /// Sets the new successor for current case.
3015 void setSuccessor(BasicBlock *S) {
3016 SI->setSuccessor(getSuccessorIndex(), S);
3020 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3022 Instruction *InsertBefore = nullptr) {
3023 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3025 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3026 unsigned NumCases, BasicBlock *InsertAtEnd) {
3027 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3030 /// Provide fast operand accessors
3031 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3033 // Accessor Methods for Switch stmt
3034 Value *getCondition() const { return getOperand(0); }
3035 void setCondition(Value *V) { setOperand(0, V); }
3037 BasicBlock *getDefaultDest() const {
3038 return cast<BasicBlock>(getOperand(1));
3041 void setDefaultDest(BasicBlock *DefaultCase) {
3042 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3045 /// getNumCases - return the number of 'cases' in this switch instruction,
3046 /// except the default case
3047 unsigned getNumCases() const {
3048 return getNumOperands()/2 - 1;
3051 /// Returns a read/write iterator that points to the first
3052 /// case in SwitchInst.
3053 CaseIt case_begin() {
3054 return CaseIt(this, 0);
3056 /// Returns a read-only iterator that points to the first
3057 /// case in the SwitchInst.
3058 ConstCaseIt case_begin() const {
3059 return ConstCaseIt(this, 0);
3062 /// Returns a read/write iterator that points one past the last
3063 /// in the SwitchInst.
3065 return CaseIt(this, getNumCases());
3067 /// Returns a read-only iterator that points one past the last
3068 /// in the SwitchInst.
3069 ConstCaseIt case_end() const {
3070 return ConstCaseIt(this, getNumCases());
3073 /// cases - iteration adapter for range-for loops.
3074 iterator_range<CaseIt> cases() {
3075 return iterator_range<CaseIt>(case_begin(), case_end());
3078 /// cases - iteration adapter for range-for loops.
3079 iterator_range<ConstCaseIt> cases() const {
3080 return iterator_range<ConstCaseIt>(case_begin(), case_end());
3083 /// Returns an iterator that points to the default case.
3084 /// Note: this iterator allows to resolve successor only. Attempt
3085 /// to resolve case value causes an assertion.
3086 /// Also note, that increment and decrement also causes an assertion and
3087 /// makes iterator invalid.
3088 CaseIt case_default() {
3089 return CaseIt(this, DefaultPseudoIndex);
3091 ConstCaseIt case_default() const {
3092 return ConstCaseIt(this, DefaultPseudoIndex);
3095 /// findCaseValue - Search all of the case values for the specified constant.
3096 /// If it is explicitly handled, return the case iterator of it, otherwise
3097 /// return default case iterator to indicate
3098 /// that it is handled by the default handler.
3099 CaseIt findCaseValue(const ConstantInt *C) {
3100 for (CaseIt i = case_begin(), e = case_end(); i != e; ++i)
3101 if (i.getCaseValue() == C)
3103 return case_default();
3105 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3106 for (ConstCaseIt i = case_begin(), e = case_end(); i != e; ++i)
3107 if (i.getCaseValue() == C)
3109 return case_default();
3112 /// findCaseDest - Finds the unique case value for a given successor. Returns
3113 /// null if the successor is not found, not unique, or is the default case.
3114 ConstantInt *findCaseDest(BasicBlock *BB) {
3115 if (BB == getDefaultDest()) return nullptr;
3117 ConstantInt *CI = nullptr;
3118 for (CaseIt i = case_begin(), e = case_end(); i != e; ++i) {
3119 if (i.getCaseSuccessor() == BB) {
3120 if (CI) return nullptr; // Multiple cases lead to BB.
3121 else CI = i.getCaseValue();
3127 /// addCase - Add an entry to the switch instruction...
3129 /// This action invalidates case_end(). Old case_end() iterator will
3130 /// point to the added case.
3131 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3133 /// removeCase - This method removes the specified case and its successor
3134 /// from the switch instruction. Note that this operation may reorder the
3135 /// remaining cases at index idx and above.
3137 /// This action invalidates iterators for all cases following the one removed,
3138 /// including the case_end() iterator.
3139 void removeCase(CaseIt i);
3141 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3142 BasicBlock *getSuccessor(unsigned idx) const {
3143 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3144 return cast<BasicBlock>(getOperand(idx*2+1));
3146 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3147 assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3148 setOperand(idx * 2 + 1, NewSucc);
3151 // Methods for support type inquiry through isa, cast, and dyn_cast:
3152 static inline bool classof(const Instruction *I) {
3153 return I->getOpcode() == Instruction::Switch;
3155 static inline bool classof(const Value *V) {
3156 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3160 BasicBlock *getSuccessorV(unsigned idx) const override;
3161 unsigned getNumSuccessorsV() const override;
3162 void setSuccessorV(unsigned idx, BasicBlock *B) override;
3166 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3169 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3171 //===----------------------------------------------------------------------===//
3172 // IndirectBrInst Class
3173 //===----------------------------------------------------------------------===//
3175 //===---------------------------------------------------------------------------
3176 /// IndirectBrInst - Indirect Branch Instruction.
3178 class IndirectBrInst : public TerminatorInst {
3179 void *operator new(size_t, unsigned) = delete;
3180 unsigned ReservedSpace;
3181 // Operand[0] = Value to switch on
3182 // Operand[1] = Default basic block destination
3183 // Operand[2n ] = Value to match
3184 // Operand[2n+1] = BasicBlock to go to on match
3185 IndirectBrInst(const IndirectBrInst &IBI);
3186 void init(Value *Address, unsigned NumDests);
3187 void growOperands();
3188 // allocate space for exactly zero operands
3189 void *operator new(size_t s) {
3190 return User::operator new(s);
3192 /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
3193 /// Address to jump to. The number of expected destinations can be specified
3194 /// here to make memory allocation more efficient. This constructor can also
3195 /// autoinsert before another instruction.
3196 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3198 /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
3199 /// Address to jump to. The number of expected destinations can be specified
3200 /// here to make memory allocation more efficient. This constructor also
3201 /// autoinserts at the end of the specified BasicBlock.
3202 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3205 // Note: Instruction needs to be a friend here to call cloneImpl.
3206 friend class Instruction;
3207 IndirectBrInst *cloneImpl() const;
3210 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3211 Instruction *InsertBefore = nullptr) {
3212 return new IndirectBrInst(Address, NumDests, InsertBefore);
3214 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3215 BasicBlock *InsertAtEnd) {
3216 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3219 /// Provide fast operand accessors.
3220 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3222 // Accessor Methods for IndirectBrInst instruction.
3223 Value *getAddress() { return getOperand(0); }
3224 const Value *getAddress() const { return getOperand(0); }
3225 void setAddress(Value *V) { setOperand(0, V); }
3227 /// getNumDestinations - return the number of possible destinations in this
3228 /// indirectbr instruction.
3229 unsigned getNumDestinations() const { return getNumOperands()-1; }
3231 /// getDestination - Return the specified destination.
3232 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3233 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3235 /// addDestination - Add a destination.
3237 void addDestination(BasicBlock *Dest);
3239 /// removeDestination - This method removes the specified successor from the
3240 /// indirectbr instruction.
3241 void removeDestination(unsigned i);
3243 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3244 BasicBlock *getSuccessor(unsigned i) const {
3245 return cast<BasicBlock>(getOperand(i+1));
3247 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3248 setOperand(i + 1, NewSucc);
3251 // Methods for support type inquiry through isa, cast, and dyn_cast:
3252 static inline bool classof(const Instruction *I) {
3253 return I->getOpcode() == Instruction::IndirectBr;
3255 static inline bool classof(const Value *V) {
3256 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3260 BasicBlock *getSuccessorV(unsigned idx) const override;
3261 unsigned getNumSuccessorsV() const override;
3262 void setSuccessorV(unsigned idx, BasicBlock *B) override;
3266 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3269 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3271 //===----------------------------------------------------------------------===//
3273 //===----------------------------------------------------------------------===//
3275 /// InvokeInst - Invoke instruction. The SubclassData field is used to hold the
3276 /// calling convention of the call.
3278 class InvokeInst : public TerminatorInst,
3279 public OperandBundleUser<InvokeInst, User::op_iterator> {
3280 AttributeSet AttributeList;
3282 InvokeInst(const InvokeInst &BI);
3283 void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3284 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3285 const Twine &NameStr) {
3286 init(cast<FunctionType>(
3287 cast<PointerType>(Func->getType())->getElementType()),
3288 Func, IfNormal, IfException, Args, Bundles, NameStr);
3290 void init(FunctionType *FTy, Value *Func, BasicBlock *IfNormal,
3291 BasicBlock *IfException, ArrayRef<Value *> Args,
3292 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3294 /// Construct an InvokeInst given a range of arguments.
3296 /// \brief Construct an InvokeInst from a range of arguments
3297 inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3298 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3299 unsigned Values, const Twine &NameStr,
3300 Instruction *InsertBefore)
3301 : InvokeInst(cast<FunctionType>(
3302 cast<PointerType>(Func->getType())->getElementType()),
3303 Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3306 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3307 BasicBlock *IfException, ArrayRef<Value *> Args,
3308 ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3309 const Twine &NameStr, Instruction *InsertBefore);
3310 /// Construct an InvokeInst given a range of arguments.
3312 /// \brief Construct an InvokeInst from a range of arguments
3313 inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3314 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3315 unsigned Values, const Twine &NameStr,
3316 BasicBlock *InsertAtEnd);
3318 friend class OperandBundleUser<InvokeInst, User::op_iterator>;
3319 bool hasDescriptor() const { return HasDescriptor; }
3322 // Note: Instruction needs to be a friend here to call cloneImpl.
3323 friend class Instruction;
3324 InvokeInst *cloneImpl() const;
3327 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3328 BasicBlock *IfException, ArrayRef<Value *> Args,
3329 const Twine &NameStr,
3330 Instruction *InsertBefore = nullptr) {
3331 return Create(cast<FunctionType>(
3332 cast<PointerType>(Func->getType())->getElementType()),
3333 Func, IfNormal, IfException, Args, None, NameStr,
3336 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3337 BasicBlock *IfException, ArrayRef<Value *> Args,
3338 ArrayRef<OperandBundleDef> Bundles = None,
3339 const Twine &NameStr = "",
3340 Instruction *InsertBefore = nullptr) {
3341 return Create(cast<FunctionType>(
3342 cast<PointerType>(Func->getType())->getElementType()),
3343 Func, IfNormal, IfException, Args, Bundles, NameStr,
3346 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3347 BasicBlock *IfException, ArrayRef<Value *> Args,
3348 const Twine &NameStr,
3349 Instruction *InsertBefore = nullptr) {
3350 unsigned Values = unsigned(Args.size()) + 3;
3351 return new (Values) InvokeInst(Ty, Func, IfNormal, IfException, Args, None,
3352 Values, NameStr, InsertBefore);
3354 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3355 BasicBlock *IfException, ArrayRef<Value *> Args,
3356 ArrayRef<OperandBundleDef> Bundles = None,
3357 const Twine &NameStr = "",
3358 Instruction *InsertBefore = nullptr) {
3359 unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3360 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3362 return new (Values, DescriptorBytes)
3363 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, Values,
3364 NameStr, InsertBefore);
3366 static InvokeInst *Create(Value *Func,
3367 BasicBlock *IfNormal, BasicBlock *IfException,
3368 ArrayRef<Value *> Args, const Twine &NameStr,
3369 BasicBlock *InsertAtEnd) {
3370 unsigned Values = unsigned(Args.size()) + 3;
3371 return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None,
3372 Values, NameStr, InsertAtEnd);
3374 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3375 BasicBlock *IfException, ArrayRef<Value *> Args,
3376 ArrayRef<OperandBundleDef> Bundles,
3377 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3378 unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3379 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3381 return new (Values, DescriptorBytes)
3382 InvokeInst(Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3386 /// Provide fast operand accessors
3387 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3389 FunctionType *getFunctionType() const { return FTy; }
3391 void mutateFunctionType(FunctionType *FTy) {
3392 mutateType(FTy->getReturnType());
3396 /// getNumArgOperands - Return the number of invoke arguments.
3398 unsigned getNumArgOperands() const {
3399 return getNumOperands() - getNumTotalBundleOperands() - 3;
3402 /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3404 Value *getArgOperand(unsigned i) const {
3405 assert(i < getNumArgOperands() && "Out of bounds!");
3406 return getOperand(i);
3408 void setArgOperand(unsigned i, Value *v) {
3409 assert(i < getNumArgOperands() && "Out of bounds!");
3413 /// arg_operands - iteration adapter for range-for loops.
3414 iterator_range<op_iterator> arg_operands() {
3415 return iterator_range<op_iterator>(
3416 op_begin(), op_end() - getNumTotalBundleOperands() - 3);
3419 /// arg_operands - iteration adapter for range-for loops.
3420 iterator_range<const_op_iterator> arg_operands() const {
3421 return iterator_range<const_op_iterator>(
3422 op_begin(), op_end() - getNumTotalBundleOperands() - 3);
3425 /// \brief Wrappers for getting the \c Use of a invoke argument.
3426 const Use &getArgOperandUse(unsigned i) const {
3427 assert(i < getNumArgOperands() && "Out of bounds!");
3428 return getOperandUse(i);
3430 Use &getArgOperandUse(unsigned i) {
3431 assert(i < getNumArgOperands() && "Out of bounds!");
3432 return getOperandUse(i);
3435 /// getCallingConv/setCallingConv - Get or set the calling convention of this
3437 CallingConv::ID getCallingConv() const {
3438 return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3440 void setCallingConv(CallingConv::ID CC) {
3441 auto ID = static_cast<unsigned>(CC);
3442 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
3443 setInstructionSubclassData(ID);
3446 /// getAttributes - Return the parameter attributes for this invoke.
3448 const AttributeSet &getAttributes() const { return AttributeList; }
3450 /// setAttributes - Set the parameter attributes for this invoke.
3452 void setAttributes(const AttributeSet &Attrs) { AttributeList = Attrs; }
3454 /// addAttribute - adds the attribute to the list of attributes.
3455 void addAttribute(unsigned i, Attribute::AttrKind attr);
3457 /// removeAttribute - removes the attribute from the list of attributes.
3458 void removeAttribute(unsigned i, Attribute attr);
3460 /// \brief adds the dereferenceable attribute to the list of attributes.
3461 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3463 /// \brief adds the dereferenceable_or_null attribute to the list of
3465 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
3467 /// \brief Determine whether this call has the given attribute.
3468 bool hasFnAttr(Attribute::AttrKind A) const {
3469 assert(A != Attribute::NoBuiltin &&
3470 "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");