[llvm] [cmake] Add possibility to use ChooseMSVCCRT.cmake when include LLVM library
[llvm-core.git] / include / llvm / IR / Instructions.h
blobc99fd78426300f581a87339da2b91ae79eb50947
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. The value returned by this instruction is a pair containing the
527 /// original value as first element, and an i1 indicating success (true) or
528 /// failure (false) as second element.
530 class AtomicCmpXchgInst : public Instruction {
531 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
532 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
533 SyncScope::ID SSID);
535 protected:
536 // Note: Instruction needs to be a friend here to call cloneImpl.
537 friend class Instruction;
539 AtomicCmpXchgInst *cloneImpl() const;
541 public:
542 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
543 AtomicOrdering SuccessOrdering,
544 AtomicOrdering FailureOrdering,
545 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
546 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
547 AtomicOrdering SuccessOrdering,
548 AtomicOrdering FailureOrdering,
549 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
551 // allocate space for exactly three operands
552 void *operator new(size_t s) {
553 return User::operator new(s, 3);
556 /// Return true if this is a cmpxchg from a volatile memory
557 /// location.
559 bool isVolatile() const {
560 return getSubclassDataFromInstruction() & 1;
563 /// Specify whether this is a volatile cmpxchg.
565 void setVolatile(bool V) {
566 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
567 (unsigned)V);
570 /// Return true if this cmpxchg may spuriously fail.
571 bool isWeak() const {
572 return getSubclassDataFromInstruction() & 0x100;
575 void setWeak(bool IsWeak) {
576 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
577 (IsWeak << 8));
580 /// Transparently provide more efficient getOperand methods.
581 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
583 /// Returns the success ordering constraint of this cmpxchg instruction.
584 AtomicOrdering getSuccessOrdering() const {
585 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
588 /// Sets the success ordering constraint of this cmpxchg instruction.
589 void setSuccessOrdering(AtomicOrdering Ordering) {
590 assert(Ordering != AtomicOrdering::NotAtomic &&
591 "CmpXchg instructions can only be atomic.");
592 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
593 ((unsigned)Ordering << 2));
596 /// Returns the failure ordering constraint of this cmpxchg instruction.
597 AtomicOrdering getFailureOrdering() const {
598 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
601 /// Sets the failure ordering constraint of this cmpxchg instruction.
602 void setFailureOrdering(AtomicOrdering Ordering) {
603 assert(Ordering != AtomicOrdering::NotAtomic &&
604 "CmpXchg instructions can only be atomic.");
605 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
606 ((unsigned)Ordering << 5));
609 /// Returns the synchronization scope ID of this cmpxchg instruction.
610 SyncScope::ID getSyncScopeID() const {
611 return SSID;
614 /// Sets the synchronization scope ID of this cmpxchg instruction.
615 void setSyncScopeID(SyncScope::ID SSID) {
616 this->SSID = SSID;
619 Value *getPointerOperand() { return getOperand(0); }
620 const Value *getPointerOperand() const { return getOperand(0); }
621 static unsigned getPointerOperandIndex() { return 0U; }
623 Value *getCompareOperand() { return getOperand(1); }
624 const Value *getCompareOperand() const { return getOperand(1); }
626 Value *getNewValOperand() { return getOperand(2); }
627 const Value *getNewValOperand() const { return getOperand(2); }
629 /// Returns the address space of the pointer operand.
630 unsigned getPointerAddressSpace() const {
631 return getPointerOperand()->getType()->getPointerAddressSpace();
634 /// Returns the strongest permitted ordering on failure, given the
635 /// desired ordering on success.
637 /// If the comparison in a cmpxchg operation fails, there is no atomic store
638 /// so release semantics cannot be provided. So this function drops explicit
639 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
640 /// operation would remain SequentiallyConsistent.
641 static AtomicOrdering
642 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
643 switch (SuccessOrdering) {
644 default:
645 llvm_unreachable("invalid cmpxchg success ordering");
646 case AtomicOrdering::Release:
647 case AtomicOrdering::Monotonic:
648 return AtomicOrdering::Monotonic;
649 case AtomicOrdering::AcquireRelease:
650 case AtomicOrdering::Acquire:
651 return AtomicOrdering::Acquire;
652 case AtomicOrdering::SequentiallyConsistent:
653 return AtomicOrdering::SequentiallyConsistent;
657 // Methods for support type inquiry through isa, cast, and dyn_cast:
658 static bool classof(const Instruction *I) {
659 return I->getOpcode() == Instruction::AtomicCmpXchg;
661 static bool classof(const Value *V) {
662 return isa<Instruction>(V) && classof(cast<Instruction>(V));
665 private:
666 // Shadow Instruction::setInstructionSubclassData with a private forwarding
667 // method so that subclasses cannot accidentally use it.
668 void setInstructionSubclassData(unsigned short D) {
669 Instruction::setInstructionSubclassData(D);
672 /// The synchronization scope ID of this cmpxchg instruction. Not quite
673 /// enough room in SubClassData for everything, so synchronization scope ID
674 /// gets its own field.
675 SyncScope::ID SSID;
678 template <>
679 struct OperandTraits<AtomicCmpXchgInst> :
680 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
683 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
685 //===----------------------------------------------------------------------===//
686 // AtomicRMWInst Class
687 //===----------------------------------------------------------------------===//
689 /// an instruction that atomically reads a memory location,
690 /// combines it with another value, and then stores the result back. Returns
691 /// the old value.
693 class AtomicRMWInst : public Instruction {
694 protected:
695 // Note: Instruction needs to be a friend here to call cloneImpl.
696 friend class Instruction;
698 AtomicRMWInst *cloneImpl() const;
700 public:
701 /// This enumeration lists the possible modifications atomicrmw can make. In
702 /// the descriptions, 'p' is the pointer to the instruction's memory location,
703 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
704 /// instruction. These instructions always return 'old'.
705 enum BinOp {
706 /// *p = v
707 Xchg,
708 /// *p = old + v
709 Add,
710 /// *p = old - v
711 Sub,
712 /// *p = old & v
713 And,
714 /// *p = ~(old & v)
715 Nand,
716 /// *p = old | v
718 /// *p = old ^ v
719 Xor,
720 /// *p = old >signed v ? old : v
721 Max,
722 /// *p = old <signed v ? old : v
723 Min,
724 /// *p = old >unsigned v ? old : v
725 UMax,
726 /// *p = old <unsigned v ? old : v
727 UMin,
729 /// *p = old + v
730 FAdd,
732 /// *p = old - v
733 FSub,
735 FIRST_BINOP = Xchg,
736 LAST_BINOP = FSub,
737 BAD_BINOP
740 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
741 AtomicOrdering Ordering, SyncScope::ID SSID,
742 Instruction *InsertBefore = nullptr);
743 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
744 AtomicOrdering Ordering, SyncScope::ID SSID,
745 BasicBlock *InsertAtEnd);
747 // allocate space for exactly two operands
748 void *operator new(size_t s) {
749 return User::operator new(s, 2);
752 BinOp getOperation() const {
753 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
756 static StringRef getOperationName(BinOp Op);
758 static bool isFPOperation(BinOp Op) {
759 switch (Op) {
760 case AtomicRMWInst::FAdd:
761 case AtomicRMWInst::FSub:
762 return true;
763 default:
764 return false;
768 void setOperation(BinOp Operation) {
769 unsigned short SubclassData = getSubclassDataFromInstruction();
770 setInstructionSubclassData((SubclassData & 31) |
771 (Operation << 5));
774 /// Return true if this is a RMW on a volatile memory location.
776 bool isVolatile() const {
777 return getSubclassDataFromInstruction() & 1;
780 /// Specify whether this is a volatile RMW or not.
782 void setVolatile(bool V) {
783 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
784 (unsigned)V);
787 /// Transparently provide more efficient getOperand methods.
788 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
790 /// Returns the ordering constraint of this rmw instruction.
791 AtomicOrdering getOrdering() const {
792 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
795 /// Sets the ordering constraint of this rmw instruction.
796 void setOrdering(AtomicOrdering Ordering) {
797 assert(Ordering != AtomicOrdering::NotAtomic &&
798 "atomicrmw instructions can only be atomic.");
799 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
800 ((unsigned)Ordering << 2));
803 /// Returns the synchronization scope ID of this rmw instruction.
804 SyncScope::ID getSyncScopeID() const {
805 return SSID;
808 /// Sets the synchronization scope ID of this rmw instruction.
809 void setSyncScopeID(SyncScope::ID SSID) {
810 this->SSID = SSID;
813 Value *getPointerOperand() { return getOperand(0); }
814 const Value *getPointerOperand() const { return getOperand(0); }
815 static unsigned getPointerOperandIndex() { return 0U; }
817 Value *getValOperand() { return getOperand(1); }
818 const Value *getValOperand() const { return getOperand(1); }
820 /// Returns the address space of the pointer operand.
821 unsigned getPointerAddressSpace() const {
822 return getPointerOperand()->getType()->getPointerAddressSpace();
825 bool isFloatingPointOperation() const {
826 return isFPOperation(getOperation());
829 // Methods for support type inquiry through isa, cast, and dyn_cast:
830 static bool classof(const Instruction *I) {
831 return I->getOpcode() == Instruction::AtomicRMW;
833 static bool classof(const Value *V) {
834 return isa<Instruction>(V) && classof(cast<Instruction>(V));
837 private:
838 void Init(BinOp Operation, Value *Ptr, Value *Val,
839 AtomicOrdering Ordering, SyncScope::ID SSID);
841 // Shadow Instruction::setInstructionSubclassData with a private forwarding
842 // method so that subclasses cannot accidentally use it.
843 void setInstructionSubclassData(unsigned short D) {
844 Instruction::setInstructionSubclassData(D);
847 /// The synchronization scope ID of this rmw instruction. Not quite enough
848 /// room in SubClassData for everything, so synchronization scope ID gets its
849 /// own field.
850 SyncScope::ID SSID;
853 template <>
854 struct OperandTraits<AtomicRMWInst>
855 : public FixedNumOperandTraits<AtomicRMWInst,2> {
858 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
860 //===----------------------------------------------------------------------===//
861 // GetElementPtrInst Class
862 //===----------------------------------------------------------------------===//
864 // checkGEPType - Simple wrapper function to give a better assertion failure
865 // message on bad indexes for a gep instruction.
867 inline Type *checkGEPType(Type *Ty) {
868 assert(Ty && "Invalid GetElementPtrInst indices for type!");
869 return Ty;
872 /// an instruction for type-safe pointer arithmetic to
873 /// access elements of arrays and structs
875 class GetElementPtrInst : public Instruction {
876 Type *SourceElementType;
877 Type *ResultElementType;
879 GetElementPtrInst(const GetElementPtrInst &GEPI);
881 /// Constructors - Create a getelementptr instruction with a base pointer an
882 /// list of indices. The first ctor can optionally insert before an existing
883 /// instruction, the second appends the new instruction to the specified
884 /// BasicBlock.
885 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
886 ArrayRef<Value *> IdxList, unsigned Values,
887 const Twine &NameStr, Instruction *InsertBefore);
888 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
889 ArrayRef<Value *> IdxList, unsigned Values,
890 const Twine &NameStr, BasicBlock *InsertAtEnd);
892 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
894 protected:
895 // Note: Instruction needs to be a friend here to call cloneImpl.
896 friend class Instruction;
898 GetElementPtrInst *cloneImpl() const;
900 public:
901 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
902 ArrayRef<Value *> IdxList,
903 const Twine &NameStr = "",
904 Instruction *InsertBefore = nullptr) {
905 unsigned Values = 1 + unsigned(IdxList.size());
906 if (!PointeeType)
907 PointeeType =
908 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
909 else
910 assert(
911 PointeeType ==
912 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
913 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
914 NameStr, InsertBefore);
917 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
918 ArrayRef<Value *> IdxList,
919 const Twine &NameStr,
920 BasicBlock *InsertAtEnd) {
921 unsigned Values = 1 + unsigned(IdxList.size());
922 if (!PointeeType)
923 PointeeType =
924 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
925 else
926 assert(
927 PointeeType ==
928 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
929 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
930 NameStr, InsertAtEnd);
933 /// Create an "inbounds" getelementptr. See the documentation for the
934 /// "inbounds" flag in LangRef.html for details.
935 static GetElementPtrInst *CreateInBounds(Value *Ptr,
936 ArrayRef<Value *> IdxList,
937 const Twine &NameStr = "",
938 Instruction *InsertBefore = nullptr){
939 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
942 static GetElementPtrInst *
943 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
944 const Twine &NameStr = "",
945 Instruction *InsertBefore = nullptr) {
946 GetElementPtrInst *GEP =
947 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
948 GEP->setIsInBounds(true);
949 return GEP;
952 static GetElementPtrInst *CreateInBounds(Value *Ptr,
953 ArrayRef<Value *> IdxList,
954 const Twine &NameStr,
955 BasicBlock *InsertAtEnd) {
956 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
959 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
960 ArrayRef<Value *> IdxList,
961 const Twine &NameStr,
962 BasicBlock *InsertAtEnd) {
963 GetElementPtrInst *GEP =
964 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
965 GEP->setIsInBounds(true);
966 return GEP;
969 /// Transparently provide more efficient getOperand methods.
970 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
972 Type *getSourceElementType() const { return SourceElementType; }
974 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
975 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
977 Type *getResultElementType() const {
978 assert(ResultElementType ==
979 cast<PointerType>(getType()->getScalarType())->getElementType());
980 return ResultElementType;
983 /// Returns the address space of this instruction's pointer type.
984 unsigned getAddressSpace() const {
985 // Note that this is always the same as the pointer operand's address space
986 // and that is cheaper to compute, so cheat here.
987 return getPointerAddressSpace();
990 /// Returns the type of the element that would be loaded with
991 /// a load instruction with the specified parameters.
993 /// Null is returned if the indices are invalid for the specified
994 /// pointer type.
996 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
997 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
998 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1000 inline op_iterator idx_begin() { return op_begin()+1; }
1001 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1002 inline op_iterator idx_end() { return op_end(); }
1003 inline const_op_iterator idx_end() const { return op_end(); }
1005 inline iterator_range<op_iterator> indices() {
1006 return make_range(idx_begin(), idx_end());
1009 inline iterator_range<const_op_iterator> indices() const {
1010 return make_range(idx_begin(), idx_end());
1013 Value *getPointerOperand() {
1014 return getOperand(0);
1016 const Value *getPointerOperand() const {
1017 return getOperand(0);
1019 static unsigned getPointerOperandIndex() {
1020 return 0U; // get index for modifying correct operand.
1023 /// Method to return the pointer operand as a
1024 /// PointerType.
1025 Type *getPointerOperandType() const {
1026 return getPointerOperand()->getType();
1029 /// Returns the address space of the pointer operand.
1030 unsigned getPointerAddressSpace() const {
1031 return getPointerOperandType()->getPointerAddressSpace();
1034 /// Returns the pointer type returned by the GEP
1035 /// instruction, which may be a vector of pointers.
1036 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
1037 return getGEPReturnType(
1038 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1039 Ptr, IdxList);
1041 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1042 ArrayRef<Value *> IdxList) {
1043 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1044 Ptr->getType()->getPointerAddressSpace());
1045 // Vector GEP
1046 if (Ptr->getType()->isVectorTy()) {
1047 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1048 return VectorType::get(PtrTy, NumElem);
1050 for (Value *Index : IdxList)
1051 if (Index->getType()->isVectorTy()) {
1052 unsigned NumElem = Index->getType()->getVectorNumElements();
1053 return VectorType::get(PtrTy, NumElem);
1055 // Scalar GEP
1056 return PtrTy;
1059 unsigned getNumIndices() const { // Note: always non-negative
1060 return getNumOperands() - 1;
1063 bool hasIndices() const {
1064 return getNumOperands() > 1;
1067 /// Return true if all of the indices of this GEP are
1068 /// zeros. If so, the result pointer and the first operand have the same
1069 /// value, just potentially different types.
1070 bool hasAllZeroIndices() const;
1072 /// Return true if all of the indices of this GEP are
1073 /// constant integers. If so, the result pointer and the first operand have
1074 /// a constant offset between them.
1075 bool hasAllConstantIndices() const;
1077 /// Set or clear the inbounds flag on this GEP instruction.
1078 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1079 void setIsInBounds(bool b = true);
1081 /// Determine whether the GEP has the inbounds flag.
1082 bool isInBounds() const;
1084 /// Accumulate the constant address offset of this GEP if possible.
1086 /// This routine accepts an APInt into which it will accumulate the constant
1087 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1088 /// all-constant, it returns false and the value of the offset APInt is
1089 /// undefined (it is *not* preserved!). The APInt passed into this routine
1090 /// must be at least as wide as the IntPtr type for the address space of
1091 /// the base GEP pointer.
1092 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1094 // Methods for support type inquiry through isa, cast, and dyn_cast:
1095 static bool classof(const Instruction *I) {
1096 return (I->getOpcode() == Instruction::GetElementPtr);
1098 static bool classof(const Value *V) {
1099 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1103 template <>
1104 struct OperandTraits<GetElementPtrInst> :
1105 public VariadicOperandTraits<GetElementPtrInst, 1> {
1108 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1109 ArrayRef<Value *> IdxList, unsigned Values,
1110 const Twine &NameStr,
1111 Instruction *InsertBefore)
1112 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1113 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1114 Values, InsertBefore),
1115 SourceElementType(PointeeType),
1116 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1117 assert(ResultElementType ==
1118 cast<PointerType>(getType()->getScalarType())->getElementType());
1119 init(Ptr, IdxList, NameStr);
1122 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1123 ArrayRef<Value *> IdxList, unsigned Values,
1124 const Twine &NameStr,
1125 BasicBlock *InsertAtEnd)
1126 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1127 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1128 Values, InsertAtEnd),
1129 SourceElementType(PointeeType),
1130 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1131 assert(ResultElementType ==
1132 cast<PointerType>(getType()->getScalarType())->getElementType());
1133 init(Ptr, IdxList, NameStr);
1136 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1138 //===----------------------------------------------------------------------===//
1139 // ICmpInst Class
1140 //===----------------------------------------------------------------------===//
1142 /// This instruction compares its operands according to the predicate given
1143 /// to the constructor. It only operates on integers or pointers. The operands
1144 /// must be identical types.
1145 /// Represent an integer comparison operator.
1146 class ICmpInst: public CmpInst {
1147 void AssertOK() {
1148 assert(isIntPredicate() &&
1149 "Invalid ICmp predicate value");
1150 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1151 "Both operands to ICmp instruction are not of the same type!");
1152 // Check that the operands are the right type
1153 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1154 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1155 "Invalid operand types for ICmp instruction");
1158 protected:
1159 // Note: Instruction needs to be a friend here to call cloneImpl.
1160 friend class Instruction;
1162 /// Clone an identical ICmpInst
1163 ICmpInst *cloneImpl() const;
1165 public:
1166 /// Constructor with insert-before-instruction semantics.
1167 ICmpInst(
1168 Instruction *InsertBefore, ///< Where to insert
1169 Predicate pred, ///< The predicate to use for the comparison
1170 Value *LHS, ///< The left-hand-side of the expression
1171 Value *RHS, ///< The right-hand-side of the expression
1172 const Twine &NameStr = "" ///< Name of the instruction
1173 ) : CmpInst(makeCmpResultType(LHS->getType()),
1174 Instruction::ICmp, pred, LHS, RHS, NameStr,
1175 InsertBefore) {
1176 #ifndef NDEBUG
1177 AssertOK();
1178 #endif
1181 /// Constructor with insert-at-end semantics.
1182 ICmpInst(
1183 BasicBlock &InsertAtEnd, ///< Block to insert into.
1184 Predicate pred, ///< The predicate to use for the comparison
1185 Value *LHS, ///< The left-hand-side of the expression
1186 Value *RHS, ///< The right-hand-side of the expression
1187 const Twine &NameStr = "" ///< Name of the instruction
1188 ) : CmpInst(makeCmpResultType(LHS->getType()),
1189 Instruction::ICmp, pred, LHS, RHS, NameStr,
1190 &InsertAtEnd) {
1191 #ifndef NDEBUG
1192 AssertOK();
1193 #endif
1196 /// Constructor with no-insertion semantics
1197 ICmpInst(
1198 Predicate pred, ///< The predicate to use for the comparison
1199 Value *LHS, ///< The left-hand-side of the expression
1200 Value *RHS, ///< The right-hand-side of the expression
1201 const Twine &NameStr = "" ///< Name of the instruction
1202 ) : CmpInst(makeCmpResultType(LHS->getType()),
1203 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1204 #ifndef NDEBUG
1205 AssertOK();
1206 #endif
1209 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1210 /// @returns the predicate that would be the result if the operand were
1211 /// regarded as signed.
1212 /// Return the signed version of the predicate
1213 Predicate getSignedPredicate() const {
1214 return getSignedPredicate(getPredicate());
1217 /// This is a static version that you can use without an instruction.
1218 /// Return the signed version of the predicate.
1219 static Predicate getSignedPredicate(Predicate pred);
1221 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1222 /// @returns the predicate that would be the result if the operand were
1223 /// regarded as unsigned.
1224 /// Return the unsigned version of the predicate
1225 Predicate getUnsignedPredicate() const {
1226 return getUnsignedPredicate(getPredicate());
1229 /// This is a static version that you can use without an instruction.
1230 /// Return the unsigned version of the predicate.
1231 static Predicate getUnsignedPredicate(Predicate pred);
1233 /// Return true if this predicate is either EQ or NE. This also
1234 /// tests for commutativity.
1235 static bool isEquality(Predicate P) {
1236 return P == ICMP_EQ || P == ICMP_NE;
1239 /// Return true if this predicate is either EQ or NE. This also
1240 /// tests for commutativity.
1241 bool isEquality() const {
1242 return isEquality(getPredicate());
1245 /// @returns true if the predicate of this ICmpInst is commutative
1246 /// Determine if this relation is commutative.
1247 bool isCommutative() const { return isEquality(); }
1249 /// Return true if the predicate is relational (not EQ or NE).
1251 bool isRelational() const {
1252 return !isEquality();
1255 /// Return true if the predicate is relational (not EQ or NE).
1257 static bool isRelational(Predicate P) {
1258 return !isEquality(P);
1261 /// Exchange the two operands to this instruction in such a way that it does
1262 /// not modify the semantics of the instruction. The predicate value may be
1263 /// changed to retain the same result if the predicate is order dependent
1264 /// (e.g. ult).
1265 /// Swap operands and adjust predicate.
1266 void swapOperands() {
1267 setPredicate(getSwappedPredicate());
1268 Op<0>().swap(Op<1>());
1271 // Methods for support type inquiry through isa, cast, and dyn_cast:
1272 static bool classof(const Instruction *I) {
1273 return I->getOpcode() == Instruction::ICmp;
1275 static bool classof(const Value *V) {
1276 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1280 //===----------------------------------------------------------------------===//
1281 // FCmpInst Class
1282 //===----------------------------------------------------------------------===//
1284 /// This instruction compares its operands according to the predicate given
1285 /// to the constructor. It only operates on floating point values or packed
1286 /// vectors of floating point values. The operands must be identical types.
1287 /// Represents a floating point comparison operator.
1288 class FCmpInst: public CmpInst {
1289 void AssertOK() {
1290 assert(isFPPredicate() && "Invalid FCmp predicate value");
1291 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1292 "Both operands to FCmp instruction are not of the same type!");
1293 // Check that the operands are the right type
1294 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1295 "Invalid operand types for FCmp instruction");
1298 protected:
1299 // Note: Instruction needs to be a friend here to call cloneImpl.
1300 friend class Instruction;
1302 /// Clone an identical FCmpInst
1303 FCmpInst *cloneImpl() const;
1305 public:
1306 /// Constructor with insert-before-instruction semantics.
1307 FCmpInst(
1308 Instruction *InsertBefore, ///< Where to insert
1309 Predicate pred, ///< The predicate to use for the comparison
1310 Value *LHS, ///< The left-hand-side of the expression
1311 Value *RHS, ///< The right-hand-side of the expression
1312 const Twine &NameStr = "" ///< Name of the instruction
1313 ) : CmpInst(makeCmpResultType(LHS->getType()),
1314 Instruction::FCmp, pred, LHS, RHS, NameStr,
1315 InsertBefore) {
1316 AssertOK();
1319 /// Constructor with insert-at-end semantics.
1320 FCmpInst(
1321 BasicBlock &InsertAtEnd, ///< Block to insert into.
1322 Predicate pred, ///< The predicate to use for the comparison
1323 Value *LHS, ///< The left-hand-side of the expression
1324 Value *RHS, ///< The right-hand-side of the expression
1325 const Twine &NameStr = "" ///< Name of the instruction
1326 ) : CmpInst(makeCmpResultType(LHS->getType()),
1327 Instruction::FCmp, pred, LHS, RHS, NameStr,
1328 &InsertAtEnd) {
1329 AssertOK();
1332 /// Constructor with no-insertion semantics
1333 FCmpInst(
1334 Predicate Pred, ///< The predicate to use for the comparison
1335 Value *LHS, ///< The left-hand-side of the expression
1336 Value *RHS, ///< The right-hand-side of the expression
1337 const Twine &NameStr = "", ///< Name of the instruction
1338 Instruction *FlagsSource = nullptr
1339 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1340 RHS, NameStr, nullptr, FlagsSource) {
1341 AssertOK();
1344 /// @returns true if the predicate of this instruction is EQ or NE.
1345 /// Determine if this is an equality predicate.
1346 static bool isEquality(Predicate Pred) {
1347 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1348 Pred == FCMP_UNE;
1351 /// @returns true if the predicate of this instruction is EQ or NE.
1352 /// Determine if this is an equality predicate.
1353 bool isEquality() const { return isEquality(getPredicate()); }
1355 /// @returns true if the predicate of this instruction is commutative.
1356 /// Determine if this is a commutative predicate.
1357 bool isCommutative() const {
1358 return isEquality() ||
1359 getPredicate() == FCMP_FALSE ||
1360 getPredicate() == FCMP_TRUE ||
1361 getPredicate() == FCMP_ORD ||
1362 getPredicate() == FCMP_UNO;
1365 /// @returns true if the predicate is relational (not EQ or NE).
1366 /// Determine if this a relational predicate.
1367 bool isRelational() const { return !isEquality(); }
1369 /// Exchange the two operands to this instruction in such a way that it does
1370 /// not modify the semantics of the instruction. The predicate value may be
1371 /// changed to retain the same result if the predicate is order dependent
1372 /// (e.g. ult).
1373 /// Swap operands and adjust predicate.
1374 void swapOperands() {
1375 setPredicate(getSwappedPredicate());
1376 Op<0>().swap(Op<1>());
1379 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1380 static bool classof(const Instruction *I) {
1381 return I->getOpcode() == Instruction::FCmp;
1383 static bool classof(const Value *V) {
1384 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1388 //===----------------------------------------------------------------------===//
1389 /// This class represents a function call, abstracting a target
1390 /// machine's calling convention. This class uses low bit of the SubClassData
1391 /// field to indicate whether or not this is a tail call. The rest of the bits
1392 /// hold the calling convention of the call.
1394 class CallInst : public CallBase {
1395 CallInst(const CallInst &CI);
1397 /// Construct a CallInst given a range of arguments.
1398 /// Construct a CallInst from a range of arguments
1399 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1400 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1401 Instruction *InsertBefore);
1403 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1404 const Twine &NameStr, Instruction *InsertBefore)
1405 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1407 /// Construct a CallInst given a range of arguments.
1408 /// Construct a CallInst from a range of arguments
1409 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1410 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1411 BasicBlock *InsertAtEnd);
1413 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1414 Instruction *InsertBefore);
1416 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1417 BasicBlock *InsertAtEnd);
1419 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1420 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1421 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1423 /// Compute the number of operands to allocate.
1424 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1425 // We need one operand for the called function, plus the input operand
1426 // counts provided.
1427 return 1 + NumArgs + NumBundleInputs;
1430 protected:
1431 // Note: Instruction needs to be a friend here to call cloneImpl.
1432 friend class Instruction;
1434 CallInst *cloneImpl() const;
1436 public:
1437 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1438 Instruction *InsertBefore = nullptr) {
1439 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1442 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1443 const Twine &NameStr,
1444 Instruction *InsertBefore = nullptr) {
1445 return new (ComputeNumOperands(Args.size()))
1446 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1449 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1450 ArrayRef<OperandBundleDef> Bundles = None,
1451 const Twine &NameStr = "",
1452 Instruction *InsertBefore = nullptr) {
1453 const int NumOperands =
1454 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1455 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1457 return new (NumOperands, DescriptorBytes)
1458 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1461 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1462 BasicBlock *InsertAtEnd) {
1463 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1466 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1467 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1468 return new (ComputeNumOperands(Args.size()))
1469 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1472 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1473 ArrayRef<OperandBundleDef> Bundles,
1474 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1475 const int NumOperands =
1476 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1477 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1479 return new (NumOperands, DescriptorBytes)
1480 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1483 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1484 Instruction *InsertBefore = nullptr) {
1485 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1486 InsertBefore);
1489 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1490 ArrayRef<OperandBundleDef> Bundles = None,
1491 const Twine &NameStr = "",
1492 Instruction *InsertBefore = nullptr) {
1493 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1494 NameStr, InsertBefore);
1497 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1498 const Twine &NameStr,
1499 Instruction *InsertBefore = nullptr) {
1500 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1501 InsertBefore);
1504 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1505 BasicBlock *InsertAtEnd) {
1506 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1507 InsertAtEnd);
1510 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1511 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1512 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1513 InsertAtEnd);
1516 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1517 ArrayRef<OperandBundleDef> Bundles,
1518 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1519 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1520 NameStr, InsertAtEnd);
1523 // Deprecated [opaque pointer types]
1524 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1525 Instruction *InsertBefore = nullptr) {
1526 return Create(cast<FunctionType>(
1527 cast<PointerType>(Func->getType())->getElementType()),
1528 Func, NameStr, InsertBefore);
1531 // Deprecated [opaque pointer types]
1532 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1533 const Twine &NameStr,
1534 Instruction *InsertBefore = nullptr) {
1535 return Create(cast<FunctionType>(
1536 cast<PointerType>(Func->getType())->getElementType()),
1537 Func, Args, NameStr, InsertBefore);
1540 // Deprecated [opaque pointer types]
1541 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1542 ArrayRef<OperandBundleDef> Bundles = None,
1543 const Twine &NameStr = "",
1544 Instruction *InsertBefore = nullptr) {
1545 return Create(cast<FunctionType>(
1546 cast<PointerType>(Func->getType())->getElementType()),
1547 Func, Args, Bundles, NameStr, InsertBefore);
1550 // Deprecated [opaque pointer types]
1551 static CallInst *Create(Value *Func, const Twine &NameStr,
1552 BasicBlock *InsertAtEnd) {
1553 return Create(cast<FunctionType>(
1554 cast<PointerType>(Func->getType())->getElementType()),
1555 Func, NameStr, InsertAtEnd);
1558 // Deprecated [opaque pointer types]
1559 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1560 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1561 return Create(cast<FunctionType>(
1562 cast<PointerType>(Func->getType())->getElementType()),
1563 Func, Args, NameStr, InsertAtEnd);
1566 // Deprecated [opaque pointer types]
1567 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1568 ArrayRef<OperandBundleDef> Bundles,
1569 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1570 return Create(cast<FunctionType>(
1571 cast<PointerType>(Func->getType())->getElementType()),
1572 Func, Args, Bundles, NameStr, InsertAtEnd);
1575 /// Create a clone of \p CI with a different set of operand bundles and
1576 /// insert it before \p InsertPt.
1578 /// The returned call instruction is identical \p CI in every way except that
1579 /// the operand bundles for the new instruction are set to the operand bundles
1580 /// in \p Bundles.
1581 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1582 Instruction *InsertPt = nullptr);
1584 /// Generate the IR for a call to malloc:
1585 /// 1. Compute the malloc call's argument as the specified type's size,
1586 /// possibly multiplied by the array size if the array size is not
1587 /// constant 1.
1588 /// 2. Call malloc with that argument.
1589 /// 3. Bitcast the result of the malloc call to the specified type.
1590 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1591 Type *AllocTy, Value *AllocSize,
1592 Value *ArraySize = nullptr,
1593 Function *MallocF = nullptr,
1594 const Twine &Name = "");
1595 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1596 Type *AllocTy, Value *AllocSize,
1597 Value *ArraySize = nullptr,
1598 Function *MallocF = nullptr,
1599 const Twine &Name = "");
1600 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1601 Type *AllocTy, Value *AllocSize,
1602 Value *ArraySize = nullptr,
1603 ArrayRef<OperandBundleDef> Bundles = None,
1604 Function *MallocF = nullptr,
1605 const Twine &Name = "");
1606 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1607 Type *AllocTy, Value *AllocSize,
1608 Value *ArraySize = nullptr,
1609 ArrayRef<OperandBundleDef> Bundles = None,
1610 Function *MallocF = nullptr,
1611 const Twine &Name = "");
1612 /// Generate the IR for a call to the builtin free function.
1613 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1614 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1615 static Instruction *CreateFree(Value *Source,
1616 ArrayRef<OperandBundleDef> Bundles,
1617 Instruction *InsertBefore);
1618 static Instruction *CreateFree(Value *Source,
1619 ArrayRef<OperandBundleDef> Bundles,
1620 BasicBlock *InsertAtEnd);
1622 // Note that 'musttail' implies 'tail'.
1623 enum TailCallKind {
1624 TCK_None = 0,
1625 TCK_Tail = 1,
1626 TCK_MustTail = 2,
1627 TCK_NoTail = 3
1629 TailCallKind getTailCallKind() const {
1630 return TailCallKind(getSubclassDataFromInstruction() & 3);
1633 bool isTailCall() const {
1634 unsigned Kind = getSubclassDataFromInstruction() & 3;
1635 return Kind == TCK_Tail || Kind == TCK_MustTail;
1638 bool isMustTailCall() const {
1639 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1642 bool isNoTailCall() const {
1643 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1646 void setTailCall(bool isTC = true) {
1647 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1648 unsigned(isTC ? TCK_Tail : TCK_None));
1651 void setTailCallKind(TailCallKind TCK) {
1652 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1653 unsigned(TCK));
1656 /// Return true if the call can return twice
1657 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1658 void setCanReturnTwice() {
1659 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1662 // Methods for support type inquiry through isa, cast, and dyn_cast:
1663 static bool classof(const Instruction *I) {
1664 return I->getOpcode() == Instruction::Call;
1666 static bool classof(const Value *V) {
1667 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1670 /// Updates profile metadata by scaling it by \p S / \p T.
1671 void updateProfWeight(uint64_t S, uint64_t T);
1673 private:
1674 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1675 // method so that subclasses cannot accidentally use it.
1676 void setInstructionSubclassData(unsigned short D) {
1677 Instruction::setInstructionSubclassData(D);
1681 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1682 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1683 BasicBlock *InsertAtEnd)
1684 : CallBase(Ty->getReturnType(), Instruction::Call,
1685 OperandTraits<CallBase>::op_end(this) -
1686 (Args.size() + CountBundleInputs(Bundles) + 1),
1687 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1688 InsertAtEnd) {
1689 init(Ty, Func, Args, Bundles, NameStr);
1692 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1693 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1694 Instruction *InsertBefore)
1695 : CallBase(Ty->getReturnType(), Instruction::Call,
1696 OperandTraits<CallBase>::op_end(this) -
1697 (Args.size() + CountBundleInputs(Bundles) + 1),
1698 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1699 InsertBefore) {
1700 init(Ty, Func, Args, Bundles, NameStr);
1703 //===----------------------------------------------------------------------===//
1704 // SelectInst Class
1705 //===----------------------------------------------------------------------===//
1707 /// This class represents the LLVM 'select' instruction.
1709 class SelectInst : public Instruction {
1710 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1711 Instruction *InsertBefore)
1712 : Instruction(S1->getType(), Instruction::Select,
1713 &Op<0>(), 3, InsertBefore) {
1714 init(C, S1, S2);
1715 setName(NameStr);
1718 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1719 BasicBlock *InsertAtEnd)
1720 : Instruction(S1->getType(), Instruction::Select,
1721 &Op<0>(), 3, InsertAtEnd) {
1722 init(C, S1, S2);
1723 setName(NameStr);
1726 void init(Value *C, Value *S1, Value *S2) {
1727 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1728 Op<0>() = C;
1729 Op<1>() = S1;
1730 Op<2>() = S2;
1733 protected:
1734 // Note: Instruction needs to be a friend here to call cloneImpl.
1735 friend class Instruction;
1737 SelectInst *cloneImpl() const;
1739 public:
1740 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1741 const Twine &NameStr = "",
1742 Instruction *InsertBefore = nullptr,
1743 Instruction *MDFrom = nullptr) {
1744 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1745 if (MDFrom)
1746 Sel->copyMetadata(*MDFrom);
1747 return Sel;
1750 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1751 const Twine &NameStr,
1752 BasicBlock *InsertAtEnd) {
1753 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1756 const Value *getCondition() const { return Op<0>(); }
1757 const Value *getTrueValue() const { return Op<1>(); }
1758 const Value *getFalseValue() const { return Op<2>(); }
1759 Value *getCondition() { return Op<0>(); }
1760 Value *getTrueValue() { return Op<1>(); }
1761 Value *getFalseValue() { return Op<2>(); }
1763 void setCondition(Value *V) { Op<0>() = V; }
1764 void setTrueValue(Value *V) { Op<1>() = V; }
1765 void setFalseValue(Value *V) { Op<2>() = V; }
1767 /// Swap the true and false values of the select instruction.
1768 /// This doesn't swap prof metadata.
1769 void swapValues() { Op<1>().swap(Op<2>()); }
1771 /// Return a string if the specified operands are invalid
1772 /// for a select operation, otherwise return null.
1773 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1775 /// Transparently provide more efficient getOperand methods.
1776 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1778 OtherOps getOpcode() const {
1779 return static_cast<OtherOps>(Instruction::getOpcode());
1782 // Methods for support type inquiry through isa, cast, and dyn_cast:
1783 static bool classof(const Instruction *I) {
1784 return I->getOpcode() == Instruction::Select;
1786 static bool classof(const Value *V) {
1787 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1791 template <>
1792 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1795 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1797 //===----------------------------------------------------------------------===//
1798 // VAArgInst Class
1799 //===----------------------------------------------------------------------===//
1801 /// This class represents the va_arg llvm instruction, which returns
1802 /// an argument of the specified type given a va_list and increments that list
1804 class VAArgInst : public UnaryInstruction {
1805 protected:
1806 // Note: Instruction needs to be a friend here to call cloneImpl.
1807 friend class Instruction;
1809 VAArgInst *cloneImpl() const;
1811 public:
1812 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1813 Instruction *InsertBefore = nullptr)
1814 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1815 setName(NameStr);
1818 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1819 BasicBlock *InsertAtEnd)
1820 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1821 setName(NameStr);
1824 Value *getPointerOperand() { return getOperand(0); }
1825 const Value *getPointerOperand() const { return getOperand(0); }
1826 static unsigned getPointerOperandIndex() { return 0U; }
1828 // Methods for support type inquiry through isa, cast, and dyn_cast:
1829 static bool classof(const Instruction *I) {
1830 return I->getOpcode() == VAArg;
1832 static bool classof(const Value *V) {
1833 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1837 //===----------------------------------------------------------------------===//
1838 // ExtractElementInst Class
1839 //===----------------------------------------------------------------------===//
1841 /// This instruction extracts a single (scalar)
1842 /// element from a VectorType value
1844 class ExtractElementInst : public Instruction {
1845 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1846 Instruction *InsertBefore = nullptr);
1847 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1848 BasicBlock *InsertAtEnd);
1850 protected:
1851 // Note: Instruction needs to be a friend here to call cloneImpl.
1852 friend class Instruction;
1854 ExtractElementInst *cloneImpl() const;
1856 public:
1857 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1858 const Twine &NameStr = "",
1859 Instruction *InsertBefore = nullptr) {
1860 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1863 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1864 const Twine &NameStr,
1865 BasicBlock *InsertAtEnd) {
1866 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1869 /// Return true if an extractelement instruction can be
1870 /// formed with the specified operands.
1871 static bool isValidOperands(const Value *Vec, const Value *Idx);
1873 Value *getVectorOperand() { return Op<0>(); }
1874 Value *getIndexOperand() { return Op<1>(); }
1875 const Value *getVectorOperand() const { return Op<0>(); }
1876 const Value *getIndexOperand() const { return Op<1>(); }
1878 VectorType *getVectorOperandType() const {
1879 return cast<VectorType>(getVectorOperand()->getType());
1882 /// Transparently provide more efficient getOperand methods.
1883 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1885 // Methods for support type inquiry through isa, cast, and dyn_cast:
1886 static bool classof(const Instruction *I) {
1887 return I->getOpcode() == Instruction::ExtractElement;
1889 static bool classof(const Value *V) {
1890 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1894 template <>
1895 struct OperandTraits<ExtractElementInst> :
1896 public FixedNumOperandTraits<ExtractElementInst, 2> {
1899 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1901 //===----------------------------------------------------------------------===//
1902 // InsertElementInst Class
1903 //===----------------------------------------------------------------------===//
1905 /// This instruction inserts a single (scalar)
1906 /// element into a VectorType value
1908 class InsertElementInst : public Instruction {
1909 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1910 const Twine &NameStr = "",
1911 Instruction *InsertBefore = nullptr);
1912 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1913 BasicBlock *InsertAtEnd);
1915 protected:
1916 // Note: Instruction needs to be a friend here to call cloneImpl.
1917 friend class Instruction;
1919 InsertElementInst *cloneImpl() const;
1921 public:
1922 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1923 const Twine &NameStr = "",
1924 Instruction *InsertBefore = nullptr) {
1925 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1928 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1929 const Twine &NameStr,
1930 BasicBlock *InsertAtEnd) {
1931 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1934 /// Return true if an insertelement instruction can be
1935 /// formed with the specified operands.
1936 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1937 const Value *Idx);
1939 /// Overload to return most specific vector type.
1941 VectorType *getType() const {
1942 return cast<VectorType>(Instruction::getType());
1945 /// Transparently provide more efficient getOperand methods.
1946 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1948 // Methods for support type inquiry through isa, cast, and dyn_cast:
1949 static bool classof(const Instruction *I) {
1950 return I->getOpcode() == Instruction::InsertElement;
1952 static bool classof(const Value *V) {
1953 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1957 template <>
1958 struct OperandTraits<InsertElementInst> :
1959 public FixedNumOperandTraits<InsertElementInst, 3> {
1962 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
1964 //===----------------------------------------------------------------------===//
1965 // ShuffleVectorInst Class
1966 //===----------------------------------------------------------------------===//
1968 /// This instruction constructs a fixed permutation of two
1969 /// input vectors.
1971 class ShuffleVectorInst : public Instruction {
1972 protected:
1973 // Note: Instruction needs to be a friend here to call cloneImpl.
1974 friend class Instruction;
1976 ShuffleVectorInst *cloneImpl() const;
1978 public:
1979 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1980 const Twine &NameStr = "",
1981 Instruction *InsertBefor = nullptr);
1982 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1983 const Twine &NameStr, BasicBlock *InsertAtEnd);
1985 // allocate space for exactly three operands
1986 void *operator new(size_t s) {
1987 return User::operator new(s, 3);
1990 /// Swap the first 2 operands and adjust the mask to preserve the semantics
1991 /// of the instruction.
1992 void commute();
1994 /// Return true if a shufflevector instruction can be
1995 /// formed with the specified operands.
1996 static bool isValidOperands(const Value *V1, const Value *V2,
1997 const Value *Mask);
1999 /// Overload to return most specific vector type.
2001 VectorType *getType() const {
2002 return cast<VectorType>(Instruction::getType());
2005 /// Transparently provide more efficient getOperand methods.
2006 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2008 Constant *getMask() const {
2009 return cast<Constant>(getOperand(2));
2012 /// Return the shuffle mask value for the specified element of the mask.
2013 /// Return -1 if the element is undef.
2014 static int getMaskValue(const Constant *Mask, unsigned Elt);
2016 /// Return the shuffle mask value of this instruction for the given element
2017 /// index. Return -1 if the element is undef.
2018 int getMaskValue(unsigned Elt) const {
2019 return getMaskValue(getMask(), Elt);
2022 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2023 /// elements of the mask are returned as -1.
2024 static void getShuffleMask(const Constant *Mask,
2025 SmallVectorImpl<int> &Result);
2027 /// Return the mask for this instruction as a vector of integers. Undefined
2028 /// elements of the mask are returned as -1.
2029 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2030 return getShuffleMask(getMask(), Result);
2033 SmallVector<int, 16> getShuffleMask() const {
2034 SmallVector<int, 16> Mask;
2035 getShuffleMask(Mask);
2036 return Mask;
2039 /// Return true if this shuffle returns a vector with a different number of
2040 /// elements than its source vectors.
2041 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2042 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2043 bool changesLength() const {
2044 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2045 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2046 return NumSourceElts != NumMaskElts;
2049 /// Return true if this shuffle returns a vector with a greater number of
2050 /// elements than its source vectors.
2051 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2052 bool increasesLength() const {
2053 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2054 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2055 return NumSourceElts < NumMaskElts;
2058 /// Return true if this shuffle mask chooses elements from exactly one source
2059 /// vector.
2060 /// Example: <7,5,undef,7>
2061 /// This assumes that vector operands are the same length as the mask.
2062 static bool isSingleSourceMask(ArrayRef<int> Mask);
2063 static bool isSingleSourceMask(const Constant *Mask) {
2064 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2065 SmallVector<int, 16> MaskAsInts;
2066 getShuffleMask(Mask, MaskAsInts);
2067 return isSingleSourceMask(MaskAsInts);
2070 /// Return true if this shuffle chooses elements from exactly one source
2071 /// vector without changing the length of that vector.
2072 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2073 /// TODO: Optionally allow length-changing shuffles.
2074 bool isSingleSource() const {
2075 return !changesLength() && isSingleSourceMask(getMask());
2078 /// Return true if this shuffle mask chooses elements from exactly one source
2079 /// vector without lane crossings. A shuffle using this mask is not
2080 /// necessarily a no-op because it may change the number of elements from its
2081 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2082 /// Example: <undef,undef,2,3>
2083 static bool isIdentityMask(ArrayRef<int> Mask);
2084 static bool isIdentityMask(const Constant *Mask) {
2085 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2086 SmallVector<int, 16> MaskAsInts;
2087 getShuffleMask(Mask, MaskAsInts);
2088 return isIdentityMask(MaskAsInts);
2091 /// Return true if this shuffle chooses elements from exactly one source
2092 /// vector without lane crossings and does not change the number of elements
2093 /// from its input vectors.
2094 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2095 bool isIdentity() const {
2096 return !changesLength() && isIdentityMask(getShuffleMask());
2099 /// Return true if this shuffle lengthens exactly one source vector with
2100 /// undefs in the high elements.
2101 bool isIdentityWithPadding() const;
2103 /// Return true if this shuffle extracts the first N elements of exactly one
2104 /// source vector.
2105 bool isIdentityWithExtract() const;
2107 /// Return true if this shuffle concatenates its 2 source vectors. This
2108 /// returns false if either input is undefined. In that case, the shuffle is
2109 /// is better classified as an identity with padding operation.
2110 bool isConcat() const;
2112 /// Return true if this shuffle mask chooses elements from its source vectors
2113 /// without lane crossings. A shuffle using this mask would be
2114 /// equivalent to a vector select with a constant condition operand.
2115 /// Example: <4,1,6,undef>
2116 /// This returns false if the mask does not choose from both input vectors.
2117 /// In that case, the shuffle is better classified as an identity shuffle.
2118 /// This assumes that vector operands are the same length as the mask
2119 /// (a length-changing shuffle can never be equivalent to a vector select).
2120 static bool isSelectMask(ArrayRef<int> Mask);
2121 static bool isSelectMask(const Constant *Mask) {
2122 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2123 SmallVector<int, 16> MaskAsInts;
2124 getShuffleMask(Mask, MaskAsInts);
2125 return isSelectMask(MaskAsInts);
2128 /// Return true if this shuffle chooses elements from its source vectors
2129 /// without lane crossings and all operands have the same number of elements.
2130 /// In other words, this shuffle is equivalent to a vector select with a
2131 /// constant condition operand.
2132 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2133 /// This returns false if the mask does not choose from both input vectors.
2134 /// In that case, the shuffle is better classified as an identity shuffle.
2135 /// TODO: Optionally allow length-changing shuffles.
2136 bool isSelect() const {
2137 return !changesLength() && isSelectMask(getMask());
2140 /// Return true if this shuffle mask swaps the order of elements from exactly
2141 /// one source vector.
2142 /// Example: <7,6,undef,4>
2143 /// This assumes that vector operands are the same length as the mask.
2144 static bool isReverseMask(ArrayRef<int> Mask);
2145 static bool isReverseMask(const Constant *Mask) {
2146 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2147 SmallVector<int, 16> MaskAsInts;
2148 getShuffleMask(Mask, MaskAsInts);
2149 return isReverseMask(MaskAsInts);
2152 /// Return true if this shuffle swaps the order of elements from exactly
2153 /// one source vector.
2154 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2155 /// TODO: Optionally allow length-changing shuffles.
2156 bool isReverse() const {
2157 return !changesLength() && isReverseMask(getMask());
2160 /// Return true if this shuffle mask chooses all elements with the same value
2161 /// as the first element of exactly one source vector.
2162 /// Example: <4,undef,undef,4>
2163 /// This assumes that vector operands are the same length as the mask.
2164 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2165 static bool isZeroEltSplatMask(const Constant *Mask) {
2166 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2167 SmallVector<int, 16> MaskAsInts;
2168 getShuffleMask(Mask, MaskAsInts);
2169 return isZeroEltSplatMask(MaskAsInts);
2172 /// Return true if all elements of this shuffle are the same value as the
2173 /// first element of exactly one source vector without changing the length
2174 /// of that vector.
2175 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2176 /// TODO: Optionally allow length-changing shuffles.
2177 /// TODO: Optionally allow splats from other elements.
2178 bool isZeroEltSplat() const {
2179 return !changesLength() && isZeroEltSplatMask(getMask());
2182 /// Return true if this shuffle mask is a transpose mask.
2183 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2184 /// even- or odd-numbered vector elements from two n-dimensional source
2185 /// vectors and write each result into consecutive elements of an
2186 /// n-dimensional destination vector. Two shuffles are necessary to complete
2187 /// the transpose, one for the even elements and another for the odd elements.
2188 /// This description closely follows how the TRN1 and TRN2 AArch64
2189 /// instructions operate.
2191 /// For example, a simple 2x2 matrix can be transposed with:
2193 /// ; Original matrix
2194 /// m0 = < a, b >
2195 /// m1 = < c, d >
2197 /// ; Transposed matrix
2198 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2199 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2201 /// For matrices having greater than n columns, the resulting nx2 transposed
2202 /// matrix is stored in two result vectors such that one vector contains
2203 /// interleaved elements from all the even-numbered rows and the other vector
2204 /// contains interleaved elements from all the odd-numbered rows. For example,
2205 /// a 2x4 matrix can be transposed with:
2207 /// ; Original matrix
2208 /// m0 = < a, b, c, d >
2209 /// m1 = < e, f, g, h >
2211 /// ; Transposed matrix
2212 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2213 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2214 static bool isTransposeMask(ArrayRef<int> Mask);
2215 static bool isTransposeMask(const Constant *Mask) {
2216 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2217 SmallVector<int, 16> MaskAsInts;
2218 getShuffleMask(Mask, MaskAsInts);
2219 return isTransposeMask(MaskAsInts);
2222 /// Return true if this shuffle transposes the elements of its inputs without
2223 /// changing the length of the vectors. This operation may also be known as a
2224 /// merge or interleave. See the description for isTransposeMask() for the
2225 /// exact specification.
2226 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2227 bool isTranspose() const {
2228 return !changesLength() && isTransposeMask(getMask());
2231 /// Return true if this shuffle mask is an extract subvector mask.
2232 /// A valid extract subvector mask returns a smaller vector from a single
2233 /// source operand. The base extraction index is returned as well.
2234 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2235 int &Index);
2236 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2237 int &Index) {
2238 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2239 SmallVector<int, 16> MaskAsInts;
2240 getShuffleMask(Mask, MaskAsInts);
2241 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2244 /// Return true if this shuffle mask is an extract subvector mask.
2245 bool isExtractSubvectorMask(int &Index) const {
2246 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2247 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2250 /// Change values in a shuffle permute mask assuming the two vector operands
2251 /// of length InVecNumElts have swapped position.
2252 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2253 unsigned InVecNumElts) {
2254 for (int &Idx : Mask) {
2255 if (Idx == -1)
2256 continue;
2257 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2258 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2259 "shufflevector mask index out of range");
2263 // Methods for support type inquiry through isa, cast, and dyn_cast:
2264 static bool classof(const Instruction *I) {
2265 return I->getOpcode() == Instruction::ShuffleVector;
2267 static bool classof(const Value *V) {
2268 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2272 template <>
2273 struct OperandTraits<ShuffleVectorInst> :
2274 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2277 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2279 //===----------------------------------------------------------------------===//
2280 // ExtractValueInst Class
2281 //===----------------------------------------------------------------------===//
2283 /// This instruction extracts a struct member or array
2284 /// element value from an aggregate value.
2286 class ExtractValueInst : public UnaryInstruction {
2287 SmallVector<unsigned, 4> Indices;
2289 ExtractValueInst(const ExtractValueInst &EVI);
2291 /// Constructors - Create a extractvalue instruction with a base aggregate
2292 /// value and a list of indices. The first ctor can optionally insert before
2293 /// an existing instruction, the second appends the new instruction to the
2294 /// specified BasicBlock.
2295 inline ExtractValueInst(Value *Agg,
2296 ArrayRef<unsigned> Idxs,
2297 const Twine &NameStr,
2298 Instruction *InsertBefore);
2299 inline ExtractValueInst(Value *Agg,
2300 ArrayRef<unsigned> Idxs,
2301 const Twine &NameStr, BasicBlock *InsertAtEnd);
2303 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2305 protected:
2306 // Note: Instruction needs to be a friend here to call cloneImpl.
2307 friend class Instruction;
2309 ExtractValueInst *cloneImpl() const;
2311 public:
2312 static ExtractValueInst *Create(Value *Agg,
2313 ArrayRef<unsigned> Idxs,
2314 const Twine &NameStr = "",
2315 Instruction *InsertBefore = nullptr) {
2316 return new
2317 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2320 static ExtractValueInst *Create(Value *Agg,
2321 ArrayRef<unsigned> Idxs,
2322 const Twine &NameStr,
2323 BasicBlock *InsertAtEnd) {
2324 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2327 /// Returns the type of the element that would be extracted
2328 /// with an extractvalue instruction with the specified parameters.
2330 /// Null is returned if the indices are invalid for the specified type.
2331 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2333 using idx_iterator = const unsigned*;
2335 inline idx_iterator idx_begin() const { return Indices.begin(); }
2336 inline idx_iterator idx_end() const { return Indices.end(); }
2337 inline iterator_range<idx_iterator> indices() const {
2338 return make_range(idx_begin(), idx_end());
2341 Value *getAggregateOperand() {
2342 return getOperand(0);
2344 const Value *getAggregateOperand() const {
2345 return getOperand(0);
2347 static unsigned getAggregateOperandIndex() {
2348 return 0U; // get index for modifying correct operand
2351 ArrayRef<unsigned> getIndices() const {
2352 return Indices;
2355 unsigned getNumIndices() const {
2356 return (unsigned)Indices.size();
2359 bool hasIndices() const {
2360 return true;
2363 // Methods for support type inquiry through isa, cast, and dyn_cast:
2364 static bool classof(const Instruction *I) {
2365 return I->getOpcode() == Instruction::ExtractValue;
2367 static bool classof(const Value *V) {
2368 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2372 ExtractValueInst::ExtractValueInst(Value *Agg,
2373 ArrayRef<unsigned> Idxs,
2374 const Twine &NameStr,
2375 Instruction *InsertBefore)
2376 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2377 ExtractValue, Agg, InsertBefore) {
2378 init(Idxs, NameStr);
2381 ExtractValueInst::ExtractValueInst(Value *Agg,
2382 ArrayRef<unsigned> Idxs,
2383 const Twine &NameStr,
2384 BasicBlock *InsertAtEnd)
2385 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2386 ExtractValue, Agg, InsertAtEnd) {
2387 init(Idxs, NameStr);
2390 //===----------------------------------------------------------------------===//
2391 // InsertValueInst Class
2392 //===----------------------------------------------------------------------===//
2394 /// This instruction inserts a struct field of array element
2395 /// value into an aggregate value.
2397 class InsertValueInst : public Instruction {
2398 SmallVector<unsigned, 4> Indices;
2400 InsertValueInst(const InsertValueInst &IVI);
2402 /// Constructors - Create a insertvalue instruction with a base aggregate
2403 /// value, a value to insert, and a list of indices. The first ctor can
2404 /// optionally insert before an existing instruction, the second appends
2405 /// the new instruction to the specified BasicBlock.
2406 inline InsertValueInst(Value *Agg, Value *Val,
2407 ArrayRef<unsigned> Idxs,
2408 const Twine &NameStr,
2409 Instruction *InsertBefore);
2410 inline InsertValueInst(Value *Agg, Value *Val,
2411 ArrayRef<unsigned> Idxs,
2412 const Twine &NameStr, BasicBlock *InsertAtEnd);
2414 /// Constructors - These two constructors are convenience methods because one
2415 /// and two index insertvalue instructions are so common.
2416 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2417 const Twine &NameStr = "",
2418 Instruction *InsertBefore = nullptr);
2419 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2420 BasicBlock *InsertAtEnd);
2422 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2423 const Twine &NameStr);
2425 protected:
2426 // Note: Instruction needs to be a friend here to call cloneImpl.
2427 friend class Instruction;
2429 InsertValueInst *cloneImpl() const;
2431 public:
2432 // allocate space for exactly two operands
2433 void *operator new(size_t s) {
2434 return User::operator new(s, 2);
2437 static InsertValueInst *Create(Value *Agg, Value *Val,
2438 ArrayRef<unsigned> Idxs,
2439 const Twine &NameStr = "",
2440 Instruction *InsertBefore = nullptr) {
2441 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2444 static InsertValueInst *Create(Value *Agg, Value *Val,
2445 ArrayRef<unsigned> Idxs,
2446 const Twine &NameStr,
2447 BasicBlock *InsertAtEnd) {
2448 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2451 /// Transparently provide more efficient getOperand methods.
2452 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2454 using idx_iterator = const unsigned*;
2456 inline idx_iterator idx_begin() const { return Indices.begin(); }
2457 inline idx_iterator idx_end() const { return Indices.end(); }
2458 inline iterator_range<idx_iterator> indices() const {
2459 return make_range(idx_begin(), idx_end());
2462 Value *getAggregateOperand() {
2463 return getOperand(0);
2465 const Value *getAggregateOperand() const {
2466 return getOperand(0);
2468 static unsigned getAggregateOperandIndex() {
2469 return 0U; // get index for modifying correct operand
2472 Value *getInsertedValueOperand() {
2473 return getOperand(1);
2475 const Value *getInsertedValueOperand() const {
2476 return getOperand(1);
2478 static unsigned getInsertedValueOperandIndex() {
2479 return 1U; // get index for modifying correct operand
2482 ArrayRef<unsigned> getIndices() const {
2483 return Indices;
2486 unsigned getNumIndices() const {
2487 return (unsigned)Indices.size();
2490 bool hasIndices() const {
2491 return true;
2494 // Methods for support type inquiry through isa, cast, and dyn_cast:
2495 static bool classof(const Instruction *I) {
2496 return I->getOpcode() == Instruction::InsertValue;
2498 static bool classof(const Value *V) {
2499 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2503 template <>
2504 struct OperandTraits<InsertValueInst> :
2505 public FixedNumOperandTraits<InsertValueInst, 2> {
2508 InsertValueInst::InsertValueInst(Value *Agg,
2509 Value *Val,
2510 ArrayRef<unsigned> Idxs,
2511 const Twine &NameStr,
2512 Instruction *InsertBefore)
2513 : Instruction(Agg->getType(), InsertValue,
2514 OperandTraits<InsertValueInst>::op_begin(this),
2515 2, InsertBefore) {
2516 init(Agg, Val, Idxs, NameStr);
2519 InsertValueInst::InsertValueInst(Value *Agg,
2520 Value *Val,
2521 ArrayRef<unsigned> Idxs,
2522 const Twine &NameStr,
2523 BasicBlock *InsertAtEnd)
2524 : Instruction(Agg->getType(), InsertValue,
2525 OperandTraits<InsertValueInst>::op_begin(this),
2526 2, InsertAtEnd) {
2527 init(Agg, Val, Idxs, NameStr);
2530 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2532 //===----------------------------------------------------------------------===//
2533 // PHINode Class
2534 //===----------------------------------------------------------------------===//
2536 // PHINode - The PHINode class is used to represent the magical mystical PHI
2537 // node, that can not exist in nature, but can be synthesized in a computer
2538 // scientist's overactive imagination.
2540 class PHINode : public Instruction {
2541 /// The number of operands actually allocated. NumOperands is
2542 /// the number actually in use.
2543 unsigned ReservedSpace;
2545 PHINode(const PHINode &PN);
2547 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2548 const Twine &NameStr = "",
2549 Instruction *InsertBefore = nullptr)
2550 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2551 ReservedSpace(NumReservedValues) {
2552 setName(NameStr);
2553 allocHungoffUses(ReservedSpace);
2556 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2557 BasicBlock *InsertAtEnd)
2558 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2559 ReservedSpace(NumReservedValues) {
2560 setName(NameStr);
2561 allocHungoffUses(ReservedSpace);
2564 protected:
2565 // Note: Instruction needs to be a friend here to call cloneImpl.
2566 friend class Instruction;
2568 PHINode *cloneImpl() const;
2570 // allocHungoffUses - this is more complicated than the generic
2571 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2572 // values and pointers to the incoming blocks, all in one allocation.
2573 void allocHungoffUses(unsigned N) {
2574 User::allocHungoffUses(N, /* IsPhi */ true);
2577 public:
2578 /// Constructors - NumReservedValues is a hint for the number of incoming
2579 /// edges that this phi node will have (use 0 if you really have no idea).
2580 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2581 const Twine &NameStr = "",
2582 Instruction *InsertBefore = nullptr) {
2583 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2586 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2587 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2588 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2591 /// Provide fast operand accessors
2592 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2594 // Block iterator interface. This provides access to the list of incoming
2595 // basic blocks, which parallels the list of incoming values.
2597 using block_iterator = BasicBlock **;
2598 using const_block_iterator = BasicBlock * const *;
2600 block_iterator block_begin() {
2601 Use::UserRef *ref =
2602 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2603 return reinterpret_cast<block_iterator>(ref + 1);
2606 const_block_iterator block_begin() const {
2607 const Use::UserRef *ref =
2608 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2609 return reinterpret_cast<const_block_iterator>(ref + 1);
2612 block_iterator block_end() {
2613 return block_begin() + getNumOperands();
2616 const_block_iterator block_end() const {
2617 return block_begin() + getNumOperands();
2620 iterator_range<block_iterator> blocks() {
2621 return make_range(block_begin(), block_end());
2624 iterator_range<const_block_iterator> blocks() const {
2625 return make_range(block_begin(), block_end());
2628 op_range incoming_values() { return operands(); }
2630 const_op_range incoming_values() const { return operands(); }
2632 /// Return the number of incoming edges
2634 unsigned getNumIncomingValues() const { return getNumOperands(); }
2636 /// Return incoming value number x
2638 Value *getIncomingValue(unsigned i) const {
2639 return getOperand(i);
2641 void setIncomingValue(unsigned i, Value *V) {
2642 assert(V && "PHI node got a null value!");
2643 assert(getType() == V->getType() &&
2644 "All operands to PHI node must be the same type as the PHI node!");
2645 setOperand(i, V);
2648 static unsigned getOperandNumForIncomingValue(unsigned i) {
2649 return i;
2652 static unsigned getIncomingValueNumForOperand(unsigned i) {
2653 return i;
2656 /// Return incoming basic block number @p i.
2658 BasicBlock *getIncomingBlock(unsigned i) const {
2659 return block_begin()[i];
2662 /// Return incoming basic block corresponding
2663 /// to an operand of the PHI.
2665 BasicBlock *getIncomingBlock(const Use &U) const {
2666 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2667 return getIncomingBlock(unsigned(&U - op_begin()));
2670 /// Return incoming basic block corresponding
2671 /// to value use iterator.
2673 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2674 return getIncomingBlock(I.getUse());
2677 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2678 assert(BB && "PHI node got a null basic block!");
2679 block_begin()[i] = BB;
2682 /// Replace every incoming basic block \p Old to basic block \p New.
2683 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
2684 assert(New && Old && "PHI node got a null basic block!");
2685 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2686 if (getIncomingBlock(Op) == Old)
2687 setIncomingBlock(Op, New);
2690 /// Add an incoming value to the end of the PHI list
2692 void addIncoming(Value *V, BasicBlock *BB) {
2693 if (getNumOperands() == ReservedSpace)
2694 growOperands(); // Get more space!
2695 // Initialize some new operands.
2696 setNumHungOffUseOperands(getNumOperands() + 1);
2697 setIncomingValue(getNumOperands() - 1, V);
2698 setIncomingBlock(getNumOperands() - 1, BB);
2701 /// Remove an incoming value. This is useful if a
2702 /// predecessor basic block is deleted. The value removed is returned.
2704 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2705 /// is true), the PHI node is destroyed and any uses of it are replaced with
2706 /// dummy values. The only time there should be zero incoming values to a PHI
2707 /// node is when the block is dead, so this strategy is sound.
2709 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2711 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2712 int Idx = getBasicBlockIndex(BB);
2713 assert(Idx >= 0 && "Invalid basic block argument to remove!");
2714 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2717 /// Return the first index of the specified basic
2718 /// block in the value list for this PHI. Returns -1 if no instance.
2720 int getBasicBlockIndex(const BasicBlock *BB) const {
2721 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2722 if (block_begin()[i] == BB)
2723 return i;
2724 return -1;
2727 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2728 int Idx = getBasicBlockIndex(BB);
2729 assert(Idx >= 0 && "Invalid basic block argument!");
2730 return getIncomingValue(Idx);
2733 /// Set every incoming value(s) for block \p BB to \p V.
2734 void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
2735 assert(BB && "PHI node got a null basic block!");
2736 bool Found = false;
2737 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2738 if (getIncomingBlock(Op) == BB) {
2739 Found = true;
2740 setIncomingValue(Op, V);
2742 (void)Found;
2743 assert(Found && "Invalid basic block argument to set!");
2746 /// If the specified PHI node always merges together the
2747 /// same value, return the value, otherwise return null.
2748 Value *hasConstantValue() const;
2750 /// Whether the specified PHI node always merges
2751 /// together the same value, assuming undefs are equal to a unique
2752 /// non-undef value.
2753 bool hasConstantOrUndefValue() const;
2755 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2756 static bool classof(const Instruction *I) {
2757 return I->getOpcode() == Instruction::PHI;
2759 static bool classof(const Value *V) {
2760 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2763 private:
2764 void growOperands();
2767 template <>
2768 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2771 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2773 //===----------------------------------------------------------------------===//
2774 // LandingPadInst Class
2775 //===----------------------------------------------------------------------===//
2777 //===---------------------------------------------------------------------------
2778 /// The landingpad instruction holds all of the information
2779 /// necessary to generate correct exception handling. The landingpad instruction
2780 /// cannot be moved from the top of a landing pad block, which itself is
2781 /// accessible only from the 'unwind' edge of an invoke. This uses the
2782 /// SubclassData field in Value to store whether or not the landingpad is a
2783 /// cleanup.
2785 class LandingPadInst : public Instruction {
2786 /// The number of operands actually allocated. NumOperands is
2787 /// the number actually in use.
2788 unsigned ReservedSpace;
2790 LandingPadInst(const LandingPadInst &LP);
2792 public:
2793 enum ClauseType { Catch, Filter };
2795 private:
2796 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2797 const Twine &NameStr, Instruction *InsertBefore);
2798 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2799 const Twine &NameStr, BasicBlock *InsertAtEnd);
2801 // Allocate space for exactly zero operands.
2802 void *operator new(size_t s) {
2803 return User::operator new(s);
2806 void growOperands(unsigned Size);
2807 void init(unsigned NumReservedValues, const Twine &NameStr);
2809 protected:
2810 // Note: Instruction needs to be a friend here to call cloneImpl.
2811 friend class Instruction;
2813 LandingPadInst *cloneImpl() const;
2815 public:
2816 /// Constructors - NumReservedClauses is a hint for the number of incoming
2817 /// clauses that this landingpad will have (use 0 if you really have no idea).
2818 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2819 const Twine &NameStr = "",
2820 Instruction *InsertBefore = nullptr);
2821 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2822 const Twine &NameStr, BasicBlock *InsertAtEnd);
2824 /// Provide fast operand accessors
2825 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2827 /// Return 'true' if this landingpad instruction is a
2828 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2829 /// doesn't catch the exception.
2830 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2832 /// Indicate that this landingpad instruction is a cleanup.
2833 void setCleanup(bool V) {
2834 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2835 (V ? 1 : 0));
2838 /// Add a catch or filter clause to the landing pad.
2839 void addClause(Constant *ClauseVal);
2841 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2842 /// determine what type of clause this is.
2843 Constant *getClause(unsigned Idx) const {
2844 return cast<Constant>(getOperandList()[Idx]);
2847 /// Return 'true' if the clause and index Idx is a catch clause.
2848 bool isCatch(unsigned Idx) const {
2849 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2852 /// Return 'true' if the clause and index Idx is a filter clause.
2853 bool isFilter(unsigned Idx) const {
2854 return isa<ArrayType>(getOperandList()[Idx]->getType());
2857 /// Get the number of clauses for this landing pad.
2858 unsigned getNumClauses() const { return getNumOperands(); }
2860 /// Grow the size of the operand list to accommodate the new
2861 /// number of clauses.
2862 void reserveClauses(unsigned Size) { growOperands(Size); }
2864 // Methods for support type inquiry through isa, cast, and dyn_cast:
2865 static bool classof(const Instruction *I) {
2866 return I->getOpcode() == Instruction::LandingPad;
2868 static bool classof(const Value *V) {
2869 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2873 template <>
2874 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2877 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2879 //===----------------------------------------------------------------------===//
2880 // ReturnInst Class
2881 //===----------------------------------------------------------------------===//
2883 //===---------------------------------------------------------------------------
2884 /// Return a value (possibly void), from a function. Execution
2885 /// does not continue in this function any longer.
2887 class ReturnInst : public Instruction {
2888 ReturnInst(const ReturnInst &RI);
2890 private:
2891 // ReturnInst constructors:
2892 // ReturnInst() - 'ret void' instruction
2893 // ReturnInst( null) - 'ret void' instruction
2894 // ReturnInst(Value* X) - 'ret X' instruction
2895 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2896 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2897 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2898 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2900 // NOTE: If the Value* passed is of type void then the constructor behaves as
2901 // if it was passed NULL.
2902 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2903 Instruction *InsertBefore = nullptr);
2904 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2905 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2907 protected:
2908 // Note: Instruction needs to be a friend here to call cloneImpl.
2909 friend class Instruction;
2911 ReturnInst *cloneImpl() const;
2913 public:
2914 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2915 Instruction *InsertBefore = nullptr) {
2916 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2919 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2920 BasicBlock *InsertAtEnd) {
2921 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2924 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2925 return new(0) ReturnInst(C, InsertAtEnd);
2928 /// Provide fast operand accessors
2929 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2931 /// Convenience accessor. Returns null if there is no return value.
2932 Value *getReturnValue() const {
2933 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2936 unsigned getNumSuccessors() const { return 0; }
2938 // Methods for support type inquiry through isa, cast, and dyn_cast:
2939 static bool classof(const Instruction *I) {
2940 return (I->getOpcode() == Instruction::Ret);
2942 static bool classof(const Value *V) {
2943 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2946 private:
2947 BasicBlock *getSuccessor(unsigned idx) const {
2948 llvm_unreachable("ReturnInst has no successors!");
2951 void setSuccessor(unsigned idx, BasicBlock *B) {
2952 llvm_unreachable("ReturnInst has no successors!");
2956 template <>
2957 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2960 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2962 //===----------------------------------------------------------------------===//
2963 // BranchInst Class
2964 //===----------------------------------------------------------------------===//
2966 //===---------------------------------------------------------------------------
2967 /// Conditional or Unconditional Branch instruction.
2969 class BranchInst : public Instruction {
2970 /// Ops list - Branches are strange. The operands are ordered:
2971 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2972 /// they don't have to check for cond/uncond branchness. These are mostly
2973 /// accessed relative from op_end().
2974 BranchInst(const BranchInst &BI);
2975 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2976 // BranchInst(BB *B) - 'br B'
2977 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2978 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2979 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2980 // BranchInst(BB* B, BB *I) - 'br B' insert at end
2981 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2982 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2983 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2984 Instruction *InsertBefore = nullptr);
2985 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2986 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2987 BasicBlock *InsertAtEnd);
2989 void AssertOK();
2991 protected:
2992 // Note: Instruction needs to be a friend here to call cloneImpl.
2993 friend class Instruction;
2995 BranchInst *cloneImpl() const;
2997 public:
2998 /// Iterator type that casts an operand to a basic block.
3000 /// This only makes sense because the successors are stored as adjacent
3001 /// operands for branch instructions.
3002 struct succ_op_iterator
3003 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3004 std::random_access_iterator_tag, BasicBlock *,
3005 ptrdiff_t, BasicBlock *, BasicBlock *> {
3006 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3008 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3009 BasicBlock *operator->() const { return operator*(); }
3012 /// The const version of `succ_op_iterator`.
3013 struct const_succ_op_iterator
3014 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3015 std::random_access_iterator_tag,
3016 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3017 const BasicBlock *> {
3018 explicit const_succ_op_iterator(const_value_op_iterator I)
3019 : iterator_adaptor_base(I) {}
3021 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3022 const BasicBlock *operator->() const { return operator*(); }
3025 static BranchInst *Create(BasicBlock *IfTrue,
3026 Instruction *InsertBefore = nullptr) {
3027 return new(1) BranchInst(IfTrue, InsertBefore);
3030 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3031 Value *Cond, Instruction *InsertBefore = nullptr) {
3032 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3035 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3036 return new(1) BranchInst(IfTrue, InsertAtEnd);
3039 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3040 Value *Cond, BasicBlock *InsertAtEnd) {
3041 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3044 /// Transparently provide more efficient getOperand methods.
3045 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3047 bool isUnconditional() const { return getNumOperands() == 1; }
3048 bool isConditional() const { return getNumOperands() == 3; }
3050 Value *getCondition() const {
3051 assert(isConditional() && "Cannot get condition of an uncond branch!");
3052 return Op<-3>();
3055 void setCondition(Value *V) {
3056 assert(isConditional() && "Cannot set condition of unconditional branch!");
3057 Op<-3>() = V;
3060 unsigned getNumSuccessors() const { return 1+isConditional(); }
3062 BasicBlock *getSuccessor(unsigned i) const {
3063 assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3064 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3067 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3068 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3069 *(&Op<-1>() - idx) = NewSucc;
3072 /// Swap the successors of this branch instruction.
3074 /// Swaps the successors of the branch instruction. This also swaps any
3075 /// branch weight metadata associated with the instruction so that it
3076 /// continues to map correctly to each operand.
3077 void swapSuccessors();
3079 iterator_range<succ_op_iterator> successors() {
3080 return make_range(
3081 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3082 succ_op_iterator(value_op_end()));
3085 iterator_range<const_succ_op_iterator> successors() const {
3086 return make_range(const_succ_op_iterator(
3087 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3088 const_succ_op_iterator(value_op_end()));
3091 // Methods for support type inquiry through isa, cast, and dyn_cast:
3092 static bool classof(const Instruction *I) {
3093 return (I->getOpcode() == Instruction::Br);
3095 static bool classof(const Value *V) {
3096 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3100 template <>
3101 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3104 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
3106 //===----------------------------------------------------------------------===//
3107 // SwitchInst Class
3108 //===----------------------------------------------------------------------===//
3110 //===---------------------------------------------------------------------------
3111 /// Multiway switch
3113 class SwitchInst : public Instruction {
3114 unsigned ReservedSpace;
3116 // Operand[0] = Value to switch on
3117 // Operand[1] = Default basic block destination
3118 // Operand[2n ] = Value to match
3119 // Operand[2n+1] = BasicBlock to go to on match
3120 SwitchInst(const SwitchInst &SI);
3122 /// Create a new switch instruction, specifying a value to switch on and a
3123 /// default destination. The number of additional cases can be specified here
3124 /// to make memory allocation more efficient. This constructor can also
3125 /// auto-insert before another instruction.
3126 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3127 Instruction *InsertBefore);
3129 /// Create a new switch instruction, specifying a value to switch on and a
3130 /// default destination. The number of additional cases can be specified here
3131 /// to make memory allocation more efficient. This constructor also
3132 /// auto-inserts at the end of the specified BasicBlock.
3133 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3134 BasicBlock *InsertAtEnd);
3136 // allocate space for exactly zero operands
3137 void *operator new(size_t s) {
3138 return User::operator new(s);
3141 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3142 void growOperands();
3144 protected:
3145 // Note: Instruction needs to be a friend here to call cloneImpl.
3146 friend class Instruction;
3148 SwitchInst *cloneImpl() const;
3150 public:
3151 // -2
3152 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3154 template <typename CaseHandleT> class CaseIteratorImpl;
3156 /// A handle to a particular switch case. It exposes a convenient interface
3157 /// to both the case value and the successor block.
3159 /// We define this as a template and instantiate it to form both a const and
3160 /// non-const handle.
3161 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3162 class CaseHandleImpl {
3163 // Directly befriend both const and non-const iterators.
3164 friend class SwitchInst::CaseIteratorImpl<
3165 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3167 protected:
3168 // Expose the switch type we're parameterized with to the iterator.
3169 using SwitchInstType = SwitchInstT;
3171 SwitchInstT *SI;
3172 ptrdiff_t Index;
3174 CaseHandleImpl() = default;
3175 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3177 public:
3178 /// Resolves case value for current case.
3179 ConstantIntT *getCaseValue() const {
3180 assert((unsigned)Index < SI->getNumCases() &&
3181 "Index out the number of cases.");
3182 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3185 /// Resolves successor for current case.
3186 BasicBlockT *getCaseSuccessor() const {
3187 assert(((unsigned)Index < SI->getNumCases() ||
3188 (unsigned)Index == DefaultPseudoIndex) &&
3189 "Index out the number of cases.");
3190 return SI->getSuccessor(getSuccessorIndex());
3193 /// Returns number of current case.
3194 unsigned getCaseIndex() const { return Index; }
3196 /// Returns successor index for current case successor.
3197 unsigned getSuccessorIndex() const {
3198 assert(((unsigned)Index == DefaultPseudoIndex ||
3199 (unsigned)Index < SI->getNumCases()) &&
3200 "Index out the number of cases.");
3201 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3204 bool operator==(const CaseHandleImpl &RHS) const {
3205 assert(SI == RHS.SI && "Incompatible operators.");
3206 return Index == RHS.Index;
3210 using ConstCaseHandle =
3211 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3213 class CaseHandle
3214 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3215 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3217 public:
3218 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3220 /// Sets the new value for current case.
3221 void setValue(ConstantInt *V) {
3222 assert((unsigned)Index < SI->getNumCases() &&
3223 "Index out the number of cases.");
3224 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3227 /// Sets the new successor for current case.
3228 void setSuccessor(BasicBlock *S) {
3229 SI->setSuccessor(getSuccessorIndex(), S);
3233 template <typename CaseHandleT>
3234 class CaseIteratorImpl
3235 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3236 std::random_access_iterator_tag,
3237 CaseHandleT> {
3238 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3240 CaseHandleT Case;
3242 public:
3243 /// Default constructed iterator is in an invalid state until assigned to
3244 /// a case for a particular switch.
3245 CaseIteratorImpl() = default;
3247 /// Initializes case iterator for given SwitchInst and for given
3248 /// case number.
3249 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3251 /// Initializes case iterator for given SwitchInst and for given
3252 /// successor index.
3253 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3254 unsigned SuccessorIndex) {
3255 assert(SuccessorIndex < SI->getNumSuccessors() &&
3256 "Successor index # out of range!");
3257 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3258 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3261 /// Support converting to the const variant. This will be a no-op for const
3262 /// variant.
3263 operator CaseIteratorImpl<ConstCaseHandle>() const {
3264 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3267 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3268 // Check index correctness after addition.
3269 // Note: Index == getNumCases() means end().
3270 assert(Case.Index + N >= 0 &&
3271 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3272 "Case.Index out the number of cases.");
3273 Case.Index += N;
3274 return *this;
3276 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3277 // Check index correctness after subtraction.
3278 // Note: Case.Index == getNumCases() means end().
3279 assert(Case.Index - N >= 0 &&
3280 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3281 "Case.Index out the number of cases.");
3282 Case.Index -= N;
3283 return *this;
3285 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3286 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3287 return Case.Index - RHS.Case.Index;
3289 bool operator==(const CaseIteratorImpl &RHS) const {
3290 return Case == RHS.Case;
3292 bool operator<(const CaseIteratorImpl &RHS) const {
3293 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3294 return Case.Index < RHS.Case.Index;
3296 CaseHandleT &operator*() { return Case; }
3297 const CaseHandleT &operator*() const { return Case; }
3300 using CaseIt = CaseIteratorImpl<CaseHandle>;
3301 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3303 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3304 unsigned NumCases,
3305 Instruction *InsertBefore = nullptr) {
3306 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3309 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3310 unsigned NumCases, BasicBlock *InsertAtEnd) {
3311 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3314 /// Provide fast operand accessors
3315 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3317 // Accessor Methods for Switch stmt
3318 Value *getCondition() const { return getOperand(0); }
3319 void setCondition(Value *V) { setOperand(0, V); }
3321 BasicBlock *getDefaultDest() const {
3322 return cast<BasicBlock>(getOperand(1));
3325 void setDefaultDest(BasicBlock *DefaultCase) {
3326 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3329 /// Return the number of 'cases' in this switch instruction, excluding the
3330 /// default case.
3331 unsigned getNumCases() const {
3332 return getNumOperands()/2 - 1;
3335 /// Returns a read/write iterator that points to the first case in the
3336 /// SwitchInst.
3337 CaseIt case_begin() {
3338 return CaseIt(this, 0);
3341 /// Returns a read-only iterator that points to the first case in the
3342 /// SwitchInst.
3343 ConstCaseIt case_begin() const {
3344 return ConstCaseIt(this, 0);
3347 /// Returns a read/write iterator that points one past the last in the
3348 /// SwitchInst.
3349 CaseIt case_end() {
3350 return CaseIt(this, getNumCases());
3353 /// Returns a read-only iterator that points one past the last in the
3354 /// SwitchInst.
3355 ConstCaseIt case_end() const {
3356 return ConstCaseIt(this, getNumCases());
3359 /// Iteration adapter for range-for loops.
3360 iterator_range<CaseIt> cases() {
3361 return make_range(case_begin(), case_end());
3364 /// Constant iteration adapter for range-for loops.
3365 iterator_range<ConstCaseIt> cases() const {
3366 return make_range(case_begin(), case_end());
3369 /// Returns an iterator that points to the default case.
3370 /// Note: this iterator allows to resolve successor only. Attempt
3371 /// to resolve case value causes an assertion.
3372 /// Also note, that increment and decrement also causes an assertion and
3373 /// makes iterator invalid.
3374 CaseIt case_default() {
3375 return CaseIt(this, DefaultPseudoIndex);
3377 ConstCaseIt case_default() const {
3378 return ConstCaseIt(this, DefaultPseudoIndex);
3381 /// Search all of the case values for the specified constant. If it is
3382 /// explicitly handled, return the case iterator of it, otherwise return
3383 /// default case iterator to indicate that it is handled by the default
3384 /// handler.
3385 CaseIt findCaseValue(const ConstantInt *C) {
3386 CaseIt I = llvm::find_if(
3387 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3388 if (I != case_end())
3389 return I;
3391 return case_default();
3393 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3394 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3395 return Case.getCaseValue() == C;
3397 if (I != case_end())
3398 return I;
3400 return case_default();
3403 /// Finds the unique case value for a given successor. Returns null if the
3404 /// successor is not found, not unique, or is the default case.
3405 ConstantInt *findCaseDest(BasicBlock *BB) {
3406 if (BB == getDefaultDest())
3407 return nullptr;
3409 ConstantInt *CI = nullptr;
3410 for (auto Case : cases()) {
3411 if (Case.getCaseSuccessor() != BB)
3412 continue;
3414 if (CI)
3415 return nullptr; // Multiple cases lead to BB.
3417 CI = Case.getCaseValue();
3420 return CI;
3423 /// Add an entry to the switch instruction.
3424 /// Note:
3425 /// This action invalidates case_end(). Old case_end() iterator will
3426 /// point to the added case.
3427 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3429 /// This method removes the specified case and its successor from the switch
3430 /// instruction. Note that this operation may reorder the remaining cases at
3431 /// index idx and above.
3432 /// Note:
3433 /// This action invalidates iterators for all cases following the one removed,
3434 /// including the case_end() iterator. It returns an iterator for the next
3435 /// case.
3436 CaseIt removeCase(CaseIt I);
3438 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3439 BasicBlock *getSuccessor(unsigned idx) const {
3440 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3441 return cast<BasicBlock>(getOperand(idx*2+1));
3443 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3444 assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3445 setOperand(idx * 2 + 1, NewSucc);
3448 // Methods for support type inquiry through isa, cast, and dyn_cast:
3449 static bool classof(const Instruction *I) {
3450 return I->getOpcode() == Instruction::Switch;
3452 static bool classof(const Value *V) {
3453 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3457 /// A wrapper class to simplify modification of SwitchInst cases along with
3458 /// their prof branch_weights metadata.
3459 class SwitchInstProfUpdateWrapper {
3460 SwitchInst &SI;
3461 Optional<SmallVector<uint32_t, 8> > Weights = None;
3462 bool Changed = false;
3464 protected:
3465 static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
3467 MDNode *buildProfBranchWeightsMD();
3469 void init();
3471 public:
3472 using CaseWeightOpt = Optional<uint32_t>;
3473 SwitchInst *operator->() { return &SI; }
3474 SwitchInst &operator*() { return SI; }
3475 operator SwitchInst *() { return &SI; }
3477 SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); }
3479 ~SwitchInstProfUpdateWrapper() {
3480 if (Changed)
3481 SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
3484 /// Delegate the call to the underlying SwitchInst::removeCase() and remove
3485 /// correspondent branch weight.
3486 SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
3488 /// Delegate the call to the underlying SwitchInst::addCase() and set the
3489 /// specified branch weight for the added case.
3490 void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
3492 /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
3493 /// this object to not touch the underlying SwitchInst in destructor.
3494 SymbolTableList<Instruction>::iterator eraseFromParent();
3496 void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
3497 CaseWeightOpt getSuccessorWeight(unsigned idx);
3499 static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
3502 template <>
3503 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3506 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3508 //===----------------------------------------------------------------------===//
3509 // IndirectBrInst Class
3510 //===----------------------------------------------------------------------===//
3512 //===---------------------------------------------------------------------------
3513 /// Indirect Branch Instruction.
3515 class IndirectBrInst : public Instruction {
3516 unsigned ReservedSpace;
3518 // Operand[0] = Address to jump to
3519 // Operand[n+1] = n-th destination
3520 IndirectBrInst(const IndirectBrInst &IBI);
3522 /// Create a new indirectbr instruction, specifying an
3523 /// Address to jump to. The number of expected destinations can be specified
3524 /// here to make memory allocation more efficient. This constructor can also
3525 /// autoinsert before another instruction.
3526 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3528 /// Create a new indirectbr instruction, specifying an
3529 /// Address to jump to. The number of expected destinations can be specified
3530 /// here to make memory allocation more efficient. This constructor also
3531 /// autoinserts at the end of the specified BasicBlock.
3532 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3534 // allocate space for exactly zero operands
3535 void *operator new(size_t s) {
3536 return User::operator new(s);
3539 void init(Value *Address, unsigned NumDests);
3540 void growOperands();
3542 protected:
3543 // Note: Instruction needs to be a friend here to call cloneImpl.
3544 friend class Instruction;
3546 IndirectBrInst *cloneImpl() const;
3548 public:
3549 /// Iterator type that casts an operand to a basic block.
3551 /// This only makes sense because the successors are stored as adjacent
3552 /// operands for indirectbr instructions.
3553 struct succ_op_iterator
3554 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3555 std::random_access_iterator_tag, BasicBlock *,
3556 ptrdiff_t, BasicBlock *, BasicBlock *> {
3557 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3559 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3560 BasicBlock *operator->() const { return operator*(); }
3563 /// The const version of `succ_op_iterator`.
3564 struct const_succ_op_iterator
3565 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3566 std::random_access_iterator_tag,
3567 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3568 const BasicBlock *> {
3569 explicit const_succ_op_iterator(const_value_op_iterator I)
3570 : iterator_adaptor_base(I) {}
3572 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3573 const BasicBlock *operator->() const { return operator*(); }
3576 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3577 Instruction *InsertBefore = nullptr) {
3578 return new IndirectBrInst(Address, NumDests, InsertBefore);
3581 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3582 BasicBlock *InsertAtEnd) {
3583 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3586 /// Provide fast operand accessors.
3587 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3589 // Accessor Methods for IndirectBrInst instruction.
3590 Value *getAddress() { return getOperand(0); }
3591 const Value *getAddress() const { return getOperand(0); }
3592 void setAddress(Value *V) { setOperand(0, V); }
3594 /// return the number of possible destinations in this
3595 /// indirectbr instruction.
3596 unsigned getNumDestinations() const { return getNumOperands()-1; }
3598 /// Return the specified destination.
3599 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3600 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3602 /// Add a destination.
3604 void addDestination(BasicBlock *Dest);
3606 /// This method removes the specified successor from the
3607 /// indirectbr instruction.
3608 void removeDestination(unsigned i);
3610 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3611 BasicBlock *getSuccessor(unsigned i) const {
3612 return cast<BasicBlock>(getOperand(i+1));
3614 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3615 setOperand(i + 1, NewSucc);
3618 iterator_range<succ_op_iterator> successors() {
3619 return make_range(succ_op_iterator(std::next(value_op_begin())),
3620 succ_op_iterator(value_op_end()));
3623 iterator_range<const_succ_op_iterator> successors() const {
3624 return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3625 const_succ_op_iterator(value_op_end()));
3628 // Methods for support type inquiry through isa, cast, and dyn_cast:
3629 static bool classof(const Instruction *I) {
3630 return I->getOpcode() == Instruction::IndirectBr;
3632 static bool classof(const Value *V) {
3633 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3637 template <>
3638 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3641 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3643 //===----------------------------------------------------------------------===//
3644 // InvokeInst Class
3645 //===----------------------------------------------------------------------===//
3647 /// Invoke instruction. The SubclassData field is used to hold the
3648 /// calling convention of the call.
3650 class InvokeInst : public CallBase {
3651 /// The number of operands for this call beyond the called function,
3652 /// arguments, and operand bundles.
3653 static constexpr int NumExtraOperands = 2;
3655 /// The index from the end of the operand array to the normal destination.
3656 static constexpr int NormalDestOpEndIdx = -3;
3658 /// The index from the end of the operand array to the unwind destination.
3659 static constexpr int UnwindDestOpEndIdx = -2;
3661 InvokeInst(const InvokeInst &BI);
3663 /// Construct an InvokeInst given a range of arguments.
3665 /// Construct an InvokeInst from a range of arguments
3666 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3667 BasicBlock *IfException, ArrayRef<Value *> Args,
3668 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3669 const Twine &NameStr, Instruction *InsertBefore);
3671 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3672 BasicBlock *IfException, ArrayRef<Value *> Args,
3673 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3674 const Twine &NameStr, BasicBlock *InsertAtEnd);
3676 void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3677 BasicBlock *IfException, ArrayRef<Value *> Args,
3678 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3680 /// Compute the number of operands to allocate.
3681 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3682 // We need one operand for the called function, plus our extra operands and
3683 // the input operand counts provided.
3684 return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3687 protected:
3688 // Note: Instruction needs to be a friend here to call cloneImpl.
3689 friend class Instruction;
3691 InvokeInst *cloneImpl() const;
3693 public:
3694 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3695 BasicBlock *IfException, ArrayRef<Value *> Args,
3696 const Twine &NameStr,
3697 Instruction *InsertBefore = nullptr) {
3698 int NumOperands = ComputeNumOperands(Args.size());
3699 return new (NumOperands)
3700 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3701 NameStr, InsertBefore);
3704 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3705 BasicBlock *IfException, ArrayRef<Value *> Args,
3706 ArrayRef<OperandBundleDef> Bundles = None,
3707 const Twine &NameStr = "",
3708 Instruction *InsertBefore = nullptr) {
3709 int NumOperands =
3710 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3711 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3713 return new (NumOperands, DescriptorBytes)
3714 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3715 NameStr, InsertBefore);
3718 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3719 BasicBlock *IfException, ArrayRef<Value *> Args,
3720 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3721 int NumOperands = ComputeNumOperands(Args.size());
3722 return new (NumOperands)
3723 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3724 NameStr, InsertAtEnd);
3727 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3728 BasicBlock *IfException, ArrayRef<Value *> Args,
3729 ArrayRef<OperandBundleDef> Bundles,
3730 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3731 int NumOperands =
3732 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3733 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3735 return new (NumOperands, DescriptorBytes)
3736 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3737 NameStr, InsertAtEnd);
3740 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3741 BasicBlock *IfException, ArrayRef<Value *> Args,
3742 const Twine &NameStr,
3743 Instruction *InsertBefore = nullptr) {
3744 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3745 IfException, Args, None, NameStr, InsertBefore);
3748 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3749 BasicBlock *IfException, ArrayRef<Value *> Args,
3750 ArrayRef<OperandBundleDef> Bundles = None,
3751 const Twine &NameStr = "",
3752 Instruction *InsertBefore = nullptr) {
3753 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3754 IfException, Args, Bundles, NameStr, InsertBefore);
3757 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3758 BasicBlock *IfException, ArrayRef<Value *> Args,
3759 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3760 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3761 IfException, Args, NameStr, InsertAtEnd);
3764 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3765 BasicBlock *IfException, ArrayRef<Value *> Args,
3766 ArrayRef<OperandBundleDef> Bundles,
3767 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3768 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3769 IfException, Args, Bundles, NameStr, InsertAtEnd);
3772 // Deprecated [opaque pointer types]
3773 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3774 BasicBlock *IfException, ArrayRef<Value *> Args,
3775 const Twine &NameStr,
3776 Instruction *InsertBefore = nullptr) {
3777 return Create(cast<FunctionType>(
3778 cast<PointerType>(Func->getType())->getElementType()),
3779 Func, IfNormal, IfException, Args, None, NameStr,
3780 InsertBefore);
3783 // Deprecated [opaque pointer types]
3784 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3785 BasicBlock *IfException, ArrayRef<Value *> Args,
3786 ArrayRef<OperandBundleDef> Bundles = None,
3787 const Twine &NameStr = "",
3788 Instruction *InsertBefore = nullptr) {
3789 return Create(cast<FunctionType>(
3790 cast<PointerType>(Func->getType())->getElementType()),
3791 Func, IfNormal, IfException, Args, Bundles, NameStr,
3792 InsertBefore);
3795 // Deprecated [opaque pointer types]
3796 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3797 BasicBlock *IfException, ArrayRef<Value *> Args,
3798 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3799 return Create(cast<FunctionType>(
3800 cast<PointerType>(Func->getType())->getElementType()),
3801 Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3804 // Deprecated [opaque pointer types]
3805 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3806 BasicBlock *IfException, ArrayRef<Value *> Args,
3807 ArrayRef<OperandBundleDef> Bundles,
3808 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3809 return Create(cast<FunctionType>(
3810 cast<PointerType>(Func->getType())->getElementType()),
3811 Func, IfNormal, IfException, Args, Bundles, NameStr,
3812 InsertAtEnd);
3815 /// Create a clone of \p II with a different set of operand bundles and
3816 /// insert it before \p InsertPt.
3818 /// The returned invoke instruction is identical to \p II in every way except
3819 /// that the operand bundles for the new instruction are set to the operand
3820 /// bundles in \p Bundles.
3821 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3822 Instruction *InsertPt = nullptr);
3824 /// Determine if the call should not perform indirect branch tracking.
3825 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3827 /// Determine if the call cannot unwind.
3828 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3829 void setDoesNotThrow() {
3830 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3833 // get*Dest - Return the destination basic blocks...
3834 BasicBlock *getNormalDest() const {
3835 return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3837 BasicBlock *getUnwindDest() const {
3838 return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3840 void setNormalDest(BasicBlock *B) {
3841 Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3843 void setUnwindDest(BasicBlock *B) {
3844 Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3847 /// Get the landingpad instruction from the landing pad
3848 /// block (the unwind destination).
3849 LandingPadInst *getLandingPadInst() const;
3851 BasicBlock *getSuccessor(unsigned i) const {
3852 assert(i < 2 && "Successor # out of range for invoke!");
3853 return i == 0 ? getNormalDest() : getUnwindDest();
3856 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3857 assert(i < 2 && "Successor # out of range for invoke!");
3858 if (i == 0)
3859 setNormalDest(NewSucc);
3860 else
3861 setUnwindDest(NewSucc);
3864 unsigned getNumSuccessors() const { return 2; }
3866 // Methods for support type inquiry through isa, cast, and dyn_cast:
3867 static bool classof(const Instruction *I) {
3868 return (I->getOpcode() == Instruction::Invoke);
3870 static bool classof(const Value *V) {
3871 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3874 private:
3876 // Shadow Instruction::setInstructionSubclassData with a private forwarding
3877 // method so that subclasses cannot accidentally use it.
3878 void setInstructionSubclassData(unsigned short D) {
3879 Instruction::setInstructionSubclassData(D);
3883 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3884 BasicBlock *IfException, ArrayRef<Value *> Args,
3885 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3886 const Twine &NameStr, Instruction *InsertBefore)
3887 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3888 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3889 InsertBefore) {
3890 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3893 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3894 BasicBlock *IfException, ArrayRef<Value *> Args,
3895 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3896 const Twine &NameStr, BasicBlock *InsertAtEnd)
3897 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3898 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3899 InsertAtEnd) {
3900 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3903 //===----------------------------------------------------------------------===//
3904 // CallBrInst Class
3905 //===----------------------------------------------------------------------===//
3907 /// CallBr instruction, tracking function calls that may not return control but
3908 /// instead transfer it to a third location. The SubclassData field is used to
3909 /// hold the calling convention of the call.
3911 class CallBrInst : public CallBase {
3913 unsigned NumIndirectDests;
3915 CallBrInst(const CallBrInst &BI);
3917 /// Construct a CallBrInst given a range of arguments.
3919 /// Construct a CallBrInst from a range of arguments
3920 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3921 ArrayRef<BasicBlock *> IndirectDests,
3922 ArrayRef<Value *> Args,
3923 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3924 const Twine &NameStr, Instruction *InsertBefore);
3926 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3927 ArrayRef<BasicBlock *> IndirectDests,
3928 ArrayRef<Value *> Args,
3929 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3930 const Twine &NameStr, BasicBlock *InsertAtEnd);
3932 void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3933 ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3934 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3936 /// Should the Indirect Destinations change, scan + update the Arg list.
3937 void updateArgBlockAddresses(unsigned i, BasicBlock *B);
3939 /// Compute the number of operands to allocate.
3940 static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3941 int NumBundleInputs = 0) {
3942 // We need one operand for the called function, plus our extra operands and
3943 // the input operand counts provided.
3944 return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3947 protected:
3948 // Note: Instruction needs to be a friend here to call cloneImpl.
3949 friend class Instruction;
3951 CallBrInst *cloneImpl() const;
3953 public:
3954 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3955 BasicBlock *DefaultDest,
3956 ArrayRef<BasicBlock *> IndirectDests,
3957 ArrayRef<Value *> Args, const Twine &NameStr,
3958 Instruction *InsertBefore = nullptr) {
3959 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3960 return new (NumOperands)
3961 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3962 NumOperands, NameStr, InsertBefore);
3965 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3966 BasicBlock *DefaultDest,
3967 ArrayRef<BasicBlock *> IndirectDests,
3968 ArrayRef<Value *> Args,
3969 ArrayRef<OperandBundleDef> Bundles = None,
3970 const Twine &NameStr = "",
3971 Instruction *InsertBefore = nullptr) {
3972 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3973 CountBundleInputs(Bundles));
3974 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3976 return new (NumOperands, DescriptorBytes)
3977 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3978 NumOperands, NameStr, InsertBefore);
3981 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3982 BasicBlock *DefaultDest,
3983 ArrayRef<BasicBlock *> IndirectDests,
3984 ArrayRef<Value *> Args, const Twine &NameStr,
3985 BasicBlock *InsertAtEnd) {
3986 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3987 return new (NumOperands)
3988 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3989 NumOperands, NameStr, InsertAtEnd);
3992 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3993 BasicBlock *DefaultDest,
3994 ArrayRef<BasicBlock *> IndirectDests,
3995 ArrayRef<Value *> Args,
3996 ArrayRef<OperandBundleDef> Bundles,
3997 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3998 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3999 CountBundleInputs(Bundles));
4000 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
4002 return new (NumOperands, DescriptorBytes)
4003 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
4004 NumOperands, NameStr, InsertAtEnd);
4007 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4008 ArrayRef<BasicBlock *> IndirectDests,
4009 ArrayRef<Value *> Args, const Twine &NameStr,
4010 Instruction *InsertBefore = nullptr) {
4011 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4012 IndirectDests, Args, NameStr, InsertBefore);
4015 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4016 ArrayRef<BasicBlock *> IndirectDests,
4017 ArrayRef<Value *> Args,
4018 ArrayRef<OperandBundleDef> Bundles = None,
4019 const Twine &NameStr = "",
4020 Instruction *InsertBefore = nullptr) {
4021 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4022 IndirectDests, Args, Bundles, NameStr, InsertBefore);
4025 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4026 ArrayRef<BasicBlock *> IndirectDests,
4027 ArrayRef<Value *> Args, const Twine &NameStr,
4028 BasicBlock *InsertAtEnd) {
4029 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4030 IndirectDests, Args, NameStr, InsertAtEnd);
4033 static CallBrInst *Create(FunctionCallee Func,
4034 BasicBlock *DefaultDest,
4035 ArrayRef<BasicBlock *> IndirectDests,
4036 ArrayRef<Value *> Args,
4037 ArrayRef<OperandBundleDef> Bundles,
4038 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4039 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4040 IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4043 /// Create a clone of \p CBI with a different set of operand bundles and
4044 /// insert it before \p InsertPt.
4046 /// The returned callbr instruction is identical to \p CBI in every way
4047 /// except that the operand bundles for the new instruction are set to the
4048 /// operand bundles in \p Bundles.
4049 static CallBrInst *Create(CallBrInst *CBI,
4050 ArrayRef<OperandBundleDef> Bundles,
4051 Instruction *InsertPt = nullptr);
4053 /// Return the number of callbr indirect dest labels.
4055 unsigned getNumIndirectDests() const { return NumIndirectDests; }
4057 /// getIndirectDestLabel - Return the i-th indirect dest label.
4059 Value *getIndirectDestLabel(unsigned i) const {
4060 assert(i < getNumIndirectDests() && "Out of bounds!");
4061 return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4065 Value *getIndirectDestLabelUse(unsigned i) const {
4066 assert(i < getNumIndirectDests() && "Out of bounds!");
4067 return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4071 // Return the destination basic blocks...
4072 BasicBlock *getDefaultDest() const {
4073 return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4075 BasicBlock *getIndirectDest(unsigned i) const {
4076 return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4078 SmallVector<BasicBlock *, 16> getIndirectDests() const {
4079 SmallVector<BasicBlock *, 16> IndirectDests;
4080 for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4081 IndirectDests.push_back(getIndirectDest(i));
4082 return IndirectDests;
4084 void setDefaultDest(BasicBlock *B) {
4085 *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4087 void setIndirectDest(unsigned i, BasicBlock *B) {
4088 updateArgBlockAddresses(i, B);
4089 *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4092 BasicBlock *getSuccessor(unsigned i) const {
4093 assert(i < getNumSuccessors() + 1 &&
4094 "Successor # out of range for callbr!");
4095 return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4098 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
4099 assert(i < getNumIndirectDests() + 1 &&
4100 "Successor # out of range for callbr!");
4101 return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
4104 unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4106 // Methods for support type inquiry through isa, cast, and dyn_cast:
4107 static bool classof(const Instruction *I) {
4108 return (I->getOpcode() == Instruction::CallBr);
4110 static bool classof(const Value *V) {
4111 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4114 private:
4116 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4117 // method so that subclasses cannot accidentally use it.
4118 void setInstructionSubclassData(unsigned short D) {
4119 Instruction::setInstructionSubclassData(D);
4123 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4124 ArrayRef<BasicBlock *> IndirectDests,
4125 ArrayRef<Value *> Args,
4126 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4127 const Twine &NameStr, Instruction *InsertBefore)
4128 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4129 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4130 InsertBefore) {
4131 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4134 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4135 ArrayRef<BasicBlock *> IndirectDests,
4136 ArrayRef<Value *> Args,
4137 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4138 const Twine &NameStr, BasicBlock *InsertAtEnd)
4139 : CallBase(
4140 cast<FunctionType>(
4141 cast<PointerType>(Func->getType())->getElementType())
4142 ->getReturnType(),
4143 Instruction::CallBr,
4144 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4145 InsertAtEnd) {
4146 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4149 //===----------------------------------------------------------------------===//
4150 // ResumeInst Class
4151 //===----------------------------------------------------------------------===//
4153 //===---------------------------------------------------------------------------
4154 /// Resume the propagation of an exception.
4156 class ResumeInst : public Instruction {
4157 ResumeInst(const ResumeInst &RI);
4159 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4160 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4162 protected:
4163 // Note: Instruction needs to be a friend here to call cloneImpl.
4164 friend class Instruction;
4166 ResumeInst *cloneImpl() const;
4168 public:
4169 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4170 return new(1) ResumeInst(Exn, InsertBefore);
4173 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4174 return new(1) ResumeInst(Exn, InsertAtEnd);
4177 /// Provide fast operand accessors
4178 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4180 /// Convenience accessor.
4181 Value *getValue() const { return Op<0>(); }
4183 unsigned getNumSuccessors() const { return 0; }
4185 // Methods for support type inquiry through isa, cast, and dyn_cast:
4186 static bool classof(const Instruction *I) {
4187 return I->getOpcode() == Instruction::Resume;
4189 static bool classof(const Value *V) {
4190 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4193 private:
4194 BasicBlock *getSuccessor(unsigned idx) const {
4195 llvm_unreachable("ResumeInst has no successors!");
4198 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4199 llvm_unreachable("ResumeInst has no successors!");
4203 template <>
4204 struct OperandTraits<ResumeInst> :
4205 public FixedNumOperandTraits<ResumeInst, 1> {
4208 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4210 //===----------------------------------------------------------------------===//
4211 // CatchSwitchInst Class
4212 //===----------------------------------------------------------------------===//
4213 class CatchSwitchInst : public Instruction {
4214 /// The number of operands actually allocated. NumOperands is
4215 /// the number actually in use.
4216 unsigned ReservedSpace;
4218 // Operand[0] = Outer scope
4219 // Operand[1] = Unwind block destination
4220 // Operand[n] = BasicBlock to go to on match
4221 CatchSwitchInst(const CatchSwitchInst &CSI);
4223 /// Create a new switch instruction, specifying a
4224 /// default destination. The number of additional handlers can be specified
4225 /// here to make memory allocation more efficient.
4226 /// This constructor can also autoinsert before another instruction.
4227 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4228 unsigned NumHandlers, const Twine &NameStr,
4229 Instruction *InsertBefore);
4231 /// Create a new switch instruction, specifying a
4232 /// default destination. The number of additional handlers can be specified
4233 /// here to make memory allocation more efficient.
4234 /// This constructor also autoinserts at the end of the specified BasicBlock.
4235 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4236 unsigned NumHandlers, const Twine &NameStr,
4237 BasicBlock *InsertAtEnd);
4239 // allocate space for exactly zero operands
4240 void *operator new(size_t s) { return User::operator new(s); }
4242 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4243 void growOperands(unsigned Size);
4245 protected:
4246 // Note: Instruction needs to be a friend here to call cloneImpl.
4247 friend class Instruction;
4249 CatchSwitchInst *cloneImpl() const;
4251 public:
4252 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4253 unsigned NumHandlers,
4254 const Twine &NameStr = "",
4255 Instruction *InsertBefore = nullptr) {
4256 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4257 InsertBefore);
4260 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4261 unsigned NumHandlers, const Twine &NameStr,
4262 BasicBlock *InsertAtEnd) {
4263 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4264 InsertAtEnd);
4267 /// Provide fast operand accessors
4268 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4270 // Accessor Methods for CatchSwitch stmt
4271 Value *getParentPad() const { return getOperand(0); }
4272 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4274 // Accessor Methods for CatchSwitch stmt
4275 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4276 bool unwindsToCaller() const { return !hasUnwindDest(); }
4277 BasicBlock *getUnwindDest() const {
4278 if (hasUnwindDest())
4279 return cast<BasicBlock>(getOperand(1));
4280 return nullptr;
4282 void setUnwindDest(BasicBlock *UnwindDest) {
4283 assert(UnwindDest);
4284 assert(hasUnwindDest());
4285 setOperand(1, UnwindDest);
4288 /// return the number of 'handlers' in this catchswitch
4289 /// instruction, except the default handler
4290 unsigned getNumHandlers() const {
4291 if (hasUnwindDest())
4292 return getNumOperands() - 2;
4293 return getNumOperands() - 1;
4296 private:
4297 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4298 static const BasicBlock *handler_helper(const Value *V) {
4299 return cast<BasicBlock>(V);
4302 public:
4303 using DerefFnTy = BasicBlock *(*)(Value *);
4304 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4305 using handler_range = iterator_range<handler_iterator>;
4306 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4307 using const_handler_iterator =
4308 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4309 using const_handler_range = iterator_range<const_handler_iterator>;
4311 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4312 handler_iterator handler_begin() {
4313 op_iterator It = op_begin() + 1;
4314 if (hasUnwindDest())
4315 ++It;
4316 return handler_iterator(It, DerefFnTy(handler_helper));
4319 /// Returns an iterator that points to the first handler in the
4320 /// CatchSwitchInst.
4321 const_handler_iterator handler_begin() const {
4322 const_op_iterator It = op_begin() + 1;
4323 if (hasUnwindDest())
4324 ++It;
4325 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4328 /// Returns a read-only iterator that points one past the last
4329 /// handler in the CatchSwitchInst.
4330 handler_iterator handler_end() {
4331 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4334 /// Returns an iterator that points one past the last handler in the
4335 /// CatchSwitchInst.
4336 const_handler_iterator handler_end() const {
4337 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4340 /// iteration adapter for range-for loops.
4341 handler_range handlers() {
4342 return make_range(handler_begin(), handler_end());
4345 /// iteration adapter for range-for loops.
4346 const_handler_range handlers() const {
4347 return make_range(handler_begin(), handler_end());
4350 /// Add an entry to the switch instruction...
4351 /// Note:
4352 /// This action invalidates handler_end(). Old handler_end() iterator will
4353 /// point to the added handler.
4354 void addHandler(BasicBlock *Dest);
4356 void removeHandler(handler_iterator HI);
4358 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4359 BasicBlock *getSuccessor(unsigned Idx) const {
4360 assert(Idx < getNumSuccessors() &&
4361 "Successor # out of range for catchswitch!");
4362 return cast<BasicBlock>(getOperand(Idx + 1));
4364 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4365 assert(Idx < getNumSuccessors() &&
4366 "Successor # out of range for catchswitch!");
4367 setOperand(Idx + 1, NewSucc);
4370 // Methods for support type inquiry through isa, cast, and dyn_cast:
4371 static bool classof(const Instruction *I) {
4372 return I->getOpcode() == Instruction::CatchSwitch;
4374 static bool classof(const Value *V) {
4375 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4379 template <>
4380 struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4382 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4384 //===----------------------------------------------------------------------===//
4385 // CleanupPadInst Class
4386 //===----------------------------------------------------------------------===//
4387 class CleanupPadInst : public FuncletPadInst {
4388 private:
4389 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4390 unsigned Values, const Twine &NameStr,
4391 Instruction *InsertBefore)
4392 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4393 NameStr, InsertBefore) {}
4394 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4395 unsigned Values, const Twine &NameStr,
4396 BasicBlock *InsertAtEnd)
4397 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4398 NameStr, InsertAtEnd) {}
4400 public:
4401 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4402 const Twine &NameStr = "",
4403 Instruction *InsertBefore = nullptr) {
4404 unsigned Values = 1 + Args.size();
4405 return new (Values)
4406 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4409 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4410 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4411 unsigned Values = 1 + Args.size();
4412 return new (Values)
4413 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4416 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4417 static bool classof(const Instruction *I) {
4418 return I->getOpcode() == Instruction::CleanupPad;
4420 static bool classof(const Value *V) {
4421 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4425 //===----------------------------------------------------------------------===//
4426 // CatchPadInst Class
4427 //===----------------------------------------------------------------------===//
4428 class CatchPadInst : public FuncletPadInst {
4429 private:
4430 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4431 unsigned Values, const Twine &NameStr,
4432 Instruction *InsertBefore)
4433 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4434 NameStr, InsertBefore) {}
4435 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4436 unsigned Values, const Twine &NameStr,
4437 BasicBlock *InsertAtEnd)
4438 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4439 NameStr, InsertAtEnd) {}
4441 public:
4442 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4443 const Twine &NameStr = "",
4444 Instruction *InsertBefore = nullptr) {
4445 unsigned Values = 1 + Args.size();
4446 return new (Values)
4447 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4450 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4451 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4452 unsigned Values = 1 + Args.size();
4453 return new (Values)
4454 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4457 /// Convenience accessors
4458 CatchSwitchInst *getCatchSwitch() const {
4459 return cast<CatchSwitchInst>(Op<-1>());
4461 void setCatchSwitch(Value *CatchSwitch) {
4462 assert(CatchSwitch);
4463 Op<-1>() = CatchSwitch;
4466 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4467 static bool classof(const Instruction *I) {
4468 return I->getOpcode() == Instruction::CatchPad;
4470 static bool classof(const Value *V) {
4471 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4475 //===----------------------------------------------------------------------===//
4476 // CatchReturnInst Class
4477 //===----------------------------------------------------------------------===//
4479 class CatchReturnInst : public Instruction {
4480 CatchReturnInst(const CatchReturnInst &RI);
4481 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4482 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4484 void init(Value *CatchPad, BasicBlock *BB);
4486 protected:
4487 // Note: Instruction needs to be a friend here to call cloneImpl.
4488 friend class Instruction;
4490 CatchReturnInst *cloneImpl() const;
4492 public:
4493 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4494 Instruction *InsertBefore = nullptr) {
4495 assert(CatchPad);
4496 assert(BB);
4497 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4500 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4501 BasicBlock *InsertAtEnd) {
4502 assert(CatchPad);
4503 assert(BB);
4504 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4507 /// Provide fast operand accessors
4508 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4510 /// Convenience accessors.
4511 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4512 void setCatchPad(CatchPadInst *CatchPad) {
4513 assert(CatchPad);
4514 Op<0>() = CatchPad;
4517 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4518 void setSuccessor(BasicBlock *NewSucc) {
4519 assert(NewSucc);
4520 Op<1>() = NewSucc;
4522 unsigned getNumSuccessors() const { return 1; }
4524 /// Get the parentPad of this catchret's catchpad's catchswitch.
4525 /// The successor block is implicitly a member of this funclet.
4526 Value *getCatchSwitchParentPad() const {
4527 return getCatchPad()->getCatchSwitch()->getParentPad();
4530 // Methods for support type inquiry through isa, cast, and dyn_cast:
4531 static bool classof(const Instruction *I) {
4532 return (I->getOpcode() == Instruction::CatchRet);
4534 static bool classof(const Value *V) {
4535 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4538 private:
4539 BasicBlock *getSuccessor(unsigned Idx) const {
4540 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4541 return getSuccessor();
4544 void setSuccessor(unsigned Idx, BasicBlock *B) {
4545 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4546 setSuccessor(B);
4550 template <>
4551 struct OperandTraits<CatchReturnInst>
4552 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4554 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4556 //===----------------------------------------------------------------------===//
4557 // CleanupReturnInst Class
4558 //===----------------------------------------------------------------------===//
4560 class CleanupReturnInst : public Instruction {
4561 private:
4562 CleanupReturnInst(const CleanupReturnInst &RI);
4563 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4564 Instruction *InsertBefore = nullptr);
4565 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4566 BasicBlock *InsertAtEnd);
4568 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4570 protected:
4571 // Note: Instruction needs to be a friend here to call cloneImpl.
4572 friend class Instruction;
4574 CleanupReturnInst *cloneImpl() const;
4576 public:
4577 static CleanupReturnInst *Create(Value *CleanupPad,
4578 BasicBlock *UnwindBB = nullptr,
4579 Instruction *InsertBefore = nullptr) {
4580 assert(CleanupPad);
4581 unsigned Values = 1;
4582 if (UnwindBB)
4583 ++Values;
4584 return new (Values)
4585 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4588 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4589 BasicBlock *InsertAtEnd) {
4590 assert(CleanupPad);
4591 unsigned Values = 1;
4592 if (UnwindBB)
4593 ++Values;
4594 return new (Values)
4595 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4598 /// Provide fast operand accessors
4599 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4601 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4602 bool unwindsToCaller() const { return !hasUnwindDest(); }
4604 /// Convenience accessor.
4605 CleanupPadInst *getCleanupPad() const {
4606 return cast<CleanupPadInst>(Op<0>());
4608 void setCleanupPad(CleanupPadInst *CleanupPad) {
4609 assert(CleanupPad);
4610 Op<0>() = CleanupPad;
4613 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4615 BasicBlock *getUnwindDest() const {
4616 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4618 void setUnwindDest(BasicBlock *NewDest) {
4619 assert(NewDest);
4620 assert(hasUnwindDest());
4621 Op<1>() = NewDest;
4624 // Methods for support type inquiry through isa, cast, and dyn_cast:
4625 static bool classof(const Instruction *I) {
4626 return (I->getOpcode() == Instruction::CleanupRet);
4628 static bool classof(const Value *V) {
4629 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4632 private:
4633 BasicBlock *getSuccessor(unsigned Idx) const {
4634 assert(Idx == 0);
4635 return getUnwindDest();
4638 void setSuccessor(unsigned Idx, BasicBlock *B) {
4639 assert(Idx == 0);
4640 setUnwindDest(B);
4643 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4644 // method so that subclasses cannot accidentally use it.
4645 void setInstructionSubclassData(unsigned short D) {
4646 Instruction::setInstructionSubclassData(D);
4650 template <>
4651 struct OperandTraits<CleanupReturnInst>
4652 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4654 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4656 //===----------------------------------------------------------------------===//
4657 // UnreachableInst Class
4658 //===----------------------------------------------------------------------===//
4660 //===---------------------------------------------------------------------------
4661 /// This function has undefined behavior. In particular, the
4662 /// presence of this instruction indicates some higher level knowledge that the
4663 /// end of the block cannot be reached.
4665 class UnreachableInst : public Instruction {
4666 protected:
4667 // Note: Instruction needs to be a friend here to call cloneImpl.
4668 friend class Instruction;
4670 UnreachableInst *cloneImpl() const;
4672 public:
4673 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4674 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4676 // allocate space for exactly zero operands
4677 void *operator new(size_t s) {
4678 return User::operator new(s, 0);
4681 unsigned getNumSuccessors() const { return 0; }
4683 // Methods for support type inquiry through isa, cast, and dyn_cast:
4684 static bool classof(const Instruction *I) {
4685 return I->getOpcode() == Instruction::Unreachable;
4687 static bool classof(const Value *V) {
4688 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4691 private:
4692 BasicBlock *getSuccessor(unsigned idx) const {
4693 llvm_unreachable("UnreachableInst has no successors!");
4696 void setSuccessor(unsigned idx, BasicBlock *B) {
4697 llvm_unreachable("UnreachableInst has no successors!");
4701 //===----------------------------------------------------------------------===//
4702 // TruncInst Class
4703 //===----------------------------------------------------------------------===//
4705 /// This class represents a truncation of integer types.
4706 class TruncInst : public CastInst {
4707 protected:
4708 // Note: Instruction needs to be a friend here to call cloneImpl.
4709 friend class Instruction;
4711 /// Clone an identical TruncInst
4712 TruncInst *cloneImpl() const;
4714 public:
4715 /// Constructor with insert-before-instruction semantics
4716 TruncInst(
4717 Value *S, ///< The value to be truncated
4718 Type *Ty, ///< The (smaller) type to truncate to
4719 const Twine &NameStr = "", ///< A name for the new instruction
4720 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4723 /// Constructor with insert-at-end-of-block semantics
4724 TruncInst(
4725 Value *S, ///< The value to be truncated
4726 Type *Ty, ///< The (smaller) type to truncate to
4727 const Twine &NameStr, ///< A name for the new instruction
4728 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4731 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4732 static bool classof(const Instruction *I) {
4733 return I->getOpcode() == Trunc;
4735 static bool classof(const Value *V) {
4736 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4740 //===----------------------------------------------------------------------===//
4741 // ZExtInst Class
4742 //===----------------------------------------------------------------------===//
4744 /// This class represents zero extension of integer types.
4745 class ZExtInst : public CastInst {
4746 protected:
4747 // Note: Instruction needs to be a friend here to call cloneImpl.
4748 friend class Instruction;
4750 /// Clone an identical ZExtInst
4751 ZExtInst *cloneImpl() const;
4753 public:
4754 /// Constructor with insert-before-instruction semantics
4755 ZExtInst(
4756 Value *S, ///< The value to be zero extended
4757 Type *Ty, ///< The type to zero extend to
4758 const Twine &NameStr = "", ///< A name for the new instruction
4759 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4762 /// Constructor with insert-at-end semantics.
4763 ZExtInst(
4764 Value *S, ///< The value to be zero extended
4765 Type *Ty, ///< The type to zero extend to
4766 const Twine &NameStr, ///< A name for the new instruction
4767 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4770 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4771 static bool classof(const Instruction *I) {
4772 return I->getOpcode() == ZExt;
4774 static bool classof(const Value *V) {
4775 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4779 //===----------------------------------------------------------------------===//
4780 // SExtInst Class
4781 //===----------------------------------------------------------------------===//
4783 /// This class represents a sign extension of integer types.
4784 class SExtInst : public CastInst {
4785 protected:
4786 // Note: Instruction needs to be a friend here to call cloneImpl.
4787 friend class Instruction;
4789 /// Clone an identical SExtInst
4790 SExtInst *cloneImpl() const;
4792 public:
4793 /// Constructor with insert-before-instruction semantics
4794 SExtInst(
4795 Value *S, ///< The value to be sign extended
4796 Type *Ty, ///< The type to sign extend to
4797 const Twine &NameStr = "", ///< A name for the new instruction
4798 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4801 /// Constructor with insert-at-end-of-block semantics
4802 SExtInst(
4803 Value *S, ///< The value to be sign extended
4804 Type *Ty, ///< The type to sign extend to
4805 const Twine &NameStr, ///< A name for the new instruction
4806 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4809 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4810 static bool classof(const Instruction *I) {
4811 return I->getOpcode() == SExt;
4813 static bool classof(const Value *V) {
4814 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4818 //===----------------------------------------------------------------------===//
4819 // FPTruncInst Class
4820 //===----------------------------------------------------------------------===//
4822 /// This class represents a truncation of floating point types.
4823 class FPTruncInst : public CastInst {
4824 protected:
4825 // Note: Instruction needs to be a friend here to call cloneImpl.
4826 friend class Instruction;
4828 /// Clone an identical FPTruncInst
4829 FPTruncInst *cloneImpl() const;
4831 public:
4832 /// Constructor with insert-before-instruction semantics
4833 FPTruncInst(
4834 Value *S, ///< The value to be truncated
4835 Type *Ty, ///< The type to truncate to
4836 const Twine &NameStr = "", ///< A name for the new instruction
4837 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4840 /// Constructor with insert-before-instruction semantics
4841 FPTruncInst(
4842 Value *S, ///< The value to be truncated
4843 Type *Ty, ///< The type to truncate to
4844 const Twine &NameStr, ///< A name for the new instruction
4845 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4848 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4849 static bool classof(const Instruction *I) {
4850 return I->getOpcode() == FPTrunc;
4852 static bool classof(const Value *V) {
4853 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4857 //===----------------------------------------------------------------------===//
4858 // FPExtInst Class
4859 //===----------------------------------------------------------------------===//
4861 /// This class represents an extension of floating point types.
4862 class FPExtInst : public CastInst {
4863 protected:
4864 // Note: Instruction needs to be a friend here to call cloneImpl.
4865 friend class Instruction;
4867 /// Clone an identical FPExtInst
4868 FPExtInst *cloneImpl() const;
4870 public:
4871 /// Constructor with insert-before-instruction semantics
4872 FPExtInst(
4873 Value *S, ///< The value to be extended
4874 Type *Ty, ///< The type to extend to
4875 const Twine &NameStr = "", ///< A name for the new instruction
4876 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4879 /// Constructor with insert-at-end-of-block semantics
4880 FPExtInst(
4881 Value *S, ///< The value to be extended
4882 Type *Ty, ///< The type to extend to
4883 const Twine &NameStr, ///< A name for the new instruction
4884 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4887 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4888 static bool classof(const Instruction *I) {
4889 return I->getOpcode() == FPExt;
4891 static bool classof(const Value *V) {
4892 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4896 //===----------------------------------------------------------------------===//
4897 // UIToFPInst Class
4898 //===----------------------------------------------------------------------===//
4900 /// This class represents a cast unsigned integer to floating point.
4901 class UIToFPInst : public CastInst {
4902 protected:
4903 // Note: Instruction needs to be a friend here to call cloneImpl.
4904 friend class Instruction;
4906 /// Clone an identical UIToFPInst
4907 UIToFPInst *cloneImpl() const;
4909 public:
4910 /// Constructor with insert-before-instruction semantics
4911 UIToFPInst(
4912 Value *S, ///< The value to be converted
4913 Type *Ty, ///< The type to convert to
4914 const Twine &NameStr = "", ///< A name for the new instruction
4915 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4918 /// Constructor with insert-at-end-of-block semantics
4919 UIToFPInst(
4920 Value *S, ///< The value to be converted
4921 Type *Ty, ///< The type to convert to
4922 const Twine &NameStr, ///< A name for the new instruction
4923 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4926 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4927 static bool classof(const Instruction *I) {
4928 return I->getOpcode() == UIToFP;
4930 static bool classof(const Value *V) {
4931 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4935 //===----------------------------------------------------------------------===//
4936 // SIToFPInst Class
4937 //===----------------------------------------------------------------------===//
4939 /// This class represents a cast from signed integer to floating point.
4940 class SIToFPInst : public CastInst {
4941 protected:
4942 // Note: Instruction needs to be a friend here to call cloneImpl.
4943 friend class Instruction;
4945 /// Clone an identical SIToFPInst
4946 SIToFPInst *cloneImpl() const;
4948 public:
4949 /// Constructor with insert-before-instruction semantics
4950 SIToFPInst(
4951 Value *S, ///< The value to be converted
4952 Type *Ty, ///< The type to convert to
4953 const Twine &NameStr = "", ///< A name for the new instruction
4954 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4957 /// Constructor with insert-at-end-of-block semantics
4958 SIToFPInst(
4959 Value *S, ///< The value to be converted
4960 Type *Ty, ///< The type to convert to
4961 const Twine &NameStr, ///< A name for the new instruction
4962 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4965 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4966 static bool classof(const Instruction *I) {
4967 return I->getOpcode() == SIToFP;
4969 static bool classof(const Value *V) {
4970 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4974 //===----------------------------------------------------------------------===//
4975 // FPToUIInst Class
4976 //===----------------------------------------------------------------------===//
4978 /// This class represents a cast from floating point to unsigned integer
4979 class FPToUIInst : public CastInst {
4980 protected:
4981 // Note: Instruction needs to be a friend here to call cloneImpl.
4982 friend class Instruction;
4984 /// Clone an identical FPToUIInst
4985 FPToUIInst *cloneImpl() const;
4987 public:
4988 /// Constructor with insert-before-instruction semantics
4989 FPToUIInst(
4990 Value *S, ///< The value to be converted
4991 Type *Ty, ///< The type to convert to
4992 const Twine &NameStr = "", ///< A name for the new instruction
4993 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4996 /// Constructor with insert-at-end-of-block semantics
4997 FPToUIInst(
4998 Value *S, ///< The value to be converted
4999 Type *Ty, ///< The type to convert to
5000 const Twine &NameStr, ///< A name for the new instruction
5001 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
5004 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5005 static bool classof(const Instruction *I) {
5006 return I->getOpcode() == FPToUI;
5008 static bool classof(const Value *V) {
5009 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5013 //===----------------------------------------------------------------------===//
5014 // FPToSIInst Class
5015 //===----------------------------------------------------------------------===//
5017 /// This class represents a cast from floating point to signed integer.
5018 class FPToSIInst : public CastInst {
5019 protected:
5020 // Note: Instruction needs to be a friend here to call cloneImpl.
5021 friend class Instruction;
5023 /// Clone an identical FPToSIInst
5024 FPToSIInst *cloneImpl() const;
5026 public:
5027 /// Constructor with insert-before-instruction semantics
5028 FPToSIInst(
5029 Value *S, ///< The value to be converted
5030 Type *Ty, ///< The type to convert to
5031 const Twine &NameStr = "", ///< A name for the new instruction
5032 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5035 /// Constructor with insert-at-end-of-block semantics
5036 FPToSIInst(
5037 Value *S, ///< The value to be converted
5038 Type *Ty, ///< The type to convert to
5039 const Twine &NameStr, ///< A name for the new instruction
5040 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5043 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5044 static bool classof(const Instruction *I) {
5045 return I->getOpcode() == FPToSI;
5047 static bool classof(const Value *V) {
5048 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5052 //===----------------------------------------------------------------------===//
5053 // IntToPtrInst Class
5054 //===----------------------------------------------------------------------===//
5056 /// This class represents a cast from an integer to a pointer.
5057 class IntToPtrInst : public CastInst {
5058 public:
5059 // Note: Instruction needs to be a friend here to call cloneImpl.
5060 friend class Instruction;
5062 /// Constructor with insert-before-instruction semantics
5063 IntToPtrInst(
5064 Value *S, ///< The value to be converted
5065 Type *Ty, ///< The type to convert to
5066 const Twine &NameStr = "", ///< A name for the new instruction
5067 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5070 /// Constructor with insert-at-end-of-block semantics
5071 IntToPtrInst(
5072 Value *S, ///< The value to be converted
5073 Type *Ty, ///< The type to convert to
5074 const Twine &NameStr, ///< A name for the new instruction
5075 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5078 /// Clone an identical IntToPtrInst.
5079 IntToPtrInst *cloneImpl() const;
5081 /// Returns the address space of this instruction's pointer type.
5082 unsigned getAddressSpace() const {
5083 return getType()->getPointerAddressSpace();
5086 // Methods for support type inquiry through isa, cast, and dyn_cast:
5087 static bool classof(const Instruction *I) {
5088 return I->getOpcode() == IntToPtr;
5090 static bool classof(const Value *V) {
5091 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5095 //===----------------------------------------------------------------------===//
5096 // PtrToIntInst Class
5097 //===----------------------------------------------------------------------===//
5099 /// This class represents a cast from a pointer to an integer.
5100 class PtrToIntInst : public CastInst {
5101 protected:
5102 // Note: Instruction needs to be a friend here to call cloneImpl.
5103 friend class Instruction;
5105 /// Clone an identical PtrToIntInst.
5106 PtrToIntInst *cloneImpl() const;
5108 public:
5109 /// Constructor with insert-before-instruction semantics
5110 PtrToIntInst(
5111 Value *S, ///< The value to be converted
5112 Type *Ty, ///< The type to convert to
5113 const Twine &NameStr = "", ///< A name for the new instruction
5114 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5117 /// Constructor with insert-at-end-of-block semantics
5118 PtrToIntInst(
5119 Value *S, ///< The value to be converted
5120 Type *Ty, ///< The type to convert to
5121 const Twine &NameStr, ///< A name for the new instruction
5122 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5125 /// Gets the pointer operand.
5126 Value *getPointerOperand() { return getOperand(0); }
5127 /// Gets the pointer operand.
5128 const Value *getPointerOperand() const { return getOperand(0); }
5129 /// Gets the operand index of the pointer operand.
5130 static unsigned getPointerOperandIndex() { return 0U; }
5132 /// Returns the address space of the pointer operand.
5133 unsigned getPointerAddressSpace() const {
5134 return getPointerOperand()->getType()->getPointerAddressSpace();
5137 // Methods for support type inquiry through isa, cast, and dyn_cast:
5138 static bool classof(const Instruction *I) {
5139 return I->getOpcode() == PtrToInt;
5141 static bool classof(const Value *V) {
5142 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5146 //===----------------------------------------------------------------------===//
5147 // BitCastInst Class
5148 //===----------------------------------------------------------------------===//
5150 /// This class represents a no-op cast from one type to another.
5151 class BitCastInst : public CastInst {
5152 protected:
5153 // Note: Instruction needs to be a friend here to call cloneImpl.
5154 friend class Instruction;
5156 /// Clone an identical BitCastInst.
5157 BitCastInst *cloneImpl() const;
5159 public:
5160 /// Constructor with insert-before-instruction semantics
5161 BitCastInst(
5162 Value *S, ///< The value to be casted
5163 Type *Ty, ///< The type to casted to
5164 const Twine &NameStr = "", ///< A name for the new instruction
5165 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5168 /// Constructor with insert-at-end-of-block semantics
5169 BitCastInst(
5170 Value *S, ///< The value to be casted
5171 Type *Ty, ///< The type to casted to
5172 const Twine &NameStr, ///< A name for the new instruction
5173 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5176 // Methods for support type inquiry through isa, cast, and dyn_cast:
5177 static bool classof(const Instruction *I) {
5178 return I->getOpcode() == BitCast;
5180 static bool classof(const Value *V) {
5181 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5185 //===----------------------------------------------------------------------===//
5186 // AddrSpaceCastInst Class
5187 //===----------------------------------------------------------------------===//
5189 /// This class represents a conversion between pointers from one address space
5190 /// to another.
5191 class AddrSpaceCastInst : public CastInst {
5192 protected:
5193 // Note: Instruction needs to be a friend here to call cloneImpl.
5194 friend class Instruction;
5196 /// Clone an identical AddrSpaceCastInst.
5197 AddrSpaceCastInst *cloneImpl() const;
5199 public:
5200 /// Constructor with insert-before-instruction semantics
5201 AddrSpaceCastInst(
5202 Value *S, ///< The value to be casted
5203 Type *Ty, ///< The type to casted to
5204 const Twine &NameStr = "", ///< A name for the new instruction
5205 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5208 /// Constructor with insert-at-end-of-block semantics
5209 AddrSpaceCastInst(
5210 Value *S, ///< The value to be casted
5211 Type *Ty, ///< The type to casted to
5212 const Twine &NameStr, ///< A name for the new instruction
5213 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5216 // Methods for support type inquiry through isa, cast, and dyn_cast:
5217 static bool classof(const Instruction *I) {
5218 return I->getOpcode() == AddrSpaceCast;
5220 static bool classof(const Value *V) {
5221 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5224 /// Gets the pointer operand.
5225 Value *getPointerOperand() {
5226 return getOperand(0);
5229 /// Gets the pointer operand.
5230 const Value *getPointerOperand() const {
5231 return getOperand(0);
5234 /// Gets the operand index of the pointer operand.
5235 static unsigned getPointerOperandIndex() {
5236 return 0U;
5239 /// Returns the address space of the pointer operand.
5240 unsigned getSrcAddressSpace() const {
5241 return getPointerOperand()->getType()->getPointerAddressSpace();
5244 /// Returns the address space of the result.
5245 unsigned getDestAddressSpace() const {
5246 return getType()->getPointerAddressSpace();
5250 /// A helper function that returns the pointer operand of a load or store
5251 /// instruction. Returns nullptr if not load or store.
5252 inline const Value *getLoadStorePointerOperand(const Value *V) {
5253 if (auto *Load = dyn_cast<LoadInst>(V))
5254 return Load->getPointerOperand();
5255 if (auto *Store = dyn_cast<StoreInst>(V))
5256 return Store->getPointerOperand();
5257 return nullptr;
5259 inline Value *getLoadStorePointerOperand(Value *V) {
5260 return const_cast<Value *>(
5261 getLoadStorePointerOperand(static_cast<const Value *>(V)));
5264 /// A helper function that returns the pointer operand of a load, store
5265 /// or GEP instruction. Returns nullptr if not load, store, or GEP.
5266 inline const Value *getPointerOperand(const Value *V) {
5267 if (auto *Ptr = getLoadStorePointerOperand(V))
5268 return Ptr;
5269 if (auto *Gep = dyn_cast<GetElementPtrInst>(V))
5270 return Gep->getPointerOperand();
5271 return nullptr;
5273 inline Value *getPointerOperand(Value *V) {
5274 return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V)));
5277 /// A helper function that returns the alignment of load or store instruction.
5278 inline unsigned getLoadStoreAlignment(Value *I) {
5279 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5280 "Expected Load or Store instruction");
5281 if (auto *LI = dyn_cast<LoadInst>(I))
5282 return LI->getAlignment();
5283 return cast<StoreInst>(I)->getAlignment();
5286 /// A helper function that returns the address space of the pointer operand of
5287 /// load or store instruction.
5288 inline unsigned getLoadStoreAddressSpace(Value *I) {
5289 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5290 "Expected Load or Store instruction");
5291 if (auto *LI = dyn_cast<LoadInst>(I))
5292 return LI->getPointerAddressSpace();
5293 return cast<StoreInst>(I)->getPointerAddressSpace();
5296 } // end namespace llvm
5298 #endif // LLVM_IR_INSTRUCTIONS_H