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