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