1 //===-- llvm/Instruction.h - Instruction class definition -------*- 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 contains the declaration of the Instruction class, which is the 11 // base class for all of the LLVM instructions. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_IR_INSTRUCTION_H 16 #define LLVM_IR_INSTRUCTION_H 17 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/ilist_node.h" 20 #include "llvm/IR/DebugLoc.h" 21 #include "llvm/IR/SymbolTableListTraits.h" 22 #include "llvm/IR/User.h" 23 24 namespace llvm { 25 26 class FastMathFlags; 27 class LLVMContext; 28 class MDNode; 29 class BasicBlock; 30 struct AAMDNodes; 31 32 template <> 33 struct ilist_traits<Instruction> 34 : public SymbolTableListTraits<Instruction, BasicBlock> { 35 36 /// \brief Return a node that marks the end of a list. 37 /// 38 /// The sentinel is relative to this instance, so we use a non-static 39 /// method. 40 Instruction *createSentinel() const; 41 static void destroySentinel(Instruction *) {} 42 43 Instruction *provideInitialHead() const { return createSentinel(); } 44 Instruction *ensureHead(Instruction *) const { return createSentinel(); } 45 static void noteHead(Instruction *, Instruction *) {} 46 47 private: 48 mutable ilist_half_node<Instruction> Sentinel; 49 }; 50 51 class Instruction : public User, public ilist_node<Instruction> { 52 void operator=(const Instruction &) = delete; 53 Instruction(const Instruction &) = delete; 54 55 BasicBlock *Parent; 56 DebugLoc DbgLoc; // 'dbg' Metadata cache. 57 58 enum { 59 /// HasMetadataBit - This is a bit stored in the SubClassData field which 60 /// indicates whether this instruction has metadata attached to it or not. 61 HasMetadataBit = 1 << 15 62 }; 63 public: 64 // Out of line virtual method, so the vtable, etc has a home. 65 ~Instruction() override; 66 67 /// user_back - Specialize the methods defined in Value, as we know that an 68 /// instruction can only be used by other instructions. 69 Instruction *user_back() { return cast<Instruction>(*user_begin());} 70 const Instruction *user_back() const { return cast<Instruction>(*user_begin());} 71 72 inline const BasicBlock *getParent() const { return Parent; } 73 inline BasicBlock *getParent() { return Parent; } 74 75 /// \brief Return the module owning the function this instruction belongs to 76 /// or nullptr it the function does not have a module. 77 /// 78 /// Note: this is undefined behavior if the instruction does not have a 79 /// parent, or the parent basic block does not have a parent function. 80 const Module *getModule() const; 81 82 /// removeFromParent - This method unlinks 'this' from the containing basic 83 /// block, but does not delete it. 84 /// 85 void removeFromParent(); 86 87 /// eraseFromParent - This method unlinks 'this' from the containing basic 88 /// block and deletes it. 89 /// 90 /// \returns an iterator pointing to the element after the erased one 91 iplist<Instruction>::iterator eraseFromParent(); 92 93 /// insertBefore - Insert an unlinked instructions into a basic block 94 /// immediately before the specified instruction. 95 void insertBefore(Instruction *InsertPos); 96 97 /// insertAfter - Insert an unlinked instructions into a basic block 98 /// immediately after the specified instruction. 99 void insertAfter(Instruction *InsertPos); 100 101 /// moveBefore - Unlink this instruction from its current basic block and 102 /// insert it into the basic block that MovePos lives in, right before 103 /// MovePos. 104 void moveBefore(Instruction *MovePos); 105 106 //===--------------------------------------------------------------------===// 107 // Subclass classification. 108 //===--------------------------------------------------------------------===// 109 110 /// getOpcode() returns a member of one of the enums like Instruction::Add. 111 unsigned getOpcode() const { return getValueID() - InstructionVal; } 112 113 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); } 114 bool isTerminator() const { return isTerminator(getOpcode()); } 115 bool isBinaryOp() const { return isBinaryOp(getOpcode()); } 116 bool isShift() { return isShift(getOpcode()); } 117 bool isCast() const { return isCast(getOpcode()); } 118 119 static const char* getOpcodeName(unsigned OpCode); 120 121 static inline bool isTerminator(unsigned OpCode) { 122 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd; 123 } 124 125 static inline bool isBinaryOp(unsigned Opcode) { 126 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd; 127 } 128 129 /// @brief Determine if the Opcode is one of the shift instructions. 130 static inline bool isShift(unsigned Opcode) { 131 return Opcode >= Shl && Opcode <= AShr; 132 } 133 134 /// isLogicalShift - Return true if this is a logical shift left or a logical 135 /// shift right. 136 inline bool isLogicalShift() const { 137 return getOpcode() == Shl || getOpcode() == LShr; 138 } 139 140 /// isArithmeticShift - Return true if this is an arithmetic shift right. 141 inline bool isArithmeticShift() const { 142 return getOpcode() == AShr; 143 } 144 145 /// @brief Determine if the OpCode is one of the CastInst instructions. 146 static inline bool isCast(unsigned OpCode) { 147 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd; 148 } 149 150 //===--------------------------------------------------------------------===// 151 // Metadata manipulation. 152 //===--------------------------------------------------------------------===// 153 154 /// hasMetadata() - Return true if this instruction has any metadata attached 155 /// to it. 156 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); } 157 158 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has 159 /// metadata attached to it other than a debug location. 160 bool hasMetadataOtherThanDebugLoc() const { 161 return hasMetadataHashEntry(); 162 } 163 164 /// getMetadata - Get the metadata of given kind attached to this Instruction. 165 /// If the metadata is not found then return null. 166 MDNode *getMetadata(unsigned KindID) const { 167 if (!hasMetadata()) return nullptr; 168 return getMetadataImpl(KindID); 169 } 170 171 /// getMetadata - Get the metadata of given kind attached to this Instruction. 172 /// If the metadata is not found then return null. 173 MDNode *getMetadata(StringRef Kind) const { 174 if (!hasMetadata()) return nullptr; 175 return getMetadataImpl(Kind); 176 } 177 178 /// getAllMetadata - Get all metadata attached to this Instruction. The first 179 /// element of each pair returned is the KindID, the second element is the 180 /// metadata value. This list is returned sorted by the KindID. 181 void 182 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 183 if (hasMetadata()) 184 getAllMetadataImpl(MDs); 185 } 186 187 /// getAllMetadataOtherThanDebugLoc - This does the same thing as 188 /// getAllMetadata, except that it filters out the debug location. 189 void getAllMetadataOtherThanDebugLoc( 190 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 191 if (hasMetadataOtherThanDebugLoc()) 192 getAllMetadataOtherThanDebugLocImpl(MDs); 193 } 194 195 /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from 196 /// this instruction. When Merge is true, the existing AA metadata is 197 /// merged with that from this instruction providing the most-general result. 198 void getAAMetadata(AAMDNodes &N, bool Merge = false) const; 199 200 /// setMetadata - Set the metadata of the specified kind to the specified 201 /// node. This updates/replaces metadata if already present, or removes it if 202 /// Node is null. 203 void setMetadata(unsigned KindID, MDNode *Node); 204 void setMetadata(StringRef Kind, MDNode *Node); 205 206 /// \brief Drop unknown metadata. 207 /// Passes are required to drop metadata they don't understand. This is a 208 /// convenience method for passes to do so. 209 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs); 210 void dropUnknownMetadata() { 211 return dropUnknownMetadata(None); 212 } 213 void dropUnknownMetadata(unsigned ID1) { 214 return dropUnknownMetadata(makeArrayRef(ID1)); 215 } 216 void dropUnknownMetadata(unsigned ID1, unsigned ID2) { 217 unsigned IDs[] = {ID1, ID2}; 218 return dropUnknownMetadata(IDs); 219 } 220 221 /// setAAMetadata - Sets the metadata on this instruction from the 222 /// AAMDNodes structure. 223 void setAAMetadata(const AAMDNodes &N); 224 225 /// setDebugLoc - Set the debug location information for this instruction. 226 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); } 227 228 /// getDebugLoc - Return the debug location for this node as a DebugLoc. 229 const DebugLoc &getDebugLoc() const { return DbgLoc; } 230 231 /// Set or clear the unsafe-algebra flag on this instruction, which must be an 232 /// operator which supports this flag. See LangRef.html for the meaning of 233 /// this flag. 234 void setHasUnsafeAlgebra(bool B); 235 236 /// Set or clear the no-nans flag on this instruction, which must be an 237 /// operator which supports this flag. See LangRef.html for the meaning of 238 /// this flag. 239 void setHasNoNaNs(bool B); 240 241 /// Set or clear the no-infs flag on this instruction, which must be an 242 /// operator which supports this flag. See LangRef.html for the meaning of 243 /// this flag. 244 void setHasNoInfs(bool B); 245 246 /// Set or clear the no-signed-zeros flag on this instruction, which must be 247 /// an operator which supports this flag. See LangRef.html for the meaning of 248 /// this flag. 249 void setHasNoSignedZeros(bool B); 250 251 /// Set or clear the allow-reciprocal flag on this instruction, which must be 252 /// an operator which supports this flag. See LangRef.html for the meaning of 253 /// this flag. 254 void setHasAllowReciprocal(bool B); 255 256 /// Convenience function for setting multiple fast-math flags on this 257 /// instruction, which must be an operator which supports these flags. See 258 /// LangRef.html for the meaning of these flags. 259 void setFastMathFlags(FastMathFlags FMF); 260 261 /// Convenience function for transferring all fast-math flag values to this 262 /// instruction, which must be an operator which supports these flags. See 263 /// LangRef.html for the meaning of these flags. 264 void copyFastMathFlags(FastMathFlags FMF); 265 266 /// Determine whether the unsafe-algebra flag is set. 267 bool hasUnsafeAlgebra() const; 268 269 /// Determine whether the no-NaNs flag is set. 270 bool hasNoNaNs() const; 271 272 /// Determine whether the no-infs flag is set. 273 bool hasNoInfs() const; 274 275 /// Determine whether the no-signed-zeros flag is set. 276 bool hasNoSignedZeros() const; 277 278 /// Determine whether the allow-reciprocal flag is set. 279 bool hasAllowReciprocal() const; 280 281 /// Convenience function for getting all the fast-math flags, which must be an 282 /// operator which supports these flags. See LangRef.html for the meaning of 283 /// these flags. 284 FastMathFlags getFastMathFlags() const; 285 286 /// Copy I's fast-math flags 287 void copyFastMathFlags(const Instruction *I); 288 289 private: 290 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side 291 /// metadata hash. 292 bool hasMetadataHashEntry() const { 293 return (getSubclassDataFromValue() & HasMetadataBit) != 0; 294 } 295 296 // These are all implemented in Metadata.cpp. 297 MDNode *getMetadataImpl(unsigned KindID) const; 298 MDNode *getMetadataImpl(StringRef Kind) const; 299 void 300 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const; 301 void getAllMetadataOtherThanDebugLocImpl( 302 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const; 303 void clearMetadataHashEntries(); 304 public: 305 //===--------------------------------------------------------------------===// 306 // Predicates and helper methods. 307 //===--------------------------------------------------------------------===// 308 309 310 /// isAssociative - Return true if the instruction is associative: 311 /// 312 /// Associative operators satisfy: x op (y op z) === (x op y) op z 313 /// 314 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative. 315 /// 316 bool isAssociative() const; 317 static bool isAssociative(unsigned op); 318 319 /// isCommutative - Return true if the instruction is commutative: 320 /// 321 /// Commutative operators satisfy: (x op y) === (y op x) 322 /// 323 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when 324 /// applied to any type. 325 /// 326 bool isCommutative() const { return isCommutative(getOpcode()); } 327 static bool isCommutative(unsigned op); 328 329 /// isIdempotent - Return true if the instruction is idempotent: 330 /// 331 /// Idempotent operators satisfy: x op x === x 332 /// 333 /// In LLVM, the And and Or operators are idempotent. 334 /// 335 bool isIdempotent() const { return isIdempotent(getOpcode()); } 336 static bool isIdempotent(unsigned op); 337 338 /// isNilpotent - Return true if the instruction is nilpotent: 339 /// 340 /// Nilpotent operators satisfy: x op x === Id, 341 /// 342 /// where Id is the identity for the operator, i.e. a constant such that 343 /// x op Id === x and Id op x === x for all x. 344 /// 345 /// In LLVM, the Xor operator is nilpotent. 346 /// 347 bool isNilpotent() const { return isNilpotent(getOpcode()); } 348 static bool isNilpotent(unsigned op); 349 350 /// mayWriteToMemory - Return true if this instruction may modify memory. 351 /// 352 bool mayWriteToMemory() const; 353 354 /// mayReadFromMemory - Return true if this instruction may read memory. 355 /// 356 bool mayReadFromMemory() const; 357 358 /// mayReadOrWriteMemory - Return true if this instruction may read or 359 /// write memory. 360 /// 361 bool mayReadOrWriteMemory() const { 362 return mayReadFromMemory() || mayWriteToMemory(); 363 } 364 365 /// isAtomic - Return true if this instruction has an 366 /// AtomicOrdering of unordered or higher. 367 /// 368 bool isAtomic() const; 369 370 /// mayThrow - Return true if this instruction may throw an exception. 371 /// 372 bool mayThrow() const; 373 374 /// mayReturn - Return true if this is a function that may return. 375 /// this is true for all normal instructions. The only exception 376 /// is functions that are marked with the 'noreturn' attribute. 377 /// 378 bool mayReturn() const; 379 380 /// mayHaveSideEffects - Return true if the instruction may have side effects. 381 /// 382 /// Note that this does not consider malloc and alloca to have side 383 /// effects because the newly allocated memory is completely invisible to 384 /// instructions which don't used the returned value. For cases where this 385 /// matters, isSafeToSpeculativelyExecute may be more appropriate. 386 bool mayHaveSideEffects() const { 387 return mayWriteToMemory() || mayThrow() || !mayReturn(); 388 } 389 390 /// clone() - Create a copy of 'this' instruction that is identical in all 391 /// ways except the following: 392 /// * The instruction has no parent 393 /// * The instruction has no name 394 /// 395 Instruction *clone() const; 396 397 /// isIdenticalTo - Return true if the specified instruction is exactly 398 /// identical to the current one. This means that all operands match and any 399 /// extra information (e.g. load is volatile) agree. 400 bool isIdenticalTo(const Instruction *I) const; 401 402 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it 403 /// ignores the SubclassOptionalData flags, which specify conditions 404 /// under which the instruction's result is undefined. 405 bool isIdenticalToWhenDefined(const Instruction *I) const; 406 407 /// When checking for operation equivalence (using isSameOperationAs) it is 408 /// sometimes useful to ignore certain attributes. 409 enum OperationEquivalenceFlags { 410 /// Check for equivalence ignoring load/store alignment. 411 CompareIgnoringAlignment = 1<<0, 412 /// Check for equivalence treating a type and a vector of that type 413 /// as equivalent. 414 CompareUsingScalarTypes = 1<<1 415 }; 416 417 /// This function determines if the specified instruction executes the same 418 /// operation as the current one. This means that the opcodes, type, operand 419 /// types and any other factors affecting the operation must be the same. This 420 /// is similar to isIdenticalTo except the operands themselves don't have to 421 /// be identical. 422 /// @returns true if the specified instruction is the same operation as 423 /// the current one. 424 /// @brief Determine if one instruction is the same operation as another. 425 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const; 426 427 /// isUsedOutsideOfBlock - Return true if there are any uses of this 428 /// instruction in blocks other than the specified block. Note that PHI nodes 429 /// are considered to evaluate their operands in the corresponding predecessor 430 /// block. 431 bool isUsedOutsideOfBlock(const BasicBlock *BB) const; 432 433 434 /// Methods for support type inquiry through isa, cast, and dyn_cast: 435 static inline bool classof(const Value *V) { 436 return V->getValueID() >= Value::InstructionVal; 437 } 438 439 //---------------------------------------------------------------------- 440 // Exported enumerations. 441 // 442 enum TermOps { // These terminate basic blocks 443 #define FIRST_TERM_INST(N) TermOpsBegin = N, 444 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N, 445 #define LAST_TERM_INST(N) TermOpsEnd = N+1 446 #include "llvm/IR/Instruction.def" 447 }; 448 449 enum BinaryOps { 450 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N, 451 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N, 452 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1 453 #include "llvm/IR/Instruction.def" 454 }; 455 456 enum MemoryOps { 457 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N, 458 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N, 459 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1 460 #include "llvm/IR/Instruction.def" 461 }; 462 463 enum CastOps { 464 #define FIRST_CAST_INST(N) CastOpsBegin = N, 465 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N, 466 #define LAST_CAST_INST(N) CastOpsEnd = N+1 467 #include "llvm/IR/Instruction.def" 468 }; 469 470 enum OtherOps { 471 #define FIRST_OTHER_INST(N) OtherOpsBegin = N, 472 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N, 473 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1 474 #include "llvm/IR/Instruction.def" 475 }; 476 private: 477 // Shadow Value::setValueSubclassData with a private forwarding method so that 478 // subclasses cannot accidentally use it. 479 void setValueSubclassData(unsigned short D) { 480 Value::setValueSubclassData(D); 481 } 482 unsigned short getSubclassDataFromValue() const { 483 return Value::getSubclassDataFromValue(); 484 } 485 486 void setHasMetadataHashEntry(bool V) { 487 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) | 488 (V ? HasMetadataBit : 0)); 489 } 490 491 friend class SymbolTableListTraits<Instruction, BasicBlock>; 492 void setParent(BasicBlock *P); 493 protected: 494 // Instruction subclasses can stick up to 15 bits of stuff into the 495 // SubclassData field of instruction with these members. 496 497 // Verify that only the low 15 bits are used. 498 void setInstructionSubclassData(unsigned short D) { 499 assert((D & HasMetadataBit) == 0 && "Out of range value put into field"); 500 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D); 501 } 502 503 unsigned getSubclassDataFromInstruction() const { 504 return getSubclassDataFromValue() & ~HasMetadataBit; 505 } 506 507 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 508 Instruction *InsertBefore = nullptr); 509 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 510 BasicBlock *InsertAtEnd); 511 virtual Instruction *clone_impl() const = 0; 512 513 }; 514 515 inline Instruction *ilist_traits<Instruction>::createSentinel() const { 516 // Since i(p)lists always publicly derive from their corresponding traits, 517 // placing a data member in this class will augment the i(p)list. But since 518 // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>, 519 // there is a legal viable downcast from it to NodeTy. We use this trick to 520 // superimpose an i(p)list with a "ghostly" NodeTy, which becomes the 521 // sentinel. Dereferencing the sentinel is forbidden (save the 522 // ilist_node<NodeTy>), so no one will ever notice the superposition. 523 return static_cast<Instruction *>(&Sentinel); 524 } 525 526 // Instruction* is only 4-byte aligned. 527 template<> 528 class PointerLikeTypeTraits<Instruction*> { 529 typedef Instruction* PT; 530 public: 531 static inline void *getAsVoidPointer(PT P) { return P; } 532 static inline PT getFromVoidPointer(void *P) { 533 return static_cast<PT>(P); 534 } 535 enum { NumLowBitsAvailable = 2 }; 536 }; 537 538 } // End llvm namespace 539 540 #endif 541