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