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"
26#include "llvm/ADT/iterator_range.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"
40#include "llvm/Support/AtomicOrdering.h"
41#include "llvm/Support/Casting.h"
42#include "llvm/Support/ErrorHandling.h"
43#include <cassert>
44#include <cstddef>
45#include <cstdint>
46#include <iterator>
47
48namespace llvm {
49
50class APInt;
51class ConstantInt;
52class DataLayout;
53class LLVMContext;
54
55//===----------------------------------------------------------------------===//
56//                                AllocaInst Class
57//===----------------------------------------------------------------------===//
58
59/// an instruction to allocate memory on the stack
60class AllocaInst : public UnaryInstruction {
61  Type *AllocatedType;
62
63protected:
64  // Note: Instruction needs to be a friend here to call cloneImpl.
65  friend class Instruction;
66
67  AllocaInst *cloneImpl() const;
68
69public:
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
150private:
151  // Shadow Instruction::setInstructionSubclassData with a private forwarding
152  // method so that subclasses cannot accidentally use it.
153  void setInstructionSubclassData(unsigned short D) {
154    Instruction::setInstructionSubclassData(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.
164class LoadInst : public UnaryInstruction {
165  void AssertOK();
166
167protected:
168  // Note: Instruction needs to be a friend here to call cloneImpl.
169  friend class Instruction;
170
171  LoadInst *cloneImpl() const;
172
173public:
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,
193           AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
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,
199           SyncScope::ID SSID = SyncScope::System,
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.
233  AtomicOrdering getOrdering() const {
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.
245  SyncScope::ID getSyncScopeID() const {
246    return SSID;
247  }
248
249  /// Sets the synchronization scope ID of this load instruction.
250  void setSyncScopeID(SyncScope::ID SSID) {
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,
257                 SyncScope::ID SSID = SyncScope::System) {
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
270  Value *getPointerOperand() { return getOperand(0); }
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
288private:
289  // Shadow Instruction::setInstructionSubclassData with a private forwarding
290  // method so that subclasses cannot accidentally use it.
291  void setInstructionSubclassData(unsigned short D) {
292    Instruction::setInstructionSubclassData(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.
306class StoreInst : public Instruction {
307  void AssertOK();
308
309protected:
310  // Note: Instruction needs to be a friend here to call cloneImpl.
311  friend class Instruction;
312
313  StoreInst *cloneImpl() const;
314
315public:
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,
327            SyncScope::ID SSID = SyncScope::System,
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.
348  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
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.
358  AtomicOrdering getOrdering() const {
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.
370  SyncScope::ID getSyncScopeID() const {
371    return SSID;
372  }
373
374  /// Sets the synchronization scope ID of this store instruction.
375  void setSyncScopeID(SyncScope::ID SSID) {
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,
382                 SyncScope::ID SSID = SyncScope::System) {
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
398  Value *getPointerOperand() { return getOperand(1); }
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
416private:
417  // Shadow Instruction::setInstructionSubclassData with a private forwarding
418  // method so that subclasses cannot accidentally use it.
419  void setInstructionSubclassData(unsigned short D) {
420    Instruction::setInstructionSubclassData(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
429template <>
430struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
431};
432
433DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
434
435//===----------------------------------------------------------------------===//
436//                                FenceInst Class
437//===----------------------------------------------------------------------===//
438
439/// An instruction for ordering other memory operations.
440class FenceInst : public Instruction {
441  void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
442
443protected:
444  // Note: Instruction needs to be a friend here to call cloneImpl.
445  friend class Instruction;
446
447  FenceInst *cloneImpl() const;
448
449public:
450  // Ordering may only be Acquire, Release, AcquireRelease, or
451  // SequentiallyConsistent.
452  FenceInst(LLVMContext &C, AtomicOrdering Ordering,
453            SyncScope::ID SSID = SyncScope::System,
454            Instruction *InsertBefore = nullptr);
455  FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
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.
464  AtomicOrdering getOrdering() const {
465    return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
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.
476  SyncScope::ID getSyncScopeID() const {
477    return SSID;
478  }
479
480  /// Sets the synchronization scope ID of this fence instruction.
481  void setSyncScopeID(SyncScope::ID SSID) {
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
493private:
494  // Shadow Instruction::setInstructionSubclassData with a private forwarding
495  // method so that subclasses cannot accidentally use it.
496  void setInstructionSubclassData(unsigned short D) {
497    Instruction::setInstructionSubclassData(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///
514class AtomicCmpXchgInst : public Instruction {
515  void Init(Value *Ptr, Value *Cmp, Value *NewVal,
516            AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
517            SyncScope::ID SSID);
518
519protected:
520  // Note: Instruction needs to be a friend here to call cloneImpl.
521  friend class Instruction;
522
523  AtomicCmpXchgInst *cloneImpl() const;
524
525public:
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.
565  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
566
567  /// Returns the success ordering constraint of this cmpxchg instruction.
568  AtomicOrdering getSuccessOrdering() const {
569    return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
570  }
571
572  /// Sets the success ordering constraint of this cmpxchg instruction.
573  void setSuccessOrdering(AtomicOrdering Ordering) {
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.
581  AtomicOrdering getFailureOrdering() const {
582    return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
583  }
584
585  /// Sets the failure ordering constraint of this cmpxchg instruction.
586  void setFailureOrdering(AtomicOrdering Ordering) {
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.
594  SyncScope::ID getSyncScopeID() const {
595    return SSID;
596  }
597
598  /// Sets the synchronization scope ID of this cmpxchg instruction.
599  void setSyncScopeID(SyncScope::ID SSID) {
600    this->SSID = SSID;
601  }
602
603  Value *getPointerOperand() { return getOperand(0); }
604  const Value *getPointerOperand() const { return getOperand(0); }
605  static unsigned getPointerOperandIndex() { return 0U; }
606
607  Value *getCompareOperand() { return getOperand(1); }
608  const Value *getCompareOperand() const { return getOperand(1); }
609
610  Value *getNewValOperand() { return getOperand(2); }
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
626  getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
627    switch (SuccessOrdering) {
628    default:
629      llvm_unreachable("invalid cmpxchg success ordering");
630    case AtomicOrdering::Release:
631    case AtomicOrdering::Monotonic:
632      return AtomicOrdering::Monotonic;
633    case AtomicOrdering::AcquireRelease:
634    case AtomicOrdering::Acquire:
635      return AtomicOrdering::Acquire;
636    case AtomicOrdering::SequentiallyConsistent:
637      return AtomicOrdering::SequentiallyConsistent;
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
649private:
650  // Shadow Instruction::setInstructionSubclassData with a private forwarding
651  // method so that subclasses cannot accidentally use it.
652  void setInstructionSubclassData(unsigned short D) {
653    Instruction::setInstructionSubclassData(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
662template <>
663struct OperandTraits<AtomicCmpXchgInst> :
664    public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
665};
666
667DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
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///
677class AtomicRMWInst : public Instruction {
678protected:
679  // Note: Instruction needs to be a friend here to call cloneImpl.
680  friend class Instruction;
681
682  AtomicRMWInst *cloneImpl() const;
683
684public:
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
691    Xchg,
692    /// *p = old + v
693    Add,
694    /// *p = old - v
695    Sub,
696    /// *p = old & v
697    And,
698    /// *p = ~(old & v)
699    Nand,
700    /// *p = old | v
701    Or,
702    /// *p = old ^ v
703    Xor,
704    /// *p = old >signed v ? old : v
705    Max,
706    /// *p = old <signed v ? old : v
707    Min,
708    /// *p = old >unsigned v ? old : v
709    UMax,
710    /// *p = old <unsigned v ? old : v
711    UMin,
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.
754  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
755
756  /// Returns the ordering constraint of this rmw instruction.
757  AtomicOrdering getOrdering() const {
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.
770  SyncScope::ID getSyncScopeID() const {
771    return SSID;
772  }
773
774  /// Sets the synchronization scope ID of this rmw instruction.
775  void setSyncScopeID(SyncScope::ID SSID) {
776    this->SSID = SSID;
777  }
778
779  Value *getPointerOperand() { return getOperand(0); }
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
799private:
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) {
806    Instruction::setInstructionSubclassData(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
815template <>
816struct OperandTraits<AtomicRMWInst>
817    : public FixedNumOperandTraits<AtomicRMWInst,2> {
818};
819
820DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
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//
829inline Type *checkGEPType(Type *Ty) {
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///
837class GetElementPtrInst : public Instruction {
838  Type *SourceElementType;
839  Type *ResultElementType;
840
841  GetElementPtrInst(const GetElementPtrInst &GEPI);
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
856protected:
857  // Note: Instruction needs to be a friend here to call cloneImpl.
858  friend class Instruction;
859
860  GetElementPtrInst *cloneImpl() const;
861
862public:
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.
897  static GetElementPtrInst *CreateInBounds(Value *Ptr,
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) {
908    GetElementPtrInst *GEP =
909        Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
910    GEP->setIsInBounds(true);
911    return GEP;
912  }
913
914  static GetElementPtrInst *CreateInBounds(Value *Ptr,
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) {
925    GetElementPtrInst *GEP =
926        Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
927    GEP->setIsInBounds(true);
928    return GEP;
929  }
930
931  /// Transparently provide more efficient getOperand methods.
932  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
933
934  Type *getSourceElementType() const { return SourceElementType; }
935
936  void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
937  void setResultElementType(Type *Ty) { ResultElementType = Ty; }
938
939  Type *getResultElementType() const {
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
967  inline iterator_range<op_iterator> indices() {
968    return make_range(idx_begin(), idx_end());
969  }
970
971  inline iterator_range<const_op_iterator> indices() const {
972    return make_range(idx_begin(), idx_end());
973  }
974
975  Value *getPointerOperand() {
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.
987  Type *getPointerOperandType() const {
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
1065template <>
1066struct OperandTraits<GetElementPtrInst> :
1067  public VariadicOperandTraits<GetElementPtrInst, 1> {
1068};
1069
1070GetElementPtrInst::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,
1075                  OperandTraits<GetElementPtrInst>::op_end(this) - Values,
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
1084GetElementPtrInst::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,
1089                  OperandTraits<GetElementPtrInst>::op_end(this) - Values,
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
1098DEFINE_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.
1108class 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
1120protected:
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
1127public:
1128  /// Constructor with insert-before-instruction semantics.
1129  ICmpInst(
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.
1144  ICmpInst(
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
1159  ICmpInst(
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
1175  Predicate getSignedPredicate() const {
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
1187  Predicate getUnsignedPredicate() const {
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.
1250class 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
1260protected:
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
1267public:
1268  /// Constructor with insert-before-instruction semantics.
1269  FCmpInst(
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.
1282  FCmpInst(
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
1295  FCmpInst(
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///
1355class CallInst : public Instruction,
1356                 public OperandBundleUser<CallInst, User::op_iterator> {
1357  friend class 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
1404protected:
1405  // Note: Instruction needs to be a friend here to call cloneImpl.
1406  friend class Instruction;
1407
1408  CallInst *cloneImpl() const;
1409
1410public:
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,
1448                          ArrayRef<OperandBundleDef> Bundles,
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,
1517                                 ArrayRef<OperandBundleDef> Bundles,
1518                                 Instruction *InsertBefore);
1519  static Instruction *CreateFree(Value *Source,
1520                                 ArrayRef<OperandBundleDef> Bundles,
1521                                 BasicBlock *InsertAtEnd);
1522
1523  FunctionType *getFunctionType() const { return FTy; }
1524
1525  void mutateFunctionType(FunctionType *FTy) {
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 };
1533  TailCallKind getTailCallKind() const {
1534    return TailCallKind(getSubclassDataFromInstruction() & 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
1555  void setTailCallKind(TailCallKind TCK) {
1556    setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1557                               unsigned(TCK));
1558  }
1559
1560  /// Provide fast operand accessors
1561  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
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.
1581  op_iterator arg_begin() { return op_begin(); }
1582
1583  /// Return the iterator pointing to the end of the argument list.
1584  op_iterator arg_end() {
1585    // [ call args ], [ operand bundles ], callee
1586    return op_end() - getNumTotalBundleOperands() - 1;
1587  }
1588
1589  /// Iteration adapter for range-for loops.
1590  iterator_range<op_iterator> arg_operands() {
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.
1598  const_op_iterator arg_end() const {
1599    // [ call args ], [ operand bundles ], callee
1600    return op_end() - getNumTotalBundleOperands() - 1;
1601  }
1602
1603  /// Iteration adapter for range-for loops.
1604  iterator_range<const_op_iterator> arg_operands() const {
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.
1624  CallingConv::ID getCallingConv() const {
1625    return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1626  }
1627  void setCallingConv(CallingConv::ID CC) {
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  ///
1640  void setAttributes(AttributeList A) { Attrs = A; }
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  /// Determine if the call requires strict floating point semantics.
1761  bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1762
1763  /// Return true if the call should not be inlined.
1764  bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1765  void setIsNoInline() {
1766    addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1767  }
1768
1769  /// Return true if the call can return twice
1770  bool canReturnTwice() const {
1771    return hasFnAttr(Attribute::ReturnsTwice);
1772  }
1773  void setCanReturnTwice() {
1774    addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1775  }
1776
1777  /// Determine if the call does not access memory.
1778  bool doesNotAccessMemory() const {
1779    return hasFnAttr(Attribute::ReadNone);
1780  }
1781  void setDoesNotAccessMemory() {
1782    addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1783  }
1784
1785  /// Determine if the call does not access or only reads memory.
1786  bool onlyReadsMemory() const {
1787    return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1788  }
1789  void setOnlyReadsMemory() {
1790    addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1791  }
1792
1793  /// Determine if the call does not access or only writes memory.
1794  bool doesNotReadMemory() const {
1795    return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1796  }
1797  void setDoesNotReadMemory() {
1798    addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1799  }
1800
1801  /// @brief Determine if the call can access memmory only using pointers based
1802  /// on its arguments.
1803  bool onlyAccessesArgMemory() const {
1804    return hasFnAttr(Attribute::ArgMemOnly);
1805  }
1806  void setOnlyAccessesArgMemory() {
1807    addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1808  }
1809
1810  /// Determine if the call cannot return.
1811  bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1812  void setDoesNotReturn() {
1813    addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1814  }
1815
1816  /// Determine if the call cannot unwind.
1817  bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1818  void setDoesNotThrow() {
1819    addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1820  }
1821
1822  /// Determine if the call cannot be duplicated.
1823  bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1824  void setCannotDuplicate() {
1825    addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1826  }
1827
1828  /// Determine if the call is convergent
1829  bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1830  void setConvergent() {
1831    addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1832  }
1833  void setNotConvergent() {
1834    removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1835  }
1836
1837  /// Determine if the call returns a structure through first
1838  /// pointer argument.
1839  bool hasStructRetAttr() const {
1840    if (getNumArgOperands() == 0)
1841      return false;
1842
1843    // Be friendly and also check the callee.
1844    return paramHasAttr(0, Attribute::StructRet);
1845  }
1846
1847  /// Determine if any call argument is an aggregate passed by value.
1848  bool hasByValArgument() const {
1849    return Attrs.hasAttrSomewhere(Attribute::ByVal);
1850  }
1851
1852  /// Return the function called, or null if this is an
1853  /// indirect function invocation.
1854  ///
1855  Function *getCalledFunction() const {
1856    return dyn_cast<Function>(Op<-1>());
1857  }
1858
1859  /// Get a pointer to the function that is invoked by this
1860  /// instruction.
1861  const Value *getCalledValue() const { return Op<-1>(); }
1862        Value *getCalledValue()       { return Op<-1>(); }
1863
1864  /// Set the function called.
1865  void setCalledFunction(Value* Fn) {
1866    setCalledFunction(
1867        cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1868        Fn);
1869  }
1870  void setCalledFunction(FunctionType *FTy, Value *Fn) {
1871    this->FTy = FTy;
1872    assert(FTy == cast<FunctionType>(
1873                      cast<PointerType>(Fn->getType())->getElementType()));
1874    Op<-1>() = Fn;
1875  }
1876
1877  /// Check if this call is an inline asm statement.
1878  bool isInlineAsm() const {
1879    return isa<InlineAsm>(Op<-1>());
1880  }
1881
1882  // Methods for support type inquiry through isa, cast, and dyn_cast:
1883  static bool classof(const Instruction *I) {
1884    return I->getOpcode() == Instruction::Call;
1885  }
1886  static bool classof(const Value *V) {
1887    return isa<Instruction>(V) && classof(cast<Instruction>(V));
1888  }
1889
1890private:
1891  template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
1892    if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
1893      return true;
1894
1895    // Operand bundles override attributes on the called function, but don't
1896    // override attributes directly present on the call instruction.
1897    if (isFnAttrDisallowedByOpBundle(Kind))
1898      return false;
1899
1900    if (const Function *F = getCalledFunction())
1901      return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
1902                                             Kind);
1903    return false;
1904  }
1905
1906  // Shadow Instruction::setInstructionSubclassData with a private forwarding
1907  // method so that subclasses cannot accidentally use it.
1908  void setInstructionSubclassData(unsigned short D) {
1909    Instruction::setInstructionSubclassData(D);
1910  }
1911};
1912
1913template <>
1914struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1915};
1916
1917CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1918                   ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1919                   BasicBlock *InsertAtEnd)
1920    : Instruction(
1921          cast<FunctionType>(cast<PointerType>(Func->getType())
1922                                 ->getElementType())->getReturnType(),
1923          Instruction::Call, OperandTraits<CallInst>::op_end(this) -
1924                                 (Args.size() + CountBundleInputs(Bundles) + 1),
1925          unsigned(Args.size() + CountBundleInputs(Bundles) + 1), InsertAtEnd) {
1926  init(Func, Args, Bundles, NameStr);
1927}
1928
1929CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1930                   ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1931                   Instruction *InsertBefore)
1932    : Instruction(Ty->getReturnType(), Instruction::Call,
1933                  OperandTraits<CallInst>::op_end(this) -
1934                      (Args.size() + CountBundleInputs(Bundles) + 1),
1935                  unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1936                  InsertBefore) {
1937  init(Ty, Func, Args, Bundles, NameStr);
1938}
1939
1940// Note: if you get compile errors about private methods then
1941//       please update your code to use the high-level operand
1942//       interfaces. See line 943 above.
1943DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
1944
1945//===----------------------------------------------------------------------===//
1946//                               SelectInst Class
1947//===----------------------------------------------------------------------===//
1948
1949/// This class represents the LLVM 'select' instruction.
1950///
1951class SelectInst : public Instruction {
1952  SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1953             Instruction *InsertBefore)
1954    : Instruction(S1->getType(), Instruction::Select,
1955                  &Op<0>(), 3, InsertBefore) {
1956    init(C, S1, S2);
1957    setName(NameStr);
1958  }
1959
1960  SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1961             BasicBlock *InsertAtEnd)
1962    : Instruction(S1->getType(), Instruction::Select,
1963                  &Op<0>(), 3, InsertAtEnd) {
1964    init(C, S1, S2);
1965    setName(NameStr);
1966  }
1967
1968  void init(Value *C, Value *S1, Value *S2) {
1969    assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1970    Op<0>() = C;
1971    Op<1>() = S1;
1972    Op<2>() = S2;
1973  }
1974
1975protected:
1976  // Note: Instruction needs to be a friend here to call cloneImpl.
1977  friend class Instruction;
1978
1979  SelectInst *cloneImpl() const;
1980
1981public:
1982  static SelectInst *Create(Value *C, Value *S1, Value *S2,
1983                            const Twine &NameStr = "",
1984                            Instruction *InsertBefore = nullptr,
1985                            Instruction *MDFrom = nullptr) {
1986    SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1987    if (MDFrom)
1988      Sel->copyMetadata(*MDFrom);
1989    return Sel;
1990  }
1991
1992  static SelectInst *Create(Value *C, Value *S1, Value *S2,
1993                            const Twine &NameStr,
1994                            BasicBlock *InsertAtEnd) {
1995    return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1996  }
1997
1998  const Value *getCondition() const { return Op<0>(); }
1999  const Value *getTrueValue() const { return Op<1>(); }
2000  const Value *getFalseValue() const { return Op<2>(); }
2001  Value *getCondition() { return Op<0>(); }
2002  Value *getTrueValue() { return Op<1>(); }
2003  Value *getFalseValue() { return Op<2>(); }
2004
2005  void setCondition(Value *V) { Op<0>() = V; }
2006  void setTrueValue(Value *V) { Op<1>() = V; }
2007  void setFalseValue(Value *V) { Op<2>() = V; }
2008
2009  /// Return a string if the specified operands are invalid
2010  /// for a select operation, otherwise return null.
2011  static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
2012
2013  /// Transparently provide more efficient getOperand methods.
2014  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2015
2016  OtherOps getOpcode() const {
2017    return static_cast<OtherOps>(Instruction::getOpcode());
2018  }
2019
2020  // Methods for support type inquiry through isa, cast, and dyn_cast:
2021  static bool classof(const Instruction *I) {
2022    return I->getOpcode() == Instruction::Select;
2023  }
2024  static bool classof(const Value *V) {
2025    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2026  }
2027};
2028
2029template <>
2030struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
2031};
2032
2033DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
2034
2035//===----------------------------------------------------------------------===//
2036//                                VAArgInst Class
2037//===----------------------------------------------------------------------===//
2038
2039/// This class represents the va_arg llvm instruction, which returns
2040/// an argument of the specified type given a va_list and increments that list
2041///
2042class VAArgInst : public UnaryInstruction {
2043protected:
2044  // Note: Instruction needs to be a friend here to call cloneImpl.
2045  friend class Instruction;
2046
2047  VAArgInst *cloneImpl() const;
2048
2049public:
2050  VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
2051             Instruction *InsertBefore = nullptr)
2052    : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
2053    setName(NameStr);
2054  }
2055
2056  VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
2057            BasicBlock *InsertAtEnd)
2058    : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
2059    setName(NameStr);
2060  }
2061
2062  Value *getPointerOperand() { return getOperand(0); }
2063  const Value *getPointerOperand() const { return getOperand(0); }
2064  static unsigned getPointerOperandIndex() { return 0U; }
2065
2066  // Methods for support type inquiry through isa, cast, and dyn_cast:
2067  static bool classof(const Instruction *I) {
2068    return I->getOpcode() == VAArg;
2069  }
2070  static bool classof(const Value *V) {
2071    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2072  }
2073};
2074
2075//===----------------------------------------------------------------------===//
2076//                                ExtractElementInst Class
2077//===----------------------------------------------------------------------===//
2078
2079/// This instruction extracts a single (scalar)
2080/// element from a VectorType value
2081///
2082class ExtractElementInst : public Instruction {
2083  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
2084                     Instruction *InsertBefore = nullptr);
2085  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
2086                     BasicBlock *InsertAtEnd);
2087
2088protected:
2089  // Note: Instruction needs to be a friend here to call cloneImpl.
2090  friend class Instruction;
2091
2092  ExtractElementInst *cloneImpl() const;
2093
2094public:
2095  static ExtractElementInst *Create(Value *Vec, Value *Idx,
2096                                   const Twine &NameStr = "",
2097                                   Instruction *InsertBefore = nullptr) {
2098    return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
2099  }
2100
2101  static ExtractElementInst *Create(Value *Vec, Value *Idx,
2102                                   const Twine &NameStr,
2103                                   BasicBlock *InsertAtEnd) {
2104    return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
2105  }
2106
2107  /// Return true if an extractelement instruction can be
2108  /// formed with the specified operands.
2109  static bool isValidOperands(const Value *Vec, const Value *Idx);
2110
2111  Value *getVectorOperand() { return Op<0>(); }
2112  Value *getIndexOperand() { return Op<1>(); }
2113  const Value *getVectorOperand() const { return Op<0>(); }
2114  const Value *getIndexOperand() const { return Op<1>(); }
2115
2116  VectorType *getVectorOperandType() const {
2117    return cast<VectorType>(getVectorOperand()->getType());
2118  }
2119
2120  /// Transparently provide more efficient getOperand methods.
2121  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2122
2123  // Methods for support type inquiry through isa, cast, and dyn_cast:
2124  static bool classof(const Instruction *I) {
2125    return I->getOpcode() == Instruction::ExtractElement;
2126  }
2127  static bool classof(const Value *V) {
2128    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2129  }
2130};
2131
2132template <>
2133struct OperandTraits<ExtractElementInst> :
2134  public FixedNumOperandTraits<ExtractElementInst, 2> {
2135};
2136
2137DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
2138
2139//===----------------------------------------------------------------------===//
2140//                                InsertElementInst Class
2141//===----------------------------------------------------------------------===//
2142
2143/// This instruction inserts a single (scalar)
2144/// element into a VectorType value
2145///
2146class InsertElementInst : public Instruction {
2147  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
2148                    const Twine &NameStr = "",
2149                    Instruction *InsertBefore = nullptr);
2150  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
2151                    BasicBlock *InsertAtEnd);
2152
2153protected:
2154  // Note: Instruction needs to be a friend here to call cloneImpl.
2155  friend class Instruction;
2156
2157  InsertElementInst *cloneImpl() const;
2158
2159public:
2160  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2161                                   const Twine &NameStr = "",
2162                                   Instruction *InsertBefore = nullptr) {
2163    return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
2164  }
2165
2166  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2167                                   const Twine &NameStr,
2168                                   BasicBlock *InsertAtEnd) {
2169    return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
2170  }
2171
2172  /// Return true if an insertelement instruction can be
2173  /// formed with the specified operands.
2174  static bool isValidOperands(const Value *Vec, const Value *NewElt,
2175                              const Value *Idx);
2176
2177  /// Overload to return most specific vector type.
2178  ///
2179  VectorType *getType() const {
2180    return cast<VectorType>(Instruction::getType());
2181  }
2182
2183  /// Transparently provide more efficient getOperand methods.
2184  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2185
2186  // Methods for support type inquiry through isa, cast, and dyn_cast:
2187  static bool classof(const Instruction *I) {
2188    return I->getOpcode() == Instruction::InsertElement;
2189  }
2190  static bool classof(const Value *V) {
2191    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2192  }
2193};
2194
2195template <>
2196struct OperandTraits<InsertElementInst> :
2197  public FixedNumOperandTraits<InsertElementInst, 3> {
2198};
2199
2200DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2201
2202//===----------------------------------------------------------------------===//
2203//                           ShuffleVectorInst Class
2204//===----------------------------------------------------------------------===//
2205
2206/// This instruction constructs a fixed permutation of two
2207/// input vectors.
2208///
2209class ShuffleVectorInst : public Instruction {
2210protected:
2211  // Note: Instruction needs to be a friend here to call cloneImpl.
2212  friend class Instruction;
2213
2214  ShuffleVectorInst *cloneImpl() const;
2215
2216public:
2217  ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2218                    const Twine &NameStr = "",
2219                    Instruction *InsertBefor = nullptr);
2220  ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2221                    const Twine &NameStr, BasicBlock *InsertAtEnd);
2222
2223  // allocate space for exactly three operands
2224  void *operator new(size_t s) {
2225    return User::operator new(s, 3);
2226  }
2227
2228  /// Return true if a shufflevector instruction can be
2229  /// formed with the specified operands.
2230  static bool isValidOperands(const Value *V1, const Value *V2,
2231                              const Value *Mask);
2232
2233  /// Overload to return most specific vector type.
2234  ///
2235  VectorType *getType() const {
2236    return cast<VectorType>(Instruction::getType());
2237  }
2238
2239  /// Transparently provide more efficient getOperand methods.
2240  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2241
2242  Constant *getMask() const {
2243    return cast<Constant>(getOperand(2));
2244  }
2245
2246  /// Return the shuffle mask value for the specified element of the mask.
2247  /// Return -1 if the element is undef.
2248  static int getMaskValue(Constant *Mask, unsigned Elt);
2249
2250  /// Return the shuffle mask value of this instruction for the given element
2251  /// index. Return -1 if the element is undef.
2252  int getMaskValue(unsigned Elt) const {
2253    return getMaskValue(getMask(), Elt);
2254  }
2255
2256  /// Convert the input shuffle mask operand to a vector of integers. Undefined
2257  /// elements of the mask are returned as -1.
2258  static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
2259
2260  /// Return the mask for this instruction as a vector of integers. Undefined
2261  /// elements of the mask are returned as -1.
2262  void getShuffleMask(SmallVectorImpl<int> &Result) const {
2263    return getShuffleMask(getMask(), Result);
2264  }
2265
2266  SmallVector<int, 16> getShuffleMask() const {
2267    SmallVector<int, 16> Mask;
2268    getShuffleMask(Mask);
2269    return Mask;
2270  }
2271
2272  /// Change values in a shuffle permute mask assuming the two vector operands
2273  /// of length InVecNumElts have swapped position.
2274  static void commuteShuffleMask(MutableArrayRef<int> Mask,
2275                                 unsigned InVecNumElts) {
2276    for (int &Idx : Mask) {
2277      if (Idx == -1)
2278        continue;
2279      Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2280      assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2281             "shufflevector mask index out of range");
2282    }
2283  }
2284
2285  // Methods for support type inquiry through isa, cast, and dyn_cast:
2286  static bool classof(const Instruction *I) {
2287    return I->getOpcode() == Instruction::ShuffleVector;
2288  }
2289  static bool classof(const Value *V) {
2290    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2291  }
2292};
2293
2294template <>
2295struct OperandTraits<ShuffleVectorInst> :
2296  public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2297};
2298
2299DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2300
2301//===----------------------------------------------------------------------===//
2302//                                ExtractValueInst Class
2303//===----------------------------------------------------------------------===//
2304
2305/// This instruction extracts a struct member or array
2306/// element value from an aggregate value.
2307///
2308class ExtractValueInst : public UnaryInstruction {
2309  SmallVector<unsigned, 4> Indices;
2310
2311  ExtractValueInst(const ExtractValueInst &EVI);
2312
2313  /// Constructors - Create a extractvalue instruction with a base aggregate
2314  /// value and a list of indices.  The first ctor can optionally insert before
2315  /// an existing instruction, the second appends the new instruction to the
2316  /// specified BasicBlock.
2317  inline ExtractValueInst(Value *Agg,
2318                          ArrayRef<unsigned> Idxs,
2319                          const Twine &NameStr,
2320                          Instruction *InsertBefore);
2321  inline ExtractValueInst(Value *Agg,
2322                          ArrayRef<unsigned> Idxs,
2323                          const Twine &NameStr, BasicBlock *InsertAtEnd);
2324
2325  void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2326
2327protected:
2328  // Note: Instruction needs to be a friend here to call cloneImpl.
2329  friend class Instruction;
2330
2331  ExtractValueInst *cloneImpl() const;
2332
2333public:
2334  static ExtractValueInst *Create(Value *Agg,
2335                                  ArrayRef<unsigned> Idxs,
2336                                  const Twine &NameStr = "",
2337                                  Instruction *InsertBefore = nullptr) {
2338    return new
2339      ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2340  }
2341
2342  static ExtractValueInst *Create(Value *Agg,
2343                                  ArrayRef<unsigned> Idxs,
2344                                  const Twine &NameStr,
2345                                  BasicBlock *InsertAtEnd) {
2346    return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2347  }
2348
2349  /// Returns the type of the element that would be extracted
2350  /// with an extractvalue instruction with the specified parameters.
2351  ///
2352  /// Null is returned if the indices are invalid for the specified type.
2353  static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2354
2355  using idx_iterator = const unsigned*;
2356
2357  inline idx_iterator idx_begin() const { return Indices.begin(); }
2358  inline idx_iterator idx_end()   const { return Indices.end(); }
2359  inline iterator_range<idx_iterator> indices() const {
2360    return make_range(idx_begin(), idx_end());
2361  }
2362
2363  Value *getAggregateOperand() {
2364    return getOperand(0);
2365  }
2366  const Value *getAggregateOperand() const {
2367    return getOperand(0);
2368  }
2369  static unsigned getAggregateOperandIndex() {
2370    return 0U;                      // get index for modifying correct operand
2371  }
2372
2373  ArrayRef<unsigned> getIndices() const {
2374    return Indices;
2375  }
2376
2377  unsigned getNumIndices() const {
2378    return (unsigned)Indices.size();
2379  }
2380
2381  bool hasIndices() const {
2382    return true;
2383  }
2384
2385  // Methods for support type inquiry through isa, cast, and dyn_cast:
2386  static bool classof(const Instruction *I) {
2387    return I->getOpcode() == Instruction::ExtractValue;
2388  }
2389  static bool classof(const Value *V) {
2390    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2391  }
2392};
2393
2394ExtractValueInst::ExtractValueInst(Value *Agg,
2395                                   ArrayRef<unsigned> Idxs,
2396                                   const Twine &NameStr,
2397                                   Instruction *InsertBefore)
2398  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2399                     ExtractValue, Agg, InsertBefore) {
2400  init(Idxs, NameStr);
2401}
2402
2403ExtractValueInst::ExtractValueInst(Value *Agg,
2404                                   ArrayRef<unsigned> Idxs,
2405                                   const Twine &NameStr,
2406                                   BasicBlock *InsertAtEnd)
2407  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2408                     ExtractValue, Agg, InsertAtEnd) {
2409  init(Idxs, NameStr);
2410}
2411
2412//===----------------------------------------------------------------------===//
2413//                                InsertValueInst Class
2414//===----------------------------------------------------------------------===//
2415
2416/// This instruction inserts a struct field of array element
2417/// value into an aggregate value.
2418///
2419class InsertValueInst : public Instruction {
2420  SmallVector<unsigned, 4> Indices;
2421
2422  InsertValueInst(const InsertValueInst &IVI);
2423
2424  /// Constructors - Create a insertvalue instruction with a base aggregate
2425  /// value, a value to insert, and a list of indices.  The first ctor can
2426  /// optionally insert before an existing instruction, the second appends
2427  /// the new instruction to the specified BasicBlock.
2428  inline InsertValueInst(Value *Agg, Value *Val,
2429                         ArrayRef<unsigned> Idxs,
2430                         const Twine &NameStr,
2431                         Instruction *InsertBefore);
2432  inline InsertValueInst(Value *Agg, Value *Val,
2433                         ArrayRef<unsigned> Idxs,
2434                         const Twine &NameStr, BasicBlock *InsertAtEnd);
2435
2436  /// Constructors - These two constructors are convenience methods because one
2437  /// and two index insertvalue instructions are so common.
2438  InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2439                  const Twine &NameStr = "",
2440                  Instruction *InsertBefore = nullptr);
2441  InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2442                  BasicBlock *InsertAtEnd);
2443
2444  void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2445            const Twine &NameStr);
2446
2447protected:
2448  // Note: Instruction needs to be a friend here to call cloneImpl.
2449  friend class Instruction;
2450
2451  InsertValueInst *cloneImpl() const;
2452
2453public:
2454  // allocate space for exactly two operands
2455  void *operator new(size_t s) {
2456    return User::operator new(s, 2);
2457  }
2458
2459  static InsertValueInst *Create(Value *Agg, Value *Val,
2460                                 ArrayRef<unsigned> Idxs,
2461                                 const Twine &NameStr = "",
2462                                 Instruction *InsertBefore = nullptr) {
2463    return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2464  }
2465
2466  static InsertValueInst *Create(Value *Agg, Value *Val,
2467                                 ArrayRef<unsigned> Idxs,
2468                                 const Twine &NameStr,
2469                                 BasicBlock *InsertAtEnd) {
2470    return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2471  }
2472
2473  /// Transparently provide more efficient getOperand methods.
2474  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2475
2476  using idx_iterator = const unsigned*;
2477
2478  inline idx_iterator idx_begin() const { return Indices.begin(); }
2479  inline idx_iterator idx_end()   const { return Indices.end(); }
2480  inline iterator_range<idx_iterator> indices() const {
2481    return make_range(idx_begin(), idx_end());
2482  }
2483
2484  Value *getAggregateOperand() {
2485    return getOperand(0);
2486  }
2487  const Value *getAggregateOperand() const {
2488    return getOperand(0);
2489  }
2490  static unsigned getAggregateOperandIndex() {
2491    return 0U;                      // get index for modifying correct operand
2492  }
2493
2494  Value *getInsertedValueOperand() {
2495    return getOperand(1);
2496  }
2497  const Value *getInsertedValueOperand() const {
2498    return getOperand(1);
2499  }
2500  static unsigned getInsertedValueOperandIndex() {
2501    return 1U;                      // get index for modifying correct operand
2502  }
2503
2504  ArrayRef<unsigned> getIndices() const {
2505    return Indices;
2506  }
2507
2508  unsigned getNumIndices() const {
2509    return (unsigned)Indices.size();
2510  }
2511
2512  bool hasIndices() const {
2513    return true;
2514  }
2515
2516  // Methods for support type inquiry through isa, cast, and dyn_cast:
2517  static bool classof(const Instruction *I) {
2518    return I->getOpcode() == Instruction::InsertValue;
2519  }
2520  static bool classof(const Value *V) {
2521    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2522  }
2523};
2524
2525template <>
2526struct OperandTraits<InsertValueInst> :
2527  public FixedNumOperandTraits<InsertValueInst, 2> {
2528};
2529
2530InsertValueInst::InsertValueInst(Value *Agg,
2531                                 Value *Val,
2532                                 ArrayRef<unsigned> Idxs,
2533                                 const Twine &NameStr,
2534                                 Instruction *InsertBefore)
2535  : Instruction(Agg->getType(), InsertValue,
2536                OperandTraits<InsertValueInst>::op_begin(this),
2537                2, InsertBefore) {
2538  init(Agg, Val, Idxs, NameStr);
2539}
2540
2541InsertValueInst::InsertValueInst(Value *Agg,
2542                                 Value *Val,
2543                                 ArrayRef<unsigned> Idxs,
2544                                 const Twine &NameStr,
2545                                 BasicBlock *InsertAtEnd)
2546  : Instruction(Agg->getType(), InsertValue,
2547                OperandTraits<InsertValueInst>::op_begin(this),
2548                2, InsertAtEnd) {
2549  init(Agg, Val, Idxs, NameStr);
2550}
2551
2552DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2553
2554//===----------------------------------------------------------------------===//
2555//                               PHINode Class
2556//===----------------------------------------------------------------------===//
2557
2558// PHINode - The PHINode class is used to represent the magical mystical PHI
2559// node, that can not exist in nature, but can be synthesized in a computer
2560// scientist's overactive imagination.
2561//
2562class PHINode : public Instruction {
2563  /// The number of operands actually allocated.  NumOperands is
2564  /// the number actually in use.
2565  unsigned ReservedSpace;
2566
2567  PHINode(const PHINode &PN);
2568
2569  explicit PHINode(Type *Ty, unsigned NumReservedValues,
2570                   const Twine &NameStr = "",
2571                   Instruction *InsertBefore = nullptr)
2572    : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2573      ReservedSpace(NumReservedValues) {
2574    setName(NameStr);
2575    allocHungoffUses(ReservedSpace);
2576  }
2577
2578  PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2579          BasicBlock *InsertAtEnd)
2580    : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2581      ReservedSpace(NumReservedValues) {
2582    setName(NameStr);
2583    allocHungoffUses(ReservedSpace);
2584  }
2585
2586protected:
2587  // Note: Instruction needs to be a friend here to call cloneImpl.
2588  friend class Instruction;
2589
2590  PHINode *cloneImpl() const;
2591
2592  // allocHungoffUses - this is more complicated than the generic
2593  // User::allocHungoffUses, because we have to allocate Uses for the incoming
2594  // values and pointers to the incoming blocks, all in one allocation.
2595  void allocHungoffUses(unsigned N) {
2596    User::allocHungoffUses(N, /* IsPhi */ true);
2597  }
2598
2599public:
2600  /// Constructors - NumReservedValues is a hint for the number of incoming
2601  /// edges that this phi node will have (use 0 if you really have no idea).
2602  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2603                         const Twine &NameStr = "",
2604                         Instruction *InsertBefore = nullptr) {
2605    return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2606  }
2607
2608  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2609                         const Twine &NameStr, BasicBlock *InsertAtEnd) {
2610    return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2611  }
2612
2613  /// Provide fast operand accessors
2614  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2615
2616  // Block iterator interface. This provides access to the list of incoming
2617  // basic blocks, which parallels the list of incoming values.
2618
2619  using block_iterator = BasicBlock **;
2620  using const_block_iterator = BasicBlock * const *;
2621
2622  block_iterator block_begin() {
2623    Use::UserRef *ref =
2624      reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2625    return reinterpret_cast<block_iterator>(ref + 1);
2626  }
2627
2628  const_block_iterator block_begin() const {
2629    const Use::UserRef *ref =
2630      reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2631    return reinterpret_cast<const_block_iterator>(ref + 1);
2632  }
2633
2634  block_iterator block_end() {
2635    return block_begin() + getNumOperands();
2636  }
2637
2638  const_block_iterator block_end() const {
2639    return block_begin() + getNumOperands();
2640  }
2641
2642  iterator_range<block_iterator> blocks() {
2643    return make_range(block_begin(), block_end());
2644  }
2645
2646  iterator_range<const_block_iterator> blocks() const {
2647    return make_range(block_begin(), block_end());
2648  }
2649
2650  op_range incoming_values() { return operands(); }
2651
2652  const_op_range incoming_values() const { return operands(); }
2653
2654  /// Return the number of incoming edges
2655  ///
2656  unsigned getNumIncomingValues() const { return getNumOperands(); }
2657
2658  /// Return incoming value number x
2659  ///
2660  Value *getIncomingValue(unsigned i) const {
2661    return getOperand(i);
2662  }
2663  void setIncomingValue(unsigned i, Value *V) {
2664    assert(V && "PHI node got a null value!");
2665    assert(getType() == V->getType() &&
2666           "All operands to PHI node must be the same type as the PHI node!");
2667    setOperand(i, V);
2668  }
2669
2670  static unsigned getOperandNumForIncomingValue(unsigned i) {
2671    return i;
2672  }
2673
2674  static unsigned getIncomingValueNumForOperand(unsigned i) {
2675    return i;
2676  }
2677
2678  /// Return incoming basic block number @p i.
2679  ///
2680  BasicBlock *getIncomingBlock(unsigned i) const {
2681    return block_begin()[i];
2682  }
2683
2684  /// Return incoming basic block corresponding
2685  /// to an operand of the PHI.
2686  ///
2687  BasicBlock *getIncomingBlock(const Use &U) const {
2688    assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2689    return getIncomingBlock(unsigned(&U - op_begin()));
2690  }
2691
2692  /// Return incoming basic block corresponding
2693  /// to value use iterator.
2694  ///
2695  BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2696    return getIncomingBlock(I.getUse());
2697  }
2698
2699  void setIncomingBlock(unsigned i, BasicBlock *BB) {
2700    assert(BB && "PHI node got a null basic block!");
2701    block_begin()[i] = BB;
2702  }
2703
2704  /// Add an incoming value to the end of the PHI list
2705  ///
2706  void addIncoming(Value *V, BasicBlock *BB) {
2707    if (getNumOperands() == ReservedSpace)
2708      growOperands();  // Get more space!
2709    // Initialize some new operands.
2710    setNumHungOffUseOperands(getNumOperands() + 1);
2711    setIncomingValue(getNumOperands() - 1, V);
2712    setIncomingBlock(getNumOperands() - 1, BB);
2713  }
2714
2715  /// Remove an incoming value.  This is useful if a
2716  /// predecessor basic block is deleted.  The value removed is returned.
2717  ///
2718  /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2719  /// is true), the PHI node is destroyed and any uses of it are replaced with
2720  /// dummy values.  The only time there should be zero incoming values to a PHI
2721  /// node is when the block is dead, so this strategy is sound.
2722  ///
2723  Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2724
2725  Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2726    int Idx = getBasicBlockIndex(BB);
2727    assert(Idx >= 0 && "Invalid basic block argument to remove!");
2728    return removeIncomingValue(Idx, DeletePHIIfEmpty);
2729  }
2730
2731  /// Return the first index of the specified basic
2732  /// block in the value list for this PHI.  Returns -1 if no instance.
2733  ///
2734  int getBasicBlockIndex(const BasicBlock *BB) const {
2735    for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2736      if (block_begin()[i] == BB)
2737        return i;
2738    return -1;
2739  }
2740
2741  Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2742    int Idx = getBasicBlockIndex(BB);
2743    assert(Idx >= 0 && "Invalid basic block argument!");
2744    return getIncomingValue(Idx);
2745  }
2746
2747  /// If the specified PHI node always merges together the
2748  /// same value, return the value, otherwise return null.
2749  Value *hasConstantValue() const;
2750
2751  /// Whether the specified PHI node always merges
2752  /// together the same value, assuming undefs are equal to a unique
2753  /// non-undef value.
2754  bool hasConstantOrUndefValue() const;
2755
2756  /// Methods for support type inquiry through isa, cast, and dyn_cast:
2757  static bool classof(const Instruction *I) {
2758    return I->getOpcode() == Instruction::PHI;
2759  }
2760  static bool classof(const Value *V) {
2761    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2762  }
2763
2764private:
2765  void growOperands();
2766};
2767
2768template <>
2769struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2770};
2771
2772DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2773
2774//===----------------------------------------------------------------------===//
2775//                           LandingPadInst Class
2776//===----------------------------------------------------------------------===//
2777
2778//===---------------------------------------------------------------------------
2779/// The landingpad instruction holds all of the information
2780/// necessary to generate correct exception handling. The landingpad instruction
2781/// cannot be moved from the top of a landing pad block, which itself is
2782/// accessible only from the 'unwind' edge of an invoke. This uses the
2783/// SubclassData field in Value to store whether or not the landingpad is a
2784/// cleanup.
2785///
2786class LandingPadInst : public Instruction {
2787  /// The number of operands actually allocated.  NumOperands is
2788  /// the number actually in use.
2789  unsigned ReservedSpace;
2790
2791  LandingPadInst(const LandingPadInst &LP);
2792
2793public:
2794  enum ClauseType { Catch, Filter };
2795
2796private:
2797  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2798                          const Twine &NameStr, Instruction *InsertBefore);
2799  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2800                          const Twine &NameStr, BasicBlock *InsertAtEnd);
2801
2802  // Allocate space for exactly zero operands.
2803  void *operator new(size_t s) {
2804    return User::operator new(s);
2805  }
2806
2807  void growOperands(unsigned Size);
2808  void init(unsigned NumReservedValues, const Twine &NameStr);
2809
2810protected:
2811  // Note: Instruction needs to be a friend here to call cloneImpl.
2812  friend class Instruction;
2813
2814  LandingPadInst *cloneImpl() const;
2815
2816public:
2817  /// Constructors - NumReservedClauses is a hint for the number of incoming
2818  /// clauses that this landingpad will have (use 0 if you really have no idea).
2819  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2820                                const Twine &NameStr = "",
2821                                Instruction *InsertBefore = nullptr);
2822  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2823                                const Twine &NameStr, BasicBlock *InsertAtEnd);
2824
2825  /// Provide fast operand accessors
2826  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2827
2828  /// Return 'true' if this landingpad instruction is a
2829  /// cleanup. I.e., it should be run when unwinding even if its landing pad
2830  /// doesn't catch the exception.
2831  bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2832
2833  /// Indicate that this landingpad instruction is a cleanup.
2834  void setCleanup(bool V) {
2835    setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2836                               (V ? 1 : 0));
2837  }
2838
2839  /// Add a catch or filter clause to the landing pad.
2840  void addClause(Constant *ClauseVal);
2841
2842  /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2843  /// determine what type of clause this is.
2844  Constant *getClause(unsigned Idx) const {
2845    return cast<Constant>(getOperandList()[Idx]);
2846  }
2847
2848  /// Return 'true' if the clause and index Idx is a catch clause.
2849  bool isCatch(unsigned Idx) const {
2850    return !isa<ArrayType>(getOperandList()[Idx]->getType());
2851  }
2852
2853  /// Return 'true' if the clause and index Idx is a filter clause.
2854  bool isFilter(unsigned Idx) const {
2855    return isa<ArrayType>(getOperandList()[Idx]->getType());
2856  }
2857
2858  /// Get the number of clauses for this landing pad.
2859  unsigned getNumClauses() const { return getNumOperands(); }
2860
2861  /// Grow the size of the operand list to accommodate the new
2862  /// number of clauses.
2863  void reserveClauses(unsigned Size) { growOperands(Size); }
2864
2865  // Methods for support type inquiry through isa, cast, and dyn_cast:
2866  static bool classof(const Instruction *I) {
2867    return I->getOpcode() == Instruction::LandingPad;
2868  }
2869  static bool classof(const Value *V) {
2870    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2871  }
2872};
2873
2874template <>
2875struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2876};
2877
2878DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2879
2880//===----------------------------------------------------------------------===//
2881//                               ReturnInst Class
2882//===----------------------------------------------------------------------===//
2883
2884//===---------------------------------------------------------------------------
2885/// Return a value (possibly void), from a function.  Execution
2886/// does not continue in this function any longer.
2887///
2888class ReturnInst : public TerminatorInst {
2889  ReturnInst(const ReturnInst &RI);
2890
2891private:
2892  // ReturnInst constructors:
2893  // ReturnInst()                  - 'ret void' instruction
2894  // ReturnInst(    null)          - 'ret void' instruction
2895  // ReturnInst(Value* X)          - 'ret X'    instruction
2896  // ReturnInst(    null, Inst *I) - 'ret void' instruction, insert before I
2897  // ReturnInst(Value* X, Inst *I) - 'ret X'    instruction, insert before I
2898  // ReturnInst(    null, BB *B)   - 'ret void' instruction, insert @ end of B
2899  // ReturnInst(Value* X, BB *B)   - 'ret X'    instruction, insert @ end of B
2900  //
2901  // NOTE: If the Value* passed is of type void then the constructor behaves as
2902  // if it was passed NULL.
2903  explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2904                      Instruction *InsertBefore = nullptr);
2905  ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2906  explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2907
2908protected:
2909  // Note: Instruction needs to be a friend here to call cloneImpl.
2910  friend class Instruction;
2911
2912  ReturnInst *cloneImpl() const;
2913
2914public:
2915  static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2916                            Instruction *InsertBefore = nullptr) {
2917    return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2918  }
2919
2920  static ReturnInst* Create(LLVMContext &C, Value *retVal,
2921                            BasicBlock *InsertAtEnd) {
2922    return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2923  }
2924
2925  static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2926    return new(0) ReturnInst(C, InsertAtEnd);
2927  }
2928
2929  /// Provide fast operand accessors
2930  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2931
2932  /// Convenience accessor. Returns null if there is no return value.
2933  Value *getReturnValue() const {
2934    return getNumOperands() != 0 ? getOperand(0) : nullptr;
2935  }
2936
2937  unsigned getNumSuccessors() const { return 0; }
2938
2939  // Methods for support type inquiry through isa, cast, and dyn_cast:
2940  static bool classof(const Instruction *I) {
2941    return (I->getOpcode() == Instruction::Ret);
2942  }
2943  static bool classof(const Value *V) {
2944    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2945  }
2946
2947private:
2948  friend TerminatorInst;
2949
2950  BasicBlock *getSuccessor(unsigned idx) const {
2951    llvm_unreachable("ReturnInst has no successors!");
2952  }
2953
2954  void setSuccessor(unsigned idx, BasicBlock *B) {
2955    llvm_unreachable("ReturnInst has no successors!");
2956  }
2957};
2958
2959template <>
2960struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2961};
2962
2963DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2964
2965//===----------------------------------------------------------------------===//
2966//                               BranchInst Class
2967//===----------------------------------------------------------------------===//
2968
2969//===---------------------------------------------------------------------------
2970/// Conditional or Unconditional Branch instruction.
2971///
2972class BranchInst : public TerminatorInst {
2973  /// Ops list - Branches are strange.  The operands are ordered:
2974  ///  [Cond, FalseDest,] TrueDest.  This makes some accessors faster because
2975  /// they don't have to check for cond/uncond branchness. These are mostly
2976  /// accessed relative from op_end().
2977  BranchInst(const BranchInst &BI);
2978  // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2979  // BranchInst(BB *B)                           - 'br B'
2980  // BranchInst(BB* T, BB *F, Value *C)          - 'br C, T, F'
2981  // BranchInst(BB* B, Inst *I)                  - 'br B'        insert before I
2982  // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2983  // BranchInst(BB* B, BB *I)                    - 'br B'        insert at end
2984  // BranchInst(BB* T, BB *F, Value *C, BB *I)   - 'br C, T, F', insert at end
2985  explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2986  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2987             Instruction *InsertBefore = nullptr);
2988  BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2989  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2990             BasicBlock *InsertAtEnd);
2991
2992  void AssertOK();
2993
2994protected:
2995  // Note: Instruction needs to be a friend here to call cloneImpl.
2996  friend class Instruction;
2997
2998  BranchInst *cloneImpl() const;
2999
3000public:
3001  static BranchInst *Create(BasicBlock *IfTrue,
3002                            Instruction *InsertBefore = nullptr) {
3003    return new(1) BranchInst(IfTrue, InsertBefore);
3004  }
3005
3006  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3007                            Value *Cond, Instruction *InsertBefore = nullptr) {
3008    return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3009  }
3010
3011  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3012    return new(1) BranchInst(IfTrue, InsertAtEnd);
3013  }
3014
3015  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3016                            Value *Cond, BasicBlock *InsertAtEnd) {
3017    return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3018  }
3019
3020  /// Transparently provide more efficient getOperand methods.
3021  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3022
3023  bool isUnconditional() const { return getNumOperands() == 1; }
3024  bool isConditional()   const { return getNumOperands() == 3; }
3025
3026  Value *getCondition() const {
3027    assert(isConditional() && "Cannot get condition of an uncond branch!");
3028    return Op<-3>();
3029  }
3030
3031  void setCondition(Value *V) {
3032    assert(isConditional() && "Cannot set condition of unconditional branch!");
3033    Op<-3>() = V;
3034  }
3035
3036  unsigned getNumSuccessors() const { return 1+isConditional(); }
3037
3038  BasicBlock *getSuccessor(unsigned i) const {
3039    assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3040    return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3041  }
3042
3043  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3044    assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3045    *(&Op<-1>() - idx) = NewSucc;
3046  }
3047
3048  /// Swap the successors of this branch instruction.
3049  ///
3050  /// Swaps the successors of the branch instruction. This also swaps any
3051  /// branch weight metadata associated with the instruction so that it
3052  /// continues to map correctly to each operand.
3053  void swapSuccessors();
3054
3055  // Methods for support type inquiry through isa, cast, and dyn_cast:
3056  static bool classof(const Instruction *I) {
3057    return (I->getOpcode() == Instruction::Br);
3058  }
3059  static bool classof(const Value *V) {
3060    return isa<Instruction>(V) && classof(cast<Instruction>(V));
3061  }
3062};
3063
3064template <>
3065struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3066};
3067
3068DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
3069
3070//===----------------------------------------------------------------------===//
3071//                               SwitchInst Class
3072//===----------------------------------------------------------------------===//
3073
3074//===---------------------------------------------------------------------------
3075/// Multiway switch
3076///
3077class SwitchInst : public TerminatorInst {
3078  unsigned ReservedSpace;
3079
3080  // Operand[0]    = Value to switch on
3081  // Operand[1]    = Default basic block destination
3082  // Operand[2n  ] = Value to match
3083  // Operand[2n+1] = BasicBlock to go to on match
3084  SwitchInst(const SwitchInst &SI);
3085
3086  /// Create a new switch instruction, specifying a value to switch on and a
3087  /// default destination. The number of additional cases can be specified here
3088  /// to make memory allocation more efficient. This constructor can also
3089  /// auto-insert before another instruction.
3090  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3091             Instruction *InsertBefore);
3092
3093  /// Create a new switch instruction, specifying a value to switch on and a
3094  /// default destination. The number of additional cases can be specified here
3095  /// to make memory allocation more efficient. This constructor also
3096  /// auto-inserts at the end of the specified BasicBlock.
3097  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3098             BasicBlock *InsertAtEnd);
3099
3100  // allocate space for exactly zero operands
3101  void *operator new(size_t s) {
3102    return User::operator new(s);
3103  }
3104
3105  void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3106  void growOperands();
3107
3108protected:
3109  // Note: Instruction needs to be a friend here to call cloneImpl.
3110  friend class Instruction;
3111
3112  SwitchInst *cloneImpl() const;
3113
3114public:
3115  // -2
3116  static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3117
3118  template <typename CaseHandleT> class CaseIteratorImpl;
3119
3120  /// A handle to a particular switch case. It exposes a convenient interface
3121  /// to both the case value and the successor block.
3122  ///
3123  /// We define this as a template and instantiate it to form both a const and
3124  /// non-const handle.
3125  template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3126  class CaseHandleImpl {
3127    // Directly befriend both const and non-const iterators.
3128    friend class SwitchInst::CaseIteratorImpl<
3129        CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3130
3131  protected:
3132    // Expose the switch type we're parameterized with to the iterator.
3133    using SwitchInstType = SwitchInstT;
3134
3135    SwitchInstT *SI;
3136    ptrdiff_t Index;
3137
3138    CaseHandleImpl() = default;
3139    CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3140
3141  public:
3142    /// Resolves case value for current case.
3143    ConstantIntT *getCaseValue() const {
3144      assert((unsigned)Index < SI->getNumCases() &&
3145             "Index out the number of cases.");
3146      return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3147    }
3148
3149    /// Resolves successor for current case.
3150    BasicBlockT *getCaseSuccessor() const {
3151      assert(((unsigned)Index < SI->getNumCases() ||
3152              (unsigned)Index == DefaultPseudoIndex) &&
3153             "Index out the number of cases.");
3154      return SI->getSuccessor(getSuccessorIndex());
3155    }
3156
3157    /// Returns number of current case.
3158    unsigned getCaseIndex() const { return Index; }
3159
3160    /// Returns TerminatorInst's successor index for current case successor.
3161    unsigned getSuccessorIndex() const {
3162      assert(((unsigned)Index == DefaultPseudoIndex ||
3163              (unsigned)Index < SI->getNumCases()) &&
3164             "Index out the number of cases.");
3165      return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3166    }
3167
3168    bool operator==(const CaseHandleImpl &RHS) const {
3169      assert(SI == RHS.SI && "Incompatible operators.");
3170      return Index == RHS.Index;
3171    }
3172  };
3173
3174  using ConstCaseHandle =
3175      CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3176
3177  class CaseHandle
3178      : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3179    friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3180
3181  public:
3182    CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3183
3184    /// Sets the new value for current case.
3185    void setValue(ConstantInt *V) {
3186      assert((unsigned)Index < SI->getNumCases() &&
3187             "Index out the number of cases.");
3188      SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3189    }
3190
3191    /// Sets the new successor for current case.
3192    void setSuccessor(BasicBlock *S) {
3193      SI->setSuccessor(getSuccessorIndex(), S);
3194    }
3195  };
3196
3197  template <typename CaseHandleT>
3198  class CaseIteratorImpl
3199      : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3200                                    std::random_access_iterator_tag,
3201                                    CaseHandleT> {
3202    using SwitchInstT = typename CaseHandleT::SwitchInstType;
3203
3204    CaseHandleT Case;
3205
3206  public:
3207    /// Default constructed iterator is in an invalid state until assigned to
3208    /// a case for a particular switch.
3209    CaseIteratorImpl() = default;
3210
3211    /// Initializes case iterator for given SwitchInst and for given
3212    /// case number.
3213    CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3214
3215    /// Initializes case iterator for given SwitchInst and for given
3216    /// TerminatorInst's successor index.
3217    static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3218                                               unsigned SuccessorIndex) {
3219      assert(SuccessorIndex < SI->getNumSuccessors() &&
3220             "Successor index # out of range!");
3221      return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3222                                 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3223    }
3224
3225    /// Support converting to the const variant. This will be a no-op for const
3226    /// variant.
3227    operator CaseIteratorImpl<ConstCaseHandle>() const {
3228      return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3229    }
3230
3231    CaseIteratorImpl &operator+=(ptrdiff_t N) {
3232      // Check index correctness after addition.
3233      // Note: Index == getNumCases() means end().
3234      assert(Case.Index + N >= 0 &&
3235             (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3236             "Case.Index out the number of cases.");
3237      Case.Index += N;
3238      return *this;
3239    }
3240    CaseIteratorImpl &operator-=(ptrdiff_t N) {
3241      // Check index correctness after subtraction.
3242      // Note: Case.Index == getNumCases() means end().
3243      assert(Case.Index - N >= 0 &&
3244             (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3245             "Case.Index out the number of cases.");
3246      Case.Index -= N;
3247      return *this;
3248    }
3249    ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3250      assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3251      return Case.Index - RHS.Case.Index;
3252    }
3253    bool operator==(const CaseIteratorImpl &RHS) const {
3254      return Case == RHS.Case;
3255    }
3256    bool operator<(const CaseIteratorImpl &RHS) const {
3257      assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3258      return Case.Index < RHS.Case.Index;
3259    }
3260    CaseHandleT &operator*() { return Case; }
3261    const CaseHandleT &operator*() const { return Case; }
3262  };
3263
3264  using CaseIt = CaseIteratorImpl<CaseHandle>;
3265  using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3266
3267  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3268                            unsigned NumCases,
3269                            Instruction *InsertBefore = nullptr) {
3270    return new SwitchInst(Value, Default, NumCases, InsertBefore);
3271  }
3272
3273  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3274                            unsigned NumCases, BasicBlock *InsertAtEnd) {
3275    return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3276  }
3277
3278  /// Provide fast operand accessors
3279  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3280
3281  // Accessor Methods for Switch stmt
3282  Value *getCondition() const { return getOperand(0); }
3283  void setCondition(Value *V) { setOperand(0, V); }
3284
3285  BasicBlock *getDefaultDest() const {
3286    return cast<BasicBlock>(getOperand(1));
3287  }
3288
3289  void setDefaultDest(BasicBlock *DefaultCase) {
3290    setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3291  }
3292
3293  /// Return the number of 'cases' in this switch instruction, excluding the
3294  /// default case.
3295  unsigned getNumCases() const {
3296    return getNumOperands()/2 - 1;
3297  }
3298
3299  /// Returns a read/write iterator that points to the first case in the
3300  /// SwitchInst.
3301  CaseIt case_begin() {
3302    return CaseIt(this, 0);
3303  }
3304
3305  /// Returns a read-only iterator that points to the first case in the
3306  /// SwitchInst.
3307  ConstCaseIt case_begin() const {
3308    return ConstCaseIt(this, 0);
3309  }
3310
3311  /// Returns a read/write iterator that points one past the last in the
3312  /// SwitchInst.
3313  CaseIt case_end() {
3314    return CaseIt(this, getNumCases());
3315  }
3316
3317  /// Returns a read-only iterator that points one past the last in the
3318  /// SwitchInst.
3319  ConstCaseIt case_end() const {
3320    return ConstCaseIt(this, getNumCases());
3321  }
3322
3323  /// Iteration adapter for range-for loops.
3324  iterator_range<CaseIt> cases() {
3325    return make_range(case_begin(), case_end());
3326  }
3327
3328  /// Constant iteration adapter for range-for loops.
3329  iterator_range<ConstCaseIt> cases() const {
3330    return make_range(case_begin(), case_end());
3331  }
3332
3333  /// Returns an iterator that points to the default case.
3334  /// Note: this iterator allows to resolve successor only. Attempt
3335  /// to resolve case value causes an assertion.
3336  /// Also note, that increment and decrement also causes an assertion and
3337  /// makes iterator invalid.
3338  CaseIt case_default() {
3339    return CaseIt(this, DefaultPseudoIndex);
3340  }
3341  ConstCaseIt case_default() const {
3342    return ConstCaseIt(this, DefaultPseudoIndex);
3343  }
3344
3345  /// Search all of the case values for the specified constant. If it is
3346  /// explicitly handled, return the case iterator of it, otherwise return
3347  /// default case iterator to indicate that it is handled by the default
3348  /// handler.
3349  CaseIt findCaseValue(const ConstantInt *C) {
3350    CaseIt I = llvm::find_if(
3351        cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3352    if (I != case_end())
3353      return I;
3354
3355    return case_default();
3356  }
3357  ConstCaseIt findCaseValue(const ConstantInt *C) const {
3358    ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3359      return Case.getCaseValue() == C;
3360    });
3361    if (I != case_end())
3362      return I;
3363
3364    return case_default();
3365  }
3366
3367  /// Finds the unique case value for a given successor. Returns null if the
3368  /// successor is not found, not unique, or is the default case.
3369  ConstantInt *findCaseDest(BasicBlock *BB) {
3370    if (BB == getDefaultDest())
3371      return nullptr;
3372
3373    ConstantInt *CI = nullptr;
3374    for (auto Case : cases()) {
3375      if (Case.getCaseSuccessor() != BB)
3376        continue;
3377
3378      if (CI)
3379        return nullptr; // Multiple cases lead to BB.
3380
3381      CI = Case.getCaseValue();
3382    }
3383
3384    return CI;
3385  }
3386
3387  /// Add an entry to the switch instruction.
3388  /// Note:
3389  /// This action invalidates case_end(). Old case_end() iterator will
3390  /// point to the added case.
3391  void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3392
3393  /// This method removes the specified case and its successor from the switch
3394  /// instruction. Note that this operation may reorder the remaining cases at
3395  /// index idx and above.
3396  /// Note:
3397  /// This action invalidates iterators for all cases following the one removed,
3398  /// including the case_end() iterator. It returns an iterator for the next
3399  /// case.
3400  CaseIt removeCase(CaseIt I);
3401
3402  unsigned getNumSuccessors() const { return getNumOperands()/2; }
3403  BasicBlock *getSuccessor(unsigned idx) const {
3404    assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3405    return cast<BasicBlock>(getOperand(idx*2+1));
3406  }
3407  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3408    assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3409    setOperand(idx * 2 + 1, NewSucc);
3410  }
3411
3412  // Methods for support type inquiry through isa, cast, and dyn_cast:
3413  static bool classof(const Instruction *I) {
3414    return I->getOpcode() == Instruction::Switch;
3415  }
3416  static bool classof(const Value *V) {
3417    return isa<Instruction>(V) && classof(cast<Instruction>(V));
3418  }
3419};
3420
3421template <>
3422struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3423};
3424
3425DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3426
3427//===----------------------------------------------------------------------===//
3428//                             IndirectBrInst Class
3429//===----------------------------------------------------------------------===//
3430
3431//===---------------------------------------------------------------------------
3432/// Indirect Branch Instruction.
3433///
3434class IndirectBrInst : public TerminatorInst {
3435  unsigned ReservedSpace;
3436
3437  // Operand[0]   = Address to jump to
3438  // Operand[n+1] = n-th destination
3439  IndirectBrInst(const IndirectBrInst &IBI);
3440
3441  /// Create a new indirectbr instruction, specifying an
3442  /// Address to jump to.  The number of expected destinations can be specified
3443  /// here to make memory allocation more efficient.  This constructor can also
3444  /// autoinsert before another instruction.
3445  IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3446
3447  /// Create a new indirectbr instruction, specifying an
3448  /// Address to jump to.  The number of expected destinations can be specified
3449  /// here to make memory allocation more efficient.  This constructor also
3450  /// autoinserts at the end of the specified BasicBlock.
3451  IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3452
3453  // allocate space for exactly zero operands
3454  void *operator new(size_t s) {
3455    return User::operator new(s);
3456  }
3457
3458  void init(Value *Address, unsigned NumDests);
3459  void growOperands();
3460
3461protected:
3462  // Note: Instruction needs to be a friend here to call cloneImpl.
3463  friend class Instruction;
3464
3465  IndirectBrInst *cloneImpl() const;
3466
3467public:
3468  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3469                                Instruction *InsertBefore = nullptr) {
3470    return new IndirectBrInst(Address, NumDests, InsertBefore);
3471  }
3472
3473  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3474                                BasicBlock *InsertAtEnd) {
3475    return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3476  }
3477
3478  /// Provide fast operand accessors.
3479  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3480
3481  // Accessor Methods for IndirectBrInst instruction.
3482  Value *getAddress() { return getOperand(0); }
3483  const Value *getAddress() const { return getOperand(0); }
3484  void setAddress(Value *V) { setOperand(0, V); }
3485
3486  /// return the number of possible destinations in this
3487  /// indirectbr instruction.
3488  unsigned getNumDestinations() const { return getNumOperands()-1; }
3489
3490  /// Return the specified destination.
3491  BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3492  const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3493
3494  /// Add a destination.
3495  ///
3496  void addDestination(BasicBlock *Dest);
3497
3498  /// This method removes the specified successor from the
3499  /// indirectbr instruction.
3500  void removeDestination(unsigned i);
3501
3502  unsigned getNumSuccessors() const { return getNumOperands()-1; }
3503  BasicBlock *getSuccessor(unsigned i) const {
3504    return cast<BasicBlock>(getOperand(i+1));
3505  }
3506  void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3507    setOperand(i + 1, NewSucc);
3508  }
3509
3510  // Methods for support type inquiry through isa, cast, and dyn_cast:
3511  static bool classof(const Instruction *I) {
3512    return I->getOpcode() == Instruction::IndirectBr;
3513  }
3514  static bool classof(const Value *V) {
3515    return isa<Instruction>(V) && classof(cast<Instruction>(V));
3516  }
3517};
3518
3519template <>
3520struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3521};
3522
3523DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3524
3525//===----------------------------------------------------------------------===//
3526//                               InvokeInst Class
3527//===----------------------------------------------------------------------===//
3528
3529/// Invoke instruction.  The SubclassData field is used to hold the
3530/// calling convention of the call.
3531///
3532class InvokeInst : public TerminatorInst,
3533                   public OperandBundleUser<InvokeInst, User::op_iterator> {
3534  friend class OperandBundleUser<InvokeInst, User::op_iterator>;
3535
3536  AttributeList Attrs;
3537  FunctionType *FTy;
3538
3539  InvokeInst(const InvokeInst &BI);
3540
3541  /// Construct an InvokeInst given a range of arguments.
3542  ///
3543  /// Construct an InvokeInst from a range of arguments
3544  inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3545                    ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3546                    unsigned Values, const Twine &NameStr,
3547                    Instruction *InsertBefore)
3548      : InvokeInst(cast<FunctionType>(
3549                       cast<PointerType>(Func->getType())->getElementType()),
3550                   Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3551                   InsertBefore) {}
3552
3553  inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3554                    BasicBlock *IfException, ArrayRef<Value *> Args,
3555                    ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3556                    const Twine &NameStr, Instruction *InsertBefore);
3557  /// Construct an InvokeInst given a range of arguments.
3558  ///
3559  /// Construct an InvokeInst from a range of arguments
3560  inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3561                    ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3562                    unsigned Values, const Twine &NameStr,
3563                    BasicBlock *InsertAtEnd);
3564
3565  bool hasDescriptor() const { return HasDescriptor; }
3566
3567  void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3568            ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3569            const Twine &NameStr) {
3570    init(cast<FunctionType>(
3571             cast<PointerType>(Func->getType())->getElementType()),
3572         Func, IfNormal, IfException, Args, Bundles, NameStr);
3573  }
3574
3575  void init(FunctionType *FTy, Value *Func, BasicBlock *IfNormal,
3576            BasicBlock *IfException, ArrayRef<Value *> Args,
3577            ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3578
3579protected:
3580  // Note: Instruction needs to be a friend here to call cloneImpl.
3581  friend class Instruction;
3582
3583  InvokeInst *cloneImpl() const;
3584
3585public:
3586  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3587                            BasicBlock *IfException, ArrayRef<Value *> Args,
3588                            const Twine &NameStr,
3589                            Instruction *InsertBefore = nullptr) {
3590    return Create(cast<FunctionType>(
3591                      cast<PointerType>(Func->getType())->getElementType()),
3592                  Func, IfNormal, IfException, Args, None, NameStr,
3593                  InsertBefore);
3594  }
3595
3596  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3597                            BasicBlock *IfException, ArrayRef<Value *> Args,
3598                            ArrayRef<OperandBundleDef> Bundles = None,
3599                            const Twine &NameStr = "",
3600                            Instruction *InsertBefore = nullptr) {
3601    return Create(cast<FunctionType>(
3602                      cast<PointerType>(Func->getType())->getElementType()),
3603                  Func, IfNormal, IfException, Args, Bundles, NameStr,
3604                  InsertBefore);
3605  }
3606
3607  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3608                            BasicBlock *IfException, ArrayRef<Value *> Args,
3609                            const Twine &NameStr,
3610                            Instruction *InsertBefore = nullptr) {
3611    unsigned Values = unsigned(Args.size()) + 3;
3612    return new (Values) InvokeInst(Ty, Func, IfNormal, IfException, Args, None,
3613                                   Values, NameStr, InsertBefore);
3614  }
3615
3616  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3617                            BasicBlock *IfException, ArrayRef<Value *> Args,
3618                            ArrayRef<OperandBundleDef> Bundles = None,
3619                            const Twine &NameStr = "",
3620                            Instruction *InsertBefore = nullptr) {
3621    unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3622    unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3623
3624    return new (Values, DescriptorBytes)
3625        InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, Values,
3626                   NameStr, InsertBefore);
3627  }
3628
3629  static InvokeInst *Create(Value *Func,
3630                            BasicBlock *IfNormal, BasicBlock *IfException,
3631                            ArrayRef<Value *> Args, const Twine &NameStr,
3632                            BasicBlock *InsertAtEnd) {
3633    unsigned Values = unsigned(Args.size()) + 3;
3634    return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None,
3635                                   Values, NameStr, InsertAtEnd);
3636  }
3637
3638  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3639                            BasicBlock *IfException, ArrayRef<Value *> Args,
3640                            ArrayRef<OperandBundleDef> Bundles,
3641                            const Twine &NameStr, BasicBlock *InsertAtEnd) {
3642    unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3643    unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3644
3645    return new (Values, DescriptorBytes)
3646        InvokeInst(Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3647                   InsertAtEnd);
3648  }
3649
3650  /// Create a clone of \p II with a different set of operand bundles and
3651  /// insert it before \p InsertPt.
3652  ///
3653  /// The returned invoke instruction is identical to \p II in every way except
3654  /// that the operand bundles for the new instruction are set to the operand
3655  /// bundles in \p Bundles.
3656  static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3657                            Instruction *InsertPt = nullptr);
3658
3659  /// Provide fast operand accessors
3660  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3661
3662  FunctionType *getFunctionType() const { return FTy; }
3663
3664  void mutateFunctionType(FunctionType *FTy) {
3665    mutateType(FTy->getReturnType());
3666    this->FTy = FTy;
3667  }
3668
3669  /// Return the number of invoke arguments.
3670  ///
3671  unsigned getNumArgOperands() const {
3672    return getNumOperands() - getNumTotalBundleOperands() - 3;
3673  }
3674
3675  /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3676  ///
3677  Value *getArgOperand(unsigned i) const {
3678    assert(i < getNumArgOperands() && "Out of bounds!");
3679    return getOperand(i);
3680  }
3681  void setArgOperand(unsigned i, Value *v) {
3682    assert(i < getNumArgOperands() && "Out of bounds!");
3683    setOperand(i, v);
3684  }
3685
3686  /// Return the iterator pointing to the beginning of the argument list.
3687  op_iterator arg_begin() { return op_begin(); }
3688
3689  /// Return the iterator pointing to the end of the argument list.
3690  op_iterator arg_end() {
3691    // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3692    return op_end() - getNumTotalBundleOperands() - 3;
3693  }
3694
3695  /// Iteration adapter for range-for loops.
3696  iterator_range<op_iterator> arg_operands() {
3697    return make_range(arg_begin(), arg_end());
3698  }
3699
3700  /// Return the iterator pointing to the beginning of the argument list.
3701  const_op_iterator arg_begin() const { return op_begin(); }
3702
3703  /// Return the iterator pointing to the end of the argument list.
3704  const_op_iterator arg_end() const {
3705    // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3706    return op_end() - getNumTotalBundleOperands() - 3;
3707  }
3708
3709  /// Iteration adapter for range-for loops.
3710  iterator_range<const_op_iterator> arg_operands() const {
3711    return make_range(arg_begin(), arg_end());
3712  }
3713
3714  /// Wrappers for getting the \c Use of a invoke argument.
3715  const Use &getArgOperandUse(unsigned i) const {
3716    assert(i < getNumArgOperands() && "Out of bounds!");
3717    return getOperandUse(i);
3718  }
3719  Use &getArgOperandUse(unsigned i) {
3720    assert(i < getNumArgOperands() && "Out of bounds!");
3721    return getOperandUse(i);
3722  }
3723
3724  /// If one of the arguments has the 'returned' attribute, return its
3725  /// operand value. Otherwise, return nullptr.
3726  Value *getReturnedArgOperand() const;
3727
3728  /// getCallingConv/setCallingConv - Get or set the calling convention of this
3729  /// function call.
3730  CallingConv::ID getCallingConv() const {
3731    return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3732  }
3733  void setCallingConv(CallingConv::ID CC) {
3734    auto ID = static_cast<unsigned>(CC);
3735    assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
3736    setInstructionSubclassData(ID);
3737  }
3738
3739  /// Return the parameter attributes for this invoke.
3740  ///
3741  AttributeList getAttributes() const { return Attrs; }
3742
3743  /// Set the parameter attributes for this invoke.
3744  ///
3745  void setAttributes(AttributeList A) { Attrs = A; }
3746
3747  /// adds the attribute to the list of attributes.
3748  void addAttribute(unsigned i, Attribute::AttrKind Kind);
3749
3750  /// adds the attribute to the list of attributes.
3751  void addAttribute(unsigned i, Attribute Attr);
3752
3753  /// Adds the attribute to the indicated argument
3754  void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3755
3756  /// removes the attribute from the list of attributes.
3757  void removeAttribute(unsigned i, Attribute::AttrKind Kind);
3758
3759  /// removes the attribute from the list of attributes.
3760  void removeAttribute(unsigned i, StringRef Kind);
3761
3762  /// Removes the attribute from the given argument
3763  void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3764
3765  /// adds the dereferenceable attribute to the list of attributes.
3766  void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3767
3768  /// adds the dereferenceable_or_null attribute to the list of
3769  /// attributes.
3770  void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
3771
3772  /// Determine whether this call has the given attribute.
3773  bool hasFnAttr(Attribute::AttrKind Kind) const {
3774    assert(Kind != Attribute::NoBuiltin &&
3775           "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
3776    return hasFnAttrImpl(Kind);
3777  }
3778
3779  /// Determine whether this call has the given attribute.
3780  bool hasFnAttr(StringRef Kind) const {
3781    return hasFnAttrImpl(Kind);
3782  }
3783
3784  /// Determine whether the return value has the given attribute.
3785  bool hasRetAttr(Attribute::AttrKind Kind) const;
3786
3787  /// Determine whether the argument or parameter has the given attribute.
3788  bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
3789
3790  /// Get the attribute of a given kind at a position.
3791  Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
3792    return getAttributes().getAttribute(i, Kind);
3793  }
3794
3795  /// Get the attribute of a given kind at a position.
3796  Attribute getAttribute(unsigned i, StringRef Kind) const {
3797    return getAttributes().getAttribute(i, Kind);
3798  }
3799
3800  /// Return true if the data operand at index \p i has the attribute \p
3801  /// A.
3802  ///
3803  /// Data operands include invoke arguments and values used in operand bundles,
3804  /// but does not include the invokee operand, or the two successor blocks.
3805  /// This routine dispatches to the underlying AttributeList or the
3806  /// OperandBundleUser as appropriate.
3807  ///
3808  /// The index \p i is interpreted as
3809  ///
3810  ///  \p i == Attribute::ReturnIndex  -> the return value
3811  ///  \p i in [1, arg_size + 1)  -> argument number (\p i - 1)
3812  ///  \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
3813  ///     (\p i - 1) in the operand list.
3814  bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
3815
3816  /// Extract the alignment of the return value.
3817  unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
3818
3819  /// Extract the alignment for a call or parameter (0=unknown).
3820  unsigned getParamAlignment(unsigned ArgNo) const {
3821    return Attrs.getParamAlignment(ArgNo);
3822  }
3823
3824  /// Extract the number of dereferenceable bytes for a call or
3825  /// parameter (0=unknown).
3826  uint64_t getDereferenceableBytes(unsigned i) const {
3827    return Attrs.getDereferenceableBytes(i);
3828  }
3829
3830  /// Extract the number of dereferenceable_or_null bytes for a call or
3831  /// parameter (0=unknown).
3832  uint64_t getDereferenceableOrNullBytes(unsigned i) const {
3833    return Attrs.getDereferenceableOrNullBytes(i);
3834  }
3835
3836  /// @brief Determine if the return value is marked with NoAlias attribute.
3837  bool returnDoesNotAlias() const {
3838    return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
3839  }
3840
3841  /// Return true if the call should not be treated as a call to a
3842  /// builtin.
3843  bool isNoBuiltin() const {
3844    // We assert in hasFnAttr if one passes in Attribute::NoBuiltin, so we have
3845    // to check it by hand.
3846    return hasFnAttrImpl(Attribute::NoBuiltin) &&
3847      !hasFnAttrImpl(Attribute::Builtin);
3848  }
3849
3850  /// Determine if the call requires strict floating point semantics.
3851  bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
3852
3853  /// Return true if the call should not be inlined.
3854  bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
3855  void setIsNoInline() {
3856    addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
3857  }
3858
3859  /// Determine if the call does not access memory.
3860  bool doesNotAccessMemory() const {
3861    return hasFnAttr(Attribute::ReadNone);
3862  }
3863  void setDoesNotAccessMemory() {
3864    addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
3865  }
3866
3867  /// Determine if the call does not access or only reads memory.
3868  bool onlyReadsMemory() const {
3869    return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
3870  }
3871  void setOnlyReadsMemory() {
3872    addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
3873  }
3874
3875  /// Determine if the call does not access or only writes memory.
3876  bool doesNotReadMemory() const {
3877    return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
3878  }
3879  void setDoesNotReadMemory() {
3880    addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
3881  }
3882
3883  /// @brief Determine if the call access memmory only using it's pointer
3884  /// arguments.
3885  bool onlyAccessesArgMemory() const {
3886    return hasFnAttr(Attribute::ArgMemOnly);
3887  }
3888  void setOnlyAccessesArgMemory() {
3889    addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
3890  }
3891
3892  /// Determine if the call cannot return.
3893  bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
3894  void setDoesNotReturn() {
3895    addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
3896  }
3897
3898  /// Determine if the call cannot unwind.
3899  bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3900  void setDoesNotThrow() {
3901    addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3902  }
3903
3904  /// Determine if the invoke cannot be duplicated.
3905  bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
3906  void setCannotDuplicate() {
3907    addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
3908  }
3909
3910  /// Determine if the invoke is convergent
3911  bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
3912  void setConvergent() {
3913    addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
3914  }
3915  void setNotConvergent() {
3916    removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
3917  }
3918
3919  /// Determine if the call returns a structure through first
3920  /// pointer argument.
3921  bool hasStructRetAttr() const {
3922    if (getNumArgOperands() == 0)
3923      return false;
3924
3925    // Be friendly and also check the callee.
3926    return paramHasAttr(0, Attribute::StructRet);
3927  }
3928
3929  /// Determine if any call argument is an aggregate passed by value.
3930  bool hasByValArgument() const {
3931    return Attrs.hasAttrSomewhere(Attribute::ByVal);
3932  }
3933
3934  /// Return the function called, or null if this is an
3935  /// indirect function invocation.
3936  ///
3937  Function *getCalledFunction() const {
3938    return dyn_cast<Function>(Op<-3>());
3939  }
3940
3941  /// Get a pointer to the function that is invoked by this
3942  /// instruction
3943  const Value *getCalledValue() const { return Op<-3>(); }
3944        Value *getCalledValue()       { return Op<-3>(); }
3945
3946  /// Set the function called.
3947  void setCalledFunction(Value* Fn) {
3948    setCalledFunction(
3949        cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
3950        Fn);
3951  }
3952  void setCalledFunction(FunctionType *FTy, Value *Fn) {
3953    this->FTy = FTy;
3954    assert(FTy == cast<FunctionType>(
3955                      cast<PointerType>(Fn->getType())->getElementType()));
3956    Op<-3>() = Fn;
3957  }
3958
3959  // get*Dest - Return the destination basic blocks...
3960  BasicBlock *getNormalDest() const {
3961    return cast<BasicBlock>(Op<-2>());
3962  }
3963  BasicBlock *getUnwindDest() const {
3964    return cast<BasicBlock>(Op<-1>());
3965  }
3966  void setNormalDest(BasicBlock *B) {
3967    Op<-2>() = reinterpret_cast<Value*>(B);
3968  }
3969  void setUnwindDest(BasicBlock *B) {
3970    Op<-1>() = reinterpret_cast<Value*>(B);
3971  }
3972
3973  /// Get the landingpad instruction from the landing pad
3974  /// block (the unwind destination).
3975  LandingPadInst *getLandingPadInst() const;
3976
3977  BasicBlock *getSuccessor(unsigned i) const {
3978    assert(i < 2 && "Successor # out of range for invoke!");
3979    return i == 0 ? getNormalDest() : getUnwindDest();
3980  }
3981
3982  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3983    assert(idx < 2 && "Successor # out of range for invoke!");
3984    *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
3985  }
3986
3987  unsigned getNumSuccessors() const { return 2; }
3988
3989  // Methods for support type inquiry through isa, cast, and dyn_cast:
3990  static bool classof(const Instruction *I) {
3991    return (I->getOpcode() == Instruction::Invoke);
3992  }
3993  static bool classof(const Value *V) {
3994    return isa<Instruction>(V) && classof(cast<Instruction>(V));
3995  }
3996
3997private:
3998  template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
3999    if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
4000      return true;
4001
4002    // Operand bundles override attributes on the called function, but don't
4003    // override attributes directly present on the invoke instruction.
4004    if (isFnAttrDisallowedByOpBundle(Kind))
4005      return false;
4006
4007    if (const Function *F = getCalledFunction())
4008      return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
4009                                             Kind);
4010    return false;
4011  }
4012
4013  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4014  // method so that subclasses cannot accidentally use it.
4015  void setInstructionSubclassData(unsigned short D) {
4016    Instruction::setInstructionSubclassData(D);
4017  }
4018};
4019
4020template <>
4021struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
4022};
4023
4024InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
4025                       BasicBlock *IfException, ArrayRef<Value *> Args,
4026                       ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4027                       const Twine &NameStr, Instruction *InsertBefore)
4028    : TerminatorInst(Ty->getReturnType(), Instruction::Invoke,
4029                     OperandTraits<InvokeInst>::op_end(this) - Values, Values,
4030                     InsertBefore) {
4031  init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
4032}
4033
4034InvokeInst::InvokeInst(Value *Func, BasicBlock *IfNormal,
4035                       BasicBlock *IfException, ArrayRef<Value *> Args,
4036                       ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4037                       const Twine &NameStr, BasicBlock *InsertAtEnd)
4038    : TerminatorInst(
4039          cast<FunctionType>(cast<PointerType>(Func->getType())
4040                                 ->getElementType())->getReturnType(),
4041          Instruction::Invoke, OperandTraits<InvokeInst>::op_end(this) - Values,
4042          Values, InsertAtEnd) {
4043  init(Func, IfNormal, IfException, Args, Bundles, NameStr);
4044}
4045
4046DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
4047
4048//===----------------------------------------------------------------------===//
4049//                              ResumeInst Class
4050//===----------------------------------------------------------------------===//
4051
4052//===---------------------------------------------------------------------------
4053/// Resume the propagation of an exception.
4054///
4055class ResumeInst : public TerminatorInst {
4056  ResumeInst(const ResumeInst &RI);
4057
4058  explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4059  ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4060
4061protected:
4062  // Note: Instruction needs to be a friend here to call cloneImpl.
4063  friend class Instruction;
4064
4065  ResumeInst *cloneImpl() const;
4066
4067public:
4068  static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4069    return new(1) ResumeInst(Exn, InsertBefore);
4070  }
4071
4072  static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4073    return new(1) ResumeInst(Exn, InsertAtEnd);
4074  }
4075
4076  /// Provide fast operand accessors
4077  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4078
4079  /// Convenience accessor.
4080  Value *getValue() const { return Op<0>(); }
4081
4082  unsigned getNumSuccessors() const { return 0; }
4083
4084  // Methods for support type inquiry through isa, cast, and dyn_cast:
4085  static bool classof(const Instruction *I) {
4086    return I->getOpcode() == Instruction::Resume;
4087  }
4088  static bool classof(const Value *V) {
4089    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4090  }
4091
4092private:
4093  friend TerminatorInst;
4094
4095  BasicBlock *getSuccessor(unsigned idx) const {
4096    llvm_unreachable("ResumeInst has no successors!");
4097  }
4098
4099  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4100    llvm_unreachable("ResumeInst has no successors!");
4101  }
4102};
4103
4104template <>
4105struct OperandTraits<ResumeInst> :
4106    public FixedNumOperandTraits<ResumeInst, 1> {
4107};
4108
4109DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4110
4111//===----------------------------------------------------------------------===//
4112//                         CatchSwitchInst Class
4113//===----------------------------------------------------------------------===//
4114class CatchSwitchInst : public TerminatorInst {
4115  /// The number of operands actually allocated.  NumOperands is
4116  /// the number actually in use.
4117  unsigned ReservedSpace;
4118
4119  // Operand[0] = Outer scope
4120  // Operand[1] = Unwind block destination
4121  // Operand[n] = BasicBlock to go to on match
4122  CatchSwitchInst(const CatchSwitchInst &CSI);
4123
4124  /// Create a new switch instruction, specifying a
4125  /// default destination.  The number of additional handlers can be specified
4126  /// here to make memory allocation more efficient.
4127  /// This constructor can also autoinsert before another instruction.
4128  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4129                  unsigned NumHandlers, const Twine &NameStr,
4130                  Instruction *InsertBefore);
4131
4132  /// Create a new switch instruction, specifying a
4133  /// default destination.  The number of additional handlers can be specified
4134  /// here to make memory allocation more efficient.
4135  /// This constructor also autoinserts at the end of the specified BasicBlock.
4136  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4137                  unsigned NumHandlers, const Twine &NameStr,
4138                  BasicBlock *InsertAtEnd);
4139
4140  // allocate space for exactly zero operands
4141  void *operator new(size_t s) { return User::operator new(s); }
4142
4143  void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4144  void growOperands(unsigned Size);
4145
4146protected:
4147  // Note: Instruction needs to be a friend here to call cloneImpl.
4148  friend class Instruction;
4149
4150  CatchSwitchInst *cloneImpl() const;
4151
4152public:
4153  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4154                                 unsigned NumHandlers,
4155                                 const Twine &NameStr = "",
4156                                 Instruction *InsertBefore = nullptr) {
4157    return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4158                               InsertBefore);
4159  }
4160
4161  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4162                                 unsigned NumHandlers, const Twine &NameStr,
4163                                 BasicBlock *InsertAtEnd) {
4164    return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4165                               InsertAtEnd);
4166  }
4167
4168  /// Provide fast operand accessors
4169  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4170
4171  // Accessor Methods for CatchSwitch stmt
4172  Value *getParentPad() const { return getOperand(0); }
4173  void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4174
4175  // Accessor Methods for CatchSwitch stmt
4176  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4177  bool unwindsToCaller() const { return !hasUnwindDest(); }
4178  BasicBlock *getUnwindDest() const {
4179    if (hasUnwindDest())
4180      return cast<BasicBlock>(getOperand(1));
4181    return nullptr;
4182  }
4183  void setUnwindDest(BasicBlock *UnwindDest) {
4184    assert(UnwindDest);
4185    assert(hasUnwindDest());
4186    setOperand(1, UnwindDest);
4187  }
4188
4189  /// return the number of 'handlers' in this catchswitch
4190  /// instruction, except the default handler
4191  unsigned getNumHandlers() const {
4192    if (hasUnwindDest())
4193      return getNumOperands() - 2;
4194    return getNumOperands() - 1;
4195  }
4196
4197private:
4198  static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4199  static const BasicBlock *handler_helper(const Value *V) {
4200    return cast<BasicBlock>(V);
4201  }
4202
4203public:
4204  using DerefFnTy = BasicBlock *(*)(Value *);
4205  using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4206  using handler_range = iterator_range<handler_iterator>;
4207  using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4208  using const_handler_iterator =
4209      mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4210  using const_handler_range = iterator_range<const_handler_iterator>;
4211
4212  /// Returns an iterator that points to the first handler in CatchSwitchInst.
4213  handler_iterator handler_begin() {
4214    op_iterator It = op_begin() + 1;
4215    if (hasUnwindDest())
4216      ++It;
4217    return handler_iterator(It, DerefFnTy(handler_helper));
4218  }
4219
4220  /// Returns an iterator that points to the first handler in the
4221  /// CatchSwitchInst.
4222  const_handler_iterator handler_begin() const {
4223    const_op_iterator It = op_begin() + 1;
4224    if (hasUnwindDest())
4225      ++It;
4226    return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4227  }
4228
4229  /// Returns a read-only iterator that points one past the last
4230  /// handler in the CatchSwitchInst.
4231  handler_iterator handler_end() {
4232    return handler_iterator(op_end(), DerefFnTy(handler_helper));
4233  }
4234
4235  /// Returns an iterator that points one past the last handler in the
4236  /// CatchSwitchInst.
4237  const_handler_iterator handler_end() const {
4238    return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4239  }
4240
4241  /// iteration adapter for range-for loops.
4242  handler_range handlers() {
4243    return make_range(handler_begin(), handler_end());
4244  }
4245
4246  /// iteration adapter for range-for loops.
4247  const_handler_range handlers() const {
4248    return make_range(handler_begin(), handler_end());
4249  }
4250
4251  /// Add an entry to the switch instruction...
4252  /// Note:
4253  /// This action invalidates handler_end(). Old handler_end() iterator will
4254  /// point to the added handler.
4255  void addHandler(BasicBlock *Dest);
4256
4257  void removeHandler(handler_iterator HI);
4258
4259  unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4260  BasicBlock *getSuccessor(unsigned Idx) const {
4261    assert(Idx < getNumSuccessors() &&
4262           "Successor # out of range for catchswitch!");
4263    return cast<BasicBlock>(getOperand(Idx + 1));
4264  }
4265  void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4266    assert(Idx < getNumSuccessors() &&
4267           "Successor # out of range for catchswitch!");
4268    setOperand(Idx + 1, NewSucc);
4269  }
4270
4271  // Methods for support type inquiry through isa, cast, and dyn_cast:
4272  static bool classof(const Instruction *I) {
4273    return I->getOpcode() == Instruction::CatchSwitch;
4274  }
4275  static bool classof(const Value *V) {
4276    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4277  }
4278};
4279
4280template <>
4281struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4282
4283DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4284
4285//===----------------------------------------------------------------------===//
4286//                               CleanupPadInst Class
4287//===----------------------------------------------------------------------===//
4288class CleanupPadInst : public FuncletPadInst {
4289private:
4290  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4291                          unsigned Values, const Twine &NameStr,
4292                          Instruction *InsertBefore)
4293      : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4294                       NameStr, InsertBefore) {}
4295  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4296                          unsigned Values, const Twine &NameStr,
4297                          BasicBlock *InsertAtEnd)
4298      : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4299                       NameStr, InsertAtEnd) {}
4300
4301public:
4302  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4303                                const Twine &NameStr = "",
4304                                Instruction *InsertBefore = nullptr) {
4305    unsigned Values = 1 + Args.size();
4306    return new (Values)
4307        CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4308  }
4309
4310  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4311                                const Twine &NameStr, BasicBlock *InsertAtEnd) {
4312    unsigned Values = 1 + Args.size();
4313    return new (Values)
4314        CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4315  }
4316
4317  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4318  static bool classof(const Instruction *I) {
4319    return I->getOpcode() == Instruction::CleanupPad;
4320  }
4321  static bool classof(const Value *V) {
4322    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4323  }
4324};
4325
4326//===----------------------------------------------------------------------===//
4327//                               CatchPadInst Class
4328//===----------------------------------------------------------------------===//
4329class CatchPadInst : public FuncletPadInst {
4330private:
4331  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4332                        unsigned Values, const Twine &NameStr,
4333                        Instruction *InsertBefore)
4334      : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4335                       NameStr, InsertBefore) {}
4336  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4337                        unsigned Values, const Twine &NameStr,
4338                        BasicBlock *InsertAtEnd)
4339      : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4340                       NameStr, InsertAtEnd) {}
4341
4342public:
4343  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4344                              const Twine &NameStr = "",
4345                              Instruction *InsertBefore = nullptr) {
4346    unsigned Values = 1 + Args.size();
4347    return new (Values)
4348        CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4349  }
4350
4351  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4352                              const Twine &NameStr, BasicBlock *InsertAtEnd) {
4353    unsigned Values = 1 + Args.size();
4354    return new (Values)
4355        CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4356  }
4357
4358  /// Convenience accessors
4359  CatchSwitchInst *getCatchSwitch() const {
4360    return cast<CatchSwitchInst>(Op<-1>());
4361  }
4362  void setCatchSwitch(Value *CatchSwitch) {
4363    assert(CatchSwitch);
4364    Op<-1>() = CatchSwitch;
4365  }
4366
4367  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4368  static bool classof(const Instruction *I) {
4369    return I->getOpcode() == Instruction::CatchPad;
4370  }
4371  static bool classof(const Value *V) {
4372    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4373  }
4374};
4375
4376//===----------------------------------------------------------------------===//
4377//                               CatchReturnInst Class
4378//===----------------------------------------------------------------------===//
4379
4380class CatchReturnInst : public TerminatorInst {
4381  CatchReturnInst(const CatchReturnInst &RI);
4382  CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4383  CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4384
4385  void init(Value *CatchPad, BasicBlock *BB);
4386
4387protected:
4388  // Note: Instruction needs to be a friend here to call cloneImpl.
4389  friend class Instruction;
4390
4391  CatchReturnInst *cloneImpl() const;
4392
4393public:
4394  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4395                                 Instruction *InsertBefore = nullptr) {
4396    assert(CatchPad);
4397    assert(BB);
4398    return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4399  }
4400
4401  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4402                                 BasicBlock *InsertAtEnd) {
4403    assert(CatchPad);
4404    assert(BB);
4405    return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4406  }
4407
4408  /// Provide fast operand accessors
4409  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4410
4411  /// Convenience accessors.
4412  CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4413  void setCatchPad(CatchPadInst *CatchPad) {
4414    assert(CatchPad);
4415    Op<0>() = CatchPad;
4416  }
4417
4418  BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4419  void setSuccessor(BasicBlock *NewSucc) {
4420    assert(NewSucc);
4421    Op<1>() = NewSucc;
4422  }
4423  unsigned getNumSuccessors() const { return 1; }
4424
4425  /// Get the parentPad of this catchret's catchpad's catchswitch.
4426  /// The successor block is implicitly a member of this funclet.
4427  Value *getCatchSwitchParentPad() const {
4428    return getCatchPad()->getCatchSwitch()->getParentPad();
4429  }
4430
4431  // Methods for support type inquiry through isa, cast, and dyn_cast:
4432  static bool classof(const Instruction *I) {
4433    return (I->getOpcode() == Instruction::CatchRet);
4434  }
4435  static bool classof(const Value *V) {
4436    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4437  }
4438
4439private:
4440  friend TerminatorInst;
4441
4442  BasicBlock *getSuccessor(unsigned Idx) const {
4443    assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4444    return getSuccessor();
4445  }
4446
4447  void setSuccessor(unsigned Idx, BasicBlock *B) {
4448    assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4449    setSuccessor(B);
4450  }
4451};
4452
4453template <>
4454struct OperandTraits<CatchReturnInst>
4455    : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4456
4457DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4458
4459//===----------------------------------------------------------------------===//
4460//                               CleanupReturnInst Class
4461//===----------------------------------------------------------------------===//
4462
4463class CleanupReturnInst : public TerminatorInst {
4464private:
4465  CleanupReturnInst(const CleanupReturnInst &RI);
4466  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4467                    Instruction *InsertBefore = nullptr);
4468  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4469                    BasicBlock *InsertAtEnd);
4470
4471  void init(Value *CleanupPad, BasicBlock *UnwindBB);
4472
4473protected:
4474  // Note: Instruction needs to be a friend here to call cloneImpl.
4475  friend class Instruction;
4476
4477  CleanupReturnInst *cloneImpl() const;
4478
4479public:
4480  static CleanupReturnInst *Create(Value *CleanupPad,
4481                                   BasicBlock *UnwindBB = nullptr,
4482                                   Instruction *InsertBefore = nullptr) {
4483    assert(CleanupPad);
4484    unsigned Values = 1;
4485    if (UnwindBB)
4486      ++Values;
4487    return new (Values)
4488        CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4489  }
4490
4491  static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4492                                   BasicBlock *InsertAtEnd) {
4493    assert(CleanupPad);
4494    unsigned Values = 1;
4495    if (UnwindBB)
4496      ++Values;
4497    return new (Values)
4498        CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4499  }
4500
4501  /// Provide fast operand accessors
4502  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4503
4504  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4505  bool unwindsToCaller() const { return !hasUnwindDest(); }
4506
4507  /// Convenience accessor.
4508  CleanupPadInst *getCleanupPad() const {
4509    return cast<CleanupPadInst>(Op<0>());
4510  }
4511  void setCleanupPad(CleanupPadInst *CleanupPad) {
4512    assert(CleanupPad);
4513    Op<0>() = CleanupPad;
4514  }
4515
4516  unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4517
4518  BasicBlock *getUnwindDest() const {
4519    return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4520  }
4521  void setUnwindDest(BasicBlock *NewDest) {
4522    assert(NewDest);
4523    assert(hasUnwindDest());
4524    Op<1>() = NewDest;
4525  }
4526
4527  // Methods for support type inquiry through isa, cast, and dyn_cast:
4528  static bool classof(const Instruction *I) {
4529    return (I->getOpcode() == Instruction::CleanupRet);
4530  }
4531  static bool classof(const Value *V) {
4532    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4533  }
4534
4535private:
4536  friend TerminatorInst;
4537
4538  BasicBlock *getSuccessor(unsigned Idx) const {
4539    assert(Idx == 0);
4540    return getUnwindDest();
4541  }
4542
4543  void setSuccessor(unsigned Idx, BasicBlock *B) {
4544    assert(Idx == 0);
4545    setUnwindDest(B);
4546  }
4547
4548  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4549  // method so that subclasses cannot accidentally use it.
4550  void setInstructionSubclassData(unsigned short D) {
4551    Instruction::setInstructionSubclassData(D);
4552  }
4553};
4554
4555template <>
4556struct OperandTraits<CleanupReturnInst>
4557    : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4558
4559DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4560
4561//===----------------------------------------------------------------------===//
4562//                           UnreachableInst Class
4563//===----------------------------------------------------------------------===//
4564
4565//===---------------------------------------------------------------------------
4566/// This function has undefined behavior.  In particular, the
4567/// presence of this instruction indicates some higher level knowledge that the
4568/// end of the block cannot be reached.
4569///
4570class UnreachableInst : public TerminatorInst {
4571protected:
4572  // Note: Instruction needs to be a friend here to call cloneImpl.
4573  friend class Instruction;
4574
4575  UnreachableInst *cloneImpl() const;
4576
4577public:
4578  explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4579  explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4580
4581  // allocate space for exactly zero operands
4582  void *operator new(size_t s) {
4583    return User::operator new(s, 0);
4584  }
4585
4586  unsigned getNumSuccessors() const { return 0; }
4587
4588  // Methods for support type inquiry through isa, cast, and dyn_cast:
4589  static bool classof(const Instruction *I) {
4590    return I->getOpcode() == Instruction::Unreachable;
4591  }
4592  static bool classof(const Value *V) {
4593    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4594  }
4595
4596private:
4597  friend TerminatorInst;
4598
4599  BasicBlock *getSuccessor(unsigned idx) const {
4600    llvm_unreachable("UnreachableInst has no successors!");
4601  }
4602
4603  void setSuccessor(unsigned idx, BasicBlock *B) {
4604    llvm_unreachable("UnreachableInst has no successors!");
4605  }
4606};
4607
4608//===----------------------------------------------------------------------===//
4609//                                 TruncInst Class
4610//===----------------------------------------------------------------------===//
4611
4612/// This class represents a truncation of integer types.
4613class TruncInst : public CastInst {
4614protected:
4615  // Note: Instruction needs to be a friend here to call cloneImpl.
4616  friend class Instruction;
4617
4618  /// Clone an identical TruncInst
4619  TruncInst *cloneImpl() const;
4620
4621public:
4622  /// Constructor with insert-before-instruction semantics
4623  TruncInst(
4624    Value *S,                           ///< The value to be truncated
4625    Type *Ty,                           ///< The (smaller) type to truncate to
4626    const Twine &NameStr = "",          ///< A name for the new instruction
4627    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4628  );
4629
4630  /// Constructor with insert-at-end-of-block semantics
4631  TruncInst(
4632    Value *S,                     ///< The value to be truncated
4633    Type *Ty,                     ///< The (smaller) type to truncate to
4634    const Twine &NameStr,         ///< A name for the new instruction
4635    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4636  );
4637
4638  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4639  static bool classof(const Instruction *I) {
4640    return I->getOpcode() == Trunc;
4641  }
4642  static bool classof(const Value *V) {
4643    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4644  }
4645};
4646
4647//===----------------------------------------------------------------------===//
4648//                                 ZExtInst Class
4649//===----------------------------------------------------------------------===//
4650
4651/// This class represents zero extension of integer types.
4652class ZExtInst : public CastInst {
4653protected:
4654  // Note: Instruction needs to be a friend here to call cloneImpl.
4655  friend class Instruction;
4656
4657  /// Clone an identical ZExtInst
4658  ZExtInst *cloneImpl() const;
4659
4660public:
4661  /// Constructor with insert-before-instruction semantics
4662  ZExtInst(
4663    Value *S,                           ///< The value to be zero extended
4664    Type *Ty,                           ///< The type to zero extend to
4665    const Twine &NameStr = "",          ///< A name for the new instruction
4666    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4667  );
4668
4669  /// Constructor with insert-at-end semantics.
4670  ZExtInst(
4671    Value *S,                     ///< The value to be zero extended
4672    Type *Ty,                     ///< The type to zero extend to
4673    const Twine &NameStr,         ///< A name for the new instruction
4674    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4675  );
4676
4677  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4678  static bool classof(const Instruction *I) {
4679    return I->getOpcode() == ZExt;
4680  }
4681  static bool classof(const Value *V) {
4682    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4683  }
4684};
4685
4686//===----------------------------------------------------------------------===//
4687//                                 SExtInst Class
4688//===----------------------------------------------------------------------===//
4689
4690/// This class represents a sign extension of integer types.
4691class SExtInst : public CastInst {
4692protected:
4693  // Note: Instruction needs to be a friend here to call cloneImpl.
4694  friend class Instruction;
4695
4696  /// Clone an identical SExtInst
4697  SExtInst *cloneImpl() const;
4698
4699public:
4700  /// Constructor with insert-before-instruction semantics
4701  SExtInst(
4702    Value *S,                           ///< The value to be sign extended
4703    Type *Ty,                           ///< The type to sign extend to
4704    const Twine &NameStr = "",          ///< A name for the new instruction
4705    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4706  );
4707
4708  /// Constructor with insert-at-end-of-block semantics
4709  SExtInst(
4710    Value *S,                     ///< The value to be sign extended
4711    Type *Ty,                     ///< The type to sign extend to
4712    const Twine &NameStr,         ///< A name for the new instruction
4713    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4714  );
4715
4716  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4717  static bool classof(const Instruction *I) {
4718    return I->getOpcode() == SExt;
4719  }
4720  static bool classof(const Value *V) {
4721    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4722  }
4723};
4724
4725//===----------------------------------------------------------------------===//
4726//                                 FPTruncInst Class
4727//===----------------------------------------------------------------------===//
4728
4729/// This class represents a truncation of floating point types.
4730class FPTruncInst : public CastInst {
4731protected:
4732  // Note: Instruction needs to be a friend here to call cloneImpl.
4733  friend class Instruction;
4734
4735  /// Clone an identical FPTruncInst
4736  FPTruncInst *cloneImpl() const;
4737
4738public:
4739  /// Constructor with insert-before-instruction semantics
4740  FPTruncInst(
4741    Value *S,                           ///< The value to be truncated
4742    Type *Ty,                           ///< The type to truncate to
4743    const Twine &NameStr = "",          ///< A name for the new instruction
4744    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4745  );
4746
4747  /// Constructor with insert-before-instruction semantics
4748  FPTruncInst(
4749    Value *S,                     ///< The value to be truncated
4750    Type *Ty,                     ///< The type to truncate to
4751    const Twine &NameStr,         ///< A name for the new instruction
4752    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4753  );
4754
4755  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4756  static bool classof(const Instruction *I) {
4757    return I->getOpcode() == FPTrunc;
4758  }
4759  static bool classof(const Value *V) {
4760    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4761  }
4762};
4763
4764//===----------------------------------------------------------------------===//
4765//                                 FPExtInst Class
4766//===----------------------------------------------------------------------===//
4767
4768/// This class represents an extension of floating point types.
4769class FPExtInst : public CastInst {
4770protected:
4771  // Note: Instruction needs to be a friend here to call cloneImpl.
4772  friend class Instruction;
4773
4774  /// Clone an identical FPExtInst
4775  FPExtInst *cloneImpl() const;
4776
4777public:
4778  /// Constructor with insert-before-instruction semantics
4779  FPExtInst(
4780    Value *S,                           ///< The value to be extended
4781    Type *Ty,                           ///< The type to extend to
4782    const Twine &NameStr = "",          ///< A name for the new instruction
4783    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4784  );
4785
4786  /// Constructor with insert-at-end-of-block semantics
4787  FPExtInst(
4788    Value *S,                     ///< The value to be extended
4789    Type *Ty,                     ///< The type to extend to
4790    const Twine &NameStr,         ///< A name for the new instruction
4791    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4792  );
4793
4794  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4795  static bool classof(const Instruction *I) {
4796    return I->getOpcode() == FPExt;
4797  }
4798  static bool classof(const Value *V) {
4799    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4800  }
4801};
4802
4803//===----------------------------------------------------------------------===//
4804//                                 UIToFPInst Class
4805//===----------------------------------------------------------------------===//
4806
4807/// This class represents a cast unsigned integer to floating point.
4808class UIToFPInst : public CastInst {
4809protected:
4810  // Note: Instruction needs to be a friend here to call cloneImpl.
4811  friend class Instruction;
4812
4813  /// Clone an identical UIToFPInst
4814  UIToFPInst *cloneImpl() const;
4815
4816public:
4817  /// Constructor with insert-before-instruction semantics
4818  UIToFPInst(
4819    Value *S,                           ///< The value to be converted
4820    Type *Ty,                           ///< The type to convert to
4821    const Twine &NameStr = "",          ///< A name for the new instruction
4822    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4823  );
4824
4825  /// Constructor with insert-at-end-of-block semantics
4826  UIToFPInst(
4827    Value *S,                     ///< The value to be converted
4828    Type *Ty,                     ///< The type to convert to
4829    const Twine &NameStr,         ///< A name for the new instruction
4830    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4831  );
4832
4833  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4834  static bool classof(const Instruction *I) {
4835    return I->getOpcode() == UIToFP;
4836  }
4837  static bool classof(const Value *V) {
4838    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4839  }
4840};
4841
4842//===----------------------------------------------------------------------===//
4843//                                 SIToFPInst Class
4844//===----------------------------------------------------------------------===//
4845
4846/// This class represents a cast from signed integer to floating point.
4847class SIToFPInst : public CastInst {
4848protected:
4849  // Note: Instruction needs to be a friend here to call cloneImpl.
4850  friend class Instruction;
4851
4852  /// Clone an identical SIToFPInst
4853  SIToFPInst *cloneImpl() const;
4854
4855public:
4856  /// Constructor with insert-before-instruction semantics
4857  SIToFPInst(
4858    Value *S,                           ///< The value to be converted
4859    Type *Ty,                           ///< The type to convert to
4860    const Twine &NameStr = "",          ///< A name for the new instruction
4861    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4862  );
4863
4864  /// Constructor with insert-at-end-of-block semantics
4865  SIToFPInst(
4866    Value *S,                     ///< The value to be converted
4867    Type *Ty,                     ///< The type to convert to
4868    const Twine &NameStr,         ///< A name for the new instruction
4869    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4870  );
4871
4872  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4873  static bool classof(const Instruction *I) {
4874    return I->getOpcode() == SIToFP;
4875  }
4876  static bool classof(const Value *V) {
4877    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4878  }
4879};
4880
4881//===----------------------------------------------------------------------===//
4882//                                 FPToUIInst Class
4883//===----------------------------------------------------------------------===//
4884
4885/// This class represents a cast from floating point to unsigned integer
4886class FPToUIInst  : public CastInst {
4887protected:
4888  // Note: Instruction needs to be a friend here to call cloneImpl.
4889  friend class Instruction;
4890
4891  /// Clone an identical FPToUIInst
4892  FPToUIInst *cloneImpl() const;
4893
4894public:
4895  /// Constructor with insert-before-instruction semantics
4896  FPToUIInst(
4897    Value *S,                           ///< The value to be converted
4898    Type *Ty,                           ///< The type to convert to
4899    const Twine &NameStr = "",          ///< A name for the new instruction
4900    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4901  );
4902
4903  /// Constructor with insert-at-end-of-block semantics
4904  FPToUIInst(
4905    Value *S,                     ///< The value to be converted
4906    Type *Ty,                     ///< The type to convert to
4907    const Twine &NameStr,         ///< A name for the new instruction
4908    BasicBlock *InsertAtEnd       ///< Where to insert the new instruction
4909  );
4910
4911  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4912  static bool classof(const Instruction *I) {
4913    return I->getOpcode() == FPToUI;
4914  }
4915  static bool classof(const Value *V) {
4916    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4917  }
4918};
4919
4920//===----------------------------------------------------------------------===//
4921//                                 FPToSIInst Class
4922//===----------------------------------------------------------------------===//
4923
4924/// This class represents a cast from floating point to signed integer.
4925class FPToSIInst  : public CastInst {
4926protected:
4927  // Note: Instruction needs to be a friend here to call cloneImpl.
4928  friend class Instruction;
4929
4930  /// Clone an identical FPToSIInst
4931  FPToSIInst *cloneImpl() const;
4932
4933public:
4934  /// Constructor with insert-before-instruction semantics
4935  FPToSIInst(
4936    Value *S,                           ///< The value to be converted
4937    Type *Ty,                           ///< The type to convert to
4938    const Twine &NameStr = "",          ///< A name for the new instruction
4939    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4940  );
4941
4942  /// Constructor with insert-at-end-of-block semantics
4943  FPToSIInst(
4944    Value *S,                     ///< The value to be converted
4945    Type *Ty,                     ///< The type to convert to
4946    const Twine &NameStr,         ///< A name for the new instruction
4947    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4948  );
4949
4950  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4951  static bool classof(const Instruction *I) {
4952    return I->getOpcode() == FPToSI;
4953  }
4954  static bool classof(const Value *V) {
4955    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4956  }
4957};
4958
4959//===----------------------------------------------------------------------===//
4960//                                 IntToPtrInst Class
4961//===----------------------------------------------------------------------===//
4962
4963/// This class represents a cast from an integer to a pointer.
4964class IntToPtrInst : public CastInst {
4965public:
4966  // Note: Instruction needs to be a friend here to call cloneImpl.
4967  friend class Instruction;
4968
4969  /// Constructor with insert-before-instruction semantics
4970  IntToPtrInst(
4971    Value *S,                           ///< The value to be converted
4972    Type *Ty,                           ///< The type to convert to
4973    const Twine &NameStr = "",          ///< A name for the new instruction
4974    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4975  );
4976
4977  /// Constructor with insert-at-end-of-block semantics
4978  IntToPtrInst(
4979    Value *S,                     ///< The value to be converted
4980    Type *Ty,                     ///< The type to convert to
4981    const Twine &NameStr,         ///< A name for the new instruction
4982    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4983  );
4984
4985  /// Clone an identical IntToPtrInst.
4986  IntToPtrInst *cloneImpl() const;
4987
4988  /// Returns the address space of this instruction's pointer type.
4989  unsigned getAddressSpace() const {
4990    return getType()->getPointerAddressSpace();
4991  }
4992
4993  // Methods for support type inquiry through isa, cast, and dyn_cast:
4994  static bool classof(const Instruction *I) {
4995    return I->getOpcode() == IntToPtr;
4996  }
4997  static bool classof(const Value *V) {
4998    return isa<Instruction>(V) && classof(cast<Instruction>(V));
4999  }
5000};
5001
5002//===----------------------------------------------------------------------===//
5003//                                 PtrToIntInst Class
5004//===----------------------------------------------------------------------===//
5005
5006/// This class represents a cast from a pointer to an integer.
5007class PtrToIntInst : public CastInst {
5008protected:
5009  // Note: Instruction needs to be a friend here to call cloneImpl.
5010  friend class Instruction;
5011
5012  /// Clone an identical PtrToIntInst.
5013  PtrToIntInst *cloneImpl() const;
5014
5015public:
5016  /// Constructor with insert-before-instruction semantics
5017  PtrToIntInst(
5018    Value *S,                           ///< The value to be converted
5019    Type *Ty,                           ///< The type to convert to
5020    const Twine &NameStr = "",          ///< A name for the new instruction
5021    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5022  );
5023
5024  /// Constructor with insert-at-end-of-block semantics
5025  PtrToIntInst(
5026    Value *S,                     ///< The value to be converted
5027    Type *Ty,                     ///< The type to convert to
5028    const Twine &NameStr,         ///< A name for the new instruction
5029    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
5030  );
5031
5032  /// Gets the pointer operand.
5033  Value *getPointerOperand() { return getOperand(0); }
5034  /// Gets the pointer operand.
5035  const Value *getPointerOperand() const { return getOperand(0); }
5036  /// Gets the operand index of the pointer operand.
5037  static unsigned getPointerOperandIndex() { return 0U; }
5038
5039  /// Returns the address space of the pointer operand.
5040  unsigned getPointerAddressSpace() const {
5041    return getPointerOperand()->getType()->getPointerAddressSpace();
5042  }
5043
5044  // Methods for support type inquiry through isa, cast, and dyn_cast:
5045  static bool classof(const Instruction *I) {
5046    return I->getOpcode() == PtrToInt;
5047  }
5048  static bool classof(const Value *V) {
5049    return isa<Instruction>(V) && classof(cast<Instruction>(V));
5050  }
5051};
5052
5053//===----------------------------------------------------------------------===//
5054//                             BitCastInst Class
5055//===----------------------------------------------------------------------===//
5056
5057/// This class represents a no-op cast from one type to another.
5058class BitCastInst : public CastInst {
5059protected:
5060  // Note: Instruction needs to be a friend here to call cloneImpl.
5061  friend class Instruction;
5062
5063  /// Clone an identical BitCastInst.
5064  BitCastInst *cloneImpl() const;
5065
5066public:
5067  /// Constructor with insert-before-instruction semantics
5068  BitCastInst(
5069    Value *S,                           ///< The value to be casted
5070    Type *Ty,                           ///< The type to casted to
5071    const Twine &NameStr = "",          ///< A name for the new instruction
5072    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5073  );
5074
5075  /// Constructor with insert-at-end-of-block semantics
5076  BitCastInst(
5077    Value *S,                     ///< The value to be casted
5078    Type *Ty,                     ///< The type to casted to
5079    const Twine &NameStr,         ///< A name for the new instruction
5080    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
5081  );
5082
5083  // Methods for support type inquiry through isa, cast, and dyn_cast:
5084  static bool classof(const Instruction *I) {
5085    return I->getOpcode() == BitCast;
5086  }
5087  static bool classof(const Value *V) {
5088    return isa<Instruction>(V) && classof(cast<Instruction>(V));
5089  }
5090};
5091
5092//===----------------------------------------------------------------------===//
5093//                          AddrSpaceCastInst Class
5094//===----------------------------------------------------------------------===//
5095
5096/// This class represents a conversion between pointers from one address space
5097/// to another.
5098class AddrSpaceCastInst : public CastInst {
5099protected:
5100  // Note: Instruction needs to be a friend here to call cloneImpl.
5101  friend class Instruction;
5102
5103  /// Clone an identical AddrSpaceCastInst.
5104  AddrSpaceCastInst *cloneImpl() const;
5105
5106public:
5107  /// Constructor with insert-before-instruction semantics
5108  AddrSpaceCastInst(
5109    Value *S,                           ///< The value to be casted
5110    Type *Ty,                           ///< The type to casted to
5111    const Twine &NameStr = "",          ///< A name for the new instruction
5112    Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5113  );
5114
5115  /// Constructor with insert-at-end-of-block semantics
5116  AddrSpaceCastInst(
5117    Value *S,                     ///< The value to be casted
5118    Type *Ty,                     ///< The type to casted to
5119    const Twine &NameStr,         ///< A name for the new instruction
5120    BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
5121  );
5122
5123  // Methods for support type inquiry through isa, cast, and dyn_cast:
5124  static bool classof(const Instruction *I) {
5125    return I->getOpcode() == AddrSpaceCast;
5126  }
5127  static bool classof(const Value *V) {
5128    return isa<Instruction>(V) && classof(cast<Instruction>(V));
5129  }
5130
5131  /// Gets the pointer operand.
5132  Value *getPointerOperand() {
5133    return getOperand(0);
5134  }
5135
5136  /// Gets the pointer operand.
5137  const Value *getPointerOperand() const {
5138    return getOperand(0);
5139  }
5140
5141  /// Gets the operand index of the pointer operand.
5142  static unsigned getPointerOperandIndex() {
5143    return 0U;
5144  }
5145
5146  /// Returns the address space of the pointer operand.
5147  unsigned getSrcAddressSpace() const {
5148    return getPointerOperand()->getType()->getPointerAddressSpace();
5149  }
5150
5151  /// Returns the address space of the result.
5152  unsigned getDestAddressSpace() const {
5153    return getType()->getPointerAddressSpace();
5154  }
5155};
5156
5157} // end namespace llvm
5158
5159#endif // LLVM_IR_INSTRUCTIONS_H
5160