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