LLVM  6.0.0svn
Instructions.h
Go to the documentation of this file.
1 //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file exposes the class definitions of all of the subclasses of the
11 // Instruction class. This is meant to be an easy way to get access to all
12 // instruction subclasses.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_IR_INSTRUCTIONS_H
17 #define LLVM_IR_INSTRUCTIONS_H
18 
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/ADT/iterator.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/InstrTypes.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/OperandTraits.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Use.h"
38 #include "llvm/IR/User.h"
39 #include "llvm/IR/Value.h"
41 #include "llvm/Support/Casting.h"
43 #include <cassert>
44 #include <cstddef>
45 #include <cstdint>
46 #include <iterator>
47 
48 namespace llvm {
49 
50 class APInt;
51 class ConstantInt;
52 class DataLayout;
53 class LLVMContext;
54 
55 //===----------------------------------------------------------------------===//
56 // AllocaInst Class
57 //===----------------------------------------------------------------------===//
58 
59 /// an instruction to allocate memory on the stack
60 class AllocaInst : public UnaryInstruction {
61  Type *AllocatedType;
62 
63 protected:
64  // Note: Instruction needs to be a friend here to call cloneImpl.
65  friend class Instruction;
66 
67  AllocaInst *cloneImpl() const;
68 
69 public:
70  explicit AllocaInst(Type *Ty, unsigned AddrSpace,
71  Value *ArraySize = nullptr,
72  const Twine &Name = "",
73  Instruction *InsertBefore = nullptr);
74  AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
75  const Twine &Name, BasicBlock *InsertAtEnd);
76 
77  AllocaInst(Type *Ty, unsigned AddrSpace,
78  const Twine &Name, Instruction *InsertBefore = nullptr);
79  AllocaInst(Type *Ty, unsigned AddrSpace,
80  const Twine &Name, BasicBlock *InsertAtEnd);
81 
82  AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
83  const Twine &Name = "", Instruction *InsertBefore = nullptr);
84  AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
85  const Twine &Name, BasicBlock *InsertAtEnd);
86 
87  /// Return true if there is an allocation size parameter to the allocation
88  /// instruction that is not 1.
89  bool isArrayAllocation() const;
90 
91  /// Get the number of elements allocated. For a simple allocation of a single
92  /// element, this will return a constant 1 value.
93  const Value *getArraySize() const { return getOperand(0); }
94  Value *getArraySize() { return getOperand(0); }
95 
96  /// Overload to return most specific pointer type.
97  PointerType *getType() const {
98  return cast<PointerType>(Instruction::getType());
99  }
100 
101  /// Return the type that is being allocated by the instruction.
102  Type *getAllocatedType() const { return AllocatedType; }
103  /// for use only in special circumstances that need to generically
104  /// transform a whole instruction (eg: IR linking and vectorization).
105  void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
106 
107  /// Return the alignment of the memory that is being allocated by the
108  /// instruction.
109  unsigned getAlignment() const {
110  return (1u << (getSubclassDataFromInstruction() & 31)) >> 1;
111  }
112  void setAlignment(unsigned Align);
113 
114  /// Return true if this alloca is in the entry block of the function and is a
115  /// constant size. If so, the code generator will fold it into the
116  /// prolog/epilog code, so it is basically free.
117  bool isStaticAlloca() const;
118 
119  /// Return true if this alloca is used as an inalloca argument to a call. Such
120  /// allocas are never considered static even if they are in the entry block.
121  bool isUsedWithInAlloca() const {
122  return getSubclassDataFromInstruction() & 32;
123  }
124 
125  /// Specify whether this alloca is used to represent the arguments to a call.
126  void setUsedWithInAlloca(bool V) {
127  setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
128  (V ? 32 : 0));
129  }
130 
131  /// Return true if this alloca is used as a swifterror argument to a call.
132  bool isSwiftError() const {
133  return getSubclassDataFromInstruction() & 64;
134  }
135 
136  /// Specify whether this alloca is used to represent a swifterror.
137  void setSwiftError(bool V) {
138  setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
139  (V ? 64 : 0));
140  }
141 
142  // Methods for support type inquiry through isa, cast, and dyn_cast:
143  static bool classof(const Instruction *I) {
144  return (I->getOpcode() == Instruction::Alloca);
145  }
146  static bool classof(const Value *V) {
147  return isa<Instruction>(V) && classof(cast<Instruction>(V));
148  }
149 
150 private:
151  // Shadow Instruction::setInstructionSubclassData with a private forwarding
152  // method so that subclasses cannot accidentally use it.
153  void setInstructionSubclassData(unsigned short D) {
155  }
156 };
157 
158 //===----------------------------------------------------------------------===//
159 // LoadInst Class
160 //===----------------------------------------------------------------------===//
161 
162 /// An instruction for reading from memory. This uses the SubclassData field in
163 /// Value to store whether or not the load is volatile.
164 class LoadInst : public UnaryInstruction {
165  void AssertOK();
166 
167 protected:
168  // Note: Instruction needs to be a friend here to call cloneImpl.
169  friend class Instruction;
170 
171  LoadInst *cloneImpl() const;
172 
173 public:
174  LoadInst(Value *Ptr, const Twine &NameStr, Instruction *InsertBefore);
175  LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
176  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile = false,
177  Instruction *InsertBefore = nullptr);
178  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile = false,
179  Instruction *InsertBefore = nullptr)
180  : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
181  NameStr, isVolatile, InsertBefore) {}
182  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
183  BasicBlock *InsertAtEnd);
184  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
185  Instruction *InsertBefore = nullptr)
186  : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
187  NameStr, isVolatile, Align, InsertBefore) {}
188  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189  unsigned Align, Instruction *InsertBefore = nullptr);
190  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
191  unsigned Align, BasicBlock *InsertAtEnd);
192  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
194  Instruction *InsertBefore = nullptr)
195  : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
196  NameStr, isVolatile, Align, Order, SSID, InsertBefore) {}
197  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
198  unsigned Align, AtomicOrdering Order,
200  Instruction *InsertBefore = nullptr);
201  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
202  unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
203  BasicBlock *InsertAtEnd);
204  LoadInst(Value *Ptr, const char *NameStr, Instruction *InsertBefore);
205  LoadInst(Value *Ptr, const char *NameStr, BasicBlock *InsertAtEnd);
206  LoadInst(Type *Ty, Value *Ptr, const char *NameStr = nullptr,
207  bool isVolatile = false, Instruction *InsertBefore = nullptr);
208  explicit LoadInst(Value *Ptr, const char *NameStr = nullptr,
209  bool isVolatile = false,
210  Instruction *InsertBefore = nullptr)
211  : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
212  NameStr, isVolatile, InsertBefore) {}
213  LoadInst(Value *Ptr, const char *NameStr, bool isVolatile,
214  BasicBlock *InsertAtEnd);
215 
216  /// Return true if this is a load from a volatile memory location.
217  bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
218 
219  /// Specify whether this is a volatile load or not.
220  void setVolatile(bool V) {
221  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
222  (V ? 1 : 0));
223  }
224 
225  /// Return the alignment of the access that is being performed.
226  unsigned getAlignment() const {
227  return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
228  }
229 
230  void setAlignment(unsigned Align);
231 
232  /// Returns the ordering constraint of this load instruction.
234  return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
235  }
236 
237  /// Sets the ordering constraint of this load instruction. May not be Release
238  /// or AcquireRelease.
239  void setOrdering(AtomicOrdering Ordering) {
240  setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
241  ((unsigned)Ordering << 7));
242  }
243 
244  /// Returns the synchronization scope ID of this load instruction.
246  return SSID;
247  }
248 
249  /// Sets the synchronization scope ID of this load instruction.
251  this->SSID = SSID;
252  }
253 
254  /// Sets the ordering constraint and the synchronization scope ID of this load
255  /// instruction.
256  void setAtomic(AtomicOrdering Ordering,
258  setOrdering(Ordering);
259  setSyncScopeID(SSID);
260  }
261 
262  bool isSimple() const { return !isAtomic() && !isVolatile(); }
263 
264  bool isUnordered() const {
265  return (getOrdering() == AtomicOrdering::NotAtomic ||
266  getOrdering() == AtomicOrdering::Unordered) &&
267  !isVolatile();
268  }
269 
271  const Value *getPointerOperand() const { return getOperand(0); }
272  static unsigned getPointerOperandIndex() { return 0U; }
273  Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
274 
275  /// Returns the address space of the pointer operand.
276  unsigned getPointerAddressSpace() const {
277  return getPointerOperandType()->getPointerAddressSpace();
278  }
279 
280  // Methods for support type inquiry through isa, cast, and dyn_cast:
281  static bool classof(const Instruction *I) {
282  return I->getOpcode() == Instruction::Load;
283  }
284  static bool classof(const Value *V) {
285  return isa<Instruction>(V) && classof(cast<Instruction>(V));
286  }
287 
288 private:
289  // Shadow Instruction::setInstructionSubclassData with a private forwarding
290  // method so that subclasses cannot accidentally use it.
291  void setInstructionSubclassData(unsigned short D) {
293  }
294 
295  /// The synchronization scope ID of this load instruction. Not quite enough
296  /// room in SubClassData for everything, so synchronization scope ID gets its
297  /// own field.
298  SyncScope::ID SSID;
299 };
300 
301 //===----------------------------------------------------------------------===//
302 // StoreInst Class
303 //===----------------------------------------------------------------------===//
304 
305 /// An instruction for storing to memory.
306 class StoreInst : public Instruction {
307  void AssertOK();
308 
309 protected:
310  // Note: Instruction needs to be a friend here to call cloneImpl.
311  friend class Instruction;
312 
313  StoreInst *cloneImpl() const;
314 
315 public:
316  StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
317  StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
318  StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
319  Instruction *InsertBefore = nullptr);
320  StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
321  StoreInst(Value *Val, Value *Ptr, bool isVolatile,
322  unsigned Align, Instruction *InsertBefore = nullptr);
323  StoreInst(Value *Val, Value *Ptr, bool isVolatile,
324  unsigned Align, BasicBlock *InsertAtEnd);
325  StoreInst(Value *Val, Value *Ptr, bool isVolatile,
326  unsigned Align, AtomicOrdering Order,
328  Instruction *InsertBefore = nullptr);
329  StoreInst(Value *Val, Value *Ptr, bool isVolatile,
330  unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
331  BasicBlock *InsertAtEnd);
332 
333  // allocate space for exactly two operands
334  void *operator new(size_t s) {
335  return User::operator new(s, 2);
336  }
337 
338  /// Return true if this is a store to a volatile memory location.
339  bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
340 
341  /// Specify whether this is a volatile store or not.
342  void setVolatile(bool V) {
343  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
344  (V ? 1 : 0));
345  }
346 
347  /// Transparently provide more efficient getOperand methods.
349 
350  /// Return the alignment of the access that is being performed
351  unsigned getAlignment() const {
352  return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
353  }
354 
355  void setAlignment(unsigned Align);
356 
357  /// Returns the ordering constraint of this store instruction.
359  return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
360  }
361 
362  /// Sets the ordering constraint of this store instruction. May not be
363  /// Acquire or AcquireRelease.
364  void setOrdering(AtomicOrdering Ordering) {
365  setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
366  ((unsigned)Ordering << 7));
367  }
368 
369  /// Returns the synchronization scope ID of this store instruction.
371  return SSID;
372  }
373 
374  /// Sets the synchronization scope ID of this store instruction.
376  this->SSID = SSID;
377  }
378 
379  /// Sets the ordering constraint and the synchronization scope ID of this
380  /// store instruction.
381  void setAtomic(AtomicOrdering Ordering,
383  setOrdering(Ordering);
384  setSyncScopeID(SSID);
385  }
386 
387  bool isSimple() const { return !isAtomic() && !isVolatile(); }
388 
389  bool isUnordered() const {
390  return (getOrdering() == AtomicOrdering::NotAtomic ||
391  getOrdering() == AtomicOrdering::Unordered) &&
392  !isVolatile();
393  }
394 
395  Value *getValueOperand() { return getOperand(0); }
396  const Value *getValueOperand() const { return getOperand(0); }
397 
399  const Value *getPointerOperand() const { return getOperand(1); }
400  static unsigned getPointerOperandIndex() { return 1U; }
401  Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
402 
403  /// Returns the address space of the pointer operand.
404  unsigned getPointerAddressSpace() const {
405  return getPointerOperandType()->getPointerAddressSpace();
406  }
407 
408  // Methods for support type inquiry through isa, cast, and dyn_cast:
409  static bool classof(const Instruction *I) {
410  return I->getOpcode() == Instruction::Store;
411  }
412  static bool classof(const Value *V) {
413  return isa<Instruction>(V) && classof(cast<Instruction>(V));
414  }
415 
416 private:
417  // Shadow Instruction::setInstructionSubclassData with a private forwarding
418  // method so that subclasses cannot accidentally use it.
419  void setInstructionSubclassData(unsigned short D) {
421  }
422 
423  /// The synchronization scope ID of this store instruction. Not quite enough
424  /// room in SubClassData for everything, so synchronization scope ID gets its
425  /// own field.
426  SyncScope::ID SSID;
427 };
428 
429 template <>
430 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
431 };
432 
434 
435 //===----------------------------------------------------------------------===//
436 // FenceInst Class
437 //===----------------------------------------------------------------------===//
438 
439 /// An instruction for ordering other memory operations.
440 class FenceInst : public Instruction {
441  void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
442 
443 protected:
444  // Note: Instruction needs to be a friend here to call cloneImpl.
445  friend class Instruction;
446 
447  FenceInst *cloneImpl() const;
448 
449 public:
450  // Ordering may only be Acquire, Release, AcquireRelease, or
451  // SequentiallyConsistent.
454  Instruction *InsertBefore = nullptr);
456  BasicBlock *InsertAtEnd);
457 
458  // allocate space for exactly zero operands
459  void *operator new(size_t s) {
460  return User::operator new(s, 0);
461  }
462 
463  /// Returns the ordering constraint of this fence instruction.
466  }
467 
468  /// Sets the ordering constraint of this fence instruction. May only be
469  /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
470  void setOrdering(AtomicOrdering Ordering) {
471  setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
472  ((unsigned)Ordering << 1));
473  }
474 
475  /// Returns the synchronization scope ID of this fence instruction.
477  return SSID;
478  }
479 
480  /// Sets the synchronization scope ID of this fence instruction.
482  this->SSID = SSID;
483  }
484 
485  // Methods for support type inquiry through isa, cast, and dyn_cast:
486  static bool classof(const Instruction *I) {
487  return I->getOpcode() == Instruction::Fence;
488  }
489  static bool classof(const Value *V) {
490  return isa<Instruction>(V) && classof(cast<Instruction>(V));
491  }
492 
493 private:
494  // Shadow Instruction::setInstructionSubclassData with a private forwarding
495  // method so that subclasses cannot accidentally use it.
496  void setInstructionSubclassData(unsigned short D) {
498  }
499 
500  /// The synchronization scope ID of this fence instruction. Not quite enough
501  /// room in SubClassData for everything, so synchronization scope ID gets its
502  /// own field.
503  SyncScope::ID SSID;
504 };
505 
506 //===----------------------------------------------------------------------===//
507 // AtomicCmpXchgInst Class
508 //===----------------------------------------------------------------------===//
509 
510 /// an instruction that atomically checks whether a
511 /// specified value is in a memory location, and, if it is, stores a new value
512 /// there. Returns the value that was loaded.
513 ///
515  void Init(Value *Ptr, Value *Cmp, Value *NewVal,
516  AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
517  SyncScope::ID SSID);
518 
519 protected:
520  // Note: Instruction needs to be a friend here to call cloneImpl.
521  friend class Instruction;
522 
523  AtomicCmpXchgInst *cloneImpl() const;
524 
525 public:
526  AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
527  AtomicOrdering SuccessOrdering,
528  AtomicOrdering FailureOrdering,
529  SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
530  AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
531  AtomicOrdering SuccessOrdering,
532  AtomicOrdering FailureOrdering,
533  SyncScope::ID SSID, BasicBlock *InsertAtEnd);
534 
535  // allocate space for exactly three operands
536  void *operator new(size_t s) {
537  return User::operator new(s, 3);
538  }
539 
540  /// Return true if this is a cmpxchg from a volatile memory
541  /// location.
542  ///
543  bool isVolatile() const {
544  return getSubclassDataFromInstruction() & 1;
545  }
546 
547  /// Specify whether this is a volatile cmpxchg.
548  ///
549  void setVolatile(bool V) {
550  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
551  (unsigned)V);
552  }
553 
554  /// Return true if this cmpxchg may spuriously fail.
555  bool isWeak() const {
556  return getSubclassDataFromInstruction() & 0x100;
557  }
558 
559  void setWeak(bool IsWeak) {
560  setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
561  (IsWeak << 8));
562  }
563 
564  /// Transparently provide more efficient getOperand methods.
566 
567  /// Returns the success ordering constraint of this cmpxchg instruction.
569  return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
570  }
571 
572  /// Sets the success ordering constraint of this cmpxchg instruction.
574  assert(Ordering != AtomicOrdering::NotAtomic &&
575  "CmpXchg instructions can only be atomic.");
576  setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
577  ((unsigned)Ordering << 2));
578  }
579 
580  /// Returns the failure ordering constraint of this cmpxchg instruction.
582  return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
583  }
584 
585  /// Sets the failure ordering constraint of this cmpxchg instruction.
587  assert(Ordering != AtomicOrdering::NotAtomic &&
588  "CmpXchg instructions can only be atomic.");
589  setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
590  ((unsigned)Ordering << 5));
591  }
592 
593  /// Returns the synchronization scope ID of this cmpxchg instruction.
595  return SSID;
596  }
597 
598  /// Sets the synchronization scope ID of this cmpxchg instruction.
600  this->SSID = SSID;
601  }
602 
604  const Value *getPointerOperand() const { return getOperand(0); }
605  static unsigned getPointerOperandIndex() { return 0U; }
606 
608  const Value *getCompareOperand() const { return getOperand(1); }
609 
611  const Value *getNewValOperand() const { return getOperand(2); }
612 
613  /// Returns the address space of the pointer operand.
614  unsigned getPointerAddressSpace() const {
615  return getPointerOperand()->getType()->getPointerAddressSpace();
616  }
617 
618  /// Returns the strongest permitted ordering on failure, given the
619  /// desired ordering on success.
620  ///
621  /// If the comparison in a cmpxchg operation fails, there is no atomic store
622  /// so release semantics cannot be provided. So this function drops explicit
623  /// Release requests from the AtomicOrdering. A SequentiallyConsistent
624  /// operation would remain SequentiallyConsistent.
625  static AtomicOrdering
627  switch (SuccessOrdering) {
628  default:
629  llvm_unreachable("invalid cmpxchg success ordering");
638  }
639  }
640 
641  // Methods for support type inquiry through isa, cast, and dyn_cast:
642  static bool classof(const Instruction *I) {
643  return I->getOpcode() == Instruction::AtomicCmpXchg;
644  }
645  static bool classof(const Value *V) {
646  return isa<Instruction>(V) && classof(cast<Instruction>(V));
647  }
648 
649 private:
650  // Shadow Instruction::setInstructionSubclassData with a private forwarding
651  // method so that subclasses cannot accidentally use it.
652  void setInstructionSubclassData(unsigned short D) {
654  }
655 
656  /// The synchronization scope ID of this cmpxchg instruction. Not quite
657  /// enough room in SubClassData for everything, so synchronization scope ID
658  /// gets its own field.
659  SyncScope::ID SSID;
660 };
661 
662 template <>
664  public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
665 };
666 
668 
669 //===----------------------------------------------------------------------===//
670 // AtomicRMWInst Class
671 //===----------------------------------------------------------------------===//
672 
673 /// an instruction that atomically reads a memory location,
674 /// combines it with another value, and then stores the result back. Returns
675 /// the old value.
676 ///
677 class AtomicRMWInst : public Instruction {
678 protected:
679  // Note: Instruction needs to be a friend here to call cloneImpl.
680  friend class Instruction;
681 
682  AtomicRMWInst *cloneImpl() const;
683 
684 public:
685  /// This enumeration lists the possible modifications atomicrmw can make. In
686  /// the descriptions, 'p' is the pointer to the instruction's memory location,
687  /// 'old' is the initial value of *p, and 'v' is the other value passed to the
688  /// instruction. These instructions always return 'old'.
689  enum BinOp {
690  /// *p = v
692  /// *p = old + v
694  /// *p = old - v
696  /// *p = old & v
698  /// *p = ~(old & v)
700  /// *p = old | v
701  Or,
702  /// *p = old ^ v
704  /// *p = old >signed v ? old : v
706  /// *p = old <signed v ? old : v
708  /// *p = old >unsigned v ? old : v
710  /// *p = old <unsigned v ? old : v
712 
713  FIRST_BINOP = Xchg,
714  LAST_BINOP = UMin,
715  BAD_BINOP
716  };
717 
718  AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
719  AtomicOrdering Ordering, SyncScope::ID SSID,
720  Instruction *InsertBefore = nullptr);
721  AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
722  AtomicOrdering Ordering, SyncScope::ID SSID,
723  BasicBlock *InsertAtEnd);
724 
725  // allocate space for exactly two operands
726  void *operator new(size_t s) {
727  return User::operator new(s, 2);
728  }
729 
730  BinOp getOperation() const {
731  return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
732  }
733 
734  void setOperation(BinOp Operation) {
735  unsigned short SubclassData = getSubclassDataFromInstruction();
736  setInstructionSubclassData((SubclassData & 31) |
737  (Operation << 5));
738  }
739 
740  /// Return true if this is a RMW on a volatile memory location.
741  ///
742  bool isVolatile() const {
743  return getSubclassDataFromInstruction() & 1;
744  }
745 
746  /// Specify whether this is a volatile RMW or not.
747  ///
748  void setVolatile(bool V) {
749  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
750  (unsigned)V);
751  }
752 
753  /// Transparently provide more efficient getOperand methods.
755 
756  /// Returns the ordering constraint of this rmw instruction.
758  return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
759  }
760 
761  /// Sets the ordering constraint of this rmw instruction.
762  void setOrdering(AtomicOrdering Ordering) {
763  assert(Ordering != AtomicOrdering::NotAtomic &&
764  "atomicrmw instructions can only be atomic.");
765  setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
766  ((unsigned)Ordering << 2));
767  }
768 
769  /// Returns the synchronization scope ID of this rmw instruction.
771  return SSID;
772  }
773 
774  /// Sets the synchronization scope ID of this rmw instruction.
776  this->SSID = SSID;
777  }
778 
780  const Value *getPointerOperand() const { return getOperand(0); }
781  static unsigned getPointerOperandIndex() { return 0U; }
782 
783  Value *getValOperand() { return getOperand(1); }
784  const Value *getValOperand() const { return getOperand(1); }
785 
786  /// Returns the address space of the pointer operand.
787  unsigned getPointerAddressSpace() const {
788  return getPointerOperand()->getType()->getPointerAddressSpace();
789  }
790 
791  // Methods for support type inquiry through isa, cast, and dyn_cast:
792  static bool classof(const Instruction *I) {
793  return I->getOpcode() == Instruction::AtomicRMW;
794  }
795  static bool classof(const Value *V) {
796  return isa<Instruction>(V) && classof(cast<Instruction>(V));
797  }
798 
799 private:
800  void Init(BinOp Operation, Value *Ptr, Value *Val,
801  AtomicOrdering Ordering, SyncScope::ID SSID);
802 
803  // Shadow Instruction::setInstructionSubclassData with a private forwarding
804  // method so that subclasses cannot accidentally use it.
805  void setInstructionSubclassData(unsigned short D) {
807  }
808 
809  /// The synchronization scope ID of this rmw instruction. Not quite enough
810  /// room in SubClassData for everything, so synchronization scope ID gets its
811  /// own field.
812  SyncScope::ID SSID;
813 };
814 
815 template <>
817  : public FixedNumOperandTraits<AtomicRMWInst,2> {
818 };
819 
821 
822 //===----------------------------------------------------------------------===//
823 // GetElementPtrInst Class
824 //===----------------------------------------------------------------------===//
825 
826 // checkGEPType - Simple wrapper function to give a better assertion failure
827 // message on bad indexes for a gep instruction.
828 //
830  assert(Ty && "Invalid GetElementPtrInst indices for type!");
831  return Ty;
832 }
833 
834 /// an instruction for type-safe pointer arithmetic to
835 /// access elements of arrays and structs
836 ///
838  Type *SourceElementType;
839  Type *ResultElementType;
840 
842 
843  /// Constructors - Create a getelementptr instruction with a base pointer an
844  /// list of indices. The first ctor can optionally insert before an existing
845  /// instruction, the second appends the new instruction to the specified
846  /// BasicBlock.
847  inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
848  ArrayRef<Value *> IdxList, unsigned Values,
849  const Twine &NameStr, Instruction *InsertBefore);
850  inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
851  ArrayRef<Value *> IdxList, unsigned Values,
852  const Twine &NameStr, BasicBlock *InsertAtEnd);
853 
854  void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
855 
856 protected:
857  // Note: Instruction needs to be a friend here to call cloneImpl.
858  friend class Instruction;
859 
860  GetElementPtrInst *cloneImpl() const;
861 
862 public:
863  static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
864  ArrayRef<Value *> IdxList,
865  const Twine &NameStr = "",
866  Instruction *InsertBefore = nullptr) {
867  unsigned Values = 1 + unsigned(IdxList.size());
868  if (!PointeeType)
869  PointeeType =
870  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
871  else
872  assert(
873  PointeeType ==
874  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
875  return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
876  NameStr, InsertBefore);
877  }
878 
879  static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
880  ArrayRef<Value *> IdxList,
881  const Twine &NameStr,
882  BasicBlock *InsertAtEnd) {
883  unsigned Values = 1 + unsigned(IdxList.size());
884  if (!PointeeType)
885  PointeeType =
886  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
887  else
888  assert(
889  PointeeType ==
890  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
891  return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
892  NameStr, InsertAtEnd);
893  }
894 
895  /// Create an "inbounds" getelementptr. See the documentation for the
896  /// "inbounds" flag in LangRef.html for details.
898  ArrayRef<Value *> IdxList,
899  const Twine &NameStr = "",
900  Instruction *InsertBefore = nullptr){
901  return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
902  }
903 
904  static GetElementPtrInst *
905  CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
906  const Twine &NameStr = "",
907  Instruction *InsertBefore = nullptr) {
909  Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
910  GEP->setIsInBounds(true);
911  return GEP;
912  }
913 
915  ArrayRef<Value *> IdxList,
916  const Twine &NameStr,
917  BasicBlock *InsertAtEnd) {
918  return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
919  }
920 
921  static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
922  ArrayRef<Value *> IdxList,
923  const Twine &NameStr,
924  BasicBlock *InsertAtEnd) {
926  Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
927  GEP->setIsInBounds(true);
928  return GEP;
929  }
930 
931  /// Transparently provide more efficient getOperand methods.
933 
934  Type *getSourceElementType() const { return SourceElementType; }
935 
936  void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
937  void setResultElementType(Type *Ty) { ResultElementType = Ty; }
938 
940  assert(ResultElementType ==
941  cast<PointerType>(getType()->getScalarType())->getElementType());
942  return ResultElementType;
943  }
944 
945  /// Returns the address space of this instruction's pointer type.
946  unsigned getAddressSpace() const {
947  // Note that this is always the same as the pointer operand's address space
948  // and that is cheaper to compute, so cheat here.
949  return getPointerAddressSpace();
950  }
951 
952  /// Returns the type of the element that would be loaded with
953  /// a load instruction with the specified parameters.
954  ///
955  /// Null is returned if the indices are invalid for the specified
956  /// pointer type.
957  ///
958  static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
959  static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
960  static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
961 
962  inline op_iterator idx_begin() { return op_begin()+1; }
963  inline const_op_iterator idx_begin() const { return op_begin()+1; }
964  inline op_iterator idx_end() { return op_end(); }
965  inline const_op_iterator idx_end() const { return op_end(); }
966 
968  return make_range(idx_begin(), idx_end());
969  }
970 
972  return make_range(idx_begin(), idx_end());
973  }
974 
976  return getOperand(0);
977  }
978  const Value *getPointerOperand() const {
979  return getOperand(0);
980  }
981  static unsigned getPointerOperandIndex() {
982  return 0U; // get index for modifying correct operand.
983  }
984 
985  /// Method to return the pointer operand as a
986  /// PointerType.
988  return getPointerOperand()->getType();
989  }
990 
991  /// Returns the address space of the pointer operand.
992  unsigned getPointerAddressSpace() const {
993  return getPointerOperandType()->getPointerAddressSpace();
994  }
995 
996  /// Returns the pointer type returned by the GEP
997  /// instruction, which may be a vector of pointers.
998  static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
999  return getGEPReturnType(
1000  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1001  Ptr, IdxList);
1002  }
1003  static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1004  ArrayRef<Value *> IdxList) {
1005  Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1006  Ptr->getType()->getPointerAddressSpace());
1007  // Vector GEP
1008  if (Ptr->getType()->isVectorTy()) {
1009  unsigned NumElem = Ptr->getType()->getVectorNumElements();
1010  return VectorType::get(PtrTy, NumElem);
1011  }
1012  for (Value *Index : IdxList)
1013  if (Index->getType()->isVectorTy()) {
1014  unsigned NumElem = Index->getType()->getVectorNumElements();
1015  return VectorType::get(PtrTy, NumElem);
1016  }
1017  // Scalar GEP
1018  return PtrTy;
1019  }
1020 
1021  unsigned getNumIndices() const { // Note: always non-negative
1022  return getNumOperands() - 1;
1023  }
1024 
1025  bool hasIndices() const {
1026  return getNumOperands() > 1;
1027  }
1028 
1029  /// Return true if all of the indices of this GEP are
1030  /// zeros. If so, the result pointer and the first operand have the same
1031  /// value, just potentially different types.
1032  bool hasAllZeroIndices() const;
1033 
1034  /// Return true if all of the indices of this GEP are
1035  /// constant integers. If so, the result pointer and the first operand have
1036  /// a constant offset between them.
1037  bool hasAllConstantIndices() const;
1038 
1039  /// Set or clear the inbounds flag on this GEP instruction.
1040  /// See LangRef.html for the meaning of inbounds on a getelementptr.
1041  void setIsInBounds(bool b = true);
1042 
1043  /// Determine whether the GEP has the inbounds flag.
1044  bool isInBounds() const;
1045 
1046  /// Accumulate the constant address offset of this GEP if possible.
1047  ///
1048  /// This routine accepts an APInt into which it will accumulate the constant
1049  /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1050  /// all-constant, it returns false and the value of the offset APInt is
1051  /// undefined (it is *not* preserved!). The APInt passed into this routine
1052  /// must be at least as wide as the IntPtr type for the address space of
1053  /// the base GEP pointer.
1054  bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1055 
1056  // Methods for support type inquiry through isa, cast, and dyn_cast:
1057  static bool classof(const Instruction *I) {
1058  return (I->getOpcode() == Instruction::GetElementPtr);
1059  }
1060  static bool classof(const Value *V) {
1061  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1062  }
1063 };
1064 
1065 template <>
1067  public VariadicOperandTraits<GetElementPtrInst, 1> {
1068 };
1069 
1070 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1071  ArrayRef<Value *> IdxList, unsigned Values,
1072  const Twine &NameStr,
1073  Instruction *InsertBefore)
1074  : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1076  Values, InsertBefore),
1077  SourceElementType(PointeeType),
1078  ResultElementType(getIndexedType(PointeeType, IdxList)) {
1079  assert(ResultElementType ==
1080  cast<PointerType>(getType()->getScalarType())->getElementType());
1081  init(Ptr, IdxList, NameStr);
1082 }
1083 
1084 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1085  ArrayRef<Value *> IdxList, unsigned Values,
1086  const Twine &NameStr,
1087  BasicBlock *InsertAtEnd)
1088  : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1090  Values, InsertAtEnd),
1091  SourceElementType(PointeeType),
1092  ResultElementType(getIndexedType(PointeeType, IdxList)) {
1093  assert(ResultElementType ==
1094  cast<PointerType>(getType()->getScalarType())->getElementType());
1095  init(Ptr, IdxList, NameStr);
1096 }
1097 
1098 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1099 
1100 //===----------------------------------------------------------------------===//
1101 // ICmpInst Class
1102 //===----------------------------------------------------------------------===//
1103 
1104 /// This instruction compares its operands according to the predicate given
1105 /// to the constructor. It only operates on integers or pointers. The operands
1106 /// must be identical types.
1107 /// Represent an integer comparison operator.
1108 class ICmpInst: public CmpInst {
1109  void AssertOK() {
1110  assert(isIntPredicate() &&
1111  "Invalid ICmp predicate value");
1112  assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1113  "Both operands to ICmp instruction are not of the same type!");
1114  // Check that the operands are the right type
1115  assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1116  getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1117  "Invalid operand types for ICmp instruction");
1118  }
1119 
1120 protected:
1121  // Note: Instruction needs to be a friend here to call cloneImpl.
1122  friend class Instruction;
1123 
1124  /// Clone an identical ICmpInst
1125  ICmpInst *cloneImpl() const;
1126 
1127 public:
1128  /// Constructor with insert-before-instruction semantics.
1130  Instruction *InsertBefore, ///< Where to insert
1131  Predicate pred, ///< The predicate to use for the comparison
1132  Value *LHS, ///< The left-hand-side of the expression
1133  Value *RHS, ///< The right-hand-side of the expression
1134  const Twine &NameStr = "" ///< Name of the instruction
1135  ) : CmpInst(makeCmpResultType(LHS->getType()),
1136  Instruction::ICmp, pred, LHS, RHS, NameStr,
1137  InsertBefore) {
1138 #ifndef NDEBUG
1139  AssertOK();
1140 #endif
1141  }
1142 
1143  /// Constructor with insert-at-end semantics.
1145  BasicBlock &InsertAtEnd, ///< Block to insert into.
1146  Predicate pred, ///< The predicate to use for the comparison
1147  Value *LHS, ///< The left-hand-side of the expression
1148  Value *RHS, ///< The right-hand-side of the expression
1149  const Twine &NameStr = "" ///< Name of the instruction
1150  ) : CmpInst(makeCmpResultType(LHS->getType()),
1151  Instruction::ICmp, pred, LHS, RHS, NameStr,
1152  &InsertAtEnd) {
1153 #ifndef NDEBUG
1154  AssertOK();
1155 #endif
1156  }
1157 
1158  /// Constructor with no-insertion semantics
1160  Predicate pred, ///< The predicate to use for the comparison
1161  Value *LHS, ///< The left-hand-side of the expression
1162  Value *RHS, ///< The right-hand-side of the expression
1163  const Twine &NameStr = "" ///< Name of the instruction
1164  ) : CmpInst(makeCmpResultType(LHS->getType()),
1165  Instruction::ICmp, pred, LHS, RHS, NameStr) {
1166 #ifndef NDEBUG
1167  AssertOK();
1168 #endif
1169  }
1170 
1171  /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1172  /// @returns the predicate that would be the result if the operand were
1173  /// regarded as signed.
1174  /// Return the signed version of the predicate
1176  return getSignedPredicate(getPredicate());
1177  }
1178 
1179  /// This is a static version that you can use without an instruction.
1180  /// Return the signed version of the predicate.
1181  static Predicate getSignedPredicate(Predicate pred);
1182 
1183  /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1184  /// @returns the predicate that would be the result if the operand were
1185  /// regarded as unsigned.
1186  /// Return the unsigned version of the predicate
1188  return getUnsignedPredicate(getPredicate());
1189  }
1190 
1191  /// This is a static version that you can use without an instruction.
1192  /// Return the unsigned version of the predicate.
1193  static Predicate getUnsignedPredicate(Predicate pred);
1194 
1195  /// Return true if this predicate is either EQ or NE. This also
1196  /// tests for commutativity.
1197  static bool isEquality(Predicate P) {
1198  return P == ICMP_EQ || P == ICMP_NE;
1199  }
1200 
1201  /// Return true if this predicate is either EQ or NE. This also
1202  /// tests for commutativity.
1203  bool isEquality() const {
1204  return isEquality(getPredicate());
1205  }
1206 
1207  /// @returns true if the predicate of this ICmpInst is commutative
1208  /// Determine if this relation is commutative.
1209  bool isCommutative() const { return isEquality(); }
1210 
1211  /// Return true if the predicate is relational (not EQ or NE).
1212  ///
1213  bool isRelational() const {
1214  return !isEquality();
1215  }
1216 
1217  /// Return true if the predicate is relational (not EQ or NE).
1218  ///
1219  static bool isRelational(Predicate P) {
1220  return !isEquality(P);
1221  }
1222 
1223  /// Exchange the two operands to this instruction in such a way that it does
1224  /// not modify the semantics of the instruction. The predicate value may be
1225  /// changed to retain the same result if the predicate is order dependent
1226  /// (e.g. ult).
1227  /// Swap operands and adjust predicate.
1228  void swapOperands() {
1229  setPredicate(getSwappedPredicate());
1230  Op<0>().swap(Op<1>());
1231  }
1232 
1233  // Methods for support type inquiry through isa, cast, and dyn_cast:
1234  static bool classof(const Instruction *I) {
1235  return I->getOpcode() == Instruction::ICmp;
1236  }
1237  static bool classof(const Value *V) {
1238  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1239  }
1240 };
1241 
1242 //===----------------------------------------------------------------------===//
1243 // FCmpInst Class
1244 //===----------------------------------------------------------------------===//
1245 
1246 /// This instruction compares its operands according to the predicate given
1247 /// to the constructor. It only operates on floating point values or packed
1248 /// vectors of floating point values. The operands must be identical types.
1249 /// Represents a floating point comparison operator.
1250 class FCmpInst: public CmpInst {
1251  void AssertOK() {
1252  assert(isFPPredicate() && "Invalid FCmp predicate value");
1253  assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1254  "Both operands to FCmp instruction are not of the same type!");
1255  // Check that the operands are the right type
1256  assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1257  "Invalid operand types for FCmp instruction");
1258  }
1259 
1260 protected:
1261  // Note: Instruction needs to be a friend here to call cloneImpl.
1262  friend class Instruction;
1263 
1264  /// Clone an identical FCmpInst
1265  FCmpInst *cloneImpl() const;
1266 
1267 public:
1268  /// Constructor with insert-before-instruction semantics.
1270  Instruction *InsertBefore, ///< Where to insert
1271  Predicate pred, ///< The predicate to use for the comparison
1272  Value *LHS, ///< The left-hand-side of the expression
1273  Value *RHS, ///< The right-hand-side of the expression
1274  const Twine &NameStr = "" ///< Name of the instruction
1275  ) : CmpInst(makeCmpResultType(LHS->getType()),
1276  Instruction::FCmp, pred, LHS, RHS, NameStr,
1277  InsertBefore) {
1278  AssertOK();
1279  }
1280 
1281  /// Constructor with insert-at-end semantics.
1283  BasicBlock &InsertAtEnd, ///< Block to insert into.
1284  Predicate pred, ///< The predicate to use for the comparison
1285  Value *LHS, ///< The left-hand-side of the expression
1286  Value *RHS, ///< The right-hand-side of the expression
1287  const Twine &NameStr = "" ///< Name of the instruction
1288  ) : CmpInst(makeCmpResultType(LHS->getType()),
1289  Instruction::FCmp, pred, LHS, RHS, NameStr,
1290  &InsertAtEnd) {
1291  AssertOK();
1292  }
1293 
1294  /// Constructor with no-insertion semantics
1296  Predicate pred, ///< The predicate to use for the comparison
1297  Value *LHS, ///< The left-hand-side of the expression
1298  Value *RHS, ///< The right-hand-side of the expression
1299  const Twine &NameStr = "" ///< Name of the instruction
1300  ) : CmpInst(makeCmpResultType(LHS->getType()),
1301  Instruction::FCmp, pred, LHS, RHS, NameStr) {
1302  AssertOK();
1303  }
1304 
1305  /// @returns true if the predicate of this instruction is EQ or NE.
1306  /// Determine if this is an equality predicate.
1307  static bool isEquality(Predicate Pred) {
1308  return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1309  Pred == FCMP_UNE;
1310  }
1311 
1312  /// @returns true if the predicate of this instruction is EQ or NE.
1313  /// Determine if this is an equality predicate.
1314  bool isEquality() const { return isEquality(getPredicate()); }
1315 
1316  /// @returns true if the predicate of this instruction is commutative.
1317  /// Determine if this is a commutative predicate.
1318  bool isCommutative() const {
1319  return isEquality() ||
1320  getPredicate() == FCMP_FALSE ||
1321  getPredicate() == FCMP_TRUE ||
1322  getPredicate() == FCMP_ORD ||
1323  getPredicate() == FCMP_UNO;
1324  }
1325 
1326  /// @returns true if the predicate is relational (not EQ or NE).
1327  /// Determine if this a relational predicate.
1328  bool isRelational() const { return !isEquality(); }
1329 
1330  /// Exchange the two operands to this instruction in such a way that it does
1331  /// not modify the semantics of the instruction. The predicate value may be
1332  /// changed to retain the same result if the predicate is order dependent
1333  /// (e.g. ult).
1334  /// Swap operands and adjust predicate.
1335  void swapOperands() {
1336  setPredicate(getSwappedPredicate());
1337  Op<0>().swap(Op<1>());
1338  }
1339 
1340  /// Methods for support type inquiry through isa, cast, and dyn_cast:
1341  static bool classof(const Instruction *I) {
1342  return I->getOpcode() == Instruction::FCmp;
1343  }
1344  static bool classof(const Value *V) {
1345  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1346  }
1347 };
1348 
1349 //===----------------------------------------------------------------------===//
1350 /// This class represents a function call, abstracting a target
1351 /// machine's calling convention. This class uses low bit of the SubClassData
1352 /// field to indicate whether or not this is a tail call. The rest of the bits
1353 /// hold the calling convention of the call.
1354 ///
1355 class CallInst : public Instruction,
1356  public OperandBundleUser<CallInst, User::op_iterator> {
1358 
1359  AttributeList Attrs; ///< parameter attributes for call
1360  FunctionType *FTy;
1361 
1362  CallInst(const CallInst &CI);
1363 
1364  /// Construct a CallInst given a range of arguments.
1365  /// Construct a CallInst from a range of arguments
1366  inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1367  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1368  Instruction *InsertBefore);
1369 
1370  inline CallInst(Value *Func, ArrayRef<Value *> Args,
1371  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1372  Instruction *InsertBefore)
1373  : CallInst(cast<FunctionType>(
1374  cast<PointerType>(Func->getType())->getElementType()),
1375  Func, Args, Bundles, NameStr, InsertBefore) {}
1376 
1377  inline CallInst(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr,
1378  Instruction *InsertBefore)
1379  : CallInst(Func, Args, None, NameStr, InsertBefore) {}
1380 
1381  /// Construct a CallInst given a range of arguments.
1382  /// Construct a CallInst from a range of arguments
1383  inline CallInst(Value *Func, ArrayRef<Value *> Args,
1384  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1385  BasicBlock *InsertAtEnd);
1386 
1387  explicit CallInst(Value *F, const Twine &NameStr,
1388  Instruction *InsertBefore);
1389 
1390  CallInst(Value *F, const Twine &NameStr, BasicBlock *InsertAtEnd);
1391 
1392  void init(Value *Func, ArrayRef<Value *> Args,
1393  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
1394  init(cast<FunctionType>(
1395  cast<PointerType>(Func->getType())->getElementType()),
1396  Func, Args, Bundles, NameStr);
1397  }
1398  void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1399  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1400  void init(Value *Func, const Twine &NameStr);
1401 
1402  bool hasDescriptor() const { return HasDescriptor; }
1403 
1404 protected:
1405  // Note: Instruction needs to be a friend here to call cloneImpl.
1406  friend class Instruction;
1407 
1408  CallInst *cloneImpl() const;
1409 
1410 public:
1411  static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1412  ArrayRef<OperandBundleDef> Bundles = None,
1413  const Twine &NameStr = "",
1414  Instruction *InsertBefore = nullptr) {
1415  return Create(cast<FunctionType>(
1416  cast<PointerType>(Func->getType())->getElementType()),
1417  Func, Args, Bundles, NameStr, InsertBefore);
1418  }
1419 
1420  static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1421  const Twine &NameStr,
1422  Instruction *InsertBefore = nullptr) {
1423  return Create(cast<FunctionType>(
1424  cast<PointerType>(Func->getType())->getElementType()),
1425  Func, Args, None, NameStr, InsertBefore);
1426  }
1427 
1428  static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1429  const Twine &NameStr,
1430  Instruction *InsertBefore = nullptr) {
1431  return new (unsigned(Args.size() + 1))
1432  CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1433  }
1434 
1435  static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1436  ArrayRef<OperandBundleDef> Bundles = None,
1437  const Twine &NameStr = "",
1438  Instruction *InsertBefore = nullptr) {
1439  const unsigned TotalOps =
1440  unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1441  const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1442 
1443  return new (TotalOps, DescriptorBytes)
1444  CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1445  }
1446 
1447  static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1449  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1450  const unsigned TotalOps =
1451  unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1452  const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1453 
1454  return new (TotalOps, DescriptorBytes)
1455  CallInst(Func, Args, Bundles, NameStr, InsertAtEnd);
1456  }
1457 
1458  static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1459  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1460  return new (unsigned(Args.size() + 1))
1461  CallInst(Func, Args, None, NameStr, InsertAtEnd);
1462  }
1463 
1464  static CallInst *Create(Value *F, const Twine &NameStr = "",
1465  Instruction *InsertBefore = nullptr) {
1466  return new(1) CallInst(F, NameStr, InsertBefore);
1467  }
1468 
1469  static CallInst *Create(Value *F, const Twine &NameStr,
1470  BasicBlock *InsertAtEnd) {
1471  return new(1) CallInst(F, NameStr, InsertAtEnd);
1472  }
1473 
1474  /// Create a clone of \p CI with a different set of operand bundles and
1475  /// insert it before \p InsertPt.
1476  ///
1477  /// The returned call instruction is identical \p CI in every way except that
1478  /// the operand bundles for the new instruction are set to the operand bundles
1479  /// in \p Bundles.
1480  static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1481  Instruction *InsertPt = nullptr);
1482 
1483  /// Generate the IR for a call to malloc:
1484  /// 1. Compute the malloc call's argument as the specified type's size,
1485  /// possibly multiplied by the array size if the array size is not
1486  /// constant 1.
1487  /// 2. Call malloc with that argument.
1488  /// 3. Bitcast the result of the malloc call to the specified type.
1489  static Instruction *CreateMalloc(Instruction *InsertBefore,
1490  Type *IntPtrTy, Type *AllocTy,
1491  Value *AllocSize, Value *ArraySize = nullptr,
1492  Function* MallocF = nullptr,
1493  const Twine &Name = "");
1494  static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1495  Type *IntPtrTy, Type *AllocTy,
1496  Value *AllocSize, Value *ArraySize = nullptr,
1497  Function* MallocF = nullptr,
1498  const Twine &Name = "");
1499  static Instruction *CreateMalloc(Instruction *InsertBefore,
1500  Type *IntPtrTy, Type *AllocTy,
1501  Value *AllocSize, Value *ArraySize = nullptr,
1502  ArrayRef<OperandBundleDef> Bundles = None,
1503  Function* MallocF = nullptr,
1504  const Twine &Name = "");
1505  static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1506  Type *IntPtrTy, Type *AllocTy,
1507  Value *AllocSize, Value *ArraySize = nullptr,
1508  ArrayRef<OperandBundleDef> Bundles = None,
1509  Function* MallocF = nullptr,
1510  const Twine &Name = "");
1511  /// Generate the IR for a call to the builtin free function.
1512  static Instruction *CreateFree(Value *Source,
1513  Instruction *InsertBefore);
1514  static Instruction *CreateFree(Value *Source,
1515  BasicBlock *InsertAtEnd);
1516  static Instruction *CreateFree(Value *Source,
1518  Instruction *InsertBefore);
1519  static Instruction *CreateFree(Value *Source,
1521  BasicBlock *InsertAtEnd);
1522 
1523  FunctionType *getFunctionType() const { return FTy; }
1524 
1526  mutateType(FTy->getReturnType());
1527  this->FTy = FTy;
1528  }
1529 
1530  // Note that 'musttail' implies 'tail'.
1531  enum TailCallKind { TCK_None = 0, TCK_Tail = 1, TCK_MustTail = 2,
1532  TCK_NoTail = 3 };
1535  }
1536 
1537  bool isTailCall() const {
1538  unsigned Kind = getSubclassDataFromInstruction() & 3;
1539  return Kind == TCK_Tail || Kind == TCK_MustTail;
1540  }
1541 
1542  bool isMustTailCall() const {
1543  return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1544  }
1545 
1546  bool isNoTailCall() const {
1547  return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1548  }
1549 
1550  void setTailCall(bool isTC = true) {
1551  setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1552  unsigned(isTC ? TCK_Tail : TCK_None));
1553  }
1554 
1556  setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1557  unsigned(TCK));
1558  }
1559 
1560  /// Provide fast operand accessors
1562 
1563  /// Return the number of call arguments.
1564  ///
1565  unsigned getNumArgOperands() const {
1566  return getNumOperands() - getNumTotalBundleOperands() - 1;
1567  }
1568 
1569  /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1570  ///
1571  Value *getArgOperand(unsigned i) const {
1572  assert(i < getNumArgOperands() && "Out of bounds!");
1573  return getOperand(i);
1574  }
1575  void setArgOperand(unsigned i, Value *v) {
1576  assert(i < getNumArgOperands() && "Out of bounds!");
1577  setOperand(i, v);
1578  }
1579 
1580  /// Return the iterator pointing to the beginning of the argument list.
1582 
1583  /// Return the iterator pointing to the end of the argument list.
1585  // [ call args ], [ operand bundles ], callee
1586  return op_end() - getNumTotalBundleOperands() - 1;
1587  }
1588 
1589  /// Iteration adapter for range-for loops.
1591  return make_range(arg_begin(), arg_end());
1592  }
1593 
1594  /// Return the iterator pointing to the beginning of the argument list.
1595  const_op_iterator arg_begin() const { return op_begin(); }
1596 
1597  /// Return the iterator pointing to the end of the argument list.
1599  // [ call args ], [ operand bundles ], callee
1600  return op_end() - getNumTotalBundleOperands() - 1;
1601  }
1602 
1603  /// Iteration adapter for range-for loops.
1605  return make_range(arg_begin(), arg_end());
1606  }
1607 
1608  /// Wrappers for getting the \c Use of a call argument.
1609  const Use &getArgOperandUse(unsigned i) const {
1610  assert(i < getNumArgOperands() && "Out of bounds!");
1611  return getOperandUse(i);
1612  }
1613  Use &getArgOperandUse(unsigned i) {
1614  assert(i < getNumArgOperands() && "Out of bounds!");
1615  return getOperandUse(i);
1616  }
1617 
1618  /// If one of the arguments has the 'returned' attribute, return its
1619  /// operand value. Otherwise, return nullptr.
1620  Value *getReturnedArgOperand() const;
1621 
1622  /// getCallingConv/setCallingConv - Get or set the calling convention of this
1623  /// function call.
1625  return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1626  }
1628  auto ID = static_cast<unsigned>(CC);
1629  assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1630  setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1631  (ID << 2));
1632  }
1633 
1634  /// Return the parameter attributes for this call.
1635  ///
1636  AttributeList getAttributes() const { return Attrs; }
1637 
1638  /// Set the parameter attributes for this call.
1639  ///
1641 
1642  /// adds the attribute to the list of attributes.
1643  void addAttribute(unsigned i, Attribute::AttrKind Kind);
1644 
1645  /// adds the attribute to the list of attributes.
1646  void addAttribute(unsigned i, Attribute Attr);
1647 
1648  /// Adds the attribute to the indicated argument
1649  void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
1650 
1651  /// Adds the attribute to the indicated argument
1652  void addParamAttr(unsigned ArgNo, Attribute Attr);
1653 
1654  /// removes the attribute from the list of attributes.
1655  void removeAttribute(unsigned i, Attribute::AttrKind Kind);
1656 
1657  /// removes the attribute from the list of attributes.
1658  void removeAttribute(unsigned i, StringRef Kind);
1659 
1660  /// Removes the attribute from the given argument
1661  void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
1662 
1663  /// Removes the attribute from the given argument
1664  void removeParamAttr(unsigned ArgNo, StringRef Kind);
1665 
1666  /// adds the dereferenceable attribute to the list of attributes.
1667  void addDereferenceableAttr(unsigned i, uint64_t Bytes);
1668 
1669  /// adds the dereferenceable_or_null attribute to the list of
1670  /// attributes.
1671  void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
1672 
1673  /// Determine whether this call has the given attribute.
1674  bool hasFnAttr(Attribute::AttrKind Kind) const {
1675  assert(Kind != Attribute::NoBuiltin &&
1676  "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
1677  return hasFnAttrImpl(Kind);
1678  }
1679 
1680  /// Determine whether this call has the given attribute.
1681  bool hasFnAttr(StringRef Kind) const {
1682  return hasFnAttrImpl(Kind);
1683  }
1684 
1685  /// Determine whether the return value has the given attribute.
1686  bool hasRetAttr(Attribute::AttrKind Kind) const;
1687 
1688  /// Determine whether the argument or parameter has the given attribute.
1689  bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1690 
1691  /// Get the attribute of a given kind at a position.
1692  Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
1693  return getAttributes().getAttribute(i, Kind);
1694  }
1695 
1696  /// Get the attribute of a given kind at a position.
1697  Attribute getAttribute(unsigned i, StringRef Kind) const {
1698  return getAttributes().getAttribute(i, Kind);
1699  }
1700 
1701  /// Get the attribute of a given kind from a given arg
1702  Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1703  assert(ArgNo < getNumArgOperands() && "Out of bounds");
1704  return getAttributes().getParamAttr(ArgNo, Kind);
1705  }
1706 
1707  /// Get the attribute of a given kind from a given arg
1708  Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1709  assert(ArgNo < getNumArgOperands() && "Out of bounds");
1710  return getAttributes().getParamAttr(ArgNo, Kind);
1711  }
1712 
1713  /// Return true if the data operand at index \p i has the attribute \p
1714  /// A.
1715  ///
1716  /// Data operands include call arguments and values used in operand bundles,
1717  /// but does not include the callee operand. This routine dispatches to the
1718  /// underlying AttributeList or the OperandBundleUser as appropriate.
1719  ///
1720  /// The index \p i is interpreted as
1721  ///
1722  /// \p i == Attribute::ReturnIndex -> the return value
1723  /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
1724  /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1725  /// (\p i - 1) in the operand list.
1726  bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
1727 
1728  /// Extract the alignment of the return value.
1729  unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
1730 
1731  /// Extract the alignment for a call or parameter (0=unknown).
1732  unsigned getParamAlignment(unsigned ArgNo) const {
1733  return Attrs.getParamAlignment(ArgNo);
1734  }
1735 
1736  /// Extract the number of dereferenceable bytes for a call or
1737  /// parameter (0=unknown).
1738  uint64_t getDereferenceableBytes(unsigned i) const {
1739  return Attrs.getDereferenceableBytes(i);
1740  }
1741 
1742  /// Extract the number of dereferenceable_or_null bytes for a call or
1743  /// parameter (0=unknown).
1744  uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1745  return Attrs.getDereferenceableOrNullBytes(i);
1746  }
1747 
1748  /// @brief Determine if the return value is marked with NoAlias attribute.
1749  bool returnDoesNotAlias() const {
1750  return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1751  }
1752 
1753  /// Return true if the call should not be treated as a call to a
1754  /// builtin.
1755  bool isNoBuiltin() const {
1756  return hasFnAttrImpl(Attribute::NoBuiltin) &&
1757  !hasFnAttrImpl(Attribute::Builtin);
1758  }
1759 
1760  /// Return true if the call should not be inlined.
1761  bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1762  void setIsNoInline() {
1763  addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1764  }
1765 
1766  /// Return true if the call can return twice
1767  bool canReturnTwice() const {
1768  return hasFnAttr(Attribute::ReturnsTwice);
1769  }
1771  addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1772  }
1773 
1774  /// Determine if the call does not access memory.
1775  bool doesNotAccessMemory() const {
1776  return hasFnAttr(Attribute::ReadNone);
1777  }
1779  addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1780  }
1781 
1782  /// Determine if the call does not access or only reads memory.
1783  bool onlyReadsMemory() const {
1784  return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1785  }
1787  addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1788  }
1789 
1790  /// Determine if the call does not access or only writes memory.
1791  bool doesNotReadMemory() const {
1792  return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1793  }
1795  addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1796  }
1797 
1798  /// @brief Determine if the call can access memmory only using pointers based
1799  /// on its arguments.
1800  bool onlyAccessesArgMemory() const {
1801  return hasFnAttr(Attribute::ArgMemOnly);
1802  }
1804  addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1805  }
1806 
1807  /// Determine if the call cannot return.
1808  bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1810  addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1811  }
1812 
1813  /// Determine if the call cannot unwind.
1814  bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1816  addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1817  }
1818 
1819  /// Determine if the call cannot be duplicated.
1820  bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1822  addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1823  }
1824 
1825  /// Determine if the call is convergent
1826  bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1827  void setConvergent() {
1829  }
1832  }
1833 
1834  /// Determine if the call returns a structure through first
1835  /// pointer argument.
1836  bool hasStructRetAttr() const {
1837  if (getNumArgOperands() == 0)
1838  return false;
1839 
1840  // Be friendly and also check the callee.
1841  return paramHasAttr(0, Attribute::StructRet);
1842  }
1843 
1844  /// Determine if any call argument is an aggregate passed by value.
1845  bool hasByValArgument() const {
1846  return Attrs.hasAttrSomewhere(Attribute::ByVal);
1847  }
1848 
1849  /// Return the function called, or null if this is an
1850  /// indirect function invocation.
1851  ///
1853  return dyn_cast<Function>(Op<-1>());
1854  }
1855 
1856  /// Get a pointer to the function that is invoked by this
1857  /// instruction.
1858  const Value *getCalledValue() const { return Op<-1>(); }
1859  Value *getCalledValue() { return Op<-1>(); }
1860 
1861  /// Set the function called.
1863  setCalledFunction(
1864  cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1865  Fn);
1866  }
1868  this->FTy = FTy;
1869  assert(FTy == cast<FunctionType>(
1870  cast<PointerType>(Fn->getType())->getElementType()));
1871  Op<-1>() = Fn;
1872  }
1873 
1874  /// Check if this call is an inline asm statement.
1875  bool isInlineAsm() const {
1876  return isa<InlineAsm>(Op<-1>());
1877  }
1878 
1879  // Methods for support type inquiry through isa, cast, and dyn_cast:
1880  static bool classof(const Instruction *I) {
1881  return I->getOpcode() == Instruction::Call;
1882  }
1883  static bool classof(const Value *V) {
1884  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1885  }
1886 
1887 private:
1888  template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
1889  if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
1890  return true;
1891 
1892  // Operand bundles override attributes on the called function, but don't
1893  // override attributes directly present on the call instruction.
1894  if (isFnAttrDisallowedByOpBundle(Kind))
1895  return false;
1896 
1897  if (const Function *F = getCalledFunction())
1898  return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
1899  Kind);
1900  return false;
1901  }
1902 
1903  // Shadow Instruction::setInstructionSubclassData with a private forwarding
1904  // method so that subclasses cannot accidentally use it.
1905  void setInstructionSubclassData(unsigned short D) {
1907  }
1908 };
1909 
1910 template <>
1911 struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1912 };
1913 
1914 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1915  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1916  BasicBlock *InsertAtEnd)
1917  : Instruction(
1918  cast<FunctionType>(cast<PointerType>(Func->getType())
1919  ->getElementType())->getReturnType(),
1921  (Args.size() + CountBundleInputs(Bundles) + 1),
1922  unsigned(Args.size() + CountBundleInputs(Bundles) + 1), InsertAtEnd) {
1923  init(Func, Args, Bundles, NameStr);
1924 }
1925 
1926 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1927  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1928  Instruction *InsertBefore)
1931  (Args.size() + CountBundleInputs(Bundles) + 1),
1932  unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1933  InsertBefore) {
1934  init(Ty, Func, Args, Bundles, NameStr);
1935 }
1936 
1937 // Note: if you get compile errors about private methods then
1938 // please update your code to use the high-level operand
1939 // interfaces. See line 943 above.
1941 
1942 //===----------------------------------------------------------------------===//
1943 // SelectInst Class
1944 //===----------------------------------------------------------------------===//
1945 
1946 /// This class represents the LLVM 'select' instruction.
1947 ///
1948 class SelectInst : public Instruction {
1949  SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1950  Instruction *InsertBefore)
1952  &Op<0>(), 3, InsertBefore) {
1953  init(C, S1, S2);
1954  setName(NameStr);
1955  }
1956 
1957  SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1958  BasicBlock *InsertAtEnd)
1960  &Op<0>(), 3, InsertAtEnd) {
1961  init(C, S1, S2);
1962  setName(NameStr);
1963  }
1964 
1965  void init(Value *C, Value *S1, Value *S2) {
1966  assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1967  Op<0>() = C;
1968  Op<1>() = S1;
1969  Op<2>() = S2;
1970  }
1971 
1972 protected:
1973  // Note: Instruction needs to be a friend here to call cloneImpl.
1974  friend class Instruction;
1975 
1976  SelectInst *cloneImpl() const;
1977 
1978 public:
1979  static SelectInst *Create(Value *C, Value *S1, Value *S2,
1980  const Twine &NameStr = "",
1981  Instruction *InsertBefore = nullptr,
1982  Instruction *MDFrom = nullptr) {
1983  SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1984  if (MDFrom)
1985  Sel->copyMetadata(*MDFrom);
1986  return Sel;
1987  }
1988 
1989  static SelectInst *Create(Value *C, Value *S1, Value *S2,
1990  const Twine &NameStr,
1991  BasicBlock *InsertAtEnd) {
1992  return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1993  }
1994 
1995  const Value *getCondition() const { return Op<0>(); }
1996  const Value *getTrueValue() const { return Op<1>(); }
1997  const Value *getFalseValue() const { return Op<2>(); }
1998  Value *getCondition() { return Op<0>(); }
1999  Value *getTrueValue() { return Op<1>(); }
2000  Value *getFalseValue() { return Op<2>(); }
2001 
2002  void setCondition(Value *V) { Op<0>() = V; }
2003  void setTrueValue(Value *V) { Op<1>() = V; }
2004  void setFalseValue(Value *V) { Op<2>() = V; }
2005 
2006  /// Return a string if the specified operands are invalid
2007  /// for a select operation, otherwise return null.
2008  static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
2009 
2010  /// Transparently provide more efficient getOperand methods.
2012 
2014  return static_cast<OtherOps>(Instruction::getOpcode());
2015  }
2016 
2017  // Methods for support type inquiry through isa, cast, and dyn_cast:
2018  static bool classof(const Instruction *I) {
2019  return I->getOpcode() == Instruction::Select;
2020  }
2021  static bool classof(const Value *V) {
2022  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2023  }
2024 };
2025 
2026 template <>
2027 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
2028 };
2029 
2031 
2032 //===----------------------------------------------------------------------===//
2033 // VAArgInst Class
2034 //===----------------------------------------------------------------------===//
2035 
2036 /// This class represents the va_arg llvm instruction, which returns
2037 /// an argument of the specified type given a va_list and increments that list
2038 ///
2039 class VAArgInst : public UnaryInstruction {
2040 protected:
2041  // Note: Instruction needs to be a friend here to call cloneImpl.
2042  friend class Instruction;
2043 
2044  VAArgInst *cloneImpl() const;
2045 
2046 public:
2047  VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
2048  Instruction *InsertBefore = nullptr)
2049  : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
2050  setName(NameStr);
2051  }
2052 
2053  VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
2054  BasicBlock *InsertAtEnd)
2055  : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
2056  setName(NameStr);
2057  }
2058 
2060  const Value *getPointerOperand() const { return getOperand(0); }
2061  static unsigned getPointerOperandIndex() { return 0U; }
2062 
2063  // Methods for support type inquiry through isa, cast, and dyn_cast:
2064  static bool classof(const Instruction *I) {
2065  return I->getOpcode() == VAArg;
2066  }
2067  static bool classof(const Value *V) {
2068  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2069  }
2070 };
2071 
2072 //===----------------------------------------------------------------------===//
2073 // ExtractElementInst Class
2074 //===----------------------------------------------------------------------===//
2075 
2076 /// This instruction extracts a single (scalar)
2077 /// element from a VectorType value
2078 ///
2080  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
2081  Instruction *InsertBefore = nullptr);
2082  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
2083  BasicBlock *InsertAtEnd);
2084 
2085 protected:
2086  // Note: Instruction needs to be a friend here to call cloneImpl.
2087  friend class Instruction;
2088 
2089  ExtractElementInst *cloneImpl() const;
2090 
2091 public:
2092  static ExtractElementInst *Create(Value *Vec, Value *Idx,
2093  const Twine &NameStr = "",
2094  Instruction *InsertBefore = nullptr) {
2095  return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
2096  }
2097 
2098  static ExtractElementInst *Create(Value *Vec, Value *Idx,
2099  const Twine &NameStr,
2100  BasicBlock *InsertAtEnd) {
2101  return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
2102  }
2103 
2104  /// Return true if an extractelement instruction can be
2105  /// formed with the specified operands.
2106  static bool isValidOperands(const Value *Vec, const Value *Idx);
2107 
2108  Value *getVectorOperand() { return Op<0>(); }
2109  Value *getIndexOperand() { return Op<1>(); }
2110  const Value *getVectorOperand() const { return Op<0>(); }
2111  const Value *getIndexOperand() const { return Op<1>(); }
2112 
2114  return cast<VectorType>(getVectorOperand()->getType());
2115  }
2116 
2117  /// Transparently provide more efficient getOperand methods.
2119 
2120  // Methods for support type inquiry through isa, cast, and dyn_cast:
2121  static bool classof(const Instruction *I) {
2122  return I->getOpcode() == Instruction::ExtractElement;
2123  }
2124  static bool classof(const Value *V) {
2125  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2126  }
2127 };
2128 
2129 template <>
2131  public FixedNumOperandTraits<ExtractElementInst, 2> {
2132 };
2133 
2134 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
2135 
2136 //===----------------------------------------------------------------------===//
2137 // InsertElementInst Class
2138 //===----------------------------------------------------------------------===//
2139 
2140 /// This instruction inserts a single (scalar)
2141 /// element into a VectorType value
2142 ///
2144  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
2145  const Twine &NameStr = "",
2146  Instruction *InsertBefore = nullptr);
2147  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
2148  BasicBlock *InsertAtEnd);
2149 
2150 protected:
2151  // Note: Instruction needs to be a friend here to call cloneImpl.
2152  friend class Instruction;
2153 
2154  InsertElementInst *cloneImpl() const;
2155 
2156 public:
2157  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2158  const Twine &NameStr = "",
2159  Instruction *InsertBefore = nullptr) {
2160  return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
2161  }
2162 
2163  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2164  const Twine &NameStr,
2165  BasicBlock *InsertAtEnd) {
2166  return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
2167  }
2168 
2169  /// Return true if an insertelement instruction can be
2170  /// formed with the specified operands.
2171  static bool isValidOperands(const Value *Vec, const Value *NewElt,
2172  const Value *Idx);
2173 
2174  /// Overload to return most specific vector type.
2175  ///
2176  VectorType *getType() const {
2177  return cast<VectorType>(Instruction::getType());
2178  }
2179 
2180  /// Transparently provide more efficient getOperand methods.
2182 
2183  // Methods for support type inquiry through isa, cast, and dyn_cast:
2184  static bool classof(const Instruction *I) {
2185  return I->getOpcode() == Instruction::InsertElement;
2186  }
2187  static bool classof(const Value *V) {
2188  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2189  }
2190 };
2191 
2192 template <>
2194  public FixedNumOperandTraits<InsertElementInst, 3> {
2195 };
2196 
2197 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2198 
2199 //===----------------------------------------------------------------------===//
2200 // ShuffleVectorInst Class
2201 //===----------------------------------------------------------------------===//
2202 
2203 /// This instruction constructs a fixed permutation of two
2204 /// input vectors.
2205 ///
2207 protected:
2208  // Note: Instruction needs to be a friend here to call cloneImpl.
2209  friend class Instruction;
2210 
2211  ShuffleVectorInst *cloneImpl() const;
2212 
2213 public:
2215  const Twine &NameStr = "",
2216  Instruction *InsertBefor = nullptr);
2218  const Twine &NameStr, BasicBlock *InsertAtEnd);
2219 
2220  // allocate space for exactly three operands
2221  void *operator new(size_t s) {
2222  return User::operator new(s, 3);
2223  }
2224 
2225  /// Return true if a shufflevector instruction can be
2226  /// formed with the specified operands.
2227  static bool isValidOperands(const Value *V1, const Value *V2,
2228  const Value *Mask);
2229 
2230  /// Overload to return most specific vector type.
2231  ///
2232  VectorType *getType() const {
2233  return cast<VectorType>(Instruction::getType());
2234  }
2235 
2236  /// Transparently provide more efficient getOperand methods.
2238 
2239  Constant *getMask() const {
2240  return cast<Constant>(getOperand(2));
2241  }
2242 
2243  /// Return the shuffle mask value for the specified element of the mask.
2244  /// Return -1 if the element is undef.
2245  static int getMaskValue(Constant *Mask, unsigned Elt);
2246 
2247  /// Return the shuffle mask value of this instruction for the given element
2248  /// index. Return -1 if the element is undef.
2249  int getMaskValue(unsigned Elt) const {
2250  return getMaskValue(getMask(), Elt);
2251  }
2252 
2253  /// Convert the input shuffle mask operand to a vector of integers. Undefined
2254  /// elements of the mask are returned as -1.
2255  static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
2256 
2257  /// Return the mask for this instruction as a vector of integers. Undefined
2258  /// elements of the mask are returned as -1.
2259  void getShuffleMask(SmallVectorImpl<int> &Result) const {
2260  return getShuffleMask(getMask(), Result);
2261  }
2262 
2265  getShuffleMask(Mask);
2266  return Mask;
2267  }
2268 
2269  /// Change values in a shuffle permute mask assuming the two vector operands
2270  /// of length InVecNumElts have swapped position.
2272  unsigned InVecNumElts) {
2273  for (int &Idx : Mask) {
2274  if (Idx == -1)
2275  continue;
2276  Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2277  assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2278  "shufflevector mask index out of range");
2279  }
2280  }
2281 
2282  // Methods for support type inquiry through isa, cast, and dyn_cast:
2283  static bool classof(const Instruction *I) {
2284  return I->getOpcode() == Instruction::ShuffleVector;
2285  }
2286  static bool classof(const Value *V) {
2287  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2288  }
2289 };
2290 
2291 template <>
2293  public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2294 };
2295 
2296 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2297 
2298 //===----------------------------------------------------------------------===//
2299 // ExtractValueInst Class
2300 //===----------------------------------------------------------------------===//
2301 
2302 /// This instruction extracts a struct member or array
2303 /// element value from an aggregate value.
2304 ///
2306  SmallVector<unsigned, 4> Indices;
2307 
2308  ExtractValueInst(const ExtractValueInst &EVI);
2309 
2310  /// Constructors - Create a extractvalue instruction with a base aggregate
2311  /// value and a list of indices. The first ctor can optionally insert before
2312  /// an existing instruction, the second appends the new instruction to the
2313  /// specified BasicBlock.
2314  inline ExtractValueInst(Value *Agg,
2315  ArrayRef<unsigned> Idxs,
2316  const Twine &NameStr,
2317  Instruction *InsertBefore);
2318  inline ExtractValueInst(Value *Agg,
2319  ArrayRef<unsigned> Idxs,
2320  const Twine &NameStr, BasicBlock *InsertAtEnd);
2321 
2322  void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2323 
2324 protected:
2325  // Note: Instruction needs to be a friend here to call cloneImpl.
2326  friend class Instruction;
2327 
2328  ExtractValueInst *cloneImpl() const;
2329 
2330 public:
2332  ArrayRef<unsigned> Idxs,
2333  const Twine &NameStr = "",
2334  Instruction *InsertBefore = nullptr) {
2335  return new
2336  ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2337  }
2338 
2340  ArrayRef<unsigned> Idxs,
2341  const Twine &NameStr,
2342  BasicBlock *InsertAtEnd) {
2343  return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2344  }
2345 
2346  /// Returns the type of the element that would be extracted
2347  /// with an extractvalue instruction with the specified parameters.
2348  ///
2349  /// Null is returned if the indices are invalid for the specified type.
2350  static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2351 
2352  using idx_iterator = const unsigned*;
2353 
2354  inline idx_iterator idx_begin() const { return Indices.begin(); }
2355  inline idx_iterator idx_end() const { return Indices.end(); }
2357  return make_range(idx_begin(), idx_end());
2358  }
2359 
2361  return getOperand(0);
2362  }
2363  const Value *getAggregateOperand() const {
2364  return getOperand(0);
2365  }
2366  static unsigned getAggregateOperandIndex() {
2367  return 0U; // get index for modifying correct operand
2368  }
2369 
2371  return Indices;
2372  }
2373 
2374  unsigned getNumIndices() const {
2375  return (unsigned)Indices.size();
2376  }
2377 
2378  bool hasIndices() const {
2379  return true;
2380  }
2381 
2382  // Methods for support type inquiry through isa, cast, and dyn_cast:
2383  static bool classof(const Instruction *I) {
2384  return I->getOpcode() == Instruction::ExtractValue;
2385  }
2386  static bool classof(const Value *V) {
2387  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2388  }
2389 };
2390 
2391 ExtractValueInst::ExtractValueInst(Value *Agg,
2392  ArrayRef<unsigned> Idxs,
2393  const Twine &NameStr,
2394  Instruction *InsertBefore)
2395  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2396  ExtractValue, Agg, InsertBefore) {
2397  init(Idxs, NameStr);
2398 }
2399 
2400 ExtractValueInst::ExtractValueInst(Value *Agg,
2401  ArrayRef<unsigned> Idxs,
2402  const Twine &NameStr,
2403  BasicBlock *InsertAtEnd)
2404  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2405  ExtractValue, Agg, InsertAtEnd) {
2406  init(Idxs, NameStr);
2407 }
2408 
2409 //===----------------------------------------------------------------------===//
2410 // InsertValueInst Class
2411 //===----------------------------------------------------------------------===//
2412 
2413 /// This instruction inserts a struct field of array element
2414 /// value into an aggregate value.
2415 ///
2417  SmallVector<unsigned, 4> Indices;
2418 
2419  InsertValueInst(const InsertValueInst &IVI);
2420 
2421  /// Constructors - Create a insertvalue instruction with a base aggregate
2422  /// value, a value to insert, and a list of indices. The first ctor can
2423  /// optionally insert before an existing instruction, the second appends
2424  /// the new instruction to the specified BasicBlock.
2425  inline InsertValueInst(Value *Agg, Value *Val,
2426  ArrayRef<unsigned> Idxs,
2427  const Twine &NameStr,
2428  Instruction *InsertBefore);
2429  inline InsertValueInst(Value *Agg, Value *Val,
2430  ArrayRef<unsigned> Idxs,
2431  const Twine &NameStr, BasicBlock *InsertAtEnd);
2432 
2433  /// Constructors - These two constructors are convenience methods because one
2434  /// and two index insertvalue instructions are so common.
2435  InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2436  const Twine &NameStr = "",
2437  Instruction *InsertBefore = nullptr);
2438  InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2439  BasicBlock *InsertAtEnd);
2440 
2441  void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2442  const Twine &NameStr);
2443 
2444 protected:
2445  // Note: Instruction needs to be a friend here to call cloneImpl.
2446  friend class Instruction;
2447 
2448  InsertValueInst *cloneImpl() const;
2449 
2450 public:
2451  // allocate space for exactly two operands
2452  void *operator new(size_t s) {
2453  return User::operator new(s, 2);
2454  }
2455 
2456  static InsertValueInst *Create(Value *Agg, Value *Val,
2457  ArrayRef<unsigned> Idxs,
2458  const Twine &NameStr = "",
2459  Instruction *InsertBefore = nullptr) {
2460  return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2461  }
2462 
2463  static InsertValueInst *Create(Value *Agg, Value *Val,
2464  ArrayRef<unsigned> Idxs,
2465  const Twine &NameStr,
2466  BasicBlock *InsertAtEnd) {
2467  return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2468  }
2469 
2470  /// Transparently provide more efficient getOperand methods.
2472 
2473  using idx_iterator = const unsigned*;
2474 
2475  inline idx_iterator idx_begin() const { return Indices.begin(); }
2476  inline idx_iterator idx_end() const { return Indices.end(); }
2478  return make_range(idx_begin(), idx_end());
2479  }
2480 
2482  return getOperand(0);
2483  }
2484  const Value *getAggregateOperand() const {
2485  return getOperand(0);
2486  }
2487  static unsigned getAggregateOperandIndex() {
2488  return 0U; // get index for modifying correct operand
2489  }
2490 
2492  return getOperand(1);
2493  }
2495  return getOperand(1);
2496  }
2497  static unsigned getInsertedValueOperandIndex() {
2498  return 1U; // get index for modifying correct operand
2499  }
2500 
2502  return Indices;
2503  }
2504 
2505  unsigned getNumIndices() const {
2506  return (unsigned)Indices.size();
2507  }
2508 
2509  bool hasIndices() const {
2510  return true;
2511  }
2512 
2513  // Methods for support type inquiry through isa, cast, and dyn_cast:
2514  static bool classof(const Instruction *I) {
2515  return I->getOpcode() == Instruction::InsertValue;
2516  }
2517  static bool classof(const Value *V) {
2518  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2519  }
2520 };
2521 
2522 template <>
2524  public FixedNumOperandTraits<InsertValueInst, 2> {
2525 };
2526 
2527 InsertValueInst::InsertValueInst(Value *Agg,
2528  Value *Val,
2529  ArrayRef<unsigned> Idxs,
2530  const Twine &NameStr,
2531  Instruction *InsertBefore)
2532  : Instruction(Agg->getType(), InsertValue,
2534  2, InsertBefore) {
2535  init(Agg, Val, Idxs, NameStr);
2536 }
2537 
2538 InsertValueInst::InsertValueInst(Value *Agg,
2539  Value *Val,
2540  ArrayRef<unsigned> Idxs,
2541  const Twine &NameStr,
2542  BasicBlock *InsertAtEnd)
2543  : Instruction(Agg->getType(), InsertValue,
2545  2, InsertAtEnd) {
2546  init(Agg, Val, Idxs, NameStr);
2547 }
2548 
2550 
2551 //===----------------------------------------------------------------------===//
2552 // PHINode Class
2553 //===----------------------------------------------------------------------===//
2554 
2555 // PHINode - The PHINode class is used to represent the magical mystical PHI
2556 // node, that can not exist in nature, but can be synthesized in a computer
2557 // scientist's overactive imagination.
2558 //
2559 class PHINode : public Instruction {
2560  /// The number of operands actually allocated. NumOperands is
2561  /// the number actually in use.
2562  unsigned ReservedSpace;
2563 
2564  PHINode(const PHINode &PN);
2565 
2566  explicit PHINode(Type *Ty, unsigned NumReservedValues,
2567  const Twine &NameStr = "",
2568  Instruction *InsertBefore = nullptr)
2569  : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2570  ReservedSpace(NumReservedValues) {
2571  setName(NameStr);
2572  allocHungoffUses(ReservedSpace);
2573  }
2574 
2575  PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2576  BasicBlock *InsertAtEnd)
2577  : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2578  ReservedSpace(NumReservedValues) {
2579  setName(NameStr);
2580  allocHungoffUses(ReservedSpace);
2581  }
2582 
2583 protected:
2584  // Note: Instruction needs to be a friend here to call cloneImpl.
2585  friend class Instruction;
2586 
2587  PHINode *cloneImpl() const;
2588 
2589  // allocHungoffUses - this is more complicated than the generic
2590  // User::allocHungoffUses, because we have to allocate Uses for the incoming
2591  // values and pointers to the incoming blocks, all in one allocation.
2592  void allocHungoffUses(unsigned N) {
2593  User::allocHungoffUses(N, /* IsPhi */ true);
2594  }
2595 
2596 public:
2597  /// Constructors - NumReservedValues is a hint for the number of incoming
2598  /// edges that this phi node will have (use 0 if you really have no idea).
2599  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2600  const Twine &NameStr = "",
2601  Instruction *InsertBefore = nullptr) {
2602  return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2603  }
2604 
2605  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2606  const Twine &NameStr, BasicBlock *InsertAtEnd) {
2607  return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2608  }
2609 
2610  /// Provide fast operand accessors
2612 
2613  // Block iterator interface. This provides access to the list of incoming
2614  // basic blocks, which parallels the list of incoming values.
2615 
2618 
2620  Use::UserRef *ref =
2621  reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2622  return reinterpret_cast<block_iterator>(ref + 1);
2623  }
2624 
2626  const Use::UserRef *ref =
2627  reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2628  return reinterpret_cast<const_block_iterator>(ref + 1);
2629  }
2630 
2632  return block_begin() + getNumOperands();
2633  }
2634 
2636  return block_begin() + getNumOperands();
2637  }
2638 
2640  return make_range(block_begin(), block_end());
2641  }
2642 
2644  return make_range(block_begin(), block_end());
2645  }
2646 
2648 
2650 
2651  /// Return the number of incoming edges
2652  ///
2653  unsigned getNumIncomingValues() const { return getNumOperands(); }
2654 
2655  /// Return incoming value number x
2656  ///
2657  Value *getIncomingValue(unsigned i) const {
2658  return getOperand(i);
2659  }
2660  void setIncomingValue(unsigned i, Value *V) {
2661  assert(V && "PHI node got a null value!");
2662  assert(getType() == V->getType() &&
2663  "All operands to PHI node must be the same type as the PHI node!");
2664  setOperand(i, V);
2665  }
2666 
2667  static unsigned getOperandNumForIncomingValue(unsigned i) {
2668  return i;
2669  }
2670 
2671  static unsigned getIncomingValueNumForOperand(unsigned i) {
2672  return i;
2673  }
2674 
2675  /// Return incoming basic block number @p i.
2676  ///
2677  BasicBlock *getIncomingBlock(unsigned i) const {
2678  return block_begin()[i];
2679  }
2680 
2681  /// Return incoming basic block corresponding
2682  /// to an operand of the PHI.
2683  ///
2684  BasicBlock *getIncomingBlock(const Use &U) const {
2685  assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2686  return getIncomingBlock(unsigned(&U - op_begin()));
2687  }
2688 
2689  /// Return incoming basic block corresponding
2690  /// to value use iterator.
2691  ///
2693  return getIncomingBlock(I.getUse());
2694  }
2695 
2696  void setIncomingBlock(unsigned i, BasicBlock *BB) {
2697  assert(BB && "PHI node got a null basic block!");
2698  block_begin()[i] = BB;
2699  }
2700 
2701  /// Add an incoming value to the end of the PHI list
2702  ///
2703  void addIncoming(Value *V, BasicBlock *BB) {
2704  if (getNumOperands() == ReservedSpace)
2705  growOperands(); // Get more space!
2706  // Initialize some new operands.
2708  setIncomingValue(getNumOperands() - 1, V);
2709  setIncomingBlock(getNumOperands() - 1, BB);
2710  }
2711 
2712  /// Remove an incoming value. This is useful if a
2713  /// predecessor basic block is deleted. The value removed is returned.
2714  ///
2715  /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2716  /// is true), the PHI node is destroyed and any uses of it are replaced with
2717  /// dummy values. The only time there should be zero incoming values to a PHI
2718  /// node is when the block is dead, so this strategy is sound.
2719  ///
2720  Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2721 
2722  Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2723  int Idx = getBasicBlockIndex(BB);
2724  assert(Idx >= 0 && "Invalid basic block argument to remove!");
2725  return removeIncomingValue(Idx, DeletePHIIfEmpty);
2726  }
2727 
2728  /// Return the first index of the specified basic
2729  /// block in the value list for this PHI. Returns -1 if no instance.
2730  ///
2731  int getBasicBlockIndex(const BasicBlock *BB) const {
2732  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2733  if (block_begin()[i] == BB)
2734  return i;
2735  return -1;
2736  }
2737 
2739  int Idx = getBasicBlockIndex(BB);
2740  assert(Idx >= 0 && "Invalid basic block argument!");
2741  return getIncomingValue(Idx);
2742  }
2743 
2744  /// If the specified PHI node always merges together the
2745  /// same value, return the value, otherwise return null.
2746  Value *hasConstantValue() const;
2747 
2748  /// Whether the specified PHI node always merges
2749  /// together the same value, assuming undefs are equal to a unique
2750  /// non-undef value.
2751  bool hasConstantOrUndefValue() const;
2752 
2753  /// Methods for support type inquiry through isa, cast, and dyn_cast:
2754  static bool classof(const Instruction *I) {
2755  return I->getOpcode() == Instruction::PHI;
2756  }
2757  static bool classof(const Value *V) {
2758  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2759  }
2760 
2761 private:
2762  void growOperands();
2763 };
2764 
2765 template <>
2767 };
2768 
2770 
2771 //===----------------------------------------------------------------------===//
2772 // LandingPadInst Class
2773 //===----------------------------------------------------------------------===//
2774 
2775 //===---------------------------------------------------------------------------
2776 /// The landingpad instruction holds all of the information
2777 /// necessary to generate correct exception handling. The landingpad instruction
2778 /// cannot be moved from the top of a landing pad block, which itself is
2779 /// accessible only from the 'unwind' edge of an invoke. This uses the
2780 /// SubclassData field in Value to store whether or not the landingpad is a
2781 /// cleanup.
2782 ///
2783 class LandingPadInst : public Instruction {
2784  /// The number of operands actually allocated. NumOperands is
2785  /// the number actually in use.
2786  unsigned ReservedSpace;
2787 
2788  LandingPadInst(const LandingPadInst &LP);
2789 
2790 public:
2792 
2793 private:
2794  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2795  const Twine &NameStr, Instruction *InsertBefore);
2796  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2797  const Twine &NameStr, BasicBlock *InsertAtEnd);
2798 
2799  // Allocate space for exactly zero operands.
2800  void *operator new(size_t s) {
2801  return User::operator new(s);
2802  }
2803 
2804  void growOperands(unsigned Size);
2805  void init(unsigned NumReservedValues, const Twine &NameStr);
2806 
2807 protected:
2808  // Note: Instruction needs to be a friend here to call cloneImpl.
2809  friend class Instruction;
2810 
2811  LandingPadInst *cloneImpl() const;
2812 
2813 public:
2814  /// Constructors - NumReservedClauses is a hint for the number of incoming
2815  /// clauses that this landingpad will have (use 0 if you really have no idea).
2816  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2817  const Twine &NameStr = "",
2818  Instruction *InsertBefore = nullptr);
2819  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2820  const Twine &NameStr, BasicBlock *InsertAtEnd);
2821 
2822  /// Provide fast operand accessors
2824 
2825  /// Return 'true' if this landingpad instruction is a
2826  /// cleanup. I.e., it should be run when unwinding even if its landing pad
2827  /// doesn't catch the exception.
2828  bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2829 
2830  /// Indicate that this landingpad instruction is a cleanup.
2831  void setCleanup(bool V) {
2832  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2833  (V ? 1 : 0));
2834  }
2835 
2836  /// Add a catch or filter clause to the landing pad.
2837  void addClause(Constant *ClauseVal);
2838 
2839  /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2840  /// determine what type of clause this is.
2841  Constant *getClause(unsigned Idx) const {
2842  return cast<Constant>(getOperandList()[Idx]);
2843  }
2844 
2845  /// Return 'true' if the clause and index Idx is a catch clause.
2846  bool isCatch(unsigned Idx) const {
2847  return !isa<ArrayType>(getOperandList()[Idx]->getType());
2848  }
2849 
2850  /// Return 'true' if the clause and index Idx is a filter clause.
2851  bool isFilter(unsigned Idx) const {
2852  return isa<ArrayType>(getOperandList()[Idx]->getType());
2853  }
2854 
2855  /// Get the number of clauses for this landing pad.
2856  unsigned getNumClauses() const { return getNumOperands(); }
2857 
2858  /// Grow the size of the operand list to accommodate the new
2859  /// number of clauses.
2860  void reserveClauses(unsigned Size) { growOperands(Size); }
2861 
2862  // Methods for support type inquiry through isa, cast, and dyn_cast:
2863  static bool classof(const Instruction *I) {
2864  return I->getOpcode() == Instruction::LandingPad;
2865  }
2866  static bool classof(const Value *V) {
2867  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2868  }
2869 };
2870 
2871 template <>
2873 };
2874 
2876 
2877 //===----------------------------------------------------------------------===//
2878 // ReturnInst Class
2879 //===----------------------------------------------------------------------===//
2880 
2881 //===---------------------------------------------------------------------------
2882 /// Return a value (possibly void), from a function. Execution
2883 /// does not continue in this function any longer.
2884 ///
2885 class ReturnInst : public TerminatorInst {
2886  ReturnInst(const ReturnInst &RI);
2887 
2888 private:
2889  // ReturnInst constructors:
2890  // ReturnInst() - 'ret void' instruction
2891  // ReturnInst( null) - 'ret void' instruction
2892  // ReturnInst(Value* X) - 'ret X' instruction
2893  // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2894  // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2895  // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2896  // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2897  //
2898  // NOTE: If the Value* passed is of type void then the constructor behaves as
2899  // if it was passed NULL.
2900  explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2901  Instruction *InsertBefore = nullptr);
2902  ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2903  explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2904 
2905 protected:
2906  // Note: Instruction needs to be a friend here to call cloneImpl.
2907  friend class Instruction;
2908 
2909  ReturnInst *cloneImpl() const;
2910 
2911 public:
2912  static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2913  Instruction *InsertBefore = nullptr) {
2914  return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2915  }
2916 
2917  static ReturnInst* Create(LLVMContext &C, Value *retVal,
2918  BasicBlock *InsertAtEnd) {
2919  return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2920  }
2921 
2922  static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2923  return new(0) ReturnInst(C, InsertAtEnd);
2924  }
2925 
2926  /// Provide fast operand accessors
2928 
2929  /// Convenience accessor. Returns null if there is no return value.
2931  return getNumOperands() != 0 ? getOperand(0) : nullptr;
2932  }
2933 
2934  unsigned getNumSuccessors() const { return 0; }
2935 
2936  // Methods for support type inquiry through isa, cast, and dyn_cast:
2937  static bool classof(const Instruction *I) {
2938  return (I->getOpcode() == Instruction::Ret);
2939  }
2940  static bool classof(const Value *V) {
2941  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2942  }
2943 
2944 private:
2945  friend TerminatorInst;
2946 
2947  BasicBlock *getSuccessor(unsigned idx) const {
2948  llvm_unreachable("ReturnInst has no successors!");
2949  }
2950 
2951  void setSuccessor(unsigned idx, BasicBlock *B) {
2952  llvm_unreachable("ReturnInst has no successors!");
2953  }
2954 };
2955 
2956 template <>
2957 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2958 };
2959 
2961 
2962 //===----------------------------------------------------------------------===//
2963 // BranchInst Class
2964 //===----------------------------------------------------------------------===//
2965 
2966 //===---------------------------------------------------------------------------
2967 /// Conditional or Unconditional Branch instruction.
2968 ///
2969 class BranchInst : public TerminatorInst {
2970  /// Ops list - Branches are strange. The operands are ordered:
2971  /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2972  /// they don't have to check for cond/uncond branchness. These are mostly
2973  /// accessed relative from op_end().
2974  BranchInst(const BranchInst &BI);
2975  // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2976  // BranchInst(BB *B) - 'br B'
2977  // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2978  // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2979  // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2980  // BranchInst(BB* B, BB *I) - 'br B' insert at end
2981  // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2982  explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2983  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2984  Instruction *InsertBefore = nullptr);
2985  BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2986  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2987  BasicBlock *InsertAtEnd);
2988 
2989  void AssertOK();
2990 
2991 protected:
2992  // Note: Instruction needs to be a friend here to call cloneImpl.
2993  friend class Instruction;
2994 
2995  BranchInst *cloneImpl() const;
2996 
2997 public:
2998  static BranchInst *Create(BasicBlock *IfTrue,
2999  Instruction *InsertBefore = nullptr) {
3000  return new(1) BranchInst(IfTrue, InsertBefore);
3001  }
3002 
3003  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3004  Value *Cond, Instruction *InsertBefore = nullptr) {
3005  return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3006  }
3007 
3008  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3009  return new(1) BranchInst(IfTrue, InsertAtEnd);
3010  }
3011 
3012  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3013  Value *Cond, BasicBlock *InsertAtEnd) {
3014  return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3015  }
3016 
3017  /// Transparently provide more efficient getOperand methods.
3019 
3020  bool isUnconditional() const { return getNumOperands() == 1; }
3021  bool isConditional() const { return getNumOperands() == 3; }
3022 
3023  Value *getCondition() const {
3024  assert(isConditional() && "Cannot get condition of an uncond branch!");
3025  return Op<-3>();
3026  }
3027 
3028  void setCondition(Value *V) {
3029  assert(isConditional() && "Cannot set condition of unconditional branch!");
3030  Op<-3>() = V;
3031  }
3032 
3033  unsigned getNumSuccessors() const { return 1+isConditional(); }
3034 
3035  BasicBlock *getSuccessor(unsigned i) const {
3036  assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3037  return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3038  }
3039 
3040  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3041  assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3042  *(&Op<-1>() - idx) = NewSucc;
3043  }
3044 
3045  /// Swap the successors of this branch instruction.
3046  ///
3047  /// Swaps the successors of the branch instruction. This also swaps any
3048  /// branch weight metadata associated with the instruction so that it
3049  /// continues to map correctly to each operand.
3050  void swapSuccessors();
3051 
3052  // Methods for support type inquiry through isa, cast, and dyn_cast:
3053  static bool classof(const Instruction *I) {
3054  return (I->getOpcode() == Instruction::Br);
3055  }
3056  static bool classof(const Value *V) {
3057  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3058  }
3059 };
3060 
3061 template <>
3062 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3063 };
3064 
3066 
3067 //===----------------------------------------------------------------------===//
3068 // SwitchInst Class
3069 //===----------------------------------------------------------------------===//
3070 
3071 //===---------------------------------------------------------------------------
3072 /// Multiway switch
3073 ///
3074 class SwitchInst : public TerminatorInst {
3075  unsigned ReservedSpace;
3076 
3077  // Operand[0] = Value to switch on
3078  // Operand[1] = Default basic block destination
3079  // Operand[2n ] = Value to match
3080  // Operand[2n+1] = BasicBlock to go to on match
3081  SwitchInst(const SwitchInst &SI);
3082 
3083  /// Create a new switch instruction, specifying a value to switch on and a
3084  /// default destination. The number of additional cases can be specified here
3085  /// to make memory allocation more efficient. This constructor can also
3086  /// auto-insert before another instruction.
3087  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3088  Instruction *InsertBefore);
3089 
3090  /// Create a new switch instruction, specifying a value to switch on and a
3091  /// default destination. The number of additional cases can be specified here
3092  /// to make memory allocation more efficient. This constructor also
3093  /// auto-inserts at the end of the specified BasicBlock.
3094  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3095  BasicBlock *InsertAtEnd);
3096 
3097  // allocate space for exactly zero operands
3098  void *operator new(size_t s) {
3099  return User::operator new(s);
3100  }
3101 
3102  void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3103  void growOperands();
3104 
3105 protected:
3106  // Note: Instruction needs to be a friend here to call cloneImpl.
3107  friend class Instruction;
3108 
3109  SwitchInst *cloneImpl() const;
3110 
3111 public:
3112  // -2
3113  static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3114 
3115  template <typename CaseHandleT> class CaseIteratorImpl;
3116 
3117  /// A handle to a particular switch case. It exposes a convenient interface
3118  /// to both the case value and the successor block.
3119  ///
3120  /// We define this as a template and instantiate it to form both a const and
3121  /// non-const handle.
3122  template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3124  // Directly befriend both const and non-const iterators.
3125  friend class SwitchInst::CaseIteratorImpl<
3126  CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3127 
3128  protected:
3129  // Expose the switch type we're parameterized with to the iterator.
3130  using SwitchInstType = SwitchInstT;
3131 
3132  SwitchInstT *SI;
3134 
3135  CaseHandleImpl() = default;
3136  CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3137 
3138  public:
3139  /// Resolves case value for current case.
3140  ConstantIntT *getCaseValue() const {
3141  assert((unsigned)Index < SI->getNumCases() &&
3142  "Index out the number of cases.");
3143  return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3144  }
3145 
3146  /// Resolves successor for current case.
3147  BasicBlockT *getCaseSuccessor() const {
3148  assert(((unsigned)Index < SI->getNumCases() ||
3149  (unsigned)Index == DefaultPseudoIndex) &&
3150  "Index out the number of cases.");
3151  return SI->getSuccessor(getSuccessorIndex());
3152  }
3153 
3154  /// Returns number of current case.
3155  unsigned getCaseIndex() const { return Index; }
3156 
3157  /// Returns TerminatorInst's successor index for current case successor.
3158  unsigned getSuccessorIndex() const {
3159  assert(((unsigned)Index == DefaultPseudoIndex ||
3160  (unsigned)Index < SI->getNumCases()) &&
3161  "Index out the number of cases.");
3162  return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3163  }
3164 
3165  bool operator==(const CaseHandleImpl &RHS) const {
3166  assert(SI == RHS.SI && "Incompatible operators.");
3167  return Index == RHS.Index;
3168  }
3169  };
3170 
3171  using ConstCaseHandle =
3173 
3175  : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3177 
3178  public:
3179  CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3180 
3181  /// Sets the new value for current case.
3183  assert((unsigned)Index < SI->getNumCases() &&
3184  "Index out the number of cases.");
3185  SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3186  }
3187 
3188  /// Sets the new successor for current case.
3190  SI->setSuccessor(getSuccessorIndex(), S);
3191  }
3192  };
3193 
3194  template <typename CaseHandleT>
3195  class CaseIteratorImpl
3196  : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3197  std::random_access_iterator_tag,
3198  CaseHandleT> {
3199  using SwitchInstT = typename CaseHandleT::SwitchInstType;
3200 
3201  CaseHandleT Case;
3202 
3203  public:
3204  /// Default constructed iterator is in an invalid state until assigned to
3205  /// a case for a particular switch.
3206  CaseIteratorImpl() = default;
3207 
3208  /// Initializes case iterator for given SwitchInst and for given
3209  /// case number.
3210  CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3211 
3212  /// Initializes case iterator for given SwitchInst and for given
3213  /// TerminatorInst's successor index.
3214  static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3215  unsigned SuccessorIndex) {
3216  assert(SuccessorIndex < SI->getNumSuccessors() &&
3217  "Successor index # out of range!");
3218  return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3219  : CaseIteratorImpl(SI, DefaultPseudoIndex);
3220  }
3221 
3222  /// Support converting to the const variant. This will be a no-op for const
3223  /// variant.
3225  return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3226  }
3227 
3229  // Check index correctness after addition.
3230  // Note: Index == getNumCases() means end().
3231  assert(Case.Index + N >= 0 &&
3232  (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3233  "Case.Index out the number of cases.");
3234  Case.Index += N;
3235  return *this;
3236  }
3238  // Check index correctness after subtraction.
3239  // Note: Case.Index == getNumCases() means end().
3240  assert(Case.Index - N >= 0 &&
3241  (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3242  "Case.Index out the number of cases.");
3243  Case.Index -= N;
3244  return *this;
3245  }
3247  assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3248  return Case.Index - RHS.Case.Index;
3249  }
3250  bool operator==(const CaseIteratorImpl &RHS) const {
3251  return Case == RHS.Case;
3252  }
3253  bool operator<(const CaseIteratorImpl &RHS) const {
3254  assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3255  return Case.Index < RHS.Case.Index;
3256  }
3257  CaseHandleT &operator*() { return Case; }
3258  const CaseHandleT &operator*() const { return Case; }
3259  };
3260 
3263 
3264  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3265  unsigned NumCases,
3266  Instruction *InsertBefore = nullptr) {
3267  return new SwitchInst(Value, Default, NumCases, InsertBefore);
3268  }
3269 
3270  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3271  unsigned NumCases, BasicBlock *InsertAtEnd) {
3272  return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3273  }
3274 
3275  /// Provide fast operand accessors
3277 
3278  // Accessor Methods for Switch stmt
3279  Value *getCondition() const { return getOperand(0); }
3280  void setCondition(Value *V) { setOperand(0, V); }
3281 
3283  return cast<BasicBlock>(getOperand(1));
3284  }
3285 
3286  void setDefaultDest(BasicBlock *DefaultCase) {
3287  setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3288  }
3289 
3290  /// Return the number of 'cases' in this switch instruction, excluding the
3291  /// default case.
3292  unsigned getNumCases() const {
3293  return getNumOperands()/2 - 1;
3294  }
3295 
3296  /// Returns a read/write iterator that points to the first case in the
3297  /// SwitchInst.
3299  return CaseIt(this, 0);
3300  }
3301 
3302  /// Returns a read-only iterator that points to the first case in the
3303  /// SwitchInst.
3305  return ConstCaseIt(this, 0);
3306  }
3307 
3308  /// Returns a read/write iterator that points one past the last in the
3309  /// SwitchInst.
3311  return CaseIt(this, getNumCases());
3312  }
3313 
3314  /// Returns a read-only iterator that points one past the last in the
3315  /// SwitchInst.
3317  return ConstCaseIt(this, getNumCases());
3318  }
3319 
3320  /// Iteration adapter for range-for loops.
3322  return make_range(case_begin(), case_end());
3323  }
3324 
3325  /// Constant iteration adapter for range-for loops.
3327  return make_range(case_begin(), case_end());
3328  }
3329 
3330  /// Returns an iterator that points to the default case.
3331  /// Note: this iterator allows to resolve successor only. Attempt
3332  /// to resolve case value causes an assertion.
3333  /// Also note, that increment and decrement also causes an assertion and
3334  /// makes iterator invalid.
3336  return CaseIt(this, DefaultPseudoIndex);
3337  }
3339  return ConstCaseIt(this, DefaultPseudoIndex);
3340  }
3341 
3342  /// Search all of the case values for the specified constant. If it is
3343  /// explicitly handled, return the case iterator of it, otherwise return
3344  /// default case iterator to indicate that it is handled by the default
3345  /// handler.
3348  cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3349  if (I != case_end())
3350  return I;
3351 
3352  return case_default();
3353  }
3355  ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3356  return Case.getCaseValue() == C;
3357  });
3358  if (I != case_end())
3359  return I;
3360 
3361  return case_default();
3362  }
3363 
3364  /// Finds the unique case value for a given successor. Returns null if the
3365  /// successor is not found, not unique, or is the default case.
3367  if (BB == getDefaultDest())
3368  return nullptr;
3369 
3370  ConstantInt *CI = nullptr;
3371  for (auto Case : cases()) {
3372  if (Case.getCaseSuccessor() != BB)
3373  continue;
3374 
3375  if (CI)
3376  return nullptr; // Multiple cases lead to BB.
3377 
3378  CI = Case.getCaseValue();
3379  }
3380 
3381  return CI;
3382  }
3383 
3384  /// Add an entry to the switch instruction.
3385  /// Note:
3386  /// This action invalidates case_end(). Old case_end() iterator will
3387  /// point to the added case.
3388  void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3389 
3390  /// This method removes the specified case and its successor from the switch
3391  /// instruction. Note that this operation may reorder the remaining cases at
3392  /// index idx and above.
3393  /// Note:
3394  /// This action invalidates iterators for all cases following the one removed,
3395  /// including the case_end() iterator. It returns an iterator for the next
3396  /// case.
3397  CaseIt removeCase(CaseIt I);
3398 
3399  unsigned getNumSuccessors() const { return getNumOperands()/2; }
3400  BasicBlock *getSuccessor(unsigned idx) const {
3401  assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3402  return cast<BasicBlock>(getOperand(idx*2+1));
3403  }
3404  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3405  assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3406  setOperand(idx * 2 + 1, NewSucc);
3407  }
3408 
3409  // Methods for support type inquiry through isa, cast, and dyn_cast:
3410  static bool classof(const Instruction *I) {
3411  return I->getOpcode() == Instruction::Switch;
3412  }
3413  static bool classof(const Value *V) {
3414  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3415  }
3416 };
3417 
3418 template <>
3420 };
3421 
3422 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3423 
3424 //===----------------------------------------------------------------------===//
3425 // IndirectBrInst Class
3426 //===----------------------------------------------------------------------===//
3427 
3428 //===---------------------------------------------------------------------------
3429 /// Indirect Branch Instruction.
3430 ///
3432  unsigned ReservedSpace;
3433 
3434  // Operand[0] = Address to jump to
3435  // Operand[n+1] = n-th destination
3436  IndirectBrInst(const IndirectBrInst &IBI);
3437 
3438  /// Create a new indirectbr instruction, specifying an
3439  /// Address to jump to. The number of expected destinations can be specified
3440  /// here to make memory allocation more efficient. This constructor can also
3441  /// autoinsert before another instruction.
3442  IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3443 
3444  /// Create a new indirectbr instruction, specifying an
3445  /// Address to jump to. The number of expected destinations can be specified
3446  /// here to make memory allocation more efficient. This constructor also
3447  /// autoinserts at the end of the specified BasicBlock.
3448  IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3449 
3450  // allocate space for exactly zero operands
3451  void *operator new(size_t s) {
3452  return User::operator new(s);
3453  }
3454 
3455  void init(Value *Address, unsigned NumDests);
3456  void growOperands();
3457 
3458 protected:
3459  // Note: Instruction needs to be a friend here to call cloneImpl.
3460  friend class Instruction;
3461 
3462  IndirectBrInst *cloneImpl() const;
3463 
3464 public:
3465  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3466  Instruction *InsertBefore = nullptr) {
3467  return new IndirectBrInst(Address, NumDests, InsertBefore);
3468  }
3469 
3470  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3471  BasicBlock *InsertAtEnd) {
3472  return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3473  }
3474 
3475  /// Provide fast operand accessors.
3477 
3478  // Accessor Methods for IndirectBrInst instruction.
3479  Value *getAddress() { return getOperand(0); }
3480  const Value *getAddress() const { return getOperand(0); }
3481  void setAddress(Value *V) { setOperand(0, V); }
3482 
3483  /// return the number of possible destinations in this
3484  /// indirectbr instruction.
3485  unsigned getNumDestinations() const { return getNumOperands()-1; }
3486 
3487  /// Return the specified destination.
3488  BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3489  const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3490 
3491  /// Add a destination.
3492  ///
3493  void addDestination(BasicBlock *Dest);
3494 
3495  /// This method removes the specified successor from the
3496  /// indirectbr instruction.
3497  void removeDestination(unsigned i);
3498 
3499  unsigned getNumSuccessors() const { return getNumOperands()-1; }
3500  BasicBlock *getSuccessor(unsigned i) const {
3501  return cast<BasicBlock>(getOperand(i+1));
3502  }
3503  void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3504  setOperand(i + 1, NewSucc);
3505  }
3506 
3507  // Methods for support type inquiry through isa, cast, and dyn_cast:
3508  static bool classof(const Instruction *I) {
3509  return I->getOpcode() == Instruction::IndirectBr;
3510  }
3511  static bool classof(const Value *V) {
3512  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3513  }
3514 };
3515 
3516 template <>
3518 };
3519 
3520 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3521 
3522 //===----------------------------------------------------------------------===//
3523 // InvokeInst Class
3524 //===----------------------------------------------------------------------===//
3525 
3526 /// Invoke instruction. The SubclassData field is used to hold the
3527 /// calling convention of the call.
3528 ///
3532 
3534  FunctionType *FTy;
3535 
3536  InvokeInst(const InvokeInst &BI);
3537 
3538  /// Construct an InvokeInst given a range of arguments.
3539  ///
3540  /// Construct an InvokeInst from a range of arguments
3541  inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3542  ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3543  unsigned Values, const Twine &NameStr,
3544  Instruction *InsertBefore)
3545  : InvokeInst(cast<FunctionType>(
3546  cast<PointerType>(Func->getType())->getElementType()),
3547  Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3548  InsertBefore) {}
3549 
3550  inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3551  BasicBlock *IfException, ArrayRef<Value *> Args,
3552  ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3553  const Twine &NameStr, Instruction *InsertBefore);
3554  /// Construct an InvokeInst given a range of arguments.
3555  ///
3556  /// Construct an InvokeInst from a range of arguments
3557  inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3559  unsigned Values, const Twine &NameStr,
3560  BasicBlock *InsertAtEnd);
3561 
3562  bool hasDescriptor() const { return HasDescriptor; }
3563 
3564  void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3566  const Twine &NameStr) {
3567  init(cast<FunctionType>(
3568  cast<PointerType>(Func->getType())->getElementType()),
3569  Func, IfNormal, IfException, Args, Bundles, NameStr);
3570  }
3571 
3572  void init(FunctionType *FTy, Value *Func, BasicBlock *IfNormal,
3573  BasicBlock *IfException, ArrayRef<Value *> Args,
3574  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3575 
3576 protected:
3577  // Note: Instruction needs to be a friend here to call cloneImpl.
3578  friend class Instruction;
3579 
3580  InvokeInst *cloneImpl() const;
3581 
3582 public:
3583  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3584  BasicBlock *IfException, ArrayRef<Value *> Args,
3585  const Twine &NameStr,
3586  Instruction *InsertBefore = nullptr) {
3587  return Create(cast<FunctionType>(
3588  cast<PointerType>(Func->getType())->getElementType()),
3589  Func, IfNormal, IfException, Args, None, NameStr,
3590  InsertBefore);
3591  }
3592 
3593  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3594  BasicBlock *IfException, ArrayRef<Value *> Args,
3595  ArrayRef<OperandBundleDef> Bundles = None,
3596  const Twine &NameStr = "",
3597  Instruction *InsertBefore = nullptr) {
3598  return Create(cast<FunctionType>(
3599  cast<PointerType>(Func->getType())->getElementType()),
3600  Func, IfNormal, IfException, Args, Bundles, NameStr,
3601  InsertBefore);
3602  }
3603 
3604  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3605  BasicBlock *IfException, ArrayRef<Value *> Args,
3606  const Twine &NameStr,
3607  Instruction *InsertBefore = nullptr) {
3608  unsigned Values = unsigned(Args.size()) + 3;
3609  return new (Values) InvokeInst(Ty, Func, IfNormal, IfException, Args, None,
3610  Values, NameStr, InsertBefore);
3611  }
3612 
3613  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3614  BasicBlock *IfException, ArrayRef<Value *> Args,
3615  ArrayRef<OperandBundleDef> Bundles = None,
3616  const Twine &NameStr = "",
3617  Instruction *InsertBefore = nullptr) {
3618  unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3619  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3620 
3621  return new (Values, DescriptorBytes)
3622  InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, Values,
3623  NameStr, InsertBefore);
3624  }
3625 
3626  static InvokeInst *Create(Value *Func,
3627  BasicBlock *IfNormal, BasicBlock *IfException,
3628  ArrayRef<Value *> Args, const Twine &NameStr,
3629  BasicBlock *InsertAtEnd) {
3630  unsigned Values = unsigned(Args.size()) + 3;
3631  return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None,
3632  Values, NameStr, InsertAtEnd);
3633  }
3634 
3635  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3636  BasicBlock *IfException, ArrayRef<Value *> Args,
3638  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3639  unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3640  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3641 
3642  return new (Values, DescriptorBytes)
3643  InvokeInst(Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3644  InsertAtEnd);
3645  }
3646 
3647  /// Create a clone of \p II with a different set of operand bundles and
3648  /// insert it before \p InsertPt.
3649  ///
3650  /// The returned invoke instruction is identical to \p II in every way except
3651  /// that the operand bundles for the new instruction are set to the operand
3652  /// bundles in \p Bundles.
3653  static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3654  Instruction *InsertPt = nullptr);
3655 
3656  /// Provide fast operand accessors
3658 
3659  FunctionType *getFunctionType() const { return FTy; }
3660 
3662  mutateType(FTy->getReturnType());
3663  this->FTy = FTy;
3664  }
3665 
3666  /// Return the number of invoke arguments.
3667  ///
3668  unsigned getNumArgOperands() const {
3669  return getNumOperands() - getNumTotalBundleOperands() - 3;
3670  }
3671 
3672  /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3673  ///
3674  Value *getArgOperand(unsigned i) const {
3675  assert(i < getNumArgOperands() && "Out of bounds!");
3676  return getOperand(i);
3677  }
3678  void setArgOperand(unsigned i, Value *v) {
3679  assert(i < getNumArgOperands() && "Out of bounds!");
3680  setOperand(i, v);
3681  }
3682 
3683  /// Return the iterator pointing to the beginning of the argument list.
3685 
3686  /// Return the iterator pointing to the end of the argument list.
3688  // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3689  return op_end() - getNumTotalBundleOperands() - 3;
3690  }
3691 
3692  /// Iteration adapter for range-for loops.
3694  return make_range(arg_begin(), arg_end());
3695  }
3696 
3697  /// Return the iterator pointing to the beginning of the argument list.
3698  const_op_iterator arg_begin() const { return op_begin(); }
3699 
3700  /// Return the iterator pointing to the end of the argument list.
3702  // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3703  return op_end() - getNumTotalBundleOperands() - 3;
3704  }
3705 
3706  /// Iteration adapter for range-for loops.
3708  return make_range(arg_begin(), arg_end());
3709  }
3710 
3711  /// Wrappers for getting the \c Use of a invoke argument.
3712  const Use &getArgOperandUse(unsigned i) const {
3713  assert(i < getNumArgOperands() && "Out of bounds!");
3714  return getOperandUse(i);
3715  }
3716  Use &getArgOperandUse(unsigned i) {
3717  assert(i < getNumArgOperands() && "Out of bounds!");
3718  return getOperandUse(i);
3719  }
3720 
3721  /// If one of the arguments has the 'returned' attribute, return its
3722  /// operand value. Otherwise, return nullptr.
3723  Value *getReturnedArgOperand() const;
3724 
3725  /// getCallingConv/setCallingConv - Get or set the calling convention of this
3726  /// function call.
3728  return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3729  }
3731  auto ID = static_cast<unsigned>(CC);
3732  assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
3733  setInstructionSubclassData(ID);
3734  }
3735 
3736  /// Return the parameter attributes for this invoke.
3737  ///
3738  AttributeList getAttributes() const { return Attrs; }
3739 
3740  /// Set the parameter attributes for this invoke.
3741  ///
3743 
3744  /// adds the attribute to the list of attributes.
3745  void addAttribute(unsigned i, Attribute::AttrKind Kind);
3746 
3747  /// adds the attribute to the list of attributes.
3748  void addAttribute(unsigned i, Attribute Attr);
3749 
3750  /// Adds the attribute to the indicated argument
3751  void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3752 
3753  /// removes the attribute from the list of attributes.
3754  void removeAttribute(unsigned i, Attribute::AttrKind Kind);
3755 
3756  /// removes the attribute from the list of attributes.
3757  void removeAttribute(unsigned i, StringRef Kind);
3758 
3759  /// Removes the attribute from the given argument
3760  void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3761 
3762  /// adds the dereferenceable attribute to the list of attributes.
3763  void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3764 
3765  /// adds the dereferenceable_or_null attribute to the list of
3766  /// attributes.
3767  void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
3768 
3769  /// Determine whether this call has the given attribute.
3770  bool hasFnAttr(Attribute::AttrKind Kind) const {
3771  assert(Kind != Attribute::NoBuiltin &&
3772  "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
3773  return hasFnAttrImpl(Kind);
3774  }
3775 
3776  /// Determine whether this call has the given attribute.
3777  bool hasFnAttr(StringRef Kind) const {
3778  return hasFnAttrImpl(Kind);
3779  }
3780 
3781  /// Determine whether the return value has the given attribute.
3782  bool hasRetAttr(Attribute::AttrKind Kind) const;
3783 
3784  /// Determine whether the argument or parameter has the given attribute.
3785  bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
3786 
3787  /// Get the attribute of a given kind at a position.
3788  Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
3789  return getAttributes().getAttribute(i, Kind);
3790  }
3791 
3792  /// Get the attribute of a given kind at a position.
3793  Attribute getAttribute(unsigned i, StringRef Kind) const {
3794  return getAttributes().getAttribute(i, Kind);
3795  }
3796 
3797  /// Return true if the data operand at index \p i has the attribute \p
3798  /// A.
3799  ///
3800  /// Data operands include invoke arguments and values used in operand bundles,
3801  /// but does not include the invokee operand, or the two successor blocks.
3802  /// This routine dispatches to the underlying AttributeList or the
3803  /// OperandBundleUser as appropriate.
3804  ///
3805  /// The index \p i is interpreted as
3806  ///
3807  /// \p i == Attribute::ReturnIndex -> the return value
3808  /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
3809  /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
3810  /// (\p i - 1) in the operand list.
3811  bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
3812 
3813  /// Extract the alignment of the return value.
3814  unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
3815 
3816  /// Extract the alignment for a call or parameter (0=unknown).
3817  unsigned getParamAlignment(unsigned ArgNo) const {
3818  return Attrs.getParamAlignment(ArgNo);
3819  }
3820 
3821  /// Extract the number of dereferenceable bytes for a call or
3822  /// parameter (0=unknown).
3823  uint64_t getDereferenceableBytes(unsigned i) const {
3824  return Attrs.getDereferenceableBytes(i);
3825  }
3826 
3827  /// Extract the number of dereferenceable_or_null bytes for a call or
3828  /// parameter (0=unknown).
3829  uint64_t getDereferenceableOrNullBytes(unsigned i) const {
3830  return Attrs.getDereferenceableOrNullBytes(i);
3831  }
3832 
3833  /// @brief Determine if the return value is marked with NoAlias attribute.
3834  bool returnDoesNotAlias() const {
3835  return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
3836  }
3837 
3838  /// Return true if the call should not be treated as a call to a
3839  /// builtin.
3840  bool isNoBuiltin() const {
3841  // We assert in hasFnAttr if one passes in Attribute::NoBuiltin, so we have
3842  // to check it by hand.
3843  return hasFnAttrImpl(Attribute::NoBuiltin) &&
3844  !hasFnAttrImpl(Attribute::Builtin);
3845  }
3846 
3847  /// Return true if the call should not be inlined.
3848  bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
3849  void setIsNoInline() {
3850  addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
3851  }
3852 
3853  /// Determine if the call does not access memory.
3854  bool doesNotAccessMemory() const {
3855  return hasFnAttr(Attribute::ReadNone);
3856  }
3858  addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
3859  }
3860 
3861  /// Determine if the call does not access or only reads memory.
3862  bool onlyReadsMemory() const {
3863  return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
3864  }
3866  addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
3867  }
3868 
3869  /// Determine if the call does not access or only writes memory.
3870  bool doesNotReadMemory() const {
3871  return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
3872  }
3874  addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
3875  }
3876 
3877  /// @brief Determine if the call access memmory only using it's pointer
3878  /// arguments.
3879  bool onlyAccessesArgMemory() const {
3880  return hasFnAttr(Attribute::ArgMemOnly);
3881  }
3883  addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
3884  }
3885 
3886  /// Determine if the call cannot return.
3887  bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
3889  addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
3890  }
3891 
3892  /// Determine if the call cannot unwind.
3893  bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3895  addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3896  }
3897 
3898  /// Determine if the invoke cannot be duplicated.
3899  bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
3901  addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
3902  }
3903 
3904  /// Determine if the invoke is convergent
3905  bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
3906  void setConvergent() {
3908  }
3911  }
3912 
3913  /// Determine if the call returns a structure through first
3914  /// pointer argument.
3915  bool hasStructRetAttr() const {
3916  if (getNumArgOperands() == 0)
3917  return false;
3918 
3919  // Be friendly and also check the callee.
3920  return paramHasAttr(0, Attribute::StructRet);
3921  }
3922 
3923  /// Determine if any call argument is an aggregate passed by value.
3924  bool hasByValArgument() const {
3925  return Attrs.hasAttrSomewhere(Attribute::ByVal);
3926  }
3927 
3928  /// Return the function called, or null if this is an
3929  /// indirect function invocation.
3930  ///
3932  return dyn_cast<Function>(Op<-3>());
3933  }
3934 
3935  /// Get a pointer to the function that is invoked by this
3936  /// instruction
3937  const Value *getCalledValue() const { return Op<-3>(); }
3938  Value *getCalledValue() { return Op<-3>(); }
3939 
3940  /// Set the function called.
3941  void setCalledFunction(Value* Fn) {
3942  setCalledFunction(
3943  cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
3944  Fn);
3945  }
3946  void setCalledFunction(FunctionType *FTy, Value *Fn) {
3947  this->FTy = FTy;
3948  assert(FTy == cast<FunctionType>(
3949  cast<PointerType>(Fn->getType())->getElementType()));
3950  Op<-3>() = Fn;
3951  }
3952 
3953  // get*Dest - Return the destination basic blocks...
3955  return cast<BasicBlock>(Op<-2>());
3956  }
3958  return cast<BasicBlock>(Op<-1>());
3959  }
3961  Op<-2>() = reinterpret_cast<Value*>(B);
3962  }
3964  Op<-1>() = reinterpret_cast<Value*>(B);
3965  }
3966 
3967  /// Get the landingpad instruction from the landing pad
3968  /// block (the unwind destination).
3969  LandingPadInst *getLandingPadInst() const;
3970 
3971  BasicBlock *getSuccessor(unsigned i) const {
3972  assert(i < 2 && "Successor # out of range for invoke!");
3973  return i == 0 ? getNormalDest() : getUnwindDest();
3974  }
3975 
3976  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3977  assert(idx < 2 && "Successor # out of range for invoke!");
3978  *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
3979  }
3980 
3981  unsigned getNumSuccessors() const { return 2; }
3982 
3983  // Methods for support type inquiry through isa, cast, and dyn_cast:
3984  static bool classof(const Instruction *I) {
3985  return (I->getOpcode() == Instruction::Invoke);
3986  }
3987  static bool classof(const Value *V) {
3988  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3989  }
3990 
3991 private:
3992  template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
3993  if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
3994  return true;
3995 
3996  // Operand bundles override attributes on the called function, but don't
3997  // override attributes directly present on the invoke instruction.
3998  if (isFnAttrDisallowedByOpBundle(Kind))
3999  return false;
4000 
4001  if (const Function *F = getCalledFunction())
4002  return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
4003  Kind);
4004  return false;
4005  }
4006 
4007  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4008  // method so that subclasses cannot accidentally use it.
4009  void setInstructionSubclassData(unsigned short D) {
4011  }
4012 };
4013 
4014 template <>
4015 struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
4016 };
4017 
4018 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
4019  BasicBlock *IfException, ArrayRef<Value *> Args,
4020  ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4021  const Twine &NameStr, Instruction *InsertBefore)
4022  : TerminatorInst(Ty->getReturnType(), Instruction::Invoke,
4023  OperandTraits<InvokeInst>::op_end(this) - Values, Values,
4024  InsertBefore) {
4025  init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
4026 }
4027 
4028 InvokeInst::InvokeInst(Value *Func, BasicBlock *IfNormal,
4029  BasicBlock *IfException, ArrayRef<Value *> Args,
4030  ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4031  const Twine &NameStr, BasicBlock *InsertAtEnd)
4032  : TerminatorInst(
4033  cast<FunctionType>(cast<PointerType>(Func->getType())
4034  ->getElementType())->getReturnType(),
4035  Instruction::Invoke, OperandTraits<InvokeInst>::op_end(this) - Values,
4036  Values, InsertAtEnd) {
4037  init(Func, IfNormal, IfException, Args, Bundles, NameStr);
4038 }
4039 
4040 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
4041 
4042 //===----------------------------------------------------------------------===//
4043 // ResumeInst Class
4044 //===----------------------------------------------------------------------===//
4045 
4046 //===---------------------------------------------------------------------------
4047 /// Resume the propagation of an exception.
4048 ///
4049 class ResumeInst : public TerminatorInst {
4050  ResumeInst(const ResumeInst &RI);
4051 
4052  explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4053  ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4054 
4055 protected:
4056  // Note: Instruction needs to be a friend here to call cloneImpl.
4057  friend class Instruction;
4058 
4059  ResumeInst *cloneImpl() const;
4060 
4061 public:
4062  static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4063  return new(1) ResumeInst(Exn, InsertBefore);
4064  }
4065 
4066  static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4067  return new(1) ResumeInst(Exn, InsertAtEnd);
4068  }
4069 
4070  /// Provide fast operand accessors
4072 
4073  /// Convenience accessor.
4074  Value *getValue() const { return Op<0>(); }
4075 
4076  unsigned getNumSuccessors() const { return 0; }
4077 
4078  // Methods for support type inquiry through isa, cast, and dyn_cast:
4079  static bool classof(const Instruction *I) {
4080  return I->getOpcode() == Instruction::Resume;
4081  }
4082  static bool classof(const Value *V) {
4083  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4084  }
4085 
4086 private:
4087  friend TerminatorInst;
4088 
4089  BasicBlock *getSuccessor(unsigned idx) const {
4090  llvm_unreachable("ResumeInst has no successors!");
4091  }
4092 
4093  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4094  llvm_unreachable("ResumeInst has no successors!");
4095  }
4096 };
4097 
4098 template <>
4100  public FixedNumOperandTraits<ResumeInst, 1> {
4101 };
4102 
4103 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4104 
4105 //===----------------------------------------------------------------------===//
4106 // CatchSwitchInst Class
4107 //===----------------------------------------------------------------------===//
4109  /// The number of operands actually allocated. NumOperands is
4110  /// the number actually in use.
4111  unsigned ReservedSpace;
4112 
4113  // Operand[0] = Outer scope
4114  // Operand[1] = Unwind block destination
4115  // Operand[n] = BasicBlock to go to on match
4116  CatchSwitchInst(const CatchSwitchInst &CSI);
4117 
4118  /// Create a new switch instruction, specifying a
4119  /// default destination. The number of additional handlers can be specified
4120  /// here to make memory allocation more efficient.
4121  /// This constructor can also autoinsert before another instruction.
4122  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4123  unsigned NumHandlers, const Twine &NameStr,
4124  Instruction *InsertBefore);
4125 
4126  /// Create a new switch instruction, specifying a
4127  /// default destination. The number of additional handlers can be specified
4128  /// here to make memory allocation more efficient.
4129  /// This constructor also autoinserts at the end of the specified BasicBlock.
4130  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4131  unsigned NumHandlers, const Twine &NameStr,
4132  BasicBlock *InsertAtEnd);
4133 
4134  // allocate space for exactly zero operands
4135  void *operator new(size_t s) { return User::operator new(s); }
4136 
4137  void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4138  void growOperands(unsigned Size);
4139 
4140 protected:
4141  // Note: Instruction needs to be a friend here to call cloneImpl.
4142  friend class Instruction;
4143 
4144  CatchSwitchInst *cloneImpl() const;
4145 
4146 public:
4147  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4148  unsigned NumHandlers,
4149  const Twine &NameStr = "",
4150  Instruction *InsertBefore = nullptr) {
4151  return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4152  InsertBefore);
4153  }
4154 
4155  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4156  unsigned NumHandlers, const Twine &NameStr,
4157  BasicBlock *InsertAtEnd) {
4158  return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4159  InsertAtEnd);
4160  }
4161 
4162  /// Provide fast operand accessors
4164 
4165  // Accessor Methods for CatchSwitch stmt
4166  Value *getParentPad() const { return getOperand(0); }
4167  void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4168 
4169  // Accessor Methods for CatchSwitch stmt
4170  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4171  bool unwindsToCaller() const { return !hasUnwindDest(); }
4173  if (hasUnwindDest())
4174  return cast<BasicBlock>(getOperand(1));
4175  return nullptr;
4176  }
4177  void setUnwindDest(BasicBlock *UnwindDest) {
4178  assert(UnwindDest);
4179  assert(hasUnwindDest());
4180  setOperand(1, UnwindDest);
4181  }
4182 
4183  /// return the number of 'handlers' in this catchswitch
4184  /// instruction, except the default handler
4185  unsigned getNumHandlers() const {
4186  if (hasUnwindDest())
4187  return getNumOperands() - 2;
4188  return getNumOperands() - 1;
4189  }
4190 
4191 private:
4192  static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4193  static const BasicBlock *handler_helper(const Value *V) {
4194  return cast<BasicBlock>(V);
4195  }
4196 
4197 public:
4198  using DerefFnTy = std::pointer_to_unary_function<Value *, BasicBlock *>;
4201  using ConstDerefFnTy =
4202  std::pointer_to_unary_function<const Value *, const BasicBlock *>;
4203  using const_handler_iterator =
4206 
4207  /// Returns an iterator that points to the first handler in CatchSwitchInst.
4209  op_iterator It = op_begin() + 1;
4210  if (hasUnwindDest())
4211  ++It;
4212  return handler_iterator(It, DerefFnTy(handler_helper));
4213  }
4214 
4215  /// Returns an iterator that points to the first handler in the
4216  /// CatchSwitchInst.
4218  const_op_iterator It = op_begin() + 1;
4219  if (hasUnwindDest())
4220  ++It;
4221  return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4222  }
4223 
4224  /// Returns a read-only iterator that points one past the last
4225  /// handler in the CatchSwitchInst.
4227  return handler_iterator(op_end(), DerefFnTy(handler_helper));
4228  }
4229 
4230  /// Returns an iterator that points one past the last handler in the
4231  /// CatchSwitchInst.
4233  return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4234  }
4235 
4236  /// iteration adapter for range-for loops.
4238  return make_range(handler_begin(), handler_end());
4239  }
4240 
4241  /// iteration adapter for range-for loops.
4243  return make_range(handler_begin(), handler_end());
4244  }
4245 
4246  /// Add an entry to the switch instruction...
4247  /// Note:
4248  /// This action invalidates handler_end(). Old handler_end() iterator will
4249  /// point to the added handler.
4250  void addHandler(BasicBlock *Dest);
4251 
4252  void removeHandler(handler_iterator HI);
4253 
4254  unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4255  BasicBlock *getSuccessor(unsigned Idx) const {
4256  assert(Idx < getNumSuccessors() &&
4257  "Successor # out of range for catchswitch!");
4258  return cast<BasicBlock>(getOperand(Idx + 1));
4259  }
4260  void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4261  assert(Idx < getNumSuccessors() &&
4262  "Successor # out of range for catchswitch!");
4263  setOperand(Idx + 1, NewSucc);
4264  }
4265 
4266  // Methods for support type inquiry through isa, cast, and dyn_cast:
4267  static bool classof(const Instruction *I) {
4268  return I->getOpcode() == Instruction::CatchSwitch;
4269  }
4270  static bool classof(const Value *V) {
4271  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4272  }
4273 };
4274 
4275 template <>
4277 
4278 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4279 
4280 //===----------------------------------------------------------------------===//
4281 // CleanupPadInst Class
4282 //===----------------------------------------------------------------------===//
4284 private:
4285  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4286  unsigned Values, const Twine &NameStr,
4287  Instruction *InsertBefore)
4288  : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4289  NameStr, InsertBefore) {}
4290  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4291  unsigned Values, const Twine &NameStr,
4292  BasicBlock *InsertAtEnd)
4293  : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4294  NameStr, InsertAtEnd) {}
4295 
4296 public:
4297  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4298  const Twine &NameStr = "",
4299  Instruction *InsertBefore = nullptr) {
4300  unsigned Values = 1 + Args.size();
4301  return new (Values)
4302  CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4303  }
4304 
4305  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4306  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4307  unsigned Values = 1 + Args.size();
4308  return new (Values)
4309  CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4310  }
4311 
4312  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4313  static bool classof(const Instruction *I) {
4314  return I->getOpcode() == Instruction::CleanupPad;
4315  }
4316  static bool classof(const Value *V) {
4317  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4318  }
4319 };
4320 
4321 //===----------------------------------------------------------------------===//
4322 // CatchPadInst Class
4323 //===----------------------------------------------------------------------===//
4325 private:
4326  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4327  unsigned Values, const Twine &NameStr,
4328  Instruction *InsertBefore)
4329  : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4330  NameStr, InsertBefore) {}
4331  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4332  unsigned Values, const Twine &NameStr,
4333  BasicBlock *InsertAtEnd)
4334  : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4335  NameStr, InsertAtEnd) {}
4336 
4337 public:
4338  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4339  const Twine &NameStr = "",
4340  Instruction *InsertBefore = nullptr) {
4341  unsigned Values = 1 + Args.size();
4342  return new (Values)
4343  CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4344  }
4345 
4346  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4347  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4348  unsigned Values = 1 + Args.size();
4349  return new (Values)
4350  CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4351  }
4352 
4353  /// Convenience accessors
4354  CatchSwitchInst *getCatchSwitch() const {
4355  return cast<CatchSwitchInst>(Op<-1>());
4356  }
4357  void setCatchSwitch(Value *CatchSwitch) {
4358  assert(CatchSwitch);
4359  Op<-1>() = CatchSwitch;
4360  }
4361 
4362  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4363  static bool classof(const Instruction *I) {
4364  return I->getOpcode() == Instruction::CatchPad;
4365  }
4366  static bool classof(const Value *V) {
4367  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4368  }
4369 };
4370 
4371 //===----------------------------------------------------------------------===//
4372 // CatchReturnInst Class
4373 //===----------------------------------------------------------------------===//
4374 
4376  CatchReturnInst(const CatchReturnInst &RI);
4377  CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4378  CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4379 
4380  void init(Value *CatchPad, BasicBlock *BB);
4381 
4382 protected:
4383  // Note: Instruction needs to be a friend here to call cloneImpl.
4384  friend class Instruction;
4385 
4386  CatchReturnInst *cloneImpl() const;
4387 
4388 public:
4389  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4390  Instruction *InsertBefore = nullptr) {
4391  assert(CatchPad);
4392  assert(BB);
4393  return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4394  }
4395 
4396  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4397  BasicBlock *InsertAtEnd) {
4398  assert(CatchPad);
4399  assert(BB);
4400  return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4401  }
4402 
4403  /// Provide fast operand accessors
4405 
4406  /// Convenience accessors.
4407  CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4408  void setCatchPad(CatchPadInst *CatchPad) {
4409  assert(CatchPad);
4410  Op<0>() = CatchPad;
4411  }
4412 
4413  BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4414  void setSuccessor(BasicBlock *NewSucc) {
4415  assert(NewSucc);
4416  Op<1>() = NewSucc;
4417  }
4418  unsigned getNumSuccessors() const { return 1; }
4419 
4420  /// Get the parentPad of this catchret's catchpad's catchswitch.
4421  /// The successor block is implicitly a member of this funclet.
4422  Value *getCatchSwitchParentPad() const {
4423  return getCatchPad()->getCatchSwitch()->getParentPad();
4424  }
4425 
4426  // Methods for support type inquiry through isa, cast, and dyn_cast:
4427  static bool classof(const Instruction *I) {
4428  return (I->getOpcode() == Instruction::CatchRet);
4429  }
4430  static bool classof(const Value *V) {
4431  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4432  }
4433 
4434 private:
4435  friend TerminatorInst;
4436 
4437  BasicBlock *getSuccessor(unsigned Idx) const {
4438  assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4439  return getSuccessor();
4440  }
4441 
4442  void setSuccessor(unsigned Idx, BasicBlock *B) {
4443  assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4444  setSuccessor(B);
4445  }
4446 };
4447 
4448 template <>
4450  : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4451 
4452 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4453 
4454 //===----------------------------------------------------------------------===//
4455 // CleanupReturnInst Class
4456 //===----------------------------------------------------------------------===//
4457 
4459 private:
4461  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4462  Instruction *InsertBefore = nullptr);
4463  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4464  BasicBlock *InsertAtEnd);
4465 
4466  void init(Value *CleanupPad, BasicBlock *UnwindBB);
4467 
4468 protected:
4469  // Note: Instruction needs to be a friend here to call cloneImpl.
4470  friend class Instruction;
4471 
4472  CleanupReturnInst *cloneImpl() const;
4473 
4474 public:
4475  static CleanupReturnInst *Create(Value *CleanupPad,
4476  BasicBlock *UnwindBB = nullptr,
4477  Instruction *InsertBefore = nullptr) {
4478  assert(CleanupPad);
4479  unsigned Values = 1;
4480  if (UnwindBB)
4481  ++Values;
4482  return new (Values)
4483  CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4484  }
4485 
4486  static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4487  BasicBlock *InsertAtEnd) {
4488  assert(CleanupPad);
4489  unsigned Values = 1;
4490  if (UnwindBB)
4491  ++Values;
4492  return new (Values)
4493  CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4494  }
4495 
4496  /// Provide fast operand accessors
4498 
4499  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4500  bool unwindsToCaller() const { return !hasUnwindDest(); }
4501 
4502  /// Convenience accessor.
4504  return cast<CleanupPadInst>(Op<0>());
4505  }
4506  void setCleanupPad(CleanupPadInst *CleanupPad) {
4507  assert(CleanupPad);
4508  Op<0>() = CleanupPad;
4509  }
4510 
4511  unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4512 
4514  return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4515  }
4516  void setUnwindDest(BasicBlock *NewDest) {
4517  assert(NewDest);
4518  assert(hasUnwindDest());
4519  Op<1>() = NewDest;
4520  }
4521 
4522  // Methods for support type inquiry through isa, cast, and dyn_cast:
4523  static bool classof(const Instruction *I) {
4524  return (I->getOpcode() == Instruction::CleanupRet);
4525  }
4526  static bool classof(const Value *V) {
4527  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4528  }
4529 
4530 private:
4531  friend TerminatorInst;
4532 
4533  BasicBlock *getSuccessor(unsigned Idx) const {
4534  assert(Idx == 0);
4535  return getUnwindDest();
4536  }
4537 
4538  void setSuccessor(unsigned Idx, BasicBlock *B) {
4539  assert(Idx == 0);
4540  setUnwindDest(B);
4541  }
4542 
4543  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4544  // method so that subclasses cannot accidentally use it.
4545  void setInstructionSubclassData(unsigned short D) {
4547  }
4548 };
4549 
4550 template <>
4552  : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4553 
4554 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4555 
4556 //===----------------------------------------------------------------------===//
4557 // UnreachableInst Class
4558 //===----------------------------------------------------------------------===//
4559 
4560 //===---------------------------------------------------------------------------
4561 /// This function has undefined behavior. In particular, the
4562 /// presence of this instruction indicates some higher level knowledge that the
4563 /// end of the block cannot be reached.
4564 ///
4566 protected:
4567  // Note: Instruction needs to be a friend here to call cloneImpl.
4568  friend class Instruction;
4569 
4570  UnreachableInst *cloneImpl() const;
4571 
4572 public:
4573  explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4574  explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4575 
4576  // allocate space for exactly zero operands
4577  void *operator new(size_t s) {
4578  return User::operator new(s, 0);
4579  }
4580 
4581  unsigned getNumSuccessors() const { return 0; }
4582 
4583  // Methods for support type inquiry through isa, cast, and dyn_cast:
4584  static bool classof(const Instruction *I) {
4585  return I->getOpcode() == Instruction::Unreachable;
4586  }
4587  static bool classof(const Value *V) {
4588  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4589  }
4590 
4591 private:
4592  friend TerminatorInst;
4593 
4594  BasicBlock *getSuccessor(unsigned idx) const {
4595  llvm_unreachable("UnreachableInst has no successors!");
4596  }
4597 
4598  void setSuccessor(unsigned idx, BasicBlock *B) {
4599  llvm_unreachable("UnreachableInst has no successors!");
4600  }
4601 };
4602 
4603 //===----------------------------------------------------------------------===//
4604 // TruncInst Class
4605 //===----------------------------------------------------------------------===//
4606 
4607 /// This class represents a truncation of integer types.
4608 class TruncInst : public CastInst {
4609 protected:
4610  // Note: Instruction needs to be a friend here to call cloneImpl.
4611  friend class Instruction;
4612 
4613  /// Clone an identical TruncInst
4614  TruncInst *cloneImpl() const;
4615 
4616 public:
4617  /// Constructor with insert-before-instruction semantics
4618  TruncInst(
4619  Value *S, ///< The value to be truncated
4620  Type *Ty, ///< The (smaller) type to truncate to
4621  const Twine &NameStr = "", ///< A name for the new instruction
4622  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4623  );
4624 
4625  /// Constructor with insert-at-end-of-block semantics
4626  TruncInst(
4627  Value *S, ///< The value to be truncated
4628  Type *Ty, ///< The (smaller) type to truncate to
4629  const Twine &NameStr, ///< A name for the new instruction
4630  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4631  );
4632 
4633  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4634  static bool classof(const Instruction *I) {
4635  return I->getOpcode() == Trunc;
4636  }
4637  static bool classof(const Value *V) {
4638  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4639  }
4640 };
4641 
4642 //===----------------------------------------------------------------------===//
4643 // ZExtInst Class
4644 //===----------------------------------------------------------------------===//
4645 
4646 /// This class represents zero extension of integer types.
4647 class ZExtInst : public CastInst {
4648 protected:
4649  // Note: Instruction needs to be a friend here to call cloneImpl.
4650  friend class Instruction;
4651 
4652  /// Clone an identical ZExtInst
4653  ZExtInst *cloneImpl() const;
4654 
4655 public:
4656  /// Constructor with insert-before-instruction semantics
4657  ZExtInst(
4658  Value *S, ///< The value to be zero extended
4659  Type *Ty, ///< The type to zero extend to
4660  const Twine &NameStr = "", ///< A name for the new instruction
4661  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4662  );
4663 
4664  /// Constructor with insert-at-end semantics.
4665  ZExtInst(
4666  Value *S, ///< The value to be zero extended
4667  Type *Ty, ///< The type to zero extend to
4668  const Twine &NameStr, ///< A name for the new instruction
4669  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4670  );
4671 
4672  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4673  static bool classof(const Instruction *I) {
4674  return I->getOpcode() == ZExt;
4675  }
4676  static bool classof(const Value *V) {
4677  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4678  }
4679 };
4680 
4681 //===----------------------------------------------------------------------===//
4682 // SExtInst Class
4683 //===----------------------------------------------------------------------===//
4684 
4685 /// This class represents a sign extension of integer types.
4686 class SExtInst : public CastInst {
4687 protected:
4688  // Note: Instruction needs to be a friend here to call cloneImpl.
4689  friend class Instruction;
4690 
4691  /// Clone an identical SExtInst
4692  SExtInst *cloneImpl() const;
4693 
4694 public:
4695  /// Constructor with insert-before-instruction semantics
4696  SExtInst(
4697  Value *S, ///< The value to be sign extended
4698  Type *Ty, ///< The type to sign extend to
4699  const Twine &NameStr = "", ///< A name for the new instruction
4700  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4701  );
4702 
4703  /// Constructor with insert-at-end-of-block semantics
4704  SExtInst(
4705  Value *S, ///< The value to be sign extended
4706  Type *Ty, ///< The type to sign extend to
4707  const Twine &NameStr, ///< A name for the new instruction
4708  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4709  );
4710 
4711  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4712  static bool classof(const Instruction *I) {
4713  return I->getOpcode() == SExt;
4714  }
4715  static bool classof(const Value *V) {
4716  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4717  }
4718 };
4719 
4720 //===----------------------------------------------------------------------===//
4721 // FPTruncInst Class
4722 //===----------------------------------------------------------------------===//
4723 
4724 /// This class represents a truncation of floating point types.
4725 class FPTruncInst : public CastInst {
4726 protected:
4727  // Note: Instruction needs to be a friend here to call cloneImpl.
4728  friend class Instruction;
4729 
4730  /// Clone an identical FPTruncInst
4731  FPTruncInst *cloneImpl() const;
4732 
4733 public:
4734  /// Constructor with insert-before-instruction semantics
4735  FPTruncInst(
4736  Value *S, ///< The value to be truncated
4737  Type *Ty, ///< The type to truncate to
4738  const Twine &NameStr = "", ///< A name for the new instruction
4739  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4740  );
4741 
4742  /// Constructor with insert-before-instruction semantics
4743  FPTruncInst(
4744  Value *S, ///< The value to be truncated
4745  Type *Ty, ///< The type to truncate to
4746  const Twine &NameStr, ///< A name for the new instruction
4747  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4748  );
4749 
4750  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4751  static bool classof(const Instruction *I) {
4752  return I->getOpcode() == FPTrunc;
4753  }
4754  static bool classof(const Value *V) {
4755  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4756  }
4757 };
4758 
4759 //===----------------------------------------------------------------------===//
4760 // FPExtInst Class
4761 //===----------------------------------------------------------------------===//
4762 
4763 /// This class represents an extension of floating point types.
4764 class FPExtInst : public CastInst {
4765 protected:
4766  // Note: Instruction needs to be a friend here to call cloneImpl.
4767  friend class Instruction;
4768 
4769  /// Clone an identical FPExtInst
4770  FPExtInst *cloneImpl() const;
4771 
4772 public:
4773  /// Constructor with insert-before-instruction semantics
4774  FPExtInst(
4775  Value *S, ///< The value to be extended
4776  Type *Ty, ///< The type to extend to
4777  const Twine &NameStr = "", ///< A name for the new instruction
4778  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4779  );
4780 
4781  /// Constructor with insert-at-end-of-block semantics
4782  FPExtInst(
4783  Value *S, ///< The value to be extended
4784  Type *Ty, ///< The type to extend to
4785  const Twine &NameStr, ///< A name for the new instruction
4786  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4787  );
4788 
4789  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4790  static bool classof(const Instruction *I) {
4791  return I->getOpcode() == FPExt;
4792  }
4793  static bool classof(const Value *V) {
4794  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4795  }
4796 };
4797 
4798 //===----------------------------------------------------------------------===//
4799 // UIToFPInst Class
4800 //===----------------------------------------------------------------------===//
4801 
4802 /// This class represents a cast unsigned integer to floating point.
4803 class UIToFPInst : public CastInst {
4804 protected:
4805  // Note: Instruction needs to be a friend here to call cloneImpl.
4806  friend class Instruction;
4807 
4808  /// Clone an identical UIToFPInst
4809  UIToFPInst *cloneImpl() const;
4810 
4811 public:
4812  /// Constructor with insert-before-instruction semantics
4813  UIToFPInst(
4814  Value *S, ///< The value to be converted
4815  Type *Ty, ///< The type to convert to
4816  const Twine &NameStr = "", ///< A name for the new instruction
4817  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4818  );
4819 
4820  /// Constructor with insert-at-end-of-block semantics
4821  UIToFPInst(
4822  Value *S, ///< The value to be converted
4823  Type *Ty, ///< The type to convert to
4824  const Twine &NameStr, ///< A name for the new instruction
4825  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4826  );
4827 
4828  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4829  static bool classof(const Instruction *I) {
4830  return I->getOpcode() == UIToFP;
4831  }
4832  static bool classof(const Value *V) {
4833  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4834  }
4835 };
4836 
4837 //===----------------------------------------------------------------------===//
4838 // SIToFPInst Class
4839 //===----------------------------------------------------------------------===//
4840 
4841 /// This class represents a cast from signed integer to floating point.
4842 class SIToFPInst : public CastInst {
4843 protected:
4844  // Note: Instruction needs to be a friend here to call cloneImpl.
4845  friend class Instruction;
4846 
4847  /// Clone an identical SIToFPInst
4848  SIToFPInst *cloneImpl() const;
4849 
4850 public:
4851  /// Constructor with insert-before-instruction semantics
4852  SIToFPInst(
4853  Value *S, ///< The value to be converted
4854  Type *Ty, ///< The type to convert to
4855  const Twine &NameStr = "", ///< A name for the new instruction
4856  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4857  );
4858 
4859  /// Constructor with insert-at-end-of-block semantics
4860  SIToFPInst(
4861  Value *S, ///< The value to be converted
4862  Type *Ty, ///< The type to convert to
4863  const Twine &NameStr, ///< A name for the new instruction
4864  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4865  );
4866 
4867  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4868  static bool classof(const Instruction *I) {
4869  return I->getOpcode() == SIToFP;
4870  }
4871  static bool classof(const Value *V) {
4872  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4873  }
4874 };
4875 
4876 //===----------------------------------------------------------------------===//
4877 // FPToUIInst Class
4878 //===----------------------------------------------------------------------===//
4879 
4880 /// This class represents a cast from floating point to unsigned integer
4881 class FPToUIInst : public CastInst {
4882 protected:
4883  // Note: Instruction needs to be a friend here to call cloneImpl.
4884  friend class Instruction;
4885 
4886  /// Clone an identical FPToUIInst
4887  FPToUIInst *cloneImpl() const;
4888 
4889 public:
4890  /// Constructor with insert-before-instruction semantics
4891  FPToUIInst(
4892  Value *S, ///< The value to be converted
4893  Type *Ty, ///< The type to convert to
4894  const Twine &NameStr = "", ///< A name for the new instruction
4895  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4896  );
4897 
4898  /// Constructor with insert-at-end-of-block semantics
4899  FPToUIInst(
4900  Value *S, ///< The value to be converted
4901  Type *Ty, ///< The type to convert to
4902  const Twine &NameStr, ///< A name for the new instruction
4903  BasicBlock *InsertAtEnd ///< Where to insert the new instruction
4904  );
4905 
4906  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4907  static bool classof(const Instruction *I) {
4908  return I->getOpcode() == FPToUI;
4909  }
4910  static bool classof(const Value *V) {
4911  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4912  }
4913 };
4914 
4915 //===----------------------------------------------------------------------===//
4916 // FPToSIInst Class
4917 //===----------------------------------------------------------------------===//
4918 
4919 /// This class represents a cast from floating point to signed integer.
4920 class FPToSIInst : public CastInst {
4921 protected:
4922  // Note: Instruction needs to be a friend here to call cloneImpl.
4923  friend class Instruction;
4924 
4925  /// Clone an identical FPToSIInst
4926  FPToSIInst *cloneImpl() const;
4927 
4928 public:
4929  /// Constructor with insert-before-instruction semantics
4930  FPToSIInst(
4931  Value *S, ///< The value to be converted
4932  Type *Ty, ///< The type to convert to
4933  const Twine &NameStr = "", ///< A name for the new instruction
4934  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4935  );
4936