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