InstrTypes.h revision 360784
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
47namespace llvm {
48
49namespace Intrinsic {
50typedef unsigned ID;
51}
52
53//===----------------------------------------------------------------------===//
54//                          UnaryInstruction Class
55//===----------------------------------------------------------------------===//
56
57class UnaryInstruction : public Instruction {
58protected:
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
69public:
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
92template <>
93struct OperandTraits<UnaryInstruction> :
94  public FixedNumOperandTraits<UnaryInstruction, 1> {
95};
96
97DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
98
99//===----------------------------------------------------------------------===//
100//                                UnaryOperator Class
101//===----------------------------------------------------------------------===//
102
103class UnaryOperator : public UnaryInstruction {
104  void AssertOK();
105
106protected:
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
117public:
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
188class BinaryOperator : public Instruction {
189  void AssertOK();
190
191protected:
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
202public:
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
422template <>
423struct OperandTraits<BinaryOperator> :
424  public FixedNumOperandTraits<BinaryOperator, 2> {
425};
426
427DEFINE_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.
439class CastInst : public UnaryInstruction {
440protected:
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
454public:
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.
722class CmpInst : public Instruction {
723public:
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
768protected:
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
778public:
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->getElementCount());
979    }
980    return Type::getInt1Ty(opnd_type->getContext());
981  }
982
983private:
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
992template <>
993struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
994};
995
996DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
997
998/// A lightweight accessor for an operand bundle meant to be passed
999/// around by value.
1000struct 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  /// Return true if this is a "cfguardtarget" operand bundle.
1043  bool isCFGuardTargetOperandBundle() const {
1044    return getTagID() == LLVMContext::OB_cfguardtarget;
1045  }
1046
1047private:
1048  /// Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1049  StringMapEntry<uint32_t> *Tag;
1050};
1051
1052/// A container for an operand bundle being viewed as a set of values
1053/// rather than a set of uses.
1054///
1055/// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1056/// so it is possible to create and pass around "self-contained" instances of
1057/// OperandBundleDef and ConstOperandBundleDef.
1058template <typename InputTy> class OperandBundleDefT {
1059  std::string Tag;
1060  std::vector<InputTy> Inputs;
1061
1062public:
1063  explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1064      : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1065  explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs)
1066      : Tag(std::move(Tag)), Inputs(Inputs) {}
1067
1068  explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1069    Tag = OBU.getTagName();
1070    Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
1071  }
1072
1073  ArrayRef<InputTy> inputs() const { return Inputs; }
1074
1075  using input_iterator = typename std::vector<InputTy>::const_iterator;
1076
1077  size_t input_size() const { return Inputs.size(); }
1078  input_iterator input_begin() const { return Inputs.begin(); }
1079  input_iterator input_end() const { return Inputs.end(); }
1080
1081  StringRef getTag() const { return Tag; }
1082};
1083
1084using OperandBundleDef = OperandBundleDefT<Value *>;
1085using ConstOperandBundleDef = OperandBundleDefT<const Value *>;
1086
1087//===----------------------------------------------------------------------===//
1088//                               CallBase Class
1089//===----------------------------------------------------------------------===//
1090
1091/// Base class for all callable instructions (InvokeInst and CallInst)
1092/// Holds everything related to calling a function.
1093///
1094/// All call-like instructions are required to use a common operand layout:
1095/// - Zero or more arguments to the call,
1096/// - Zero or more operand bundles with zero or more operand inputs each
1097///   bundle,
1098/// - Zero or more subclass controlled operands
1099/// - The called function.
1100///
1101/// This allows this base class to easily access the called function and the
1102/// start of the arguments without knowing how many other operands a particular
1103/// subclass requires. Note that accessing the end of the argument list isn't
1104/// as cheap as most other operations on the base class.
1105class CallBase : public Instruction {
1106protected:
1107  /// The last operand is the called operand.
1108  static constexpr int CalledOperandOpEndIdx = -1;
1109
1110  AttributeList Attrs; ///< parameter attributes for callable
1111  FunctionType *FTy;
1112
1113  template <class... ArgsTy>
1114  CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args)
1115      : Instruction(std::forward<ArgsTy>(Args)...), Attrs(A), FTy(FT) {}
1116
1117  using Instruction::Instruction;
1118
1119  bool hasDescriptor() const { return Value::HasDescriptor; }
1120
1121  unsigned getNumSubclassExtraOperands() const {
1122    switch (getOpcode()) {
1123    case Instruction::Call:
1124      return 0;
1125    case Instruction::Invoke:
1126      return 2;
1127    case Instruction::CallBr:
1128      return getNumSubclassExtraOperandsDynamic();
1129    }
1130    llvm_unreachable("Invalid opcode!");
1131  }
1132
1133  /// Get the number of extra operands for instructions that don't have a fixed
1134  /// number of extra operands.
1135  unsigned getNumSubclassExtraOperandsDynamic() const;
1136
1137public:
1138  using Instruction::getContext;
1139
1140  static bool classof(const Instruction *I) {
1141    return I->getOpcode() == Instruction::Call ||
1142           I->getOpcode() == Instruction::Invoke ||
1143           I->getOpcode() == Instruction::CallBr;
1144  }
1145  static bool classof(const Value *V) {
1146    return isa<Instruction>(V) && classof(cast<Instruction>(V));
1147  }
1148
1149  FunctionType *getFunctionType() const { return FTy; }
1150
1151  void mutateFunctionType(FunctionType *FTy) {
1152    Value::mutateType(FTy->getReturnType());
1153    this->FTy = FTy;
1154  }
1155
1156  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1157
1158  /// data_operands_begin/data_operands_end - Return iterators iterating over
1159  /// the call / invoke argument list and bundle operands.  For invokes, this is
1160  /// the set of instruction operands except the invoke target and the two
1161  /// successor blocks; and for calls this is the set of instruction operands
1162  /// except the call target.
1163  User::op_iterator data_operands_begin() { return op_begin(); }
1164  User::const_op_iterator data_operands_begin() const {
1165    return const_cast<CallBase *>(this)->data_operands_begin();
1166  }
1167  User::op_iterator data_operands_end() {
1168    // Walk from the end of the operands over the called operand and any
1169    // subclass operands.
1170    return op_end() - getNumSubclassExtraOperands() - 1;
1171  }
1172  User::const_op_iterator data_operands_end() const {
1173    return const_cast<CallBase *>(this)->data_operands_end();
1174  }
1175  iterator_range<User::op_iterator> data_ops() {
1176    return make_range(data_operands_begin(), data_operands_end());
1177  }
1178  iterator_range<User::const_op_iterator> data_ops() const {
1179    return make_range(data_operands_begin(), data_operands_end());
1180  }
1181  bool data_operands_empty() const {
1182    return data_operands_end() == data_operands_begin();
1183  }
1184  unsigned data_operands_size() const {
1185    return std::distance(data_operands_begin(), data_operands_end());
1186  }
1187
1188  bool isDataOperand(const Use *U) const {
1189    assert(this == U->getUser() &&
1190           "Only valid to query with a use of this instruction!");
1191    return data_operands_begin() <= U && U < data_operands_end();
1192  }
1193  bool isDataOperand(Value::const_user_iterator UI) const {
1194    return isDataOperand(&UI.getUse());
1195  }
1196
1197  /// Given a value use iterator, return the data operand corresponding to it.
1198  /// Iterator must actually correspond to a data operand.
1199  unsigned getDataOperandNo(Value::const_user_iterator UI) const {
1200    return getDataOperandNo(&UI.getUse());
1201  }
1202
1203  /// Given a use for a data operand, get the data operand number that
1204  /// corresponds to it.
1205  unsigned getDataOperandNo(const Use *U) const {
1206    assert(isDataOperand(U) && "Data operand # out of range!");
1207    return U - data_operands_begin();
1208  }
1209
1210  /// Return the iterator pointing to the beginning of the argument list.
1211  User::op_iterator arg_begin() { return op_begin(); }
1212  User::const_op_iterator arg_begin() const {
1213    return const_cast<CallBase *>(this)->arg_begin();
1214  }
1215
1216  /// Return the iterator pointing to the end of the argument list.
1217  User::op_iterator arg_end() {
1218    // From the end of the data operands, walk backwards past the bundle
1219    // operands.
1220    return data_operands_end() - getNumTotalBundleOperands();
1221  }
1222  User::const_op_iterator arg_end() const {
1223    return const_cast<CallBase *>(this)->arg_end();
1224  }
1225
1226  /// Iteration adapter for range-for loops.
1227  iterator_range<User::op_iterator> args() {
1228    return make_range(arg_begin(), arg_end());
1229  }
1230  iterator_range<User::const_op_iterator> args() const {
1231    return make_range(arg_begin(), arg_end());
1232  }
1233  bool arg_empty() const { return arg_end() == arg_begin(); }
1234  unsigned arg_size() const { return arg_end() - arg_begin(); }
1235
1236  // Legacy API names that duplicate the above and will be removed once users
1237  // are migrated.
1238  iterator_range<User::op_iterator> arg_operands() {
1239    return make_range(arg_begin(), arg_end());
1240  }
1241  iterator_range<User::const_op_iterator> arg_operands() const {
1242    return make_range(arg_begin(), arg_end());
1243  }
1244  unsigned getNumArgOperands() const { return arg_size(); }
1245
1246  Value *getArgOperand(unsigned i) const {
1247    assert(i < getNumArgOperands() && "Out of bounds!");
1248    return getOperand(i);
1249  }
1250
1251  void setArgOperand(unsigned i, Value *v) {
1252    assert(i < getNumArgOperands() && "Out of bounds!");
1253    setOperand(i, v);
1254  }
1255
1256  /// Wrappers for getting the \c Use of a call argument.
1257  const Use &getArgOperandUse(unsigned i) const {
1258    assert(i < getNumArgOperands() && "Out of bounds!");
1259    return User::getOperandUse(i);
1260  }
1261  Use &getArgOperandUse(unsigned i) {
1262    assert(i < getNumArgOperands() && "Out of bounds!");
1263    return User::getOperandUse(i);
1264  }
1265
1266  bool isArgOperand(const Use *U) const {
1267    assert(this == U->getUser() &&
1268           "Only valid to query with a use of this instruction!");
1269    return arg_begin() <= U && U < arg_end();
1270  }
1271  bool isArgOperand(Value::const_user_iterator UI) const {
1272    return isArgOperand(&UI.getUse());
1273  }
1274
1275  /// Given a use for a arg operand, get the arg operand number that
1276  /// corresponds to it.
1277  unsigned getArgOperandNo(const Use *U) const {
1278    assert(isArgOperand(U) && "Arg operand # out of range!");
1279    return U - arg_begin();
1280  }
1281
1282  /// Given a value use iterator, return the arg operand number corresponding to
1283  /// it. Iterator must actually correspond to a data operand.
1284  unsigned getArgOperandNo(Value::const_user_iterator UI) const {
1285    return getArgOperandNo(&UI.getUse());
1286  }
1287
1288  /// Returns true if this CallSite passes the given Value* as an argument to
1289  /// the called function.
1290  bool hasArgument(const Value *V) const {
1291    return llvm::any_of(args(), [V](const Value *Arg) { return Arg == V; });
1292  }
1293
1294  Value *getCalledOperand() const { return Op<CalledOperandOpEndIdx>(); }
1295
1296  // DEPRECATED: This routine will be removed in favor of `getCalledOperand` in
1297  // the near future.
1298  Value *getCalledValue() const { return getCalledOperand(); }
1299
1300  const Use &getCalledOperandUse() const { return Op<CalledOperandOpEndIdx>(); }
1301  Use &getCalledOperandUse() { return Op<CalledOperandOpEndIdx>(); }
1302
1303  /// Returns the function called, or null if this is an
1304  /// indirect function invocation.
1305  Function *getCalledFunction() const {
1306    return dyn_cast_or_null<Function>(getCalledOperand());
1307  }
1308
1309  /// Return true if the callsite is an indirect call.
1310  bool isIndirectCall() const;
1311
1312  /// Determine whether the passed iterator points to the callee operand's Use.
1313  bool isCallee(Value::const_user_iterator UI) const {
1314    return isCallee(&UI.getUse());
1315  }
1316
1317  /// Determine whether this Use is the callee operand's Use.
1318  bool isCallee(const Use *U) const { return &getCalledOperandUse() == U; }
1319
1320  /// Helper to get the caller (the parent function).
1321  Function *getCaller();
1322  const Function *getCaller() const {
1323    return const_cast<CallBase *>(this)->getCaller();
1324  }
1325
1326  /// Tests if this call site must be tail call optimized. Only a CallInst can
1327  /// be tail call optimized.
1328  bool isMustTailCall() const;
1329
1330  /// Tests if this call site is marked as a tail call.
1331  bool isTailCall() const;
1332
1333  /// Returns the intrinsic ID of the intrinsic called or
1334  /// Intrinsic::not_intrinsic if the called function is not an intrinsic, or if
1335  /// this is an indirect call.
1336  Intrinsic::ID getIntrinsicID() const;
1337
1338  void setCalledOperand(Value *V) { Op<CalledOperandOpEndIdx>() = V; }
1339
1340  /// Sets the function called, including updating the function type.
1341  void setCalledFunction(Function *Fn) {
1342    setCalledFunction(Fn->getFunctionType(), Fn);
1343  }
1344
1345  /// Sets the function called, including updating the function type.
1346  void setCalledFunction(FunctionCallee Fn) {
1347    setCalledFunction(Fn.getFunctionType(), Fn.getCallee());
1348  }
1349
1350  /// Sets the function called, including updating to the specified function
1351  /// type.
1352  void setCalledFunction(FunctionType *FTy, Value *Fn) {
1353    this->FTy = FTy;
1354    assert(FTy == cast<FunctionType>(
1355                      cast<PointerType>(Fn->getType())->getElementType()));
1356    // This function doesn't mutate the return type, only the function
1357    // type. Seems broken, but I'm just gonna stick an assert in for now.
1358    assert(getType() == FTy->getReturnType());
1359    setCalledOperand(Fn);
1360  }
1361
1362  CallingConv::ID getCallingConv() const {
1363    return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1364  }
1365
1366  void setCallingConv(CallingConv::ID CC) {
1367    auto ID = static_cast<unsigned>(CC);
1368    assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1369    setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1370                               (ID << 2));
1371  }
1372
1373  /// Check if this call is an inline asm statement.
1374  bool isInlineAsm() const { return isa<InlineAsm>(getCalledOperand()); }
1375
1376  /// \name Attribute API
1377  ///
1378  /// These methods access and modify attributes on this call (including
1379  /// looking through to the attributes on the called function when necessary).
1380  ///@{
1381
1382  /// Return the parameter attributes for this call.
1383  ///
1384  AttributeList getAttributes() const { return Attrs; }
1385
1386  /// Set the parameter attributes for this call.
1387  ///
1388  void setAttributes(AttributeList A) { Attrs = A; }
1389
1390  /// Determine whether this call has the given attribute.
1391  bool hasFnAttr(Attribute::AttrKind Kind) const {
1392    assert(Kind != Attribute::NoBuiltin &&
1393           "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin");
1394    return hasFnAttrImpl(Kind);
1395  }
1396
1397  /// Determine whether this call has the given attribute.
1398  bool hasFnAttr(StringRef Kind) const { return hasFnAttrImpl(Kind); }
1399
1400  /// adds the attribute to the list of attributes.
1401  void addAttribute(unsigned i, Attribute::AttrKind Kind) {
1402    AttributeList PAL = getAttributes();
1403    PAL = PAL.addAttribute(getContext(), i, Kind);
1404    setAttributes(PAL);
1405  }
1406
1407  /// adds the attribute to the list of attributes.
1408  void addAttribute(unsigned i, Attribute Attr) {
1409    AttributeList PAL = getAttributes();
1410    PAL = PAL.addAttribute(getContext(), i, Attr);
1411    setAttributes(PAL);
1412  }
1413
1414  /// Adds the attribute to the indicated argument
1415  void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1416    assert(ArgNo < getNumArgOperands() && "Out of bounds");
1417    AttributeList PAL = getAttributes();
1418    PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
1419    setAttributes(PAL);
1420  }
1421
1422  /// Adds the attribute to the indicated argument
1423  void addParamAttr(unsigned ArgNo, Attribute Attr) {
1424    assert(ArgNo < getNumArgOperands() && "Out of bounds");
1425    AttributeList PAL = getAttributes();
1426    PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
1427    setAttributes(PAL);
1428  }
1429
1430  /// removes the attribute from the list of attributes.
1431  void removeAttribute(unsigned i, Attribute::AttrKind Kind) {
1432    AttributeList PAL = getAttributes();
1433    PAL = PAL.removeAttribute(getContext(), i, Kind);
1434    setAttributes(PAL);
1435  }
1436
1437  /// removes the attribute from the list of attributes.
1438  void removeAttribute(unsigned i, StringRef Kind) {
1439    AttributeList PAL = getAttributes();
1440    PAL = PAL.removeAttribute(getContext(), i, Kind);
1441    setAttributes(PAL);
1442  }
1443
1444  /// Removes the attribute from the given argument
1445  void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1446    assert(ArgNo < getNumArgOperands() && "Out of bounds");
1447    AttributeList PAL = getAttributes();
1448    PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1449    setAttributes(PAL);
1450  }
1451
1452  /// Removes the attribute from the given argument
1453  void removeParamAttr(unsigned ArgNo, StringRef Kind) {
1454    assert(ArgNo < getNumArgOperands() && "Out of bounds");
1455    AttributeList PAL = getAttributes();
1456    PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1457    setAttributes(PAL);
1458  }
1459
1460  /// adds the dereferenceable attribute to the list of attributes.
1461  void addDereferenceableAttr(unsigned i, uint64_t Bytes) {
1462    AttributeList PAL = getAttributes();
1463    PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
1464    setAttributes(PAL);
1465  }
1466
1467  /// adds the dereferenceable_or_null attribute to the list of
1468  /// attributes.
1469  void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
1470    AttributeList PAL = getAttributes();
1471    PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
1472    setAttributes(PAL);
1473  }
1474
1475  /// Determine whether the return value has the given attribute.
1476  bool hasRetAttr(Attribute::AttrKind Kind) const;
1477
1478  /// Determine whether the argument or parameter has the given attribute.
1479  bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1480
1481  /// Get the attribute of a given kind at a position.
1482  Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
1483    return getAttributes().getAttribute(i, Kind);
1484  }
1485
1486  /// Get the attribute of a given kind at a position.
1487  Attribute getAttribute(unsigned i, StringRef Kind) const {
1488    return getAttributes().getAttribute(i, Kind);
1489  }
1490
1491  /// Get the attribute of a given kind from a given arg
1492  Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1493    assert(ArgNo < getNumArgOperands() && "Out of bounds");
1494    return getAttributes().getParamAttr(ArgNo, Kind);
1495  }
1496
1497  /// Get the attribute of a given kind from a given arg
1498  Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1499    assert(ArgNo < getNumArgOperands() && "Out of bounds");
1500    return getAttributes().getParamAttr(ArgNo, Kind);
1501  }
1502
1503  /// Return true if the data operand at index \p i has the attribute \p
1504  /// A.
1505  ///
1506  /// Data operands include call arguments and values used in operand bundles,
1507  /// but does not include the callee operand.  This routine dispatches to the
1508  /// underlying AttributeList or the OperandBundleUser as appropriate.
1509  ///
1510  /// The index \p i is interpreted as
1511  ///
1512  ///  \p i == Attribute::ReturnIndex  -> the return value
1513  ///  \p i in [1, arg_size + 1)  -> argument number (\p i - 1)
1514  ///  \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1515  ///     (\p i - 1) in the operand list.
1516  bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const {
1517    // Note that we have to add one because `i` isn't zero-indexed.
1518    assert(i < (getNumArgOperands() + getNumTotalBundleOperands() + 1) &&
1519           "Data operand index out of bounds!");
1520
1521    // The attribute A can either be directly specified, if the operand in
1522    // question is a call argument; or be indirectly implied by the kind of its
1523    // containing operand bundle, if the operand is a bundle operand.
1524
1525    if (i == AttributeList::ReturnIndex)
1526      return hasRetAttr(Kind);
1527
1528    // FIXME: Avoid these i - 1 calculations and update the API to use
1529    // zero-based indices.
1530    if (i < (getNumArgOperands() + 1))
1531      return paramHasAttr(i - 1, Kind);
1532
1533    assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
1534           "Must be either a call argument or an operand bundle!");
1535    return bundleOperandHasAttr(i - 1, Kind);
1536  }
1537
1538  /// Determine whether this data operand is not captured.
1539  // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1540  // better indicate that this may return a conservative answer.
1541  bool doesNotCapture(unsigned OpNo) const {
1542    return dataOperandHasImpliedAttr(OpNo + 1, Attribute::NoCapture);
1543  }
1544
1545  /// Determine whether this argument is passed by value.
1546  bool isByValArgument(unsigned ArgNo) const {
1547    return paramHasAttr(ArgNo, Attribute::ByVal);
1548  }
1549
1550  /// Determine whether this argument is passed in an alloca.
1551  bool isInAllocaArgument(unsigned ArgNo) const {
1552    return paramHasAttr(ArgNo, Attribute::InAlloca);
1553  }
1554
1555  /// Determine whether this argument is passed by value or in an alloca.
1556  bool isByValOrInAllocaArgument(unsigned ArgNo) const {
1557    return paramHasAttr(ArgNo, Attribute::ByVal) ||
1558           paramHasAttr(ArgNo, Attribute::InAlloca);
1559  }
1560
1561  /// Determine if there are is an inalloca argument. Only the last argument can
1562  /// have the inalloca attribute.
1563  bool hasInAllocaArgument() const {
1564    return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca);
1565  }
1566
1567  // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1568  // better indicate that this may return a conservative answer.
1569  bool doesNotAccessMemory(unsigned OpNo) const {
1570    return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1571  }
1572
1573  // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1574  // better indicate that this may return a conservative answer.
1575  bool onlyReadsMemory(unsigned OpNo) const {
1576    return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadOnly) ||
1577           dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1578  }
1579
1580  // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1581  // better indicate that this may return a conservative answer.
1582  bool doesNotReadMemory(unsigned OpNo) const {
1583    return dataOperandHasImpliedAttr(OpNo + 1, Attribute::WriteOnly) ||
1584           dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
1585  }
1586
1587  /// Extract the alignment of the return value.
1588  /// FIXME: Remove this function once transition to Align is over.
1589  /// Use getRetAlign() instead.
1590  unsigned getRetAlignment() const {
1591    if (const auto MA = Attrs.getRetAlignment())
1592      return MA->value();
1593    return 0;
1594  }
1595
1596  /// Extract the alignment of the return value.
1597  MaybeAlign getRetAlign() const { return Attrs.getRetAlignment(); }
1598
1599  /// Extract the alignment for a call or parameter (0=unknown).
1600  /// FIXME: Remove this function once transition to Align is over.
1601  /// Use getParamAlign() instead.
1602  unsigned getParamAlignment(unsigned ArgNo) const {
1603    if (const auto MA = Attrs.getParamAlignment(ArgNo))
1604      return MA->value();
1605    return 0;
1606  }
1607
1608  /// Extract the alignment for a call or parameter (0=unknown).
1609  MaybeAlign getParamAlign(unsigned ArgNo) const {
1610    return Attrs.getParamAlignment(ArgNo);
1611  }
1612
1613  /// Extract the byval type for a call or parameter.
1614  Type *getParamByValType(unsigned ArgNo) const {
1615    Type *Ty = Attrs.getParamByValType(ArgNo);
1616    return Ty ? Ty : getArgOperand(ArgNo)->getType()->getPointerElementType();
1617  }
1618
1619  /// Extract the number of dereferenceable bytes for a call or
1620  /// parameter (0=unknown).
1621  uint64_t getDereferenceableBytes(unsigned i) const {
1622    return Attrs.getDereferenceableBytes(i);
1623  }
1624
1625  /// Extract the number of dereferenceable_or_null bytes for a call or
1626  /// parameter (0=unknown).
1627  uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1628    return Attrs.getDereferenceableOrNullBytes(i);
1629  }
1630
1631  /// Return true if the return value is known to be not null.
1632  /// This may be because it has the nonnull attribute, or because at least
1633  /// one byte is dereferenceable and the pointer is in addrspace(0).
1634  bool isReturnNonNull() const;
1635
1636  /// Determine if the return value is marked with NoAlias attribute.
1637  bool returnDoesNotAlias() const {
1638    return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1639  }
1640
1641  /// If one of the arguments has the 'returned' attribute, returns its
1642  /// operand value. Otherwise, return nullptr.
1643  Value *getReturnedArgOperand() const;
1644
1645  /// Return true if the call should not be treated as a call to a
1646  /// builtin.
1647  bool isNoBuiltin() const {
1648    return hasFnAttrImpl(Attribute::NoBuiltin) &&
1649           !hasFnAttrImpl(Attribute::Builtin);
1650  }
1651
1652  /// Determine if the call requires strict floating point semantics.
1653  bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1654
1655  /// Return true if the call should not be inlined.
1656  bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1657  void setIsNoInline() {
1658    addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1659  }
1660  /// Determine if the call does not access memory.
1661  bool doesNotAccessMemory() const { return hasFnAttr(Attribute::ReadNone); }
1662  void setDoesNotAccessMemory() {
1663    addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1664  }
1665
1666  /// Determine if the call does not access or only reads memory.
1667  bool onlyReadsMemory() const {
1668    return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1669  }
1670  void setOnlyReadsMemory() {
1671    addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1672  }
1673
1674  /// Determine if the call does not access or only writes memory.
1675  bool doesNotReadMemory() const {
1676    return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1677  }
1678  void setDoesNotReadMemory() {
1679    addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1680  }
1681
1682  /// Determine if the call can access memmory only using pointers based
1683  /// on its arguments.
1684  bool onlyAccessesArgMemory() const {
1685    return hasFnAttr(Attribute::ArgMemOnly);
1686  }
1687  void setOnlyAccessesArgMemory() {
1688    addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1689  }
1690
1691  /// Determine if the function may only access memory that is
1692  /// inaccessible from the IR.
1693  bool onlyAccessesInaccessibleMemory() const {
1694    return hasFnAttr(Attribute::InaccessibleMemOnly);
1695  }
1696  void setOnlyAccessesInaccessibleMemory() {
1697    addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOnly);
1698  }
1699
1700  /// Determine if the function may only access memory that is
1701  /// either inaccessible from the IR or pointed to by its arguments.
1702  bool onlyAccessesInaccessibleMemOrArgMem() const {
1703    return hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
1704  }
1705  void setOnlyAccessesInaccessibleMemOrArgMem() {
1706    addAttribute(AttributeList::FunctionIndex,
1707                 Attribute::InaccessibleMemOrArgMemOnly);
1708  }
1709  /// Determine if the call cannot return.
1710  bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1711  void setDoesNotReturn() {
1712    addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1713  }
1714
1715  /// Determine if the call should not perform indirect branch tracking.
1716  bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
1717
1718  /// Determine if the call cannot unwind.
1719  bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1720  void setDoesNotThrow() {
1721    addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1722  }
1723
1724  /// Determine if the invoke cannot be duplicated.
1725  bool cannotDuplicate() const { return hasFnAttr(Attribute::NoDuplicate); }
1726  void setCannotDuplicate() {
1727    addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1728  }
1729
1730  /// Determine if the invoke is convergent
1731  bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1732  void setConvergent() {
1733    addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1734  }
1735  void setNotConvergent() {
1736    removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1737  }
1738
1739  /// Determine if the call returns a structure through first
1740  /// pointer argument.
1741  bool hasStructRetAttr() const {
1742    if (getNumArgOperands() == 0)
1743      return false;
1744
1745    // Be friendly and also check the callee.
1746    return paramHasAttr(0, Attribute::StructRet);
1747  }
1748
1749  /// Determine if any call argument is an aggregate passed by value.
1750  bool hasByValArgument() const {
1751    return Attrs.hasAttrSomewhere(Attribute::ByVal);
1752  }
1753
1754  ///@{
1755  // End of attribute API.
1756
1757  /// \name Operand Bundle API
1758  ///
1759  /// This group of methods provides the API to access and manipulate operand
1760  /// bundles on this call.
1761  /// @{
1762
1763  /// Return the number of operand bundles associated with this User.
1764  unsigned getNumOperandBundles() const {
1765    return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1766  }
1767
1768  /// Return true if this User has any operand bundles.
1769  bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1770
1771  /// Return the index of the first bundle operand in the Use array.
1772  unsigned getBundleOperandsStartIndex() const {
1773    assert(hasOperandBundles() && "Don't call otherwise!");
1774    return bundle_op_info_begin()->Begin;
1775  }
1776
1777  /// Return the index of the last bundle operand in the Use array.
1778  unsigned getBundleOperandsEndIndex() const {
1779    assert(hasOperandBundles() && "Don't call otherwise!");
1780    return bundle_op_info_end()[-1].End;
1781  }
1782
1783  /// Return true if the operand at index \p Idx is a bundle operand.
1784  bool isBundleOperand(unsigned Idx) const {
1785    return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() &&
1786           Idx < getBundleOperandsEndIndex();
1787  }
1788
1789  /// Returns true if the use is a bundle operand.
1790  bool isBundleOperand(const Use *U) const {
1791    assert(this == U->getUser() &&
1792           "Only valid to query with a use of this instruction!");
1793    return hasOperandBundles() && isBundleOperand(U - op_begin());
1794  }
1795  bool isBundleOperand(Value::const_user_iterator UI) const {
1796    return isBundleOperand(&UI.getUse());
1797  }
1798
1799  /// Return the total number operands (not operand bundles) used by
1800  /// every operand bundle in this OperandBundleUser.
1801  unsigned getNumTotalBundleOperands() const {
1802    if (!hasOperandBundles())
1803      return 0;
1804
1805    unsigned Begin = getBundleOperandsStartIndex();
1806    unsigned End = getBundleOperandsEndIndex();
1807
1808    assert(Begin <= End && "Should be!");
1809    return End - Begin;
1810  }
1811
1812  /// Return the operand bundle at a specific index.
1813  OperandBundleUse getOperandBundleAt(unsigned Index) const {
1814    assert(Index < getNumOperandBundles() && "Index out of bounds!");
1815    return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1816  }
1817
1818  /// Return the number of operand bundles with the tag Name attached to
1819  /// this instruction.
1820  unsigned countOperandBundlesOfType(StringRef Name) const {
1821    unsigned Count = 0;
1822    for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1823      if (getOperandBundleAt(i).getTagName() == Name)
1824        Count++;
1825
1826    return Count;
1827  }
1828
1829  /// Return the number of operand bundles with the tag ID attached to
1830  /// this instruction.
1831  unsigned countOperandBundlesOfType(uint32_t ID) const {
1832    unsigned Count = 0;
1833    for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1834      if (getOperandBundleAt(i).getTagID() == ID)
1835        Count++;
1836
1837    return Count;
1838  }
1839
1840  /// Return an operand bundle by name, if present.
1841  ///
1842  /// It is an error to call this for operand bundle types that may have
1843  /// multiple instances of them on the same instruction.
1844  Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1845    assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
1846
1847    for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1848      OperandBundleUse U = getOperandBundleAt(i);
1849      if (U.getTagName() == Name)
1850        return U;
1851    }
1852
1853    return None;
1854  }
1855
1856  /// Return an operand bundle by tag ID, if present.
1857  ///
1858  /// It is an error to call this for operand bundle types that may have
1859  /// multiple instances of them on the same instruction.
1860  Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1861    assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
1862
1863    for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1864      OperandBundleUse U = getOperandBundleAt(i);
1865      if (U.getTagID() == ID)
1866        return U;
1867    }
1868
1869    return None;
1870  }
1871
1872  /// Return the list of operand bundles attached to this instruction as
1873  /// a vector of OperandBundleDefs.
1874  ///
1875  /// This function copies the OperandBundeUse instances associated with this
1876  /// OperandBundleUser to a vector of OperandBundleDefs.  Note:
1877  /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1878  /// representations of operand bundles (see documentation above).
1879  void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
1880    for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1881      Defs.emplace_back(getOperandBundleAt(i));
1882  }
1883
1884  /// Return the operand bundle for the operand at index OpIdx.
1885  ///
1886  /// It is an error to call this with an OpIdx that does not correspond to an
1887  /// bundle operand.
1888  OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1889    return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
1890  }
1891
1892  /// Return true if this operand bundle user has operand bundles that
1893  /// may read from the heap.
1894  bool hasReadingOperandBundles() const {
1895    // Implementation note: this is a conservative implementation of operand
1896    // bundle semantics, where *any* operand bundle forces a callsite to be at
1897    // least readonly.
1898    return hasOperandBundles();
1899  }
1900
1901  /// Return true if this operand bundle user has operand bundles that
1902  /// may write to the heap.
1903  bool hasClobberingOperandBundles() const {
1904    for (auto &BOI : bundle_op_infos()) {
1905      if (BOI.Tag->second == LLVMContext::OB_deopt ||
1906          BOI.Tag->second == LLVMContext::OB_funclet)
1907        continue;
1908
1909      // This instruction has an operand bundle that is not known to us.
1910      // Assume the worst.
1911      return true;
1912    }
1913
1914    return false;
1915  }
1916
1917  /// Return true if the bundle operand at index \p OpIdx has the
1918  /// attribute \p A.
1919  bool bundleOperandHasAttr(unsigned OpIdx,  Attribute::AttrKind A) const {
1920    auto &BOI = getBundleOpInfoForOperand(OpIdx);
1921    auto OBU = operandBundleFromBundleOpInfo(BOI);
1922    return OBU.operandHasAttr(OpIdx - BOI.Begin, A);
1923  }
1924
1925  /// Return true if \p Other has the same sequence of operand bundle
1926  /// tags with the same number of operands on each one of them as this
1927  /// OperandBundleUser.
1928  bool hasIdenticalOperandBundleSchema(const CallBase &Other) const {
1929    if (getNumOperandBundles() != Other.getNumOperandBundles())
1930      return false;
1931
1932    return std::equal(bundle_op_info_begin(), bundle_op_info_end(),
1933                      Other.bundle_op_info_begin());
1934  }
1935
1936  /// Return true if this operand bundle user contains operand bundles
1937  /// with tags other than those specified in \p IDs.
1938  bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const {
1939    for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1940      uint32_t ID = getOperandBundleAt(i).getTagID();
1941      if (!is_contained(IDs, ID))
1942        return true;
1943    }
1944    return false;
1945  }
1946
1947  /// Is the function attribute S disallowed by some operand bundle on
1948  /// this operand bundle user?
1949  bool isFnAttrDisallowedByOpBundle(StringRef S) const {
1950    // Operand bundles only possibly disallow readnone, readonly and argmemonly
1951    // attributes.  All String attributes are fine.
1952    return false;
1953  }
1954
1955  /// Is the function attribute A disallowed by some operand bundle on
1956  /// this operand bundle user?
1957  bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
1958    switch (A) {
1959    default:
1960      return false;
1961
1962    case Attribute::InaccessibleMemOrArgMemOnly:
1963      return hasReadingOperandBundles();
1964
1965    case Attribute::InaccessibleMemOnly:
1966      return hasReadingOperandBundles();
1967
1968    case Attribute::ArgMemOnly:
1969      return hasReadingOperandBundles();
1970
1971    case Attribute::ReadNone:
1972      return hasReadingOperandBundles();
1973
1974    case Attribute::ReadOnly:
1975      return hasClobberingOperandBundles();
1976    }
1977
1978    llvm_unreachable("switch has a default case!");
1979  }
1980
1981  /// Used to keep track of an operand bundle.  See the main comment on
1982  /// OperandBundleUser above.
1983  struct BundleOpInfo {
1984    /// The operand bundle tag, interned by
1985    /// LLVMContextImpl::getOrInsertBundleTag.
1986    StringMapEntry<uint32_t> *Tag;
1987
1988    /// The index in the Use& vector where operands for this operand
1989    /// bundle starts.
1990    uint32_t Begin;
1991
1992    /// The index in the Use& vector where operands for this operand
1993    /// bundle ends.
1994    uint32_t End;
1995
1996    bool operator==(const BundleOpInfo &Other) const {
1997      return Tag == Other.Tag && Begin == Other.Begin && End == Other.End;
1998    }
1999  };
2000
2001  /// Simple helper function to map a BundleOpInfo to an
2002  /// OperandBundleUse.
2003  OperandBundleUse
2004  operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
2005    auto begin = op_begin();
2006    ArrayRef<Use> Inputs(begin + BOI.Begin, begin + BOI.End);
2007    return OperandBundleUse(BOI.Tag, Inputs);
2008  }
2009
2010  using bundle_op_iterator = BundleOpInfo *;
2011  using const_bundle_op_iterator = const BundleOpInfo *;
2012
2013  /// Return the start of the list of BundleOpInfo instances associated
2014  /// with this OperandBundleUser.
2015  ///
2016  /// OperandBundleUser uses the descriptor area co-allocated with the host User
2017  /// to store some meta information about which operands are "normal" operands,
2018  /// and which ones belong to some operand bundle.
2019  ///
2020  /// The layout of an operand bundle user is
2021  ///
2022  ///          +-----------uint32_t End-------------------------------------+
2023  ///          |                                                            |
2024  ///          |  +--------uint32_t Begin--------------------+              |
2025  ///          |  |                                          |              |
2026  ///          ^  ^                                          v              v
2027  ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
2028  ///  | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
2029  ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
2030  ///   v  v                                  ^              ^
2031  ///   |  |                                  |              |
2032  ///   |  +--------uint32_t Begin------------+              |
2033  ///   |                                                    |
2034  ///   +-----------uint32_t End-----------------------------+
2035  ///
2036  ///
2037  /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use
2038  /// list. These descriptions are installed and managed by this class, and
2039  /// they're all instances of OperandBundleUser<T>::BundleOpInfo.
2040  ///
2041  /// DU is an additional descriptor installed by User's 'operator new' to keep
2042  /// track of the 'BOI0 ... BOIN' co-allocation.  OperandBundleUser does not
2043  /// access or modify DU in any way, it's an implementation detail private to
2044  /// User.
2045  ///
2046  /// The regular Use& vector for the User starts at U0.  The operand bundle
2047  /// uses are part of the Use& vector, just like normal uses.  In the diagram
2048  /// above, the operand bundle uses start at BOI0_U0.  Each instance of
2049  /// BundleOpInfo has information about a contiguous set of uses constituting
2050  /// an operand bundle, and the total set of operand bundle uses themselves
2051  /// form a contiguous set of uses (i.e. there are no gaps between uses
2052  /// corresponding to individual operand bundles).
2053  ///
2054  /// This class does not know the location of the set of operand bundle uses
2055  /// within the use list -- that is decided by the User using this class via
2056  /// the BeginIdx argument in populateBundleOperandInfos.
2057  ///
2058  /// Currently operand bundle users with hung-off operands are not supported.
2059  bundle_op_iterator bundle_op_info_begin() {
2060    if (!hasDescriptor())
2061      return nullptr;
2062
2063    uint8_t *BytesBegin = getDescriptor().begin();
2064    return reinterpret_cast<bundle_op_iterator>(BytesBegin);
2065  }
2066
2067  /// Return the start of the list of BundleOpInfo instances associated
2068  /// with this OperandBundleUser.
2069  const_bundle_op_iterator bundle_op_info_begin() const {
2070    auto *NonConstThis = const_cast<CallBase *>(this);
2071    return NonConstThis->bundle_op_info_begin();
2072  }
2073
2074  /// Return the end of the list of BundleOpInfo instances associated
2075  /// with this OperandBundleUser.
2076  bundle_op_iterator bundle_op_info_end() {
2077    if (!hasDescriptor())
2078      return nullptr;
2079
2080    uint8_t *BytesEnd = getDescriptor().end();
2081    return reinterpret_cast<bundle_op_iterator>(BytesEnd);
2082  }
2083
2084  /// Return the end of the list of BundleOpInfo instances associated
2085  /// with this OperandBundleUser.
2086  const_bundle_op_iterator bundle_op_info_end() const {
2087    auto *NonConstThis = const_cast<CallBase *>(this);
2088    return NonConstThis->bundle_op_info_end();
2089  }
2090
2091  /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
2092  iterator_range<bundle_op_iterator> bundle_op_infos() {
2093    return make_range(bundle_op_info_begin(), bundle_op_info_end());
2094  }
2095
2096  /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
2097  iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
2098    return make_range(bundle_op_info_begin(), bundle_op_info_end());
2099  }
2100
2101  /// Populate the BundleOpInfo instances and the Use& vector from \p
2102  /// Bundles.  Return the op_iterator pointing to the Use& one past the last
2103  /// last bundle operand use.
2104  ///
2105  /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
2106  /// instance allocated in this User's descriptor.
2107  op_iterator populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
2108                                         const unsigned BeginIndex);
2109
2110  /// Return the BundleOpInfo for the operand at index OpIdx.
2111  ///
2112  /// It is an error to call this with an OpIdx that does not correspond to an
2113  /// bundle operand.
2114  const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
2115    for (auto &BOI : bundle_op_infos())
2116      if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
2117        return BOI;
2118
2119    llvm_unreachable("Did not find operand bundle for operand!");
2120  }
2121
2122protected:
2123  /// Return the total number of values used in \p Bundles.
2124  static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
2125    unsigned Total = 0;
2126    for (auto &B : Bundles)
2127      Total += B.input_size();
2128    return Total;
2129  }
2130
2131  /// @}
2132  // End of operand bundle API.
2133
2134private:
2135  bool hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
2136  bool hasFnAttrOnCalledFunction(StringRef Kind) const;
2137
2138  template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
2139    if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
2140      return true;
2141
2142    // Operand bundles override attributes on the called function, but don't
2143    // override attributes directly present on the call instruction.
2144    if (isFnAttrDisallowedByOpBundle(Kind))
2145      return false;
2146
2147    return hasFnAttrOnCalledFunction(Kind);
2148  }
2149};
2150
2151template <>
2152struct OperandTraits<CallBase> : public VariadicOperandTraits<CallBase, 1> {};
2153
2154DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallBase, Value)
2155
2156//===----------------------------------------------------------------------===//
2157//                           FuncletPadInst Class
2158//===----------------------------------------------------------------------===//
2159class FuncletPadInst : public Instruction {
2160private:
2161  FuncletPadInst(const FuncletPadInst &CPI);
2162
2163  explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2164                          ArrayRef<Value *> Args, unsigned Values,
2165                          const Twine &NameStr, Instruction *InsertBefore);
2166  explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2167                          ArrayRef<Value *> Args, unsigned Values,
2168                          const Twine &NameStr, BasicBlock *InsertAtEnd);
2169
2170  void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
2171
2172protected:
2173  // Note: Instruction needs to be a friend here to call cloneImpl.
2174  friend class Instruction;
2175  friend class CatchPadInst;
2176  friend class CleanupPadInst;
2177
2178  FuncletPadInst *cloneImpl() const;
2179
2180public:
2181  /// Provide fast operand accessors
2182  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2183
2184  /// getNumArgOperands - Return the number of funcletpad arguments.
2185  ///
2186  unsigned getNumArgOperands() const { return getNumOperands() - 1; }
2187
2188  /// Convenience accessors
2189
2190  /// Return the outer EH-pad this funclet is nested within.
2191  ///
2192  /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
2193  /// is a CatchPadInst.
2194  Value *getParentPad() const { return Op<-1>(); }
2195  void setParentPad(Value *ParentPad) {
2196    assert(ParentPad);
2197    Op<-1>() = ParentPad;
2198  }
2199
2200  /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
2201  ///
2202  Value *getArgOperand(unsigned i) const { return getOperand(i); }
2203  void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
2204
2205  /// arg_operands - iteration adapter for range-for loops.
2206  op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
2207
2208  /// arg_operands - iteration adapter for range-for loops.
2209  const_op_range arg_operands() const {
2210    return const_op_range(op_begin(), op_end() - 1);
2211  }
2212
2213  // Methods for support type inquiry through isa, cast, and dyn_cast:
2214  static bool classof(const Instruction *I) { return I->isFuncletPad(); }
2215  static bool classof(const Value *V) {
2216    return isa<Instruction>(V) && classof(cast<Instruction>(V));
2217  }
2218};
2219
2220template <>
2221struct OperandTraits<FuncletPadInst>
2222    : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {};
2223
2224DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)
2225
2226} // end namespace llvm
2227
2228#endif // LLVM_IR_INSTRTYPES_H
2229