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