[Alignment][NFC] Instructions::getLoadStoreAlignment
[llvm-core.git] / include / llvm / IR / Instructions.h
blob1e29d2cd361d1dee6eba63fa32b8b978fde0865d
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 if (const auto MA = decodeMaybeAlign(getSubclassDataFromInstruction() & 31))
114 return MA->value();
115 return 0;
117 void setAlignment(MaybeAlign Align);
119 /// Return true if this alloca is in the entry block of the function and is a
120 /// constant size. If so, the code generator will fold it into the
121 /// prolog/epilog code, so it is basically free.
122 bool isStaticAlloca() const;
124 /// Return true if this alloca is used as an inalloca argument to a call. Such
125 /// allocas are never considered static even if they are in the entry block.
126 bool isUsedWithInAlloca() const {
127 return getSubclassDataFromInstruction() & 32;
130 /// Specify whether this alloca is used to represent the arguments to a call.
131 void setUsedWithInAlloca(bool V) {
132 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
133 (V ? 32 : 0));
136 /// Return true if this alloca is used as a swifterror argument to a call.
137 bool isSwiftError() const {
138 return getSubclassDataFromInstruction() & 64;
141 /// Specify whether this alloca is used to represent a swifterror.
142 void setSwiftError(bool V) {
143 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
144 (V ? 64 : 0));
147 // Methods for support type inquiry through isa, cast, and dyn_cast:
148 static bool classof(const Instruction *I) {
149 return (I->getOpcode() == Instruction::Alloca);
151 static bool classof(const Value *V) {
152 return isa<Instruction>(V) && classof(cast<Instruction>(V));
155 private:
156 // Shadow Instruction::setInstructionSubclassData with a private forwarding
157 // method so that subclasses cannot accidentally use it.
158 void setInstructionSubclassData(unsigned short D) {
159 Instruction::setInstructionSubclassData(D);
163 //===----------------------------------------------------------------------===//
164 // LoadInst Class
165 //===----------------------------------------------------------------------===//
167 /// An instruction for reading from memory. This uses the SubclassData field in
168 /// Value to store whether or not the load is volatile.
169 class LoadInst : public UnaryInstruction {
170 void AssertOK();
172 protected:
173 // Note: Instruction needs to be a friend here to call cloneImpl.
174 friend class Instruction;
176 LoadInst *cloneImpl() const;
178 public:
179 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
180 Instruction *InsertBefore = nullptr);
181 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
182 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
183 Instruction *InsertBefore = nullptr);
184 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
185 BasicBlock *InsertAtEnd);
186 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187 unsigned Align, Instruction *InsertBefore = nullptr);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 unsigned Align, BasicBlock *InsertAtEnd);
190 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
191 unsigned Align, AtomicOrdering Order,
192 SyncScope::ID SSID = SyncScope::System,
193 Instruction *InsertBefore = nullptr);
194 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
195 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
196 BasicBlock *InsertAtEnd);
198 // Deprecated [opaque pointer types]
199 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
200 Instruction *InsertBefore = nullptr)
201 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
202 InsertBefore) {}
203 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
204 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
205 InsertAtEnd) {}
206 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
207 Instruction *InsertBefore = nullptr)
208 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
209 isVolatile, InsertBefore) {}
210 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
211 BasicBlock *InsertAtEnd)
212 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
213 isVolatile, InsertAtEnd) {}
214 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
215 Instruction *InsertBefore = nullptr)
216 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
217 isVolatile, Align, InsertBefore) {}
218 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
219 BasicBlock *InsertAtEnd)
220 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
221 isVolatile, Align, InsertAtEnd) {}
222 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
223 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
224 Instruction *InsertBefore = nullptr)
225 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
226 isVolatile, Align, Order, SSID, InsertBefore) {}
227 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
228 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
229 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
230 isVolatile, Align, Order, SSID, InsertAtEnd) {}
232 /// Return true if this is a load from a volatile memory location.
233 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
235 /// Specify whether this is a volatile load or not.
236 void setVolatile(bool V) {
237 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
238 (V ? 1 : 0));
241 /// Return the alignment of the access that is being performed.
242 unsigned getAlignment() const {
243 if (const auto MA =
244 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
245 return MA->value();
246 return 0;
249 void setAlignment(MaybeAlign Align);
251 /// Returns the ordering constraint of this load instruction.
252 AtomicOrdering getOrdering() const {
253 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
256 /// Sets the ordering constraint of this load instruction. May not be Release
257 /// or AcquireRelease.
258 void setOrdering(AtomicOrdering Ordering) {
259 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
260 ((unsigned)Ordering << 7));
263 /// Returns the synchronization scope ID of this load instruction.
264 SyncScope::ID getSyncScopeID() const {
265 return SSID;
268 /// Sets the synchronization scope ID of this load instruction.
269 void setSyncScopeID(SyncScope::ID SSID) {
270 this->SSID = SSID;
273 /// Sets the ordering constraint and the synchronization scope ID of this load
274 /// instruction.
275 void setAtomic(AtomicOrdering Ordering,
276 SyncScope::ID SSID = SyncScope::System) {
277 setOrdering(Ordering);
278 setSyncScopeID(SSID);
281 bool isSimple() const { return !isAtomic() && !isVolatile(); }
283 bool isUnordered() const {
284 return (getOrdering() == AtomicOrdering::NotAtomic ||
285 getOrdering() == AtomicOrdering::Unordered) &&
286 !isVolatile();
289 Value *getPointerOperand() { return getOperand(0); }
290 const Value *getPointerOperand() const { return getOperand(0); }
291 static unsigned getPointerOperandIndex() { return 0U; }
292 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
294 /// Returns the address space of the pointer operand.
295 unsigned getPointerAddressSpace() const {
296 return getPointerOperandType()->getPointerAddressSpace();
299 // Methods for support type inquiry through isa, cast, and dyn_cast:
300 static bool classof(const Instruction *I) {
301 return I->getOpcode() == Instruction::Load;
303 static bool classof(const Value *V) {
304 return isa<Instruction>(V) && classof(cast<Instruction>(V));
307 private:
308 // Shadow Instruction::setInstructionSubclassData with a private forwarding
309 // method so that subclasses cannot accidentally use it.
310 void setInstructionSubclassData(unsigned short D) {
311 Instruction::setInstructionSubclassData(D);
314 /// The synchronization scope ID of this load instruction. Not quite enough
315 /// room in SubClassData for everything, so synchronization scope ID gets its
316 /// own field.
317 SyncScope::ID SSID;
320 //===----------------------------------------------------------------------===//
321 // StoreInst Class
322 //===----------------------------------------------------------------------===//
324 /// An instruction for storing to memory.
325 class StoreInst : public Instruction {
326 void AssertOK();
328 protected:
329 // Note: Instruction needs to be a friend here to call cloneImpl.
330 friend class Instruction;
332 StoreInst *cloneImpl() const;
334 public:
335 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
336 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
337 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
338 Instruction *InsertBefore = nullptr);
339 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
340 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
341 unsigned Align, Instruction *InsertBefore = nullptr);
342 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
343 unsigned Align, BasicBlock *InsertAtEnd);
344 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
345 unsigned Align, AtomicOrdering Order,
346 SyncScope::ID SSID = SyncScope::System,
347 Instruction *InsertBefore = nullptr);
348 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
349 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
350 BasicBlock *InsertAtEnd);
352 // allocate space for exactly two operands
353 void *operator new(size_t s) {
354 return User::operator new(s, 2);
357 /// Return true if this is a store to a volatile memory location.
358 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
360 /// Specify whether this is a volatile store or not.
361 void setVolatile(bool V) {
362 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
363 (V ? 1 : 0));
366 /// Transparently provide more efficient getOperand methods.
367 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
369 /// Return the alignment of the access that is being performed
370 unsigned getAlignment() const {
371 if (const auto MA =
372 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
373 return MA->value();
374 return 0;
377 void setAlignment(MaybeAlign Align);
379 /// Returns the ordering constraint of this store instruction.
380 AtomicOrdering getOrdering() const {
381 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
384 /// Sets the ordering constraint of this store instruction. May not be
385 /// Acquire or AcquireRelease.
386 void setOrdering(AtomicOrdering Ordering) {
387 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
388 ((unsigned)Ordering << 7));
391 /// Returns the synchronization scope ID of this store instruction.
392 SyncScope::ID getSyncScopeID() const {
393 return SSID;
396 /// Sets the synchronization scope ID of this store instruction.
397 void setSyncScopeID(SyncScope::ID SSID) {
398 this->SSID = SSID;
401 /// Sets the ordering constraint and the synchronization scope ID of this
402 /// store instruction.
403 void setAtomic(AtomicOrdering Ordering,
404 SyncScope::ID SSID = SyncScope::System) {
405 setOrdering(Ordering);
406 setSyncScopeID(SSID);
409 bool isSimple() const { return !isAtomic() && !isVolatile(); }
411 bool isUnordered() const {
412 return (getOrdering() == AtomicOrdering::NotAtomic ||
413 getOrdering() == AtomicOrdering::Unordered) &&
414 !isVolatile();
417 Value *getValueOperand() { return getOperand(0); }
418 const Value *getValueOperand() const { return getOperand(0); }
420 Value *getPointerOperand() { return getOperand(1); }
421 const Value *getPointerOperand() const { return getOperand(1); }
422 static unsigned getPointerOperandIndex() { return 1U; }
423 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
425 /// Returns the address space of the pointer operand.
426 unsigned getPointerAddressSpace() const {
427 return getPointerOperandType()->getPointerAddressSpace();
430 // Methods for support type inquiry through isa, cast, and dyn_cast:
431 static bool classof(const Instruction *I) {
432 return I->getOpcode() == Instruction::Store;
434 static bool classof(const Value *V) {
435 return isa<Instruction>(V) && classof(cast<Instruction>(V));
438 private:
439 // Shadow Instruction::setInstructionSubclassData with a private forwarding
440 // method so that subclasses cannot accidentally use it.
441 void setInstructionSubclassData(unsigned short D) {
442 Instruction::setInstructionSubclassData(D);
445 /// The synchronization scope ID of this store instruction. Not quite enough
446 /// room in SubClassData for everything, so synchronization scope ID gets its
447 /// own field.
448 SyncScope::ID SSID;
451 template <>
452 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
455 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
457 //===----------------------------------------------------------------------===//
458 // FenceInst Class
459 //===----------------------------------------------------------------------===//
461 /// An instruction for ordering other memory operations.
462 class FenceInst : public Instruction {
463 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
465 protected:
466 // Note: Instruction needs to be a friend here to call cloneImpl.
467 friend class Instruction;
469 FenceInst *cloneImpl() const;
471 public:
472 // Ordering may only be Acquire, Release, AcquireRelease, or
473 // SequentiallyConsistent.
474 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
475 SyncScope::ID SSID = SyncScope::System,
476 Instruction *InsertBefore = nullptr);
477 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
478 BasicBlock *InsertAtEnd);
480 // allocate space for exactly zero operands
481 void *operator new(size_t s) {
482 return User::operator new(s, 0);
485 /// Returns the ordering constraint of this fence instruction.
486 AtomicOrdering getOrdering() const {
487 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
490 /// Sets the ordering constraint of this fence instruction. May only be
491 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
492 void setOrdering(AtomicOrdering Ordering) {
493 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
494 ((unsigned)Ordering << 1));
497 /// Returns the synchronization scope ID of this fence instruction.
498 SyncScope::ID getSyncScopeID() const {
499 return SSID;
502 /// Sets the synchronization scope ID of this fence instruction.
503 void setSyncScopeID(SyncScope::ID SSID) {
504 this->SSID = SSID;
507 // Methods for support type inquiry through isa, cast, and dyn_cast:
508 static bool classof(const Instruction *I) {
509 return I->getOpcode() == Instruction::Fence;
511 static bool classof(const Value *V) {
512 return isa<Instruction>(V) && classof(cast<Instruction>(V));
515 private:
516 // Shadow Instruction::setInstructionSubclassData with a private forwarding
517 // method so that subclasses cannot accidentally use it.
518 void setInstructionSubclassData(unsigned short D) {
519 Instruction::setInstructionSubclassData(D);
522 /// The synchronization scope ID of this fence instruction. Not quite enough
523 /// room in SubClassData for everything, so synchronization scope ID gets its
524 /// own field.
525 SyncScope::ID SSID;
528 //===----------------------------------------------------------------------===//
529 // AtomicCmpXchgInst Class
530 //===----------------------------------------------------------------------===//
532 /// An instruction that atomically checks whether a
533 /// specified value is in a memory location, and, if it is, stores a new value
534 /// there. The value returned by this instruction is a pair containing the
535 /// original value as first element, and an i1 indicating success (true) or
536 /// failure (false) as second element.
538 class AtomicCmpXchgInst : public Instruction {
539 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
540 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
541 SyncScope::ID SSID);
543 protected:
544 // Note: Instruction needs to be a friend here to call cloneImpl.
545 friend class Instruction;
547 AtomicCmpXchgInst *cloneImpl() const;
549 public:
550 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
551 AtomicOrdering SuccessOrdering,
552 AtomicOrdering FailureOrdering,
553 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
554 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
555 AtomicOrdering SuccessOrdering,
556 AtomicOrdering FailureOrdering,
557 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
559 // allocate space for exactly three operands
560 void *operator new(size_t s) {
561 return User::operator new(s, 3);
564 /// Return true if this is a cmpxchg from a volatile memory
565 /// location.
567 bool isVolatile() const {
568 return getSubclassDataFromInstruction() & 1;
571 /// Specify whether this is a volatile cmpxchg.
573 void setVolatile(bool V) {
574 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
575 (unsigned)V);
578 /// Return true if this cmpxchg may spuriously fail.
579 bool isWeak() const {
580 return getSubclassDataFromInstruction() & 0x100;
583 void setWeak(bool IsWeak) {
584 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
585 (IsWeak << 8));
588 /// Transparently provide more efficient getOperand methods.
589 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
591 /// Returns the success ordering constraint of this cmpxchg instruction.
592 AtomicOrdering getSuccessOrdering() const {
593 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
596 /// Sets the success ordering constraint of this cmpxchg instruction.
597 void setSuccessOrdering(AtomicOrdering Ordering) {
598 assert(Ordering != AtomicOrdering::NotAtomic &&
599 "CmpXchg instructions can only be atomic.");
600 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
601 ((unsigned)Ordering << 2));
604 /// Returns the failure ordering constraint of this cmpxchg instruction.
605 AtomicOrdering getFailureOrdering() const {
606 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
609 /// Sets the failure ordering constraint of this cmpxchg instruction.
610 void setFailureOrdering(AtomicOrdering Ordering) {
611 assert(Ordering != AtomicOrdering::NotAtomic &&
612 "CmpXchg instructions can only be atomic.");
613 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
614 ((unsigned)Ordering << 5));
617 /// Returns the synchronization scope ID of this cmpxchg instruction.
618 SyncScope::ID getSyncScopeID() const {
619 return SSID;
622 /// Sets the synchronization scope ID of this cmpxchg instruction.
623 void setSyncScopeID(SyncScope::ID SSID) {
624 this->SSID = SSID;
627 Value *getPointerOperand() { return getOperand(0); }
628 const Value *getPointerOperand() const { return getOperand(0); }
629 static unsigned getPointerOperandIndex() { return 0U; }
631 Value *getCompareOperand() { return getOperand(1); }
632 const Value *getCompareOperand() const { return getOperand(1); }
634 Value *getNewValOperand() { return getOperand(2); }
635 const Value *getNewValOperand() const { return getOperand(2); }
637 /// Returns the address space of the pointer operand.
638 unsigned getPointerAddressSpace() const {
639 return getPointerOperand()->getType()->getPointerAddressSpace();
642 /// Returns the strongest permitted ordering on failure, given the
643 /// desired ordering on success.
645 /// If the comparison in a cmpxchg operation fails, there is no atomic store
646 /// so release semantics cannot be provided. So this function drops explicit
647 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
648 /// operation would remain SequentiallyConsistent.
649 static AtomicOrdering
650 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
651 switch (SuccessOrdering) {
652 default:
653 llvm_unreachable("invalid cmpxchg success ordering");
654 case AtomicOrdering::Release:
655 case AtomicOrdering::Monotonic:
656 return AtomicOrdering::Monotonic;
657 case AtomicOrdering::AcquireRelease:
658 case AtomicOrdering::Acquire:
659 return AtomicOrdering::Acquire;
660 case AtomicOrdering::SequentiallyConsistent:
661 return AtomicOrdering::SequentiallyConsistent;
665 // Methods for support type inquiry through isa, cast, and dyn_cast:
666 static bool classof(const Instruction *I) {
667 return I->getOpcode() == Instruction::AtomicCmpXchg;
669 static bool classof(const Value *V) {
670 return isa<Instruction>(V) && classof(cast<Instruction>(V));
673 private:
674 // Shadow Instruction::setInstructionSubclassData with a private forwarding
675 // method so that subclasses cannot accidentally use it.
676 void setInstructionSubclassData(unsigned short D) {
677 Instruction::setInstructionSubclassData(D);
680 /// The synchronization scope ID of this cmpxchg instruction. Not quite
681 /// enough room in SubClassData for everything, so synchronization scope ID
682 /// gets its own field.
683 SyncScope::ID SSID;
686 template <>
687 struct OperandTraits<AtomicCmpXchgInst> :
688 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
691 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
693 //===----------------------------------------------------------------------===//
694 // AtomicRMWInst Class
695 //===----------------------------------------------------------------------===//
697 /// an instruction that atomically reads a memory location,
698 /// combines it with another value, and then stores the result back. Returns
699 /// the old value.
701 class AtomicRMWInst : public Instruction {
702 protected:
703 // Note: Instruction needs to be a friend here to call cloneImpl.
704 friend class Instruction;
706 AtomicRMWInst *cloneImpl() const;
708 public:
709 /// This enumeration lists the possible modifications atomicrmw can make. In
710 /// the descriptions, 'p' is the pointer to the instruction's memory location,
711 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
712 /// instruction. These instructions always return 'old'.
713 enum BinOp {
714 /// *p = v
715 Xchg,
716 /// *p = old + v
717 Add,
718 /// *p = old - v
719 Sub,
720 /// *p = old & v
721 And,
722 /// *p = ~(old & v)
723 Nand,
724 /// *p = old | v
726 /// *p = old ^ v
727 Xor,
728 /// *p = old >signed v ? old : v
729 Max,
730 /// *p = old <signed v ? old : v
731 Min,
732 /// *p = old >unsigned v ? old : v
733 UMax,
734 /// *p = old <unsigned v ? old : v
735 UMin,
737 /// *p = old + v
738 FAdd,
740 /// *p = old - v
741 FSub,
743 FIRST_BINOP = Xchg,
744 LAST_BINOP = FSub,
745 BAD_BINOP
748 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
749 AtomicOrdering Ordering, SyncScope::ID SSID,
750 Instruction *InsertBefore = nullptr);
751 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
752 AtomicOrdering Ordering, SyncScope::ID SSID,
753 BasicBlock *InsertAtEnd);
755 // allocate space for exactly two operands
756 void *operator new(size_t s) {
757 return User::operator new(s, 2);
760 BinOp getOperation() const {
761 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
764 static StringRef getOperationName(BinOp Op);
766 static bool isFPOperation(BinOp Op) {
767 switch (Op) {
768 case AtomicRMWInst::FAdd:
769 case AtomicRMWInst::FSub:
770 return true;
771 default:
772 return false;
776 void setOperation(BinOp Operation) {
777 unsigned short SubclassData = getSubclassDataFromInstruction();
778 setInstructionSubclassData((SubclassData & 31) |
779 (Operation << 5));
782 /// Return true if this is a RMW on a volatile memory location.
784 bool isVolatile() const {
785 return getSubclassDataFromInstruction() & 1;
788 /// Specify whether this is a volatile RMW or not.
790 void setVolatile(bool V) {
791 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
792 (unsigned)V);
795 /// Transparently provide more efficient getOperand methods.
796 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
798 /// Returns the ordering constraint of this rmw instruction.
799 AtomicOrdering getOrdering() const {
800 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
803 /// Sets the ordering constraint of this rmw instruction.
804 void setOrdering(AtomicOrdering Ordering) {
805 assert(Ordering != AtomicOrdering::NotAtomic &&
806 "atomicrmw instructions can only be atomic.");
807 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
808 ((unsigned)Ordering << 2));
811 /// Returns the synchronization scope ID of this rmw instruction.
812 SyncScope::ID getSyncScopeID() const {
813 return SSID;
816 /// Sets the synchronization scope ID of this rmw instruction.
817 void setSyncScopeID(SyncScope::ID SSID) {
818 this->SSID = SSID;
821 Value *getPointerOperand() { return getOperand(0); }
822 const Value *getPointerOperand() const { return getOperand(0); }
823 static unsigned getPointerOperandIndex() { return 0U; }
825 Value *getValOperand() { return getOperand(1); }
826 const Value *getValOperand() const { return getOperand(1); }
828 /// Returns the address space of the pointer operand.
829 unsigned getPointerAddressSpace() const {
830 return getPointerOperand()->getType()->getPointerAddressSpace();
833 bool isFloatingPointOperation() const {
834 return isFPOperation(getOperation());
837 // Methods for support type inquiry through isa, cast, and dyn_cast:
838 static bool classof(const Instruction *I) {
839 return I->getOpcode() == Instruction::AtomicRMW;
841 static bool classof(const Value *V) {
842 return isa<Instruction>(V) && classof(cast<Instruction>(V));
845 private:
846 void Init(BinOp Operation, Value *Ptr, Value *Val,
847 AtomicOrdering Ordering, SyncScope::ID SSID);
849 // Shadow Instruction::setInstructionSubclassData with a private forwarding
850 // method so that subclasses cannot accidentally use it.
851 void setInstructionSubclassData(unsigned short D) {
852 Instruction::setInstructionSubclassData(D);
855 /// The synchronization scope ID of this rmw instruction. Not quite enough
856 /// room in SubClassData for everything, so synchronization scope ID gets its
857 /// own field.
858 SyncScope::ID SSID;
861 template <>
862 struct OperandTraits<AtomicRMWInst>
863 : public FixedNumOperandTraits<AtomicRMWInst,2> {
866 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
868 //===----------------------------------------------------------------------===//
869 // GetElementPtrInst Class
870 //===----------------------------------------------------------------------===//
872 // checkGEPType - Simple wrapper function to give a better assertion failure
873 // message on bad indexes for a gep instruction.
875 inline Type *checkGEPType(Type *Ty) {
876 assert(Ty && "Invalid GetElementPtrInst indices for type!");
877 return Ty;
880 /// an instruction for type-safe pointer arithmetic to
881 /// access elements of arrays and structs
883 class GetElementPtrInst : public Instruction {
884 Type *SourceElementType;
885 Type *ResultElementType;
887 GetElementPtrInst(const GetElementPtrInst &GEPI);
889 /// Constructors - Create a getelementptr instruction with a base pointer an
890 /// list of indices. The first ctor can optionally insert before an existing
891 /// instruction, the second appends the new instruction to the specified
892 /// BasicBlock.
893 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
894 ArrayRef<Value *> IdxList, unsigned Values,
895 const Twine &NameStr, Instruction *InsertBefore);
896 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
897 ArrayRef<Value *> IdxList, unsigned Values,
898 const Twine &NameStr, BasicBlock *InsertAtEnd);
900 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
902 protected:
903 // Note: Instruction needs to be a friend here to call cloneImpl.
904 friend class Instruction;
906 GetElementPtrInst *cloneImpl() const;
908 public:
909 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
910 ArrayRef<Value *> IdxList,
911 const Twine &NameStr = "",
912 Instruction *InsertBefore = nullptr) {
913 unsigned Values = 1 + unsigned(IdxList.size());
914 if (!PointeeType)
915 PointeeType =
916 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
917 else
918 assert(
919 PointeeType ==
920 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
921 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
922 NameStr, InsertBefore);
925 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
926 ArrayRef<Value *> IdxList,
927 const Twine &NameStr,
928 BasicBlock *InsertAtEnd) {
929 unsigned Values = 1 + unsigned(IdxList.size());
930 if (!PointeeType)
931 PointeeType =
932 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
933 else
934 assert(
935 PointeeType ==
936 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
937 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
938 NameStr, InsertAtEnd);
941 /// Create an "inbounds" getelementptr. See the documentation for the
942 /// "inbounds" flag in LangRef.html for details.
943 static GetElementPtrInst *CreateInBounds(Value *Ptr,
944 ArrayRef<Value *> IdxList,
945 const Twine &NameStr = "",
946 Instruction *InsertBefore = nullptr){
947 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
950 static GetElementPtrInst *
951 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
952 const Twine &NameStr = "",
953 Instruction *InsertBefore = nullptr) {
954 GetElementPtrInst *GEP =
955 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
956 GEP->setIsInBounds(true);
957 return GEP;
960 static GetElementPtrInst *CreateInBounds(Value *Ptr,
961 ArrayRef<Value *> IdxList,
962 const Twine &NameStr,
963 BasicBlock *InsertAtEnd) {
964 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
967 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
968 ArrayRef<Value *> IdxList,
969 const Twine &NameStr,
970 BasicBlock *InsertAtEnd) {
971 GetElementPtrInst *GEP =
972 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
973 GEP->setIsInBounds(true);
974 return GEP;
977 /// Transparently provide more efficient getOperand methods.
978 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
980 Type *getSourceElementType() const { return SourceElementType; }
982 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
983 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
985 Type *getResultElementType() const {
986 assert(ResultElementType ==
987 cast<PointerType>(getType()->getScalarType())->getElementType());
988 return ResultElementType;
991 /// Returns the address space of this instruction's pointer type.
992 unsigned getAddressSpace() const {
993 // Note that this is always the same as the pointer operand's address space
994 // and that is cheaper to compute, so cheat here.
995 return getPointerAddressSpace();
998 /// Returns the type of the element that would be loaded with
999 /// a load instruction with the specified parameters.
1001 /// Null is returned if the indices are invalid for the specified
1002 /// pointer type.
1004 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1005 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1006 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1008 inline op_iterator idx_begin() { return op_begin()+1; }
1009 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1010 inline op_iterator idx_end() { return op_end(); }
1011 inline const_op_iterator idx_end() const { return op_end(); }
1013 inline iterator_range<op_iterator> indices() {
1014 return make_range(idx_begin(), idx_end());
1017 inline iterator_range<const_op_iterator> indices() const {
1018 return make_range(idx_begin(), idx_end());
1021 Value *getPointerOperand() {
1022 return getOperand(0);
1024 const Value *getPointerOperand() const {
1025 return getOperand(0);
1027 static unsigned getPointerOperandIndex() {
1028 return 0U; // get index for modifying correct operand.
1031 /// Method to return the pointer operand as a
1032 /// PointerType.
1033 Type *getPointerOperandType() const {
1034 return getPointerOperand()->getType();
1037 /// Returns the address space of the pointer operand.
1038 unsigned getPointerAddressSpace() const {
1039 return getPointerOperandType()->getPointerAddressSpace();
1042 /// Returns the pointer type returned by the GEP
1043 /// instruction, which may be a vector of pointers.
1044 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
1045 return getGEPReturnType(
1046 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1047 Ptr, IdxList);
1049 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1050 ArrayRef<Value *> IdxList) {
1051 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1052 Ptr->getType()->getPointerAddressSpace());
1053 // Vector GEP
1054 if (Ptr->getType()->isVectorTy()) {
1055 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1056 return VectorType::get(PtrTy, NumElem);
1058 for (Value *Index : IdxList)
1059 if (Index->getType()->isVectorTy()) {
1060 unsigned NumElem = Index->getType()->getVectorNumElements();
1061 return VectorType::get(PtrTy, NumElem);
1063 // Scalar GEP
1064 return PtrTy;
1067 unsigned getNumIndices() const { // Note: always non-negative
1068 return getNumOperands() - 1;
1071 bool hasIndices() const {
1072 return getNumOperands() > 1;
1075 /// Return true if all of the indices of this GEP are
1076 /// zeros. If so, the result pointer and the first operand have the same
1077 /// value, just potentially different types.
1078 bool hasAllZeroIndices() const;
1080 /// Return true if all of the indices of this GEP are
1081 /// constant integers. If so, the result pointer and the first operand have
1082 /// a constant offset between them.
1083 bool hasAllConstantIndices() const;
1085 /// Set or clear the inbounds flag on this GEP instruction.
1086 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1087 void setIsInBounds(bool b = true);
1089 /// Determine whether the GEP has the inbounds flag.
1090 bool isInBounds() const;
1092 /// Accumulate the constant address offset of this GEP if possible.
1094 /// This routine accepts an APInt into which it will accumulate the constant
1095 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1096 /// all-constant, it returns false and the value of the offset APInt is
1097 /// undefined (it is *not* preserved!). The APInt passed into this routine
1098 /// must be at least as wide as the IntPtr type for the address space of
1099 /// the base GEP pointer.
1100 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1102 // Methods for support type inquiry through isa, cast, and dyn_cast:
1103 static bool classof(const Instruction *I) {
1104 return (I->getOpcode() == Instruction::GetElementPtr);
1106 static bool classof(const Value *V) {
1107 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1111 template <>
1112 struct OperandTraits<GetElementPtrInst> :
1113 public VariadicOperandTraits<GetElementPtrInst, 1> {
1116 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1117 ArrayRef<Value *> IdxList, unsigned Values,
1118 const Twine &NameStr,
1119 Instruction *InsertBefore)
1120 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1121 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1122 Values, InsertBefore),
1123 SourceElementType(PointeeType),
1124 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1125 assert(ResultElementType ==
1126 cast<PointerType>(getType()->getScalarType())->getElementType());
1127 init(Ptr, IdxList, NameStr);
1130 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1131 ArrayRef<Value *> IdxList, unsigned Values,
1132 const Twine &NameStr,
1133 BasicBlock *InsertAtEnd)
1134 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1135 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1136 Values, InsertAtEnd),
1137 SourceElementType(PointeeType),
1138 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1139 assert(ResultElementType ==
1140 cast<PointerType>(getType()->getScalarType())->getElementType());
1141 init(Ptr, IdxList, NameStr);
1144 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1146 //===----------------------------------------------------------------------===//
1147 // ICmpInst Class
1148 //===----------------------------------------------------------------------===//
1150 /// This instruction compares its operands according to the predicate given
1151 /// to the constructor. It only operates on integers or pointers. The operands
1152 /// must be identical types.
1153 /// Represent an integer comparison operator.
1154 class ICmpInst: public CmpInst {
1155 void AssertOK() {
1156 assert(isIntPredicate() &&
1157 "Invalid ICmp predicate value");
1158 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1159 "Both operands to ICmp instruction are not of the same type!");
1160 // Check that the operands are the right type
1161 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1162 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1163 "Invalid operand types for ICmp instruction");
1166 protected:
1167 // Note: Instruction needs to be a friend here to call cloneImpl.
1168 friend class Instruction;
1170 /// Clone an identical ICmpInst
1171 ICmpInst *cloneImpl() const;
1173 public:
1174 /// Constructor with insert-before-instruction semantics.
1175 ICmpInst(
1176 Instruction *InsertBefore, ///< Where to insert
1177 Predicate pred, ///< The predicate to use for the comparison
1178 Value *LHS, ///< The left-hand-side of the expression
1179 Value *RHS, ///< The right-hand-side of the expression
1180 const Twine &NameStr = "" ///< Name of the instruction
1181 ) : CmpInst(makeCmpResultType(LHS->getType()),
1182 Instruction::ICmp, pred, LHS, RHS, NameStr,
1183 InsertBefore) {
1184 #ifndef NDEBUG
1185 AssertOK();
1186 #endif
1189 /// Constructor with insert-at-end semantics.
1190 ICmpInst(
1191 BasicBlock &InsertAtEnd, ///< Block to insert into.
1192 Predicate pred, ///< The predicate to use for the comparison
1193 Value *LHS, ///< The left-hand-side of the expression
1194 Value *RHS, ///< The right-hand-side of the expression
1195 const Twine &NameStr = "" ///< Name of the instruction
1196 ) : CmpInst(makeCmpResultType(LHS->getType()),
1197 Instruction::ICmp, pred, LHS, RHS, NameStr,
1198 &InsertAtEnd) {
1199 #ifndef NDEBUG
1200 AssertOK();
1201 #endif
1204 /// Constructor with no-insertion semantics
1205 ICmpInst(
1206 Predicate pred, ///< The predicate to use for the comparison
1207 Value *LHS, ///< The left-hand-side of the expression
1208 Value *RHS, ///< The right-hand-side of the expression
1209 const Twine &NameStr = "" ///< Name of the instruction
1210 ) : CmpInst(makeCmpResultType(LHS->getType()),
1211 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1212 #ifndef NDEBUG
1213 AssertOK();
1214 #endif
1217 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1218 /// @returns the predicate that would be the result if the operand were
1219 /// regarded as signed.
1220 /// Return the signed version of the predicate
1221 Predicate getSignedPredicate() const {
1222 return getSignedPredicate(getPredicate());
1225 /// This is a static version that you can use without an instruction.
1226 /// Return the signed version of the predicate.
1227 static Predicate getSignedPredicate(Predicate pred);
1229 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1230 /// @returns the predicate that would be the result if the operand were
1231 /// regarded as unsigned.
1232 /// Return the unsigned version of the predicate
1233 Predicate getUnsignedPredicate() const {
1234 return getUnsignedPredicate(getPredicate());
1237 /// This is a static version that you can use without an instruction.
1238 /// Return the unsigned version of the predicate.
1239 static Predicate getUnsignedPredicate(Predicate pred);
1241 /// Return true if this predicate is either EQ or NE. This also
1242 /// tests for commutativity.
1243 static bool isEquality(Predicate P) {
1244 return P == ICMP_EQ || P == ICMP_NE;
1247 /// Return true if this predicate is either EQ or NE. This also
1248 /// tests for commutativity.
1249 bool isEquality() const {
1250 return isEquality(getPredicate());
1253 /// @returns true if the predicate of this ICmpInst is commutative
1254 /// Determine if this relation is commutative.
1255 bool isCommutative() const { return isEquality(); }
1257 /// Return true if the predicate is relational (not EQ or NE).
1259 bool isRelational() const {
1260 return !isEquality();
1263 /// Return true if the predicate is relational (not EQ or NE).
1265 static bool isRelational(Predicate P) {
1266 return !isEquality(P);
1269 /// Exchange the two operands to this instruction in such a way that it does
1270 /// not modify the semantics of the instruction. The predicate value may be
1271 /// changed to retain the same result if the predicate is order dependent
1272 /// (e.g. ult).
1273 /// Swap operands and adjust predicate.
1274 void swapOperands() {
1275 setPredicate(getSwappedPredicate());
1276 Op<0>().swap(Op<1>());
1279 // Methods for support type inquiry through isa, cast, and dyn_cast:
1280 static bool classof(const Instruction *I) {
1281 return I->getOpcode() == Instruction::ICmp;
1283 static bool classof(const Value *V) {
1284 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1288 //===----------------------------------------------------------------------===//
1289 // FCmpInst Class
1290 //===----------------------------------------------------------------------===//
1292 /// This instruction compares its operands according to the predicate given
1293 /// to the constructor. It only operates on floating point values or packed
1294 /// vectors of floating point values. The operands must be identical types.
1295 /// Represents a floating point comparison operator.
1296 class FCmpInst: public CmpInst {
1297 void AssertOK() {
1298 assert(isFPPredicate() && "Invalid FCmp predicate value");
1299 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1300 "Both operands to FCmp instruction are not of the same type!");
1301 // Check that the operands are the right type
1302 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1303 "Invalid operand types for FCmp instruction");
1306 protected:
1307 // Note: Instruction needs to be a friend here to call cloneImpl.
1308 friend class Instruction;
1310 /// Clone an identical FCmpInst
1311 FCmpInst *cloneImpl() const;
1313 public:
1314 /// Constructor with insert-before-instruction semantics.
1315 FCmpInst(
1316 Instruction *InsertBefore, ///< Where to insert
1317 Predicate pred, ///< The predicate to use for the comparison
1318 Value *LHS, ///< The left-hand-side of the expression
1319 Value *RHS, ///< The right-hand-side of the expression
1320 const Twine &NameStr = "" ///< Name of the instruction
1321 ) : CmpInst(makeCmpResultType(LHS->getType()),
1322 Instruction::FCmp, pred, LHS, RHS, NameStr,
1323 InsertBefore) {
1324 AssertOK();
1327 /// Constructor with insert-at-end semantics.
1328 FCmpInst(
1329 BasicBlock &InsertAtEnd, ///< Block to insert into.
1330 Predicate pred, ///< The predicate to use for the comparison
1331 Value *LHS, ///< The left-hand-side of the expression
1332 Value *RHS, ///< The right-hand-side of the expression
1333 const Twine &NameStr = "" ///< Name of the instruction
1334 ) : CmpInst(makeCmpResultType(LHS->getType()),
1335 Instruction::FCmp, pred, LHS, RHS, NameStr,
1336 &InsertAtEnd) {
1337 AssertOK();
1340 /// Constructor with no-insertion semantics
1341 FCmpInst(
1342 Predicate Pred, ///< The predicate to use for the comparison
1343 Value *LHS, ///< The left-hand-side of the expression
1344 Value *RHS, ///< The right-hand-side of the expression
1345 const Twine &NameStr = "", ///< Name of the instruction
1346 Instruction *FlagsSource = nullptr
1347 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1348 RHS, NameStr, nullptr, FlagsSource) {
1349 AssertOK();
1352 /// @returns true if the predicate of this instruction is EQ or NE.
1353 /// Determine if this is an equality predicate.
1354 static bool isEquality(Predicate Pred) {
1355 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1356 Pred == FCMP_UNE;
1359 /// @returns true if the predicate of this instruction is EQ or NE.
1360 /// Determine if this is an equality predicate.
1361 bool isEquality() const { return isEquality(getPredicate()); }
1363 /// @returns true if the predicate of this instruction is commutative.
1364 /// Determine if this is a commutative predicate.
1365 bool isCommutative() const {
1366 return isEquality() ||
1367 getPredicate() == FCMP_FALSE ||
1368 getPredicate() == FCMP_TRUE ||
1369 getPredicate() == FCMP_ORD ||
1370 getPredicate() == FCMP_UNO;
1373 /// @returns true if the predicate is relational (not EQ or NE).
1374 /// Determine if this a relational predicate.
1375 bool isRelational() const { return !isEquality(); }
1377 /// Exchange the two operands to this instruction in such a way that it does
1378 /// not modify the semantics of the instruction. The predicate value may be
1379 /// changed to retain the same result if the predicate is order dependent
1380 /// (e.g. ult).
1381 /// Swap operands and adjust predicate.
1382 void swapOperands() {
1383 setPredicate(getSwappedPredicate());
1384 Op<0>().swap(Op<1>());
1387 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1388 static bool classof(const Instruction *I) {
1389 return I->getOpcode() == Instruction::FCmp;
1391 static bool classof(const Value *V) {
1392 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1396 //===----------------------------------------------------------------------===//
1397 /// This class represents a function call, abstracting a target
1398 /// machine's calling convention. This class uses low bit of the SubClassData
1399 /// field to indicate whether or not this is a tail call. The rest of the bits
1400 /// hold the calling convention of the call.
1402 class CallInst : public CallBase {
1403 CallInst(const CallInst &CI);
1405 /// Construct a CallInst given a range of arguments.
1406 /// Construct a CallInst from a range of arguments
1407 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1408 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1409 Instruction *InsertBefore);
1411 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1412 const Twine &NameStr, Instruction *InsertBefore)
1413 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1415 /// Construct a CallInst given a range of arguments.
1416 /// Construct a CallInst from a range of arguments
1417 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1418 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1419 BasicBlock *InsertAtEnd);
1421 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1422 Instruction *InsertBefore);
1424 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1425 BasicBlock *InsertAtEnd);
1427 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1428 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1429 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1431 /// Compute the number of operands to allocate.
1432 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1433 // We need one operand for the called function, plus the input operand
1434 // counts provided.
1435 return 1 + NumArgs + NumBundleInputs;
1438 protected:
1439 // Note: Instruction needs to be a friend here to call cloneImpl.
1440 friend class Instruction;
1442 CallInst *cloneImpl() const;
1444 public:
1445 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1446 Instruction *InsertBefore = nullptr) {
1447 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1450 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1451 const Twine &NameStr,
1452 Instruction *InsertBefore = nullptr) {
1453 return new (ComputeNumOperands(Args.size()))
1454 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1457 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1458 ArrayRef<OperandBundleDef> Bundles = None,
1459 const Twine &NameStr = "",
1460 Instruction *InsertBefore = nullptr) {
1461 const int NumOperands =
1462 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1463 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1465 return new (NumOperands, DescriptorBytes)
1466 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1469 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1470 BasicBlock *InsertAtEnd) {
1471 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1474 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1475 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1476 return new (ComputeNumOperands(Args.size()))
1477 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1480 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1481 ArrayRef<OperandBundleDef> Bundles,
1482 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1483 const int NumOperands =
1484 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1485 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1487 return new (NumOperands, DescriptorBytes)
1488 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1491 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1492 Instruction *InsertBefore = nullptr) {
1493 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1494 InsertBefore);
1497 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1498 ArrayRef<OperandBundleDef> Bundles = None,
1499 const Twine &NameStr = "",
1500 Instruction *InsertBefore = nullptr) {
1501 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1502 NameStr, InsertBefore);
1505 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1506 const Twine &NameStr,
1507 Instruction *InsertBefore = nullptr) {
1508 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1509 InsertBefore);
1512 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1513 BasicBlock *InsertAtEnd) {
1514 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1515 InsertAtEnd);
1518 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1519 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1520 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1521 InsertAtEnd);
1524 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1525 ArrayRef<OperandBundleDef> Bundles,
1526 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1527 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1528 NameStr, InsertAtEnd);
1531 // Deprecated [opaque pointer types]
1532 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1533 Instruction *InsertBefore = nullptr) {
1534 return Create(cast<FunctionType>(
1535 cast<PointerType>(Func->getType())->getElementType()),
1536 Func, NameStr, InsertBefore);
1539 // Deprecated [opaque pointer types]
1540 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1541 const Twine &NameStr,
1542 Instruction *InsertBefore = nullptr) {
1543 return Create(cast<FunctionType>(
1544 cast<PointerType>(Func->getType())->getElementType()),
1545 Func, Args, NameStr, InsertBefore);
1548 // Deprecated [opaque pointer types]
1549 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1550 ArrayRef<OperandBundleDef> Bundles = None,
1551 const Twine &NameStr = "",
1552 Instruction *InsertBefore = nullptr) {
1553 return Create(cast<FunctionType>(
1554 cast<PointerType>(Func->getType())->getElementType()),
1555 Func, Args, Bundles, NameStr, InsertBefore);
1558 // Deprecated [opaque pointer types]
1559 static CallInst *Create(Value *Func, const Twine &NameStr,
1560 BasicBlock *InsertAtEnd) {
1561 return Create(cast<FunctionType>(
1562 cast<PointerType>(Func->getType())->getElementType()),
1563 Func, NameStr, InsertAtEnd);
1566 // Deprecated [opaque pointer types]
1567 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1568 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1569 return Create(cast<FunctionType>(
1570 cast<PointerType>(Func->getType())->getElementType()),
1571 Func, Args, NameStr, InsertAtEnd);
1574 // Deprecated [opaque pointer types]
1575 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1576 ArrayRef<OperandBundleDef> Bundles,
1577 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1578 return Create(cast<FunctionType>(
1579 cast<PointerType>(Func->getType())->getElementType()),
1580 Func, Args, Bundles, NameStr, InsertAtEnd);
1583 /// Create a clone of \p CI with a different set of operand bundles and
1584 /// insert it before \p InsertPt.
1586 /// The returned call instruction is identical \p CI in every way except that
1587 /// the operand bundles for the new instruction are set to the operand bundles
1588 /// in \p Bundles.
1589 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1590 Instruction *InsertPt = nullptr);
1592 /// Generate the IR for a call to malloc:
1593 /// 1. Compute the malloc call's argument as the specified type's size,
1594 /// possibly multiplied by the array size if the array size is not
1595 /// constant 1.
1596 /// 2. Call malloc with that argument.
1597 /// 3. Bitcast the result of the malloc call to the specified type.
1598 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1599 Type *AllocTy, Value *AllocSize,
1600 Value *ArraySize = nullptr,
1601 Function *MallocF = nullptr,
1602 const Twine &Name = "");
1603 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1604 Type *AllocTy, Value *AllocSize,
1605 Value *ArraySize = nullptr,
1606 Function *MallocF = nullptr,
1607 const Twine &Name = "");
1608 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1609 Type *AllocTy, Value *AllocSize,
1610 Value *ArraySize = nullptr,
1611 ArrayRef<OperandBundleDef> Bundles = None,
1612 Function *MallocF = nullptr,
1613 const Twine &Name = "");
1614 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1615 Type *AllocTy, Value *AllocSize,
1616 Value *ArraySize = nullptr,
1617 ArrayRef<OperandBundleDef> Bundles = None,
1618 Function *MallocF = nullptr,
1619 const Twine &Name = "");
1620 /// Generate the IR for a call to the builtin free function.
1621 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1622 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1623 static Instruction *CreateFree(Value *Source,
1624 ArrayRef<OperandBundleDef> Bundles,
1625 Instruction *InsertBefore);
1626 static Instruction *CreateFree(Value *Source,
1627 ArrayRef<OperandBundleDef> Bundles,
1628 BasicBlock *InsertAtEnd);
1630 // Note that 'musttail' implies 'tail'.
1631 enum TailCallKind {
1632 TCK_None = 0,
1633 TCK_Tail = 1,
1634 TCK_MustTail = 2,
1635 TCK_NoTail = 3
1637 TailCallKind getTailCallKind() const {
1638 return TailCallKind(getSubclassDataFromInstruction() & 3);
1641 bool isTailCall() const {
1642 unsigned Kind = getSubclassDataFromInstruction() & 3;
1643 return Kind == TCK_Tail || Kind == TCK_MustTail;
1646 bool isMustTailCall() const {
1647 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1650 bool isNoTailCall() const {
1651 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1654 void setTailCall(bool isTC = true) {
1655 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1656 unsigned(isTC ? TCK_Tail : TCK_None));
1659 void setTailCallKind(TailCallKind TCK) {
1660 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1661 unsigned(TCK));
1664 /// Return true if the call can return twice
1665 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1666 void setCanReturnTwice() {
1667 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1670 // Methods for support type inquiry through isa, cast, and dyn_cast:
1671 static bool classof(const Instruction *I) {
1672 return I->getOpcode() == Instruction::Call;
1674 static bool classof(const Value *V) {
1675 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1678 /// Updates profile metadata by scaling it by \p S / \p T.
1679 void updateProfWeight(uint64_t S, uint64_t T);
1681 private:
1682 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1683 // method so that subclasses cannot accidentally use it.
1684 void setInstructionSubclassData(unsigned short D) {
1685 Instruction::setInstructionSubclassData(D);
1689 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1690 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1691 BasicBlock *InsertAtEnd)
1692 : CallBase(Ty->getReturnType(), Instruction::Call,
1693 OperandTraits<CallBase>::op_end(this) -
1694 (Args.size() + CountBundleInputs(Bundles) + 1),
1695 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1696 InsertAtEnd) {
1697 init(Ty, Func, Args, Bundles, NameStr);
1700 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1701 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1702 Instruction *InsertBefore)
1703 : CallBase(Ty->getReturnType(), Instruction::Call,
1704 OperandTraits<CallBase>::op_end(this) -
1705 (Args.size() + CountBundleInputs(Bundles) + 1),
1706 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1707 InsertBefore) {
1708 init(Ty, Func, Args, Bundles, NameStr);
1711 //===----------------------------------------------------------------------===//
1712 // SelectInst Class
1713 //===----------------------------------------------------------------------===//
1715 /// This class represents the LLVM 'select' instruction.
1717 class SelectInst : public Instruction {
1718 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1719 Instruction *InsertBefore)
1720 : Instruction(S1->getType(), Instruction::Select,
1721 &Op<0>(), 3, InsertBefore) {
1722 init(C, S1, S2);
1723 setName(NameStr);
1726 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1727 BasicBlock *InsertAtEnd)
1728 : Instruction(S1->getType(), Instruction::Select,
1729 &Op<0>(), 3, InsertAtEnd) {
1730 init(C, S1, S2);
1731 setName(NameStr);
1734 void init(Value *C, Value *S1, Value *S2) {
1735 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1736 Op<0>() = C;
1737 Op<1>() = S1;
1738 Op<2>() = S2;
1741 protected:
1742 // Note: Instruction needs to be a friend here to call cloneImpl.
1743 friend class Instruction;
1745 SelectInst *cloneImpl() const;
1747 public:
1748 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1749 const Twine &NameStr = "",
1750 Instruction *InsertBefore = nullptr,
1751 Instruction *MDFrom = nullptr) {
1752 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1753 if (MDFrom)
1754 Sel->copyMetadata(*MDFrom);
1755 return Sel;
1758 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1759 const Twine &NameStr,
1760 BasicBlock *InsertAtEnd) {
1761 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1764 const Value *getCondition() const { return Op<0>(); }
1765 const Value *getTrueValue() const { return Op<1>(); }
1766 const Value *getFalseValue() const { return Op<2>(); }
1767 Value *getCondition() { return Op<0>(); }
1768 Value *getTrueValue() { return Op<1>(); }
1769 Value *getFalseValue() { return Op<2>(); }
1771 void setCondition(Value *V) { Op<0>() = V; }
1772 void setTrueValue(Value *V) { Op<1>() = V; }
1773 void setFalseValue(Value *V) { Op<2>() = V; }
1775 /// Swap the true and false values of the select instruction.
1776 /// This doesn't swap prof metadata.
1777 void swapValues() { Op<1>().swap(Op<2>()); }
1779 /// Return a string if the specified operands are invalid
1780 /// for a select operation, otherwise return null.
1781 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1783 /// Transparently provide more efficient getOperand methods.
1784 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1786 OtherOps getOpcode() const {
1787 return static_cast<OtherOps>(Instruction::getOpcode());
1790 // Methods for support type inquiry through isa, cast, and dyn_cast:
1791 static bool classof(const Instruction *I) {
1792 return I->getOpcode() == Instruction::Select;
1794 static bool classof(const Value *V) {
1795 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1799 template <>
1800 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1803 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1805 //===----------------------------------------------------------------------===//
1806 // VAArgInst Class
1807 //===----------------------------------------------------------------------===//
1809 /// This class represents the va_arg llvm instruction, which returns
1810 /// an argument of the specified type given a va_list and increments that list
1812 class VAArgInst : public UnaryInstruction {
1813 protected:
1814 // Note: Instruction needs to be a friend here to call cloneImpl.
1815 friend class Instruction;
1817 VAArgInst *cloneImpl() const;
1819 public:
1820 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1821 Instruction *InsertBefore = nullptr)
1822 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1823 setName(NameStr);
1826 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1827 BasicBlock *InsertAtEnd)
1828 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1829 setName(NameStr);
1832 Value *getPointerOperand() { return getOperand(0); }
1833 const Value *getPointerOperand() const { return getOperand(0); }
1834 static unsigned getPointerOperandIndex() { return 0U; }
1836 // Methods for support type inquiry through isa, cast, and dyn_cast:
1837 static bool classof(const Instruction *I) {
1838 return I->getOpcode() == VAArg;
1840 static bool classof(const Value *V) {
1841 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1845 //===----------------------------------------------------------------------===//
1846 // ExtractElementInst Class
1847 //===----------------------------------------------------------------------===//
1849 /// This instruction extracts a single (scalar)
1850 /// element from a VectorType value
1852 class ExtractElementInst : public Instruction {
1853 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1854 Instruction *InsertBefore = nullptr);
1855 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1856 BasicBlock *InsertAtEnd);
1858 protected:
1859 // Note: Instruction needs to be a friend here to call cloneImpl.
1860 friend class Instruction;
1862 ExtractElementInst *cloneImpl() const;
1864 public:
1865 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1866 const Twine &NameStr = "",
1867 Instruction *InsertBefore = nullptr) {
1868 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1871 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1872 const Twine &NameStr,
1873 BasicBlock *InsertAtEnd) {
1874 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1877 /// Return true if an extractelement instruction can be
1878 /// formed with the specified operands.
1879 static bool isValidOperands(const Value *Vec, const Value *Idx);
1881 Value *getVectorOperand() { return Op<0>(); }
1882 Value *getIndexOperand() { return Op<1>(); }
1883 const Value *getVectorOperand() const { return Op<0>(); }
1884 const Value *getIndexOperand() const { return Op<1>(); }
1886 VectorType *getVectorOperandType() const {
1887 return cast<VectorType>(getVectorOperand()->getType());
1890 /// Transparently provide more efficient getOperand methods.
1891 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1893 // Methods for support type inquiry through isa, cast, and dyn_cast:
1894 static bool classof(const Instruction *I) {
1895 return I->getOpcode() == Instruction::ExtractElement;
1897 static bool classof(const Value *V) {
1898 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1902 template <>
1903 struct OperandTraits<ExtractElementInst> :
1904 public FixedNumOperandTraits<ExtractElementInst, 2> {
1907 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1909 //===----------------------------------------------------------------------===//
1910 // InsertElementInst Class
1911 //===----------------------------------------------------------------------===//
1913 /// This instruction inserts a single (scalar)
1914 /// element into a VectorType value
1916 class InsertElementInst : public Instruction {
1917 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1918 const Twine &NameStr = "",
1919 Instruction *InsertBefore = nullptr);
1920 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1921 BasicBlock *InsertAtEnd);
1923 protected:
1924 // Note: Instruction needs to be a friend here to call cloneImpl.
1925 friend class Instruction;
1927 InsertElementInst *cloneImpl() const;
1929 public:
1930 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1931 const Twine &NameStr = "",
1932 Instruction *InsertBefore = nullptr) {
1933 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1936 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1937 const Twine &NameStr,
1938 BasicBlock *InsertAtEnd) {
1939 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1942 /// Return true if an insertelement instruction can be
1943 /// formed with the specified operands.
1944 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1945 const Value *Idx);
1947 /// Overload to return most specific vector type.
1949 VectorType *getType() const {
1950 return cast<VectorType>(Instruction::getType());
1953 /// Transparently provide more efficient getOperand methods.
1954 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1956 // Methods for support type inquiry through isa, cast, and dyn_cast:
1957 static bool classof(const Instruction *I) {
1958 return I->getOpcode() == Instruction::InsertElement;
1960 static bool classof(const Value *V) {
1961 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1965 template <>
1966 struct OperandTraits<InsertElementInst> :
1967 public FixedNumOperandTraits<InsertElementInst, 3> {
1970 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
1972 //===----------------------------------------------------------------------===//
1973 // ShuffleVectorInst Class
1974 //===----------------------------------------------------------------------===//
1976 /// This instruction constructs a fixed permutation of two
1977 /// input vectors.
1979 class ShuffleVectorInst : public Instruction {
1980 protected:
1981 // Note: Instruction needs to be a friend here to call cloneImpl.
1982 friend class Instruction;
1984 ShuffleVectorInst *cloneImpl() const;
1986 public:
1987 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1988 const Twine &NameStr = "",
1989 Instruction *InsertBefor = nullptr);
1990 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1991 const Twine &NameStr, BasicBlock *InsertAtEnd);
1993 // allocate space for exactly three operands
1994 void *operator new(size_t s) {
1995 return User::operator new(s, 3);
1998 /// Swap the first 2 operands and adjust the mask to preserve the semantics
1999 /// of the instruction.
2000 void commute();
2002 /// Return true if a shufflevector instruction can be
2003 /// formed with the specified operands.
2004 static bool isValidOperands(const Value *V1, const Value *V2,
2005 const Value *Mask);
2007 /// Overload to return most specific vector type.
2009 VectorType *getType() const {
2010 return cast<VectorType>(Instruction::getType());
2013 /// Transparently provide more efficient getOperand methods.
2014 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2016 Constant *getMask() const {
2017 return cast<Constant>(getOperand(2));
2020 /// Return the shuffle mask value for the specified element of the mask.
2021 /// Return -1 if the element is undef.
2022 static int getMaskValue(const Constant *Mask, unsigned Elt);
2024 /// Return the shuffle mask value of this instruction for the given element
2025 /// index. Return -1 if the element is undef.
2026 int getMaskValue(unsigned Elt) const {
2027 return getMaskValue(getMask(), Elt);
2030 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2031 /// elements of the mask are returned as -1.
2032 static void getShuffleMask(const Constant *Mask,
2033 SmallVectorImpl<int> &Result);
2035 /// Return the mask for this instruction as a vector of integers. Undefined
2036 /// elements of the mask are returned as -1.
2037 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2038 return getShuffleMask(getMask(), Result);
2041 SmallVector<int, 16> getShuffleMask() const {
2042 SmallVector<int, 16> Mask;
2043 getShuffleMask(Mask);
2044 return Mask;
2047 /// Return true if this shuffle returns a vector with a different number of
2048 /// elements than its source vectors.
2049 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2050 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2051 bool changesLength() const {
2052 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2053 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2054 return NumSourceElts != NumMaskElts;
2057 /// Return true if this shuffle returns a vector with a greater number of
2058 /// elements than its source vectors.
2059 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2060 bool increasesLength() const {
2061 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2062 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2063 return NumSourceElts < NumMaskElts;
2066 /// Return true if this shuffle mask chooses elements from exactly one source
2067 /// vector.
2068 /// Example: <7,5,undef,7>
2069 /// This assumes that vector operands are the same length as the mask.
2070 static bool isSingleSourceMask(ArrayRef<int> Mask);
2071 static bool isSingleSourceMask(const Constant *Mask) {
2072 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2073 SmallVector<int, 16> MaskAsInts;
2074 getShuffleMask(Mask, MaskAsInts);
2075 return isSingleSourceMask(MaskAsInts);
2078 /// Return true if this shuffle chooses elements from exactly one source
2079 /// vector without changing the length of that vector.
2080 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2081 /// TODO: Optionally allow length-changing shuffles.
2082 bool isSingleSource() const {
2083 return !changesLength() && isSingleSourceMask(getMask());
2086 /// Return true if this shuffle mask chooses elements from exactly one source
2087 /// vector without lane crossings. A shuffle using this mask is not
2088 /// necessarily a no-op because it may change the number of elements from its
2089 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2090 /// Example: <undef,undef,2,3>
2091 static bool isIdentityMask(ArrayRef<int> Mask);
2092 static bool isIdentityMask(const Constant *Mask) {
2093 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2094 SmallVector<int, 16> MaskAsInts;
2095 getShuffleMask(Mask, MaskAsInts);
2096 return isIdentityMask(MaskAsInts);
2099 /// Return true if this shuffle chooses elements from exactly one source
2100 /// vector without lane crossings and does not change the number of elements
2101 /// from its input vectors.
2102 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2103 bool isIdentity() const {
2104 return !changesLength() && isIdentityMask(getShuffleMask());
2107 /// Return true if this shuffle lengthens exactly one source vector with
2108 /// undefs in the high elements.
2109 bool isIdentityWithPadding() const;
2111 /// Return true if this shuffle extracts the first N elements of exactly one
2112 /// source vector.
2113 bool isIdentityWithExtract() const;
2115 /// Return true if this shuffle concatenates its 2 source vectors. This
2116 /// returns false if either input is undefined. In that case, the shuffle is
2117 /// is better classified as an identity with padding operation.
2118 bool isConcat() const;
2120 /// Return true if this shuffle mask chooses elements from its source vectors
2121 /// without lane crossings. A shuffle using this mask would be
2122 /// equivalent to a vector select with a constant condition operand.
2123 /// Example: <4,1,6,undef>
2124 /// This returns false if the mask does not choose from both input vectors.
2125 /// In that case, the shuffle is better classified as an identity shuffle.
2126 /// This assumes that vector operands are the same length as the mask
2127 /// (a length-changing shuffle can never be equivalent to a vector select).
2128 static bool isSelectMask(ArrayRef<int> Mask);
2129 static bool isSelectMask(const Constant *Mask) {
2130 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2131 SmallVector<int, 16> MaskAsInts;
2132 getShuffleMask(Mask, MaskAsInts);
2133 return isSelectMask(MaskAsInts);
2136 /// Return true if this shuffle chooses elements from its source vectors
2137 /// without lane crossings and all operands have the same number of elements.
2138 /// In other words, this shuffle is equivalent to a vector select with a
2139 /// constant condition operand.
2140 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2141 /// This returns false if the mask does not choose from both input vectors.
2142 /// In that case, the shuffle is better classified as an identity shuffle.
2143 /// TODO: Optionally allow length-changing shuffles.
2144 bool isSelect() const {
2145 return !changesLength() && isSelectMask(getMask());
2148 /// Return true if this shuffle mask swaps the order of elements from exactly
2149 /// one source vector.
2150 /// Example: <7,6,undef,4>
2151 /// This assumes that vector operands are the same length as the mask.
2152 static bool isReverseMask(ArrayRef<int> Mask);
2153 static bool isReverseMask(const Constant *Mask) {
2154 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2155 SmallVector<int, 16> MaskAsInts;
2156 getShuffleMask(Mask, MaskAsInts);
2157 return isReverseMask(MaskAsInts);
2160 /// Return true if this shuffle swaps the order of elements from exactly
2161 /// one source vector.
2162 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2163 /// TODO: Optionally allow length-changing shuffles.
2164 bool isReverse() const {
2165 return !changesLength() && isReverseMask(getMask());
2168 /// Return true if this shuffle mask chooses all elements with the same value
2169 /// as the first element of exactly one source vector.
2170 /// Example: <4,undef,undef,4>
2171 /// This assumes that vector operands are the same length as the mask.
2172 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2173 static bool isZeroEltSplatMask(const Constant *Mask) {
2174 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2175 SmallVector<int, 16> MaskAsInts;
2176 getShuffleMask(Mask, MaskAsInts);
2177 return isZeroEltSplatMask(MaskAsInts);
2180 /// Return true if all elements of this shuffle are the same value as the
2181 /// first element of exactly one source vector without changing the length
2182 /// of that vector.
2183 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2184 /// TODO: Optionally allow length-changing shuffles.
2185 /// TODO: Optionally allow splats from other elements.
2186 bool isZeroEltSplat() const {
2187 return !changesLength() && isZeroEltSplatMask(getMask());
2190 /// Return true if this shuffle mask is a transpose mask.
2191 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2192 /// even- or odd-numbered vector elements from two n-dimensional source
2193 /// vectors and write each result into consecutive elements of an
2194 /// n-dimensional destination vector. Two shuffles are necessary to complete
2195 /// the transpose, one for the even elements and another for the odd elements.
2196 /// This description closely follows how the TRN1 and TRN2 AArch64
2197 /// instructions operate.
2199 /// For example, a simple 2x2 matrix can be transposed with:
2201 /// ; Original matrix
2202 /// m0 = < a, b >
2203 /// m1 = < c, d >
2205 /// ; Transposed matrix
2206 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2207 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2209 /// For matrices having greater than n columns, the resulting nx2 transposed
2210 /// matrix is stored in two result vectors such that one vector contains
2211 /// interleaved elements from all the even-numbered rows and the other vector
2212 /// contains interleaved elements from all the odd-numbered rows. For example,
2213 /// a 2x4 matrix can be transposed with:
2215 /// ; Original matrix
2216 /// m0 = < a, b, c, d >
2217 /// m1 = < e, f, g, h >
2219 /// ; Transposed matrix
2220 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2221 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2222 static bool isTransposeMask(ArrayRef<int> Mask);
2223 static bool isTransposeMask(const Constant *Mask) {
2224 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2225 SmallVector<int, 16> MaskAsInts;
2226 getShuffleMask(Mask, MaskAsInts);
2227 return isTransposeMask(MaskAsInts);
2230 /// Return true if this shuffle transposes the elements of its inputs without
2231 /// changing the length of the vectors. This operation may also be known as a
2232 /// merge or interleave. See the description for isTransposeMask() for the
2233 /// exact specification.
2234 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2235 bool isTranspose() const {
2236 return !changesLength() && isTransposeMask(getMask());
2239 /// Return true if this shuffle mask is an extract subvector mask.
2240 /// A valid extract subvector mask returns a smaller vector from a single
2241 /// source operand. The base extraction index is returned as well.
2242 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2243 int &Index);
2244 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2245 int &Index) {
2246 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2247 SmallVector<int, 16> MaskAsInts;
2248 getShuffleMask(Mask, MaskAsInts);
2249 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2252 /// Return true if this shuffle mask is an extract subvector mask.
2253 bool isExtractSubvectorMask(int &Index) const {
2254 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2255 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2258 /// Change values in a shuffle permute mask assuming the two vector operands
2259 /// of length InVecNumElts have swapped position.
2260 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2261 unsigned InVecNumElts) {
2262 for (int &Idx : Mask) {
2263 if (Idx == -1)
2264 continue;
2265 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2266 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2267 "shufflevector mask index out of range");
2271 // Methods for support type inquiry through isa, cast, and dyn_cast:
2272 static bool classof(const Instruction *I) {
2273 return I->getOpcode() == Instruction::ShuffleVector;
2275 static bool classof(const Value *V) {
2276 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2280 template <>
2281 struct OperandTraits<ShuffleVectorInst> :
2282 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2285 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2287 //===----------------------------------------------------------------------===//
2288 // ExtractValueInst Class
2289 //===----------------------------------------------------------------------===//
2291 /// This instruction extracts a struct member or array
2292 /// element value from an aggregate value.
2294 class ExtractValueInst : public UnaryInstruction {
2295 SmallVector<unsigned, 4> Indices;
2297 ExtractValueInst(const ExtractValueInst &EVI);
2299 /// Constructors - Create a extractvalue instruction with a base aggregate
2300 /// value and a list of indices. The first ctor can optionally insert before
2301 /// an existing instruction, the second appends the new instruction to the
2302 /// specified BasicBlock.
2303 inline ExtractValueInst(Value *Agg,
2304 ArrayRef<unsigned> Idxs,
2305 const Twine &NameStr,
2306 Instruction *InsertBefore);
2307 inline ExtractValueInst(Value *Agg,
2308 ArrayRef<unsigned> Idxs,
2309 const Twine &NameStr, BasicBlock *InsertAtEnd);
2311 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2313 protected:
2314 // Note: Instruction needs to be a friend here to call cloneImpl.
2315 friend class Instruction;
2317 ExtractValueInst *cloneImpl() const;
2319 public:
2320 static ExtractValueInst *Create(Value *Agg,
2321 ArrayRef<unsigned> Idxs,
2322 const Twine &NameStr = "",
2323 Instruction *InsertBefore = nullptr) {
2324 return new
2325 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2328 static ExtractValueInst *Create(Value *Agg,
2329 ArrayRef<unsigned> Idxs,
2330 const Twine &NameStr,
2331 BasicBlock *InsertAtEnd) {
2332 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2335 /// Returns the type of the element that would be extracted
2336 /// with an extractvalue instruction with the specified parameters.
2338 /// Null is returned if the indices are invalid for the specified type.
2339 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2341 using idx_iterator = const unsigned*;
2343 inline idx_iterator idx_begin() const { return Indices.begin(); }
2344 inline idx_iterator idx_end() const { return Indices.end(); }
2345 inline iterator_range<idx_iterator> indices() const {
2346 return make_range(idx_begin(), idx_end());
2349 Value *getAggregateOperand() {
2350 return getOperand(0);
2352 const Value *getAggregateOperand() const {
2353 return getOperand(0);
2355 static unsigned getAggregateOperandIndex() {
2356 return 0U; // get index for modifying correct operand
2359 ArrayRef<unsigned> getIndices() const {
2360 return Indices;
2363 unsigned getNumIndices() const {
2364 return (unsigned)Indices.size();
2367 bool hasIndices() const {
2368 return true;
2371 // Methods for support type inquiry through isa, cast, and dyn_cast:
2372 static bool classof(const Instruction *I) {
2373 return I->getOpcode() == Instruction::ExtractValue;
2375 static bool classof(const Value *V) {
2376 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2380 ExtractValueInst::ExtractValueInst(Value *Agg,
2381 ArrayRef<unsigned> Idxs,
2382 const Twine &NameStr,
2383 Instruction *InsertBefore)
2384 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2385 ExtractValue, Agg, InsertBefore) {
2386 init(Idxs, NameStr);
2389 ExtractValueInst::ExtractValueInst(Value *Agg,
2390 ArrayRef<unsigned> Idxs,
2391 const Twine &NameStr,
2392 BasicBlock *InsertAtEnd)
2393 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2394 ExtractValue, Agg, InsertAtEnd) {
2395 init(Idxs, NameStr);
2398 //===----------------------------------------------------------------------===//
2399 // InsertValueInst Class
2400 //===----------------------------------------------------------------------===//
2402 /// This instruction inserts a struct field of array element
2403 /// value into an aggregate value.
2405 class InsertValueInst : public Instruction {
2406 SmallVector<unsigned, 4> Indices;
2408 InsertValueInst(const InsertValueInst &IVI);
2410 /// Constructors - Create a insertvalue instruction with a base aggregate
2411 /// value, a value to insert, and a list of indices. The first ctor can
2412 /// optionally insert before an existing instruction, the second appends
2413 /// the new instruction to the specified BasicBlock.
2414 inline InsertValueInst(Value *Agg, Value *Val,
2415 ArrayRef<unsigned> Idxs,
2416 const Twine &NameStr,
2417 Instruction *InsertBefore);
2418 inline InsertValueInst(Value *Agg, Value *Val,
2419 ArrayRef<unsigned> Idxs,
2420 const Twine &NameStr, BasicBlock *InsertAtEnd);
2422 /// Constructors - These two constructors are convenience methods because one
2423 /// and two index insertvalue instructions are so common.
2424 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2425 const Twine &NameStr = "",
2426 Instruction *InsertBefore = nullptr);
2427 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2428 BasicBlock *InsertAtEnd);
2430 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2431 const Twine &NameStr);
2433 protected:
2434 // Note: Instruction needs to be a friend here to call cloneImpl.
2435 friend class Instruction;
2437 InsertValueInst *cloneImpl() const;
2439 public:
2440 // allocate space for exactly two operands
2441 void *operator new(size_t s) {
2442 return User::operator new(s, 2);
2445 static InsertValueInst *Create(Value *Agg, Value *Val,
2446 ArrayRef<unsigned> Idxs,
2447 const Twine &NameStr = "",
2448 Instruction *InsertBefore = nullptr) {
2449 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2452 static InsertValueInst *Create(Value *Agg, Value *Val,
2453 ArrayRef<unsigned> Idxs,
2454 const Twine &NameStr,
2455 BasicBlock *InsertAtEnd) {
2456 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2459 /// Transparently provide more efficient getOperand methods.
2460 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2462 using idx_iterator = const unsigned*;
2464 inline idx_iterator idx_begin() const { return Indices.begin(); }
2465 inline idx_iterator idx_end() const { return Indices.end(); }
2466 inline iterator_range<idx_iterator> indices() const {
2467 return make_range(idx_begin(), idx_end());
2470 Value *getAggregateOperand() {
2471 return getOperand(0);
2473 const Value *getAggregateOperand() const {
2474 return getOperand(0);
2476 static unsigned getAggregateOperandIndex() {
2477 return 0U; // get index for modifying correct operand
2480 Value *getInsertedValueOperand() {
2481 return getOperand(1);
2483 const Value *getInsertedValueOperand() const {
2484 return getOperand(1);
2486 static unsigned getInsertedValueOperandIndex() {
2487 return 1U; // get index for modifying correct operand
2490 ArrayRef<unsigned> getIndices() const {
2491 return Indices;
2494 unsigned getNumIndices() const {
2495 return (unsigned)Indices.size();
2498 bool hasIndices() const {
2499 return true;
2502 // Methods for support type inquiry through isa, cast, and dyn_cast:
2503 static bool classof(const Instruction *I) {
2504 return I->getOpcode() == Instruction::InsertValue;
2506 static bool classof(const Value *V) {
2507 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2511 template <>
2512 struct OperandTraits<InsertValueInst> :
2513 public FixedNumOperandTraits<InsertValueInst, 2> {
2516 InsertValueInst::InsertValueInst(Value *Agg,
2517 Value *Val,
2518 ArrayRef<unsigned> Idxs,
2519 const Twine &NameStr,
2520 Instruction *InsertBefore)
2521 : Instruction(Agg->getType(), InsertValue,
2522 OperandTraits<InsertValueInst>::op_begin(this),
2523 2, InsertBefore) {
2524 init(Agg, Val, Idxs, NameStr);
2527 InsertValueInst::InsertValueInst(Value *Agg,
2528 Value *Val,
2529 ArrayRef<unsigned> Idxs,
2530 const Twine &NameStr,
2531 BasicBlock *InsertAtEnd)
2532 : Instruction(Agg->getType(), InsertValue,
2533 OperandTraits<InsertValueInst>::op_begin(this),
2534 2, InsertAtEnd) {
2535 init(Agg, Val, Idxs, NameStr);
2538 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2540 //===----------------------------------------------------------------------===//
2541 // PHINode Class
2542 //===----------------------------------------------------------------------===//
2544 // PHINode - The PHINode class is used to represent the magical mystical PHI
2545 // node, that can not exist in nature, but can be synthesized in a computer
2546 // scientist's overactive imagination.
2548 class PHINode : public Instruction {
2549 /// The number of operands actually allocated. NumOperands is
2550 /// the number actually in use.
2551 unsigned ReservedSpace;
2553 PHINode(const PHINode &PN);
2555 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2556 const Twine &NameStr = "",
2557 Instruction *InsertBefore = nullptr)
2558 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2559 ReservedSpace(NumReservedValues) {
2560 setName(NameStr);
2561 allocHungoffUses(ReservedSpace);
2564 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2565 BasicBlock *InsertAtEnd)
2566 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2567 ReservedSpace(NumReservedValues) {
2568 setName(NameStr);
2569 allocHungoffUses(ReservedSpace);
2572 protected:
2573 // Note: Instruction needs to be a friend here to call cloneImpl.
2574 friend class Instruction;
2576 PHINode *cloneImpl() const;
2578 // allocHungoffUses - this is more complicated than the generic
2579 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2580 // values and pointers to the incoming blocks, all in one allocation.
2581 void allocHungoffUses(unsigned N) {
2582 User::allocHungoffUses(N, /* IsPhi */ true);
2585 public:
2586 /// Constructors - NumReservedValues is a hint for the number of incoming
2587 /// edges that this phi node will have (use 0 if you really have no idea).
2588 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2589 const Twine &NameStr = "",
2590 Instruction *InsertBefore = nullptr) {
2591 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2594 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2595 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2596 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2599 /// Provide fast operand accessors
2600 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2602 // Block iterator interface. This provides access to the list of incoming
2603 // basic blocks, which parallels the list of incoming values.
2605 using block_iterator = BasicBlock **;
2606 using const_block_iterator = BasicBlock * const *;
2608 block_iterator block_begin() {
2609 Use::UserRef *ref =
2610 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2611 return reinterpret_cast<block_iterator>(ref + 1);
2614 const_block_iterator block_begin() const {
2615 const Use::UserRef *ref =
2616 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2617 return reinterpret_cast<const_block_iterator>(ref + 1);
2620 block_iterator block_end() {
2621 return block_begin() + getNumOperands();
2624 const_block_iterator block_end() const {
2625 return block_begin() + getNumOperands();
2628 iterator_range<block_iterator> blocks() {
2629 return make_range(block_begin(), block_end());
2632 iterator_range<const_block_iterator> blocks() const {
2633 return make_range(block_begin(), block_end());
2636 op_range incoming_values() { return operands(); }
2638 const_op_range incoming_values() const { return operands(); }
2640 /// Return the number of incoming edges
2642 unsigned getNumIncomingValues() const { return getNumOperands(); }
2644 /// Return incoming value number x
2646 Value *getIncomingValue(unsigned i) const {
2647 return getOperand(i);
2649 void setIncomingValue(unsigned i, Value *V) {
2650 assert(V && "PHI node got a null value!");
2651 assert(getType() == V->getType() &&
2652 "All operands to PHI node must be the same type as the PHI node!");
2653 setOperand(i, V);
2656 static unsigned getOperandNumForIncomingValue(unsigned i) {
2657 return i;
2660 static unsigned getIncomingValueNumForOperand(unsigned i) {
2661 return i;
2664 /// Return incoming basic block number @p i.
2666 BasicBlock *getIncomingBlock(unsigned i) const {
2667 return block_begin()[i];
2670 /// Return incoming basic block corresponding
2671 /// to an operand of the PHI.
2673 BasicBlock *getIncomingBlock(const Use &U) const {
2674 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2675 return getIncomingBlock(unsigned(&U - op_begin()));
2678 /// Return incoming basic block corresponding
2679 /// to value use iterator.
2681 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2682 return getIncomingBlock(I.getUse());
2685 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2686 assert(BB && "PHI node got a null basic block!");
2687 block_begin()[i] = BB;
2690 /// Replace every incoming basic block \p Old to basic block \p New.
2691 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
2692 assert(New && Old && "PHI node got a null basic block!");
2693 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2694 if (getIncomingBlock(Op) == Old)
2695 setIncomingBlock(Op, New);
2698 /// Add an incoming value to the end of the PHI list
2700 void addIncoming(Value *V, BasicBlock *BB) {
2701 if (getNumOperands() == ReservedSpace)
2702 growOperands(); // Get more space!
2703 // Initialize some new operands.
2704 setNumHungOffUseOperands(getNumOperands() + 1);
2705 setIncomingValue(getNumOperands() - 1, V);
2706 setIncomingBlock(getNumOperands() - 1, BB);
2709 /// Remove an incoming value. This is useful if a
2710 /// predecessor basic block is deleted. The value removed is returned.
2712 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2713 /// is true), the PHI node is destroyed and any uses of it are replaced with
2714 /// dummy values. The only time there should be zero incoming values to a PHI
2715 /// node is when the block is dead, so this strategy is sound.
2717 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2719 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2720 int Idx = getBasicBlockIndex(BB);
2721 assert(Idx >= 0 && "Invalid basic block argument to remove!");
2722 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2725 /// Return the first index of the specified basic
2726 /// block in the value list for this PHI. Returns -1 if no instance.
2728 int getBasicBlockIndex(const BasicBlock *BB) const {
2729 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2730 if (block_begin()[i] == BB)
2731 return i;
2732 return -1;
2735 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2736 int Idx = getBasicBlockIndex(BB);
2737 assert(Idx >= 0 && "Invalid basic block argument!");
2738 return getIncomingValue(Idx);
2741 /// Set every incoming value(s) for block \p BB to \p V.
2742 void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
2743 assert(BB && "PHI node got a null basic block!");
2744 bool Found = false;
2745 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2746 if (getIncomingBlock(Op) == BB) {
2747 Found = true;
2748 setIncomingValue(Op, V);
2750 (void)Found;
2751 assert(Found && "Invalid basic block argument to set!");
2754 /// If the specified PHI node always merges together the
2755 /// same value, return the value, otherwise return null.
2756 Value *hasConstantValue() const;
2758 /// Whether the specified PHI node always merges
2759 /// together the same value, assuming undefs are equal to a unique
2760 /// non-undef value.
2761 bool hasConstantOrUndefValue() const;
2763 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2764 static bool classof(const Instruction *I) {
2765 return I->getOpcode() == Instruction::PHI;
2767 static bool classof(const Value *V) {
2768 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2771 private:
2772 void growOperands();
2775 template <>
2776 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2779 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2781 //===----------------------------------------------------------------------===//
2782 // LandingPadInst Class
2783 //===----------------------------------------------------------------------===//
2785 //===---------------------------------------------------------------------------
2786 /// The landingpad instruction holds all of the information
2787 /// necessary to generate correct exception handling. The landingpad instruction
2788 /// cannot be moved from the top of a landing pad block, which itself is
2789 /// accessible only from the 'unwind' edge of an invoke. This uses the
2790 /// SubclassData field in Value to store whether or not the landingpad is a
2791 /// cleanup.
2793 class LandingPadInst : public Instruction {
2794 /// The number of operands actually allocated. NumOperands is
2795 /// the number actually in use.
2796 unsigned ReservedSpace;
2798 LandingPadInst(const LandingPadInst &LP);
2800 public:
2801 enum ClauseType { Catch, Filter };
2803 private:
2804 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2805 const Twine &NameStr, Instruction *InsertBefore);
2806 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2807 const Twine &NameStr, BasicBlock *InsertAtEnd);
2809 // Allocate space for exactly zero operands.
2810 void *operator new(size_t s) {
2811 return User::operator new(s);
2814 void growOperands(unsigned Size);
2815 void init(unsigned NumReservedValues, const Twine &NameStr);
2817 protected:
2818 // Note: Instruction needs to be a friend here to call cloneImpl.
2819 friend class Instruction;
2821 LandingPadInst *cloneImpl() const;
2823 public:
2824 /// Constructors - NumReservedClauses is a hint for the number of incoming
2825 /// clauses that this landingpad will have (use 0 if you really have no idea).
2826 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2827 const Twine &NameStr = "",
2828 Instruction *InsertBefore = nullptr);
2829 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2830 const Twine &NameStr, BasicBlock *InsertAtEnd);
2832 /// Provide fast operand accessors
2833 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2835 /// Return 'true' if this landingpad instruction is a
2836 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2837 /// doesn't catch the exception.
2838 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2840 /// Indicate that this landingpad instruction is a cleanup.
2841 void setCleanup(bool V) {
2842 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2843 (V ? 1 : 0));
2846 /// Add a catch or filter clause to the landing pad.
2847 void addClause(Constant *ClauseVal);
2849 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2850 /// determine what type of clause this is.
2851 Constant *getClause(unsigned Idx) const {
2852 return cast<Constant>(getOperandList()[Idx]);
2855 /// Return 'true' if the clause and index Idx is a catch clause.
2856 bool isCatch(unsigned Idx) const {
2857 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2860 /// Return 'true' if the clause and index Idx is a filter clause.
2861 bool isFilter(unsigned Idx) const {
2862 return isa<ArrayType>(getOperandList()[Idx]->getType());
2865 /// Get the number of clauses for this landing pad.
2866 unsigned getNumClauses() const { return getNumOperands(); }
2868 /// Grow the size of the operand list to accommodate the new
2869 /// number of clauses.
2870 void reserveClauses(unsigned Size) { growOperands(Size); }
2872 // Methods for support type inquiry through isa, cast, and dyn_cast:
2873 static bool classof(const Instruction *I) {
2874 return I->getOpcode() == Instruction::LandingPad;
2876 static bool classof(const Value *V) {
2877 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2881 template <>
2882 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2885 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2887 //===----------------------------------------------------------------------===//
2888 // ReturnInst Class
2889 //===----------------------------------------------------------------------===//
2891 //===---------------------------------------------------------------------------
2892 /// Return a value (possibly void), from a function. Execution
2893 /// does not continue in this function any longer.
2895 class ReturnInst : public Instruction {
2896 ReturnInst(const ReturnInst &RI);
2898 private:
2899 // ReturnInst constructors:
2900 // ReturnInst() - 'ret void' instruction
2901 // ReturnInst( null) - 'ret void' instruction
2902 // ReturnInst(Value* X) - 'ret X' instruction
2903 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2904 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2905 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2906 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2908 // NOTE: If the Value* passed is of type void then the constructor behaves as
2909 // if it was passed NULL.
2910 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2911 Instruction *InsertBefore = nullptr);
2912 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2913 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2915 protected:
2916 // Note: Instruction needs to be a friend here to call cloneImpl.
2917 friend class Instruction;
2919 ReturnInst *cloneImpl() const;
2921 public:
2922 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2923 Instruction *InsertBefore = nullptr) {
2924 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2927 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2928 BasicBlock *InsertAtEnd) {
2929 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2932 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2933 return new(0) ReturnInst(C, InsertAtEnd);
2936 /// Provide fast operand accessors
2937 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2939 /// Convenience accessor. Returns null if there is no return value.
2940 Value *getReturnValue() const {
2941 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2944 unsigned getNumSuccessors() const { return 0; }
2946 // Methods for support type inquiry through isa, cast, and dyn_cast:
2947 static bool classof(const Instruction *I) {
2948 return (I->getOpcode() == Instruction::Ret);
2950 static bool classof(const Value *V) {
2951 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2954 private:
2955 BasicBlock *getSuccessor(unsigned idx) const {
2956 llvm_unreachable("ReturnInst has no successors!");
2959 void setSuccessor(unsigned idx, BasicBlock *B) {
2960 llvm_unreachable("ReturnInst has no successors!");
2964 template <>
2965 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2968 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2970 //===----------------------------------------------------------------------===//
2971 // BranchInst Class
2972 //===----------------------------------------------------------------------===//
2974 //===---------------------------------------------------------------------------
2975 /// Conditional or Unconditional Branch instruction.
2977 class BranchInst : public Instruction {
2978 /// Ops list - Branches are strange. The operands are ordered:
2979 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2980 /// they don't have to check for cond/uncond branchness. These are mostly
2981 /// accessed relative from op_end().
2982 BranchInst(const BranchInst &BI);
2983 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2984 // BranchInst(BB *B) - 'br B'
2985 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2986 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2987 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2988 // BranchInst(BB* B, BB *I) - 'br B' insert at end
2989 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2990 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2991 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2992 Instruction *InsertBefore = nullptr);
2993 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2994 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2995 BasicBlock *InsertAtEnd);
2997 void AssertOK();
2999 protected:
3000 // Note: Instruction needs to be a friend here to call cloneImpl.
3001 friend class Instruction;
3003 BranchInst *cloneImpl() const;
3005 public:
3006 /// Iterator type that casts an operand to a basic block.
3008 /// This only makes sense because the successors are stored as adjacent
3009 /// operands for branch instructions.
3010 struct succ_op_iterator
3011 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3012 std::random_access_iterator_tag, BasicBlock *,
3013 ptrdiff_t, BasicBlock *, BasicBlock *> {
3014 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3016 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3017 BasicBlock *operator->() const { return operator*(); }
3020 /// The const version of `succ_op_iterator`.
3021 struct const_succ_op_iterator
3022 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3023 std::random_access_iterator_tag,
3024 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3025 const BasicBlock *> {
3026 explicit const_succ_op_iterator(const_value_op_iterator I)
3027 : iterator_adaptor_base(I) {}
3029 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3030 const BasicBlock *operator->() const { return operator*(); }
3033 static BranchInst *Create(BasicBlock *IfTrue,
3034 Instruction *InsertBefore = nullptr) {
3035 return new(1) BranchInst(IfTrue, InsertBefore);
3038 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3039 Value *Cond, Instruction *InsertBefore = nullptr) {
3040 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3043 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3044 return new(1) BranchInst(IfTrue, InsertAtEnd);
3047 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3048 Value *Cond, BasicBlock *InsertAtEnd) {
3049 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3052 /// Transparently provide more efficient getOperand methods.
3053 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3055 bool isUnconditional() const { return getNumOperands() == 1; }
3056 bool isConditional() const { return getNumOperands() == 3; }
3058 Value *getCondition() const {
3059 assert(isConditional() && "Cannot get condition of an uncond branch!");
3060 return Op<-3>();
3063 void setCondition(Value *V) {
3064 assert(isConditional() && "Cannot set condition of unconditional branch!");
3065 Op<-3>() = V;
3068 unsigned getNumSuccessors() const { return 1+isConditional(); }
3070 BasicBlock *getSuccessor(unsigned i) const {
3071 assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3072 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3075 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3076 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3077 *(&Op<-1>() - idx) = NewSucc;
3080 /// Swap the successors of this branch instruction.
3082 /// Swaps the successors of the branch instruction. This also swaps any
3083 /// branch weight metadata associated with the instruction so that it
3084 /// continues to map correctly to each operand.
3085 void swapSuccessors();
3087 iterator_range<succ_op_iterator> successors() {
3088 return make_range(
3089 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3090 succ_op_iterator(value_op_end()));
3093 iterator_range<const_succ_op_iterator> successors() const {
3094 return make_range(const_succ_op_iterator(
3095 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3096 const_succ_op_iterator(value_op_end()));
3099 // Methods for support type inquiry through isa, cast, and dyn_cast:
3100 static bool classof(const Instruction *I) {
3101 return (I->getOpcode() == Instruction::Br);
3103 static bool classof(const Value *V) {
3104 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3108 template <>
3109 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3112 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
3114 //===----------------------------------------------------------------------===//
3115 // SwitchInst Class
3116 //===----------------------------------------------------------------------===//
3118 //===---------------------------------------------------------------------------
3119 /// Multiway switch
3121 class SwitchInst : public Instruction {
3122 unsigned ReservedSpace;
3124 // Operand[0] = Value to switch on
3125 // Operand[1] = Default basic block destination
3126 // Operand[2n ] = Value to match
3127 // Operand[2n+1] = BasicBlock to go to on match
3128 SwitchInst(const SwitchInst &SI);
3130 /// Create a new switch instruction, specifying a value to switch on and a
3131 /// default destination. The number of additional cases can be specified here
3132 /// to make memory allocation more efficient. This constructor can also
3133 /// auto-insert before another instruction.
3134 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3135 Instruction *InsertBefore);
3137 /// Create a new switch instruction, specifying a value to switch on and a
3138 /// default destination. The number of additional cases can be specified here
3139 /// to make memory allocation more efficient. This constructor also
3140 /// auto-inserts at the end of the specified BasicBlock.
3141 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3142 BasicBlock *InsertAtEnd);
3144 // allocate space for exactly zero operands
3145 void *operator new(size_t s) {
3146 return User::operator new(s);
3149 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3150 void growOperands();
3152 protected:
3153 // Note: Instruction needs to be a friend here to call cloneImpl.
3154 friend class Instruction;
3156 SwitchInst *cloneImpl() const;
3158 public:
3159 // -2
3160 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3162 template <typename CaseHandleT> class CaseIteratorImpl;
3164 /// A handle to a particular switch case. It exposes a convenient interface
3165 /// to both the case value and the successor block.
3167 /// We define this as a template and instantiate it to form both a const and
3168 /// non-const handle.
3169 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3170 class CaseHandleImpl {
3171 // Directly befriend both const and non-const iterators.
3172 friend class SwitchInst::CaseIteratorImpl<
3173 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3175 protected:
3176 // Expose the switch type we're parameterized with to the iterator.
3177 using SwitchInstType = SwitchInstT;
3179 SwitchInstT *SI;
3180 ptrdiff_t Index;
3182 CaseHandleImpl() = default;
3183 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3185 public:
3186 /// Resolves case value for current case.
3187 ConstantIntT *getCaseValue() const {
3188 assert((unsigned)Index < SI->getNumCases() &&
3189 "Index out the number of cases.");
3190 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3193 /// Resolves successor for current case.
3194 BasicBlockT *getCaseSuccessor() const {
3195 assert(((unsigned)Index < SI->getNumCases() ||
3196 (unsigned)Index == DefaultPseudoIndex) &&
3197 "Index out the number of cases.");
3198 return SI->getSuccessor(getSuccessorIndex());
3201 /// Returns number of current case.
3202 unsigned getCaseIndex() const { return Index; }
3204 /// Returns successor index for current case successor.
3205 unsigned getSuccessorIndex() const {
3206 assert(((unsigned)Index == DefaultPseudoIndex ||
3207 (unsigned)Index < SI->getNumCases()) &&
3208 "Index out the number of cases.");
3209 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3212 bool operator==(const CaseHandleImpl &RHS) const {
3213 assert(SI == RHS.SI && "Incompatible operators.");
3214 return Index == RHS.Index;
3218 using ConstCaseHandle =
3219 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3221 class CaseHandle
3222 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3223 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3225 public:
3226 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3228 /// Sets the new value for current case.
3229 void setValue(ConstantInt *V) {
3230 assert((unsigned)Index < SI->getNumCases() &&
3231 "Index out the number of cases.");
3232 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3235 /// Sets the new successor for current case.
3236 void setSuccessor(BasicBlock *S) {
3237 SI->setSuccessor(getSuccessorIndex(), S);
3241 template <typename CaseHandleT>
3242 class CaseIteratorImpl
3243 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3244 std::random_access_iterator_tag,
3245 CaseHandleT> {
3246 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3248 CaseHandleT Case;
3250 public:
3251 /// Default constructed iterator is in an invalid state until assigned to
3252 /// a case for a particular switch.
3253 CaseIteratorImpl() = default;
3255 /// Initializes case iterator for given SwitchInst and for given
3256 /// case number.
3257 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3259 /// Initializes case iterator for given SwitchInst and for given
3260 /// successor index.
3261 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3262 unsigned SuccessorIndex) {
3263 assert(SuccessorIndex < SI->getNumSuccessors() &&
3264 "Successor index # out of range!");
3265 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3266 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3269 /// Support converting to the const variant. This will be a no-op for const
3270 /// variant.
3271 operator CaseIteratorImpl<ConstCaseHandle>() const {
3272 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3275 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3276 // Check index correctness after addition.
3277 // Note: Index == getNumCases() means end().
3278 assert(Case.Index + N >= 0 &&
3279 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3280 "Case.Index out the number of cases.");
3281 Case.Index += N;
3282 return *this;
3284 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3285 // Check index correctness after subtraction.
3286 // Note: Case.Index == getNumCases() means end().
3287 assert(Case.Index - N >= 0 &&
3288 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3289 "Case.Index out the number of cases.");
3290 Case.Index -= N;
3291 return *this;
3293 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3294 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3295 return Case.Index - RHS.Case.Index;
3297 bool operator==(const CaseIteratorImpl &RHS) const {
3298 return Case == RHS.Case;
3300 bool operator<(const CaseIteratorImpl &RHS) const {
3301 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3302 return Case.Index < RHS.Case.Index;
3304 CaseHandleT &operator*() { return Case; }
3305 const CaseHandleT &operator*() const { return Case; }
3308 using CaseIt = CaseIteratorImpl<CaseHandle>;
3309 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3311 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3312 unsigned NumCases,
3313 Instruction *InsertBefore = nullptr) {
3314 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3317 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3318 unsigned NumCases, BasicBlock *InsertAtEnd) {
3319 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3322 /// Provide fast operand accessors
3323 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3325 // Accessor Methods for Switch stmt
3326 Value *getCondition() const { return getOperand(0); }
3327 void setCondition(Value *V) { setOperand(0, V); }
3329 BasicBlock *getDefaultDest() const {
3330 return cast<BasicBlock>(getOperand(1));
3333 void setDefaultDest(BasicBlock *DefaultCase) {
3334 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3337 /// Return the number of 'cases' in this switch instruction, excluding the
3338 /// default case.
3339 unsigned getNumCases() const {
3340 return getNumOperands()/2 - 1;
3343 /// Returns a read/write iterator that points to the first case in the
3344 /// SwitchInst.
3345 CaseIt case_begin() {
3346 return CaseIt(this, 0);
3349 /// Returns a read-only iterator that points to the first case in the
3350 /// SwitchInst.
3351 ConstCaseIt case_begin() const {
3352 return ConstCaseIt(this, 0);
3355 /// Returns a read/write iterator that points one past the last in the
3356 /// SwitchInst.
3357 CaseIt case_end() {
3358 return CaseIt(this, getNumCases());
3361 /// Returns a read-only iterator that points one past the last in the
3362 /// SwitchInst.
3363 ConstCaseIt case_end() const {
3364 return ConstCaseIt(this, getNumCases());
3367 /// Iteration adapter for range-for loops.
3368 iterator_range<CaseIt> cases() {
3369 return make_range(case_begin(), case_end());
3372 /// Constant iteration adapter for range-for loops.
3373 iterator_range<ConstCaseIt> cases() const {
3374 return make_range(case_begin(), case_end());
3377 /// Returns an iterator that points to the default case.
3378 /// Note: this iterator allows to resolve successor only. Attempt
3379 /// to resolve case value causes an assertion.
3380 /// Also note, that increment and decrement also causes an assertion and
3381 /// makes iterator invalid.
3382 CaseIt case_default() {
3383 return CaseIt(this, DefaultPseudoIndex);
3385 ConstCaseIt case_default() const {
3386 return ConstCaseIt(this, DefaultPseudoIndex);
3389 /// Search all of the case values for the specified constant. If it is
3390 /// explicitly handled, return the case iterator of it, otherwise return
3391 /// default case iterator to indicate that it is handled by the default
3392 /// handler.
3393 CaseIt findCaseValue(const ConstantInt *C) {
3394 CaseIt I = llvm::find_if(
3395 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3396 if (I != case_end())
3397 return I;
3399 return case_default();
3401 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3402 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3403 return Case.getCaseValue() == C;
3405 if (I != case_end())
3406 return I;
3408 return case_default();
3411 /// Finds the unique case value for a given successor. Returns null if the
3412 /// successor is not found, not unique, or is the default case.
3413 ConstantInt *findCaseDest(BasicBlock *BB) {
3414 if (BB == getDefaultDest())
3415 return nullptr;
3417 ConstantInt *CI = nullptr;
3418 for (auto Case : cases()) {
3419 if (Case.getCaseSuccessor() != BB)
3420 continue;
3422 if (CI)
3423 return nullptr; // Multiple cases lead to BB.
3425 CI = Case.getCaseValue();
3428 return CI;
3431 /// Add an entry to the switch instruction.
3432 /// Note:
3433 /// This action invalidates case_end(). Old case_end() iterator will
3434 /// point to the added case.
3435 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3437 /// This method removes the specified case and its successor from the switch
3438 /// instruction. Note that this operation may reorder the remaining cases at
3439 /// index idx and above.
3440 /// Note:
3441 /// This action invalidates iterators for all cases following the one removed,
3442 /// including the case_end() iterator. It returns an iterator for the next
3443 /// case.
3444 CaseIt removeCase(CaseIt I);
3446 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3447 BasicBlock *getSuccessor(unsigned idx) const {
3448 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3449 return cast<BasicBlock>(getOperand(idx*2+1));
3451 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3452 assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3453 setOperand(idx * 2 + 1, NewSucc);
3456 // Methods for support type inquiry through isa, cast, and dyn_cast:
3457 static bool classof(const Instruction *I) {
3458 return I->getOpcode() == Instruction::Switch;
3460 static bool classof(const Value *V) {
3461 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3465 /// A wrapper class to simplify modification of SwitchInst cases along with
3466 /// their prof branch_weights metadata.
3467 class SwitchInstProfUpdateWrapper {
3468 SwitchInst &SI;
3469 Optional<SmallVector<uint32_t, 8> > Weights = None;
3470 bool Changed = false;
3472 protected:
3473 static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
3475 MDNode *buildProfBranchWeightsMD();
3477 void init();
3479 public:
3480 using CaseWeightOpt = Optional<uint32_t>;
3481 SwitchInst *operator->() { return &SI; }
3482 SwitchInst &operator*() { return SI; }
3483 operator SwitchInst *() { return &SI; }
3485 SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); }
3487 ~SwitchInstProfUpdateWrapper() {
3488 if (Changed)
3489 SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
3492 /// Delegate the call to the underlying SwitchInst::removeCase() and remove
3493 /// correspondent branch weight.
3494 SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
3496 /// Delegate the call to the underlying SwitchInst::addCase() and set the
3497 /// specified branch weight for the added case.
3498 void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
3500 /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
3501 /// this object to not touch the underlying SwitchInst in destructor.
3502 SymbolTableList<Instruction>::iterator eraseFromParent();
3504 void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
3505 CaseWeightOpt getSuccessorWeight(unsigned idx);
3507 static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
3510 template <>
3511 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3514 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3516 //===----------------------------------------------------------------------===//
3517 // IndirectBrInst Class
3518 //===----------------------------------------------------------------------===//
3520 //===---------------------------------------------------------------------------
3521 /// Indirect Branch Instruction.
3523 class IndirectBrInst : public Instruction {
3524 unsigned ReservedSpace;
3526 // Operand[0] = Address to jump to
3527 // Operand[n+1] = n-th destination
3528 IndirectBrInst(const IndirectBrInst &IBI);
3530 /// Create a new indirectbr instruction, specifying an
3531 /// Address to jump to. The number of expected destinations can be specified
3532 /// here to make memory allocation more efficient. This constructor can also
3533 /// autoinsert before another instruction.
3534 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3536 /// Create a new indirectbr instruction, specifying an
3537 /// Address to jump to. The number of expected destinations can be specified
3538 /// here to make memory allocation more efficient. This constructor also
3539 /// autoinserts at the end of the specified BasicBlock.
3540 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3542 // allocate space for exactly zero operands
3543 void *operator new(size_t s) {
3544 return User::operator new(s);
3547 void init(Value *Address, unsigned NumDests);
3548 void growOperands();
3550 protected:
3551 // Note: Instruction needs to be a friend here to call cloneImpl.
3552 friend class Instruction;
3554 IndirectBrInst *cloneImpl() const;
3556 public:
3557 /// Iterator type that casts an operand to a basic block.
3559 /// This only makes sense because the successors are stored as adjacent
3560 /// operands for indirectbr instructions.
3561 struct succ_op_iterator
3562 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3563 std::random_access_iterator_tag, BasicBlock *,
3564 ptrdiff_t, BasicBlock *, BasicBlock *> {
3565 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3567 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3568 BasicBlock *operator->() const { return operator*(); }
3571 /// The const version of `succ_op_iterator`.
3572 struct const_succ_op_iterator
3573 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3574 std::random_access_iterator_tag,
3575 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3576 const BasicBlock *> {
3577 explicit const_succ_op_iterator(const_value_op_iterator I)
3578 : iterator_adaptor_base(I) {}
3580 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3581 const BasicBlock *operator->() const { return operator*(); }
3584 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3585 Instruction *InsertBefore = nullptr) {
3586 return new IndirectBrInst(Address, NumDests, InsertBefore);
3589 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3590 BasicBlock *InsertAtEnd) {
3591 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3594 /// Provide fast operand accessors.
3595 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3597 // Accessor Methods for IndirectBrInst instruction.
3598 Value *getAddress() { return getOperand(0); }
3599 const Value *getAddress() const { return getOperand(0); }
3600 void setAddress(Value *V) { setOperand(0, V); }
3602 /// return the number of possible destinations in this
3603 /// indirectbr instruction.
3604 unsigned getNumDestinations() const { return getNumOperands()-1; }
3606 /// Return the specified destination.
3607 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3608 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3610 /// Add a destination.
3612 void addDestination(BasicBlock *Dest);
3614 /// This method removes the specified successor from the
3615 /// indirectbr instruction.
3616 void removeDestination(unsigned i);
3618 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3619 BasicBlock *getSuccessor(unsigned i) const {
3620 return cast<BasicBlock>(getOperand(i+1));
3622 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3623 setOperand(i + 1, NewSucc);
3626 iterator_range<succ_op_iterator> successors() {
3627 return make_range(succ_op_iterator(std::next(value_op_begin())),
3628 succ_op_iterator(value_op_end()));
3631 iterator_range<const_succ_op_iterator> successors() const {
3632 return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3633 const_succ_op_iterator(value_op_end()));
3636 // Methods for support type inquiry through isa, cast, and dyn_cast:
3637 static bool classof(const Instruction *I) {
3638 return I->getOpcode() == Instruction::IndirectBr;
3640 static bool classof(const Value *V) {
3641 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3645 template <>
3646 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3649 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3651 //===----------------------------------------------------------------------===//
3652 // InvokeInst Class
3653 //===----------------------------------------------------------------------===//
3655 /// Invoke instruction. The SubclassData field is used to hold the
3656 /// calling convention of the call.
3658 class InvokeInst : public CallBase {
3659 /// The number of operands for this call beyond the called function,
3660 /// arguments, and operand bundles.
3661 static constexpr int NumExtraOperands = 2;
3663 /// The index from the end of the operand array to the normal destination.
3664 static constexpr int NormalDestOpEndIdx = -3;
3666 /// The index from the end of the operand array to the unwind destination.
3667 static constexpr int UnwindDestOpEndIdx = -2;
3669 InvokeInst(const InvokeInst &BI);
3671 /// Construct an InvokeInst given a range of arguments.
3673 /// Construct an InvokeInst from a range of arguments
3674 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3675 BasicBlock *IfException, ArrayRef<Value *> Args,
3676 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3677 const Twine &NameStr, Instruction *InsertBefore);
3679 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3680 BasicBlock *IfException, ArrayRef<Value *> Args,
3681 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3682 const Twine &NameStr, BasicBlock *InsertAtEnd);
3684 void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3685 BasicBlock *IfException, ArrayRef<Value *> Args,
3686 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3688 /// Compute the number of operands to allocate.
3689 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3690 // We need one operand for the called function, plus our extra operands and
3691 // the input operand counts provided.
3692 return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3695 protected:
3696 // Note: Instruction needs to be a friend here to call cloneImpl.
3697 friend class Instruction;
3699 InvokeInst *cloneImpl() const;
3701 public:
3702 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3703 BasicBlock *IfException, ArrayRef<Value *> Args,
3704 const Twine &NameStr,
3705 Instruction *InsertBefore = nullptr) {
3706 int NumOperands = ComputeNumOperands(Args.size());
3707 return new (NumOperands)
3708 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3709 NameStr, InsertBefore);
3712 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3713 BasicBlock *IfException, ArrayRef<Value *> Args,
3714 ArrayRef<OperandBundleDef> Bundles = None,
3715 const Twine &NameStr = "",
3716 Instruction *InsertBefore = nullptr) {
3717 int NumOperands =
3718 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3719 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3721 return new (NumOperands, DescriptorBytes)
3722 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3723 NameStr, InsertBefore);
3726 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3727 BasicBlock *IfException, ArrayRef<Value *> Args,
3728 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3729 int NumOperands = ComputeNumOperands(Args.size());
3730 return new (NumOperands)
3731 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3732 NameStr, InsertAtEnd);
3735 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3736 BasicBlock *IfException, ArrayRef<Value *> Args,
3737 ArrayRef<OperandBundleDef> Bundles,
3738 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3739 int NumOperands =
3740 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3741 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3743 return new (NumOperands, DescriptorBytes)
3744 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3745 NameStr, InsertAtEnd);
3748 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3749 BasicBlock *IfException, ArrayRef<Value *> Args,
3750 const Twine &NameStr,
3751 Instruction *InsertBefore = nullptr) {
3752 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3753 IfException, Args, None, NameStr, InsertBefore);
3756 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3757 BasicBlock *IfException, ArrayRef<Value *> Args,
3758 ArrayRef<OperandBundleDef> Bundles = None,
3759 const Twine &NameStr = "",
3760 Instruction *InsertBefore = nullptr) {
3761 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3762 IfException, Args, Bundles, NameStr, InsertBefore);
3765 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3766 BasicBlock *IfException, ArrayRef<Value *> Args,
3767 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3768 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3769 IfException, Args, NameStr, InsertAtEnd);
3772 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3773 BasicBlock *IfException, ArrayRef<Value *> Args,
3774 ArrayRef<OperandBundleDef> Bundles,
3775 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3776 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3777 IfException, Args, Bundles, NameStr, InsertAtEnd);
3780 // Deprecated [opaque pointer types]
3781 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3782 BasicBlock *IfException, ArrayRef<Value *> Args,
3783 const Twine &NameStr,
3784 Instruction *InsertBefore = nullptr) {
3785 return Create(cast<FunctionType>(
3786 cast<PointerType>(Func->getType())->getElementType()),
3787 Func, IfNormal, IfException, Args, None, NameStr,
3788 InsertBefore);
3791 // Deprecated [opaque pointer types]
3792 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3793 BasicBlock *IfException, ArrayRef<Value *> Args,
3794 ArrayRef<OperandBundleDef> Bundles = None,
3795 const Twine &NameStr = "",
3796 Instruction *InsertBefore = nullptr) {
3797 return Create(cast<FunctionType>(
3798 cast<PointerType>(Func->getType())->getElementType()),
3799 Func, IfNormal, IfException, Args, Bundles, NameStr,
3800 InsertBefore);
3803 // Deprecated [opaque pointer types]
3804 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3805 BasicBlock *IfException, ArrayRef<Value *> Args,
3806 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3807 return Create(cast<FunctionType>(
3808 cast<PointerType>(Func->getType())->getElementType()),
3809 Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3812 // Deprecated [opaque pointer types]
3813 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3814 BasicBlock *IfException, ArrayRef<Value *> Args,
3815 ArrayRef<OperandBundleDef> Bundles,
3816 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3817 return Create(cast<FunctionType>(
3818 cast<PointerType>(Func->getType())->getElementType()),
3819 Func, IfNormal, IfException, Args, Bundles, NameStr,
3820 InsertAtEnd);
3823 /// Create a clone of \p II with a different set of operand bundles and
3824 /// insert it before \p InsertPt.
3826 /// The returned invoke instruction is identical to \p II in every way except
3827 /// that the operand bundles for the new instruction are set to the operand
3828 /// bundles in \p Bundles.
3829 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3830 Instruction *InsertPt = nullptr);
3832 /// Determine if the call should not perform indirect branch tracking.
3833 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3835 /// Determine if the call cannot unwind.
3836 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3837 void setDoesNotThrow() {
3838 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3841 // get*Dest - Return the destination basic blocks...
3842 BasicBlock *getNormalDest() const {
3843 return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3845 BasicBlock *getUnwindDest() const {
3846 return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3848 void setNormalDest(BasicBlock *B) {
3849 Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3851 void setUnwindDest(BasicBlock *B) {
3852 Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3855 /// Get the landingpad instruction from the landing pad
3856 /// block (the unwind destination).
3857 LandingPadInst *getLandingPadInst() const;
3859 BasicBlock *getSuccessor(unsigned i) const {
3860 assert(i < 2 && "Successor # out of range for invoke!");
3861 return i == 0 ? getNormalDest() : getUnwindDest();
3864 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3865 assert(i < 2 && "Successor # out of range for invoke!");
3866 if (i == 0)
3867 setNormalDest(NewSucc);
3868 else
3869 setUnwindDest(NewSucc);
3872 unsigned getNumSuccessors() const { return 2; }
3874 // Methods for support type inquiry through isa, cast, and dyn_cast:
3875 static bool classof(const Instruction *I) {
3876 return (I->getOpcode() == Instruction::Invoke);
3878 static bool classof(const Value *V) {
3879 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3882 private:
3884 // Shadow Instruction::setInstructionSubclassData with a private forwarding
3885 // method so that subclasses cannot accidentally use it.
3886 void setInstructionSubclassData(unsigned short D) {
3887 Instruction::setInstructionSubclassData(D);
3891 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3892 BasicBlock *IfException, ArrayRef<Value *> Args,
3893 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3894 const Twine &NameStr, Instruction *InsertBefore)
3895 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3896 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3897 InsertBefore) {
3898 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3901 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3902 BasicBlock *IfException, ArrayRef<Value *> Args,
3903 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3904 const Twine &NameStr, BasicBlock *InsertAtEnd)
3905 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3906 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3907 InsertAtEnd) {
3908 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3911 //===----------------------------------------------------------------------===//
3912 // CallBrInst Class
3913 //===----------------------------------------------------------------------===//
3915 /// CallBr instruction, tracking function calls that may not return control but
3916 /// instead transfer it to a third location. The SubclassData field is used to
3917 /// hold the calling convention of the call.
3919 class CallBrInst : public CallBase {
3921 unsigned NumIndirectDests;
3923 CallBrInst(const CallBrInst &BI);
3925 /// Construct a CallBrInst given a range of arguments.
3927 /// Construct a CallBrInst from a range of arguments
3928 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3929 ArrayRef<BasicBlock *> IndirectDests,
3930 ArrayRef<Value *> Args,
3931 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3932 const Twine &NameStr, Instruction *InsertBefore);
3934 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3935 ArrayRef<BasicBlock *> IndirectDests,
3936 ArrayRef<Value *> Args,
3937 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3938 const Twine &NameStr, BasicBlock *InsertAtEnd);
3940 void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3941 ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3942 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3944 /// Should the Indirect Destinations change, scan + update the Arg list.
3945 void updateArgBlockAddresses(unsigned i, BasicBlock *B);
3947 /// Compute the number of operands to allocate.
3948 static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3949 int NumBundleInputs = 0) {
3950 // We need one operand for the called function, plus our extra operands and
3951 // the input operand counts provided.
3952 return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3955 protected:
3956 // Note: Instruction needs to be a friend here to call cloneImpl.
3957 friend class Instruction;
3959 CallBrInst *cloneImpl() const;
3961 public:
3962 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3963 BasicBlock *DefaultDest,
3964 ArrayRef<BasicBlock *> IndirectDests,
3965 ArrayRef<Value *> Args, const Twine &NameStr,
3966 Instruction *InsertBefore = nullptr) {
3967 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3968 return new (NumOperands)
3969 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3970 NumOperands, NameStr, InsertBefore);
3973 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3974 BasicBlock *DefaultDest,
3975 ArrayRef<BasicBlock *> IndirectDests,
3976 ArrayRef<Value *> Args,
3977 ArrayRef<OperandBundleDef> Bundles = None,
3978 const Twine &NameStr = "",
3979 Instruction *InsertBefore = nullptr) {
3980 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3981 CountBundleInputs(Bundles));
3982 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3984 return new (NumOperands, DescriptorBytes)
3985 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3986 NumOperands, NameStr, InsertBefore);
3989 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3990 BasicBlock *DefaultDest,
3991 ArrayRef<BasicBlock *> IndirectDests,
3992 ArrayRef<Value *> Args, const Twine &NameStr,
3993 BasicBlock *InsertAtEnd) {
3994 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3995 return new (NumOperands)
3996 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3997 NumOperands, NameStr, InsertAtEnd);
4000 static CallBrInst *Create(FunctionType *Ty, Value *Func,
4001 BasicBlock *DefaultDest,
4002 ArrayRef<BasicBlock *> IndirectDests,
4003 ArrayRef<Value *> Args,
4004 ArrayRef<OperandBundleDef> Bundles,
4005 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4006 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
4007 CountBundleInputs(Bundles));
4008 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
4010 return new (NumOperands, DescriptorBytes)
4011 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
4012 NumOperands, NameStr, InsertAtEnd);
4015 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4016 ArrayRef<BasicBlock *> IndirectDests,
4017 ArrayRef<Value *> Args, const Twine &NameStr,
4018 Instruction *InsertBefore = nullptr) {
4019 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4020 IndirectDests, Args, NameStr, InsertBefore);
4023 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4024 ArrayRef<BasicBlock *> IndirectDests,
4025 ArrayRef<Value *> Args,
4026 ArrayRef<OperandBundleDef> Bundles = None,
4027 const Twine &NameStr = "",
4028 Instruction *InsertBefore = nullptr) {
4029 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4030 IndirectDests, Args, Bundles, NameStr, InsertBefore);
4033 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4034 ArrayRef<BasicBlock *> IndirectDests,
4035 ArrayRef<Value *> Args, const Twine &NameStr,
4036 BasicBlock *InsertAtEnd) {
4037 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4038 IndirectDests, Args, NameStr, InsertAtEnd);
4041 static CallBrInst *Create(FunctionCallee Func,
4042 BasicBlock *DefaultDest,
4043 ArrayRef<BasicBlock *> IndirectDests,
4044 ArrayRef<Value *> Args,
4045 ArrayRef<OperandBundleDef> Bundles,
4046 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4047 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4048 IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4051 /// Create a clone of \p CBI with a different set of operand bundles and
4052 /// insert it before \p InsertPt.
4054 /// The returned callbr instruction is identical to \p CBI in every way
4055 /// except that the operand bundles for the new instruction are set to the
4056 /// operand bundles in \p Bundles.
4057 static CallBrInst *Create(CallBrInst *CBI,
4058 ArrayRef<OperandBundleDef> Bundles,
4059 Instruction *InsertPt = nullptr);
4061 /// Return the number of callbr indirect dest labels.
4063 unsigned getNumIndirectDests() const { return NumIndirectDests; }
4065 /// getIndirectDestLabel - Return the i-th indirect dest label.
4067 Value *getIndirectDestLabel(unsigned i) const {
4068 assert(i < getNumIndirectDests() && "Out of bounds!");
4069 return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4073 Value *getIndirectDestLabelUse(unsigned i) const {
4074 assert(i < getNumIndirectDests() && "Out of bounds!");
4075 return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4079 // Return the destination basic blocks...
4080 BasicBlock *getDefaultDest() const {
4081 return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4083 BasicBlock *getIndirectDest(unsigned i) const {
4084 return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4086 SmallVector<BasicBlock *, 16> getIndirectDests() const {
4087 SmallVector<BasicBlock *, 16> IndirectDests;
4088 for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4089 IndirectDests.push_back(getIndirectDest(i));
4090 return IndirectDests;
4092 void setDefaultDest(BasicBlock *B) {
4093 *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4095 void setIndirectDest(unsigned i, BasicBlock *B) {
4096 updateArgBlockAddresses(i, B);
4097 *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4100 BasicBlock *getSuccessor(unsigned i) const {
4101 assert(i < getNumSuccessors() + 1 &&
4102 "Successor # out of range for callbr!");
4103 return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4106 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
4107 assert(i < getNumIndirectDests() + 1 &&
4108 "Successor # out of range for callbr!");
4109 return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
4112 unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4114 // Methods for support type inquiry through isa, cast, and dyn_cast:
4115 static bool classof(const Instruction *I) {
4116 return (I->getOpcode() == Instruction::CallBr);
4118 static bool classof(const Value *V) {
4119 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4122 private:
4124 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4125 // method so that subclasses cannot accidentally use it.
4126 void setInstructionSubclassData(unsigned short D) {
4127 Instruction::setInstructionSubclassData(D);
4131 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4132 ArrayRef<BasicBlock *> IndirectDests,
4133 ArrayRef<Value *> Args,
4134 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4135 const Twine &NameStr, Instruction *InsertBefore)
4136 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4137 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4138 InsertBefore) {
4139 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4142 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4143 ArrayRef<BasicBlock *> IndirectDests,
4144 ArrayRef<Value *> Args,
4145 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4146 const Twine &NameStr, BasicBlock *InsertAtEnd)
4147 : CallBase(
4148 cast<FunctionType>(
4149 cast<PointerType>(Func->getType())->getElementType())
4150 ->getReturnType(),
4151 Instruction::CallBr,
4152 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4153 InsertAtEnd) {
4154 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4157 //===----------------------------------------------------------------------===//
4158 // ResumeInst Class
4159 //===----------------------------------------------------------------------===//
4161 //===---------------------------------------------------------------------------
4162 /// Resume the propagation of an exception.
4164 class ResumeInst : public Instruction {
4165 ResumeInst(const ResumeInst &RI);
4167 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4168 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4170 protected:
4171 // Note: Instruction needs to be a friend here to call cloneImpl.
4172 friend class Instruction;
4174 ResumeInst *cloneImpl() const;
4176 public:
4177 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4178 return new(1) ResumeInst(Exn, InsertBefore);
4181 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4182 return new(1) ResumeInst(Exn, InsertAtEnd);
4185 /// Provide fast operand accessors
4186 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4188 /// Convenience accessor.
4189 Value *getValue() const { return Op<0>(); }
4191 unsigned getNumSuccessors() const { return 0; }
4193 // Methods for support type inquiry through isa, cast, and dyn_cast:
4194 static bool classof(const Instruction *I) {
4195 return I->getOpcode() == Instruction::Resume;
4197 static bool classof(const Value *V) {
4198 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4201 private:
4202 BasicBlock *getSuccessor(unsigned idx) const {
4203 llvm_unreachable("ResumeInst has no successors!");
4206 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4207 llvm_unreachable("ResumeInst has no successors!");
4211 template <>
4212 struct OperandTraits<ResumeInst> :
4213 public FixedNumOperandTraits<ResumeInst, 1> {
4216 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4218 //===----------------------------------------------------------------------===//
4219 // CatchSwitchInst Class
4220 //===----------------------------------------------------------------------===//
4221 class CatchSwitchInst : public Instruction {
4222 /// The number of operands actually allocated. NumOperands is
4223 /// the number actually in use.
4224 unsigned ReservedSpace;
4226 // Operand[0] = Outer scope
4227 // Operand[1] = Unwind block destination
4228 // Operand[n] = BasicBlock to go to on match
4229 CatchSwitchInst(const CatchSwitchInst &CSI);
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 can also autoinsert before another instruction.
4235 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4236 unsigned NumHandlers, const Twine &NameStr,
4237 Instruction *InsertBefore);
4239 /// Create a new switch instruction, specifying a
4240 /// default destination. The number of additional handlers can be specified
4241 /// here to make memory allocation more efficient.
4242 /// This constructor also autoinserts at the end of the specified BasicBlock.
4243 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4244 unsigned NumHandlers, const Twine &NameStr,
4245 BasicBlock *InsertAtEnd);
4247 // allocate space for exactly zero operands
4248 void *operator new(size_t s) { return User::operator new(s); }
4250 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4251 void growOperands(unsigned Size);
4253 protected:
4254 // Note: Instruction needs to be a friend here to call cloneImpl.
4255 friend class Instruction;
4257 CatchSwitchInst *cloneImpl() const;
4259 public:
4260 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4261 unsigned NumHandlers,
4262 const Twine &NameStr = "",
4263 Instruction *InsertBefore = nullptr) {
4264 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4265 InsertBefore);
4268 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4269 unsigned NumHandlers, const Twine &NameStr,
4270 BasicBlock *InsertAtEnd) {
4271 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4272 InsertAtEnd);
4275 /// Provide fast operand accessors
4276 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4278 // Accessor Methods for CatchSwitch stmt
4279 Value *getParentPad() const { return getOperand(0); }
4280 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4282 // Accessor Methods for CatchSwitch stmt
4283 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4284 bool unwindsToCaller() const { return !hasUnwindDest(); }
4285 BasicBlock *getUnwindDest() const {
4286 if (hasUnwindDest())
4287 return cast<BasicBlock>(getOperand(1));
4288 return nullptr;
4290 void setUnwindDest(BasicBlock *UnwindDest) {
4291 assert(UnwindDest);
4292 assert(hasUnwindDest());
4293 setOperand(1, UnwindDest);
4296 /// return the number of 'handlers' in this catchswitch
4297 /// instruction, except the default handler
4298 unsigned getNumHandlers() const {
4299 if (hasUnwindDest())
4300 return getNumOperands() - 2;
4301 return getNumOperands() - 1;
4304 private:
4305 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4306 static const BasicBlock *handler_helper(const Value *V) {
4307 return cast<BasicBlock>(V);
4310 public:
4311 using DerefFnTy = BasicBlock *(*)(Value *);
4312 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4313 using handler_range = iterator_range<handler_iterator>;
4314 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4315 using const_handler_iterator =
4316 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4317 using const_handler_range = iterator_range<const_handler_iterator>;
4319 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4320 handler_iterator handler_begin() {
4321 op_iterator It = op_begin() + 1;
4322 if (hasUnwindDest())
4323 ++It;
4324 return handler_iterator(It, DerefFnTy(handler_helper));
4327 /// Returns an iterator that points to the first handler in the
4328 /// CatchSwitchInst.
4329 const_handler_iterator handler_begin() const {
4330 const_op_iterator It = op_begin() + 1;
4331 if (hasUnwindDest())
4332 ++It;
4333 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4336 /// Returns a read-only iterator that points one past the last
4337 /// handler in the CatchSwitchInst.
4338 handler_iterator handler_end() {
4339 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4342 /// Returns an iterator that points one past the last handler in the
4343 /// CatchSwitchInst.
4344 const_handler_iterator handler_end() const {
4345 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4348 /// iteration adapter for range-for loops.
4349 handler_range handlers() {
4350 return make_range(handler_begin(), handler_end());
4353 /// iteration adapter for range-for loops.
4354 const_handler_range handlers() const {
4355 return make_range(handler_begin(), handler_end());
4358 /// Add an entry to the switch instruction...
4359 /// Note:
4360 /// This action invalidates handler_end(). Old handler_end() iterator will
4361 /// point to the added handler.
4362 void addHandler(BasicBlock *Dest);
4364 void removeHandler(handler_iterator HI);
4366 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4367 BasicBlock *getSuccessor(unsigned Idx) const {
4368 assert(Idx < getNumSuccessors() &&
4369 "Successor # out of range for catchswitch!");
4370 return cast<BasicBlock>(getOperand(Idx + 1));
4372 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4373 assert(Idx < getNumSuccessors() &&
4374 "Successor # out of range for catchswitch!");
4375 setOperand(Idx + 1, NewSucc);
4378 // Methods for support type inquiry through isa, cast, and dyn_cast:
4379 static bool classof(const Instruction *I) {
4380 return I->getOpcode() == Instruction::CatchSwitch;
4382 static bool classof(const Value *V) {
4383 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4387 template <>
4388 struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4390 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4392 //===----------------------------------------------------------------------===//
4393 // CleanupPadInst Class
4394 //===----------------------------------------------------------------------===//
4395 class CleanupPadInst : public FuncletPadInst {
4396 private:
4397 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4398 unsigned Values, const Twine &NameStr,
4399 Instruction *InsertBefore)
4400 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4401 NameStr, InsertBefore) {}
4402 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4403 unsigned Values, const Twine &NameStr,
4404 BasicBlock *InsertAtEnd)
4405 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4406 NameStr, InsertAtEnd) {}
4408 public:
4409 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4410 const Twine &NameStr = "",
4411 Instruction *InsertBefore = nullptr) {
4412 unsigned Values = 1 + Args.size();
4413 return new (Values)
4414 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4417 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4418 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4419 unsigned Values = 1 + Args.size();
4420 return new (Values)
4421 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4424 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4425 static bool classof(const Instruction *I) {
4426 return I->getOpcode() == Instruction::CleanupPad;
4428 static bool classof(const Value *V) {
4429 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4433 //===----------------------------------------------------------------------===//
4434 // CatchPadInst Class
4435 //===----------------------------------------------------------------------===//
4436 class CatchPadInst : public FuncletPadInst {
4437 private:
4438 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4439 unsigned Values, const Twine &NameStr,
4440 Instruction *InsertBefore)
4441 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4442 NameStr, InsertBefore) {}
4443 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4444 unsigned Values, const Twine &NameStr,
4445 BasicBlock *InsertAtEnd)
4446 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4447 NameStr, InsertAtEnd) {}
4449 public:
4450 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4451 const Twine &NameStr = "",
4452 Instruction *InsertBefore = nullptr) {
4453 unsigned Values = 1 + Args.size();
4454 return new (Values)
4455 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4458 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4459 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4460 unsigned Values = 1 + Args.size();
4461 return new (Values)
4462 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4465 /// Convenience accessors
4466 CatchSwitchInst *getCatchSwitch() const {
4467 return cast<CatchSwitchInst>(Op<-1>());
4469 void setCatchSwitch(Value *CatchSwitch) {
4470 assert(CatchSwitch);
4471 Op<-1>() = CatchSwitch;
4474 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4475 static bool classof(const Instruction *I) {
4476 return I->getOpcode() == Instruction::CatchPad;
4478 static bool classof(const Value *V) {
4479 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4483 //===----------------------------------------------------------------------===//
4484 // CatchReturnInst Class
4485 //===----------------------------------------------------------------------===//
4487 class CatchReturnInst : public Instruction {
4488 CatchReturnInst(const CatchReturnInst &RI);
4489 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4490 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4492 void init(Value *CatchPad, BasicBlock *BB);
4494 protected:
4495 // Note: Instruction needs to be a friend here to call cloneImpl.
4496 friend class Instruction;
4498 CatchReturnInst *cloneImpl() const;
4500 public:
4501 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4502 Instruction *InsertBefore = nullptr) {
4503 assert(CatchPad);
4504 assert(BB);
4505 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4508 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4509 BasicBlock *InsertAtEnd) {
4510 assert(CatchPad);
4511 assert(BB);
4512 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4515 /// Provide fast operand accessors
4516 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4518 /// Convenience accessors.
4519 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4520 void setCatchPad(CatchPadInst *CatchPad) {
4521 assert(CatchPad);
4522 Op<0>() = CatchPad;
4525 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4526 void setSuccessor(BasicBlock *NewSucc) {
4527 assert(NewSucc);
4528 Op<1>() = NewSucc;
4530 unsigned getNumSuccessors() const { return 1; }
4532 /// Get the parentPad of this catchret's catchpad's catchswitch.
4533 /// The successor block is implicitly a member of this funclet.
4534 Value *getCatchSwitchParentPad() const {
4535 return getCatchPad()->getCatchSwitch()->getParentPad();
4538 // Methods for support type inquiry through isa, cast, and dyn_cast:
4539 static bool classof(const Instruction *I) {
4540 return (I->getOpcode() == Instruction::CatchRet);
4542 static bool classof(const Value *V) {
4543 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4546 private:
4547 BasicBlock *getSuccessor(unsigned Idx) const {
4548 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4549 return getSuccessor();
4552 void setSuccessor(unsigned Idx, BasicBlock *B) {
4553 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4554 setSuccessor(B);
4558 template <>
4559 struct OperandTraits<CatchReturnInst>
4560 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4562 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4564 //===----------------------------------------------------------------------===//
4565 // CleanupReturnInst Class
4566 //===----------------------------------------------------------------------===//
4568 class CleanupReturnInst : public Instruction {
4569 private:
4570 CleanupReturnInst(const CleanupReturnInst &RI);
4571 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4572 Instruction *InsertBefore = nullptr);
4573 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4574 BasicBlock *InsertAtEnd);
4576 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4578 protected:
4579 // Note: Instruction needs to be a friend here to call cloneImpl.
4580 friend class Instruction;
4582 CleanupReturnInst *cloneImpl() const;
4584 public:
4585 static CleanupReturnInst *Create(Value *CleanupPad,
4586 BasicBlock *UnwindBB = nullptr,
4587 Instruction *InsertBefore = nullptr) {
4588 assert(CleanupPad);
4589 unsigned Values = 1;
4590 if (UnwindBB)
4591 ++Values;
4592 return new (Values)
4593 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4596 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4597 BasicBlock *InsertAtEnd) {
4598 assert(CleanupPad);
4599 unsigned Values = 1;
4600 if (UnwindBB)
4601 ++Values;
4602 return new (Values)
4603 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4606 /// Provide fast operand accessors
4607 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4609 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4610 bool unwindsToCaller() const { return !hasUnwindDest(); }
4612 /// Convenience accessor.
4613 CleanupPadInst *getCleanupPad() const {
4614 return cast<CleanupPadInst>(Op<0>());
4616 void setCleanupPad(CleanupPadInst *CleanupPad) {
4617 assert(CleanupPad);
4618 Op<0>() = CleanupPad;
4621 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4623 BasicBlock *getUnwindDest() const {
4624 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4626 void setUnwindDest(BasicBlock *NewDest) {
4627 assert(NewDest);
4628 assert(hasUnwindDest());
4629 Op<1>() = NewDest;
4632 // Methods for support type inquiry through isa, cast, and dyn_cast:
4633 static bool classof(const Instruction *I) {
4634 return (I->getOpcode() == Instruction::CleanupRet);
4636 static bool classof(const Value *V) {
4637 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4640 private:
4641 BasicBlock *getSuccessor(unsigned Idx) const {
4642 assert(Idx == 0);
4643 return getUnwindDest();
4646 void setSuccessor(unsigned Idx, BasicBlock *B) {
4647 assert(Idx == 0);
4648 setUnwindDest(B);
4651 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4652 // method so that subclasses cannot accidentally use it.
4653 void setInstructionSubclassData(unsigned short D) {
4654 Instruction::setInstructionSubclassData(D);
4658 template <>
4659 struct OperandTraits<CleanupReturnInst>
4660 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4662 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4664 //===----------------------------------------------------------------------===//
4665 // UnreachableInst Class
4666 //===----------------------------------------------------------------------===//
4668 //===---------------------------------------------------------------------------
4669 /// This function has undefined behavior. In particular, the
4670 /// presence of this instruction indicates some higher level knowledge that the
4671 /// end of the block cannot be reached.
4673 class UnreachableInst : public Instruction {
4674 protected:
4675 // Note: Instruction needs to be a friend here to call cloneImpl.
4676 friend class Instruction;
4678 UnreachableInst *cloneImpl() const;
4680 public:
4681 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4682 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4684 // allocate space for exactly zero operands
4685 void *operator new(size_t s) {
4686 return User::operator new(s, 0);
4689 unsigned getNumSuccessors() const { return 0; }
4691 // Methods for support type inquiry through isa, cast, and dyn_cast:
4692 static bool classof(const Instruction *I) {
4693 return I->getOpcode() == Instruction::Unreachable;
4695 static bool classof(const Value *V) {
4696 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4699 private:
4700 BasicBlock *getSuccessor(unsigned idx) const {
4701 llvm_unreachable("UnreachableInst has no successors!");
4704 void setSuccessor(unsigned idx, BasicBlock *B) {
4705 llvm_unreachable("UnreachableInst has no successors!");
4709 //===----------------------------------------------------------------------===//
4710 // TruncInst Class
4711 //===----------------------------------------------------------------------===//
4713 /// This class represents a truncation of integer types.
4714 class TruncInst : public CastInst {
4715 protected:
4716 // Note: Instruction needs to be a friend here to call cloneImpl.
4717 friend class Instruction;
4719 /// Clone an identical TruncInst
4720 TruncInst *cloneImpl() const;
4722 public:
4723 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4731 /// Constructor with insert-at-end-of-block semantics
4732 TruncInst(
4733 Value *S, ///< The value to be truncated
4734 Type *Ty, ///< The (smaller) type to truncate to
4735 const Twine &NameStr, ///< A name for the new instruction
4736 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4739 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4740 static bool classof(const Instruction *I) {
4741 return I->getOpcode() == Trunc;
4743 static bool classof(const Value *V) {
4744 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4748 //===----------------------------------------------------------------------===//
4749 // ZExtInst Class
4750 //===----------------------------------------------------------------------===//
4752 /// This class represents zero extension of integer types.
4753 class ZExtInst : public CastInst {
4754 protected:
4755 // Note: Instruction needs to be a friend here to call cloneImpl.
4756 friend class Instruction;
4758 /// Clone an identical ZExtInst
4759 ZExtInst *cloneImpl() const;
4761 public:
4762 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4770 /// Constructor with insert-at-end semantics.
4771 ZExtInst(
4772 Value *S, ///< The value to be zero extended
4773 Type *Ty, ///< The type to zero extend to
4774 const Twine &NameStr, ///< A name for the new instruction
4775 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4778 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4779 static bool classof(const Instruction *I) {
4780 return I->getOpcode() == ZExt;
4782 static bool classof(const Value *V) {
4783 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4787 //===----------------------------------------------------------------------===//
4788 // SExtInst Class
4789 //===----------------------------------------------------------------------===//
4791 /// This class represents a sign extension of integer types.
4792 class SExtInst : public CastInst {
4793 protected:
4794 // Note: Instruction needs to be a friend here to call cloneImpl.
4795 friend class Instruction;
4797 /// Clone an identical SExtInst
4798 SExtInst *cloneImpl() const;
4800 public:
4801 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4809 /// Constructor with insert-at-end-of-block semantics
4810 SExtInst(
4811 Value *S, ///< The value to be sign extended
4812 Type *Ty, ///< The type to sign extend to
4813 const Twine &NameStr, ///< A name for the new instruction
4814 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4817 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4818 static bool classof(const Instruction *I) {
4819 return I->getOpcode() == SExt;
4821 static bool classof(const Value *V) {
4822 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4826 //===----------------------------------------------------------------------===//
4827 // FPTruncInst Class
4828 //===----------------------------------------------------------------------===//
4830 /// This class represents a truncation of floating point types.
4831 class FPTruncInst : public CastInst {
4832 protected:
4833 // Note: Instruction needs to be a friend here to call cloneImpl.
4834 friend class Instruction;
4836 /// Clone an identical FPTruncInst
4837 FPTruncInst *cloneImpl() const;
4839 public:
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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4848 /// Constructor with insert-before-instruction semantics
4849 FPTruncInst(
4850 Value *S, ///< The value to be truncated
4851 Type *Ty, ///< The type to truncate to
4852 const Twine &NameStr, ///< A name for the new instruction
4853 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4856 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4857 static bool classof(const Instruction *I) {
4858 return I->getOpcode() == FPTrunc;
4860 static bool classof(const Value *V) {
4861 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4865 //===----------------------------------------------------------------------===//
4866 // FPExtInst Class
4867 //===----------------------------------------------------------------------===//
4869 /// This class represents an extension of floating point types.
4870 class FPExtInst : public CastInst {
4871 protected:
4872 // Note: Instruction needs to be a friend here to call cloneImpl.
4873 friend class Instruction;
4875 /// Clone an identical FPExtInst
4876 FPExtInst *cloneImpl() const;
4878 public:
4879 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4887 /// Constructor with insert-at-end-of-block semantics
4888 FPExtInst(
4889 Value *S, ///< The value to be extended
4890 Type *Ty, ///< The type to extend to
4891 const Twine &NameStr, ///< A name for the new instruction
4892 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4895 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4896 static bool classof(const Instruction *I) {
4897 return I->getOpcode() == FPExt;
4899 static bool classof(const Value *V) {
4900 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4904 //===----------------------------------------------------------------------===//
4905 // UIToFPInst Class
4906 //===----------------------------------------------------------------------===//
4908 /// This class represents a cast unsigned integer to floating point.
4909 class UIToFPInst : public CastInst {
4910 protected:
4911 // Note: Instruction needs to be a friend here to call cloneImpl.
4912 friend class Instruction;
4914 /// Clone an identical UIToFPInst
4915 UIToFPInst *cloneImpl() const;
4917 public:
4918 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4926 /// Constructor with insert-at-end-of-block semantics
4927 UIToFPInst(
4928 Value *S, ///< The value to be converted
4929 Type *Ty, ///< The type to convert to
4930 const Twine &NameStr, ///< A name for the new instruction
4931 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4934 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4935 static bool classof(const Instruction *I) {
4936 return I->getOpcode() == UIToFP;
4938 static bool classof(const Value *V) {
4939 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4943 //===----------------------------------------------------------------------===//
4944 // SIToFPInst Class
4945 //===----------------------------------------------------------------------===//
4947 /// This class represents a cast from signed integer to floating point.
4948 class SIToFPInst : public CastInst {
4949 protected:
4950 // Note: Instruction needs to be a friend here to call cloneImpl.
4951 friend class Instruction;
4953 /// Clone an identical SIToFPInst
4954 SIToFPInst *cloneImpl() const;
4956 public:
4957 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4965 /// Constructor with insert-at-end-of-block semantics
4966 SIToFPInst(
4967 Value *S, ///< The value to be converted
4968 Type *Ty, ///< The type to convert to
4969 const Twine &NameStr, ///< A name for the new instruction
4970 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4973 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4974 static bool classof(const Instruction *I) {
4975 return I->getOpcode() == SIToFP;
4977 static bool classof(const Value *V) {
4978 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4982 //===----------------------------------------------------------------------===//
4983 // FPToUIInst Class
4984 //===----------------------------------------------------------------------===//
4986 /// This class represents a cast from floating point to unsigned integer
4987 class FPToUIInst : public CastInst {
4988 protected:
4989 // Note: Instruction needs to be a friend here to call cloneImpl.
4990 friend class Instruction;
4992 /// Clone an identical FPToUIInst
4993 FPToUIInst *cloneImpl() const;
4995 public:
4996 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5004 /// Constructor with insert-at-end-of-block semantics
5005 FPToUIInst(
5006 Value *S, ///< The value to be converted
5007 Type *Ty, ///< The type to convert to
5008 const Twine &NameStr, ///< A name for the new instruction
5009 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
5012 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5013 static bool classof(const Instruction *I) {
5014 return I->getOpcode() == FPToUI;
5016 static bool classof(const Value *V) {
5017 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5021 //===----------------------------------------------------------------------===//
5022 // FPToSIInst Class
5023 //===----------------------------------------------------------------------===//
5025 /// This class represents a cast from floating point to signed integer.
5026 class FPToSIInst : public CastInst {
5027 protected:
5028 // Note: Instruction needs to be a friend here to call cloneImpl.
5029 friend class Instruction;
5031 /// Clone an identical FPToSIInst
5032 FPToSIInst *cloneImpl() const;
5034 public:
5035 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5043 /// Constructor with insert-at-end-of-block semantics
5044 FPToSIInst(
5045 Value *S, ///< The value to be converted
5046 Type *Ty, ///< The type to convert to
5047 const Twine &NameStr, ///< A name for the new instruction
5048 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5051 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5052 static bool classof(const Instruction *I) {
5053 return I->getOpcode() == FPToSI;
5055 static bool classof(const Value *V) {
5056 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5060 //===----------------------------------------------------------------------===//
5061 // IntToPtrInst Class
5062 //===----------------------------------------------------------------------===//
5064 /// This class represents a cast from an integer to a pointer.
5065 class IntToPtrInst : public CastInst {
5066 public:
5067 // Note: Instruction needs to be a friend here to call cloneImpl.
5068 friend class Instruction;
5070 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5078 /// Constructor with insert-at-end-of-block semantics
5079 IntToPtrInst(
5080 Value *S, ///< The value to be converted
5081 Type *Ty, ///< The type to convert to
5082 const Twine &NameStr, ///< A name for the new instruction
5083 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5086 /// Clone an identical IntToPtrInst.
5087 IntToPtrInst *cloneImpl() const;
5089 /// Returns the address space of this instruction's pointer type.
5090 unsigned getAddressSpace() const {
5091 return getType()->getPointerAddressSpace();
5094 // Methods for support type inquiry through isa, cast, and dyn_cast:
5095 static bool classof(const Instruction *I) {
5096 return I->getOpcode() == IntToPtr;
5098 static bool classof(const Value *V) {
5099 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5103 //===----------------------------------------------------------------------===//
5104 // PtrToIntInst Class
5105 //===----------------------------------------------------------------------===//
5107 /// This class represents a cast from a pointer to an integer.
5108 class PtrToIntInst : public CastInst {
5109 protected:
5110 // Note: Instruction needs to be a friend here to call cloneImpl.
5111 friend class Instruction;
5113 /// Clone an identical PtrToIntInst.
5114 PtrToIntInst *cloneImpl() const;
5116 public:
5117 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5125 /// Constructor with insert-at-end-of-block semantics
5126 PtrToIntInst(
5127 Value *S, ///< The value to be converted
5128 Type *Ty, ///< The type to convert to
5129 const Twine &NameStr, ///< A name for the new instruction
5130 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5133 /// Gets the pointer operand.
5134 Value *getPointerOperand() { return getOperand(0); }
5135 /// Gets the pointer operand.
5136 const Value *getPointerOperand() const { return getOperand(0); }
5137 /// Gets the operand index of the pointer operand.
5138 static unsigned getPointerOperandIndex() { return 0U; }
5140 /// Returns the address space of the pointer operand.
5141 unsigned getPointerAddressSpace() const {
5142 return getPointerOperand()->getType()->getPointerAddressSpace();
5145 // Methods for support type inquiry through isa, cast, and dyn_cast:
5146 static bool classof(const Instruction *I) {
5147 return I->getOpcode() == PtrToInt;
5149 static bool classof(const Value *V) {
5150 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5154 //===----------------------------------------------------------------------===//
5155 // BitCastInst Class
5156 //===----------------------------------------------------------------------===//
5158 /// This class represents a no-op cast from one type to another.
5159 class BitCastInst : public CastInst {
5160 protected:
5161 // Note: Instruction needs to be a friend here to call cloneImpl.
5162 friend class Instruction;
5164 /// Clone an identical BitCastInst.
5165 BitCastInst *cloneImpl() const;
5167 public:
5168 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5176 /// Constructor with insert-at-end-of-block semantics
5177 BitCastInst(
5178 Value *S, ///< The value to be casted
5179 Type *Ty, ///< The type to casted to
5180 const Twine &NameStr, ///< A name for the new instruction
5181 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5184 // Methods for support type inquiry through isa, cast, and dyn_cast:
5185 static bool classof(const Instruction *I) {
5186 return I->getOpcode() == BitCast;
5188 static bool classof(const Value *V) {
5189 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5193 //===----------------------------------------------------------------------===//
5194 // AddrSpaceCastInst Class
5195 //===----------------------------------------------------------------------===//
5197 /// This class represents a conversion between pointers from one address space
5198 /// to another.
5199 class AddrSpaceCastInst : public CastInst {
5200 protected:
5201 // Note: Instruction needs to be a friend here to call cloneImpl.
5202 friend class Instruction;
5204 /// Clone an identical AddrSpaceCastInst.
5205 AddrSpaceCastInst *cloneImpl() const;
5207 public:
5208 /// Constructor with insert-before-instruction 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 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5216 /// Constructor with insert-at-end-of-block semantics
5217 AddrSpaceCastInst(
5218 Value *S, ///< The value to be casted
5219 Type *Ty, ///< The type to casted to
5220 const Twine &NameStr, ///< A name for the new instruction
5221 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5224 // Methods for support type inquiry through isa, cast, and dyn_cast:
5225 static bool classof(const Instruction *I) {
5226 return I->getOpcode() == AddrSpaceCast;
5228 static bool classof(const Value *V) {
5229 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5232 /// Gets the pointer operand.
5233 Value *getPointerOperand() {
5234 return getOperand(0);
5237 /// Gets the pointer operand.
5238 const Value *getPointerOperand() const {
5239 return getOperand(0);
5242 /// Gets the operand index of the pointer operand.
5243 static unsigned getPointerOperandIndex() {
5244 return 0U;
5247 /// Returns the address space of the pointer operand.
5248 unsigned getSrcAddressSpace() const {
5249 return getPointerOperand()->getType()->getPointerAddressSpace();
5252 /// Returns the address space of the result.
5253 unsigned getDestAddressSpace() const {
5254 return getType()->getPointerAddressSpace();
5258 /// A helper function that returns the pointer operand of a load or store
5259 /// instruction. Returns nullptr if not load or store.
5260 inline const Value *getLoadStorePointerOperand(const Value *V) {
5261 if (auto *Load = dyn_cast<LoadInst>(V))
5262 return Load->getPointerOperand();
5263 if (auto *Store = dyn_cast<StoreInst>(V))
5264 return Store->getPointerOperand();
5265 return nullptr;
5267 inline Value *getLoadStorePointerOperand(Value *V) {
5268 return const_cast<Value *>(
5269 getLoadStorePointerOperand(static_cast<const Value *>(V)));
5272 /// A helper function that returns the pointer operand of a load, store
5273 /// or GEP instruction. Returns nullptr if not load, store, or GEP.
5274 inline const Value *getPointerOperand(const Value *V) {
5275 if (auto *Ptr = getLoadStorePointerOperand(V))
5276 return Ptr;
5277 if (auto *Gep = dyn_cast<GetElementPtrInst>(V))
5278 return Gep->getPointerOperand();
5279 return nullptr;
5281 inline Value *getPointerOperand(Value *V) {
5282 return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V)));
5285 /// A helper function that returns the alignment of load or store instruction.
5286 inline MaybeAlign getLoadStoreAlignment(Value *I) {
5287 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5288 "Expected Load or Store instruction");
5289 if (auto *LI = dyn_cast<LoadInst>(I))
5290 return MaybeAlign(LI->getAlignment());
5291 return MaybeAlign(cast<StoreInst>(I)->getAlignment());
5294 /// A helper function that returns the address space of the pointer operand of
5295 /// load or store instruction.
5296 inline unsigned getLoadStoreAddressSpace(Value *I) {
5297 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5298 "Expected Load or Store instruction");
5299 if (auto *LI = dyn_cast<LoadInst>(I))
5300 return LI->getPointerAddressSpace();
5301 return cast<StoreInst>(I)->getPointerAddressSpace();
5304 } // end namespace llvm
5306 #endif // LLVM_IR_INSTRUCTIONS_H