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