Use make_range to reduce mentions of iterator type. NFC
[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
1463   /// \brief Create a clone of \p CI with a different set of operand bundles and
1464   /// insert it before \p InsertPt.
1465   ///
1466   /// The returned call instruction is identical \p CI in every way except that
1467   /// the operand bundles for the new instruction are set to the operand bundles
1468   /// in \p Bundles.
1469   static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1470                           Instruction *InsertPt = nullptr);
1471
1472   /// CreateMalloc - Generate the IR for a call to malloc:
1473   /// 1. Compute the malloc call's argument as the specified type's size,
1474   ///    possibly multiplied by the array size if the array size is not
1475   ///    constant 1.
1476   /// 2. Call malloc with that argument.
1477   /// 3. Bitcast the result of the malloc call to the specified type.
1478   static Instruction *CreateMalloc(Instruction *InsertBefore,
1479                                    Type *IntPtrTy, Type *AllocTy,
1480                                    Value *AllocSize, Value *ArraySize = nullptr,
1481                                    Function* MallocF = nullptr,
1482                                    const Twine &Name = "");
1483   static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1484                                    Type *IntPtrTy, Type *AllocTy,
1485                                    Value *AllocSize, Value *ArraySize = nullptr,
1486                                    Function* MallocF = nullptr,
1487                                    const Twine &Name = "");
1488   /// CreateFree - Generate the IR for a call to the builtin free function.
1489   static Instruction* CreateFree(Value* Source, Instruction *InsertBefore);
1490   static Instruction* CreateFree(Value* Source, BasicBlock *InsertAtEnd);
1491
1492   ~CallInst() override;
1493
1494   FunctionType *getFunctionType() const { return FTy; }
1495
1496   void mutateFunctionType(FunctionType *FTy) {
1497     mutateType(FTy->getReturnType());
1498     this->FTy = FTy;
1499   }
1500
1501   // Note that 'musttail' implies 'tail'.
1502   enum TailCallKind { TCK_None = 0, TCK_Tail = 1, TCK_MustTail = 2,
1503                       TCK_NoTail = 3 };
1504   TailCallKind getTailCallKind() const {
1505     return TailCallKind(getSubclassDataFromInstruction() & 3);
1506   }
1507   bool isTailCall() const {
1508     unsigned Kind = getSubclassDataFromInstruction() & 3;
1509     return Kind == TCK_Tail || Kind == TCK_MustTail;
1510   }
1511   bool isMustTailCall() const {
1512     return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1513   }
1514   bool isNoTailCall() const {
1515     return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1516   }
1517   void setTailCall(bool isTC = true) {
1518     setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1519                                unsigned(isTC ? TCK_Tail : TCK_None));
1520   }
1521   void setTailCallKind(TailCallKind TCK) {
1522     setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1523                                unsigned(TCK));
1524   }
1525
1526   /// Provide fast operand accessors
1527   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1528
1529   /// getNumArgOperands - Return the number of call arguments.
1530   ///
1531   unsigned getNumArgOperands() const {
1532     return getNumOperands() - getNumTotalBundleOperands() - 1;
1533   }
1534
1535   /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1536   ///
1537   Value *getArgOperand(unsigned i) const {
1538     assert(i < getNumArgOperands() && "Out of bounds!");
1539     return getOperand(i);
1540   }
1541   void setArgOperand(unsigned i, Value *v) {
1542     assert(i < getNumArgOperands() && "Out of bounds!");
1543     setOperand(i, v);
1544   }
1545
1546   /// arg_operands - iteration adapter for range-for loops.
1547   iterator_range<op_iterator> arg_operands() {
1548     // The last operand in the op list is the callee - it's not one of the args
1549     // so we don't want to iterate over it.
1550     return make_range(op_begin(), op_end() - getNumTotalBundleOperands() - 1);
1551   }
1552
1553   /// arg_operands - iteration adapter for range-for loops.
1554   iterator_range<const_op_iterator> arg_operands() const {
1555     return make_range(op_begin(), op_end() - getNumTotalBundleOperands() - 1);
1556   }
1557
1558   /// \brief Wrappers for getting the \c Use of a call argument.
1559   const Use &getArgOperandUse(unsigned i) const {
1560     assert(i < getNumArgOperands() && "Out of bounds!");
1561     return getOperandUse(i);
1562   }
1563   Use &getArgOperandUse(unsigned i) {
1564     assert(i < getNumArgOperands() && "Out of bounds!");
1565     return getOperandUse(i);
1566   }
1567
1568   /// getCallingConv/setCallingConv - Get or set the calling convention of this
1569   /// function call.
1570   CallingConv::ID getCallingConv() const {
1571     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1572   }
1573   void setCallingConv(CallingConv::ID CC) {
1574     auto ID = static_cast<unsigned>(CC);
1575     assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1576     setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1577                                (ID << 2));
1578   }
1579
1580   /// getAttributes - Return the parameter attributes for this call.
1581   ///
1582   const AttributeSet &getAttributes() const { return AttributeList; }
1583
1584   /// setAttributes - Set the parameter attributes for this call.
1585   ///
1586   void setAttributes(const AttributeSet &Attrs) { AttributeList = Attrs; }
1587
1588   /// addAttribute - adds the attribute to the list of attributes.
1589   void addAttribute(unsigned i, Attribute::AttrKind attr);
1590
1591   /// addAttribute - adds the attribute to the list of attributes.
1592   void addAttribute(unsigned i, StringRef Kind, StringRef Value);
1593
1594   /// removeAttribute - removes the attribute from the list of attributes.
1595   void removeAttribute(unsigned i, Attribute attr);
1596
1597   /// \brief adds the dereferenceable attribute to the list of attributes.
1598   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
1599
1600   /// \brief adds the dereferenceable_or_null attribute to the list of
1601   /// attributes.
1602   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
1603
1604   /// \brief Determine whether this call has the given attribute.
1605   bool hasFnAttr(Attribute::AttrKind A) const {
1606     assert(A != Attribute::NoBuiltin &&
1607            "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
1608     return hasFnAttrImpl(A);
1609   }
1610
1611   /// \brief Determine whether this call has the given attribute.
1612   bool hasFnAttr(StringRef A) const {
1613     return hasFnAttrImpl(A);
1614   }
1615
1616   /// \brief Determine whether the call or the callee has the given attributes.
1617   bool paramHasAttr(unsigned i, Attribute::AttrKind A) const;
1618
1619   /// \brief Return true if the data operand at index \p i has the attribute \p
1620   /// A.
1621   ///
1622   /// Data operands include call arguments and values used in operand bundles,
1623   /// but does not include the callee operand.  This routine dispatches to the
1624   /// underlying AttributeList or the OperandBundleUser as appropriate.
1625   ///
1626   /// The index \p i is interpreted as
1627   ///
1628   ///  \p i == Attribute::ReturnIndex  -> the return value
1629   ///  \p i in [1, arg_size + 1)  -> argument number (\p i - 1)
1630   ///  \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1631   ///     (\p i - 1) in the operand list.
1632   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind A) const;
1633
1634   /// \brief Extract the alignment for a call or parameter (0=unknown).
1635   unsigned getParamAlignment(unsigned i) const {
1636     return AttributeList.getParamAlignment(i);
1637   }
1638
1639   /// \brief Extract the number of dereferenceable bytes for a call or
1640   /// parameter (0=unknown).
1641   uint64_t getDereferenceableBytes(unsigned i) const {
1642     return AttributeList.getDereferenceableBytes(i);
1643   }
1644
1645   /// \brief Extract the number of dereferenceable_or_null bytes for a call or
1646   /// parameter (0=unknown).
1647   uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1648     return AttributeList.getDereferenceableOrNullBytes(i);
1649   }
1650
1651   /// @brief Determine if the parameter or return value is marked with NoAlias
1652   /// attribute.
1653   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
1654   bool doesNotAlias(unsigned n) const {
1655     return AttributeList.hasAttribute(n, Attribute::NoAlias);
1656   }
1657
1658   /// \brief Return true if the call should not be treated as a call to a
1659   /// builtin.
1660   bool isNoBuiltin() const {
1661     return hasFnAttrImpl(Attribute::NoBuiltin) &&
1662       !hasFnAttrImpl(Attribute::Builtin);
1663   }
1664
1665   /// \brief Return true if the call should not be inlined.
1666   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1667   void setIsNoInline() {
1668     addAttribute(AttributeSet::FunctionIndex, Attribute::NoInline);
1669   }
1670
1671   /// \brief Return true if the call can return twice
1672   bool canReturnTwice() const {
1673     return hasFnAttr(Attribute::ReturnsTwice);
1674   }
1675   void setCanReturnTwice() {
1676     addAttribute(AttributeSet::FunctionIndex, Attribute::ReturnsTwice);
1677   }
1678
1679   /// \brief Determine if the call does not access memory.
1680   bool doesNotAccessMemory() const {
1681     return hasFnAttr(Attribute::ReadNone);
1682   }
1683   void setDoesNotAccessMemory() {
1684     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
1685   }
1686
1687   /// \brief Determine if the call does not access or only reads memory.
1688   bool onlyReadsMemory() const {
1689     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1690   }
1691   void setOnlyReadsMemory() {
1692     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
1693   }
1694
1695   /// @brief Determine if the call can access memmory only using pointers based
1696   /// on its arguments.
1697   bool onlyAccessesArgMemory() const {
1698     return hasFnAttr(Attribute::ArgMemOnly);
1699   }
1700   void setOnlyAccessesArgMemory() {
1701     addAttribute(AttributeSet::FunctionIndex, Attribute::ArgMemOnly);
1702   }
1703
1704   /// \brief Determine if the call cannot return.
1705   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1706   void setDoesNotReturn() {
1707     addAttribute(AttributeSet::FunctionIndex, Attribute::NoReturn);
1708   }
1709
1710   /// \brief Determine if the call cannot unwind.
1711   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1712   void setDoesNotThrow() {
1713     addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
1714   }
1715
1716   /// \brief Determine if the call cannot be duplicated.
1717   bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1718   void setCannotDuplicate() {
1719     addAttribute(AttributeSet::FunctionIndex, Attribute::NoDuplicate);
1720   }
1721
1722   /// \brief Determine if the call is convergent
1723   bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1724   void setConvergent() {
1725     addAttribute(AttributeSet::FunctionIndex, Attribute::Convergent);
1726   }
1727
1728   /// \brief Determine if the call returns a structure through first
1729   /// pointer argument.
1730   bool hasStructRetAttr() const {
1731     if (getNumArgOperands() == 0)
1732       return false;
1733
1734     // Be friendly and also check the callee.
1735     return paramHasAttr(1, Attribute::StructRet);
1736   }
1737
1738   /// \brief Determine if any call argument is an aggregate passed by value.
1739   bool hasByValArgument() const {
1740     return AttributeList.hasAttrSomewhere(Attribute::ByVal);
1741   }
1742
1743   /// getCalledFunction - Return the function called, or null if this is an
1744   /// indirect function invocation.
1745   ///
1746   Function *getCalledFunction() const {
1747     return dyn_cast<Function>(Op<-1>());
1748   }
1749
1750   /// getCalledValue - Get a pointer to the function that is invoked by this
1751   /// instruction.
1752   const Value *getCalledValue() const { return Op<-1>(); }
1753         Value *getCalledValue()       { return Op<-1>(); }
1754
1755   /// setCalledFunction - Set the function called.
1756   void setCalledFunction(Value* Fn) {
1757     setCalledFunction(
1758         cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1759         Fn);
1760   }
1761   void setCalledFunction(FunctionType *FTy, Value *Fn) {
1762     this->FTy = FTy;
1763     assert(FTy == cast<FunctionType>(
1764                       cast<PointerType>(Fn->getType())->getElementType()));
1765     Op<-1>() = Fn;
1766   }
1767
1768   /// isInlineAsm - Check if this call is an inline asm statement.
1769   bool isInlineAsm() const {
1770     return isa<InlineAsm>(Op<-1>());
1771   }
1772
1773   // Methods for support type inquiry through isa, cast, and dyn_cast:
1774   static inline bool classof(const Instruction *I) {
1775     return I->getOpcode() == Instruction::Call;
1776   }
1777   static inline bool classof(const Value *V) {
1778     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1779   }
1780
1781 private:
1782   template <typename AttrKind> bool hasFnAttrImpl(AttrKind A) const {
1783     if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
1784       return true;
1785
1786     // Operand bundles override attributes on the called function, but don't
1787     // override attributes directly present on the call instruction.
1788     if (isFnAttrDisallowedByOpBundle(A))
1789       return false;
1790
1791     if (const Function *F = getCalledFunction())
1792       return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
1793     return false;
1794   }
1795
1796   // Shadow Instruction::setInstructionSubclassData with a private forwarding
1797   // method so that subclasses cannot accidentally use it.
1798   void setInstructionSubclassData(unsigned short D) {
1799     Instruction::setInstructionSubclassData(D);
1800   }
1801 };
1802
1803 template <>
1804 struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1805 };
1806
1807 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1808                    ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1809                    BasicBlock *InsertAtEnd)
1810     : Instruction(
1811           cast<FunctionType>(cast<PointerType>(Func->getType())
1812                                  ->getElementType())->getReturnType(),
1813           Instruction::Call, OperandTraits<CallInst>::op_end(this) -
1814                                  (Args.size() + CountBundleInputs(Bundles) + 1),
1815           unsigned(Args.size() + CountBundleInputs(Bundles) + 1), InsertAtEnd) {
1816   init(Func, Args, Bundles, NameStr);
1817 }
1818
1819 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1820                    ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1821                    Instruction *InsertBefore)
1822     : Instruction(Ty->getReturnType(), Instruction::Call,
1823                   OperandTraits<CallInst>::op_end(this) -
1824                       (Args.size() + CountBundleInputs(Bundles) + 1),
1825                   unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1826                   InsertBefore) {
1827   init(Ty, Func, Args, Bundles, NameStr);
1828 }
1829
1830 // Note: if you get compile errors about private methods then
1831 //       please update your code to use the high-level operand
1832 //       interfaces. See line 943 above.
1833 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
1834
1835 //===----------------------------------------------------------------------===//
1836 //                               SelectInst Class
1837 //===----------------------------------------------------------------------===//
1838
1839 /// SelectInst - This class represents the LLVM 'select' instruction.
1840 ///
1841 class SelectInst : public Instruction {
1842   void init(Value *C, Value *S1, Value *S2) {
1843     assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1844     Op<0>() = C;
1845     Op<1>() = S1;
1846     Op<2>() = S2;
1847   }
1848
1849   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1850              Instruction *InsertBefore)
1851     : Instruction(S1->getType(), Instruction::Select,
1852                   &Op<0>(), 3, InsertBefore) {
1853     init(C, S1, S2);
1854     setName(NameStr);
1855   }
1856   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1857              BasicBlock *InsertAtEnd)
1858     : Instruction(S1->getType(), Instruction::Select,
1859                   &Op<0>(), 3, InsertAtEnd) {
1860     init(C, S1, S2);
1861     setName(NameStr);
1862   }
1863
1864 protected:
1865   // Note: Instruction needs to be a friend here to call cloneImpl.
1866   friend class Instruction;
1867   SelectInst *cloneImpl() const;
1868
1869 public:
1870   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1871                             const Twine &NameStr = "",
1872                             Instruction *InsertBefore = nullptr) {
1873     return new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1874   }
1875   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1876                             const Twine &NameStr,
1877                             BasicBlock *InsertAtEnd) {
1878     return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1879   }
1880
1881   const Value *getCondition() const { return Op<0>(); }
1882   const Value *getTrueValue() const { return Op<1>(); }
1883   const Value *getFalseValue() const { return Op<2>(); }
1884   Value *getCondition() { return Op<0>(); }
1885   Value *getTrueValue() { return Op<1>(); }
1886   Value *getFalseValue() { return Op<2>(); }
1887
1888   /// areInvalidOperands - Return a string if the specified operands are invalid
1889   /// for a select operation, otherwise return null.
1890   static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1891
1892   /// Transparently provide more efficient getOperand methods.
1893   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1894
1895   OtherOps getOpcode() const {
1896     return static_cast<OtherOps>(Instruction::getOpcode());
1897   }
1898
1899   // Methods for support type inquiry through isa, cast, and dyn_cast:
1900   static inline bool classof(const Instruction *I) {
1901     return I->getOpcode() == Instruction::Select;
1902   }
1903   static inline bool classof(const Value *V) {
1904     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1905   }
1906 };
1907
1908 template <>
1909 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1910 };
1911
1912 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1913
1914 //===----------------------------------------------------------------------===//
1915 //                                VAArgInst Class
1916 //===----------------------------------------------------------------------===//
1917
1918 /// VAArgInst - This class represents the va_arg llvm instruction, which returns
1919 /// an argument of the specified type given a va_list and increments that list
1920 ///
1921 class VAArgInst : public UnaryInstruction {
1922 protected:
1923   // Note: Instruction needs to be a friend here to call cloneImpl.
1924   friend class Instruction;
1925   VAArgInst *cloneImpl() const;
1926
1927 public:
1928   VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1929              Instruction *InsertBefore = nullptr)
1930     : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1931     setName(NameStr);
1932   }
1933   VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1934             BasicBlock *InsertAtEnd)
1935     : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1936     setName(NameStr);
1937   }
1938
1939   Value *getPointerOperand() { return getOperand(0); }
1940   const Value *getPointerOperand() const { return getOperand(0); }
1941   static unsigned getPointerOperandIndex() { return 0U; }
1942
1943   // Methods for support type inquiry through isa, cast, and dyn_cast:
1944   static inline bool classof(const Instruction *I) {
1945     return I->getOpcode() == VAArg;
1946   }
1947   static inline bool classof(const Value *V) {
1948     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1949   }
1950 };
1951
1952 //===----------------------------------------------------------------------===//
1953 //                                ExtractElementInst Class
1954 //===----------------------------------------------------------------------===//
1955
1956 /// ExtractElementInst - This instruction extracts a single (scalar)
1957 /// element from a VectorType value
1958 ///
1959 class ExtractElementInst : public Instruction {
1960   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1961                      Instruction *InsertBefore = nullptr);
1962   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1963                      BasicBlock *InsertAtEnd);
1964
1965 protected:
1966   // Note: Instruction needs to be a friend here to call cloneImpl.
1967   friend class Instruction;
1968   ExtractElementInst *cloneImpl() const;
1969
1970 public:
1971   static ExtractElementInst *Create(Value *Vec, Value *Idx,
1972                                    const Twine &NameStr = "",
1973                                    Instruction *InsertBefore = nullptr) {
1974     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1975   }
1976   static ExtractElementInst *Create(Value *Vec, Value *Idx,
1977                                    const Twine &NameStr,
1978                                    BasicBlock *InsertAtEnd) {
1979     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1980   }
1981
1982   /// isValidOperands - Return true if an extractelement instruction can be
1983   /// formed with the specified operands.
1984   static bool isValidOperands(const Value *Vec, const Value *Idx);
1985
1986   Value *getVectorOperand() { return Op<0>(); }
1987   Value *getIndexOperand() { return Op<1>(); }
1988   const Value *getVectorOperand() const { return Op<0>(); }
1989   const Value *getIndexOperand() const { return Op<1>(); }
1990
1991   VectorType *getVectorOperandType() const {
1992     return cast<VectorType>(getVectorOperand()->getType());
1993   }
1994
1995   /// Transparently provide more efficient getOperand methods.
1996   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1997
1998   // Methods for support type inquiry through isa, cast, and dyn_cast:
1999   static inline bool classof(const Instruction *I) {
2000     return I->getOpcode() == Instruction::ExtractElement;
2001   }
2002   static inline bool classof(const Value *V) {
2003     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2004   }
2005 };
2006
2007 template <>
2008 struct OperandTraits<ExtractElementInst> :
2009   public FixedNumOperandTraits<ExtractElementInst, 2> {
2010 };
2011
2012 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
2013
2014 //===----------------------------------------------------------------------===//
2015 //                                InsertElementInst Class
2016 //===----------------------------------------------------------------------===//
2017
2018 /// InsertElementInst - This instruction inserts a single (scalar)
2019 /// element into a VectorType value
2020 ///
2021 class InsertElementInst : public Instruction {
2022   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
2023                     const Twine &NameStr = "",
2024                     Instruction *InsertBefore = nullptr);
2025   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
2026                     BasicBlock *InsertAtEnd);
2027
2028 protected:
2029   // Note: Instruction needs to be a friend here to call cloneImpl.
2030   friend class Instruction;
2031   InsertElementInst *cloneImpl() const;
2032
2033 public:
2034   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2035                                    const Twine &NameStr = "",
2036                                    Instruction *InsertBefore = nullptr) {
2037     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
2038   }
2039   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2040                                    const Twine &NameStr,
2041                                    BasicBlock *InsertAtEnd) {
2042     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
2043   }
2044
2045   /// isValidOperands - Return true if an insertelement instruction can be
2046   /// formed with the specified operands.
2047   static bool isValidOperands(const Value *Vec, const Value *NewElt,
2048                               const Value *Idx);
2049
2050   /// getType - Overload to return most specific vector type.
2051   ///
2052   VectorType *getType() const {
2053     return cast<VectorType>(Instruction::getType());
2054   }
2055
2056   /// Transparently provide more efficient getOperand methods.
2057   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2058
2059   // Methods for support type inquiry through isa, cast, and dyn_cast:
2060   static inline bool classof(const Instruction *I) {
2061     return I->getOpcode() == Instruction::InsertElement;
2062   }
2063   static inline bool classof(const Value *V) {
2064     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2065   }
2066 };
2067
2068 template <>
2069 struct OperandTraits<InsertElementInst> :
2070   public FixedNumOperandTraits<InsertElementInst, 3> {
2071 };
2072
2073 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2074
2075 //===----------------------------------------------------------------------===//
2076 //                           ShuffleVectorInst Class
2077 //===----------------------------------------------------------------------===//
2078
2079 /// ShuffleVectorInst - This instruction constructs a fixed permutation of two
2080 /// input vectors.
2081 ///
2082 class ShuffleVectorInst : public Instruction {
2083 protected:
2084   // Note: Instruction needs to be a friend here to call cloneImpl.
2085   friend class Instruction;
2086   ShuffleVectorInst *cloneImpl() const;
2087
2088 public:
2089   // allocate space for exactly three operands
2090   void *operator new(size_t s) {
2091     return User::operator new(s, 3);
2092   }
2093   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2094                     const Twine &NameStr = "",
2095                     Instruction *InsertBefor = nullptr);
2096   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2097                     const Twine &NameStr, BasicBlock *InsertAtEnd);
2098
2099   /// isValidOperands - Return true if a shufflevector instruction can be
2100   /// formed with the specified operands.
2101   static bool isValidOperands(const Value *V1, const Value *V2,
2102                               const Value *Mask);
2103
2104   /// getType - Overload to return most specific vector type.
2105   ///
2106   VectorType *getType() const {
2107     return cast<VectorType>(Instruction::getType());
2108   }
2109
2110   /// Transparently provide more efficient getOperand methods.
2111   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2112
2113   Constant *getMask() const {
2114     return cast<Constant>(getOperand(2));
2115   }
2116
2117   /// getMaskValue - Return the index from the shuffle mask for the specified
2118   /// output result.  This is either -1 if the element is undef or a number less
2119   /// than 2*numelements.
2120   static int getMaskValue(Constant *Mask, unsigned i);
2121
2122   int getMaskValue(unsigned i) const {
2123     return getMaskValue(getMask(), i);
2124   }
2125
2126   /// getShuffleMask - Return the full mask for this instruction, where each
2127   /// element is the element number and undef's are returned as -1.
2128   static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
2129
2130   void getShuffleMask(SmallVectorImpl<int> &Result) const {
2131     return getShuffleMask(getMask(), Result);
2132   }
2133
2134   SmallVector<int, 16> getShuffleMask() const {
2135     SmallVector<int, 16> Mask;
2136     getShuffleMask(Mask);
2137     return Mask;
2138   }
2139
2140   // Methods for support type inquiry through isa, cast, and dyn_cast:
2141   static inline bool classof(const Instruction *I) {
2142     return I->getOpcode() == Instruction::ShuffleVector;
2143   }
2144   static inline bool classof(const Value *V) {
2145     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2146   }
2147 };
2148
2149 template <>
2150 struct OperandTraits<ShuffleVectorInst> :
2151   public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2152 };
2153
2154 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2155
2156 //===----------------------------------------------------------------------===//
2157 //                                ExtractValueInst Class
2158 //===----------------------------------------------------------------------===//
2159
2160 /// ExtractValueInst - This instruction extracts a struct member or array
2161 /// element value from an aggregate value.
2162 ///
2163 class ExtractValueInst : public UnaryInstruction {
2164   SmallVector<unsigned, 4> Indices;
2165
2166   ExtractValueInst(const ExtractValueInst &EVI);
2167   void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2168
2169   /// Constructors - Create a extractvalue instruction with a base aggregate
2170   /// value and a list of indices.  The first ctor can optionally insert before
2171   /// an existing instruction, the second appends the new instruction to the
2172   /// specified BasicBlock.
2173   inline ExtractValueInst(Value *Agg,
2174                           ArrayRef<unsigned> Idxs,
2175                           const Twine &NameStr,
2176                           Instruction *InsertBefore);
2177   inline ExtractValueInst(Value *Agg,
2178                           ArrayRef<unsigned> Idxs,
2179                           const Twine &NameStr, BasicBlock *InsertAtEnd);
2180
2181   // allocate space for exactly one operand
2182   void *operator new(size_t s) { return User::operator new(s, 1); }
2183
2184 protected:
2185   // Note: Instruction needs to be a friend here to call cloneImpl.
2186   friend class Instruction;
2187   ExtractValueInst *cloneImpl() const;
2188
2189 public:
2190   static ExtractValueInst *Create(Value *Agg,
2191                                   ArrayRef<unsigned> Idxs,
2192                                   const Twine &NameStr = "",
2193                                   Instruction *InsertBefore = nullptr) {
2194     return new
2195       ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2196   }
2197   static ExtractValueInst *Create(Value *Agg,
2198                                   ArrayRef<unsigned> Idxs,
2199                                   const Twine &NameStr,
2200                                   BasicBlock *InsertAtEnd) {
2201     return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2202   }
2203
2204   /// getIndexedType - Returns the type of the element that would be extracted
2205   /// with an extractvalue instruction with the specified parameters.
2206   ///
2207   /// Null is returned if the indices are invalid for the specified type.
2208   static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2209
2210   typedef const unsigned* idx_iterator;
2211   inline idx_iterator idx_begin() const { return Indices.begin(); }
2212   inline idx_iterator idx_end()   const { return Indices.end(); }
2213   inline iterator_range<idx_iterator> indices() const {
2214     return make_range(idx_begin(), idx_end());
2215   }
2216
2217   Value *getAggregateOperand() {
2218     return getOperand(0);
2219   }
2220   const Value *getAggregateOperand() const {
2221     return getOperand(0);
2222   }
2223   static unsigned getAggregateOperandIndex() {
2224     return 0U;                      // get index for modifying correct operand
2225   }
2226
2227   ArrayRef<unsigned> getIndices() const {
2228     return Indices;
2229   }
2230
2231   unsigned getNumIndices() const {
2232     return (unsigned)Indices.size();
2233   }
2234
2235   bool hasIndices() const {
2236     return true;
2237   }
2238
2239   // Methods for support type inquiry through isa, cast, and dyn_cast:
2240   static inline bool classof(const Instruction *I) {
2241     return I->getOpcode() == Instruction::ExtractValue;
2242   }
2243   static inline bool classof(const Value *V) {
2244     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2245   }
2246 };
2247
2248 ExtractValueInst::ExtractValueInst(Value *Agg,
2249                                    ArrayRef<unsigned> Idxs,
2250                                    const Twine &NameStr,
2251                                    Instruction *InsertBefore)
2252   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2253                      ExtractValue, Agg, InsertBefore) {
2254   init(Idxs, NameStr);
2255 }
2256 ExtractValueInst::ExtractValueInst(Value *Agg,
2257                                    ArrayRef<unsigned> Idxs,
2258                                    const Twine &NameStr,
2259                                    BasicBlock *InsertAtEnd)
2260   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2261                      ExtractValue, Agg, InsertAtEnd) {
2262   init(Idxs, NameStr);
2263 }
2264
2265 //===----------------------------------------------------------------------===//
2266 //                                InsertValueInst Class
2267 //===----------------------------------------------------------------------===//
2268
2269 /// InsertValueInst - This instruction inserts a struct field of array element
2270 /// value into an aggregate value.
2271 ///
2272 class InsertValueInst : public Instruction {
2273   SmallVector<unsigned, 4> Indices;
2274
2275   void *operator new(size_t, unsigned) = delete;
2276   InsertValueInst(const InsertValueInst &IVI);
2277   void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2278             const Twine &NameStr);
2279
2280   /// Constructors - Create a insertvalue instruction with a base aggregate
2281   /// value, a value to insert, and a list of indices.  The first ctor can
2282   /// optionally insert before an existing instruction, the second appends
2283   /// the new instruction to the specified BasicBlock.
2284   inline InsertValueInst(Value *Agg, Value *Val,
2285                          ArrayRef<unsigned> Idxs,
2286                          const Twine &NameStr,
2287                          Instruction *InsertBefore);
2288   inline InsertValueInst(Value *Agg, Value *Val,
2289                          ArrayRef<unsigned> Idxs,
2290                          const Twine &NameStr, BasicBlock *InsertAtEnd);
2291
2292   /// Constructors - These two constructors are convenience methods because one
2293   /// and two index insertvalue instructions are so common.
2294   InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2295                   const Twine &NameStr = "",
2296                   Instruction *InsertBefore = nullptr);
2297   InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2298                   BasicBlock *InsertAtEnd);
2299
2300 protected:
2301   // Note: Instruction needs to be a friend here to call cloneImpl.
2302   friend class Instruction;
2303   InsertValueInst *cloneImpl() const;
2304
2305 public:
2306   // allocate space for exactly two operands
2307   void *operator new(size_t s) {
2308     return User::operator new(s, 2);
2309   }
2310
2311   static InsertValueInst *Create(Value *Agg, Value *Val,
2312                                  ArrayRef<unsigned> Idxs,
2313                                  const Twine &NameStr = "",
2314                                  Instruction *InsertBefore = nullptr) {
2315     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2316   }
2317   static InsertValueInst *Create(Value *Agg, Value *Val,
2318                                  ArrayRef<unsigned> Idxs,
2319                                  const Twine &NameStr,
2320                                  BasicBlock *InsertAtEnd) {
2321     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2322   }
2323
2324   /// Transparently provide more efficient getOperand methods.
2325   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2326
2327   typedef const unsigned* idx_iterator;
2328   inline idx_iterator idx_begin() const { return Indices.begin(); }
2329   inline idx_iterator idx_end()   const { return Indices.end(); }
2330   inline iterator_range<idx_iterator> indices() const {
2331     return make_range(idx_begin(), idx_end());
2332   }
2333
2334   Value *getAggregateOperand() {
2335     return getOperand(0);
2336   }
2337   const Value *getAggregateOperand() const {
2338     return getOperand(0);
2339   }
2340   static unsigned getAggregateOperandIndex() {
2341     return 0U;                      // get index for modifying correct operand
2342   }
2343
2344   Value *getInsertedValueOperand() {
2345     return getOperand(1);
2346   }
2347   const Value *getInsertedValueOperand() const {
2348     return getOperand(1);
2349   }
2350   static unsigned getInsertedValueOperandIndex() {
2351     return 1U;                      // get index for modifying correct operand
2352   }
2353
2354   ArrayRef<unsigned> getIndices() const {
2355     return Indices;
2356   }
2357
2358   unsigned getNumIndices() const {
2359     return (unsigned)Indices.size();
2360   }
2361
2362   bool hasIndices() const {
2363     return true;
2364   }
2365
2366   // Methods for support type inquiry through isa, cast, and dyn_cast:
2367   static inline bool classof(const Instruction *I) {
2368     return I->getOpcode() == Instruction::InsertValue;
2369   }
2370   static inline bool classof(const Value *V) {
2371     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2372   }
2373 };
2374
2375 template <>
2376 struct OperandTraits<InsertValueInst> :
2377   public FixedNumOperandTraits<InsertValueInst, 2> {
2378 };
2379
2380 InsertValueInst::InsertValueInst(Value *Agg,
2381                                  Value *Val,
2382                                  ArrayRef<unsigned> Idxs,
2383                                  const Twine &NameStr,
2384                                  Instruction *InsertBefore)
2385   : Instruction(Agg->getType(), InsertValue,
2386                 OperandTraits<InsertValueInst>::op_begin(this),
2387                 2, InsertBefore) {
2388   init(Agg, Val, Idxs, NameStr);
2389 }
2390 InsertValueInst::InsertValueInst(Value *Agg,
2391                                  Value *Val,
2392                                  ArrayRef<unsigned> Idxs,
2393                                  const Twine &NameStr,
2394                                  BasicBlock *InsertAtEnd)
2395   : Instruction(Agg->getType(), InsertValue,
2396                 OperandTraits<InsertValueInst>::op_begin(this),
2397                 2, InsertAtEnd) {
2398   init(Agg, Val, Idxs, NameStr);
2399 }
2400
2401 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2402
2403 //===----------------------------------------------------------------------===//
2404 //                               PHINode Class
2405 //===----------------------------------------------------------------------===//
2406
2407 // PHINode - The PHINode class is used to represent the magical mystical PHI
2408 // node, that can not exist in nature, but can be synthesized in a computer
2409 // scientist's overactive imagination.
2410 //
2411 class PHINode : public Instruction {
2412   void *operator new(size_t, unsigned) = delete;
2413   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
2414   /// the number actually in use.
2415   unsigned ReservedSpace;
2416   PHINode(const PHINode &PN);
2417   // allocate space for exactly zero operands
2418   void *operator new(size_t s) {
2419     return User::operator new(s);
2420   }
2421   explicit PHINode(Type *Ty, unsigned NumReservedValues,
2422                    const Twine &NameStr = "",
2423                    Instruction *InsertBefore = nullptr)
2424     : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2425       ReservedSpace(NumReservedValues) {
2426     setName(NameStr);
2427     allocHungoffUses(ReservedSpace);
2428   }
2429
2430   PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2431           BasicBlock *InsertAtEnd)
2432     : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2433       ReservedSpace(NumReservedValues) {
2434     setName(NameStr);
2435     allocHungoffUses(ReservedSpace);
2436   }
2437
2438 protected:
2439   // allocHungoffUses - this is more complicated than the generic
2440   // User::allocHungoffUses, because we have to allocate Uses for the incoming
2441   // values and pointers to the incoming blocks, all in one allocation.
2442   void allocHungoffUses(unsigned N) {
2443     User::allocHungoffUses(N, /* IsPhi */ true);
2444   }
2445
2446   // Note: Instruction needs to be a friend here to call cloneImpl.
2447   friend class Instruction;
2448   PHINode *cloneImpl() const;
2449
2450 public:
2451   /// Constructors - NumReservedValues is a hint for the number of incoming
2452   /// edges that this phi node will have (use 0 if you really have no idea).
2453   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2454                          const Twine &NameStr = "",
2455                          Instruction *InsertBefore = nullptr) {
2456     return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2457   }
2458   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2459                          const Twine &NameStr, BasicBlock *InsertAtEnd) {
2460     return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2461   }
2462
2463   /// Provide fast operand accessors
2464   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2465
2466   // Block iterator interface. This provides access to the list of incoming
2467   // basic blocks, which parallels the list of incoming values.
2468
2469   typedef BasicBlock **block_iterator;
2470   typedef BasicBlock * const *const_block_iterator;
2471
2472   block_iterator block_begin() {
2473     Use::UserRef *ref =
2474       reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2475     return reinterpret_cast<block_iterator>(ref + 1);
2476   }
2477
2478   const_block_iterator block_begin() const {
2479     const Use::UserRef *ref =
2480       reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2481     return reinterpret_cast<const_block_iterator>(ref + 1);
2482   }
2483
2484   block_iterator block_end() {
2485     return block_begin() + getNumOperands();
2486   }
2487
2488   const_block_iterator block_end() const {
2489     return block_begin() + getNumOperands();
2490   }
2491
2492   op_range incoming_values() { return operands(); }
2493
2494   const_op_range incoming_values() const { return operands(); }
2495
2496   /// getNumIncomingValues - Return the number of incoming edges
2497   ///
2498   unsigned getNumIncomingValues() const { return getNumOperands(); }
2499
2500   /// getIncomingValue - Return incoming value number x
2501   ///
2502   Value *getIncomingValue(unsigned i) const {
2503     return getOperand(i);
2504   }
2505   void setIncomingValue(unsigned i, Value *V) {
2506     assert(V && "PHI node got a null value!");
2507     assert(getType() == V->getType() &&
2508            "All operands to PHI node must be the same type as the PHI node!");
2509     setOperand(i, V);
2510   }
2511   static unsigned getOperandNumForIncomingValue(unsigned i) {
2512     return i;
2513   }
2514   static unsigned getIncomingValueNumForOperand(unsigned i) {
2515     return i;
2516   }
2517
2518   /// getIncomingBlock - Return incoming basic block number @p i.
2519   ///
2520   BasicBlock *getIncomingBlock(unsigned i) const {
2521     return block_begin()[i];
2522   }
2523
2524   /// getIncomingBlock - Return incoming basic block corresponding
2525   /// to an operand of the PHI.
2526   ///
2527   BasicBlock *getIncomingBlock(const Use &U) const {
2528     assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2529     return getIncomingBlock(unsigned(&U - op_begin()));
2530   }
2531
2532   /// getIncomingBlock - Return incoming basic block corresponding
2533   /// to value use iterator.
2534   ///
2535   BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2536     return getIncomingBlock(I.getUse());
2537   }
2538
2539   void setIncomingBlock(unsigned i, BasicBlock *BB) {
2540     assert(BB && "PHI node got a null basic block!");
2541     block_begin()[i] = BB;
2542   }
2543
2544   /// addIncoming - Add an incoming value to the end of the PHI list
2545   ///
2546   void addIncoming(Value *V, BasicBlock *BB) {
2547     if (getNumOperands() == ReservedSpace)
2548       growOperands();  // Get more space!
2549     // Initialize some new operands.
2550     setNumHungOffUseOperands(getNumOperands() + 1);
2551     setIncomingValue(getNumOperands() - 1, V);
2552     setIncomingBlock(getNumOperands() - 1, BB);
2553   }
2554
2555   /// removeIncomingValue - Remove an incoming value.  This is useful if a
2556   /// predecessor basic block is deleted.  The value removed is returned.
2557   ///
2558   /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2559   /// is true), the PHI node is destroyed and any uses of it are replaced with
2560   /// dummy values.  The only time there should be zero incoming values to a PHI
2561   /// node is when the block is dead, so this strategy is sound.
2562   ///
2563   Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2564
2565   Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2566     int Idx = getBasicBlockIndex(BB);
2567     assert(Idx >= 0 && "Invalid basic block argument to remove!");
2568     return removeIncomingValue(Idx, DeletePHIIfEmpty);
2569   }
2570
2571   /// getBasicBlockIndex - Return the first index of the specified basic
2572   /// block in the value list for this PHI.  Returns -1 if no instance.
2573   ///
2574   int getBasicBlockIndex(const BasicBlock *BB) const {
2575     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2576       if (block_begin()[i] == BB)
2577         return i;
2578     return -1;
2579   }
2580
2581   Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2582     int Idx = getBasicBlockIndex(BB);
2583     assert(Idx >= 0 && "Invalid basic block argument!");
2584     return getIncomingValue(Idx);
2585   }
2586
2587   /// hasConstantValue - If the specified PHI node always merges together the
2588   /// same value, return the value, otherwise return null.
2589   Value *hasConstantValue() const;
2590
2591   /// Methods for support type inquiry through isa, cast, and dyn_cast:
2592   static inline bool classof(const Instruction *I) {
2593     return I->getOpcode() == Instruction::PHI;
2594   }
2595   static inline bool classof(const Value *V) {
2596     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2597   }
2598
2599 private:
2600   void growOperands();
2601 };
2602
2603 template <>
2604 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2605 };
2606
2607 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2608
2609 //===----------------------------------------------------------------------===//
2610 //                           LandingPadInst Class
2611 //===----------------------------------------------------------------------===//
2612
2613 //===---------------------------------------------------------------------------
2614 /// LandingPadInst - The landingpad instruction holds all of the information
2615 /// necessary to generate correct exception handling. The landingpad instruction
2616 /// cannot be moved from the top of a landing pad block, which itself is
2617 /// accessible only from the 'unwind' edge of an invoke. This uses the
2618 /// SubclassData field in Value to store whether or not the landingpad is a
2619 /// cleanup.
2620 ///
2621 class LandingPadInst : public Instruction {
2622   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
2623   /// the number actually in use.
2624   unsigned ReservedSpace;
2625   LandingPadInst(const LandingPadInst &LP);
2626
2627 public:
2628   enum ClauseType { Catch, Filter };
2629
2630 private:
2631   void *operator new(size_t, unsigned) = delete;
2632   // Allocate space for exactly zero operands.
2633   void *operator new(size_t s) {
2634     return User::operator new(s);
2635   }
2636   void growOperands(unsigned Size);
2637   void init(unsigned NumReservedValues, const Twine &NameStr);
2638
2639   explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2640                           const Twine &NameStr, Instruction *InsertBefore);
2641   explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2642                           const Twine &NameStr, BasicBlock *InsertAtEnd);
2643
2644 protected:
2645   // Note: Instruction needs to be a friend here to call cloneImpl.
2646   friend class Instruction;
2647   LandingPadInst *cloneImpl() const;
2648
2649 public:
2650   /// Constructors - NumReservedClauses is a hint for the number of incoming
2651   /// clauses that this landingpad will have (use 0 if you really have no idea).
2652   static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2653                                 const Twine &NameStr = "",
2654                                 Instruction *InsertBefore = nullptr);
2655   static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2656                                 const Twine &NameStr, BasicBlock *InsertAtEnd);
2657
2658   /// Provide fast operand accessors
2659   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2660
2661   /// isCleanup - Return 'true' if this landingpad instruction is a
2662   /// cleanup. I.e., it should be run when unwinding even if its landing pad
2663   /// doesn't catch the exception.
2664   bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2665
2666   /// setCleanup - Indicate that this landingpad instruction is a cleanup.
2667   void setCleanup(bool V) {
2668     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2669                                (V ? 1 : 0));
2670   }
2671
2672   /// Add a catch or filter clause to the landing pad.
2673   void addClause(Constant *ClauseVal);
2674
2675   /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2676   /// determine what type of clause this is.
2677   Constant *getClause(unsigned Idx) const {
2678     return cast<Constant>(getOperandList()[Idx]);
2679   }
2680
2681   /// isCatch - Return 'true' if the clause and index Idx is a catch clause.
2682   bool isCatch(unsigned Idx) const {
2683     return !isa<ArrayType>(getOperandList()[Idx]->getType());
2684   }
2685
2686   /// isFilter - Return 'true' if the clause and index Idx is a filter clause.
2687   bool isFilter(unsigned Idx) const {
2688     return isa<ArrayType>(getOperandList()[Idx]->getType());
2689   }
2690
2691   /// getNumClauses - Get the number of clauses for this landing pad.
2692   unsigned getNumClauses() const { return getNumOperands(); }
2693
2694   /// reserveClauses - Grow the size of the operand list to accommodate the new
2695   /// number of clauses.
2696   void reserveClauses(unsigned Size) { growOperands(Size); }
2697
2698   // Methods for support type inquiry through isa, cast, and dyn_cast:
2699   static inline bool classof(const Instruction *I) {
2700     return I->getOpcode() == Instruction::LandingPad;
2701   }
2702   static inline bool classof(const Value *V) {
2703     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2704   }
2705 };
2706
2707 template <>
2708 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2709 };
2710
2711 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2712
2713 //===----------------------------------------------------------------------===//
2714 //                               ReturnInst Class
2715 //===----------------------------------------------------------------------===//
2716
2717 //===---------------------------------------------------------------------------
2718 /// ReturnInst - Return a value (possibly void), from a function.  Execution
2719 /// does not continue in this function any longer.
2720 ///
2721 class ReturnInst : public TerminatorInst {
2722   ReturnInst(const ReturnInst &RI);
2723
2724 private:
2725   // ReturnInst constructors:
2726   // ReturnInst()                  - 'ret void' instruction
2727   // ReturnInst(    null)          - 'ret void' instruction
2728   // ReturnInst(Value* X)          - 'ret X'    instruction
2729   // ReturnInst(    null, Inst *I) - 'ret void' instruction, insert before I
2730   // ReturnInst(Value* X, Inst *I) - 'ret X'    instruction, insert before I
2731   // ReturnInst(    null, BB *B)   - 'ret void' instruction, insert @ end of B
2732   // ReturnInst(Value* X, BB *B)   - 'ret X'    instruction, insert @ end of B
2733   //
2734   // NOTE: If the Value* passed is of type void then the constructor behaves as
2735   // if it was passed NULL.
2736   explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2737                       Instruction *InsertBefore = nullptr);
2738   ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2739   explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2740
2741 protected:
2742   // Note: Instruction needs to be a friend here to call cloneImpl.
2743   friend class Instruction;
2744   ReturnInst *cloneImpl() const;
2745
2746 public:
2747   static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2748                             Instruction *InsertBefore = nullptr) {
2749     return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2750   }
2751   static ReturnInst* Create(LLVMContext &C, Value *retVal,
2752                             BasicBlock *InsertAtEnd) {
2753     return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2754   }
2755   static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2756     return new(0) ReturnInst(C, InsertAtEnd);
2757   }
2758   ~ReturnInst() override;
2759
2760   /// Provide fast operand accessors
2761   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2762
2763   /// Convenience accessor. Returns null if there is no return value.
2764   Value *getReturnValue() const {
2765     return getNumOperands() != 0 ? getOperand(0) : nullptr;
2766   }
2767
2768   unsigned getNumSuccessors() const { return 0; }
2769
2770   // Methods for support type inquiry through isa, cast, and dyn_cast:
2771   static inline bool classof(const Instruction *I) {
2772     return (I->getOpcode() == Instruction::Ret);
2773   }
2774   static inline bool classof(const Value *V) {
2775     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2776   }
2777
2778 private:
2779   BasicBlock *getSuccessorV(unsigned idx) const override;
2780   unsigned getNumSuccessorsV() const override;
2781   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2782 };
2783
2784 template <>
2785 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2786 };
2787
2788 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2789
2790 //===----------------------------------------------------------------------===//
2791 //                               BranchInst Class
2792 //===----------------------------------------------------------------------===//
2793
2794 //===---------------------------------------------------------------------------
2795 /// BranchInst - Conditional or Unconditional Branch instruction.
2796 ///
2797 class BranchInst : public TerminatorInst {
2798   /// Ops list - Branches are strange.  The operands are ordered:
2799   ///  [Cond, FalseDest,] TrueDest.  This makes some accessors faster because
2800   /// they don't have to check for cond/uncond branchness. These are mostly
2801   /// accessed relative from op_end().
2802   BranchInst(const BranchInst &BI);
2803   void AssertOK();
2804   // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2805   // BranchInst(BB *B)                           - 'br B'
2806   // BranchInst(BB* T, BB *F, Value *C)          - 'br C, T, F'
2807   // BranchInst(BB* B, Inst *I)                  - 'br B'        insert before I
2808   // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2809   // BranchInst(BB* B, BB *I)                    - 'br B'        insert at end
2810   // BranchInst(BB* T, BB *F, Value *C, BB *I)   - 'br C, T, F', insert at end
2811   explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2812   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2813              Instruction *InsertBefore = nullptr);
2814   BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2815   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2816              BasicBlock *InsertAtEnd);
2817
2818 protected:
2819   // Note: Instruction needs to be a friend here to call cloneImpl.
2820   friend class Instruction;
2821   BranchInst *cloneImpl() const;
2822
2823 public:
2824   static BranchInst *Create(BasicBlock *IfTrue,
2825                             Instruction *InsertBefore = nullptr) {
2826     return new(1) BranchInst(IfTrue, InsertBefore);
2827   }
2828   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2829                             Value *Cond, Instruction *InsertBefore = nullptr) {
2830     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
2831   }
2832   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
2833     return new(1) BranchInst(IfTrue, InsertAtEnd);
2834   }
2835   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2836                             Value *Cond, BasicBlock *InsertAtEnd) {
2837     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
2838   }
2839
2840   /// Transparently provide more efficient getOperand methods.
2841   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2842
2843   bool isUnconditional() const { return getNumOperands() == 1; }
2844   bool isConditional()   const { return getNumOperands() == 3; }
2845
2846   Value *getCondition() const {
2847     assert(isConditional() && "Cannot get condition of an uncond branch!");
2848     return Op<-3>();
2849   }
2850
2851   void setCondition(Value *V) {
2852     assert(isConditional() && "Cannot set condition of unconditional branch!");
2853     Op<-3>() = V;
2854   }
2855
2856   unsigned getNumSuccessors() const { return 1+isConditional(); }
2857
2858   BasicBlock *getSuccessor(unsigned i) const {
2859     assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
2860     return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
2861   }
2862
2863   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
2864     assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
2865     *(&Op<-1>() - idx) = NewSucc;
2866   }
2867
2868   /// \brief Swap the successors of this branch instruction.
2869   ///
2870   /// Swaps the successors of the branch instruction. This also swaps any
2871   /// branch weight metadata associated with the instruction so that it
2872   /// continues to map correctly to each operand.
2873   void swapSuccessors();
2874
2875   // Methods for support type inquiry through isa, cast, and dyn_cast:
2876   static inline bool classof(const Instruction *I) {
2877     return (I->getOpcode() == Instruction::Br);
2878   }
2879   static inline bool classof(const Value *V) {
2880     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2881   }
2882
2883 private:
2884   BasicBlock *getSuccessorV(unsigned idx) const override;
2885   unsigned getNumSuccessorsV() const override;
2886   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2887 };
2888
2889 template <>
2890 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
2891 };
2892
2893 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
2894
2895 //===----------------------------------------------------------------------===//
2896 //                               SwitchInst Class
2897 //===----------------------------------------------------------------------===//
2898
2899 //===---------------------------------------------------------------------------
2900 /// SwitchInst - Multiway switch
2901 ///
2902 class SwitchInst : public TerminatorInst {
2903   void *operator new(size_t, unsigned) = delete;
2904   unsigned ReservedSpace;
2905   // Operand[0]    = Value to switch on
2906   // Operand[1]    = Default basic block destination
2907   // Operand[2n  ] = Value to match
2908   // Operand[2n+1] = BasicBlock to go to on match
2909   SwitchInst(const SwitchInst &SI);
2910   void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
2911   void growOperands();
2912   // allocate space for exactly zero operands
2913   void *operator new(size_t s) {
2914     return User::operator new(s);
2915   }
2916   /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2917   /// switch on and a default destination.  The number of additional cases can
2918   /// be specified here to make memory allocation more efficient.  This
2919   /// constructor can also autoinsert before another instruction.
2920   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2921              Instruction *InsertBefore);
2922
2923   /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2924   /// switch on and a default destination.  The number of additional cases can
2925   /// be specified here to make memory allocation more efficient.  This
2926   /// constructor also autoinserts at the end of the specified BasicBlock.
2927   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2928              BasicBlock *InsertAtEnd);
2929
2930 protected:
2931   // Note: Instruction needs to be a friend here to call cloneImpl.
2932   friend class Instruction;
2933   SwitchInst *cloneImpl() const;
2934
2935 public:
2936   // -2
2937   static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
2938
2939   template <class SwitchInstTy, class ConstantIntTy, class BasicBlockTy>
2940   class CaseIteratorT {
2941   protected:
2942     SwitchInstTy *SI;
2943     unsigned Index;
2944
2945   public:
2946     typedef CaseIteratorT<SwitchInstTy, ConstantIntTy, BasicBlockTy> Self;
2947
2948     /// Initializes case iterator for given SwitchInst and for given
2949     /// case number.
2950     CaseIteratorT(SwitchInstTy *SI, unsigned CaseNum) {
2951       this->SI = SI;
2952       Index = CaseNum;
2953     }
2954
2955     /// Initializes case iterator for given SwitchInst and for given
2956     /// TerminatorInst's successor index.
2957     static Self fromSuccessorIndex(SwitchInstTy *SI, unsigned SuccessorIndex) {
2958       assert(SuccessorIndex < SI->getNumSuccessors() &&
2959              "Successor index # out of range!");
2960       return SuccessorIndex != 0 ?
2961              Self(SI, SuccessorIndex - 1) :
2962              Self(SI, DefaultPseudoIndex);
2963     }
2964
2965     /// Resolves case value for current case.
2966     ConstantIntTy *getCaseValue() {
2967       assert(Index < SI->getNumCases() && "Index out the number of cases.");
2968       return reinterpret_cast<ConstantIntTy*>(SI->getOperand(2 + Index*2));
2969     }
2970
2971     /// Resolves successor for current case.
2972     BasicBlockTy *getCaseSuccessor() {
2973       assert((Index < SI->getNumCases() ||
2974               Index == DefaultPseudoIndex) &&
2975              "Index out the number of cases.");
2976       return SI->getSuccessor(getSuccessorIndex());
2977     }
2978
2979     /// Returns number of current case.
2980     unsigned getCaseIndex() const { return Index; }
2981
2982     /// Returns TerminatorInst's successor index for current case successor.
2983     unsigned getSuccessorIndex() const {
2984       assert((Index == DefaultPseudoIndex || Index < SI->getNumCases()) &&
2985              "Index out the number of cases.");
2986       return Index != DefaultPseudoIndex ? Index + 1 : 0;
2987     }
2988
2989     Self operator++() {
2990       // Check index correctness after increment.
2991       // Note: Index == getNumCases() means end().
2992       assert(Index+1 <= SI->getNumCases() && "Index out the number of cases.");
2993       ++Index;
2994       return *this;
2995     }
2996     Self operator++(int) {
2997       Self tmp = *this;
2998       ++(*this);
2999       return tmp;
3000     }
3001     Self operator--() {
3002       // Check index correctness after decrement.
3003       // Note: Index == getNumCases() means end().
3004       // Also allow "-1" iterator here. That will became valid after ++.
3005       assert((Index == 0 || Index-1 <= SI->getNumCases()) &&
3006              "Index out the number of cases.");
3007       --Index;
3008       return *this;
3009     }
3010     Self operator--(int) {
3011       Self tmp = *this;
3012       --(*this);
3013       return tmp;
3014     }
3015     bool operator==(const Self& RHS) const {
3016       assert(RHS.SI == SI && "Incompatible operators.");
3017       return RHS.Index == Index;
3018     }
3019     bool operator!=(const Self& RHS) const {
3020       assert(RHS.SI == SI && "Incompatible operators.");
3021       return RHS.Index != Index;
3022     }
3023     Self &operator*() {
3024       return *this;
3025     }
3026   };
3027
3028   typedef CaseIteratorT<const SwitchInst, const ConstantInt, const BasicBlock>
3029     ConstCaseIt;
3030
3031   class CaseIt : public CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> {
3032
3033     typedef CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> ParentTy;
3034
3035   public:
3036     CaseIt(const ParentTy &Src) : ParentTy(Src) {}
3037     CaseIt(SwitchInst *SI, unsigned CaseNum) : ParentTy(SI, CaseNum) {}
3038
3039     /// Sets the new value for current case.
3040     void setValue(ConstantInt *V) {
3041       assert(Index < SI->getNumCases() && "Index out the number of cases.");
3042       SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3043     }
3044
3045     /// Sets the new successor for current case.
3046     void setSuccessor(BasicBlock *S) {
3047       SI->setSuccessor(getSuccessorIndex(), S);
3048     }
3049   };
3050
3051   static SwitchInst *Create(Value *Value, BasicBlock *Default,
3052                             unsigned NumCases,
3053                             Instruction *InsertBefore = nullptr) {
3054     return new SwitchInst(Value, Default, NumCases, InsertBefore);
3055   }
3056   static SwitchInst *Create(Value *Value, BasicBlock *Default,
3057                             unsigned NumCases, BasicBlock *InsertAtEnd) {
3058     return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3059   }
3060
3061   /// Provide fast operand accessors
3062   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3063
3064   // Accessor Methods for Switch stmt
3065   Value *getCondition() const { return getOperand(0); }
3066   void setCondition(Value *V) { setOperand(0, V); }
3067
3068   BasicBlock *getDefaultDest() const {
3069     return cast<BasicBlock>(getOperand(1));
3070   }
3071
3072   void setDefaultDest(BasicBlock *DefaultCase) {
3073     setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3074   }
3075
3076   /// getNumCases - return the number of 'cases' in this switch instruction,
3077   /// except the default case
3078   unsigned getNumCases() const {
3079     return getNumOperands()/2 - 1;
3080   }
3081
3082   /// Returns a read/write iterator that points to the first
3083   /// case in SwitchInst.
3084   CaseIt case_begin() {
3085     return CaseIt(this, 0);
3086   }
3087   /// Returns a read-only iterator that points to the first
3088   /// case in the SwitchInst.
3089   ConstCaseIt case_begin() const {
3090     return ConstCaseIt(this, 0);
3091   }
3092
3093   /// Returns a read/write iterator that points one past the last
3094   /// in the SwitchInst.
3095   CaseIt case_end() {
3096     return CaseIt(this, getNumCases());
3097   }
3098   /// Returns a read-only iterator that points one past the last
3099   /// in the SwitchInst.
3100   ConstCaseIt case_end() const {
3101     return ConstCaseIt(this, getNumCases());
3102   }
3103
3104   /// cases - iteration adapter for range-for loops.
3105   iterator_range<CaseIt> cases() {
3106     return make_range(case_begin(), case_end());
3107   }
3108
3109   /// cases - iteration adapter for range-for loops.
3110   iterator_range<ConstCaseIt> cases() const {
3111     return make_range(case_begin(), case_end());
3112   }
3113
3114   /// Returns an iterator that points to the default case.
3115   /// Note: this iterator allows to resolve successor only. Attempt
3116   /// to resolve case value causes an assertion.
3117   /// Also note, that increment and decrement also causes an assertion and
3118   /// makes iterator invalid.
3119   CaseIt case_default() {
3120     return CaseIt(this, DefaultPseudoIndex);
3121   }
3122   ConstCaseIt case_default() const {
3123     return ConstCaseIt(this, DefaultPseudoIndex);
3124   }
3125
3126   /// findCaseValue - Search all of the case values for the specified constant.
3127   /// If it is explicitly handled, return the case iterator of it, otherwise
3128   /// return default case iterator to indicate
3129   /// that it is handled by the default handler.
3130   CaseIt findCaseValue(const ConstantInt *C) {
3131     for (CaseIt i = case_begin(), e = case_end(); i != e; ++i)
3132       if (i.getCaseValue() == C)
3133         return i;
3134     return case_default();
3135   }
3136   ConstCaseIt findCaseValue(const ConstantInt *C) const {
3137     for (ConstCaseIt i = case_begin(), e = case_end(); i != e; ++i)
3138       if (i.getCaseValue() == C)
3139         return i;
3140     return case_default();
3141   }
3142
3143   /// findCaseDest - Finds the unique case value for a given successor. Returns
3144   /// null if the successor is not found, not unique, or is the default case.
3145   ConstantInt *findCaseDest(BasicBlock *BB) {
3146     if (BB == getDefaultDest()) return nullptr;
3147
3148     ConstantInt *CI = nullptr;
3149     for (CaseIt i = case_begin(), e = case_end(); i != e; ++i) {
3150       if (i.getCaseSuccessor() == BB) {
3151         if (CI) return nullptr;   // Multiple cases lead to BB.
3152         else CI = i.getCaseValue();
3153       }
3154     }
3155     return CI;
3156   }
3157
3158   /// addCase - Add an entry to the switch instruction...
3159   /// Note:
3160   /// This action invalidates case_end(). Old case_end() iterator will
3161   /// point to the added case.
3162   void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3163
3164   /// removeCase - This method removes the specified case and its successor
3165   /// from the switch instruction. Note that this operation may reorder the
3166   /// remaining cases at index idx and above.
3167   /// Note:
3168   /// This action invalidates iterators for all cases following the one removed,
3169   /// including the case_end() iterator.
3170   void removeCase(CaseIt i);
3171
3172   unsigned getNumSuccessors() const { return getNumOperands()/2; }
3173   BasicBlock *getSuccessor(unsigned idx) const {
3174     assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3175     return cast<BasicBlock>(getOperand(idx*2+1));
3176   }
3177   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3178     assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3179     setOperand(idx * 2 + 1, NewSucc);
3180   }
3181
3182   // Methods for support type inquiry through isa, cast, and dyn_cast:
3183   static inline bool classof(const Instruction *I) {
3184     return I->getOpcode() == Instruction::Switch;
3185   }
3186   static inline bool classof(const Value *V) {
3187     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3188   }
3189
3190 private:
3191   BasicBlock *getSuccessorV(unsigned idx) const override;
3192   unsigned getNumSuccessorsV() const override;
3193   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3194 };
3195
3196 template <>
3197 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3198 };
3199
3200 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3201
3202 //===----------------------------------------------------------------------===//
3203 //                             IndirectBrInst Class
3204 //===----------------------------------------------------------------------===//
3205
3206 //===---------------------------------------------------------------------------
3207 /// IndirectBrInst - Indirect Branch Instruction.
3208 ///
3209 class IndirectBrInst : public TerminatorInst {
3210   void *operator new(size_t, unsigned) = delete;
3211   unsigned ReservedSpace;
3212   // Operand[0]    = Value to switch on
3213   // Operand[1]    = Default basic block destination
3214   // Operand[2n  ] = Value to match
3215   // Operand[2n+1] = BasicBlock to go to on match
3216   IndirectBrInst(const IndirectBrInst &IBI);
3217   void init(Value *Address, unsigned NumDests);
3218   void growOperands();
3219   // allocate space for exactly zero operands
3220   void *operator new(size_t s) {
3221     return User::operator new(s);
3222   }
3223   /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
3224   /// Address to jump to.  The number of expected destinations can be specified
3225   /// here to make memory allocation more efficient.  This constructor can also
3226   /// autoinsert before another instruction.
3227   IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3228
3229   /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
3230   /// Address to jump to.  The number of expected destinations can be specified
3231   /// here to make memory allocation more efficient.  This constructor also
3232   /// autoinserts at the end of the specified BasicBlock.
3233   IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3234
3235 protected:
3236   // Note: Instruction needs to be a friend here to call cloneImpl.
3237   friend class Instruction;
3238   IndirectBrInst *cloneImpl() const;
3239
3240 public:
3241   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3242                                 Instruction *InsertBefore = nullptr) {
3243     return new IndirectBrInst(Address, NumDests, InsertBefore);
3244   }
3245   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3246                                 BasicBlock *InsertAtEnd) {
3247     return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3248   }
3249
3250   /// Provide fast operand accessors.
3251   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3252
3253   // Accessor Methods for IndirectBrInst instruction.
3254   Value *getAddress() { return getOperand(0); }
3255   const Value *getAddress() const { return getOperand(0); }
3256   void setAddress(Value *V) { setOperand(0, V); }
3257
3258   /// getNumDestinations - return the number of possible destinations in this
3259   /// indirectbr instruction.
3260   unsigned getNumDestinations() const { return getNumOperands()-1; }
3261
3262   /// getDestination - Return the specified destination.
3263   BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3264   const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3265
3266   /// addDestination - Add a destination.
3267   ///
3268   void addDestination(BasicBlock *Dest);
3269
3270   /// removeDestination - This method removes the specified successor from the
3271   /// indirectbr instruction.
3272   void removeDestination(unsigned i);
3273
3274   unsigned getNumSuccessors() const { return getNumOperands()-1; }
3275   BasicBlock *getSuccessor(unsigned i) const {
3276     return cast<BasicBlock>(getOperand(i+1));
3277   }
3278   void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3279     setOperand(i + 1, NewSucc);
3280   }
3281
3282   // Methods for support type inquiry through isa, cast, and dyn_cast:
3283   static inline bool classof(const Instruction *I) {
3284     return I->getOpcode() == Instruction::IndirectBr;
3285   }
3286   static inline bool classof(const Value *V) {
3287     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3288   }
3289
3290 private:
3291   BasicBlock *getSuccessorV(unsigned idx) const override;
3292   unsigned getNumSuccessorsV() const override;
3293   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3294 };
3295
3296 template <>
3297 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3298 };
3299
3300 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3301
3302 //===----------------------------------------------------------------------===//
3303 //                               InvokeInst Class
3304 //===----------------------------------------------------------------------===//
3305
3306 /// InvokeInst - Invoke instruction.  The SubclassData field is used to hold the
3307 /// calling convention of the call.
3308 ///
3309 class InvokeInst : public TerminatorInst,
3310                    public OperandBundleUser<InvokeInst, User::op_iterator> {
3311   AttributeSet AttributeList;
3312   FunctionType *FTy;
3313   InvokeInst(const InvokeInst &BI);
3314   void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3315             ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3316             const Twine &NameStr) {
3317     init(cast<FunctionType>(
3318              cast<PointerType>(Func->getType())->getElementType()),
3319          Func, IfNormal, IfException, Args, Bundles, NameStr);
3320   }
3321   void init(FunctionType *FTy, Value *Func, BasicBlock *IfNormal,
3322             BasicBlock *IfException, ArrayRef<Value *> Args,
3323             ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3324
3325   /// Construct an InvokeInst given a range of arguments.
3326   ///
3327   /// \brief Construct an InvokeInst from a range of arguments
3328   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3329                     ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3330                     unsigned Values, const Twine &NameStr,
3331                     Instruction *InsertBefore)
3332       : InvokeInst(cast<FunctionType>(
3333                        cast<PointerType>(Func->getType())->getElementType()),
3334                    Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3335                    InsertBefore) {}
3336
3337   inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3338                     BasicBlock *IfException, ArrayRef<Value *> Args,
3339                     ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3340                     const Twine &NameStr, Instruction *InsertBefore);
3341   /// Construct an InvokeInst given a range of arguments.
3342   ///
3343   /// \brief Construct an InvokeInst from a range of arguments
3344   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3345                     ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3346                     unsigned Values, const Twine &NameStr,
3347                     BasicBlock *InsertAtEnd);
3348
3349   friend class OperandBundleUser<InvokeInst, User::op_iterator>;
3350   bool hasDescriptor() const { return HasDescriptor; }
3351
3352 protected:
3353   // Note: Instruction needs to be a friend here to call cloneImpl.
3354   friend class Instruction;
3355   InvokeInst *cloneImpl() const;
3356
3357 public:
3358   static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3359                             BasicBlock *IfException, ArrayRef<Value *> Args,
3360                             const Twine &NameStr,
3361                             Instruction *InsertBefore = nullptr) {
3362     return Create(cast<FunctionType>(
3363                       cast<PointerType>(Func->getType())->getElementType()),
3364                   Func, IfNormal, IfException, Args, None, NameStr,
3365                   InsertBefore);
3366   }
3367   static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3368                             BasicBlock *IfException, ArrayRef<Value *> Args,
3369                             ArrayRef<OperandBundleDef> Bundles = None,
3370                             const Twine &NameStr = "",
3371                             Instruction *InsertBefore = nullptr) {
3372     return Create(cast<FunctionType>(
3373                       cast<PointerType>(Func->getType())->getElementType()),
3374                   Func, IfNormal, IfException, Args, Bundles, NameStr,
3375                   InsertBefore);
3376   }
3377   static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3378                             BasicBlock *IfException, ArrayRef<Value *> Args,
3379                             const Twine &NameStr,
3380                             Instruction *InsertBefore = nullptr) {
3381     unsigned Values = unsigned(Args.size()) + 3;
3382     return new (Values) InvokeInst(Ty, Func, IfNormal, IfException, Args, None,
3383                                    Values, NameStr, InsertBefore);
3384   }
3385   static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3386                             BasicBlock *IfException, ArrayRef<Value *> Args,
3387                             ArrayRef<OperandBundleDef> Bundles = None,
3388                             const Twine &NameStr = "",
3389                             Instruction *InsertBefore = nullptr) {
3390     unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3391     unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3392
3393     return new (Values, DescriptorBytes)
3394         InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, Values,
3395                    NameStr, InsertBefore);
3396   }
3397   static InvokeInst *Create(Value *Func,
3398                             BasicBlock *IfNormal, BasicBlock *IfException,
3399                             ArrayRef<Value *> Args, const Twine &NameStr,
3400                             BasicBlock *InsertAtEnd) {
3401     unsigned Values = unsigned(Args.size()) + 3;
3402     return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None,
3403                                    Values, NameStr, InsertAtEnd);
3404   }
3405   static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3406                             BasicBlock *IfException, ArrayRef<Value *> Args,
3407                             ArrayRef<OperandBundleDef> Bundles,
3408                             const Twine &NameStr, BasicBlock *InsertAtEnd) {
3409     unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3410     unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3411
3412     return new (Values, DescriptorBytes)
3413         InvokeInst(Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3414                    InsertAtEnd);
3415   }
3416
3417   /// \brief Create a clone of \p II with a different set of operand bundles and
3418   /// insert it before \p InsertPt.
3419   ///
3420   /// The returned invoke instruction is identical to \p II in every way except
3421   /// that the operand bundles for the new instruction are set to the operand
3422   /// bundles in \p Bundles.
3423   static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3424                             Instruction *InsertPt = nullptr);
3425
3426   /// Provide fast operand accessors
3427   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3428
3429   FunctionType *getFunctionType() const { return FTy; }
3430
3431   void mutateFunctionType(FunctionType *FTy) {
3432     mutateType(FTy->getReturnType());
3433     this->FTy = FTy;
3434   }
3435
3436   /// getNumArgOperands - Return the number of invoke arguments.
3437   ///
3438   unsigned getNumArgOperands() const {
3439     return getNumOperands() - getNumTotalBundleOperands() - 3;
3440   }
3441
3442   /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3443   ///
3444   Value *getArgOperand(unsigned i) const {
3445     assert(i < getNumArgOperands() && "Out of bounds!");
3446     return getOperand(i);
3447   }
3448   void setArgOperand(unsigned i, Value *v) {
3449     assert(i < getNumArgOperands() && "Out of bounds!");
3450     setOperand(i, v);
3451   }
3452
3453   /// arg_operands - iteration adapter for range-for loops.
3454   iterator_range<op_iterator> arg_operands() {
3455     return make_range(op_begin(), op_end() - getNumTotalBundleOperands() - 3);
3456   }
3457
3458   /// arg_operands - iteration adapter for range-for loops.
3459   iterator_range<const_op_iterator> arg_operands() const {
3460     return make_range(op_begin(), op_end() - getNumTotalBundleOperands() - 3);
3461   }
3462
3463   /// \brief Wrappers for getting the \c Use of a invoke argument.
3464   const Use &getArgOperandUse(unsigned i) const {
3465     assert(i < getNumArgOperands() && "Out of bounds!");
3466     return getOperandUse(i);
3467   }
3468   Use &getArgOperandUse(unsigned i) {
3469     assert(i < getNumArgOperands() && "Out of bounds!");
3470     return getOperandUse(i);
3471   }
3472
3473   /// getCallingConv/setCallingConv - Get or set the calling convention of this
3474   /// function call.
3475   CallingConv::ID getCallingConv() const {
3476     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3477   }
3478   void setCallingConv(CallingConv::ID CC) {
3479     auto ID = static_cast<unsigned>(CC);
3480     assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
3481     setInstructionSubclassData(ID);
3482   }
3483
3484   /// getAttributes - Return the parameter attributes for this invoke.
3485   ///
3486   const AttributeSet &getAttributes() const { return AttributeList; }
3487
3488   /// setAttributes - Set the parameter attributes for this invoke.
3489   ///
3490   void setAttributes(const AttributeSet &Attrs) { AttributeList = Attrs; }
3491
3492   /// addAttribute - adds the attribute to the list of attributes.
3493   void addAttribute(unsigned i, Attribute::AttrKind attr);
3494
3495   /// removeAttribute - removes the attribute from the list of attributes.
3496   void removeAttribute(unsigned i, Attribute attr);
3497
3498   /// \brief adds the dereferenceable attribute to the list of attributes.
3499   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3500
3501   /// \brief adds the dereferenceable_or_null attribute to the list of
3502   /// attributes.
3503   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
3504
3505   /// \brief Determine whether this call has the given attribute.
3506   bool hasFnAttr(Attribute::AttrKind A) const {
3507     assert(A != Attribute::NoBuiltin &&
3508            "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
3509     return hasFnAttrImpl(A);
3510   }
3511
3512   /// \brief Determine whether the call or the callee has the given attributes.
3513   bool paramHasAttr(unsigned i, Attribute::AttrKind A) const;
3514
3515   /// \brief Return true if the data operand at index \p i has the attribute \p
3516   /// A.
3517   ///
3518   /// Data operands include invoke arguments and values used in operand bundles,
3519   /// but does not include the invokee operand, or the two successor blocks.
3520   /// This routine dispatches to the underlying AttributeList or the
3521   /// OperandBundleUser as appropriate.
3522   ///
3523   /// The index \p i is interpreted as
3524   ///
3525   ///  \p i == Attribute::ReturnIndex  -> the return value
3526   ///  \p i in [1, arg_size + 1)  -> argument number (\p i - 1)
3527   ///  \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
3528   ///     (\p i - 1) in the operand list.
3529   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind A) const;
3530
3531   /// \brief Extract the alignment for a call or parameter (0=unknown).
3532   unsigned getParamAlignment(unsigned i) const {
3533     return AttributeList.getParamAlignment(i);
3534   }
3535
3536   /// \brief Extract the number of dereferenceable bytes for a call or
3537   /// parameter (0=unknown).
3538   uint64_t getDereferenceableBytes(unsigned i) const {
3539     return AttributeList.getDereferenceableBytes(i);
3540   }
3541
3542   /// \brief Extract the number of dereferenceable_or_null bytes for a call or
3543   /// parameter (0=unknown).
3544   uint64_t getDereferenceableOrNullBytes(unsigned i) const {
3545     return AttributeList.getDereferenceableOrNullBytes(i);
3546   }
3547
3548   /// @brief Determine if the parameter or return value is marked with NoAlias
3549   /// attribute.
3550   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
3551   bool doesNotAlias(unsigned n) const {
3552     return AttributeList.hasAttribute(n, Attribute::NoAlias);
3553   }
3554
3555   /// \brief Return true if the call should not be treated as a call to a
3556   /// builtin.
3557   bool isNoBuiltin() const {
3558     // We assert in hasFnAttr if one passes in Attribute::NoBuiltin, so we have
3559     // to check it by hand.
3560     return hasFnAttrImpl(Attribute::NoBuiltin) &&
3561       !hasFnAttrImpl(Attribute::Builtin);
3562   }
3563
3564   /// \brief Return true if the call should not be inlined.
3565   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
3566   void setIsNoInline() {
3567     addAttribute(AttributeSet::FunctionIndex, Attribute::NoInline);
3568   }
3569
3570   /// \brief Determine if the call does not access memory.
3571   bool doesNotAccessMemory() const {
3572     return hasFnAttr(Attribute::ReadNone);
3573   }
3574   void setDoesNotAccessMemory() {
3575     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
3576   }
3577
3578   /// \brief Determine if the call does not access or only reads memory.
3579   bool onlyReadsMemory() const {
3580     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
3581   }
3582   void setOnlyReadsMemory() {
3583     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
3584   }
3585
3586   /// @brief Determine if the call access memmory only using it's pointer
3587   /// arguments.
3588   bool onlyAccessesArgMemory() const {
3589     return hasFnAttr(Attribute::ArgMemOnly);
3590   }
3591   void setOnlyAccessesArgMemory() {
3592     addAttribute(AttributeSet::FunctionIndex, Attribute::ArgMemOnly);
3593   }
3594
3595   /// \brief Determine if the call cannot return.
3596   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
3597   void setDoesNotReturn() {
3598     addAttribute(AttributeSet::FunctionIndex, Attribute::NoReturn);
3599   }
3600
3601   /// \brief Determine if the call cannot unwind.
3602   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3603   void setDoesNotThrow() {
3604     addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
3605   }
3606
3607   /// \brief Determine if the invoke cannot be duplicated.
3608   bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
3609   void setCannotDuplicate() {
3610     addAttribute(AttributeSet::FunctionIndex, Attribute::NoDuplicate);
3611   }
3612
3613   /// \brief Determine if the call returns a structure through first
3614   /// pointer argument.
3615   bool hasStructRetAttr() const {
3616     if (getNumArgOperands() == 0)
3617       return false;
3618
3619     // Be friendly and also check the callee.
3620     return paramHasAttr(1, Attribute::StructRet);
3621   }
3622
3623   /// \brief Determine if any call argument is an aggregate passed by value.
3624   bool hasByValArgument() const {
3625     return AttributeList.hasAttrSomewhere(Attribute::ByVal);
3626   }
3627
3628   /// getCalledFunction - Return the function called, or null if this is an
3629   /// indirect function invocation.
3630   ///
3631   Function *getCalledFunction() const {
3632     return dyn_cast<Function>(Op<-3>());
3633   }
3634
3635   /// getCalledValue - Get a pointer to the function that is invoked by this
3636   /// instruction
3637   const Value *getCalledValue() const { return Op<-3>(); }
3638         Value *getCalledValue()       { return Op<-3>(); }
3639
3640   /// setCalledFunction - Set the function called.
3641   void setCalledFunction(Value* Fn) {
3642     setCalledFunction(
3643         cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
3644         Fn);
3645   }
3646   void setCalledFunction(FunctionType *FTy, Value *Fn) {
3647     this->FTy = FTy;
3648     assert(FTy == cast<FunctionType>(
3649                       cast<PointerType>(Fn->getType())->getElementType()));
3650     Op<-3>() = Fn;
3651   }
3652
3653   // get*Dest - Return the destination basic blocks...
3654   BasicBlock *getNormalDest() const {
3655     return cast<BasicBlock>(Op<-2>());
3656   }
3657   BasicBlock *getUnwindDest() const {
3658     return cast<BasicBlock>(Op<-1>());
3659   }
3660   void setNormalDest(BasicBlock *B) {
3661     Op<-2>() = reinterpret_cast<Value*>(B);
3662   }
3663   void setUnwindDest(BasicBlock *B) {
3664     Op<-1>() = reinterpret_cast<Value*>(B);
3665   }
3666
3667   /// getLandingPadInst - Get the landingpad instruction from the landing pad
3668   /// block (the unwind destination).
3669   LandingPadInst *getLandingPadInst() const;
3670
3671   BasicBlock *getSuccessor(unsigned i) const {
3672     assert(i < 2 && "Successor # out of range for invoke!");
3673     return i == 0 ? getNormalDest() : getUnwindDest();
3674   }
3675
3676   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3677     assert(idx < 2 && "Successor # out of range for invoke!");
3678     *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
3679   }
3680
3681   unsigned getNumSuccessors() const { return 2; }
3682
3683   // Methods for support type inquiry through isa, cast, and dyn_cast:
3684   static inline bool classof(const Instruction *I) {
3685     return (I->getOpcode() == Instruction::Invoke);
3686   }
3687   static inline bool classof(const Value *V) {
3688     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3689   }
3690
3691 private:
3692   BasicBlock *getSuccessorV(unsigned idx) const override;
3693   unsigned getNumSuccessorsV() const override;
3694   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3695
3696   bool hasFnAttrImpl(Attribute::AttrKind A) const;
3697
3698   // Shadow Instruction::setInstructionSubclassData with a private forwarding
3699   // method so that subclasses cannot accidentally use it.
3700   void setInstructionSubclassData(unsigned short D) {
3701     Instruction::setInstructionSubclassData(D);
3702   }
3703 };
3704
3705 template <>
3706 struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
3707 };
3708
3709 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3710                        BasicBlock *IfException, ArrayRef<Value *> Args,
3711                        ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3712                        const Twine &NameStr, Instruction *InsertBefore)
3713     : TerminatorInst(Ty->getReturnType(), Instruction::Invoke,
3714                      OperandTraits<InvokeInst>::op_end(this) - Values, Values,
3715                      InsertBefore) {
3716   init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3717 }
3718 InvokeInst::InvokeInst(Value *Func, BasicBlock *IfNormal,
3719                        BasicBlock *IfException, ArrayRef<Value *> Args,
3720                        ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3721                        const Twine &NameStr, BasicBlock *InsertAtEnd)
3722     : TerminatorInst(
3723           cast<FunctionType>(cast<PointerType>(Func->getType())
3724                                  ->getElementType())->getReturnType(),
3725           Instruction::Invoke, OperandTraits<InvokeInst>::op_end(this) - Values,
3726           Values, InsertAtEnd) {
3727   init(Func, IfNormal, IfException, Args, Bundles, NameStr);
3728 }
3729
3730 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
3731
3732 //===----------------------------------------------------------------------===//
3733 //                              ResumeInst Class
3734 //===----------------------------------------------------------------------===//
3735
3736 //===---------------------------------------------------------------------------
3737 /// ResumeInst - Resume the propagation of an exception.
3738 ///
3739 class ResumeInst : public TerminatorInst {
3740   ResumeInst(const ResumeInst &RI);
3741
3742   explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
3743   ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
3744
3745 protected:
3746   // Note: Instruction needs to be a friend here to call cloneImpl.
3747   friend class Instruction;
3748   ResumeInst *cloneImpl() const;
3749
3750 public:
3751   static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
3752     return new(1) ResumeInst(Exn, InsertBefore);
3753   }
3754   static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
3755     return new(1) ResumeInst(Exn, InsertAtEnd);
3756   }
3757
3758   /// Provide fast operand accessors
3759   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3760
3761   /// Convenience accessor.
3762   Value *getValue() const { return Op<0>(); }
3763
3764   unsigned getNumSuccessors() const { return 0; }
3765
3766   // Methods for support type inquiry through isa, cast, and dyn_cast:
3767   static inline bool classof(const Instruction *I) {
3768     return I->getOpcode() == Instruction::Resume;
3769   }
3770   static inline bool classof(const Value *V) {
3771     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3772   }
3773
3774 private:
3775   BasicBlock *getSuccessorV(unsigned idx) const override;
3776   unsigned getNumSuccessorsV() const override;
3777   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3778 };
3779
3780 template <>
3781 struct OperandTraits<ResumeInst> :
3782     public FixedNumOperandTraits<ResumeInst, 1> {
3783 };
3784
3785 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
3786
3787 //===----------------------------------------------------------------------===//
3788 //                               CatchEndPadInst Class
3789 //===----------------------------------------------------------------------===//
3790
3791 class CatchEndPadInst : public TerminatorInst {
3792 private:
3793   CatchEndPadInst(const CatchEndPadInst &RI);
3794
3795   void init(BasicBlock *UnwindBB);
3796   CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB, unsigned Values,
3797                   Instruction *InsertBefore = nullptr);
3798   CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB, unsigned Values,
3799                   BasicBlock *InsertAtEnd);
3800
3801 protected:
3802   // Note: Instruction needs to be a friend here to call cloneImpl.
3803   friend class Instruction;
3804   CatchEndPadInst *cloneImpl() const;
3805
3806 public:
3807   static CatchEndPadInst *Create(LLVMContext &C, BasicBlock *UnwindBB = nullptr,
3808                                  Instruction *InsertBefore = nullptr) {
3809     unsigned Values = UnwindBB ? 1 : 0;
3810     return new (Values) CatchEndPadInst(C, UnwindBB, Values, InsertBefore);
3811   }
3812   static CatchEndPadInst *Create(LLVMContext &C, BasicBlock *UnwindBB,
3813                                  BasicBlock *InsertAtEnd) {
3814     unsigned Values = UnwindBB ? 1 : 0;
3815     return new (Values) CatchEndPadInst(C, UnwindBB, Values, InsertAtEnd);
3816   }
3817
3818   /// Provide fast operand accessors
3819   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3820
3821   bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
3822   bool unwindsToCaller() const { return !hasUnwindDest(); }
3823
3824   /// Convenience accessor. Returns null if there is no return value.
3825   unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
3826
3827   BasicBlock *getUnwindDest() const {
3828     return hasUnwindDest() ? cast<BasicBlock>(Op<-1>()) : nullptr;
3829   }
3830   void setUnwindDest(BasicBlock *NewDest) {
3831     assert(NewDest);
3832     Op<-1>() = NewDest;
3833   }
3834
3835   // Methods for support type inquiry through isa, cast, and dyn_cast:
3836   static inline bool classof(const Instruction *I) {
3837     return (I->getOpcode() == Instruction::CatchEndPad);
3838   }
3839   static inline bool classof(const Value *V) {
3840     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3841   }
3842
3843 private:
3844   BasicBlock *getSuccessorV(unsigned Idx) const override;
3845   unsigned getNumSuccessorsV() const override;
3846   void setSuccessorV(unsigned Idx, BasicBlock *B) override;
3847
3848   // Shadow Instruction::setInstructionSubclassData with a private forwarding
3849   // method so that subclasses cannot accidentally use it.
3850   void setInstructionSubclassData(unsigned short D) {
3851     Instruction::setInstructionSubclassData(D);
3852   }
3853 };
3854
3855 template <>
3856 struct OperandTraits<CatchEndPadInst>
3857     : public VariadicOperandTraits<CatchEndPadInst> {};
3858
3859 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchEndPadInst, Value)
3860
3861 //===----------------------------------------------------------------------===//
3862 //                           CatchPadInst Class
3863 //===----------------------------------------------------------------------===//
3864
3865 class CatchPadInst : public TerminatorInst {
3866 private:
3867   void init(BasicBlock *IfNormal, BasicBlock *IfException,
3868             ArrayRef<Value *> Args, const Twine &NameStr);
3869
3870   CatchPadInst(const CatchPadInst &CPI);
3871
3872   explicit CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
3873                         ArrayRef<Value *> Args, unsigned Values,
3874                         const Twine &NameStr, Instruction *InsertBefore);
3875   explicit CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
3876                         ArrayRef<Value *> Args, unsigned Values,
3877                         const Twine &NameStr, BasicBlock *InsertAtEnd);
3878
3879 protected:
3880   // Note: Instruction needs to be a friend here to call cloneImpl.
3881   friend class Instruction;
3882   CatchPadInst *cloneImpl() const;
3883
3884 public:
3885   static CatchPadInst *Create(BasicBlock *IfNormal, BasicBlock *IfException,
3886                               ArrayRef<Value *> Args, const Twine &NameStr = "",
3887                               Instruction *InsertBefore = nullptr) {
3888     unsigned Values = unsigned(Args.size()) + 2;
3889     return new (Values) CatchPadInst(IfNormal, IfException, Args, Values,
3890                                      NameStr, InsertBefore);
3891   }
3892   static CatchPadInst *Create(BasicBlock *IfNormal, BasicBlock *IfException,
3893                               ArrayRef<Value *> Args, const Twine &NameStr,
3894                               BasicBlock *InsertAtEnd) {
3895     unsigned Values = unsigned(Args.size()) + 2;
3896     return new (Values)
3897         CatchPadInst(IfNormal, IfException, Args, Values, NameStr, InsertAtEnd);
3898   }
3899
3900   /// Provide fast operand accessors
3901   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3902
3903   /// getNumArgOperands - Return the number of catchpad arguments.
3904   ///
3905   unsigned getNumArgOperands() const { return getNumOperands() - 2; }
3906
3907   /// getArgOperand/setArgOperand - Return/set the i-th catchpad argument.
3908   ///
3909   Value *getArgOperand(unsigned i) const { return getOperand(i); }
3910   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
3911
3912   /// arg_operands - iteration adapter for range-for loops.
3913   iterator_range<op_iterator> arg_operands() {
3914     return make_range(op_begin(), op_end() - 2);
3915   }
3916
3917   /// arg_operands - iteration adapter for range-for loops.
3918   iterator_range<const_op_iterator> arg_operands() const {
3919     return make_range(op_begin(), op_end() - 2);
3920   }
3921
3922   /// \brief Wrappers for getting the \c Use of a catchpad argument.
3923   const Use &getArgOperandUse(unsigned i) const { return getOperandUse(i); }
3924   Use &getArgOperandUse(unsigned i) { return getOperandUse(i); }
3925
3926   // get*Dest - Return the destination basic blocks...
3927   BasicBlock *getNormalDest() const { return cast<BasicBlock>(Op<-2>()); }
3928   BasicBlock *getUnwindDest() const { return cast<BasicBlock>(Op<-1>()); }
3929   void setNormalDest(BasicBlock *B) { Op<-2>() = B; }
3930   void setUnwindDest(BasicBlock *B) { Op<-1>() = B; }
3931
3932   BasicBlock *getSuccessor(unsigned i) const {
3933     assert(i < 2 && "Successor # out of range for catchpad!");
3934     return i == 0 ? getNormalDest() : getUnwindDest();
3935   }
3936
3937   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3938     assert(idx < 2 && "Successor # out of range for catchpad!");
3939     *(&Op<-2>() + idx) = NewSucc;
3940   }
3941
3942   unsigned getNumSuccessors() const { return 2; }
3943
3944   // Methods for support type inquiry through isa, cast, and dyn_cast:
3945   static inline bool classof(const Instruction *I) {
3946     return I->getOpcode() == Instruction::CatchPad;
3947   }
3948   static inline bool classof(const Value *V) {
3949     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3950   }
3951
3952 private:
3953   BasicBlock *getSuccessorV(unsigned idx) const override;
3954   unsigned getNumSuccessorsV() const override;
3955   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3956 };
3957
3958 template <>
3959 struct OperandTraits<CatchPadInst>
3960     : public VariadicOperandTraits<CatchPadInst, /*MINARITY=*/2> {};
3961
3962 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchPadInst, Value)
3963
3964 //===----------------------------------------------------------------------===//
3965 //                           TerminatePadInst Class
3966 //===----------------------------------------------------------------------===//
3967
3968 class TerminatePadInst : public TerminatorInst {
3969 private:
3970   void init(BasicBlock *BB, ArrayRef<Value *> Args);
3971
3972   TerminatePadInst(const TerminatePadInst &TPI);
3973
3974   explicit TerminatePadInst(LLVMContext &C, BasicBlock *BB,
3975                             ArrayRef<Value *> Args, unsigned Values,
3976                             Instruction *InsertBefore);
3977   explicit TerminatePadInst(LLVMContext &C, BasicBlock *BB,
3978                             ArrayRef<Value *> Args, unsigned Values,
3979                             BasicBlock *InsertAtEnd);
3980
3981 protected:
3982   // Note: Instruction needs to be a friend here to call cloneImpl.
3983   friend class Instruction;
3984   TerminatePadInst *cloneImpl() const;
3985
3986 public:
3987   static TerminatePadInst *Create(LLVMContext &C, BasicBlock *BB = nullptr,
3988                                   ArrayRef<Value *> Args = None,
3989                                   Instruction *InsertBefore = nullptr) {
3990     unsigned Values = unsigned(Args.size());
3991     if (BB)
3992       ++Values;
3993     return new (Values) TerminatePadInst(C, BB, Args, Values, InsertBefore);
3994   }
3995   static TerminatePadInst *Create(LLVMContext &C, BasicBlock *BB,
3996                                   ArrayRef<Value *> Args,
3997                                   BasicBlock *InsertAtEnd) {
3998     unsigned Values = unsigned(Args.size());
3999     if (BB)
4000       ++Values;
4001     return new (Values) TerminatePadInst(C, BB, Args, Values, InsertAtEnd);
4002   }
4003
4004   /// Provide fast operand accessors
4005   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4006
4007   bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4008   bool unwindsToCaller() const { return !hasUnwindDest(); }
4009
4010   /// getNumArgOperands - Return the number of terminatepad arguments.
4011   ///
4012   unsigned getNumArgOperands() const {
4013     unsigned NumOperands = getNumOperands();
4014     if (hasUnwindDest())
4015       return NumOperands - 1;
4016     return NumOperands;
4017   }
4018
4019   /// getArgOperand/setArgOperand - Return/set the i-th terminatepad argument.
4020   ///
4021   Value *getArgOperand(unsigned i) const { return getOperand(i); }
4022   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
4023
4024   const_op_iterator arg_end() const {
4025     if (hasUnwindDest())
4026       return op_end() - 1;
4027     return op_end();
4028   }
4029
4030   op_iterator arg_end() {
4031     if (hasUnwindDest())
4032       return op_end() - 1;
4033     return op_end();
4034   }
4035
4036   /// arg_operands - iteration adapter for range-for loops.
4037   iterator_range<op_iterator> arg_operands() {
4038     return make_range(op_begin(), arg_end());
4039   }
4040
4041   /// arg_operands - iteration adapter for range-for loops.
4042   iterator_range<const_op_iterator> arg_operands() const {
4043     return make_range(op_begin(), arg_end());
4044   }
4045
4046   /// \brief Wrappers for getting the \c Use of a terminatepad argument.
4047   const Use &getArgOperandUse(unsigned i) const { return getOperandUse(i); }
4048   Use &getArgOperandUse(unsigned i) { return getOperandUse(i); }
4049
4050   // get*Dest - Return the destination basic blocks...
4051   BasicBlock *getUnwindDest() const {
4052     if (!hasUnwindDest())
4053       return nullptr;
4054     return cast<BasicBlock>(Op<-1>());
4055   }
4056   void setUnwindDest(BasicBlock *B) {
4057     assert(B && hasUnwindDest());
4058     Op<-1>() = B;
4059   }
4060
4061   unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4062
4063   // Methods for support type inquiry through isa, cast, and dyn_cast:
4064   static inline bool classof(const Instruction *I) {
4065     return I->getOpcode() == Instruction::TerminatePad;
4066   }
4067   static inline bool classof(const Value *V) {
4068     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4069   }
4070
4071 private:
4072   BasicBlock *getSuccessorV(unsigned idx) const override;
4073   unsigned getNumSuccessorsV() const override;
4074   void setSuccessorV(unsigned idx, BasicBlock *B) override;
4075
4076   // Shadow Instruction::setInstructionSubclassData with a private forwarding
4077   // method so that subclasses cannot accidentally use it.
4078   void setInstructionSubclassData(unsigned short D) {
4079     Instruction::setInstructionSubclassData(D);
4080   }
4081 };
4082
4083 template <>
4084 struct OperandTraits<TerminatePadInst>
4085     : public VariadicOperandTraits<TerminatePadInst, /*MINARITY=*/1> {};
4086
4087 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(TerminatePadInst, Value)
4088
4089 //===----------------------------------------------------------------------===//
4090 //                           CleanupPadInst Class
4091 //===----------------------------------------------------------------------===//
4092
4093 class CleanupPadInst : public Instruction {
4094 private:
4095   void init(ArrayRef<Value *> Args, const Twine &NameStr);
4096
4097   CleanupPadInst(const CleanupPadInst &CPI);
4098
4099   explicit CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
4100                           const Twine &NameStr, Instruction *InsertBefore);
4101   explicit CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
4102                           const Twine &NameStr, BasicBlock *InsertAtEnd);
4103
4104 protected:
4105   // Note: Instruction needs to be a friend here to call cloneImpl.
4106   friend class Instruction;
4107   CleanupPadInst *cloneImpl() const;
4108
4109 public:
4110   static CleanupPadInst *Create(LLVMContext &C, ArrayRef<Value *> Args,
4111                                 const Twine &NameStr = "",
4112                                 Instruction *InsertBefore = nullptr) {
4113     return new (Args.size()) CleanupPadInst(C, Args, NameStr, InsertBefore);
4114   }
4115   static CleanupPadInst *Create(LLVMContext &C, ArrayRef<Value *> Args,
4116                                 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4117     return new (Args.size()) CleanupPadInst(C, Args, NameStr, InsertAtEnd);
4118   }
4119
4120   /// Provide fast operand accessors
4121   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4122
4123   // Methods for support type inquiry through isa, cast, and dyn_cast:
4124   static inline bool classof(const Instruction *I) {
4125     return I->getOpcode() == Instruction::CleanupPad;
4126   }
4127   static inline bool classof(const Value *V) {
4128     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4129   }
4130 };
4131
4132 template <>
4133 struct OperandTraits<CleanupPadInst>
4134     : public VariadicOperandTraits<CleanupPadInst, /*MINARITY=*/0> {};
4135
4136 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupPadInst, Value)
4137
4138 //===----------------------------------------------------------------------===//
4139 //                               CatchReturnInst Class
4140 //===----------------------------------------------------------------------===//
4141
4142 class CatchReturnInst : public TerminatorInst {
4143   CatchReturnInst(const CatchReturnInst &RI);
4144
4145   void init(CatchPadInst *CatchPad, BasicBlock *BB);
4146   CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
4147                   Instruction *InsertBefore);
4148   CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
4149                   BasicBlock *InsertAtEnd);
4150
4151 protected:
4152   // Note: Instruction needs to be a friend here to call cloneImpl.
4153   friend class Instruction;
4154   CatchReturnInst *cloneImpl() const;
4155
4156 public:
4157   static CatchReturnInst *Create(CatchPadInst *CatchPad, BasicBlock *BB,
4158                                  Instruction *InsertBefore = nullptr) {
4159     assert(CatchPad);
4160     assert(BB);
4161     return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4162   }
4163   static CatchReturnInst *Create(CatchPadInst *CatchPad, BasicBlock *BB,
4164                                  BasicBlock *InsertAtEnd) {
4165     assert(CatchPad);
4166     assert(BB);
4167     return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4168   }
4169
4170   /// Provide fast operand accessors
4171   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4172
4173   /// Convenience accessors.
4174   CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4175   void setCatchPad(CatchPadInst *CatchPad) {
4176     assert(CatchPad);
4177     Op<0>() = CatchPad;
4178   }
4179
4180   BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4181   void setSuccessor(BasicBlock *NewSucc) {
4182     assert(NewSucc);
4183     Op<1>() = NewSucc;
4184   }
4185   unsigned getNumSuccessors() const { return 1; }
4186
4187   // Methods for support type inquiry through isa, cast, and dyn_cast:
4188   static inline bool classof(const Instruction *I) {
4189     return (I->getOpcode() == Instruction::CatchRet);
4190   }
4191   static inline bool classof(const Value *V) {
4192     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4193   }
4194
4195 private:
4196   BasicBlock *getSuccessorV(unsigned Idx) const override;
4197   unsigned getNumSuccessorsV() const override;
4198   void setSuccessorV(unsigned Idx, BasicBlock *B) override;
4199 };
4200
4201 template <>
4202 struct OperandTraits<CatchReturnInst>
4203     : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4204
4205 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4206
4207 //===----------------------------------------------------------------------===//
4208 //                               CleanupEndPadInst Class
4209 //===----------------------------------------------------------------------===//
4210
4211 class CleanupEndPadInst : public TerminatorInst {
4212 private:
4213   CleanupEndPadInst(const CleanupEndPadInst &CEPI);
4214
4215   void init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB);
4216   CleanupEndPadInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB,
4217                     unsigned Values, Instruction *InsertBefore = nullptr);
4218   CleanupEndPadInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB,
4219                     unsigned Values, BasicBlock *InsertAtEnd);
4220
4221 protected:
4222   // Note: Instruction needs to be a friend here to call cloneImpl.
4223   friend class Instruction;
4224   CleanupEndPadInst *cloneImpl() const;
4225
4226 public:
4227   static CleanupEndPadInst *Create(CleanupPadInst *CleanupPad,
4228                                    BasicBlock *UnwindBB = nullptr,
4229                                    Instruction *InsertBefore = nullptr) {
4230     unsigned Values = UnwindBB ? 2 : 1;
4231     return new (Values)
4232         CleanupEndPadInst(CleanupPad, UnwindBB, Values, InsertBefore);
4233   }
4234   static CleanupEndPadInst *Create(CleanupPadInst *CleanupPad,
4235                                    BasicBlock *UnwindBB,
4236                                    BasicBlock *InsertAtEnd) {
4237     unsigned Values = UnwindBB ? 2 : 1;
4238     return new (Values)
4239         CleanupEndPadInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4240   }
4241
4242   /// Provide fast operand accessors
4243   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4244
4245   bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4246   bool unwindsToCaller() const { return !hasUnwindDest(); }
4247
4248   unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4249
4250   /// Convenience accessors
4251   CleanupPadInst *getCleanupPad() const {
4252     return cast<CleanupPadInst>(Op<-1>());
4253   }
4254   void setCleanupPad(CleanupPadInst *CleanupPad) {
4255     assert(CleanupPad);
4256     Op<-1>() = CleanupPad;
4257   }
4258
4259   BasicBlock *getUnwindDest() const {
4260     return hasUnwindDest() ? cast<BasicBlock>(Op<-2>()) : nullptr;
4261   }
4262   void setUnwindDest(BasicBlock *NewDest) {
4263     assert(hasUnwindDest());
4264     assert(NewDest);
4265     Op<-2>() = NewDest;
4266   }
4267
4268   // Methods for support type inquiry through isa, cast, and dyn_cast:
4269   static inline bool classof(const Instruction *I) {
4270     return (I->getOpcode() == Instruction::CleanupEndPad);
4271   }
4272   static inline bool classof(const Value *V) {
4273     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4274   }
4275
4276 private:
4277   BasicBlock *getSuccessorV(unsigned Idx) const override;
4278   unsigned getNumSuccessorsV() const override;
4279   void setSuccessorV(unsigned Idx, BasicBlock *B) override;
4280
4281   // Shadow Instruction::setInstructionSubclassData with a private forwarding
4282   // method so that subclasses cannot accidentally use it.
4283   void setInstructionSubclassData(unsigned short D) {
4284     Instruction::setInstructionSubclassData(D);
4285   }
4286 };
4287
4288 template <>
4289 struct OperandTraits<CleanupEndPadInst>
4290     : public VariadicOperandTraits<CleanupEndPadInst, /*MINARITY=*/1> {};
4291
4292 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupEndPadInst, Value)
4293
4294 //===----------------------------------------------------------------------===//
4295 //                               CleanupReturnInst Class
4296 //===----------------------------------------------------------------------===//
4297
4298 class CleanupReturnInst : public TerminatorInst {
4299 private:
4300   CleanupReturnInst(const CleanupReturnInst &RI);
4301
4302   void init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB);
4303   CleanupReturnInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB,
4304                     unsigned Values, Instruction *InsertBefore = nullptr);
4305   CleanupReturnInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB,
4306                     unsigned Values, BasicBlock *InsertAtEnd);
4307
4308 protected:
4309   // Note: Instruction needs to be a friend here to call cloneImpl.
4310   friend class Instruction;
4311   CleanupReturnInst *cloneImpl() const;
4312
4313 public:
4314   static CleanupReturnInst *Create(CleanupPadInst *CleanupPad,
4315                                    BasicBlock *UnwindBB = nullptr,
4316                                    Instruction *InsertBefore = nullptr) {
4317     assert(CleanupPad);
4318     unsigned Values = 1;
4319     if (UnwindBB)
4320       ++Values;
4321     return new (Values)
4322         CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4323   }
4324   static CleanupReturnInst *Create(CleanupPadInst *CleanupPad,
4325                                    BasicBlock *UnwindBB,
4326                                    BasicBlock *InsertAtEnd) {
4327     assert(CleanupPad);
4328     unsigned Values = 1;
4329     if (UnwindBB)
4330       ++Values;
4331     return new (Values)
4332         CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4333   }
4334
4335   /// Provide fast operand accessors
4336   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4337
4338   bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4339   bool unwindsToCaller() const { return !hasUnwindDest(); }
4340
4341   /// Convenience accessor.
4342   CleanupPadInst *getCleanupPad() const {
4343     return cast<CleanupPadInst>(Op<-1>());
4344   }
4345   void setCleanupPad(CleanupPadInst *CleanupPad) {
4346     assert(CleanupPad);
4347     Op<-1>() = CleanupPad;
4348   }
4349
4350   unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4351
4352   BasicBlock *getUnwindDest() const {
4353     return hasUnwindDest() ? cast<BasicBlock>(Op<-2>()) : nullptr;
4354   }
4355   void setUnwindDest(BasicBlock *NewDest) {
4356     assert(NewDest);
4357     assert(hasUnwindDest());
4358     Op<-2>() = NewDest;
4359   }
4360
4361   // Methods for support type inquiry through isa, cast, and dyn_cast:
4362   static inline bool classof(const Instruction *I) {
4363     return (I->getOpcode() == Instruction::CleanupRet);
4364   }
4365   static inline bool classof(const Value *V) {
4366     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4367   }
4368
4369 private:
4370   BasicBlock *getSuccessorV(unsigned Idx) const override;
4371   unsigned getNumSuccessorsV() const override;
4372   void setSuccessorV(unsigned Idx, BasicBlock *B) override;
4373
4374   // Shadow Instruction::setInstructionSubclassData with a private forwarding
4375   // method so that subclasses cannot accidentally use it.
4376   void setInstructionSubclassData(unsigned short D) {
4377     Instruction::setInstructionSubclassData(D);
4378   }
4379 };
4380
4381 template <>
4382 struct OperandTraits<CleanupReturnInst>
4383     : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4384
4385 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4386
4387 //===----------------------------------------------------------------------===//
4388 //                           UnreachableInst Class
4389 //===----------------------------------------------------------------------===//
4390
4391 //===---------------------------------------------------------------------------
4392 /// UnreachableInst - This function has undefined behavior.  In particular, the
4393 /// presence of this instruction indicates some higher level knowledge that the
4394 /// end of the block cannot be reached.
4395 ///
4396 class UnreachableInst : public TerminatorInst {
4397   void *operator new(size_t, unsigned) = delete;
4398
4399 protected:
4400   // Note: Instruction needs to be a friend here to call cloneImpl.
4401   friend class Instruction;
4402   UnreachableInst *cloneImpl() const;
4403
4404 public:
4405   // allocate space for exactly zero operands
4406   void *operator new(size_t s) {
4407     return User::operator new(s, 0);
4408   }
4409   explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4410   explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4411
4412   unsigned getNumSuccessors() const { return 0; }
4413
4414   // Methods for support type inquiry through isa, cast, and dyn_cast:
4415   static inline bool classof(const Instruction *I) {
4416     return I->getOpcode() == Instruction::Unreachable;
4417   }
4418   static inline bool classof(const Value *V) {
4419     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4420   }
4421
4422 private:
4423   BasicBlock *getSuccessorV(unsigned idx) const override;
4424   unsigned getNumSuccessorsV() const override;
4425   void setSuccessorV(unsigned idx, BasicBlock *B) override;
4426 };
4427
4428 //===----------------------------------------------------------------------===//
4429 //                                 TruncInst Class
4430 //===----------------------------------------------------------------------===//
4431
4432 /// \brief This class represents a truncation of integer types.
4433 class TruncInst : public CastInst {
4434 protected:
4435   // Note: Instruction needs to be a friend here to call cloneImpl.
4436   friend class Instruction;
4437   /// \brief Clone an identical TruncInst
4438   TruncInst *cloneImpl() const;
4439
4440 public:
4441   /// \brief Constructor with insert-before-instruction semantics
4442   TruncInst(
4443     Value *S,                           ///< The value to be truncated
4444     Type *Ty,                           ///< The (smaller) type to truncate to
4445     const Twine &NameStr = "",          ///< A name for the new instruction
4446     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4447   );
4448
4449   /// \brief Constructor with insert-at-end-of-block semantics
4450   TruncInst(
4451     Value *S,                     ///< The value to be truncated
4452     Type *Ty,                     ///< The (smaller) type to truncate to
4453     const Twine &NameStr,         ///< A name for the new instruction
4454     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4455   );
4456
4457   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4458   static inline bool classof(const Instruction *I) {
4459     return I->getOpcode() == Trunc;
4460   }
4461   static inline bool classof(const Value *V) {
4462     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4463   }
4464 };
4465
4466 //===----------------------------------------------------------------------===//
4467 //                                 ZExtInst Class
4468 //===----------------------------------------------------------------------===//
4469
4470 /// \brief This class represents zero extension of integer types.
4471 class ZExtInst : public CastInst {
4472 protected:
4473   // Note: Instruction needs to be a friend here to call cloneImpl.
4474   friend class Instruction;
4475   /// \brief Clone an identical ZExtInst
4476   ZExtInst *cloneImpl() const;
4477
4478 public:
4479   /// \brief Constructor with insert-before-instruction semantics
4480   ZExtInst(
4481     Value *S,                           ///< The value to be zero extended
4482     Type *Ty,                           ///< The type to zero extend to
4483     const Twine &NameStr = "",          ///< A name for the new instruction
4484     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4485   );
4486
4487   /// \brief Constructor with insert-at-end semantics.
4488   ZExtInst(
4489     Value *S,                     ///< The value to be zero extended
4490     Type *Ty,                     ///< The type to zero extend to
4491     const Twine &NameStr,         ///< A name for the new instruction
4492     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4493   );
4494
4495   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4496   static inline bool classof(const Instruction *I) {
4497     return I->getOpcode() == ZExt;
4498   }
4499   static inline bool classof(const Value *V) {
4500     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4501   }
4502 };
4503
4504 //===----------------------------------------------------------------------===//
4505 //                                 SExtInst Class
4506 //===----------------------------------------------------------------------===//
4507
4508 /// \brief This class represents a sign extension of integer types.
4509 class SExtInst : public CastInst {
4510 protected:
4511   // Note: Instruction needs to be a friend here to call cloneImpl.
4512   friend class Instruction;
4513   /// \brief Clone an identical SExtInst
4514   SExtInst *cloneImpl() const;
4515
4516 public:
4517   /// \brief Constructor with insert-before-instruction semantics
4518   SExtInst(
4519     Value *S,                           ///< The value to be sign extended
4520     Type *Ty,                           ///< The type to sign extend to
4521     const Twine &NameStr = "",          ///< A name for the new instruction
4522     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4523   );
4524
4525   /// \brief Constructor with insert-at-end-of-block semantics
4526   SExtInst(
4527     Value *S,                     ///< The value to be sign extended
4528     Type *Ty,                     ///< The type to sign extend to
4529     const Twine &NameStr,         ///< A name for the new instruction
4530     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4531   );
4532
4533   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4534   static inline bool classof(const Instruction *I) {
4535     return I->getOpcode() == SExt;
4536   }
4537   static inline bool classof(const Value *V) {
4538     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4539   }
4540 };
4541
4542 //===----------------------------------------------------------------------===//
4543 //                                 FPTruncInst Class
4544 //===----------------------------------------------------------------------===//
4545
4546 /// \brief This class represents a truncation of floating point types.
4547 class FPTruncInst : public CastInst {
4548 protected:
4549   // Note: Instruction needs to be a friend here to call cloneImpl.
4550   friend class Instruction;
4551   /// \brief Clone an identical FPTruncInst
4552   FPTruncInst *cloneImpl() const;
4553
4554 public:
4555   /// \brief Constructor with insert-before-instruction semantics
4556   FPTruncInst(
4557     Value *S,                           ///< The value to be truncated
4558     Type *Ty,                           ///< The type to truncate to
4559     const Twine &NameStr = "",          ///< A name for the new instruction
4560     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4561   );
4562
4563   /// \brief Constructor with insert-before-instruction semantics
4564   FPTruncInst(
4565     Value *S,                     ///< The value to be truncated
4566     Type *Ty,                     ///< The type to truncate to
4567     const Twine &NameStr,         ///< A name for the new instruction
4568     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4569   );
4570
4571   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4572   static inline bool classof(const Instruction *I) {
4573     return I->getOpcode() == FPTrunc;
4574   }
4575   static inline bool classof(const Value *V) {
4576     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4577   }
4578 };
4579
4580 //===----------------------------------------------------------------------===//
4581 //                                 FPExtInst Class
4582 //===----------------------------------------------------------------------===//
4583
4584 /// \brief This class represents an extension of floating point types.
4585 class FPExtInst : public CastInst {
4586 protected:
4587   // Note: Instruction needs to be a friend here to call cloneImpl.
4588   friend class Instruction;
4589   /// \brief Clone an identical FPExtInst
4590   FPExtInst *cloneImpl() const;
4591
4592 public:
4593   /// \brief Constructor with insert-before-instruction semantics
4594   FPExtInst(
4595     Value *S,                           ///< The value to be extended
4596     Type *Ty,                           ///< The type to extend to
4597     const Twine &NameStr = "",          ///< A name for the new instruction
4598     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4599   );
4600
4601   /// \brief Constructor with insert-at-end-of-block semantics
4602   FPExtInst(
4603     Value *S,                     ///< The value to be extended
4604     Type *Ty,                     ///< The type to extend to
4605     const Twine &NameStr,         ///< A name for the new instruction
4606     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4607   );
4608
4609   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4610   static inline bool classof(const Instruction *I) {
4611     return I->getOpcode() == FPExt;
4612   }
4613   static inline bool classof(const Value *V) {
4614     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4615   }
4616 };
4617
4618 //===----------------------------------------------------------------------===//
4619 //                                 UIToFPInst Class
4620 //===----------------------------------------------------------------------===//
4621
4622 /// \brief This class represents a cast unsigned integer to floating point.
4623 class UIToFPInst : public CastInst {
4624 protected:
4625   // Note: Instruction needs to be a friend here to call cloneImpl.
4626   friend class Instruction;
4627   /// \brief Clone an identical UIToFPInst
4628   UIToFPInst *cloneImpl() const;
4629
4630 public:
4631   /// \brief Constructor with insert-before-instruction semantics
4632   UIToFPInst(
4633     Value *S,                           ///< The value to be converted
4634     Type *Ty,                           ///< The type to convert to
4635     const Twine &NameStr = "",          ///< A name for the new instruction
4636     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4637   );
4638
4639   /// \brief Constructor with insert-at-end-of-block semantics
4640   UIToFPInst(
4641     Value *S,                     ///< The value to be converted
4642     Type *Ty,                     ///< The type to convert to
4643     const Twine &NameStr,         ///< A name for the new instruction
4644     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4645   );
4646
4647   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4648   static inline bool classof(const Instruction *I) {
4649     return I->getOpcode() == UIToFP;
4650   }
4651   static inline bool classof(const Value *V) {
4652     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4653   }
4654 };
4655
4656 //===----------------------------------------------------------------------===//
4657 //                                 SIToFPInst Class
4658 //===----------------------------------------------------------------------===//
4659
4660 /// \brief This class represents a cast from signed integer to floating point.
4661 class SIToFPInst : public CastInst {
4662 protected:
4663   // Note: Instruction needs to be a friend here to call cloneImpl.
4664   friend class Instruction;
4665   /// \brief Clone an identical SIToFPInst
4666   SIToFPInst *cloneImpl() const;
4667
4668 public:
4669   /// \brief Constructor with insert-before-instruction semantics
4670   SIToFPInst(
4671     Value *S,                           ///< The value to be converted
4672     Type *Ty,                           ///< The type to convert to
4673     const Twine &NameStr = "",          ///< A name for the new instruction
4674     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4675   );
4676
4677   /// \brief Constructor with insert-at-end-of-block semantics
4678   SIToFPInst(
4679     Value *S,                     ///< The value to be converted
4680     Type *Ty,                     ///< The type to convert to
4681     const Twine &NameStr,         ///< A name for the new instruction
4682     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4683   );
4684
4685   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4686   static inline bool classof(const Instruction *I) {
4687     return I->getOpcode() == SIToFP;
4688   }
4689   static inline bool classof(const Value *V) {
4690     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4691   }
4692 };
4693
4694 //===----------------------------------------------------------------------===//
4695 //                                 FPToUIInst Class
4696 //===----------------------------------------------------------------------===//
4697
4698 /// \brief This class represents a cast from floating point to unsigned integer
4699 class FPToUIInst  : public CastInst {
4700 protected:
4701   // Note: Instruction needs to be a friend here to call cloneImpl.
4702   friend class Instruction;
4703   /// \brief Clone an identical FPToUIInst
4704   FPToUIInst *cloneImpl() const;
4705
4706 public:
4707   /// \brief Constructor with insert-before-instruction semantics
4708   FPToUIInst(
4709     Value *S,                           ///< The value to be converted
4710     Type *Ty,                           ///< The type to convert to
4711     const Twine &NameStr = "",          ///< A name for the new instruction
4712     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4713   );
4714
4715   /// \brief Constructor with insert-at-end-of-block semantics
4716   FPToUIInst(
4717     Value *S,                     ///< The value to be converted
4718     Type *Ty,                     ///< The type to convert to
4719     const Twine &NameStr,         ///< A name for the new instruction
4720     BasicBlock *InsertAtEnd       ///< Where to insert the new instruction
4721   );
4722
4723   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4724   static inline bool classof(const Instruction *I) {
4725     return I->getOpcode() == FPToUI;
4726   }
4727   static inline bool classof(const Value *V) {
4728     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4729   }
4730 };
4731
4732 //===----------------------------------------------------------------------===//
4733 //                                 FPToSIInst Class
4734 //===----------------------------------------------------------------------===//
4735
4736 /// \brief This class represents a cast from floating point to signed integer.
4737 class FPToSIInst  : public CastInst {
4738 protected:
4739   // Note: Instruction needs to be a friend here to call cloneImpl.
4740   friend class Instruction;
4741   /// \brief Clone an identical FPToSIInst
4742   FPToSIInst *cloneImpl() const;
4743
4744 public:
4745   /// \brief Constructor with insert-before-instruction semantics
4746   FPToSIInst(
4747     Value *S,                           ///< The value to be converted
4748     Type *Ty,                           ///< The type to convert to
4749     const Twine &NameStr = "",          ///< A name for the new instruction
4750     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4751   );
4752
4753   /// \brief Constructor with insert-at-end-of-block semantics
4754   FPToSIInst(
4755     Value *S,                     ///< The value to be converted
4756     Type *Ty,                     ///< The type to convert to
4757     const Twine &NameStr,         ///< A name for the new instruction
4758     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4759   );
4760
4761   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4762   static inline bool classof(const Instruction *I) {
4763     return I->getOpcode() == FPToSI;
4764   }
4765   static inline bool classof(const Value *V) {
4766     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4767   }
4768 };
4769
4770 //===----------------------------------------------------------------------===//
4771 //                                 IntToPtrInst Class
4772 //===----------------------------------------------------------------------===//
4773
4774 /// \brief This class represents a cast from an integer to a pointer.
4775 class IntToPtrInst : public CastInst {
4776 public:
4777   /// \brief Constructor with insert-before-instruction semantics
4778   IntToPtrInst(
4779     Value *S,                           ///< The value to be converted
4780     Type *Ty,                           ///< The type to convert to
4781     const Twine &NameStr = "",          ///< A name for the new instruction
4782     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4783   );
4784
4785   /// \brief Constructor with insert-at-end-of-block semantics
4786   IntToPtrInst(
4787     Value *S,                     ///< The value to be converted
4788     Type *Ty,                     ///< The type to convert to
4789     const Twine &NameStr,         ///< A name for the new instruction
4790     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4791   );
4792
4793   // Note: Instruction needs to be a friend here to call cloneImpl.
4794   friend class Instruction;
4795   /// \brief Clone an identical IntToPtrInst
4796   IntToPtrInst *cloneImpl() const;
4797
4798   /// \brief Returns the address space of this instruction's pointer type.
4799   unsigned getAddressSpace() const {
4800     return getType()->getPointerAddressSpace();
4801   }
4802
4803   // Methods for support type inquiry through isa, cast, and dyn_cast:
4804   static inline bool classof(const Instruction *I) {
4805     return I->getOpcode() == IntToPtr;
4806   }
4807   static inline bool classof(const Value *V) {
4808     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4809   }
4810 };
4811
4812 //===----------------------------------------------------------------------===//
4813 //                                 PtrToIntInst Class
4814 //===----------------------------------------------------------------------===//
4815
4816 /// \brief This class represents a cast from a pointer to an integer
4817 class PtrToIntInst : public CastInst {
4818 protected:
4819   // Note: Instruction needs to be a friend here to call cloneImpl.
4820   friend class Instruction;
4821   /// \brief Clone an identical PtrToIntInst
4822   PtrToIntInst *cloneImpl() const;
4823
4824 public:
4825   /// \brief Constructor with insert-before-instruction semantics
4826   PtrToIntInst(
4827     Value *S,                           ///< The value to be converted
4828     Type *Ty,                           ///< The type to convert to
4829     const Twine &NameStr = "",          ///< A name for the new instruction
4830     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4831   );
4832
4833   /// \brief Constructor with insert-at-end-of-block semantics
4834   PtrToIntInst(
4835     Value *S,                     ///< The value to be converted
4836     Type *Ty,                     ///< The type to convert to
4837     const Twine &NameStr,         ///< A name for the new instruction
4838     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4839   );
4840
4841   /// \brief Gets the pointer operand.
4842   Value *getPointerOperand() { return getOperand(0); }
4843   /// \brief Gets the pointer operand.
4844   const Value *getPointerOperand() const { return getOperand(0); }
4845   /// \brief Gets the operand index of the pointer operand.
4846   static unsigned getPointerOperandIndex() { return 0U; }
4847
4848   /// \brief Returns the address space of the pointer operand.
4849   unsigned getPointerAddressSpace() const {
4850     return getPointerOperand()->getType()->getPointerAddressSpace();
4851   }
4852
4853   // Methods for support type inquiry through isa, cast, and dyn_cast:
4854   static inline bool classof(const Instruction *I) {
4855     return I->getOpcode() == PtrToInt;
4856   }
4857   static inline bool classof(const Value *V) {
4858     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4859   }
4860 };
4861
4862 //===----------------------------------------------------------------------===//
4863 //                             BitCastInst Class
4864 //===----------------------------------------------------------------------===//
4865
4866 /// \brief This class represents a no-op cast from one type to another.
4867 class BitCastInst : public CastInst {
4868 protected:
4869   // Note: Instruction needs to be a friend here to call cloneImpl.
4870   friend class Instruction;
4871   /// \brief Clone an identical BitCastInst
4872   BitCastInst *cloneImpl() const;
4873
4874 public:
4875   /// \brief Constructor with insert-before-instruction semantics
4876   BitCastInst(
4877     Value *S,                           ///< The value to be casted
4878     Type *Ty,                           ///< The type to casted to
4879     const Twine &NameStr = "",          ///< A name for the new instruction
4880     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4881   );
4882
4883   /// \brief Constructor with insert-at-end-of-block semantics
4884   BitCastInst(
4885     Value *S,                     ///< The value to be casted
4886     Type *Ty,                     ///< The type to casted to
4887     const Twine &NameStr,         ///< A name for the new instruction
4888     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4889   );
4890
4891   // Methods for support type inquiry through isa, cast, and dyn_cast:
4892   static inline bool classof(const Instruction *I) {
4893     return I->getOpcode() == BitCast;
4894   }
4895   static inline bool classof(const Value *V) {
4896     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4897   }
4898 };
4899
4900 //===----------------------------------------------------------------------===//
4901 //                          AddrSpaceCastInst Class
4902 //===----------------------------------------------------------------------===//
4903
4904 /// \brief This class represents a conversion between pointers from
4905 /// one address space to another.
4906 class AddrSpaceCastInst : public CastInst {
4907 protected:
4908   // Note: Instruction needs to be a friend here to call cloneImpl.
4909   friend class Instruction;
4910   /// \brief Clone an identical AddrSpaceCastInst
4911   AddrSpaceCastInst *cloneImpl() const;
4912
4913 public:
4914   /// \brief Constructor with insert-before-instruction semantics
4915   AddrSpaceCastInst(
4916     Value *S,                           ///< The value to be casted
4917     Type *Ty,                           ///< The type to casted to
4918     const Twine &NameStr = "",          ///< A name for the new instruction
4919     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4920   );
4921
4922   /// \brief Constructor with insert-at-end-of-block semantics
4923   AddrSpaceCastInst(
4924     Value *S,                     ///< The value to be casted
4925     Type *Ty,                     ///< The type to casted to
4926     const Twine &NameStr,         ///< A name for the new instruction
4927     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4928   );
4929
4930   // Methods for support type inquiry through isa, cast, and dyn_cast:
4931   static inline bool classof(const Instruction *I) {
4932     return I->getOpcode() == AddrSpaceCast;
4933   }
4934   static inline bool classof(const Value *V) {
4935     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4936   }
4937 };
4938
4939 } // End llvm namespace
4940
4941 #endif