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