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