]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/InstrTypes.h
Merge llvm, clang, compiler-rt, libc++, lld, and lldb release_80 branch
[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/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/OperandTraits.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/User.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include <algorithm>
40 #include <cassert>
41 #include <cstddef>
42 #include <cstdint>
43 #include <iterator>
44 #include <string>
45 #include <vector>
46
47 namespace llvm {
48
49 namespace Intrinsic {
50 enum ID : unsigned;
51 }
52
53 //===----------------------------------------------------------------------===//
54 //                          UnaryInstruction Class
55 //===----------------------------------------------------------------------===//
56
57 class UnaryInstruction : public Instruction {
58 protected:
59   UnaryInstruction(Type *Ty, unsigned iType, Value *V,
60                    Instruction *IB = nullptr)
61     : Instruction(Ty, iType, &Op<0>(), 1, IB) {
62     Op<0>() = V;
63   }
64   UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
65     : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
66     Op<0>() = V;
67   }
68
69 public:
70   // allocate space for exactly one operand
71   void *operator new(size_t s) {
72     return User::operator new(s, 1);
73   }
74
75   /// Transparently provide more efficient getOperand methods.
76   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
77
78   // Methods for support type inquiry through isa, cast, and dyn_cast:
79   static bool classof(const Instruction *I) {
80     return I->getOpcode() == Instruction::Alloca ||
81            I->getOpcode() == Instruction::Load ||
82            I->getOpcode() == Instruction::VAArg ||
83            I->getOpcode() == Instruction::ExtractValue ||
84            (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
85   }
86   static bool classof(const Value *V) {
87     return isa<Instruction>(V) && classof(cast<Instruction>(V));
88   }
89 };
90
91 template <>
92 struct OperandTraits<UnaryInstruction> :
93   public FixedNumOperandTraits<UnaryInstruction, 1> {
94 };
95
96 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
97
98 //===----------------------------------------------------------------------===//
99 //                           BinaryOperator Class
100 //===----------------------------------------------------------------------===//
101
102 class BinaryOperator : public Instruction {
103   void AssertOK();
104
105 protected:
106   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
107                  const Twine &Name, Instruction *InsertBefore);
108   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
109                  const Twine &Name, BasicBlock *InsertAtEnd);
110
111   // Note: Instruction needs to be a friend here to call cloneImpl.
112   friend class Instruction;
113
114   BinaryOperator *cloneImpl() const;
115
116 public:
117   // allocate space for exactly two operands
118   void *operator new(size_t s) {
119     return User::operator new(s, 2);
120   }
121
122   /// Transparently provide more efficient getOperand methods.
123   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
124
125   /// Construct a binary instruction, given the opcode and the two
126   /// operands.  Optionally (if InstBefore is specified) insert the instruction
127   /// into a BasicBlock right before the specified instruction.  The specified
128   /// Instruction is allowed to be a dereferenced end iterator.
129   ///
130   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
131                                 const Twine &Name = Twine(),
132                                 Instruction *InsertBefore = nullptr);
133
134   /// Construct a binary instruction, given the opcode and the two
135   /// operands.  Also automatically insert this instruction to the end of the
136   /// BasicBlock specified.
137   ///
138   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
139                                 const Twine &Name, BasicBlock *InsertAtEnd);
140
141   /// These methods just forward to Create, and are useful when you
142   /// statically know what type of instruction you're going to create.  These
143   /// helpers just save some typing.
144 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
145   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
146                                      const Twine &Name = "") {\
147     return Create(Instruction::OPC, V1, V2, Name);\
148   }
149 #include "llvm/IR/Instruction.def"
150 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
151   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
152                                      const Twine &Name, BasicBlock *BB) {\
153     return Create(Instruction::OPC, V1, V2, Name, BB);\
154   }
155 #include "llvm/IR/Instruction.def"
156 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
157   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
158                                      const Twine &Name, Instruction *I) {\
159     return Create(Instruction::OPC, V1, V2, Name, I);\
160   }
161 #include "llvm/IR/Instruction.def"
162
163   static BinaryOperator *CreateWithCopiedFlags(BinaryOps Opc,
164                                                Value *V1, Value *V2,
165                                                BinaryOperator *CopyBO,
166                                                const Twine &Name = "") {
167     BinaryOperator *BO = Create(Opc, V1, V2, Name);
168     BO->copyIRFlags(CopyBO);
169     return BO;
170   }
171
172   static BinaryOperator *CreateFAddFMF(Value *V1, Value *V2,
173                                        BinaryOperator *FMFSource,
174                                        const Twine &Name = "") {
175     return CreateWithCopiedFlags(Instruction::FAdd, V1, V2, FMFSource, Name);
176   }
177   static BinaryOperator *CreateFSubFMF(Value *V1, Value *V2,
178                                        BinaryOperator *FMFSource,
179                                        const Twine &Name = "") {
180     return CreateWithCopiedFlags(Instruction::FSub, V1, V2, FMFSource, Name);
181   }
182   static BinaryOperator *CreateFMulFMF(Value *V1, Value *V2,
183                                        BinaryOperator *FMFSource,
184                                        const Twine &Name = "") {
185     return CreateWithCopiedFlags(Instruction::FMul, V1, V2, FMFSource, Name);
186   }
187   static BinaryOperator *CreateFDivFMF(Value *V1, Value *V2,
188                                        BinaryOperator *FMFSource,
189                                        const Twine &Name = "") {
190     return CreateWithCopiedFlags(Instruction::FDiv, V1, V2, FMFSource, Name);
191   }
192   static BinaryOperator *CreateFRemFMF(Value *V1, Value *V2,
193                                        BinaryOperator *FMFSource,
194                                        const Twine &Name = "") {
195     return CreateWithCopiedFlags(Instruction::FRem, V1, V2, FMFSource, Name);
196   }
197   static BinaryOperator *CreateFNegFMF(Value *Op, BinaryOperator *FMFSource,
198                                        const Twine &Name = "") {
199     Value *Zero = ConstantFP::getNegativeZero(Op->getType());
200     return CreateWithCopiedFlags(Instruction::FSub, Zero, Op, FMFSource);
201   }
202
203   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
204                                    const Twine &Name = "") {
205     BinaryOperator *BO = Create(Opc, V1, V2, Name);
206     BO->setHasNoSignedWrap(true);
207     return BO;
208   }
209   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
210                                    const Twine &Name, BasicBlock *BB) {
211     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
212     BO->setHasNoSignedWrap(true);
213     return BO;
214   }
215   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
216                                    const Twine &Name, Instruction *I) {
217     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
218     BO->setHasNoSignedWrap(true);
219     return BO;
220   }
221
222   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
223                                    const Twine &Name = "") {
224     BinaryOperator *BO = Create(Opc, V1, V2, Name);
225     BO->setHasNoUnsignedWrap(true);
226     return BO;
227   }
228   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
229                                    const Twine &Name, BasicBlock *BB) {
230     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
231     BO->setHasNoUnsignedWrap(true);
232     return BO;
233   }
234   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
235                                    const Twine &Name, Instruction *I) {
236     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
237     BO->setHasNoUnsignedWrap(true);
238     return BO;
239   }
240
241   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
242                                      const Twine &Name = "") {
243     BinaryOperator *BO = Create(Opc, V1, V2, Name);
244     BO->setIsExact(true);
245     return BO;
246   }
247   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
248                                      const Twine &Name, BasicBlock *BB) {
249     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
250     BO->setIsExact(true);
251     return BO;
252   }
253   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
254                                      const Twine &Name, Instruction *I) {
255     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
256     BO->setIsExact(true);
257     return BO;
258   }
259
260 #define DEFINE_HELPERS(OPC, NUWNSWEXACT)                                       \
261   static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2,        \
262                                                   const Twine &Name = "") {    \
263     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name);                \
264   }                                                                            \
265   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
266       Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) {               \
267     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB);            \
268   }                                                                            \
269   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
270       Value *V1, Value *V2, const Twine &Name, Instruction *I) {               \
271     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I);             \
272   }
273
274   DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
275   DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
276   DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
277   DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
278   DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
279   DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
280   DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
281   DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
282
283   DEFINE_HELPERS(SDiv, Exact)  // CreateExactSDiv
284   DEFINE_HELPERS(UDiv, Exact)  // CreateExactUDiv
285   DEFINE_HELPERS(AShr, Exact)  // CreateExactAShr
286   DEFINE_HELPERS(LShr, Exact)  // CreateExactLShr
287
288 #undef DEFINE_HELPERS
289
290   /// Helper functions to construct and inspect unary operations (NEG and NOT)
291   /// via binary operators SUB and XOR:
292   ///
293   /// Create the NEG and NOT instructions out of SUB and XOR instructions.
294   ///
295   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
296                                    Instruction *InsertBefore = nullptr);
297   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
298                                    BasicBlock *InsertAtEnd);
299   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
300                                       Instruction *InsertBefore = nullptr);
301   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
302                                       BasicBlock *InsertAtEnd);
303   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
304                                       Instruction *InsertBefore = nullptr);
305   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
306                                       BasicBlock *InsertAtEnd);
307   static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
308                                     Instruction *InsertBefore = nullptr);
309   static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
310                                     BasicBlock *InsertAtEnd);
311   static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
312                                    Instruction *InsertBefore = nullptr);
313   static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
314                                    BasicBlock *InsertAtEnd);
315
316   BinaryOps getOpcode() const {
317     return static_cast<BinaryOps>(Instruction::getOpcode());
318   }
319
320   /// Exchange the two operands to this instruction.
321   /// This instruction is safe to use on any binary instruction and
322   /// does not modify the semantics of the instruction.  If the instruction
323   /// cannot be reversed (ie, it's a Div), then return true.
324   ///
325   bool swapOperands();
326
327   // Methods for support type inquiry through isa, cast, and dyn_cast:
328   static bool classof(const Instruction *I) {
329     return I->isBinaryOp();
330   }
331   static bool classof(const Value *V) {
332     return isa<Instruction>(V) && classof(cast<Instruction>(V));
333   }
334 };
335
336 template <>
337 struct OperandTraits<BinaryOperator> :
338   public FixedNumOperandTraits<BinaryOperator, 2> {
339 };
340
341 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
342
343 //===----------------------------------------------------------------------===//
344 //                               CastInst Class
345 //===----------------------------------------------------------------------===//
346
347 /// This is the base class for all instructions that perform data
348 /// casts. It is simply provided so that instruction category testing
349 /// can be performed with code like:
350 ///
351 /// if (isa<CastInst>(Instr)) { ... }
352 /// Base class of casting instructions.
353 class CastInst : public UnaryInstruction {
354 protected:
355   /// Constructor with insert-before-instruction semantics for subclasses
356   CastInst(Type *Ty, unsigned iType, Value *S,
357            const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
358     : UnaryInstruction(Ty, iType, S, InsertBefore) {
359     setName(NameStr);
360   }
361   /// Constructor with insert-at-end-of-block semantics for subclasses
362   CastInst(Type *Ty, unsigned iType, Value *S,
363            const Twine &NameStr, BasicBlock *InsertAtEnd)
364     : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
365     setName(NameStr);
366   }
367
368 public:
369   /// Provides a way to construct any of the CastInst subclasses using an
370   /// opcode instead of the subclass's constructor. The opcode must be in the
371   /// CastOps category (Instruction::isCast(opcode) returns true). This
372   /// constructor has insert-before-instruction semantics to automatically
373   /// insert the new CastInst before InsertBefore (if it is non-null).
374   /// Construct any of the CastInst subclasses
375   static CastInst *Create(
376     Instruction::CastOps,    ///< The opcode of the cast instruction
377     Value *S,                ///< The value to be casted (operand 0)
378     Type *Ty,          ///< The type to which cast should be made
379     const Twine &Name = "", ///< Name for the instruction
380     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
381   );
382   /// Provides a way to construct any of the CastInst subclasses using an
383   /// opcode instead of the subclass's constructor. The opcode must be in the
384   /// CastOps category. This constructor has insert-at-end-of-block semantics
385   /// to automatically insert the new CastInst at the end of InsertAtEnd (if
386   /// its non-null).
387   /// Construct any of the CastInst subclasses
388   static CastInst *Create(
389     Instruction::CastOps,    ///< The opcode for the cast instruction
390     Value *S,                ///< The value to be casted (operand 0)
391     Type *Ty,          ///< The type to which operand is casted
392     const Twine &Name, ///< The name for the instruction
393     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
394   );
395
396   /// Create a ZExt or BitCast cast instruction
397   static CastInst *CreateZExtOrBitCast(
398     Value *S,                ///< The value to be casted (operand 0)
399     Type *Ty,          ///< The type to which cast should be made
400     const Twine &Name = "", ///< Name for the instruction
401     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
402   );
403
404   /// Create a ZExt or BitCast cast instruction
405   static CastInst *CreateZExtOrBitCast(
406     Value *S,                ///< The value to be casted (operand 0)
407     Type *Ty,          ///< The type to which operand is casted
408     const Twine &Name, ///< The name for the instruction
409     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
410   );
411
412   /// Create a SExt or BitCast cast instruction
413   static CastInst *CreateSExtOrBitCast(
414     Value *S,                ///< The value to be casted (operand 0)
415     Type *Ty,          ///< The type to which cast should be made
416     const Twine &Name = "", ///< Name for the instruction
417     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
418   );
419
420   /// Create a SExt or BitCast cast instruction
421   static CastInst *CreateSExtOrBitCast(
422     Value *S,                ///< The value to be casted (operand 0)
423     Type *Ty,          ///< The type to which operand is casted
424     const Twine &Name, ///< The name for the instruction
425     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
426   );
427
428   /// Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
429   static CastInst *CreatePointerCast(
430     Value *S,                ///< The pointer value to be casted (operand 0)
431     Type *Ty,          ///< The type to which operand is casted
432     const Twine &Name, ///< The name for the instruction
433     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
434   );
435
436   /// Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
437   static CastInst *CreatePointerCast(
438     Value *S,                ///< The pointer value to be casted (operand 0)
439     Type *Ty,          ///< The type to which cast should be made
440     const Twine &Name = "", ///< Name for the instruction
441     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
442   );
443
444   /// Create a BitCast or an AddrSpaceCast cast instruction.
445   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
446     Value *S,                ///< The pointer value to be casted (operand 0)
447     Type *Ty,          ///< The type to which operand is casted
448     const Twine &Name, ///< The name for the instruction
449     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
450   );
451
452   /// Create a BitCast or an AddrSpaceCast cast instruction.
453   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
454     Value *S,                ///< The pointer value to be casted (operand 0)
455     Type *Ty,          ///< The type to which cast should be made
456     const Twine &Name = "", ///< Name for the instruction
457     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
458   );
459
460   /// Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
461   ///
462   /// If the value is a pointer type and the destination an integer type,
463   /// creates a PtrToInt cast. If the value is an integer type and the
464   /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
465   /// a bitcast.
466   static CastInst *CreateBitOrPointerCast(
467     Value *S,                ///< The pointer value to be casted (operand 0)
468     Type *Ty,          ///< The type to which cast should be made
469     const Twine &Name = "", ///< Name for the instruction
470     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
471   );
472
473   /// Create a ZExt, BitCast, or Trunc for int -> int casts.
474   static CastInst *CreateIntegerCast(
475     Value *S,                ///< The pointer value to be casted (operand 0)
476     Type *Ty,          ///< The type to which cast should be made
477     bool isSigned,           ///< Whether to regard S as signed or not
478     const Twine &Name = "", ///< Name for the instruction
479     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
480   );
481
482   /// Create a ZExt, BitCast, or Trunc for int -> int casts.
483   static CastInst *CreateIntegerCast(
484     Value *S,                ///< The integer value to be casted (operand 0)
485     Type *Ty,          ///< The integer type to which operand is casted
486     bool isSigned,           ///< Whether to regard S as signed or not
487     const Twine &Name, ///< The name for the instruction
488     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
489   );
490
491   /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
492   static CastInst *CreateFPCast(
493     Value *S,                ///< The floating point value to be casted
494     Type *Ty,          ///< The floating point type to cast to
495     const Twine &Name = "", ///< Name for the instruction
496     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
497   );
498
499   /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
500   static CastInst *CreateFPCast(
501     Value *S,                ///< The floating point value to be casted
502     Type *Ty,          ///< The floating point type to cast to
503     const Twine &Name, ///< The name for the instruction
504     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
505   );
506
507   /// Create a Trunc or BitCast cast instruction
508   static CastInst *CreateTruncOrBitCast(
509     Value *S,                ///< The value to be casted (operand 0)
510     Type *Ty,          ///< The type to which cast should be made
511     const Twine &Name = "", ///< Name for the instruction
512     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
513   );
514
515   /// Create a Trunc or BitCast cast instruction
516   static CastInst *CreateTruncOrBitCast(
517     Value *S,                ///< The value to be casted (operand 0)
518     Type *Ty,          ///< The type to which operand is casted
519     const Twine &Name, ///< The name for the instruction
520     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
521   );
522
523   /// Check whether it is valid to call getCastOpcode for these types.
524   static bool isCastable(
525     Type *SrcTy, ///< The Type from which the value should be cast.
526     Type *DestTy ///< The Type to which the value should be cast.
527   );
528
529   /// Check whether a bitcast between these types is valid
530   static bool isBitCastable(
531     Type *SrcTy, ///< The Type from which the value should be cast.
532     Type *DestTy ///< The Type to which the value should be cast.
533   );
534
535   /// Check whether a bitcast, inttoptr, or ptrtoint cast between these
536   /// types is valid and a no-op.
537   ///
538   /// This ensures that any pointer<->integer cast has enough bits in the
539   /// integer and any other cast is a bitcast.
540   static bool isBitOrNoopPointerCastable(
541       Type *SrcTy,  ///< The Type from which the value should be cast.
542       Type *DestTy, ///< The Type to which the value should be cast.
543       const DataLayout &DL);
544
545   /// Returns the opcode necessary to cast Val into Ty using usual casting
546   /// rules.
547   /// Infer the opcode for cast operand and type
548   static Instruction::CastOps getCastOpcode(
549     const Value *Val, ///< The value to cast
550     bool SrcIsSigned, ///< Whether to treat the source as signed
551     Type *Ty,   ///< The Type to which the value should be casted
552     bool DstIsSigned  ///< Whether to treate the dest. as signed
553   );
554
555   /// There are several places where we need to know if a cast instruction
556   /// only deals with integer source and destination types. To simplify that
557   /// logic, this method is provided.
558   /// @returns true iff the cast has only integral typed operand and dest type.
559   /// Determine if this is an integer-only cast.
560   bool isIntegerCast() const;
561
562   /// A lossless cast is one that does not alter the basic value. It implies
563   /// a no-op cast but is more stringent, preventing things like int->float,
564   /// long->double, or int->ptr.
565   /// @returns true iff the cast is lossless.
566   /// Determine if this is a lossless cast.
567   bool isLosslessCast() const;
568
569   /// A no-op cast is one that can be effected without changing any bits.
570   /// It implies that the source and destination types are the same size. The
571   /// DataLayout argument is to determine the pointer size when examining casts
572   /// involving Integer and Pointer types. They are no-op casts if the integer
573   /// is the same size as the pointer. However, pointer size varies with
574   /// platform.
575   /// Determine if the described cast is a no-op cast.
576   static bool isNoopCast(
577     Instruction::CastOps Opcode, ///< Opcode of cast
578     Type *SrcTy,         ///< SrcTy of cast
579     Type *DstTy,         ///< DstTy of cast
580     const DataLayout &DL ///< DataLayout to get the Int Ptr type from.
581   );
582
583   /// Determine if this cast is a no-op cast.
584   ///
585   /// \param DL is the DataLayout to determine pointer size.
586   bool isNoopCast(const DataLayout &DL) const;
587
588   /// Determine how a pair of casts can be eliminated, if they can be at all.
589   /// This is a helper function for both CastInst and ConstantExpr.
590   /// @returns 0 if the CastInst pair can't be eliminated, otherwise
591   /// returns Instruction::CastOps value for a cast that can replace
592   /// the pair, casting SrcTy to DstTy.
593   /// Determine if a cast pair is eliminable
594   static unsigned isEliminableCastPair(
595     Instruction::CastOps firstOpcode,  ///< Opcode of first cast
596     Instruction::CastOps secondOpcode, ///< Opcode of second cast
597     Type *SrcTy, ///< SrcTy of 1st cast
598     Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
599     Type *DstTy, ///< DstTy of 2nd cast
600     Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
601     Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
602     Type *DstIntPtrTy  ///< Integer type corresponding to Ptr DstTy, or null
603   );
604
605   /// Return the opcode of this CastInst
606   Instruction::CastOps getOpcode() const {
607     return Instruction::CastOps(Instruction::getOpcode());
608   }
609
610   /// Return the source type, as a convenience
611   Type* getSrcTy() const { return getOperand(0)->getType(); }
612   /// Return the destination type, as a convenience
613   Type* getDestTy() const { return getType(); }
614
615   /// This method can be used to determine if a cast from S to DstTy using
616   /// Opcode op is valid or not.
617   /// @returns true iff the proposed cast is valid.
618   /// Determine if a cast is valid without creating one.
619   static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
620
621   /// Methods for support type inquiry through isa, cast, and dyn_cast:
622   static bool classof(const Instruction *I) {
623     return I->isCast();
624   }
625   static bool classof(const Value *V) {
626     return isa<Instruction>(V) && classof(cast<Instruction>(V));
627   }
628 };
629
630 //===----------------------------------------------------------------------===//
631 //                               CmpInst Class
632 //===----------------------------------------------------------------------===//
633
634 /// This class is the base class for the comparison instructions.
635 /// Abstract base class of comparison instructions.
636 class CmpInst : public Instruction {
637 public:
638   /// This enumeration lists the possible predicates for CmpInst subclasses.
639   /// Values in the range 0-31 are reserved for FCmpInst, while values in the
640   /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
641   /// predicate values are not overlapping between the classes.
642   ///
643   /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of
644   /// FCMP_* values. Changing the bit patterns requires a potential change to
645   /// those passes.
646   enum Predicate {
647     // Opcode              U L G E    Intuitive operation
648     FCMP_FALSE =  0,  ///< 0 0 0 0    Always false (always folded)
649     FCMP_OEQ   =  1,  ///< 0 0 0 1    True if ordered and equal
650     FCMP_OGT   =  2,  ///< 0 0 1 0    True if ordered and greater than
651     FCMP_OGE   =  3,  ///< 0 0 1 1    True if ordered and greater than or equal
652     FCMP_OLT   =  4,  ///< 0 1 0 0    True if ordered and less than
653     FCMP_OLE   =  5,  ///< 0 1 0 1    True if ordered and less than or equal
654     FCMP_ONE   =  6,  ///< 0 1 1 0    True if ordered and operands are unequal
655     FCMP_ORD   =  7,  ///< 0 1 1 1    True if ordered (no nans)
656     FCMP_UNO   =  8,  ///< 1 0 0 0    True if unordered: isnan(X) | isnan(Y)
657     FCMP_UEQ   =  9,  ///< 1 0 0 1    True if unordered or equal
658     FCMP_UGT   = 10,  ///< 1 0 1 0    True if unordered or greater than
659     FCMP_UGE   = 11,  ///< 1 0 1 1    True if unordered, greater than, or equal
660     FCMP_ULT   = 12,  ///< 1 1 0 0    True if unordered or less than
661     FCMP_ULE   = 13,  ///< 1 1 0 1    True if unordered, less than, or equal
662     FCMP_UNE   = 14,  ///< 1 1 1 0    True if unordered or not equal
663     FCMP_TRUE  = 15,  ///< 1 1 1 1    Always true (always folded)
664     FIRST_FCMP_PREDICATE = FCMP_FALSE,
665     LAST_FCMP_PREDICATE = FCMP_TRUE,
666     BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
667     ICMP_EQ    = 32,  ///< equal
668     ICMP_NE    = 33,  ///< not equal
669     ICMP_UGT   = 34,  ///< unsigned greater than
670     ICMP_UGE   = 35,  ///< unsigned greater or equal
671     ICMP_ULT   = 36,  ///< unsigned less than
672     ICMP_ULE   = 37,  ///< unsigned less or equal
673     ICMP_SGT   = 38,  ///< signed greater than
674     ICMP_SGE   = 39,  ///< signed greater or equal
675     ICMP_SLT   = 40,  ///< signed less than
676     ICMP_SLE   = 41,  ///< signed less or equal
677     FIRST_ICMP_PREDICATE = ICMP_EQ,
678     LAST_ICMP_PREDICATE = ICMP_SLE,
679     BAD_ICMP_PREDICATE = ICMP_SLE + 1
680   };
681
682 protected:
683   CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
684           Value *LHS, Value *RHS, const Twine &Name = "",
685           Instruction *InsertBefore = nullptr,
686           Instruction *FlagsSource = nullptr);
687
688   CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
689           Value *LHS, Value *RHS, const Twine &Name,
690           BasicBlock *InsertAtEnd);
691
692 public:
693   // allocate space for exactly two operands
694   void *operator new(size_t s) {
695     return User::operator new(s, 2);
696   }
697
698   /// Construct a compare instruction, given the opcode, the predicate and
699   /// the two operands.  Optionally (if InstBefore is specified) insert the
700   /// instruction into a BasicBlock right before the specified instruction.
701   /// The specified Instruction is allowed to be a dereferenced end iterator.
702   /// Create a CmpInst
703   static CmpInst *Create(OtherOps Op,
704                          Predicate predicate, Value *S1,
705                          Value *S2, const Twine &Name = "",
706                          Instruction *InsertBefore = nullptr);
707
708   /// Construct a compare instruction, given the opcode, the predicate and the
709   /// two operands.  Also automatically insert this instruction to the end of
710   /// the BasicBlock specified.
711   /// Create a CmpInst
712   static CmpInst *Create(OtherOps Op, Predicate predicate, Value *S1,
713                          Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
714
715   /// Get the opcode casted to the right type
716   OtherOps getOpcode() const {
717     return static_cast<OtherOps>(Instruction::getOpcode());
718   }
719
720   /// Return the predicate for this instruction.
721   Predicate getPredicate() const {
722     return Predicate(getSubclassDataFromInstruction());
723   }
724
725   /// Set the predicate for this instruction to the specified value.
726   void setPredicate(Predicate P) { setInstructionSubclassData(P); }
727
728   static bool isFPPredicate(Predicate P) {
729     return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
730   }
731
732   static bool isIntPredicate(Predicate P) {
733     return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
734   }
735
736   static StringRef getPredicateName(Predicate P);
737
738   bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
739   bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
740
741   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
742   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
743   /// @returns the inverse predicate for the instruction's current predicate.
744   /// Return the inverse of the instruction's predicate.
745   Predicate getInversePredicate() const {
746     return getInversePredicate(getPredicate());
747   }
748
749   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
750   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
751   /// @returns the inverse predicate for predicate provided in \p pred.
752   /// Return the inverse of a given predicate
753   static Predicate getInversePredicate(Predicate pred);
754
755   /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
756   ///              OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
757   /// @returns the predicate that would be the result of exchanging the two
758   /// operands of the CmpInst instruction without changing the result
759   /// produced.
760   /// Return the predicate as if the operands were swapped
761   Predicate getSwappedPredicate() const {
762     return getSwappedPredicate(getPredicate());
763   }
764
765   /// This is a static version that you can use without an instruction
766   /// available.
767   /// Return the predicate as if the operands were swapped.
768   static Predicate getSwappedPredicate(Predicate pred);
769
770   /// For predicate of kind "is X or equal to 0" returns the predicate "is X".
771   /// For predicate of kind "is X" returns the predicate "is X or equal to 0".
772   /// does not support other kind of predicates.
773   /// @returns the predicate that does not contains is equal to zero if
774   /// it had and vice versa.
775   /// Return the flipped strictness of predicate
776   Predicate getFlippedStrictnessPredicate() const {
777     return getFlippedStrictnessPredicate(getPredicate());
778   }
779
780   /// This is a static version that you can use without an instruction
781   /// available.
782   /// Return the flipped strictness of predicate
783   static Predicate getFlippedStrictnessPredicate(Predicate pred);
784
785   /// For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
786   /// Returns the non-strict version of strict comparisons.
787   Predicate getNonStrictPredicate() const {
788     return getNonStrictPredicate(getPredicate());
789   }
790
791   /// This is a static version that you can use without an instruction
792   /// available.
793   /// @returns the non-strict version of comparison provided in \p pred.
794   /// If \p pred is not a strict comparison predicate, returns \p pred.
795   /// Returns the non-strict version of strict comparisons.
796   static Predicate getNonStrictPredicate(Predicate pred);
797
798   /// Provide more efficient getOperand methods.
799   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
800
801   /// This is just a convenience that dispatches to the subclasses.
802   /// Swap the operands and adjust predicate accordingly to retain
803   /// the same comparison.
804   void swapOperands();
805
806   /// This is just a convenience that dispatches to the subclasses.
807   /// Determine if this CmpInst is commutative.
808   bool isCommutative() const;
809
810   /// This is just a convenience that dispatches to the subclasses.
811   /// Determine if this is an equals/not equals predicate.
812   bool isEquality() const;
813
814   /// @returns true if the comparison is signed, false otherwise.
815   /// Determine if this instruction is using a signed comparison.
816   bool isSigned() const {
817     return isSigned(getPredicate());
818   }
819
820   /// @returns true if the comparison is unsigned, false otherwise.
821   /// Determine if this instruction is using an unsigned comparison.
822   bool isUnsigned() const {
823     return isUnsigned(getPredicate());
824   }
825
826   /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
827   /// @returns the signed version of the unsigned predicate pred.
828   /// return the signed version of a predicate
829   static Predicate getSignedPredicate(Predicate pred);
830
831   /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
832   /// @returns the signed version of the predicate for this instruction (which
833   /// has to be an unsigned predicate).
834   /// return the signed version of a predicate
835   Predicate getSignedPredicate() {
836     return getSignedPredicate(getPredicate());
837   }
838
839   /// This is just a convenience.
840   /// Determine if this is true when both operands are the same.
841   bool isTrueWhenEqual() const {
842     return isTrueWhenEqual(getPredicate());
843   }
844
845   /// This is just a convenience.
846   /// Determine if this is false when both operands are the same.
847   bool isFalseWhenEqual() const {
848     return isFalseWhenEqual(getPredicate());
849   }
850
851   /// @returns true if the predicate is unsigned, false otherwise.
852   /// Determine if the predicate is an unsigned operation.
853   static bool isUnsigned(Predicate predicate);
854
855   /// @returns true if the predicate is signed, false otherwise.
856   /// Determine if the predicate is an signed operation.
857   static bool isSigned(Predicate predicate);
858
859   /// Determine if the predicate is an ordered operation.
860   static bool isOrdered(Predicate predicate);
861
862   /// Determine if the predicate is an unordered operation.
863   static bool isUnordered(Predicate predicate);
864
865   /// Determine if the predicate is true when comparing a value with itself.
866   static bool isTrueWhenEqual(Predicate predicate);
867
868   /// Determine if the predicate is false when comparing a value with itself.
869   static bool isFalseWhenEqual(Predicate predicate);
870
871   /// Determine if Pred1 implies Pred2 is true when two compares have matching
872   /// operands.
873   static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2);
874
875   /// Determine if Pred1 implies Pred2 is false when two compares have matching
876   /// operands.
877   static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2);
878
879   /// Methods for support type inquiry through isa, cast, and dyn_cast:
880   static bool classof(const Instruction *I) {
881     return I->getOpcode() == Instruction::ICmp ||
882            I->getOpcode() == Instruction::FCmp;
883   }
884   static bool classof(const Value *V) {
885     return isa<Instruction>(V) && classof(cast<Instruction>(V));
886   }
887
888   /// Create a result type for fcmp/icmp
889   static Type* makeCmpResultType(Type* opnd_type) {
890     if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
891       return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
892                              vt->getNumElements());
893     }
894     return Type::getInt1Ty(opnd_type->getContext());
895   }
896
897 private:
898   // Shadow Value::setValueSubclassData with a private forwarding method so that
899   // subclasses cannot accidentally use it.
900   void setValueSubclassData(unsigned short D) {
901     Value::setValueSubclassData(D);
902   }
903 };
904
905 // FIXME: these are redundant if CmpInst < BinaryOperator
906 template <>
907 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
908 };
909
910 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
911
912 /// A lightweight accessor for an operand bundle meant to be passed
913 /// around by value.
914 struct OperandBundleUse {
915   ArrayRef<Use> Inputs;
916
917   OperandBundleUse() = default;
918   explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
919       : Inputs(Inputs), Tag(Tag) {}
920
921   /// Return true if the operand at index \p Idx in this operand bundle
922   /// has the attribute A.
923   bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const {
924     if (isDeoptOperandBundle())
925       if (A == Attribute::ReadOnly || A == Attribute::NoCapture)
926         return Inputs[Idx]->getType()->isPointerTy();
927
928     // Conservative answer:  no operands have any attributes.
929     return false;
930   }
931
932   /// Return the tag of this operand bundle as a string.
933   StringRef getTagName() const {
934     return Tag->getKey();
935   }
936
937   /// Return the tag of this operand bundle as an integer.
938   ///
939   /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
940   /// and this function returns the unique integer getOrInsertBundleTag
941   /// associated the tag of this operand bundle to.
942   uint32_t getTagID() const {
943     return Tag->getValue();
944   }
945
946   /// Return true if this is a "deopt" operand bundle.
947   bool isDeoptOperandBundle() const {
948     return getTagID() == LLVMContext::OB_deopt;
949   }
950
951   /// Return true if this is a "funclet" operand bundle.
952   bool isFuncletOperandBundle() const {
953     return getTagID() == LLVMContext::OB_funclet;
954   }
955
956 private:
957   /// Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
958   StringMapEntry<uint32_t> *Tag;
959 };
960
961 /// A container for an operand bundle being viewed as a set of values
962 /// rather than a set of uses.
963 ///
964 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
965 /// so it is possible to create and pass around "self-contained" instances of
966 /// OperandBundleDef and ConstOperandBundleDef.
967 template <typename InputTy> class OperandBundleDefT {
968   std::string Tag;
969   std::vector<InputTy> Inputs;
970
971 public:
972   explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
973       : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
974   explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs)
975       : Tag(std::move(Tag)), Inputs(Inputs) {}
976
977   explicit OperandBundleDefT(const OperandBundleUse &OBU) {
978     Tag = OBU.getTagName();
979     Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
980   }
981
982   ArrayRef<InputTy> inputs() const { return Inputs; }
983
984   using input_iterator = typename std::vector<InputTy>::const_iterator;
985
986   size_t input_size() const { return Inputs.size(); }
987   input_iterator input_begin() const { return Inputs.begin(); }
988   input_iterator input_end() const { return Inputs.end(); }
989
990   StringRef getTag() const { return Tag; }
991 };
992
993 using OperandBundleDef = OperandBundleDefT<Value *>;
994 using ConstOperandBundleDef = OperandBundleDefT<const Value *>;
995
996 //===----------------------------------------------------------------------===//
997 //                               CallBase Class
998 //===----------------------------------------------------------------------===//
999
1000 /// Base class for all callable instructions (InvokeInst and CallInst)
1001 /// Holds everything related to calling a function.
1002 ///
1003 /// All call-like instructions are required to use a common operand layout:
1004 /// - Zero or more arguments to the call,
1005 /// - Zero or more operand bundles with zero or more operand inputs each
1006 ///   bundle,
1007 /// - Zero or more subclass controlled operands
1008 /// - The called function.
1009 ///
1010 /// This allows this base class to easily access the called function and the
1011 /// start of the arguments without knowing how many other operands a particular
1012 /// subclass requires. Note that accessing the end of the argument list isn't
1013 /// as cheap as most other operations on the base class.
1014 class CallBase : public Instruction {
1015 protected:
1016   /// The last operand is the called operand.
1017   static constexpr int CalledOperandOpEndIdx = -1;
1018
1019   AttributeList Attrs; ///< parameter attributes for callable
1020   FunctionType *FTy;
1021
1022   template <class... ArgsTy>
1023   CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args)
1024       : Instruction(std::forward<ArgsTy>(Args)...), Attrs(A), FTy(FT) {}
1025
1026   using Instruction::Instruction;
1027
1028   bool hasDescriptor() const { return Value::HasDescriptor; }
1029
1030   unsigned getNumSubclassExtraOperands() const {
1031     switch (getOpcode()) {
1032     case Instruction::Call:
1033       return 0;
1034     case Instruction::Invoke:
1035       return 2;
1036     }
1037     llvm_unreachable("Invalid opcode!");
1038   }
1039
1040 public:
1041   using Instruction::getContext;
1042
1043   static bool classof(const Instruction *I) {
1044     return I->getOpcode() == Instruction::Call ||
1045            I->getOpcode() == Instruction::Invoke;
1046   }
1047   static bool classof(const Value *V) {
1048     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1049   }
1050
1051   FunctionType *getFunctionType() const { return FTy; }
1052
1053   void mutateFunctionType(FunctionType *FTy) {
1054     Value::mutateType(FTy->getReturnType());
1055     this->FTy = FTy;
1056   }
1057
1058   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1059
1060   /// data_operands_begin/data_operands_end - Return iterators iterating over
1061   /// the call / invoke argument list and bundle operands.  For invokes, this is
1062   /// the set of instruction operands except the invoke target and the two
1063   /// successor blocks; and for calls this is the set of instruction operands
1064   /// except the call target.
1065   User::op_iterator data_operands_begin() { return op_begin(); }
1066   User::const_op_iterator data_operands_begin() const {
1067     return const_cast<CallBase *>(this)->data_operands_begin();
1068   }
1069   User::op_iterator data_operands_end() {
1070     // Walk from the end of the operands over the called operand and any
1071     // subclass operands.
1072     return op_end() - getNumSubclassExtraOperands() - 1;
1073   }
1074   User::const_op_iterator data_operands_end() const {
1075     return const_cast<CallBase *>(this)->data_operands_end();
1076   }
1077   iterator_range<User::op_iterator> data_ops() {
1078     return make_range(data_operands_begin(), data_operands_end());
1079   }
1080   iterator_range<User::const_op_iterator> data_ops() const {
1081     return make_range(data_operands_begin(), data_operands_end());
1082   }
1083   bool data_operands_empty() const {
1084     return data_operands_end() == data_operands_begin();
1085   }
1086   unsigned data_operands_size() const {
1087     return std::distance(data_operands_begin(), data_operands_end());
1088   }
1089
1090   bool isDataOperand(const Use *U) const {
1091     assert(this == U->getUser() &&
1092            "Only valid to query with a use of this instruction!");
1093     return data_operands_begin() <= U && U < data_operands_end();
1094   }
1095   bool isDataOperand(Value::const_user_iterator UI) const {
1096     return isDataOperand(&UI.getUse());
1097   }
1098
1099   /// Return the iterator pointing to the beginning of the argument list.
1100   User::op_iterator arg_begin() { return op_begin(); }
1101   User::const_op_iterator arg_begin() const {
1102     return const_cast<CallBase *>(this)->arg_begin();
1103   }
1104
1105   /// Return the iterator pointing to the end of the argument list.
1106   User::op_iterator arg_end() {
1107     // From the end of the data operands, walk backwards past the bundle
1108     // operands.
1109     return data_operands_end() - getNumTotalBundleOperands();
1110   }
1111   User::const_op_iterator arg_end() const {
1112     return const_cast<CallBase *>(this)->arg_end();
1113   }
1114
1115   /// Iteration adapter for range-for loops.
1116   iterator_range<User::op_iterator> args() {
1117     return make_range(arg_begin(), arg_end());
1118   }
1119   iterator_range<User::const_op_iterator> args() const {
1120     return make_range(arg_begin(), arg_end());
1121   }
1122   bool arg_empty() const { return arg_end() == arg_begin(); }
1123   unsigned arg_size() const { return arg_end() - arg_begin(); }
1124
1125   // Legacy API names that duplicate the above and will be removed once users
1126   // are migrated.
1127   iterator_range<User::op_iterator> arg_operands() {
1128     return make_range(arg_begin(), arg_end());
1129   }
1130   iterator_range<User::const_op_iterator> arg_operands() const {
1131     return make_range(arg_begin(), arg_end());
1132   }
1133   unsigned getNumArgOperands() const { return arg_size(); }
1134
1135   Value *getArgOperand(unsigned i) const {
1136     assert(i < getNumArgOperands() && "Out of bounds!");
1137     return getOperand(i);
1138   }
1139
1140   void setArgOperand(unsigned i, Value *v) {
1141     assert(i < getNumArgOperands() && "Out of bounds!");
1142     setOperand(i, v);
1143   }
1144
1145   /// Wrappers for getting the \c Use of a call argument.
1146   const Use &getArgOperandUse(unsigned i) const {
1147     assert(i < getNumArgOperands() && "Out of bounds!");
1148     return User::getOperandUse(i);
1149   }
1150   Use &getArgOperandUse(unsigned i) {
1151     assert(i < getNumArgOperands() && "Out of bounds!");
1152     return User::getOperandUse(i);
1153   }
1154
1155   bool isArgOperand(const Use *U) const {
1156     assert(this == U->getUser() &&
1157            "Only valid to query with a use of this instruction!");
1158     return arg_begin() <= U && U < arg_end();
1159   }
1160   bool isArgOperand(Value::const_user_iterator UI) const {
1161     return isArgOperand(&UI.getUse());
1162   }
1163
1164   /// Returns true if this CallSite passes the given Value* as an argument to
1165   /// the called function.
1166   bool hasArgument(const Value *V) const {
1167     return llvm::any_of(args(), [V](const Value *Arg) { return Arg == V; });
1168   }
1169
1170   Value *getCalledOperand() const { return Op<CalledOperandOpEndIdx>(); }
1171
1172   // DEPRECATED: This routine will be removed in favor of `getCalledOperand` in
1173   // the near future.
1174   Value *getCalledValue() const { return getCalledOperand(); }
1175
1176   const Use &getCalledOperandUse() const { return Op<CalledOperandOpEndIdx>(); }
1177   Use &getCalledOperandUse() { return Op<CalledOperandOpEndIdx>(); }
1178
1179   /// Returns the function called, or null if this is an
1180   /// indirect function invocation.
1181   Function *getCalledFunction() const {
1182     return dyn_cast_or_null<Function>(getCalledOperand());
1183   }
1184
1185   /// Return true if the callsite is an indirect call.
1186   bool isIndirectCall() const;
1187
1188   /// Determine whether the passed iterator points to the callee operand's Use.
1189   bool isCallee(Value::const_user_iterator UI) const {
1190     return isCallee(&UI.getUse());
1191   }
1192
1193   /// Determine whether this Use is the callee operand's Use.
1194   bool isCallee(const Use *U) const { return &getCalledOperandUse() == U; }
1195
1196   /// Helper to get the caller (the parent function).
1197   Function *getCaller();
1198   const Function *getCaller() const {
1199     return const_cast<CallBase *>(this)->getCaller();
1200   }
1201
1202   /// Returns the intrinsic ID of the intrinsic called or
1203   /// Intrinsic::not_intrinsic if the called function is not an intrinsic, or if
1204   /// this is an indirect call.
1205   Intrinsic::ID getIntrinsicID() const;
1206
1207   void setCalledOperand(Value *V) { Op<CalledOperandOpEndIdx>() = V; }
1208
1209   /// Sets the function called, including updating the function type.
1210   void setCalledFunction(Value *Fn) {
1211     setCalledFunction(
1212         cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1213         Fn);
1214   }
1215
1216   /// Sets the function called, including updating to the specified function
1217   /// type.
1218   void setCalledFunction(FunctionType *FTy, Value *Fn) {
1219     this->FTy = FTy;
1220     assert(FTy == cast<FunctionType>(
1221                       cast<PointerType>(Fn->getType())->getElementType()));
1222     setCalledOperand(Fn);
1223   }
1224
1225   CallingConv::ID getCallingConv() const {
1226     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1227   }
1228
1229   void setCallingConv(CallingConv::ID CC) {
1230     auto ID = static_cast<unsigned>(CC);
1231     assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1232     setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1233                                (ID << 2));
1234   }
1235
1236   /// \name Attribute API
1237   ///
1238   /// These methods access and modify attributes on this call (including
1239   /// looking through to the attributes on the called function when necessary).
1240   ///@{
1241
1242   /// Return the parameter attributes for this call.
1243   ///
1244   AttributeList getAttributes() const { return Attrs; }
1245
1246   /// Set the parameter attributes for this call.
1247   ///
1248   void setAttributes(AttributeList A) { Attrs = A; }
1249
1250   /// Determine whether this call has the given attribute.
1251   bool hasFnAttr(Attribute::AttrKind Kind) const {
1252     assert(Kind != Attribute::NoBuiltin &&
1253            "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin");
1254     return hasFnAttrImpl(Kind);
1255   }
1256
1257   /// Determine whether this call has the given attribute.
1258   bool hasFnAttr(StringRef Kind) const { return hasFnAttrImpl(Kind); }
1259
1260   /// adds the attribute to the list of attributes.
1261   void addAttribute(unsigned i, Attribute::AttrKind Kind) {
1262     AttributeList PAL = getAttributes();
1263     PAL = PAL.addAttribute(getContext(), i, Kind);
1264     setAttributes(PAL);
1265   }
1266
1267   /// adds the attribute to the list of attributes.
1268   void addAttribute(unsigned i, Attribute Attr) {
1269     AttributeList PAL = getAttributes();
1270     PAL = PAL.addAttribute(getContext(), i, Attr);
1271     setAttributes(PAL);
1272   }
1273
1274   /// Adds the attribute to the indicated argument
1275   void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1276     assert(ArgNo < getNumArgOperands() && "Out of bounds");
1277     AttributeList PAL = getAttributes();
1278     PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
1279     setAttributes(PAL);
1280   }
1281
1282   /// Adds the attribute to the indicated argument
1283   void addParamAttr(unsigned ArgNo, Attribute Attr) {
1284     assert(ArgNo < getNumArgOperands() && "Out of bounds");
1285     AttributeList PAL = getAttributes();
1286     PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
1287     setAttributes(PAL);
1288   }
1289
1290   /// removes the attribute from the list of attributes.
1291   void removeAttribute(unsigned i, Attribute::AttrKind Kind) {
1292     AttributeList PAL = getAttributes();
1293     PAL = PAL.removeAttribute(getContext(), i, Kind);
1294     setAttributes(PAL);
1295   }
1296
1297   /// removes the attribute from the list of attributes.
1298   void removeAttribute(unsigned i, StringRef Kind) {
1299     AttributeList PAL = getAttributes();
1300     PAL = PAL.removeAttribute(getContext(), i, Kind);
1301     setAttributes(PAL);
1302   }
1303
1304   /// Removes the attribute from the given argument
1305   void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1306     assert(ArgNo < getNumArgOperands() && "Out of bounds");
1307     AttributeList PAL = getAttributes();
1308     PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1309     setAttributes(PAL);
1310   }
1311
1312   /// Removes the attribute from the given argument
1313   void removeParamAttr(unsigned ArgNo, StringRef Kind) {
1314     assert(ArgNo < getNumArgOperands() && "Out of bounds");
1315     AttributeList PAL = getAttributes();
1316     PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1317     setAttributes(PAL);
1318   }
1319
1320   /// adds the dereferenceable attribute to the list of attributes.
1321   void addDereferenceableAttr(unsigned i, uint64_t Bytes) {
1322     AttributeList PAL = getAttributes();
1323     PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
1324     setAttributes(PAL);
1325   }
1326
1327   /// adds the dereferenceable_or_null attribute to the list of
1328   /// attributes.
1329   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
1330     AttributeList PAL = getAttributes();
1331     PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
1332     setAttributes(PAL);
1333   }
1334
1335   /// Determine whether the return value has the given attribute.
1336   bool hasRetAttr(Attribute::AttrKind Kind) const;
1337
1338   /// Determine whether the argument or parameter has the given attribute.
1339   bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1340
1341   /// Get the attribute of a given kind at a position.
1342   Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
1343     return getAttributes().getAttribute(i, Kind);
1344   }
1345
1346   /// Get the attribute of a given kind at a position.
1347   Attribute getAttribute(unsigned i, StringRef Kind) const {
1348     return getAttributes().getAttribute(i, Kind);
1349   }
1350
1351   /// Get the attribute of a given kind from a given arg
1352   Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1353     assert(ArgNo < getNumArgOperands() && "Out of bounds");
1354     return getAttributes().getParamAttr(ArgNo, Kind);
1355   }
1356
1357   /// Get the attribute of a given kind from a given arg
1358   Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1359     assert(ArgNo < getNumArgOperands() && "Out of bounds");
1360     return getAttributes().getParamAttr(ArgNo, Kind);
1361   }
1362
1363   /// Return true if the data operand at index \p i has the attribute \p
1364   /// A.
1365   ///
1366   /// Data operands include call arguments and values used in operand bundles,
1367   /// but does not include the callee operand.  This routine dispatches to the
1368   /// underlying AttributeList or the OperandBundleUser as appropriate.
1369   ///
1370   /// The index \p i is interpreted as
1371   ///
1372   ///  \p i == Attribute::ReturnIndex  -> the return value
1373   ///  \p i in [1, arg_size + 1)  -> argument number (\p i - 1)
1374   ///  \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1375   ///     (\p i - 1) in the operand list.
1376   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const {
1377     // Note that we have to add one because `i` isn't zero-indexed.
1378     assert(i < (getNumArgOperands() + getNumTotalBundleOperands() + 1) &&
1379            "Data operand index out of bounds!");
1380
1381     // The attribute A can either be directly specified, if the operand in
1382     // question is a call argument; or be indirectly implied by the kind of its
1383     // containing operand bundle, if the operand is a bundle operand.
1384
1385     if (i == AttributeList::ReturnIndex)
1386       return hasRetAttr(Kind);
1387
1388     // FIXME: Avoid these i - 1 calculations and update the API to use
1389     // zero-based indices.
1390     if (i < (getNumArgOperands() + 1))
1391       return paramHasAttr(i - 1, Kind);
1392
1393     assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
1394            "Must be either a call argument or an operand bundle!");
1395     return bundleOperandHasAttr(i - 1, Kind);
1396   }
1397
1398   /// Determine whether this data operand is not captured.
1399   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1400   // better indicate that this may return a conservative answer.
1401   bool doesNotCapture(unsigned OpNo) const {
1402     return dataOperandHasImpliedAttr(OpNo + 1, Attribute::NoCapture);
1403   }
1404
1405   /// Determine whether this argument is passed by value.
1406   bool isByValArgument(unsigned ArgNo) const {
1407     return paramHasAttr(ArgNo, Attribute::ByVal);
1408   }
1409
1410   /// Determine whether this argument is passed in an alloca.
1411   bool isInAllocaArgument(unsigned ArgNo) const {
1412     return paramHasAttr(ArgNo, Attribute::InAlloca);
1413   }
1414
1415   /// Determine whether this argument is passed by value or in an alloca.
1416   bool isByValOrInAllocaArgument(unsigned ArgNo) const {
1417     return paramHasAttr(ArgNo, Attribute::ByVal) ||
1418            paramHasAttr(ArgNo, Attribute::InAlloca);
1419   }
1420
1421   /// Determine if there are is an inalloca argument. Only the last argument can
1422   /// have the inalloca attribute.
1423   bool hasInAllocaArgument() const {
1424     return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca);
1425   }
1426
1427   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1428   // better indicate that this may return a conservative answer.
1429   bool doesNotAccessMemory(unsigned OpNo) const {
1430     return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1431   }
1432
1433   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1434   // better indicate that this may return a conservative answer.
1435   bool onlyReadsMemory(unsigned OpNo) const {
1436     return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadOnly) ||
1437            dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1438   }
1439
1440   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1441   // better indicate that this may return a conservative answer.
1442   bool doesNotReadMemory(unsigned OpNo) const {
1443     return dataOperandHasImpliedAttr(OpNo + 1, Attribute::WriteOnly) ||
1444            dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1445   }
1446
1447   /// Extract the alignment of the return value.
1448   unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
1449
1450   /// Extract the alignment for a call or parameter (0=unknown).
1451   unsigned getParamAlignment(unsigned ArgNo) const {
1452     return Attrs.getParamAlignment(ArgNo);
1453   }
1454
1455   /// Extract the number of dereferenceable bytes for a call or
1456   /// parameter (0=unknown).
1457   uint64_t getDereferenceableBytes(unsigned i) const {
1458     return Attrs.getDereferenceableBytes(i);
1459   }
1460
1461   /// Extract the number of dereferenceable_or_null bytes for a call or
1462   /// parameter (0=unknown).
1463   uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1464     return Attrs.getDereferenceableOrNullBytes(i);
1465   }
1466
1467   /// Return true if the return value is known to be not null.
1468   /// This may be because it has the nonnull attribute, or because at least
1469   /// one byte is dereferenceable and the pointer is in addrspace(0).
1470   bool isReturnNonNull() const;
1471
1472   /// Determine if the return value is marked with NoAlias attribute.
1473   bool returnDoesNotAlias() const {
1474     return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1475   }
1476
1477   /// If one of the arguments has the 'returned' attribute, returns its
1478   /// operand value. Otherwise, return nullptr.
1479   Value *getReturnedArgOperand() const;
1480
1481   /// Return true if the call should not be treated as a call to a
1482   /// builtin.
1483   bool isNoBuiltin() const {
1484     return hasFnAttrImpl(Attribute::NoBuiltin) &&
1485            !hasFnAttrImpl(Attribute::Builtin);
1486   }
1487
1488   /// Determine if the call requires strict floating point semantics.
1489   bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1490
1491   /// Return true if the call should not be inlined.
1492   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1493   void setIsNoInline() {
1494     addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1495   }
1496   /// Determine if the call does not access memory.
1497   bool doesNotAccessMemory() const { return hasFnAttr(Attribute::ReadNone); }
1498   void setDoesNotAccessMemory() {
1499     addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1500   }
1501
1502   /// Determine if the call does not access or only reads memory.
1503   bool onlyReadsMemory() const {
1504     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1505   }
1506   void setOnlyReadsMemory() {
1507     addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1508   }
1509
1510   /// Determine if the call does not access or only writes memory.
1511   bool doesNotReadMemory() const {
1512     return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1513   }
1514   void setDoesNotReadMemory() {
1515     addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1516   }
1517
1518   /// Determine if the call can access memmory only using pointers based
1519   /// on its arguments.
1520   bool onlyAccessesArgMemory() const {
1521     return hasFnAttr(Attribute::ArgMemOnly);
1522   }
1523   void setOnlyAccessesArgMemory() {
1524     addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1525   }
1526
1527   /// Determine if the function may only access memory that is
1528   /// inaccessible from the IR.
1529   bool onlyAccessesInaccessibleMemory() const {
1530     return hasFnAttr(Attribute::InaccessibleMemOnly);
1531   }
1532   void setOnlyAccessesInaccessibleMemory() {
1533     addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOnly);
1534   }
1535
1536   /// Determine if the function may only access memory that is
1537   /// either inaccessible from the IR or pointed to by its arguments.
1538   bool onlyAccessesInaccessibleMemOrArgMem() const {
1539     return hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
1540   }
1541   void setOnlyAccessesInaccessibleMemOrArgMem() {
1542     addAttribute(AttributeList::FunctionIndex,
1543                  Attribute::InaccessibleMemOrArgMemOnly);
1544   }
1545   /// Determine if the call cannot return.
1546   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1547   void setDoesNotReturn() {
1548     addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1549   }
1550
1551   /// Determine if the call should not perform indirect branch tracking.
1552   bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
1553
1554   /// Determine if the call cannot unwind.
1555   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1556   void setDoesNotThrow() {
1557     addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1558   }
1559
1560   /// Determine if the invoke cannot be duplicated.
1561   bool cannotDuplicate() const { return hasFnAttr(Attribute::NoDuplicate); }
1562   void setCannotDuplicate() {
1563     addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1564   }
1565
1566   /// Determine if the invoke is convergent
1567   bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1568   void setConvergent() {
1569     addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1570   }
1571   void setNotConvergent() {
1572     removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1573   }
1574
1575   /// Determine if the call returns a structure through first
1576   /// pointer argument.
1577   bool hasStructRetAttr() const {
1578     if (getNumArgOperands() == 0)
1579       return false;
1580
1581     // Be friendly and also check the callee.
1582     return paramHasAttr(0, Attribute::StructRet);
1583   }
1584
1585   /// Determine if any call argument is an aggregate passed by value.
1586   bool hasByValArgument() const {
1587     return Attrs.hasAttrSomewhere(Attribute::ByVal);
1588   }
1589
1590   ///@{
1591   // End of attribute API.
1592
1593   /// \name Operand Bundle API
1594   ///
1595   /// This group of methods provides the API to access and manipulate operand
1596   /// bundles on this call.
1597   /// @{
1598
1599   /// Return the number of operand bundles associated with this User.
1600   unsigned getNumOperandBundles() const {
1601     return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1602   }
1603
1604   /// Return true if this User has any operand bundles.
1605   bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1606
1607   /// Return the index of the first bundle operand in the Use array.
1608   unsigned getBundleOperandsStartIndex() const {
1609     assert(hasOperandBundles() && "Don't call otherwise!");
1610     return bundle_op_info_begin()->Begin;
1611   }
1612
1613   /// Return the index of the last bundle operand in the Use array.
1614   unsigned getBundleOperandsEndIndex() const {
1615     assert(hasOperandBundles() && "Don't call otherwise!");
1616     return bundle_op_info_end()[-1].End;
1617   }
1618
1619   /// Return true if the operand at index \p Idx is a bundle operand.
1620   bool isBundleOperand(unsigned Idx) const {
1621     return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() &&
1622            Idx < getBundleOperandsEndIndex();
1623   }
1624
1625   /// Returns true if the use is a bundle operand.
1626   bool isBundleOperand(const Use *U) const {
1627     assert(this == U->getUser() &&
1628            "Only valid to query with a use of this instruction!");
1629     return hasOperandBundles() && isBundleOperand(U - op_begin());
1630   }
1631   bool isBundleOperand(Value::const_user_iterator UI) const {
1632     return isBundleOperand(&UI.getUse());
1633   }
1634
1635   /// Return the total number operands (not operand bundles) used by
1636   /// every operand bundle in this OperandBundleUser.
1637   unsigned getNumTotalBundleOperands() const {
1638     if (!hasOperandBundles())
1639       return 0;
1640
1641     unsigned Begin = getBundleOperandsStartIndex();
1642     unsigned End = getBundleOperandsEndIndex();
1643
1644     assert(Begin <= End && "Should be!");
1645     return End - Begin;
1646   }
1647
1648   /// Return the operand bundle at a specific index.
1649   OperandBundleUse getOperandBundleAt(unsigned Index) const {
1650     assert(Index < getNumOperandBundles() && "Index out of bounds!");
1651     return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1652   }
1653
1654   /// Return the number of operand bundles with the tag Name attached to
1655   /// this instruction.
1656   unsigned countOperandBundlesOfType(StringRef Name) const {
1657     unsigned Count = 0;
1658     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1659       if (getOperandBundleAt(i).getTagName() == Name)
1660         Count++;
1661
1662     return Count;
1663   }
1664
1665   /// Return the number of operand bundles with the tag ID attached to
1666   /// this instruction.
1667   unsigned countOperandBundlesOfType(uint32_t ID) const {
1668     unsigned Count = 0;
1669     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1670       if (getOperandBundleAt(i).getTagID() == ID)
1671         Count++;
1672
1673     return Count;
1674   }
1675
1676   /// Return an operand bundle by name, if present.
1677   ///
1678   /// It is an error to call this for operand bundle types that may have
1679   /// multiple instances of them on the same instruction.
1680   Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1681     assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
1682
1683     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1684       OperandBundleUse U = getOperandBundleAt(i);
1685       if (U.getTagName() == Name)
1686         return U;
1687     }
1688
1689     return None;
1690   }
1691
1692   /// Return an operand bundle by tag ID, if present.
1693   ///
1694   /// It is an error to call this for operand bundle types that may have
1695   /// multiple instances of them on the same instruction.
1696   Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1697     assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
1698
1699     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1700       OperandBundleUse U = getOperandBundleAt(i);
1701       if (U.getTagID() == ID)
1702         return U;
1703     }
1704
1705     return None;
1706   }
1707
1708   /// Return the list of operand bundles attached to this instruction as
1709   /// a vector of OperandBundleDefs.
1710   ///
1711   /// This function copies the OperandBundeUse instances associated with this
1712   /// OperandBundleUser to a vector of OperandBundleDefs.  Note:
1713   /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1714   /// representations of operand bundles (see documentation above).
1715   void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
1716     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1717       Defs.emplace_back(getOperandBundleAt(i));
1718   }
1719
1720   /// Return the operand bundle for the operand at index OpIdx.
1721   ///
1722   /// It is an error to call this with an OpIdx that does not correspond to an
1723   /// bundle operand.
1724   OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1725     return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
1726   }
1727
1728   /// Return true if this operand bundle user has operand bundles that
1729   /// may read from the heap.
1730   bool hasReadingOperandBundles() const {
1731     // Implementation note: this is a conservative implementation of operand
1732     // bundle semantics, where *any* operand bundle forces a callsite to be at
1733     // least readonly.
1734     return hasOperandBundles();
1735   }
1736
1737   /// Return true if this operand bundle user has operand bundles that
1738   /// may write to the heap.
1739   bool hasClobberingOperandBundles() const {
1740     for (auto &BOI : bundle_op_infos()) {
1741       if (BOI.Tag->second == LLVMContext::OB_deopt ||
1742           BOI.Tag->second == LLVMContext::OB_funclet)
1743         continue;
1744
1745       // This instruction has an operand bundle that is not known to us.
1746       // Assume the worst.
1747       return true;
1748     }
1749
1750     return false;
1751   }
1752
1753   /// Return true if the bundle operand at index \p OpIdx has the
1754   /// attribute \p A.
1755   bool bundleOperandHasAttr(unsigned OpIdx,  Attribute::AttrKind A) const {
1756     auto &BOI = getBundleOpInfoForOperand(OpIdx);
1757     auto OBU = operandBundleFromBundleOpInfo(BOI);
1758     return OBU.operandHasAttr(OpIdx - BOI.Begin, A);
1759   }
1760
1761   /// Return true if \p Other has the same sequence of operand bundle
1762   /// tags with the same number of operands on each one of them as this
1763   /// OperandBundleUser.
1764   bool hasIdenticalOperandBundleSchema(const CallBase &Other) const {
1765     if (getNumOperandBundles() != Other.getNumOperandBundles())
1766       return false;
1767
1768     return std::equal(bundle_op_info_begin(), bundle_op_info_end(),
1769                       Other.bundle_op_info_begin());
1770   }
1771
1772   /// Return true if this operand bundle user contains operand bundles
1773   /// with tags other than those specified in \p IDs.
1774   bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const {
1775     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1776       uint32_t ID = getOperandBundleAt(i).getTagID();
1777       if (!is_contained(IDs, ID))
1778         return true;
1779     }
1780     return false;
1781   }
1782
1783   /// Is the function attribute S disallowed by some operand bundle on
1784   /// this operand bundle user?
1785   bool isFnAttrDisallowedByOpBundle(StringRef S) const {
1786     // Operand bundles only possibly disallow readnone, readonly and argmenonly
1787     // attributes.  All String attributes are fine.
1788     return false;
1789   }
1790
1791   /// Is the function attribute A disallowed by some operand bundle on
1792   /// this operand bundle user?
1793   bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
1794     switch (A) {
1795     default:
1796       return false;
1797
1798     case Attribute::InaccessibleMemOrArgMemOnly:
1799       return hasReadingOperandBundles();
1800
1801     case Attribute::InaccessibleMemOnly:
1802       return hasReadingOperandBundles();
1803
1804     case Attribute::ArgMemOnly:
1805       return hasReadingOperandBundles();
1806
1807     case Attribute::ReadNone:
1808       return hasReadingOperandBundles();
1809
1810     case Attribute::ReadOnly:
1811       return hasClobberingOperandBundles();
1812     }
1813
1814     llvm_unreachable("switch has a default case!");
1815   }
1816
1817   /// Used to keep track of an operand bundle.  See the main comment on
1818   /// OperandBundleUser above.
1819   struct BundleOpInfo {
1820     /// The operand bundle tag, interned by
1821     /// LLVMContextImpl::getOrInsertBundleTag.
1822     StringMapEntry<uint32_t> *Tag;
1823
1824     /// The index in the Use& vector where operands for this operand
1825     /// bundle starts.
1826     uint32_t Begin;
1827
1828     /// The index in the Use& vector where operands for this operand
1829     /// bundle ends.
1830     uint32_t End;
1831
1832     bool operator==(const BundleOpInfo &Other) const {
1833       return Tag == Other.Tag && Begin == Other.Begin && End == Other.End;
1834     }
1835   };
1836
1837   /// Simple helper function to map a BundleOpInfo to an
1838   /// OperandBundleUse.
1839   OperandBundleUse
1840   operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
1841     auto begin = op_begin();
1842     ArrayRef<Use> Inputs(begin + BOI.Begin, begin + BOI.End);
1843     return OperandBundleUse(BOI.Tag, Inputs);
1844   }
1845
1846   using bundle_op_iterator = BundleOpInfo *;
1847   using const_bundle_op_iterator = const BundleOpInfo *;
1848
1849   /// Return the start of the list of BundleOpInfo instances associated
1850   /// with this OperandBundleUser.
1851   ///
1852   /// OperandBundleUser uses the descriptor area co-allocated with the host User
1853   /// to store some meta information about which operands are "normal" operands,
1854   /// and which ones belong to some operand bundle.
1855   ///
1856   /// The layout of an operand bundle user is
1857   ///
1858   ///          +-----------uint32_t End-------------------------------------+
1859   ///          |                                                            |
1860   ///          |  +--------uint32_t Begin--------------------+              |
1861   ///          |  |                                          |              |
1862   ///          ^  ^                                          v              v
1863   ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
1864   ///  | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
1865   ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
1866   ///   v  v                                  ^              ^
1867   ///   |  |                                  |              |
1868   ///   |  +--------uint32_t Begin------------+              |
1869   ///   |                                                    |
1870   ///   +-----------uint32_t End-----------------------------+
1871   ///
1872   ///
1873   /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use
1874   /// list. These descriptions are installed and managed by this class, and
1875   /// they're all instances of OperandBundleUser<T>::BundleOpInfo.
1876   ///
1877   /// DU is an additional descriptor installed by User's 'operator new' to keep
1878   /// track of the 'BOI0 ... BOIN' co-allocation.  OperandBundleUser does not
1879   /// access or modify DU in any way, it's an implementation detail private to
1880   /// User.
1881   ///
1882   /// The regular Use& vector for the User starts at U0.  The operand bundle
1883   /// uses are part of the Use& vector, just like normal uses.  In the diagram
1884   /// above, the operand bundle uses start at BOI0_U0.  Each instance of
1885   /// BundleOpInfo has information about a contiguous set of uses constituting
1886   /// an operand bundle, and the total set of operand bundle uses themselves
1887   /// form a contiguous set of uses (i.e. there are no gaps between uses
1888   /// corresponding to individual operand bundles).
1889   ///
1890   /// This class does not know the location of the set of operand bundle uses
1891   /// within the use list -- that is decided by the User using this class via
1892   /// the BeginIdx argument in populateBundleOperandInfos.
1893   ///
1894   /// Currently operand bundle users with hung-off operands are not supported.
1895   bundle_op_iterator bundle_op_info_begin() {
1896     if (!hasDescriptor())
1897       return nullptr;
1898
1899     uint8_t *BytesBegin = getDescriptor().begin();
1900     return reinterpret_cast<bundle_op_iterator>(BytesBegin);
1901   }
1902
1903   /// Return the start of the list of BundleOpInfo instances associated
1904   /// with this OperandBundleUser.
1905   const_bundle_op_iterator bundle_op_info_begin() const {
1906     auto *NonConstThis = const_cast<CallBase *>(this);
1907     return NonConstThis->bundle_op_info_begin();
1908   }
1909
1910   /// Return the end of the list of BundleOpInfo instances associated
1911   /// with this OperandBundleUser.
1912   bundle_op_iterator bundle_op_info_end() {
1913     if (!hasDescriptor())
1914       return nullptr;
1915
1916     uint8_t *BytesEnd = getDescriptor().end();
1917     return reinterpret_cast<bundle_op_iterator>(BytesEnd);
1918   }
1919
1920   /// Return the end of the list of BundleOpInfo instances associated
1921   /// with this OperandBundleUser.
1922   const_bundle_op_iterator bundle_op_info_end() const {
1923     auto *NonConstThis = const_cast<CallBase *>(this);
1924     return NonConstThis->bundle_op_info_end();
1925   }
1926
1927   /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1928   iterator_range<bundle_op_iterator> bundle_op_infos() {
1929     return make_range(bundle_op_info_begin(), bundle_op_info_end());
1930   }
1931
1932   /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1933   iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
1934     return make_range(bundle_op_info_begin(), bundle_op_info_end());
1935   }
1936
1937   /// Populate the BundleOpInfo instances and the Use& vector from \p
1938   /// Bundles.  Return the op_iterator pointing to the Use& one past the last
1939   /// last bundle operand use.
1940   ///
1941   /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
1942   /// instance allocated in this User's descriptor.
1943   op_iterator populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
1944                                          const unsigned BeginIndex);
1945
1946   /// Return the BundleOpInfo for the operand at index OpIdx.
1947   ///
1948   /// It is an error to call this with an OpIdx that does not correspond to an
1949   /// bundle operand.
1950   const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
1951     for (auto &BOI : bundle_op_infos())
1952       if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
1953         return BOI;
1954
1955     llvm_unreachable("Did not find operand bundle for operand!");
1956   }
1957
1958 protected:
1959   /// Return the total number of values used in \p Bundles.
1960   static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
1961     unsigned Total = 0;
1962     for (auto &B : Bundles)
1963       Total += B.input_size();
1964     return Total;
1965   }
1966
1967   /// @}
1968   // End of operand bundle API.
1969
1970 private:
1971   bool hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
1972   bool hasFnAttrOnCalledFunction(StringRef Kind) const;
1973
1974   template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
1975     if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
1976       return true;
1977
1978     // Operand bundles override attributes on the called function, but don't
1979     // override attributes directly present on the call instruction.
1980     if (isFnAttrDisallowedByOpBundle(Kind))
1981       return false;
1982
1983     return hasFnAttrOnCalledFunction(Kind);
1984   }
1985 };
1986
1987 template <>
1988 struct OperandTraits<CallBase> : public VariadicOperandTraits<CallBase, 1> {};
1989
1990 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallBase, Value)
1991
1992 //===----------------------------------------------------------------------===//
1993 //                           FuncletPadInst Class
1994 //===----------------------------------------------------------------------===//
1995 class FuncletPadInst : public Instruction {
1996 private:
1997   FuncletPadInst(const FuncletPadInst &CPI);
1998
1999   explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2000                           ArrayRef<Value *> Args, unsigned Values,
2001                           const Twine &NameStr, Instruction *InsertBefore);
2002   explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2003                           ArrayRef<Value *> Args, unsigned Values,
2004                           const Twine &NameStr, BasicBlock *InsertAtEnd);
2005
2006   void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
2007
2008 protected:
2009   // Note: Instruction needs to be a friend here to call cloneImpl.
2010   friend class Instruction;
2011   friend class CatchPadInst;
2012   friend class CleanupPadInst;
2013
2014   FuncletPadInst *cloneImpl() const;
2015
2016 public:
2017   /// Provide fast operand accessors
2018   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2019
2020   /// getNumArgOperands - Return the number of funcletpad arguments.
2021   ///
2022   unsigned getNumArgOperands() const { return getNumOperands() - 1; }
2023
2024   /// Convenience accessors
2025
2026   /// Return the outer EH-pad this funclet is nested within.
2027   ///
2028   /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
2029   /// is a CatchPadInst.
2030   Value *getParentPad() const { return Op<-1>(); }
2031   void setParentPad(Value *ParentPad) {
2032     assert(ParentPad);
2033     Op<-1>() = ParentPad;
2034   }
2035
2036   /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
2037   ///
2038   Value *getArgOperand(unsigned i) const { return getOperand(i); }
2039   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
2040
2041   /// arg_operands - iteration adapter for range-for loops.
2042   op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
2043
2044   /// arg_operands - iteration adapter for range-for loops.
2045   const_op_range arg_operands() const {
2046     return const_op_range(op_begin(), op_end() - 1);
2047   }
2048
2049   // Methods for support type inquiry through isa, cast, and dyn_cast:
2050   static bool classof(const Instruction *I) { return I->isFuncletPad(); }
2051   static bool classof(const Value *V) {
2052     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2053   }
2054 };
2055
2056 template <>
2057 struct OperandTraits<FuncletPadInst>
2058     : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {};
2059
2060 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)
2061
2062 } // end namespace llvm
2063
2064 #endif // LLVM_IR_INSTRTYPES_H