Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / IR / Instructions.h
bloba82cedab25d4bddda0a4c112f07728979d702328
1 //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file exposes the class definitions of all of the subclasses of the
10 // Instruction class. This is meant to be an easy way to get access to all
11 // instruction subclasses.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_INSTRUCTIONS_H
16 #define LLVM_IR_INSTRUCTIONS_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/ADT/iterator.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/InstrTypes.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/OperandTraits.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/Use.h"
37 #include "llvm/IR/User.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Support/AtomicOrdering.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include <cassert>
43 #include <cstddef>
44 #include <cstdint>
45 #include <iterator>
47 namespace llvm {
49 class APInt;
50 class ConstantInt;
51 class DataLayout;
52 class LLVMContext;
54 //===----------------------------------------------------------------------===//
55 // AllocaInst Class
56 //===----------------------------------------------------------------------===//
58 /// an instruction to allocate memory on the stack
59 class AllocaInst : public UnaryInstruction {
60 Type *AllocatedType;
62 protected:
63 // Note: Instruction needs to be a friend here to call cloneImpl.
64 friend class Instruction;
66 AllocaInst *cloneImpl() const;
68 public:
69 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
70 Value *ArraySize = nullptr,
71 const Twine &Name = "",
72 Instruction *InsertBefore = nullptr);
73 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
74 const Twine &Name, BasicBlock *InsertAtEnd);
76 AllocaInst(Type *Ty, unsigned AddrSpace,
77 const Twine &Name, Instruction *InsertBefore = nullptr);
78 AllocaInst(Type *Ty, unsigned AddrSpace,
79 const Twine &Name, BasicBlock *InsertAtEnd);
81 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
82 const Twine &Name = "", Instruction *InsertBefore = nullptr);
83 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
84 const Twine &Name, BasicBlock *InsertAtEnd);
86 /// Return true if there is an allocation size parameter to the allocation
87 /// instruction that is not 1.
88 bool isArrayAllocation() const;
90 /// Get the number of elements allocated. For a simple allocation of a single
91 /// element, this will return a constant 1 value.
92 const Value *getArraySize() const { return getOperand(0); }
93 Value *getArraySize() { return getOperand(0); }
95 /// Overload to return most specific pointer type.
96 PointerType *getType() const {
97 return cast<PointerType>(Instruction::getType());
100 /// Get allocation size in bits. Returns None if size can't be determined,
101 /// e.g. in case of a VLA.
102 Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const;
104 /// Return the type that is being allocated by the instruction.
105 Type *getAllocatedType() const { return AllocatedType; }
106 /// for use only in special circumstances that need to generically
107 /// transform a whole instruction (eg: IR linking and vectorization).
108 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
110 /// Return the alignment of the memory that is being allocated by the
111 /// instruction.
112 unsigned getAlignment() const {
113 return (1u << (getSubclassDataFromInstruction() & 31)) >> 1;
115 void setAlignment(unsigned Align);
117 /// Return true if this alloca is in the entry block of the function and is a
118 /// constant size. If so, the code generator will fold it into the
119 /// prolog/epilog code, so it is basically free.
120 bool isStaticAlloca() const;
122 /// Return true if this alloca is used as an inalloca argument to a call. Such
123 /// allocas are never considered static even if they are in the entry block.
124 bool isUsedWithInAlloca() const {
125 return getSubclassDataFromInstruction() & 32;
128 /// Specify whether this alloca is used to represent the arguments to a call.
129 void setUsedWithInAlloca(bool V) {
130 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
131 (V ? 32 : 0));
134 /// Return true if this alloca is used as a swifterror argument to a call.
135 bool isSwiftError() const {
136 return getSubclassDataFromInstruction() & 64;
139 /// Specify whether this alloca is used to represent a swifterror.
140 void setSwiftError(bool V) {
141 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
142 (V ? 64 : 0));
145 // Methods for support type inquiry through isa, cast, and dyn_cast:
146 static bool classof(const Instruction *I) {
147 return (I->getOpcode() == Instruction::Alloca);
149 static bool classof(const Value *V) {
150 return isa<Instruction>(V) && classof(cast<Instruction>(V));
153 private:
154 // Shadow Instruction::setInstructionSubclassData with a private forwarding
155 // method so that subclasses cannot accidentally use it.
156 void setInstructionSubclassData(unsigned short D) {
157 Instruction::setInstructionSubclassData(D);
161 //===----------------------------------------------------------------------===//
162 // LoadInst Class
163 //===----------------------------------------------------------------------===//
165 /// An instruction for reading from memory. This uses the SubclassData field in
166 /// Value to store whether or not the load is volatile.
167 class LoadInst : public UnaryInstruction {
168 void AssertOK();
170 protected:
171 // Note: Instruction needs to be a friend here to call cloneImpl.
172 friend class Instruction;
174 LoadInst *cloneImpl() const;
176 public:
177 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
178 Instruction *InsertBefore = nullptr);
179 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
180 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
181 Instruction *InsertBefore = nullptr);
182 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
183 BasicBlock *InsertAtEnd);
184 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
185 unsigned Align, Instruction *InsertBefore = nullptr);
186 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187 unsigned Align, BasicBlock *InsertAtEnd);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 unsigned Align, AtomicOrdering Order,
190 SyncScope::ID SSID = SyncScope::System,
191 Instruction *InsertBefore = nullptr);
192 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
193 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
194 BasicBlock *InsertAtEnd);
196 // Deprecated [opaque pointer types]
197 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
198 Instruction *InsertBefore = nullptr)
199 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
200 InsertBefore) {}
201 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
202 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
203 InsertAtEnd) {}
204 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
205 Instruction *InsertBefore = nullptr)
206 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
207 isVolatile, InsertBefore) {}
208 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
209 BasicBlock *InsertAtEnd)
210 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
211 isVolatile, InsertAtEnd) {}
212 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
213 Instruction *InsertBefore = nullptr)
214 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
215 isVolatile, Align, InsertBefore) {}
216 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
217 BasicBlock *InsertAtEnd)
218 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
219 isVolatile, Align, InsertAtEnd) {}
220 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
221 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
222 Instruction *InsertBefore = nullptr)
223 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
224 isVolatile, Align, Order, SSID, InsertBefore) {}
225 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
226 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
227 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
228 isVolatile, Align, Order, SSID, InsertAtEnd) {}
230 /// Return true if this is a load from a volatile memory location.
231 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
233 /// Specify whether this is a volatile load or not.
234 void setVolatile(bool V) {
235 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
236 (V ? 1 : 0));
239 /// Return the alignment of the access that is being performed.
240 unsigned getAlignment() const {
241 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
244 void setAlignment(unsigned Align);
246 /// Returns the ordering constraint of this load instruction.
247 AtomicOrdering getOrdering() const {
248 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
251 /// Sets the ordering constraint of this load instruction. May not be Release
252 /// or AcquireRelease.
253 void setOrdering(AtomicOrdering Ordering) {
254 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
255 ((unsigned)Ordering << 7));
258 /// Returns the synchronization scope ID of this load instruction.
259 SyncScope::ID getSyncScopeID() const {
260 return SSID;
263 /// Sets the synchronization scope ID of this load instruction.
264 void setSyncScopeID(SyncScope::ID SSID) {
265 this->SSID = SSID;
268 /// Sets the ordering constraint and the synchronization scope ID of this load
269 /// instruction.
270 void setAtomic(AtomicOrdering Ordering,
271 SyncScope::ID SSID = SyncScope::System) {
272 setOrdering(Ordering);
273 setSyncScopeID(SSID);
276 bool isSimple() const { return !isAtomic() && !isVolatile(); }
278 bool isUnordered() const {
279 return (getOrdering() == AtomicOrdering::NotAtomic ||
280 getOrdering() == AtomicOrdering::Unordered) &&
281 !isVolatile();
284 Value *getPointerOperand() { return getOperand(0); }
285 const Value *getPointerOperand() const { return getOperand(0); }
286 static unsigned getPointerOperandIndex() { return 0U; }
287 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
289 /// Returns the address space of the pointer operand.
290 unsigned getPointerAddressSpace() const {
291 return getPointerOperandType()->getPointerAddressSpace();
294 // Methods for support type inquiry through isa, cast, and dyn_cast:
295 static bool classof(const Instruction *I) {
296 return I->getOpcode() == Instruction::Load;
298 static bool classof(const Value *V) {
299 return isa<Instruction>(V) && classof(cast<Instruction>(V));
302 private:
303 // Shadow Instruction::setInstructionSubclassData with a private forwarding
304 // method so that subclasses cannot accidentally use it.
305 void setInstructionSubclassData(unsigned short D) {
306 Instruction::setInstructionSubclassData(D);
309 /// The synchronization scope ID of this load instruction. Not quite enough
310 /// room in SubClassData for everything, so synchronization scope ID gets its
311 /// own field.
312 SyncScope::ID SSID;
315 //===----------------------------------------------------------------------===//
316 // StoreInst Class
317 //===----------------------------------------------------------------------===//
319 /// An instruction for storing to memory.
320 class StoreInst : public Instruction {
321 void AssertOK();
323 protected:
324 // Note: Instruction needs to be a friend here to call cloneImpl.
325 friend class Instruction;
327 StoreInst *cloneImpl() const;
329 public:
330 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
331 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
332 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
333 Instruction *InsertBefore = nullptr);
334 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
335 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
336 unsigned Align, Instruction *InsertBefore = nullptr);
337 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
338 unsigned Align, BasicBlock *InsertAtEnd);
339 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
340 unsigned Align, AtomicOrdering Order,
341 SyncScope::ID SSID = SyncScope::System,
342 Instruction *InsertBefore = nullptr);
343 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
344 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
345 BasicBlock *InsertAtEnd);
347 // allocate space for exactly two operands
348 void *operator new(size_t s) {
349 return User::operator new(s, 2);
352 /// Return true if this is a store to a volatile memory location.
353 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
355 /// Specify whether this is a volatile store or not.
356 void setVolatile(bool V) {
357 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
358 (V ? 1 : 0));
361 /// Transparently provide more efficient getOperand methods.
362 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
364 /// Return the alignment of the access that is being performed
365 unsigned getAlignment() const {
366 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
369 void setAlignment(unsigned Align);
371 /// Returns the ordering constraint of this store instruction.
372 AtomicOrdering getOrdering() const {
373 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
376 /// Sets the ordering constraint of this store instruction. May not be
377 /// Acquire or AcquireRelease.
378 void setOrdering(AtomicOrdering Ordering) {
379 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
380 ((unsigned)Ordering << 7));
383 /// Returns the synchronization scope ID of this store instruction.
384 SyncScope::ID getSyncScopeID() const {
385 return SSID;
388 /// Sets the synchronization scope ID of this store instruction.
389 void setSyncScopeID(SyncScope::ID SSID) {
390 this->SSID = SSID;
393 /// Sets the ordering constraint and the synchronization scope ID of this
394 /// store instruction.
395 void setAtomic(AtomicOrdering Ordering,
396 SyncScope::ID SSID = SyncScope::System) {
397 setOrdering(Ordering);
398 setSyncScopeID(SSID);
401 bool isSimple() const { return !isAtomic() && !isVolatile(); }
403 bool isUnordered() const {
404 return (getOrdering() == AtomicOrdering::NotAtomic ||
405 getOrdering() == AtomicOrdering::Unordered) &&
406 !isVolatile();
409 Value *getValueOperand() { return getOperand(0); }
410 const Value *getValueOperand() const { return getOperand(0); }
412 Value *getPointerOperand() { return getOperand(1); }
413 const Value *getPointerOperand() const { return getOperand(1); }
414 static unsigned getPointerOperandIndex() { return 1U; }
415 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
417 /// Returns the address space of the pointer operand.
418 unsigned getPointerAddressSpace() const {
419 return getPointerOperandType()->getPointerAddressSpace();
422 // Methods for support type inquiry through isa, cast, and dyn_cast:
423 static bool classof(const Instruction *I) {
424 return I->getOpcode() == Instruction::Store;
426 static bool classof(const Value *V) {
427 return isa<Instruction>(V) && classof(cast<Instruction>(V));
430 private:
431 // Shadow Instruction::setInstructionSubclassData with a private forwarding
432 // method so that subclasses cannot accidentally use it.
433 void setInstructionSubclassData(unsigned short D) {
434 Instruction::setInstructionSubclassData(D);
437 /// The synchronization scope ID of this store instruction. Not quite enough
438 /// room in SubClassData for everything, so synchronization scope ID gets its
439 /// own field.
440 SyncScope::ID SSID;
443 template <>
444 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
447 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
449 //===----------------------------------------------------------------------===//
450 // FenceInst Class
451 //===----------------------------------------------------------------------===//
453 /// An instruction for ordering other memory operations.
454 class FenceInst : public Instruction {
455 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
457 protected:
458 // Note: Instruction needs to be a friend here to call cloneImpl.
459 friend class Instruction;
461 FenceInst *cloneImpl() const;
463 public:
464 // Ordering may only be Acquire, Release, AcquireRelease, or
465 // SequentiallyConsistent.
466 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
467 SyncScope::ID SSID = SyncScope::System,
468 Instruction *InsertBefore = nullptr);
469 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
470 BasicBlock *InsertAtEnd);
472 // allocate space for exactly zero operands
473 void *operator new(size_t s) {
474 return User::operator new(s, 0);
477 /// Returns the ordering constraint of this fence instruction.
478 AtomicOrdering getOrdering() const {
479 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
482 /// Sets the ordering constraint of this fence instruction. May only be
483 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
484 void setOrdering(AtomicOrdering Ordering) {
485 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
486 ((unsigned)Ordering << 1));
489 /// Returns the synchronization scope ID of this fence instruction.
490 SyncScope::ID getSyncScopeID() const {
491 return SSID;
494 /// Sets the synchronization scope ID of this fence instruction.
495 void setSyncScopeID(SyncScope::ID SSID) {
496 this->SSID = SSID;
499 // Methods for support type inquiry through isa, cast, and dyn_cast:
500 static bool classof(const Instruction *I) {
501 return I->getOpcode() == Instruction::Fence;
503 static bool classof(const Value *V) {
504 return isa<Instruction>(V) && classof(cast<Instruction>(V));
507 private:
508 // Shadow Instruction::setInstructionSubclassData with a private forwarding
509 // method so that subclasses cannot accidentally use it.
510 void setInstructionSubclassData(unsigned short D) {
511 Instruction::setInstructionSubclassData(D);
514 /// The synchronization scope ID of this fence instruction. Not quite enough
515 /// room in SubClassData for everything, so synchronization scope ID gets its
516 /// own field.
517 SyncScope::ID SSID;
520 //===----------------------------------------------------------------------===//
521 // AtomicCmpXchgInst Class
522 //===----------------------------------------------------------------------===//
524 /// an instruction that atomically checks whether a
525 /// specified value is in a memory location, and, if it is, stores a new value
526 /// there. Returns the value that was loaded.
528 class AtomicCmpXchgInst : public Instruction {
529 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
530 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
531 SyncScope::ID SSID);
533 protected:
534 // Note: Instruction needs to be a friend here to call cloneImpl.
535 friend class Instruction;
537 AtomicCmpXchgInst *cloneImpl() const;
539 public:
540 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
541 AtomicOrdering SuccessOrdering,
542 AtomicOrdering FailureOrdering,
543 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
544 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
545 AtomicOrdering SuccessOrdering,
546 AtomicOrdering FailureOrdering,
547 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
549 // allocate space for exactly three operands
550 void *operator new(size_t s) {
551 return User::operator new(s, 3);
554 /// Return true if this is a cmpxchg from a volatile memory
555 /// location.
557 bool isVolatile() const {
558 return getSubclassDataFromInstruction() & 1;
561 /// Specify whether this is a volatile cmpxchg.
563 void setVolatile(bool V) {
564 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
565 (unsigned)V);
568 /// Return true if this cmpxchg may spuriously fail.
569 bool isWeak() const {
570 return getSubclassDataFromInstruction() & 0x100;
573 void setWeak(bool IsWeak) {
574 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
575 (IsWeak << 8));
578 /// Transparently provide more efficient getOperand methods.
579 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
581 /// Returns the success ordering constraint of this cmpxchg instruction.
582 AtomicOrdering getSuccessOrdering() const {
583 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
586 /// Sets the success ordering constraint of this cmpxchg instruction.
587 void setSuccessOrdering(AtomicOrdering Ordering) {
588 assert(Ordering != AtomicOrdering::NotAtomic &&
589 "CmpXchg instructions can only be atomic.");
590 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
591 ((unsigned)Ordering << 2));
594 /// Returns the failure ordering constraint of this cmpxchg instruction.
595 AtomicOrdering getFailureOrdering() const {
596 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
599 /// Sets the failure ordering constraint of this cmpxchg instruction.
600 void setFailureOrdering(AtomicOrdering Ordering) {
601 assert(Ordering != AtomicOrdering::NotAtomic &&
602 "CmpXchg instructions can only be atomic.");
603 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
604 ((unsigned)Ordering << 5));
607 /// Returns the synchronization scope ID of this cmpxchg instruction.
608 SyncScope::ID getSyncScopeID() const {
609 return SSID;
612 /// Sets the synchronization scope ID of this cmpxchg instruction.
613 void setSyncScopeID(SyncScope::ID SSID) {
614 this->SSID = SSID;
617 Value *getPointerOperand() { return getOperand(0); }
618 const Value *getPointerOperand() const { return getOperand(0); }
619 static unsigned getPointerOperandIndex() { return 0U; }
621 Value *getCompareOperand() { return getOperand(1); }
622 const Value *getCompareOperand() const { return getOperand(1); }
624 Value *getNewValOperand() { return getOperand(2); }
625 const Value *getNewValOperand() const { return getOperand(2); }
627 /// Returns the address space of the pointer operand.
628 unsigned getPointerAddressSpace() const {
629 return getPointerOperand()->getType()->getPointerAddressSpace();
632 /// Returns the strongest permitted ordering on failure, given the
633 /// desired ordering on success.
635 /// If the comparison in a cmpxchg operation fails, there is no atomic store
636 /// so release semantics cannot be provided. So this function drops explicit
637 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
638 /// operation would remain SequentiallyConsistent.
639 static AtomicOrdering
640 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
641 switch (SuccessOrdering) {
642 default:
643 llvm_unreachable("invalid cmpxchg success ordering");
644 case AtomicOrdering::Release:
645 case AtomicOrdering::Monotonic:
646 return AtomicOrdering::Monotonic;
647 case AtomicOrdering::AcquireRelease:
648 case AtomicOrdering::Acquire:
649 return AtomicOrdering::Acquire;
650 case AtomicOrdering::SequentiallyConsistent:
651 return AtomicOrdering::SequentiallyConsistent;
655 // Methods for support type inquiry through isa, cast, and dyn_cast:
656 static bool classof(const Instruction *I) {
657 return I->getOpcode() == Instruction::AtomicCmpXchg;
659 static bool classof(const Value *V) {
660 return isa<Instruction>(V) && classof(cast<Instruction>(V));
663 private:
664 // Shadow Instruction::setInstructionSubclassData with a private forwarding
665 // method so that subclasses cannot accidentally use it.
666 void setInstructionSubclassData(unsigned short D) {
667 Instruction::setInstructionSubclassData(D);
670 /// The synchronization scope ID of this cmpxchg instruction. Not quite
671 /// enough room in SubClassData for everything, so synchronization scope ID
672 /// gets its own field.
673 SyncScope::ID SSID;
676 template <>
677 struct OperandTraits<AtomicCmpXchgInst> :
678 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
681 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
683 //===----------------------------------------------------------------------===//
684 // AtomicRMWInst Class
685 //===----------------------------------------------------------------------===//
687 /// an instruction that atomically reads a memory location,
688 /// combines it with another value, and then stores the result back. Returns
689 /// the old value.
691 class AtomicRMWInst : public Instruction {
692 protected:
693 // Note: Instruction needs to be a friend here to call cloneImpl.
694 friend class Instruction;
696 AtomicRMWInst *cloneImpl() const;
698 public:
699 /// This enumeration lists the possible modifications atomicrmw can make. In
700 /// the descriptions, 'p' is the pointer to the instruction's memory location,
701 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
702 /// instruction. These instructions always return 'old'.
703 enum BinOp {
704 /// *p = v
705 Xchg,
706 /// *p = old + v
707 Add,
708 /// *p = old - v
709 Sub,
710 /// *p = old & v
711 And,
712 /// *p = ~(old & v)
713 Nand,
714 /// *p = old | v
716 /// *p = old ^ v
717 Xor,
718 /// *p = old >signed v ? old : v
719 Max,
720 /// *p = old <signed v ? old : v
721 Min,
722 /// *p = old >unsigned v ? old : v
723 UMax,
724 /// *p = old <unsigned v ? old : v
725 UMin,
727 /// *p = old + v
728 FAdd,
730 /// *p = old - v
731 FSub,
733 FIRST_BINOP = Xchg,
734 LAST_BINOP = FSub,
735 BAD_BINOP
738 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
739 AtomicOrdering Ordering, SyncScope::ID SSID,
740 Instruction *InsertBefore = nullptr);
741 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
742 AtomicOrdering Ordering, SyncScope::ID SSID,
743 BasicBlock *InsertAtEnd);
745 // allocate space for exactly two operands
746 void *operator new(size_t s) {
747 return User::operator new(s, 2);
750 BinOp getOperation() const {
751 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
754 static StringRef getOperationName(BinOp Op);
756 static bool isFPOperation(BinOp Op) {
757 switch (Op) {
758 case AtomicRMWInst::FAdd:
759 case AtomicRMWInst::FSub:
760 return true;
761 default:
762 return false;
766 void setOperation(BinOp Operation) {
767 unsigned short SubclassData = getSubclassDataFromInstruction();
768 setInstructionSubclassData((SubclassData & 31) |
769 (Operation << 5));
772 /// Return true if this is a RMW on a volatile memory location.
774 bool isVolatile() const {
775 return getSubclassDataFromInstruction() & 1;
778 /// Specify whether this is a volatile RMW or not.
780 void setVolatile(bool V) {
781 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
782 (unsigned)V);
785 /// Transparently provide more efficient getOperand methods.
786 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
788 /// Returns the ordering constraint of this rmw instruction.
789 AtomicOrdering getOrdering() const {
790 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
793 /// Sets the ordering constraint of this rmw instruction.
794 void setOrdering(AtomicOrdering Ordering) {
795 assert(Ordering != AtomicOrdering::NotAtomic &&
796 "atomicrmw instructions can only be atomic.");
797 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
798 ((unsigned)Ordering << 2));
801 /// Returns the synchronization scope ID of this rmw instruction.
802 SyncScope::ID getSyncScopeID() const {
803 return SSID;
806 /// Sets the synchronization scope ID of this rmw instruction.
807 void setSyncScopeID(SyncScope::ID SSID) {
808 this->SSID = SSID;
811 Value *getPointerOperand() { return getOperand(0); }
812 const Value *getPointerOperand() const { return getOperand(0); }
813 static unsigned getPointerOperandIndex() { return 0U; }
815 Value *getValOperand() { return getOperand(1); }
816 const Value *getValOperand() const { return getOperand(1); }
818 /// Returns the address space of the pointer operand.
819 unsigned getPointerAddressSpace() const {
820 return getPointerOperand()->getType()->getPointerAddressSpace();
823 bool isFloatingPointOperation() const {
824 return isFPOperation(getOperation());
827 // Methods for support type inquiry through isa, cast, and dyn_cast:
828 static bool classof(const Instruction *I) {
829 return I->getOpcode() == Instruction::AtomicRMW;
831 static bool classof(const Value *V) {
832 return isa<Instruction>(V) && classof(cast<Instruction>(V));
835 private:
836 void Init(BinOp Operation, Value *Ptr, Value *Val,
837 AtomicOrdering Ordering, SyncScope::ID SSID);
839 // Shadow Instruction::setInstructionSubclassData with a private forwarding
840 // method so that subclasses cannot accidentally use it.
841 void setInstructionSubclassData(unsigned short D) {
842 Instruction::setInstructionSubclassData(D);
845 /// The synchronization scope ID of this rmw instruction. Not quite enough
846 /// room in SubClassData for everything, so synchronization scope ID gets its
847 /// own field.
848 SyncScope::ID SSID;
851 template <>
852 struct OperandTraits<AtomicRMWInst>
853 : public FixedNumOperandTraits<AtomicRMWInst,2> {
856 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
858 //===----------------------------------------------------------------------===//
859 // GetElementPtrInst Class
860 //===----------------------------------------------------------------------===//
862 // checkGEPType - Simple wrapper function to give a better assertion failure
863 // message on bad indexes for a gep instruction.
865 inline Type *checkGEPType(Type *Ty) {
866 assert(Ty && "Invalid GetElementPtrInst indices for type!");
867 return Ty;
870 /// an instruction for type-safe pointer arithmetic to
871 /// access elements of arrays and structs
873 class GetElementPtrInst : public Instruction {
874 Type *SourceElementType;
875 Type *ResultElementType;
877 GetElementPtrInst(const GetElementPtrInst &GEPI);
879 /// Constructors - Create a getelementptr instruction with a base pointer an
880 /// list of indices. The first ctor can optionally insert before an existing
881 /// instruction, the second appends the new instruction to the specified
882 /// BasicBlock.
883 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
884 ArrayRef<Value *> IdxList, unsigned Values,
885 const Twine &NameStr, Instruction *InsertBefore);
886 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
887 ArrayRef<Value *> IdxList, unsigned Values,
888 const Twine &NameStr, BasicBlock *InsertAtEnd);
890 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
892 protected:
893 // Note: Instruction needs to be a friend here to call cloneImpl.
894 friend class Instruction;
896 GetElementPtrInst *cloneImpl() const;
898 public:
899 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
900 ArrayRef<Value *> IdxList,
901 const Twine &NameStr = "",
902 Instruction *InsertBefore = nullptr) {
903 unsigned Values = 1 + unsigned(IdxList.size());
904 if (!PointeeType)
905 PointeeType =
906 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
907 else
908 assert(
909 PointeeType ==
910 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
911 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
912 NameStr, InsertBefore);
915 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
916 ArrayRef<Value *> IdxList,
917 const Twine &NameStr,
918 BasicBlock *InsertAtEnd) {
919 unsigned Values = 1 + unsigned(IdxList.size());
920 if (!PointeeType)
921 PointeeType =
922 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
923 else
924 assert(
925 PointeeType ==
926 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
927 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
928 NameStr, InsertAtEnd);
931 /// Create an "inbounds" getelementptr. See the documentation for the
932 /// "inbounds" flag in LangRef.html for details.
933 static GetElementPtrInst *CreateInBounds(Value *Ptr,
934 ArrayRef<Value *> IdxList,
935 const Twine &NameStr = "",
936 Instruction *InsertBefore = nullptr){
937 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
940 static GetElementPtrInst *
941 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
942 const Twine &NameStr = "",
943 Instruction *InsertBefore = nullptr) {
944 GetElementPtrInst *GEP =
945 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
946 GEP->setIsInBounds(true);
947 return GEP;
950 static GetElementPtrInst *CreateInBounds(Value *Ptr,
951 ArrayRef<Value *> IdxList,
952 const Twine &NameStr,
953 BasicBlock *InsertAtEnd) {
954 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
957 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
958 ArrayRef<Value *> IdxList,
959 const Twine &NameStr,
960 BasicBlock *InsertAtEnd) {
961 GetElementPtrInst *GEP =
962 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
963 GEP->setIsInBounds(true);
964 return GEP;
967 /// Transparently provide more efficient getOperand methods.
968 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
970 Type *getSourceElementType() const { return SourceElementType; }
972 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
973 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
975 Type *getResultElementType() const {
976 assert(ResultElementType ==
977 cast<PointerType>(getType()->getScalarType())->getElementType());
978 return ResultElementType;
981 /// Returns the address space of this instruction's pointer type.
982 unsigned getAddressSpace() const {
983 // Note that this is always the same as the pointer operand's address space
984 // and that is cheaper to compute, so cheat here.
985 return getPointerAddressSpace();
988 /// Returns the type of the element that would be loaded with
989 /// a load instruction with the specified parameters.
991 /// Null is returned if the indices are invalid for the specified
992 /// pointer type.
994 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
995 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
996 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
998 inline op_iterator idx_begin() { return op_begin()+1; }
999 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1000 inline op_iterator idx_end() { return op_end(); }
1001 inline const_op_iterator idx_end() const { return op_end(); }
1003 inline iterator_range<op_iterator> indices() {
1004 return make_range(idx_begin(), idx_end());
1007 inline iterator_range<const_op_iterator> indices() const {
1008 return make_range(idx_begin(), idx_end());
1011 Value *getPointerOperand() {
1012 return getOperand(0);
1014 const Value *getPointerOperand() const {
1015 return getOperand(0);
1017 static unsigned getPointerOperandIndex() {
1018 return 0U; // get index for modifying correct operand.
1021 /// Method to return the pointer operand as a
1022 /// PointerType.
1023 Type *getPointerOperandType() const {
1024 return getPointerOperand()->getType();
1027 /// Returns the address space of the pointer operand.
1028 unsigned getPointerAddressSpace() const {
1029 return getPointerOperandType()->getPointerAddressSpace();
1032 /// Returns the pointer type returned by the GEP
1033 /// instruction, which may be a vector of pointers.
1034 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
1035 return getGEPReturnType(
1036 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1037 Ptr, IdxList);
1039 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1040 ArrayRef<Value *> IdxList) {
1041 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1042 Ptr->getType()->getPointerAddressSpace());
1043 // Vector GEP
1044 if (Ptr->getType()->isVectorTy()) {
1045 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1046 return VectorType::get(PtrTy, NumElem);
1048 for (Value *Index : IdxList)
1049 if (Index->getType()->isVectorTy()) {
1050 unsigned NumElem = Index->getType()->getVectorNumElements();
1051 return VectorType::get(PtrTy, NumElem);
1053 // Scalar GEP
1054 return PtrTy;
1057 unsigned getNumIndices() const { // Note: always non-negative
1058 return getNumOperands() - 1;
1061 bool hasIndices() const {
1062 return getNumOperands() > 1;
1065 /// Return true if all of the indices of this GEP are
1066 /// zeros. If so, the result pointer and the first operand have the same
1067 /// value, just potentially different types.
1068 bool hasAllZeroIndices() const;
1070 /// Return true if all of the indices of this GEP are
1071 /// constant integers. If so, the result pointer and the first operand have
1072 /// a constant offset between them.
1073 bool hasAllConstantIndices() const;
1075 /// Set or clear the inbounds flag on this GEP instruction.
1076 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1077 void setIsInBounds(bool b = true);
1079 /// Determine whether the GEP has the inbounds flag.
1080 bool isInBounds() const;
1082 /// Accumulate the constant address offset of this GEP if possible.
1084 /// This routine accepts an APInt into which it will accumulate the constant
1085 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1086 /// all-constant, it returns false and the value of the offset APInt is
1087 /// undefined (it is *not* preserved!). The APInt passed into this routine
1088 /// must be at least as wide as the IntPtr type for the address space of
1089 /// the base GEP pointer.
1090 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1092 // Methods for support type inquiry through isa, cast, and dyn_cast:
1093 static bool classof(const Instruction *I) {
1094 return (I->getOpcode() == Instruction::GetElementPtr);
1096 static bool classof(const Value *V) {
1097 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1101 template <>
1102 struct OperandTraits<GetElementPtrInst> :
1103 public VariadicOperandTraits<GetElementPtrInst, 1> {
1106 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1107 ArrayRef<Value *> IdxList, unsigned Values,
1108 const Twine &NameStr,
1109 Instruction *InsertBefore)
1110 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1111 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1112 Values, InsertBefore),
1113 SourceElementType(PointeeType),
1114 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1115 assert(ResultElementType ==
1116 cast<PointerType>(getType()->getScalarType())->getElementType());
1117 init(Ptr, IdxList, NameStr);
1120 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1121 ArrayRef<Value *> IdxList, unsigned Values,
1122 const Twine &NameStr,
1123 BasicBlock *InsertAtEnd)
1124 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1125 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1126 Values, InsertAtEnd),
1127 SourceElementType(PointeeType),
1128 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1129 assert(ResultElementType ==
1130 cast<PointerType>(getType()->getScalarType())->getElementType());
1131 init(Ptr, IdxList, NameStr);
1134 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1136 //===----------------------------------------------------------------------===//
1137 // UnaryOperator Class
1138 //===----------------------------------------------------------------------===//
1140 /// a unary instruction
1141 class UnaryOperator : public UnaryInstruction {
1142 void AssertOK();
1144 protected:
1145 UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
1146 const Twine &Name, Instruction *InsertBefore);
1147 UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
1148 const Twine &Name, BasicBlock *InsertAtEnd);
1150 // Note: Instruction needs to be a friend here to call cloneImpl.
1151 friend class Instruction;
1153 UnaryOperator *cloneImpl() const;
1155 public:
1157 /// Construct a unary instruction, given the opcode and an operand.
1158 /// Optionally (if InstBefore is specified) insert the instruction
1159 /// into a BasicBlock right before the specified instruction. The specified
1160 /// Instruction is allowed to be a dereferenced end iterator.
1162 static UnaryOperator *Create(UnaryOps Op, Value *S,
1163 const Twine &Name = Twine(),
1164 Instruction *InsertBefore = nullptr);
1166 /// Construct a unary instruction, given the opcode and an operand.
1167 /// Also automatically insert this instruction to the end of the
1168 /// BasicBlock specified.
1170 static UnaryOperator *Create(UnaryOps Op, Value *S,
1171 const Twine &Name,
1172 BasicBlock *InsertAtEnd);
1174 /// These methods just forward to Create, and are useful when you
1175 /// statically know what type of instruction you're going to create. These
1176 /// helpers just save some typing.
1177 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1178 static UnaryInstruction *Create##OPC(Value *V, \
1179 const Twine &Name = "") {\
1180 return Create(Instruction::OPC, V, Name);\
1182 #include "llvm/IR/Instruction.def"
1183 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1184 static UnaryInstruction *Create##OPC(Value *V, \
1185 const Twine &Name, BasicBlock *BB) {\
1186 return Create(Instruction::OPC, V, Name, BB);\
1188 #include "llvm/IR/Instruction.def"
1189 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1190 static UnaryInstruction *Create##OPC(Value *V, \
1191 const Twine &Name, Instruction *I) {\
1192 return Create(Instruction::OPC, V, Name, I);\
1194 #include "llvm/IR/Instruction.def"
1196 UnaryOps getOpcode() const {
1197 return static_cast<UnaryOps>(Instruction::getOpcode());
1201 //===----------------------------------------------------------------------===//
1202 // ICmpInst Class
1203 //===----------------------------------------------------------------------===//
1205 /// This instruction compares its operands according to the predicate given
1206 /// to the constructor. It only operates on integers or pointers. The operands
1207 /// must be identical types.
1208 /// Represent an integer comparison operator.
1209 class ICmpInst: public CmpInst {
1210 void AssertOK() {
1211 assert(isIntPredicate() &&
1212 "Invalid ICmp predicate value");
1213 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1214 "Both operands to ICmp instruction are not of the same type!");
1215 // Check that the operands are the right type
1216 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1217 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1218 "Invalid operand types for ICmp instruction");
1221 protected:
1222 // Note: Instruction needs to be a friend here to call cloneImpl.
1223 friend class Instruction;
1225 /// Clone an identical ICmpInst
1226 ICmpInst *cloneImpl() const;
1228 public:
1229 /// Constructor with insert-before-instruction semantics.
1230 ICmpInst(
1231 Instruction *InsertBefore, ///< Where to insert
1232 Predicate pred, ///< The predicate to use for the comparison
1233 Value *LHS, ///< The left-hand-side of the expression
1234 Value *RHS, ///< The right-hand-side of the expression
1235 const Twine &NameStr = "" ///< Name of the instruction
1236 ) : CmpInst(makeCmpResultType(LHS->getType()),
1237 Instruction::ICmp, pred, LHS, RHS, NameStr,
1238 InsertBefore) {
1239 #ifndef NDEBUG
1240 AssertOK();
1241 #endif
1244 /// Constructor with insert-at-end semantics.
1245 ICmpInst(
1246 BasicBlock &InsertAtEnd, ///< Block to insert into.
1247 Predicate pred, ///< The predicate to use for the comparison
1248 Value *LHS, ///< The left-hand-side of the expression
1249 Value *RHS, ///< The right-hand-side of the expression
1250 const Twine &NameStr = "" ///< Name of the instruction
1251 ) : CmpInst(makeCmpResultType(LHS->getType()),
1252 Instruction::ICmp, pred, LHS, RHS, NameStr,
1253 &InsertAtEnd) {
1254 #ifndef NDEBUG
1255 AssertOK();
1256 #endif
1259 /// Constructor with no-insertion semantics
1260 ICmpInst(
1261 Predicate pred, ///< The predicate to use for the comparison
1262 Value *LHS, ///< The left-hand-side of the expression
1263 Value *RHS, ///< The right-hand-side of the expression
1264 const Twine &NameStr = "" ///< Name of the instruction
1265 ) : CmpInst(makeCmpResultType(LHS->getType()),
1266 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1267 #ifndef NDEBUG
1268 AssertOK();
1269 #endif
1272 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1273 /// @returns the predicate that would be the result if the operand were
1274 /// regarded as signed.
1275 /// Return the signed version of the predicate
1276 Predicate getSignedPredicate() const {
1277 return getSignedPredicate(getPredicate());
1280 /// This is a static version that you can use without an instruction.
1281 /// Return the signed version of the predicate.
1282 static Predicate getSignedPredicate(Predicate pred);
1284 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1285 /// @returns the predicate that would be the result if the operand were
1286 /// regarded as unsigned.
1287 /// Return the unsigned version of the predicate
1288 Predicate getUnsignedPredicate() const {
1289 return getUnsignedPredicate(getPredicate());
1292 /// This is a static version that you can use without an instruction.
1293 /// Return the unsigned version of the predicate.
1294 static Predicate getUnsignedPredicate(Predicate pred);
1296 /// Return true if this predicate is either EQ or NE. This also
1297 /// tests for commutativity.
1298 static bool isEquality(Predicate P) {
1299 return P == ICMP_EQ || P == ICMP_NE;
1302 /// Return true if this predicate is either EQ or NE. This also
1303 /// tests for commutativity.
1304 bool isEquality() const {
1305 return isEquality(getPredicate());
1308 /// @returns true if the predicate of this ICmpInst is commutative
1309 /// Determine if this relation is commutative.
1310 bool isCommutative() const { return isEquality(); }
1312 /// Return true if the predicate is relational (not EQ or NE).
1314 bool isRelational() const {
1315 return !isEquality();
1318 /// Return true if the predicate is relational (not EQ or NE).
1320 static bool isRelational(Predicate P) {
1321 return !isEquality(P);
1324 /// Exchange the two operands to this instruction in such a way that it does
1325 /// not modify the semantics of the instruction. The predicate value may be
1326 /// changed to retain the same result if the predicate is order dependent
1327 /// (e.g. ult).
1328 /// Swap operands and adjust predicate.
1329 void swapOperands() {
1330 setPredicate(getSwappedPredicate());
1331 Op<0>().swap(Op<1>());
1334 // Methods for support type inquiry through isa, cast, and dyn_cast:
1335 static bool classof(const Instruction *I) {
1336 return I->getOpcode() == Instruction::ICmp;
1338 static bool classof(const Value *V) {
1339 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1343 //===----------------------------------------------------------------------===//
1344 // FCmpInst Class
1345 //===----------------------------------------------------------------------===//
1347 /// This instruction compares its operands according to the predicate given
1348 /// to the constructor. It only operates on floating point values or packed
1349 /// vectors of floating point values. The operands must be identical types.
1350 /// Represents a floating point comparison operator.
1351 class FCmpInst: public CmpInst {
1352 void AssertOK() {
1353 assert(isFPPredicate() && "Invalid FCmp predicate value");
1354 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1355 "Both operands to FCmp instruction are not of the same type!");
1356 // Check that the operands are the right type
1357 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1358 "Invalid operand types for FCmp instruction");
1361 protected:
1362 // Note: Instruction needs to be a friend here to call cloneImpl.
1363 friend class Instruction;
1365 /// Clone an identical FCmpInst
1366 FCmpInst *cloneImpl() const;
1368 public:
1369 /// Constructor with insert-before-instruction semantics.
1370 FCmpInst(
1371 Instruction *InsertBefore, ///< Where to insert
1372 Predicate pred, ///< The predicate to use for the comparison
1373 Value *LHS, ///< The left-hand-side of the expression
1374 Value *RHS, ///< The right-hand-side of the expression
1375 const Twine &NameStr = "" ///< Name of the instruction
1376 ) : CmpInst(makeCmpResultType(LHS->getType()),
1377 Instruction::FCmp, pred, LHS, RHS, NameStr,
1378 InsertBefore) {
1379 AssertOK();
1382 /// Constructor with insert-at-end semantics.
1383 FCmpInst(
1384 BasicBlock &InsertAtEnd, ///< Block to insert into.
1385 Predicate pred, ///< The predicate to use for the comparison
1386 Value *LHS, ///< The left-hand-side of the expression
1387 Value *RHS, ///< The right-hand-side of the expression
1388 const Twine &NameStr = "" ///< Name of the instruction
1389 ) : CmpInst(makeCmpResultType(LHS->getType()),
1390 Instruction::FCmp, pred, LHS, RHS, NameStr,
1391 &InsertAtEnd) {
1392 AssertOK();
1395 /// Constructor with no-insertion semantics
1396 FCmpInst(
1397 Predicate Pred, ///< The predicate to use for the comparison
1398 Value *LHS, ///< The left-hand-side of the expression
1399 Value *RHS, ///< The right-hand-side of the expression
1400 const Twine &NameStr = "", ///< Name of the instruction
1401 Instruction *FlagsSource = nullptr
1402 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1403 RHS, NameStr, nullptr, FlagsSource) {
1404 AssertOK();
1407 /// @returns true if the predicate of this instruction is EQ or NE.
1408 /// Determine if this is an equality predicate.
1409 static bool isEquality(Predicate Pred) {
1410 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1411 Pred == FCMP_UNE;
1414 /// @returns true if the predicate of this instruction is EQ or NE.
1415 /// Determine if this is an equality predicate.
1416 bool isEquality() const { return isEquality(getPredicate()); }
1418 /// @returns true if the predicate of this instruction is commutative.
1419 /// Determine if this is a commutative predicate.
1420 bool isCommutative() const {
1421 return isEquality() ||
1422 getPredicate() == FCMP_FALSE ||
1423 getPredicate() == FCMP_TRUE ||
1424 getPredicate() == FCMP_ORD ||
1425 getPredicate() == FCMP_UNO;
1428 /// @returns true if the predicate is relational (not EQ or NE).
1429 /// Determine if this a relational predicate.
1430 bool isRelational() const { return !isEquality(); }
1432 /// Exchange the two operands to this instruction in such a way that it does
1433 /// not modify the semantics of the instruction. The predicate value may be
1434 /// changed to retain the same result if the predicate is order dependent
1435 /// (e.g. ult).
1436 /// Swap operands and adjust predicate.
1437 void swapOperands() {
1438 setPredicate(getSwappedPredicate());
1439 Op<0>().swap(Op<1>());
1442 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1443 static bool classof(const Instruction *I) {
1444 return I->getOpcode() == Instruction::FCmp;
1446 static bool classof(const Value *V) {
1447 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1451 //===----------------------------------------------------------------------===//
1452 /// This class represents a function call, abstracting a target
1453 /// machine's calling convention. This class uses low bit of the SubClassData
1454 /// field to indicate whether or not this is a tail call. The rest of the bits
1455 /// hold the calling convention of the call.
1457 class CallInst : public CallBase {
1458 CallInst(const CallInst &CI);
1460 /// Construct a CallInst given a range of arguments.
1461 /// Construct a CallInst from a range of arguments
1462 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1463 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1464 Instruction *InsertBefore);
1466 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1467 const Twine &NameStr, Instruction *InsertBefore)
1468 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1470 /// Construct a CallInst given a range of arguments.
1471 /// Construct a CallInst from a range of arguments
1472 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1473 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1474 BasicBlock *InsertAtEnd);
1476 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1477 Instruction *InsertBefore);
1479 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1480 BasicBlock *InsertAtEnd);
1482 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1483 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1484 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1486 /// Compute the number of operands to allocate.
1487 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1488 // We need one operand for the called function, plus the input operand
1489 // counts provided.
1490 return 1 + NumArgs + NumBundleInputs;
1493 protected:
1494 // Note: Instruction needs to be a friend here to call cloneImpl.
1495 friend class Instruction;
1497 CallInst *cloneImpl() const;
1499 public:
1500 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1501 Instruction *InsertBefore = nullptr) {
1502 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1505 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1506 const Twine &NameStr,
1507 Instruction *InsertBefore = nullptr) {
1508 return new (ComputeNumOperands(Args.size()))
1509 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1512 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1513 ArrayRef<OperandBundleDef> Bundles = None,
1514 const Twine &NameStr = "",
1515 Instruction *InsertBefore = nullptr) {
1516 const int NumOperands =
1517 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1518 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1520 return new (NumOperands, DescriptorBytes)
1521 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1524 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1525 BasicBlock *InsertAtEnd) {
1526 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1529 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1530 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1531 return new (ComputeNumOperands(Args.size()))
1532 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1535 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1536 ArrayRef<OperandBundleDef> Bundles,
1537 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1538 const int NumOperands =
1539 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1540 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1542 return new (NumOperands, DescriptorBytes)
1543 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1546 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1547 Instruction *InsertBefore = nullptr) {
1548 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1549 InsertBefore);
1552 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1553 ArrayRef<OperandBundleDef> Bundles = None,
1554 const Twine &NameStr = "",
1555 Instruction *InsertBefore = nullptr) {
1556 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1557 NameStr, InsertBefore);
1560 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1561 const Twine &NameStr,
1562 Instruction *InsertBefore = nullptr) {
1563 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1564 InsertBefore);
1567 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1568 BasicBlock *InsertAtEnd) {
1569 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1570 InsertAtEnd);
1573 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1574 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1575 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1576 InsertAtEnd);
1579 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1580 ArrayRef<OperandBundleDef> Bundles,
1581 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1582 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1583 NameStr, InsertAtEnd);
1586 // Deprecated [opaque pointer types]
1587 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1588 Instruction *InsertBefore = nullptr) {
1589 return Create(cast<FunctionType>(
1590 cast<PointerType>(Func->getType())->getElementType()),
1591 Func, NameStr, InsertBefore);
1594 // Deprecated [opaque pointer types]
1595 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1596 const Twine &NameStr,
1597 Instruction *InsertBefore = nullptr) {
1598 return Create(cast<FunctionType>(
1599 cast<PointerType>(Func->getType())->getElementType()),
1600 Func, Args, NameStr, InsertBefore);
1603 // Deprecated [opaque pointer types]
1604 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1605 ArrayRef<OperandBundleDef> Bundles = None,
1606 const Twine &NameStr = "",
1607 Instruction *InsertBefore = nullptr) {
1608 return Create(cast<FunctionType>(
1609 cast<PointerType>(Func->getType())->getElementType()),
1610 Func, Args, Bundles, NameStr, InsertBefore);
1613 // Deprecated [opaque pointer types]
1614 static CallInst *Create(Value *Func, const Twine &NameStr,
1615 BasicBlock *InsertAtEnd) {
1616 return Create(cast<FunctionType>(
1617 cast<PointerType>(Func->getType())->getElementType()),
1618 Func, NameStr, InsertAtEnd);
1621 // Deprecated [opaque pointer types]
1622 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1623 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1624 return Create(cast<FunctionType>(
1625 cast<PointerType>(Func->getType())->getElementType()),
1626 Func, Args, NameStr, InsertAtEnd);
1629 // Deprecated [opaque pointer types]
1630 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1631 ArrayRef<OperandBundleDef> Bundles,
1632 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1633 return Create(cast<FunctionType>(
1634 cast<PointerType>(Func->getType())->getElementType()),
1635 Func, Args, Bundles, NameStr, InsertAtEnd);
1638 /// Create a clone of \p CI with a different set of operand bundles and
1639 /// insert it before \p InsertPt.
1641 /// The returned call instruction is identical \p CI in every way except that
1642 /// the operand bundles for the new instruction are set to the operand bundles
1643 /// in \p Bundles.
1644 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1645 Instruction *InsertPt = nullptr);
1647 /// Generate the IR for a call to malloc:
1648 /// 1. Compute the malloc call's argument as the specified type's size,
1649 /// possibly multiplied by the array size if the array size is not
1650 /// constant 1.
1651 /// 2. Call malloc with that argument.
1652 /// 3. Bitcast the result of the malloc call to the specified type.
1653 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1654 Type *AllocTy, Value *AllocSize,
1655 Value *ArraySize = nullptr,
1656 Function *MallocF = nullptr,
1657 const Twine &Name = "");
1658 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1659 Type *AllocTy, Value *AllocSize,
1660 Value *ArraySize = nullptr,
1661 Function *MallocF = nullptr,
1662 const Twine &Name = "");
1663 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1664 Type *AllocTy, Value *AllocSize,
1665 Value *ArraySize = nullptr,
1666 ArrayRef<OperandBundleDef> Bundles = None,
1667 Function *MallocF = nullptr,
1668 const Twine &Name = "");
1669 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1670 Type *AllocTy, Value *AllocSize,
1671 Value *ArraySize = nullptr,
1672 ArrayRef<OperandBundleDef> Bundles = None,
1673 Function *MallocF = nullptr,
1674 const Twine &Name = "");
1675 /// Generate the IR for a call to the builtin free function.
1676 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1677 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1678 static Instruction *CreateFree(Value *Source,
1679 ArrayRef<OperandBundleDef> Bundles,
1680 Instruction *InsertBefore);
1681 static Instruction *CreateFree(Value *Source,
1682 ArrayRef<OperandBundleDef> Bundles,
1683 BasicBlock *InsertAtEnd);
1685 // Note that 'musttail' implies 'tail'.
1686 enum TailCallKind {
1687 TCK_None = 0,
1688 TCK_Tail = 1,
1689 TCK_MustTail = 2,
1690 TCK_NoTail = 3
1692 TailCallKind getTailCallKind() const {
1693 return TailCallKind(getSubclassDataFromInstruction() & 3);
1696 bool isTailCall() const {
1697 unsigned Kind = getSubclassDataFromInstruction() & 3;
1698 return Kind == TCK_Tail || Kind == TCK_MustTail;
1701 bool isMustTailCall() const {
1702 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1705 bool isNoTailCall() const {
1706 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1709 void setTailCall(bool isTC = true) {
1710 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1711 unsigned(isTC ? TCK_Tail : TCK_None));
1714 void setTailCallKind(TailCallKind TCK) {
1715 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1716 unsigned(TCK));
1719 /// Return true if the call can return twice
1720 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1721 void setCanReturnTwice() {
1722 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1725 // Methods for support type inquiry through isa, cast, and dyn_cast:
1726 static bool classof(const Instruction *I) {
1727 return I->getOpcode() == Instruction::Call;
1729 static bool classof(const Value *V) {
1730 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1733 private:
1734 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1735 // method so that subclasses cannot accidentally use it.
1736 void setInstructionSubclassData(unsigned short D) {
1737 Instruction::setInstructionSubclassData(D);
1741 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1742 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1743 BasicBlock *InsertAtEnd)
1744 : CallBase(Ty->getReturnType(), Instruction::Call,
1745 OperandTraits<CallBase>::op_end(this) -
1746 (Args.size() + CountBundleInputs(Bundles) + 1),
1747 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1748 InsertAtEnd) {
1749 init(Ty, Func, Args, Bundles, NameStr);
1752 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1753 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1754 Instruction *InsertBefore)
1755 : CallBase(Ty->getReturnType(), Instruction::Call,
1756 OperandTraits<CallBase>::op_end(this) -
1757 (Args.size() + CountBundleInputs(Bundles) + 1),
1758 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1759 InsertBefore) {
1760 init(Ty, Func, Args, Bundles, NameStr);
1763 //===----------------------------------------------------------------------===//
1764 // SelectInst Class
1765 //===----------------------------------------------------------------------===//
1767 /// This class represents the LLVM 'select' instruction.
1769 class SelectInst : public Instruction {
1770 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1771 Instruction *InsertBefore)
1772 : Instruction(S1->getType(), Instruction::Select,
1773 &Op<0>(), 3, InsertBefore) {
1774 init(C, S1, S2);
1775 setName(NameStr);
1778 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1779 BasicBlock *InsertAtEnd)
1780 : Instruction(S1->getType(), Instruction::Select,
1781 &Op<0>(), 3, InsertAtEnd) {
1782 init(C, S1, S2);
1783 setName(NameStr);
1786 void init(Value *C, Value *S1, Value *S2) {
1787 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1788 Op<0>() = C;
1789 Op<1>() = S1;
1790 Op<2>() = S2;
1793 protected:
1794 // Note: Instruction needs to be a friend here to call cloneImpl.
1795 friend class Instruction;
1797 SelectInst *cloneImpl() const;
1799 public:
1800 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1801 const Twine &NameStr = "",
1802 Instruction *InsertBefore = nullptr,
1803 Instruction *MDFrom = nullptr) {
1804 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1805 if (MDFrom)
1806 Sel->copyMetadata(*MDFrom);
1807 return Sel;
1810 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1811 const Twine &NameStr,
1812 BasicBlock *InsertAtEnd) {
1813 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1816 const Value *getCondition() const { return Op<0>(); }
1817 const Value *getTrueValue() const { return Op<1>(); }
1818 const Value *getFalseValue() const { return Op<2>(); }
1819 Value *getCondition() { return Op<0>(); }
1820 Value *getTrueValue() { return Op<1>(); }
1821 Value *getFalseValue() { return Op<2>(); }
1823 void setCondition(Value *V) { Op<0>() = V; }
1824 void setTrueValue(Value *V) { Op<1>() = V; }
1825 void setFalseValue(Value *V) { Op<2>() = V; }
1827 /// Return a string if the specified operands are invalid
1828 /// for a select operation, otherwise return null.
1829 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1831 /// Transparently provide more efficient getOperand methods.
1832 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1834 OtherOps getOpcode() const {
1835 return static_cast<OtherOps>(Instruction::getOpcode());
1838 // Methods for support type inquiry through isa, cast, and dyn_cast:
1839 static bool classof(const Instruction *I) {
1840 return I->getOpcode() == Instruction::Select;
1842 static bool classof(const Value *V) {
1843 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1847 template <>
1848 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1851 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1853 //===----------------------------------------------------------------------===//
1854 // VAArgInst Class
1855 //===----------------------------------------------------------------------===//
1857 /// This class represents the va_arg llvm instruction, which returns
1858 /// an argument of the specified type given a va_list and increments that list
1860 class VAArgInst : public UnaryInstruction {
1861 protected:
1862 // Note: Instruction needs to be a friend here to call cloneImpl.
1863 friend class Instruction;
1865 VAArgInst *cloneImpl() const;
1867 public:
1868 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1869 Instruction *InsertBefore = nullptr)
1870 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1871 setName(NameStr);
1874 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1875 BasicBlock *InsertAtEnd)
1876 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1877 setName(NameStr);
1880 Value *getPointerOperand() { return getOperand(0); }
1881 const Value *getPointerOperand() const { return getOperand(0); }
1882 static unsigned getPointerOperandIndex() { return 0U; }
1884 // Methods for support type inquiry through isa, cast, and dyn_cast:
1885 static bool classof(const Instruction *I) {
1886 return I->getOpcode() == VAArg;
1888 static bool classof(const Value *V) {
1889 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1893 //===----------------------------------------------------------------------===//
1894 // ExtractElementInst Class
1895 //===----------------------------------------------------------------------===//
1897 /// This instruction extracts a single (scalar)
1898 /// element from a VectorType value
1900 class ExtractElementInst : public Instruction {
1901 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1902 Instruction *InsertBefore = nullptr);
1903 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1904 BasicBlock *InsertAtEnd);
1906 protected:
1907 // Note: Instruction needs to be a friend here to call cloneImpl.
1908 friend class Instruction;
1910 ExtractElementInst *cloneImpl() const;
1912 public:
1913 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1914 const Twine &NameStr = "",
1915 Instruction *InsertBefore = nullptr) {
1916 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1919 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1920 const Twine &NameStr,
1921 BasicBlock *InsertAtEnd) {
1922 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1925 /// Return true if an extractelement instruction can be
1926 /// formed with the specified operands.
1927 static bool isValidOperands(const Value *Vec, const Value *Idx);
1929 Value *getVectorOperand() { return Op<0>(); }
1930 Value *getIndexOperand() { return Op<1>(); }
1931 const Value *getVectorOperand() const { return Op<0>(); }
1932 const Value *getIndexOperand() const { return Op<1>(); }
1934 VectorType *getVectorOperandType() const {
1935 return cast<VectorType>(getVectorOperand()->getType());
1938 /// Transparently provide more efficient getOperand methods.
1939 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1941 // Methods for support type inquiry through isa, cast, and dyn_cast:
1942 static bool classof(const Instruction *I) {
1943 return I->getOpcode() == Instruction::ExtractElement;
1945 static bool classof(const Value *V) {
1946 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1950 template <>
1951 struct OperandTraits<ExtractElementInst> :
1952 public FixedNumOperandTraits<ExtractElementInst, 2> {
1955 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1957 //===----------------------------------------------------------------------===//
1958 // InsertElementInst Class
1959 //===----------------------------------------------------------------------===//
1961 /// This instruction inserts a single (scalar)
1962 /// element into a VectorType value
1964 class InsertElementInst : public Instruction {
1965 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1966 const Twine &NameStr = "",
1967 Instruction *InsertBefore = nullptr);
1968 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1969 BasicBlock *InsertAtEnd);
1971 protected:
1972 // Note: Instruction needs to be a friend here to call cloneImpl.
1973 friend class Instruction;
1975 InsertElementInst *cloneImpl() const;
1977 public:
1978 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1979 const Twine &NameStr = "",
1980 Instruction *InsertBefore = nullptr) {
1981 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1984 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1985 const Twine &NameStr,
1986 BasicBlock *InsertAtEnd) {
1987 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1990 /// Return true if an insertelement instruction can be
1991 /// formed with the specified operands.
1992 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1993 const Value *Idx);
1995 /// Overload to return most specific vector type.
1997 VectorType *getType() const {
1998 return cast<VectorType>(Instruction::getType());
2001 /// Transparently provide more efficient getOperand methods.
2002 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2004 // Methods for support type inquiry through isa, cast, and dyn_cast:
2005 static bool classof(const Instruction *I) {
2006 return I->getOpcode() == Instruction::InsertElement;
2008 static bool classof(const Value *V) {
2009 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2013 template <>
2014 struct OperandTraits<InsertElementInst> :
2015 public FixedNumOperandTraits<InsertElementInst, 3> {
2018 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2020 //===----------------------------------------------------------------------===//
2021 // ShuffleVectorInst Class
2022 //===----------------------------------------------------------------------===//
2024 /// This instruction constructs a fixed permutation of two
2025 /// input vectors.
2027 class ShuffleVectorInst : public Instruction {
2028 protected:
2029 // Note: Instruction needs to be a friend here to call cloneImpl.
2030 friend class Instruction;
2032 ShuffleVectorInst *cloneImpl() const;
2034 public:
2035 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2036 const Twine &NameStr = "",
2037 Instruction *InsertBefor = nullptr);
2038 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2039 const Twine &NameStr, BasicBlock *InsertAtEnd);
2041 // allocate space for exactly three operands
2042 void *operator new(size_t s) {
2043 return User::operator new(s, 3);
2046 /// Return true if a shufflevector instruction can be
2047 /// formed with the specified operands.
2048 static bool isValidOperands(const Value *V1, const Value *V2,
2049 const Value *Mask);
2051 /// Overload to return most specific vector type.
2053 VectorType *getType() const {
2054 return cast<VectorType>(Instruction::getType());
2057 /// Transparently provide more efficient getOperand methods.
2058 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2060 Constant *getMask() const {
2061 return cast<Constant>(getOperand(2));
2064 /// Return the shuffle mask value for the specified element of the mask.
2065 /// Return -1 if the element is undef.
2066 static int getMaskValue(const Constant *Mask, unsigned Elt);
2068 /// Return the shuffle mask value of this instruction for the given element
2069 /// index. Return -1 if the element is undef.
2070 int getMaskValue(unsigned Elt) const {
2071 return getMaskValue(getMask(), Elt);
2074 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2075 /// elements of the mask are returned as -1.
2076 static void getShuffleMask(const Constant *Mask,
2077 SmallVectorImpl<int> &Result);
2079 /// Return the mask for this instruction as a vector of integers. Undefined
2080 /// elements of the mask are returned as -1.
2081 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2082 return getShuffleMask(getMask(), Result);
2085 SmallVector<int, 16> getShuffleMask() const {
2086 SmallVector<int, 16> Mask;
2087 getShuffleMask(Mask);
2088 return Mask;
2091 /// Return true if this shuffle returns a vector with a different number of
2092 /// elements than its source vectors.
2093 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2094 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2095 bool changesLength() const {
2096 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2097 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2098 return NumSourceElts != NumMaskElts;
2101 /// Return true if this shuffle returns a vector with a greater number of
2102 /// elements than its source vectors.
2103 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2104 bool increasesLength() const {
2105 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2106 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2107 return NumSourceElts < NumMaskElts;
2110 /// Return true if this shuffle mask chooses elements from exactly one source
2111 /// vector.
2112 /// Example: <7,5,undef,7>
2113 /// This assumes that vector operands are the same length as the mask.
2114 static bool isSingleSourceMask(ArrayRef<int> Mask);
2115 static bool isSingleSourceMask(const Constant *Mask) {
2116 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2117 SmallVector<int, 16> MaskAsInts;
2118 getShuffleMask(Mask, MaskAsInts);
2119 return isSingleSourceMask(MaskAsInts);
2122 /// Return true if this shuffle chooses elements from exactly one source
2123 /// vector without changing the length of that vector.
2124 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2125 /// TODO: Optionally allow length-changing shuffles.
2126 bool isSingleSource() const {
2127 return !changesLength() && isSingleSourceMask(getMask());
2130 /// Return true if this shuffle mask chooses elements from exactly one source
2131 /// vector without lane crossings. A shuffle using this mask is not
2132 /// necessarily a no-op because it may change the number of elements from its
2133 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2134 /// Example: <undef,undef,2,3>
2135 static bool isIdentityMask(ArrayRef<int> Mask);
2136 static bool isIdentityMask(const Constant *Mask) {
2137 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2138 SmallVector<int, 16> MaskAsInts;
2139 getShuffleMask(Mask, MaskAsInts);
2140 return isIdentityMask(MaskAsInts);
2143 /// Return true if this shuffle chooses elements from exactly one source
2144 /// vector without lane crossings and does not change the number of elements
2145 /// from its input vectors.
2146 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2147 bool isIdentity() const {
2148 return !changesLength() && isIdentityMask(getShuffleMask());
2151 /// Return true if this shuffle lengthens exactly one source vector with
2152 /// undefs in the high elements.
2153 bool isIdentityWithPadding() const;
2155 /// Return true if this shuffle extracts the first N elements of exactly one
2156 /// source vector.
2157 bool isIdentityWithExtract() const;
2159 /// Return true if this shuffle concatenates its 2 source vectors. This
2160 /// returns false if either input is undefined. In that case, the shuffle is
2161 /// is better classified as an identity with padding operation.
2162 bool isConcat() const;
2164 /// Return true if this shuffle mask chooses elements from its source vectors
2165 /// without lane crossings. A shuffle using this mask would be
2166 /// equivalent to a vector select with a constant condition operand.
2167 /// Example: <4,1,6,undef>
2168 /// This returns false if the mask does not choose from both input vectors.
2169 /// In that case, the shuffle is better classified as an identity shuffle.
2170 /// This assumes that vector operands are the same length as the mask
2171 /// (a length-changing shuffle can never be equivalent to a vector select).
2172 static bool isSelectMask(ArrayRef<int> Mask);
2173 static bool isSelectMask(const Constant *Mask) {
2174 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2175 SmallVector<int, 16> MaskAsInts;
2176 getShuffleMask(Mask, MaskAsInts);
2177 return isSelectMask(MaskAsInts);
2180 /// Return true if this shuffle chooses elements from its source vectors
2181 /// without lane crossings and all operands have the same number of elements.
2182 /// In other words, this shuffle is equivalent to a vector select with a
2183 /// constant condition operand.
2184 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2185 /// This returns false if the mask does not choose from both input vectors.
2186 /// In that case, the shuffle is better classified as an identity shuffle.
2187 /// TODO: Optionally allow length-changing shuffles.
2188 bool isSelect() const {
2189 return !changesLength() && isSelectMask(getMask());
2192 /// Return true if this shuffle mask swaps the order of elements from exactly
2193 /// one source vector.
2194 /// Example: <7,6,undef,4>
2195 /// This assumes that vector operands are the same length as the mask.
2196 static bool isReverseMask(ArrayRef<int> Mask);
2197 static bool isReverseMask(const Constant *Mask) {
2198 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2199 SmallVector<int, 16> MaskAsInts;
2200 getShuffleMask(Mask, MaskAsInts);
2201 return isReverseMask(MaskAsInts);
2204 /// Return true if this shuffle swaps the order of elements from exactly
2205 /// one source vector.
2206 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2207 /// TODO: Optionally allow length-changing shuffles.
2208 bool isReverse() const {
2209 return !changesLength() && isReverseMask(getMask());
2212 /// Return true if this shuffle mask chooses all elements with the same value
2213 /// as the first element of exactly one source vector.
2214 /// Example: <4,undef,undef,4>
2215 /// This assumes that vector operands are the same length as the mask.
2216 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2217 static bool isZeroEltSplatMask(const Constant *Mask) {
2218 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2219 SmallVector<int, 16> MaskAsInts;
2220 getShuffleMask(Mask, MaskAsInts);
2221 return isZeroEltSplatMask(MaskAsInts);
2224 /// Return true if all elements of this shuffle are the same value as the
2225 /// first element of exactly one source vector without changing the length
2226 /// of that vector.
2227 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2228 /// TODO: Optionally allow length-changing shuffles.
2229 /// TODO: Optionally allow splats from other elements.
2230 bool isZeroEltSplat() const {
2231 return !changesLength() && isZeroEltSplatMask(getMask());
2234 /// Return true if this shuffle mask is a transpose mask.
2235 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2236 /// even- or odd-numbered vector elements from two n-dimensional source
2237 /// vectors and write each result into consecutive elements of an
2238 /// n-dimensional destination vector. Two shuffles are necessary to complete
2239 /// the transpose, one for the even elements and another for the odd elements.
2240 /// This description closely follows how the TRN1 and TRN2 AArch64
2241 /// instructions operate.
2243 /// For example, a simple 2x2 matrix can be transposed with:
2245 /// ; Original matrix
2246 /// m0 = < a, b >
2247 /// m1 = < c, d >
2249 /// ; Transposed matrix
2250 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2251 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2253 /// For matrices having greater than n columns, the resulting nx2 transposed
2254 /// matrix is stored in two result vectors such that one vector contains
2255 /// interleaved elements from all the even-numbered rows and the other vector
2256 /// contains interleaved elements from all the odd-numbered rows. For example,
2257 /// a 2x4 matrix can be transposed with:
2259 /// ; Original matrix
2260 /// m0 = < a, b, c, d >
2261 /// m1 = < e, f, g, h >
2263 /// ; Transposed matrix
2264 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2265 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2266 static bool isTransposeMask(ArrayRef<int> Mask);
2267 static bool isTransposeMask(const Constant *Mask) {
2268 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2269 SmallVector<int, 16> MaskAsInts;
2270 getShuffleMask(Mask, MaskAsInts);
2271 return isTransposeMask(MaskAsInts);
2274 /// Return true if this shuffle transposes the elements of its inputs without
2275 /// changing the length of the vectors. This operation may also be known as a
2276 /// merge or interleave. See the description for isTransposeMask() for the
2277 /// exact specification.
2278 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2279 bool isTranspose() const {
2280 return !changesLength() && isTransposeMask(getMask());
2283 /// Return true if this shuffle mask is an extract subvector mask.
2284 /// A valid extract subvector mask returns a smaller vector from a single
2285 /// source operand. The base extraction index is returned as well.
2286 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2287 int &Index);
2288 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2289 int &Index) {
2290 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2291 SmallVector<int, 16> MaskAsInts;
2292 getShuffleMask(Mask, MaskAsInts);
2293 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2296 /// Return true if this shuffle mask is an extract subvector mask.
2297 bool isExtractSubvectorMask(int &Index) const {
2298 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2299 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2302 /// Change values in a shuffle permute mask assuming the two vector operands
2303 /// of length InVecNumElts have swapped position.
2304 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2305 unsigned InVecNumElts) {
2306 for (int &Idx : Mask) {
2307 if (Idx == -1)
2308 continue;
2309 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2310 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2311 "shufflevector mask index out of range");
2315 // Methods for support type inquiry through isa, cast, and dyn_cast:
2316 static bool classof(const Instruction *I) {
2317 return I->getOpcode() == Instruction::ShuffleVector;
2319 static bool classof(const Value *V) {
2320 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2324 template <>
2325 struct OperandTraits<ShuffleVectorInst> :
2326 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2329 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2331 //===----------------------------------------------------------------------===//
2332 // ExtractValueInst Class
2333 //===----------------------------------------------------------------------===//
2335 /// This instruction extracts a struct member or array
2336 /// element value from an aggregate value.
2338 class ExtractValueInst : public UnaryInstruction {
2339 SmallVector<unsigned, 4> Indices;
2341 ExtractValueInst(const ExtractValueInst &EVI);
2343 /// Constructors - Create a extractvalue instruction with a base aggregate
2344 /// value and a list of indices. The first ctor can optionally insert before
2345 /// an existing instruction, the second appends the new instruction to the
2346 /// specified BasicBlock.
2347 inline ExtractValueInst(Value *Agg,
2348 ArrayRef<unsigned> Idxs,
2349 const Twine &NameStr,
2350 Instruction *InsertBefore);
2351 inline ExtractValueInst(Value *Agg,
2352 ArrayRef<unsigned> Idxs,
2353 const Twine &NameStr, BasicBlock *InsertAtEnd);
2355 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2357 protected:
2358 // Note: Instruction needs to be a friend here to call cloneImpl.
2359 friend class Instruction;
2361 ExtractValueInst *cloneImpl() const;
2363 public:
2364 static ExtractValueInst *Create(Value *Agg,
2365 ArrayRef<unsigned> Idxs,
2366 const Twine &NameStr = "",
2367 Instruction *InsertBefore = nullptr) {
2368 return new
2369 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2372 static ExtractValueInst *Create(Value *Agg,
2373 ArrayRef<unsigned> Idxs,
2374 const Twine &NameStr,
2375 BasicBlock *InsertAtEnd) {
2376 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2379 /// Returns the type of the element that would be extracted
2380 /// with an extractvalue instruction with the specified parameters.
2382 /// Null is returned if the indices are invalid for the specified type.
2383 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2385 using idx_iterator = const unsigned*;
2387 inline idx_iterator idx_begin() const { return Indices.begin(); }
2388 inline idx_iterator idx_end() const { return Indices.end(); }
2389 inline iterator_range<idx_iterator> indices() const {
2390 return make_range(idx_begin(), idx_end());
2393 Value *getAggregateOperand() {
2394 return getOperand(0);
2396 const Value *getAggregateOperand() const {
2397 return getOperand(0);
2399 static unsigned getAggregateOperandIndex() {
2400 return 0U; // get index for modifying correct operand
2403 ArrayRef<unsigned> getIndices() const {
2404 return Indices;
2407 unsigned getNumIndices() const {
2408 return (unsigned)Indices.size();
2411 bool hasIndices() const {
2412 return true;
2415 // Methods for support type inquiry through isa, cast, and dyn_cast:
2416 static bool classof(const Instruction *I) {
2417 return I->getOpcode() == Instruction::ExtractValue;
2419 static bool classof(const Value *V) {
2420 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2424 ExtractValueInst::ExtractValueInst(Value *Agg,
2425 ArrayRef<unsigned> Idxs,
2426 const Twine &NameStr,
2427 Instruction *InsertBefore)
2428 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2429 ExtractValue, Agg, InsertBefore) {
2430 init(Idxs, NameStr);
2433 ExtractValueInst::ExtractValueInst(Value *Agg,
2434 ArrayRef<unsigned> Idxs,
2435 const Twine &NameStr,
2436 BasicBlock *InsertAtEnd)
2437 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2438 ExtractValue, Agg, InsertAtEnd) {
2439 init(Idxs, NameStr);
2442 //===----------------------------------------------------------------------===//
2443 // InsertValueInst Class
2444 //===----------------------------------------------------------------------===//
2446 /// This instruction inserts a struct field of array element
2447 /// value into an aggregate value.
2449 class InsertValueInst : public Instruction {
2450 SmallVector<unsigned, 4> Indices;
2452 InsertValueInst(const InsertValueInst &IVI);
2454 /// Constructors - Create a insertvalue instruction with a base aggregate
2455 /// value, a value to insert, and a list of indices. The first ctor can
2456 /// optionally insert before an existing instruction, the second appends
2457 /// the new instruction to the specified BasicBlock.
2458 inline InsertValueInst(Value *Agg, Value *Val,
2459 ArrayRef<unsigned> Idxs,
2460 const Twine &NameStr,
2461 Instruction *InsertBefore);
2462 inline InsertValueInst(Value *Agg, Value *Val,
2463 ArrayRef<unsigned> Idxs,
2464 const Twine &NameStr, BasicBlock *InsertAtEnd);
2466 /// Constructors - These two constructors are convenience methods because one
2467 /// and two index insertvalue instructions are so common.
2468 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2469 const Twine &NameStr = "",
2470 Instruction *InsertBefore = nullptr);
2471 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2472 BasicBlock *InsertAtEnd);
2474 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2475 const Twine &NameStr);
2477 protected:
2478 // Note: Instruction needs to be a friend here to call cloneImpl.
2479 friend class Instruction;
2481 InsertValueInst *cloneImpl() const;
2483 public:
2484 // allocate space for exactly two operands
2485 void *operator new(size_t s) {
2486 return User::operator new(s, 2);
2489 static InsertValueInst *Create(Value *Agg, Value *Val,
2490 ArrayRef<unsigned> Idxs,
2491 const Twine &NameStr = "",
2492 Instruction *InsertBefore = nullptr) {
2493 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2496 static InsertValueInst *Create(Value *Agg, Value *Val,
2497 ArrayRef<unsigned> Idxs,
2498 const Twine &NameStr,
2499 BasicBlock *InsertAtEnd) {
2500 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2503 /// Transparently provide more efficient getOperand methods.
2504 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2506 using idx_iterator = const unsigned*;
2508 inline idx_iterator idx_begin() const { return Indices.begin(); }
2509 inline idx_iterator idx_end() const { return Indices.end(); }
2510 inline iterator_range<idx_iterator> indices() const {
2511 return make_range(idx_begin(), idx_end());
2514 Value *getAggregateOperand() {
2515 return getOperand(0);
2517 const Value *getAggregateOperand() const {
2518 return getOperand(0);
2520 static unsigned getAggregateOperandIndex() {
2521 return 0U; // get index for modifying correct operand
2524 Value *getInsertedValueOperand() {
2525 return getOperand(1);
2527 const Value *getInsertedValueOperand() const {
2528 return getOperand(1);
2530 static unsigned getInsertedValueOperandIndex() {
2531 return 1U; // get index for modifying correct operand
2534 ArrayRef<unsigned> getIndices() const {
2535 return Indices;
2538 unsigned getNumIndices() const {
2539 return (unsigned)Indices.size();
2542 bool hasIndices() const {
2543 return true;
2546 // Methods for support type inquiry through isa, cast, and dyn_cast:
2547 static bool classof(const Instruction *I) {
2548 return I->getOpcode() == Instruction::InsertValue;
2550 static bool classof(const Value *V) {
2551 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2555 template <>
2556 struct OperandTraits<InsertValueInst> :
2557 public FixedNumOperandTraits<InsertValueInst, 2> {
2560 InsertValueInst::InsertValueInst(Value *Agg,
2561 Value *Val,
2562 ArrayRef<unsigned> Idxs,
2563 const Twine &NameStr,
2564 Instruction *InsertBefore)
2565 : Instruction(Agg->getType(), InsertValue,
2566 OperandTraits<InsertValueInst>::op_begin(this),
2567 2, InsertBefore) {
2568 init(Agg, Val, Idxs, NameStr);
2571 InsertValueInst::InsertValueInst(Value *Agg,
2572 Value *Val,
2573 ArrayRef<unsigned> Idxs,
2574 const Twine &NameStr,
2575 BasicBlock *InsertAtEnd)
2576 : Instruction(Agg->getType(), InsertValue,
2577 OperandTraits<InsertValueInst>::op_begin(this),
2578 2, InsertAtEnd) {
2579 init(Agg, Val, Idxs, NameStr);
2582 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2584 //===----------------------------------------------------------------------===//
2585 // PHINode Class
2586 //===----------------------------------------------------------------------===//
2588 // PHINode - The PHINode class is used to represent the magical mystical PHI
2589 // node, that can not exist in nature, but can be synthesized in a computer
2590 // scientist's overactive imagination.
2592 class PHINode : public Instruction {
2593 /// The number of operands actually allocated. NumOperands is
2594 /// the number actually in use.
2595 unsigned ReservedSpace;
2597 PHINode(const PHINode &PN);
2599 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2600 const Twine &NameStr = "",
2601 Instruction *InsertBefore = nullptr)
2602 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2603 ReservedSpace(NumReservedValues) {
2604 setName(NameStr);
2605 allocHungoffUses(ReservedSpace);
2608 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2609 BasicBlock *InsertAtEnd)
2610 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2611 ReservedSpace(NumReservedValues) {
2612 setName(NameStr);
2613 allocHungoffUses(ReservedSpace);
2616 protected:
2617 // Note: Instruction needs to be a friend here to call cloneImpl.
2618 friend class Instruction;
2620 PHINode *cloneImpl() const;
2622 // allocHungoffUses - this is more complicated than the generic
2623 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2624 // values and pointers to the incoming blocks, all in one allocation.
2625 void allocHungoffUses(unsigned N) {
2626 User::allocHungoffUses(N, /* IsPhi */ true);
2629 public:
2630 /// Constructors - NumReservedValues is a hint for the number of incoming
2631 /// edges that this phi node will have (use 0 if you really have no idea).
2632 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2633 const Twine &NameStr = "",
2634 Instruction *InsertBefore = nullptr) {
2635 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2638 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2639 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2640 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2643 /// Provide fast operand accessors
2644 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2646 // Block iterator interface. This provides access to the list of incoming
2647 // basic blocks, which parallels the list of incoming values.
2649 using block_iterator = BasicBlock **;
2650 using const_block_iterator = BasicBlock * const *;
2652 block_iterator block_begin() {
2653 Use::UserRef *ref =
2654 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2655 return reinterpret_cast<block_iterator>(ref + 1);
2658 const_block_iterator block_begin() const {
2659 const Use::UserRef *ref =
2660 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2661 return reinterpret_cast<const_block_iterator>(ref + 1);
2664 block_iterator block_end() {
2665 return block_begin() + getNumOperands();
2668 const_block_iterator block_end() const {
2669 return block_begin() + getNumOperands();
2672 iterator_range<block_iterator> blocks() {
2673 return make_range(block_begin(), block_end());
2676 iterator_range<const_block_iterator> blocks() const {
2677 return make_range(block_begin(), block_end());
2680 op_range incoming_values() { return operands(); }
2682 const_op_range incoming_values() const { return operands(); }
2684 /// Return the number of incoming edges
2686 unsigned getNumIncomingValues() const { return getNumOperands(); }
2688 /// Return incoming value number x
2690 Value *getIncomingValue(unsigned i) const {
2691 return getOperand(i);
2693 void setIncomingValue(unsigned i, Value *V) {
2694 assert(V && "PHI node got a null value!");
2695 assert(getType() == V->getType() &&
2696 "All operands to PHI node must be the same type as the PHI node!");
2697 setOperand(i, V);
2700 static unsigned getOperandNumForIncomingValue(unsigned i) {
2701 return i;
2704 static unsigned getIncomingValueNumForOperand(unsigned i) {
2705 return i;
2708 /// Return incoming basic block number @p i.
2710 BasicBlock *getIncomingBlock(unsigned i) const {
2711 return block_begin()[i];
2714 /// Return incoming basic block corresponding
2715 /// to an operand of the PHI.
2717 BasicBlock *getIncomingBlock(const Use &U) const {
2718 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2719 return getIncomingBlock(unsigned(&U - op_begin()));
2722 /// Return incoming basic block corresponding
2723 /// to value use iterator.
2725 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2726 return getIncomingBlock(I.getUse());
2729 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2730 assert(BB && "PHI node got a null basic block!");
2731 block_begin()[i] = BB;
2734 /// Add an incoming value to the end of the PHI list
2736 void addIncoming(Value *V, BasicBlock *BB) {
2737 if (getNumOperands() == ReservedSpace)
2738 growOperands(); // Get more space!
2739 // Initialize some new operands.
2740 setNumHungOffUseOperands(getNumOperands() + 1);
2741 setIncomingValue(getNumOperands() - 1, V);
2742 setIncomingBlock(getNumOperands() - 1, BB);
2745 /// Remove an incoming value. This is useful if a
2746 /// predecessor basic block is deleted. The value removed is returned.
2748 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2749 /// is true), the PHI node is destroyed and any uses of it are replaced with
2750 /// dummy values. The only time there should be zero incoming values to a PHI
2751 /// node is when the block is dead, so this strategy is sound.
2753 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2755 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2756 int Idx = getBasicBlockIndex(BB);
2757 assert(Idx >= 0 && "Invalid basic block argument to remove!");
2758 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2761 /// Return the first index of the specified basic
2762 /// block in the value list for this PHI. Returns -1 if no instance.
2764 int getBasicBlockIndex(const BasicBlock *BB) const {
2765 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2766 if (block_begin()[i] == BB)
2767 return i;
2768 return -1;
2771 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2772 int Idx = getBasicBlockIndex(BB);
2773 assert(Idx >= 0 && "Invalid basic block argument!");
2774 return getIncomingValue(Idx);
2777 /// If the specified PHI node always merges together the
2778 /// same value, return the value, otherwise return null.
2779 Value *hasConstantValue() const;
2781 /// Whether the specified PHI node always merges
2782 /// together the same value, assuming undefs are equal to a unique
2783 /// non-undef value.
2784 bool hasConstantOrUndefValue() const;
2786 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2787 static bool classof(const Instruction *I) {
2788 return I->getOpcode() == Instruction::PHI;
2790 static bool classof(const Value *V) {
2791 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2794 private:
2795 void growOperands();
2798 template <>
2799 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2802 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2804 //===----------------------------------------------------------------------===//
2805 // LandingPadInst Class
2806 //===----------------------------------------------------------------------===//
2808 //===---------------------------------------------------------------------------
2809 /// The landingpad instruction holds all of the information
2810 /// necessary to generate correct exception handling. The landingpad instruction
2811 /// cannot be moved from the top of a landing pad block, which itself is
2812 /// accessible only from the 'unwind' edge of an invoke. This uses the
2813 /// SubclassData field in Value to store whether or not the landingpad is a
2814 /// cleanup.
2816 class LandingPadInst : public Instruction {
2817 /// The number of operands actually allocated. NumOperands is
2818 /// the number actually in use.
2819 unsigned ReservedSpace;
2821 LandingPadInst(const LandingPadInst &LP);
2823 public:
2824 enum ClauseType { Catch, Filter };
2826 private:
2827 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2828 const Twine &NameStr, Instruction *InsertBefore);
2829 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2830 const Twine &NameStr, BasicBlock *InsertAtEnd);
2832 // Allocate space for exactly zero operands.
2833 void *operator new(size_t s) {
2834 return User::operator new(s);
2837 void growOperands(unsigned Size);
2838 void init(unsigned NumReservedValues, const Twine &NameStr);
2840 protected:
2841 // Note: Instruction needs to be a friend here to call cloneImpl.
2842 friend class Instruction;
2844 LandingPadInst *cloneImpl() const;
2846 public:
2847 /// Constructors - NumReservedClauses is a hint for the number of incoming
2848 /// clauses that this landingpad will have (use 0 if you really have no idea).
2849 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2850 const Twine &NameStr = "",
2851 Instruction *InsertBefore = nullptr);
2852 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2853 const Twine &NameStr, BasicBlock *InsertAtEnd);
2855 /// Provide fast operand accessors
2856 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2858 /// Return 'true' if this landingpad instruction is a
2859 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2860 /// doesn't catch the exception.
2861 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2863 /// Indicate that this landingpad instruction is a cleanup.
2864 void setCleanup(bool V) {
2865 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2866 (V ? 1 : 0));
2869 /// Add a catch or filter clause to the landing pad.
2870 void addClause(Constant *ClauseVal);
2872 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2873 /// determine what type of clause this is.
2874 Constant *getClause(unsigned Idx) const {
2875 return cast<Constant>(getOperandList()[Idx]);
2878 /// Return 'true' if the clause and index Idx is a catch clause.
2879 bool isCatch(unsigned Idx) const {
2880 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2883 /// Return 'true' if the clause and index Idx is a filter clause.
2884 bool isFilter(unsigned Idx) const {
2885 return isa<ArrayType>(getOperandList()[Idx]->getType());
2888 /// Get the number of clauses for this landing pad.
2889 unsigned getNumClauses() const { return getNumOperands(); }
2891 /// Grow the size of the operand list to accommodate the new
2892 /// number of clauses.
2893 void reserveClauses(unsigned Size) { growOperands(Size); }
2895 // Methods for support type inquiry through isa, cast, and dyn_cast:
2896 static bool classof(const Instruction *I) {
2897 return I->getOpcode() == Instruction::LandingPad;
2899 static bool classof(const Value *V) {
2900 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2904 template <>
2905 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2908 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2910 //===----------------------------------------------------------------------===//
2911 // ReturnInst Class
2912 //===----------------------------------------------------------------------===//
2914 //===---------------------------------------------------------------------------
2915 /// Return a value (possibly void), from a function. Execution
2916 /// does not continue in this function any longer.
2918 class ReturnInst : public Instruction {
2919 ReturnInst(const ReturnInst &RI);
2921 private:
2922 // ReturnInst constructors:
2923 // ReturnInst() - 'ret void' instruction
2924 // ReturnInst( null) - 'ret void' instruction
2925 // ReturnInst(Value* X) - 'ret X' instruction
2926 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2927 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2928 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2929 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2931 // NOTE: If the Value* passed is of type void then the constructor behaves as
2932 // if it was passed NULL.
2933 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2934 Instruction *InsertBefore = nullptr);
2935 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2936 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2938 protected:
2939 // Note: Instruction needs to be a friend here to call cloneImpl.
2940 friend class Instruction;
2942 ReturnInst *cloneImpl() const;
2944 public:
2945 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2946 Instruction *InsertBefore = nullptr) {
2947 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2950 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2951 BasicBlock *InsertAtEnd) {
2952 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2955 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2956 return new(0) ReturnInst(C, InsertAtEnd);
2959 /// Provide fast operand accessors
2960 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2962 /// Convenience accessor. Returns null if there is no return value.
2963 Value *getReturnValue() const {
2964 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2967 unsigned getNumSuccessors() const { return 0; }
2969 // Methods for support type inquiry through isa, cast, and dyn_cast:
2970 static bool classof(const Instruction *I) {
2971 return (I->getOpcode() == Instruction::Ret);
2973 static bool classof(const Value *V) {
2974 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2977 private:
2978 BasicBlock *getSuccessor(unsigned idx) const {
2979 llvm_unreachable("ReturnInst has no successors!");
2982 void setSuccessor(unsigned idx, BasicBlock *B) {
2983 llvm_unreachable("ReturnInst has no successors!");
2987 template <>
2988 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2991 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2993 //===----------------------------------------------------------------------===//
2994 // BranchInst Class
2995 //===----------------------------------------------------------------------===//
2997 //===---------------------------------------------------------------------------
2998 /// Conditional or Unconditional Branch instruction.
3000 class BranchInst : public Instruction {
3001 /// Ops list - Branches are strange. The operands are ordered:
3002 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
3003 /// they don't have to check for cond/uncond branchness. These are mostly
3004 /// accessed relative from op_end().
3005 BranchInst(const BranchInst &BI);
3006 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
3007 // BranchInst(BB *B) - 'br B'
3008 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
3009 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
3010 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
3011 // BranchInst(BB* B, BB *I) - 'br B' insert at end
3012 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
3013 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
3014 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3015 Instruction *InsertBefore = nullptr);
3016 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
3017 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3018 BasicBlock *InsertAtEnd);
3020 void AssertOK();
3022 protected:
3023 // Note: Instruction needs to be a friend here to call cloneImpl.
3024 friend class Instruction;
3026 BranchInst *cloneImpl() const;
3028 public:
3029 /// Iterator type that casts an operand to a basic block.
3031 /// This only makes sense because the successors are stored as adjacent
3032 /// operands for branch instructions.
3033 struct succ_op_iterator
3034 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3035 std::random_access_iterator_tag, BasicBlock *,
3036 ptrdiff_t, BasicBlock *, BasicBlock *> {
3037 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3039 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3040 BasicBlock *operator->() const { return operator*(); }
3043 /// The const version of `succ_op_iterator`.
3044 struct const_succ_op_iterator
3045 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3046 std::random_access_iterator_tag,
3047 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3048 const BasicBlock *> {
3049 explicit const_succ_op_iterator(const_value_op_iterator I)
3050 : iterator_adaptor_base(I) {}
3052 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3053 const BasicBlock *operator->() const { return operator*(); }
3056 static BranchInst *Create(BasicBlock *IfTrue,
3057 Instruction *InsertBefore = nullptr) {
3058 return new(1) BranchInst(IfTrue, InsertBefore);
3061 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3062 Value *Cond, Instruction *InsertBefore = nullptr) {
3063 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3066 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3067 return new(1) BranchInst(IfTrue, InsertAtEnd);
3070 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3071 Value *Cond, BasicBlock *InsertAtEnd) {
3072 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3075 /// Transparently provide more efficient getOperand methods.
3076 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3078 bool isUnconditional() const { return getNumOperands() == 1; }
3079 bool isConditional() const { return getNumOperands() == 3; }
3081 Value *getCondition() const {
3082 assert(isConditional() && "Cannot get condition of an uncond branch!");
3083 return Op<-3>();
3086 void setCondition(Value *V) {
3087 assert(isConditional() && "Cannot set condition of unconditional branch!");
3088 Op<-3>() = V;
3091 unsigned getNumSuccessors() const { return 1+isConditional(); }
3093 BasicBlock *getSuccessor(unsigned i) const {
3094 assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3095 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3098 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3099 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3100 *(&Op<-1>() - idx) = NewSucc;
3103 /// Swap the successors of this branch instruction.
3105 /// Swaps the successors of the branch instruction. This also swaps any
3106 /// branch weight metadata associated with the instruction so that it
3107 /// continues to map correctly to each operand.
3108 void swapSuccessors();
3110 iterator_range<succ_op_iterator> successors() {
3111 return make_range(
3112 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3113 succ_op_iterator(value_op_end()));
3116 iterator_range<const_succ_op_iterator> successors() const {
3117 return make_range(const_succ_op_iterator(
3118 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3119 const_succ_op_iterator(value_op_end()));
3122 // Methods for support type inquiry through isa, cast, and dyn_cast:
3123 static bool classof(const Instruction *I) {
3124 return (I->getOpcode() == Instruction::Br);
3126 static bool classof(const Value *V) {
3127 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3131 template <>
3132 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3135 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
3137 //===----------------------------------------------------------------------===//
3138 // SwitchInst Class
3139 //===----------------------------------------------------------------------===//
3141 //===---------------------------------------------------------------------------
3142 /// Multiway switch
3144 class SwitchInst : public Instruction {
3145 unsigned ReservedSpace;
3147 // Operand[0] = Value to switch on
3148 // Operand[1] = Default basic block destination
3149 // Operand[2n ] = Value to match
3150 // Operand[2n+1] = BasicBlock to go to on match
3151 SwitchInst(const SwitchInst &SI);
3153 /// Create a new switch instruction, specifying a value to switch on and a
3154 /// default destination. The number of additional cases can be specified here
3155 /// to make memory allocation more efficient. This constructor can also
3156 /// auto-insert before another instruction.
3157 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3158 Instruction *InsertBefore);
3160 /// Create a new switch instruction, specifying a value to switch on and a
3161 /// default destination. The number of additional cases can be specified here
3162 /// to make memory allocation more efficient. This constructor also
3163 /// auto-inserts at the end of the specified BasicBlock.
3164 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3165 BasicBlock *InsertAtEnd);
3167 // allocate space for exactly zero operands
3168 void *operator new(size_t s) {
3169 return User::operator new(s);
3172 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3173 void growOperands();
3175 protected:
3176 // Note: Instruction needs to be a friend here to call cloneImpl.
3177 friend class Instruction;
3179 SwitchInst *cloneImpl() const;
3181 public:
3182 // -2
3183 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3185 template <typename CaseHandleT> class CaseIteratorImpl;
3187 /// A handle to a particular switch case. It exposes a convenient interface
3188 /// to both the case value and the successor block.
3190 /// We define this as a template and instantiate it to form both a const and
3191 /// non-const handle.
3192 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3193 class CaseHandleImpl {
3194 // Directly befriend both const and non-const iterators.
3195 friend class SwitchInst::CaseIteratorImpl<
3196 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3198 protected:
3199 // Expose the switch type we're parameterized with to the iterator.
3200 using SwitchInstType = SwitchInstT;
3202 SwitchInstT *SI;
3203 ptrdiff_t Index;
3205 CaseHandleImpl() = default;
3206 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3208 public:
3209 /// Resolves case value for current case.
3210 ConstantIntT *getCaseValue() const {
3211 assert((unsigned)Index < SI->getNumCases() &&
3212 "Index out the number of cases.");
3213 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3216 /// Resolves successor for current case.
3217 BasicBlockT *getCaseSuccessor() const {
3218 assert(((unsigned)Index < SI->getNumCases() ||
3219 (unsigned)Index == DefaultPseudoIndex) &&
3220 "Index out the number of cases.");
3221 return SI->getSuccessor(getSuccessorIndex());
3224 /// Returns number of current case.
3225 unsigned getCaseIndex() const { return Index; }
3227 /// Returns successor index for current case successor.
3228 unsigned getSuccessorIndex() const {
3229 assert(((unsigned)Index == DefaultPseudoIndex ||
3230 (unsigned)Index < SI->getNumCases()) &&
3231 "Index out the number of cases.");
3232 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3235 bool operator==(const CaseHandleImpl &RHS) const {
3236 assert(SI == RHS.SI && "Incompatible operators.");
3237 return Index == RHS.Index;
3241 using ConstCaseHandle =
3242 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3244 class CaseHandle
3245 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3246 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3248 public:
3249 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3251 /// Sets the new value for current case.
3252 void setValue(ConstantInt *V) {
3253 assert((unsigned)Index < SI->getNumCases() &&
3254 "Index out the number of cases.");
3255 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3258 /// Sets the new successor for current case.
3259 void setSuccessor(BasicBlock *S) {
3260 SI->setSuccessor(getSuccessorIndex(), S);
3264 template <typename CaseHandleT>
3265 class CaseIteratorImpl
3266 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3267 std::random_access_iterator_tag,
3268 CaseHandleT> {
3269 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3271 CaseHandleT Case;
3273 public:
3274 /// Default constructed iterator is in an invalid state until assigned to
3275 /// a case for a particular switch.
3276 CaseIteratorImpl() = default;
3278 /// Initializes case iterator for given SwitchInst and for given
3279 /// case number.
3280 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3282 /// Initializes case iterator for given SwitchInst and for given
3283 /// successor index.
3284 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3285 unsigned SuccessorIndex) {
3286 assert(SuccessorIndex < SI->getNumSuccessors() &&
3287 "Successor index # out of range!");
3288 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3289 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3292 /// Support converting to the const variant. This will be a no-op for const
3293 /// variant.
3294 operator CaseIteratorImpl<ConstCaseHandle>() const {
3295 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3298 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3299 // Check index correctness after addition.
3300 // Note: Index == getNumCases() means end().
3301 assert(Case.Index + N >= 0 &&
3302 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3303 "Case.Index out the number of cases.");
3304 Case.Index += N;
3305 return *this;
3307 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3308 // Check index correctness after subtraction.
3309 // Note: Case.Index == getNumCases() means end().
3310 assert(Case.Index - N >= 0 &&
3311 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3312 "Case.Index out the number of cases.");
3313 Case.Index -= N;
3314 return *this;
3316 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3317 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3318 return Case.Index - RHS.Case.Index;
3320 bool operator==(const CaseIteratorImpl &RHS) const {
3321 return Case == RHS.Case;
3323 bool operator<(const CaseIteratorImpl &RHS) const {
3324 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3325 return Case.Index < RHS.Case.Index;
3327 CaseHandleT &operator*() { return Case; }
3328 const CaseHandleT &operator*() const { return Case; }
3331 using CaseIt = CaseIteratorImpl<CaseHandle>;
3332 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3334 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3335 unsigned NumCases,
3336 Instruction *InsertBefore = nullptr) {
3337 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3340 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3341 unsigned NumCases, BasicBlock *InsertAtEnd) {
3342 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3345 /// Provide fast operand accessors
3346 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3348 // Accessor Methods for Switch stmt
3349 Value *getCondition() const { return getOperand(0); }
3350 void setCondition(Value *V) { setOperand(0, V); }
3352 BasicBlock *getDefaultDest() const {
3353 return cast<BasicBlock>(getOperand(1));
3356 void setDefaultDest(BasicBlock *DefaultCase) {
3357 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3360 /// Return the number of 'cases' in this switch instruction, excluding the
3361 /// default case.
3362 unsigned getNumCases() const {
3363 return getNumOperands()/2 - 1;
3366 /// Returns a read/write iterator that points to the first case in the
3367 /// SwitchInst.
3368 CaseIt case_begin() {
3369 return CaseIt(this, 0);
3372 /// Returns a read-only iterator that points to the first case in the
3373 /// SwitchInst.
3374 ConstCaseIt case_begin() const {
3375 return ConstCaseIt(this, 0);
3378 /// Returns a read/write iterator that points one past the last in the
3379 /// SwitchInst.
3380 CaseIt case_end() {
3381 return CaseIt(this, getNumCases());
3384 /// Returns a read-only iterator that points one past the last in the
3385 /// SwitchInst.
3386 ConstCaseIt case_end() const {
3387 return ConstCaseIt(this, getNumCases());
3390 /// Iteration adapter for range-for loops.
3391 iterator_range<CaseIt> cases() {
3392 return make_range(case_begin(), case_end());
3395 /// Constant iteration adapter for range-for loops.
3396 iterator_range<ConstCaseIt> cases() const {
3397 return make_range(case_begin(), case_end());
3400 /// Returns an iterator that points to the default case.
3401 /// Note: this iterator allows to resolve successor only. Attempt
3402 /// to resolve case value causes an assertion.
3403 /// Also note, that increment and decrement also causes an assertion and
3404 /// makes iterator invalid.
3405 CaseIt case_default() {
3406 return CaseIt(this, DefaultPseudoIndex);
3408 ConstCaseIt case_default() const {
3409 return ConstCaseIt(this, DefaultPseudoIndex);
3412 /// Search all of the case values for the specified constant. If it is
3413 /// explicitly handled, return the case iterator of it, otherwise return
3414 /// default case iterator to indicate that it is handled by the default
3415 /// handler.
3416 CaseIt findCaseValue(const ConstantInt *C) {
3417 CaseIt I = llvm::find_if(
3418 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3419 if (I != case_end())
3420 return I;
3422 return case_default();
3424 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3425 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3426 return Case.getCaseValue() == C;
3428 if (I != case_end())
3429 return I;
3431 return case_default();
3434 /// Finds the unique case value for a given successor. Returns null if the
3435 /// successor is not found, not unique, or is the default case.
3436 ConstantInt *findCaseDest(BasicBlock *BB) {
3437 if (BB == getDefaultDest())
3438 return nullptr;
3440 ConstantInt *CI = nullptr;
3441 for (auto Case : cases()) {
3442 if (Case.getCaseSuccessor() != BB)
3443 continue;
3445 if (CI)
3446 return nullptr; // Multiple cases lead to BB.
3448 CI = Case.getCaseValue();
3451 return CI;
3454 /// Add an entry to the switch instruction.
3455 /// Note:
3456 /// This action invalidates case_end(). Old case_end() iterator will
3457 /// point to the added case.
3458 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3460 /// This method removes the specified case and its successor from the switch
3461 /// instruction. Note that this operation may reorder the remaining cases at
3462 /// index idx and above.
3463 /// Note:
3464 /// This action invalidates iterators for all cases following the one removed,
3465 /// including the case_end() iterator. It returns an iterator for the next
3466 /// case.
3467 CaseIt removeCase(CaseIt I);
3469 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3470 BasicBlock *getSuccessor(unsigned idx) const {
3471 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3472 return cast<BasicBlock>(getOperand(idx*2+1));
3474 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3475 assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3476 setOperand(idx * 2 + 1, NewSucc);
3479 // Methods for support type inquiry through isa, cast, and dyn_cast:
3480 static bool classof(const Instruction *I) {
3481 return I->getOpcode() == Instruction::Switch;
3483 static bool classof(const Value *V) {
3484 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3488 template <>
3489 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3492 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3494 //===----------------------------------------------------------------------===//
3495 // IndirectBrInst Class
3496 //===----------------------------------------------------------------------===//
3498 //===---------------------------------------------------------------------------
3499 /// Indirect Branch Instruction.
3501 class IndirectBrInst : public Instruction {
3502 unsigned ReservedSpace;
3504 // Operand[0] = Address to jump to
3505 // Operand[n+1] = n-th destination
3506 IndirectBrInst(const IndirectBrInst &IBI);
3508 /// Create a new indirectbr instruction, specifying an
3509 /// Address to jump to. The number of expected destinations can be specified
3510 /// here to make memory allocation more efficient. This constructor can also
3511 /// autoinsert before another instruction.
3512 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3514 /// Create a new indirectbr instruction, specifying an
3515 /// Address to jump to. The number of expected destinations can be specified
3516 /// here to make memory allocation more efficient. This constructor also
3517 /// autoinserts at the end of the specified BasicBlock.
3518 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3520 // allocate space for exactly zero operands
3521 void *operator new(size_t s) {
3522 return User::operator new(s);
3525 void init(Value *Address, unsigned NumDests);
3526 void growOperands();
3528 protected:
3529 // Note: Instruction needs to be a friend here to call cloneImpl.
3530 friend class Instruction;
3532 IndirectBrInst *cloneImpl() const;
3534 public:
3535 /// Iterator type that casts an operand to a basic block.
3537 /// This only makes sense because the successors are stored as adjacent
3538 /// operands for indirectbr instructions.
3539 struct succ_op_iterator
3540 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3541 std::random_access_iterator_tag, BasicBlock *,
3542 ptrdiff_t, BasicBlock *, BasicBlock *> {
3543 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3545 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3546 BasicBlock *operator->() const { return operator*(); }
3549 /// The const version of `succ_op_iterator`.
3550 struct const_succ_op_iterator
3551 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3552 std::random_access_iterator_tag,
3553 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3554 const BasicBlock *> {
3555 explicit const_succ_op_iterator(const_value_op_iterator I)
3556 : iterator_adaptor_base(I) {}
3558 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3559 const BasicBlock *operator->() const { return operator*(); }
3562 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3563 Instruction *InsertBefore = nullptr) {
3564 return new IndirectBrInst(Address, NumDests, InsertBefore);
3567 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3568 BasicBlock *InsertAtEnd) {
3569 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3572 /// Provide fast operand accessors.
3573 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3575 // Accessor Methods for IndirectBrInst instruction.
3576 Value *getAddress() { return getOperand(0); }
3577 const Value *getAddress() const { return getOperand(0); }
3578 void setAddress(Value *V) { setOperand(0, V); }
3580 /// return the number of possible destinations in this
3581 /// indirectbr instruction.
3582 unsigned getNumDestinations() const { return getNumOperands()-1; }
3584 /// Return the specified destination.
3585 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3586 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3588 /// Add a destination.
3590 void addDestination(BasicBlock *Dest);
3592 /// This method removes the specified successor from the
3593 /// indirectbr instruction.
3594 void removeDestination(unsigned i);
3596 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3597 BasicBlock *getSuccessor(unsigned i) const {
3598 return cast<BasicBlock>(getOperand(i+1));
3600 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3601 setOperand(i + 1, NewSucc);
3604 iterator_range<succ_op_iterator> successors() {
3605 return make_range(succ_op_iterator(std::next(value_op_begin())),
3606 succ_op_iterator(value_op_end()));
3609 iterator_range<const_succ_op_iterator> successors() const {
3610 return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3611 const_succ_op_iterator(value_op_end()));
3614 // Methods for support type inquiry through isa, cast, and dyn_cast:
3615 static bool classof(const Instruction *I) {
3616 return I->getOpcode() == Instruction::IndirectBr;
3618 static bool classof(const Value *V) {
3619 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3623 template <>
3624 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3627 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3629 //===----------------------------------------------------------------------===//
3630 // InvokeInst Class
3631 //===----------------------------------------------------------------------===//
3633 /// Invoke instruction. The SubclassData field is used to hold the
3634 /// calling convention of the call.
3636 class InvokeInst : public CallBase {
3637 /// The number of operands for this call beyond the called function,
3638 /// arguments, and operand bundles.
3639 static constexpr int NumExtraOperands = 2;
3641 /// The index from the end of the operand array to the normal destination.
3642 static constexpr int NormalDestOpEndIdx = -3;
3644 /// The index from the end of the operand array to the unwind destination.
3645 static constexpr int UnwindDestOpEndIdx = -2;
3647 InvokeInst(const InvokeInst &BI);
3649 /// Construct an InvokeInst given a range of arguments.
3651 /// Construct an InvokeInst from a range of arguments
3652 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3653 BasicBlock *IfException, ArrayRef<Value *> Args,
3654 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3655 const Twine &NameStr, Instruction *InsertBefore);
3657 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3658 BasicBlock *IfException, ArrayRef<Value *> Args,
3659 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3660 const Twine &NameStr, BasicBlock *InsertAtEnd);
3662 void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3663 BasicBlock *IfException, ArrayRef<Value *> Args,
3664 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3666 /// Compute the number of operands to allocate.
3667 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3668 // We need one operand for the called function, plus our extra operands and
3669 // the input operand counts provided.
3670 return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3673 protected:
3674 // Note: Instruction needs to be a friend here to call cloneImpl.
3675 friend class Instruction;
3677 InvokeInst *cloneImpl() const;
3679 public:
3680 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3681 BasicBlock *IfException, ArrayRef<Value *> Args,
3682 const Twine &NameStr,
3683 Instruction *InsertBefore = nullptr) {
3684 int NumOperands = ComputeNumOperands(Args.size());
3685 return new (NumOperands)
3686 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3687 NameStr, InsertBefore);
3690 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3691 BasicBlock *IfException, ArrayRef<Value *> Args,
3692 ArrayRef<OperandBundleDef> Bundles = None,
3693 const Twine &NameStr = "",
3694 Instruction *InsertBefore = nullptr) {
3695 int NumOperands =
3696 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3697 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3699 return new (NumOperands, DescriptorBytes)
3700 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3701 NameStr, InsertBefore);
3704 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3705 BasicBlock *IfException, ArrayRef<Value *> Args,
3706 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3707 int NumOperands = ComputeNumOperands(Args.size());
3708 return new (NumOperands)
3709 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3710 NameStr, InsertAtEnd);
3713 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3714 BasicBlock *IfException, ArrayRef<Value *> Args,
3715 ArrayRef<OperandBundleDef> Bundles,
3716 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3717 int NumOperands =
3718 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3719 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3721 return new (NumOperands, DescriptorBytes)
3722 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3723 NameStr, InsertAtEnd);
3726 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3727 BasicBlock *IfException, ArrayRef<Value *> Args,
3728 const Twine &NameStr,
3729 Instruction *InsertBefore = nullptr) {
3730 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3731 IfException, Args, None, NameStr, InsertBefore);
3734 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3735 BasicBlock *IfException, ArrayRef<Value *> Args,
3736 ArrayRef<OperandBundleDef> Bundles = None,
3737 const Twine &NameStr = "",
3738 Instruction *InsertBefore = nullptr) {
3739 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3740 IfException, Args, Bundles, NameStr, InsertBefore);
3743 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3744 BasicBlock *IfException, ArrayRef<Value *> Args,
3745 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3746 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3747 IfException, Args, NameStr, InsertAtEnd);
3750 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3751 BasicBlock *IfException, ArrayRef<Value *> Args,
3752 ArrayRef<OperandBundleDef> Bundles,
3753 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3754 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3755 IfException, Args, Bundles, NameStr, InsertAtEnd);
3758 // Deprecated [opaque pointer types]
3759 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3760 BasicBlock *IfException, ArrayRef<Value *> Args,
3761 const Twine &NameStr,
3762 Instruction *InsertBefore = nullptr) {
3763 return Create(cast<FunctionType>(
3764 cast<PointerType>(Func->getType())->getElementType()),
3765 Func, IfNormal, IfException, Args, None, NameStr,
3766 InsertBefore);
3769 // Deprecated [opaque pointer types]
3770 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3771 BasicBlock *IfException, ArrayRef<Value *> Args,
3772 ArrayRef<OperandBundleDef> Bundles = None,
3773 const Twine &NameStr = "",
3774 Instruction *InsertBefore = nullptr) {
3775 return Create(cast<FunctionType>(
3776 cast<PointerType>(Func->getType())->getElementType()),
3777 Func, IfNormal, IfException, Args, Bundles, NameStr,
3778 InsertBefore);
3781 // Deprecated [opaque pointer types]
3782 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3783 BasicBlock *IfException, ArrayRef<Value *> Args,
3784 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3785 return Create(cast<FunctionType>(
3786 cast<PointerType>(Func->getType())->getElementType()),
3787 Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3790 // Deprecated [opaque pointer types]
3791 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3792 BasicBlock *IfException, ArrayRef<Value *> Args,
3793 ArrayRef<OperandBundleDef> Bundles,
3794 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3795 return Create(cast<FunctionType>(
3796 cast<PointerType>(Func->getType())->getElementType()),
3797 Func, IfNormal, IfException, Args, Bundles, NameStr,
3798 InsertAtEnd);
3801 /// Create a clone of \p II with a different set of operand bundles and
3802 /// insert it before \p InsertPt.
3804 /// The returned invoke instruction is identical to \p II in every way except
3805 /// that the operand bundles for the new instruction are set to the operand
3806 /// bundles in \p Bundles.
3807 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3808 Instruction *InsertPt = nullptr);
3810 /// Determine if the call should not perform indirect branch tracking.
3811 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3813 /// Determine if the call cannot unwind.
3814 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3815 void setDoesNotThrow() {
3816 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3819 // get*Dest - Return the destination basic blocks...
3820 BasicBlock *getNormalDest() const {
3821 return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3823 BasicBlock *getUnwindDest() const {
3824 return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3826 void setNormalDest(BasicBlock *B) {
3827 Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3829 void setUnwindDest(BasicBlock *B) {
3830 Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3833 /// Get the landingpad instruction from the landing pad
3834 /// block (the unwind destination).
3835 LandingPadInst *getLandingPadInst() const;
3837 BasicBlock *getSuccessor(unsigned i) const {
3838 assert(i < 2 && "Successor # out of range for invoke!");
3839 return i == 0 ? getNormalDest() : getUnwindDest();
3842 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3843 assert(i < 2 && "Successor # out of range for invoke!");
3844 if (i == 0)
3845 setNormalDest(NewSucc);
3846 else
3847 setUnwindDest(NewSucc);
3850 unsigned getNumSuccessors() const { return 2; }
3852 // Methods for support type inquiry through isa, cast, and dyn_cast:
3853 static bool classof(const Instruction *I) {
3854 return (I->getOpcode() == Instruction::Invoke);
3856 static bool classof(const Value *V) {
3857 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3860 private:
3862 // Shadow Instruction::setInstructionSubclassData with a private forwarding
3863 // method so that subclasses cannot accidentally use it.
3864 void setInstructionSubclassData(unsigned short D) {
3865 Instruction::setInstructionSubclassData(D);
3869 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3870 BasicBlock *IfException, ArrayRef<Value *> Args,
3871 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3872 const Twine &NameStr, Instruction *InsertBefore)
3873 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3874 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3875 InsertBefore) {
3876 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3879 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3880 BasicBlock *IfException, ArrayRef<Value *> Args,
3881 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3882 const Twine &NameStr, BasicBlock *InsertAtEnd)
3883 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3884 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3885 InsertAtEnd) {
3886 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3889 //===----------------------------------------------------------------------===//
3890 // CallBrInst Class
3891 //===----------------------------------------------------------------------===//
3893 /// CallBr instruction, tracking function calls that may not return control but
3894 /// instead transfer it to a third location. The SubclassData field is used to
3895 /// hold the calling convention of the call.
3897 class CallBrInst : public CallBase {
3899 unsigned NumIndirectDests;
3901 CallBrInst(const CallBrInst &BI);
3903 /// Construct a CallBrInst given a range of arguments.
3905 /// Construct a CallBrInst from a range of arguments
3906 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3907 ArrayRef<BasicBlock *> IndirectDests,
3908 ArrayRef<Value *> Args,
3909 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3910 const Twine &NameStr, Instruction *InsertBefore);
3912 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3913 ArrayRef<BasicBlock *> IndirectDests,
3914 ArrayRef<Value *> Args,
3915 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3916 const Twine &NameStr, BasicBlock *InsertAtEnd);
3918 void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3919 ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3920 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3922 /// Compute the number of operands to allocate.
3923 static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3924 int NumBundleInputs = 0) {
3925 // We need one operand for the called function, plus our extra operands and
3926 // the input operand counts provided.
3927 return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3930 protected:
3931 // Note: Instruction needs to be a friend here to call cloneImpl.
3932 friend class Instruction;
3934 CallBrInst *cloneImpl() const;
3936 public:
3937 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3938 BasicBlock *DefaultDest,
3939 ArrayRef<BasicBlock *> IndirectDests,
3940 ArrayRef<Value *> Args, const Twine &NameStr,
3941 Instruction *InsertBefore = nullptr) {
3942 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3943 return new (NumOperands)
3944 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3945 NumOperands, NameStr, InsertBefore);
3948 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3949 BasicBlock *DefaultDest,
3950 ArrayRef<BasicBlock *> IndirectDests,
3951 ArrayRef<Value *> Args,
3952 ArrayRef<OperandBundleDef> Bundles = None,
3953 const Twine &NameStr = "",
3954 Instruction *InsertBefore = nullptr) {
3955 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3956 CountBundleInputs(Bundles));
3957 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3959 return new (NumOperands, DescriptorBytes)
3960 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3961 NumOperands, NameStr, InsertBefore);
3964 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3965 BasicBlock *DefaultDest,
3966 ArrayRef<BasicBlock *> IndirectDests,
3967 ArrayRef<Value *> Args, const Twine &NameStr,
3968 BasicBlock *InsertAtEnd) {
3969 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3970 return new (NumOperands)
3971 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3972 NumOperands, NameStr, InsertAtEnd);
3975 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3976 BasicBlock *DefaultDest,
3977 ArrayRef<BasicBlock *> IndirectDests,
3978 ArrayRef<Value *> Args,
3979 ArrayRef<OperandBundleDef> Bundles,
3980 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3981 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3982 CountBundleInputs(Bundles));
3983 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3985 return new (NumOperands, DescriptorBytes)
3986 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3987 NumOperands, NameStr, InsertAtEnd);
3990 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
3991 ArrayRef<BasicBlock *> IndirectDests,
3992 ArrayRef<Value *> Args, const Twine &NameStr,
3993 Instruction *InsertBefore = nullptr) {
3994 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
3995 IndirectDests, Args, NameStr, InsertBefore);
3998 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
3999 ArrayRef<BasicBlock *> IndirectDests,
4000 ArrayRef<Value *> Args,
4001 ArrayRef<OperandBundleDef> Bundles = None,
4002 const Twine &NameStr = "",
4003 Instruction *InsertBefore = nullptr) {
4004 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4005 IndirectDests, Args, Bundles, NameStr, InsertBefore);
4008 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4009 ArrayRef<BasicBlock *> IndirectDests,
4010 ArrayRef<Value *> Args, const Twine &NameStr,
4011 BasicBlock *InsertAtEnd) {
4012 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4013 IndirectDests, Args, NameStr, InsertAtEnd);
4016 static CallBrInst *Create(FunctionCallee Func,
4017 BasicBlock *DefaultDest,
4018 ArrayRef<BasicBlock *> IndirectDests,
4019 ArrayRef<Value *> Args,
4020 ArrayRef<OperandBundleDef> Bundles,
4021 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4022 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4023 IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4026 /// Create a clone of \p CBI with a different set of operand bundles and
4027 /// insert it before \p InsertPt.
4029 /// The returned callbr instruction is identical to \p CBI in every way
4030 /// except that the operand bundles for the new instruction are set to the
4031 /// operand bundles in \p Bundles.
4032 static CallBrInst *Create(CallBrInst *CBI,
4033 ArrayRef<OperandBundleDef> Bundles,
4034 Instruction *InsertPt = nullptr);
4036 /// Return the number of callbr indirect dest labels.
4038 unsigned getNumIndirectDests() const { return NumIndirectDests; }
4040 /// getIndirectDestLabel - Return the i-th indirect dest label.
4042 Value *getIndirectDestLabel(unsigned i) const {
4043 assert(i < getNumIndirectDests() && "Out of bounds!");
4044 return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4048 Value *getIndirectDestLabelUse(unsigned i) const {
4049 assert(i < getNumIndirectDests() && "Out of bounds!");
4050 return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4054 // Return the destination basic blocks...
4055 BasicBlock *getDefaultDest() const {
4056 return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4058 BasicBlock *getIndirectDest(unsigned i) const {
4059 return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4061 SmallVector<BasicBlock *, 16> getIndirectDests() const {
4062 SmallVector<BasicBlock *, 16> IndirectDests;
4063 for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4064 IndirectDests.push_back(getIndirectDest(i));
4065 return IndirectDests;
4067 void setDefaultDest(BasicBlock *B) {
4068 *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4070 void setIndirectDest(unsigned i, BasicBlock *B) {
4071 *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4074 BasicBlock *getSuccessor(unsigned i) const {
4075 assert(i < getNumSuccessors() + 1 &&
4076 "Successor # out of range for callbr!");
4077 return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4080 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4081 assert(idx < getNumIndirectDests() + 1 &&
4082 "Successor # out of range for callbr!");
4083 *(&Op<-1>() - getNumIndirectDests() -1 + idx) =
4084 reinterpret_cast<Value *>(NewSucc);
4087 unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4089 // Methods for support type inquiry through isa, cast, and dyn_cast:
4090 static bool classof(const Instruction *I) {
4091 return (I->getOpcode() == Instruction::CallBr);
4093 static bool classof(const Value *V) {
4094 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4097 private:
4099 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4100 // method so that subclasses cannot accidentally use it.
4101 void setInstructionSubclassData(unsigned short D) {
4102 Instruction::setInstructionSubclassData(D);
4106 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4107 ArrayRef<BasicBlock *> IndirectDests,
4108 ArrayRef<Value *> Args,
4109 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4110 const Twine &NameStr, Instruction *InsertBefore)
4111 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4112 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4113 InsertBefore) {
4114 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4117 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4118 ArrayRef<BasicBlock *> IndirectDests,
4119 ArrayRef<Value *> Args,
4120 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4121 const Twine &NameStr, BasicBlock *InsertAtEnd)
4122 : CallBase(
4123 cast<FunctionType>(
4124 cast<PointerType>(Func->getType())->getElementType())
4125 ->getReturnType(),
4126 Instruction::CallBr,
4127 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4128 InsertAtEnd) {
4129 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4132 //===----------------------------------------------------------------------===//
4133 // ResumeInst Class
4134 //===----------------------------------------------------------------------===//
4136 //===---------------------------------------------------------------------------
4137 /// Resume the propagation of an exception.
4139 class ResumeInst : public Instruction {
4140 ResumeInst(const ResumeInst &RI);
4142 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4143 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4145 protected:
4146 // Note: Instruction needs to be a friend here to call cloneImpl.
4147 friend class Instruction;
4149 ResumeInst *cloneImpl() const;
4151 public:
4152 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4153 return new(1) ResumeInst(Exn, InsertBefore);
4156 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4157 return new(1) ResumeInst(Exn, InsertAtEnd);
4160 /// Provide fast operand accessors
4161 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4163 /// Convenience accessor.
4164 Value *getValue() const { return Op<0>(); }
4166 unsigned getNumSuccessors() const { return 0; }
4168 // Methods for support type inquiry through isa, cast, and dyn_cast:
4169 static bool classof(const Instruction *I) {
4170 return I->getOpcode() == Instruction::Resume;
4172 static bool classof(const Value *V) {
4173 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4176 private:
4177 BasicBlock *getSuccessor(unsigned idx) const {
4178 llvm_unreachable("ResumeInst has no successors!");
4181 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4182 llvm_unreachable("ResumeInst has no successors!");
4186 template <>
4187 struct OperandTraits<ResumeInst> :
4188 public FixedNumOperandTraits<ResumeInst, 1> {
4191 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4193 //===----------------------------------------------------------------------===//
4194 // CatchSwitchInst Class
4195 //===----------------------------------------------------------------------===//
4196 class CatchSwitchInst : public Instruction {
4197 /// The number of operands actually allocated. NumOperands is
4198 /// the number actually in use.
4199 unsigned ReservedSpace;
4201 // Operand[0] = Outer scope
4202 // Operand[1] = Unwind block destination
4203 // Operand[n] = BasicBlock to go to on match
4204 CatchSwitchInst(const CatchSwitchInst &CSI);
4206 /// Create a new switch instruction, specifying a
4207 /// default destination. The number of additional handlers can be specified
4208 /// here to make memory allocation more efficient.
4209 /// This constructor can also autoinsert before another instruction.
4210 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4211 unsigned NumHandlers, const Twine &NameStr,
4212 Instruction *InsertBefore);
4214 /// Create a new switch instruction, specifying a
4215 /// default destination. The number of additional handlers can be specified
4216 /// here to make memory allocation more efficient.
4217 /// This constructor also autoinserts at the end of the specified BasicBlock.
4218 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4219 unsigned NumHandlers, const Twine &NameStr,
4220 BasicBlock *InsertAtEnd);
4222 // allocate space for exactly zero operands
4223 void *operator new(size_t s) { return User::operator new(s); }
4225 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4226 void growOperands(unsigned Size);
4228 protected:
4229 // Note: Instruction needs to be a friend here to call cloneImpl.
4230 friend class Instruction;
4232 CatchSwitchInst *cloneImpl() const;
4234 public:
4235 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4236 unsigned NumHandlers,
4237 const Twine &NameStr = "",
4238 Instruction *InsertBefore = nullptr) {
4239 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4240 InsertBefore);
4243 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4244 unsigned NumHandlers, const Twine &NameStr,
4245 BasicBlock *InsertAtEnd) {
4246 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4247 InsertAtEnd);
4250 /// Provide fast operand accessors
4251 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4253 // Accessor Methods for CatchSwitch stmt
4254 Value *getParentPad() const { return getOperand(0); }
4255 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4257 // Accessor Methods for CatchSwitch stmt
4258 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4259 bool unwindsToCaller() const { return !hasUnwindDest(); }
4260 BasicBlock *getUnwindDest() const {
4261 if (hasUnwindDest())
4262 return cast<BasicBlock>(getOperand(1));
4263 return nullptr;
4265 void setUnwindDest(BasicBlock *UnwindDest) {
4266 assert(UnwindDest);
4267 assert(hasUnwindDest());
4268 setOperand(1, UnwindDest);
4271 /// return the number of 'handlers' in this catchswitch
4272 /// instruction, except the default handler
4273 unsigned getNumHandlers() const {
4274 if (hasUnwindDest())
4275 return getNumOperands() - 2;
4276 return getNumOperands() - 1;
4279 private:
4280 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4281 static const BasicBlock *handler_helper(const Value *V) {
4282 return cast<BasicBlock>(V);
4285 public:
4286 using DerefFnTy = BasicBlock *(*)(Value *);
4287 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4288 using handler_range = iterator_range<handler_iterator>;
4289 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4290 using const_handler_iterator =
4291 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4292 using const_handler_range = iterator_range<const_handler_iterator>;
4294 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4295 handler_iterator handler_begin() {
4296 op_iterator It = op_begin() + 1;
4297 if (hasUnwindDest())
4298 ++It;
4299 return handler_iterator(It, DerefFnTy(handler_helper));
4302 /// Returns an iterator that points to the first handler in the
4303 /// CatchSwitchInst.
4304 const_handler_iterator handler_begin() const {
4305 const_op_iterator It = op_begin() + 1;
4306 if (hasUnwindDest())
4307 ++It;
4308 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4311 /// Returns a read-only iterator that points one past the last
4312 /// handler in the CatchSwitchInst.
4313 handler_iterator handler_end() {
4314 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4317 /// Returns an iterator that points one past the last handler in the
4318 /// CatchSwitchInst.
4319 const_handler_iterator handler_end() const {
4320 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4323 /// iteration adapter for range-for loops.
4324 handler_range handlers() {
4325 return make_range(handler_begin(), handler_end());
4328 /// iteration adapter for range-for loops.
4329 const_handler_range handlers() const {
4330 return make_range(handler_begin(), handler_end());
4333 /// Add an entry to the switch instruction...
4334 /// Note:
4335 /// This action invalidates handler_end(). Old handler_end() iterator will
4336 /// point to the added handler.
4337 void addHandler(BasicBlock *Dest);
4339 void removeHandler(handler_iterator HI);
4341 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4342 BasicBlock *getSuccessor(unsigned Idx) const {
4343 assert(Idx < getNumSuccessors() &&
4344 "Successor # out of range for catchswitch!");
4345 return cast<BasicBlock>(getOperand(Idx + 1));
4347 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4348 assert(Idx < getNumSuccessors() &&
4349 "Successor # out of range for catchswitch!");
4350 setOperand(Idx + 1, NewSucc);
4353 // Methods for support type inquiry through isa, cast, and dyn_cast:
4354 static bool classof(const Instruction *I) {
4355 return I->getOpcode() == Instruction::CatchSwitch;
4357 static bool classof(const Value *V) {
4358 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4362 template <>
4363 struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4365 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4367 //===----------------------------------------------------------------------===//
4368 // CleanupPadInst Class
4369 //===----------------------------------------------------------------------===//
4370 class CleanupPadInst : public FuncletPadInst {
4371 private:
4372 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4373 unsigned Values, const Twine &NameStr,
4374 Instruction *InsertBefore)
4375 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4376 NameStr, InsertBefore) {}
4377 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4378 unsigned Values, const Twine &NameStr,
4379 BasicBlock *InsertAtEnd)
4380 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4381 NameStr, InsertAtEnd) {}
4383 public:
4384 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4385 const Twine &NameStr = "",
4386 Instruction *InsertBefore = nullptr) {
4387 unsigned Values = 1 + Args.size();
4388 return new (Values)
4389 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4392 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4393 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4394 unsigned Values = 1 + Args.size();
4395 return new (Values)
4396 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4399 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4400 static bool classof(const Instruction *I) {
4401 return I->getOpcode() == Instruction::CleanupPad;
4403 static bool classof(const Value *V) {
4404 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4408 //===----------------------------------------------------------------------===//
4409 // CatchPadInst Class
4410 //===----------------------------------------------------------------------===//
4411 class CatchPadInst : public FuncletPadInst {
4412 private:
4413 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4414 unsigned Values, const Twine &NameStr,
4415 Instruction *InsertBefore)
4416 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4417 NameStr, InsertBefore) {}
4418 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4419 unsigned Values, const Twine &NameStr,
4420 BasicBlock *InsertAtEnd)
4421 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4422 NameStr, InsertAtEnd) {}
4424 public:
4425 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4426 const Twine &NameStr = "",
4427 Instruction *InsertBefore = nullptr) {
4428 unsigned Values = 1 + Args.size();
4429 return new (Values)
4430 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4433 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4434 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4435 unsigned Values = 1 + Args.size();
4436 return new (Values)
4437 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4440 /// Convenience accessors
4441 CatchSwitchInst *getCatchSwitch() const {
4442 return cast<CatchSwitchInst>(Op<-1>());
4444 void setCatchSwitch(Value *CatchSwitch) {
4445 assert(CatchSwitch);
4446 Op<-1>() = CatchSwitch;
4449 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4450 static bool classof(const Instruction *I) {
4451 return I->getOpcode() == Instruction::CatchPad;
4453 static bool classof(const Value *V) {
4454 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4458 //===----------------------------------------------------------------------===//
4459 // CatchReturnInst Class
4460 //===----------------------------------------------------------------------===//
4462 class CatchReturnInst : public Instruction {
4463 CatchReturnInst(const CatchReturnInst &RI);
4464 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4465 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4467 void init(Value *CatchPad, BasicBlock *BB);
4469 protected:
4470 // Note: Instruction needs to be a friend here to call cloneImpl.
4471 friend class Instruction;
4473 CatchReturnInst *cloneImpl() const;
4475 public:
4476 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4477 Instruction *InsertBefore = nullptr) {
4478 assert(CatchPad);
4479 assert(BB);
4480 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4483 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4484 BasicBlock *InsertAtEnd) {
4485 assert(CatchPad);
4486 assert(BB);
4487 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4490 /// Provide fast operand accessors
4491 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4493 /// Convenience accessors.
4494 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4495 void setCatchPad(CatchPadInst *CatchPad) {
4496 assert(CatchPad);
4497 Op<0>() = CatchPad;
4500 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4501 void setSuccessor(BasicBlock *NewSucc) {
4502 assert(NewSucc);
4503 Op<1>() = NewSucc;
4505 unsigned getNumSuccessors() const { return 1; }
4507 /// Get the parentPad of this catchret's catchpad's catchswitch.
4508 /// The successor block is implicitly a member of this funclet.
4509 Value *getCatchSwitchParentPad() const {
4510 return getCatchPad()->getCatchSwitch()->getParentPad();
4513 // Methods for support type inquiry through isa, cast, and dyn_cast:
4514 static bool classof(const Instruction *I) {
4515 return (I->getOpcode() == Instruction::CatchRet);
4517 static bool classof(const Value *V) {
4518 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4521 private:
4522 BasicBlock *getSuccessor(unsigned Idx) const {
4523 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4524 return getSuccessor();
4527 void setSuccessor(unsigned Idx, BasicBlock *B) {
4528 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4529 setSuccessor(B);
4533 template <>
4534 struct OperandTraits<CatchReturnInst>
4535 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4537 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4539 //===----------------------------------------------------------------------===//
4540 // CleanupReturnInst Class
4541 //===----------------------------------------------------------------------===//
4543 class CleanupReturnInst : public Instruction {
4544 private:
4545 CleanupReturnInst(const CleanupReturnInst &RI);
4546 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4547 Instruction *InsertBefore = nullptr);
4548 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4549 BasicBlock *InsertAtEnd);
4551 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4553 protected:
4554 // Note: Instruction needs to be a friend here to call cloneImpl.
4555 friend class Instruction;
4557 CleanupReturnInst *cloneImpl() const;
4559 public:
4560 static CleanupReturnInst *Create(Value *CleanupPad,
4561 BasicBlock *UnwindBB = nullptr,
4562 Instruction *InsertBefore = nullptr) {
4563 assert(CleanupPad);
4564 unsigned Values = 1;
4565 if (UnwindBB)
4566 ++Values;
4567 return new (Values)
4568 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4571 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4572 BasicBlock *InsertAtEnd) {
4573 assert(CleanupPad);
4574 unsigned Values = 1;
4575 if (UnwindBB)
4576 ++Values;
4577 return new (Values)
4578 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4581 /// Provide fast operand accessors
4582 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4584 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4585 bool unwindsToCaller() const { return !hasUnwindDest(); }
4587 /// Convenience accessor.
4588 CleanupPadInst *getCleanupPad() const {
4589 return cast<CleanupPadInst>(Op<0>());
4591 void setCleanupPad(CleanupPadInst *CleanupPad) {
4592 assert(CleanupPad);
4593 Op<0>() = CleanupPad;
4596 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4598 BasicBlock *getUnwindDest() const {
4599 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4601 void setUnwindDest(BasicBlock *NewDest) {
4602 assert(NewDest);
4603 assert(hasUnwindDest());
4604 Op<1>() = NewDest;
4607 // Methods for support type inquiry through isa, cast, and dyn_cast:
4608 static bool classof(const Instruction *I) {
4609 return (I->getOpcode() == Instruction::CleanupRet);
4611 static bool classof(const Value *V) {
4612 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4615 private:
4616 BasicBlock *getSuccessor(unsigned Idx) const {
4617 assert(Idx == 0);
4618 return getUnwindDest();
4621 void setSuccessor(unsigned Idx, BasicBlock *B) {
4622 assert(Idx == 0);
4623 setUnwindDest(B);
4626 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4627 // method so that subclasses cannot accidentally use it.
4628 void setInstructionSubclassData(unsigned short D) {
4629 Instruction::setInstructionSubclassData(D);
4633 template <>
4634 struct OperandTraits<CleanupReturnInst>
4635 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4637 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4639 //===----------------------------------------------------------------------===//
4640 // UnreachableInst Class
4641 //===----------------------------------------------------------------------===//
4643 //===---------------------------------------------------------------------------
4644 /// This function has undefined behavior. In particular, the
4645 /// presence of this instruction indicates some higher level knowledge that the
4646 /// end of the block cannot be reached.
4648 class UnreachableInst : public Instruction {
4649 protected:
4650 // Note: Instruction needs to be a friend here to call cloneImpl.
4651 friend class Instruction;
4653 UnreachableInst *cloneImpl() const;
4655 public:
4656 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4657 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4659 // allocate space for exactly zero operands
4660 void *operator new(size_t s) {
4661 return User::operator new(s, 0);
4664 unsigned getNumSuccessors() const { return 0; }
4666 // Methods for support type inquiry through isa, cast, and dyn_cast:
4667 static bool classof(const Instruction *I) {
4668 return I->getOpcode() == Instruction::Unreachable;
4670 static bool classof(const Value *V) {
4671 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4674 private:
4675 BasicBlock *getSuccessor(unsigned idx) const {
4676 llvm_unreachable("UnreachableInst has no successors!");
4679 void setSuccessor(unsigned idx, BasicBlock *B) {
4680 llvm_unreachable("UnreachableInst has no successors!");
4684 //===----------------------------------------------------------------------===//
4685 // TruncInst Class
4686 //===----------------------------------------------------------------------===//
4688 /// This class represents a truncation of integer types.
4689 class TruncInst : public CastInst {
4690 protected:
4691 // Note: Instruction needs to be a friend here to call cloneImpl.
4692 friend class Instruction;
4694 /// Clone an identical TruncInst
4695 TruncInst *cloneImpl() const;
4697 public:
4698 /// Constructor with insert-before-instruction semantics
4699 TruncInst(
4700 Value *S, ///< The value to be truncated
4701 Type *Ty, ///< The (smaller) type to truncate to
4702 const Twine &NameStr = "", ///< A name for the new instruction
4703 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4706 /// Constructor with insert-at-end-of-block semantics
4707 TruncInst(
4708 Value *S, ///< The value to be truncated
4709 Type *Ty, ///< The (smaller) type to truncate to
4710 const Twine &NameStr, ///< A name for the new instruction
4711 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4714 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4715 static bool classof(const Instruction *I) {
4716 return I->getOpcode() == Trunc;
4718 static bool classof(const Value *V) {
4719 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4723 //===----------------------------------------------------------------------===//
4724 // ZExtInst Class
4725 //===----------------------------------------------------------------------===//
4727 /// This class represents zero extension of integer types.
4728 class ZExtInst : public CastInst {
4729 protected:
4730 // Note: Instruction needs to be a friend here to call cloneImpl.
4731 friend class Instruction;
4733 /// Clone an identical ZExtInst
4734 ZExtInst *cloneImpl() const;
4736 public:
4737 /// Constructor with insert-before-instruction semantics
4738 ZExtInst(
4739 Value *S, ///< The value to be zero extended
4740 Type *Ty, ///< The type to zero extend to
4741 const Twine &NameStr = "", ///< A name for the new instruction
4742 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4745 /// Constructor with insert-at-end semantics.
4746 ZExtInst(
4747 Value *S, ///< The value to be zero extended
4748 Type *Ty, ///< The type to zero extend to
4749 const Twine &NameStr, ///< A name for the new instruction
4750 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4753 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4754 static bool classof(const Instruction *I) {
4755 return I->getOpcode() == ZExt;
4757 static bool classof(const Value *V) {
4758 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4762 //===----------------------------------------------------------------------===//
4763 // SExtInst Class
4764 //===----------------------------------------------------------------------===//
4766 /// This class represents a sign extension of integer types.
4767 class SExtInst : public CastInst {
4768 protected:
4769 // Note: Instruction needs to be a friend here to call cloneImpl.
4770 friend class Instruction;
4772 /// Clone an identical SExtInst
4773 SExtInst *cloneImpl() const;
4775 public:
4776 /// Constructor with insert-before-instruction semantics
4777 SExtInst(
4778 Value *S, ///< The value to be sign extended
4779 Type *Ty, ///< The type to sign extend to
4780 const Twine &NameStr = "", ///< A name for the new instruction
4781 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4784 /// Constructor with insert-at-end-of-block semantics
4785 SExtInst(
4786 Value *S, ///< The value to be sign extended
4787 Type *Ty, ///< The type to sign extend to
4788 const Twine &NameStr, ///< A name for the new instruction
4789 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4792 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4793 static bool classof(const Instruction *I) {
4794 return I->getOpcode() == SExt;
4796 static bool classof(const Value *V) {
4797 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4801 //===----------------------------------------------------------------------===//
4802 // FPTruncInst Class
4803 //===----------------------------------------------------------------------===//
4805 /// This class represents a truncation of floating point types.
4806 class FPTruncInst : public CastInst {
4807 protected:
4808 // Note: Instruction needs to be a friend here to call cloneImpl.
4809 friend class Instruction;
4811 /// Clone an identical FPTruncInst
4812 FPTruncInst *cloneImpl() const;
4814 public:
4815 /// Constructor with insert-before-instruction semantics
4816 FPTruncInst(
4817 Value *S, ///< The value to be truncated
4818 Type *Ty, ///< The type to truncate to
4819 const Twine &NameStr = "", ///< A name for the new instruction
4820 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4823 /// Constructor with insert-before-instruction semantics
4824 FPTruncInst(
4825 Value *S, ///< The value to be truncated
4826 Type *Ty, ///< The type to truncate to
4827 const Twine &NameStr, ///< A name for the new instruction
4828 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4831 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4832 static bool classof(const Instruction *I) {
4833 return I->getOpcode() == FPTrunc;
4835 static bool classof(const Value *V) {
4836 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4840 //===----------------------------------------------------------------------===//
4841 // FPExtInst Class
4842 //===----------------------------------------------------------------------===//
4844 /// This class represents an extension of floating point types.
4845 class FPExtInst : public CastInst {
4846 protected:
4847 // Note: Instruction needs to be a friend here to call cloneImpl.
4848 friend class Instruction;
4850 /// Clone an identical FPExtInst
4851 FPExtInst *cloneImpl() const;
4853 public:
4854 /// Constructor with insert-before-instruction semantics
4855 FPExtInst(
4856 Value *S, ///< The value to be extended
4857 Type *Ty, ///< The type to extend to
4858 const Twine &NameStr = "", ///< A name for the new instruction
4859 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4862 /// Constructor with insert-at-end-of-block semantics
4863 FPExtInst(
4864 Value *S, ///< The value to be extended
4865 Type *Ty, ///< The type to extend to
4866 const Twine &NameStr, ///< A name for the new instruction
4867 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4870 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4871 static bool classof(const Instruction *I) {
4872 return I->getOpcode() == FPExt;
4874 static bool classof(const Value *V) {
4875 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4879 //===----------------------------------------------------------------------===//
4880 // UIToFPInst Class
4881 //===----------------------------------------------------------------------===//
4883 /// This class represents a cast unsigned integer to floating point.
4884 class UIToFPInst : public CastInst {
4885 protected:
4886 // Note: Instruction needs to be a friend here to call cloneImpl.
4887 friend class Instruction;
4889 /// Clone an identical UIToFPInst
4890 UIToFPInst *cloneImpl() const;
4892 public:
4893 /// Constructor with insert-before-instruction semantics
4894 UIToFPInst(
4895 Value *S, ///< The value to be converted
4896 Type *Ty, ///< The type to convert to
4897 const Twine &NameStr = "", ///< A name for the new instruction
4898 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4901 /// Constructor with insert-at-end-of-block semantics
4902 UIToFPInst(
4903 Value *S, ///< The value to be converted
4904 Type *Ty, ///< The type to convert to
4905 const Twine &NameStr, ///< A name for the new instruction
4906 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4909 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4910 static bool classof(const Instruction *I) {
4911 return I->getOpcode() == UIToFP;
4913 static bool classof(const Value *V) {
4914 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4918 //===----------------------------------------------------------------------===//
4919 // SIToFPInst Class
4920 //===----------------------------------------------------------------------===//
4922 /// This class represents a cast from signed integer to floating point.
4923 class SIToFPInst : public CastInst {
4924 protected:
4925 // Note: Instruction needs to be a friend here to call cloneImpl.
4926 friend class Instruction;
4928 /// Clone an identical SIToFPInst
4929 SIToFPInst *cloneImpl() const;
4931 public:
4932 /// Constructor with insert-before-instruction semantics
4933 SIToFPInst(
4934 Value *S, ///< The value to be converted
4935 Type *Ty, ///< The type to convert to
4936 const Twine &NameStr = "", ///< A name for the new instruction
4937 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4940 /// Constructor with insert-at-end-of-block semantics
4941 SIToFPInst(
4942 Value *S, ///< The value to be converted
4943 Type *Ty, ///< The type to convert to
4944 const Twine &NameStr, ///< A name for the new instruction
4945 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4948 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4949 static bool classof(const Instruction *I) {
4950 return I->getOpcode() == SIToFP;
4952 static bool classof(const Value *V) {
4953 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4957 //===----------------------------------------------------------------------===//
4958 // FPToUIInst Class
4959 //===----------------------------------------------------------------------===//
4961 /// This class represents a cast from floating point to unsigned integer
4962 class FPToUIInst : public CastInst {
4963 protected:
4964 // Note: Instruction needs to be a friend here to call cloneImpl.
4965 friend class Instruction;
4967 /// Clone an identical FPToUIInst
4968 FPToUIInst *cloneImpl() const;
4970 public:
4971 /// Constructor with insert-before-instruction semantics
4972 FPToUIInst(
4973 Value *S, ///< The value to be converted
4974 Type *Ty, ///< The type to convert to
4975 const Twine &NameStr = "", ///< A name for the new instruction
4976 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4979 /// Constructor with insert-at-end-of-block semantics
4980 FPToUIInst(
4981 Value *S, ///< The value to be converted
4982 Type *Ty, ///< The type to convert to
4983 const Twine &NameStr, ///< A name for the new instruction
4984 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
4987 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4988 static bool classof(const Instruction *I) {
4989 return I->getOpcode() == FPToUI;
4991 static bool classof(const Value *V) {
4992 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4996 //===----------------------------------------------------------------------===//
4997 // FPToSIInst Class
4998 //===----------------------------------------------------------------------===//
5000 /// This class represents a cast from floating point to signed integer.
5001 class FPToSIInst : public CastInst {
5002 protected:
5003 // Note: Instruction needs to be a friend here to call cloneImpl.
5004 friend class Instruction;
5006 /// Clone an identical FPToSIInst
5007 FPToSIInst *cloneImpl() const;
5009 public:
5010 /// Constructor with insert-before-instruction semantics
5011 FPToSIInst(
5012 Value *S, ///< The value to be converted
5013 Type *Ty, ///< The type to convert to
5014 const Twine &NameStr = "", ///< A name for the new instruction
5015 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5018 /// Constructor with insert-at-end-of-block semantics
5019 FPToSIInst(
5020 Value *S, ///< The value to be converted
5021 Type *Ty, ///< The type to convert to
5022 const Twine &NameStr, ///< A name for the new instruction
5023 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5026 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5027 static bool classof(const Instruction *I) {
5028 return I->getOpcode() == FPToSI;
5030 static bool classof(const Value *V) {
5031 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5035 //===----------------------------------------------------------------------===//
5036 // IntToPtrInst Class
5037 //===----------------------------------------------------------------------===//
5039 /// This class represents a cast from an integer to a pointer.
5040 class IntToPtrInst : public CastInst {
5041 public:
5042 // Note: Instruction needs to be a friend here to call cloneImpl.
5043 friend class Instruction;
5045 /// Constructor with insert-before-instruction semantics
5046 IntToPtrInst(
5047 Value *S, ///< The value to be converted
5048 Type *Ty, ///< The type to convert to
5049 const Twine &NameStr = "", ///< A name for the new instruction
5050 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5053 /// Constructor with insert-at-end-of-block semantics
5054 IntToPtrInst(
5055 Value *S, ///< The value to be converted
5056 Type *Ty, ///< The type to convert to
5057 const Twine &NameStr, ///< A name for the new instruction
5058 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5061 /// Clone an identical IntToPtrInst.
5062 IntToPtrInst *cloneImpl() const;
5064 /// Returns the address space of this instruction's pointer type.
5065 unsigned getAddressSpace() const {
5066 return getType()->getPointerAddressSpace();
5069 // Methods for support type inquiry through isa, cast, and dyn_cast:
5070 static bool classof(const Instruction *I) {
5071 return I->getOpcode() == IntToPtr;
5073 static bool classof(const Value *V) {
5074 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5078 //===----------------------------------------------------------------------===//
5079 // PtrToIntInst Class
5080 //===----------------------------------------------------------------------===//
5082 /// This class represents a cast from a pointer to an integer.
5083 class PtrToIntInst : public CastInst {
5084 protected:
5085 // Note: Instruction needs to be a friend here to call cloneImpl.
5086 friend class Instruction;
5088 /// Clone an identical PtrToIntInst.
5089 PtrToIntInst *cloneImpl() const;
5091 public:
5092 /// Constructor with insert-before-instruction semantics
5093 PtrToIntInst(
5094 Value *S, ///< The value to be converted
5095 Type *Ty, ///< The type to convert to
5096 const Twine &NameStr = "", ///< A name for the new instruction
5097 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5100 /// Constructor with insert-at-end-of-block semantics
5101 PtrToIntInst(
5102 Value *S, ///< The value to be converted
5103 Type *Ty, ///< The type to convert to
5104 const Twine &NameStr, ///< A name for the new instruction
5105 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5108 /// Gets the pointer operand.
5109 Value *getPointerOperand() { return getOperand(0); }
5110 /// Gets the pointer operand.
5111 const Value *getPointerOperand() const { return getOperand(0); }
5112 /// Gets the operand index of the pointer operand.
5113 static unsigned getPointerOperandIndex() { return 0U; }
5115 /// Returns the address space of the pointer operand.
5116 unsigned getPointerAddressSpace() const {
5117 return getPointerOperand()->getType()->getPointerAddressSpace();
5120 // Methods for support type inquiry through isa, cast, and dyn_cast:
5121 static bool classof(const Instruction *I) {
5122 return I->getOpcode() == PtrToInt;
5124 static bool classof(const Value *V) {
5125 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5129 //===----------------------------------------------------------------------===//
5130 // BitCastInst Class
5131 //===----------------------------------------------------------------------===//
5133 /// This class represents a no-op cast from one type to another.
5134 class BitCastInst : public CastInst {
5135 protected:
5136 // Note: Instruction needs to be a friend here to call cloneImpl.
5137 friend class Instruction;
5139 /// Clone an identical BitCastInst.
5140 BitCastInst *cloneImpl() const;
5142 public:
5143 /// Constructor with insert-before-instruction semantics
5144 BitCastInst(
5145 Value *S, ///< The value to be casted
5146 Type *Ty, ///< The type to casted to
5147 const Twine &NameStr = "", ///< A name for the new instruction
5148 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5151 /// Constructor with insert-at-end-of-block semantics
5152 BitCastInst(
5153 Value *S, ///< The value to be casted
5154 Type *Ty, ///< The type to casted to
5155 const Twine &NameStr, ///< A name for the new instruction
5156 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5159 // Methods for support type inquiry through isa, cast, and dyn_cast:
5160 static bool classof(const Instruction *I) {
5161 return I->getOpcode() == BitCast;
5163 static bool classof(const Value *V) {
5164 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5168 //===----------------------------------------------------------------------===//
5169 // AddrSpaceCastInst Class
5170 //===----------------------------------------------------------------------===//
5172 /// This class represents a conversion between pointers from one address space
5173 /// to another.
5174 class AddrSpaceCastInst : public CastInst {
5175 protected:
5176 // Note: Instruction needs to be a friend here to call cloneImpl.
5177 friend class Instruction;
5179 /// Clone an identical AddrSpaceCastInst.
5180 AddrSpaceCastInst *cloneImpl() const;
5182 public:
5183 /// Constructor with insert-before-instruction semantics
5184 AddrSpaceCastInst(
5185 Value *S, ///< The value to be casted
5186 Type *Ty, ///< The type to casted to
5187 const Twine &NameStr = "", ///< A name for the new instruction
5188 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5191 /// Constructor with insert-at-end-of-block semantics
5192 AddrSpaceCastInst(
5193 Value *S, ///< The value to be casted
5194 Type *Ty, ///< The type to casted to
5195 const Twine &NameStr, ///< A name for the new instruction
5196 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5199 // Methods for support type inquiry through isa, cast, and dyn_cast:
5200 static bool classof(const Instruction *I) {
5201 return I->getOpcode() == AddrSpaceCast;
5203 static bool classof(const Value *V) {
5204 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5207 /// Gets the pointer operand.
5208 Value *getPointerOperand() {
5209 return getOperand(0);
5212 /// Gets the pointer operand.
5213 const Value *getPointerOperand() const {
5214 return getOperand(0);
5217 /// Gets the operand index of the pointer operand.
5218 static unsigned getPointerOperandIndex() {
5219 return 0U;
5222 /// Returns the address space of the pointer operand.
5223 unsigned getSrcAddressSpace() const {
5224 return getPointerOperand()->getType()->getPointerAddressSpace();
5227 /// Returns the address space of the result.
5228 unsigned getDestAddressSpace() const {
5229 return getType()->getPointerAddressSpace();
5233 /// A helper function that returns the pointer operand of a load or store
5234 /// instruction. Returns nullptr if not load or store.
5235 inline Value *getLoadStorePointerOperand(Value *V) {
5236 if (auto *Load = dyn_cast<LoadInst>(V))
5237 return Load->getPointerOperand();
5238 if (auto *Store = dyn_cast<StoreInst>(V))
5239 return Store->getPointerOperand();
5240 return nullptr;
5243 /// A helper function that returns the pointer operand of a load, store
5244 /// or GEP instruction. Returns nullptr if not load, store, or GEP.
5245 inline Value *getPointerOperand(Value *V) {
5246 if (auto *Ptr = getLoadStorePointerOperand(V))
5247 return Ptr;
5248 if (auto *Gep = dyn_cast<GetElementPtrInst>(V))
5249 return Gep->getPointerOperand();
5250 return nullptr;
5253 /// A helper function that returns the alignment of load or store instruction.
5254 inline unsigned getLoadStoreAlignment(Value *I) {
5255 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5256 "Expected Load or Store instruction");
5257 if (auto *LI = dyn_cast<LoadInst>(I))
5258 return LI->getAlignment();
5259 return cast<StoreInst>(I)->getAlignment();
5262 /// A helper function that returns the address space of the pointer operand of
5263 /// load or store instruction.
5264 inline unsigned getLoadStoreAddressSpace(Value *I) {
5265 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5266 "Expected Load or Store instruction");
5267 if (auto *LI = dyn_cast<LoadInst>(I))
5268 return LI->getPointerAddressSpace();
5269 return cast<StoreInst>(I)->getPointerAddressSpace();
5272 } // end namespace llvm
5274 #endif // LLVM_IR_INSTRUCTIONS_H