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