LLVM  9.0.0svn
Instructions.h
Go to the documentation of this file.
1 //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file exposes the class definitions of all of the subclasses of the
10 // Instruction class. This is meant to be an easy way to get access to all
11 // instruction subclasses.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_IR_INSTRUCTIONS_H
16 #define LLVM_IR_INSTRUCTIONS_H
17 
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/ADT/iterator.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/InstrTypes.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/OperandTraits.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/Use.h"
37 #include "llvm/IR/User.h"
38 #include "llvm/IR/Value.h"
40 #include "llvm/Support/Casting.h"
42 #include <cassert>
43 #include <cstddef>
44 #include <cstdint>
45 #include <iterator>
46 
47 namespace llvm {
48 
49 class APInt;
50 class ConstantInt;
51 class DataLayout;
52 class LLVMContext;
53 
54 //===----------------------------------------------------------------------===//
55 // AllocaInst Class
56 //===----------------------------------------------------------------------===//
57 
58 /// an instruction to allocate memory on the stack
59 class AllocaInst : public UnaryInstruction {
60  Type *AllocatedType;
61 
62 protected:
63  // Note: Instruction needs to be a friend here to call cloneImpl.
64  friend class Instruction;
65 
66  AllocaInst *cloneImpl() const;
67 
68 public:
69  explicit AllocaInst(Type *Ty, unsigned AddrSpace,
70  Value *ArraySize = nullptr,
71  const Twine &Name = "",
72  Instruction *InsertBefore = nullptr);
73  AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
74  const Twine &Name, BasicBlock *InsertAtEnd);
75 
76  AllocaInst(Type *Ty, unsigned AddrSpace,
77  const Twine &Name, Instruction *InsertBefore = nullptr);
78  AllocaInst(Type *Ty, unsigned AddrSpace,
79  const Twine &Name, BasicBlock *InsertAtEnd);
80 
81  AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
82  const Twine &Name = "", Instruction *InsertBefore = nullptr);
83  AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
84  const Twine &Name, BasicBlock *InsertAtEnd);
85 
86  /// Return true if there is an allocation size parameter to the allocation
87  /// instruction that is not 1.
88  bool isArrayAllocation() const;
89 
90  /// Get the number of elements allocated. For a simple allocation of a single
91  /// element, this will return a constant 1 value.
92  const Value *getArraySize() const { return getOperand(0); }
93  Value *getArraySize() { return getOperand(0); }
94 
95  /// Overload to return most specific pointer type.
96  PointerType *getType() const {
97  return cast<PointerType>(Instruction::getType());
98  }
99 
100  /// Get allocation size in bits. Returns None if size can't be determined,
101  /// e.g. in case of a VLA.
103 
104  /// Return the type that is being allocated by the instruction.
105  Type *getAllocatedType() const { return AllocatedType; }
106  /// for use only in special circumstances that need to generically
107  /// transform a whole instruction (eg: IR linking and vectorization).
108  void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
109 
110  /// Return the alignment of the memory that is being allocated by the
111  /// instruction.
112  unsigned getAlignment() const {
113  return (1u << (getSubclassDataFromInstruction() & 31)) >> 1;
114  }
115  void setAlignment(unsigned Align);
116 
117  /// Return true if this alloca is in the entry block of the function and is a
118  /// constant size. If so, the code generator will fold it into the
119  /// prolog/epilog code, so it is basically free.
120  bool isStaticAlloca() const;
121 
122  /// Return true if this alloca is used as an inalloca argument to a call. Such
123  /// allocas are never considered static even if they are in the entry block.
124  bool isUsedWithInAlloca() const {
125  return getSubclassDataFromInstruction() & 32;
126  }
127 
128  /// Specify whether this alloca is used to represent the arguments to a call.
129  void setUsedWithInAlloca(bool V) {
130  setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
131  (V ? 32 : 0));
132  }
133 
134  /// Return true if this alloca is used as a swifterror argument to a call.
135  bool isSwiftError() const {
136  return getSubclassDataFromInstruction() & 64;
137  }
138 
139  /// Specify whether this alloca is used to represent a swifterror.
140  void setSwiftError(bool V) {
141  setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
142  (V ? 64 : 0));
143  }
144 
145  // Methods for support type inquiry through isa, cast, and dyn_cast:
146  static bool classof(const Instruction *I) {
147  return (I->getOpcode() == Instruction::Alloca);
148  }
149  static bool classof(const Value *V) {
150  return isa<Instruction>(V) && classof(cast<Instruction>(V));
151  }
152 
153 private:
154  // Shadow Instruction::setInstructionSubclassData with a private forwarding
155  // method so that subclasses cannot accidentally use it.
156  void setInstructionSubclassData(unsigned short D) {
158  }
159 };
160 
161 //===----------------------------------------------------------------------===//
162 // LoadInst Class
163 //===----------------------------------------------------------------------===//
164 
165 /// An instruction for reading from memory. This uses the SubclassData field in
166 /// Value to store whether or not the load is volatile.
167 class LoadInst : public UnaryInstruction {
168  void AssertOK();
169 
170 protected:
171  // Note: Instruction needs to be a friend here to call cloneImpl.
172  friend class Instruction;
173 
174  LoadInst *cloneImpl() const;
175 
176 public:
177  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
178  Instruction *InsertBefore = nullptr);
179  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
180  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
181  Instruction *InsertBefore = nullptr);
182  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
183  BasicBlock *InsertAtEnd);
184  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
185  unsigned Align, Instruction *InsertBefore = nullptr);
186  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187  unsigned Align, BasicBlock *InsertAtEnd);
188  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189  unsigned Align, AtomicOrdering Order,
191  Instruction *InsertBefore = nullptr);
192  LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
193  unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
194  BasicBlock *InsertAtEnd);
195 
196  // Deprecated [opaque pointer types]
197  explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
198  Instruction *InsertBefore = nullptr)
199  : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
200  InsertBefore) {}
201  LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
202  : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
203  InsertAtEnd) {}
204  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
205  Instruction *InsertBefore = nullptr)
206  : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
207  isVolatile, InsertBefore) {}
208  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
209  BasicBlock *InsertAtEnd)
210  : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
211  isVolatile, InsertAtEnd) {}
212  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
213  Instruction *InsertBefore = nullptr)
214  : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
215  isVolatile, Align, InsertBefore) {}
216  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
217  BasicBlock *InsertAtEnd)
218  : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
219  isVolatile, Align, InsertAtEnd) {}
220  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
222  Instruction *InsertBefore = nullptr)
223  : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
224  isVolatile, Align, Order, SSID, InsertBefore) {}
225  LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
226  AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
227  : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
228  isVolatile, Align, Order, SSID, InsertAtEnd) {}
229 
230  /// Return true if this is a load from a volatile memory location.
231  bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
232 
233  /// Specify whether this is a volatile load or not.
234  void setVolatile(bool V) {
235  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
236  (V ? 1 : 0));
237  }
238 
239  /// Return the alignment of the access that is being performed.
240  unsigned getAlignment() const {
241  return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
242  }
243 
244  void setAlignment(unsigned Align);
245 
246  /// Returns the ordering constraint of this load instruction.
248  return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
249  }
250 
251  /// Sets the ordering constraint of this load instruction. May not be Release
252  /// or AcquireRelease.
253  void setOrdering(AtomicOrdering Ordering) {
254  setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
255  ((unsigned)Ordering << 7));
256  }
257 
258  /// Returns the synchronization scope ID of this load instruction.
260  return SSID;
261  }
262 
263  /// Sets the synchronization scope ID of this load instruction.
265  this->SSID = SSID;
266  }
267 
268  /// Sets the ordering constraint and the synchronization scope ID of this load
269  /// instruction.
270  void setAtomic(AtomicOrdering Ordering,
272  setOrdering(Ordering);
273  setSyncScopeID(SSID);
274  }
275 
276  bool isSimple() const { return !isAtomic() && !isVolatile(); }
277 
278  bool isUnordered() const {
279  return (getOrdering() == AtomicOrdering::NotAtomic ||
280  getOrdering() == AtomicOrdering::Unordered) &&
281  !isVolatile();
282  }
283 
285  const Value *getPointerOperand() const { return getOperand(0); }
286  static unsigned getPointerOperandIndex() { return 0U; }
288 
289  /// Returns the address space of the pointer operand.
290  unsigned getPointerAddressSpace() const {
291  return getPointerOperandType()->getPointerAddressSpace();
292  }
293 
294  // Methods for support type inquiry through isa, cast, and dyn_cast:
295  static bool classof(const Instruction *I) {
296  return I->getOpcode() == Instruction::Load;
297  }
298  static bool classof(const Value *V) {
299  return isa<Instruction>(V) && classof(cast<Instruction>(V));
300  }
301 
302 private:
303  // Shadow Instruction::setInstructionSubclassData with a private forwarding
304  // method so that subclasses cannot accidentally use it.
305  void setInstructionSubclassData(unsigned short D) {
307  }
308 
309  /// The synchronization scope ID of this load instruction. Not quite enough
310  /// room in SubClassData for everything, so synchronization scope ID gets its
311  /// own field.
312  SyncScope::ID SSID;
313 };
314 
315 //===----------------------------------------------------------------------===//
316 // StoreInst Class
317 //===----------------------------------------------------------------------===//
318 
319 /// An instruction for storing to memory.
320 class StoreInst : public Instruction {
321  void AssertOK();
322 
323 protected:
324  // Note: Instruction needs to be a friend here to call cloneImpl.
325  friend class Instruction;
326 
327  StoreInst *cloneImpl() const;
328 
329 public:
330  StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
331  StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
332  StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
333  Instruction *InsertBefore = nullptr);
334  StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
335  StoreInst(Value *Val, Value *Ptr, bool isVolatile,
336  unsigned Align, Instruction *InsertBefore = nullptr);
337  StoreInst(Value *Val, Value *Ptr, bool isVolatile,
338  unsigned Align, BasicBlock *InsertAtEnd);
339  StoreInst(Value *Val, Value *Ptr, bool isVolatile,
340  unsigned Align, AtomicOrdering Order,
342  Instruction *InsertBefore = nullptr);
343  StoreInst(Value *Val, Value *Ptr, bool isVolatile,
344  unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
345  BasicBlock *InsertAtEnd);
346 
347  // allocate space for exactly two operands
348  void *operator new(size_t s) {
349  return User::operator new(s, 2);
350  }
351 
352  /// Return true if this is a store to a volatile memory location.
353  bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
354 
355  /// Specify whether this is a volatile store or not.
356  void setVolatile(bool V) {
357  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
358  (V ? 1 : 0));
359  }
360 
361  /// Transparently provide more efficient getOperand methods.
363 
364  /// Return the alignment of the access that is being performed
365  unsigned getAlignment() const {
366  return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
367  }
368 
369  void setAlignment(unsigned Align);
370 
371  /// Returns the ordering constraint of this store instruction.
373  return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
374  }
375 
376  /// Sets the ordering constraint of this store instruction. May not be
377  /// Acquire or AcquireRelease.
378  void setOrdering(AtomicOrdering Ordering) {
379  setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
380  ((unsigned)Ordering << 7));
381  }
382 
383  /// Returns the synchronization scope ID of this store instruction.
385  return SSID;
386  }
387 
388  /// Sets the synchronization scope ID of this store instruction.
390  this->SSID = SSID;
391  }
392 
393  /// Sets the ordering constraint and the synchronization scope ID of this
394  /// store instruction.
395  void setAtomic(AtomicOrdering Ordering,
397  setOrdering(Ordering);
398  setSyncScopeID(SSID);
399  }
400 
401  bool isSimple() const { return !isAtomic() && !isVolatile(); }
402 
403  bool isUnordered() const {
404  return (getOrdering() == AtomicOrdering::NotAtomic ||
405  getOrdering() == AtomicOrdering::Unordered) &&
406  !isVolatile();
407  }
408 
409  Value *getValueOperand() { return getOperand(0); }
410  const Value *getValueOperand() const { return getOperand(0); }
411 
413  const Value *getPointerOperand() const { return getOperand(1); }
414  static unsigned getPointerOperandIndex() { return 1U; }
416 
417  /// Returns the address space of the pointer operand.
418  unsigned getPointerAddressSpace() const {
419  return getPointerOperandType()->getPointerAddressSpace();
420  }
421 
422  // Methods for support type inquiry through isa, cast, and dyn_cast:
423  static bool classof(const Instruction *I) {
424  return I->getOpcode() == Instruction::Store;
425  }
426  static bool classof(const Value *V) {
427  return isa<Instruction>(V) && classof(cast<Instruction>(V));
428  }
429 
430 private:
431  // Shadow Instruction::setInstructionSubclassData with a private forwarding
432  // method so that subclasses cannot accidentally use it.
433  void setInstructionSubclassData(unsigned short D) {
435  }
436 
437  /// The synchronization scope ID of this store instruction. Not quite enough
438  /// room in SubClassData for everything, so synchronization scope ID gets its
439  /// own field.
440  SyncScope::ID SSID;
441 };
442 
443 template <>
444 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
445 };
446 
448 
449 //===----------------------------------------------------------------------===//
450 // FenceInst Class
451 //===----------------------------------------------------------------------===//
452 
453 /// An instruction for ordering other memory operations.
454 class FenceInst : public Instruction {
455  void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
456 
457 protected:
458  // Note: Instruction needs to be a friend here to call cloneImpl.
459  friend class Instruction;
460 
461  FenceInst *cloneImpl() const;
462 
463 public:
464  // Ordering may only be Acquire, Release, AcquireRelease, or
465  // SequentiallyConsistent.
468  Instruction *InsertBefore = nullptr);
470  BasicBlock *InsertAtEnd);
471 
472  // allocate space for exactly zero operands
473  void *operator new(size_t s) {
474  return User::operator new(s, 0);
475  }
476 
477  /// Returns the ordering constraint of this fence instruction.
480  }
481 
482  /// Sets the ordering constraint of this fence instruction. May only be
483  /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
484  void setOrdering(AtomicOrdering Ordering) {
485  setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
486  ((unsigned)Ordering << 1));
487  }
488 
489  /// Returns the synchronization scope ID of this fence instruction.
491  return SSID;
492  }
493 
494  /// Sets the synchronization scope ID of this fence instruction.
496  this->SSID = SSID;
497  }
498 
499  // Methods for support type inquiry through isa, cast, and dyn_cast:
500  static bool classof(const Instruction *I) {
501  return I->getOpcode() == Instruction::Fence;
502  }
503  static bool classof(const Value *V) {
504  return isa<Instruction>(V) && classof(cast<Instruction>(V));
505  }
506 
507 private:
508  // Shadow Instruction::setInstructionSubclassData with a private forwarding
509  // method so that subclasses cannot accidentally use it.
510  void setInstructionSubclassData(unsigned short D) {
512  }
513 
514  /// The synchronization scope ID of this fence instruction. Not quite enough
515  /// room in SubClassData for everything, so synchronization scope ID gets its
516  /// own field.
517  SyncScope::ID SSID;
518 };
519 
520 //===----------------------------------------------------------------------===//
521 // AtomicCmpXchgInst Class
522 //===----------------------------------------------------------------------===//
523 
524 /// an instruction that atomically checks whether a
525 /// specified value is in a memory location, and, if it is, stores a new value
526 /// there. Returns the value that was loaded.
527 ///
529  void Init(Value *Ptr, Value *Cmp, Value *NewVal,
530  AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
531  SyncScope::ID SSID);
532 
533 protected:
534  // Note: Instruction needs to be a friend here to call cloneImpl.
535  friend class Instruction;
536 
537  AtomicCmpXchgInst *cloneImpl() const;
538 
539 public:
540  AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
541  AtomicOrdering SuccessOrdering,
542  AtomicOrdering FailureOrdering,
543  SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
544  AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
545  AtomicOrdering SuccessOrdering,
546  AtomicOrdering FailureOrdering,
547  SyncScope::ID SSID, BasicBlock *InsertAtEnd);
548 
549  // allocate space for exactly three operands
550  void *operator new(size_t s) {
551  return User::operator new(s, 3);
552  }
553 
554  /// Return true if this is a cmpxchg from a volatile memory
555  /// location.
556  ///
557  bool isVolatile() const {
558  return getSubclassDataFromInstruction() & 1;
559  }
560 
561  /// Specify whether this is a volatile cmpxchg.
562  ///
563  void setVolatile(bool V) {
564  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
565  (unsigned)V);
566  }
567 
568  /// Return true if this cmpxchg may spuriously fail.
569  bool isWeak() const {
570  return getSubclassDataFromInstruction() & 0x100;
571  }
572 
573  void setWeak(bool IsWeak) {
574  setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
575  (IsWeak << 8));
576  }
577 
578  /// Transparently provide more efficient getOperand methods.
580 
581  /// Returns the success ordering constraint of this cmpxchg instruction.
583  return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
584  }
585 
586  /// Sets the success ordering constraint of this cmpxchg instruction.
588  assert(Ordering != AtomicOrdering::NotAtomic &&
589  "CmpXchg instructions can only be atomic.");
590  setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
591  ((unsigned)Ordering << 2));
592  }
593 
594  /// Returns the failure ordering constraint of this cmpxchg instruction.
596  return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
597  }
598 
599  /// Sets the failure ordering constraint of this cmpxchg instruction.
601  assert(Ordering != AtomicOrdering::NotAtomic &&
602  "CmpXchg instructions can only be atomic.");
603  setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
604  ((unsigned)Ordering << 5));
605  }
606 
607  /// Returns the synchronization scope ID of this cmpxchg instruction.
609  return SSID;
610  }
611 
612  /// Sets the synchronization scope ID of this cmpxchg instruction.
614  this->SSID = SSID;
615  }
616 
618  const Value *getPointerOperand() const { return getOperand(0); }
619  static unsigned getPointerOperandIndex() { return 0U; }
620 
622  const Value *getCompareOperand() const { return getOperand(1); }
623 
625  const Value *getNewValOperand() const { return getOperand(2); }
626 
627  /// Returns the address space of the pointer operand.
628  unsigned getPointerAddressSpace() const {
630  }
631 
632  /// Returns the strongest permitted ordering on failure, given the
633  /// desired ordering on success.
634  ///
635  /// If the comparison in a cmpxchg operation fails, there is no atomic store
636  /// so release semantics cannot be provided. So this function drops explicit
637  /// Release requests from the AtomicOrdering. A SequentiallyConsistent
638  /// operation would remain SequentiallyConsistent.
639  static AtomicOrdering
641  switch (SuccessOrdering) {
642  default:
643  llvm_unreachable("invalid cmpxchg success ordering");
652  }
653  }
654 
655  // Methods for support type inquiry through isa, cast, and dyn_cast:
656  static bool classof(const Instruction *I) {
657  return I->getOpcode() == Instruction::AtomicCmpXchg;
658  }
659  static bool classof(const Value *V) {
660  return isa<Instruction>(V) && classof(cast<Instruction>(V));
661  }
662 
663 private:
664  // Shadow Instruction::setInstructionSubclassData with a private forwarding
665  // method so that subclasses cannot accidentally use it.
666  void setInstructionSubclassData(unsigned short D) {
668  }
669 
670  /// The synchronization scope ID of this cmpxchg instruction. Not quite
671  /// enough room in SubClassData for everything, so synchronization scope ID
672  /// gets its own field.
673  SyncScope::ID SSID;
674 };
675 
676 template <>
678  public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
679 };
680 
682 
683 //===----------------------------------------------------------------------===//
684 // AtomicRMWInst Class
685 //===----------------------------------------------------------------------===//
686 
687 /// an instruction that atomically reads a memory location,
688 /// combines it with another value, and then stores the result back. Returns
689 /// the old value.
690 ///
691 class AtomicRMWInst : public Instruction {
692 protected:
693  // Note: Instruction needs to be a friend here to call cloneImpl.
694  friend class Instruction;
695 
696  AtomicRMWInst *cloneImpl() const;
697 
698 public:
699  /// This enumeration lists the possible modifications atomicrmw can make. In
700  /// the descriptions, 'p' is the pointer to the instruction's memory location,
701  /// 'old' is the initial value of *p, and 'v' is the other value passed to the
702  /// instruction. These instructions always return 'old'.
703  enum BinOp {
704  /// *p = v
706  /// *p = old + v
708  /// *p = old - v
710  /// *p = old & v
712  /// *p = ~(old & v)
714  /// *p = old | v
715  Or,
716  /// *p = old ^ v
718  /// *p = old >signed v ? old : v
720  /// *p = old <signed v ? old : v
722  /// *p = old >unsigned v ? old : v
724  /// *p = old <unsigned v ? old : v
726 
727  /// *p = old + v
729 
730  /// *p = old - v
732 
733  FIRST_BINOP = Xchg,
734  LAST_BINOP = FSub,
735  BAD_BINOP
736  };
737 
739  AtomicOrdering Ordering, SyncScope::ID SSID,
740  Instruction *InsertBefore = nullptr);
742  AtomicOrdering Ordering, SyncScope::ID SSID,
743  BasicBlock *InsertAtEnd);
744 
745  // allocate space for exactly two operands
746  void *operator new(size_t s) {
747  return User::operator new(s, 2);
748  }
749 
750  BinOp getOperation() const {
751  return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
752  }
753 
754  static StringRef getOperationName(BinOp Op);
755 
756  static bool isFPOperation(BinOp Op) {
757  switch (Op) {
758  case AtomicRMWInst::FAdd:
759  case AtomicRMWInst::FSub:
760  return true;
761  default:
762  return false;
763  }
764  }
765 
767  unsigned short SubclassData = getSubclassDataFromInstruction();
768  setInstructionSubclassData((SubclassData & 31) |
769  (Operation << 5));
770  }
771 
772  /// Return true if this is a RMW on a volatile memory location.
773  ///
774  bool isVolatile() const {
775  return getSubclassDataFromInstruction() & 1;
776  }
777 
778  /// Specify whether this is a volatile RMW or not.
779  ///
780  void setVolatile(bool V) {
781  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
782  (unsigned)V);
783  }
784 
785  /// Transparently provide more efficient getOperand methods.
787 
788  /// Returns the ordering constraint of this rmw instruction.
790  return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
791  }
792 
793  /// Sets the ordering constraint of this rmw instruction.
794  void setOrdering(AtomicOrdering Ordering) {
795  assert(Ordering != AtomicOrdering::NotAtomic &&
796  "atomicrmw instructions can only be atomic.");
797  setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
798  ((unsigned)Ordering << 2));
799  }
800 
801  /// Returns the synchronization scope ID of this rmw instruction.
803  return SSID;
804  }
805 
806  /// Sets the synchronization scope ID of this rmw instruction.
808  this->SSID = SSID;
809  }
810 
812  const Value *getPointerOperand() const { return getOperand(0); }
813  static unsigned getPointerOperandIndex() { return 0U; }
814 
815  Value *getValOperand() { return getOperand(1); }
816  const Value *getValOperand() const { return getOperand(1); }
817 
818  /// Returns the address space of the pointer operand.
819  unsigned getPointerAddressSpace() const {
821  }
822 
824  return isFPOperation(getOperation());
825  }
826 
827  // Methods for support type inquiry through isa, cast, and dyn_cast:
828  static bool classof(const Instruction *I) {
829  return I->getOpcode() == Instruction::AtomicRMW;
830  }
831  static bool classof(const Value *V) {
832  return isa<Instruction>(V) && classof(cast<Instruction>(V));
833  }
834 
835 private:
836  void Init(BinOp Operation, Value *Ptr, Value *Val,
837  AtomicOrdering Ordering, SyncScope::ID SSID);
838 
839  // Shadow Instruction::setInstructionSubclassData with a private forwarding
840  // method so that subclasses cannot accidentally use it.
841  void setInstructionSubclassData(unsigned short D) {
843  }
844 
845  /// The synchronization scope ID of this rmw instruction. Not quite enough
846  /// room in SubClassData for everything, so synchronization scope ID gets its
847  /// own field.
848  SyncScope::ID SSID;
849 };
850 
851 template <>
853  : public FixedNumOperandTraits<AtomicRMWInst,2> {
854 };
855 
857 
858 //===----------------------------------------------------------------------===//
859 // GetElementPtrInst Class
860 //===----------------------------------------------------------------------===//
861 
862 // checkGEPType - Simple wrapper function to give a better assertion failure
863 // message on bad indexes for a gep instruction.
864 //
866  assert(Ty && "Invalid GetElementPtrInst indices for type!");
867  return Ty;
868 }
869 
870 /// an instruction for type-safe pointer arithmetic to
871 /// access elements of arrays and structs
872 ///
874  Type *SourceElementType;
875  Type *ResultElementType;
876 
878 
879  /// Constructors - Create a getelementptr instruction with a base pointer an
880  /// list of indices. The first ctor can optionally insert before an existing
881  /// instruction, the second appends the new instruction to the specified
882  /// BasicBlock.
883  inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
884  ArrayRef<Value *> IdxList, unsigned Values,
885  const Twine &NameStr, Instruction *InsertBefore);
886  inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
887  ArrayRef<Value *> IdxList, unsigned Values,
888  const Twine &NameStr, BasicBlock *InsertAtEnd);
889 
890  void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
891 
892 protected:
893  // Note: Instruction needs to be a friend here to call cloneImpl.
894  friend class Instruction;
895 
896  GetElementPtrInst *cloneImpl() const;
897 
898 public:
899  static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
900  ArrayRef<Value *> IdxList,
901  const Twine &NameStr = "",
902  Instruction *InsertBefore = nullptr) {
903  unsigned Values = 1 + unsigned(IdxList.size());
904  if (!PointeeType)
905  PointeeType =
906  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
907  else
908  assert(
909  PointeeType ==
910  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
911  return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
912  NameStr, InsertBefore);
913  }
914 
915  static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
916  ArrayRef<Value *> IdxList,
917  const Twine &NameStr,
918  BasicBlock *InsertAtEnd) {
919  unsigned Values = 1 + unsigned(IdxList.size());
920  if (!PointeeType)
921  PointeeType =
922  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
923  else
924  assert(
925  PointeeType ==
926  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
927  return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
928  NameStr, InsertAtEnd);
929  }
930 
931  /// Create an "inbounds" getelementptr. See the documentation for the
932  /// "inbounds" flag in LangRef.html for details.
934  ArrayRef<Value *> IdxList,
935  const Twine &NameStr = "",
936  Instruction *InsertBefore = nullptr){
937  return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
938  }
939 
940  static GetElementPtrInst *
941  CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
942  const Twine &NameStr = "",
943  Instruction *InsertBefore = nullptr) {
945  Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
946  GEP->setIsInBounds(true);
947  return GEP;
948  }
949 
951  ArrayRef<Value *> IdxList,
952  const Twine &NameStr,
953  BasicBlock *InsertAtEnd) {
954  return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
955  }
956 
957  static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
958  ArrayRef<Value *> IdxList,
959  const Twine &NameStr,
960  BasicBlock *InsertAtEnd) {
962  Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
963  GEP->setIsInBounds(true);
964  return GEP;
965  }
966 
967  /// Transparently provide more efficient getOperand methods.
969 
970  Type *getSourceElementType() const { return SourceElementType; }
971 
972  void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
973  void setResultElementType(Type *Ty) { ResultElementType = Ty; }
974 
976  assert(ResultElementType ==
977  cast<PointerType>(getType()->getScalarType())->getElementType());
978  return ResultElementType;
979  }
980 
981  /// Returns the address space of this instruction's pointer type.
982  unsigned getAddressSpace() const {
983  // Note that this is always the same as the pointer operand's address space
984  // and that is cheaper to compute, so cheat here.
985  return getPointerAddressSpace();
986  }
987 
988  /// Returns the type of the element that would be loaded with
989  /// a load instruction with the specified parameters.
990  ///
991  /// Null is returned if the indices are invalid for the specified
992  /// pointer type.
993  ///
994  static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
995  static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
996  static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
997 
998  inline op_iterator idx_begin() { return op_begin()+1; }
999  inline const_op_iterator idx_begin() const { return op_begin()+1; }
1000  inline op_iterator idx_end() { return op_end(); }
1001  inline const_op_iterator idx_end() const { return op_end(); }
1002 
1004  return make_range(idx_begin(), idx_end());
1005  }
1006 
1008  return make_range(idx_begin(), idx_end());
1009  }
1010 
1012  return getOperand(0);
1013  }
1014  const Value *getPointerOperand() const {
1015  return getOperand(0);
1016  }
1017  static unsigned getPointerOperandIndex() {
1018  return 0U; // get index for modifying correct operand.
1019  }
1020 
1021  /// Method to return the pointer operand as a
1022  /// PointerType.
1024  return getPointerOperand()->getType();
1025  }
1026 
1027  /// Returns the address space of the pointer operand.
1028  unsigned getPointerAddressSpace() const {
1029  return getPointerOperandType()->getPointerAddressSpace();
1030  }
1031 
1032  /// Returns the pointer type returned by the GEP
1033  /// instruction, which may be a vector of pointers.
1035  return getGEPReturnType(
1036  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1037  Ptr, IdxList);
1038  }
1039  static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1040  ArrayRef<Value *> IdxList) {
1041  Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1042  Ptr->getType()->getPointerAddressSpace());
1043  // Vector GEP
1044  if (Ptr->getType()->isVectorTy()) {
1045  unsigned NumElem = Ptr->getType()->getVectorNumElements();
1046  return VectorType::get(PtrTy, NumElem);
1047  }
1048  for (Value *Index : IdxList)
1049  if (Index->getType()->isVectorTy()) {
1050  unsigned NumElem = Index->getType()->getVectorNumElements();
1051  return VectorType::get(PtrTy, NumElem);
1052  }
1053  // Scalar GEP
1054  return PtrTy;
1055  }
1056 
1057  unsigned getNumIndices() const { // Note: always non-negative
1058  return getNumOperands() - 1;
1059  }
1060 
1061  bool hasIndices() const {
1062  return getNumOperands() > 1;
1063  }
1064 
1065  /// Return true if all of the indices of this GEP are
1066  /// zeros. If so, the result pointer and the first operand have the same
1067  /// value, just potentially different types.
1068  bool hasAllZeroIndices() const;
1069 
1070  /// Return true if all of the indices of this GEP are
1071  /// constant integers. If so, the result pointer and the first operand have
1072  /// a constant offset between them.
1073  bool hasAllConstantIndices() const;
1074 
1075  /// Set or clear the inbounds flag on this GEP instruction.
1076  /// See LangRef.html for the meaning of inbounds on a getelementptr.
1077  void setIsInBounds(bool b = true);
1078 
1079  /// Determine whether the GEP has the inbounds flag.
1080  bool isInBounds() const;
1081 
1082  /// Accumulate the constant address offset of this GEP if possible.
1083  ///
1084  /// This routine accepts an APInt into which it will accumulate the constant
1085  /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1086  /// all-constant, it returns false and the value of the offset APInt is
1087  /// undefined (it is *not* preserved!). The APInt passed into this routine
1088  /// must be at least as wide as the IntPtr type for the address space of
1089  /// the base GEP pointer.
1090  bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1091 
1092  // Methods for support type inquiry through isa, cast, and dyn_cast:
1093  static bool classof(const Instruction *I) {
1094  return (I->getOpcode() == Instruction::GetElementPtr);
1095  }
1096  static bool classof(const Value *V) {
1097  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1098  }
1099 };
1100 
1101 template <>
1103  public VariadicOperandTraits<GetElementPtrInst, 1> {
1104 };
1105 
1106 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1107  ArrayRef<Value *> IdxList, unsigned Values,
1108  const Twine &NameStr,
1109  Instruction *InsertBefore)
1110  : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1112  Values, InsertBefore),
1113  SourceElementType(PointeeType),
1114  ResultElementType(getIndexedType(PointeeType, IdxList)) {
1115  assert(ResultElementType ==
1116  cast<PointerType>(getType()->getScalarType())->getElementType());
1117  init(Ptr, IdxList, NameStr);
1118 }
1119 
1120 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1121  ArrayRef<Value *> IdxList, unsigned Values,
1122  const Twine &NameStr,
1123  BasicBlock *InsertAtEnd)
1124  : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1126  Values, InsertAtEnd),
1127  SourceElementType(PointeeType),
1128  ResultElementType(getIndexedType(PointeeType, IdxList)) {
1129  assert(ResultElementType ==
1130  cast<PointerType>(getType()->getScalarType())->getElementType());
1131  init(Ptr, IdxList, NameStr);
1132 }
1133 
1134 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1135 
1136 //===----------------------------------------------------------------------===//
1137 // UnaryOperator Class
1138 //===----------------------------------------------------------------------===//
1139 
1140 /// a unary instruction
1142  void AssertOK();
1143 
1144 protected:
1145  UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
1146  const Twine &Name, Instruction *InsertBefore);
1147  UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
1148  const Twine &Name, BasicBlock *InsertAtEnd);
1149 
1150  // Note: Instruction needs to be a friend here to call cloneImpl.
1151  friend class Instruction;
1152 
1153  UnaryOperator *cloneImpl() const;
1154 
1155 public:
1156 
1157  /// Construct a unary instruction, given the opcode and an operand.
1158  /// Optionally (if InstBefore is specified) insert the instruction
1159  /// into a BasicBlock right before the specified instruction. The specified
1160  /// Instruction is allowed to be a dereferenced end iterator.
1161  ///
1162  static UnaryOperator *Create(UnaryOps Op, Value *S,
1163  const Twine &Name = Twine(),
1164  Instruction *InsertBefore = nullptr);
1165 
1166  /// Construct a unary instruction, given the opcode and an operand.
1167  /// Also automatically insert this instruction to the end of the
1168  /// BasicBlock specified.
1169  ///
1170  static UnaryOperator *Create(UnaryOps Op, Value *S,
1171  const Twine &Name,
1172  BasicBlock *InsertAtEnd);
1173 
1174  /// These methods just forward to Create, and are useful when you
1175  /// statically know what type of instruction you're going to create. These
1176  /// helpers just save some typing.
1177 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1178  static UnaryInstruction *Create##OPC(Value *V, \
1179  const Twine &Name = "") {\
1180  return Create(Instruction::OPC, V, Name);\
1181  }
1182 #include "llvm/IR/Instruction.def"
1183 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1184  static UnaryInstruction *Create##OPC(Value *V, \
1185  const Twine &Name, BasicBlock *BB) {\
1186  return Create(Instruction::OPC, V, Name, BB);\
1187  }
1188 #include "llvm/IR/Instruction.def"
1189 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1190  static UnaryInstruction *Create##OPC(Value *V, \
1191  const Twine &Name, Instruction *I) {\
1192  return Create(Instruction::OPC, V, Name, I);\
1193  }
1194 #include "llvm/IR/Instruction.def"
1195 
1197  return static_cast<UnaryOps>(Instruction::getOpcode());
1198  }
1199 };
1200 
1201 //===----------------------------------------------------------------------===//
1202 // ICmpInst Class
1203 //===----------------------------------------------------------------------===//
1204 
1205 /// This instruction compares its operands according to the predicate given
1206 /// to the constructor. It only operates on integers or pointers. The operands
1207 /// must be identical types.
1208 /// Represent an integer comparison operator.
1209 class ICmpInst: public CmpInst {
1210  void AssertOK() {
1211  assert(isIntPredicate() &&
1212  "Invalid ICmp predicate value");
1213  assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1214  "Both operands to ICmp instruction are not of the same type!");
1215  // Check that the operands are the right type
1216  assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1217  getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1218  "Invalid operand types for ICmp instruction");
1219  }
1220 
1221 protected:
1222  // Note: Instruction needs to be a friend here to call cloneImpl.
1223  friend class Instruction;
1224 
1225  /// Clone an identical ICmpInst
1226  ICmpInst *cloneImpl() const;
1227 
1228 public:
1229  /// Constructor with insert-before-instruction semantics.
1231  Instruction *InsertBefore, ///< Where to insert
1232  Predicate pred, ///< The predicate to use for the comparison
1233  Value *LHS, ///< The left-hand-side of the expression
1234  Value *RHS, ///< The right-hand-side of the expression
1235  const Twine &NameStr = "" ///< Name of the instruction
1236  ) : CmpInst(makeCmpResultType(LHS->getType()),
1237  Instruction::ICmp, pred, LHS, RHS, NameStr,
1238  InsertBefore) {
1239 #ifndef NDEBUG
1240  AssertOK();
1241 #endif
1242  }
1243 
1244  /// Constructor with insert-at-end semantics.
1246  BasicBlock &InsertAtEnd, ///< Block to insert into.
1247  Predicate pred, ///< The predicate to use for the comparison
1248  Value *LHS, ///< The left-hand-side of the expression
1249  Value *RHS, ///< The right-hand-side of the expression
1250  const Twine &NameStr = "" ///< Name of the instruction
1251  ) : CmpInst(makeCmpResultType(LHS->getType()),
1252  Instruction::ICmp, pred, LHS, RHS, NameStr,
1253  &InsertAtEnd) {
1254 #ifndef NDEBUG
1255  AssertOK();
1256 #endif
1257  }
1258 
1259  /// Constructor with no-insertion semantics
1261  Predicate pred, ///< The predicate to use for the comparison
1262  Value *LHS, ///< The left-hand-side of the expression
1263  Value *RHS, ///< The right-hand-side of the expression
1264  const Twine &NameStr = "" ///< Name of the instruction
1265  ) : CmpInst(makeCmpResultType(LHS->getType()),
1266  Instruction::ICmp, pred, LHS, RHS, NameStr) {
1267 #ifndef NDEBUG
1268  AssertOK();
1269 #endif
1270  }
1271 
1272  /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1273  /// @returns the predicate that would be the result if the operand were
1274  /// regarded as signed.
1275  /// Return the signed version of the predicate
1277  return getSignedPredicate(getPredicate());
1278  }
1279 
1280  /// This is a static version that you can use without an instruction.
1281  /// Return the signed version of the predicate.
1282  static Predicate getSignedPredicate(Predicate pred);
1283 
1284  /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1285  /// @returns the predicate that would be the result if the operand were
1286  /// regarded as unsigned.
1287  /// Return the unsigned version of the predicate
1289  return getUnsignedPredicate(getPredicate());
1290  }
1291 
1292  /// This is a static version that you can use without an instruction.
1293  /// Return the unsigned version of the predicate.
1294  static Predicate getUnsignedPredicate(Predicate pred);
1295 
1296  /// Return true if this predicate is either EQ or NE. This also
1297  /// tests for commutativity.
1298  static bool isEquality(Predicate P) {
1299  return P == ICMP_EQ || P == ICMP_NE;
1300  }
1301 
1302  /// Return true if this predicate is either EQ or NE. This also
1303  /// tests for commutativity.
1304  bool isEquality() const {
1305  return isEquality(getPredicate());
1306  }
1307 
1308  /// @returns true if the predicate of this ICmpInst is commutative
1309  /// Determine if this relation is commutative.
1310  bool isCommutative() const { return isEquality(); }
1311 
1312  /// Return true if the predicate is relational (not EQ or NE).
1313  ///
1314  bool isRelational() const {
1315  return !isEquality();
1316  }
1317 
1318  /// Return true if the predicate is relational (not EQ or NE).
1319  ///
1320  static bool isRelational(Predicate P) {
1321  return !isEquality(P);
1322  }
1323 
1324  /// Exchange the two operands to this instruction in such a way that it does
1325  /// not modify the semantics of the instruction. The predicate value may be
1326  /// changed to retain the same result if the predicate is order dependent
1327  /// (e.g. ult).
1328  /// Swap operands and adjust predicate.
1329  void swapOperands() {
1330  setPredicate(getSwappedPredicate());
1331  Op<0>().swap(Op<1>());
1332  }
1333 
1334  // Methods for support type inquiry through isa, cast, and dyn_cast:
1335  static bool classof(const Instruction *I) {
1336  return I->getOpcode() == Instruction::ICmp;
1337  }
1338  static bool classof(const Value *V) {
1339  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1340  }
1341 };
1342 
1343 //===----------------------------------------------------------------------===//
1344 // FCmpInst Class
1345 //===----------------------------------------------------------------------===//
1346 
1347 /// This instruction compares its operands according to the predicate given
1348 /// to the constructor. It only operates on floating point values or packed
1349 /// vectors of floating point values. The operands must be identical types.
1350 /// Represents a floating point comparison operator.
1351 class FCmpInst: public CmpInst {
1352  void AssertOK() {
1353  assert(isFPPredicate() && "Invalid FCmp predicate value");
1354  assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1355  "Both operands to FCmp instruction are not of the same type!");
1356  // Check that the operands are the right type
1357  assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1358  "Invalid operand types for FCmp instruction");
1359  }
1360 
1361 protected:
1362  // Note: Instruction needs to be a friend here to call cloneImpl.
1363  friend class Instruction;
1364 
1365  /// Clone an identical FCmpInst
1366  FCmpInst *cloneImpl() const;
1367 
1368 public:
1369  /// Constructor with insert-before-instruction semantics.
1371  Instruction *InsertBefore, ///< Where to insert
1372  Predicate pred, ///< The predicate to use for the comparison
1373  Value *LHS, ///< The left-hand-side of the expression
1374  Value *RHS, ///< The right-hand-side of the expression
1375  const Twine &NameStr = "" ///< Name of the instruction
1376  ) : CmpInst(makeCmpResultType(LHS->getType()),
1377  Instruction::FCmp, pred, LHS, RHS, NameStr,
1378  InsertBefore) {
1379  AssertOK();
1380  }
1381 
1382  /// Constructor with insert-at-end semantics.
1384  BasicBlock &InsertAtEnd, ///< Block to insert into.
1385  Predicate pred, ///< The predicate to use for the comparison
1386  Value *LHS, ///< The left-hand-side of the expression
1387  Value *RHS, ///< The right-hand-side of the expression
1388  const Twine &NameStr = "" ///< Name of the instruction
1389  ) : CmpInst(makeCmpResultType(LHS->getType()),
1390  Instruction::FCmp, pred, LHS, RHS, NameStr,
1391  &InsertAtEnd) {
1392  AssertOK();
1393  }
1394 
1395  /// Constructor with no-insertion semantics
1397  Predicate Pred, ///< The predicate to use for the comparison
1398  Value *LHS, ///< The left-hand-side of the expression
1399  Value *RHS, ///< The right-hand-side of the expression
1400  const Twine &NameStr = "", ///< Name of the instruction
1401  Instruction *FlagsSource = nullptr
1402  ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1403  RHS, NameStr, nullptr, FlagsSource) {
1404  AssertOK();
1405  }
1406 
1407  /// @returns true if the predicate of this instruction is EQ or NE.
1408  /// Determine if this is an equality predicate.
1409  static bool isEquality(Predicate Pred) {
1410  return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1411  Pred == FCMP_UNE;
1412  }
1413 
1414  /// @returns true if the predicate of this instruction is EQ or NE.
1415  /// Determine if this is an equality predicate.
1416  bool isEquality() const { return isEquality(getPredicate()); }
1417 
1418  /// @returns true if the predicate of this instruction is commutative.
1419  /// Determine if this is a commutative predicate.
1420  bool isCommutative() const {
1421  return isEquality() ||
1422  getPredicate() == FCMP_FALSE ||
1423  getPredicate() == FCMP_TRUE ||
1424  getPredicate() == FCMP_ORD ||
1425  getPredicate() == FCMP_UNO;
1426  }
1427 
1428  /// @returns true if the predicate is relational (not EQ or NE).
1429  /// Determine if this a relational predicate.
1430  bool isRelational() const { return !isEquality(); }
1431 
1432  /// Exchange the two operands to this instruction in such a way that it does
1433  /// not modify the semantics of the instruction. The predicate value may be
1434  /// changed to retain the same result if the predicate is order dependent
1435  /// (e.g. ult).
1436  /// Swap operands and adjust predicate.
1437  void swapOperands() {
1438  setPredicate(getSwappedPredicate());
1439  Op<0>().swap(Op<1>());
1440  }
1441 
1442  /// Methods for support type inquiry through isa, cast, and dyn_cast:
1443  static bool classof(const Instruction *I) {
1444  return I->getOpcode() == Instruction::FCmp;
1445  }
1446  static bool classof(const Value *V) {
1447  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1448  }
1449 };
1450 
1451 //===----------------------------------------------------------------------===//
1452 /// This class represents a function call, abstracting a target
1453 /// machine's calling convention. This class uses low bit of the SubClassData
1454 /// field to indicate whether or not this is a tail call. The rest of the bits
1455 /// hold the calling convention of the call.
1456 ///
1457 class CallInst : public CallBase {
1458  CallInst(const CallInst &CI);
1459 
1460  /// Construct a CallInst given a range of arguments.
1461  /// Construct a CallInst from a range of arguments
1462  inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1463  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1464  Instruction *InsertBefore);
1465 
1466  inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1467  const Twine &NameStr, Instruction *InsertBefore)
1468  : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1469 
1470  /// Construct a CallInst given a range of arguments.
1471  /// Construct a CallInst from a range of arguments
1472  inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1473  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1474  BasicBlock *InsertAtEnd);
1475 
1476  explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1477  Instruction *InsertBefore);
1478 
1479  CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1480  BasicBlock *InsertAtEnd);
1481 
1482  void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1483  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1484  void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1485 
1486  /// Compute the number of operands to allocate.
1487  static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1488  // We need one operand for the called function, plus the input operand
1489  // counts provided.
1490  return 1 + NumArgs + NumBundleInputs;
1491  }
1492 
1493 protected:
1494  // Note: Instruction needs to be a friend here to call cloneImpl.
1495  friend class Instruction;
1496 
1497  CallInst *cloneImpl() const;
1498 
1499 public:
1500  static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1501  Instruction *InsertBefore = nullptr) {
1502  return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1503  }
1504 
1506  const Twine &NameStr,
1507  Instruction *InsertBefore = nullptr) {
1508  return new (ComputeNumOperands(Args.size()))
1509  CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1510  }
1511 
1513  ArrayRef<OperandBundleDef> Bundles = None,
1514  const Twine &NameStr = "",
1515  Instruction *InsertBefore = nullptr) {
1516  const int NumOperands =
1517  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1518  const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1519 
1520  return new (NumOperands, DescriptorBytes)
1521  CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1522  }
1523 
1524  static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1525  BasicBlock *InsertAtEnd) {
1526  return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1527  }
1528 
1530  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1531  return new (ComputeNumOperands(Args.size()))
1532  CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1533  }
1534 
1537  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1538  const int NumOperands =
1539  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1540  const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1541 
1542  return new (NumOperands, DescriptorBytes)
1543  CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1544  }
1545 
1546  static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1547  Instruction *InsertBefore = nullptr) {
1548  return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1549  InsertBefore);
1550  }
1551 
1553  ArrayRef<OperandBundleDef> Bundles = None,
1554  const Twine &NameStr = "",
1555  Instruction *InsertBefore = nullptr) {
1556  return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1557  NameStr, InsertBefore);
1558  }
1559 
1561  const Twine &NameStr,
1562  Instruction *InsertBefore = nullptr) {
1563  return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1564  InsertBefore);
1565  }
1566 
1567  static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1568  BasicBlock *InsertAtEnd) {
1569  return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1570  InsertAtEnd);
1571  }
1572 
1574  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1575  return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1576  InsertAtEnd);
1577  }
1578 
1581  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1582  return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1583  NameStr, InsertAtEnd);
1584  }
1585 
1586  // Deprecated [opaque pointer types]
1587  static CallInst *Create(Value *Func, const Twine &NameStr = "",
1588  Instruction *InsertBefore = nullptr) {
1589  return Create(cast<FunctionType>(
1590  cast<PointerType>(Func->getType())->getElementType()),
1591  Func, NameStr, InsertBefore);
1592  }
1593 
1594  // Deprecated [opaque pointer types]
1596  const Twine &NameStr,
1597  Instruction *InsertBefore = nullptr) {
1598  return Create(cast<FunctionType>(
1599  cast<PointerType>(Func->getType())->getElementType()),
1600  Func, Args, NameStr, InsertBefore);
1601  }
1602 
1603  // Deprecated [opaque pointer types]
1605  ArrayRef<OperandBundleDef> Bundles = None,
1606  const Twine &NameStr = "",
1607  Instruction *InsertBefore = nullptr) {
1608  return Create(cast<FunctionType>(
1609  cast<PointerType>(Func->getType())->getElementType()),
1610  Func, Args, Bundles, NameStr, InsertBefore);
1611  }
1612 
1613  // Deprecated [opaque pointer types]
1614  static CallInst *Create(Value *Func, const Twine &NameStr,
1615  BasicBlock *InsertAtEnd) {
1616  return Create(cast<FunctionType>(
1617  cast<PointerType>(Func->getType())->getElementType()),
1618  Func, NameStr, InsertAtEnd);
1619  }
1620 
1621  // Deprecated [opaque pointer types]
1623  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1624  return Create(cast<FunctionType>(
1625  cast<PointerType>(Func->getType())->getElementType()),
1626  Func, Args, NameStr, InsertAtEnd);
1627  }
1628 
1629  // Deprecated [opaque pointer types]
1632  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1633  return Create(cast<FunctionType>(
1634  cast<PointerType>(Func->getType())->getElementType()),
1635  Func, Args, Bundles, NameStr, InsertAtEnd);
1636  }
1637 
1638  /// Create a clone of \p CI with a different set of operand bundles and
1639  /// insert it before \p InsertPt.
1640  ///
1641  /// The returned call instruction is identical \p CI in every way except that
1642  /// the operand bundles for the new instruction are set to the operand bundles
1643  /// in \p Bundles.
1644  static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1645  Instruction *InsertPt = nullptr);
1646 
1647  /// Generate the IR for a call to malloc:
1648  /// 1. Compute the malloc call's argument as the specified type's size,
1649  /// possibly multiplied by the array size if the array size is not
1650  /// constant 1.
1651  /// 2. Call malloc with that argument.
1652  /// 3. Bitcast the result of the malloc call to the specified type.
1653  static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1654  Type *AllocTy, Value *AllocSize,
1655  Value *ArraySize = nullptr,
1656  Function *MallocF = nullptr,
1657  const Twine &Name = "");
1658  static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1659  Type *AllocTy, Value *AllocSize,
1660  Value *ArraySize = nullptr,
1661  Function *MallocF = nullptr,
1662  const Twine &Name = "");
1663  static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1664  Type *AllocTy, Value *AllocSize,
1665  Value *ArraySize = nullptr,
1666  ArrayRef<OperandBundleDef> Bundles = None,
1667  Function *MallocF = nullptr,
1668  const Twine &Name = "");
1669  static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1670  Type *AllocTy, Value *AllocSize,
1671  Value *ArraySize = nullptr,
1672  ArrayRef<OperandBundleDef> Bundles = None,
1673  Function *MallocF = nullptr,
1674  const Twine &Name = "");
1675  /// Generate the IR for a call to the builtin free function.
1676  static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1677  static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1678  static Instruction *CreateFree(Value *Source,
1680  Instruction *InsertBefore);
1681  static Instruction *CreateFree(Value *Source,
1683  BasicBlock *InsertAtEnd);
1684 
1685  // Note that 'musttail' implies 'tail'.
1687  TCK_None = 0,
1688  TCK_Tail = 1,
1689  TCK_MustTail = 2,
1690  TCK_NoTail = 3
1691  };
1694  }
1695 
1696  bool isTailCall() const {
1697  unsigned Kind = getSubclassDataFromInstruction() & 3;
1698  return Kind == TCK_Tail || Kind == TCK_MustTail;
1699  }
1700 
1701  bool isMustTailCall() const {
1702  return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1703  }
1704 
1705  bool isNoTailCall() const {
1706  return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1707  }
1708 
1709  void setTailCall(bool isTC = true) {
1710  setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1711  unsigned(isTC ? TCK_Tail : TCK_None));
1712  }
1713 
1715  setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1716  unsigned(TCK));
1717  }
1718 
1719  /// Return true if the call can return twice
1720  bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1722  addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1723  }
1724 
1725  // Methods for support type inquiry through isa, cast, and dyn_cast:
1726  static bool classof(const Instruction *I) {
1727  return I->getOpcode() == Instruction::Call;
1728  }
1729  static bool classof(const Value *V) {
1730  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1731  }
1732 
1733 private:
1734  // Shadow Instruction::setInstructionSubclassData with a private forwarding
1735  // method so that subclasses cannot accidentally use it.
1736  void setInstructionSubclassData(unsigned short D) {
1738  }
1739 };
1740 
1741 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1742  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1743  BasicBlock *InsertAtEnd)
1746  (Args.size() + CountBundleInputs(Bundles) + 1),
1747  unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1748  InsertAtEnd) {
1749  init(Ty, Func, Args, Bundles, NameStr);
1750 }
1751 
1752 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1753  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1754  Instruction *InsertBefore)
1757  (Args.size() + CountBundleInputs(Bundles) + 1),
1758  unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1759  InsertBefore) {
1760  init(Ty, Func, Args, Bundles, NameStr);
1761 }
1762 
1763 //===----------------------------------------------------------------------===//
1764 // SelectInst Class
1765 //===----------------------------------------------------------------------===//
1766 
1767 /// This class represents the LLVM 'select' instruction.
1768 ///
1769 class SelectInst : public Instruction {
1770  SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1771  Instruction *InsertBefore)
1773  &Op<0>(), 3, InsertBefore) {
1774  init(C, S1, S2);
1775  setName(NameStr);
1776  }
1777 
1778  SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1779  BasicBlock *InsertAtEnd)
1781  &Op<0>(), 3, InsertAtEnd) {
1782  init(C, S1, S2);
1783  setName(NameStr);
1784  }
1785 
1786  void init(Value *C, Value *S1, Value *S2) {
1787  assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1788  Op<0>() = C;
1789  Op<1>() = S1;
1790  Op<2>() = S2;
1791  }
1792 
1793 protected:
1794  // Note: Instruction needs to be a friend here to call cloneImpl.
1795  friend class Instruction;
1796 
1797  SelectInst *cloneImpl() const;
1798 
1799 public:
1800  static SelectInst *Create(Value *C, Value *S1, Value *S2,
1801  const Twine &NameStr = "",
1802  Instruction *InsertBefore = nullptr,
1803  Instruction *MDFrom = nullptr) {
1804  SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1805  if (MDFrom)
1806  Sel->copyMetadata(*MDFrom);
1807  return Sel;
1808  }
1809 
1810  static SelectInst *Create(Value *C, Value *S1, Value *S2,
1811  const Twine &NameStr,
1812  BasicBlock *InsertAtEnd) {
1813  return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1814  }
1815 
1816  const Value *getCondition() const { return Op<0>(); }
1817  const Value *getTrueValue() const { return Op<1>(); }
1818  const Value *getFalseValue() const { return Op<2>(); }
1819  Value *getCondition() { return Op<0>(); }
1820  Value *getTrueValue() { return Op<1>(); }
1821  Value *getFalseValue() { return Op<2>(); }
1822 
1823  void setCondition(Value *V) { Op<0>() = V; }
1824  void setTrueValue(Value *V) { Op<1>() = V; }
1825  void setFalseValue(Value *V) { Op<2>() = V; }
1826 
1827  /// Return a string if the specified operands are invalid
1828  /// for a select operation, otherwise return null.
1829  static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1830 
1831  /// Transparently provide more efficient getOperand methods.
1833 
1835  return static_cast<OtherOps>(Instruction::getOpcode());
1836  }
1837 
1838  // Methods for support type inquiry through isa, cast, and dyn_cast:
1839  static bool classof(const Instruction *I) {
1840  return I->getOpcode() == Instruction::Select;
1841  }
1842  static bool classof(const Value *V) {
1843  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1844  }
1845 };
1846 
1847 template <>
1848 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1849 };
1850 
1852 
1853 //===----------------------------------------------------------------------===//
1854 // VAArgInst Class
1855 //===----------------------------------------------------------------------===//
1856 
1857 /// This class represents the va_arg llvm instruction, which returns
1858 /// an argument of the specified type given a va_list and increments that list
1859 ///
1860 class VAArgInst : public UnaryInstruction {
1861 protected:
1862  // Note: Instruction needs to be a friend here to call cloneImpl.
1863  friend class Instruction;
1864 
1865  VAArgInst *cloneImpl() const;
1866 
1867 public:
1868  VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1869  Instruction *InsertBefore = nullptr)
1870  : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1871  setName(NameStr);
1872  }
1873 
1874  VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1875  BasicBlock *InsertAtEnd)
1876  : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1877  setName(NameStr);
1878  }
1879 
1881  const Value *getPointerOperand() const { return getOperand(0); }
1882  static unsigned getPointerOperandIndex() { return 0U; }
1883 
1884  // Methods for support type inquiry through isa, cast, and dyn_cast:
1885  static bool classof(const Instruction *I) {
1886  return I->getOpcode() == VAArg;
1887  }
1888  static bool classof(const Value *V) {
1889  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1890  }
1891 };
1892 
1893 //===----------------------------------------------------------------------===//
1894 // ExtractElementInst Class
1895 //===----------------------------------------------------------------------===//
1896 
1897 /// This instruction extracts a single (scalar)
1898 /// element from a VectorType value
1899 ///
1901  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1902  Instruction *InsertBefore = nullptr);
1903  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1904  BasicBlock *InsertAtEnd);
1905 
1906 protected:
1907  // Note: Instruction needs to be a friend here to call cloneImpl.
1908  friend class Instruction;
1909 
1910  ExtractElementInst *cloneImpl() const;
1911 
1912 public:
1913  static ExtractElementInst *Create(Value *Vec, Value *Idx,
1914  const Twine &NameStr = "",
1915  Instruction *InsertBefore = nullptr) {
1916  return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1917  }
1918 
1919  static ExtractElementInst *Create(Value *Vec, Value *Idx,
1920  const Twine &NameStr,
1921  BasicBlock *InsertAtEnd) {
1922  return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1923  }
1924 
1925  /// Return true if an extractelement instruction can be
1926  /// formed with the specified operands.
1927  static bool isValidOperands(const Value *Vec, const Value *Idx);
1928 
1929  Value *getVectorOperand() { return Op<0>(); }
1930  Value *getIndexOperand() { return Op<1>(); }
1931  const Value *getVectorOperand() const { return Op<0>(); }
1932  const Value *getIndexOperand() const { return Op<1>(); }
1933 
1935  return cast<VectorType>(getVectorOperand()->getType());
1936  }
1937 
1938  /// Transparently provide more efficient getOperand methods.
1940 
1941  // Methods for support type inquiry through isa, cast, and dyn_cast:
1942  static bool classof(const Instruction *I) {
1943  return I->getOpcode() == Instruction::ExtractElement;
1944  }
1945  static bool classof(const Value *V) {
1946  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1947  }
1948 };
1949 
1950 template <>
1952  public FixedNumOperandTraits<ExtractElementInst, 2> {
1953 };
1954 
1955 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1956 
1957 //===----------------------------------------------------------------------===//
1958 // InsertElementInst Class
1959 //===----------------------------------------------------------------------===//
1960 
1961 /// This instruction inserts a single (scalar)
1962 /// element into a VectorType value
1963 ///
1965  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1966  const Twine &NameStr = "",
1967  Instruction *InsertBefore = nullptr);
1968  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1969  BasicBlock *InsertAtEnd);
1970 
1971 protected:
1972  // Note: Instruction needs to be a friend here to call cloneImpl.
1973  friend class Instruction;
1974 
1975  InsertElementInst *cloneImpl() const;
1976 
1977 public:
1978  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1979  const Twine &NameStr = "",
1980  Instruction *InsertBefore = nullptr) {
1981  return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1982  }
1983 
1984  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1985  const Twine &NameStr,
1986  BasicBlock *InsertAtEnd) {
1987  return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1988  }
1989 
1990  /// Return true if an insertelement instruction can be
1991  /// formed with the specified operands.
1992  static bool isValidOperands(const Value *Vec, const Value *NewElt,
1993  const Value *Idx);
1994 
1995  /// Overload to return most specific vector type.
1996  ///
1997  VectorType *getType() const {
1998  return cast<VectorType>(Instruction::getType());
1999  }
2000 
2001  /// Transparently provide more efficient getOperand methods.
2003 
2004  // Methods for support type inquiry through isa, cast, and dyn_cast:
2005  static bool classof(const Instruction *I) {
2006  return I->getOpcode() == Instruction::InsertElement;
2007  }
2008  static bool classof(const Value *V) {
2009  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2010  }
2011 };
2012 
2013 template <>
2015  public FixedNumOperandTraits<InsertElementInst, 3> {
2016 };
2017 
2018 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2019 
2020 //===----------------------------------------------------------------------===//
2021 // ShuffleVectorInst Class
2022 //===----------------------------------------------------------------------===//
2023 
2024 /// This instruction constructs a fixed permutation of two
2025 /// input vectors.
2026 ///
2028 protected:
2029  // Note: Instruction needs to be a friend here to call cloneImpl.
2030  friend class Instruction;
2031 
2032  ShuffleVectorInst *cloneImpl() const;
2033 
2034 public:
2036  const Twine &NameStr = "",
2037  Instruction *InsertBefor = nullptr);
2039  const Twine &NameStr, BasicBlock *InsertAtEnd);
2040 
2041  // allocate space for exactly three operands
2042  void *operator new(size_t s) {
2043  return User::operator new(s, 3);
2044  }
2045 
2046  /// Return true if a shufflevector instruction can be
2047  /// formed with the specified operands.
2048  static bool isValidOperands(const Value *V1, const Value *V2,
2049  const Value *Mask);
2050 
2051  /// Overload to return most specific vector type.
2052  ///
2053  VectorType *getType() const {
2054  return cast<VectorType>(Instruction::getType());
2055  }
2056 
2057  /// Transparently provide more efficient getOperand methods.
2059 
2060  Constant *getMask() const {
2061  return cast<Constant>(getOperand(2));
2062  }
2063 
2064  /// Return the shuffle mask value for the specified element of the mask.
2065  /// Return -1 if the element is undef.
2066  static int getMaskValue(const Constant *Mask, unsigned Elt);
2067 
2068  /// Return the shuffle mask value of this instruction for the given element
2069  /// index. Return -1 if the element is undef.
2070  int getMaskValue(unsigned Elt) const {
2071  return getMaskValue(getMask(), Elt);
2072  }
2073 
2074  /// Convert the input shuffle mask operand to a vector of integers. Undefined
2075  /// elements of the mask are returned as -1.
2076  static void getShuffleMask(const Constant *Mask,
2077  SmallVectorImpl<int> &Result);
2078 
2079  /// Return the mask for this instruction as a vector of integers. Undefined
2080  /// elements of the mask are returned as -1.
2081  void getShuffleMask(SmallVectorImpl<int> &Result) const {
2082  return getShuffleMask(getMask(), Result);
2083  }
2084 
2087  getShuffleMask(Mask);
2088  return Mask;
2089  }
2090 
2091  /// Return true if this shuffle returns a vector with a different number of
2092  /// elements than its source vectors.
2093  /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2094  /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2095  bool changesLength() const {
2096  unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2097  unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2098  return NumSourceElts != NumMaskElts;
2099  }
2100 
2101  /// Return true if this shuffle returns a vector with a greater number of
2102  /// elements than its source vectors.
2103  /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2104  bool increasesLength() const {
2105  unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2106  unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2107  return NumSourceElts < NumMaskElts;
2108  }
2109 
2110  /// Return true if this shuffle mask chooses elements from exactly one source
2111  /// vector.
2112  /// Example: <7,5,undef,7>
2113  /// This assumes that vector operands are the same length as the mask.
2114  static bool isSingleSourceMask(ArrayRef<int> Mask);
2115  static bool isSingleSourceMask(const Constant *Mask) {
2116  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2117  SmallVector<int, 16> MaskAsInts;
2118  getShuffleMask(Mask, MaskAsInts);
2119  return isSingleSourceMask(MaskAsInts);
2120  }
2121 
2122  /// Return true if this shuffle chooses elements from exactly one source
2123  /// vector without changing the length of that vector.
2124  /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2125  /// TODO: Optionally allow length-changing shuffles.
2126  bool isSingleSource() const {
2127  return !changesLength() && isSingleSourceMask(getMask());
2128  }
2129 
2130  /// Return true if this shuffle mask chooses elements from exactly one source
2131  /// vector without lane crossings. A shuffle using this mask is not
2132  /// necessarily a no-op because it may change the number of elements from its
2133  /// input vectors or it may provide demanded bits knowledge via undef lanes.
2134  /// Example: <undef,undef,2,3>
2135  static bool isIdentityMask(ArrayRef<int> Mask);
2136  static bool isIdentityMask(const Constant *Mask) {
2137  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2138  SmallVector<int, 16> MaskAsInts;
2139  getShuffleMask(Mask, MaskAsInts);
2140  return isIdentityMask(MaskAsInts);
2141  }
2142 
2143  /// Return true if this shuffle chooses elements from exactly one source
2144  /// vector without lane crossings and does not change the number of elements
2145  /// from its input vectors.
2146  /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2147  bool isIdentity() const {
2148  return !changesLength() && isIdentityMask(getShuffleMask());
2149  }
2150 
2151  /// Return true if this shuffle lengthens exactly one source vector with
2152  /// undefs in the high elements.
2153  bool isIdentityWithPadding() const;
2154 
2155  /// Return true if this shuffle extracts the first N elements of exactly one
2156  /// source vector.
2157  bool isIdentityWithExtract() const;
2158 
2159  /// Return true if this shuffle concatenates its 2 source vectors. This
2160  /// returns false if either input is undefined. In that case, the shuffle is
2161  /// is better classified as an identity with padding operation.
2162  bool isConcat() const;
2163 
2164  /// Return true if this shuffle mask chooses elements from its source vectors
2165  /// without lane crossings. A shuffle using this mask would be
2166  /// equivalent to a vector select with a constant condition operand.
2167  /// Example: <4,1,6,undef>
2168  /// This returns false if the mask does not choose from both input vectors.
2169  /// In that case, the shuffle is better classified as an identity shuffle.
2170  /// This assumes that vector operands are the same length as the mask
2171  /// (a length-changing shuffle can never be equivalent to a vector select).
2172  static bool isSelectMask(ArrayRef<int> Mask);
2173  static bool isSelectMask(const Constant *Mask) {
2174  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2175  SmallVector<int, 16> MaskAsInts;
2176  getShuffleMask(Mask, MaskAsInts);
2177  return isSelectMask(MaskAsInts);
2178  }
2179 
2180  /// Return true if this shuffle chooses elements from its source vectors
2181  /// without lane crossings and all operands have the same number of elements.
2182  /// In other words, this shuffle is equivalent to a vector select with a
2183  /// constant condition operand.
2184  /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2185  /// This returns false if the mask does not choose from both input vectors.
2186  /// In that case, the shuffle is better classified as an identity shuffle.
2187  /// TODO: Optionally allow length-changing shuffles.
2188  bool isSelect() const {
2189  return !changesLength() && isSelectMask(getMask());
2190  }
2191 
2192  /// Return true if this shuffle mask swaps the order of elements from exactly
2193  /// one source vector.
2194  /// Example: <7,6,undef,4>
2195  /// This assumes that vector operands are the same length as the mask.
2196  static bool isReverseMask(ArrayRef<int> Mask);
2197  static bool isReverseMask(const Constant *Mask) {
2198  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2199  SmallVector<int, 16> MaskAsInts;
2200  getShuffleMask(Mask, MaskAsInts);
2201  return isReverseMask(MaskAsInts);
2202  }
2203 
2204  /// Return true if this shuffle swaps the order of elements from exactly
2205  /// one source vector.
2206  /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2207  /// TODO: Optionally allow length-changing shuffles.
2208  bool isReverse() const {
2209  return !changesLength() && isReverseMask(getMask());
2210  }
2211 
2212  /// Return true if this shuffle mask chooses all elements with the same value
2213  /// as the first element of exactly one source vector.
2214  /// Example: <4,undef,undef,4>
2215  /// This assumes that vector operands are the same length as the mask.
2216  static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2217  static bool isZeroEltSplatMask(const Constant *Mask) {
2218  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2219  SmallVector<int, 16> MaskAsInts;
2220  getShuffleMask(Mask, MaskAsInts);
2221  return isZeroEltSplatMask(MaskAsInts);
2222  }
2223 
2224  /// Return true if all elements of this shuffle are the same value as the
2225  /// first element of exactly one source vector without changing the length
2226  /// of that vector.
2227  /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2228  /// TODO: Optionally allow length-changing shuffles.
2229  /// TODO: Optionally allow splats from other elements.
2230  bool isZeroEltSplat() const {
2231  return !changesLength() && isZeroEltSplatMask(getMask());
2232  }
2233 
2234  /// Return true if this shuffle mask is a transpose mask.
2235  /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2236  /// even- or odd-numbered vector elements from two n-dimensional source
2237  /// vectors and write each result into consecutive elements of an
2238  /// n-dimensional destination vector. Two shuffles are necessary to complete
2239  /// the transpose, one for the even elements and another for the odd elements.
2240  /// This description closely follows how the TRN1 and TRN2 AArch64
2241  /// instructions operate.
2242  ///
2243  /// For example, a simple 2x2 matrix can be transposed with:
2244  ///
2245  /// ; Original matrix
2246  /// m0 = < a, b >
2247  /// m1 = < c, d >
2248  ///
2249  /// ; Transposed matrix
2250  /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2251  /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2252  ///
2253  /// For matrices having greater than n columns, the resulting nx2 transposed
2254  /// matrix is stored in two result vectors such that one vector contains
2255  /// interleaved elements from all the even-numbered rows and the other vector
2256  /// contains interleaved elements from all the odd-numbered rows. For example,
2257  /// a 2x4 matrix can be transposed with:
2258  ///
2259  /// ; Original matrix
2260  /// m0 = < a, b, c, d >
2261  /// m1 = < e, f, g, h >
2262  ///
2263  /// ; Transposed matrix
2264  /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2265  /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2266  static bool isTransposeMask(ArrayRef<int> Mask);
2267  static bool isTransposeMask(const Constant *Mask) {
2268  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2269  SmallVector<int, 16> MaskAsInts;
2270  getShuffleMask(Mask, MaskAsInts);
2271  return isTransposeMask(MaskAsInts);
2272  }
2273 
2274  /// Return true if this shuffle transposes the elements of its inputs without
2275  /// changing the length of the vectors. This operation may also be known as a
2276  /// merge or interleave. See the description for isTransposeMask() for the
2277  /// exact specification.
2278  /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2279  bool isTranspose() const {
2280  return !changesLength() && isTransposeMask(getMask());
2281  }
2282 
2283  /// Return true if this shuffle mask is an extract subvector mask.
2284  /// A valid extract subvector mask returns a smaller vector from a single
2285  /// source operand. The base extraction index is returned as well.
2286  static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2287  int &Index);
2288  static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2289  int &Index) {
2290  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2291  SmallVector<int, 16> MaskAsInts;
2292  getShuffleMask(Mask, MaskAsInts);
2293  return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2294  }
2295 
2296  /// Return true if this shuffle mask is an extract subvector mask.
2297  bool isExtractSubvectorMask(int &Index) const {
2298  int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2299  return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2300  }
2301 
2302  /// Change values in a shuffle permute mask assuming the two vector operands
2303  /// of length InVecNumElts have swapped position.
2305  unsigned InVecNumElts) {
2306  for (int &Idx : Mask) {
2307  if (Idx == -1)
2308  continue;
2309  Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2310  assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2311  "shufflevector mask index out of range");
2312  }
2313  }
2314 
2315  // Methods for support type inquiry through isa, cast, and dyn_cast:
2316  static bool classof(const Instruction *I) {
2317  return I->getOpcode() == Instruction::ShuffleVector;
2318  }
2319  static bool classof(const Value *V) {
2320  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2321  }
2322 };
2323 
2324 template <>
2326  public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2327 };
2328 
2329 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2330 
2331 //===----------------------------------------------------------------------===//
2332 // ExtractValueInst Class
2333 //===----------------------------------------------------------------------===//
2334 
2335 /// This instruction extracts a struct member or array
2336 /// element value from an aggregate value.
2337 ///
2339  SmallVector<unsigned, 4> Indices;
2340 
2341  ExtractValueInst(const ExtractValueInst &EVI);
2342 
2343  /// Constructors - Create a extractvalue instruction with a base aggregate
2344  /// value and a list of indices. The first ctor can optionally insert before
2345  /// an existing instruction, the second appends the new instruction to the
2346  /// specified BasicBlock.
2347  inline ExtractValueInst(Value *Agg,
2348  ArrayRef<unsigned> Idxs,
2349  const Twine &NameStr,
2350  Instruction *InsertBefore);
2351  inline ExtractValueInst(Value *Agg,
2352  ArrayRef<unsigned> Idxs,
2353  const Twine &NameStr, BasicBlock *InsertAtEnd);
2354 
2355  void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2356 
2357 protected:
2358  // Note: Instruction needs to be a friend here to call cloneImpl.
2359  friend class Instruction;
2360 
2361  ExtractValueInst *cloneImpl() const;
2362 
2363 public:
2365  ArrayRef<unsigned> Idxs,
2366  const Twine &NameStr = "",
2367  Instruction *InsertBefore = nullptr) {
2368  return new
2369  ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2370  }
2371 
2373  ArrayRef<unsigned> Idxs,
2374  const Twine &NameStr,
2375  BasicBlock *InsertAtEnd) {
2376  return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2377  }
2378 
2379  /// Returns the type of the element that would be extracted
2380  /// with an extractvalue instruction with the specified parameters.
2381  ///
2382  /// Null is returned if the indices are invalid for the specified type.
2383  static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2384 
2385  using idx_iterator = const unsigned*;
2386 
2387  inline idx_iterator idx_begin() const { return Indices.begin(); }
2388  inline idx_iterator idx_end() const { return Indices.end(); }
2390  return make_range(idx_begin(), idx_end());
2391  }
2392 
2394  return getOperand(0);
2395  }
2396  const Value *getAggregateOperand() const {
2397  return getOperand(0);
2398  }
2399  static unsigned getAggregateOperandIndex() {
2400  return 0U; // get index for modifying correct operand
2401  }
2402 
2404  return Indices;
2405  }
2406 
2407  unsigned getNumIndices() const {
2408  return (unsigned)Indices.size();
2409  }
2410 
2411  bool hasIndices() const {
2412  return true;
2413  }
2414 
2415  // Methods for support type inquiry through isa, cast, and dyn_cast:
2416  static bool classof(const Instruction *I) {
2417  return I->getOpcode() == Instruction::ExtractValue;
2418  }
2419  static bool classof(const Value *V) {
2420  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2421  }
2422 };
2423 
2424 ExtractValueInst::ExtractValueInst(Value *Agg,
2425  ArrayRef<unsigned> Idxs,
2426  const Twine &NameStr,
2427  Instruction *InsertBefore)
2428  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2429  ExtractValue, Agg, InsertBefore) {
2430  init(Idxs, NameStr);
2431 }
2432 
2433 ExtractValueInst::ExtractValueInst(Value *Agg,
2434  ArrayRef<unsigned> Idxs,
2435  const Twine &NameStr,
2436  BasicBlock *InsertAtEnd)
2437  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2438  ExtractValue, Agg, InsertAtEnd) {
2439  init(Idxs, NameStr);
2440 }
2441 
2442 //===----------------------------------------------------------------------===//
2443 // InsertValueInst Class
2444 //===----------------------------------------------------------------------===//
2445 
2446 /// This instruction inserts a struct field of array element
2447 /// value into an aggregate value.
2448 ///
2450  SmallVector<unsigned, 4> Indices;
2451 
2452  InsertValueInst(const InsertValueInst &IVI);
2453 
2454  /// Constructors - Create a insertvalue instruction with a base aggregate
2455  /// value, a value to insert, and a list of indices. The first ctor can
2456  /// optionally insert before an existing instruction, the second appends
2457  /// the new instruction to the specified BasicBlock.
2458  inline InsertValueInst(Value *Agg, Value *Val,
2459  ArrayRef<unsigned> Idxs,
2460  const Twine &NameStr,
2461  Instruction *InsertBefore);
2462  inline InsertValueInst(Value *Agg, Value *Val,
2463  ArrayRef<unsigned> Idxs,
2464  const Twine &NameStr, BasicBlock *InsertAtEnd);
2465 
2466  /// Constructors - These two constructors are convenience methods because one
2467  /// and two index insertvalue instructions are so common.
2468  InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2469  const Twine &NameStr = "",
2470  Instruction *InsertBefore = nullptr);
2471  InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2472  BasicBlock *InsertAtEnd);
2473 
2474  void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2475  const Twine &NameStr);
2476 
2477 protected:
2478  // Note: Instruction needs to be a friend here to call cloneImpl.
2479  friend class Instruction;
2480 
2481  InsertValueInst *cloneImpl() const;
2482 
2483 public:
2484  // allocate space for exactly two operands
2485  void *operator new(size_t s) {
2486  return User::operator new(s, 2);
2487  }
2488 
2489  static InsertValueInst *Create(Value *Agg, Value *Val,
2490  ArrayRef<unsigned> Idxs,
2491  const Twine &NameStr = "",
2492  Instruction *InsertBefore = nullptr) {
2493  return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2494  }
2495 
2496  static InsertValueInst *Create(Value *Agg, Value *Val,
2497  ArrayRef<unsigned> Idxs,
2498  const Twine &NameStr,
2499  BasicBlock *InsertAtEnd) {
2500  return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2501  }
2502 
2503  /// Transparently provide more efficient getOperand methods.
2505 
2506  using idx_iterator = const unsigned*;
2507 
2508  inline idx_iterator idx_begin() const { return Indices.begin(); }
2509  inline idx_iterator idx_end() const { return Indices.end(); }
2511  return make_range(idx_begin(), idx_end());
2512  }
2513 
2515  return getOperand(0);
2516  }
2517  const Value *getAggregateOperand() const {
2518  return getOperand(0);
2519  }
2520  static unsigned getAggregateOperandIndex() {
2521  return 0U; // get index for modifying correct operand
2522  }
2523 
2525  return getOperand(1);
2526  }
2528  return getOperand(1);
2529  }
2530  static unsigned getInsertedValueOperandIndex() {
2531  return 1U; // get index for modifying correct operand
2532  }
2533 
2535  return Indices;
2536  }
2537 
2538  unsigned getNumIndices() const {
2539  return (unsigned)Indices.size();
2540  }
2541 
2542  bool hasIndices() const {
2543  return true;
2544  }
2545 
2546  // Methods for support type inquiry through isa, cast, and dyn_cast:
2547  static bool classof(const Instruction *I) {
2548  return I->getOpcode() == Instruction::InsertValue;
2549  }
2550  static bool classof(const Value *V) {
2551  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2552  }
2553 };
2554 
2555 template <>
2557  public FixedNumOperandTraits<InsertValueInst, 2> {
2558 };
2559 
2560 InsertValueInst::InsertValueInst(Value *Agg,
2561  Value *Val,
2562  ArrayRef<unsigned> Idxs,
2563  const Twine &NameStr,
2564  Instruction *InsertBefore)
2565  : Instruction(Agg->getType(), InsertValue,
2567  2, InsertBefore) {
2568  init(Agg, Val, Idxs, NameStr);
2569 }
2570 
2571 InsertValueInst::InsertValueInst(Value *Agg,
2572  Value *Val,
2573  ArrayRef<unsigned> Idxs,
2574  const Twine &NameStr,
2575  BasicBlock *InsertAtEnd)
2576  : Instruction(Agg->getType(), InsertValue,
2578  2, InsertAtEnd) {
2579  init(Agg, Val, Idxs, NameStr);
2580 }
2581 
2583 
2584 //===----------------------------------------------------------------------===//
2585 // PHINode Class
2586 //===----------------------------------------------------------------------===//
2587 
2588 // PHINode - The PHINode class is used to represent the magical mystical PHI
2589 // node, that can not exist in nature, but can be synthesized in a computer
2590 // scientist's overactive imagination.
2591 //
2592 class PHINode : public Instruction {
2593  /// The number of operands actually allocated. NumOperands is
2594  /// the number actually in use.
2595  unsigned ReservedSpace;
2596 
2597  PHINode(const PHINode &PN);
2598 
2599  explicit PHINode(Type *Ty, unsigned NumReservedValues,
2600  const Twine &NameStr = "",
2601  Instruction *InsertBefore = nullptr)
2602  : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2603  ReservedSpace(NumReservedValues) {
2604  setName(NameStr);
2605  allocHungoffUses(ReservedSpace);
2606  }
2607 
2608  PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2609  BasicBlock *InsertAtEnd)
2610  : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2611  ReservedSpace(NumReservedValues) {
2612  setName(NameStr);
2613  allocHungoffUses(ReservedSpace);
2614  }
2615 
2616 protected:
2617  // Note: Instruction needs to be a friend here to call cloneImpl.
2618  friend class Instruction;
2619 
2620  PHINode *cloneImpl() const;
2621 
2622  // allocHungoffUses - this is more complicated than the generic
2623  // User::allocHungoffUses, because we have to allocate Uses for the incoming
2624  // values and pointers to the incoming blocks, all in one allocation.
2625  void allocHungoffUses(unsigned N) {
2626  User::allocHungoffUses(N, /* IsPhi */ true);
2627  }
2628 
2629 public:
2630  /// Constructors - NumReservedValues is a hint for the number of incoming
2631  /// edges that this phi node will have (use 0 if you really have no idea).
2632  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2633  const Twine &NameStr = "",
2634  Instruction *InsertBefore = nullptr) {
2635  return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2636  }
2637 
2638  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2639  const Twine &NameStr, BasicBlock *InsertAtEnd) {
2640  return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2641  }
2642 
2643  /// Provide fast operand accessors
2645 
2646  // Block iterator interface. This provides access to the list of incoming
2647  // basic blocks, which parallels the list of incoming values.
2648 
2651 
2653  Use::UserRef *ref =
2654  reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2655  return reinterpret_cast<block_iterator>(ref + 1);
2656  }
2657 
2659  const Use::UserRef *ref =
2660  reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2661  return reinterpret_cast<const_block_iterator>(ref + 1);
2662  }
2663 
2665  return block_begin() + getNumOperands();
2666  }
2667 
2669  return block_begin() + getNumOperands();
2670  }
2671 
2673  return make_range(block_begin(), block_end());
2674  }
2675 
2677  return make_range(block_begin(), block_end());
2678  }
2679 
2681 
2683 
2684  /// Return the number of incoming edges
2685  ///
2686  unsigned getNumIncomingValues() const { return getNumOperands(); }
2687 
2688  /// Return incoming value number x
2689  ///
2690  Value *getIncomingValue(unsigned i) const {
2691  return getOperand(i);
2692  }
2693  void setIncomingValue(unsigned i, Value *V) {
2694  assert(V && "PHI node got a null value!");
2695  assert(getType() == V->getType() &&
2696  "All operands to PHI node must be the same type as the PHI node!");
2697  setOperand(i, V);
2698  }
2699 
2700  static unsigned getOperandNumForIncomingValue(unsigned i) {
2701  return i;
2702  }
2703 
2704  static unsigned getIncomingValueNumForOperand(unsigned i) {
2705  return i;
2706  }
2707 
2708  /// Return incoming basic block number @p i.
2709  ///
2710  BasicBlock *getIncomingBlock(unsigned i) const {
2711  return block_begin()[i];
2712  }
2713 
2714  /// Return incoming basic block corresponding
2715  /// to an operand of the PHI.
2716  ///
2717  BasicBlock *getIncomingBlock(const Use &U) const {
2718  assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2719  return getIncomingBlock(unsigned(&U - op_begin()));
2720  }
2721 
2722  /// Return incoming basic block corresponding
2723  /// to value use iterator.
2724  ///
2726  return getIncomingBlock(I.getUse());
2727  }
2728 
2729  void setIncomingBlock(unsigned i, BasicBlock *BB) {
2730  assert(BB && "PHI node got a null basic block!");
2731  block_begin()[i] = BB;
2732  }
2733 
2734  /// Add an incoming value to the end of the PHI list
2735  ///
2736  void addIncoming(Value *V, BasicBlock *BB) {
2737  if (getNumOperands() == ReservedSpace)
2738  growOperands(); // Get more space!
2739  // Initialize some new operands.
2741  setIncomingValue(getNumOperands() - 1, V);
2742  setIncomingBlock(getNumOperands() - 1, BB);
2743  }
2744 
2745  /// Remove an incoming value. This is useful if a
2746  /// predecessor basic block is deleted. The value removed is returned.
2747  ///
2748  /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2749  /// is true), the PHI node is destroyed and any uses of it are replaced with
2750  /// dummy values. The only time there should be zero incoming values to a PHI
2751  /// node is when the block is dead, so this strategy is sound.
2752  ///
2753  Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2754 
2755  Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2756  int Idx = getBasicBlockIndex(BB);
2757  assert(Idx >= 0 && "Invalid basic block argument to remove!");
2758  return removeIncomingValue(Idx, DeletePHIIfEmpty);
2759  }
2760 
2761  /// Return the first index of the specified basic
2762  /// block in the value list for this PHI. Returns -1 if no instance.
2763  ///
2764  int getBasicBlockIndex(const BasicBlock *BB) const {
2765  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2766  if (block_begin()[i] == BB)
2767  return i;
2768  return -1;
2769  }
2770 
2772  int Idx = getBasicBlockIndex(BB);
2773  assert(Idx >= 0 && "Invalid basic block argument!");
2774  return getIncomingValue(Idx);
2775  }
2776 
2777  /// If the specified PHI node always merges together the
2778  /// same value, return the value, otherwise return null.
2779  Value *hasConstantValue() const;
2780 
2781  /// Whether the specified PHI node always merges
2782  /// together the same value, assuming undefs are equal to a unique
2783  /// non-undef value.
2784  bool hasConstantOrUndefValue() const;
2785 
2786  /// Methods for support type inquiry through isa, cast, and dyn_cast:
2787  static bool classof(const Instruction *I) {
2788  return I->getOpcode() == Instruction::PHI;
2789  }
2790  static bool classof(const Value *V) {
2791  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2792  }
2793 
2794 private:
2795  void growOperands();
2796 };
2797 
2798 template <>
2800 };
2801 
2803 
2804 //===----------------------------------------------------------------------===//
2805 // LandingPadInst Class
2806 //===----------------------------------------------------------------------===//
2807 
2808 //===---------------------------------------------------------------------------
2809 /// The landingpad instruction holds all of the information
2810 /// necessary to generate correct exception handling. The landingpad instruction
2811 /// cannot be moved from the top of a landing pad block, which itself is
2812 /// accessible only from the 'unwind' edge of an invoke. This uses the
2813 /// SubclassData field in Value to store whether or not the landingpad is a
2814 /// cleanup.
2815 ///
2816 class LandingPadInst : public Instruction {
2817  /// The number of operands actually allocated. NumOperands is
2818  /// the number actually in use.
2819  unsigned ReservedSpace;
2820 
2821  LandingPadInst(const LandingPadInst &LP);
2822 
2823 public:
2825 
2826 private:
2827  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2828  const Twine &NameStr, Instruction *InsertBefore);
2829  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2830  const Twine &NameStr, BasicBlock *InsertAtEnd);
2831 
2832  // Allocate space for exactly zero operands.
2833  void *operator new(size_t s) {
2834  return User::operator new(s);
2835  }
2836 
2837  void growOperands(unsigned Size);
2838  void init(unsigned NumReservedValues, const Twine &NameStr);
2839 
2840 protected:
2841  // Note: Instruction needs to be a friend here to call cloneImpl.
2842  friend class Instruction;
2843 
2844  LandingPadInst *cloneImpl() const;
2845 
2846 public:
2847  /// Constructors - NumReservedClauses is a hint for the number of incoming
2848  /// clauses that this landingpad will have (use 0 if you really have no idea).
2849  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2850  const Twine &NameStr = "",
2851  Instruction *InsertBefore = nullptr);
2852  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2853  const Twine &NameStr, BasicBlock *InsertAtEnd);
2854 
2855  /// Provide fast operand accessors
2857 
2858  /// Return 'true' if this landingpad instruction is a
2859  /// cleanup. I.e., it should be run when unwinding even if its landing pad
2860  /// doesn't catch the exception.
2861  bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2862 
2863  /// Indicate that this landingpad instruction is a cleanup.
2864  void setCleanup(bool V) {
2865  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2866  (V ? 1 : 0));
2867  }
2868 
2869  /// Add a catch or filter clause to the landing pad.
2870  void addClause(Constant *ClauseVal);
2871 
2872  /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2873  /// determine what type of clause this is.
2874  Constant *getClause(unsigned Idx) const {
2875  return cast<Constant>(getOperandList()[Idx]);
2876  }
2877 
2878  /// Return 'true' if the clause and index Idx is a catch clause.
2879  bool isCatch(unsigned Idx) const {
2880  return !isa<ArrayType>(getOperandList()[Idx]->getType());
2881  }
2882 
2883  /// Return 'true' if the clause and index Idx is a filter clause.
2884  bool isFilter(unsigned Idx) const {
2885  return isa<ArrayType>(getOperandList()[Idx]->getType());
2886  }
2887 
2888  /// Get the number of clauses for this landing pad.
2889  unsigned getNumClauses() const { return getNumOperands(); }
2890 
2891  /// Grow the size of the operand list to accommodate the new
2892  /// number of clauses.
2893  void reserveClauses(unsigned Size) { growOperands(Size); }
2894 
2895  // Methods for support type inquiry through isa, cast, and dyn_cast:
2896  static bool classof(const Instruction *I) {
2897  return I->getOpcode() == Instruction::LandingPad;
2898  }
2899  static bool classof(const Value *V) {
2900  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2901  }
2902 };
2903 
2904 template <>
2906 };
2907 
2909 
2910 //===----------------------------------------------------------------------===//
2911 // ReturnInst Class
2912 //===----------------------------------------------------------------------===//
2913 
2914 //===---------------------------------------------------------------------------
2915 /// Return a value (possibly void), from a function. Execution
2916 /// does not continue in this function any longer.
2917 ///
2918 class ReturnInst : public Instruction {
2919  ReturnInst(const ReturnInst &RI);
2920 
2921 private:
2922  // ReturnInst constructors:
2923  // ReturnInst() - 'ret void' instruction
2924  // ReturnInst( null) - 'ret void' instruction
2925  // ReturnInst(Value* X) - 'ret X' instruction
2926  // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2927  // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2928  // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2929  // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2930  //
2931  // NOTE: If the Value* passed is of type void then the constructor behaves as
2932  // if it was passed NULL.
2933  explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2934  Instruction *InsertBefore = nullptr);
2935  ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2936  explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2937 
2938 protected:
2939  // Note: Instruction needs to be a friend here to call cloneImpl.
2940  friend class Instruction;
2941 
2942  ReturnInst *cloneImpl() const;
2943 
2944 public:
2945  static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2946  Instruction *InsertBefore = nullptr) {
2947  return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2948  }
2949 
2950  static ReturnInst* Create(LLVMContext &C, Value *retVal,
2951  BasicBlock *InsertAtEnd) {
2952  return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2953  }
2954 
2955  static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2956  return new(0) ReturnInst(C, InsertAtEnd);
2957  }
2958 
2959  /// Provide fast operand accessors
2961 
2962  /// Convenience accessor. Returns null if there is no return value.
2964  return getNumOperands() != 0 ? getOperand(0) : nullptr;
2965  }
2966 
2967  unsigned getNumSuccessors() const { return 0; }
2968 
2969  // Methods for support type inquiry through isa, cast, and dyn_cast:
2970  static bool classof(const Instruction *I) {
2971  return (I->getOpcode() == Instruction::Ret);
2972  }
2973  static bool classof(const Value *V) {
2974  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2975  }
2976 
2977 private:
2978  BasicBlock *getSuccessor(unsigned idx) const {
2979  llvm_unreachable("ReturnInst has no successors!");
2980  }
2981 
2982  void setSuccessor(unsigned idx, BasicBlock *B) {
2983  llvm_unreachable("ReturnInst has no successors!");
2984  }
2985 };
2986 
2987 template <>
2988 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2989 };
2990 
2992 
2993 //===----------------------------------------------------------------------===//
2994 // BranchInst Class
2995 //===----------------------------------------------------------------------===//
2996 
2997 //===---------------------------------------------------------------------------
2998 /// Conditional or Unconditional Branch instruction.
2999 ///
3000 class BranchInst : public Instruction {
3001  /// Ops list - Branches are strange. The operands are ordered:
3002  /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
3003  /// they don't have to check for cond/uncond branchness. These are mostly
3004  /// accessed relative from op_end().
3005  BranchInst(const BranchInst &BI);
3006  // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
3007  // BranchInst(BB *B) - 'br B'
3008  // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
3009  // BranchInst(BB* B, Inst *I) - 'br B' insert before I
3010  // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
3011  // BranchInst(BB* B, BB *I) - 'br B' insert at end
3012  // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
3013  explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
3014  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3015  Instruction *InsertBefore = nullptr);
3016  BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
3017  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3018  BasicBlock *InsertAtEnd);
3019 
3020  void AssertOK();
3021 
3022 protected:
3023  // Note: Instruction needs to be a friend here to call cloneImpl.
3024  friend class Instruction;
3025 
3026  BranchInst *cloneImpl() const;
3027 
3028 public:
3029  /// Iterator type that casts an operand to a basic block.
3030  ///
3031  /// This only makes sense because the successors are stored as adjacent
3032  /// operands for branch instructions.
3034  : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3035  std::random_access_iterator_tag, BasicBlock *,
3036  ptrdiff_t, BasicBlock *, BasicBlock *> {
3038 
3039  BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3040  BasicBlock *operator->() const { return operator*(); }
3041  };
3042 
3043  /// The const version of `succ_op_iterator`.
3045  : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3046  std::random_access_iterator_tag,
3047  const BasicBlock *, ptrdiff_t, const BasicBlock *,
3048  const BasicBlock *> {
3050  : iterator_adaptor_base(I) {}
3051 
3052  const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3053  const BasicBlock *operator->() const { return operator*(); }
3054  };
3055 
3056  static BranchInst *Create(BasicBlock *IfTrue,
3057  Instruction *InsertBefore = nullptr) {
3058  return new(1) BranchInst(IfTrue, InsertBefore);
3059  }
3060 
3061  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3062  Value *Cond, Instruction *InsertBefore = nullptr) {
3063  return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3064  }
3065 
3066  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3067  return new(1) BranchInst(IfTrue, InsertAtEnd);
3068  }
3069 
3070  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3071  Value *Cond, BasicBlock *InsertAtEnd) {
3072  return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3073  }
3074 
3075  /// Transparently provide more efficient getOperand methods.
3077 
3078  bool isUnconditional() const { return getNumOperands() == 1; }
3079  bool isConditional() const { return getNumOperands() == 3; }
3080 
3081  Value *getCondition() const {
3082  assert(isConditional() && "Cannot get condition of an uncond branch!");
3083  return Op<-3>();
3084  }
3085 
3086  void setCondition(Value *V) {
3087  assert(isConditional() && "Cannot set condition of unconditional branch!");
3088  Op<-3>() = V;
3089  }
3090 
3091  unsigned getNumSuccessors() const { return 1+isConditional(); }
3092 
3093  BasicBlock *getSuccessor(unsigned i) const {
3094  assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3095  return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3096  }
3097 
3098  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3099  assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3100  *(&Op<-1>() - idx) = NewSucc;
3101  }
3102 
3103  /// Swap the successors of this branch instruction.
3104  ///
3105  /// Swaps the successors of the branch instruction. This also swaps any
3106  /// branch weight metadata associated with the instruction so that it
3107  /// continues to map correctly to each operand.
3108  void swapSuccessors();
3109 
3111  return make_range(
3112  succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3114  }
3115 
3118  std::next(value_op_begin(), isConditional() ? 1 : 0)),
3120  }
3121 
3122  // Methods for support type inquiry through isa, cast, and dyn_cast:
3123  static bool classof(const Instruction *I) {
3124  return (I->getOpcode() == Instruction::Br);
3125  }
3126  static bool classof(const Value *V) {
3127  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3128  }
3129 };
3130 
3131 template <>
3132 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3133 };
3134 
3136 
3137 //===----------------------------------------------------------------------===//
3138 // SwitchInst Class
3139 //===----------------------------------------------------------------------===//
3140 
3141 //===---------------------------------------------------------------------------
3142 /// Multiway switch
3143 ///
3144 class SwitchInst : public Instruction {
3145  unsigned ReservedSpace;
3146 
3147  // Operand[0] = Value to switch on
3148  // Operand[1] = Default basic block destination
3149  // Operand[2n ] = Value to match
3150  // Operand[2n+1] = BasicBlock to go to on match
3151  SwitchInst(const SwitchInst &SI);
3152 
3153  /// Create a new switch instruction, specifying a value to switch on and a
3154  /// default destination. The number of additional cases can be specified here
3155  /// to make memory allocation more efficient. This constructor can also
3156  /// auto-insert before another instruction.
3157  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3158  Instruction *InsertBefore);
3159 
3160  /// Create a new switch instruction, specifying a value to switch on and a
3161  /// default destination. The number of additional cases can be specified here
3162  /// to make memory allocation more efficient. This constructor also
3163  /// auto-inserts at the end of the specified BasicBlock.
3164  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3165  BasicBlock *InsertAtEnd);
3166 
3167  // allocate space for exactly zero operands
3168  void *operator new(size_t s) {
3169  return User::operator new(s);
3170  }
3171 
3172  void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3173  void growOperands();
3174 
3175 protected:
3176  // Note: Instruction needs to be a friend here to call cloneImpl.
3177  friend class Instruction;
3178 
3179  SwitchInst *cloneImpl() const;
3180 
3181 public:
3182  // -2
3183  static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3184 
3185  template <typename CaseHandleT> class CaseIteratorImpl;
3186 
3187  /// A handle to a particular switch case. It exposes a convenient interface
3188  /// to both the case value and the successor block.
3189  ///
3190  /// We define this as a template and instantiate it to form both a const and
3191  /// non-const handle.
3192  template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3194  // Directly befriend both const and non-const iterators.
3195  friend class SwitchInst::CaseIteratorImpl<
3196  CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3197 
3198  protected:
3199  // Expose the switch type we're parameterized with to the iterator.
3200  using SwitchInstType = SwitchInstT;
3201 
3202  SwitchInstT *SI;
3204 
3205  CaseHandleImpl() = default;
3206  CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3207 
3208  public:
3209  /// Resolves case value for current case.
3210  ConstantIntT *getCaseValue() const {
3211  assert((unsigned)Index < SI->getNumCases() &&
3212  "Index out the number of cases.");
3213  return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3214  }
3215 
3216  /// Resolves successor for current case.
3217  BasicBlockT *getCaseSuccessor() const {
3218  assert(((unsigned)Index < SI->getNumCases() ||
3219  (unsigned)Index == DefaultPseudoIndex) &&
3220  "Index out the number of cases.");
3221  return SI->getSuccessor(getSuccessorIndex());
3222  }
3223 
3224  /// Returns number of current case.
3225  unsigned getCaseIndex() const { return Index; }
3226 
3227  /// Returns successor index for current case successor.
3228  unsigned getSuccessorIndex() const {
3229  assert(((unsigned)Index == DefaultPseudoIndex ||
3230  (unsigned)Index < SI->getNumCases()) &&
3231  "Index out the number of cases.");
3232  return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3233  }
3234 
3235  bool operator==(const CaseHandleImpl &RHS) const {
3236  assert(SI == RHS.SI && "Incompatible operators.");
3237  return Index == RHS.Index;
3238  }
3239  };
3240 
3241  using ConstCaseHandle =
3243 
3245  : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3247 
3248  public:
3250 
3251  /// Sets the new value for current case.
3253  assert((unsigned)Index < SI->getNumCases() &&
3254  "Index out the number of cases.");
3255  SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3256  }
3257 
3258  /// Sets the new successor for current case.
3260  SI->setSuccessor(getSuccessorIndex(), S);
3261  }
3262  };
3263 
3264  template <typename CaseHandleT>
3265  class CaseIteratorImpl
3266  : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3267  std::random_access_iterator_tag,
3268  CaseHandleT> {
3269  using SwitchInstT = typename CaseHandleT::SwitchInstType;
3270 
3271  CaseHandleT Case;
3272 
3273  public:
3274  /// Default constructed iterator is in an invalid state until assigned to
3275  /// a case for a particular switch.
3276  CaseIteratorImpl() = default;
3277 
3278  /// Initializes case iterator for given SwitchInst and for given
3279  /// case number.
3280  CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3281 
3282  /// Initializes case iterator for given SwitchInst and for given
3283  /// successor index.
3284  static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3285  unsigned SuccessorIndex) {
3286  assert(SuccessorIndex < SI->getNumSuccessors() &&
3287  "Successor index # out of range!");
3288  return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3289  : CaseIteratorImpl(SI, DefaultPseudoIndex);
3290  }
3291 
3292  /// Support converting to the const variant. This will be a no-op for const
3293  /// variant.
3295  return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3296  }
3297 
3299  // Check index correctness after addition.
3300  // Note: Index == getNumCases() means end().
3301  assert(Case.Index + N >= 0 &&
3302  (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3303  "Case.Index out the number of cases.");
3304  Case.Index += N;
3305  return *this;
3306  }
3308  // Check index correctness after subtraction.
3309  // Note: Case.Index == getNumCases() means end().
3310  assert(Case.Index - N >= 0 &&
3311  (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3312  "Case.Index out the number of cases.");
3313  Case.Index -= N;
3314  return *this;
3315  }
3317  assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3318  return Case.Index - RHS.Case.Index;
3319  }
3320  bool operator==(const CaseIteratorImpl &RHS) const {
3321  return Case == RHS.Case;
3322  }
3323  bool operator<(const CaseIteratorImpl &RHS) const {
3324  assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3325  return Case.Index < RHS.Case.Index;
3326  }
3327  CaseHandleT &operator*() { return Case; }
3328  const CaseHandleT &operator*() const { return Case; }
3329  };
3330 
3333 
3334  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3335  unsigned NumCases,
3336  Instruction *InsertBefore = nullptr) {
3337  return new SwitchInst(Value, Default, NumCases, InsertBefore);
3338  }
3339 
3340  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3341  unsigned NumCases, BasicBlock *InsertAtEnd) {
3342  return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3343  }
3344 
3345  /// Provide fast operand accessors
3347 
3348  // Accessor Methods for Switch stmt
3349  Value *getCondition() const { return getOperand(0); }
3350  void setCondition(Value *V) { setOperand(0, V); }
3351 
3353  return cast<BasicBlock>(getOperand(1));
3354  }
3355 
3356  void setDefaultDest(BasicBlock *DefaultCase) {
3357  setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3358  }
3359 
3360  /// Return the number of 'cases' in this switch instruction, excluding the
3361  /// default case.
3362  unsigned getNumCases() const {
3363  return getNumOperands()/2 - 1;
3364  }
3365 
3366  /// Returns a read/write iterator that points to the first case in the
3367  /// SwitchInst.
3369  return CaseIt(this, 0);
3370  }
3371 
3372  /// Returns a read-only iterator that points to the first case in the
3373  /// SwitchInst.
3375  return ConstCaseIt(this, 0);
3376  }
3377 
3378  /// Returns a read/write iterator that points one past the last in the
3379  /// SwitchInst.
3381  return CaseIt(this, getNumCases());
3382  }
3383 
3384  /// Returns a read-only iterator that points one past the last in the
3385  /// SwitchInst.
3387  return ConstCaseIt(this, getNumCases());
3388  }
3389 
3390  /// Iteration adapter for range-for loops.
3392  return make_range(case_begin(), case_end());
3393  }
3394 
3395  /// Constant iteration adapter for range-for loops.
3397  return make_range(case_begin(), case_end());
3398  }
3399 
3400  /// Returns an iterator that points to the default case.
3401  /// Note: this iterator allows to resolve successor only. Attempt
3402  /// to resolve case value causes an assertion.
3403  /// Also note, that increment and decrement also causes an assertion and
3404  /// makes iterator invalid.
3406  return CaseIt(this, DefaultPseudoIndex);
3407  }
3409  return ConstCaseIt(this, DefaultPseudoIndex);
3410  }
3411 
3412  /// Search all of the case values for the specified constant. If it is
3413  /// explicitly handled, return the case iterator of it, otherwise return
3414  /// default case iterator to indicate that it is handled by the default
3415  /// handler.
3418  cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3419  if (I != case_end())
3420  return I;
3421 
3422  return case_default();
3423  }
3425  ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3426  return Case.getCaseValue() == C;
3427  });
3428  if (I != case_end())
3429  return I;
3430 
3431  return case_default();
3432  }
3433 
3434  /// Finds the unique case value for a given successor. Returns null if the
3435  /// successor is not found, not unique, or is the default case.
3437  if (BB == getDefaultDest())
3438  return nullptr;
3439 
3440  ConstantInt *CI = nullptr;
3441  for (auto Case : cases()) {
3442  if (Case.getCaseSuccessor() != BB)
3443  continue;
3444 
3445  if (CI)
3446  return nullptr; // Multiple cases lead to BB.
3447 
3448  CI = Case.getCaseValue();
3449  }
3450 
3451  return CI;
3452  }
3453 
3454  /// Add an entry to the switch instruction.
3455  /// Note:
3456  /// This action invalidates case_end(). Old case_end() iterator will
3457  /// point to the added case.
3458  void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3459 
3460  /// This method removes the specified case and its successor from the switch
3461  /// instruction. Note that this operation may reorder the remaining cases at
3462  /// index idx and above.
3463  /// Note:
3464  /// This action invalidates iterators for all cases following the one removed,
3465  /// including the case_end() iterator. It returns an iterator for the next
3466  /// case.
3467  CaseIt removeCase(CaseIt I);
3468 
3469  unsigned getNumSuccessors() const { return getNumOperands()/2; }
3470  BasicBlock *getSuccessor(unsigned idx) const {
3471  assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3472  return cast<BasicBlock>(getOperand(idx*2+1));
3473  }
3474  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3475  assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3476  setOperand(idx * 2 + 1, NewSucc);
3477  }
3478 
3479  // Methods for support type inquiry through isa, cast, and dyn_cast:
3480  static bool classof(const Instruction *I) {
3481  return I->getOpcode() == Instruction::Switch;
3482  }
3483  static bool classof(const Value *V) {
3484  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3485  }
3486 };
3487 
3488 template <>
3490 };
3491 
3492 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3493 
3494 //===----------------------------------------------------------------------===//
3495 // IndirectBrInst Class
3496 //===----------------------------------------------------------------------===//
3497 
3498 //===---------------------------------------------------------------------------
3499 /// Indirect Branch Instruction.
3500 ///
3501 class IndirectBrInst : public Instruction {
3502  unsigned ReservedSpace;
3503 
3504  // Operand[0] = Address to jump to
3505  // Operand[n+1] = n-th destination
3506  IndirectBrInst(const IndirectBrInst &IBI);
3507 
3508  /// Create a new indirectbr instruction, specifying an
3509  /// Address to jump to. The number of expected destinations can be specified
3510  /// here to make memory allocation more efficient. This constructor can also
3511  /// autoinsert before another instruction.
3512  IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3513 
3514  /// Create a new indirectbr instruction, specifying an
3515  /// Address to jump to. The number of expected destinations can be specified
3516  /// here to make memory allocation more efficient. This constructor also
3517  /// autoinserts at the end of the specified BasicBlock.
3518  IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3519 
3520  // allocate space for exactly zero operands
3521  void *operator new(size_t s) {
3522  return User::operator new(s);
3523  }
3524 
3525  void init(Value *Address, unsigned NumDests);
3526  void growOperands();
3527 
3528 protected:
3529  // Note: Instruction needs to be a friend here to call cloneImpl.
3530  friend class Instruction;
3531 
3532  IndirectBrInst *cloneImpl() const;
3533 
3534 public:
3535  /// Iterator type that casts an operand to a basic block.
3536  ///
3537  /// This only makes sense because the successors are stored as adjacent
3538  /// operands for indirectbr instructions.
3540  : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3541  std::random_access_iterator_tag, BasicBlock *,
3542  ptrdiff_t, BasicBlock *, BasicBlock *> {
3544 
3545  BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3546  BasicBlock *operator->() const { return operator*(); }
3547  };
3548 
3549  /// The const version of `succ_op_iterator`.
3551  : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3552  std::random_access_iterator_tag,
3553  const BasicBlock *, ptrdiff_t, const BasicBlock *,
3554  const BasicBlock *> {
3556  : iterator_adaptor_base(I) {}
3557 
3558  const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3559  const BasicBlock *operator->() const { return operator*(); }
3560  };
3561 
3562  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3563  Instruction *InsertBefore = nullptr) {
3564  return new IndirectBrInst(Address, NumDests, InsertBefore);
3565  }
3566 
3567  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3568  BasicBlock *InsertAtEnd) {
3569  return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3570  }
3571 
3572  /// Provide fast operand accessors.
3574 
3575  // Accessor Methods for IndirectBrInst instruction.
3576  Value *getAddress() { return getOperand(0); }
3577  const Value *getAddress() const { return getOperand(0); }
3578  void setAddress(Value *V) { setOperand(0, V); }
3579 
3580  /// return the number of possible destinations in this
3581  /// indirectbr instruction.
3582  unsigned getNumDestinations() const { return getNumOperands()-1; }
3583 
3584  /// Return the specified destination.
3585  BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3586  const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3587 
3588  /// Add a destination.
3589  ///
3590  void addDestination(BasicBlock *Dest);
3591 
3592  /// This method removes the specified successor from the
3593  /// indirectbr instruction.
3594  void removeDestination(unsigned i);
3595 
3596  unsigned getNumSuccessors() const { return getNumOperands()-1; }
3597  BasicBlock *getSuccessor(unsigned i) const {
3598  return cast<BasicBlock>(getOperand(i+1));
3599  }
3600  void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3601  setOperand(i + 1, NewSucc);
3602  }
3603 
3605  return make_range(succ_op_iterator(std::next(value_op_begin())),
3607  }
3608 
3610  return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3612  }
3613 
3614  // Methods for support type inquiry through isa, cast, and dyn_cast:
3615  static bool classof(const Instruction *I) {
3616  return I->getOpcode() == Instruction::IndirectBr;
3617  }
3618  static bool classof(const Value *V) {
3619  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3620  }
3621 };
3622 
3623 template <>
3625 };
3626 
3627 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3628 
3629 //===----------------------------------------------------------------------===//
3630 // InvokeInst Class
3631 //===----------------------------------------------------------------------===//
3632 
3633 /// Invoke instruction. The SubclassData field is used to hold the
3634 /// calling convention of the call.
3635 ///
3636 class InvokeInst : public CallBase {
3637  /// The number of operands for this call beyond the called function,
3638  /// arguments, and operand bundles.
3639  static constexpr int NumExtraOperands = 2;
3640 
3641  /// The index from the end of the operand array to the normal destination.
3642  static constexpr int NormalDestOpEndIdx = -3;
3643 
3644  /// The index from the end of the operand array to the unwind destination.
3645  static constexpr int UnwindDestOpEndIdx = -2;
3646 
3647  InvokeInst(const InvokeInst &BI);
3648 
3649  /// Construct an InvokeInst given a range of arguments.
3650  ///
3651  /// Construct an InvokeInst from a range of arguments
3652  inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3653  BasicBlock *IfException, ArrayRef<Value *> Args,
3654  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3655  const Twine &NameStr, Instruction *InsertBefore);
3656 
3657  inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3658  BasicBlock *IfException, ArrayRef<Value *> Args,
3659  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3660  const Twine &NameStr, BasicBlock *InsertAtEnd);
3661 
3662  void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3663  BasicBlock *IfException, ArrayRef<Value *> Args,
3664  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3665 
3666  /// Compute the number of operands to allocate.
3667  static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3668  // We need one operand for the called function, plus our extra operands and
3669  // the input operand counts provided.
3670  return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3671  }
3672 
3673 protected:
3674  // Note: Instruction needs to be a friend here to call cloneImpl.
3675  friend class Instruction;
3676 
3677  InvokeInst *cloneImpl() const;
3678 
3679 public:
3680  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3681  BasicBlock *IfException, ArrayRef<Value *> Args,
3682  const Twine &NameStr,
3683  Instruction *InsertBefore = nullptr) {
3684  int NumOperands = ComputeNumOperands(Args.size());
3685  return new (NumOperands)
3686  InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3687  NameStr, InsertBefore);
3688  }
3689 
3690  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3691  BasicBlock *IfException, ArrayRef<Value *> Args,
3692  ArrayRef<OperandBundleDef> Bundles = None,
3693  const Twine &NameStr = "",
3694  Instruction *InsertBefore = nullptr) {
3695  int NumOperands =
3696  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3697  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3698 
3699  return new (NumOperands, DescriptorBytes)
3700  InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3701  NameStr, InsertBefore);
3702  }
3703 
3704  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3705  BasicBlock *IfException, ArrayRef<Value *> Args,
3706  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3707  int NumOperands = ComputeNumOperands(Args.size());
3708  return new (NumOperands)
3709  InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3710  NameStr, InsertAtEnd);
3711  }
3712 
3713  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3714  BasicBlock *IfException, ArrayRef<Value *> Args,
3716  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3717  int NumOperands =
3718  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3719  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3720 
3721  return new (NumOperands, DescriptorBytes)
3722  InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3723  NameStr, InsertAtEnd);
3724  }
3725 
3726  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3727  BasicBlock *IfException, ArrayRef<Value *> Args,
3728  const Twine &NameStr,
3729  Instruction *InsertBefore = nullptr) {
3730  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3731  IfException, Args, None, NameStr, InsertBefore);
3732  }
3733 
3734  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3735  BasicBlock *IfException, ArrayRef<Value *> Args,
3736  ArrayRef<OperandBundleDef> Bundles = None,
3737  const Twine &NameStr = "",
3738  Instruction *InsertBefore = nullptr) {
3739  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3740  IfException, Args, Bundles, NameStr, InsertBefore);
3741  }
3742 
3743  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3744  BasicBlock *IfException, ArrayRef<Value *> Args,
3745  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3746  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3747  IfException, Args, NameStr, InsertAtEnd);
3748  }
3749 
3750  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3751  BasicBlock *IfException, ArrayRef<Value *> Args,
3753  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3754  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3755  IfException, Args, Bundles, NameStr, InsertAtEnd);
3756  }
3757 
3758  // Deprecated [opaque pointer types]
3759  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3760  BasicBlock *IfException, ArrayRef<Value *> Args,
3761  const Twine &NameStr,
3762  Instruction *InsertBefore = nullptr) {
3763  return Create(cast<FunctionType>(
3764  cast<PointerType>(Func->getType())->getElementType()),
3765  Func, IfNormal, IfException, Args, None, NameStr,
3766  InsertBefore);
3767  }
3768 
3769  // Deprecated [opaque pointer types]
3770  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3771  BasicBlock *IfException, ArrayRef<Value *> Args,
3772  ArrayRef<OperandBundleDef> Bundles = None,
3773  const Twine &NameStr = "",
3774  Instruction *InsertBefore = nullptr) {
3775  return Create(cast<FunctionType>(
3776  cast<PointerType>(Func->getType())->getElementType()),
3777  Func, IfNormal, IfException, Args, Bundles, NameStr,
3778  InsertBefore);
3779  }
3780 
3781  // Deprecated [opaque pointer types]
3782  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3783  BasicBlock *IfException, ArrayRef<Value *> Args,
3784  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3785  return Create(cast<FunctionType>(
3786  cast<PointerType>(Func->getType())->getElementType()),
3787  Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3788  }
3789 
3790  // Deprecated [opaque pointer types]
3791  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3792  BasicBlock *IfException, ArrayRef<Value *> Args,
3794  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3795  return Create(cast<FunctionType>(
3796  cast<PointerType>(Func->getType())->getElementType()),
3797  Func, IfNormal, IfException, Args, Bundles, NameStr,
3798  InsertAtEnd);
3799  }
3800 
3801  /// Create a clone of \p II with a different set of operand bundles and
3802  /// insert it before \p InsertPt.
3803  ///
3804  /// The returned invoke instruction is identical to \p II in every way except
3805  /// that the operand bundles for the new instruction are set to the operand
3806  /// bundles in \p Bundles.
3807  static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3808  Instruction *InsertPt = nullptr);
3809 
3810  /// Determine if the call should not perform indirect branch tracking.
3811  bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3812 
3813  /// Determine if the call cannot unwind.
3814  bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3816  addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3817  }
3818 
3819  // get*Dest - Return the destination basic blocks...
3821  return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3822  }
3824  return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3825  }
3827  Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3828  }
3830  Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3831  }
3832 
3833  /// Get the landingpad instruction from the landing pad
3834  /// block (the unwind destination).
3835  LandingPadInst *getLandingPadInst() const;
3836 
3837  BasicBlock *getSuccessor(unsigned i) const {
3838  assert(i < 2 && "Successor # out of range for invoke!");
3839  return i == 0 ? getNormalDest() : getUnwindDest();
3840  }
3841 
3842  void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3843  assert(i < 2 && "Successor # out of range for invoke!");
3844  if (i == 0)
3845  setNormalDest(NewSucc);
3846  else
3847  setUnwindDest(NewSucc);
3848  }
3849 
3850  unsigned getNumSuccessors() const { return 2; }
3851 
3852  // Methods for support type inquiry through isa, cast, and dyn_cast:
3853  static bool classof(const Instruction *I) {
3854  return (I->getOpcode() == Instruction::Invoke);
3855  }
3856  static bool classof(const Value *V) {
3857  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3858  }
3859 
3860 private:
3861 
3862  // Shadow Instruction::setInstructionSubclassData with a private forwarding
3863  // method so that subclasses cannot accidentally use it.
3864  void setInstructionSubclassData(unsigned short D) {
3866  }
3867 };
3868 
3869 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3870  BasicBlock *IfException, ArrayRef<Value *> Args,
3871  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3872  const Twine &NameStr, Instruction *InsertBefore)
3873  : CallBase(Ty->getReturnType(), Instruction::Invoke,
3874  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3875  InsertBefore) {
3876  init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3877 }
3878 
3879 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3880  BasicBlock *IfException, ArrayRef<Value *> Args,
3881  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3882  const Twine &NameStr, BasicBlock *InsertAtEnd)
3883  : CallBase(Ty->getReturnType(), Instruction::Invoke,
3884  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3885  InsertAtEnd) {
3886  init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3887 }
3888 
3889 //===----------------------------------------------------------------------===//
3890 // CallBrInst Class
3891 //===----------------------------------------------------------------------===//
3892 
3893 /// CallBr instruction, tracking function calls that may not return control but
3894 /// instead transfer it to a third location. The SubclassData field is used to
3895 /// hold the calling convention of the call.
3896 ///
3897 class CallBrInst : public CallBase {
3898 
3899  unsigned NumIndirectDests;
3900 
3901  CallBrInst(const CallBrInst &BI);
3902 
3903  /// Construct a CallBrInst given a range of arguments.
3904  ///
3905  /// Construct a CallBrInst from a range of arguments
3906  inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3907  ArrayRef<BasicBlock *> IndirectDests,
3908  ArrayRef<Value *> Args,
3909  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3910  const Twine &NameStr, Instruction *InsertBefore);
3911 
3912  inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3913  ArrayRef<BasicBlock *> IndirectDests,
3914  ArrayRef<Value *> Args,
3915  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3916  const Twine &NameStr, BasicBlock *InsertAtEnd);
3917 
3918  void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3919  ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3920  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3921 
3922  /// Compute the number of operands to allocate.
3923  static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3924  int NumBundleInputs = 0) {
3925  // We need one operand for the called function, plus our extra operands and
3926  // the input operand counts provided.
3927  return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3928  }
3929 
3930 protected:
3931  // Note: Instruction needs to be a friend here to call cloneImpl.
3932  friend class Instruction;
3933 
3934  CallBrInst *cloneImpl() const;
3935 
3936 public:
3937  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3938  BasicBlock *DefaultDest,
3939  ArrayRef<BasicBlock *> IndirectDests,
3940  ArrayRef<Value *> Args, const Twine &NameStr,
3941  Instruction *InsertBefore = nullptr) {
3942  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3943  return new (NumOperands)
3944  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3945  NumOperands, NameStr, InsertBefore);
3946  }
3947 
3948  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3949  BasicBlock *DefaultDest,
3950  ArrayRef<BasicBlock *> IndirectDests,
3951  ArrayRef<Value *> Args,
3952  ArrayRef<OperandBundleDef> Bundles = None,
3953  const Twine &NameStr = "",
3954  Instruction *InsertBefore = nullptr) {
3955  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3956  CountBundleInputs(Bundles));
3957  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3958 
3959  return new (NumOperands, DescriptorBytes)
3960  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3961  NumOperands, NameStr, InsertBefore);
3962  }
3963 
3964  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3965  BasicBlock *DefaultDest,
3966  ArrayRef<BasicBlock *> IndirectDests,
3967  ArrayRef<Value *> Args, const Twine &NameStr,
3968  BasicBlock *InsertAtEnd) {
3969  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3970  return new (NumOperands)
3971  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3972  NumOperands, NameStr, InsertAtEnd);
3973  }
3974 
3975  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3976  BasicBlock *DefaultDest,
3977  ArrayRef<BasicBlock *> IndirectDests,
3978  ArrayRef<Value *> Args,
3980  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3981  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3982  CountBundleInputs(Bundles));
3983  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3984 
3985  return new (NumOperands, DescriptorBytes)
3986  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3987  NumOperands, NameStr, InsertAtEnd);
3988  }
3989 
3990  static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
3991  ArrayRef<BasicBlock *> IndirectDests,
3992  ArrayRef<Value *> Args, const Twine &NameStr,
3993  Instruction *InsertBefore = nullptr) {
3994  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
3995  IndirectDests, Args, NameStr, InsertBefore);
3996  }
3997 
3998  static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
3999  ArrayRef<BasicBlock *> IndirectDests,
4000  ArrayRef<Value *> Args,
4001  ArrayRef<OperandBundleDef> Bundles = None,
4002  const Twine &NameStr = "",
4003  Instruction *InsertBefore = nullptr) {
4004  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4005  IndirectDests, Args, Bundles, NameStr, InsertBefore);
4006  }
4007 
4008  static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4009  ArrayRef<BasicBlock *> IndirectDests,
4010  ArrayRef<Value *> Args, const Twine &NameStr,
4011  BasicBlock *InsertAtEnd) {
4012  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4013  IndirectDests, Args, NameStr, InsertAtEnd);
4014  }
4015 
4017  BasicBlock *DefaultDest,
4018  ArrayRef<BasicBlock *> IndirectDests,
4019  ArrayRef<Value *> Args,
4021  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4022  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4023  IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4024  }
4025 
4026  /// Create a clone of \p CBI with a different set of operand bundles and
4027  /// insert it before \p InsertPt.
4028  ///
4029  /// The returned callbr instruction is identical to \p CBI in every way
4030  /// except that the operand bundles for the new instruction are set to the
4031  /// operand bundles in \p Bundles.
4032  static CallBrInst *Create(CallBrInst *CBI,
4034  Instruction *InsertPt = nullptr);
4035 
4036  /// Return the number of callbr indirect dest labels.
4037  ///
4038  unsigned getNumIndirectDests() const { return NumIndirectDests; }
4039 
4040  /// getIndirectDestLabel - Return the i-th indirect dest label.
4041  ///
4042  Value *getIndirectDestLabel(unsigned i) const {
4043  assert(i < getNumIndirectDests() && "Out of bounds!");
4044  return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4045  1);
4046  }
4047 
4048  Value *getIndirectDestLabelUse(unsigned i) const {
4049  assert(i < getNumIndirectDests() && "Out of bounds!");
4050  return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4051  1);
4052  }
4053 
4054  // Return the destination basic blocks...
4056  return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4057  }
4058  BasicBlock *getIndirectDest(unsigned i) const {
4059  return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4060  }
4062  SmallVector<BasicBlock *, 16> IndirectDests;
4063  for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4064  IndirectDests.push_back(getIndirectDest(i));
4065  return IndirectDests;
4066  }
4068  *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4069  }
4070  void setIndirectDest(unsigned i, BasicBlock *B) {
4071  *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4072  }
4073 
4074  BasicBlock *getSuccessor(unsigned i) const {
4075  assert(i < getNumSuccessors() + 1 &&
4076  "Successor # out of range for callbr!");
4077  return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4078  }
4079 
4080  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4081  assert(idx < getNumIndirectDests() + 1 &&
4082  "Successor # out of range for callbr!");
4083  *(&Op<-1>() - getNumIndirectDests() -1 + idx) =
4084  reinterpret_cast<Value *>(NewSucc);
4085  }
4086 
4087  unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4088 
4089  // Methods for support type inquiry through isa, cast, and dyn_cast:
4090  static bool classof(const Instruction *I) {
4091  return (I->getOpcode() == Instruction::CallBr);
4092  }
4093  static bool classof(const Value *V) {
4094  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4095  }
4096 
4097 private:
4098 
4099  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4100  // method so that subclasses cannot accidentally use it.
4101  void setInstructionSubclassData(unsigned short D) {
4103  }
4104 };
4105 
4106 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4107  ArrayRef<BasicBlock *> IndirectDests,
4108  ArrayRef<Value *> Args,
4109  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4110  const Twine &NameStr, Instruction *InsertBefore)
4111  : CallBase(Ty->getReturnType(), Instruction::CallBr,
4112  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4113  InsertBefore) {
4114  init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4115 }
4116 
4117 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4118  ArrayRef<BasicBlock *> IndirectDests,
4119  ArrayRef<Value *> Args,
4120  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4121  const Twine &NameStr, BasicBlock *InsertAtEnd)
4122  : CallBase(
4123  cast<FunctionType>(
4124  cast<PointerType>(Func->getType())->getElementType())
4125  ->getReturnType(),
4126  Instruction::CallBr,
4127  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4128  InsertAtEnd) {
4129  init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4130 }
4131 
4132 //===----------------------------------------------------------------------===//
4133 // ResumeInst Class
4134 //===----------------------------------------------------------------------===//
4135 
4136 //===---------------------------------------------------------------------------
4137 /// Resume the propagation of an exception.
4138 ///
4139 class ResumeInst : public Instruction {
4140  ResumeInst(const ResumeInst &RI);
4141 
4142  explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4143  ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4144 
4145 protected:
4146  // Note: Instruction needs to be a friend here to call cloneImpl.
4147  friend class Instruction;
4148 
4149  ResumeInst *cloneImpl() const;
4150 
4151 public:
4152  static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4153  return new(1) ResumeInst(Exn, InsertBefore);
4154  }
4155 
4156  static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4157  return new(1) ResumeInst(Exn, InsertAtEnd);
4158  }
4159 
4160  /// Provide fast operand accessors
4162 
4163  /// Convenience accessor.
4164  Value *getValue() const { return Op<0>(); }
4165 
4166  unsigned getNumSuccessors() const { return 0; }
4167 
4168  // Methods for support type inquiry through isa, cast, and dyn_cast:
4169  static bool classof(const Instruction *I) {
4170  return I->getOpcode() == Instruction::Resume;
4171  }
4172  static bool classof(const Value *V) {
4173  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4174  }
4175 
4176 private:
4177  BasicBlock *getSuccessor(unsigned idx) const {
4178  llvm_unreachable("ResumeInst has no successors!");
4179  }
4180 
4181  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4182  llvm_unreachable("ResumeInst has no successors!");
4183  }
4184 };
4185 
4186 template <>
4188  public FixedNumOperandTraits<ResumeInst, 1> {
4189 };
4190 
4191 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4192 
4193 //===----------------------------------------------------------------------===//
4194 // CatchSwitchInst Class
4195 //===----------------------------------------------------------------------===//
4197  /// The number of operands actually allocated. NumOperands is
4198  /// the number actually in use.
4199  unsigned ReservedSpace;
4200 
4201  // Operand[0] = Outer scope
4202  // Operand[1] = Unwind block destination
4203  // Operand[n] = BasicBlock to go to on match
4204  CatchSwitchInst(const CatchSwitchInst &CSI);
4205 
4206  /// Create a new switch instruction, specifying a
4207  /// default destination. The number of additional handlers can be specified
4208  /// here to make memory allocation more efficient.
4209  /// This constructor can also autoinsert before another instruction.
4210  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4211  unsigned NumHandlers, const Twine &NameStr,
4212  Instruction *InsertBefore);
4213 
4214  /// Create a new switch instruction, specifying a
4215  /// default destination. The number of additional handlers can be specified
4216  /// here to make memory allocation more efficient.
4217  /// This constructor also autoinserts at the end of the specified BasicBlock.
4218  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4219  unsigned NumHandlers, const Twine &NameStr,
4220  BasicBlock *InsertAtEnd);
4221 
4222  // allocate space for exactly zero operands
4223  void *operator new(size_t s) { return User::operator new(s); }
4224 
4225  void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4226  void growOperands(unsigned Size);
4227 
4228 protected:
4229  // Note: Instruction needs to be a friend here to call cloneImpl.
4230  friend class Instruction;
4231 
4232  CatchSwitchInst *cloneImpl() const;
4233 
4234 public:
4235  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4236  unsigned NumHandlers,
4237  const Twine &NameStr = "",
4238  Instruction *InsertBefore = nullptr) {
4239  return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4240  InsertBefore);
4241  }
4242 
4243  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4244  unsigned NumHandlers, const Twine &NameStr,
4245  BasicBlock *InsertAtEnd) {
4246  return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4247  InsertAtEnd);
4248  }
4249 
4250  /// Provide fast operand accessors
4252 
4253  // Accessor Methods for CatchSwitch stmt
4254  Value *getParentPad() const { return getOperand(0); }
4255  void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4256 
4257  // Accessor Methods for CatchSwitch stmt
4258  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4259  bool unwindsToCaller() const { return !hasUnwindDest(); }
4261  if (hasUnwindDest())
4262  return cast<BasicBlock>(getOperand(1));
4263  return nullptr;
4264  }
4265  void setUnwindDest(BasicBlock *UnwindDest) {
4266  assert(UnwindDest);
4267  assert(hasUnwindDest());
4268  setOperand(1, UnwindDest);
4269  }
4270 
4271  /// return the number of 'handlers' in this catchswitch
4272  /// instruction, except the default handler
4273  unsigned getNumHandlers() const {
4274  if (hasUnwindDest())
4275  return getNumOperands() - 2;
4276  return getNumOperands() - 1;
4277  }
4278 
4279 private:
4280  static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4281  static const BasicBlock *handler_helper(const Value *V) {
4282  return cast<BasicBlock>(V);
4283  }
4284 
4285 public:
4286  using DerefFnTy = BasicBlock *(*)(Value *);
4289  using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4290  using const_handler_iterator =
4293 
4294  /// Returns an iterator that points to the first handler in CatchSwitchInst.
4296  op_iterator It = op_begin() + 1;
4297  if (hasUnwindDest())
4298  ++It;
4299  return handler_iterator(It, DerefFnTy(handler_helper));
4300  }
4301 
4302  /// Returns an iterator that points to the first handler in the
4303  /// CatchSwitchInst.
4304  const_handler_iterator handler_begin() const {
4305  const_op_iterator It = op_begin() + 1;
4306  if (hasUnwindDest())
4307  ++It;
4308  return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4309  }
4310 
4311  /// Returns a read-only iterator that points one past the last
4312  /// handler in the CatchSwitchInst.
4314  return handler_iterator(op_end(), DerefFnTy(handler_helper));
4315  }
4316 
4317  /// Returns an iterator that points one past the last handler in the
4318  /// CatchSwitchInst.
4319  const_handler_iterator handler_end() const {
4320  return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4321  }
4322 
4323  /// iteration adapter for range-for loops.
4325  return make_range(handler_begin(), handler_end());
4326  }
4327 
4328  /// iteration adapter for range-for loops.
4330  return make_range(handler_begin(), handler_end());
4331  }
4332 
4333  /// Add an entry to the switch instruction...
4334  /// Note:
4335  /// This action invalidates handler_end(). Old handler_end() iterator will
4336  /// point to the added handler.
4337  void addHandler(BasicBlock *Dest);
4338 
4339  void removeHandler(handler_iterator HI);
4340 
4341  unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4342  BasicBlock *getSuccessor(unsigned Idx) const {
4343  assert(Idx < getNumSuccessors() &&
4344  "Successor # out of range for catchswitch!");
4345  return cast<BasicBlock>(getOperand(Idx + 1));
4346  }
4347  void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4348  assert(Idx < getNumSuccessors() &&
4349  "Successor # out of range for catchswitch!");
4350  setOperand(Idx + 1, NewSucc);
4351  }
4352 
4353  // Methods for support type inquiry through isa, cast, and dyn_cast:
4354  static bool classof(const Instruction *I) {
4355  return I->getOpcode() == Instruction::CatchSwitch;
4356  }
4357  static bool classof(const Value *V) {
4358  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4359  }
4360 };
4361 
4362 template <>
4364 
4365 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4366 
4367 //===----------------------------------------------------------------------===//
4368 // CleanupPadInst Class
4369 //===----------------------------------------------------------------------===//
4371 private:
4372  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4373  unsigned Values, const Twine &NameStr,
4374  Instruction *InsertBefore)
4375  : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4376  NameStr, InsertBefore) {}
4377  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4378  unsigned Values, const Twine &NameStr,
4379  BasicBlock *InsertAtEnd)
4380  : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4381  NameStr, InsertAtEnd) {}
4382 
4383 public:
4384  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4385  const Twine &NameStr = "",
4386  Instruction *InsertBefore = nullptr) {
4387  unsigned Values = 1 + Args.size();
4388  return new (Values)
4389  CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4390  }
4391 
4392  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4393  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4394  unsigned Values = 1 + Args.size();
4395  return new (Values)
4396  CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4397  }
4398 
4399  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4400  static bool classof(const Instruction *I) {
4401  return I->getOpcode() == Instruction::CleanupPad;
4402  }
4403  static bool classof(const Value *V) {
4404  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4405  }
4406 };
4407 
4408 //===----------------------------------------------------------------------===//
4409 // CatchPadInst Class
4410 //===----------------------------------------------------------------------===//
4412 private:
4413  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4414  unsigned Values, const Twine &NameStr,
4415  Instruction *InsertBefore)
4416  : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4417  NameStr, InsertBefore) {}
4418  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4419  unsigned Values, const Twine &NameStr,
4420  BasicBlock *InsertAtEnd)
4421  : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4422  NameStr, InsertAtEnd) {}
4423 
4424 public:
4425  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4426  const Twine &NameStr = "",
4427  Instruction *InsertBefore = nullptr) {
4428  unsigned Values = 1 + Args.size();
4429  return new (Values)
4430  CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4431  }
4432 
4433  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4434  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4435  unsigned Values = 1 + Args.size();
4436  return new (Values)
4437  CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4438  }
4439 
4440  /// Convenience accessors
4441  CatchSwitchInst *getCatchSwitch() const {
4442  return cast<CatchSwitchInst>(Op<-1>());
4443  }
4444  void setCatchSwitch(Value *CatchSwitch) {
4445  assert(CatchSwitch);
4446  Op<-1>() = CatchSwitch;
4447  }
4448 
4449  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4450  static bool classof(const Instruction *I) {
4451  return I->getOpcode() == Instruction::CatchPad;
4452  }
4453  static bool classof(const Value *V) {
4454  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4455  }
4456 };
4457 
4458 //===----------------------------------------------------------------------===//
4459 // CatchReturnInst Class
4460 //===----------------------------------------------------------------------===//
4461 
4463  CatchReturnInst(const CatchReturnInst &RI);
4464  CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4465  CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4466 
4467  void init(Value *CatchPad, BasicBlock *BB);
4468 
4469 protected:
4470  // Note: Instruction needs to be a friend here to call cloneImpl.
4471  friend class Instruction;
4472 
4473  CatchReturnInst *cloneImpl() const;
4474 
4475 public:
4476  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4477  Instruction *InsertBefore = nullptr) {
4478  assert(CatchPad);
4479  assert(BB);
4480  return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4481  }
4482 
4483  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4484  BasicBlock *InsertAtEnd) {
4485  assert(CatchPad);
4486  assert(BB);
4487  return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4488  }
4489 
4490  /// Provide fast operand accessors
4492 
4493  /// Convenience accessors.
4494  CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4495  void setCatchPad(CatchPadInst *CatchPad) {
4496  assert(CatchPad);
4497  Op<0>() = CatchPad;
4498  }
4499 
4500  BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4501  void setSuccessor(BasicBlock *NewSucc) {
4502  assert(NewSucc);
4503  Op<1>() = NewSucc;
4504  }
4505  unsigned getNumSuccessors() const { return 1; }
4506 
4507  /// Get the parentPad of this catchret's catchpad's catchswitch.
4508  /// The successor block is implicitly a member of this funclet.
4509  Value *getCatchSwitchParentPad() const {
4510  return getCatchPad()->getCatchSwitch()->getParentPad();
4511  }
4512 
4513  // Methods for support type inquiry through isa, cast, and dyn_cast:
4514  static bool classof(const Instruction *I) {
4515  return (I->getOpcode() == Instruction::CatchRet);
4516  }
4517  static bool classof(const Value *V) {
4518  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4519  }
4520 
4521 private:
4522  BasicBlock *getSuccessor(unsigned Idx) const {
4523  assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4524  return getSuccessor();
4525  }
4526 
4527  void setSuccessor(unsigned Idx, BasicBlock *B) {
4528  assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4529  setSuccessor(B);
4530  }
4531 };
4532 
4533 template <>
4535  : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4536 
4537 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4538 
4539 //===----------------------------------------------------------------------===//
4540 // CleanupReturnInst Class
4541 //===----------------------------------------------------------------------===//
4542 
4544 private:
4546  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4547  Instruction *InsertBefore = nullptr);
4548  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4549  BasicBlock *InsertAtEnd);
4550 
4551  void init(Value *CleanupPad, BasicBlock *UnwindBB);
4552 
4553 protected:
4554  // Note: Instruction needs to be a friend here to call cloneImpl.
4555  friend class Instruction;
4556 
4557  CleanupReturnInst *cloneImpl() const;
4558 
4559 public:
4560  static CleanupReturnInst *Create(Value *CleanupPad,
4561  BasicBlock *UnwindBB = nullptr,
4562  Instruction *InsertBefore = nullptr) {
4563  assert(CleanupPad);
4564  unsigned Values = 1;
4565  if (UnwindBB)
4566  ++Values;
4567  return new (Values)
4568  CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4569  }
4570 
4571  static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4572  BasicBlock *InsertAtEnd) {
4573  assert(CleanupPad);
4574  unsigned Values = 1;
4575  if (UnwindBB)
4576  ++Values;
4577  return new (Values)
4578  CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4579  }
4580 
4581  /// Provide fast operand accessors
4583 
4584  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4585  bool unwindsToCaller() const { return !hasUnwindDest(); }
4586 
4587  /// Convenience accessor.
4589  return cast<CleanupPadInst>(Op<0>());
4590  }
4591  void setCleanupPad(CleanupPadInst *CleanupPad) {
4592  assert(CleanupPad);
4593  Op<0>() = CleanupPad;
4594  }
4595 
4596  unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4597 
4599  return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4600  }
4601  void setUnwindDest(BasicBlock *NewDest) {
4602  assert(NewDest);
4603  assert(hasUnwindDest());
4604  Op<1>() = NewDest;
4605  }
4606 
4607  // Methods for support type inquiry through isa, cast, and dyn_cast:
4608  static bool classof(const Instruction *I) {
4609  return (I->getOpcode() == Instruction::CleanupRet);
4610  }
4611  static bool classof(const Value *V) {
4612  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4613  }
4614 
4615 private:
4616  BasicBlock *getSuccessor(unsigned Idx) const {
4617  assert(Idx == 0);
4618  return getUnwindDest();
4619  }
4620 
4621  void setSuccessor(unsigned Idx, BasicBlock *B) {
4622  assert(Idx == 0);
4623  setUnwindDest(B);
4624  }
4625 
4626  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4627  // method so that subclasses cannot accidentally use it.
4628  void setInstructionSubclassData(unsigned short D) {
4630  }
4631 };
4632 
4633 template <>
4635  : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4636 
4637 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4638 
4639 //===----------------------------------------------------------------------===//
4640 // UnreachableInst Class
4641 //===----------------------------------------------------------------------===//
4642 
4643 //===---------------------------------------------------------------------------
4644 /// This function has undefined behavior. In particular, the
4645 /// presence of this instruction indicates some higher level knowledge that the
4646 /// end of the block cannot be reached.
4647 ///
4649 protected:
4650  // Note: Instruction needs to be a friend here to call cloneImpl.
4651  friend class Instruction;
4652 
4653  UnreachableInst *cloneImpl() const;
4654 
4655 public:
4656  explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4657  explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4658 
4659  // allocate space for exactly zero operands
4660  void *operator new(size_t s) {
4661  return User::operator new(s, 0);
4662  }
4663 
4664  unsigned getNumSuccessors() const { return 0; }
4665 
4666  // Methods for support type inquiry through isa, cast, and dyn_cast:
4667  static bool classof(const Instruction *I) {
4668  return I->getOpcode() == Instruction::Unreachable;
4669  }
4670  static bool classof(const Value *V) {
4671  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4672  }
4673 
4674 private:
4675  BasicBlock *getSuccessor(unsigned idx) const {
4676  llvm_unreachable("UnreachableInst has no successors!");
4677  }
4678 
4679  void setSuccessor(unsigned idx, BasicBlock *B) {
4680  llvm_unreachable("UnreachableInst has no successors!");
4681  }
4682 };
4683 
4684 //===----------------------------------------------------------------------===//
4685 // TruncInst Class
4686 //===----------------------------------------------------------------------===//
4687 
4688 /// This class represents a truncation of integer types.
4689 class TruncInst : public CastInst {
4690 protected:
4691  // Note: Instruction needs to be a friend here to call cloneImpl.
4692  friend class Instruction;
4693 
4694  /// Clone an identical TruncInst
4695  TruncInst *cloneImpl() const;
4696 
4697 public:
4698  /// Constructor with insert-before-instruction semantics
4699  TruncInst(
4700  Value *S, ///< The value to be truncated
4701  Type *Ty, ///< The (smaller) type to truncate to
4702  const Twine &NameStr = "", ///< A name for the new instruction
4703  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4704  );
4705 
4706  /// Constructor with insert-at-end-of-block semantics
4707  TruncInst(
4708  Value *S, ///< The value to be truncated
4709  Type *Ty, ///< The (smaller) type to truncate to
4710  const Twine &NameStr, ///< A name for the new instruction
4711  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4712  );
4713 
4714  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4715  static bool classof(const Instruction *I) {
4716  return I->getOpcode() == Trunc;
4717  }
4718  static bool classof(const Value *V) {
4719  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4720  }
4721 };
4722 
4723 //===----------------------------------------------------------------------===//
4724 // ZExtInst Class
4725 //===----------------------------------------------------------------------===//
4726 
4727 /// This class represents zero extension of integer types.
4728 class ZExtInst : public CastInst {
4729 protected:
4730  // Note: Instruction needs to be a friend here to call cloneImpl.
4731  friend class Instruction;
4732 
4733  /// Clone an identical ZExtInst
4734  ZExtInst *cloneImpl() const;
4735 
4736 public:
4737  /// Constructor with insert-before-instruction semantics
4738  ZExtInst(
4739  Value *S, ///< The value to be zero extended
4740  Type *Ty, ///< The type to zero extend to
4741  const Twine &NameStr = "", ///< A name for the new instruction
4742  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4743  );
4744 
4745  /// Constructor with insert-at-end semantics.
4746  ZExtInst(
4747  Value *S, ///< The value to be zero extended
4748  Type *Ty, ///< The type to zero extend to
4749  const Twine &NameStr, ///< A name for the new instruction
4750  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4751  );
4752 
4753  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4754  static bool classof(const Instruction *I) {
4755  return I->getOpcode() == ZExt;
4756  }
4757  static bool classof(const Value *V) {
4758  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4759  }
4760 };
4761 
4762 //===----------------------------------------------------------------------===//
4763 // SExtInst Class
4764 //===----------------------------------------------------------------------===//
4765 
4766 /// This class represents a sign extension of integer types.
4767 class SExtInst : public CastInst {
4768 protected:
4769  // Note: Instruction needs to be a friend here to call cloneImpl.
4770  friend class Instruction;
4771 
4772  /// Clone an identical SExtInst
4773  SExtInst *cloneImpl() const;
4774 
4775 public:
4776  /// Constructor with insert-before-instruction semantics
4777  SExtInst(
4778  Value *S, ///< The value to be sign extended
4779  Type *Ty, ///< The type to sign extend to
4780  const Twine &NameStr = "", ///< A name for the new instruction
4781  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4782  );
4783 
4784  /// Constructor with insert-at-end-of-block semantics
4785  SExtInst(
4786  Value *S, ///< The value to be sign extended
4787  Type *Ty, ///< The type to sign extend to
4788  const Twine &NameStr, ///< A name for the new instruction
4789  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4790  );
4791 
4792  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4793  static bool classof(const Instruction *I) {
4794  return I->getOpcode() == SExt;
4795  }
4796  static bool classof(const Value *V) {
4797  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4798  }
4799 };
4800 
4801 //===----------------------------------------------------------------------===//
4802 // FPTruncInst Class
4803 //===----------------------------------------------------------------------===//
4804 
4805 /// This class represents a truncation of floating point types.
4806 class FPTruncInst : public CastInst {
4807 protected:
4808  // Note: Instruction needs to be a friend here to call cloneImpl.
4809  friend class Instruction;
4810 
4811  /// Clone an identical FPTruncInst
4812  FPTruncInst *cloneImpl() const;
4813 
4814 public:
4815  /// Constructor with insert-before-instruction semantics
4816  FPTruncInst(
4817  Value *S, ///< The value to be truncated
4818  Type *Ty, ///< The type to truncate to
4819  const Twine &NameStr = "", ///< A name for the new instruction
4820  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4821  );
4822 
4823  /// Constructor with insert-before-instruction semantics
4824  FPTruncInst(
4825  Value *S, ///< The value to be truncated
4826  Type *Ty, ///< The type to truncate to
4827  const Twine &NameStr, ///< A name for the new instruction
4828  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4829  );
4830 
4831  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4832  static bool classof(const Instruction *I) {
4833  return I->getOpcode() == FPTrunc;
4834  }
4835  static bool classof(const Value *V) {
4836  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4837  }
4838 };
4839 
4840 //===----------------------------------------------------------------------===//
4841 // FPExtInst Class
4842 //===----------------------------------------------------------------------===//
4843 
4844 /// This class represents an extension of floating point types.
4845 class FPExtInst : public CastInst {
4846 protected:
4847  // Note: Instruction needs to be a friend here to call cloneImpl.
4848  friend class Instruction;
4849 
4850  /// Clone an identical FPExtInst
4851  FPExtInst *cloneImpl() const;
4852 
4853 public:
4854  /// Constructor with insert-before-instruction semantics
4855  FPExtInst(
4856  Value *S, ///< The value to be extended
4857  Type *Ty, ///< The type to extend to
4858  const Twine &NameStr = "", ///< A name for the new instruction
4859  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4860  );
4861 
4862  /// Constructor with insert-at-end-of-block semantics
4863  FPExtInst(
4864  Value *S, ///< The value to be extended
4865  Type *Ty, ///< The type to extend to
4866  const Twine &NameStr, ///< A name for the new instruction
4867  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4868  );
4869 
4870  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4871  static bool classof(const Instruction *I) {
4872  return I->getOpcode() == FPExt;
4873  }
4874  static bool classof(const Value *V) {
4875  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4876  }
4877 };
4878 
4879 //===----------------------------------------------------------------------===//
4880 // UIToFPInst Class
4881 //===----------------------------------------------------------------------===//
4882 
4883 /// This class represents a cast unsigned integer to floating point.
4884 class UIToFPInst : public CastInst {
4885 protected:
4886  // Note: Instruction needs to be a friend here to call cloneImpl.
4887  friend class Instruction;
4888 
4889  /// Clone an identical UIToFPInst
4890  UIToFPInst *cloneImpl() const;
4891 
4892 public:
4893  /// Constructor with insert-before-instruction semantics
4894  UIToFPInst(
4895  Value *S, ///< The value to be converted
4896  Type *Ty, ///< The type to convert to
4897  const Twine &NameStr = "", ///< A name for the new instruction
4898  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4899  );
4900 
4901  /// Constructor with insert-at-end-of-block semantics
4902