• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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)
isAtLeastAcquire(AtomicOrdering Ord)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)
isAtLeastRelease(AtomicOrdering Ord)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   ///
getArraySize()104   const Value *getArraySize() const { return getOperand(0); }
getArraySize()105   Value *getArraySize() { return getOperand(0); }
106 
107   /// getType - Overload to return most specific pointer type
108   ///
getType()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   ///
getAlignment()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.
isUsedWithInAlloca()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.
setUsedWithInAlloca(bool V)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:
classof(const Instruction * I)146   static inline bool classof(const Instruction *I) {
147     return (I->getOpcode() == Instruction::Alloca);
148   }
classof(const Value * V)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.
setInstructionSubclassData(unsigned short D)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   ///
isVolatile()208   bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
209 
210   /// setVolatile - Specify whether this is a volatile load or not.
211   ///
setVolatile(bool V)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   ///
getAlignment()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.
getOrdering()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.
setOrdering(AtomicOrdering Ordering)232   void setOrdering(AtomicOrdering Ordering) {
233     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
234                                (Ordering << 7));
235   }
236 
getSynchScope()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.
setSynchScope(SynchronizationScope xthread)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 
isSimple()255   bool isSimple() const { return !isAtomic() && !isVolatile(); }
isUnordered()256   bool isUnordered() const {
257     return getOrdering() <= Unordered && !isVolatile();
258   }
259 
getPointerOperand()260   Value *getPointerOperand() { return getOperand(0); }
getPointerOperand()261   const Value *getPointerOperand() const { return getOperand(0); }
getPointerOperandIndex()262   static unsigned getPointerOperandIndex() { return 0U; }
263 
264   /// \brief Returns the address space of the pointer operand.
getPointerAddressSpace()265   unsigned getPointerAddressSpace() const {
266     return getPointerOperand()->getType()->getPointerAddressSpace();
267   }
268 
269 
270   // Methods for support type inquiry through isa, cast, and dyn_cast:
classof(const Instruction * I)271   static inline bool classof(const Instruction *I) {
272     return I->getOpcode() == Instruction::Load;
273   }
classof(const Value * V)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.
setInstructionSubclassData(unsigned short D)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
new(size_t s)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   ///
isVolatile()324   bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
325 
326   /// setVolatile - Specify whether this is a volatile store or not.
327   ///
setVolatile(bool V)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   ///
getAlignment()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.
getOrdering()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.
setOrdering(AtomicOrdering Ordering)351   void setOrdering(AtomicOrdering Ordering) {
352     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
353                                (Ordering << 7));
354   }
355 
getSynchScope()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.
setSynchScope(SynchronizationScope xthread)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 
isSimple()374   bool isSimple() const { return !isAtomic() && !isVolatile(); }
isUnordered()375   bool isUnordered() const {
376     return getOrdering() <= Unordered && !isVolatile();
377   }
378 
getValueOperand()379   Value *getValueOperand() { return getOperand(0); }
getValueOperand()380   const Value *getValueOperand() const { return getOperand(0); }
381 
getPointerOperand()382   Value *getPointerOperand() { return getOperand(1); }
getPointerOperand()383   const Value *getPointerOperand() const { return getOperand(1); }
getPointerOperandIndex()384   static unsigned getPointerOperandIndex() { return 1U; }
385 
386   /// \brief Returns the address space of the pointer operand.
getPointerAddressSpace()387   unsigned getPointerAddressSpace() const {
388     return getPointerOperand()->getType()->getPointerAddressSpace();
389   }
390 
391   // Methods for support type inquiry through isa, cast, and dyn_cast:
classof(const Instruction * I)392   static inline bool classof(const Instruction *I) {
393     return I->getOpcode() == Instruction::Store;
394   }
classof(const Value * V)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.
setInstructionSubclassData(unsigned short D)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   Type *getFunctionType() const {
1341     return cast<PointerType>(getCalledValue()->getType())->getElementType();
1342   }
1343 
1344   // Note that 'musttail' implies 'tail'.
1345   enum TailCallKind { TCK_None = 0, TCK_Tail = 1, TCK_MustTail = 2 };
1346   TailCallKind getTailCallKind() const {
1347     return TailCallKind(getSubclassDataFromInstruction() & 3);
1348   }
1349   bool isTailCall() const {
1350     return (getSubclassDataFromInstruction() & 3) != TCK_None;
1351   }
1352   bool isMustTailCall() const {
1353     return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1354   }
1355   void setTailCall(bool isTC = true) {
1356     setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1357                                unsigned(isTC ? TCK_Tail : TCK_None));
1358   }
1359   void setTailCallKind(TailCallKind TCK) {
1360     setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1361                                unsigned(TCK));
1362   }
1363 
1364   /// Provide fast operand accessors
1365   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1366 
1367   /// getNumArgOperands - Return the number of call arguments.
1368   ///
1369   unsigned getNumArgOperands() const { return getNumOperands() - 1; }
1370 
1371   /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1372   ///
1373   Value *getArgOperand(unsigned i) const { return getOperand(i); }
1374   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
1375 
1376   /// arg_operands - iteration adapter for range-for loops.
1377   iterator_range<op_iterator> arg_operands() {
1378     // The last operand in the op list is the callee - it's not one of the args
1379     // so we don't want to iterate over it.
1380     return iterator_range<op_iterator>(op_begin(), op_end() - 1);
1381   }
1382 
1383   /// arg_operands - iteration adapter for range-for loops.
1384   iterator_range<const_op_iterator> arg_operands() const {
1385     return iterator_range<const_op_iterator>(op_begin(), op_end() - 1);
1386   }
1387 
1388   /// \brief Wrappers for getting the \c Use of a call argument.
1389   const Use &getArgOperandUse(unsigned i) const { return getOperandUse(i); }
1390   Use &getArgOperandUse(unsigned i) { return getOperandUse(i); }
1391 
1392   /// getCallingConv/setCallingConv - Get or set the calling convention of this
1393   /// function call.
1394   CallingConv::ID getCallingConv() const {
1395     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1396   }
1397   void setCallingConv(CallingConv::ID CC) {
1398     setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1399                                (static_cast<unsigned>(CC) << 2));
1400   }
1401 
1402   /// getAttributes - Return the parameter attributes for this call.
1403   ///
1404   const AttributeSet &getAttributes() const { return AttributeList; }
1405 
1406   /// setAttributes - Set the parameter attributes for this call.
1407   ///
1408   void setAttributes(const AttributeSet &Attrs) { AttributeList = Attrs; }
1409 
1410   /// addAttribute - adds the attribute to the list of attributes.
1411   void addAttribute(unsigned i, Attribute::AttrKind attr);
1412 
1413   /// removeAttribute - removes the attribute from the list of attributes.
1414   void removeAttribute(unsigned i, Attribute attr);
1415 
1416   /// \brief adds the dereferenceable attribute to the list of attributes.
1417   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
1418 
1419   /// \brief adds the dereferenceable_or_null attribute to the list of
1420   /// attributes.
1421   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
1422 
1423   /// \brief Determine whether this call has the given attribute.
1424   bool hasFnAttr(Attribute::AttrKind A) const {
1425     assert(A != Attribute::NoBuiltin &&
1426            "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
1427     return hasFnAttrImpl(A);
1428   }
1429 
1430   /// \brief Determine whether the call or the callee has the given attributes.
1431   bool paramHasAttr(unsigned i, Attribute::AttrKind A) const;
1432 
1433   /// \brief Extract the alignment for a call or parameter (0=unknown).
1434   unsigned getParamAlignment(unsigned i) const {
1435     return AttributeList.getParamAlignment(i);
1436   }
1437 
1438   /// \brief Extract the number of dereferenceable bytes for a call or
1439   /// parameter (0=unknown).
1440   uint64_t getDereferenceableBytes(unsigned i) const {
1441     return AttributeList.getDereferenceableBytes(i);
1442   }
1443 
1444   /// \brief Return true if the call should not be treated as a call to a
1445   /// builtin.
1446   bool isNoBuiltin() const {
1447     return hasFnAttrImpl(Attribute::NoBuiltin) &&
1448       !hasFnAttrImpl(Attribute::Builtin);
1449   }
1450 
1451   /// \brief Return true if the call should not be inlined.
1452   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1453   void setIsNoInline() {
1454     addAttribute(AttributeSet::FunctionIndex, Attribute::NoInline);
1455   }
1456 
1457   /// \brief Return true if the call can return twice
1458   bool canReturnTwice() const {
1459     return hasFnAttr(Attribute::ReturnsTwice);
1460   }
1461   void setCanReturnTwice() {
1462     addAttribute(AttributeSet::FunctionIndex, Attribute::ReturnsTwice);
1463   }
1464 
1465   /// \brief Determine if the call does not access memory.
1466   bool doesNotAccessMemory() const {
1467     return hasFnAttr(Attribute::ReadNone);
1468   }
1469   void setDoesNotAccessMemory() {
1470     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
1471   }
1472 
1473   /// \brief Determine if the call does not access or only reads memory.
1474   bool onlyReadsMemory() const {
1475     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1476   }
1477   void setOnlyReadsMemory() {
1478     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
1479   }
1480 
1481   /// \brief Determine if the call cannot return.
1482   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1483   void setDoesNotReturn() {
1484     addAttribute(AttributeSet::FunctionIndex, Attribute::NoReturn);
1485   }
1486 
1487   /// \brief Determine if the call cannot unwind.
1488   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1489   void setDoesNotThrow() {
1490     addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
1491   }
1492 
1493   /// \brief Determine if the call cannot be duplicated.
1494   bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1495   void setCannotDuplicate() {
1496     addAttribute(AttributeSet::FunctionIndex, Attribute::NoDuplicate);
1497   }
1498 
1499   /// \brief Determine if the call returns a structure through first
1500   /// pointer argument.
1501   bool hasStructRetAttr() const {
1502     // Be friendly and also check the callee.
1503     return paramHasAttr(1, Attribute::StructRet);
1504   }
1505 
1506   /// \brief Determine if any call argument is an aggregate passed by value.
1507   bool hasByValArgument() const {
1508     return AttributeList.hasAttrSomewhere(Attribute::ByVal);
1509   }
1510 
1511   /// getCalledFunction - Return the function called, or null if this is an
1512   /// indirect function invocation.
1513   ///
1514   Function *getCalledFunction() const {
1515     return dyn_cast<Function>(Op<-1>());
1516   }
1517 
1518   /// getCalledValue - Get a pointer to the function that is invoked by this
1519   /// instruction.
1520   const Value *getCalledValue() const { return Op<-1>(); }
1521         Value *getCalledValue()       { return Op<-1>(); }
1522 
1523   /// setCalledFunction - Set the function called.
1524   void setCalledFunction(Value* Fn) {
1525     Op<-1>() = Fn;
1526   }
1527 
1528   /// isInlineAsm - Check if this call is an inline asm statement.
1529   bool isInlineAsm() const {
1530     return isa<InlineAsm>(Op<-1>());
1531   }
1532 
1533   // Methods for support type inquiry through isa, cast, and dyn_cast:
1534   static inline bool classof(const Instruction *I) {
1535     return I->getOpcode() == Instruction::Call;
1536   }
1537   static inline bool classof(const Value *V) {
1538     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1539   }
1540 private:
1541 
1542   bool hasFnAttrImpl(Attribute::AttrKind A) const;
1543 
1544   // Shadow Instruction::setInstructionSubclassData with a private forwarding
1545   // method so that subclasses cannot accidentally use it.
1546   void setInstructionSubclassData(unsigned short D) {
1547     Instruction::setInstructionSubclassData(D);
1548   }
1549 };
1550 
1551 template <>
1552 struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1553 };
1554 
1555 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1556                    const Twine &NameStr, BasicBlock *InsertAtEnd)
1557   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
1558                                    ->getElementType())->getReturnType(),
1559                 Instruction::Call,
1560                 OperandTraits<CallInst>::op_end(this) - (Args.size() + 1),
1561                 unsigned(Args.size() + 1), InsertAtEnd) {
1562   init(Func, Args, NameStr);
1563 }
1564 
1565 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1566                    const Twine &NameStr, Instruction *InsertBefore)
1567   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
1568                                    ->getElementType())->getReturnType(),
1569                 Instruction::Call,
1570                 OperandTraits<CallInst>::op_end(this) - (Args.size() + 1),
1571                 unsigned(Args.size() + 1), InsertBefore) {
1572   init(Func, Args, NameStr);
1573 }
1574 
1575 
1576 // Note: if you get compile errors about private methods then
1577 //       please update your code to use the high-level operand
1578 //       interfaces. See line 943 above.
1579 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
1580 
1581 //===----------------------------------------------------------------------===//
1582 //                               SelectInst Class
1583 //===----------------------------------------------------------------------===//
1584 
1585 /// SelectInst - This class represents the LLVM 'select' instruction.
1586 ///
1587 class SelectInst : public Instruction {
1588   void init(Value *C, Value *S1, Value *S2) {
1589     assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1590     Op<0>() = C;
1591     Op<1>() = S1;
1592     Op<2>() = S2;
1593   }
1594 
1595   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1596              Instruction *InsertBefore)
1597     : Instruction(S1->getType(), Instruction::Select,
1598                   &Op<0>(), 3, InsertBefore) {
1599     init(C, S1, S2);
1600     setName(NameStr);
1601   }
1602   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1603              BasicBlock *InsertAtEnd)
1604     : Instruction(S1->getType(), Instruction::Select,
1605                   &Op<0>(), 3, InsertAtEnd) {
1606     init(C, S1, S2);
1607     setName(NameStr);
1608   }
1609 protected:
1610   SelectInst *clone_impl() const override;
1611 public:
1612   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1613                             const Twine &NameStr = "",
1614                             Instruction *InsertBefore = nullptr) {
1615     return new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1616   }
1617   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1618                             const Twine &NameStr,
1619                             BasicBlock *InsertAtEnd) {
1620     return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1621   }
1622 
1623   const Value *getCondition() const { return Op<0>(); }
1624   const Value *getTrueValue() const { return Op<1>(); }
1625   const Value *getFalseValue() const { return Op<2>(); }
1626   Value *getCondition() { return Op<0>(); }
1627   Value *getTrueValue() { return Op<1>(); }
1628   Value *getFalseValue() { return Op<2>(); }
1629 
1630   /// areInvalidOperands - Return a string if the specified operands are invalid
1631   /// for a select operation, otherwise return null.
1632   static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1633 
1634   /// Transparently provide more efficient getOperand methods.
1635   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1636 
1637   OtherOps getOpcode() const {
1638     return static_cast<OtherOps>(Instruction::getOpcode());
1639   }
1640 
1641   // Methods for support type inquiry through isa, cast, and dyn_cast:
1642   static inline bool classof(const Instruction *I) {
1643     return I->getOpcode() == Instruction::Select;
1644   }
1645   static inline bool classof(const Value *V) {
1646     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1647   }
1648 };
1649 
1650 template <>
1651 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1652 };
1653 
1654 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1655 
1656 //===----------------------------------------------------------------------===//
1657 //                                VAArgInst Class
1658 //===----------------------------------------------------------------------===//
1659 
1660 /// VAArgInst - This class represents the va_arg llvm instruction, which returns
1661 /// an argument of the specified type given a va_list and increments that list
1662 ///
1663 class VAArgInst : public UnaryInstruction {
1664 protected:
1665   VAArgInst *clone_impl() const override;
1666 
1667 public:
1668   VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1669              Instruction *InsertBefore = nullptr)
1670     : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1671     setName(NameStr);
1672   }
1673   VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1674             BasicBlock *InsertAtEnd)
1675     : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1676     setName(NameStr);
1677   }
1678 
1679   Value *getPointerOperand() { return getOperand(0); }
1680   const Value *getPointerOperand() const { return getOperand(0); }
1681   static unsigned getPointerOperandIndex() { return 0U; }
1682 
1683   // Methods for support type inquiry through isa, cast, and dyn_cast:
1684   static inline bool classof(const Instruction *I) {
1685     return I->getOpcode() == VAArg;
1686   }
1687   static inline bool classof(const Value *V) {
1688     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1689   }
1690 };
1691 
1692 //===----------------------------------------------------------------------===//
1693 //                                ExtractElementInst Class
1694 //===----------------------------------------------------------------------===//
1695 
1696 /// ExtractElementInst - This instruction extracts a single (scalar)
1697 /// element from a VectorType value
1698 ///
1699 class ExtractElementInst : public Instruction {
1700   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1701                      Instruction *InsertBefore = nullptr);
1702   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1703                      BasicBlock *InsertAtEnd);
1704 protected:
1705   ExtractElementInst *clone_impl() const override;
1706 
1707 public:
1708   static ExtractElementInst *Create(Value *Vec, Value *Idx,
1709                                    const Twine &NameStr = "",
1710                                    Instruction *InsertBefore = nullptr) {
1711     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1712   }
1713   static ExtractElementInst *Create(Value *Vec, Value *Idx,
1714                                    const Twine &NameStr,
1715                                    BasicBlock *InsertAtEnd) {
1716     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1717   }
1718 
1719   /// isValidOperands - Return true if an extractelement instruction can be
1720   /// formed with the specified operands.
1721   static bool isValidOperands(const Value *Vec, const Value *Idx);
1722 
1723   Value *getVectorOperand() { return Op<0>(); }
1724   Value *getIndexOperand() { return Op<1>(); }
1725   const Value *getVectorOperand() const { return Op<0>(); }
1726   const Value *getIndexOperand() const { return Op<1>(); }
1727 
1728   VectorType *getVectorOperandType() const {
1729     return cast<VectorType>(getVectorOperand()->getType());
1730   }
1731 
1732 
1733   /// Transparently provide more efficient getOperand methods.
1734   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1735 
1736   // Methods for support type inquiry through isa, cast, and dyn_cast:
1737   static inline bool classof(const Instruction *I) {
1738     return I->getOpcode() == Instruction::ExtractElement;
1739   }
1740   static inline bool classof(const Value *V) {
1741     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1742   }
1743 };
1744 
1745 template <>
1746 struct OperandTraits<ExtractElementInst> :
1747   public FixedNumOperandTraits<ExtractElementInst, 2> {
1748 };
1749 
1750 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1751 
1752 //===----------------------------------------------------------------------===//
1753 //                                InsertElementInst Class
1754 //===----------------------------------------------------------------------===//
1755 
1756 /// InsertElementInst - This instruction inserts a single (scalar)
1757 /// element into a VectorType value
1758 ///
1759 class InsertElementInst : public Instruction {
1760   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1761                     const Twine &NameStr = "",
1762                     Instruction *InsertBefore = nullptr);
1763   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1764                     const Twine &NameStr, BasicBlock *InsertAtEnd);
1765 protected:
1766   InsertElementInst *clone_impl() const override;
1767 
1768 public:
1769   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1770                                    const Twine &NameStr = "",
1771                                    Instruction *InsertBefore = nullptr) {
1772     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1773   }
1774   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1775                                    const Twine &NameStr,
1776                                    BasicBlock *InsertAtEnd) {
1777     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1778   }
1779 
1780   /// isValidOperands - Return true if an insertelement instruction can be
1781   /// formed with the specified operands.
1782   static bool isValidOperands(const Value *Vec, const Value *NewElt,
1783                               const Value *Idx);
1784 
1785   /// getType - Overload to return most specific vector type.
1786   ///
1787   VectorType *getType() const {
1788     return cast<VectorType>(Instruction::getType());
1789   }
1790 
1791   /// Transparently provide more efficient getOperand methods.
1792   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1793 
1794   // Methods for support type inquiry through isa, cast, and dyn_cast:
1795   static inline bool classof(const Instruction *I) {
1796     return I->getOpcode() == Instruction::InsertElement;
1797   }
1798   static inline bool classof(const Value *V) {
1799     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1800   }
1801 };
1802 
1803 template <>
1804 struct OperandTraits<InsertElementInst> :
1805   public FixedNumOperandTraits<InsertElementInst, 3> {
1806 };
1807 
1808 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
1809 
1810 //===----------------------------------------------------------------------===//
1811 //                           ShuffleVectorInst Class
1812 //===----------------------------------------------------------------------===//
1813 
1814 /// ShuffleVectorInst - This instruction constructs a fixed permutation of two
1815 /// input vectors.
1816 ///
1817 class ShuffleVectorInst : public Instruction {
1818 protected:
1819   ShuffleVectorInst *clone_impl() const override;
1820 
1821 public:
1822   // allocate space for exactly three operands
1823   void *operator new(size_t s) {
1824     return User::operator new(s, 3);
1825   }
1826   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1827                     const Twine &NameStr = "",
1828                     Instruction *InsertBefor = nullptr);
1829   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1830                     const Twine &NameStr, BasicBlock *InsertAtEnd);
1831 
1832   /// isValidOperands - Return true if a shufflevector instruction can be
1833   /// formed with the specified operands.
1834   static bool isValidOperands(const Value *V1, const Value *V2,
1835                               const Value *Mask);
1836 
1837   /// getType - Overload to return most specific vector type.
1838   ///
1839   VectorType *getType() const {
1840     return cast<VectorType>(Instruction::getType());
1841   }
1842 
1843   /// Transparently provide more efficient getOperand methods.
1844   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1845 
1846   Constant *getMask() const {
1847     return cast<Constant>(getOperand(2));
1848   }
1849 
1850   /// getMaskValue - Return the index from the shuffle mask for the specified
1851   /// output result.  This is either -1 if the element is undef or a number less
1852   /// than 2*numelements.
1853   static int getMaskValue(Constant *Mask, unsigned i);
1854 
1855   int getMaskValue(unsigned i) const {
1856     return getMaskValue(getMask(), i);
1857   }
1858 
1859   /// getShuffleMask - Return the full mask for this instruction, where each
1860   /// element is the element number and undef's are returned as -1.
1861   static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
1862 
1863   void getShuffleMask(SmallVectorImpl<int> &Result) const {
1864     return getShuffleMask(getMask(), Result);
1865   }
1866 
1867   SmallVector<int, 16> getShuffleMask() const {
1868     SmallVector<int, 16> Mask;
1869     getShuffleMask(Mask);
1870     return Mask;
1871   }
1872 
1873 
1874   // Methods for support type inquiry through isa, cast, and dyn_cast:
1875   static inline bool classof(const Instruction *I) {
1876     return I->getOpcode() == Instruction::ShuffleVector;
1877   }
1878   static inline bool classof(const Value *V) {
1879     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1880   }
1881 };
1882 
1883 template <>
1884 struct OperandTraits<ShuffleVectorInst> :
1885   public FixedNumOperandTraits<ShuffleVectorInst, 3> {
1886 };
1887 
1888 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
1889 
1890 //===----------------------------------------------------------------------===//
1891 //                                ExtractValueInst Class
1892 //===----------------------------------------------------------------------===//
1893 
1894 /// ExtractValueInst - This instruction extracts a struct member or array
1895 /// element value from an aggregate value.
1896 ///
1897 class ExtractValueInst : public UnaryInstruction {
1898   SmallVector<unsigned, 4> Indices;
1899 
1900   ExtractValueInst(const ExtractValueInst &EVI);
1901   void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
1902 
1903   /// Constructors - Create a extractvalue instruction with a base aggregate
1904   /// value and a list of indices.  The first ctor can optionally insert before
1905   /// an existing instruction, the second appends the new instruction to the
1906   /// specified BasicBlock.
1907   inline ExtractValueInst(Value *Agg,
1908                           ArrayRef<unsigned> Idxs,
1909                           const Twine &NameStr,
1910                           Instruction *InsertBefore);
1911   inline ExtractValueInst(Value *Agg,
1912                           ArrayRef<unsigned> Idxs,
1913                           const Twine &NameStr, BasicBlock *InsertAtEnd);
1914 
1915   // allocate space for exactly one operand
1916   void *operator new(size_t s) {
1917     return User::operator new(s, 1);
1918   }
1919 protected:
1920   ExtractValueInst *clone_impl() const override;
1921 
1922 public:
1923   static ExtractValueInst *Create(Value *Agg,
1924                                   ArrayRef<unsigned> Idxs,
1925                                   const Twine &NameStr = "",
1926                                   Instruction *InsertBefore = nullptr) {
1927     return new
1928       ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
1929   }
1930   static ExtractValueInst *Create(Value *Agg,
1931                                   ArrayRef<unsigned> Idxs,
1932                                   const Twine &NameStr,
1933                                   BasicBlock *InsertAtEnd) {
1934     return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
1935   }
1936 
1937   /// getIndexedType - Returns the type of the element that would be extracted
1938   /// with an extractvalue instruction with the specified parameters.
1939   ///
1940   /// Null is returned if the indices are invalid for the specified type.
1941   static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
1942 
1943   typedef const unsigned* idx_iterator;
1944   inline idx_iterator idx_begin() const { return Indices.begin(); }
1945   inline idx_iterator idx_end()   const { return Indices.end(); }
1946   inline iterator_range<idx_iterator> indices() const {
1947     return iterator_range<idx_iterator>(idx_begin(), idx_end());
1948   }
1949 
1950   Value *getAggregateOperand() {
1951     return getOperand(0);
1952   }
1953   const Value *getAggregateOperand() const {
1954     return getOperand(0);
1955   }
1956   static unsigned getAggregateOperandIndex() {
1957     return 0U;                      // get index for modifying correct operand
1958   }
1959 
1960   ArrayRef<unsigned> getIndices() const {
1961     return Indices;
1962   }
1963 
1964   unsigned getNumIndices() const {
1965     return (unsigned)Indices.size();
1966   }
1967 
1968   bool hasIndices() const {
1969     return true;
1970   }
1971 
1972   // Methods for support type inquiry through isa, cast, and dyn_cast:
1973   static inline bool classof(const Instruction *I) {
1974     return I->getOpcode() == Instruction::ExtractValue;
1975   }
1976   static inline bool classof(const Value *V) {
1977     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1978   }
1979 };
1980 
1981 ExtractValueInst::ExtractValueInst(Value *Agg,
1982                                    ArrayRef<unsigned> Idxs,
1983                                    const Twine &NameStr,
1984                                    Instruction *InsertBefore)
1985   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
1986                      ExtractValue, Agg, InsertBefore) {
1987   init(Idxs, NameStr);
1988 }
1989 ExtractValueInst::ExtractValueInst(Value *Agg,
1990                                    ArrayRef<unsigned> Idxs,
1991                                    const Twine &NameStr,
1992                                    BasicBlock *InsertAtEnd)
1993   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
1994                      ExtractValue, Agg, InsertAtEnd) {
1995   init(Idxs, NameStr);
1996 }
1997 
1998 
1999 //===----------------------------------------------------------------------===//
2000 //                                InsertValueInst Class
2001 //===----------------------------------------------------------------------===//
2002 
2003 /// InsertValueInst - This instruction inserts a struct field of array element
2004 /// value into an aggregate value.
2005 ///
2006 class InsertValueInst : public Instruction {
2007   SmallVector<unsigned, 4> Indices;
2008 
2009   void *operator new(size_t, unsigned) = delete;
2010   InsertValueInst(const InsertValueInst &IVI);
2011   void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2012             const Twine &NameStr);
2013 
2014   /// Constructors - Create a insertvalue instruction with a base aggregate
2015   /// value, a value to insert, and a list of indices.  The first ctor can
2016   /// optionally insert before an existing instruction, the second appends
2017   /// the new instruction to the specified BasicBlock.
2018   inline InsertValueInst(Value *Agg, Value *Val,
2019                          ArrayRef<unsigned> Idxs,
2020                          const Twine &NameStr,
2021                          Instruction *InsertBefore);
2022   inline InsertValueInst(Value *Agg, Value *Val,
2023                          ArrayRef<unsigned> Idxs,
2024                          const Twine &NameStr, BasicBlock *InsertAtEnd);
2025 
2026   /// Constructors - These two constructors are convenience methods because one
2027   /// and two index insertvalue instructions are so common.
2028   InsertValueInst(Value *Agg, Value *Val,
2029                   unsigned Idx, const Twine &NameStr = "",
2030                   Instruction *InsertBefore = nullptr);
2031   InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2032                   const Twine &NameStr, BasicBlock *InsertAtEnd);
2033 protected:
2034   InsertValueInst *clone_impl() const override;
2035 public:
2036   // allocate space for exactly two operands
2037   void *operator new(size_t s) {
2038     return User::operator new(s, 2);
2039   }
2040 
2041   static InsertValueInst *Create(Value *Agg, Value *Val,
2042                                  ArrayRef<unsigned> Idxs,
2043                                  const Twine &NameStr = "",
2044                                  Instruction *InsertBefore = nullptr) {
2045     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2046   }
2047   static InsertValueInst *Create(Value *Agg, Value *Val,
2048                                  ArrayRef<unsigned> Idxs,
2049                                  const Twine &NameStr,
2050                                  BasicBlock *InsertAtEnd) {
2051     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2052   }
2053 
2054   /// Transparently provide more efficient getOperand methods.
2055   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2056 
2057   typedef const unsigned* idx_iterator;
2058   inline idx_iterator idx_begin() const { return Indices.begin(); }
2059   inline idx_iterator idx_end()   const { return Indices.end(); }
2060   inline iterator_range<idx_iterator> indices() const {
2061     return iterator_range<idx_iterator>(idx_begin(), idx_end());
2062   }
2063 
2064   Value *getAggregateOperand() {
2065     return getOperand(0);
2066   }
2067   const Value *getAggregateOperand() const {
2068     return getOperand(0);
2069   }
2070   static unsigned getAggregateOperandIndex() {
2071     return 0U;                      // get index for modifying correct operand
2072   }
2073 
2074   Value *getInsertedValueOperand() {
2075     return getOperand(1);
2076   }
2077   const Value *getInsertedValueOperand() const {
2078     return getOperand(1);
2079   }
2080   static unsigned getInsertedValueOperandIndex() {
2081     return 1U;                      // get index for modifying correct operand
2082   }
2083 
2084   ArrayRef<unsigned> getIndices() const {
2085     return Indices;
2086   }
2087 
2088   unsigned getNumIndices() const {
2089     return (unsigned)Indices.size();
2090   }
2091 
2092   bool hasIndices() const {
2093     return true;
2094   }
2095 
2096   // Methods for support type inquiry through isa, cast, and dyn_cast:
2097   static inline bool classof(const Instruction *I) {
2098     return I->getOpcode() == Instruction::InsertValue;
2099   }
2100   static inline bool classof(const Value *V) {
2101     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2102   }
2103 };
2104 
2105 template <>
2106 struct OperandTraits<InsertValueInst> :
2107   public FixedNumOperandTraits<InsertValueInst, 2> {
2108 };
2109 
2110 InsertValueInst::InsertValueInst(Value *Agg,
2111                                  Value *Val,
2112                                  ArrayRef<unsigned> Idxs,
2113                                  const Twine &NameStr,
2114                                  Instruction *InsertBefore)
2115   : Instruction(Agg->getType(), InsertValue,
2116                 OperandTraits<InsertValueInst>::op_begin(this),
2117                 2, InsertBefore) {
2118   init(Agg, Val, Idxs, NameStr);
2119 }
2120 InsertValueInst::InsertValueInst(Value *Agg,
2121                                  Value *Val,
2122                                  ArrayRef<unsigned> Idxs,
2123                                  const Twine &NameStr,
2124                                  BasicBlock *InsertAtEnd)
2125   : Instruction(Agg->getType(), InsertValue,
2126                 OperandTraits<InsertValueInst>::op_begin(this),
2127                 2, InsertAtEnd) {
2128   init(Agg, Val, Idxs, NameStr);
2129 }
2130 
2131 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2132 
2133 //===----------------------------------------------------------------------===//
2134 //                               PHINode Class
2135 //===----------------------------------------------------------------------===//
2136 
2137 // PHINode - The PHINode class is used to represent the magical mystical PHI
2138 // node, that can not exist in nature, but can be synthesized in a computer
2139 // scientist's overactive imagination.
2140 //
2141 class PHINode : public Instruction {
2142   void *operator new(size_t, unsigned) = delete;
2143   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
2144   /// the number actually in use.
2145   unsigned ReservedSpace;
2146   PHINode(const PHINode &PN);
2147   // allocate space for exactly zero operands
2148   void *operator new(size_t s) {
2149     return User::operator new(s, 0);
2150   }
2151   explicit PHINode(Type *Ty, unsigned NumReservedValues,
2152                    const Twine &NameStr = "",
2153                    Instruction *InsertBefore = nullptr)
2154     : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2155       ReservedSpace(NumReservedValues) {
2156     setName(NameStr);
2157     OperandList = allocHungoffUses(ReservedSpace);
2158   }
2159 
2160   PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2161           BasicBlock *InsertAtEnd)
2162     : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2163       ReservedSpace(NumReservedValues) {
2164     setName(NameStr);
2165     OperandList = allocHungoffUses(ReservedSpace);
2166   }
2167 protected:
2168   // allocHungoffUses - this is more complicated than the generic
2169   // User::allocHungoffUses, because we have to allocate Uses for the incoming
2170   // values and pointers to the incoming blocks, all in one allocation.
2171   Use *allocHungoffUses(unsigned) const;
2172 
2173   PHINode *clone_impl() const override;
2174 public:
2175   /// Constructors - NumReservedValues is a hint for the number of incoming
2176   /// edges that this phi node will have (use 0 if you really have no idea).
2177   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2178                          const Twine &NameStr = "",
2179                          Instruction *InsertBefore = nullptr) {
2180     return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2181   }
2182   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2183                          const Twine &NameStr, BasicBlock *InsertAtEnd) {
2184     return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2185   }
2186   ~PHINode() override;
2187 
2188   /// Provide fast operand accessors
2189   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2190 
2191   // Block iterator interface. This provides access to the list of incoming
2192   // basic blocks, which parallels the list of incoming values.
2193 
2194   typedef BasicBlock **block_iterator;
2195   typedef BasicBlock * const *const_block_iterator;
2196 
2197   block_iterator block_begin() {
2198     Use::UserRef *ref =
2199       reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2200     return reinterpret_cast<block_iterator>(ref + 1);
2201   }
2202 
2203   const_block_iterator block_begin() const {
2204     const Use::UserRef *ref =
2205       reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2206     return reinterpret_cast<const_block_iterator>(ref + 1);
2207   }
2208 
2209   block_iterator block_end() {
2210     return block_begin() + getNumOperands();
2211   }
2212 
2213   const_block_iterator block_end() const {
2214     return block_begin() + getNumOperands();
2215   }
2216 
2217   op_range incoming_values() { return operands(); }
2218 
2219   /// getNumIncomingValues - Return the number of incoming edges
2220   ///
2221   unsigned getNumIncomingValues() const { return getNumOperands(); }
2222 
2223   /// getIncomingValue - Return incoming value number x
2224   ///
2225   Value *getIncomingValue(unsigned i) const {
2226     return getOperand(i);
2227   }
2228   void setIncomingValue(unsigned i, Value *V) {
2229     setOperand(i, V);
2230   }
2231   static unsigned getOperandNumForIncomingValue(unsigned i) {
2232     return i;
2233   }
2234   static unsigned getIncomingValueNumForOperand(unsigned i) {
2235     return i;
2236   }
2237 
2238   /// getIncomingBlock - Return incoming basic block number @p i.
2239   ///
2240   BasicBlock *getIncomingBlock(unsigned i) const {
2241     return block_begin()[i];
2242   }
2243 
2244   /// getIncomingBlock - Return incoming basic block corresponding
2245   /// to an operand of the PHI.
2246   ///
2247   BasicBlock *getIncomingBlock(const Use &U) const {
2248     assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2249     return getIncomingBlock(unsigned(&U - op_begin()));
2250   }
2251 
2252   /// getIncomingBlock - Return incoming basic block corresponding
2253   /// to value use iterator.
2254   ///
2255   BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2256     return getIncomingBlock(I.getUse());
2257   }
2258 
2259   void setIncomingBlock(unsigned i, BasicBlock *BB) {
2260     block_begin()[i] = BB;
2261   }
2262 
2263   /// addIncoming - Add an incoming value to the end of the PHI list
2264   ///
2265   void addIncoming(Value *V, BasicBlock *BB) {
2266     assert(V && "PHI node got a null value!");
2267     assert(BB && "PHI node got a null basic block!");
2268     assert(getType() == V->getType() &&
2269            "All operands to PHI node must be the same type as the PHI node!");
2270     if (NumOperands == ReservedSpace)
2271       growOperands();  // Get more space!
2272     // Initialize some new operands.
2273     ++NumOperands;
2274     setIncomingValue(NumOperands - 1, V);
2275     setIncomingBlock(NumOperands - 1, BB);
2276   }
2277 
2278   /// removeIncomingValue - Remove an incoming value.  This is useful if a
2279   /// predecessor basic block is deleted.  The value removed is returned.
2280   ///
2281   /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2282   /// is true), the PHI node is destroyed and any uses of it are replaced with
2283   /// dummy values.  The only time there should be zero incoming values to a PHI
2284   /// node is when the block is dead, so this strategy is sound.
2285   ///
2286   Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2287 
2288   Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2289     int Idx = getBasicBlockIndex(BB);
2290     assert(Idx >= 0 && "Invalid basic block argument to remove!");
2291     return removeIncomingValue(Idx, DeletePHIIfEmpty);
2292   }
2293 
2294   /// getBasicBlockIndex - Return the first index of the specified basic
2295   /// block in the value list for this PHI.  Returns -1 if no instance.
2296   ///
2297   int getBasicBlockIndex(const BasicBlock *BB) const {
2298     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2299       if (block_begin()[i] == BB)
2300         return i;
2301     return -1;
2302   }
2303 
2304   Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2305     int Idx = getBasicBlockIndex(BB);
2306     assert(Idx >= 0 && "Invalid basic block argument!");
2307     return getIncomingValue(Idx);
2308   }
2309 
2310   /// hasConstantValue - If the specified PHI node always merges together the
2311   /// same value, return the value, otherwise return null.
2312   Value *hasConstantValue() const;
2313 
2314   /// Methods for support type inquiry through isa, cast, and dyn_cast:
2315   static inline bool classof(const Instruction *I) {
2316     return I->getOpcode() == Instruction::PHI;
2317   }
2318   static inline bool classof(const Value *V) {
2319     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2320   }
2321  private:
2322   void growOperands();
2323 };
2324 
2325 template <>
2326 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2327 };
2328 
2329 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2330 
2331 //===----------------------------------------------------------------------===//
2332 //                           LandingPadInst Class
2333 //===----------------------------------------------------------------------===//
2334 
2335 //===---------------------------------------------------------------------------
2336 /// LandingPadInst - The landingpad instruction holds all of the information
2337 /// necessary to generate correct exception handling. The landingpad instruction
2338 /// cannot be moved from the top of a landing pad block, which itself is
2339 /// accessible only from the 'unwind' edge of an invoke. This uses the
2340 /// SubclassData field in Value to store whether or not the landingpad is a
2341 /// cleanup.
2342 ///
2343 class LandingPadInst : public Instruction {
2344   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
2345   /// the number actually in use.
2346   unsigned ReservedSpace;
2347   LandingPadInst(const LandingPadInst &LP);
2348 public:
2349   enum ClauseType { Catch, Filter };
2350 private:
2351   void *operator new(size_t, unsigned) = delete;
2352   // Allocate space for exactly zero operands.
2353   void *operator new(size_t s) {
2354     return User::operator new(s, 0);
2355   }
2356   void growOperands(unsigned Size);
2357   void init(Value *PersFn, unsigned NumReservedValues, const Twine &NameStr);
2358 
2359   explicit LandingPadInst(Type *RetTy, Value *PersonalityFn,
2360                           unsigned NumReservedValues, const Twine &NameStr,
2361                           Instruction *InsertBefore);
2362   explicit LandingPadInst(Type *RetTy, Value *PersonalityFn,
2363                           unsigned NumReservedValues, const Twine &NameStr,
2364                           BasicBlock *InsertAtEnd);
2365 protected:
2366   LandingPadInst *clone_impl() const override;
2367 public:
2368   /// Constructors - NumReservedClauses is a hint for the number of incoming
2369   /// clauses that this landingpad will have (use 0 if you really have no idea).
2370   static LandingPadInst *Create(Type *RetTy, Value *PersonalityFn,
2371                                 unsigned NumReservedClauses,
2372                                 const Twine &NameStr = "",
2373                                 Instruction *InsertBefore = nullptr);
2374   static LandingPadInst *Create(Type *RetTy, Value *PersonalityFn,
2375                                 unsigned NumReservedClauses,
2376                                 const Twine &NameStr, BasicBlock *InsertAtEnd);
2377   ~LandingPadInst() override;
2378 
2379   /// Provide fast operand accessors
2380   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2381 
2382   /// getPersonalityFn - Get the personality function associated with this
2383   /// landing pad.
2384   Value *getPersonalityFn() const { return getOperand(0); }
2385 
2386   /// isCleanup - Return 'true' if this landingpad instruction is a
2387   /// cleanup. I.e., it should be run when unwinding even if its landing pad
2388   /// doesn't catch the exception.
2389   bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2390 
2391   /// setCleanup - Indicate that this landingpad instruction is a cleanup.
2392   void setCleanup(bool V) {
2393     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2394                                (V ? 1 : 0));
2395   }
2396 
2397   /// Add a catch or filter clause to the landing pad.
2398   void addClause(Constant *ClauseVal);
2399 
2400   /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2401   /// determine what type of clause this is.
2402   Constant *getClause(unsigned Idx) const {
2403     return cast<Constant>(OperandList[Idx + 1]);
2404   }
2405 
2406   /// isCatch - Return 'true' if the clause and index Idx is a catch clause.
2407   bool isCatch(unsigned Idx) const {
2408     return !isa<ArrayType>(OperandList[Idx + 1]->getType());
2409   }
2410 
2411   /// isFilter - Return 'true' if the clause and index Idx is a filter clause.
2412   bool isFilter(unsigned Idx) const {
2413     return isa<ArrayType>(OperandList[Idx + 1]->getType());
2414   }
2415 
2416   /// getNumClauses - Get the number of clauses for this landing pad.
2417   unsigned getNumClauses() const { return getNumOperands() - 1; }
2418 
2419   /// reserveClauses - Grow the size of the operand list to accommodate the new
2420   /// number of clauses.
2421   void reserveClauses(unsigned Size) { growOperands(Size); }
2422 
2423   // Methods for support type inquiry through isa, cast, and dyn_cast:
2424   static inline bool classof(const Instruction *I) {
2425     return I->getOpcode() == Instruction::LandingPad;
2426   }
2427   static inline bool classof(const Value *V) {
2428     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2429   }
2430 };
2431 
2432 template <>
2433 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<2> {
2434 };
2435 
2436 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2437 
2438 //===----------------------------------------------------------------------===//
2439 //                               ReturnInst Class
2440 //===----------------------------------------------------------------------===//
2441 
2442 //===---------------------------------------------------------------------------
2443 /// ReturnInst - Return a value (possibly void), from a function.  Execution
2444 /// does not continue in this function any longer.
2445 ///
2446 class ReturnInst : public TerminatorInst {
2447   ReturnInst(const ReturnInst &RI);
2448 
2449 private:
2450   // ReturnInst constructors:
2451   // ReturnInst()                  - 'ret void' instruction
2452   // ReturnInst(    null)          - 'ret void' instruction
2453   // ReturnInst(Value* X)          - 'ret X'    instruction
2454   // ReturnInst(    null, Inst *I) - 'ret void' instruction, insert before I
2455   // ReturnInst(Value* X, Inst *I) - 'ret X'    instruction, insert before I
2456   // ReturnInst(    null, BB *B)   - 'ret void' instruction, insert @ end of B
2457   // ReturnInst(Value* X, BB *B)   - 'ret X'    instruction, insert @ end of B
2458   //
2459   // NOTE: If the Value* passed is of type void then the constructor behaves as
2460   // if it was passed NULL.
2461   explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2462                       Instruction *InsertBefore = nullptr);
2463   ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2464   explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2465 protected:
2466   ReturnInst *clone_impl() const override;
2467 public:
2468   static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2469                             Instruction *InsertBefore = nullptr) {
2470     return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2471   }
2472   static ReturnInst* Create(LLVMContext &C, Value *retVal,
2473                             BasicBlock *InsertAtEnd) {
2474     return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2475   }
2476   static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2477     return new(0) ReturnInst(C, InsertAtEnd);
2478   }
2479   ~ReturnInst() override;
2480 
2481   /// Provide fast operand accessors
2482   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2483 
2484   /// Convenience accessor. Returns null if there is no return value.
2485   Value *getReturnValue() const {
2486     return getNumOperands() != 0 ? getOperand(0) : nullptr;
2487   }
2488 
2489   unsigned getNumSuccessors() const { return 0; }
2490 
2491   // Methods for support type inquiry through isa, cast, and dyn_cast:
2492   static inline bool classof(const Instruction *I) {
2493     return (I->getOpcode() == Instruction::Ret);
2494   }
2495   static inline bool classof(const Value *V) {
2496     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2497   }
2498  private:
2499   BasicBlock *getSuccessorV(unsigned idx) const override;
2500   unsigned getNumSuccessorsV() const override;
2501   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2502 };
2503 
2504 template <>
2505 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2506 };
2507 
2508 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2509 
2510 //===----------------------------------------------------------------------===//
2511 //                               BranchInst Class
2512 //===----------------------------------------------------------------------===//
2513 
2514 //===---------------------------------------------------------------------------
2515 /// BranchInst - Conditional or Unconditional Branch instruction.
2516 ///
2517 class BranchInst : public TerminatorInst {
2518   /// Ops list - Branches are strange.  The operands are ordered:
2519   ///  [Cond, FalseDest,] TrueDest.  This makes some accessors faster because
2520   /// they don't have to check for cond/uncond branchness. These are mostly
2521   /// accessed relative from op_end().
2522   BranchInst(const BranchInst &BI);
2523   void AssertOK();
2524   // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2525   // BranchInst(BB *B)                           - 'br B'
2526   // BranchInst(BB* T, BB *F, Value *C)          - 'br C, T, F'
2527   // BranchInst(BB* B, Inst *I)                  - 'br B'        insert before I
2528   // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2529   // BranchInst(BB* B, BB *I)                    - 'br B'        insert at end
2530   // BranchInst(BB* T, BB *F, Value *C, BB *I)   - 'br C, T, F', insert at end
2531   explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2532   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2533              Instruction *InsertBefore = nullptr);
2534   BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2535   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2536              BasicBlock *InsertAtEnd);
2537 protected:
2538   BranchInst *clone_impl() const override;
2539 public:
2540   static BranchInst *Create(BasicBlock *IfTrue,
2541                             Instruction *InsertBefore = nullptr) {
2542     return new(1) BranchInst(IfTrue, InsertBefore);
2543   }
2544   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2545                             Value *Cond, Instruction *InsertBefore = nullptr) {
2546     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
2547   }
2548   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
2549     return new(1) BranchInst(IfTrue, InsertAtEnd);
2550   }
2551   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2552                             Value *Cond, BasicBlock *InsertAtEnd) {
2553     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
2554   }
2555 
2556   /// Transparently provide more efficient getOperand methods.
2557   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2558 
2559   bool isUnconditional() const { return getNumOperands() == 1; }
2560   bool isConditional()   const { return getNumOperands() == 3; }
2561 
2562   Value *getCondition() const {
2563     assert(isConditional() && "Cannot get condition of an uncond branch!");
2564     return Op<-3>();
2565   }
2566 
2567   void setCondition(Value *V) {
2568     assert(isConditional() && "Cannot set condition of unconditional branch!");
2569     Op<-3>() = V;
2570   }
2571 
2572   unsigned getNumSuccessors() const { return 1+isConditional(); }
2573 
2574   BasicBlock *getSuccessor(unsigned i) const {
2575     assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
2576     return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
2577   }
2578 
2579   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
2580     assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
2581     *(&Op<-1>() - idx) = (Value*)NewSucc;
2582   }
2583 
2584   /// \brief Swap the successors of this branch instruction.
2585   ///
2586   /// Swaps the successors of the branch instruction. This also swaps any
2587   /// branch weight metadata associated with the instruction so that it
2588   /// continues to map correctly to each operand.
2589   void swapSuccessors();
2590 
2591   // Methods for support type inquiry through isa, cast, and dyn_cast:
2592   static inline bool classof(const Instruction *I) {
2593     return (I->getOpcode() == Instruction::Br);
2594   }
2595   static inline bool classof(const Value *V) {
2596     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2597   }
2598 private:
2599   BasicBlock *getSuccessorV(unsigned idx) const override;
2600   unsigned getNumSuccessorsV() const override;
2601   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2602 };
2603 
2604 template <>
2605 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
2606 };
2607 
2608 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
2609 
2610 //===----------------------------------------------------------------------===//
2611 //                               SwitchInst Class
2612 //===----------------------------------------------------------------------===//
2613 
2614 //===---------------------------------------------------------------------------
2615 /// SwitchInst - Multiway switch
2616 ///
2617 class SwitchInst : public TerminatorInst {
2618   void *operator new(size_t, unsigned) = delete;
2619   unsigned ReservedSpace;
2620   // Operand[0]    = Value to switch on
2621   // Operand[1]    = Default basic block destination
2622   // Operand[2n  ] = Value to match
2623   // Operand[2n+1] = BasicBlock to go to on match
2624   SwitchInst(const SwitchInst &SI);
2625   void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
2626   void growOperands();
2627   // allocate space for exactly zero operands
2628   void *operator new(size_t s) {
2629     return User::operator new(s, 0);
2630   }
2631   /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2632   /// switch on and a default destination.  The number of additional cases can
2633   /// be specified here to make memory allocation more efficient.  This
2634   /// constructor can also autoinsert before another instruction.
2635   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2636              Instruction *InsertBefore);
2637 
2638   /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2639   /// switch on and a default destination.  The number of additional cases can
2640   /// be specified here to make memory allocation more efficient.  This
2641   /// constructor also autoinserts at the end of the specified BasicBlock.
2642   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2643              BasicBlock *InsertAtEnd);
2644 protected:
2645   SwitchInst *clone_impl() const override;
2646 public:
2647 
2648   // -2
2649   static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
2650 
2651   template <class SwitchInstTy, class ConstantIntTy, class BasicBlockTy>
2652   class CaseIteratorT {
2653   protected:
2654 
2655     SwitchInstTy *SI;
2656     unsigned Index;
2657 
2658   public:
2659 
2660     typedef CaseIteratorT<SwitchInstTy, ConstantIntTy, BasicBlockTy> Self;
2661 
2662     /// Initializes case iterator for given SwitchInst and for given
2663     /// case number.
2664     CaseIteratorT(SwitchInstTy *SI, unsigned CaseNum) {
2665       this->SI = SI;
2666       Index = CaseNum;
2667     }
2668 
2669     /// Initializes case iterator for given SwitchInst and for given
2670     /// TerminatorInst's successor index.
2671     static Self fromSuccessorIndex(SwitchInstTy *SI, unsigned SuccessorIndex) {
2672       assert(SuccessorIndex < SI->getNumSuccessors() &&
2673              "Successor index # out of range!");
2674       return SuccessorIndex != 0 ?
2675              Self(SI, SuccessorIndex - 1) :
2676              Self(SI, DefaultPseudoIndex);
2677     }
2678 
2679     /// Resolves case value for current case.
2680     ConstantIntTy *getCaseValue() {
2681       assert(Index < SI->getNumCases() && "Index out the number of cases.");
2682       return reinterpret_cast<ConstantIntTy*>(SI->getOperand(2 + Index*2));
2683     }
2684 
2685     /// Resolves successor for current case.
2686     BasicBlockTy *getCaseSuccessor() {
2687       assert((Index < SI->getNumCases() ||
2688               Index == DefaultPseudoIndex) &&
2689              "Index out the number of cases.");
2690       return SI->getSuccessor(getSuccessorIndex());
2691     }
2692 
2693     /// Returns number of current case.
2694     unsigned getCaseIndex() const { return Index; }
2695 
2696     /// Returns TerminatorInst's successor index for current case successor.
2697     unsigned getSuccessorIndex() const {
2698       assert((Index == DefaultPseudoIndex || Index < SI->getNumCases()) &&
2699              "Index out the number of cases.");
2700       return Index != DefaultPseudoIndex ? Index + 1 : 0;
2701     }
2702 
2703     Self operator++() {
2704       // Check index correctness after increment.
2705       // Note: Index == getNumCases() means end().
2706       assert(Index+1 <= SI->getNumCases() && "Index out the number of cases.");
2707       ++Index;
2708       return *this;
2709     }
2710     Self operator++(int) {
2711       Self tmp = *this;
2712       ++(*this);
2713       return tmp;
2714     }
2715     Self operator--() {
2716       // Check index correctness after decrement.
2717       // Note: Index == getNumCases() means end().
2718       // Also allow "-1" iterator here. That will became valid after ++.
2719       assert((Index == 0 || Index-1 <= SI->getNumCases()) &&
2720              "Index out the number of cases.");
2721       --Index;
2722       return *this;
2723     }
2724     Self operator--(int) {
2725       Self tmp = *this;
2726       --(*this);
2727       return tmp;
2728     }
2729     bool operator==(const Self& RHS) const {
2730       assert(RHS.SI == SI && "Incompatible operators.");
2731       return RHS.Index == Index;
2732     }
2733     bool operator!=(const Self& RHS) const {
2734       assert(RHS.SI == SI && "Incompatible operators.");
2735       return RHS.Index != Index;
2736     }
2737     Self &operator*() {
2738       return *this;
2739     }
2740   };
2741 
2742   typedef CaseIteratorT<const SwitchInst, const ConstantInt, const BasicBlock>
2743     ConstCaseIt;
2744 
2745   class CaseIt : public CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> {
2746 
2747     typedef CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> ParentTy;
2748 
2749   public:
2750 
2751     CaseIt(const ParentTy& Src) : ParentTy(Src) {}
2752     CaseIt(SwitchInst *SI, unsigned CaseNum) : ParentTy(SI, CaseNum) {}
2753 
2754     /// Sets the new value for current case.
2755     void setValue(ConstantInt *V) {
2756       assert(Index < SI->getNumCases() && "Index out the number of cases.");
2757       SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
2758     }
2759 
2760     /// Sets the new successor for current case.
2761     void setSuccessor(BasicBlock *S) {
2762       SI->setSuccessor(getSuccessorIndex(), S);
2763     }
2764   };
2765 
2766   static SwitchInst *Create(Value *Value, BasicBlock *Default,
2767                             unsigned NumCases,
2768                             Instruction *InsertBefore = nullptr) {
2769     return new SwitchInst(Value, Default, NumCases, InsertBefore);
2770   }
2771   static SwitchInst *Create(Value *Value, BasicBlock *Default,
2772                             unsigned NumCases, BasicBlock *InsertAtEnd) {
2773     return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
2774   }
2775 
2776   ~SwitchInst() override;
2777 
2778   /// Provide fast operand accessors
2779   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2780 
2781   // Accessor Methods for Switch stmt
2782   Value *getCondition() const { return getOperand(0); }
2783   void setCondition(Value *V) { setOperand(0, V); }
2784 
2785   BasicBlock *getDefaultDest() const {
2786     return cast<BasicBlock>(getOperand(1));
2787   }
2788 
2789   void setDefaultDest(BasicBlock *DefaultCase) {
2790     setOperand(1, reinterpret_cast<Value*>(DefaultCase));
2791   }
2792 
2793   /// getNumCases - return the number of 'cases' in this switch instruction,
2794   /// except the default case
2795   unsigned getNumCases() const {
2796     return getNumOperands()/2 - 1;
2797   }
2798 
2799   /// Returns a read/write iterator that points to the first
2800   /// case in SwitchInst.
2801   CaseIt case_begin() {
2802     return CaseIt(this, 0);
2803   }
2804   /// Returns a read-only iterator that points to the first
2805   /// case in the SwitchInst.
2806   ConstCaseIt case_begin() const {
2807     return ConstCaseIt(this, 0);
2808   }
2809 
2810   /// Returns a read/write iterator that points one past the last
2811   /// in the SwitchInst.
2812   CaseIt case_end() {
2813     return CaseIt(this, getNumCases());
2814   }
2815   /// Returns a read-only iterator that points one past the last
2816   /// in the SwitchInst.
2817   ConstCaseIt case_end() const {
2818     return ConstCaseIt(this, getNumCases());
2819   }
2820 
2821   /// cases - iteration adapter for range-for loops.
2822   iterator_range<CaseIt> cases() {
2823     return iterator_range<CaseIt>(case_begin(), case_end());
2824   }
2825 
2826   /// cases - iteration adapter for range-for loops.
2827   iterator_range<ConstCaseIt> cases() const {
2828     return iterator_range<ConstCaseIt>(case_begin(), case_end());
2829   }
2830 
2831   /// Returns an iterator that points to the default case.
2832   /// Note: this iterator allows to resolve successor only. Attempt
2833   /// to resolve case value causes an assertion.
2834   /// Also note, that increment and decrement also causes an assertion and
2835   /// makes iterator invalid.
2836   CaseIt case_default() {
2837     return CaseIt(this, DefaultPseudoIndex);
2838   }
2839   ConstCaseIt case_default() const {
2840     return ConstCaseIt(this, DefaultPseudoIndex);
2841   }
2842 
2843   /// findCaseValue - Search all of the case values for the specified constant.
2844   /// If it is explicitly handled, return the case iterator of it, otherwise
2845   /// return default case iterator to indicate
2846   /// that it is handled by the default handler.
2847   CaseIt findCaseValue(const ConstantInt *C) {
2848     for (CaseIt i = case_begin(), e = case_end(); i != e; ++i)
2849       if (i.getCaseValue() == C)
2850         return i;
2851     return case_default();
2852   }
2853   ConstCaseIt findCaseValue(const ConstantInt *C) const {
2854     for (ConstCaseIt i = case_begin(), e = case_end(); i != e; ++i)
2855       if (i.getCaseValue() == C)
2856         return i;
2857     return case_default();
2858   }
2859 
2860   /// findCaseDest - Finds the unique case value for a given successor. Returns
2861   /// null if the successor is not found, not unique, or is the default case.
2862   ConstantInt *findCaseDest(BasicBlock *BB) {
2863     if (BB == getDefaultDest()) return nullptr;
2864 
2865     ConstantInt *CI = nullptr;
2866     for (CaseIt i = case_begin(), e = case_end(); i != e; ++i) {
2867       if (i.getCaseSuccessor() == BB) {
2868         if (CI) return nullptr;   // Multiple cases lead to BB.
2869         else CI = i.getCaseValue();
2870       }
2871     }
2872     return CI;
2873   }
2874 
2875   /// addCase - Add an entry to the switch instruction...
2876   /// Note:
2877   /// This action invalidates case_end(). Old case_end() iterator will
2878   /// point to the added case.
2879   void addCase(ConstantInt *OnVal, BasicBlock *Dest);
2880 
2881   /// removeCase - This method removes the specified case and its successor
2882   /// from the switch instruction. Note that this operation may reorder the
2883   /// remaining cases at index idx and above.
2884   /// Note:
2885   /// This action invalidates iterators for all cases following the one removed,
2886   /// including the case_end() iterator.
2887   void removeCase(CaseIt i);
2888 
2889   unsigned getNumSuccessors() const { return getNumOperands()/2; }
2890   BasicBlock *getSuccessor(unsigned idx) const {
2891     assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
2892     return cast<BasicBlock>(getOperand(idx*2+1));
2893   }
2894   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
2895     assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
2896     setOperand(idx*2+1, (Value*)NewSucc);
2897   }
2898 
2899   // Methods for support type inquiry through isa, cast, and dyn_cast:
2900   static inline bool classof(const Instruction *I) {
2901     return I->getOpcode() == Instruction::Switch;
2902   }
2903   static inline bool classof(const Value *V) {
2904     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2905   }
2906 private:
2907   BasicBlock *getSuccessorV(unsigned idx) const override;
2908   unsigned getNumSuccessorsV() const override;
2909   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2910 };
2911 
2912 template <>
2913 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
2914 };
2915 
2916 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
2917 
2918 
2919 //===----------------------------------------------------------------------===//
2920 //                             IndirectBrInst Class
2921 //===----------------------------------------------------------------------===//
2922 
2923 //===---------------------------------------------------------------------------
2924 /// IndirectBrInst - Indirect Branch Instruction.
2925 ///
2926 class IndirectBrInst : public TerminatorInst {
2927   void *operator new(size_t, unsigned) = delete;
2928   unsigned ReservedSpace;
2929   // Operand[0]    = Value to switch on
2930   // Operand[1]    = Default basic block destination
2931   // Operand[2n  ] = Value to match
2932   // Operand[2n+1] = BasicBlock to go to on match
2933   IndirectBrInst(const IndirectBrInst &IBI);
2934   void init(Value *Address, unsigned NumDests);
2935   void growOperands();
2936   // allocate space for exactly zero operands
2937   void *operator new(size_t s) {
2938     return User::operator new(s, 0);
2939   }
2940   /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
2941   /// Address to jump to.  The number of expected destinations can be specified
2942   /// here to make memory allocation more efficient.  This constructor can also
2943   /// autoinsert before another instruction.
2944   IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
2945 
2946   /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
2947   /// Address to jump to.  The number of expected destinations can be specified
2948   /// here to make memory allocation more efficient.  This constructor also
2949   /// autoinserts at the end of the specified BasicBlock.
2950   IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
2951 protected:
2952   IndirectBrInst *clone_impl() const override;
2953 public:
2954   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
2955                                 Instruction *InsertBefore = nullptr) {
2956     return new IndirectBrInst(Address, NumDests, InsertBefore);
2957   }
2958   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
2959                                 BasicBlock *InsertAtEnd) {
2960     return new IndirectBrInst(Address, NumDests, InsertAtEnd);
2961   }
2962   ~IndirectBrInst() override;
2963 
2964   /// Provide fast operand accessors.
2965   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2966 
2967   // Accessor Methods for IndirectBrInst instruction.
2968   Value *getAddress() { return getOperand(0); }
2969   const Value *getAddress() const { return getOperand(0); }
2970   void setAddress(Value *V) { setOperand(0, V); }
2971 
2972 
2973   /// getNumDestinations - return the number of possible destinations in this
2974   /// indirectbr instruction.
2975   unsigned getNumDestinations() const { return getNumOperands()-1; }
2976 
2977   /// getDestination - Return the specified destination.
2978   BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
2979   const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
2980 
2981   /// addDestination - Add a destination.
2982   ///
2983   void addDestination(BasicBlock *Dest);
2984 
2985   /// removeDestination - This method removes the specified successor from the
2986   /// indirectbr instruction.
2987   void removeDestination(unsigned i);
2988 
2989   unsigned getNumSuccessors() const { return getNumOperands()-1; }
2990   BasicBlock *getSuccessor(unsigned i) const {
2991     return cast<BasicBlock>(getOperand(i+1));
2992   }
2993   void setSuccessor(unsigned i, BasicBlock *NewSucc) {
2994     setOperand(i+1, (Value*)NewSucc);
2995   }
2996 
2997   // Methods for support type inquiry through isa, cast, and dyn_cast:
2998   static inline bool classof(const Instruction *I) {
2999     return I->getOpcode() == Instruction::IndirectBr;
3000   }
3001   static inline bool classof(const Value *V) {
3002     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3003   }
3004 private:
3005   BasicBlock *getSuccessorV(unsigned idx) const override;
3006   unsigned getNumSuccessorsV() const override;
3007   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3008 };
3009 
3010 template <>
3011 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3012 };
3013 
3014 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3015 
3016 
3017 //===----------------------------------------------------------------------===//
3018 //                               InvokeInst Class
3019 //===----------------------------------------------------------------------===//
3020 
3021 /// InvokeInst - Invoke instruction.  The SubclassData field is used to hold the
3022 /// calling convention of the call.
3023 ///
3024 class InvokeInst : public TerminatorInst {
3025   AttributeSet AttributeList;
3026   InvokeInst(const InvokeInst &BI);
3027   void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3028             ArrayRef<Value *> Args, const Twine &NameStr);
3029 
3030   /// Construct an InvokeInst given a range of arguments.
3031   ///
3032   /// \brief Construct an InvokeInst from a range of arguments
3033   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3034                     ArrayRef<Value *> Args, unsigned Values,
3035                     const Twine &NameStr, Instruction *InsertBefore);
3036 
3037   /// Construct an InvokeInst given a range of arguments.
3038   ///
3039   /// \brief Construct an InvokeInst from a range of arguments
3040   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3041                     ArrayRef<Value *> Args, unsigned Values,
3042                     const Twine &NameStr, BasicBlock *InsertAtEnd);
3043 protected:
3044   InvokeInst *clone_impl() const override;
3045 public:
3046   static InvokeInst *Create(Value *Func,
3047                             BasicBlock *IfNormal, BasicBlock *IfException,
3048                             ArrayRef<Value *> Args, const Twine &NameStr = "",
3049                             Instruction *InsertBefore = nullptr) {
3050     unsigned Values = unsigned(Args.size()) + 3;
3051     return new(Values) InvokeInst(Func, IfNormal, IfException, Args,
3052                                   Values, NameStr, InsertBefore);
3053   }
3054   static InvokeInst *Create(Value *Func,
3055                             BasicBlock *IfNormal, BasicBlock *IfException,
3056                             ArrayRef<Value *> Args, const Twine &NameStr,
3057                             BasicBlock *InsertAtEnd) {
3058     unsigned Values = unsigned(Args.size()) + 3;
3059     return new(Values) InvokeInst(Func, IfNormal, IfException, Args,
3060                                   Values, NameStr, InsertAtEnd);
3061   }
3062 
3063   /// Provide fast operand accessors
3064   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3065 
3066   /// getNumArgOperands - Return the number of invoke arguments.
3067   ///
3068   unsigned getNumArgOperands() const { return getNumOperands() - 3; }
3069 
3070   /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3071   ///
3072   Value *getArgOperand(unsigned i) const { return getOperand(i); }
3073   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
3074 
3075   /// arg_operands - iteration adapter for range-for loops.
3076   iterator_range<op_iterator> arg_operands() {
3077     return iterator_range<op_iterator>(op_begin(), op_end() - 3);
3078   }
3079 
3080   /// arg_operands - iteration adapter for range-for loops.
3081   iterator_range<const_op_iterator> arg_operands() const {
3082     return iterator_range<const_op_iterator>(op_begin(), op_end() - 3);
3083   }
3084 
3085   /// \brief Wrappers for getting the \c Use of a invoke argument.
3086   const Use &getArgOperandUse(unsigned i) const { return getOperandUse(i); }
3087   Use &getArgOperandUse(unsigned i) { return getOperandUse(i); }
3088 
3089   /// getCallingConv/setCallingConv - Get or set the calling convention of this
3090   /// function call.
3091   CallingConv::ID getCallingConv() const {
3092     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3093   }
3094   void setCallingConv(CallingConv::ID CC) {
3095     setInstructionSubclassData(static_cast<unsigned>(CC));
3096   }
3097 
3098   /// getAttributes - Return the parameter attributes for this invoke.
3099   ///
3100   const AttributeSet &getAttributes() const { return AttributeList; }
3101 
3102   /// setAttributes - Set the parameter attributes for this invoke.
3103   ///
3104   void setAttributes(const AttributeSet &Attrs) { AttributeList = Attrs; }
3105 
3106   /// addAttribute - adds the attribute to the list of attributes.
3107   void addAttribute(unsigned i, Attribute::AttrKind attr);
3108 
3109   /// removeAttribute - removes the attribute from the list of attributes.
3110   void removeAttribute(unsigned i, Attribute attr);
3111 
3112   /// \brief adds the dereferenceable attribute to the list of attributes.
3113   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3114 
3115   /// \brief adds the dereferenceable_or_null attribute to the list of
3116   /// attributes.
3117   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
3118 
3119   /// \brief Determine whether this call has the given attribute.
3120   bool hasFnAttr(Attribute::AttrKind A) const {
3121     assert(A != Attribute::NoBuiltin &&
3122            "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
3123     return hasFnAttrImpl(A);
3124   }
3125 
3126   /// \brief Determine whether the call or the callee has the given attributes.
3127   bool paramHasAttr(unsigned i, Attribute::AttrKind A) const;
3128 
3129   /// \brief Extract the alignment for a call or parameter (0=unknown).
3130   unsigned getParamAlignment(unsigned i) const {
3131     return AttributeList.getParamAlignment(i);
3132   }
3133 
3134   /// \brief Extract the number of dereferenceable bytes for a call or
3135   /// parameter (0=unknown).
3136   uint64_t getDereferenceableBytes(unsigned i) const {
3137     return AttributeList.getDereferenceableBytes(i);
3138   }
3139 
3140   /// \brief Return true if the call should not be treated as a call to a
3141   /// builtin.
3142   bool isNoBuiltin() const {
3143     // We assert in hasFnAttr if one passes in Attribute::NoBuiltin, so we have
3144     // to check it by hand.
3145     return hasFnAttrImpl(Attribute::NoBuiltin) &&
3146       !hasFnAttrImpl(Attribute::Builtin);
3147   }
3148 
3149   /// \brief Return true if the call should not be inlined.
3150   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
3151   void setIsNoInline() {
3152     addAttribute(AttributeSet::FunctionIndex, Attribute::NoInline);
3153   }
3154 
3155   /// \brief Determine if the call does not access memory.
3156   bool doesNotAccessMemory() const {
3157     return hasFnAttr(Attribute::ReadNone);
3158   }
3159   void setDoesNotAccessMemory() {
3160     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
3161   }
3162 
3163   /// \brief Determine if the call does not access or only reads memory.
3164   bool onlyReadsMemory() const {
3165     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
3166   }
3167   void setOnlyReadsMemory() {
3168     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
3169   }
3170 
3171   /// \brief Determine if the call cannot return.
3172   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
3173   void setDoesNotReturn() {
3174     addAttribute(AttributeSet::FunctionIndex, Attribute::NoReturn);
3175   }
3176 
3177   /// \brief Determine if the call cannot unwind.
3178   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3179   void setDoesNotThrow() {
3180     addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
3181   }
3182 
3183   /// \brief Determine if the invoke cannot be duplicated.
3184   bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
3185   void setCannotDuplicate() {
3186     addAttribute(AttributeSet::FunctionIndex, Attribute::NoDuplicate);
3187   }
3188 
3189   /// \brief Determine if the call returns a structure through first
3190   /// pointer argument.
3191   bool hasStructRetAttr() const {
3192     // Be friendly and also check the callee.
3193     return paramHasAttr(1, Attribute::StructRet);
3194   }
3195 
3196   /// \brief Determine if any call argument is an aggregate passed by value.
3197   bool hasByValArgument() const {
3198     return AttributeList.hasAttrSomewhere(Attribute::ByVal);
3199   }
3200 
3201   /// getCalledFunction - Return the function called, or null if this is an
3202   /// indirect function invocation.
3203   ///
3204   Function *getCalledFunction() const {
3205     return dyn_cast<Function>(Op<-3>());
3206   }
3207 
3208   /// getCalledValue - Get a pointer to the function that is invoked by this
3209   /// instruction
3210   const Value *getCalledValue() const { return Op<-3>(); }
3211         Value *getCalledValue()       { return Op<-3>(); }
3212 
3213   /// setCalledFunction - Set the function called.
3214   void setCalledFunction(Value* Fn) {
3215     Op<-3>() = Fn;
3216   }
3217 
3218   // get*Dest - Return the destination basic blocks...
3219   BasicBlock *getNormalDest() const {
3220     return cast<BasicBlock>(Op<-2>());
3221   }
3222   BasicBlock *getUnwindDest() const {
3223     return cast<BasicBlock>(Op<-1>());
3224   }
3225   void setNormalDest(BasicBlock *B) {
3226     Op<-2>() = reinterpret_cast<Value*>(B);
3227   }
3228   void setUnwindDest(BasicBlock *B) {
3229     Op<-1>() = reinterpret_cast<Value*>(B);
3230   }
3231 
3232   /// getLandingPadInst - Get the landingpad instruction from the landing pad
3233   /// block (the unwind destination).
3234   LandingPadInst *getLandingPadInst() const;
3235 
3236   BasicBlock *getSuccessor(unsigned i) const {
3237     assert(i < 2 && "Successor # out of range for invoke!");
3238     return i == 0 ? getNormalDest() : getUnwindDest();
3239   }
3240 
3241   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3242     assert(idx < 2 && "Successor # out of range for invoke!");
3243     *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
3244   }
3245 
3246   unsigned getNumSuccessors() const { return 2; }
3247 
3248   // Methods for support type inquiry through isa, cast, and dyn_cast:
3249   static inline bool classof(const Instruction *I) {
3250     return (I->getOpcode() == Instruction::Invoke);
3251   }
3252   static inline bool classof(const Value *V) {
3253     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3254   }
3255 
3256 private:
3257   BasicBlock *getSuccessorV(unsigned idx) const override;
3258   unsigned getNumSuccessorsV() const override;
3259   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3260 
3261   bool hasFnAttrImpl(Attribute::AttrKind A) const;
3262 
3263   // Shadow Instruction::setInstructionSubclassData with a private forwarding
3264   // method so that subclasses cannot accidentally use it.
3265   void setInstructionSubclassData(unsigned short D) {
3266     Instruction::setInstructionSubclassData(D);
3267   }
3268 };
3269 
3270 template <>
3271 struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
3272 };
3273 
3274 InvokeInst::InvokeInst(Value *Func,
3275                        BasicBlock *IfNormal, BasicBlock *IfException,
3276                        ArrayRef<Value *> Args, unsigned Values,
3277                        const Twine &NameStr, Instruction *InsertBefore)
3278   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Func->getType())
3279                                       ->getElementType())->getReturnType(),
3280                    Instruction::Invoke,
3281                    OperandTraits<InvokeInst>::op_end(this) - Values,
3282                    Values, InsertBefore) {
3283   init(Func, IfNormal, IfException, Args, NameStr);
3284 }
3285 InvokeInst::InvokeInst(Value *Func,
3286                        BasicBlock *IfNormal, BasicBlock *IfException,
3287                        ArrayRef<Value *> Args, unsigned Values,
3288                        const Twine &NameStr, BasicBlock *InsertAtEnd)
3289   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Func->getType())
3290                                       ->getElementType())->getReturnType(),
3291                    Instruction::Invoke,
3292                    OperandTraits<InvokeInst>::op_end(this) - Values,
3293                    Values, InsertAtEnd) {
3294   init(Func, IfNormal, IfException, Args, NameStr);
3295 }
3296 
3297 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
3298 
3299 //===----------------------------------------------------------------------===//
3300 //                              ResumeInst Class
3301 //===----------------------------------------------------------------------===//
3302 
3303 //===---------------------------------------------------------------------------
3304 /// ResumeInst - Resume the propagation of an exception.
3305 ///
3306 class ResumeInst : public TerminatorInst {
3307   ResumeInst(const ResumeInst &RI);
3308 
3309   explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
3310   ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
3311 protected:
3312   ResumeInst *clone_impl() const override;
3313 public:
3314   static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
3315     return new(1) ResumeInst(Exn, InsertBefore);
3316   }
3317   static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
3318     return new(1) ResumeInst(Exn, InsertAtEnd);
3319   }
3320 
3321   /// Provide fast operand accessors
3322   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3323 
3324   /// Convenience accessor.
3325   Value *getValue() const { return Op<0>(); }
3326 
3327   unsigned getNumSuccessors() const { return 0; }
3328 
3329   // Methods for support type inquiry through isa, cast, and dyn_cast:
3330   static inline bool classof(const Instruction *I) {
3331     return I->getOpcode() == Instruction::Resume;
3332   }
3333   static inline bool classof(const Value *V) {
3334     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3335   }
3336 private:
3337   BasicBlock *getSuccessorV(unsigned idx) const override;
3338   unsigned getNumSuccessorsV() const override;
3339   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3340 };
3341 
3342 template <>
3343 struct OperandTraits<ResumeInst> :
3344     public FixedNumOperandTraits<ResumeInst, 1> {
3345 };
3346 
3347 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
3348 
3349 //===----------------------------------------------------------------------===//
3350 //                           UnreachableInst Class
3351 //===----------------------------------------------------------------------===//
3352 
3353 //===---------------------------------------------------------------------------
3354 /// UnreachableInst - This function has undefined behavior.  In particular, the
3355 /// presence of this instruction indicates some higher level knowledge that the
3356 /// end of the block cannot be reached.
3357 ///
3358 class UnreachableInst : public TerminatorInst {
3359   void *operator new(size_t, unsigned) = delete;
3360 protected:
3361   UnreachableInst *clone_impl() const override;
3362 
3363 public:
3364   // allocate space for exactly zero operands
3365   void *operator new(size_t s) {
3366     return User::operator new(s, 0);
3367   }
3368   explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
3369   explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
3370 
3371   unsigned getNumSuccessors() const { return 0; }
3372 
3373   // Methods for support type inquiry through isa, cast, and dyn_cast:
3374   static inline bool classof(const Instruction *I) {
3375     return I->getOpcode() == Instruction::Unreachable;
3376   }
3377   static inline bool classof(const Value *V) {
3378     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3379   }
3380 private:
3381   BasicBlock *getSuccessorV(unsigned idx) const override;
3382   unsigned getNumSuccessorsV() const override;
3383   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3384 };
3385 
3386 //===----------------------------------------------------------------------===//
3387 //                                 TruncInst Class
3388 //===----------------------------------------------------------------------===//
3389 
3390 /// \brief This class represents a truncation of integer types.
3391 class TruncInst : public CastInst {
3392 protected:
3393   /// \brief Clone an identical TruncInst
3394   TruncInst *clone_impl() const override;
3395 
3396 public:
3397   /// \brief Constructor with insert-before-instruction semantics
3398   TruncInst(
3399     Value *S,                           ///< The value to be truncated
3400     Type *Ty,                           ///< The (smaller) type to truncate to
3401     const Twine &NameStr = "",          ///< A name for the new instruction
3402     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3403   );
3404 
3405   /// \brief Constructor with insert-at-end-of-block semantics
3406   TruncInst(
3407     Value *S,                     ///< The value to be truncated
3408     Type *Ty,                     ///< The (smaller) type to truncate to
3409     const Twine &NameStr,         ///< A name for the new instruction
3410     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3411   );
3412 
3413   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3414   static inline bool classof(const Instruction *I) {
3415     return I->getOpcode() == Trunc;
3416   }
3417   static inline bool classof(const Value *V) {
3418     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3419   }
3420 };
3421 
3422 //===----------------------------------------------------------------------===//
3423 //                                 ZExtInst Class
3424 //===----------------------------------------------------------------------===//
3425 
3426 /// \brief This class represents zero extension of integer types.
3427 class ZExtInst : public CastInst {
3428 protected:
3429   /// \brief Clone an identical ZExtInst
3430   ZExtInst *clone_impl() const override;
3431 
3432 public:
3433   /// \brief Constructor with insert-before-instruction semantics
3434   ZExtInst(
3435     Value *S,                           ///< The value to be zero extended
3436     Type *Ty,                           ///< The type to zero extend to
3437     const Twine &NameStr = "",          ///< A name for the new instruction
3438     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3439   );
3440 
3441   /// \brief Constructor with insert-at-end semantics.
3442   ZExtInst(
3443     Value *S,                     ///< The value to be zero extended
3444     Type *Ty,                     ///< The type to zero extend to
3445     const Twine &NameStr,         ///< A name for the new instruction
3446     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3447   );
3448 
3449   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3450   static inline bool classof(const Instruction *I) {
3451     return I->getOpcode() == ZExt;
3452   }
3453   static inline bool classof(const Value *V) {
3454     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3455   }
3456 };
3457 
3458 //===----------------------------------------------------------------------===//
3459 //                                 SExtInst Class
3460 //===----------------------------------------------------------------------===//
3461 
3462 /// \brief This class represents a sign extension of integer types.
3463 class SExtInst : public CastInst {
3464 protected:
3465   /// \brief Clone an identical SExtInst
3466   SExtInst *clone_impl() const override;
3467 
3468 public:
3469   /// \brief Constructor with insert-before-instruction semantics
3470   SExtInst(
3471     Value *S,                           ///< The value to be sign extended
3472     Type *Ty,                           ///< The type to sign extend to
3473     const Twine &NameStr = "",          ///< A name for the new instruction
3474     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3475   );
3476 
3477   /// \brief Constructor with insert-at-end-of-block semantics
3478   SExtInst(
3479     Value *S,                     ///< The value to be sign extended
3480     Type *Ty,                     ///< The type to sign extend to
3481     const Twine &NameStr,         ///< A name for the new instruction
3482     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3483   );
3484 
3485   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3486   static inline bool classof(const Instruction *I) {
3487     return I->getOpcode() == SExt;
3488   }
3489   static inline bool classof(const Value *V) {
3490     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3491   }
3492 };
3493 
3494 //===----------------------------------------------------------------------===//
3495 //                                 FPTruncInst Class
3496 //===----------------------------------------------------------------------===//
3497 
3498 /// \brief This class represents a truncation of floating point types.
3499 class FPTruncInst : public CastInst {
3500 protected:
3501   /// \brief Clone an identical FPTruncInst
3502   FPTruncInst *clone_impl() const override;
3503 
3504 public:
3505   /// \brief Constructor with insert-before-instruction semantics
3506   FPTruncInst(
3507     Value *S,                           ///< The value to be truncated
3508     Type *Ty,                           ///< The type to truncate to
3509     const Twine &NameStr = "",          ///< A name for the new instruction
3510     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3511   );
3512 
3513   /// \brief Constructor with insert-before-instruction semantics
3514   FPTruncInst(
3515     Value *S,                     ///< The value to be truncated
3516     Type *Ty,                     ///< The type to truncate to
3517     const Twine &NameStr,         ///< A name for the new instruction
3518     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3519   );
3520 
3521   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3522   static inline bool classof(const Instruction *I) {
3523     return I->getOpcode() == FPTrunc;
3524   }
3525   static inline bool classof(const Value *V) {
3526     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3527   }
3528 };
3529 
3530 //===----------------------------------------------------------------------===//
3531 //                                 FPExtInst Class
3532 //===----------------------------------------------------------------------===//
3533 
3534 /// \brief This class represents an extension of floating point types.
3535 class FPExtInst : public CastInst {
3536 protected:
3537   /// \brief Clone an identical FPExtInst
3538   FPExtInst *clone_impl() const override;
3539 
3540 public:
3541   /// \brief Constructor with insert-before-instruction semantics
3542   FPExtInst(
3543     Value *S,                           ///< The value to be extended
3544     Type *Ty,                           ///< The type to extend to
3545     const Twine &NameStr = "",          ///< A name for the new instruction
3546     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3547   );
3548 
3549   /// \brief Constructor with insert-at-end-of-block semantics
3550   FPExtInst(
3551     Value *S,                     ///< The value to be extended
3552     Type *Ty,                     ///< The type to extend to
3553     const Twine &NameStr,         ///< A name for the new instruction
3554     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3555   );
3556 
3557   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3558   static inline bool classof(const Instruction *I) {
3559     return I->getOpcode() == FPExt;
3560   }
3561   static inline bool classof(const Value *V) {
3562     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3563   }
3564 };
3565 
3566 //===----------------------------------------------------------------------===//
3567 //                                 UIToFPInst Class
3568 //===----------------------------------------------------------------------===//
3569 
3570 /// \brief This class represents a cast unsigned integer to floating point.
3571 class UIToFPInst : public CastInst {
3572 protected:
3573   /// \brief Clone an identical UIToFPInst
3574   UIToFPInst *clone_impl() const override;
3575 
3576 public:
3577   /// \brief Constructor with insert-before-instruction semantics
3578   UIToFPInst(
3579     Value *S,                           ///< The value to be converted
3580     Type *Ty,                           ///< The type to convert to
3581     const Twine &NameStr = "",          ///< A name for the new instruction
3582     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3583   );
3584 
3585   /// \brief Constructor with insert-at-end-of-block semantics
3586   UIToFPInst(
3587     Value *S,                     ///< The value to be converted
3588     Type *Ty,                     ///< The type to convert to
3589     const Twine &NameStr,         ///< A name for the new instruction
3590     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3591   );
3592 
3593   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3594   static inline bool classof(const Instruction *I) {
3595     return I->getOpcode() == UIToFP;
3596   }
3597   static inline bool classof(const Value *V) {
3598     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3599   }
3600 };
3601 
3602 //===----------------------------------------------------------------------===//
3603 //                                 SIToFPInst Class
3604 //===----------------------------------------------------------------------===//
3605 
3606 /// \brief This class represents a cast from signed integer to floating point.
3607 class SIToFPInst : public CastInst {
3608 protected:
3609   /// \brief Clone an identical SIToFPInst
3610   SIToFPInst *clone_impl() const override;
3611 
3612 public:
3613   /// \brief Constructor with insert-before-instruction semantics
3614   SIToFPInst(
3615     Value *S,                           ///< The value to be converted
3616     Type *Ty,                           ///< The type to convert to
3617     const Twine &NameStr = "",          ///< A name for the new instruction
3618     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3619   );
3620 
3621   /// \brief Constructor with insert-at-end-of-block semantics
3622   SIToFPInst(
3623     Value *S,                     ///< The value to be converted
3624     Type *Ty,                     ///< The type to convert to
3625     const Twine &NameStr,         ///< A name for the new instruction
3626     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3627   );
3628 
3629   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3630   static inline bool classof(const Instruction *I) {
3631     return I->getOpcode() == SIToFP;
3632   }
3633   static inline bool classof(const Value *V) {
3634     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3635   }
3636 };
3637 
3638 //===----------------------------------------------------------------------===//
3639 //                                 FPToUIInst Class
3640 //===----------------------------------------------------------------------===//
3641 
3642 /// \brief This class represents a cast from floating point to unsigned integer
3643 class FPToUIInst  : public CastInst {
3644 protected:
3645   /// \brief Clone an identical FPToUIInst
3646   FPToUIInst *clone_impl() const override;
3647 
3648 public:
3649   /// \brief Constructor with insert-before-instruction semantics
3650   FPToUIInst(
3651     Value *S,                           ///< The value to be converted
3652     Type *Ty,                           ///< The type to convert to
3653     const Twine &NameStr = "",          ///< A name for the new instruction
3654     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3655   );
3656 
3657   /// \brief Constructor with insert-at-end-of-block semantics
3658   FPToUIInst(
3659     Value *S,                     ///< The value to be converted
3660     Type *Ty,                     ///< The type to convert to
3661     const Twine &NameStr,         ///< A name for the new instruction
3662     BasicBlock *InsertAtEnd       ///< Where to insert the new instruction
3663   );
3664 
3665   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3666   static inline bool classof(const Instruction *I) {
3667     return I->getOpcode() == FPToUI;
3668   }
3669   static inline bool classof(const Value *V) {
3670     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3671   }
3672 };
3673 
3674 //===----------------------------------------------------------------------===//
3675 //                                 FPToSIInst Class
3676 //===----------------------------------------------------------------------===//
3677 
3678 /// \brief This class represents a cast from floating point to signed integer.
3679 class FPToSIInst  : public CastInst {
3680 protected:
3681   /// \brief Clone an identical FPToSIInst
3682   FPToSIInst *clone_impl() const override;
3683 
3684 public:
3685   /// \brief Constructor with insert-before-instruction semantics
3686   FPToSIInst(
3687     Value *S,                           ///< The value to be converted
3688     Type *Ty,                           ///< The type to convert to
3689     const Twine &NameStr = "",          ///< A name for the new instruction
3690     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3691   );
3692 
3693   /// \brief Constructor with insert-at-end-of-block semantics
3694   FPToSIInst(
3695     Value *S,                     ///< The value to be converted
3696     Type *Ty,                     ///< The type to convert to
3697     const Twine &NameStr,         ///< A name for the new instruction
3698     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3699   );
3700 
3701   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3702   static inline bool classof(const Instruction *I) {
3703     return I->getOpcode() == FPToSI;
3704   }
3705   static inline bool classof(const Value *V) {
3706     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3707   }
3708 };
3709 
3710 //===----------------------------------------------------------------------===//
3711 //                                 IntToPtrInst Class
3712 //===----------------------------------------------------------------------===//
3713 
3714 /// \brief This class represents a cast from an integer to a pointer.
3715 class IntToPtrInst : public CastInst {
3716 public:
3717   /// \brief Constructor with insert-before-instruction semantics
3718   IntToPtrInst(
3719     Value *S,                           ///< The value to be converted
3720     Type *Ty,                           ///< The type to convert to
3721     const Twine &NameStr = "",          ///< A name for the new instruction
3722     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3723   );
3724 
3725   /// \brief Constructor with insert-at-end-of-block semantics
3726   IntToPtrInst(
3727     Value *S,                     ///< The value to be converted
3728     Type *Ty,                     ///< The type to convert to
3729     const Twine &NameStr,         ///< A name for the new instruction
3730     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3731   );
3732 
3733   /// \brief Clone an identical IntToPtrInst
3734   IntToPtrInst *clone_impl() const override;
3735 
3736   /// \brief Returns the address space of this instruction's pointer type.
3737   unsigned getAddressSpace() const {
3738     return getType()->getPointerAddressSpace();
3739   }
3740 
3741   // Methods for support type inquiry through isa, cast, and dyn_cast:
3742   static inline bool classof(const Instruction *I) {
3743     return I->getOpcode() == IntToPtr;
3744   }
3745   static inline bool classof(const Value *V) {
3746     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3747   }
3748 };
3749 
3750 //===----------------------------------------------------------------------===//
3751 //                                 PtrToIntInst Class
3752 //===----------------------------------------------------------------------===//
3753 
3754 /// \brief This class represents a cast from a pointer to an integer
3755 class PtrToIntInst : public CastInst {
3756 protected:
3757   /// \brief Clone an identical PtrToIntInst
3758   PtrToIntInst *clone_impl() const override;
3759 
3760 public:
3761   /// \brief Constructor with insert-before-instruction semantics
3762   PtrToIntInst(
3763     Value *S,                           ///< The value to be converted
3764     Type *Ty,                           ///< The type to convert to
3765     const Twine &NameStr = "",          ///< A name for the new instruction
3766     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3767   );
3768 
3769   /// \brief Constructor with insert-at-end-of-block semantics
3770   PtrToIntInst(
3771     Value *S,                     ///< The value to be converted
3772     Type *Ty,                     ///< The type to convert to
3773     const Twine &NameStr,         ///< A name for the new instruction
3774     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3775   );
3776 
3777   /// \brief Gets the pointer operand.
3778   Value *getPointerOperand() { return getOperand(0); }
3779   /// \brief Gets the pointer operand.
3780   const Value *getPointerOperand() const { return getOperand(0); }
3781   /// \brief Gets the operand index of the pointer operand.
3782   static unsigned getPointerOperandIndex() { return 0U; }
3783 
3784   /// \brief Returns the address space of the pointer operand.
3785   unsigned getPointerAddressSpace() const {
3786     return getPointerOperand()->getType()->getPointerAddressSpace();
3787   }
3788 
3789   // Methods for support type inquiry through isa, cast, and dyn_cast:
3790   static inline bool classof(const Instruction *I) {
3791     return I->getOpcode() == PtrToInt;
3792   }
3793   static inline bool classof(const Value *V) {
3794     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3795   }
3796 };
3797 
3798 //===----------------------------------------------------------------------===//
3799 //                             BitCastInst Class
3800 //===----------------------------------------------------------------------===//
3801 
3802 /// \brief This class represents a no-op cast from one type to another.
3803 class BitCastInst : public CastInst {
3804 protected:
3805   /// \brief Clone an identical BitCastInst
3806   BitCastInst *clone_impl() const override;
3807 
3808 public:
3809   /// \brief Constructor with insert-before-instruction semantics
3810   BitCastInst(
3811     Value *S,                           ///< The value to be casted
3812     Type *Ty,                           ///< The type to casted to
3813     const Twine &NameStr = "",          ///< A name for the new instruction
3814     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3815   );
3816 
3817   /// \brief Constructor with insert-at-end-of-block semantics
3818   BitCastInst(
3819     Value *S,                     ///< The value to be casted
3820     Type *Ty,                     ///< The type to casted to
3821     const Twine &NameStr,         ///< A name for the new instruction
3822     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3823   );
3824 
3825   // Methods for support type inquiry through isa, cast, and dyn_cast:
3826   static inline bool classof(const Instruction *I) {
3827     return I->getOpcode() == BitCast;
3828   }
3829   static inline bool classof(const Value *V) {
3830     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3831   }
3832 };
3833 
3834 //===----------------------------------------------------------------------===//
3835 //                          AddrSpaceCastInst Class
3836 //===----------------------------------------------------------------------===//
3837 
3838 /// \brief This class represents a conversion between pointers from
3839 /// one address space to another.
3840 class AddrSpaceCastInst : public CastInst {
3841 protected:
3842   /// \brief Clone an identical AddrSpaceCastInst
3843   AddrSpaceCastInst *clone_impl() const override;
3844 
3845 public:
3846   /// \brief Constructor with insert-before-instruction semantics
3847   AddrSpaceCastInst(
3848     Value *S,                           ///< The value to be casted
3849     Type *Ty,                           ///< The type to casted to
3850     const Twine &NameStr = "",          ///< A name for the new instruction
3851     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3852   );
3853 
3854   /// \brief Constructor with insert-at-end-of-block semantics
3855   AddrSpaceCastInst(
3856     Value *S,                     ///< The value to be casted
3857     Type *Ty,                     ///< The type to casted to
3858     const Twine &NameStr,         ///< A name for the new instruction
3859     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3860   );
3861 
3862   // Methods for support type inquiry through isa, cast, and dyn_cast:
3863   static inline bool classof(const Instruction *I) {
3864     return I->getOpcode() == AddrSpaceCast;
3865   }
3866   static inline bool classof(const Value *V) {
3867     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3868   }
3869 };
3870 
3871 } // End llvm namespace
3872 
3873 #endif
3874