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