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