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