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