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