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/None.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/ADT/iterator.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/InstrTypes.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/OperandTraits.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Use.h"
38 #include "llvm/IR/User.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/Support/AtomicOrdering.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/ErrorHandling.h"
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 /// an instruction to allocate memory on the stack
60 class AllocaInst : public UnaryInstruction {
64 // Note: Instruction needs to be a friend here to call cloneImpl.
65 friend class Instruction;
67 AllocaInst *cloneImpl() const;
70 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
71 Value *ArraySize = nullptr,
72 const Twine &Name = "",
73 Instruction *InsertBefore = nullptr);
74 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
75 const Twine &Name, BasicBlock *InsertAtEnd);
77 AllocaInst(Type *Ty, unsigned AddrSpace,
78 const Twine &Name, Instruction *InsertBefore = nullptr);
79 AllocaInst(Type *Ty, unsigned AddrSpace,
80 const Twine &Name, BasicBlock *InsertAtEnd);
82 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
83 const Twine &Name = "", Instruction *InsertBefore = nullptr);
84 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
85 const Twine &Name, BasicBlock *InsertAtEnd);
87 /// Return true if there is an allocation size parameter to the allocation
88 /// instruction that is not 1.
89 bool isArrayAllocation() const;
91 /// Get the number of elements allocated. For a simple allocation of a single
92 /// element, this will return a constant 1 value.
93 const Value *getArraySize() const { return getOperand(0); }
94 Value *getArraySize() { return getOperand(0); }
96 /// Overload to return most specific pointer type.
97 PointerType *getType() const {
98 return cast<PointerType>(Instruction::getType());
101 /// Get allocation size in bits. Returns None if size can't be determined,
102 /// e.g. in case of a VLA.
103 Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const;
105 /// Return the type that is being allocated by the instruction.
106 Type *getAllocatedType() const { return AllocatedType; }
107 /// for use only in special circumstances that need to generically
108 /// transform a whole instruction (eg: IR linking and vectorization).
109 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
111 /// Return the alignment of the memory that is being allocated by the
113 unsigned getAlignment() const {
114 return (1u << (getSubclassDataFromInstruction() & 31)) >> 1;
116 void setAlignment(unsigned Align);
118 /// Return true if this alloca is in the entry block of the function and is a
119 /// constant size. If so, the code generator will fold it into the
120 /// prolog/epilog code, so it is basically free.
121 bool isStaticAlloca() const;
123 /// Return true if this alloca is used as an inalloca argument to a call. Such
124 /// allocas are never considered static even if they are in the entry block.
125 bool isUsedWithInAlloca() const {
126 return getSubclassDataFromInstruction() & 32;
129 /// Specify whether this alloca is used to represent the arguments to a call.
130 void setUsedWithInAlloca(bool V) {
131 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
135 /// Return true if this alloca is used as a swifterror argument to a call.
136 bool isSwiftError() const {
137 return getSubclassDataFromInstruction() & 64;
140 /// Specify whether this alloca is used to represent a swifterror.
141 void setSwiftError(bool V) {
142 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
146 // Methods for support type inquiry through isa, cast, and dyn_cast:
147 static bool classof(const Instruction *I) {
148 return (I->getOpcode() == Instruction::Alloca);
150 static bool classof(const Value *V) {
151 return isa<Instruction>(V) && classof(cast<Instruction>(V));
155 // Shadow Instruction::setInstructionSubclassData with a private forwarding
156 // method so that subclasses cannot accidentally use it.
157 void setInstructionSubclassData(unsigned short D) {
158 Instruction::setInstructionSubclassData(D);
162 //===----------------------------------------------------------------------===//
164 //===----------------------------------------------------------------------===//
166 /// An instruction for reading from memory. This uses the SubclassData field in
167 /// Value to store whether or not the load is volatile.
168 class LoadInst : public UnaryInstruction {
172 // Note: Instruction needs to be a friend here to call cloneImpl.
173 friend class Instruction;
175 LoadInst *cloneImpl() const;
178 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
179 Instruction *InsertBefore = nullptr);
180 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
181 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
182 Instruction *InsertBefore = nullptr);
183 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
184 BasicBlock *InsertAtEnd);
185 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
186 unsigned Align, Instruction *InsertBefore = nullptr);
187 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
188 unsigned Align, BasicBlock *InsertAtEnd);
189 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
190 unsigned Align, AtomicOrdering Order,
191 SyncScope::ID SSID = SyncScope::System,
192 Instruction *InsertBefore = nullptr);
193 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
194 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
195 BasicBlock *InsertAtEnd);
197 // Deprecated [opaque pointer types]
198 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
199 Instruction *InsertBefore = nullptr)
200 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
202 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
203 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
205 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
206 Instruction *InsertBefore = nullptr)
207 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
208 isVolatile, InsertBefore) {}
209 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
210 BasicBlock *InsertAtEnd)
211 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
212 isVolatile, InsertAtEnd) {}
213 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
214 Instruction *InsertBefore = nullptr)
215 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
216 isVolatile, Align, InsertBefore) {}
217 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
218 BasicBlock *InsertAtEnd)
219 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
220 isVolatile, Align, InsertAtEnd) {}
221 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
222 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
223 Instruction *InsertBefore = nullptr)
224 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
225 isVolatile, Align, Order, SSID, InsertBefore) {}
226 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
227 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
228 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
229 isVolatile, Align, Order, SSID, InsertAtEnd) {}
231 /// Return true if this is a load from a volatile memory location.
232 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
234 /// Specify whether this is a volatile load or not.
235 void setVolatile(bool V) {
236 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
240 /// Return the alignment of the access that is being performed.
241 unsigned getAlignment() const {
242 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
245 void setAlignment(unsigned Align);
247 /// Returns the ordering constraint of this load instruction.
248 AtomicOrdering getOrdering() const {
249 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
252 /// Sets the ordering constraint of this load instruction. May not be Release
253 /// or AcquireRelease.
254 void setOrdering(AtomicOrdering Ordering) {
255 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
256 ((unsigned)Ordering << 7));
259 /// Returns the synchronization scope ID of this load instruction.
260 SyncScope::ID getSyncScopeID() const {
264 /// Sets the synchronization scope ID of this load instruction.
265 void setSyncScopeID(SyncScope::ID SSID) {
269 /// Sets the ordering constraint and the synchronization scope ID of this load
271 void setAtomic(AtomicOrdering Ordering,
272 SyncScope::ID SSID = SyncScope::System) {
273 setOrdering(Ordering);
274 setSyncScopeID(SSID);
277 bool isSimple() const { return !isAtomic() && !isVolatile(); }
279 bool isUnordered() const {
280 return (getOrdering() == AtomicOrdering::NotAtomic ||
281 getOrdering() == AtomicOrdering::Unordered) &&
285 Value *getPointerOperand() { return getOperand(0); }
286 const Value *getPointerOperand() const { return getOperand(0); }
287 static unsigned getPointerOperandIndex() { return 0U; }
288 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
290 /// Returns the address space of the pointer operand.
291 unsigned getPointerAddressSpace() const {
292 return getPointerOperandType()->getPointerAddressSpace();
295 // Methods for support type inquiry through isa, cast, and dyn_cast:
296 static bool classof(const Instruction *I) {
297 return I->getOpcode() == Instruction::Load;
299 static bool classof(const Value *V) {
300 return isa<Instruction>(V) && classof(cast<Instruction>(V));
304 // Shadow Instruction::setInstructionSubclassData with a private forwarding
305 // method so that subclasses cannot accidentally use it.
306 void setInstructionSubclassData(unsigned short D) {
307 Instruction::setInstructionSubclassData(D);
310 /// The synchronization scope ID of this load instruction. Not quite enough
311 /// room in SubClassData for everything, so synchronization scope ID gets its
316 //===----------------------------------------------------------------------===//
318 //===----------------------------------------------------------------------===//
320 /// An instruction for storing to memory.
321 class StoreInst : public Instruction {
325 // Note: Instruction needs to be a friend here to call cloneImpl.
326 friend class Instruction;
328 StoreInst *cloneImpl() const;
331 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
332 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
333 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
334 Instruction *InsertBefore = nullptr);
335 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
336 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
337 unsigned Align, Instruction *InsertBefore = nullptr);
338 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
339 unsigned Align, BasicBlock *InsertAtEnd);
340 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
341 unsigned Align, AtomicOrdering Order,
342 SyncScope::ID SSID = SyncScope::System,
343 Instruction *InsertBefore = nullptr);
344 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
345 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
346 BasicBlock *InsertAtEnd);
348 // allocate space for exactly two operands
349 void *operator new(size_t s) {
350 return User::operator new(s, 2);
353 /// Return true if this is a store to a volatile memory location.
354 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
356 /// Specify whether this is a volatile store or not.
357 void setVolatile(bool V) {
358 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
362 /// Transparently provide more efficient getOperand methods.
363 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
365 /// Return the alignment of the access that is being performed
366 unsigned getAlignment() const {
367 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
370 void setAlignment(unsigned Align);
372 /// Returns the ordering constraint of this store instruction.
373 AtomicOrdering getOrdering() const {
374 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
377 /// Sets the ordering constraint of this store instruction. May not be
378 /// Acquire or AcquireRelease.
379 void setOrdering(AtomicOrdering Ordering) {
380 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
381 ((unsigned)Ordering << 7));
384 /// Returns the synchronization scope ID of this store instruction.
385 SyncScope::ID getSyncScopeID() const {
389 /// Sets the synchronization scope ID of this store instruction.
390 void setSyncScopeID(SyncScope::ID SSID) {
394 /// Sets the ordering constraint and the synchronization scope ID of this
395 /// store instruction.
396 void setAtomic(AtomicOrdering Ordering,
397 SyncScope::ID SSID = SyncScope::System) {
398 setOrdering(Ordering);
399 setSyncScopeID(SSID);
402 bool isSimple() const { return !isAtomic() && !isVolatile(); }
404 bool isUnordered() const {
405 return (getOrdering() == AtomicOrdering::NotAtomic ||
406 getOrdering() == AtomicOrdering::Unordered) &&
410 Value *getValueOperand() { return getOperand(0); }
411 const Value *getValueOperand() const { return getOperand(0); }
413 Value *getPointerOperand() { return getOperand(1); }
414 const Value *getPointerOperand() const { return getOperand(1); }
415 static unsigned getPointerOperandIndex() { return 1U; }
416 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
418 /// Returns the address space of the pointer operand.
419 unsigned getPointerAddressSpace() const {
420 return getPointerOperandType()->getPointerAddressSpace();
423 // Methods for support type inquiry through isa, cast, and dyn_cast:
424 static bool classof(const Instruction *I) {
425 return I->getOpcode() == Instruction::Store;
427 static bool classof(const Value *V) {
428 return isa<Instruction>(V) && classof(cast<Instruction>(V));
432 // Shadow Instruction::setInstructionSubclassData with a private forwarding
433 // method so that subclasses cannot accidentally use it.
434 void setInstructionSubclassData(unsigned short D) {
435 Instruction::setInstructionSubclassData(D);
438 /// The synchronization scope ID of this store instruction. Not quite enough
439 /// room in SubClassData for everything, so synchronization scope ID gets its
445 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
448 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
450 //===----------------------------------------------------------------------===//
452 //===----------------------------------------------------------------------===//
454 /// An instruction for ordering other memory operations.
455 class FenceInst : public Instruction {
456 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
459 // Note: Instruction needs to be a friend here to call cloneImpl.
460 friend class Instruction;
462 FenceInst *cloneImpl() const;
465 // Ordering may only be Acquire, Release, AcquireRelease, or
466 // SequentiallyConsistent.
467 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
468 SyncScope::ID SSID = SyncScope::System,
469 Instruction *InsertBefore = nullptr);
470 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
471 BasicBlock *InsertAtEnd);
473 // allocate space for exactly zero operands
474 void *operator new(size_t s) {
475 return User::operator new(s, 0);
478 /// Returns the ordering constraint of this fence instruction.
479 AtomicOrdering getOrdering() const {
480 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
483 /// Sets the ordering constraint of this fence instruction. May only be
484 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
485 void setOrdering(AtomicOrdering Ordering) {
486 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
487 ((unsigned)Ordering << 1));
490 /// Returns the synchronization scope ID of this fence instruction.
491 SyncScope::ID getSyncScopeID() const {
495 /// Sets the synchronization scope ID of this fence instruction.
496 void setSyncScopeID(SyncScope::ID SSID) {
500 // Methods for support type inquiry through isa, cast, and dyn_cast:
501 static bool classof(const Instruction *I) {
502 return I->getOpcode() == Instruction::Fence;
504 static bool classof(const Value *V) {
505 return isa<Instruction>(V) && classof(cast<Instruction>(V));
509 // Shadow Instruction::setInstructionSubclassData with a private forwarding
510 // method so that subclasses cannot accidentally use it.
511 void setInstructionSubclassData(unsigned short D) {
512 Instruction::setInstructionSubclassData(D);
515 /// The synchronization scope ID of this fence instruction. Not quite enough
516 /// room in SubClassData for everything, so synchronization scope ID gets its
521 //===----------------------------------------------------------------------===//
522 // AtomicCmpXchgInst Class
523 //===----------------------------------------------------------------------===//
525 /// an instruction that atomically checks whether a
526 /// specified value is in a memory location, and, if it is, stores a new value
527 /// there. Returns the value that was loaded.
529 class AtomicCmpXchgInst : public Instruction {
530 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
531 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
535 // Note: Instruction needs to be a friend here to call cloneImpl.
536 friend class Instruction;
538 AtomicCmpXchgInst *cloneImpl() const;
541 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
542 AtomicOrdering SuccessOrdering,
543 AtomicOrdering FailureOrdering,
544 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
545 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
546 AtomicOrdering SuccessOrdering,
547 AtomicOrdering FailureOrdering,
548 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
550 // allocate space for exactly three operands
551 void *operator new(size_t s) {
552 return User::operator new(s, 3);
555 /// Return true if this is a cmpxchg from a volatile memory
558 bool isVolatile() const {
559 return getSubclassDataFromInstruction() & 1;
562 /// Specify whether this is a volatile cmpxchg.
564 void setVolatile(bool V) {
565 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
569 /// Return true if this cmpxchg may spuriously fail.
570 bool isWeak() const {
571 return getSubclassDataFromInstruction() & 0x100;
574 void setWeak(bool IsWeak) {
575 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
579 /// Transparently provide more efficient getOperand methods.
580 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
582 /// Returns the success ordering constraint of this cmpxchg instruction.
583 AtomicOrdering getSuccessOrdering() const {
584 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
587 /// Sets the success ordering constraint of this cmpxchg instruction.
588 void setSuccessOrdering(AtomicOrdering Ordering) {
589 assert(Ordering != AtomicOrdering::NotAtomic &&
590 "CmpXchg instructions can only be atomic.");
591 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
592 ((unsigned)Ordering << 2));
595 /// Returns the failure ordering constraint of this cmpxchg instruction.
596 AtomicOrdering getFailureOrdering() const {
597 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
600 /// Sets the failure ordering constraint of this cmpxchg instruction.
601 void setFailureOrdering(AtomicOrdering Ordering) {
602 assert(Ordering != AtomicOrdering::NotAtomic &&
603 "CmpXchg instructions can only be atomic.");
604 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
605 ((unsigned)Ordering << 5));
608 /// Returns the synchronization scope ID of this cmpxchg instruction.
609 SyncScope::ID getSyncScopeID() const {
613 /// Sets the synchronization scope ID of this cmpxchg instruction.
614 void setSyncScopeID(SyncScope::ID SSID) {
618 Value *getPointerOperand() { return getOperand(0); }
619 const Value *getPointerOperand() const { return getOperand(0); }
620 static unsigned getPointerOperandIndex() { return 0U; }
622 Value *getCompareOperand() { return getOperand(1); }
623 const Value *getCompareOperand() const { return getOperand(1); }
625 Value *getNewValOperand() { return getOperand(2); }
626 const Value *getNewValOperand() const { return getOperand(2); }
628 /// Returns the address space of the pointer operand.
629 unsigned getPointerAddressSpace() const {
630 return getPointerOperand()->getType()->getPointerAddressSpace();
633 /// Returns the strongest permitted ordering on failure, given the
634 /// desired ordering on success.
636 /// If the comparison in a cmpxchg operation fails, there is no atomic store
637 /// so release semantics cannot be provided. So this function drops explicit
638 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
639 /// operation would remain SequentiallyConsistent.
640 static AtomicOrdering
641 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
642 switch (SuccessOrdering) {
644 llvm_unreachable("invalid cmpxchg success ordering");
645 case AtomicOrdering::Release:
646 case AtomicOrdering::Monotonic:
647 return AtomicOrdering::Monotonic;
648 case AtomicOrdering::AcquireRelease:
649 case AtomicOrdering::Acquire:
650 return AtomicOrdering::Acquire;
651 case AtomicOrdering::SequentiallyConsistent:
652 return AtomicOrdering::SequentiallyConsistent;
656 // Methods for support type inquiry through isa, cast, and dyn_cast:
657 static bool classof(const Instruction *I) {
658 return I->getOpcode() == Instruction::AtomicCmpXchg;
660 static bool classof(const Value *V) {
661 return isa<Instruction>(V) && classof(cast<Instruction>(V));
665 // Shadow Instruction::setInstructionSubclassData with a private forwarding
666 // method so that subclasses cannot accidentally use it.
667 void setInstructionSubclassData(unsigned short D) {
668 Instruction::setInstructionSubclassData(D);
671 /// The synchronization scope ID of this cmpxchg instruction. Not quite
672 /// enough room in SubClassData for everything, so synchronization scope ID
673 /// gets its own field.
678 struct OperandTraits<AtomicCmpXchgInst> :
679 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
682 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
684 //===----------------------------------------------------------------------===//
685 // AtomicRMWInst Class
686 //===----------------------------------------------------------------------===//
688 /// an instruction that atomically reads a memory location,
689 /// combines it with another value, and then stores the result back. Returns
692 class AtomicRMWInst : public Instruction {
694 // Note: Instruction needs to be a friend here to call cloneImpl.
695 friend class Instruction;
697 AtomicRMWInst *cloneImpl() const;
700 /// This enumeration lists the possible modifications atomicrmw can make. In
701 /// the descriptions, 'p' is the pointer to the instruction's memory location,
702 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
703 /// instruction. These instructions always return 'old'.
719 /// *p = old >signed v ? old : v
721 /// *p = old <signed v ? old : v
723 /// *p = old >unsigned v ? old : v
725 /// *p = old <unsigned v ? old : v
733 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
734 AtomicOrdering Ordering, SyncScope::ID SSID,
735 Instruction *InsertBefore = nullptr);
736 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
737 AtomicOrdering Ordering, SyncScope::ID SSID,
738 BasicBlock *InsertAtEnd);
740 // allocate space for exactly two operands
741 void *operator new(size_t s) {
742 return User::operator new(s, 2);
745 BinOp getOperation() const {
746 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
749 static StringRef getOperationName(BinOp Op);
751 void setOperation(BinOp Operation) {
752 unsigned short SubclassData = getSubclassDataFromInstruction();
753 setInstructionSubclassData((SubclassData & 31) |
757 /// Return true if this is a RMW on a volatile memory location.
759 bool isVolatile() const {
760 return getSubclassDataFromInstruction() & 1;
763 /// Specify whether this is a volatile RMW or not.
765 void setVolatile(bool V) {
766 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
770 /// Transparently provide more efficient getOperand methods.
771 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
773 /// Returns the ordering constraint of this rmw instruction.
774 AtomicOrdering getOrdering() const {
775 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
778 /// Sets the ordering constraint of this rmw instruction.
779 void setOrdering(AtomicOrdering Ordering) {
780 assert(Ordering != AtomicOrdering::NotAtomic &&
781 "atomicrmw instructions can only be atomic.");
782 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
783 ((unsigned)Ordering << 2));
786 /// Returns the synchronization scope ID of this rmw instruction.
787 SyncScope::ID getSyncScopeID() const {
791 /// Sets the synchronization scope ID of this rmw instruction.
792 void setSyncScopeID(SyncScope::ID SSID) {
796 Value *getPointerOperand() { return getOperand(0); }
797 const Value *getPointerOperand() const { return getOperand(0); }
798 static unsigned getPointerOperandIndex() { return 0U; }
800 Value *getValOperand() { return getOperand(1); }
801 const Value *getValOperand() const { return getOperand(1); }
803 /// Returns the address space of the pointer operand.
804 unsigned getPointerAddressSpace() const {
805 return getPointerOperand()->getType()->getPointerAddressSpace();
808 // Methods for support type inquiry through isa, cast, and dyn_cast:
809 static bool classof(const Instruction *I) {
810 return I->getOpcode() == Instruction::AtomicRMW;
812 static bool classof(const Value *V) {
813 return isa<Instruction>(V) && classof(cast<Instruction>(V));
817 void Init(BinOp Operation, Value *Ptr, Value *Val,
818 AtomicOrdering Ordering, SyncScope::ID SSID);
820 // Shadow Instruction::setInstructionSubclassData with a private forwarding
821 // method so that subclasses cannot accidentally use it.
822 void setInstructionSubclassData(unsigned short D) {
823 Instruction::setInstructionSubclassData(D);
826 /// The synchronization scope ID of this rmw instruction. Not quite enough
827 /// room in SubClassData for everything, so synchronization scope ID gets its
833 struct OperandTraits<AtomicRMWInst>
834 : public FixedNumOperandTraits<AtomicRMWInst,2> {
837 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
839 //===----------------------------------------------------------------------===//
840 // GetElementPtrInst Class
841 //===----------------------------------------------------------------------===//
843 // checkGEPType - Simple wrapper function to give a better assertion failure
844 // message on bad indexes for a gep instruction.
846 inline Type *checkGEPType(Type *Ty) {
847 assert(Ty && "Invalid GetElementPtrInst indices for type!");
851 /// an instruction for type-safe pointer arithmetic to
852 /// access elements of arrays and structs
854 class GetElementPtrInst : public Instruction {
855 Type *SourceElementType;
856 Type *ResultElementType;
858 GetElementPtrInst(const GetElementPtrInst &GEPI);
860 /// Constructors - Create a getelementptr instruction with a base pointer an
861 /// list of indices. The first ctor can optionally insert before an existing
862 /// instruction, the second appends the new instruction to the specified
864 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
865 ArrayRef<Value *> IdxList, unsigned Values,
866 const Twine &NameStr, Instruction *InsertBefore);
867 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
868 ArrayRef<Value *> IdxList, unsigned Values,
869 const Twine &NameStr, BasicBlock *InsertAtEnd);
871 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
874 // Note: Instruction needs to be a friend here to call cloneImpl.
875 friend class Instruction;
877 GetElementPtrInst *cloneImpl() const;
880 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
881 ArrayRef<Value *> IdxList,
882 const Twine &NameStr = "",
883 Instruction *InsertBefore = nullptr) {
884 unsigned Values = 1 + unsigned(IdxList.size());
887 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
891 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
892 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
893 NameStr, InsertBefore);
896 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
897 ArrayRef<Value *> IdxList,
898 const Twine &NameStr,
899 BasicBlock *InsertAtEnd) {
900 unsigned Values = 1 + unsigned(IdxList.size());
903 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
907 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
908 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
909 NameStr, InsertAtEnd);
912 /// Create an "inbounds" getelementptr. See the documentation for the
913 /// "inbounds" flag in LangRef.html for details.
914 static GetElementPtrInst *CreateInBounds(Value *Ptr,
915 ArrayRef<Value *> IdxList,
916 const Twine &NameStr = "",
917 Instruction *InsertBefore = nullptr){
918 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
921 static GetElementPtrInst *
922 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
923 const Twine &NameStr = "",
924 Instruction *InsertBefore = nullptr) {
925 GetElementPtrInst *GEP =
926 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
927 GEP->setIsInBounds(true);
931 static GetElementPtrInst *CreateInBounds(Value *Ptr,
932 ArrayRef<Value *> IdxList,
933 const Twine &NameStr,
934 BasicBlock *InsertAtEnd) {
935 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
938 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
939 ArrayRef<Value *> IdxList,
940 const Twine &NameStr,
941 BasicBlock *InsertAtEnd) {
942 GetElementPtrInst *GEP =
943 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
944 GEP->setIsInBounds(true);
948 /// Transparently provide more efficient getOperand methods.
949 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
951 Type *getSourceElementType() const { return SourceElementType; }
953 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
954 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
956 Type *getResultElementType() const {
957 assert(ResultElementType ==
958 cast<PointerType>(getType()->getScalarType())->getElementType());
959 return ResultElementType;
962 /// Returns the address space of this instruction's pointer type.
963 unsigned getAddressSpace() const {
964 // Note that this is always the same as the pointer operand's address space
965 // and that is cheaper to compute, so cheat here.
966 return getPointerAddressSpace();
969 /// Returns the type of the element that would be loaded with
970 /// a load instruction with the specified parameters.
972 /// Null is returned if the indices are invalid for the specified
975 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
976 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
977 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
979 inline op_iterator idx_begin() { return op_begin()+1; }
980 inline const_op_iterator idx_begin() const { return op_begin()+1; }
981 inline op_iterator idx_end() { return op_end(); }
982 inline const_op_iterator idx_end() const { return op_end(); }
984 inline iterator_range<op_iterator> indices() {
985 return make_range(idx_begin(), idx_end());
988 inline iterator_range<const_op_iterator> indices() const {
989 return make_range(idx_begin(), idx_end());
992 Value *getPointerOperand() {
993 return getOperand(0);
995 const Value *getPointerOperand() const {
996 return getOperand(0);
998 static unsigned getPointerOperandIndex() {
999 return 0U; // get index for modifying correct operand.
1002 /// Method to return the pointer operand as a
1004 Type *getPointerOperandType() const {
1005 return getPointerOperand()->getType();
1008 /// Returns the address space of the pointer operand.
1009 unsigned getPointerAddressSpace() const {
1010 return getPointerOperandType()->getPointerAddressSpace();
1013 /// Returns the pointer type returned by the GEP
1014 /// instruction, which may be a vector of pointers.
1015 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
1016 return getGEPReturnType(
1017 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1020 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1021 ArrayRef<Value *> IdxList) {
1022 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1023 Ptr->getType()->getPointerAddressSpace());
1025 if (Ptr->getType()->isVectorTy()) {
1026 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1027 return VectorType::get(PtrTy, NumElem);
1029 for (Value *Index : IdxList)
1030 if (Index->getType()->isVectorTy()) {
1031 unsigned NumElem = Index->getType()->getVectorNumElements();
1032 return VectorType::get(PtrTy, NumElem);
1038 unsigned getNumIndices() const { // Note: always non-negative
1039 return getNumOperands() - 1;
1042 bool hasIndices() const {
1043 return getNumOperands() > 1;
1046 /// Return true if all of the indices of this GEP are
1047 /// zeros. If so, the result pointer and the first operand have the same
1048 /// value, just potentially different types.
1049 bool hasAllZeroIndices() const;
1051 /// Return true if all of the indices of this GEP are
1052 /// constant integers. If so, the result pointer and the first operand have
1053 /// a constant offset between them.
1054 bool hasAllConstantIndices() const;
1056 /// Set or clear the inbounds flag on this GEP instruction.
1057 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1058 void setIsInBounds(bool b = true);
1060 /// Determine whether the GEP has the inbounds flag.
1061 bool isInBounds() const;
1063 /// Accumulate the constant address offset of this GEP if possible.
1065 /// This routine accepts an APInt into which it will accumulate the constant
1066 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1067 /// all-constant, it returns false and the value of the offset APInt is
1068 /// undefined (it is *not* preserved!). The APInt passed into this routine
1069 /// must be at least as wide as the IntPtr type for the address space of
1070 /// the base GEP pointer.
1071 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1073 // Methods for support type inquiry through isa, cast, and dyn_cast:
1074 static bool classof(const Instruction *I) {
1075 return (I->getOpcode() == Instruction::GetElementPtr);
1077 static bool classof(const Value *V) {
1078 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1083 struct OperandTraits<GetElementPtrInst> :
1084 public VariadicOperandTraits<GetElementPtrInst, 1> {
1087 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1088 ArrayRef<Value *> IdxList, unsigned Values,
1089 const Twine &NameStr,
1090 Instruction *InsertBefore)
1091 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1092 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1093 Values, InsertBefore),
1094 SourceElementType(PointeeType),
1095 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1096 assert(ResultElementType ==
1097 cast<PointerType>(getType()->getScalarType())->getElementType());
1098 init(Ptr, IdxList, NameStr);
1101 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1102 ArrayRef<Value *> IdxList, unsigned Values,
1103 const Twine &NameStr,
1104 BasicBlock *InsertAtEnd)
1105 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1106 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1107 Values, InsertAtEnd),
1108 SourceElementType(PointeeType),
1109 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1110 assert(ResultElementType ==
1111 cast<PointerType>(getType()->getScalarType())->getElementType());
1112 init(Ptr, IdxList, NameStr);
1115 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1117 //===----------------------------------------------------------------------===//
1118 // UnaryOperator Class
1119 //===----------------------------------------------------------------------===//
1121 /// a unary instruction
1122 class UnaryOperator : public UnaryInstruction {
1126 UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
1127 const Twine &Name, Instruction *InsertBefore);
1128 UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
1129 const Twine &Name, BasicBlock *InsertAtEnd);
1131 // Note: Instruction needs to be a friend here to call cloneImpl.
1132 friend class Instruction;
1134 UnaryOperator *cloneImpl() const;
1138 /// Construct a unary instruction, given the opcode and an operand.
1139 /// Optionally (if InstBefore is specified) insert the instruction
1140 /// into a BasicBlock right before the specified instruction. The specified
1141 /// Instruction is allowed to be a dereferenced end iterator.
1143 static UnaryOperator *Create(UnaryOps Op, Value *S,
1144 const Twine &Name = Twine(),
1145 Instruction *InsertBefore = nullptr);
1147 /// Construct a unary instruction, given the opcode and an operand.
1148 /// Also automatically insert this instruction to the end of the
1149 /// BasicBlock specified.
1151 static UnaryOperator *Create(UnaryOps Op, Value *S,
1153 BasicBlock *InsertAtEnd);
1155 /// These methods just forward to Create, and are useful when you
1156 /// statically know what type of instruction you're going to create. These
1157 /// helpers just save some typing.
1158 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1159 static UnaryInstruction *Create##OPC(Value *V, \
1160 const Twine &Name = "") {\
1161 return Create(Instruction::OPC, V, Name);\
1163 #include "llvm/IR/Instruction.def"
1164 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1165 static UnaryInstruction *Create##OPC(Value *V, \
1166 const Twine &Name, BasicBlock *BB) {\
1167 return Create(Instruction::OPC, V, Name, BB);\
1169 #include "llvm/IR/Instruction.def"
1170 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1171 static UnaryInstruction *Create##OPC(Value *V, \
1172 const Twine &Name, Instruction *I) {\
1173 return Create(Instruction::OPC, V, Name, I);\
1175 #include "llvm/IR/Instruction.def"
1177 UnaryOps getOpcode() const {
1178 return static_cast<UnaryOps>(Instruction::getOpcode());
1182 //===----------------------------------------------------------------------===//
1184 //===----------------------------------------------------------------------===//
1186 /// This instruction compares its operands according to the predicate given
1187 /// to the constructor. It only operates on integers or pointers. The operands
1188 /// must be identical types.
1189 /// Represent an integer comparison operator.
1190 class ICmpInst: public CmpInst {
1192 assert(isIntPredicate() &&
1193 "Invalid ICmp predicate value");
1194 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1195 "Both operands to ICmp instruction are not of the same type!");
1196 // Check that the operands are the right type
1197 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1198 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1199 "Invalid operand types for ICmp instruction");
1203 // Note: Instruction needs to be a friend here to call cloneImpl.
1204 friend class Instruction;
1206 /// Clone an identical ICmpInst
1207 ICmpInst *cloneImpl() const;
1210 /// Constructor with insert-before-instruction semantics.
1212 Instruction *InsertBefore, ///< Where to insert
1213 Predicate pred, ///< The predicate to use for the comparison
1214 Value *LHS, ///< The left-hand-side of the expression
1215 Value *RHS, ///< The right-hand-side of the expression
1216 const Twine &NameStr = "" ///< Name of the instruction
1217 ) : CmpInst(makeCmpResultType(LHS->getType()),
1218 Instruction::ICmp, pred, LHS, RHS, NameStr,
1225 /// Constructor with insert-at-end semantics.
1227 BasicBlock &InsertAtEnd, ///< Block to insert into.
1228 Predicate pred, ///< The predicate to use for the comparison
1229 Value *LHS, ///< The left-hand-side of the expression
1230 Value *RHS, ///< The right-hand-side of the expression
1231 const Twine &NameStr = "" ///< Name of the instruction
1232 ) : CmpInst(makeCmpResultType(LHS->getType()),
1233 Instruction::ICmp, pred, LHS, RHS, NameStr,
1240 /// Constructor with no-insertion semantics
1242 Predicate pred, ///< The predicate to use for the comparison
1243 Value *LHS, ///< The left-hand-side of the expression
1244 Value *RHS, ///< The right-hand-side of the expression
1245 const Twine &NameStr = "" ///< Name of the instruction
1246 ) : CmpInst(makeCmpResultType(LHS->getType()),
1247 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1253 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1254 /// @returns the predicate that would be the result if the operand were
1255 /// regarded as signed.
1256 /// Return the signed version of the predicate
1257 Predicate getSignedPredicate() const {
1258 return getSignedPredicate(getPredicate());
1261 /// This is a static version that you can use without an instruction.
1262 /// Return the signed version of the predicate.
1263 static Predicate getSignedPredicate(Predicate pred);
1265 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1266 /// @returns the predicate that would be the result if the operand were
1267 /// regarded as unsigned.
1268 /// Return the unsigned version of the predicate
1269 Predicate getUnsignedPredicate() const {
1270 return getUnsignedPredicate(getPredicate());
1273 /// This is a static version that you can use without an instruction.
1274 /// Return the unsigned version of the predicate.
1275 static Predicate getUnsignedPredicate(Predicate pred);
1277 /// Return true if this predicate is either EQ or NE. This also
1278 /// tests for commutativity.
1279 static bool isEquality(Predicate P) {
1280 return P == ICMP_EQ || P == ICMP_NE;
1283 /// Return true if this predicate is either EQ or NE. This also
1284 /// tests for commutativity.
1285 bool isEquality() const {
1286 return isEquality(getPredicate());
1289 /// @returns true if the predicate of this ICmpInst is commutative
1290 /// Determine if this relation is commutative.
1291 bool isCommutative() const { return isEquality(); }
1293 /// Return true if the predicate is relational (not EQ or NE).
1295 bool isRelational() const {
1296 return !isEquality();
1299 /// Return true if the predicate is relational (not EQ or NE).
1301 static bool isRelational(Predicate P) {
1302 return !isEquality(P);
1305 /// Exchange the two operands to this instruction in such a way that it does
1306 /// not modify the semantics of the instruction. The predicate value may be
1307 /// changed to retain the same result if the predicate is order dependent
1309 /// Swap operands and adjust predicate.
1310 void swapOperands() {
1311 setPredicate(getSwappedPredicate());
1312 Op<0>().swap(Op<1>());
1315 // Methods for support type inquiry through isa, cast, and dyn_cast:
1316 static bool classof(const Instruction *I) {
1317 return I->getOpcode() == Instruction::ICmp;
1319 static bool classof(const Value *V) {
1320 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1324 //===----------------------------------------------------------------------===//
1326 //===----------------------------------------------------------------------===//
1328 /// This instruction compares its operands according to the predicate given
1329 /// to the constructor. It only operates on floating point values or packed
1330 /// vectors of floating point values. The operands must be identical types.
1331 /// Represents a floating point comparison operator.
1332 class FCmpInst: public CmpInst {
1334 assert(isFPPredicate() && "Invalid FCmp predicate value");
1335 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1336 "Both operands to FCmp instruction are not of the same type!");
1337 // Check that the operands are the right type
1338 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1339 "Invalid operand types for FCmp instruction");
1343 // Note: Instruction needs to be a friend here to call cloneImpl.
1344 friend class Instruction;
1346 /// Clone an identical FCmpInst
1347 FCmpInst *cloneImpl() const;
1350 /// Constructor with insert-before-instruction semantics.
1352 Instruction *InsertBefore, ///< Where to insert
1353 Predicate pred, ///< The predicate to use for the comparison
1354 Value *LHS, ///< The left-hand-side of the expression
1355 Value *RHS, ///< The right-hand-side of the expression
1356 const Twine &NameStr = "" ///< Name of the instruction
1357 ) : CmpInst(makeCmpResultType(LHS->getType()),
1358 Instruction::FCmp, pred, LHS, RHS, NameStr,
1363 /// Constructor with insert-at-end semantics.
1365 BasicBlock &InsertAtEnd, ///< Block to insert into.
1366 Predicate pred, ///< The predicate to use for the comparison
1367 Value *LHS, ///< The left-hand-side of the expression
1368 Value *RHS, ///< The right-hand-side of the expression
1369 const Twine &NameStr = "" ///< Name of the instruction
1370 ) : CmpInst(makeCmpResultType(LHS->getType()),
1371 Instruction::FCmp, pred, LHS, RHS, NameStr,
1376 /// Constructor with no-insertion semantics
1378 Predicate Pred, ///< The predicate to use for the comparison
1379 Value *LHS, ///< The left-hand-side of the expression
1380 Value *RHS, ///< The right-hand-side of the expression
1381 const Twine &NameStr = "", ///< Name of the instruction
1382 Instruction *FlagsSource = nullptr
1383 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1384 RHS, NameStr, nullptr, FlagsSource) {
1388 /// @returns true if the predicate of this instruction is EQ or NE.
1389 /// Determine if this is an equality predicate.
1390 static bool isEquality(Predicate Pred) {
1391 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1395 /// @returns true if the predicate of this instruction is EQ or NE.
1396 /// Determine if this is an equality predicate.
1397 bool isEquality() const { return isEquality(getPredicate()); }
1399 /// @returns true if the predicate of this instruction is commutative.
1400 /// Determine if this is a commutative predicate.
1401 bool isCommutative() const {
1402 return isEquality() ||
1403 getPredicate() == FCMP_FALSE ||
1404 getPredicate() == FCMP_TRUE ||
1405 getPredicate() == FCMP_ORD ||
1406 getPredicate() == FCMP_UNO;
1409 /// @returns true if the predicate is relational (not EQ or NE).
1410 /// Determine if this a relational predicate.
1411 bool isRelational() const { return !isEquality(); }
1413 /// Exchange the two operands to this instruction in such a way that it does
1414 /// not modify the semantics of the instruction. The predicate value may be
1415 /// changed to retain the same result if the predicate is order dependent
1417 /// Swap operands and adjust predicate.
1418 void swapOperands() {
1419 setPredicate(getSwappedPredicate());
1420 Op<0>().swap(Op<1>());
1423 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1424 static bool classof(const Instruction *I) {
1425 return I->getOpcode() == Instruction::FCmp;
1427 static bool classof(const Value *V) {
1428 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1432 //===----------------------------------------------------------------------===//
1433 /// This class represents a function call, abstracting a target
1434 /// machine's calling convention. This class uses low bit of the SubClassData
1435 /// field to indicate whether or not this is a tail call. The rest of the bits
1436 /// hold the calling convention of the call.
1438 class CallInst : public CallBase {
1439 CallInst(const CallInst &CI);
1441 /// Construct a CallInst given a range of arguments.
1442 /// Construct a CallInst from a range of arguments
1443 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1444 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1445 Instruction *InsertBefore);
1447 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1448 const Twine &NameStr, Instruction *InsertBefore)
1449 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1451 /// Construct a CallInst given a range of arguments.
1452 /// Construct a CallInst from a range of arguments
1453 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1454 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1455 BasicBlock *InsertAtEnd);
1457 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1458 Instruction *InsertBefore);
1460 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1461 BasicBlock *InsertAtEnd);
1463 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1464 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1465 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1467 /// Compute the number of operands to allocate.
1468 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1469 // We need one operand for the called function, plus the input operand
1471 return 1 + NumArgs + NumBundleInputs;
1475 // Note: Instruction needs to be a friend here to call cloneImpl.
1476 friend class Instruction;
1478 CallInst *cloneImpl() const;
1481 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1482 Instruction *InsertBefore = nullptr) {
1483 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1486 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1487 const Twine &NameStr,
1488 Instruction *InsertBefore = nullptr) {
1489 return new (ComputeNumOperands(Args.size()))
1490 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1493 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1494 ArrayRef<OperandBundleDef> Bundles = None,
1495 const Twine &NameStr = "",
1496 Instruction *InsertBefore = nullptr) {
1497 const int NumOperands =
1498 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1499 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1501 return new (NumOperands, DescriptorBytes)
1502 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1505 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1506 BasicBlock *InsertAtEnd) {
1507 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1510 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1511 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1512 return new (ComputeNumOperands(Args.size()))
1513 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1516 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1517 ArrayRef<OperandBundleDef> Bundles,
1518 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1519 const int NumOperands =
1520 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1521 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1523 return new (NumOperands, DescriptorBytes)
1524 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1527 static CallInst *Create(Function *Func, const Twine &NameStr = "",
1528 Instruction *InsertBefore = nullptr) {
1529 return Create(Func->getFunctionType(), Func, NameStr, InsertBefore);
1532 static CallInst *Create(Function *Func, ArrayRef<Value *> Args,
1533 const Twine &NameStr = "",
1534 Instruction *InsertBefore = nullptr) {
1535 return Create(Func->getFunctionType(), Func, Args, NameStr, InsertBefore);
1538 static CallInst *Create(Function *Func, const Twine &NameStr,
1539 BasicBlock *InsertAtEnd) {
1540 return Create(Func->getFunctionType(), Func, NameStr, InsertAtEnd);
1543 static CallInst *Create(Function *Func, ArrayRef<Value *> Args,
1544 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1545 return Create(Func->getFunctionType(), Func, Args, NameStr, InsertAtEnd);
1548 // Deprecated [opaque pointer types]
1549 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1550 Instruction *InsertBefore = nullptr) {
1551 return Create(cast<FunctionType>(
1552 cast<PointerType>(Func->getType())->getElementType()),
1553 Func, NameStr, InsertBefore);
1556 // Deprecated [opaque pointer types]
1557 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1558 const Twine &NameStr,
1559 Instruction *InsertBefore = nullptr) {
1560 return Create(cast<FunctionType>(
1561 cast<PointerType>(Func->getType())->getElementType()),
1562 Func, Args, NameStr, InsertBefore);
1565 // Deprecated [opaque pointer types]
1566 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1567 ArrayRef<OperandBundleDef> Bundles = None,
1568 const Twine &NameStr = "",
1569 Instruction *InsertBefore = nullptr) {
1570 return Create(cast<FunctionType>(
1571 cast<PointerType>(Func->getType())->getElementType()),
1572 Func, Args, Bundles, NameStr, InsertBefore);
1575 // Deprecated [opaque pointer types]
1576 static CallInst *Create(Value *Func, const Twine &NameStr,
1577 BasicBlock *InsertAtEnd) {
1578 return Create(cast<FunctionType>(
1579 cast<PointerType>(Func->getType())->getElementType()),
1580 Func, NameStr, InsertAtEnd);
1583 // Deprecated [opaque pointer types]
1584 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1585 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1586 return Create(cast<FunctionType>(
1587 cast<PointerType>(Func->getType())->getElementType()),
1588 Func, Args, NameStr, InsertAtEnd);
1591 // Deprecated [opaque pointer types]
1592 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1593 ArrayRef<OperandBundleDef> Bundles,
1594 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1595 return Create(cast<FunctionType>(
1596 cast<PointerType>(Func->getType())->getElementType()),
1597 Func, Args, Bundles, NameStr, InsertAtEnd);
1600 /// Create a clone of \p CI with a different set of operand bundles and
1601 /// insert it before \p InsertPt.
1603 /// The returned call instruction is identical \p CI in every way except that
1604 /// the operand bundles for the new instruction are set to the operand bundles
1606 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1607 Instruction *InsertPt = nullptr);
1609 /// Generate the IR for a call to malloc:
1610 /// 1. Compute the malloc call's argument as the specified type's size,
1611 /// possibly multiplied by the array size if the array size is not
1613 /// 2. Call malloc with that argument.
1614 /// 3. Bitcast the result of the malloc call to the specified type.
1615 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1616 Type *AllocTy, Value *AllocSize,
1617 Value *ArraySize = nullptr,
1618 Function *MallocF = nullptr,
1619 const Twine &Name = "");
1620 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1621 Type *AllocTy, Value *AllocSize,
1622 Value *ArraySize = nullptr,
1623 Function *MallocF = nullptr,
1624 const Twine &Name = "");
1625 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1626 Type *AllocTy, Value *AllocSize,
1627 Value *ArraySize = nullptr,
1628 ArrayRef<OperandBundleDef> Bundles = None,
1629 Function *MallocF = nullptr,
1630 const Twine &Name = "");
1631 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1632 Type *AllocTy, Value *AllocSize,
1633 Value *ArraySize = nullptr,
1634 ArrayRef<OperandBundleDef> Bundles = None,
1635 Function *MallocF = nullptr,
1636 const Twine &Name = "");
1637 /// Generate the IR for a call to the builtin free function.
1638 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1639 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1640 static Instruction *CreateFree(Value *Source,
1641 ArrayRef<OperandBundleDef> Bundles,
1642 Instruction *InsertBefore);
1643 static Instruction *CreateFree(Value *Source,
1644 ArrayRef<OperandBundleDef> Bundles,
1645 BasicBlock *InsertAtEnd);
1647 // Note that 'musttail' implies 'tail'.
1654 TailCallKind getTailCallKind() const {
1655 return TailCallKind(getSubclassDataFromInstruction() & 3);
1658 bool isTailCall() const {
1659 unsigned Kind = getSubclassDataFromInstruction() & 3;
1660 return Kind == TCK_Tail || Kind == TCK_MustTail;
1663 bool isMustTailCall() const {
1664 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1667 bool isNoTailCall() const {
1668 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1671 void setTailCall(bool isTC = true) {
1672 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1673 unsigned(isTC ? TCK_Tail : TCK_None));
1676 void setTailCallKind(TailCallKind TCK) {
1677 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1681 /// Return true if the call can return twice
1682 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1683 void setCanReturnTwice() {
1684 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1687 /// Check if this call is an inline asm statement.
1688 bool isInlineAsm() const { return isa<InlineAsm>(getCalledOperand()); }
1690 // Methods for support type inquiry through isa, cast, and dyn_cast:
1691 static bool classof(const Instruction *I) {
1692 return I->getOpcode() == Instruction::Call;
1694 static bool classof(const Value *V) {
1695 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1699 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1700 // method so that subclasses cannot accidentally use it.
1701 void setInstructionSubclassData(unsigned short D) {
1702 Instruction::setInstructionSubclassData(D);
1706 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1707 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1708 BasicBlock *InsertAtEnd)
1709 : CallBase(Ty->getReturnType(), Instruction::Call,
1710 OperandTraits<CallBase>::op_end(this) -
1711 (Args.size() + CountBundleInputs(Bundles) + 1),
1712 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1714 init(Ty, Func, Args, Bundles, NameStr);
1717 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1718 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1719 Instruction *InsertBefore)
1720 : CallBase(Ty->getReturnType(), Instruction::Call,
1721 OperandTraits<CallBase>::op_end(this) -
1722 (Args.size() + CountBundleInputs(Bundles) + 1),
1723 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1725 init(Ty, Func, Args, Bundles, NameStr);
1728 //===----------------------------------------------------------------------===//
1730 //===----------------------------------------------------------------------===//
1732 /// This class represents the LLVM 'select' instruction.
1734 class SelectInst : public Instruction {
1735 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1736 Instruction *InsertBefore)
1737 : Instruction(S1->getType(), Instruction::Select,
1738 &Op<0>(), 3, InsertBefore) {
1743 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1744 BasicBlock *InsertAtEnd)
1745 : Instruction(S1->getType(), Instruction::Select,
1746 &Op<0>(), 3, InsertAtEnd) {
1751 void init(Value *C, Value *S1, Value *S2) {
1752 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1759 // Note: Instruction needs to be a friend here to call cloneImpl.
1760 friend class Instruction;
1762 SelectInst *cloneImpl() const;
1765 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1766 const Twine &NameStr = "",
1767 Instruction *InsertBefore = nullptr,
1768 Instruction *MDFrom = nullptr) {
1769 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1771 Sel->copyMetadata(*MDFrom);
1775 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1776 const Twine &NameStr,
1777 BasicBlock *InsertAtEnd) {
1778 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1781 const Value *getCondition() const { return Op<0>(); }
1782 const Value *getTrueValue() const { return Op<1>(); }
1783 const Value *getFalseValue() const { return Op<2>(); }
1784 Value *getCondition() { return Op<0>(); }
1785 Value *getTrueValue() { return Op<1>(); }
1786 Value *getFalseValue() { return Op<2>(); }
1788 void setCondition(Value *V) { Op<0>() = V; }
1789 void setTrueValue(Value *V) { Op<1>() = V; }
1790 void setFalseValue(Value *V) { Op<2>() = V; }
1792 /// Return a string if the specified operands are invalid
1793 /// for a select operation, otherwise return null.
1794 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1796 /// Transparently provide more efficient getOperand methods.
1797 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1799 OtherOps getOpcode() const {
1800 return static_cast<OtherOps>(Instruction::getOpcode());
1803 // Methods for support type inquiry through isa, cast, and dyn_cast:
1804 static bool classof(const Instruction *I) {
1805 return I->getOpcode() == Instruction::Select;
1807 static bool classof(const Value *V) {
1808 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1813 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1816 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1818 //===----------------------------------------------------------------------===//
1820 //===----------------------------------------------------------------------===//
1822 /// This class represents the va_arg llvm instruction, which returns
1823 /// an argument of the specified type given a va_list and increments that list
1825 class VAArgInst : public UnaryInstruction {
1827 // Note: Instruction needs to be a friend here to call cloneImpl.
1828 friend class Instruction;
1830 VAArgInst *cloneImpl() const;
1833 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1834 Instruction *InsertBefore = nullptr)
1835 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1839 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1840 BasicBlock *InsertAtEnd)
1841 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1845 Value *getPointerOperand() { return getOperand(0); }
1846 const Value *getPointerOperand() const { return getOperand(0); }
1847 static unsigned getPointerOperandIndex() { return 0U; }
1849 // Methods for support type inquiry through isa, cast, and dyn_cast:
1850 static bool classof(const Instruction *I) {
1851 return I->getOpcode() == VAArg;
1853 static bool classof(const Value *V) {
1854 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1858 //===----------------------------------------------------------------------===//
1859 // ExtractElementInst Class
1860 //===----------------------------------------------------------------------===//
1862 /// This instruction extracts a single (scalar)
1863 /// element from a VectorType value
1865 class ExtractElementInst : public Instruction {
1866 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1867 Instruction *InsertBefore = nullptr);
1868 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1869 BasicBlock *InsertAtEnd);
1872 // Note: Instruction needs to be a friend here to call cloneImpl.
1873 friend class Instruction;
1875 ExtractElementInst *cloneImpl() const;
1878 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1879 const Twine &NameStr = "",
1880 Instruction *InsertBefore = nullptr) {
1881 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1884 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1885 const Twine &NameStr,
1886 BasicBlock *InsertAtEnd) {
1887 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1890 /// Return true if an extractelement instruction can be
1891 /// formed with the specified operands.
1892 static bool isValidOperands(const Value *Vec, const Value *Idx);
1894 Value *getVectorOperand() { return Op<0>(); }
1895 Value *getIndexOperand() { return Op<1>(); }
1896 const Value *getVectorOperand() const { return Op<0>(); }
1897 const Value *getIndexOperand() const { return Op<1>(); }
1899 VectorType *getVectorOperandType() const {
1900 return cast<VectorType>(getVectorOperand()->getType());
1903 /// Transparently provide more efficient getOperand methods.
1904 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1906 // Methods for support type inquiry through isa, cast, and dyn_cast:
1907 static bool classof(const Instruction *I) {
1908 return I->getOpcode() == Instruction::ExtractElement;
1910 static bool classof(const Value *V) {
1911 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1916 struct OperandTraits<ExtractElementInst> :
1917 public FixedNumOperandTraits<ExtractElementInst, 2> {
1920 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1922 //===----------------------------------------------------------------------===//
1923 // InsertElementInst Class
1924 //===----------------------------------------------------------------------===//
1926 /// This instruction inserts a single (scalar)
1927 /// element into a VectorType value
1929 class InsertElementInst : public Instruction {
1930 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1931 const Twine &NameStr = "",
1932 Instruction *InsertBefore = nullptr);
1933 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1934 BasicBlock *InsertAtEnd);
1937 // Note: Instruction needs to be a friend here to call cloneImpl.
1938 friend class Instruction;
1940 InsertElementInst *cloneImpl() const;
1943 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1944 const Twine &NameStr = "",
1945 Instruction *InsertBefore = nullptr) {
1946 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1949 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1950 const Twine &NameStr,
1951 BasicBlock *InsertAtEnd) {
1952 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1955 /// Return true if an insertelement instruction can be
1956 /// formed with the specified operands.
1957 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1960 /// Overload to return most specific vector type.
1962 VectorType *getType() const {
1963 return cast<VectorType>(Instruction::getType());
1966 /// Transparently provide more efficient getOperand methods.
1967 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1969 // Methods for support type inquiry through isa, cast, and dyn_cast:
1970 static bool classof(const Instruction *I) {
1971 return I->getOpcode() == Instruction::InsertElement;
1973 static bool classof(const Value *V) {
1974 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1979 struct OperandTraits<InsertElementInst> :
1980 public FixedNumOperandTraits<InsertElementInst, 3> {
1983 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
1985 //===----------------------------------------------------------------------===//
1986 // ShuffleVectorInst Class
1987 //===----------------------------------------------------------------------===//
1989 /// This instruction constructs a fixed permutation of two
1992 class ShuffleVectorInst : public Instruction {
1994 // Note: Instruction needs to be a friend here to call cloneImpl.
1995 friend class Instruction;
1997 ShuffleVectorInst *cloneImpl() const;
2000 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2001 const Twine &NameStr = "",
2002 Instruction *InsertBefor = nullptr);
2003 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2004 const Twine &NameStr, BasicBlock *InsertAtEnd);
2006 // allocate space for exactly three operands
2007 void *operator new(size_t s) {
2008 return User::operator new(s, 3);
2011 /// Return true if a shufflevector instruction can be
2012 /// formed with the specified operands.
2013 static bool isValidOperands(const Value *V1, const Value *V2,
2016 /// Overload to return most specific vector type.
2018 VectorType *getType() const {
2019 return cast<VectorType>(Instruction::getType());
2022 /// Transparently provide more efficient getOperand methods.
2023 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2025 Constant *getMask() const {
2026 return cast<Constant>(getOperand(2));
2029 /// Return the shuffle mask value for the specified element of the mask.
2030 /// Return -1 if the element is undef.
2031 static int getMaskValue(const Constant *Mask, unsigned Elt);
2033 /// Return the shuffle mask value of this instruction for the given element
2034 /// index. Return -1 if the element is undef.
2035 int getMaskValue(unsigned Elt) const {
2036 return getMaskValue(getMask(), Elt);
2039 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2040 /// elements of the mask are returned as -1.
2041 static void getShuffleMask(const Constant *Mask,
2042 SmallVectorImpl<int> &Result);
2044 /// Return the mask for this instruction as a vector of integers. Undefined
2045 /// elements of the mask are returned as -1.
2046 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2047 return getShuffleMask(getMask(), Result);
2050 SmallVector<int, 16> getShuffleMask() const {
2051 SmallVector<int, 16> Mask;
2052 getShuffleMask(Mask);
2056 /// Return true if this shuffle returns a vector with a different number of
2057 /// elements than its source vectors.
2058 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2059 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2060 bool changesLength() const {
2061 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2062 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2063 return NumSourceElts != NumMaskElts;
2066 /// Return true if this shuffle returns a vector with a greater number of
2067 /// elements than its source vectors.
2068 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2069 bool increasesLength() const {
2070 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2071 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2072 return NumSourceElts < NumMaskElts;
2075 /// Return true if this shuffle mask chooses elements from exactly one source
2077 /// Example: <7,5,undef,7>
2078 /// This assumes that vector operands are the same length as the mask.
2079 static bool isSingleSourceMask(ArrayRef<int> Mask);
2080 static bool isSingleSourceMask(const Constant *Mask) {
2081 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2082 SmallVector<int, 16> MaskAsInts;
2083 getShuffleMask(Mask, MaskAsInts);
2084 return isSingleSourceMask(MaskAsInts);
2087 /// Return true if this shuffle chooses elements from exactly one source
2088 /// vector without changing the length of that vector.
2089 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2090 /// TODO: Optionally allow length-changing shuffles.
2091 bool isSingleSource() const {
2092 return !changesLength() && isSingleSourceMask(getMask());
2095 /// Return true if this shuffle mask chooses elements from exactly one source
2096 /// vector without lane crossings. A shuffle using this mask is not
2097 /// necessarily a no-op because it may change the number of elements from its
2098 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2099 /// Example: <undef,undef,2,3>
2100 static bool isIdentityMask(ArrayRef<int> Mask);
2101 static bool isIdentityMask(const Constant *Mask) {
2102 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2103 SmallVector<int, 16> MaskAsInts;
2104 getShuffleMask(Mask, MaskAsInts);
2105 return isIdentityMask(MaskAsInts);
2108 /// Return true if this shuffle chooses elements from exactly one source
2109 /// vector without lane crossings and does not change the number of elements
2110 /// from its input vectors.
2111 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2112 bool isIdentity() const {
2113 return !changesLength() && isIdentityMask(getShuffleMask());
2116 /// Return true if this shuffle lengthens exactly one source vector with
2117 /// undefs in the high elements.
2118 bool isIdentityWithPadding() const;
2120 /// Return true if this shuffle extracts the first N elements of exactly one
2122 bool isIdentityWithExtract() const;
2124 /// Return true if this shuffle concatenates its 2 source vectors. This
2125 /// returns false if either input is undefined. In that case, the shuffle is
2126 /// is better classified as an identity with padding operation.
2127 bool isConcat() const;
2129 /// Return true if this shuffle mask chooses elements from its source vectors
2130 /// without lane crossings. A shuffle using this mask would be
2131 /// equivalent to a vector select with a constant condition operand.
2132 /// Example: <4,1,6,undef>
2133 /// This returns false if the mask does not choose from both input vectors.
2134 /// In that case, the shuffle is better classified as an identity shuffle.
2135 /// This assumes that vector operands are the same length as the mask
2136 /// (a length-changing shuffle can never be equivalent to a vector select).
2137 static bool isSelectMask(ArrayRef<int> Mask);
2138 static bool isSelectMask(const Constant *Mask) {
2139 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2140 SmallVector<int, 16> MaskAsInts;
2141 getShuffleMask(Mask, MaskAsInts);
2142 return isSelectMask(MaskAsInts);
2145 /// Return true if this shuffle chooses elements from its source vectors
2146 /// without lane crossings and all operands have the same number of elements.
2147 /// In other words, this shuffle is equivalent to a vector select with a
2148 /// constant condition operand.
2149 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2150 /// This returns false if the mask does not choose from both input vectors.
2151 /// In that case, the shuffle is better classified as an identity shuffle.
2152 /// TODO: Optionally allow length-changing shuffles.
2153 bool isSelect() const {
2154 return !changesLength() && isSelectMask(getMask());
2157 /// Return true if this shuffle mask swaps the order of elements from exactly
2158 /// one source vector.
2159 /// Example: <7,6,undef,4>
2160 /// This assumes that vector operands are the same length as the mask.
2161 static bool isReverseMask(ArrayRef<int> Mask);
2162 static bool isReverseMask(const Constant *Mask) {
2163 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2164 SmallVector<int, 16> MaskAsInts;
2165 getShuffleMask(Mask, MaskAsInts);
2166 return isReverseMask(MaskAsInts);
2169 /// Return true if this shuffle swaps the order of elements from exactly
2170 /// one source vector.
2171 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2172 /// TODO: Optionally allow length-changing shuffles.
2173 bool isReverse() const {
2174 return !changesLength() && isReverseMask(getMask());
2177 /// Return true if this shuffle mask chooses all elements with the same value
2178 /// as the first element of exactly one source vector.
2179 /// Example: <4,undef,undef,4>
2180 /// This assumes that vector operands are the same length as the mask.
2181 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2182 static bool isZeroEltSplatMask(const Constant *Mask) {
2183 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2184 SmallVector<int, 16> MaskAsInts;
2185 getShuffleMask(Mask, MaskAsInts);
2186 return isZeroEltSplatMask(MaskAsInts);
2189 /// Return true if all elements of this shuffle are the same value as the
2190 /// first element of exactly one source vector without changing the length
2192 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2193 /// TODO: Optionally allow length-changing shuffles.
2194 /// TODO: Optionally allow splats from other elements.
2195 bool isZeroEltSplat() const {
2196 return !changesLength() && isZeroEltSplatMask(getMask());
2199 /// Return true if this shuffle mask is a transpose mask.
2200 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2201 /// even- or odd-numbered vector elements from two n-dimensional source
2202 /// vectors and write each result into consecutive elements of an
2203 /// n-dimensional destination vector. Two shuffles are necessary to complete
2204 /// the transpose, one for the even elements and another for the odd elements.
2205 /// This description closely follows how the TRN1 and TRN2 AArch64
2206 /// instructions operate.
2208 /// For example, a simple 2x2 matrix can be transposed with:
2210 /// ; Original matrix
2214 /// ; Transposed matrix
2215 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2216 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2218 /// For matrices having greater than n columns, the resulting nx2 transposed
2219 /// matrix is stored in two result vectors such that one vector contains
2220 /// interleaved elements from all the even-numbered rows and the other vector
2221 /// contains interleaved elements from all the odd-numbered rows. For example,
2222 /// a 2x4 matrix can be transposed with:
2224 /// ; Original matrix
2225 /// m0 = < a, b, c, d >
2226 /// m1 = < e, f, g, h >
2228 /// ; Transposed matrix
2229 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2230 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2231 static bool isTransposeMask(ArrayRef<int> Mask);
2232 static bool isTransposeMask(const Constant *Mask) {
2233 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2234 SmallVector<int, 16> MaskAsInts;
2235 getShuffleMask(Mask, MaskAsInts);
2236 return isTransposeMask(MaskAsInts);
2239 /// Return true if this shuffle transposes the elements of its inputs without
2240 /// changing the length of the vectors. This operation may also be known as a
2241 /// merge or interleave. See the description for isTransposeMask() for the
2242 /// exact specification.
2243 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2244 bool isTranspose() const {
2245 return !changesLength() && isTransposeMask(getMask());
2248 /// Return true if this shuffle mask is an extract subvector mask.
2249 /// A valid extract subvector mask returns a smaller vector from a single
2250 /// source operand. The base extraction index is returned as well.
2251 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2253 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2255 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2256 SmallVector<int, 16> MaskAsInts;
2257 getShuffleMask(Mask, MaskAsInts);
2258 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2261 /// Return true if this shuffle mask is an extract subvector mask.
2262 bool isExtractSubvectorMask(int &Index) const {
2263 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2264 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2267 /// Change values in a shuffle permute mask assuming the two vector operands
2268 /// of length InVecNumElts have swapped position.
2269 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2270 unsigned InVecNumElts) {
2271 for (int &Idx : Mask) {
2274 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2275 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2276 "shufflevector mask index out of range");
2280 // Methods for support type inquiry through isa, cast, and dyn_cast:
2281 static bool classof(const Instruction *I) {
2282 return I->getOpcode() == Instruction::ShuffleVector;
2284 static bool classof(const Value *V) {
2285 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2290 struct OperandTraits<ShuffleVectorInst> :
2291 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2294 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2296 //===----------------------------------------------------------------------===//
2297 // ExtractValueInst Class
2298 //===----------------------------------------------------------------------===//
2300 /// This instruction extracts a struct member or array
2301 /// element value from an aggregate value.
2303 class ExtractValueInst : public UnaryInstruction {
2304 SmallVector<unsigned, 4> Indices;
2306 ExtractValueInst(const ExtractValueInst &EVI);
2308 /// Constructors - Create a extractvalue instruction with a base aggregate
2309 /// value and a list of indices. The first ctor can optionally insert before
2310 /// an existing instruction, the second appends the new instruction to the
2311 /// specified BasicBlock.
2312 inline ExtractValueInst(Value *Agg,
2313 ArrayRef<unsigned> Idxs,
2314 const Twine &NameStr,
2315 Instruction *InsertBefore);
2316 inline ExtractValueInst(Value *Agg,
2317 ArrayRef<unsigned> Idxs,
2318 const Twine &NameStr, BasicBlock *InsertAtEnd);
2320 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2323 // Note: Instruction needs to be a friend here to call cloneImpl.
2324 friend class Instruction;
2326 ExtractValueInst *cloneImpl() const;
2329 static ExtractValueInst *Create(Value *Agg,
2330 ArrayRef<unsigned> Idxs,
2331 const Twine &NameStr = "",
2332 Instruction *InsertBefore = nullptr) {
2334 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2337 static ExtractValueInst *Create(Value *Agg,
2338 ArrayRef<unsigned> Idxs,
2339 const Twine &NameStr,
2340 BasicBlock *InsertAtEnd) {
2341 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2344 /// Returns the type of the element that would be extracted
2345 /// with an extractvalue instruction with the specified parameters.
2347 /// Null is returned if the indices are invalid for the specified type.
2348 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2350 using idx_iterator = const unsigned*;
2352 inline idx_iterator idx_begin() const { return Indices.begin(); }
2353 inline idx_iterator idx_end() const { return Indices.end(); }
2354 inline iterator_range<idx_iterator> indices() const {
2355 return make_range(idx_begin(), idx_end());
2358 Value *getAggregateOperand() {
2359 return getOperand(0);
2361 const Value *getAggregateOperand() const {
2362 return getOperand(0);
2364 static unsigned getAggregateOperandIndex() {
2365 return 0U; // get index for modifying correct operand
2368 ArrayRef<unsigned> getIndices() const {
2372 unsigned getNumIndices() const {
2373 return (unsigned)Indices.size();
2376 bool hasIndices() const {
2380 // Methods for support type inquiry through isa, cast, and dyn_cast:
2381 static bool classof(const Instruction *I) {
2382 return I->getOpcode() == Instruction::ExtractValue;
2384 static bool classof(const Value *V) {
2385 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2389 ExtractValueInst::ExtractValueInst(Value *Agg,
2390 ArrayRef<unsigned> Idxs,
2391 const Twine &NameStr,
2392 Instruction *InsertBefore)
2393 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2394 ExtractValue, Agg, InsertBefore) {
2395 init(Idxs, NameStr);
2398 ExtractValueInst::ExtractValueInst(Value *Agg,
2399 ArrayRef<unsigned> Idxs,
2400 const Twine &NameStr,
2401 BasicBlock *InsertAtEnd)
2402 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2403 ExtractValue, Agg, InsertAtEnd) {
2404 init(Idxs, NameStr);
2407 //===----------------------------------------------------------------------===//
2408 // InsertValueInst Class
2409 //===----------------------------------------------------------------------===//
2411 /// This instruction inserts a struct field of array element
2412 /// value into an aggregate value.
2414 class InsertValueInst : public Instruction {
2415 SmallVector<unsigned, 4> Indices;
2417 InsertValueInst(const InsertValueInst &IVI);
2419 /// Constructors - Create a insertvalue instruction with a base aggregate
2420 /// value, a value to insert, and a list of indices. The first ctor can
2421 /// optionally insert before an existing instruction, the second appends
2422 /// the new instruction to the specified BasicBlock.
2423 inline InsertValueInst(Value *Agg, Value *Val,
2424 ArrayRef<unsigned> Idxs,
2425 const Twine &NameStr,
2426 Instruction *InsertBefore);
2427 inline InsertValueInst(Value *Agg, Value *Val,
2428 ArrayRef<unsigned> Idxs,
2429 const Twine &NameStr, BasicBlock *InsertAtEnd);
2431 /// Constructors - These two constructors are convenience methods because one
2432 /// and two index insertvalue instructions are so common.
2433 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2434 const Twine &NameStr = "",
2435 Instruction *InsertBefore = nullptr);
2436 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2437 BasicBlock *InsertAtEnd);
2439 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2440 const Twine &NameStr);
2443 // Note: Instruction needs to be a friend here to call cloneImpl.
2444 friend class Instruction;
2446 InsertValueInst *cloneImpl() const;
2449 // allocate space for exactly two operands
2450 void *operator new(size_t s) {
2451 return User::operator new(s, 2);
2454 static InsertValueInst *Create(Value *Agg, Value *Val,
2455 ArrayRef<unsigned> Idxs,
2456 const Twine &NameStr = "",
2457 Instruction *InsertBefore = nullptr) {
2458 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2461 static InsertValueInst *Create(Value *Agg, Value *Val,
2462 ArrayRef<unsigned> Idxs,
2463 const Twine &NameStr,
2464 BasicBlock *InsertAtEnd) {
2465 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2468 /// Transparently provide more efficient getOperand methods.
2469 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2471 using idx_iterator = const unsigned*;
2473 inline idx_iterator idx_begin() const { return Indices.begin(); }
2474 inline idx_iterator idx_end() const { return Indices.end(); }
2475 inline iterator_range<idx_iterator> indices() const {
2476 return make_range(idx_begin(), idx_end());
2479 Value *getAggregateOperand() {
2480 return getOperand(0);
2482 const Value *getAggregateOperand() const {
2483 return getOperand(0);
2485 static unsigned getAggregateOperandIndex() {
2486 return 0U; // get index for modifying correct operand
2489 Value *getInsertedValueOperand() {
2490 return getOperand(1);
2492 const Value *getInsertedValueOperand() const {
2493 return getOperand(1);
2495 static unsigned getInsertedValueOperandIndex() {
2496 return 1U; // get index for modifying correct operand
2499 ArrayRef<unsigned> getIndices() const {
2503 unsigned getNumIndices() const {
2504 return (unsigned)Indices.size();
2507 bool hasIndices() const {
2511 // Methods for support type inquiry through isa, cast, and dyn_cast:
2512 static bool classof(const Instruction *I) {
2513 return I->getOpcode() == Instruction::InsertValue;
2515 static bool classof(const Value *V) {
2516 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2521 struct OperandTraits<InsertValueInst> :
2522 public FixedNumOperandTraits<InsertValueInst, 2> {
2525 InsertValueInst::InsertValueInst(Value *Agg,
2527 ArrayRef<unsigned> Idxs,
2528 const Twine &NameStr,
2529 Instruction *InsertBefore)
2530 : Instruction(Agg->getType(), InsertValue,
2531 OperandTraits<InsertValueInst>::op_begin(this),
2533 init(Agg, Val, Idxs, NameStr);
2536 InsertValueInst::InsertValueInst(Value *Agg,
2538 ArrayRef<unsigned> Idxs,
2539 const Twine &NameStr,
2540 BasicBlock *InsertAtEnd)
2541 : Instruction(Agg->getType(), InsertValue,
2542 OperandTraits<InsertValueInst>::op_begin(this),
2544 init(Agg, Val, Idxs, NameStr);
2547 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2549 //===----------------------------------------------------------------------===//
2551 //===----------------------------------------------------------------------===//
2553 // PHINode - The PHINode class is used to represent the magical mystical PHI
2554 // node, that can not exist in nature, but can be synthesized in a computer
2555 // scientist's overactive imagination.
2557 class PHINode : public Instruction {
2558 /// The number of operands actually allocated. NumOperands is
2559 /// the number actually in use.
2560 unsigned ReservedSpace;
2562 PHINode(const PHINode &PN);
2564 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2565 const Twine &NameStr = "",
2566 Instruction *InsertBefore = nullptr)
2567 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2568 ReservedSpace(NumReservedValues) {
2570 allocHungoffUses(ReservedSpace);
2573 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2574 BasicBlock *InsertAtEnd)
2575 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2576 ReservedSpace(NumReservedValues) {
2578 allocHungoffUses(ReservedSpace);
2582 // Note: Instruction needs to be a friend here to call cloneImpl.
2583 friend class Instruction;
2585 PHINode *cloneImpl() const;
2587 // allocHungoffUses - this is more complicated than the generic
2588 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2589 // values and pointers to the incoming blocks, all in one allocation.
2590 void allocHungoffUses(unsigned N) {
2591 User::allocHungoffUses(N, /* IsPhi */ true);
2595 /// Constructors - NumReservedValues is a hint for the number of incoming
2596 /// edges that this phi node will have (use 0 if you really have no idea).
2597 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2598 const Twine &NameStr = "",
2599 Instruction *InsertBefore = nullptr) {
2600 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2603 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2604 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2605 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2608 /// Provide fast operand accessors
2609 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2611 // Block iterator interface. This provides access to the list of incoming
2612 // basic blocks, which parallels the list of incoming values.
2614 using block_iterator = BasicBlock **;
2615 using const_block_iterator = BasicBlock * const *;
2617 block_iterator block_begin() {
2619 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2620 return reinterpret_cast<block_iterator>(ref + 1);
2623 const_block_iterator block_begin() const {
2624 const Use::UserRef *ref =
2625 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2626 return reinterpret_cast<const_block_iterator>(ref + 1);
2629 block_iterator block_end() {
2630 return block_begin() + getNumOperands();
2633 const_block_iterator block_end() const {
2634 return block_begin() + getNumOperands();
2637 iterator_range<block_iterator> blocks() {
2638 return make_range(block_begin(), block_end());
2641 iterator_range<const_block_iterator> blocks() const {
2642 return make_range(block_begin(), block_end());
2645 op_range incoming_values() { return operands(); }
2647 const_op_range incoming_values() const { return operands(); }
2649 /// Return the number of incoming edges
2651 unsigned getNumIncomingValues() const { return getNumOperands(); }
2653 /// Return incoming value number x
2655 Value *getIncomingValue(unsigned i) const {
2656 return getOperand(i);
2658 void setIncomingValue(unsigned i, Value *V) {
2659 assert(V && "PHI node got a null value!");
2660 assert(getType() == V->getType() &&
2661 "All operands to PHI node must be the same type as the PHI node!");
2665 static unsigned getOperandNumForIncomingValue(unsigned i) {
2669 static unsigned getIncomingValueNumForOperand(unsigned i) {
2673 /// Return incoming basic block number @p i.
2675 BasicBlock *getIncomingBlock(unsigned i) const {
2676 return block_begin()[i];
2679 /// Return incoming basic block corresponding
2680 /// to an operand of the PHI.
2682 BasicBlock *getIncomingBlock(const Use &U) const {
2683 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2684 return getIncomingBlock(unsigned(&U - op_begin()));
2687 /// Return incoming basic block corresponding
2688 /// to value use iterator.
2690 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2691 return getIncomingBlock(I.getUse());
2694 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2695 assert(BB && "PHI node got a null basic block!");
2696 block_begin()[i] = BB;
2699 /// Add an incoming value to the end of the PHI list
2701 void addIncoming(Value *V, BasicBlock *BB) {
2702 if (getNumOperands() == ReservedSpace)
2703 growOperands(); // Get more space!
2704 // Initialize some new operands.
2705 setNumHungOffUseOperands(getNumOperands() + 1);
2706 setIncomingValue(getNumOperands() - 1, V);
2707 setIncomingBlock(getNumOperands() - 1, BB);
2710 /// Remove an incoming value. This is useful if a
2711 /// predecessor basic block is deleted. The value removed is returned.
2713 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2714 /// is true), the PHI node is destroyed and any uses of it are replaced with
2715 /// dummy values. The only time there should be zero incoming values to a PHI
2716 /// node is when the block is dead, so this strategy is sound.
2718 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2720 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2721 int Idx = getBasicBlockIndex(BB);
2722 assert(Idx >= 0 && "Invalid basic block argument to remove!");
2723 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2726 /// Return the first index of the specified basic
2727 /// block in the value list for this PHI. Returns -1 if no instance.
2729 int getBasicBlockIndex(const BasicBlock *BB) const {
2730 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2731 if (block_begin()[i] == BB)
2736 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2737 int Idx = getBasicBlockIndex(BB);
2738 assert(Idx >= 0 && "Invalid basic block argument!");
2739 return getIncomingValue(Idx);
2742 /// If the specified PHI node always merges together the
2743 /// same value, return the value, otherwise return null.
2744 Value *hasConstantValue() const;
2746 /// Whether the specified PHI node always merges
2747 /// together the same value, assuming undefs are equal to a unique
2748 /// non-undef value.
2749 bool hasConstantOrUndefValue() const;
2751 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2752 static bool classof(const Instruction *I) {
2753 return I->getOpcode() == Instruction::PHI;
2755 static bool classof(const Value *V) {
2756 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2760 void growOperands();
2764 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2767 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2769 //===----------------------------------------------------------------------===//
2770 // LandingPadInst Class
2771 //===----------------------------------------------------------------------===//
2773 //===---------------------------------------------------------------------------
2774 /// The landingpad instruction holds all of the information
2775 /// necessary to generate correct exception handling. The landingpad instruction
2776 /// cannot be moved from the top of a landing pad block, which itself is
2777 /// accessible only from the 'unwind' edge of an invoke. This uses the
2778 /// SubclassData field in Value to store whether or not the landingpad is a
2781 class LandingPadInst : public Instruction {
2782 /// The number of operands actually allocated. NumOperands is
2783 /// the number actually in use.
2784 unsigned ReservedSpace;
2786 LandingPadInst(const LandingPadInst &LP);
2789 enum ClauseType { Catch, Filter };
2792 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2793 const Twine &NameStr, Instruction *InsertBefore);
2794 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2795 const Twine &NameStr, BasicBlock *InsertAtEnd);
2797 // Allocate space for exactly zero operands.
2798 void *operator new(size_t s) {
2799 return User::operator new(s);
2802 void growOperands(unsigned Size);
2803 void init(unsigned NumReservedValues, const Twine &NameStr);
2806 // Note: Instruction needs to be a friend here to call cloneImpl.
2807 friend class Instruction;
2809 LandingPadInst *cloneImpl() const;
2812 /// Constructors - NumReservedClauses is a hint for the number of incoming
2813 /// clauses that this landingpad will have (use 0 if you really have no idea).
2814 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2815 const Twine &NameStr = "",
2816 Instruction *InsertBefore = nullptr);
2817 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2818 const Twine &NameStr, BasicBlock *InsertAtEnd);
2820 /// Provide fast operand accessors
2821 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2823 /// Return 'true' if this landingpad instruction is a
2824 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2825 /// doesn't catch the exception.
2826 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2828 /// Indicate that this landingpad instruction is a cleanup.
2829 void setCleanup(bool V) {
2830 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2834 /// Add a catch or filter clause to the landing pad.
2835 void addClause(Constant *ClauseVal);
2837 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2838 /// determine what type of clause this is.
2839 Constant *getClause(unsigned Idx) const {
2840 return cast<Constant>(getOperandList()[Idx]);
2843 /// Return 'true' if the clause and index Idx is a catch clause.
2844 bool isCatch(unsigned Idx) const {
2845 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2848 /// Return 'true' if the clause and index Idx is a filter clause.
2849 bool isFilter(unsigned Idx) const {
2850 return isa<ArrayType>(getOperandList()[Idx]->getType());
2853 /// Get the number of clauses for this landing pad.
2854 unsigned getNumClauses() const { return getNumOperands(); }
2856 /// Grow the size of the operand list to accommodate the new
2857 /// number of clauses.
2858 void reserveClauses(unsigned Size) { growOperands(Size); }
2860 // Methods for support type inquiry through isa, cast, and dyn_cast:
2861 static bool classof(const Instruction *I) {
2862 return I->getOpcode() == Instruction::LandingPad;
2864 static bool classof(const Value *V) {
2865 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2870 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2873 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2875 //===----------------------------------------------------------------------===//
2877 //===----------------------------------------------------------------------===//
2879 //===---------------------------------------------------------------------------
2880 /// Return a value (possibly void), from a function. Execution
2881 /// does not continue in this function any longer.
2883 class ReturnInst : public Instruction {
2884 ReturnInst(const ReturnInst &RI);
2887 // ReturnInst constructors:
2888 // ReturnInst() - 'ret void' instruction
2889 // ReturnInst( null) - 'ret void' instruction
2890 // ReturnInst(Value* X) - 'ret X' instruction
2891 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2892 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2893 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2894 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2896 // NOTE: If the Value* passed is of type void then the constructor behaves as
2897 // if it was passed NULL.
2898 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2899 Instruction *InsertBefore = nullptr);
2900 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2901 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2904 // Note: Instruction needs to be a friend here to call cloneImpl.
2905 friend class Instruction;
2907 ReturnInst *cloneImpl() const;
2910 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2911 Instruction *InsertBefore = nullptr) {
2912 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2915 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2916 BasicBlock *InsertAtEnd) {
2917 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2920 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2921 return new(0) ReturnInst(C, InsertAtEnd);
2924 /// Provide fast operand accessors
2925 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2927 /// Convenience accessor. Returns null if there is no return value.
2928 Value *getReturnValue() const {
2929 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2932 unsigned getNumSuccessors() const { return 0; }
2934 // Methods for support type inquiry through isa, cast, and dyn_cast:
2935 static bool classof(const Instruction *I) {
2936 return (I->getOpcode() == Instruction::Ret);
2938 static bool classof(const Value *V) {
2939 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2943 BasicBlock *getSuccessor(unsigned idx) const {
2944 llvm_unreachable("ReturnInst has no successors!");
2947 void setSuccessor(unsigned idx, BasicBlock *B) {
2948 llvm_unreachable("ReturnInst has no successors!");
2953 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2956 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2958 //===----------------------------------------------------------------------===//
2960 //===----------------------------------------------------------------------===//
2962 //===---------------------------------------------------------------------------
2963 /// Conditional or Unconditional Branch instruction.
2965 class BranchInst : public Instruction {
2966 /// Ops list - Branches are strange. The operands are ordered:
2967 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2968 /// they don't have to check for cond/uncond branchness. These are mostly
2969 /// accessed relative from op_end().
2970 BranchInst(const BranchInst &BI);
2971 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2972 // BranchInst(BB *B) - 'br B'
2973 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2974 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2975 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2976 // BranchInst(BB* B, BB *I) - 'br B' insert at end
2977 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2978 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2979 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2980 Instruction *InsertBefore = nullptr);
2981 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2982 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2983 BasicBlock *InsertAtEnd);
2988 // Note: Instruction needs to be a friend here to call cloneImpl.
2989 friend class Instruction;
2991 BranchInst *cloneImpl() const;
2994 /// Iterator type that casts an operand to a basic block.
2996 /// This only makes sense because the successors are stored as adjacent
2997 /// operands for branch instructions.
2998 struct succ_op_iterator
2999 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3000 std::random_access_iterator_tag, BasicBlock *,
3001 ptrdiff_t, BasicBlock *, BasicBlock *> {
3002 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3004 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3005 BasicBlock *operator->() const { return operator*(); }
3008 /// The const version of `succ_op_iterator`.
3009 struct const_succ_op_iterator
3010 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3011 std::random_access_iterator_tag,
3012 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3013 const BasicBlock *> {
3014 explicit const_succ_op_iterator(const_value_op_iterator I)
3015 : iterator_adaptor_base(I) {}
3017 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3018 const BasicBlock *operator->() const { return operator*(); }
3021 static BranchInst *Create(BasicBlock *IfTrue,
3022 Instruction *InsertBefore = nullptr) {
3023 return new(1) BranchInst(IfTrue, InsertBefore);
3026 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3027 Value *Cond, Instruction *InsertBefore = nullptr) {
3028 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3031 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3032 return new(1) BranchInst(IfTrue, InsertAtEnd);
3035 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3036 Value *Cond, BasicBlock *InsertAtEnd) {
3037 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3040 /// Transparently provide more efficient getOperand methods.
3041 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3043 bool isUnconditional() const { return getNumOperands() == 1; }
3044 bool isConditional() const { return getNumOperands() == 3; }
3046 Value *getCondition() const {
3047 assert(isConditional() && "Cannot get condition of an uncond branch!");
3051 void setCondition(Value *V) {
3052 assert(isConditional() && "Cannot set condition of unconditional branch!");
3056 unsigned getNumSuccessors() const { return 1+isConditional(); }
3058 BasicBlock *getSuccessor(unsigned i) const {
3059 assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3060 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3063 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3064 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3065 *(&Op<-1>() - idx) = NewSucc;
3068 /// Swap the successors of this branch instruction.
3070 /// Swaps the successors of the branch instruction. This also swaps any
3071 /// branch weight metadata associated with the instruction so that it
3072 /// continues to map correctly to each operand.
3073 void swapSuccessors();
3075 iterator_range<succ_op_iterator> successors() {
3077 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3078 succ_op_iterator(value_op_end()));
3081 iterator_range<const_succ_op_iterator> successors() const {
3082 return make_range(const_succ_op_iterator(
3083 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3084 const_succ_op_iterator(value_op_end()));
3087 // Methods for support type inquiry through isa, cast, and dyn_cast:
3088 static bool classof(const Instruction *I) {
3089 return (I->getOpcode() == Instruction::Br);
3091 static bool classof(const Value *V) {
3092 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3097 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3100 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
3102 //===----------------------------------------------------------------------===//
3104 //===----------------------------------------------------------------------===//
3106 //===---------------------------------------------------------------------------
3109 class SwitchInst : public Instruction {
3110 unsigned ReservedSpace;
3112 // Operand[0] = Value to switch on
3113 // Operand[1] = Default basic block destination
3114 // Operand[2n ] = Value to match
3115 // Operand[2n+1] = BasicBlock to go to on match
3116 SwitchInst(const SwitchInst &SI);
3118 /// Create a new switch instruction, specifying a value to switch on and a
3119 /// default destination. The number of additional cases can be specified here
3120 /// to make memory allocation more efficient. This constructor can also
3121 /// auto-insert before another instruction.
3122 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3123 Instruction *InsertBefore);
3125 /// Create a new switch instruction, specifying a value to switch on and a
3126 /// default destination. The number of additional cases can be specified here
3127 /// to make memory allocation more efficient. This constructor also
3128 /// auto-inserts at the end of the specified BasicBlock.
3129 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3130 BasicBlock *InsertAtEnd);
3132 // allocate space for exactly zero operands
3133 void *operator new(size_t s) {
3134 return User::operator new(s);
3137 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3138 void growOperands();
3141 // Note: Instruction needs to be a friend here to call cloneImpl.
3142 friend class Instruction;
3144 SwitchInst *cloneImpl() const;
3148 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3150 template <typename CaseHandleT> class CaseIteratorImpl;
3152 /// A handle to a particular switch case. It exposes a convenient interface
3153 /// to both the case value and the successor block.
3155 /// We define this as a template and instantiate it to form both a const and
3156 /// non-const handle.
3157 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3158 class CaseHandleImpl {
3159 // Directly befriend both const and non-const iterators.
3160 friend class SwitchInst::CaseIteratorImpl<
3161 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3164 // Expose the switch type we're parameterized with to the iterator.
3165 using SwitchInstType = SwitchInstT;
3170 CaseHandleImpl() = default;
3171 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3174 /// Resolves case value for current case.
3175 ConstantIntT *getCaseValue() const {
3176 assert((unsigned)Index < SI->getNumCases() &&
3177 "Index out the number of cases.");
3178 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3181 /// Resolves successor for current case.
3182 BasicBlockT *getCaseSuccessor() const {
3183 assert(((unsigned)Index < SI->getNumCases() ||
3184 (unsigned)Index == DefaultPseudoIndex) &&
3185 "Index out the number of cases.");
3186 return SI->getSuccessor(getSuccessorIndex());
3189 /// Returns number of current case.
3190 unsigned getCaseIndex() const { return Index; }
3192 /// Returns successor index for current case successor.
3193 unsigned getSuccessorIndex() const {
3194 assert(((unsigned)Index == DefaultPseudoIndex ||
3195 (unsigned)Index < SI->getNumCases()) &&
3196 "Index out the number of cases.");
3197 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3200 bool operator==(const CaseHandleImpl &RHS) const {
3201 assert(SI == RHS.SI && "Incompatible operators.");
3202 return Index == RHS.Index;
3206 using ConstCaseHandle =
3207 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3210 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3211 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3214 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3216 /// Sets the new value for current case.
3217 void setValue(ConstantInt *V) {
3218 assert((unsigned)Index < SI->getNumCases() &&
3219 "Index out the number of cases.");
3220 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3223 /// Sets the new successor for current case.
3224 void setSuccessor(BasicBlock *S) {
3225 SI->setSuccessor(getSuccessorIndex(), S);
3229 template <typename CaseHandleT>
3230 class CaseIteratorImpl
3231 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3232 std::random_access_iterator_tag,
3234 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3239 /// Default constructed iterator is in an invalid state until assigned to
3240 /// a case for a particular switch.
3241 CaseIteratorImpl() = default;
3243 /// Initializes case iterator for given SwitchInst and for given
3245 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3247 /// Initializes case iterator for given SwitchInst and for given
3248 /// successor index.
3249 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3250 unsigned SuccessorIndex) {
3251 assert(SuccessorIndex < SI->getNumSuccessors() &&
3252 "Successor index # out of range!");
3253 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3254 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3257 /// Support converting to the const variant. This will be a no-op for const
3259 operator CaseIteratorImpl<ConstCaseHandle>() const {
3260 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3263 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3264 // Check index correctness after addition.
3265 // Note: Index == getNumCases() means end().
3266 assert(Case.Index + N >= 0 &&
3267 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3268 "Case.Index out the number of cases.");
3272 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3273 // Check index correctness after subtraction.
3274 // Note: Case.Index == getNumCases() means end().
3275 assert(Case.Index - N >= 0 &&
3276 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3277 "Case.Index out the number of cases.");
3281 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3282 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3283 return Case.Index - RHS.Case.Index;
3285 bool operator==(const CaseIteratorImpl &RHS) const {
3286 return Case == RHS.Case;
3288 bool operator<(const CaseIteratorImpl &RHS) const {
3289 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3290 return Case.Index < RHS.Case.Index;
3292 CaseHandleT &operator*() { return Case; }
3293 const CaseHandleT &operator*() const { return Case; }
3296 using CaseIt = CaseIteratorImpl<CaseHandle>;
3297 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3299 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3301 Instruction *InsertBefore = nullptr) {
3302 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3305 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3306 unsigned NumCases, BasicBlock *InsertAtEnd) {
3307 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3310 /// Provide fast operand accessors
3311 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3313 // Accessor Methods for Switch stmt
3314 Value *getCondition() const { return getOperand(0); }
3315 void setCondition(Value *V) { setOperand(0, V); }
3317 BasicBlock *getDefaultDest() const {
3318 return cast<BasicBlock>(getOperand(1));
3321 void setDefaultDest(BasicBlock *DefaultCase) {
3322 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3325 /// Return the number of 'cases' in this switch instruction, excluding the
3327 unsigned getNumCases() const {
3328 return getNumOperands()/2 - 1;
3331 /// Returns a read/write iterator that points to the first case in the
3333 CaseIt case_begin() {
3334 return CaseIt(this, 0);
3337 /// Returns a read-only iterator that points to the first case in the
3339 ConstCaseIt case_begin() const {
3340 return ConstCaseIt(this, 0);
3343 /// Returns a read/write iterator that points one past the last in the
3346 return CaseIt(this, getNumCases());
3349 /// Returns a read-only iterator that points one past the last in the
3351 ConstCaseIt case_end() const {
3352 return ConstCaseIt(this, getNumCases());
3355 /// Iteration adapter for range-for loops.
3356 iterator_range<CaseIt> cases() {
3357 return make_range(case_begin(), case_end());
3360 /// Constant iteration adapter for range-for loops.
3361 iterator_range<ConstCaseIt> cases() const {
3362 return make_range(case_begin(), case_end());
3365 /// Returns an iterator that points to the default case.
3366 /// Note: this iterator allows to resolve successor only. Attempt
3367 /// to resolve case value causes an assertion.
3368 /// Also note, that increment and decrement also causes an assertion and
3369 /// makes iterator invalid.
3370 CaseIt case_default() {
3371 return CaseIt(this, DefaultPseudoIndex);
3373 ConstCaseIt case_default() const {
3374 return ConstCaseIt(this, DefaultPseudoIndex);
3377 /// Search all of the case values for the specified constant. If it is
3378 /// explicitly handled, return the case iterator of it, otherwise return
3379 /// default case iterator to indicate that it is handled by the default
3381 CaseIt findCaseValue(const ConstantInt *C) {
3382 CaseIt I = llvm::find_if(
3383 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3384 if (I != case_end())
3387 return case_default();
3389 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3390 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3391 return Case.getCaseValue() == C;
3393 if (I != case_end())
3396 return case_default();
3399 /// Finds the unique case value for a given successor. Returns null if the
3400 /// successor is not found, not unique, or is the default case.
3401 ConstantInt *findCaseDest(BasicBlock *BB) {
3402 if (BB == getDefaultDest())
3405 ConstantInt *CI = nullptr;
3406 for (auto Case : cases()) {
3407 if (Case.getCaseSuccessor() != BB)
3411 return nullptr; // Multiple cases lead to BB.
3413 CI = Case.getCaseValue();
3419 /// Add an entry to the switch instruction.
3421 /// This action invalidates case_end(). Old case_end() iterator will
3422 /// point to the added case.
3423 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3425 /// This method removes the specified case and its successor from the switch
3426 /// instruction. Note that this operation may reorder the remaining cases at
3427 /// index idx and above.
3429 /// This action invalidates iterators for all cases following the one removed,
3430 /// including the case_end() iterator. It returns an iterator for the next
3432 CaseIt removeCase(CaseIt I);
3434 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3435 BasicBlock *getSuccessor(unsigned idx) const {
3436 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3437 return cast<BasicBlock>(getOperand(idx*2+1));
3439 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3440 assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3441 setOperand(idx * 2 + 1, NewSucc);
3444 // Methods for support type inquiry through isa, cast, and dyn_cast:
3445 static bool classof(const Instruction *I) {
3446 return I->getOpcode() == Instruction::Switch;
3448 static bool classof(const Value *V) {
3449 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3454 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3457 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3459 //===----------------------------------------------------------------------===//
3460 // IndirectBrInst Class
3461 //===----------------------------------------------------------------------===//
3463 //===---------------------------------------------------------------------------
3464 /// Indirect Branch Instruction.
3466 class IndirectBrInst : public Instruction {
3467 unsigned ReservedSpace;
3469 // Operand[0] = Address to jump to
3470 // Operand[n+1] = n-th destination
3471 IndirectBrInst(const IndirectBrInst &IBI);
3473 /// Create a new indirectbr instruction, specifying an
3474 /// Address to jump to. The number of expected destinations can be specified
3475 /// here to make memory allocation more efficient. This constructor can also
3476 /// autoinsert before another instruction.
3477 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3479 /// Create a new indirectbr instruction, specifying an
3480 /// Address to jump to. The number of expected destinations can be specified
3481 /// here to make memory allocation more efficient. This constructor also
3482 /// autoinserts at the end of the specified BasicBlock.
3483 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3485 // allocate space for exactly zero operands
3486 void *operator new(size_t s) {
3487 return User::operator new(s);
3490 void init(Value *Address, unsigned NumDests);
3491 void growOperands();
3494 // Note: Instruction needs to be a friend here to call cloneImpl.
3495 friend class Instruction;
3497 IndirectBrInst *cloneImpl() const;
3500 /// Iterator type that casts an operand to a basic block.
3502 /// This only makes sense because the successors are stored as adjacent
3503 /// operands for indirectbr instructions.
3504 struct succ_op_iterator
3505 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3506 std::random_access_iterator_tag, BasicBlock *,
3507 ptrdiff_t, BasicBlock *, BasicBlock *> {
3508 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3510 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3511 BasicBlock *operator->() const { return operator*(); }
3514 /// The const version of `succ_op_iterator`.
3515 struct const_succ_op_iterator
3516 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3517 std::random_access_iterator_tag,
3518 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3519 const BasicBlock *> {
3520 explicit const_succ_op_iterator(const_value_op_iterator I)
3521 : iterator_adaptor_base(I) {}
3523 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3524 const BasicBlock *operator->() const { return operator*(); }
3527 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3528 Instruction *InsertBefore = nullptr) {
3529 return new IndirectBrInst(Address, NumDests, InsertBefore);
3532 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3533 BasicBlock *InsertAtEnd) {
3534 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3537 /// Provide fast operand accessors.
3538 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3540 // Accessor Methods for IndirectBrInst instruction.
3541 Value *getAddress() { return getOperand(0); }
3542 const Value *getAddress() const { return getOperand(0); }
3543 void setAddress(Value *V) { setOperand(0, V); }
3545 /// return the number of possible destinations in this
3546 /// indirectbr instruction.
3547 unsigned getNumDestinations() const { return getNumOperands()-1; }
3549 /// Return the specified destination.
3550 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3551 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3553 /// Add a destination.
3555 void addDestination(BasicBlock *Dest);
3557 /// This method removes the specified successor from the
3558 /// indirectbr instruction.
3559 void removeDestination(unsigned i);
3561 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3562 BasicBlock *getSuccessor(unsigned i) const {
3563 return cast<BasicBlock>(getOperand(i+1));
3565 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3566 setOperand(i + 1, NewSucc);
3569 iterator_range<succ_op_iterator> successors() {
3570 return make_range(succ_op_iterator(std::next(value_op_begin())),
3571 succ_op_iterator(value_op_end()));
3574 iterator_range<const_succ_op_iterator> successors() const {
3575 return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3576 const_succ_op_iterator(value_op_end()));
3579 // Methods for support type inquiry through isa, cast, and dyn_cast:
3580 static bool classof(const Instruction *I) {
3581 return I->getOpcode() == Instruction::IndirectBr;
3583 static bool classof(const Value *V) {
3584 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3589 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3592 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3594 //===----------------------------------------------------------------------===//
3596 //===----------------------------------------------------------------------===//
3598 /// Invoke instruction. The SubclassData field is used to hold the
3599 /// calling convention of the call.
3601 class InvokeInst : public CallBase {
3602 /// The number of operands for this call beyond the called function,
3603 /// arguments, and operand bundles.
3604 static constexpr int NumExtraOperands = 2;
3606 /// The index from the end of the operand array to the normal destination.
3607 static constexpr int NormalDestOpEndIdx = -3;
3609 /// The index from the end of the operand array to the unwind destination.
3610 static constexpr int UnwindDestOpEndIdx = -2;
3612 InvokeInst(const InvokeInst &BI);
3614 /// Construct an InvokeInst given a range of arguments.
3616 /// Construct an InvokeInst from a range of arguments
3617 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3618 BasicBlock *IfException, ArrayRef<Value *> Args,
3619 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3620 const Twine &NameStr, Instruction *InsertBefore);
3622 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3623 BasicBlock *IfException, ArrayRef<Value *> Args,
3624 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3625 const Twine &NameStr, BasicBlock *InsertAtEnd);
3627 void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3628 BasicBlock *IfException, ArrayRef<Value *> Args,
3629 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3631 /// Compute the number of operands to allocate.
3632 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3633 // We need one operand for the called function, plus our extra operands and
3634 // the input operand counts provided.
3635 return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3639 // Note: Instruction needs to be a friend here to call cloneImpl.
3640 friend class Instruction;
3642 InvokeInst *cloneImpl() const;
3645 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3646 BasicBlock *IfException, ArrayRef<Value *> Args,
3647 const Twine &NameStr,
3648 Instruction *InsertBefore = nullptr) {
3649 int NumOperands = ComputeNumOperands(Args.size());
3650 return new (NumOperands)
3651 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3652 NameStr, InsertBefore);
3655 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3656 BasicBlock *IfException, ArrayRef<Value *> Args,
3657 ArrayRef<OperandBundleDef> Bundles = None,
3658 const Twine &NameStr = "",
3659 Instruction *InsertBefore = nullptr) {
3661 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3662 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3664 return new (NumOperands, DescriptorBytes)
3665 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3666 NameStr, InsertBefore);
3669 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3670 BasicBlock *IfException, ArrayRef<Value *> Args,
3671 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3672 int NumOperands = ComputeNumOperands(Args.size());
3673 return new (NumOperands)
3674 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3675 NameStr, InsertAtEnd);
3678 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3679 BasicBlock *IfException, ArrayRef<Value *> Args,
3680 ArrayRef<OperandBundleDef> Bundles,
3681 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3683 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3684 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3686 return new (NumOperands, DescriptorBytes)
3687 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3688 NameStr, InsertAtEnd);
3691 static InvokeInst *Create(Function *Func, BasicBlock *IfNormal,
3692 BasicBlock *IfException, ArrayRef<Value *> Args,
3693 const Twine &NameStr,
3694 Instruction *InsertBefore = nullptr) {
3695 return Create(Func->getFunctionType(), Func, IfNormal, IfException, Args,
3696 None, NameStr, InsertBefore);
3699 static InvokeInst *Create(Function *Func, BasicBlock *IfNormal,
3700 BasicBlock *IfException, ArrayRef<Value *> Args,
3701 ArrayRef<OperandBundleDef> Bundles = None,
3702 const Twine &NameStr = "",
3703 Instruction *InsertBefore = nullptr) {
3704 return Create(Func->getFunctionType(), Func, IfNormal, IfException, Args,
3705 Bundles, NameStr, InsertBefore);
3708 static InvokeInst *Create(Function *Func, BasicBlock *IfNormal,
3709 BasicBlock *IfException, ArrayRef<Value *> Args,
3710 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3711 return Create(Func->getFunctionType(), Func, IfNormal, IfException, Args,
3712 NameStr, InsertAtEnd);
3715 static InvokeInst *Create(Function *Func, BasicBlock *IfNormal,
3716 BasicBlock *IfException, ArrayRef<Value *> Args,
3717 ArrayRef<OperandBundleDef> Bundles,
3718 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3719 return Create(Func->getFunctionType(), Func, IfNormal, IfException, Args,
3720 Bundles, NameStr, InsertAtEnd);
3723 // Deprecated [opaque pointer types]
3724 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3725 BasicBlock *IfException, ArrayRef<Value *> Args,
3726 const Twine &NameStr,
3727 Instruction *InsertBefore = nullptr) {
3728 return Create(cast<FunctionType>(
3729 cast<PointerType>(Func->getType())->getElementType()),
3730 Func, IfNormal, IfException, Args, None, NameStr,
3734 // Deprecated [opaque pointer types]
3735 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3736 BasicBlock *IfException, ArrayRef<Value *> Args,
3737 ArrayRef<OperandBundleDef> Bundles = None,
3738 const Twine &NameStr = "",
3739 Instruction *InsertBefore = nullptr) {
3740 return Create(cast<FunctionType>(
3741 cast<PointerType>(Func->getType())->getElementType()),
3742 Func, IfNormal, IfException, Args, Bundles, NameStr,
3746 // Deprecated [opaque pointer types]
3747 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3748 BasicBlock *IfException, ArrayRef<Value *> Args,
3749 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3750 return Create(cast<FunctionType>(
3751 cast<PointerType>(Func->getType())->getElementType()),
3752 Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3755 // Deprecated [opaque pointer types]
3756 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3757 BasicBlock *IfException, ArrayRef<Value *> Args,
3758 ArrayRef<OperandBundleDef> Bundles,
3759 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3760 return Create(cast<FunctionType>(
3761 cast<PointerType>(Func->getType())->getElementType()),
3762 Func, IfNormal, IfException, Args, Bundles, NameStr,
3766 /// Create a clone of \p II with a different set of operand bundles and
3767 /// insert it before \p InsertPt.
3769 /// The returned invoke instruction is identical to \p II in every way except
3770 /// that the operand bundles for the new instruction are set to the operand
3771 /// bundles in \p Bundles.
3772 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3773 Instruction *InsertPt = nullptr);
3775 /// Determine if the call should not perform indirect branch tracking.
3776 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3778 /// Determine if the call cannot unwind.
3779 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3780 void setDoesNotThrow() {
3781 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3784 // get*Dest - Return the destination basic blocks...
3785 BasicBlock *getNormalDest() const {
3786 return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3788 BasicBlock *getUnwindDest() const {
3789 return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3791 void setNormalDest(BasicBlock *B) {
3792 Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3794 void setUnwindDest(BasicBlock *B) {
3795 Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3798 /// Get the landingpad instruction from the landing pad
3799 /// block (the unwind destination).
3800 LandingPadInst *getLandingPadInst() const;
3802 BasicBlock *getSuccessor(unsigned i) const {
3803 assert(i < 2 && "Successor # out of range for invoke!");
3804 return i == 0 ? getNormalDest() : getUnwindDest();
3807 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3808 assert(i < 2 && "Successor # out of range for invoke!");
3810 setNormalDest(NewSucc);
3812 setUnwindDest(NewSucc);
3815 unsigned getNumSuccessors() const { return 2; }
3817 // Methods for support type inquiry through isa, cast, and dyn_cast:
3818 static bool classof(const Instruction *I) {
3819 return (I->getOpcode() == Instruction::Invoke);
3821 static bool classof(const Value *V) {
3822 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3827 // Shadow Instruction::setInstructionSubclassData with a private forwarding
3828 // method so that subclasses cannot accidentally use it.
3829 void setInstructionSubclassData(unsigned short D) {
3830 Instruction::setInstructionSubclassData(D);
3834 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3835 BasicBlock *IfException, ArrayRef<Value *> Args,
3836 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3837 const Twine &NameStr, Instruction *InsertBefore)
3838 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3839 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3841 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3844 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3845 BasicBlock *IfException, ArrayRef<Value *> Args,
3846 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3847 const Twine &NameStr, BasicBlock *InsertAtEnd)
3848 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3849 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3851 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3854 //===----------------------------------------------------------------------===//
3856 //===----------------------------------------------------------------------===//
3858 //===---------------------------------------------------------------------------
3859 /// Resume the propagation of an exception.
3861 class ResumeInst : public Instruction {
3862 ResumeInst(const ResumeInst &RI);
3864 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
3865 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
3868 // Note: Instruction needs to be a friend here to call cloneImpl.
3869 friend class Instruction;
3871 ResumeInst *cloneImpl() const;
3874 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
3875 return new(1) ResumeInst(Exn, InsertBefore);
3878 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
3879 return new(1) ResumeInst(Exn, InsertAtEnd);
3882 /// Provide fast operand accessors
3883 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3885 /// Convenience accessor.
3886 Value *getValue() const { return Op<0>(); }
3888 unsigned getNumSuccessors() const { return 0; }
3890 // Methods for support type inquiry through isa, cast, and dyn_cast:
3891 static bool classof(const Instruction *I) {
3892 return I->getOpcode() == Instruction::Resume;
3894 static bool classof(const Value *V) {
3895 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3899 BasicBlock *getSuccessor(unsigned idx) const {
3900 llvm_unreachable("ResumeInst has no successors!");
3903 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3904 llvm_unreachable("ResumeInst has no successors!");
3909 struct OperandTraits<ResumeInst> :
3910 public FixedNumOperandTraits<ResumeInst, 1> {
3913 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
3915 //===----------------------------------------------------------------------===//
3916 // CatchSwitchInst Class
3917 //===----------------------------------------------------------------------===//
3918 class CatchSwitchInst : public Instruction {
3919 /// The number of operands actually allocated. NumOperands is
3920 /// the number actually in use.
3921 unsigned ReservedSpace;
3923 // Operand[0] = Outer scope
3924 // Operand[1] = Unwind block destination
3925 // Operand[n] = BasicBlock to go to on match
3926 CatchSwitchInst(const CatchSwitchInst &CSI);
3928 /// Create a new switch instruction, specifying a
3929 /// default destination. The number of additional handlers can be specified
3930 /// here to make memory allocation more efficient.
3931 /// This constructor can also autoinsert before another instruction.
3932 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
3933 unsigned NumHandlers, const Twine &NameStr,
3934 Instruction *InsertBefore);
3936 /// Create a new switch instruction, specifying a
3937 /// default destination. The number of additional handlers can be specified
3938 /// here to make memory allocation more efficient.
3939 /// This constructor also autoinserts at the end of the specified BasicBlock.
3940 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
3941 unsigned NumHandlers, const Twine &NameStr,
3942 BasicBlock *InsertAtEnd);
3944 // allocate space for exactly zero operands
3945 void *operator new(size_t s) { return User::operator new(s); }
3947 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
3948 void growOperands(unsigned Size);
3951 // Note: Instruction needs to be a friend here to call cloneImpl.
3952 friend class Instruction;
3954 CatchSwitchInst *cloneImpl() const;
3957 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
3958 unsigned NumHandlers,
3959 const Twine &NameStr = "",
3960 Instruction *InsertBefore = nullptr) {
3961 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
3965 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
3966 unsigned NumHandlers, const Twine &NameStr,
3967 BasicBlock *InsertAtEnd) {
3968 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
3972 /// Provide fast operand accessors
3973 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3975 // Accessor Methods for CatchSwitch stmt
3976 Value *getParentPad() const { return getOperand(0); }
3977 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
3979 // Accessor Methods for CatchSwitch stmt
3980 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
3981 bool unwindsToCaller() const { return !hasUnwindDest(); }
3982 BasicBlock *getUnwindDest() const {
3983 if (hasUnwindDest())
3984 return cast<BasicBlock>(getOperand(1));
3987 void setUnwindDest(BasicBlock *UnwindDest) {
3989 assert(hasUnwindDest());
3990 setOperand(1, UnwindDest);
3993 /// return the number of 'handlers' in this catchswitch
3994 /// instruction, except the default handler
3995 unsigned getNumHandlers() const {
3996 if (hasUnwindDest())
3997 return getNumOperands() - 2;
3998 return getNumOperands() - 1;
4002 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4003 static const BasicBlock *handler_helper(const Value *V) {
4004 return cast<BasicBlock>(V);
4008 using DerefFnTy = BasicBlock *(*)(Value *);
4009 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4010 using handler_range = iterator_range<handler_iterator>;
4011 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4012 using const_handler_iterator =
4013 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4014 using const_handler_range = iterator_range<const_handler_iterator>;
4016 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4017 handler_iterator handler_begin() {
4018 op_iterator It = op_begin() + 1;
4019 if (hasUnwindDest())
4021 return handler_iterator(It, DerefFnTy(handler_helper));
4024 /// Returns an iterator that points to the first handler in the
4025 /// CatchSwitchInst.
4026 const_handler_iterator handler_begin() const {
4027 const_op_iterator It = op_begin() + 1;
4028 if (hasUnwindDest())
4030 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4033 /// Returns a read-only iterator that points one past the last
4034 /// handler in the CatchSwitchInst.
4035 handler_iterator handler_end() {
4036 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4039 /// Returns an iterator that points one past the last handler in the
4040 /// CatchSwitchInst.
4041 const_handler_iterator handler_end() const {
4042 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4045 /// iteration adapter for range-for loops.
4046 handler_range handlers() {
4047 return make_range(handler_begin(), handler_end());
4050 /// iteration adapter for range-for loops.
4051 const_handler_range handlers() const {
4052 return make_range(handler_begin(), handler_end());
4055 /// Add an entry to the switch instruction...
4057 /// This action invalidates handler_end(). Old handler_end() iterator will
4058 /// point to the added handler.
4059 void addHandler(BasicBlock *Dest);
4061 void removeHandler(handler_iterator HI);
4063 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4064 BasicBlock *getSuccessor(unsigned Idx) const {
4065 assert(Idx < getNumSuccessors() &&
4066 "Successor # out of range for catchswitch!");
4067 return cast<BasicBlock>(getOperand(Idx + 1));
4069 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4070 assert(Idx < getNumSuccessors() &&
4071 "Successor # out of range for catchswitch!");
4072 setOperand(Idx + 1, NewSucc);
4075 // Methods for support type inquiry through isa, cast, and dyn_cast:
4076 static bool classof(const Instruction *I) {
4077 return I->getOpcode() == Instruction::CatchSwitch;
4079 static bool classof(const Value *V) {
4080 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4085 struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4087 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4089 //===----------------------------------------------------------------------===//
4090 // CleanupPadInst Class
4091 //===----------------------------------------------------------------------===//
4092 class CleanupPadInst : public FuncletPadInst {
4094 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4095 unsigned Values, const Twine &NameStr,
4096 Instruction *InsertBefore)
4097 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4098 NameStr, InsertBefore) {}
4099 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4100 unsigned Values, const Twine &NameStr,
4101 BasicBlock *InsertAtEnd)
4102 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4103 NameStr, InsertAtEnd) {}
4106 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4107 const Twine &NameStr = "",
4108 Instruction *InsertBefore = nullptr) {
4109 unsigned Values = 1 + Args.size();
4111 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4114 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4115 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4116 unsigned Values = 1 + Args.size();
4118 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4121 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4122 static bool classof(const Instruction *I) {
4123 return I->getOpcode() == Instruction::CleanupPad;
4125 static bool classof(const Value *V) {
4126 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4130 //===----------------------------------------------------------------------===//
4131 // CatchPadInst Class
4132 //===----------------------------------------------------------------------===//
4133 class CatchPadInst : public FuncletPadInst {
4135 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4136 unsigned Values, const Twine &NameStr,
4137 Instruction *InsertBefore)
4138 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4139 NameStr, InsertBefore) {}
4140 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4141 unsigned Values, const Twine &NameStr,
4142 BasicBlock *InsertAtEnd)
4143 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4144 NameStr, InsertAtEnd) {}
4147 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4148 const Twine &NameStr = "",
4149 Instruction *InsertBefore = nullptr) {
4150 unsigned Values = 1 + Args.size();
4152 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4155 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4156 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4157 unsigned Values = 1 + Args.size();
4159 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4162 /// Convenience accessors
4163 CatchSwitchInst *getCatchSwitch() const {
4164 return cast<CatchSwitchInst>(Op<-1>());
4166 void setCatchSwitch(Value *CatchSwitch) {
4167 assert(CatchSwitch);
4168 Op<-1>() = CatchSwitch;
4171 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4172 static bool classof(const Instruction *I) {
4173 return I->getOpcode() == Instruction::CatchPad;
4175 static bool classof(const Value *V) {
4176 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4180 //===----------------------------------------------------------------------===//
4181 // CatchReturnInst Class
4182 //===----------------------------------------------------------------------===//
4184 class CatchReturnInst : public Instruction {
4185 CatchReturnInst(const CatchReturnInst &RI);
4186 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4187 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4189 void init(Value *CatchPad, BasicBlock *BB);
4192 // Note: Instruction needs to be a friend here to call cloneImpl.
4193 friend class Instruction;
4195 CatchReturnInst *cloneImpl() const;
4198 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4199 Instruction *InsertBefore = nullptr) {
4202 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4205 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4206 BasicBlock *InsertAtEnd) {
4209 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4212 /// Provide fast operand accessors
4213 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4215 /// Convenience accessors.
4216 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4217 void setCatchPad(CatchPadInst *CatchPad) {
4222 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4223 void setSuccessor(BasicBlock *NewSucc) {
4227 unsigned getNumSuccessors() const { return 1; }
4229 /// Get the parentPad of this catchret's catchpad's catchswitch.
4230 /// The successor block is implicitly a member of this funclet.
4231 Value *getCatchSwitchParentPad() const {
4232 return getCatchPad()->getCatchSwitch()->getParentPad();
4235 // Methods for support type inquiry through isa, cast, and dyn_cast:
4236 static bool classof(const Instruction *I) {
4237 return (I->getOpcode() == Instruction::CatchRet);
4239 static bool classof(const Value *V) {
4240 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4244 BasicBlock *getSuccessor(unsigned Idx) const {
4245 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4246 return getSuccessor();
4249 void setSuccessor(unsigned Idx, BasicBlock *B) {
4250 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4256 struct OperandTraits<CatchReturnInst>
4257 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4259 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4261 //===----------------------------------------------------------------------===//
4262 // CleanupReturnInst Class
4263 //===----------------------------------------------------------------------===//
4265 class CleanupReturnInst : public Instruction {
4267 CleanupReturnInst(const CleanupReturnInst &RI);
4268 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4269 Instruction *InsertBefore = nullptr);
4270 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4271 BasicBlock *InsertAtEnd);
4273 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4276 // Note: Instruction needs to be a friend here to call cloneImpl.
4277 friend class Instruction;
4279 CleanupReturnInst *cloneImpl() const;
4282 static CleanupReturnInst *Create(Value *CleanupPad,
4283 BasicBlock *UnwindBB = nullptr,
4284 Instruction *InsertBefore = nullptr) {
4286 unsigned Values = 1;
4290 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4293 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4294 BasicBlock *InsertAtEnd) {
4296 unsigned Values = 1;
4300 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4303 /// Provide fast operand accessors
4304 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4306 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4307 bool unwindsToCaller() const { return !hasUnwindDest(); }
4309 /// Convenience accessor.
4310 CleanupPadInst *getCleanupPad() const {
4311 return cast<CleanupPadInst>(Op<0>());
4313 void setCleanupPad(CleanupPadInst *CleanupPad) {
4315 Op<0>() = CleanupPad;
4318 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4320 BasicBlock *getUnwindDest() const {
4321 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4323 void setUnwindDest(BasicBlock *NewDest) {
4325 assert(hasUnwindDest());
4329 // Methods for support type inquiry through isa, cast, and dyn_cast:
4330 static bool classof(const Instruction *I) {
4331 return (I->getOpcode() == Instruction::CleanupRet);
4333 static bool classof(const Value *V) {
4334 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4338 BasicBlock *getSuccessor(unsigned Idx) const {
4340 return getUnwindDest();
4343 void setSuccessor(unsigned Idx, BasicBlock *B) {
4348 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4349 // method so that subclasses cannot accidentally use it.
4350 void setInstructionSubclassData(unsigned short D) {
4351 Instruction::setInstructionSubclassData(D);
4356 struct OperandTraits<CleanupReturnInst>
4357 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4359 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4361 //===----------------------------------------------------------------------===//
4362 // UnreachableInst Class
4363 //===----------------------------------------------------------------------===//
4365 //===---------------------------------------------------------------------------
4366 /// This function has undefined behavior. In particular, the
4367 /// presence of this instruction indicates some higher level knowledge that the
4368 /// end of the block cannot be reached.
4370 class UnreachableInst : public Instruction {
4372 // Note: Instruction needs to be a friend here to call cloneImpl.
4373 friend class Instruction;
4375 UnreachableInst *cloneImpl() const;
4378 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4379 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4381 // allocate space for exactly zero operands
4382 void *operator new(size_t s) {
4383 return User::operator new(s, 0);
4386 unsigned getNumSuccessors() const { return 0; }
4388 // Methods for support type inquiry through isa, cast, and dyn_cast:
4389 static bool classof(const Instruction *I) {
4390 return I->getOpcode() == Instruction::Unreachable;
4392 static bool classof(const Value *V) {
4393 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4397 BasicBlock *getSuccessor(unsigned idx) const {
4398 llvm_unreachable("UnreachableInst has no successors!");
4401 void setSuccessor(unsigned idx, BasicBlock *B) {
4402 llvm_unreachable("UnreachableInst has no successors!");
4406 //===----------------------------------------------------------------------===//
4408 //===----------------------------------------------------------------------===//
4410 /// This class represents a truncation of integer types.
4411 class TruncInst : public CastInst {
4413 // Note: Instruction needs to be a friend here to call cloneImpl.
4414 friend class Instruction;
4416 /// Clone an identical TruncInst
4417 TruncInst *cloneImpl() const;
4420 /// Constructor with insert-before-instruction semantics
4422 Value *S, ///< The value to be truncated
4423 Type *Ty, ///< The (smaller) type to truncate to
4424 const Twine &NameStr = "", ///< A name for the new instruction
4425 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4428 /// Constructor with insert-at-end-of-block semantics
4430 Value *S, ///< The value to be truncated
4431 Type *Ty, ///< The (smaller) type to truncate to
4432 const Twine &NameStr, ///< A name for the new instruction
4433 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4436 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4437 static bool classof(const Instruction *I) {
4438 return I->getOpcode() == Trunc;
4440 static bool classof(const Value *V) {
4441 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4445 //===----------------------------------------------------------------------===//
4447 //===----------------------------------------------------------------------===//
4449 /// This class represents zero extension of integer types.
4450 class ZExtInst : public CastInst {
4452 // Note: Instruction needs to be a friend here to call cloneImpl.
4453 friend class Instruction;
4455 /// Clone an identical ZExtInst
4456 ZExtInst *cloneImpl() const;
4459 /// Constructor with insert-before-instruction semantics
4461 Value *S, ///< The value to be zero extended
4462 Type *Ty, ///< The type to zero extend to
4463 const Twine &NameStr = "", ///< A name for the new instruction
4464 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4467 /// Constructor with insert-at-end semantics.
4469 Value *S, ///< The value to be zero extended
4470 Type *Ty, ///< The type to zero extend to
4471 const Twine &NameStr, ///< A name for the new instruction
4472 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4475 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4476 static bool classof(const Instruction *I) {
4477 return I->getOpcode() == ZExt;
4479 static bool classof(const Value *V) {
4480 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4484 //===----------------------------------------------------------------------===//
4486 //===----------------------------------------------------------------------===//
4488 /// This class represents a sign extension of integer types.
4489 class SExtInst : public CastInst {
4491 // Note: Instruction needs to be a friend here to call cloneImpl.
4492 friend class Instruction;
4494 /// Clone an identical SExtInst
4495 SExtInst *cloneImpl() const;
4498 /// Constructor with insert-before-instruction semantics
4500 Value *S, ///< The value to be sign extended
4501 Type *Ty, ///< The type to sign extend to
4502 const Twine &NameStr = "", ///< A name for the new instruction
4503 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4506 /// Constructor with insert-at-end-of-block semantics
4508 Value *S, ///< The value to be sign extended
4509 Type *Ty, ///< The type to sign extend to
4510 const Twine &NameStr, ///< A name for the new instruction
4511 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4514 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4515 static bool classof(const Instruction *I) {
4516 return I->getOpcode() == SExt;
4518 static bool classof(const Value *V) {
4519 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4523 //===----------------------------------------------------------------------===//
4524 // FPTruncInst Class
4525 //===----------------------------------------------------------------------===//
4527 /// This class represents a truncation of floating point types.
4528 class FPTruncInst : public CastInst {
4530 // Note: Instruction needs to be a friend here to call cloneImpl.
4531 friend class Instruction;
4533 /// Clone an identical FPTruncInst
4534 FPTruncInst *cloneImpl() const;
4537 /// Constructor with insert-before-instruction semantics
4539 Value *S, ///< The value to be truncated
4540 Type *Ty, ///< The type to truncate to
4541 const Twine &NameStr = "", ///< A name for the new instruction
4542 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4545 /// Constructor with insert-before-instruction semantics
4547 Value *S, ///< The value to be truncated
4548 Type *Ty, ///< The type to truncate to
4549 const Twine &NameStr, ///< A name for the new instruction
4550 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4553 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4554 static bool classof(const Instruction *I) {
4555 return I->getOpcode() == FPTrunc;
4557 static bool classof(const Value *V) {
4558 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4562 //===----------------------------------------------------------------------===//
4564 //===----------------------------------------------------------------------===//
4566 /// This class represents an extension of floating point types.
4567 class FPExtInst : public CastInst {
4569 // Note: Instruction needs to be a friend here to call cloneImpl.
4570 friend class Instruction;
4572 /// Clone an identical FPExtInst
4573 FPExtInst *cloneImpl() const;
4576 /// Constructor with insert-before-instruction semantics
4578 Value *S, ///< The value to be extended
4579 Type *Ty, ///< The type to extend to
4580 const Twine &NameStr = "", ///< A name for the new instruction
4581 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4584 /// Constructor with insert-at-end-of-block semantics
4586 Value *S, ///< The value to be extended
4587 Type *Ty, ///< The type to extend to
4588 const Twine &NameStr, ///< A name for the new instruction
4589 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4592 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4593 static bool classof(const Instruction *I) {
4594 return I->getOpcode() == FPExt;
4596 static bool classof(const Value *V) {
4597 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4601 //===----------------------------------------------------------------------===//
4603 //===----------------------------------------------------------------------===//
4605 /// This class represents a cast unsigned integer to floating point.
4606 class UIToFPInst : public CastInst {
4608 // Note: Instruction needs to be a friend here to call cloneImpl.
4609 friend class Instruction;
4611 /// Clone an identical UIToFPInst
4612 UIToFPInst *cloneImpl() const;
4615 /// Constructor with insert-before-instruction semantics
4617 Value *S, ///< The value to be converted
4618 Type *Ty, ///< The type to convert to
4619 const Twine &NameStr = "", ///< A name for the new instruction
4620 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4623 /// Constructor with insert-at-end-of-block semantics
4625 Value *S, ///< The value to be converted
4626 Type *Ty, ///< The type to convert to
4627 const Twine &NameStr, ///< A name for the new instruction
4628 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4631 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4632 static bool classof(const Instruction *I) {
4633 return I->getOpcode() == UIToFP;
4635 static bool classof(const Value *V) {
4636 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4640 //===----------------------------------------------------------------------===//
4642 //===----------------------------------------------------------------------===//
4644 /// This class represents a cast from signed integer to floating point.
4645 class SIToFPInst : public CastInst {
4647 // Note: Instruction needs to be a friend here to call cloneImpl.
4648 friend class Instruction;
4650 /// Clone an identical SIToFPInst
4651 SIToFPInst *cloneImpl() const;
4654 /// Constructor with insert-before-instruction semantics
4656 Value *S, ///< The value to be converted
4657 Type *Ty, ///< The type to convert to
4658 const Twine &NameStr = "", ///< A name for the new instruction
4659 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4662 /// Constructor with insert-at-end-of-block semantics
4664 Value *S, ///< The value to be converted
4665 Type *Ty, ///< The type to convert to
4666 const Twine &NameStr, ///< A name for the new instruction
4667 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4670 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4671 static bool classof(const Instruction *I) {
4672 return I->getOpcode() == SIToFP;
4674 static bool classof(const Value *V) {
4675 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4679 //===----------------------------------------------------------------------===//
4681 //===----------------------------------------------------------------------===//
4683 /// This class represents a cast from floating point to unsigned integer
4684 class FPToUIInst : public CastInst {
4686 // Note: Instruction needs to be a friend here to call cloneImpl.
4687 friend class Instruction;
4689 /// Clone an identical FPToUIInst
4690 FPToUIInst *cloneImpl() const;
4693 /// Constructor with insert-before-instruction semantics
4695 Value *S, ///< The value to be converted
4696 Type *Ty, ///< The type to convert to
4697 const Twine &NameStr = "", ///< A name for the new instruction
4698 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4701 /// Constructor with insert-at-end-of-block semantics
4703 Value *S, ///< The value to be converted
4704 Type *Ty, ///< The type to convert to
4705 const Twine &NameStr, ///< A name for the new instruction
4706 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
4709 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4710 static bool classof(const Instruction *I) {
4711 return I->getOpcode() == FPToUI;
4713 static bool classof(const Value *V) {
4714 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4718 //===----------------------------------------------------------------------===//
4720 //===----------------------------------------------------------------------===//
4722 /// This class represents a cast from floating point to signed integer.
4723 class FPToSIInst : public CastInst {
4725 // Note: Instruction needs to be a friend here to call cloneImpl.
4726 friend class Instruction;
4728 /// Clone an identical FPToSIInst
4729 FPToSIInst *cloneImpl() const;
4732 /// Constructor with insert-before-instruction semantics
4734 Value *S, ///< The value to be converted
4735 Type *Ty, ///< The type to convert to
4736 const Twine &NameStr = "", ///< A name for the new instruction
4737 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4740 /// Constructor with insert-at-end-of-block semantics
4742 Value *S, ///< The value to be converted
4743 Type *Ty, ///< The type to convert to
4744 const Twine &NameStr, ///< A name for the new instruction
4745 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4748 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4749 static bool classof(const Instruction *I) {
4750 return I->getOpcode() == FPToSI;
4752 static bool classof(const Value *V) {
4753 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4757 //===----------------------------------------------------------------------===//
4758 // IntToPtrInst Class
4759 //===----------------------------------------------------------------------===//
4761 /// This class represents a cast from an integer to a pointer.
4762 class IntToPtrInst : public CastInst {
4764 // Note: Instruction needs to be a friend here to call cloneImpl.
4765 friend class Instruction;
4767 /// Constructor with insert-before-instruction semantics
4769 Value *S, ///< The value to be converted
4770 Type *Ty, ///< The type to convert to
4771 const Twine &NameStr = "", ///< A name for the new instruction
4772 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4775 /// Constructor with insert-at-end-of-block semantics
4777 Value *S, ///< The value to be converted
4778 Type *Ty, ///< The type to convert to
4779 const Twine &NameStr, ///< A name for the new instruction
4780 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4783 /// Clone an identical IntToPtrInst.
4784 IntToPtrInst *cloneImpl() const;
4786 /// Returns the address space of this instruction's pointer type.
4787 unsigned getAddressSpace() const {
4788 return getType()->getPointerAddressSpace();
4791 // Methods for support type inquiry through isa, cast, and dyn_cast:
4792 static bool classof(const Instruction *I) {
4793 return I->getOpcode() == IntToPtr;
4795 static bool classof(const Value *V) {
4796 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4800 //===----------------------------------------------------------------------===//
4801 // PtrToIntInst Class
4802 //===----------------------------------------------------------------------===//
4804 /// This class represents a cast from a pointer to an integer.
4805 class PtrToIntInst : public CastInst {
4807 // Note: Instruction needs to be a friend here to call cloneImpl.
4808 friend class Instruction;
4810 /// Clone an identical PtrToIntInst.
4811 PtrToIntInst *cloneImpl() const;
4814 /// Constructor with insert-before-instruction semantics
4816 Value *S, ///< The value to be converted
4817 Type *Ty, ///< The type to convert to
4818 const Twine &NameStr = "", ///< A name for the new instruction
4819 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4822 /// Constructor with insert-at-end-of-block semantics
4824 Value *S, ///< The value to be converted
4825 Type *Ty, ///< The type to convert to
4826 const Twine &NameStr, ///< A name for the new instruction
4827 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4830 /// Gets the pointer operand.
4831 Value *getPointerOperand() { return getOperand(0); }
4832 /// Gets the pointer operand.
4833 const Value *getPointerOperand() const { return getOperand(0); }
4834 /// Gets the operand index of the pointer operand.
4835 static unsigned getPointerOperandIndex() { return 0U; }
4837 /// Returns the address space of the pointer operand.
4838 unsigned getPointerAddressSpace() const {
4839 return getPointerOperand()->getType()->getPointerAddressSpace();
4842 // Methods for support type inquiry through isa, cast, and dyn_cast:
4843 static bool classof(const Instruction *I) {
4844 return I->getOpcode() == PtrToInt;
4846 static bool classof(const Value *V) {
4847 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4851 //===----------------------------------------------------------------------===//
4852 // BitCastInst Class
4853 //===----------------------------------------------------------------------===//
4855 /// This class represents a no-op cast from one type to another.
4856 class BitCastInst : public CastInst {
4858 // Note: Instruction needs to be a friend here to call cloneImpl.
4859 friend class Instruction;
4861 /// Clone an identical BitCastInst.
4862 BitCastInst *cloneImpl() const;
4865 /// Constructor with insert-before-instruction semantics
4867 Value *S, ///< The value to be casted
4868 Type *Ty, ///< The type to casted to
4869 const Twine &NameStr = "", ///< A name for the new instruction
4870 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4873 /// Constructor with insert-at-end-of-block semantics
4875 Value *S, ///< The value to be casted
4876 Type *Ty, ///< The type to casted to
4877 const Twine &NameStr, ///< A name for the new instruction
4878 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4881 // Methods for support type inquiry through isa, cast, and dyn_cast:
4882 static bool classof(const Instruction *I) {
4883 return I->getOpcode() == BitCast;
4885 static bool classof(const Value *V) {
4886 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4890 //===----------------------------------------------------------------------===//
4891 // AddrSpaceCastInst Class
4892 //===----------------------------------------------------------------------===//
4894 /// This class represents a conversion between pointers from one address space
4896 class AddrSpaceCastInst : public CastInst {
4898 // Note: Instruction needs to be a friend here to call cloneImpl.
4899 friend class Instruction;
4901 /// Clone an identical AddrSpaceCastInst.
4902 AddrSpaceCastInst *cloneImpl() const;
4905 /// Constructor with insert-before-instruction semantics
4907 Value *S, ///< The value to be casted
4908 Type *Ty, ///< The type to casted to
4909 const Twine &NameStr = "", ///< A name for the new instruction
4910 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4913 /// Constructor with insert-at-end-of-block semantics
4915 Value *S, ///< The value to be casted
4916 Type *Ty, ///< The type to casted to
4917 const Twine &NameStr, ///< A name for the new instruction
4918 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4921 // Methods for support type inquiry through isa, cast, and dyn_cast:
4922 static bool classof(const Instruction *I) {
4923 return I->getOpcode() == AddrSpaceCast;
4925 static bool classof(const Value *V) {
4926 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4929 /// Gets the pointer operand.
4930 Value *getPointerOperand() {
4931 return getOperand(0);
4934 /// Gets the pointer operand.
4935 const Value *getPointerOperand() const {
4936 return getOperand(0);
4939 /// Gets the operand index of the pointer operand.
4940 static unsigned getPointerOperandIndex() {
4944 /// Returns the address space of the pointer operand.
4945 unsigned getSrcAddressSpace() const {
4946 return getPointerOperand()->getType()->getPointerAddressSpace();
4949 /// Returns the address space of the result.
4950 unsigned getDestAddressSpace() const {
4951 return getType()->getPointerAddressSpace();
4955 /// A helper function that returns the pointer operand of a load or store
4956 /// instruction. Returns nullptr if not load or store.
4957 inline Value *getLoadStorePointerOperand(Value *V) {
4958 if (auto *Load = dyn_cast<LoadInst>(V))
4959 return Load->getPointerOperand();
4960 if (auto *Store = dyn_cast<StoreInst>(V))
4961 return Store->getPointerOperand();
4965 /// A helper function that returns the pointer operand of a load, store
4966 /// or GEP instruction. Returns nullptr if not load, store, or GEP.
4967 inline Value *getPointerOperand(Value *V) {
4968 if (auto *Ptr = getLoadStorePointerOperand(V))
4970 if (auto *Gep = dyn_cast<GetElementPtrInst>(V))
4971 return Gep->getPointerOperand();
4975 /// A helper function that returns the alignment of load or store instruction.
4976 inline unsigned getLoadStoreAlignment(Value *I) {
4977 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4978 "Expected Load or Store instruction");
4979 if (auto *LI = dyn_cast<LoadInst>(I))
4980 return LI->getAlignment();
4981 return cast<StoreInst>(I)->getAlignment();
4984 /// A helper function that returns the address space of the pointer operand of
4985 /// load or store instruction.
4986 inline unsigned getLoadStoreAddressSpace(Value *I) {
4987 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4988 "Expected Load or Store instruction");
4989 if (auto *LI = dyn_cast<LoadInst>(I))
4990 return LI->getPointerAddressSpace();
4991 return cast<StoreInst>(I)->getPointerAddressSpace();
4994 } // end namespace llvm
4996 #endif // LLVM_IR_INSTRUCTIONS_H