1 //===-- llvm/Instruction.h - Instruction class definition -------*- 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 contains the declaration of the Instruction class, which is the 10 // base class for all of the LLVM instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_IR_INSTRUCTION_H 15 #define LLVM_IR_INSTRUCTION_H 16 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/Bitfields.h" 19 #include "llvm/ADT/None.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/ADT/ilist_node.h" 22 #include "llvm/IR/DebugLoc.h" 23 #include "llvm/IR/SymbolTableListTraits.h" 24 #include "llvm/IR/User.h" 25 #include "llvm/IR/Value.h" 26 #include "llvm/Support/AtomicOrdering.h" 27 #include "llvm/Support/Casting.h" 28 #include <cstdint> 29 #include <utility> 30 31 namespace llvm { 32 33 class BasicBlock; 34 class FastMathFlags; 35 class MDNode; 36 class Module; 37 struct AAMDNodes; 38 39 template <> struct ilist_alloc_traits<Instruction> { 40 static inline void deleteNode(Instruction *V); 41 }; 42 43 class Instruction : public User, 44 public ilist_node_with_parent<Instruction, BasicBlock> { 45 BasicBlock *Parent; 46 DebugLoc DbgLoc; // 'dbg' Metadata cache. 47 48 /// Relative order of this instruction in its parent basic block. Used for 49 /// O(1) local dominance checks between instructions. 50 mutable unsigned Order = 0; 51 52 protected: 53 // The 15 first bits of `Value::SubclassData` are available for subclasses of 54 // `Instruction` to use. 55 using OpaqueField = Bitfield::Element<uint16_t, 0, 15>; 56 57 // Template alias so that all Instruction storing alignment use the same 58 // definiton. 59 // Valid alignments are powers of two from 2^0 to 2^MaxAlignmentExponent = 60 // 2^32. We store them as Log2(Alignment), so we need 6 bits to encode the 33 61 // possible values. 62 template <unsigned Offset> 63 using AlignmentBitfieldElementT = 64 typename Bitfield::Element<unsigned, Offset, 6, 65 Value::MaxAlignmentExponent>; 66 67 template <unsigned Offset> 68 using BoolBitfieldElementT = typename Bitfield::Element<bool, Offset, 1>; 69 70 template <unsigned Offset> 71 using AtomicOrderingBitfieldElementT = 72 typename Bitfield::Element<AtomicOrdering, Offset, 3, 73 AtomicOrdering::LAST>; 74 75 private: 76 // The last bit is used to store whether the instruction has metadata attached 77 // or not. 78 using HasMetadataField = Bitfield::Element<bool, 15, 1>; 79 80 protected: 81 ~Instruction(); // Use deleteValue() to delete a generic Instruction. 82 83 public: 84 Instruction(const Instruction &) = delete; 85 Instruction &operator=(const Instruction &) = delete; 86 87 /// Specialize the methods defined in Value, as we know that an instruction 88 /// can only be used by other instructions. 89 Instruction *user_back() { return cast<Instruction>(*user_begin());} 90 const Instruction *user_back() const { return cast<Instruction>(*user_begin());} 91 92 inline const BasicBlock *getParent() const { return Parent; } 93 inline BasicBlock *getParent() { return Parent; } 94 95 /// Return the module owning the function this instruction belongs to 96 /// or nullptr it the function does not have a module. 97 /// 98 /// Note: this is undefined behavior if the instruction does not have a 99 /// parent, or the parent basic block does not have a parent function. 100 const Module *getModule() const; 101 Module *getModule() { 102 return const_cast<Module *>( 103 static_cast<const Instruction *>(this)->getModule()); 104 } 105 106 /// Return the function this instruction belongs to. 107 /// 108 /// Note: it is undefined behavior to call this on an instruction not 109 /// currently inserted into a function. 110 const Function *getFunction() const; 111 Function *getFunction() { 112 return const_cast<Function *>( 113 static_cast<const Instruction *>(this)->getFunction()); 114 } 115 116 /// This method unlinks 'this' from the containing basic block, but does not 117 /// delete it. 118 void removeFromParent(); 119 120 /// This method unlinks 'this' from the containing basic block and deletes it. 121 /// 122 /// \returns an iterator pointing to the element after the erased one 123 SymbolTableList<Instruction>::iterator eraseFromParent(); 124 125 /// Insert an unlinked instruction into a basic block immediately before 126 /// the specified instruction. 127 void insertBefore(Instruction *InsertPos); 128 129 /// Insert an unlinked instruction into a basic block immediately after the 130 /// specified instruction. 131 void insertAfter(Instruction *InsertPos); 132 133 /// Unlink this instruction from its current basic block and insert it into 134 /// the basic block that MovePos lives in, right before MovePos. 135 void moveBefore(Instruction *MovePos); 136 137 /// Unlink this instruction and insert into BB before I. 138 /// 139 /// \pre I is a valid iterator into BB. 140 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I); 141 142 /// Unlink this instruction from its current basic block and insert it into 143 /// the basic block that MovePos lives in, right after MovePos. 144 void moveAfter(Instruction *MovePos); 145 146 /// Given an instruction Other in the same basic block as this instruction, 147 /// return true if this instruction comes before Other. In this worst case, 148 /// this takes linear time in the number of instructions in the block. The 149 /// results are cached, so in common cases when the block remains unmodified, 150 /// it takes constant time. 151 bool comesBefore(const Instruction *Other) const; 152 153 //===--------------------------------------------------------------------===// 154 // Subclass classification. 155 //===--------------------------------------------------------------------===// 156 157 /// Returns a member of one of the enums like Instruction::Add. 158 unsigned getOpcode() const { return getValueID() - InstructionVal; } 159 160 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); } 161 bool isTerminator() const { return isTerminator(getOpcode()); } 162 bool isUnaryOp() const { return isUnaryOp(getOpcode()); } 163 bool isBinaryOp() const { return isBinaryOp(getOpcode()); } 164 bool isIntDivRem() const { return isIntDivRem(getOpcode()); } 165 bool isShift() const { return isShift(getOpcode()); } 166 bool isCast() const { return isCast(getOpcode()); } 167 bool isFuncletPad() const { return isFuncletPad(getOpcode()); } 168 bool isExceptionalTerminator() const { 169 return isExceptionalTerminator(getOpcode()); 170 } 171 172 /// It checks if this instruction is the only user of at least one of 173 /// its operands. 174 bool isOnlyUserOfAnyOperand(); 175 176 bool isIndirectTerminator() const { 177 return isIndirectTerminator(getOpcode()); 178 } 179 180 static const char* getOpcodeName(unsigned OpCode); 181 182 static inline bool isTerminator(unsigned OpCode) { 183 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd; 184 } 185 186 static inline bool isUnaryOp(unsigned Opcode) { 187 return Opcode >= UnaryOpsBegin && Opcode < UnaryOpsEnd; 188 } 189 static inline bool isBinaryOp(unsigned Opcode) { 190 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd; 191 } 192 193 static inline bool isIntDivRem(unsigned Opcode) { 194 return Opcode == UDiv || Opcode == SDiv || Opcode == URem || Opcode == SRem; 195 } 196 197 /// Determine if the Opcode is one of the shift instructions. 198 static inline bool isShift(unsigned Opcode) { 199 return Opcode >= Shl && Opcode <= AShr; 200 } 201 202 /// Return true if this is a logical shift left or a logical shift right. 203 inline bool isLogicalShift() const { 204 return getOpcode() == Shl || getOpcode() == LShr; 205 } 206 207 /// Return true if this is an arithmetic shift right. 208 inline bool isArithmeticShift() const { 209 return getOpcode() == AShr; 210 } 211 212 /// Determine if the Opcode is and/or/xor. 213 static inline bool isBitwiseLogicOp(unsigned Opcode) { 214 return Opcode == And || Opcode == Or || Opcode == Xor; 215 } 216 217 /// Return true if this is and/or/xor. 218 inline bool isBitwiseLogicOp() const { 219 return isBitwiseLogicOp(getOpcode()); 220 } 221 222 /// Determine if the OpCode is one of the CastInst instructions. 223 static inline bool isCast(unsigned OpCode) { 224 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd; 225 } 226 227 /// Determine if the OpCode is one of the FuncletPadInst instructions. 228 static inline bool isFuncletPad(unsigned OpCode) { 229 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd; 230 } 231 232 /// Returns true if the OpCode is a terminator related to exception handling. 233 static inline bool isExceptionalTerminator(unsigned OpCode) { 234 switch (OpCode) { 235 case Instruction::CatchSwitch: 236 case Instruction::CatchRet: 237 case Instruction::CleanupRet: 238 case Instruction::Invoke: 239 case Instruction::Resume: 240 return true; 241 default: 242 return false; 243 } 244 } 245 246 /// Returns true if the OpCode is a terminator with indirect targets. 247 static inline bool isIndirectTerminator(unsigned OpCode) { 248 switch (OpCode) { 249 case Instruction::IndirectBr: 250 case Instruction::CallBr: 251 return true; 252 default: 253 return false; 254 } 255 } 256 257 //===--------------------------------------------------------------------===// 258 // Metadata manipulation. 259 //===--------------------------------------------------------------------===// 260 261 /// Return true if this instruction has any metadata attached to it. 262 bool hasMetadata() const { return DbgLoc || Value::hasMetadata(); } 263 264 /// Return true if this instruction has metadata attached to it other than a 265 /// debug location. 266 bool hasMetadataOtherThanDebugLoc() const { return Value::hasMetadata(); } 267 268 /// Return true if this instruction has the given type of metadata attached. 269 bool hasMetadata(unsigned KindID) const { 270 return getMetadata(KindID) != nullptr; 271 } 272 273 /// Return true if this instruction has the given type of metadata attached. 274 bool hasMetadata(StringRef Kind) const { 275 return getMetadata(Kind) != nullptr; 276 } 277 278 /// Get the metadata of given kind attached to this Instruction. 279 /// If the metadata is not found then return null. 280 MDNode *getMetadata(unsigned KindID) const { 281 if (!hasMetadata()) return nullptr; 282 return getMetadataImpl(KindID); 283 } 284 285 /// Get the metadata of given kind attached to this Instruction. 286 /// If the metadata is not found then return null. 287 MDNode *getMetadata(StringRef Kind) const { 288 if (!hasMetadata()) return nullptr; 289 return getMetadataImpl(Kind); 290 } 291 292 /// Get all metadata attached to this Instruction. The first element of each 293 /// pair returned is the KindID, the second element is the metadata value. 294 /// This list is returned sorted by the KindID. 295 void 296 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 297 if (hasMetadata()) 298 getAllMetadataImpl(MDs); 299 } 300 301 /// This does the same thing as getAllMetadata, except that it filters out the 302 /// debug location. 303 void getAllMetadataOtherThanDebugLoc( 304 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 305 Value::getAllMetadata(MDs); 306 } 307 308 /// Set the metadata of the specified kind to the specified node. This updates 309 /// or replaces metadata if already present, or removes it if Node is null. 310 void setMetadata(unsigned KindID, MDNode *Node); 311 void setMetadata(StringRef Kind, MDNode *Node); 312 313 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty, 314 /// specifies the list of meta data that needs to be copied. If \p WL is 315 /// empty, all meta data will be copied. 316 void copyMetadata(const Instruction &SrcInst, 317 ArrayRef<unsigned> WL = ArrayRef<unsigned>()); 318 319 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode 320 /// has three operands (including name string), swap the order of the 321 /// metadata. 322 void swapProfMetadata(); 323 324 /// Drop all unknown metadata except for debug locations. 325 /// @{ 326 /// Passes are required to drop metadata they don't understand. This is a 327 /// convenience method for passes to do so. 328 /// dropUndefImplyingAttrsAndUnknownMetadata should be used instead of 329 /// this API if the Instruction being modified is a call. 330 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs); 331 void dropUnknownNonDebugMetadata() { 332 return dropUnknownNonDebugMetadata(None); 333 } 334 void dropUnknownNonDebugMetadata(unsigned ID1) { 335 return dropUnknownNonDebugMetadata(makeArrayRef(ID1)); 336 } 337 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) { 338 unsigned IDs[] = {ID1, ID2}; 339 return dropUnknownNonDebugMetadata(IDs); 340 } 341 /// @} 342 343 /// Adds an !annotation metadata node with \p Annotation to this instruction. 344 /// If this instruction already has !annotation metadata, append \p Annotation 345 /// to the existing node. 346 void addAnnotationMetadata(StringRef Annotation); 347 348 /// Returns the AA metadata for this instruction. 349 AAMDNodes getAAMetadata() const; 350 351 /// Sets the AA metadata on this instruction from the AAMDNodes structure. 352 void setAAMetadata(const AAMDNodes &N); 353 354 /// Retrieve the raw weight values of a conditional branch or select. 355 /// Returns true on success with profile weights filled in. 356 /// Returns false if no metadata or invalid metadata was found. 357 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const; 358 359 /// Retrieve total raw weight values of a branch. 360 /// Returns true on success with profile total weights filled in. 361 /// Returns false if no metadata was found. 362 bool extractProfTotalWeight(uint64_t &TotalVal) const; 363 364 /// Set the debug location information for this instruction. 365 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); } 366 367 /// Return the debug location for this node as a DebugLoc. 368 const DebugLoc &getDebugLoc() const { return DbgLoc; } 369 370 /// Set or clear the nuw flag on this instruction, which must be an operator 371 /// which supports this flag. See LangRef.html for the meaning of this flag. 372 void setHasNoUnsignedWrap(bool b = true); 373 374 /// Set or clear the nsw flag on this instruction, which must be an operator 375 /// which supports this flag. See LangRef.html for the meaning of this flag. 376 void setHasNoSignedWrap(bool b = true); 377 378 /// Set or clear the exact flag on this instruction, which must be an operator 379 /// which supports this flag. See LangRef.html for the meaning of this flag. 380 void setIsExact(bool b = true); 381 382 /// Determine whether the no unsigned wrap flag is set. 383 bool hasNoUnsignedWrap() const; 384 385 /// Determine whether the no signed wrap flag is set. 386 bool hasNoSignedWrap() const; 387 388 /// Return true if this operator has flags which may cause this instruction 389 /// to evaluate to poison despite having non-poison inputs. 390 bool hasPoisonGeneratingFlags() const; 391 392 /// Drops flags that may cause this instruction to evaluate to poison despite 393 /// having non-poison inputs. 394 void dropPoisonGeneratingFlags(); 395 396 /// This function drops non-debug unknown metadata (through 397 /// dropUnknownNonDebugMetadata). For calls, it also drops parameter and 398 /// return attributes that can cause undefined behaviour. Both of these should 399 /// be done by passes which move instructions in IR. 400 void 401 dropUndefImplyingAttrsAndUnknownMetadata(ArrayRef<unsigned> KnownIDs = {}); 402 403 /// Determine whether the exact flag is set. 404 bool isExact() const; 405 406 /// Set or clear all fast-math-flags on this instruction, which must be an 407 /// operator which supports this flag. See LangRef.html for the meaning of 408 /// this flag. 409 void setFast(bool B); 410 411 /// Set or clear the reassociation flag on this instruction, which must be 412 /// an operator which supports this flag. See LangRef.html for the meaning of 413 /// this flag. 414 void setHasAllowReassoc(bool B); 415 416 /// Set or clear the no-nans flag on this instruction, which must be an 417 /// operator which supports this flag. See LangRef.html for the meaning of 418 /// this flag. 419 void setHasNoNaNs(bool B); 420 421 /// Set or clear the no-infs flag on this instruction, which must be an 422 /// operator which supports this flag. See LangRef.html for the meaning of 423 /// this flag. 424 void setHasNoInfs(bool B); 425 426 /// Set or clear the no-signed-zeros flag on this instruction, which must be 427 /// an operator which supports this flag. See LangRef.html for the meaning of 428 /// this flag. 429 void setHasNoSignedZeros(bool B); 430 431 /// Set or clear the allow-reciprocal flag on this instruction, which must be 432 /// an operator which supports this flag. See LangRef.html for the meaning of 433 /// this flag. 434 void setHasAllowReciprocal(bool B); 435 436 /// Set or clear the allow-contract flag on this instruction, which must be 437 /// an operator which supports this flag. See LangRef.html for the meaning of 438 /// this flag. 439 void setHasAllowContract(bool B); 440 441 /// Set or clear the approximate-math-functions flag on this instruction, 442 /// which must be an operator which supports this flag. See LangRef.html for 443 /// the meaning of this flag. 444 void setHasApproxFunc(bool B); 445 446 /// Convenience function for setting multiple fast-math flags on this 447 /// instruction, which must be an operator which supports these flags. See 448 /// LangRef.html for the meaning of these flags. 449 void setFastMathFlags(FastMathFlags FMF); 450 451 /// Convenience function for transferring all fast-math flag values to this 452 /// instruction, which must be an operator which supports these flags. See 453 /// LangRef.html for the meaning of these flags. 454 void copyFastMathFlags(FastMathFlags FMF); 455 456 /// Determine whether all fast-math-flags are set. 457 bool isFast() const; 458 459 /// Determine whether the allow-reassociation flag is set. 460 bool hasAllowReassoc() const; 461 462 /// Determine whether the no-NaNs flag is set. 463 bool hasNoNaNs() const; 464 465 /// Determine whether the no-infs flag is set. 466 bool hasNoInfs() const; 467 468 /// Determine whether the no-signed-zeros flag is set. 469 bool hasNoSignedZeros() const; 470 471 /// Determine whether the allow-reciprocal flag is set. 472 bool hasAllowReciprocal() const; 473 474 /// Determine whether the allow-contract flag is set. 475 bool hasAllowContract() const; 476 477 /// Determine whether the approximate-math-functions flag is set. 478 bool hasApproxFunc() const; 479 480 /// Convenience function for getting all the fast-math flags, which must be an 481 /// operator which supports these flags. See LangRef.html for the meaning of 482 /// these flags. 483 FastMathFlags getFastMathFlags() const; 484 485 /// Copy I's fast-math flags 486 void copyFastMathFlags(const Instruction *I); 487 488 /// Convenience method to copy supported exact, fast-math, and (optionally) 489 /// wrapping flags from V to this instruction. 490 void copyIRFlags(const Value *V, bool IncludeWrapFlags = true); 491 492 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of 493 /// V and this instruction. 494 void andIRFlags(const Value *V); 495 496 /// Merge 2 debug locations and apply it to the Instruction. If the 497 /// instruction is a CallIns, we need to traverse the inline chain to find 498 /// the common scope. This is not efficient for N-way merging as each time 499 /// you merge 2 iterations, you need to rebuild the hashmap to find the 500 /// common scope. However, we still choose this API because: 501 /// 1) Simplicity: it takes 2 locations instead of a list of locations. 502 /// 2) In worst case, it increases the complexity from O(N*I) to 503 /// O(2*N*I), where N is # of Instructions to merge, and I is the 504 /// maximum level of inline stack. So it is still linear. 505 /// 3) Merging of call instructions should be extremely rare in real 506 /// applications, thus the N-way merging should be in code path. 507 /// The DebugLoc attached to this instruction will be overwritten by the 508 /// merged DebugLoc. 509 void applyMergedLocation(const DILocation *LocA, const DILocation *LocB); 510 511 /// Updates the debug location given that the instruction has been hoisted 512 /// from a block to a predecessor of that block. 513 /// Note: it is undefined behavior to call this on an instruction not 514 /// currently inserted into a function. 515 void updateLocationAfterHoist(); 516 517 /// Drop the instruction's debug location. This does not guarantee removal 518 /// of the !dbg source location attachment, as it must set a line 0 location 519 /// with scope information attached on call instructions. To guarantee 520 /// removal of the !dbg attachment, use the \ref setDebugLoc() API. 521 /// Note: it is undefined behavior to call this on an instruction not 522 /// currently inserted into a function. 523 void dropLocation(); 524 525 private: 526 // These are all implemented in Metadata.cpp. 527 MDNode *getMetadataImpl(unsigned KindID) const; 528 MDNode *getMetadataImpl(StringRef Kind) const; 529 void 530 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const; 531 532 public: 533 //===--------------------------------------------------------------------===// 534 // Predicates and helper methods. 535 //===--------------------------------------------------------------------===// 536 537 /// Return true if the instruction is associative: 538 /// 539 /// Associative operators satisfy: x op (y op z) === (x op y) op z 540 /// 541 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative. 542 /// 543 bool isAssociative() const LLVM_READONLY; 544 static bool isAssociative(unsigned Opcode) { 545 return Opcode == And || Opcode == Or || Opcode == Xor || 546 Opcode == Add || Opcode == Mul; 547 } 548 549 /// Return true if the instruction is commutative: 550 /// 551 /// Commutative operators satisfy: (x op y) === (y op x) 552 /// 553 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when 554 /// applied to any type. 555 /// 556 bool isCommutative() const LLVM_READONLY; 557 static bool isCommutative(unsigned Opcode) { 558 switch (Opcode) { 559 case Add: case FAdd: 560 case Mul: case FMul: 561 case And: case Or: case Xor: 562 return true; 563 default: 564 return false; 565 } 566 } 567 568 /// Return true if the instruction is idempotent: 569 /// 570 /// Idempotent operators satisfy: x op x === x 571 /// 572 /// In LLVM, the And and Or operators are idempotent. 573 /// 574 bool isIdempotent() const { return isIdempotent(getOpcode()); } 575 static bool isIdempotent(unsigned Opcode) { 576 return Opcode == And || Opcode == Or; 577 } 578 579 /// Return true if the instruction is nilpotent: 580 /// 581 /// Nilpotent operators satisfy: x op x === Id, 582 /// 583 /// where Id is the identity for the operator, i.e. a constant such that 584 /// x op Id === x and Id op x === x for all x. 585 /// 586 /// In LLVM, the Xor operator is nilpotent. 587 /// 588 bool isNilpotent() const { return isNilpotent(getOpcode()); } 589 static bool isNilpotent(unsigned Opcode) { 590 return Opcode == Xor; 591 } 592 593 /// Return true if this instruction may modify memory. 594 bool mayWriteToMemory() const; 595 596 /// Return true if this instruction may read memory. 597 bool mayReadFromMemory() const; 598 599 /// Return true if this instruction may read or write memory. 600 bool mayReadOrWriteMemory() const { 601 return mayReadFromMemory() || mayWriteToMemory(); 602 } 603 604 /// Return true if this instruction has an AtomicOrdering of unordered or 605 /// higher. 606 bool isAtomic() const; 607 608 /// Return true if this atomic instruction loads from memory. 609 bool hasAtomicLoad() const; 610 611 /// Return true if this atomic instruction stores to memory. 612 bool hasAtomicStore() const; 613 614 /// Return true if this instruction has a volatile memory access. 615 bool isVolatile() const; 616 617 /// Return true if this instruction may throw an exception. 618 bool mayThrow() const; 619 620 /// Return true if this instruction behaves like a memory fence: it can load 621 /// or store to memory location without being given a memory location. 622 bool isFenceLike() const { 623 switch (getOpcode()) { 624 default: 625 return false; 626 // This list should be kept in sync with the list in mayWriteToMemory for 627 // all opcodes which don't have a memory location. 628 case Instruction::Fence: 629 case Instruction::CatchPad: 630 case Instruction::CatchRet: 631 case Instruction::Call: 632 case Instruction::Invoke: 633 return true; 634 } 635 } 636 637 /// Return true if the instruction may have side effects. 638 /// 639 /// Side effects are: 640 /// * Writing to memory. 641 /// * Unwinding. 642 /// * Not returning (e.g. an infinite loop). 643 /// 644 /// Note that this does not consider malloc and alloca to have side 645 /// effects because the newly allocated memory is completely invisible to 646 /// instructions which don't use the returned value. For cases where this 647 /// matters, isSafeToSpeculativelyExecute may be more appropriate. 648 bool mayHaveSideEffects() const; 649 650 /// Return true if the instruction can be removed if the result is unused. 651 /// 652 /// When constant folding some instructions cannot be removed even if their 653 /// results are unused. Specifically terminator instructions and calls that 654 /// may have side effects cannot be removed without semantically changing the 655 /// generated program. 656 bool isSafeToRemove() const; 657 658 /// Return true if the instruction will return (unwinding is considered as 659 /// a form of returning control flow here). 660 bool willReturn() const; 661 662 /// Return true if the instruction is a variety of EH-block. 663 bool isEHPad() const { 664 switch (getOpcode()) { 665 case Instruction::CatchSwitch: 666 case Instruction::CatchPad: 667 case Instruction::CleanupPad: 668 case Instruction::LandingPad: 669 return true; 670 default: 671 return false; 672 } 673 } 674 675 /// Return true if the instruction is a llvm.lifetime.start or 676 /// llvm.lifetime.end marker. 677 bool isLifetimeStartOrEnd() const; 678 679 /// Return true if the instruction is a llvm.launder.invariant.group or 680 /// llvm.strip.invariant.group. 681 bool isLaunderOrStripInvariantGroup() const; 682 683 /// Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst. 684 bool isDebugOrPseudoInst() const; 685 686 /// Return a pointer to the next non-debug instruction in the same basic 687 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo 688 /// operations if \c SkipPseudoOp is true. 689 const Instruction * 690 getNextNonDebugInstruction(bool SkipPseudoOp = false) const; 691 Instruction *getNextNonDebugInstruction(bool SkipPseudoOp = false) { 692 return const_cast<Instruction *>( 693 static_cast<const Instruction *>(this)->getNextNonDebugInstruction( 694 SkipPseudoOp)); 695 } 696 697 /// Return a pointer to the previous non-debug instruction in the same basic 698 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo 699 /// operations if \c SkipPseudoOp is true. 700 const Instruction * 701 getPrevNonDebugInstruction(bool SkipPseudoOp = false) const; 702 Instruction *getPrevNonDebugInstruction(bool SkipPseudoOp = false) { 703 return const_cast<Instruction *>( 704 static_cast<const Instruction *>(this)->getPrevNonDebugInstruction( 705 SkipPseudoOp)); 706 } 707 708 /// Create a copy of 'this' instruction that is identical in all ways except 709 /// the following: 710 /// * The instruction has no parent 711 /// * The instruction has no name 712 /// 713 Instruction *clone() const; 714 715 /// Return true if the specified instruction is exactly identical to the 716 /// current one. This means that all operands match and any extra information 717 /// (e.g. load is volatile) agree. 718 bool isIdenticalTo(const Instruction *I) const; 719 720 /// This is like isIdenticalTo, except that it ignores the 721 /// SubclassOptionalData flags, which may specify conditions under which the 722 /// instruction's result is undefined. 723 bool isIdenticalToWhenDefined(const Instruction *I) const; 724 725 /// When checking for operation equivalence (using isSameOperationAs) it is 726 /// sometimes useful to ignore certain attributes. 727 enum OperationEquivalenceFlags { 728 /// Check for equivalence ignoring load/store alignment. 729 CompareIgnoringAlignment = 1<<0, 730 /// Check for equivalence treating a type and a vector of that type 731 /// as equivalent. 732 CompareUsingScalarTypes = 1<<1 733 }; 734 735 /// This function determines if the specified instruction executes the same 736 /// operation as the current one. This means that the opcodes, type, operand 737 /// types and any other factors affecting the operation must be the same. This 738 /// is similar to isIdenticalTo except the operands themselves don't have to 739 /// be identical. 740 /// @returns true if the specified instruction is the same operation as 741 /// the current one. 742 /// Determine if one instruction is the same operation as another. 743 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const; 744 745 /// Return true if there are any uses of this instruction in blocks other than 746 /// the specified block. Note that PHI nodes are considered to evaluate their 747 /// operands in the corresponding predecessor block. 748 bool isUsedOutsideOfBlock(const BasicBlock *BB) const; 749 750 /// Return the number of successors that this instruction has. The instruction 751 /// must be a terminator. 752 unsigned getNumSuccessors() const; 753 754 /// Return the specified successor. This instruction must be a terminator. 755 BasicBlock *getSuccessor(unsigned Idx) const; 756 757 /// Update the specified successor to point at the provided block. This 758 /// instruction must be a terminator. 759 void setSuccessor(unsigned Idx, BasicBlock *BB); 760 761 /// Replace specified successor OldBB to point at the provided block. 762 /// This instruction must be a terminator. 763 void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB); 764 765 /// Methods for support type inquiry through isa, cast, and dyn_cast: 766 static bool classof(const Value *V) { 767 return V->getValueID() >= Value::InstructionVal; 768 } 769 770 //---------------------------------------------------------------------- 771 // Exported enumerations. 772 // 773 enum TermOps { // These terminate basic blocks 774 #define FIRST_TERM_INST(N) TermOpsBegin = N, 775 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N, 776 #define LAST_TERM_INST(N) TermOpsEnd = N+1 777 #include "llvm/IR/Instruction.def" 778 }; 779 780 enum UnaryOps { 781 #define FIRST_UNARY_INST(N) UnaryOpsBegin = N, 782 #define HANDLE_UNARY_INST(N, OPC, CLASS) OPC = N, 783 #define LAST_UNARY_INST(N) UnaryOpsEnd = N+1 784 #include "llvm/IR/Instruction.def" 785 }; 786 787 enum BinaryOps { 788 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N, 789 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N, 790 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1 791 #include "llvm/IR/Instruction.def" 792 }; 793 794 enum MemoryOps { 795 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N, 796 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N, 797 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1 798 #include "llvm/IR/Instruction.def" 799 }; 800 801 enum CastOps { 802 #define FIRST_CAST_INST(N) CastOpsBegin = N, 803 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N, 804 #define LAST_CAST_INST(N) CastOpsEnd = N+1 805 #include "llvm/IR/Instruction.def" 806 }; 807 808 enum FuncletPadOps { 809 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N, 810 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N, 811 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1 812 #include "llvm/IR/Instruction.def" 813 }; 814 815 enum OtherOps { 816 #define FIRST_OTHER_INST(N) OtherOpsBegin = N, 817 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N, 818 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1 819 #include "llvm/IR/Instruction.def" 820 }; 821 822 private: 823 friend class SymbolTableListTraits<Instruction>; 824 friend class BasicBlock; // For renumbering. 825 826 // Shadow Value::setValueSubclassData with a private forwarding method so that 827 // subclasses cannot accidentally use it. 828 void setValueSubclassData(unsigned short D) { 829 Value::setValueSubclassData(D); 830 } 831 832 unsigned short getSubclassDataFromValue() const { 833 return Value::getSubclassDataFromValue(); 834 } 835 836 void setParent(BasicBlock *P); 837 838 protected: 839 // Instruction subclasses can stick up to 15 bits of stuff into the 840 // SubclassData field of instruction with these members. 841 842 template <typename BitfieldElement> 843 typename BitfieldElement::Type getSubclassData() const { 844 static_assert( 845 std::is_same<BitfieldElement, HasMetadataField>::value || 846 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), 847 "Must not overlap with the metadata bit"); 848 return Bitfield::get<BitfieldElement>(getSubclassDataFromValue()); 849 } 850 851 template <typename BitfieldElement> 852 void setSubclassData(typename BitfieldElement::Type Value) { 853 static_assert( 854 std::is_same<BitfieldElement, HasMetadataField>::value || 855 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), 856 "Must not overlap with the metadata bit"); 857 auto Storage = getSubclassDataFromValue(); 858 Bitfield::set<BitfieldElement>(Storage, Value); 859 setValueSubclassData(Storage); 860 } 861 862 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 863 Instruction *InsertBefore = nullptr); 864 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 865 BasicBlock *InsertAtEnd); 866 867 private: 868 /// Create a copy of this instruction. 869 Instruction *cloneImpl() const; 870 }; 871 872 inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) { 873 V->deleteValue(); 874 } 875 876 } // end namespace llvm 877 878 #endif // LLVM_IR_INSTRUCTION_H 879