]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/InstrTypes.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303571, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / IR / InstrTypes.h
1 //===- llvm/InstrTypes.h - Important Instruction subclasses -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines various meta classes of instructions that exist in the VM
11 // representation.  Specific concrete subclasses of these may be found in the
12 // i*.h files...
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_IR_INSTRTYPES_H
17 #define LLVM_IR_INSTRTYPES_H
18
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/OperandTraits.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/User.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstddef>
40 #include <cstdint>
41 #include <iterator>
42 #include <string>
43 #include <vector>
44
45 namespace llvm {
46
47 //===----------------------------------------------------------------------===//
48 //                            TerminatorInst Class
49 //===----------------------------------------------------------------------===//
50
51 /// Subclasses of this class are all able to terminate a basic
52 /// block. Thus, these are all the flow control type of operations.
53 ///
54 class TerminatorInst : public Instruction {
55 protected:
56   TerminatorInst(Type *Ty, Instruction::TermOps iType,
57                  Use *Ops, unsigned NumOps,
58                  Instruction *InsertBefore = nullptr)
59     : Instruction(Ty, iType, Ops, NumOps, InsertBefore) {}
60
61   TerminatorInst(Type *Ty, Instruction::TermOps iType,
62                  Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd)
63     : Instruction(Ty, iType, Ops, NumOps, InsertAtEnd) {}
64
65 public:
66   /// Return the number of successors that this terminator has.
67   unsigned getNumSuccessors() const;
68
69   /// Return the specified successor.
70   BasicBlock *getSuccessor(unsigned idx) const;
71
72   /// Update the specified successor to point at the provided block.
73   void setSuccessor(unsigned idx, BasicBlock *B);
74
75   // Methods for support type inquiry through isa, cast, and dyn_cast:
76   static inline bool classof(const Instruction *I) {
77     return I->isTerminator();
78   }
79   static inline bool classof(const Value *V) {
80     return isa<Instruction>(V) && classof(cast<Instruction>(V));
81   }
82
83   // \brief Returns true if this terminator relates to exception handling.
84   bool isExceptional() const {
85     switch (getOpcode()) {
86     case Instruction::CatchSwitch:
87     case Instruction::CatchRet:
88     case Instruction::CleanupRet:
89     case Instruction::Invoke:
90     case Instruction::Resume:
91       return true;
92     default:
93       return false;
94     }
95   }
96
97   //===--------------------------------------------------------------------===//
98   // succ_iterator definition
99   //===--------------------------------------------------------------------===//
100
101   template <class Term, class BB> // Successor Iterator
102   class SuccIterator : public std::iterator<std::random_access_iterator_tag, BB,
103                                             int, BB *, BB *> {
104     using super =
105         std::iterator<std::random_access_iterator_tag, BB, int, BB *, BB *>;
106
107   public:
108     using pointer = typename super::pointer;
109     using reference = typename super::reference;
110
111   private:
112     Term TermInst;
113     unsigned idx;
114     using Self = SuccIterator<Term, BB>;
115
116     inline bool index_is_valid(unsigned idx) {
117       return idx < TermInst->getNumSuccessors();
118     }
119
120     /// \brief Proxy object to allow write access in operator[]
121     class SuccessorProxy {
122       Self it;
123
124     public:
125       explicit SuccessorProxy(const Self &it) : it(it) {}
126
127       SuccessorProxy(const SuccessorProxy &) = default;
128
129       SuccessorProxy &operator=(SuccessorProxy r) {
130         *this = reference(r);
131         return *this;
132       }
133
134       SuccessorProxy &operator=(reference r) {
135         it.TermInst->setSuccessor(it.idx, r);
136         return *this;
137       }
138
139       operator reference() const { return *it; }
140     };
141
142   public:
143     // begin iterator
144     explicit inline SuccIterator(Term T) : TermInst(T), idx(0) {}
145     // end iterator
146     inline SuccIterator(Term T, bool) : TermInst(T) {
147       if (TermInst)
148         idx = TermInst->getNumSuccessors();
149       else
150         // Term == NULL happens, if a basic block is not fully constructed and
151         // consequently getTerminator() returns NULL. In this case we construct
152         // a SuccIterator which describes a basic block that has zero
153         // successors.
154         // Defining SuccIterator for incomplete and malformed CFGs is especially
155         // useful for debugging.
156         idx = 0;
157     }
158
159     /// This is used to interface between code that wants to
160     /// operate on terminator instructions directly.
161     unsigned getSuccessorIndex() const { return idx; }
162
163     inline bool operator==(const Self &x) const { return idx == x.idx; }
164     inline bool operator!=(const Self &x) const { return !operator==(x); }
165
166     inline reference operator*() const { return TermInst->getSuccessor(idx); }
167     inline pointer operator->() const { return operator*(); }
168
169     inline Self &operator++() {
170       ++idx;
171       return *this;
172     } // Preincrement
173
174     inline Self operator++(int) { // Postincrement
175       Self tmp = *this;
176       ++*this;
177       return tmp;
178     }
179
180     inline Self &operator--() {
181       --idx;
182       return *this;
183     }                             // Predecrement
184     inline Self operator--(int) { // Postdecrement
185       Self tmp = *this;
186       --*this;
187       return tmp;
188     }
189
190     inline bool operator<(const Self &x) const {
191       assert(TermInst == x.TermInst &&
192              "Cannot compare iterators of different blocks!");
193       return idx < x.idx;
194     }
195
196     inline bool operator<=(const Self &x) const {
197       assert(TermInst == x.TermInst &&
198              "Cannot compare iterators of different blocks!");
199       return idx <= x.idx;
200     }
201     inline bool operator>=(const Self &x) const {
202       assert(TermInst == x.TermInst &&
203              "Cannot compare iterators of different blocks!");
204       return idx >= x.idx;
205     }
206
207     inline bool operator>(const Self &x) const {
208       assert(TermInst == x.TermInst &&
209              "Cannot compare iterators of different blocks!");
210       return idx > x.idx;
211     }
212
213     inline Self &operator+=(int Right) {
214       unsigned new_idx = idx + Right;
215       assert(index_is_valid(new_idx) && "Iterator index out of bound");
216       idx = new_idx;
217       return *this;
218     }
219
220     inline Self operator+(int Right) const {
221       Self tmp = *this;
222       tmp += Right;
223       return tmp;
224     }
225
226     inline Self &operator-=(int Right) { return operator+=(-Right); }
227
228     inline Self operator-(int Right) const { return operator+(-Right); }
229
230     inline int operator-(const Self &x) const {
231       assert(TermInst == x.TermInst &&
232              "Cannot work on iterators of different blocks!");
233       int distance = idx - x.idx;
234       return distance;
235     }
236
237     inline SuccessorProxy operator[](int offset) {
238       Self tmp = *this;
239       tmp += offset;
240       return SuccessorProxy(tmp);
241     }
242
243     /// Get the source BB of this iterator.
244     inline BB *getSource() {
245       assert(TermInst && "Source not available, if basic block was malformed");
246       return TermInst->getParent();
247     }
248   };
249
250   using succ_iterator = SuccIterator<TerminatorInst *, BasicBlock>;
251   using succ_const_iterator =
252       SuccIterator<const TerminatorInst *, const BasicBlock>;
253   using succ_range = iterator_range<succ_iterator>;
254   using succ_const_range = iterator_range<succ_const_iterator>;
255
256 private:
257   inline succ_iterator succ_begin() { return succ_iterator(this); }
258   inline succ_const_iterator succ_begin() const {
259     return succ_const_iterator(this);
260   }
261   inline succ_iterator succ_end() { return succ_iterator(this, true); }
262   inline succ_const_iterator succ_end() const {
263     return succ_const_iterator(this, true);
264   }
265
266 public:
267   inline succ_range successors() {
268     return succ_range(succ_begin(), succ_end());
269   }
270   inline succ_const_range successors() const {
271     return succ_const_range(succ_begin(), succ_end());
272   }
273 };
274
275 //===----------------------------------------------------------------------===//
276 //                          UnaryInstruction Class
277 //===----------------------------------------------------------------------===//
278
279 class UnaryInstruction : public Instruction {
280 protected:
281   UnaryInstruction(Type *Ty, unsigned iType, Value *V,
282                    Instruction *IB = nullptr)
283     : Instruction(Ty, iType, &Op<0>(), 1, IB) {
284     Op<0>() = V;
285   }
286   UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
287     : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
288     Op<0>() = V;
289   }
290
291 public:
292   // allocate space for exactly one operand
293   void *operator new(size_t s) {
294     return User::operator new(s, 1);
295   }
296
297   void *operator new(size_t, unsigned) = delete;
298
299   /// Transparently provide more efficient getOperand methods.
300   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
301
302   // Methods for support type inquiry through isa, cast, and dyn_cast:
303   static inline bool classof(const Instruction *I) {
304     return I->getOpcode() == Instruction::Alloca ||
305            I->getOpcode() == Instruction::Load ||
306            I->getOpcode() == Instruction::VAArg ||
307            I->getOpcode() == Instruction::ExtractValue ||
308            (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
309   }
310   static inline bool classof(const Value *V) {
311     return isa<Instruction>(V) && classof(cast<Instruction>(V));
312   }
313 };
314
315 template <>
316 struct OperandTraits<UnaryInstruction> :
317   public FixedNumOperandTraits<UnaryInstruction, 1> {
318 };
319
320 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
321
322 //===----------------------------------------------------------------------===//
323 //                           BinaryOperator Class
324 //===----------------------------------------------------------------------===//
325
326 class BinaryOperator : public Instruction {
327 protected:
328   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
329                  const Twine &Name, Instruction *InsertBefore);
330   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
331                  const Twine &Name, BasicBlock *InsertAtEnd);
332
333   void init(BinaryOps iType);
334
335   // Note: Instruction needs to be a friend here to call cloneImpl.
336   friend class Instruction;
337
338   BinaryOperator *cloneImpl() const;
339
340 public:
341   // allocate space for exactly two operands
342   void *operator new(size_t s) {
343     return User::operator new(s, 2);
344   }
345
346   void *operator new(size_t, unsigned) = delete;
347
348   /// Transparently provide more efficient getOperand methods.
349   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
350
351   /// Construct a binary instruction, given the opcode and the two
352   /// operands.  Optionally (if InstBefore is specified) insert the instruction
353   /// into a BasicBlock right before the specified instruction.  The specified
354   /// Instruction is allowed to be a dereferenced end iterator.
355   ///
356   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
357                                 const Twine &Name = Twine(),
358                                 Instruction *InsertBefore = nullptr);
359
360   /// Construct a binary instruction, given the opcode and the two
361   /// operands.  Also automatically insert this instruction to the end of the
362   /// BasicBlock specified.
363   ///
364   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
365                                 const Twine &Name, BasicBlock *InsertAtEnd);
366
367   /// These methods just forward to Create, and are useful when you
368   /// statically know what type of instruction you're going to create.  These
369   /// helpers just save some typing.
370 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
371   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
372                                      const Twine &Name = "") {\
373     return Create(Instruction::OPC, V1, V2, Name);\
374   }
375 #include "llvm/IR/Instruction.def"
376 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
377   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
378                                      const Twine &Name, BasicBlock *BB) {\
379     return Create(Instruction::OPC, V1, V2, Name, BB);\
380   }
381 #include "llvm/IR/Instruction.def"
382 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
383   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
384                                      const Twine &Name, Instruction *I) {\
385     return Create(Instruction::OPC, V1, V2, Name, I);\
386   }
387 #include "llvm/IR/Instruction.def"
388
389   static BinaryOperator *CreateWithCopiedFlags(BinaryOps Opc,
390                                                Value *V1, Value *V2,
391                                                BinaryOperator *CopyBO,
392                                                const Twine &Name = "") {
393     BinaryOperator *BO = Create(Opc, V1, V2, Name);
394     BO->copyIRFlags(CopyBO);
395     return BO;
396   }
397
398   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
399                                    const Twine &Name = "") {
400     BinaryOperator *BO = Create(Opc, V1, V2, Name);
401     BO->setHasNoSignedWrap(true);
402     return BO;
403   }
404   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
405                                    const Twine &Name, BasicBlock *BB) {
406     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
407     BO->setHasNoSignedWrap(true);
408     return BO;
409   }
410   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
411                                    const Twine &Name, Instruction *I) {
412     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
413     BO->setHasNoSignedWrap(true);
414     return BO;
415   }
416
417   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
418                                    const Twine &Name = "") {
419     BinaryOperator *BO = Create(Opc, V1, V2, Name);
420     BO->setHasNoUnsignedWrap(true);
421     return BO;
422   }
423   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
424                                    const Twine &Name, BasicBlock *BB) {
425     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
426     BO->setHasNoUnsignedWrap(true);
427     return BO;
428   }
429   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
430                                    const Twine &Name, Instruction *I) {
431     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
432     BO->setHasNoUnsignedWrap(true);
433     return BO;
434   }
435
436   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
437                                      const Twine &Name = "") {
438     BinaryOperator *BO = Create(Opc, V1, V2, Name);
439     BO->setIsExact(true);
440     return BO;
441   }
442   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
443                                      const Twine &Name, BasicBlock *BB) {
444     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
445     BO->setIsExact(true);
446     return BO;
447   }
448   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
449                                      const Twine &Name, Instruction *I) {
450     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
451     BO->setIsExact(true);
452     return BO;
453   }
454
455 #define DEFINE_HELPERS(OPC, NUWNSWEXACT)                                       \
456   static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2,        \
457                                                   const Twine &Name = "") {    \
458     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name);                \
459   }                                                                            \
460   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
461       Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) {               \
462     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB);            \
463   }                                                                            \
464   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
465       Value *V1, Value *V2, const Twine &Name, Instruction *I) {               \
466     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I);             \
467   }
468
469   DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
470   DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
471   DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
472   DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
473   DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
474   DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
475   DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
476   DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
477
478   DEFINE_HELPERS(SDiv, Exact)  // CreateExactSDiv
479   DEFINE_HELPERS(UDiv, Exact)  // CreateExactUDiv
480   DEFINE_HELPERS(AShr, Exact)  // CreateExactAShr
481   DEFINE_HELPERS(LShr, Exact)  // CreateExactLShr
482
483 #undef DEFINE_HELPERS
484
485   /// Helper functions to construct and inspect unary operations (NEG and NOT)
486   /// via binary operators SUB and XOR:
487   ///
488   /// Create the NEG and NOT instructions out of SUB and XOR instructions.
489   ///
490   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
491                                    Instruction *InsertBefore = nullptr);
492   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
493                                    BasicBlock *InsertAtEnd);
494   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
495                                       Instruction *InsertBefore = nullptr);
496   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
497                                       BasicBlock *InsertAtEnd);
498   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
499                                       Instruction *InsertBefore = nullptr);
500   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
501                                       BasicBlock *InsertAtEnd);
502   static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
503                                     Instruction *InsertBefore = nullptr);
504   static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
505                                     BasicBlock *InsertAtEnd);
506   static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
507                                    Instruction *InsertBefore = nullptr);
508   static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
509                                    BasicBlock *InsertAtEnd);
510
511   /// Check if the given Value is a NEG, FNeg, or NOT instruction.
512   ///
513   static bool isNeg(const Value *V);
514   static bool isFNeg(const Value *V, bool IgnoreZeroSign=false);
515   static bool isNot(const Value *V);
516
517   /// Helper functions to extract the unary argument of a NEG, FNEG or NOT
518   /// operation implemented via Sub, FSub, or Xor.
519   ///
520   static const Value *getNegArgument(const Value *BinOp);
521   static       Value *getNegArgument(      Value *BinOp);
522   static const Value *getFNegArgument(const Value *BinOp);
523   static       Value *getFNegArgument(      Value *BinOp);
524   static const Value *getNotArgument(const Value *BinOp);
525   static       Value *getNotArgument(      Value *BinOp);
526
527   BinaryOps getOpcode() const {
528     return static_cast<BinaryOps>(Instruction::getOpcode());
529   }
530
531   /// Exchange the two operands to this instruction.
532   /// This instruction is safe to use on any binary instruction and
533   /// does not modify the semantics of the instruction.  If the instruction
534   /// cannot be reversed (ie, it's a Div), then return true.
535   ///
536   bool swapOperands();
537
538   // Methods for support type inquiry through isa, cast, and dyn_cast:
539   static inline bool classof(const Instruction *I) {
540     return I->isBinaryOp();
541   }
542   static inline bool classof(const Value *V) {
543     return isa<Instruction>(V) && classof(cast<Instruction>(V));
544   }
545 };
546
547 template <>
548 struct OperandTraits<BinaryOperator> :
549   public FixedNumOperandTraits<BinaryOperator, 2> {
550 };
551
552 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
553
554 //===----------------------------------------------------------------------===//
555 //                               CastInst Class
556 //===----------------------------------------------------------------------===//
557
558 /// This is the base class for all instructions that perform data
559 /// casts. It is simply provided so that instruction category testing
560 /// can be performed with code like:
561 ///
562 /// if (isa<CastInst>(Instr)) { ... }
563 /// @brief Base class of casting instructions.
564 class CastInst : public UnaryInstruction {
565 protected:
566   /// @brief Constructor with insert-before-instruction semantics for subclasses
567   CastInst(Type *Ty, unsigned iType, Value *S,
568            const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
569     : UnaryInstruction(Ty, iType, S, InsertBefore) {
570     setName(NameStr);
571   }
572   /// @brief Constructor with insert-at-end-of-block semantics for subclasses
573   CastInst(Type *Ty, unsigned iType, Value *S,
574            const Twine &NameStr, BasicBlock *InsertAtEnd)
575     : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
576     setName(NameStr);
577   }
578
579 public:
580   /// Provides a way to construct any of the CastInst subclasses using an
581   /// opcode instead of the subclass's constructor. The opcode must be in the
582   /// CastOps category (Instruction::isCast(opcode) returns true). This
583   /// constructor has insert-before-instruction semantics to automatically
584   /// insert the new CastInst before InsertBefore (if it is non-null).
585   /// @brief Construct any of the CastInst subclasses
586   static CastInst *Create(
587     Instruction::CastOps,    ///< The opcode of the cast instruction
588     Value *S,                ///< The value to be casted (operand 0)
589     Type *Ty,          ///< The type to which cast should be made
590     const Twine &Name = "", ///< Name for the instruction
591     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
592   );
593   /// Provides a way to construct any of the CastInst subclasses using an
594   /// opcode instead of the subclass's constructor. The opcode must be in the
595   /// CastOps category. This constructor has insert-at-end-of-block semantics
596   /// to automatically insert the new CastInst at the end of InsertAtEnd (if
597   /// its non-null).
598   /// @brief Construct any of the CastInst subclasses
599   static CastInst *Create(
600     Instruction::CastOps,    ///< The opcode for the cast instruction
601     Value *S,                ///< The value to be casted (operand 0)
602     Type *Ty,          ///< The type to which operand is casted
603     const Twine &Name, ///< The name for the instruction
604     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
605   );
606
607   /// @brief Create a ZExt or BitCast cast instruction
608   static CastInst *CreateZExtOrBitCast(
609     Value *S,                ///< The value to be casted (operand 0)
610     Type *Ty,          ///< The type to which cast should be made
611     const Twine &Name = "", ///< Name for the instruction
612     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
613   );
614
615   /// @brief Create a ZExt or BitCast cast instruction
616   static CastInst *CreateZExtOrBitCast(
617     Value *S,                ///< The value to be casted (operand 0)
618     Type *Ty,          ///< The type to which operand is casted
619     const Twine &Name, ///< The name for the instruction
620     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
621   );
622
623   /// @brief Create a SExt or BitCast cast instruction
624   static CastInst *CreateSExtOrBitCast(
625     Value *S,                ///< The value to be casted (operand 0)
626     Type *Ty,          ///< The type to which cast should be made
627     const Twine &Name = "", ///< Name for the instruction
628     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
629   );
630
631   /// @brief Create a SExt or BitCast cast instruction
632   static CastInst *CreateSExtOrBitCast(
633     Value *S,                ///< The value to be casted (operand 0)
634     Type *Ty,          ///< The type to which operand is casted
635     const Twine &Name, ///< The name for the instruction
636     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
637   );
638
639   /// @brief Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
640   static CastInst *CreatePointerCast(
641     Value *S,                ///< The pointer value to be casted (operand 0)
642     Type *Ty,          ///< The type to which operand is casted
643     const Twine &Name, ///< The name for the instruction
644     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
645   );
646
647   /// @brief Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
648   static CastInst *CreatePointerCast(
649     Value *S,                ///< The pointer value to be casted (operand 0)
650     Type *Ty,          ///< The type to which cast should be made
651     const Twine &Name = "", ///< Name for the instruction
652     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
653   );
654
655   /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
656   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
657     Value *S,                ///< The pointer value to be casted (operand 0)
658     Type *Ty,          ///< The type to which operand is casted
659     const Twine &Name, ///< The name for the instruction
660     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
661   );
662
663   /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
664   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
665     Value *S,                ///< The pointer value to be casted (operand 0)
666     Type *Ty,          ///< The type to which cast should be made
667     const Twine &Name = "", ///< Name for the instruction
668     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
669   );
670
671   /// @brief Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
672   ///
673   /// If the value is a pointer type and the destination an integer type,
674   /// creates a PtrToInt cast. If the value is an integer type and the
675   /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
676   /// a bitcast.
677   static CastInst *CreateBitOrPointerCast(
678     Value *S,                ///< The pointer value to be casted (operand 0)
679     Type *Ty,          ///< The type to which cast should be made
680     const Twine &Name = "", ///< Name for the instruction
681     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
682   );
683
684   /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
685   static CastInst *CreateIntegerCast(
686     Value *S,                ///< The pointer value to be casted (operand 0)
687     Type *Ty,          ///< The type to which cast should be made
688     bool isSigned,           ///< Whether to regard S as signed or not
689     const Twine &Name = "", ///< Name for the instruction
690     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
691   );
692
693   /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
694   static CastInst *CreateIntegerCast(
695     Value *S,                ///< The integer value to be casted (operand 0)
696     Type *Ty,          ///< The integer type to which operand is casted
697     bool isSigned,           ///< Whether to regard S as signed or not
698     const Twine &Name, ///< The name for the instruction
699     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
700   );
701
702   /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
703   static CastInst *CreateFPCast(
704     Value *S,                ///< The floating point value to be casted
705     Type *Ty,          ///< The floating point type to cast to
706     const Twine &Name = "", ///< Name for the instruction
707     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
708   );
709
710   /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
711   static CastInst *CreateFPCast(
712     Value *S,                ///< The floating point value to be casted
713     Type *Ty,          ///< The floating point type to cast to
714     const Twine &Name, ///< The name for the instruction
715     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
716   );
717
718   /// @brief Create a Trunc or BitCast cast instruction
719   static CastInst *CreateTruncOrBitCast(
720     Value *S,                ///< The value to be casted (operand 0)
721     Type *Ty,          ///< The type to which cast should be made
722     const Twine &Name = "", ///< Name for the instruction
723     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
724   );
725
726   /// @brief Create a Trunc or BitCast cast instruction
727   static CastInst *CreateTruncOrBitCast(
728     Value *S,                ///< The value to be casted (operand 0)
729     Type *Ty,          ///< The type to which operand is casted
730     const Twine &Name, ///< The name for the instruction
731     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
732   );
733
734   /// @brief Check whether it is valid to call getCastOpcode for these types.
735   static bool isCastable(
736     Type *SrcTy, ///< The Type from which the value should be cast.
737     Type *DestTy ///< The Type to which the value should be cast.
738   );
739
740   /// @brief Check whether a bitcast between these types is valid
741   static bool isBitCastable(
742     Type *SrcTy, ///< The Type from which the value should be cast.
743     Type *DestTy ///< The Type to which the value should be cast.
744   );
745
746   /// @brief Check whether a bitcast, inttoptr, or ptrtoint cast between these
747   /// types is valid and a no-op.
748   ///
749   /// This ensures that any pointer<->integer cast has enough bits in the
750   /// integer and any other cast is a bitcast.
751   static bool isBitOrNoopPointerCastable(
752       Type *SrcTy,  ///< The Type from which the value should be cast.
753       Type *DestTy, ///< The Type to which the value should be cast.
754       const DataLayout &DL);
755
756   /// Returns the opcode necessary to cast Val into Ty using usual casting
757   /// rules.
758   /// @brief Infer the opcode for cast operand and type
759   static Instruction::CastOps getCastOpcode(
760     const Value *Val, ///< The value to cast
761     bool SrcIsSigned, ///< Whether to treat the source as signed
762     Type *Ty,   ///< The Type to which the value should be casted
763     bool DstIsSigned  ///< Whether to treate the dest. as signed
764   );
765
766   /// There are several places where we need to know if a cast instruction
767   /// only deals with integer source and destination types. To simplify that
768   /// logic, this method is provided.
769   /// @returns true iff the cast has only integral typed operand and dest type.
770   /// @brief Determine if this is an integer-only cast.
771   bool isIntegerCast() const;
772
773   /// A lossless cast is one that does not alter the basic value. It implies
774   /// a no-op cast but is more stringent, preventing things like int->float,
775   /// long->double, or int->ptr.
776   /// @returns true iff the cast is lossless.
777   /// @brief Determine if this is a lossless cast.
778   bool isLosslessCast() const;
779
780   /// A no-op cast is one that can be effected without changing any bits.
781   /// It implies that the source and destination types are the same size. The
782   /// IntPtrTy argument is used to make accurate determinations for casts
783   /// involving Integer and Pointer types. They are no-op casts if the integer
784   /// is the same size as the pointer. However, pointer size varies with
785   /// platform. Generally, the result of DataLayout::getIntPtrType() should be
786   /// passed in. If that's not available, use Type::Int64Ty, which will make
787   /// the isNoopCast call conservative.
788   /// @brief Determine if the described cast is a no-op cast.
789   static bool isNoopCast(
790     Instruction::CastOps Opcode,  ///< Opcode of cast
791     Type *SrcTy,   ///< SrcTy of cast
792     Type *DstTy,   ///< DstTy of cast
793     Type *IntPtrTy ///< Integer type corresponding to Ptr types
794   );
795
796   /// @brief Determine if this cast is a no-op cast.
797   bool isNoopCast(
798     Type *IntPtrTy ///< Integer type corresponding to pointer
799   ) const;
800
801   /// @brief Determine if this cast is a no-op cast.
802   ///
803   /// \param DL is the DataLayout to get the Int Ptr type from.
804   bool isNoopCast(const DataLayout &DL) const;
805
806   /// Determine how a pair of casts can be eliminated, if they can be at all.
807   /// This is a helper function for both CastInst and ConstantExpr.
808   /// @returns 0 if the CastInst pair can't be eliminated, otherwise
809   /// returns Instruction::CastOps value for a cast that can replace
810   /// the pair, casting SrcTy to DstTy.
811   /// @brief Determine if a cast pair is eliminable
812   static unsigned isEliminableCastPair(
813     Instruction::CastOps firstOpcode,  ///< Opcode of first cast
814     Instruction::CastOps secondOpcode, ///< Opcode of second cast
815     Type *SrcTy, ///< SrcTy of 1st cast
816     Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
817     Type *DstTy, ///< DstTy of 2nd cast
818     Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
819     Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
820     Type *DstIntPtrTy  ///< Integer type corresponding to Ptr DstTy, or null
821   );
822
823   /// @brief Return the opcode of this CastInst
824   Instruction::CastOps getOpcode() const {
825     return Instruction::CastOps(Instruction::getOpcode());
826   }
827
828   /// @brief Return the source type, as a convenience
829   Type* getSrcTy() const { return getOperand(0)->getType(); }
830   /// @brief Return the destination type, as a convenience
831   Type* getDestTy() const { return getType(); }
832
833   /// This method can be used to determine if a cast from S to DstTy using
834   /// Opcode op is valid or not.
835   /// @returns true iff the proposed cast is valid.
836   /// @brief Determine if a cast is valid without creating one.
837   static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
838
839   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
840   static inline bool classof(const Instruction *I) {
841     return I->isCast();
842   }
843   static inline bool classof(const Value *V) {
844     return isa<Instruction>(V) && classof(cast<Instruction>(V));
845   }
846 };
847
848 //===----------------------------------------------------------------------===//
849 //                               CmpInst Class
850 //===----------------------------------------------------------------------===//
851
852 /// This class is the base class for the comparison instructions.
853 /// @brief Abstract base class of comparison instructions.
854 class CmpInst : public Instruction {
855 public:
856   /// This enumeration lists the possible predicates for CmpInst subclasses.
857   /// Values in the range 0-31 are reserved for FCmpInst, while values in the
858   /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
859   /// predicate values are not overlapping between the classes.
860   ///
861   /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of
862   /// FCMP_* values. Changing the bit patterns requires a potential change to
863   /// those passes.
864   enum Predicate {
865     // Opcode              U L G E    Intuitive operation
866     FCMP_FALSE =  0,  ///< 0 0 0 0    Always false (always folded)
867     FCMP_OEQ   =  1,  ///< 0 0 0 1    True if ordered and equal
868     FCMP_OGT   =  2,  ///< 0 0 1 0    True if ordered and greater than
869     FCMP_OGE   =  3,  ///< 0 0 1 1    True if ordered and greater than or equal
870     FCMP_OLT   =  4,  ///< 0 1 0 0    True if ordered and less than
871     FCMP_OLE   =  5,  ///< 0 1 0 1    True if ordered and less than or equal
872     FCMP_ONE   =  6,  ///< 0 1 1 0    True if ordered and operands are unequal
873     FCMP_ORD   =  7,  ///< 0 1 1 1    True if ordered (no nans)
874     FCMP_UNO   =  8,  ///< 1 0 0 0    True if unordered: isnan(X) | isnan(Y)
875     FCMP_UEQ   =  9,  ///< 1 0 0 1    True if unordered or equal
876     FCMP_UGT   = 10,  ///< 1 0 1 0    True if unordered or greater than
877     FCMP_UGE   = 11,  ///< 1 0 1 1    True if unordered, greater than, or equal
878     FCMP_ULT   = 12,  ///< 1 1 0 0    True if unordered or less than
879     FCMP_ULE   = 13,  ///< 1 1 0 1    True if unordered, less than, or equal
880     FCMP_UNE   = 14,  ///< 1 1 1 0    True if unordered or not equal
881     FCMP_TRUE  = 15,  ///< 1 1 1 1    Always true (always folded)
882     FIRST_FCMP_PREDICATE = FCMP_FALSE,
883     LAST_FCMP_PREDICATE = FCMP_TRUE,
884     BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
885     ICMP_EQ    = 32,  ///< equal
886     ICMP_NE    = 33,  ///< not equal
887     ICMP_UGT   = 34,  ///< unsigned greater than
888     ICMP_UGE   = 35,  ///< unsigned greater or equal
889     ICMP_ULT   = 36,  ///< unsigned less than
890     ICMP_ULE   = 37,  ///< unsigned less or equal
891     ICMP_SGT   = 38,  ///< signed greater than
892     ICMP_SGE   = 39,  ///< signed greater or equal
893     ICMP_SLT   = 40,  ///< signed less than
894     ICMP_SLE   = 41,  ///< signed less or equal
895     FIRST_ICMP_PREDICATE = ICMP_EQ,
896     LAST_ICMP_PREDICATE = ICMP_SLE,
897     BAD_ICMP_PREDICATE = ICMP_SLE + 1
898   };
899
900 protected:
901   CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
902           Value *LHS, Value *RHS, const Twine &Name = "",
903           Instruction *InsertBefore = nullptr);
904
905   CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
906           Value *LHS, Value *RHS, const Twine &Name,
907           BasicBlock *InsertAtEnd);
908
909 public:
910   CmpInst() = delete;
911
912   // allocate space for exactly two operands
913   void *operator new(size_t s) {
914     return User::operator new(s, 2);
915   }
916
917   void *operator new(size_t, unsigned) = delete;
918
919   /// Construct a compare instruction, given the opcode, the predicate and
920   /// the two operands.  Optionally (if InstBefore is specified) insert the
921   /// instruction into a BasicBlock right before the specified instruction.
922   /// The specified Instruction is allowed to be a dereferenced end iterator.
923   /// @brief Create a CmpInst
924   static CmpInst *Create(OtherOps Op,
925                          Predicate predicate, Value *S1,
926                          Value *S2, const Twine &Name = "",
927                          Instruction *InsertBefore = nullptr);
928
929   /// Construct a compare instruction, given the opcode, the predicate and the
930   /// two operands.  Also automatically insert this instruction to the end of
931   /// the BasicBlock specified.
932   /// @brief Create a CmpInst
933   static CmpInst *Create(OtherOps Op, Predicate predicate, Value *S1,
934                          Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
935
936   /// @brief Get the opcode casted to the right type
937   OtherOps getOpcode() const {
938     return static_cast<OtherOps>(Instruction::getOpcode());
939   }
940
941   /// @brief Return the predicate for this instruction.
942   Predicate getPredicate() const {
943     return Predicate(getSubclassDataFromInstruction());
944   }
945
946   /// @brief Set the predicate for this instruction to the specified value.
947   void setPredicate(Predicate P) { setInstructionSubclassData(P); }
948
949   static bool isFPPredicate(Predicate P) {
950     return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
951   }
952
953   static bool isIntPredicate(Predicate P) {
954     return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
955   }
956
957   static StringRef getPredicateName(Predicate P);
958
959   bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
960   bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
961
962   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
963   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
964   /// @returns the inverse predicate for the instruction's current predicate.
965   /// @brief Return the inverse of the instruction's predicate.
966   Predicate getInversePredicate() const {
967     return getInversePredicate(getPredicate());
968   }
969
970   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
971   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
972   /// @returns the inverse predicate for predicate provided in \p pred.
973   /// @brief Return the inverse of a given predicate
974   static Predicate getInversePredicate(Predicate pred);
975
976   /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
977   ///              OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
978   /// @returns the predicate that would be the result of exchanging the two
979   /// operands of the CmpInst instruction without changing the result
980   /// produced.
981   /// @brief Return the predicate as if the operands were swapped
982   Predicate getSwappedPredicate() const {
983     return getSwappedPredicate(getPredicate());
984   }
985
986   /// This is a static version that you can use without an instruction
987   /// available.
988   /// @brief Return the predicate as if the operands were swapped.
989   static Predicate getSwappedPredicate(Predicate pred);
990
991   /// @brief Provide more efficient getOperand methods.
992   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
993
994   /// This is just a convenience that dispatches to the subclasses.
995   /// @brief Swap the operands and adjust predicate accordingly to retain
996   /// the same comparison.
997   void swapOperands();
998
999   /// This is just a convenience that dispatches to the subclasses.
1000   /// @brief Determine if this CmpInst is commutative.
1001   bool isCommutative() const;
1002
1003   /// This is just a convenience that dispatches to the subclasses.
1004   /// @brief Determine if this is an equals/not equals predicate.
1005   bool isEquality() const;
1006
1007   /// @returns true if the comparison is signed, false otherwise.
1008   /// @brief Determine if this instruction is using a signed comparison.
1009   bool isSigned() const {
1010     return isSigned(getPredicate());
1011   }
1012
1013   /// @returns true if the comparison is unsigned, false otherwise.
1014   /// @brief Determine if this instruction is using an unsigned comparison.
1015   bool isUnsigned() const {
1016     return isUnsigned(getPredicate());
1017   }
1018
1019   /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1020   /// @returns the signed version of the unsigned predicate pred.
1021   /// @brief return the signed version of a predicate
1022   static Predicate getSignedPredicate(Predicate pred);
1023
1024   /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1025   /// @returns the signed version of the predicate for this instruction (which
1026   /// has to be an unsigned predicate).
1027   /// @brief return the signed version of a predicate
1028   Predicate getSignedPredicate() {
1029     return getSignedPredicate(getPredicate());
1030   }
1031
1032   /// This is just a convenience.
1033   /// @brief Determine if this is true when both operands are the same.
1034   bool isTrueWhenEqual() const {
1035     return isTrueWhenEqual(getPredicate());
1036   }
1037
1038   /// This is just a convenience.
1039   /// @brief Determine if this is false when both operands are the same.
1040   bool isFalseWhenEqual() const {
1041     return isFalseWhenEqual(getPredicate());
1042   }
1043
1044   /// @returns true if the predicate is unsigned, false otherwise.
1045   /// @brief Determine if the predicate is an unsigned operation.
1046   static bool isUnsigned(Predicate predicate);
1047
1048   /// @returns true if the predicate is signed, false otherwise.
1049   /// @brief Determine if the predicate is an signed operation.
1050   static bool isSigned(Predicate predicate);
1051
1052   /// @brief Determine if the predicate is an ordered operation.
1053   static bool isOrdered(Predicate predicate);
1054
1055   /// @brief Determine if the predicate is an unordered operation.
1056   static bool isUnordered(Predicate predicate);
1057
1058   /// Determine if the predicate is true when comparing a value with itself.
1059   static bool isTrueWhenEqual(Predicate predicate);
1060
1061   /// Determine if the predicate is false when comparing a value with itself.
1062   static bool isFalseWhenEqual(Predicate predicate);
1063
1064   /// Determine if Pred1 implies Pred2 is true when two compares have matching
1065   /// operands.
1066   static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2);
1067
1068   /// Determine if Pred1 implies Pred2 is false when two compares have matching
1069   /// operands.
1070   static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2);
1071
1072   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
1073   static inline bool classof(const Instruction *I) {
1074     return I->getOpcode() == Instruction::ICmp ||
1075            I->getOpcode() == Instruction::FCmp;
1076   }
1077   static inline bool classof(const Value *V) {
1078     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1079   }
1080
1081   /// @brief Create a result type for fcmp/icmp
1082   static Type* makeCmpResultType(Type* opnd_type) {
1083     if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
1084       return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
1085                              vt->getNumElements());
1086     }
1087     return Type::getInt1Ty(opnd_type->getContext());
1088   }
1089
1090 private:
1091   // Shadow Value::setValueSubclassData with a private forwarding method so that
1092   // subclasses cannot accidentally use it.
1093   void setValueSubclassData(unsigned short D) {
1094     Value::setValueSubclassData(D);
1095   }
1096 };
1097
1098 // FIXME: these are redundant if CmpInst < BinaryOperator
1099 template <>
1100 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
1101 };
1102
1103 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
1104
1105 //===----------------------------------------------------------------------===//
1106 //                           FuncletPadInst Class
1107 //===----------------------------------------------------------------------===//
1108 class FuncletPadInst : public Instruction {
1109 private:
1110   FuncletPadInst(const FuncletPadInst &CPI);
1111
1112   explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1113                           ArrayRef<Value *> Args, unsigned Values,
1114                           const Twine &NameStr, Instruction *InsertBefore);
1115   explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1116                           ArrayRef<Value *> Args, unsigned Values,
1117                           const Twine &NameStr, BasicBlock *InsertAtEnd);
1118
1119   void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
1120
1121 protected:
1122   // Note: Instruction needs to be a friend here to call cloneImpl.
1123   friend class Instruction;
1124   friend class CatchPadInst;
1125   friend class CleanupPadInst;
1126
1127   FuncletPadInst *cloneImpl() const;
1128
1129 public:
1130   /// Provide fast operand accessors
1131   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1132
1133   /// getNumArgOperands - Return the number of funcletpad arguments.
1134   ///
1135   unsigned getNumArgOperands() const { return getNumOperands() - 1; }
1136
1137   /// Convenience accessors
1138
1139   /// \brief Return the outer EH-pad this funclet is nested within.
1140   ///
1141   /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
1142   /// is a CatchPadInst.
1143   Value *getParentPad() const { return Op<-1>(); }
1144   void setParentPad(Value *ParentPad) {
1145     assert(ParentPad);
1146     Op<-1>() = ParentPad;
1147   }
1148
1149   /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
1150   ///
1151   Value *getArgOperand(unsigned i) const { return getOperand(i); }
1152   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
1153
1154   /// arg_operands - iteration adapter for range-for loops.
1155   op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
1156
1157   /// arg_operands - iteration adapter for range-for loops.
1158   const_op_range arg_operands() const {
1159     return const_op_range(op_begin(), op_end() - 1);
1160   }
1161
1162   // Methods for support type inquiry through isa, cast, and dyn_cast:
1163   static inline bool classof(const Instruction *I) { return I->isFuncletPad(); }
1164   static inline bool classof(const Value *V) {
1165     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1166   }
1167 };
1168
1169 template <>
1170 struct OperandTraits<FuncletPadInst>
1171     : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {};
1172
1173 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)
1174
1175 /// \brief A lightweight accessor for an operand bundle meant to be passed
1176 /// around by value.
1177 struct OperandBundleUse {
1178   ArrayRef<Use> Inputs;
1179
1180   OperandBundleUse() = default;
1181   explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
1182       : Inputs(Inputs), Tag(Tag) {}
1183
1184   /// \brief Return true if the operand at index \p Idx in this operand bundle
1185   /// has the attribute A.
1186   bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const {
1187     if (isDeoptOperandBundle())
1188       if (A == Attribute::ReadOnly || A == Attribute::NoCapture)
1189         return Inputs[Idx]->getType()->isPointerTy();
1190
1191     // Conservative answer:  no operands have any attributes.
1192     return false;
1193   }
1194
1195   /// \brief Return the tag of this operand bundle as a string.
1196   StringRef getTagName() const {
1197     return Tag->getKey();
1198   }
1199
1200   /// \brief Return the tag of this operand bundle as an integer.
1201   ///
1202   /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
1203   /// and this function returns the unique integer getOrInsertBundleTag
1204   /// associated the tag of this operand bundle to.
1205   uint32_t getTagID() const {
1206     return Tag->getValue();
1207   }
1208
1209   /// \brief Return true if this is a "deopt" operand bundle.
1210   bool isDeoptOperandBundle() const {
1211     return getTagID() == LLVMContext::OB_deopt;
1212   }
1213
1214   /// \brief Return true if this is a "funclet" operand bundle.
1215   bool isFuncletOperandBundle() const {
1216     return getTagID() == LLVMContext::OB_funclet;
1217   }
1218
1219 private:
1220   /// \brief Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1221   StringMapEntry<uint32_t> *Tag;
1222 };
1223
1224 /// \brief A container for an operand bundle being viewed as a set of values
1225 /// rather than a set of uses.
1226 ///
1227 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1228 /// so it is possible to create and pass around "self-contained" instances of
1229 /// OperandBundleDef and ConstOperandBundleDef.
1230 template <typename InputTy> class OperandBundleDefT {
1231   std::string Tag;
1232   std::vector<InputTy> Inputs;
1233
1234 public:
1235   explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1236       : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1237   explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs)
1238       : Tag(std::move(Tag)), Inputs(Inputs) {}
1239
1240   explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1241     Tag = OBU.getTagName();
1242     Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
1243   }
1244
1245   ArrayRef<InputTy> inputs() const { return Inputs; }
1246
1247   using input_iterator = typename std::vector<InputTy>::const_iterator;
1248
1249   size_t input_size() const { return Inputs.size(); }
1250   input_iterator input_begin() const { return Inputs.begin(); }
1251   input_iterator input_end() const { return Inputs.end(); }
1252
1253   StringRef getTag() const { return Tag; }
1254 };
1255
1256 using OperandBundleDef = OperandBundleDefT<Value *>;
1257 using ConstOperandBundleDef = OperandBundleDefT<const Value *>;
1258
1259 /// \brief A mixin to add operand bundle functionality to llvm instruction
1260 /// classes.
1261 ///
1262 /// OperandBundleUser uses the descriptor area co-allocated with the host User
1263 /// to store some meta information about which operands are "normal" operands,
1264 /// and which ones belong to some operand bundle.
1265 ///
1266 /// The layout of an operand bundle user is
1267 ///
1268 ///          +-----------uint32_t End-------------------------------------+
1269 ///          |                                                            |
1270 ///          |  +--------uint32_t Begin--------------------+              |
1271 ///          |  |                                          |              |
1272 ///          ^  ^                                          v              v
1273 ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
1274 ///  | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
1275 ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
1276 ///   v  v                                  ^              ^
1277 ///   |  |                                  |              |
1278 ///   |  +--------uint32_t Begin------------+              |
1279 ///   |                                                    |
1280 ///   +-----------uint32_t End-----------------------------+
1281 ///
1282 ///
1283 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use list.
1284 /// These descriptions are installed and managed by this class, and they're all
1285 /// instances of OperandBundleUser<T>::BundleOpInfo.
1286 ///
1287 /// DU is an additional descriptor installed by User's 'operator new' to keep
1288 /// track of the 'BOI0 ... BOIN' co-allocation.  OperandBundleUser does not
1289 /// access or modify DU in any way, it's an implementation detail private to
1290 /// User.
1291 ///
1292 /// The regular Use& vector for the User starts at U0.  The operand bundle uses
1293 /// are part of the Use& vector, just like normal uses.  In the diagram above,
1294 /// the operand bundle uses start at BOI0_U0.  Each instance of BundleOpInfo has
1295 /// information about a contiguous set of uses constituting an operand bundle,
1296 /// and the total set of operand bundle uses themselves form a contiguous set of
1297 /// uses (i.e. there are no gaps between uses corresponding to individual
1298 /// operand bundles).
1299 ///
1300 /// This class does not know the location of the set of operand bundle uses
1301 /// within the use list -- that is decided by the User using this class via the
1302 /// BeginIdx argument in populateBundleOperandInfos.
1303 ///
1304 /// Currently operand bundle users with hung-off operands are not supported.
1305 template <typename InstrTy, typename OpIteratorTy> class OperandBundleUser {
1306 public:
1307   /// \brief Return the number of operand bundles associated with this User.
1308   unsigned getNumOperandBundles() const {
1309     return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1310   }
1311
1312   /// \brief Return true if this User has any operand bundles.
1313   bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1314
1315   /// \brief Return the index of the first bundle operand in the Use array.
1316   unsigned getBundleOperandsStartIndex() const {
1317     assert(hasOperandBundles() && "Don't call otherwise!");
1318     return bundle_op_info_begin()->Begin;
1319   }
1320
1321   /// \brief Return the index of the last bundle operand in the Use array.
1322   unsigned getBundleOperandsEndIndex() const {
1323     assert(hasOperandBundles() && "Don't call otherwise!");
1324     return bundle_op_info_end()[-1].End;
1325   }
1326
1327   /// Return true if the operand at index \p Idx is a bundle operand.
1328   bool isBundleOperand(unsigned Idx) const {
1329     return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() &&
1330            Idx < getBundleOperandsEndIndex();
1331   }
1332
1333   /// \brief Return the total number operands (not operand bundles) used by
1334   /// every operand bundle in this OperandBundleUser.
1335   unsigned getNumTotalBundleOperands() const {
1336     if (!hasOperandBundles())
1337       return 0;
1338
1339     unsigned Begin = getBundleOperandsStartIndex();
1340     unsigned End = getBundleOperandsEndIndex();
1341
1342     assert(Begin <= End && "Should be!");
1343     return End - Begin;
1344   }
1345
1346   /// \brief Return the operand bundle at a specific index.
1347   OperandBundleUse getOperandBundleAt(unsigned Index) const {
1348     assert(Index < getNumOperandBundles() && "Index out of bounds!");
1349     return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1350   }
1351
1352   /// \brief Return the number of operand bundles with the tag Name attached to
1353   /// this instruction.
1354   unsigned countOperandBundlesOfType(StringRef Name) const {
1355     unsigned Count = 0;
1356     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1357       if (getOperandBundleAt(i).getTagName() == Name)
1358         Count++;
1359
1360     return Count;
1361   }
1362
1363   /// \brief Return the number of operand bundles with the tag ID attached to
1364   /// this instruction.
1365   unsigned countOperandBundlesOfType(uint32_t ID) const {
1366     unsigned Count = 0;
1367     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1368       if (getOperandBundleAt(i).getTagID() == ID)
1369         Count++;
1370
1371     return Count;
1372   }
1373
1374   /// \brief Return an operand bundle by name, if present.
1375   ///
1376   /// It is an error to call this for operand bundle types that may have
1377   /// multiple instances of them on the same instruction.
1378   Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1379     assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
1380
1381     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1382       OperandBundleUse U = getOperandBundleAt(i);
1383       if (U.getTagName() == Name)
1384         return U;
1385     }
1386
1387     return None;
1388   }
1389
1390   /// \brief Return an operand bundle by tag ID, if present.
1391   ///
1392   /// It is an error to call this for operand bundle types that may have
1393   /// multiple instances of them on the same instruction.
1394   Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1395     assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
1396
1397     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1398       OperandBundleUse U = getOperandBundleAt(i);
1399       if (U.getTagID() == ID)
1400         return U;
1401     }
1402
1403     return None;
1404   }
1405
1406   /// \brief Return the list of operand bundles attached to this instruction as
1407   /// a vector of OperandBundleDefs.
1408   ///
1409   /// This function copies the OperandBundeUse instances associated with this
1410   /// OperandBundleUser to a vector of OperandBundleDefs.  Note:
1411   /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1412   /// representations of operand bundles (see documentation above).
1413   void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
1414     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1415       Defs.emplace_back(getOperandBundleAt(i));
1416   }
1417
1418   /// \brief Return the operand bundle for the operand at index OpIdx.
1419   ///
1420   /// It is an error to call this with an OpIdx that does not correspond to an
1421   /// bundle operand.
1422   OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1423     return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
1424   }
1425
1426   /// \brief Return true if this operand bundle user has operand bundles that
1427   /// may read from the heap.
1428   bool hasReadingOperandBundles() const {
1429     // Implementation note: this is a conservative implementation of operand
1430     // bundle semantics, where *any* operand bundle forces a callsite to be at
1431     // least readonly.
1432     return hasOperandBundles();
1433   }
1434
1435   /// \brief Return true if this operand bundle user has operand bundles that
1436   /// may write to the heap.
1437   bool hasClobberingOperandBundles() const {
1438     for (auto &BOI : bundle_op_infos()) {
1439       if (BOI.Tag->second == LLVMContext::OB_deopt ||
1440           BOI.Tag->second == LLVMContext::OB_funclet)
1441         continue;
1442
1443       // This instruction has an operand bundle that is not known to us.
1444       // Assume the worst.
1445       return true;
1446     }
1447
1448     return false;
1449   }
1450
1451   /// \brief Return true if the bundle operand at index \p OpIdx has the
1452   /// attribute \p A.
1453   bool bundleOperandHasAttr(unsigned OpIdx,  Attribute::AttrKind A) const {
1454     auto &BOI = getBundleOpInfoForOperand(OpIdx);
1455     auto OBU = operandBundleFromBundleOpInfo(BOI);
1456     return OBU.operandHasAttr(OpIdx - BOI.Begin, A);
1457   }
1458
1459   /// \brief Return true if \p Other has the same sequence of operand bundle
1460   /// tags with the same number of operands on each one of them as this
1461   /// OperandBundleUser.
1462   bool hasIdenticalOperandBundleSchema(
1463       const OperandBundleUser<InstrTy, OpIteratorTy> &Other) const {
1464     if (getNumOperandBundles() != Other.getNumOperandBundles())
1465       return false;
1466
1467     return std::equal(bundle_op_info_begin(), bundle_op_info_end(),
1468                       Other.bundle_op_info_begin());
1469   }
1470
1471   /// \brief Return true if this operand bundle user contains operand bundles
1472   /// with tags other than those specified in \p IDs.
1473   bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const {
1474     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1475       uint32_t ID = getOperandBundleAt(i).getTagID();
1476       if (!is_contained(IDs, ID))
1477         return true;
1478     }
1479     return false;
1480   }
1481
1482 protected:
1483   /// \brief Is the function attribute S disallowed by some operand bundle on
1484   /// this operand bundle user?
1485   bool isFnAttrDisallowedByOpBundle(StringRef S) const {
1486     // Operand bundles only possibly disallow readnone, readonly and argmenonly
1487     // attributes.  All String attributes are fine.
1488     return false;
1489   }
1490
1491   /// \brief Is the function attribute A disallowed by some operand bundle on
1492   /// this operand bundle user?
1493   bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
1494     switch (A) {
1495     default:
1496       return false;
1497
1498     case Attribute::ArgMemOnly:
1499       return hasReadingOperandBundles();
1500
1501     case Attribute::ReadNone:
1502       return hasReadingOperandBundles();
1503
1504     case Attribute::ReadOnly:
1505       return hasClobberingOperandBundles();
1506     }
1507
1508     llvm_unreachable("switch has a default case!");
1509   }
1510
1511   /// \brief Used to keep track of an operand bundle.  See the main comment on
1512   /// OperandBundleUser above.
1513   struct BundleOpInfo {
1514     /// \brief The operand bundle tag, interned by
1515     /// LLVMContextImpl::getOrInsertBundleTag.
1516     StringMapEntry<uint32_t> *Tag;
1517
1518     /// \brief The index in the Use& vector where operands for this operand
1519     /// bundle starts.
1520     uint32_t Begin;
1521
1522     /// \brief The index in the Use& vector where operands for this operand
1523     /// bundle ends.
1524     uint32_t End;
1525
1526     bool operator==(const BundleOpInfo &Other) const {
1527       return Tag == Other.Tag && Begin == Other.Begin && End == Other.End;
1528     }
1529   };
1530
1531   /// \brief Simple helper function to map a BundleOpInfo to an
1532   /// OperandBundleUse.
1533   OperandBundleUse
1534   operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
1535     auto op_begin = static_cast<const InstrTy *>(this)->op_begin();
1536     ArrayRef<Use> Inputs(op_begin + BOI.Begin, op_begin + BOI.End);
1537     return OperandBundleUse(BOI.Tag, Inputs);
1538   }
1539
1540   using bundle_op_iterator = BundleOpInfo *;
1541   using const_bundle_op_iterator = const BundleOpInfo *;
1542
1543   /// \brief Return the start of the list of BundleOpInfo instances associated
1544   /// with this OperandBundleUser.
1545   bundle_op_iterator bundle_op_info_begin() {
1546     if (!static_cast<InstrTy *>(this)->hasDescriptor())
1547       return nullptr;
1548
1549     uint8_t *BytesBegin = static_cast<InstrTy *>(this)->getDescriptor().begin();
1550     return reinterpret_cast<bundle_op_iterator>(BytesBegin);
1551   }
1552
1553   /// \brief Return the start of the list of BundleOpInfo instances associated
1554   /// with this OperandBundleUser.
1555   const_bundle_op_iterator bundle_op_info_begin() const {
1556     auto *NonConstThis =
1557         const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1558     return NonConstThis->bundle_op_info_begin();
1559   }
1560
1561   /// \brief Return the end of the list of BundleOpInfo instances associated
1562   /// with this OperandBundleUser.
1563   bundle_op_iterator bundle_op_info_end() {
1564     if (!static_cast<InstrTy *>(this)->hasDescriptor())
1565       return nullptr;
1566
1567     uint8_t *BytesEnd = static_cast<InstrTy *>(this)->getDescriptor().end();
1568     return reinterpret_cast<bundle_op_iterator>(BytesEnd);
1569   }
1570
1571   /// \brief Return the end of the list of BundleOpInfo instances associated
1572   /// with this OperandBundleUser.
1573   const_bundle_op_iterator bundle_op_info_end() const {
1574     auto *NonConstThis =
1575         const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1576     return NonConstThis->bundle_op_info_end();
1577   }
1578
1579   /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1580   iterator_range<bundle_op_iterator> bundle_op_infos() {
1581     return make_range(bundle_op_info_begin(), bundle_op_info_end());
1582   }
1583
1584   /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1585   iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
1586     return make_range(bundle_op_info_begin(), bundle_op_info_end());
1587   }
1588
1589   /// \brief Populate the BundleOpInfo instances and the Use& vector from \p
1590   /// Bundles.  Return the op_iterator pointing to the Use& one past the last
1591   /// last bundle operand use.
1592   ///
1593   /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
1594   /// instance allocated in this User's descriptor.
1595   OpIteratorTy populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
1596                                           const unsigned BeginIndex) {
1597     auto It = static_cast<InstrTy *>(this)->op_begin() + BeginIndex;
1598     for (auto &B : Bundles)
1599       It = std::copy(B.input_begin(), B.input_end(), It);
1600
1601     auto *ContextImpl = static_cast<InstrTy *>(this)->getContext().pImpl;
1602     auto BI = Bundles.begin();
1603     unsigned CurrentIndex = BeginIndex;
1604
1605     for (auto &BOI : bundle_op_infos()) {
1606       assert(BI != Bundles.end() && "Incorrect allocation?");
1607
1608       BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
1609       BOI.Begin = CurrentIndex;
1610       BOI.End = CurrentIndex + BI->input_size();
1611       CurrentIndex = BOI.End;
1612       BI++;
1613     }
1614
1615     assert(BI == Bundles.end() && "Incorrect allocation?");
1616
1617     return It;
1618   }
1619
1620   /// \brief Return the BundleOpInfo for the operand at index OpIdx.
1621   ///
1622   /// It is an error to call this with an OpIdx that does not correspond to an
1623   /// bundle operand.
1624   const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
1625     for (auto &BOI : bundle_op_infos())
1626       if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
1627         return BOI;
1628
1629     llvm_unreachable("Did not find operand bundle for operand!");
1630   }
1631
1632   /// \brief Return the total number of values used in \p Bundles.
1633   static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
1634     unsigned Total = 0;
1635     for (auto &B : Bundles)
1636       Total += B.input_size();
1637     return Total;
1638   }
1639 };
1640
1641 } // end namespace llvm
1642
1643 #endif // LLVM_IR_INSTRTYPES_H