[Alignment][NFC] Migrate Instructions to Align
[llvm-core.git] / include / llvm / IR / Instructions.h
blob5c9b03a4c8af60a43d7731f5a5e9638325a95599
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 // FIXME: Remove once migration to llvm::Align is over.
118 void setAlignment(unsigned Align);
119 void setAlignment(llvm::MaybeAlign Align);
121 /// Return true if this alloca is in the entry block of the function and is a
122 /// constant size. If so, the code generator will fold it into the
123 /// prolog/epilog code, so it is basically free.
124 bool isStaticAlloca() const;
126 /// Return true if this alloca is used as an inalloca argument to a call. Such
127 /// allocas are never considered static even if they are in the entry block.
128 bool isUsedWithInAlloca() const {
129 return getSubclassDataFromInstruction() & 32;
132 /// Specify whether this alloca is used to represent the arguments to a call.
133 void setUsedWithInAlloca(bool V) {
134 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
135 (V ? 32 : 0));
138 /// Return true if this alloca is used as a swifterror argument to a call.
139 bool isSwiftError() const {
140 return getSubclassDataFromInstruction() & 64;
143 /// Specify whether this alloca is used to represent a swifterror.
144 void setSwiftError(bool V) {
145 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
146 (V ? 64 : 0));
149 // Methods for support type inquiry through isa, cast, and dyn_cast:
150 static bool classof(const Instruction *I) {
151 return (I->getOpcode() == Instruction::Alloca);
153 static bool classof(const Value *V) {
154 return isa<Instruction>(V) && classof(cast<Instruction>(V));
157 private:
158 // Shadow Instruction::setInstructionSubclassData with a private forwarding
159 // method so that subclasses cannot accidentally use it.
160 void setInstructionSubclassData(unsigned short D) {
161 Instruction::setInstructionSubclassData(D);
165 //===----------------------------------------------------------------------===//
166 // LoadInst Class
167 //===----------------------------------------------------------------------===//
169 /// An instruction for reading from memory. This uses the SubclassData field in
170 /// Value to store whether or not the load is volatile.
171 class LoadInst : public UnaryInstruction {
172 void AssertOK();
174 protected:
175 // Note: Instruction needs to be a friend here to call cloneImpl.
176 friend class Instruction;
178 LoadInst *cloneImpl() const;
180 public:
181 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
182 Instruction *InsertBefore = nullptr);
183 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
184 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
185 Instruction *InsertBefore = nullptr);
186 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187 BasicBlock *InsertAtEnd);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 unsigned Align, Instruction *InsertBefore = nullptr);
190 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
191 unsigned Align, BasicBlock *InsertAtEnd);
192 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
193 unsigned Align, AtomicOrdering Order,
194 SyncScope::ID SSID = SyncScope::System,
195 Instruction *InsertBefore = nullptr);
196 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
197 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
198 BasicBlock *InsertAtEnd);
200 // Deprecated [opaque pointer types]
201 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
202 Instruction *InsertBefore = nullptr)
203 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
204 InsertBefore) {}
205 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
206 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
207 InsertAtEnd) {}
208 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
209 Instruction *InsertBefore = nullptr)
210 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
211 isVolatile, InsertBefore) {}
212 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
213 BasicBlock *InsertAtEnd)
214 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
215 isVolatile, InsertAtEnd) {}
216 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
217 Instruction *InsertBefore = nullptr)
218 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
219 isVolatile, Align, InsertBefore) {}
220 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
221 BasicBlock *InsertAtEnd)
222 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
223 isVolatile, Align, InsertAtEnd) {}
224 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
225 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
226 Instruction *InsertBefore = nullptr)
227 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
228 isVolatile, Align, Order, SSID, InsertBefore) {}
229 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
230 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
231 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
232 isVolatile, Align, Order, SSID, InsertAtEnd) {}
234 /// Return true if this is a load from a volatile memory location.
235 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
237 /// Specify whether this is a volatile load or not.
238 void setVolatile(bool V) {
239 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
240 (V ? 1 : 0));
243 /// Return the alignment of the access that is being performed.
244 unsigned getAlignment() const {
245 if (const auto MA =
246 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
247 return MA->value();
248 return 0;
251 // FIXME: Remove once migration to llvm::Align is over.
252 void setAlignment(unsigned Align);
253 void setAlignment(llvm::MaybeAlign Align);
255 /// Returns the ordering constraint of this load instruction.
256 AtomicOrdering getOrdering() const {
257 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
260 /// Sets the ordering constraint of this load instruction. May not be Release
261 /// or AcquireRelease.
262 void setOrdering(AtomicOrdering Ordering) {
263 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
264 ((unsigned)Ordering << 7));
267 /// Returns the synchronization scope ID of this load instruction.
268 SyncScope::ID getSyncScopeID() const {
269 return SSID;
272 /// Sets the synchronization scope ID of this load instruction.
273 void setSyncScopeID(SyncScope::ID SSID) {
274 this->SSID = SSID;
277 /// Sets the ordering constraint and the synchronization scope ID of this load
278 /// instruction.
279 void setAtomic(AtomicOrdering Ordering,
280 SyncScope::ID SSID = SyncScope::System) {
281 setOrdering(Ordering);
282 setSyncScopeID(SSID);
285 bool isSimple() const { return !isAtomic() && !isVolatile(); }
287 bool isUnordered() const {
288 return (getOrdering() == AtomicOrdering::NotAtomic ||
289 getOrdering() == AtomicOrdering::Unordered) &&
290 !isVolatile();
293 Value *getPointerOperand() { return getOperand(0); }
294 const Value *getPointerOperand() const { return getOperand(0); }
295 static unsigned getPointerOperandIndex() { return 0U; }
296 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
298 /// Returns the address space of the pointer operand.
299 unsigned getPointerAddressSpace() const {
300 return getPointerOperandType()->getPointerAddressSpace();
303 // Methods for support type inquiry through isa, cast, and dyn_cast:
304 static bool classof(const Instruction *I) {
305 return I->getOpcode() == Instruction::Load;
307 static bool classof(const Value *V) {
308 return isa<Instruction>(V) && classof(cast<Instruction>(V));
311 private:
312 // Shadow Instruction::setInstructionSubclassData with a private forwarding
313 // method so that subclasses cannot accidentally use it.
314 void setInstructionSubclassData(unsigned short D) {
315 Instruction::setInstructionSubclassData(D);
318 /// The synchronization scope ID of this load instruction. Not quite enough
319 /// room in SubClassData for everything, so synchronization scope ID gets its
320 /// own field.
321 SyncScope::ID SSID;
324 //===----------------------------------------------------------------------===//
325 // StoreInst Class
326 //===----------------------------------------------------------------------===//
328 /// An instruction for storing to memory.
329 class StoreInst : public Instruction {
330 void AssertOK();
332 protected:
333 // Note: Instruction needs to be a friend here to call cloneImpl.
334 friend class Instruction;
336 StoreInst *cloneImpl() const;
338 public:
339 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
340 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
341 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
342 Instruction *InsertBefore = nullptr);
343 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
344 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
345 unsigned Align, Instruction *InsertBefore = nullptr);
346 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
347 unsigned Align, BasicBlock *InsertAtEnd);
348 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
349 unsigned Align, AtomicOrdering Order,
350 SyncScope::ID SSID = SyncScope::System,
351 Instruction *InsertBefore = nullptr);
352 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
353 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
354 BasicBlock *InsertAtEnd);
356 // allocate space for exactly two operands
357 void *operator new(size_t s) {
358 return User::operator new(s, 2);
361 /// Return true if this is a store to a volatile memory location.
362 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
364 /// Specify whether this is a volatile store or not.
365 void setVolatile(bool V) {
366 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
367 (V ? 1 : 0));
370 /// Transparently provide more efficient getOperand methods.
371 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
373 /// Return the alignment of the access that is being performed
374 unsigned getAlignment() const {
375 if (const auto MA =
376 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
377 return MA->value();
378 return 0;
381 // FIXME: Remove once migration to llvm::Align is over.
382 void setAlignment(unsigned Align);
383 void setAlignment(llvm::MaybeAlign Align);
385 /// Returns the ordering constraint of this store instruction.
386 AtomicOrdering getOrdering() const {
387 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
390 /// Sets the ordering constraint of this store instruction. May not be
391 /// Acquire or AcquireRelease.
392 void setOrdering(AtomicOrdering Ordering) {
393 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
394 ((unsigned)Ordering << 7));
397 /// Returns the synchronization scope ID of this store instruction.
398 SyncScope::ID getSyncScopeID() const {
399 return SSID;
402 /// Sets the synchronization scope ID of this store instruction.
403 void setSyncScopeID(SyncScope::ID SSID) {
404 this->SSID = SSID;
407 /// Sets the ordering constraint and the synchronization scope ID of this
408 /// store instruction.
409 void setAtomic(AtomicOrdering Ordering,
410 SyncScope::ID SSID = SyncScope::System) {
411 setOrdering(Ordering);
412 setSyncScopeID(SSID);
415 bool isSimple() const { return !isAtomic() && !isVolatile(); }
417 bool isUnordered() const {
418 return (getOrdering() == AtomicOrdering::NotAtomic ||
419 getOrdering() == AtomicOrdering::Unordered) &&
420 !isVolatile();
423 Value *getValueOperand() { return getOperand(0); }
424 const Value *getValueOperand() const { return getOperand(0); }
426 Value *getPointerOperand() { return getOperand(1); }
427 const Value *getPointerOperand() const { return getOperand(1); }
428 static unsigned getPointerOperandIndex() { return 1U; }
429 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
431 /// Returns the address space of the pointer operand.
432 unsigned getPointerAddressSpace() const {
433 return getPointerOperandType()->getPointerAddressSpace();
436 // Methods for support type inquiry through isa, cast, and dyn_cast:
437 static bool classof(const Instruction *I) {
438 return I->getOpcode() == Instruction::Store;
440 static bool classof(const Value *V) {
441 return isa<Instruction>(V) && classof(cast<Instruction>(V));
444 private:
445 // Shadow Instruction::setInstructionSubclassData with a private forwarding
446 // method so that subclasses cannot accidentally use it.
447 void setInstructionSubclassData(unsigned short D) {
448 Instruction::setInstructionSubclassData(D);
451 /// The synchronization scope ID of this store instruction. Not quite enough
452 /// room in SubClassData for everything, so synchronization scope ID gets its
453 /// own field.
454 SyncScope::ID SSID;
457 template <>
458 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
461 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
463 //===----------------------------------------------------------------------===//
464 // FenceInst Class
465 //===----------------------------------------------------------------------===//
467 /// An instruction for ordering other memory operations.
468 class FenceInst : public Instruction {
469 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
471 protected:
472 // Note: Instruction needs to be a friend here to call cloneImpl.
473 friend class Instruction;
475 FenceInst *cloneImpl() const;
477 public:
478 // Ordering may only be Acquire, Release, AcquireRelease, or
479 // SequentiallyConsistent.
480 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
481 SyncScope::ID SSID = SyncScope::System,
482 Instruction *InsertBefore = nullptr);
483 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
484 BasicBlock *InsertAtEnd);
486 // allocate space for exactly zero operands
487 void *operator new(size_t s) {
488 return User::operator new(s, 0);
491 /// Returns the ordering constraint of this fence instruction.
492 AtomicOrdering getOrdering() const {
493 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
496 /// Sets the ordering constraint of this fence instruction. May only be
497 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
498 void setOrdering(AtomicOrdering Ordering) {
499 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
500 ((unsigned)Ordering << 1));
503 /// Returns the synchronization scope ID of this fence instruction.
504 SyncScope::ID getSyncScopeID() const {
505 return SSID;
508 /// Sets the synchronization scope ID of this fence instruction.
509 void setSyncScopeID(SyncScope::ID SSID) {
510 this->SSID = SSID;
513 // Methods for support type inquiry through isa, cast, and dyn_cast:
514 static bool classof(const Instruction *I) {
515 return I->getOpcode() == Instruction::Fence;
517 static bool classof(const Value *V) {
518 return isa<Instruction>(V) && classof(cast<Instruction>(V));
521 private:
522 // Shadow Instruction::setInstructionSubclassData with a private forwarding
523 // method so that subclasses cannot accidentally use it.
524 void setInstructionSubclassData(unsigned short D) {
525 Instruction::setInstructionSubclassData(D);
528 /// The synchronization scope ID of this fence instruction. Not quite enough
529 /// room in SubClassData for everything, so synchronization scope ID gets its
530 /// own field.
531 SyncScope::ID SSID;
534 //===----------------------------------------------------------------------===//
535 // AtomicCmpXchgInst Class
536 //===----------------------------------------------------------------------===//
538 /// An instruction that atomically checks whether a
539 /// specified value is in a memory location, and, if it is, stores a new value
540 /// there. The value returned by this instruction is a pair containing the
541 /// original value as first element, and an i1 indicating success (true) or
542 /// failure (false) as second element.
544 class AtomicCmpXchgInst : public Instruction {
545 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
546 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
547 SyncScope::ID SSID);
549 protected:
550 // Note: Instruction needs to be a friend here to call cloneImpl.
551 friend class Instruction;
553 AtomicCmpXchgInst *cloneImpl() const;
555 public:
556 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
557 AtomicOrdering SuccessOrdering,
558 AtomicOrdering FailureOrdering,
559 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
560 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
561 AtomicOrdering SuccessOrdering,
562 AtomicOrdering FailureOrdering,
563 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
565 // allocate space for exactly three operands
566 void *operator new(size_t s) {
567 return User::operator new(s, 3);
570 /// Return true if this is a cmpxchg from a volatile memory
571 /// location.
573 bool isVolatile() const {
574 return getSubclassDataFromInstruction() & 1;
577 /// Specify whether this is a volatile cmpxchg.
579 void setVolatile(bool V) {
580 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
581 (unsigned)V);
584 /// Return true if this cmpxchg may spuriously fail.
585 bool isWeak() const {
586 return getSubclassDataFromInstruction() & 0x100;
589 void setWeak(bool IsWeak) {
590 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
591 (IsWeak << 8));
594 /// Transparently provide more efficient getOperand methods.
595 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
597 /// Returns the success ordering constraint of this cmpxchg instruction.
598 AtomicOrdering getSuccessOrdering() const {
599 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
602 /// Sets the success ordering constraint of this cmpxchg instruction.
603 void setSuccessOrdering(AtomicOrdering Ordering) {
604 assert(Ordering != AtomicOrdering::NotAtomic &&
605 "CmpXchg instructions can only be atomic.");
606 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
607 ((unsigned)Ordering << 2));
610 /// Returns the failure ordering constraint of this cmpxchg instruction.
611 AtomicOrdering getFailureOrdering() const {
612 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
615 /// Sets the failure ordering constraint of this cmpxchg instruction.
616 void setFailureOrdering(AtomicOrdering Ordering) {
617 assert(Ordering != AtomicOrdering::NotAtomic &&
618 "CmpXchg instructions can only be atomic.");
619 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
620 ((unsigned)Ordering << 5));
623 /// Returns the synchronization scope ID of this cmpxchg instruction.
624 SyncScope::ID getSyncScopeID() const {
625 return SSID;
628 /// Sets the synchronization scope ID of this cmpxchg instruction.
629 void setSyncScopeID(SyncScope::ID SSID) {
630 this->SSID = SSID;
633 Value *getPointerOperand() { return getOperand(0); }
634 const Value *getPointerOperand() const { return getOperand(0); }
635 static unsigned getPointerOperandIndex() { return 0U; }
637 Value *getCompareOperand() { return getOperand(1); }
638 const Value *getCompareOperand() const { return getOperand(1); }
640 Value *getNewValOperand() { return getOperand(2); }
641 const Value *getNewValOperand() const { return getOperand(2); }
643 /// Returns the address space of the pointer operand.
644 unsigned getPointerAddressSpace() const {
645 return getPointerOperand()->getType()->getPointerAddressSpace();
648 /// Returns the strongest permitted ordering on failure, given the
649 /// desired ordering on success.
651 /// If the comparison in a cmpxchg operation fails, there is no atomic store
652 /// so release semantics cannot be provided. So this function drops explicit
653 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
654 /// operation would remain SequentiallyConsistent.
655 static AtomicOrdering
656 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
657 switch (SuccessOrdering) {
658 default:
659 llvm_unreachable("invalid cmpxchg success ordering");
660 case AtomicOrdering::Release:
661 case AtomicOrdering::Monotonic:
662 return AtomicOrdering::Monotonic;
663 case AtomicOrdering::AcquireRelease:
664 case AtomicOrdering::Acquire:
665 return AtomicOrdering::Acquire;
666 case AtomicOrdering::SequentiallyConsistent:
667 return AtomicOrdering::SequentiallyConsistent;
671 // Methods for support type inquiry through isa, cast, and dyn_cast:
672 static bool classof(const Instruction *I) {
673 return I->getOpcode() == Instruction::AtomicCmpXchg;
675 static bool classof(const Value *V) {
676 return isa<Instruction>(V) && classof(cast<Instruction>(V));
679 private:
680 // Shadow Instruction::setInstructionSubclassData with a private forwarding
681 // method so that subclasses cannot accidentally use it.
682 void setInstructionSubclassData(unsigned short D) {
683 Instruction::setInstructionSubclassData(D);
686 /// The synchronization scope ID of this cmpxchg instruction. Not quite
687 /// enough room in SubClassData for everything, so synchronization scope ID
688 /// gets its own field.
689 SyncScope::ID SSID;
692 template <>
693 struct OperandTraits<AtomicCmpXchgInst> :
694 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
697 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
699 //===----------------------------------------------------------------------===//
700 // AtomicRMWInst Class
701 //===----------------------------------------------------------------------===//
703 /// an instruction that atomically reads a memory location,
704 /// combines it with another value, and then stores the result back. Returns
705 /// the old value.
707 class AtomicRMWInst : public Instruction {
708 protected:
709 // Note: Instruction needs to be a friend here to call cloneImpl.
710 friend class Instruction;
712 AtomicRMWInst *cloneImpl() const;
714 public:
715 /// This enumeration lists the possible modifications atomicrmw can make. In
716 /// the descriptions, 'p' is the pointer to the instruction's memory location,
717 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
718 /// instruction. These instructions always return 'old'.
719 enum BinOp {
720 /// *p = v
721 Xchg,
722 /// *p = old + v
723 Add,
724 /// *p = old - v
725 Sub,
726 /// *p = old & v
727 And,
728 /// *p = ~(old & v)
729 Nand,
730 /// *p = old | v
732 /// *p = old ^ v
733 Xor,
734 /// *p = old >signed v ? old : v
735 Max,
736 /// *p = old <signed v ? old : v
737 Min,
738 /// *p = old >unsigned v ? old : v
739 UMax,
740 /// *p = old <unsigned v ? old : v
741 UMin,
743 /// *p = old + v
744 FAdd,
746 /// *p = old - v
747 FSub,
749 FIRST_BINOP = Xchg,
750 LAST_BINOP = FSub,
751 BAD_BINOP
754 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
755 AtomicOrdering Ordering, SyncScope::ID SSID,
756 Instruction *InsertBefore = nullptr);
757 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
758 AtomicOrdering Ordering, SyncScope::ID SSID,
759 BasicBlock *InsertAtEnd);
761 // allocate space for exactly two operands
762 void *operator new(size_t s) {
763 return User::operator new(s, 2);
766 BinOp getOperation() const {
767 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
770 static StringRef getOperationName(BinOp Op);
772 static bool isFPOperation(BinOp Op) {
773 switch (Op) {
774 case AtomicRMWInst::FAdd:
775 case AtomicRMWInst::FSub:
776 return true;
777 default:
778 return false;
782 void setOperation(BinOp Operation) {
783 unsigned short SubclassData = getSubclassDataFromInstruction();
784 setInstructionSubclassData((SubclassData & 31) |
785 (Operation << 5));
788 /// Return true if this is a RMW on a volatile memory location.
790 bool isVolatile() const {
791 return getSubclassDataFromInstruction() & 1;
794 /// Specify whether this is a volatile RMW or not.
796 void setVolatile(bool V) {
797 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
798 (unsigned)V);
801 /// Transparently provide more efficient getOperand methods.
802 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
804 /// Returns the ordering constraint of this rmw instruction.
805 AtomicOrdering getOrdering() const {
806 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
809 /// Sets the ordering constraint of this rmw instruction.
810 void setOrdering(AtomicOrdering Ordering) {
811 assert(Ordering != AtomicOrdering::NotAtomic &&
812 "atomicrmw instructions can only be atomic.");
813 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
814 ((unsigned)Ordering << 2));
817 /// Returns the synchronization scope ID of this rmw instruction.
818 SyncScope::ID getSyncScopeID() const {
819 return SSID;
822 /// Sets the synchronization scope ID of this rmw instruction.
823 void setSyncScopeID(SyncScope::ID SSID) {
824 this->SSID = SSID;
827 Value *getPointerOperand() { return getOperand(0); }
828 const Value *getPointerOperand() const { return getOperand(0); }
829 static unsigned getPointerOperandIndex() { return 0U; }
831 Value *getValOperand() { return getOperand(1); }
832 const Value *getValOperand() const { return getOperand(1); }
834 /// Returns the address space of the pointer operand.
835 unsigned getPointerAddressSpace() const {
836 return getPointerOperand()->getType()->getPointerAddressSpace();
839 bool isFloatingPointOperation() const {
840 return isFPOperation(getOperation());
843 // Methods for support type inquiry through isa, cast, and dyn_cast:
844 static bool classof(const Instruction *I) {
845 return I->getOpcode() == Instruction::AtomicRMW;
847 static bool classof(const Value *V) {
848 return isa<Instruction>(V) && classof(cast<Instruction>(V));
851 private:
852 void Init(BinOp Operation, Value *Ptr, Value *Val,
853 AtomicOrdering Ordering, SyncScope::ID SSID);
855 // Shadow Instruction::setInstructionSubclassData with a private forwarding
856 // method so that subclasses cannot accidentally use it.
857 void setInstructionSubclassData(unsigned short D) {
858 Instruction::setInstructionSubclassData(D);
861 /// The synchronization scope ID of this rmw instruction. Not quite enough
862 /// room in SubClassData for everything, so synchronization scope ID gets its
863 /// own field.
864 SyncScope::ID SSID;
867 template <>
868 struct OperandTraits<AtomicRMWInst>
869 : public FixedNumOperandTraits<AtomicRMWInst,2> {
872 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
874 //===----------------------------------------------------------------------===//
875 // GetElementPtrInst Class
876 //===----------------------------------------------------------------------===//
878 // checkGEPType - Simple wrapper function to give a better assertion failure
879 // message on bad indexes for a gep instruction.
881 inline Type *checkGEPType(Type *Ty) {
882 assert(Ty && "Invalid GetElementPtrInst indices for type!");
883 return Ty;
886 /// an instruction for type-safe pointer arithmetic to
887 /// access elements of arrays and structs
889 class GetElementPtrInst : public Instruction {
890 Type *SourceElementType;
891 Type *ResultElementType;
893 GetElementPtrInst(const GetElementPtrInst &GEPI);
895 /// Constructors - Create a getelementptr instruction with a base pointer an
896 /// list of indices. The first ctor can optionally insert before an existing
897 /// instruction, the second appends the new instruction to the specified
898 /// BasicBlock.
899 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
900 ArrayRef<Value *> IdxList, unsigned Values,
901 const Twine &NameStr, Instruction *InsertBefore);
902 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
903 ArrayRef<Value *> IdxList, unsigned Values,
904 const Twine &NameStr, BasicBlock *InsertAtEnd);
906 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
908 protected:
909 // Note: Instruction needs to be a friend here to call cloneImpl.
910 friend class Instruction;
912 GetElementPtrInst *cloneImpl() const;
914 public:
915 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
916 ArrayRef<Value *> IdxList,
917 const Twine &NameStr = "",
918 Instruction *InsertBefore = nullptr) {
919 unsigned Values = 1 + unsigned(IdxList.size());
920 if (!PointeeType)
921 PointeeType =
922 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
923 else
924 assert(
925 PointeeType ==
926 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
927 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
928 NameStr, InsertBefore);
931 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
932 ArrayRef<Value *> IdxList,
933 const Twine &NameStr,
934 BasicBlock *InsertAtEnd) {
935 unsigned Values = 1 + unsigned(IdxList.size());
936 if (!PointeeType)
937 PointeeType =
938 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
939 else
940 assert(
941 PointeeType ==
942 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
943 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
944 NameStr, InsertAtEnd);
947 /// Create an "inbounds" getelementptr. See the documentation for the
948 /// "inbounds" flag in LangRef.html for details.
949 static GetElementPtrInst *CreateInBounds(Value *Ptr,
950 ArrayRef<Value *> IdxList,
951 const Twine &NameStr = "",
952 Instruction *InsertBefore = nullptr){
953 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
956 static GetElementPtrInst *
957 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
958 const Twine &NameStr = "",
959 Instruction *InsertBefore = nullptr) {
960 GetElementPtrInst *GEP =
961 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
962 GEP->setIsInBounds(true);
963 return GEP;
966 static GetElementPtrInst *CreateInBounds(Value *Ptr,
967 ArrayRef<Value *> IdxList,
968 const Twine &NameStr,
969 BasicBlock *InsertAtEnd) {
970 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
973 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
974 ArrayRef<Value *> IdxList,
975 const Twine &NameStr,
976 BasicBlock *InsertAtEnd) {
977 GetElementPtrInst *GEP =
978 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
979 GEP->setIsInBounds(true);
980 return GEP;
983 /// Transparently provide more efficient getOperand methods.
984 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
986 Type *getSourceElementType() const { return SourceElementType; }
988 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
989 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
991 Type *getResultElementType() const {
992 assert(ResultElementType ==
993 cast<PointerType>(getType()->getScalarType())->getElementType());
994 return ResultElementType;
997 /// Returns the address space of this instruction's pointer type.
998 unsigned getAddressSpace() const {
999 // Note that this is always the same as the pointer operand's address space
1000 // and that is cheaper to compute, so cheat here.
1001 return getPointerAddressSpace();
1004 /// Returns the type of the element that would be loaded with
1005 /// a load instruction with the specified parameters.
1007 /// Null is returned if the indices are invalid for the specified
1008 /// pointer type.
1010 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1011 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1012 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1014 inline op_iterator idx_begin() { return op_begin()+1; }
1015 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1016 inline op_iterator idx_end() { return op_end(); }
1017 inline const_op_iterator idx_end() const { return op_end(); }
1019 inline iterator_range<op_iterator> indices() {
1020 return make_range(idx_begin(), idx_end());
1023 inline iterator_range<const_op_iterator> indices() const {
1024 return make_range(idx_begin(), idx_end());
1027 Value *getPointerOperand() {
1028 return getOperand(0);
1030 const Value *getPointerOperand() const {
1031 return getOperand(0);
1033 static unsigned getPointerOperandIndex() {
1034 return 0U; // get index for modifying correct operand.
1037 /// Method to return the pointer operand as a
1038 /// PointerType.
1039 Type *getPointerOperandType() const {
1040 return getPointerOperand()->getType();
1043 /// Returns the address space of the pointer operand.
1044 unsigned getPointerAddressSpace() const {
1045 return getPointerOperandType()->getPointerAddressSpace();
1048 /// Returns the pointer type returned by the GEP
1049 /// instruction, which may be a vector of pointers.
1050 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
1051 return getGEPReturnType(
1052 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1053 Ptr, IdxList);
1055 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1056 ArrayRef<Value *> IdxList) {
1057 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1058 Ptr->getType()->getPointerAddressSpace());
1059 // Vector GEP
1060 if (Ptr->getType()->isVectorTy()) {
1061 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1062 return VectorType::get(PtrTy, NumElem);
1064 for (Value *Index : IdxList)
1065 if (Index->getType()->isVectorTy()) {
1066 unsigned NumElem = Index->getType()->getVectorNumElements();
1067 return VectorType::get(PtrTy, NumElem);
1069 // Scalar GEP
1070 return PtrTy;
1073 unsigned getNumIndices() const { // Note: always non-negative
1074 return getNumOperands() - 1;
1077 bool hasIndices() const {
1078 return getNumOperands() > 1;
1081 /// Return true if all of the indices of this GEP are
1082 /// zeros. If so, the result pointer and the first operand have the same
1083 /// value, just potentially different types.
1084 bool hasAllZeroIndices() const;
1086 /// Return true if all of the indices of this GEP are
1087 /// constant integers. If so, the result pointer and the first operand have
1088 /// a constant offset between them.
1089 bool hasAllConstantIndices() const;
1091 /// Set or clear the inbounds flag on this GEP instruction.
1092 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1093 void setIsInBounds(bool b = true);
1095 /// Determine whether the GEP has the inbounds flag.
1096 bool isInBounds() const;
1098 /// Accumulate the constant address offset of this GEP if possible.
1100 /// This routine accepts an APInt into which it will accumulate the constant
1101 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1102 /// all-constant, it returns false and the value of the offset APInt is
1103 /// undefined (it is *not* preserved!). The APInt passed into this routine
1104 /// must be at least as wide as the IntPtr type for the address space of
1105 /// the base GEP pointer.
1106 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1108 // Methods for support type inquiry through isa, cast, and dyn_cast:
1109 static bool classof(const Instruction *I) {
1110 return (I->getOpcode() == Instruction::GetElementPtr);
1112 static bool classof(const Value *V) {
1113 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1117 template <>
1118 struct OperandTraits<GetElementPtrInst> :
1119 public VariadicOperandTraits<GetElementPtrInst, 1> {
1122 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1123 ArrayRef<Value *> IdxList, unsigned Values,
1124 const Twine &NameStr,
1125 Instruction *InsertBefore)
1126 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1127 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1128 Values, InsertBefore),
1129 SourceElementType(PointeeType),
1130 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1131 assert(ResultElementType ==
1132 cast<PointerType>(getType()->getScalarType())->getElementType());
1133 init(Ptr, IdxList, NameStr);
1136 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1137 ArrayRef<Value *> IdxList, unsigned Values,
1138 const Twine &NameStr,
1139 BasicBlock *InsertAtEnd)
1140 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1141 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1142 Values, InsertAtEnd),
1143 SourceElementType(PointeeType),
1144 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1145 assert(ResultElementType ==
1146 cast<PointerType>(getType()->getScalarType())->getElementType());
1147 init(Ptr, IdxList, NameStr);
1150 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1152 //===----------------------------------------------------------------------===//
1153 // ICmpInst Class
1154 //===----------------------------------------------------------------------===//
1156 /// This instruction compares its operands according to the predicate given
1157 /// to the constructor. It only operates on integers or pointers. The operands
1158 /// must be identical types.
1159 /// Represent an integer comparison operator.
1160 class ICmpInst: public CmpInst {
1161 void AssertOK() {
1162 assert(isIntPredicate() &&
1163 "Invalid ICmp predicate value");
1164 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1165 "Both operands to ICmp instruction are not of the same type!");
1166 // Check that the operands are the right type
1167 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1168 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1169 "Invalid operand types for ICmp instruction");
1172 protected:
1173 // Note: Instruction needs to be a friend here to call cloneImpl.
1174 friend class Instruction;
1176 /// Clone an identical ICmpInst
1177 ICmpInst *cloneImpl() const;
1179 public:
1180 /// Constructor with insert-before-instruction semantics.
1181 ICmpInst(
1182 Instruction *InsertBefore, ///< Where to insert
1183 Predicate pred, ///< The predicate to use for the comparison
1184 Value *LHS, ///< The left-hand-side of the expression
1185 Value *RHS, ///< The right-hand-side of the expression
1186 const Twine &NameStr = "" ///< Name of the instruction
1187 ) : CmpInst(makeCmpResultType(LHS->getType()),
1188 Instruction::ICmp, pred, LHS, RHS, NameStr,
1189 InsertBefore) {
1190 #ifndef NDEBUG
1191 AssertOK();
1192 #endif
1195 /// Constructor with insert-at-end semantics.
1196 ICmpInst(
1197 BasicBlock &InsertAtEnd, ///< Block to insert into.
1198 Predicate pred, ///< The predicate to use for the comparison
1199 Value *LHS, ///< The left-hand-side of the expression
1200 Value *RHS, ///< The right-hand-side of the expression
1201 const Twine &NameStr = "" ///< Name of the instruction
1202 ) : CmpInst(makeCmpResultType(LHS->getType()),
1203 Instruction::ICmp, pred, LHS, RHS, NameStr,
1204 &InsertAtEnd) {
1205 #ifndef NDEBUG
1206 AssertOK();
1207 #endif
1210 /// Constructor with no-insertion semantics
1211 ICmpInst(
1212 Predicate pred, ///< The predicate to use for the comparison
1213 Value *LHS, ///< The left-hand-side of the expression
1214 Value *RHS, ///< The right-hand-side of the expression
1215 const Twine &NameStr = "" ///< Name of the instruction
1216 ) : CmpInst(makeCmpResultType(LHS->getType()),
1217 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1218 #ifndef NDEBUG
1219 AssertOK();
1220 #endif
1223 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1224 /// @returns the predicate that would be the result if the operand were
1225 /// regarded as signed.
1226 /// Return the signed version of the predicate
1227 Predicate getSignedPredicate() const {
1228 return getSignedPredicate(getPredicate());
1231 /// This is a static version that you can use without an instruction.
1232 /// Return the signed version of the predicate.
1233 static Predicate getSignedPredicate(Predicate pred);
1235 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1236 /// @returns the predicate that would be the result if the operand were
1237 /// regarded as unsigned.
1238 /// Return the unsigned version of the predicate
1239 Predicate getUnsignedPredicate() const {
1240 return getUnsignedPredicate(getPredicate());
1243 /// This is a static version that you can use without an instruction.
1244 /// Return the unsigned version of the predicate.
1245 static Predicate getUnsignedPredicate(Predicate pred);
1247 /// Return true if this predicate is either EQ or NE. This also
1248 /// tests for commutativity.
1249 static bool isEquality(Predicate P) {
1250 return P == ICMP_EQ || P == ICMP_NE;
1253 /// Return true if this predicate is either EQ or NE. This also
1254 /// tests for commutativity.
1255 bool isEquality() const {
1256 return isEquality(getPredicate());
1259 /// @returns true if the predicate of this ICmpInst is commutative
1260 /// Determine if this relation is commutative.
1261 bool isCommutative() const { return isEquality(); }
1263 /// Return true if the predicate is relational (not EQ or NE).
1265 bool isRelational() const {
1266 return !isEquality();
1269 /// Return true if the predicate is relational (not EQ or NE).
1271 static bool isRelational(Predicate P) {
1272 return !isEquality(P);
1275 /// Exchange the two operands to this instruction in such a way that it does
1276 /// not modify the semantics of the instruction. The predicate value may be
1277 /// changed to retain the same result if the predicate is order dependent
1278 /// (e.g. ult).
1279 /// Swap operands and adjust predicate.
1280 void swapOperands() {
1281 setPredicate(getSwappedPredicate());
1282 Op<0>().swap(Op<1>());
1285 // Methods for support type inquiry through isa, cast, and dyn_cast:
1286 static bool classof(const Instruction *I) {
1287 return I->getOpcode() == Instruction::ICmp;
1289 static bool classof(const Value *V) {
1290 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1294 //===----------------------------------------------------------------------===//
1295 // FCmpInst Class
1296 //===----------------------------------------------------------------------===//
1298 /// This instruction compares its operands according to the predicate given
1299 /// to the constructor. It only operates on floating point values or packed
1300 /// vectors of floating point values. The operands must be identical types.
1301 /// Represents a floating point comparison operator.
1302 class FCmpInst: public CmpInst {
1303 void AssertOK() {
1304 assert(isFPPredicate() && "Invalid FCmp predicate value");
1305 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1306 "Both operands to FCmp instruction are not of the same type!");
1307 // Check that the operands are the right type
1308 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1309 "Invalid operand types for FCmp instruction");
1312 protected:
1313 // Note: Instruction needs to be a friend here to call cloneImpl.
1314 friend class Instruction;
1316 /// Clone an identical FCmpInst
1317 FCmpInst *cloneImpl() const;
1319 public:
1320 /// Constructor with insert-before-instruction semantics.
1321 FCmpInst(
1322 Instruction *InsertBefore, ///< Where to insert
1323 Predicate pred, ///< The predicate to use for the comparison
1324 Value *LHS, ///< The left-hand-side of the expression
1325 Value *RHS, ///< The right-hand-side of the expression
1326 const Twine &NameStr = "" ///< Name of the instruction
1327 ) : CmpInst(makeCmpResultType(LHS->getType()),
1328 Instruction::FCmp, pred, LHS, RHS, NameStr,
1329 InsertBefore) {
1330 AssertOK();
1333 /// Constructor with insert-at-end semantics.
1334 FCmpInst(
1335 BasicBlock &InsertAtEnd, ///< Block to insert into.
1336 Predicate pred, ///< The predicate to use for the comparison
1337 Value *LHS, ///< The left-hand-side of the expression
1338 Value *RHS, ///< The right-hand-side of the expression
1339 const Twine &NameStr = "" ///< Name of the instruction
1340 ) : CmpInst(makeCmpResultType(LHS->getType()),
1341 Instruction::FCmp, pred, LHS, RHS, NameStr,
1342 &InsertAtEnd) {
1343 AssertOK();
1346 /// Constructor with no-insertion semantics
1347 FCmpInst(
1348 Predicate Pred, ///< The predicate to use for the comparison
1349 Value *LHS, ///< The left-hand-side of the expression
1350 Value *RHS, ///< The right-hand-side of the expression
1351 const Twine &NameStr = "", ///< Name of the instruction
1352 Instruction *FlagsSource = nullptr
1353 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1354 RHS, NameStr, nullptr, FlagsSource) {
1355 AssertOK();
1358 /// @returns true if the predicate of this instruction is EQ or NE.
1359 /// Determine if this is an equality predicate.
1360 static bool isEquality(Predicate Pred) {
1361 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1362 Pred == FCMP_UNE;
1365 /// @returns true if the predicate of this instruction is EQ or NE.
1366 /// Determine if this is an equality predicate.
1367 bool isEquality() const { return isEquality(getPredicate()); }
1369 /// @returns true if the predicate of this instruction is commutative.
1370 /// Determine if this is a commutative predicate.
1371 bool isCommutative() const {
1372 return isEquality() ||
1373 getPredicate() == FCMP_FALSE ||
1374 getPredicate() == FCMP_TRUE ||
1375 getPredicate() == FCMP_ORD ||
1376 getPredicate() == FCMP_UNO;
1379 /// @returns true if the predicate is relational (not EQ or NE).
1380 /// Determine if this a relational predicate.
1381 bool isRelational() const { return !isEquality(); }
1383 /// Exchange the two operands to this instruction in such a way that it does
1384 /// not modify the semantics of the instruction. The predicate value may be
1385 /// changed to retain the same result if the predicate is order dependent
1386 /// (e.g. ult).
1387 /// Swap operands and adjust predicate.
1388 void swapOperands() {
1389 setPredicate(getSwappedPredicate());
1390 Op<0>().swap(Op<1>());
1393 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1394 static bool classof(const Instruction *I) {
1395 return I->getOpcode() == Instruction::FCmp;
1397 static bool classof(const Value *V) {
1398 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1402 //===----------------------------------------------------------------------===//
1403 /// This class represents a function call, abstracting a target
1404 /// machine's calling convention. This class uses low bit of the SubClassData
1405 /// field to indicate whether or not this is a tail call. The rest of the bits
1406 /// hold the calling convention of the call.
1408 class CallInst : public CallBase {
1409 CallInst(const CallInst &CI);
1411 /// Construct a CallInst given a range of arguments.
1412 /// Construct a CallInst from a range of arguments
1413 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1414 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1415 Instruction *InsertBefore);
1417 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1418 const Twine &NameStr, Instruction *InsertBefore)
1419 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1421 /// Construct a CallInst given a range of arguments.
1422 /// Construct a CallInst from a range of arguments
1423 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1424 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1425 BasicBlock *InsertAtEnd);
1427 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1428 Instruction *InsertBefore);
1430 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1431 BasicBlock *InsertAtEnd);
1433 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1434 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1435 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1437 /// Compute the number of operands to allocate.
1438 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1439 // We need one operand for the called function, plus the input operand
1440 // counts provided.
1441 return 1 + NumArgs + NumBundleInputs;
1444 protected:
1445 // Note: Instruction needs to be a friend here to call cloneImpl.
1446 friend class Instruction;
1448 CallInst *cloneImpl() const;
1450 public:
1451 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1452 Instruction *InsertBefore = nullptr) {
1453 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1456 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1457 const Twine &NameStr,
1458 Instruction *InsertBefore = nullptr) {
1459 return new (ComputeNumOperands(Args.size()))
1460 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1463 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1464 ArrayRef<OperandBundleDef> Bundles = None,
1465 const Twine &NameStr = "",
1466 Instruction *InsertBefore = nullptr) {
1467 const int NumOperands =
1468 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1469 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1471 return new (NumOperands, DescriptorBytes)
1472 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1475 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1476 BasicBlock *InsertAtEnd) {
1477 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1480 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1481 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1482 return new (ComputeNumOperands(Args.size()))
1483 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1486 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1487 ArrayRef<OperandBundleDef> Bundles,
1488 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1489 const int NumOperands =
1490 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1491 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1493 return new (NumOperands, DescriptorBytes)
1494 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1497 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1498 Instruction *InsertBefore = nullptr) {
1499 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1500 InsertBefore);
1503 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1504 ArrayRef<OperandBundleDef> Bundles = None,
1505 const Twine &NameStr = "",
1506 Instruction *InsertBefore = nullptr) {
1507 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1508 NameStr, InsertBefore);
1511 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1512 const Twine &NameStr,
1513 Instruction *InsertBefore = nullptr) {
1514 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1515 InsertBefore);
1518 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1519 BasicBlock *InsertAtEnd) {
1520 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1521 InsertAtEnd);
1524 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1525 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1526 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1527 InsertAtEnd);
1530 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1531 ArrayRef<OperandBundleDef> Bundles,
1532 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1533 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1534 NameStr, InsertAtEnd);
1537 // Deprecated [opaque pointer types]
1538 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1539 Instruction *InsertBefore = nullptr) {
1540 return Create(cast<FunctionType>(
1541 cast<PointerType>(Func->getType())->getElementType()),
1542 Func, NameStr, InsertBefore);
1545 // Deprecated [opaque pointer types]
1546 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1547 const Twine &NameStr,
1548 Instruction *InsertBefore = nullptr) {
1549 return Create(cast<FunctionType>(
1550 cast<PointerType>(Func->getType())->getElementType()),
1551 Func, Args, NameStr, InsertBefore);
1554 // Deprecated [opaque pointer types]
1555 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1556 ArrayRef<OperandBundleDef> Bundles = None,
1557 const Twine &NameStr = "",
1558 Instruction *InsertBefore = nullptr) {
1559 return Create(cast<FunctionType>(
1560 cast<PointerType>(Func->getType())->getElementType()),
1561 Func, Args, Bundles, NameStr, InsertBefore);
1564 // Deprecated [opaque pointer types]
1565 static CallInst *Create(Value *Func, const Twine &NameStr,
1566 BasicBlock *InsertAtEnd) {
1567 return Create(cast<FunctionType>(
1568 cast<PointerType>(Func->getType())->getElementType()),
1569 Func, NameStr, InsertAtEnd);
1572 // Deprecated [opaque pointer types]
1573 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1574 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1575 return Create(cast<FunctionType>(
1576 cast<PointerType>(Func->getType())->getElementType()),
1577 Func, Args, NameStr, InsertAtEnd);
1580 // Deprecated [opaque pointer types]
1581 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1582 ArrayRef<OperandBundleDef> Bundles,
1583 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1584 return Create(cast<FunctionType>(
1585 cast<PointerType>(Func->getType())->getElementType()),
1586 Func, Args, Bundles, NameStr, InsertAtEnd);
1589 /// Create a clone of \p CI with a different set of operand bundles and
1590 /// insert it before \p InsertPt.
1592 /// The returned call instruction is identical \p CI in every way except that
1593 /// the operand bundles for the new instruction are set to the operand bundles
1594 /// in \p Bundles.
1595 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1596 Instruction *InsertPt = nullptr);
1598 /// Generate the IR for a call to malloc:
1599 /// 1. Compute the malloc call's argument as the specified type's size,
1600 /// possibly multiplied by the array size if the array size is not
1601 /// constant 1.
1602 /// 2. Call malloc with that argument.
1603 /// 3. Bitcast the result of the malloc call to the specified type.
1604 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1605 Type *AllocTy, Value *AllocSize,
1606 Value *ArraySize = nullptr,
1607 Function *MallocF = nullptr,
1608 const Twine &Name = "");
1609 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1610 Type *AllocTy, Value *AllocSize,
1611 Value *ArraySize = nullptr,
1612 Function *MallocF = nullptr,
1613 const Twine &Name = "");
1614 static Instruction *CreateMalloc(Instruction *InsertBefore, 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 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1621 Type *AllocTy, Value *AllocSize,
1622 Value *ArraySize = nullptr,
1623 ArrayRef<OperandBundleDef> Bundles = None,
1624 Function *MallocF = nullptr,
1625 const Twine &Name = "");
1626 /// Generate the IR for a call to the builtin free function.
1627 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1628 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1629 static Instruction *CreateFree(Value *Source,
1630 ArrayRef<OperandBundleDef> Bundles,
1631 Instruction *InsertBefore);
1632 static Instruction *CreateFree(Value *Source,
1633 ArrayRef<OperandBundleDef> Bundles,
1634 BasicBlock *InsertAtEnd);
1636 // Note that 'musttail' implies 'tail'.
1637 enum TailCallKind {
1638 TCK_None = 0,
1639 TCK_Tail = 1,
1640 TCK_MustTail = 2,
1641 TCK_NoTail = 3
1643 TailCallKind getTailCallKind() const {
1644 return TailCallKind(getSubclassDataFromInstruction() & 3);
1647 bool isTailCall() const {
1648 unsigned Kind = getSubclassDataFromInstruction() & 3;
1649 return Kind == TCK_Tail || Kind == TCK_MustTail;
1652 bool isMustTailCall() const {
1653 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1656 bool isNoTailCall() const {
1657 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1660 void setTailCall(bool isTC = true) {
1661 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1662 unsigned(isTC ? TCK_Tail : TCK_None));
1665 void setTailCallKind(TailCallKind TCK) {
1666 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1667 unsigned(TCK));
1670 /// Return true if the call can return twice
1671 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1672 void setCanReturnTwice() {
1673 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1676 // Methods for support type inquiry through isa, cast, and dyn_cast:
1677 static bool classof(const Instruction *I) {
1678 return I->getOpcode() == Instruction::Call;
1680 static bool classof(const Value *V) {
1681 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1684 /// Updates profile metadata by scaling it by \p S / \p T.
1685 void updateProfWeight(uint64_t S, uint64_t T);
1687 private:
1688 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1689 // method so that subclasses cannot accidentally use it.
1690 void setInstructionSubclassData(unsigned short D) {
1691 Instruction::setInstructionSubclassData(D);
1695 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1696 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1697 BasicBlock *InsertAtEnd)
1698 : CallBase(Ty->getReturnType(), Instruction::Call,
1699 OperandTraits<CallBase>::op_end(this) -
1700 (Args.size() + CountBundleInputs(Bundles) + 1),
1701 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1702 InsertAtEnd) {
1703 init(Ty, Func, Args, Bundles, NameStr);
1706 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1707 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1708 Instruction *InsertBefore)
1709 : CallBase(Ty->getReturnType(), Instruction::Call,
1710 OperandTraits<CallBase>::op_end(this) -
1711 (Args.size() + CountBundleInputs(Bundles) + 1),
1712 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1713 InsertBefore) {
1714 init(Ty, Func, Args, Bundles, NameStr);
1717 //===----------------------------------------------------------------------===//
1718 // SelectInst Class
1719 //===----------------------------------------------------------------------===//
1721 /// This class represents the LLVM 'select' instruction.
1723 class SelectInst : public Instruction {
1724 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1725 Instruction *InsertBefore)
1726 : Instruction(S1->getType(), Instruction::Select,
1727 &Op<0>(), 3, InsertBefore) {
1728 init(C, S1, S2);
1729 setName(NameStr);
1732 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1733 BasicBlock *InsertAtEnd)
1734 : Instruction(S1->getType(), Instruction::Select,
1735 &Op<0>(), 3, InsertAtEnd) {
1736 init(C, S1, S2);
1737 setName(NameStr);
1740 void init(Value *C, Value *S1, Value *S2) {
1741 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1742 Op<0>() = C;
1743 Op<1>() = S1;
1744 Op<2>() = S2;
1747 protected:
1748 // Note: Instruction needs to be a friend here to call cloneImpl.
1749 friend class Instruction;
1751 SelectInst *cloneImpl() const;
1753 public:
1754 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1755 const Twine &NameStr = "",
1756 Instruction *InsertBefore = nullptr,
1757 Instruction *MDFrom = nullptr) {
1758 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1759 if (MDFrom)
1760 Sel->copyMetadata(*MDFrom);
1761 return Sel;
1764 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1765 const Twine &NameStr,
1766 BasicBlock *InsertAtEnd) {
1767 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1770 const Value *getCondition() const { return Op<0>(); }
1771 const Value *getTrueValue() const { return Op<1>(); }
1772 const Value *getFalseValue() const { return Op<2>(); }
1773 Value *getCondition() { return Op<0>(); }
1774 Value *getTrueValue() { return Op<1>(); }
1775 Value *getFalseValue() { return Op<2>(); }
1777 void setCondition(Value *V) { Op<0>() = V; }
1778 void setTrueValue(Value *V) { Op<1>() = V; }
1779 void setFalseValue(Value *V) { Op<2>() = V; }
1781 /// Swap the true and false values of the select instruction.
1782 /// This doesn't swap prof metadata.
1783 void swapValues() { Op<1>().swap(Op<2>()); }
1785 /// Return a string if the specified operands are invalid
1786 /// for a select operation, otherwise return null.
1787 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1789 /// Transparently provide more efficient getOperand methods.
1790 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1792 OtherOps getOpcode() const {
1793 return static_cast<OtherOps>(Instruction::getOpcode());
1796 // Methods for support type inquiry through isa, cast, and dyn_cast:
1797 static bool classof(const Instruction *I) {
1798 return I->getOpcode() == Instruction::Select;
1800 static bool classof(const Value *V) {
1801 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1805 template <>
1806 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1809 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1811 //===----------------------------------------------------------------------===//
1812 // VAArgInst Class
1813 //===----------------------------------------------------------------------===//
1815 /// This class represents the va_arg llvm instruction, which returns
1816 /// an argument of the specified type given a va_list and increments that list
1818 class VAArgInst : public UnaryInstruction {
1819 protected:
1820 // Note: Instruction needs to be a friend here to call cloneImpl.
1821 friend class Instruction;
1823 VAArgInst *cloneImpl() const;
1825 public:
1826 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1827 Instruction *InsertBefore = nullptr)
1828 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1829 setName(NameStr);
1832 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1833 BasicBlock *InsertAtEnd)
1834 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1835 setName(NameStr);
1838 Value *getPointerOperand() { return getOperand(0); }
1839 const Value *getPointerOperand() const { return getOperand(0); }
1840 static unsigned getPointerOperandIndex() { return 0U; }
1842 // Methods for support type inquiry through isa, cast, and dyn_cast:
1843 static bool classof(const Instruction *I) {
1844 return I->getOpcode() == VAArg;
1846 static bool classof(const Value *V) {
1847 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1851 //===----------------------------------------------------------------------===//
1852 // ExtractElementInst Class
1853 //===----------------------------------------------------------------------===//
1855 /// This instruction extracts a single (scalar)
1856 /// element from a VectorType value
1858 class ExtractElementInst : public Instruction {
1859 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1860 Instruction *InsertBefore = nullptr);
1861 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1862 BasicBlock *InsertAtEnd);
1864 protected:
1865 // Note: Instruction needs to be a friend here to call cloneImpl.
1866 friend class Instruction;
1868 ExtractElementInst *cloneImpl() const;
1870 public:
1871 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1872 const Twine &NameStr = "",
1873 Instruction *InsertBefore = nullptr) {
1874 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1877 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1878 const Twine &NameStr,
1879 BasicBlock *InsertAtEnd) {
1880 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1883 /// Return true if an extractelement instruction can be
1884 /// formed with the specified operands.
1885 static bool isValidOperands(const Value *Vec, const Value *Idx);
1887 Value *getVectorOperand() { return Op<0>(); }
1888 Value *getIndexOperand() { return Op<1>(); }
1889 const Value *getVectorOperand() const { return Op<0>(); }
1890 const Value *getIndexOperand() const { return Op<1>(); }
1892 VectorType *getVectorOperandType() const {
1893 return cast<VectorType>(getVectorOperand()->getType());
1896 /// Transparently provide more efficient getOperand methods.
1897 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1899 // Methods for support type inquiry through isa, cast, and dyn_cast:
1900 static bool classof(const Instruction *I) {
1901 return I->getOpcode() == Instruction::ExtractElement;
1903 static bool classof(const Value *V) {
1904 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1908 template <>
1909 struct OperandTraits<ExtractElementInst> :
1910 public FixedNumOperandTraits<ExtractElementInst, 2> {
1913 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1915 //===----------------------------------------------------------------------===//
1916 // InsertElementInst Class
1917 //===----------------------------------------------------------------------===//
1919 /// This instruction inserts a single (scalar)
1920 /// element into a VectorType value
1922 class InsertElementInst : public Instruction {
1923 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1924 const Twine &NameStr = "",
1925 Instruction *InsertBefore = nullptr);
1926 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1927 BasicBlock *InsertAtEnd);
1929 protected:
1930 // Note: Instruction needs to be a friend here to call cloneImpl.
1931 friend class Instruction;
1933 InsertElementInst *cloneImpl() const;
1935 public:
1936 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1937 const Twine &NameStr = "",
1938 Instruction *InsertBefore = nullptr) {
1939 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1942 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1943 const Twine &NameStr,
1944 BasicBlock *InsertAtEnd) {
1945 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1948 /// Return true if an insertelement instruction can be
1949 /// formed with the specified operands.
1950 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1951 const Value *Idx);
1953 /// Overload to return most specific vector type.
1955 VectorType *getType() const {
1956 return cast<VectorType>(Instruction::getType());
1959 /// Transparently provide more efficient getOperand methods.
1960 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1962 // Methods for support type inquiry through isa, cast, and dyn_cast:
1963 static bool classof(const Instruction *I) {
1964 return I->getOpcode() == Instruction::InsertElement;
1966 static bool classof(const Value *V) {
1967 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1971 template <>
1972 struct OperandTraits<InsertElementInst> :
1973 public FixedNumOperandTraits<InsertElementInst, 3> {
1976 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
1978 //===----------------------------------------------------------------------===//
1979 // ShuffleVectorInst Class
1980 //===----------------------------------------------------------------------===//
1982 /// This instruction constructs a fixed permutation of two
1983 /// input vectors.
1985 class ShuffleVectorInst : public Instruction {
1986 protected:
1987 // Note: Instruction needs to be a friend here to call cloneImpl.
1988 friend class Instruction;
1990 ShuffleVectorInst *cloneImpl() const;
1992 public:
1993 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1994 const Twine &NameStr = "",
1995 Instruction *InsertBefor = nullptr);
1996 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1997 const Twine &NameStr, BasicBlock *InsertAtEnd);
1999 // allocate space for exactly three operands
2000 void *operator new(size_t s) {
2001 return User::operator new(s, 3);
2004 /// Swap the first 2 operands and adjust the mask to preserve the semantics
2005 /// of the instruction.
2006 void commute();
2008 /// Return true if a shufflevector instruction can be
2009 /// formed with the specified operands.
2010 static bool isValidOperands(const Value *V1, const Value *V2,
2011 const Value *Mask);
2013 /// Overload to return most specific vector type.
2015 VectorType *getType() const {
2016 return cast<VectorType>(Instruction::getType());
2019 /// Transparently provide more efficient getOperand methods.
2020 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2022 Constant *getMask() const {
2023 return cast<Constant>(getOperand(2));
2026 /// Return the shuffle mask value for the specified element of the mask.
2027 /// Return -1 if the element is undef.
2028 static int getMaskValue(const Constant *Mask, unsigned Elt);
2030 /// Return the shuffle mask value of this instruction for the given element
2031 /// index. Return -1 if the element is undef.
2032 int getMaskValue(unsigned Elt) const {
2033 return getMaskValue(getMask(), Elt);
2036 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2037 /// elements of the mask are returned as -1.
2038 static void getShuffleMask(const Constant *Mask,
2039 SmallVectorImpl<int> &Result);
2041 /// Return the mask for this instruction as a vector of integers. Undefined
2042 /// elements of the mask are returned as -1.
2043 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2044 return getShuffleMask(getMask(), Result);
2047 SmallVector<int, 16> getShuffleMask() const {
2048 SmallVector<int, 16> Mask;
2049 getShuffleMask(Mask);
2050 return Mask;
2053 /// Return true if this shuffle returns a vector with a different number of
2054 /// elements than its source vectors.
2055 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2056 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2057 bool changesLength() const {
2058 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2059 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2060 return NumSourceElts != NumMaskElts;
2063 /// Return true if this shuffle returns a vector with a greater number of
2064 /// elements than its source vectors.
2065 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2066 bool increasesLength() const {
2067 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2068 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2069 return NumSourceElts < NumMaskElts;
2072 /// Return true if this shuffle mask chooses elements from exactly one source
2073 /// vector.
2074 /// Example: <7,5,undef,7>
2075 /// This assumes that vector operands are the same length as the mask.
2076 static bool isSingleSourceMask(ArrayRef<int> Mask);
2077 static bool isSingleSourceMask(const Constant *Mask) {
2078 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2079 SmallVector<int, 16> MaskAsInts;
2080 getShuffleMask(Mask, MaskAsInts);
2081 return isSingleSourceMask(MaskAsInts);
2084 /// Return true if this shuffle chooses elements from exactly one source
2085 /// vector without changing the length of that vector.
2086 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2087 /// TODO: Optionally allow length-changing shuffles.
2088 bool isSingleSource() const {
2089 return !changesLength() && isSingleSourceMask(getMask());
2092 /// Return true if this shuffle mask chooses elements from exactly one source
2093 /// vector without lane crossings. A shuffle using this mask is not
2094 /// necessarily a no-op because it may change the number of elements from its
2095 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2096 /// Example: <undef,undef,2,3>
2097 static bool isIdentityMask(ArrayRef<int> Mask);
2098 static bool isIdentityMask(const Constant *Mask) {
2099 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2100 SmallVector<int, 16> MaskAsInts;
2101 getShuffleMask(Mask, MaskAsInts);
2102 return isIdentityMask(MaskAsInts);
2105 /// Return true if this shuffle chooses elements from exactly one source
2106 /// vector without lane crossings and does not change the number of elements
2107 /// from its input vectors.
2108 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2109 bool isIdentity() const {
2110 return !changesLength() && isIdentityMask(getShuffleMask());
2113 /// Return true if this shuffle lengthens exactly one source vector with
2114 /// undefs in the high elements.
2115 bool isIdentityWithPadding() const;
2117 /// Return true if this shuffle extracts the first N elements of exactly one
2118 /// source vector.
2119 bool isIdentityWithExtract() const;
2121 /// Return true if this shuffle concatenates its 2 source vectors. This
2122 /// returns false if either input is undefined. In that case, the shuffle is
2123 /// is better classified as an identity with padding operation.
2124 bool isConcat() const;
2126 /// Return true if this shuffle mask chooses elements from its source vectors
2127 /// without lane crossings. A shuffle using this mask would be
2128 /// equivalent to a vector select with a constant condition operand.
2129 /// Example: <4,1,6,undef>
2130 /// This returns false if the mask does not choose from both input vectors.
2131 /// In that case, the shuffle is better classified as an identity shuffle.
2132 /// This assumes that vector operands are the same length as the mask
2133 /// (a length-changing shuffle can never be equivalent to a vector select).
2134 static bool isSelectMask(ArrayRef<int> Mask);
2135 static bool isSelectMask(const Constant *Mask) {
2136 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2137 SmallVector<int, 16> MaskAsInts;
2138 getShuffleMask(Mask, MaskAsInts);
2139 return isSelectMask(MaskAsInts);
2142 /// Return true if this shuffle chooses elements from its source vectors
2143 /// without lane crossings and all operands have the same number of elements.
2144 /// In other words, this shuffle is equivalent to a vector select with a
2145 /// constant condition operand.
2146 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2147 /// This returns false if the mask does not choose from both input vectors.
2148 /// In that case, the shuffle is better classified as an identity shuffle.
2149 /// TODO: Optionally allow length-changing shuffles.
2150 bool isSelect() const {
2151 return !changesLength() && isSelectMask(getMask());
2154 /// Return true if this shuffle mask swaps the order of elements from exactly
2155 /// one source vector.
2156 /// Example: <7,6,undef,4>
2157 /// This assumes that vector operands are the same length as the mask.
2158 static bool isReverseMask(ArrayRef<int> Mask);
2159 static bool isReverseMask(const Constant *Mask) {
2160 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2161 SmallVector<int, 16> MaskAsInts;
2162 getShuffleMask(Mask, MaskAsInts);
2163 return isReverseMask(MaskAsInts);
2166 /// Return true if this shuffle swaps the order of elements from exactly
2167 /// one source vector.
2168 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2169 /// TODO: Optionally allow length-changing shuffles.
2170 bool isReverse() const {
2171 return !changesLength() && isReverseMask(getMask());
2174 /// Return true if this shuffle mask chooses all elements with the same value
2175 /// as the first element of exactly one source vector.
2176 /// Example: <4,undef,undef,4>
2177 /// This assumes that vector operands are the same length as the mask.
2178 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2179 static bool isZeroEltSplatMask(const Constant *Mask) {
2180 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2181 SmallVector<int, 16> MaskAsInts;
2182 getShuffleMask(Mask, MaskAsInts);
2183 return isZeroEltSplatMask(MaskAsInts);
2186 /// Return true if all elements of this shuffle are the same value as the
2187 /// first element of exactly one source vector without changing the length
2188 /// of that vector.
2189 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2190 /// TODO: Optionally allow length-changing shuffles.
2191 /// TODO: Optionally allow splats from other elements.
2192 bool isZeroEltSplat() const {
2193 return !changesLength() && isZeroEltSplatMask(getMask());
2196 /// Return true if this shuffle mask is a transpose mask.
2197 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2198 /// even- or odd-numbered vector elements from two n-dimensional source
2199 /// vectors and write each result into consecutive elements of an
2200 /// n-dimensional destination vector. Two shuffles are necessary to complete
2201 /// the transpose, one for the even elements and another for the odd elements.
2202 /// This description closely follows how the TRN1 and TRN2 AArch64
2203 /// instructions operate.
2205 /// For example, a simple 2x2 matrix can be transposed with:
2207 /// ; Original matrix
2208 /// m0 = < a, b >
2209 /// m1 = < c, d >
2211 /// ; Transposed matrix
2212 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2213 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2215 /// For matrices having greater than n columns, the resulting nx2 transposed
2216 /// matrix is stored in two result vectors such that one vector contains
2217 /// interleaved elements from all the even-numbered rows and the other vector
2218 /// contains interleaved elements from all the odd-numbered rows. For example,
2219 /// a 2x4 matrix can be transposed with:
2221 /// ; Original matrix
2222 /// m0 = < a, b, c, d >
2223 /// m1 = < e, f, g, h >
2225 /// ; Transposed matrix
2226 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2227 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2228 static bool isTransposeMask(ArrayRef<int> Mask);
2229 static bool isTransposeMask(const Constant *Mask) {
2230 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2231 SmallVector<int, 16> MaskAsInts;
2232 getShuffleMask(Mask, MaskAsInts);
2233 return isTransposeMask(MaskAsInts);
2236 /// Return true if this shuffle transposes the elements of its inputs without
2237 /// changing the length of the vectors. This operation may also be known as a
2238 /// merge or interleave. See the description for isTransposeMask() for the
2239 /// exact specification.
2240 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2241 bool isTranspose() const {
2242 return !changesLength() && isTransposeMask(getMask());
2245 /// Return true if this shuffle mask is an extract subvector mask.
2246 /// A valid extract subvector mask returns a smaller vector from a single
2247 /// source operand. The base extraction index is returned as well.
2248 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2249 int &Index);
2250 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2251 int &Index) {
2252 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2253 SmallVector<int, 16> MaskAsInts;
2254 getShuffleMask(Mask, MaskAsInts);
2255 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2258 /// Return true if this shuffle mask is an extract subvector mask.
2259 bool isExtractSubvectorMask(int &Index) const {
2260 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2261 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2264 /// Change values in a shuffle permute mask assuming the two vector operands
2265 /// of length InVecNumElts have swapped position.
2266 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2267 unsigned InVecNumElts) {
2268 for (int &Idx : Mask) {
2269 if (Idx == -1)
2270 continue;
2271 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2272 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2273 "shufflevector mask index out of range");
2277 // Methods for support type inquiry through isa, cast, and dyn_cast:
2278 static bool classof(const Instruction *I) {
2279 return I->getOpcode() == Instruction::ShuffleVector;
2281 static bool classof(const Value *V) {
2282 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2286 template <>
2287 struct OperandTraits<ShuffleVectorInst> :
2288 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2291 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2293 //===----------------------------------------------------------------------===//
2294 // ExtractValueInst Class
2295 //===----------------------------------------------------------------------===//
2297 /// This instruction extracts a struct member or array
2298 /// element value from an aggregate value.
2300 class ExtractValueInst : public UnaryInstruction {
2301 SmallVector<unsigned, 4> Indices;
2303 ExtractValueInst(const ExtractValueInst &EVI);
2305 /// Constructors - Create a extractvalue instruction with a base aggregate
2306 /// value and a list of indices. The first ctor can optionally insert before
2307 /// an existing instruction, the second appends the new instruction to the
2308 /// specified BasicBlock.
2309 inline ExtractValueInst(Value *Agg,
2310 ArrayRef<unsigned> Idxs,
2311 const Twine &NameStr,
2312 Instruction *InsertBefore);
2313 inline ExtractValueInst(Value *Agg,
2314 ArrayRef<unsigned> Idxs,
2315 const Twine &NameStr, BasicBlock *InsertAtEnd);
2317 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2319 protected:
2320 // Note: Instruction needs to be a friend here to call cloneImpl.
2321 friend class Instruction;
2323 ExtractValueInst *cloneImpl() const;
2325 public:
2326 static ExtractValueInst *Create(Value *Agg,
2327 ArrayRef<unsigned> Idxs,
2328 const Twine &NameStr = "",
2329 Instruction *InsertBefore = nullptr) {
2330 return new
2331 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2334 static ExtractValueInst *Create(Value *Agg,
2335 ArrayRef<unsigned> Idxs,
2336 const Twine &NameStr,
2337 BasicBlock *InsertAtEnd) {
2338 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2341 /// Returns the type of the element that would be extracted
2342 /// with an extractvalue instruction with the specified parameters.
2344 /// Null is returned if the indices are invalid for the specified type.
2345 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2347 using idx_iterator = const unsigned*;
2349 inline idx_iterator idx_begin() const { return Indices.begin(); }
2350 inline idx_iterator idx_end() const { return Indices.end(); }
2351 inline iterator_range<idx_iterator> indices() const {
2352 return make_range(idx_begin(), idx_end());
2355 Value *getAggregateOperand() {
2356 return getOperand(0);
2358 const Value *getAggregateOperand() const {
2359 return getOperand(0);
2361 static unsigned getAggregateOperandIndex() {
2362 return 0U; // get index for modifying correct operand
2365 ArrayRef<unsigned> getIndices() const {
2366 return Indices;
2369 unsigned getNumIndices() const {
2370 return (unsigned)Indices.size();
2373 bool hasIndices() const {
2374 return true;
2377 // Methods for support type inquiry through isa, cast, and dyn_cast:
2378 static bool classof(const Instruction *I) {
2379 return I->getOpcode() == Instruction::ExtractValue;
2381 static bool classof(const Value *V) {
2382 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2386 ExtractValueInst::ExtractValueInst(Value *Agg,
2387 ArrayRef<unsigned> Idxs,
2388 const Twine &NameStr,
2389 Instruction *InsertBefore)
2390 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2391 ExtractValue, Agg, InsertBefore) {
2392 init(Idxs, NameStr);
2395 ExtractValueInst::ExtractValueInst(Value *Agg,
2396 ArrayRef<unsigned> Idxs,
2397 const Twine &NameStr,
2398 BasicBlock *InsertAtEnd)
2399 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2400 ExtractValue, Agg, InsertAtEnd) {
2401 init(Idxs, NameStr);
2404 //===----------------------------------------------------------------------===//
2405 // InsertValueInst Class
2406 //===----------------------------------------------------------------------===//
2408 /// This instruction inserts a struct field of array element
2409 /// value into an aggregate value.
2411 class InsertValueInst : public Instruction {
2412 SmallVector<unsigned, 4> Indices;
2414 InsertValueInst(const InsertValueInst &IVI);
2416 /// Constructors - Create a insertvalue instruction with a base aggregate
2417 /// value, a value to insert, and a list of indices. The first ctor can
2418 /// optionally insert before an existing instruction, the second appends
2419 /// the new instruction to the specified BasicBlock.
2420 inline InsertValueInst(Value *Agg, Value *Val,
2421 ArrayRef<unsigned> Idxs,
2422 const Twine &NameStr,
2423 Instruction *InsertBefore);
2424 inline InsertValueInst(Value *Agg, Value *Val,
2425 ArrayRef<unsigned> Idxs,
2426 const Twine &NameStr, BasicBlock *InsertAtEnd);
2428 /// Constructors - These two constructors are convenience methods because one
2429 /// and two index insertvalue instructions are so common.
2430 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2431 const Twine &NameStr = "",
2432 Instruction *InsertBefore = nullptr);
2433 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2434 BasicBlock *InsertAtEnd);
2436 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2437 const Twine &NameStr);
2439 protected:
2440 // Note: Instruction needs to be a friend here to call cloneImpl.
2441 friend class Instruction;
2443 InsertValueInst *cloneImpl() const;
2445 public:
2446 // allocate space for exactly two operands
2447 void *operator new(size_t s) {
2448 return User::operator new(s, 2);
2451 static InsertValueInst *Create(Value *Agg, Value *Val,
2452 ArrayRef<unsigned> Idxs,
2453 const Twine &NameStr = "",
2454 Instruction *InsertBefore = nullptr) {
2455 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2458 static InsertValueInst *Create(Value *Agg, Value *Val,
2459 ArrayRef<unsigned> Idxs,
2460 const Twine &NameStr,
2461 BasicBlock *InsertAtEnd) {
2462 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2465 /// Transparently provide more efficient getOperand methods.
2466 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2468 using idx_iterator = const unsigned*;
2470 inline idx_iterator idx_begin() const { return Indices.begin(); }
2471 inline idx_iterator idx_end() const { return Indices.end(); }
2472 inline iterator_range<idx_iterator> indices() const {
2473 return make_range(idx_begin(), idx_end());
2476 Value *getAggregateOperand() {
2477 return getOperand(0);
2479 const Value *getAggregateOperand() const {
2480 return getOperand(0);
2482 static unsigned getAggregateOperandIndex() {
2483 return 0U; // get index for modifying correct operand
2486 Value *getInsertedValueOperand() {
2487 return getOperand(1);
2489 const Value *getInsertedValueOperand() const {
2490 return getOperand(1);
2492 static unsigned getInsertedValueOperandIndex() {
2493 return 1U; // get index for modifying correct operand
2496 ArrayRef<unsigned> getIndices() const {
2497 return Indices;
2500 unsigned getNumIndices() const {
2501 return (unsigned)Indices.size();
2504 bool hasIndices() const {
2505 return true;
2508 // Methods for support type inquiry through isa, cast, and dyn_cast:
2509 static bool classof(const Instruction *I) {
2510 return I->getOpcode() == Instruction::InsertValue;
2512 static bool classof(const Value *V) {
2513 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2517 template <>
2518 struct OperandTraits<InsertValueInst> :
2519 public FixedNumOperandTraits<InsertValueInst, 2> {
2522 InsertValueInst::InsertValueInst(Value *Agg,
2523 Value *Val,
2524 ArrayRef<unsigned> Idxs,
2525 const Twine &NameStr,
2526 Instruction *InsertBefore)
2527 : Instruction(Agg->getType(), InsertValue,
2528 OperandTraits<InsertValueInst>::op_begin(this),
2529 2, InsertBefore) {
2530 init(Agg, Val, Idxs, NameStr);
2533 InsertValueInst::InsertValueInst(Value *Agg,
2534 Value *Val,
2535 ArrayRef<unsigned> Idxs,
2536 const Twine &NameStr,
2537 BasicBlock *InsertAtEnd)
2538 : Instruction(Agg->getType(), InsertValue,
2539 OperandTraits<InsertValueInst>::op_begin(this),
2540 2, InsertAtEnd) {
2541 init(Agg, Val, Idxs, NameStr);
2544 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2546 //===----------------------------------------------------------------------===//
2547 // PHINode Class
2548 //===----------------------------------------------------------------------===//
2550 // PHINode - The PHINode class is used to represent the magical mystical PHI
2551 // node, that can not exist in nature, but can be synthesized in a computer
2552 // scientist's overactive imagination.
2554 class PHINode : public Instruction {
2555 /// The number of operands actually allocated. NumOperands is
2556 /// the number actually in use.
2557 unsigned ReservedSpace;
2559 PHINode(const PHINode &PN);
2561 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2562 const Twine &NameStr = "",
2563 Instruction *InsertBefore = nullptr)
2564 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2565 ReservedSpace(NumReservedValues) {
2566 setName(NameStr);
2567 allocHungoffUses(ReservedSpace);
2570 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2571 BasicBlock *InsertAtEnd)
2572 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2573 ReservedSpace(NumReservedValues) {
2574 setName(NameStr);
2575 allocHungoffUses(ReservedSpace);
2578 protected:
2579 // Note: Instruction needs to be a friend here to call cloneImpl.
2580 friend class Instruction;
2582 PHINode *cloneImpl() const;
2584 // allocHungoffUses - this is more complicated than the generic
2585 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2586 // values and pointers to the incoming blocks, all in one allocation.
2587 void allocHungoffUses(unsigned N) {
2588 User::allocHungoffUses(N, /* IsPhi */ true);
2591 public:
2592 /// Constructors - NumReservedValues is a hint for the number of incoming
2593 /// edges that this phi node will have (use 0 if you really have no idea).
2594 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2595 const Twine &NameStr = "",
2596 Instruction *InsertBefore = nullptr) {
2597 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2600 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2601 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2602 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2605 /// Provide fast operand accessors
2606 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2608 // Block iterator interface. This provides access to the list of incoming
2609 // basic blocks, which parallels the list of incoming values.
2611 using block_iterator = BasicBlock **;
2612 using const_block_iterator = BasicBlock * const *;
2614 block_iterator block_begin() {
2615 Use::UserRef *ref =
2616 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2617 return reinterpret_cast<block_iterator>(ref + 1);
2620 const_block_iterator block_begin() const {
2621 const Use::UserRef *ref =
2622 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2623 return reinterpret_cast<const_block_iterator>(ref + 1);
2626 block_iterator block_end() {
2627 return block_begin() + getNumOperands();
2630 const_block_iterator block_end() const {
2631 return block_begin() + getNumOperands();
2634 iterator_range<block_iterator> blocks() {
2635 return make_range(block_begin(), block_end());
2638 iterator_range<const_block_iterator> blocks() const {
2639 return make_range(block_begin(), block_end());
2642 op_range incoming_values() { return operands(); }
2644 const_op_range incoming_values() const { return operands(); }
2646 /// Return the number of incoming edges
2648 unsigned getNumIncomingValues() const { return getNumOperands(); }
2650 /// Return incoming value number x
2652 Value *getIncomingValue(unsigned i) const {
2653 return getOperand(i);
2655 void setIncomingValue(unsigned i, Value *V) {
2656 assert(V && "PHI node got a null value!");
2657 assert(getType() == V->getType() &&
2658 "All operands to PHI node must be the same type as the PHI node!");
2659 setOperand(i, V);
2662 static unsigned getOperandNumForIncomingValue(unsigned i) {
2663 return i;
2666 static unsigned getIncomingValueNumForOperand(unsigned i) {
2667 return i;
2670 /// Return incoming basic block number @p i.
2672 BasicBlock *getIncomingBlock(unsigned i) const {
2673 return block_begin()[i];
2676 /// Return incoming basic block corresponding
2677 /// to an operand of the PHI.
2679 BasicBlock *getIncomingBlock(const Use &U) const {
2680 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2681 return getIncomingBlock(unsigned(&U - op_begin()));
2684 /// Return incoming basic block corresponding
2685 /// to value use iterator.
2687 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2688 return getIncomingBlock(I.getUse());
2691 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2692 assert(BB && "PHI node got a null basic block!");
2693 block_begin()[i] = BB;
2696 /// Replace every incoming basic block \p Old to basic block \p New.
2697 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
2698 assert(New && Old && "PHI node got a null basic block!");
2699 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2700 if (getIncomingBlock(Op) == Old)
2701 setIncomingBlock(Op, New);
2704 /// Add an incoming value to the end of the PHI list
2706 void addIncoming(Value *V, BasicBlock *BB) {
2707 if (getNumOperands() == ReservedSpace)
2708 growOperands(); // Get more space!
2709 // Initialize some new operands.
2710 setNumHungOffUseOperands(getNumOperands() + 1);
2711 setIncomingValue(getNumOperands() - 1, V);
2712 setIncomingBlock(getNumOperands() - 1, BB);
2715 /// Remove an incoming value. This is useful if a
2716 /// predecessor basic block is deleted. The value removed is returned.
2718 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2719 /// is true), the PHI node is destroyed and any uses of it are replaced with
2720 /// dummy values. The only time there should be zero incoming values to a PHI
2721 /// node is when the block is dead, so this strategy is sound.
2723 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2725 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2726 int Idx = getBasicBlockIndex(BB);
2727 assert(Idx >= 0 && "Invalid basic block argument to remove!");
2728 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2731 /// Return the first index of the specified basic
2732 /// block in the value list for this PHI. Returns -1 if no instance.
2734 int getBasicBlockIndex(const BasicBlock *BB) const {
2735 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2736 if (block_begin()[i] == BB)
2737 return i;
2738 return -1;
2741 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2742 int Idx = getBasicBlockIndex(BB);
2743 assert(Idx >= 0 && "Invalid basic block argument!");
2744 return getIncomingValue(Idx);
2747 /// Set every incoming value(s) for block \p BB to \p V.
2748 void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
2749 assert(BB && "PHI node got a null basic block!");
2750 bool Found = false;
2751 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2752 if (getIncomingBlock(Op) == BB) {
2753 Found = true;
2754 setIncomingValue(Op, V);
2756 (void)Found;
2757 assert(Found && "Invalid basic block argument to set!");
2760 /// If the specified PHI node always merges together the
2761 /// same value, return the value, otherwise return null.
2762 Value *hasConstantValue() const;
2764 /// Whether the specified PHI node always merges
2765 /// together the same value, assuming undefs are equal to a unique
2766 /// non-undef value.
2767 bool hasConstantOrUndefValue() const;
2769 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2770 static bool classof(const Instruction *I) {
2771 return I->getOpcode() == Instruction::PHI;
2773 static bool classof(const Value *V) {
2774 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2777 private:
2778 void growOperands();
2781 template <>
2782 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2785 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2787 //===----------------------------------------------------------------------===//
2788 // LandingPadInst Class
2789 //===----------------------------------------------------------------------===//
2791 //===---------------------------------------------------------------------------
2792 /// The landingpad instruction holds all of the information
2793 /// necessary to generate correct exception handling. The landingpad instruction
2794 /// cannot be moved from the top of a landing pad block, which itself is
2795 /// accessible only from the 'unwind' edge of an invoke. This uses the
2796 /// SubclassData field in Value to store whether or not the landingpad is a
2797 /// cleanup.
2799 class LandingPadInst : public Instruction {
2800 /// The number of operands actually allocated. NumOperands is
2801 /// the number actually in use.
2802 unsigned ReservedSpace;
2804 LandingPadInst(const LandingPadInst &LP);
2806 public:
2807 enum ClauseType { Catch, Filter };
2809 private:
2810 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2811 const Twine &NameStr, Instruction *InsertBefore);
2812 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2813 const Twine &NameStr, BasicBlock *InsertAtEnd);
2815 // Allocate space for exactly zero operands.
2816 void *operator new(size_t s) {
2817 return User::operator new(s);
2820 void growOperands(unsigned Size);
2821 void init(unsigned NumReservedValues, const Twine &NameStr);
2823 protected:
2824 // Note: Instruction needs to be a friend here to call cloneImpl.
2825 friend class Instruction;
2827 LandingPadInst *cloneImpl() const;
2829 public:
2830 /// Constructors - NumReservedClauses is a hint for the number of incoming
2831 /// clauses that this landingpad will have (use 0 if you really have no idea).
2832 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2833 const Twine &NameStr = "",
2834 Instruction *InsertBefore = nullptr);
2835 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2836 const Twine &NameStr, BasicBlock *InsertAtEnd);
2838 /// Provide fast operand accessors
2839 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2841 /// Return 'true' if this landingpad instruction is a
2842 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2843 /// doesn't catch the exception.
2844 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2846 /// Indicate that this landingpad instruction is a cleanup.
2847 void setCleanup(bool V) {
2848 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2849 (V ? 1 : 0));
2852 /// Add a catch or filter clause to the landing pad.
2853 void addClause(Constant *ClauseVal);
2855 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2856 /// determine what type of clause this is.
2857 Constant *getClause(unsigned Idx) const {
2858 return cast<Constant>(getOperandList()[Idx]);
2861 /// Return 'true' if the clause and index Idx is a catch clause.
2862 bool isCatch(unsigned Idx) const {
2863 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2866 /// Return 'true' if the clause and index Idx is a filter clause.
2867 bool isFilter(unsigned Idx) const {
2868 return isa<ArrayType>(getOperandList()[Idx]->getType());
2871 /// Get the number of clauses for this landing pad.
2872 unsigned getNumClauses() const { return getNumOperands(); }
2874 /// Grow the size of the operand list to accommodate the new
2875 /// number of clauses.
2876 void reserveClauses(unsigned Size) { growOperands(Size); }
2878 // Methods for support type inquiry through isa, cast, and dyn_cast:
2879 static bool classof(const Instruction *I) {
2880 return I->getOpcode() == Instruction::LandingPad;
2882 static bool classof(const Value *V) {
2883 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2887 template <>
2888 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2891 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2893 //===----------------------------------------------------------------------===//
2894 // ReturnInst Class
2895 //===----------------------------------------------------------------------===//
2897 //===---------------------------------------------------------------------------
2898 /// Return a value (possibly void), from a function. Execution
2899 /// does not continue in this function any longer.
2901 class ReturnInst : public Instruction {
2902 ReturnInst(const ReturnInst &RI);
2904 private:
2905 // ReturnInst constructors:
2906 // ReturnInst() - 'ret void' instruction
2907 // ReturnInst( null) - 'ret void' instruction
2908 // ReturnInst(Value* X) - 'ret X' instruction
2909 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2910 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2911 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2912 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2914 // NOTE: If the Value* passed is of type void then the constructor behaves as
2915 // if it was passed NULL.
2916 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2917 Instruction *InsertBefore = nullptr);
2918 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2919 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2921 protected:
2922 // Note: Instruction needs to be a friend here to call cloneImpl.
2923 friend class Instruction;
2925 ReturnInst *cloneImpl() const;
2927 public:
2928 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2929 Instruction *InsertBefore = nullptr) {
2930 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2933 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2934 BasicBlock *InsertAtEnd) {
2935 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2938 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2939 return new(0) ReturnInst(C, InsertAtEnd);
2942 /// Provide fast operand accessors
2943 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2945 /// Convenience accessor. Returns null if there is no return value.
2946 Value *getReturnValue() const {
2947 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2950 unsigned getNumSuccessors() const { return 0; }
2952 // Methods for support type inquiry through isa, cast, and dyn_cast:
2953 static bool classof(const Instruction *I) {
2954 return (I->getOpcode() == Instruction::Ret);
2956 static bool classof(const Value *V) {
2957 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2960 private:
2961 BasicBlock *getSuccessor(unsigned idx) const {
2962 llvm_unreachable("ReturnInst has no successors!");
2965 void setSuccessor(unsigned idx, BasicBlock *B) {
2966 llvm_unreachable("ReturnInst has no successors!");
2970 template <>
2971 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2974 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2976 //===----------------------------------------------------------------------===//
2977 // BranchInst Class
2978 //===----------------------------------------------------------------------===//
2980 //===---------------------------------------------------------------------------
2981 /// Conditional or Unconditional Branch instruction.
2983 class BranchInst : public Instruction {
2984 /// Ops list - Branches are strange. The operands are ordered:
2985 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2986 /// they don't have to check for cond/uncond branchness. These are mostly
2987 /// accessed relative from op_end().
2988 BranchInst(const BranchInst &BI);
2989 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2990 // BranchInst(BB *B) - 'br B'
2991 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2992 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2993 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2994 // BranchInst(BB* B, BB *I) - 'br B' insert at end
2995 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2996 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2997 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2998 Instruction *InsertBefore = nullptr);
2999 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
3000 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3001 BasicBlock *InsertAtEnd);
3003 void AssertOK();
3005 protected:
3006 // Note: Instruction needs to be a friend here to call cloneImpl.
3007 friend class Instruction;
3009 BranchInst *cloneImpl() const;
3011 public:
3012 /// Iterator type that casts an operand to a basic block.
3014 /// This only makes sense because the successors are stored as adjacent
3015 /// operands for branch instructions.
3016 struct succ_op_iterator
3017 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3018 std::random_access_iterator_tag, BasicBlock *,
3019 ptrdiff_t, BasicBlock *, BasicBlock *> {
3020 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3022 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3023 BasicBlock *operator->() const { return operator*(); }
3026 /// The const version of `succ_op_iterator`.
3027 struct const_succ_op_iterator
3028 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3029 std::random_access_iterator_tag,
3030 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3031 const BasicBlock *> {
3032 explicit const_succ_op_iterator(const_value_op_iterator I)
3033 : iterator_adaptor_base(I) {}
3035 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3036 const BasicBlock *operator->() const { return operator*(); }
3039 static BranchInst *Create(BasicBlock *IfTrue,
3040 Instruction *InsertBefore = nullptr) {
3041 return new(1) BranchInst(IfTrue, InsertBefore);
3044 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3045 Value *Cond, Instruction *InsertBefore = nullptr) {
3046 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3049 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3050 return new(1) BranchInst(IfTrue, InsertAtEnd);
3053 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3054 Value *Cond, BasicBlock *InsertAtEnd) {
3055 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3058 /// Transparently provide more efficient getOperand methods.
3059 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3061 bool isUnconditional() const { return getNumOperands() == 1; }
3062 bool isConditional() const { return getNumOperands() == 3; }
3064 Value *getCondition() const {
3065 assert(isConditional() && "Cannot get condition of an uncond branch!");
3066 return Op<-3>();
3069 void setCondition(Value *V) {
3070 assert(isConditional() && "Cannot set condition of unconditional branch!");
3071 Op<-3>() = V;
3074 unsigned getNumSuccessors() const { return 1+isConditional(); }
3076 BasicBlock *getSuccessor(unsigned i) const {
3077 assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3078 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3081 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3082 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3083 *(&Op<-1>() - idx) = NewSucc;
3086 /// Swap the successors of this branch instruction.
3088 /// Swaps the successors of the branch instruction. This also swaps any
3089 /// branch weight metadata associated with the instruction so that it
3090 /// continues to map correctly to each operand.
3091 void swapSuccessors();
3093 iterator_range<succ_op_iterator> successors() {
3094 return make_range(
3095 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3096 succ_op_iterator(value_op_end()));
3099 iterator_range<const_succ_op_iterator> successors() const {
3100 return make_range(const_succ_op_iterator(
3101 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3102 const_succ_op_iterator(value_op_end()));
3105 // Methods for support type inquiry through isa, cast, and dyn_cast:
3106 static bool classof(const Instruction *I) {
3107 return (I->getOpcode() == Instruction::Br);
3109 static bool classof(const Value *V) {
3110 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3114 template <>
3115 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3118 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
3120 //===----------------------------------------------------------------------===//
3121 // SwitchInst Class
3122 //===----------------------------------------------------------------------===//
3124 //===---------------------------------------------------------------------------
3125 /// Multiway switch
3127 class SwitchInst : public Instruction {
3128 unsigned ReservedSpace;
3130 // Operand[0] = Value to switch on
3131 // Operand[1] = Default basic block destination
3132 // Operand[2n ] = Value to match
3133 // Operand[2n+1] = BasicBlock to go to on match
3134 SwitchInst(const SwitchInst &SI);
3136 /// Create a new switch instruction, specifying a value to switch on and a
3137 /// default destination. The number of additional cases can be specified here
3138 /// to make memory allocation more efficient. This constructor can also
3139 /// auto-insert before another instruction.
3140 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3141 Instruction *InsertBefore);
3143 /// Create a new switch instruction, specifying a value to switch on and a
3144 /// default destination. The number of additional cases can be specified here
3145 /// to make memory allocation more efficient. This constructor also
3146 /// auto-inserts at the end of the specified BasicBlock.
3147 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3148 BasicBlock *InsertAtEnd);
3150 // allocate space for exactly zero operands
3151 void *operator new(size_t s) {
3152 return User::operator new(s);
3155 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3156 void growOperands();
3158 protected:
3159 // Note: Instruction needs to be a friend here to call cloneImpl.
3160 friend class Instruction;
3162 SwitchInst *cloneImpl() const;
3164 public:
3165 // -2
3166 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3168 template <typename CaseHandleT> class CaseIteratorImpl;
3170 /// A handle to a particular switch case. It exposes a convenient interface
3171 /// to both the case value and the successor block.
3173 /// We define this as a template and instantiate it to form both a const and
3174 /// non-const handle.
3175 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3176 class CaseHandleImpl {
3177 // Directly befriend both const and non-const iterators.
3178 friend class SwitchInst::CaseIteratorImpl<
3179 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3181 protected:
3182 // Expose the switch type we're parameterized with to the iterator.
3183 using SwitchInstType = SwitchInstT;
3185 SwitchInstT *SI;
3186 ptrdiff_t Index;
3188 CaseHandleImpl() = default;
3189 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3191 public:
3192 /// Resolves case value for current case.
3193 ConstantIntT *getCaseValue() const {
3194 assert((unsigned)Index < SI->getNumCases() &&
3195 "Index out the number of cases.");
3196 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3199 /// Resolves successor for current case.
3200 BasicBlockT *getCaseSuccessor() const {
3201 assert(((unsigned)Index < SI->getNumCases() ||
3202 (unsigned)Index == DefaultPseudoIndex) &&
3203 "Index out the number of cases.");
3204 return SI->getSuccessor(getSuccessorIndex());
3207 /// Returns number of current case.
3208 unsigned getCaseIndex() const { return Index; }
3210 /// Returns successor index for current case successor.
3211 unsigned getSuccessorIndex() const {
3212 assert(((unsigned)Index == DefaultPseudoIndex ||
3213 (unsigned)Index < SI->getNumCases()) &&
3214 "Index out the number of cases.");
3215 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3218 bool operator==(const CaseHandleImpl &RHS) const {
3219 assert(SI == RHS.SI && "Incompatible operators.");
3220 return Index == RHS.Index;
3224 using ConstCaseHandle =
3225 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3227 class CaseHandle
3228 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3229 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3231 public:
3232 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3234 /// Sets the new value for current case.
3235 void setValue(ConstantInt *V) {
3236 assert((unsigned)Index < SI->getNumCases() &&
3237 "Index out the number of cases.");
3238 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3241 /// Sets the new successor for current case.
3242 void setSuccessor(BasicBlock *S) {
3243 SI->setSuccessor(getSuccessorIndex(), S);
3247 template <typename CaseHandleT>
3248 class CaseIteratorImpl
3249 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3250 std::random_access_iterator_tag,
3251 CaseHandleT> {
3252 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3254 CaseHandleT Case;
3256 public:
3257 /// Default constructed iterator is in an invalid state until assigned to
3258 /// a case for a particular switch.
3259 CaseIteratorImpl() = default;
3261 /// Initializes case iterator for given SwitchInst and for given
3262 /// case number.
3263 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3265 /// Initializes case iterator for given SwitchInst and for given
3266 /// successor index.
3267 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3268 unsigned SuccessorIndex) {
3269 assert(SuccessorIndex < SI->getNumSuccessors() &&
3270 "Successor index # out of range!");
3271 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3272 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3275 /// Support converting to the const variant. This will be a no-op for const
3276 /// variant.
3277 operator CaseIteratorImpl<ConstCaseHandle>() const {
3278 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3281 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3282 // Check index correctness after addition.
3283 // Note: Index == getNumCases() means end().
3284 assert(Case.Index + N >= 0 &&
3285 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3286 "Case.Index out the number of cases.");
3287 Case.Index += N;
3288 return *this;
3290 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3291 // Check index correctness after subtraction.
3292 // Note: Case.Index == getNumCases() means end().
3293 assert(Case.Index - N >= 0 &&
3294 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3295 "Case.Index out the number of cases.");
3296 Case.Index -= N;
3297 return *this;
3299 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3300 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3301 return Case.Index - RHS.Case.Index;
3303 bool operator==(const CaseIteratorImpl &RHS) const {
3304 return Case == RHS.Case;
3306 bool operator<(const CaseIteratorImpl &RHS) const {
3307 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3308 return Case.Index < RHS.Case.Index;
3310 CaseHandleT &operator*() { return Case; }
3311 const CaseHandleT &operator*() const { return Case; }
3314 using CaseIt = CaseIteratorImpl<CaseHandle>;
3315 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3317 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3318 unsigned NumCases,
3319 Instruction *InsertBefore = nullptr) {
3320 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3323 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3324 unsigned NumCases, BasicBlock *InsertAtEnd) {
3325 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3328 /// Provide fast operand accessors
3329 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3331 // Accessor Methods for Switch stmt
3332 Value *getCondition() const { return getOperand(0); }
3333 void setCondition(Value *V) { setOperand(0, V); }
3335 BasicBlock *getDefaultDest() const {
3336 return cast<BasicBlock>(getOperand(1));
3339 void setDefaultDest(BasicBlock *DefaultCase) {
3340 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3343 /// Return the number of 'cases' in this switch instruction, excluding the
3344 /// default case.
3345 unsigned getNumCases() const {
3346 return getNumOperands()/2 - 1;
3349 /// Returns a read/write iterator that points to the first case in the
3350 /// SwitchInst.
3351 CaseIt case_begin() {
3352 return CaseIt(this, 0);
3355 /// Returns a read-only iterator that points to the first case in the
3356 /// SwitchInst.
3357 ConstCaseIt case_begin() const {
3358 return ConstCaseIt(this, 0);
3361 /// Returns a read/write iterator that points one past the last in the
3362 /// SwitchInst.
3363 CaseIt case_end() {
3364 return CaseIt(this, getNumCases());
3367 /// Returns a read-only iterator that points one past the last in the
3368 /// SwitchInst.
3369 ConstCaseIt case_end() const {
3370 return ConstCaseIt(this, getNumCases());
3373 /// Iteration adapter for range-for loops.
3374 iterator_range<CaseIt> cases() {
3375 return make_range(case_begin(), case_end());
3378 /// Constant iteration adapter for range-for loops.
3379 iterator_range<ConstCaseIt> cases() const {
3380 return make_range(case_begin(), case_end());
3383 /// Returns an iterator that points to the default case.
3384 /// Note: this iterator allows to resolve successor only. Attempt
3385 /// to resolve case value causes an assertion.
3386 /// Also note, that increment and decrement also causes an assertion and
3387 /// makes iterator invalid.
3388 CaseIt case_default() {
3389 return CaseIt(this, DefaultPseudoIndex);
3391 ConstCaseIt case_default() const {
3392 return ConstCaseIt(this, DefaultPseudoIndex);
3395 /// Search all of the case values for the specified constant. If it is
3396 /// explicitly handled, return the case iterator of it, otherwise return
3397 /// default case iterator to indicate that it is handled by the default
3398 /// handler.
3399 CaseIt findCaseValue(const ConstantInt *C) {
3400 CaseIt I = llvm::find_if(
3401 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3402 if (I != case_end())
3403 return I;
3405 return case_default();
3407 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3408 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3409 return Case.getCaseValue() == C;
3411 if (I != case_end())
3412 return I;
3414 return case_default();
3417 /// Finds the unique case value for a given successor. Returns null if the
3418 /// successor is not found, not unique, or is the default case.
3419 ConstantInt *findCaseDest(BasicBlock *BB) {
3420 if (BB == getDefaultDest())
3421 return nullptr;
3423 ConstantInt *CI = nullptr;
3424 for (auto Case : cases()) {
3425 if (Case.getCaseSuccessor() != BB)
3426 continue;
3428 if (CI)
3429 return nullptr; // Multiple cases lead to BB.
3431 CI = Case.getCaseValue();
3434 return CI;
3437 /// Add an entry to the switch instruction.
3438 /// Note:
3439 /// This action invalidates case_end(). Old case_end() iterator will
3440 /// point to the added case.
3441 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3443 /// This method removes the specified case and its successor from the switch
3444 /// instruction. Note that this operation may reorder the remaining cases at
3445 /// index idx and above.
3446 /// Note:
3447 /// This action invalidates iterators for all cases following the one removed,
3448 /// including the case_end() iterator. It returns an iterator for the next
3449 /// case.
3450 CaseIt removeCase(CaseIt I);
3452 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3453 BasicBlock *getSuccessor(unsigned idx) const {
3454 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3455 return cast<BasicBlock>(getOperand(idx*2+1));
3457 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3458 assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3459 setOperand(idx * 2 + 1, NewSucc);
3462 // Methods for support type inquiry through isa, cast, and dyn_cast:
3463 static bool classof(const Instruction *I) {
3464 return I->getOpcode() == Instruction::Switch;
3466 static bool classof(const Value *V) {
3467 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3471 /// A wrapper class to simplify modification of SwitchInst cases along with
3472 /// their prof branch_weights metadata.
3473 class SwitchInstProfUpdateWrapper {
3474 SwitchInst &SI;
3475 Optional<SmallVector<uint32_t, 8> > Weights = None;
3476 bool Changed = false;
3478 protected:
3479 static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
3481 MDNode *buildProfBranchWeightsMD();
3483 void init();
3485 public:
3486 using CaseWeightOpt = Optional<uint32_t>;
3487 SwitchInst *operator->() { return &SI; }
3488 SwitchInst &operator*() { return SI; }
3489 operator SwitchInst *() { return &SI; }
3491 SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); }
3493 ~SwitchInstProfUpdateWrapper() {
3494 if (Changed)
3495 SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
3498 /// Delegate the call to the underlying SwitchInst::removeCase() and remove
3499 /// correspondent branch weight.
3500 SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
3502 /// Delegate the call to the underlying SwitchInst::addCase() and set the
3503 /// specified branch weight for the added case.
3504 void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
3506 /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
3507 /// this object to not touch the underlying SwitchInst in destructor.
3508 SymbolTableList<Instruction>::iterator eraseFromParent();
3510 void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
3511 CaseWeightOpt getSuccessorWeight(unsigned idx);
3513 static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
3516 template <>
3517 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3520 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3522 //===----------------------------------------------------------------------===//
3523 // IndirectBrInst Class
3524 //===----------------------------------------------------------------------===//
3526 //===---------------------------------------------------------------------------
3527 /// Indirect Branch Instruction.
3529 class IndirectBrInst : public Instruction {
3530 unsigned ReservedSpace;
3532 // Operand[0] = Address to jump to
3533 // Operand[n+1] = n-th destination
3534 IndirectBrInst(const IndirectBrInst &IBI);
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 can also
3539 /// autoinsert before another instruction.
3540 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3542 /// Create a new indirectbr instruction, specifying an
3543 /// Address to jump to. The number of expected destinations can be specified
3544 /// here to make memory allocation more efficient. This constructor also
3545 /// autoinserts at the end of the specified BasicBlock.
3546 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3548 // allocate space for exactly zero operands
3549 void *operator new(size_t s) {
3550 return User::operator new(s);
3553 void init(Value *Address, unsigned NumDests);
3554 void growOperands();
3556 protected:
3557 // Note: Instruction needs to be a friend here to call cloneImpl.
3558 friend class Instruction;
3560 IndirectBrInst *cloneImpl() const;
3562 public:
3563 /// Iterator type that casts an operand to a basic block.
3565 /// This only makes sense because the successors are stored as adjacent
3566 /// operands for indirectbr instructions.
3567 struct succ_op_iterator
3568 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3569 std::random_access_iterator_tag, BasicBlock *,
3570 ptrdiff_t, BasicBlock *, BasicBlock *> {
3571 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3573 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3574 BasicBlock *operator->() const { return operator*(); }
3577 /// The const version of `succ_op_iterator`.
3578 struct const_succ_op_iterator
3579 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3580 std::random_access_iterator_tag,
3581 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3582 const BasicBlock *> {
3583 explicit const_succ_op_iterator(const_value_op_iterator I)
3584 : iterator_adaptor_base(I) {}
3586 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3587 const BasicBlock *operator->() const { return operator*(); }
3590 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3591 Instruction *InsertBefore = nullptr) {
3592 return new IndirectBrInst(Address, NumDests, InsertBefore);
3595 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3596 BasicBlock *InsertAtEnd) {
3597 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3600 /// Provide fast operand accessors.
3601 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3603 // Accessor Methods for IndirectBrInst instruction.
3604 Value *getAddress() { return getOperand(0); }
3605 const Value *getAddress() const { return getOperand(0); }
3606 void setAddress(Value *V) { setOperand(0, V); }
3608 /// return the number of possible destinations in this
3609 /// indirectbr instruction.
3610 unsigned getNumDestinations() const { return getNumOperands()-1; }
3612 /// Return the specified destination.
3613 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3614 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3616 /// Add a destination.
3618 void addDestination(BasicBlock *Dest);
3620 /// This method removes the specified successor from the
3621 /// indirectbr instruction.
3622 void removeDestination(unsigned i);
3624 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3625 BasicBlock *getSuccessor(unsigned i) const {
3626 return cast<BasicBlock>(getOperand(i+1));
3628 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3629 setOperand(i + 1, NewSucc);
3632 iterator_range<succ_op_iterator> successors() {
3633 return make_range(succ_op_iterator(std::next(value_op_begin())),
3634 succ_op_iterator(value_op_end()));
3637 iterator_range<const_succ_op_iterator> successors() const {
3638 return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3639 const_succ_op_iterator(value_op_end()));
3642 // Methods for support type inquiry through isa, cast, and dyn_cast:
3643 static bool classof(const Instruction *I) {
3644 return I->getOpcode() == Instruction::IndirectBr;
3646 static bool classof(const Value *V) {
3647 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3651 template <>
3652 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3655 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3657 //===----------------------------------------------------------------------===//
3658 // InvokeInst Class
3659 //===----------------------------------------------------------------------===//
3661 /// Invoke instruction. The SubclassData field is used to hold the
3662 /// calling convention of the call.
3664 class InvokeInst : public CallBase {
3665 /// The number of operands for this call beyond the called function,
3666 /// arguments, and operand bundles.
3667 static constexpr int NumExtraOperands = 2;
3669 /// The index from the end of the operand array to the normal destination.
3670 static constexpr int NormalDestOpEndIdx = -3;
3672 /// The index from the end of the operand array to the unwind destination.
3673 static constexpr int UnwindDestOpEndIdx = -2;
3675 InvokeInst(const InvokeInst &BI);
3677 /// Construct an InvokeInst given a range of arguments.
3679 /// Construct an InvokeInst from a range of arguments
3680 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3681 BasicBlock *IfException, ArrayRef<Value *> Args,
3682 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3683 const Twine &NameStr, Instruction *InsertBefore);
3685 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3686 BasicBlock *IfException, ArrayRef<Value *> Args,
3687 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3688 const Twine &NameStr, BasicBlock *InsertAtEnd);
3690 void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3691 BasicBlock *IfException, ArrayRef<Value *> Args,
3692 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3694 /// Compute the number of operands to allocate.
3695 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3696 // We need one operand for the called function, plus our extra operands and
3697 // the input operand counts provided.
3698 return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3701 protected:
3702 // Note: Instruction needs to be a friend here to call cloneImpl.
3703 friend class Instruction;
3705 InvokeInst *cloneImpl() const;
3707 public:
3708 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3709 BasicBlock *IfException, ArrayRef<Value *> Args,
3710 const Twine &NameStr,
3711 Instruction *InsertBefore = nullptr) {
3712 int NumOperands = ComputeNumOperands(Args.size());
3713 return new (NumOperands)
3714 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3715 NameStr, InsertBefore);
3718 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3719 BasicBlock *IfException, ArrayRef<Value *> Args,
3720 ArrayRef<OperandBundleDef> Bundles = None,
3721 const Twine &NameStr = "",
3722 Instruction *InsertBefore = nullptr) {
3723 int NumOperands =
3724 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3725 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3727 return new (NumOperands, DescriptorBytes)
3728 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3729 NameStr, InsertBefore);
3732 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3733 BasicBlock *IfException, ArrayRef<Value *> Args,
3734 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3735 int NumOperands = ComputeNumOperands(Args.size());
3736 return new (NumOperands)
3737 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3738 NameStr, InsertAtEnd);
3741 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3742 BasicBlock *IfException, ArrayRef<Value *> Args,
3743 ArrayRef<OperandBundleDef> Bundles,
3744 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3745 int NumOperands =
3746 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3747 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3749 return new (NumOperands, DescriptorBytes)
3750 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3751 NameStr, InsertAtEnd);
3754 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3755 BasicBlock *IfException, ArrayRef<Value *> Args,
3756 const Twine &NameStr,
3757 Instruction *InsertBefore = nullptr) {
3758 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3759 IfException, Args, None, NameStr, InsertBefore);
3762 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3763 BasicBlock *IfException, ArrayRef<Value *> Args,
3764 ArrayRef<OperandBundleDef> Bundles = None,
3765 const Twine &NameStr = "",
3766 Instruction *InsertBefore = nullptr) {
3767 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3768 IfException, Args, Bundles, NameStr, InsertBefore);
3771 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3772 BasicBlock *IfException, ArrayRef<Value *> Args,
3773 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3774 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3775 IfException, Args, NameStr, InsertAtEnd);
3778 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3779 BasicBlock *IfException, ArrayRef<Value *> Args,
3780 ArrayRef<OperandBundleDef> Bundles,
3781 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3782 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3783 IfException, Args, Bundles, NameStr, InsertAtEnd);
3786 // Deprecated [opaque pointer types]
3787 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3788 BasicBlock *IfException, ArrayRef<Value *> Args,
3789 const Twine &NameStr,
3790 Instruction *InsertBefore = nullptr) {
3791 return Create(cast<FunctionType>(
3792 cast<PointerType>(Func->getType())->getElementType()),
3793 Func, IfNormal, IfException, Args, None, NameStr,
3794 InsertBefore);
3797 // Deprecated [opaque pointer types]
3798 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3799 BasicBlock *IfException, ArrayRef<Value *> Args,
3800 ArrayRef<OperandBundleDef> Bundles = None,
3801 const Twine &NameStr = "",
3802 Instruction *InsertBefore = nullptr) {
3803 return Create(cast<FunctionType>(
3804 cast<PointerType>(Func->getType())->getElementType()),
3805 Func, IfNormal, IfException, Args, Bundles, NameStr,
3806 InsertBefore);
3809 // Deprecated [opaque pointer types]
3810 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3811 BasicBlock *IfException, ArrayRef<Value *> Args,
3812 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3813 return Create(cast<FunctionType>(
3814 cast<PointerType>(Func->getType())->getElementType()),
3815 Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3818 // Deprecated [opaque pointer types]
3819 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3820 BasicBlock *IfException, ArrayRef<Value *> Args,
3821 ArrayRef<OperandBundleDef> Bundles,
3822 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3823 return Create(cast<FunctionType>(
3824 cast<PointerType>(Func->getType())->getElementType()),
3825 Func, IfNormal, IfException, Args, Bundles, NameStr,
3826 InsertAtEnd);
3829 /// Create a clone of \p II with a different set of operand bundles and
3830 /// insert it before \p InsertPt.
3832 /// The returned invoke instruction is identical to \p II in every way except
3833 /// that the operand bundles for the new instruction are set to the operand
3834 /// bundles in \p Bundles.
3835 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3836 Instruction *InsertPt = nullptr);
3838 /// Determine if the call should not perform indirect branch tracking.
3839 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3841 /// Determine if the call cannot unwind.
3842 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3843 void setDoesNotThrow() {
3844 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3847 // get*Dest - Return the destination basic blocks...
3848 BasicBlock *getNormalDest() const {
3849 return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3851 BasicBlock *getUnwindDest() const {
3852 return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3854 void setNormalDest(BasicBlock *B) {
3855 Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3857 void setUnwindDest(BasicBlock *B) {
3858 Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3861 /// Get the landingpad instruction from the landing pad
3862 /// block (the unwind destination).
3863 LandingPadInst *getLandingPadInst() const;
3865 BasicBlock *getSuccessor(unsigned i) const {
3866 assert(i < 2 && "Successor # out of range for invoke!");
3867 return i == 0 ? getNormalDest() : getUnwindDest();
3870 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3871 assert(i < 2 && "Successor # out of range for invoke!");
3872 if (i == 0)
3873 setNormalDest(NewSucc);
3874 else
3875 setUnwindDest(NewSucc);
3878 unsigned getNumSuccessors() const { return 2; }
3880 // Methods for support type inquiry through isa, cast, and dyn_cast:
3881 static bool classof(const Instruction *I) {
3882 return (I->getOpcode() == Instruction::Invoke);
3884 static bool classof(const Value *V) {
3885 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3888 private:
3890 // Shadow Instruction::setInstructionSubclassData with a private forwarding
3891 // method so that subclasses cannot accidentally use it.
3892 void setInstructionSubclassData(unsigned short D) {
3893 Instruction::setInstructionSubclassData(D);
3897 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3898 BasicBlock *IfException, ArrayRef<Value *> Args,
3899 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3900 const Twine &NameStr, Instruction *InsertBefore)
3901 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3902 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3903 InsertBefore) {
3904 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3907 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3908 BasicBlock *IfException, ArrayRef<Value *> Args,
3909 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3910 const Twine &NameStr, BasicBlock *InsertAtEnd)
3911 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3912 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3913 InsertAtEnd) {
3914 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3917 //===----------------------------------------------------------------------===//
3918 // CallBrInst Class
3919 //===----------------------------------------------------------------------===//
3921 /// CallBr instruction, tracking function calls that may not return control but
3922 /// instead transfer it to a third location. The SubclassData field is used to
3923 /// hold the calling convention of the call.
3925 class CallBrInst : public CallBase {
3927 unsigned NumIndirectDests;
3929 CallBrInst(const CallBrInst &BI);
3931 /// Construct a CallBrInst given a range of arguments.
3933 /// Construct a CallBrInst from a range of arguments
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, Instruction *InsertBefore);
3940 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3941 ArrayRef<BasicBlock *> IndirectDests,
3942 ArrayRef<Value *> Args,
3943 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3944 const Twine &NameStr, BasicBlock *InsertAtEnd);
3946 void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3947 ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3948 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3950 /// Should the Indirect Destinations change, scan + update the Arg list.
3951 void updateArgBlockAddresses(unsigned i, BasicBlock *B);
3953 /// Compute the number of operands to allocate.
3954 static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3955 int NumBundleInputs = 0) {
3956 // We need one operand for the called function, plus our extra operands and
3957 // the input operand counts provided.
3958 return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3961 protected:
3962 // Note: Instruction needs to be a friend here to call cloneImpl.
3963 friend class Instruction;
3965 CallBrInst *cloneImpl() const;
3967 public:
3968 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3969 BasicBlock *DefaultDest,
3970 ArrayRef<BasicBlock *> IndirectDests,
3971 ArrayRef<Value *> Args, const Twine &NameStr,
3972 Instruction *InsertBefore = nullptr) {
3973 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3974 return new (NumOperands)
3975 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3976 NumOperands, NameStr, InsertBefore);
3979 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3980 BasicBlock *DefaultDest,
3981 ArrayRef<BasicBlock *> IndirectDests,
3982 ArrayRef<Value *> Args,
3983 ArrayRef<OperandBundleDef> Bundles = None,
3984 const Twine &NameStr = "",
3985 Instruction *InsertBefore = nullptr) {
3986 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3987 CountBundleInputs(Bundles));
3988 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3990 return new (NumOperands, DescriptorBytes)
3991 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3992 NumOperands, NameStr, InsertBefore);
3995 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3996 BasicBlock *DefaultDest,
3997 ArrayRef<BasicBlock *> IndirectDests,
3998 ArrayRef<Value *> Args, const Twine &NameStr,
3999 BasicBlock *InsertAtEnd) {
4000 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
4001 return new (NumOperands)
4002 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
4003 NumOperands, NameStr, InsertAtEnd);
4006 static CallBrInst *Create(FunctionType *Ty, Value *Func,
4007 BasicBlock *DefaultDest,
4008 ArrayRef<BasicBlock *> IndirectDests,
4009 ArrayRef<Value *> Args,
4010 ArrayRef<OperandBundleDef> Bundles,
4011 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4012 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
4013 CountBundleInputs(Bundles));
4014 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
4016 return new (NumOperands, DescriptorBytes)
4017 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
4018 NumOperands, NameStr, InsertAtEnd);
4021 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4022 ArrayRef<BasicBlock *> IndirectDests,
4023 ArrayRef<Value *> Args, const Twine &NameStr,
4024 Instruction *InsertBefore = nullptr) {
4025 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4026 IndirectDests, Args, NameStr, InsertBefore);
4029 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4030 ArrayRef<BasicBlock *> IndirectDests,
4031 ArrayRef<Value *> Args,
4032 ArrayRef<OperandBundleDef> Bundles = None,
4033 const Twine &NameStr = "",
4034 Instruction *InsertBefore = nullptr) {
4035 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4036 IndirectDests, Args, Bundles, NameStr, InsertBefore);
4039 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4040 ArrayRef<BasicBlock *> IndirectDests,
4041 ArrayRef<Value *> Args, const Twine &NameStr,
4042 BasicBlock *InsertAtEnd) {
4043 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4044 IndirectDests, Args, NameStr, InsertAtEnd);
4047 static CallBrInst *Create(FunctionCallee Func,
4048 BasicBlock *DefaultDest,
4049 ArrayRef<BasicBlock *> IndirectDests,
4050 ArrayRef<Value *> Args,
4051 ArrayRef<OperandBundleDef> Bundles,
4052 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4053 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4054 IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4057 /// Create a clone of \p CBI with a different set of operand bundles and
4058 /// insert it before \p InsertPt.
4060 /// The returned callbr instruction is identical to \p CBI in every way
4061 /// except that the operand bundles for the new instruction are set to the
4062 /// operand bundles in \p Bundles.
4063 static CallBrInst *Create(CallBrInst *CBI,
4064 ArrayRef<OperandBundleDef> Bundles,
4065 Instruction *InsertPt = nullptr);
4067 /// Return the number of callbr indirect dest labels.
4069 unsigned getNumIndirectDests() const { return NumIndirectDests; }
4071 /// getIndirectDestLabel - Return the i-th indirect dest label.
4073 Value *getIndirectDestLabel(unsigned i) const {
4074 assert(i < getNumIndirectDests() && "Out of bounds!");
4075 return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4079 Value *getIndirectDestLabelUse(unsigned i) const {
4080 assert(i < getNumIndirectDests() && "Out of bounds!");
4081 return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4085 // Return the destination basic blocks...
4086 BasicBlock *getDefaultDest() const {
4087 return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4089 BasicBlock *getIndirectDest(unsigned i) const {
4090 return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4092 SmallVector<BasicBlock *, 16> getIndirectDests() const {
4093 SmallVector<BasicBlock *, 16> IndirectDests;
4094 for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4095 IndirectDests.push_back(getIndirectDest(i));
4096 return IndirectDests;
4098 void setDefaultDest(BasicBlock *B) {
4099 *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4101 void setIndirectDest(unsigned i, BasicBlock *B) {
4102 updateArgBlockAddresses(i, B);
4103 *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4106 BasicBlock *getSuccessor(unsigned i) const {
4107 assert(i < getNumSuccessors() + 1 &&
4108 "Successor # out of range for callbr!");
4109 return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4112 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
4113 assert(i < getNumIndirectDests() + 1 &&
4114 "Successor # out of range for callbr!");
4115 return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
4118 unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4120 // Methods for support type inquiry through isa, cast, and dyn_cast:
4121 static bool classof(const Instruction *I) {
4122 return (I->getOpcode() == Instruction::CallBr);
4124 static bool classof(const Value *V) {
4125 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4128 private:
4130 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4131 // method so that subclasses cannot accidentally use it.
4132 void setInstructionSubclassData(unsigned short D) {
4133 Instruction::setInstructionSubclassData(D);
4137 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4138 ArrayRef<BasicBlock *> IndirectDests,
4139 ArrayRef<Value *> Args,
4140 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4141 const Twine &NameStr, Instruction *InsertBefore)
4142 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4143 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4144 InsertBefore) {
4145 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4148 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4149 ArrayRef<BasicBlock *> IndirectDests,
4150 ArrayRef<Value *> Args,
4151 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4152 const Twine &NameStr, BasicBlock *InsertAtEnd)
4153 : CallBase(
4154 cast<FunctionType>(
4155 cast<PointerType>(Func->getType())->getElementType())
4156 ->getReturnType(),
4157 Instruction::CallBr,
4158 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4159 InsertAtEnd) {
4160 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4163 //===----------------------------------------------------------------------===//
4164 // ResumeInst Class
4165 //===----------------------------------------------------------------------===//
4167 //===---------------------------------------------------------------------------
4168 /// Resume the propagation of an exception.
4170 class ResumeInst : public Instruction {
4171 ResumeInst(const ResumeInst &RI);
4173 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4174 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4176 protected:
4177 // Note: Instruction needs to be a friend here to call cloneImpl.
4178 friend class Instruction;
4180 ResumeInst *cloneImpl() const;
4182 public:
4183 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4184 return new(1) ResumeInst(Exn, InsertBefore);
4187 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4188 return new(1) ResumeInst(Exn, InsertAtEnd);
4191 /// Provide fast operand accessors
4192 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4194 /// Convenience accessor.
4195 Value *getValue() const { return Op<0>(); }
4197 unsigned getNumSuccessors() const { return 0; }
4199 // Methods for support type inquiry through isa, cast, and dyn_cast:
4200 static bool classof(const Instruction *I) {
4201 return I->getOpcode() == Instruction::Resume;
4203 static bool classof(const Value *V) {
4204 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4207 private:
4208 BasicBlock *getSuccessor(unsigned idx) const {
4209 llvm_unreachable("ResumeInst has no successors!");
4212 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4213 llvm_unreachable("ResumeInst has no successors!");
4217 template <>
4218 struct OperandTraits<ResumeInst> :
4219 public FixedNumOperandTraits<ResumeInst, 1> {
4222 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4224 //===----------------------------------------------------------------------===//
4225 // CatchSwitchInst Class
4226 //===----------------------------------------------------------------------===//
4227 class CatchSwitchInst : public Instruction {
4228 /// The number of operands actually allocated. NumOperands is
4229 /// the number actually in use.
4230 unsigned ReservedSpace;
4232 // Operand[0] = Outer scope
4233 // Operand[1] = Unwind block destination
4234 // Operand[n] = BasicBlock to go to on match
4235 CatchSwitchInst(const CatchSwitchInst &CSI);
4237 /// Create a new switch instruction, specifying a
4238 /// default destination. The number of additional handlers can be specified
4239 /// here to make memory allocation more efficient.
4240 /// This constructor can also autoinsert before another instruction.
4241 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4242 unsigned NumHandlers, const Twine &NameStr,
4243 Instruction *InsertBefore);
4245 /// Create a new switch instruction, specifying a
4246 /// default destination. The number of additional handlers can be specified
4247 /// here to make memory allocation more efficient.
4248 /// This constructor also autoinserts at the end of the specified BasicBlock.
4249 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4250 unsigned NumHandlers, const Twine &NameStr,
4251 BasicBlock *InsertAtEnd);
4253 // allocate space for exactly zero operands
4254 void *operator new(size_t s) { return User::operator new(s); }
4256 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4257 void growOperands(unsigned Size);
4259 protected:
4260 // Note: Instruction needs to be a friend here to call cloneImpl.
4261 friend class Instruction;
4263 CatchSwitchInst *cloneImpl() const;
4265 public:
4266 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4267 unsigned NumHandlers,
4268 const Twine &NameStr = "",
4269 Instruction *InsertBefore = nullptr) {
4270 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4271 InsertBefore);
4274 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4275 unsigned NumHandlers, const Twine &NameStr,
4276 BasicBlock *InsertAtEnd) {
4277 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4278 InsertAtEnd);
4281 /// Provide fast operand accessors
4282 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4284 // Accessor Methods for CatchSwitch stmt
4285 Value *getParentPad() const { return getOperand(0); }
4286 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4288 // Accessor Methods for CatchSwitch stmt
4289 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4290 bool unwindsToCaller() const { return !hasUnwindDest(); }
4291 BasicBlock *getUnwindDest() const {
4292 if (hasUnwindDest())
4293 return cast<BasicBlock>(getOperand(1));
4294 return nullptr;
4296 void setUnwindDest(BasicBlock *UnwindDest) {
4297 assert(UnwindDest);
4298 assert(hasUnwindDest());
4299 setOperand(1, UnwindDest);
4302 /// return the number of 'handlers' in this catchswitch
4303 /// instruction, except the default handler
4304 unsigned getNumHandlers() const {
4305 if (hasUnwindDest())
4306 return getNumOperands() - 2;
4307 return getNumOperands() - 1;
4310 private:
4311 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4312 static const BasicBlock *handler_helper(const Value *V) {
4313 return cast<BasicBlock>(V);
4316 public:
4317 using DerefFnTy = BasicBlock *(*)(Value *);
4318 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4319 using handler_range = iterator_range<handler_iterator>;
4320 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4321 using const_handler_iterator =
4322 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4323 using const_handler_range = iterator_range<const_handler_iterator>;
4325 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4326 handler_iterator handler_begin() {
4327 op_iterator It = op_begin() + 1;
4328 if (hasUnwindDest())
4329 ++It;
4330 return handler_iterator(It, DerefFnTy(handler_helper));
4333 /// Returns an iterator that points to the first handler in the
4334 /// CatchSwitchInst.
4335 const_handler_iterator handler_begin() const {
4336 const_op_iterator It = op_begin() + 1;
4337 if (hasUnwindDest())
4338 ++It;
4339 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4342 /// Returns a read-only iterator that points one past the last
4343 /// handler in the CatchSwitchInst.
4344 handler_iterator handler_end() {
4345 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4348 /// Returns an iterator that points one past the last handler in the
4349 /// CatchSwitchInst.
4350 const_handler_iterator handler_end() const {
4351 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4354 /// iteration adapter for range-for loops.
4355 handler_range handlers() {
4356 return make_range(handler_begin(), handler_end());
4359 /// iteration adapter for range-for loops.
4360 const_handler_range handlers() const {
4361 return make_range(handler_begin(), handler_end());
4364 /// Add an entry to the switch instruction...
4365 /// Note:
4366 /// This action invalidates handler_end(). Old handler_end() iterator will
4367 /// point to the added handler.
4368 void addHandler(BasicBlock *Dest);
4370 void removeHandler(handler_iterator HI);
4372 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4373 BasicBlock *getSuccessor(unsigned Idx) const {
4374 assert(Idx < getNumSuccessors() &&
4375 "Successor # out of range for catchswitch!");
4376 return cast<BasicBlock>(getOperand(Idx + 1));
4378 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4379 assert(Idx < getNumSuccessors() &&
4380 "Successor # out of range for catchswitch!");
4381 setOperand(Idx + 1, NewSucc);
4384 // Methods for support type inquiry through isa, cast, and dyn_cast:
4385 static bool classof(const Instruction *I) {
4386 return I->getOpcode() == Instruction::CatchSwitch;
4388 static bool classof(const Value *V) {
4389 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4393 template <>
4394 struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4396 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4398 //===----------------------------------------------------------------------===//
4399 // CleanupPadInst Class
4400 //===----------------------------------------------------------------------===//
4401 class CleanupPadInst : public FuncletPadInst {
4402 private:
4403 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4404 unsigned Values, const Twine &NameStr,
4405 Instruction *InsertBefore)
4406 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4407 NameStr, InsertBefore) {}
4408 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4409 unsigned Values, const Twine &NameStr,
4410 BasicBlock *InsertAtEnd)
4411 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4412 NameStr, InsertAtEnd) {}
4414 public:
4415 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4416 const Twine &NameStr = "",
4417 Instruction *InsertBefore = nullptr) {
4418 unsigned Values = 1 + Args.size();
4419 return new (Values)
4420 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4423 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4424 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4425 unsigned Values = 1 + Args.size();
4426 return new (Values)
4427 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4430 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4431 static bool classof(const Instruction *I) {
4432 return I->getOpcode() == Instruction::CleanupPad;
4434 static bool classof(const Value *V) {
4435 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4439 //===----------------------------------------------------------------------===//
4440 // CatchPadInst Class
4441 //===----------------------------------------------------------------------===//
4442 class CatchPadInst : public FuncletPadInst {
4443 private:
4444 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4445 unsigned Values, const Twine &NameStr,
4446 Instruction *InsertBefore)
4447 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4448 NameStr, InsertBefore) {}
4449 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4450 unsigned Values, const Twine &NameStr,
4451 BasicBlock *InsertAtEnd)
4452 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4453 NameStr, InsertAtEnd) {}
4455 public:
4456 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4457 const Twine &NameStr = "",
4458 Instruction *InsertBefore = nullptr) {
4459 unsigned Values = 1 + Args.size();
4460 return new (Values)
4461 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4464 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4465 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4466 unsigned Values = 1 + Args.size();
4467 return new (Values)
4468 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4471 /// Convenience accessors
4472 CatchSwitchInst *getCatchSwitch() const {
4473 return cast<CatchSwitchInst>(Op<-1>());
4475 void setCatchSwitch(Value *CatchSwitch) {
4476 assert(CatchSwitch);
4477 Op<-1>() = CatchSwitch;
4480 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4481 static bool classof(const Instruction *I) {
4482 return I->getOpcode() == Instruction::CatchPad;
4484 static bool classof(const Value *V) {
4485 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4489 //===----------------------------------------------------------------------===//
4490 // CatchReturnInst Class
4491 //===----------------------------------------------------------------------===//
4493 class CatchReturnInst : public Instruction {
4494 CatchReturnInst(const CatchReturnInst &RI);
4495 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4496 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4498 void init(Value *CatchPad, BasicBlock *BB);
4500 protected:
4501 // Note: Instruction needs to be a friend here to call cloneImpl.
4502 friend class Instruction;
4504 CatchReturnInst *cloneImpl() const;
4506 public:
4507 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4508 Instruction *InsertBefore = nullptr) {
4509 assert(CatchPad);
4510 assert(BB);
4511 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4514 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4515 BasicBlock *InsertAtEnd) {
4516 assert(CatchPad);
4517 assert(BB);
4518 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4521 /// Provide fast operand accessors
4522 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4524 /// Convenience accessors.
4525 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4526 void setCatchPad(CatchPadInst *CatchPad) {
4527 assert(CatchPad);
4528 Op<0>() = CatchPad;
4531 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4532 void setSuccessor(BasicBlock *NewSucc) {
4533 assert(NewSucc);
4534 Op<1>() = NewSucc;
4536 unsigned getNumSuccessors() const { return 1; }
4538 /// Get the parentPad of this catchret's catchpad's catchswitch.
4539 /// The successor block is implicitly a member of this funclet.
4540 Value *getCatchSwitchParentPad() const {
4541 return getCatchPad()->getCatchSwitch()->getParentPad();
4544 // Methods for support type inquiry through isa, cast, and dyn_cast:
4545 static bool classof(const Instruction *I) {
4546 return (I->getOpcode() == Instruction::CatchRet);
4548 static bool classof(const Value *V) {
4549 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4552 private:
4553 BasicBlock *getSuccessor(unsigned Idx) const {
4554 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4555 return getSuccessor();
4558 void setSuccessor(unsigned Idx, BasicBlock *B) {
4559 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4560 setSuccessor(B);
4564 template <>
4565 struct OperandTraits<CatchReturnInst>
4566 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4568 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4570 //===----------------------------------------------------------------------===//
4571 // CleanupReturnInst Class
4572 //===----------------------------------------------------------------------===//
4574 class CleanupReturnInst : public Instruction {
4575 private:
4576 CleanupReturnInst(const CleanupReturnInst &RI);
4577 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4578 Instruction *InsertBefore = nullptr);
4579 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4580 BasicBlock *InsertAtEnd);
4582 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4584 protected:
4585 // Note: Instruction needs to be a friend here to call cloneImpl.
4586 friend class Instruction;
4588 CleanupReturnInst *cloneImpl() const;
4590 public:
4591 static CleanupReturnInst *Create(Value *CleanupPad,
4592 BasicBlock *UnwindBB = nullptr,
4593 Instruction *InsertBefore = nullptr) {
4594 assert(CleanupPad);
4595 unsigned Values = 1;
4596 if (UnwindBB)
4597 ++Values;
4598 return new (Values)
4599 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4602 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4603 BasicBlock *InsertAtEnd) {
4604 assert(CleanupPad);
4605 unsigned Values = 1;
4606 if (UnwindBB)
4607 ++Values;
4608 return new (Values)
4609 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4612 /// Provide fast operand accessors
4613 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4615 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4616 bool unwindsToCaller() const { return !hasUnwindDest(); }
4618 /// Convenience accessor.
4619 CleanupPadInst *getCleanupPad() const {
4620 return cast<CleanupPadInst>(Op<0>());
4622 void setCleanupPad(CleanupPadInst *CleanupPad) {
4623 assert(CleanupPad);
4624 Op<0>() = CleanupPad;
4627 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4629 BasicBlock *getUnwindDest() const {
4630 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4632 void setUnwindDest(BasicBlock *NewDest) {
4633 assert(NewDest);
4634 assert(hasUnwindDest());
4635 Op<1>() = NewDest;
4638 // Methods for support type inquiry through isa, cast, and dyn_cast:
4639 static bool classof(const Instruction *I) {
4640 return (I->getOpcode() == Instruction::CleanupRet);
4642 static bool classof(const Value *V) {
4643 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4646 private:
4647 BasicBlock *getSuccessor(unsigned Idx) const {
4648 assert(Idx == 0);
4649 return getUnwindDest();
4652 void setSuccessor(unsigned Idx, BasicBlock *B) {
4653 assert(Idx == 0);
4654 setUnwindDest(B);
4657 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4658 // method so that subclasses cannot accidentally use it.
4659 void setInstructionSubclassData(unsigned short D) {
4660 Instruction::setInstructionSubclassData(D);
4664 template <>
4665 struct OperandTraits<CleanupReturnInst>
4666 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4668 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4670 //===----------------------------------------------------------------------===//
4671 // UnreachableInst Class
4672 //===----------------------------------------------------------------------===//
4674 //===---------------------------------------------------------------------------
4675 /// This function has undefined behavior. In particular, the
4676 /// presence of this instruction indicates some higher level knowledge that the
4677 /// end of the block cannot be reached.
4679 class UnreachableInst : public Instruction {
4680 protected:
4681 // Note: Instruction needs to be a friend here to call cloneImpl.
4682 friend class Instruction;
4684 UnreachableInst *cloneImpl() const;
4686 public:
4687 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4688 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4690 // allocate space for exactly zero operands
4691 void *operator new(size_t s) {
4692 return User::operator new(s, 0);
4695 unsigned getNumSuccessors() const { return 0; }
4697 // Methods for support type inquiry through isa, cast, and dyn_cast:
4698 static bool classof(const Instruction *I) {
4699 return I->getOpcode() == Instruction::Unreachable;
4701 static bool classof(const Value *V) {
4702 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4705 private:
4706 BasicBlock *getSuccessor(unsigned idx) const {
4707 llvm_unreachable("UnreachableInst has no successors!");
4710 void setSuccessor(unsigned idx, BasicBlock *B) {
4711 llvm_unreachable("UnreachableInst has no successors!");
4715 //===----------------------------------------------------------------------===//
4716 // TruncInst Class
4717 //===----------------------------------------------------------------------===//
4719 /// This class represents a truncation of integer types.
4720 class TruncInst : public CastInst {
4721 protected:
4722 // Note: Instruction needs to be a friend here to call cloneImpl.
4723 friend class Instruction;
4725 /// Clone an identical TruncInst
4726 TruncInst *cloneImpl() const;
4728 public:
4729 /// Constructor with insert-before-instruction semantics
4730 TruncInst(
4731 Value *S, ///< The value to be truncated
4732 Type *Ty, ///< The (smaller) type to truncate to
4733 const Twine &NameStr = "", ///< A name for the new instruction
4734 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4737 /// Constructor with insert-at-end-of-block semantics
4738 TruncInst(
4739 Value *S, ///< The value to be truncated
4740 Type *Ty, ///< The (smaller) type to truncate to
4741 const Twine &NameStr, ///< A name for the new instruction
4742 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4745 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4746 static bool classof(const Instruction *I) {
4747 return I->getOpcode() == Trunc;
4749 static bool classof(const Value *V) {
4750 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4754 //===----------------------------------------------------------------------===//
4755 // ZExtInst Class
4756 //===----------------------------------------------------------------------===//
4758 /// This class represents zero extension of integer types.
4759 class ZExtInst : public CastInst {
4760 protected:
4761 // Note: Instruction needs to be a friend here to call cloneImpl.
4762 friend class Instruction;
4764 /// Clone an identical ZExtInst
4765 ZExtInst *cloneImpl() const;
4767 public:
4768 /// Constructor with insert-before-instruction semantics
4769 ZExtInst(
4770 Value *S, ///< The value to be zero extended
4771 Type *Ty, ///< The type to zero extend to
4772 const Twine &NameStr = "", ///< A name for the new instruction
4773 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4776 /// Constructor with insert-at-end semantics.
4777 ZExtInst(
4778 Value *S, ///< The value to be zero extended
4779 Type *Ty, ///< The type to zero extend to
4780 const Twine &NameStr, ///< A name for the new instruction
4781 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4784 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4785 static bool classof(const Instruction *I) {
4786 return I->getOpcode() == ZExt;
4788 static bool classof(const Value *V) {
4789 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4793 //===----------------------------------------------------------------------===//
4794 // SExtInst Class
4795 //===----------------------------------------------------------------------===//
4797 /// This class represents a sign extension of integer types.
4798 class SExtInst : public CastInst {
4799 protected:
4800 // Note: Instruction needs to be a friend here to call cloneImpl.
4801 friend class Instruction;
4803 /// Clone an identical SExtInst
4804 SExtInst *cloneImpl() const;
4806 public:
4807 /// Constructor with insert-before-instruction semantics
4808 SExtInst(
4809 Value *S, ///< The value to be sign extended
4810 Type *Ty, ///< The type to sign extend to
4811 const Twine &NameStr = "", ///< A name for the new instruction
4812 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4815 /// Constructor with insert-at-end-of-block semantics
4816 SExtInst(
4817 Value *S, ///< The value to be sign extended
4818 Type *Ty, ///< The type to sign extend to
4819 const Twine &NameStr, ///< A name for the new instruction
4820 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4823 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4824 static bool classof(const Instruction *I) {
4825 return I->getOpcode() == SExt;
4827 static bool classof(const Value *V) {
4828 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4832 //===----------------------------------------------------------------------===//
4833 // FPTruncInst Class
4834 //===----------------------------------------------------------------------===//
4836 /// This class represents a truncation of floating point types.
4837 class FPTruncInst : public CastInst {
4838 protected:
4839 // Note: Instruction needs to be a friend here to call cloneImpl.
4840 friend class Instruction;
4842 /// Clone an identical FPTruncInst
4843 FPTruncInst *cloneImpl() const;
4845 public:
4846 /// Constructor with insert-before-instruction semantics
4847 FPTruncInst(
4848 Value *S, ///< The value to be truncated
4849 Type *Ty, ///< The type to truncate to
4850 const Twine &NameStr = "", ///< A name for the new instruction
4851 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4854 /// Constructor with insert-before-instruction semantics
4855 FPTruncInst(
4856 Value *S, ///< The value to be truncated
4857 Type *Ty, ///< The type to truncate to
4858 const Twine &NameStr, ///< A name for the new instruction
4859 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4862 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4863 static bool classof(const Instruction *I) {
4864 return I->getOpcode() == FPTrunc;
4866 static bool classof(const Value *V) {
4867 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4871 //===----------------------------------------------------------------------===//
4872 // FPExtInst Class
4873 //===----------------------------------------------------------------------===//
4875 /// This class represents an extension of floating point types.
4876 class FPExtInst : public CastInst {
4877 protected:
4878 // Note: Instruction needs to be a friend here to call cloneImpl.
4879 friend class Instruction;
4881 /// Clone an identical FPExtInst
4882 FPExtInst *cloneImpl() const;
4884 public:
4885 /// Constructor with insert-before-instruction semantics
4886 FPExtInst(
4887 Value *S, ///< The value to be extended
4888 Type *Ty, ///< The type to extend to
4889 const Twine &NameStr = "", ///< A name for the new instruction
4890 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4893 /// Constructor with insert-at-end-of-block semantics
4894 FPExtInst(
4895 Value *S, ///< The value to be extended
4896 Type *Ty, ///< The type to extend to
4897 const Twine &NameStr, ///< A name for the new instruction
4898 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4901 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4902 static bool classof(const Instruction *I) {
4903 return I->getOpcode() == FPExt;
4905 static bool classof(const Value *V) {
4906 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4910 //===----------------------------------------------------------------------===//
4911 // UIToFPInst Class
4912 //===----------------------------------------------------------------------===//
4914 /// This class represents a cast unsigned integer to floating point.
4915 class UIToFPInst : public CastInst {
4916 protected:
4917 // Note: Instruction needs to be a friend here to call cloneImpl.
4918 friend class Instruction;
4920 /// Clone an identical UIToFPInst
4921 UIToFPInst *cloneImpl() const;
4923 public:
4924 /// Constructor with insert-before-instruction semantics
4925 UIToFPInst(
4926 Value *S, ///< The value to be converted
4927 Type *Ty, ///< The type to convert to
4928 const Twine &NameStr = "", ///< A name for the new instruction
4929 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4932 /// Constructor with insert-at-end-of-block semantics
4933 UIToFPInst(
4934 Value *S, ///< The value to be converted
4935 Type *Ty, ///< The type to convert to
4936 const Twine &NameStr, ///< A name for the new instruction
4937 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4940 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4941 static bool classof(const Instruction *I) {
4942 return I->getOpcode() == UIToFP;
4944 static bool classof(const Value *V) {
4945 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4949 //===----------------------------------------------------------------------===//
4950 // SIToFPInst Class
4951 //===----------------------------------------------------------------------===//
4953 /// This class represents a cast from signed integer to floating point.
4954 class SIToFPInst : public CastInst {
4955 protected:
4956 // Note: Instruction needs to be a friend here to call cloneImpl.
4957 friend class Instruction;
4959 /// Clone an identical SIToFPInst
4960 SIToFPInst *cloneImpl() const;
4962 public:
4963 /// Constructor with insert-before-instruction semantics
4964 SIToFPInst(
4965 Value *S, ///< The value to be converted
4966 Type *Ty, ///< The type to convert to
4967 const Twine &NameStr = "", ///< A name for the new instruction
4968 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4971 /// Constructor with insert-at-end-of-block semantics
4972 SIToFPInst(
4973 Value *S, ///< The value to be converted
4974 Type *Ty, ///< The type to convert to
4975 const Twine &NameStr, ///< A name for the new instruction
4976 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4979 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4980 static bool classof(const Instruction *I) {
4981 return I->getOpcode() == SIToFP;
4983 static bool classof(const Value *V) {
4984 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4988 //===----------------------------------------------------------------------===//
4989 // FPToUIInst Class
4990 //===----------------------------------------------------------------------===//
4992 /// This class represents a cast from floating point to unsigned integer
4993 class FPToUIInst : public CastInst {
4994 protected:
4995 // Note: Instruction needs to be a friend here to call cloneImpl.
4996 friend class Instruction;
4998 /// Clone an identical FPToUIInst
4999 FPToUIInst *cloneImpl() const;
5001 public:
5002 /// Constructor with insert-before-instruction semantics
5003 FPToUIInst(
5004 Value *S, ///< The value to be converted
5005 Type *Ty, ///< The type to convert to
5006 const Twine &NameStr = "", ///< A name for the new instruction
5007 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5010 /// Constructor with insert-at-end-of-block semantics
5011 FPToUIInst(
5012 Value *S, ///< The value to be converted
5013 Type *Ty, ///< The type to convert to
5014 const Twine &NameStr, ///< A name for the new instruction
5015 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
5018 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5019 static bool classof(const Instruction *I) {
5020 return I->getOpcode() == FPToUI;
5022 static bool classof(const Value *V) {
5023 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5027 //===----------------------------------------------------------------------===//
5028 // FPToSIInst Class
5029 //===----------------------------------------------------------------------===//
5031 /// This class represents a cast from floating point to signed integer.
5032 class FPToSIInst : public CastInst {
5033 protected:
5034 // Note: Instruction needs to be a friend here to call cloneImpl.
5035 friend class Instruction;
5037 /// Clone an identical FPToSIInst
5038 FPToSIInst *cloneImpl() const;
5040 public:
5041 /// Constructor with insert-before-instruction semantics
5042 FPToSIInst(
5043 Value *S, ///< The value to be converted
5044 Type *Ty, ///< The type to convert to
5045 const Twine &NameStr = "", ///< A name for the new instruction
5046 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5049 /// Constructor with insert-at-end-of-block semantics
5050 FPToSIInst(
5051 Value *S, ///< The value to be converted
5052 Type *Ty, ///< The type to convert to
5053 const Twine &NameStr, ///< A name for the new instruction
5054 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5057 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5058 static bool classof(const Instruction *I) {
5059 return I->getOpcode() == FPToSI;
5061 static bool classof(const Value *V) {
5062 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5066 //===----------------------------------------------------------------------===//
5067 // IntToPtrInst Class
5068 //===----------------------------------------------------------------------===//
5070 /// This class represents a cast from an integer to a pointer.
5071 class IntToPtrInst : public CastInst {
5072 public:
5073 // Note: Instruction needs to be a friend here to call cloneImpl.
5074 friend class Instruction;
5076 /// Constructor with insert-before-instruction semantics
5077 IntToPtrInst(
5078 Value *S, ///< The value to be converted
5079 Type *Ty, ///< The type to convert to
5080 const Twine &NameStr = "", ///< A name for the new instruction
5081 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5084 /// Constructor with insert-at-end-of-block semantics
5085 IntToPtrInst(
5086 Value *S, ///< The value to be converted
5087 Type *Ty, ///< The type to convert to
5088 const Twine &NameStr, ///< A name for the new instruction
5089 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5092 /// Clone an identical IntToPtrInst.
5093 IntToPtrInst *cloneImpl() const;
5095 /// Returns the address space of this instruction's pointer type.
5096 unsigned getAddressSpace() const {
5097 return getType()->getPointerAddressSpace();
5100 // Methods for support type inquiry through isa, cast, and dyn_cast:
5101 static bool classof(const Instruction *I) {
5102 return I->getOpcode() == IntToPtr;
5104 static bool classof(const Value *V) {
5105 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5109 //===----------------------------------------------------------------------===//
5110 // PtrToIntInst Class
5111 //===----------------------------------------------------------------------===//
5113 /// This class represents a cast from a pointer to an integer.
5114 class PtrToIntInst : public CastInst {
5115 protected:
5116 // Note: Instruction needs to be a friend here to call cloneImpl.
5117 friend class Instruction;
5119 /// Clone an identical PtrToIntInst.
5120 PtrToIntInst *cloneImpl() const;
5122 public:
5123 /// Constructor with insert-before-instruction semantics
5124 PtrToIntInst(
5125 Value *S, ///< The value to be converted
5126 Type *Ty, ///< The type to convert to
5127 const Twine &NameStr = "", ///< A name for the new instruction
5128 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5131 /// Constructor with insert-at-end-of-block semantics
5132 PtrToIntInst(
5133 Value *S, ///< The value to be converted
5134 Type *Ty, ///< The type to convert to
5135 const Twine &NameStr, ///< A name for the new instruction
5136 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5139 /// Gets the pointer operand.
5140 Value *getPointerOperand() { return getOperand(0); }
5141 /// Gets the pointer operand.
5142 const Value *getPointerOperand() const { return getOperand(0); }
5143 /// Gets the operand index of the pointer operand.
5144 static unsigned getPointerOperandIndex() { return 0U; }
5146 /// Returns the address space of the pointer operand.
5147 unsigned getPointerAddressSpace() const {
5148 return getPointerOperand()->getType()->getPointerAddressSpace();
5151 // Methods for support type inquiry through isa, cast, and dyn_cast:
5152 static bool classof(const Instruction *I) {
5153 return I->getOpcode() == PtrToInt;
5155 static bool classof(const Value *V) {
5156 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5160 //===----------------------------------------------------------------------===//
5161 // BitCastInst Class
5162 //===----------------------------------------------------------------------===//
5164 /// This class represents a no-op cast from one type to another.
5165 class BitCastInst : public CastInst {
5166 protected:
5167 // Note: Instruction needs to be a friend here to call cloneImpl.
5168 friend class Instruction;
5170 /// Clone an identical BitCastInst.
5171 BitCastInst *cloneImpl() const;
5173 public:
5174 /// Constructor with insert-before-instruction semantics
5175 BitCastInst(
5176 Value *S, ///< The value to be casted
5177 Type *Ty, ///< The type to casted to
5178 const Twine &NameStr = "", ///< A name for the new instruction
5179 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5182 /// Constructor with insert-at-end-of-block semantics
5183 BitCastInst(
5184 Value *S, ///< The value to be casted
5185 Type *Ty, ///< The type to casted to
5186 const Twine &NameStr, ///< A name for the new instruction
5187 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5190 // Methods for support type inquiry through isa, cast, and dyn_cast:
5191 static bool classof(const Instruction *I) {
5192 return I->getOpcode() == BitCast;
5194 static bool classof(const Value *V) {
5195 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5199 //===----------------------------------------------------------------------===//
5200 // AddrSpaceCastInst Class
5201 //===----------------------------------------------------------------------===//
5203 /// This class represents a conversion between pointers from one address space
5204 /// to another.
5205 class AddrSpaceCastInst : public CastInst {
5206 protected:
5207 // Note: Instruction needs to be a friend here to call cloneImpl.
5208 friend class Instruction;
5210 /// Clone an identical AddrSpaceCastInst.
5211 AddrSpaceCastInst *cloneImpl() const;
5213 public:
5214 /// Constructor with insert-before-instruction semantics
5215 AddrSpaceCastInst(
5216 Value *S, ///< The value to be casted
5217 Type *Ty, ///< The type to casted to
5218 const Twine &NameStr = "", ///< A name for the new instruction
5219 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5222 /// Constructor with insert-at-end-of-block semantics
5223 AddrSpaceCastInst(
5224 Value *S, ///< The value to be casted
5225 Type *Ty, ///< The type to casted to
5226 const Twine &NameStr, ///< A name for the new instruction
5227 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5230 // Methods for support type inquiry through isa, cast, and dyn_cast:
5231 static bool classof(const Instruction *I) {
5232 return I->getOpcode() == AddrSpaceCast;
5234 static bool classof(const Value *V) {
5235 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5238 /// Gets the pointer operand.
5239 Value *getPointerOperand() {
5240 return getOperand(0);
5243 /// Gets the pointer operand.
5244 const Value *getPointerOperand() const {
5245 return getOperand(0);
5248 /// Gets the operand index of the pointer operand.
5249 static unsigned getPointerOperandIndex() {
5250 return 0U;
5253 /// Returns the address space of the pointer operand.
5254 unsigned getSrcAddressSpace() const {
5255 return getPointerOperand()->getType()->getPointerAddressSpace();
5258 /// Returns the address space of the result.
5259 unsigned getDestAddressSpace() const {
5260 return getType()->getPointerAddressSpace();
5264 /// A helper function that returns the pointer operand of a load or store
5265 /// instruction. Returns nullptr if not load or store.
5266 inline const Value *getLoadStorePointerOperand(const Value *V) {
5267 if (auto *Load = dyn_cast<LoadInst>(V))
5268 return Load->getPointerOperand();
5269 if (auto *Store = dyn_cast<StoreInst>(V))
5270 return Store->getPointerOperand();
5271 return nullptr;
5273 inline Value *getLoadStorePointerOperand(Value *V) {
5274 return const_cast<Value *>(
5275 getLoadStorePointerOperand(static_cast<const Value *>(V)));
5278 /// A helper function that returns the pointer operand of a load, store
5279 /// or GEP instruction. Returns nullptr if not load, store, or GEP.
5280 inline const Value *getPointerOperand(const Value *V) {
5281 if (auto *Ptr = getLoadStorePointerOperand(V))
5282 return Ptr;
5283 if (auto *Gep = dyn_cast<GetElementPtrInst>(V))
5284 return Gep->getPointerOperand();
5285 return nullptr;
5287 inline Value *getPointerOperand(Value *V) {
5288 return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V)));
5291 /// A helper function that returns the alignment of load or store instruction.
5292 inline unsigned getLoadStoreAlignment(Value *I) {
5293 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5294 "Expected Load or Store instruction");
5295 if (auto *LI = dyn_cast<LoadInst>(I))
5296 return LI->getAlignment();
5297 return cast<StoreInst>(I)->getAlignment();
5300 /// A helper function that returns the address space of the pointer operand of
5301 /// load or store instruction.
5302 inline unsigned getLoadStoreAddressSpace(Value *I) {
5303 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5304 "Expected Load or Store instruction");
5305 if (auto *LI = dyn_cast<LoadInst>(I))
5306 return LI->getPointerAddressSpace();
5307 return cast<StoreInst>(I)->getPointerAddressSpace();
5310 } // end namespace llvm
5312 #endif // LLVM_IR_INSTRUCTIONS_H