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