1 //===-- Instruction.cpp - Implement the Instruction class -----------------===// 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 implements the Instruction class for the IR library. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/Instruction.h" 15 #include "llvm/IR/CallSite.h" 16 #include "llvm/IR/Constants.h" 17 #include "llvm/IR/Instructions.h" 18 #include "llvm/IR/Module.h" 19 #include "llvm/IR/Operator.h" 20 #include "llvm/IR/Type.h" 21 using namespace llvm; 22 23 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps, 24 Instruction *InsertBefore) 25 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) { 26 27 // If requested, insert this instruction into a basic block... 28 if (InsertBefore) { 29 BasicBlock *BB = InsertBefore->getParent(); 30 assert(BB && "Instruction to insert before is not in a basic block!"); 31 BB->getInstList().insert(InsertBefore->getIterator(), this); 32 } 33 } 34 35 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps, 36 BasicBlock *InsertAtEnd) 37 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) { 38 39 // append this instruction into the basic block 40 assert(InsertAtEnd && "Basic block to append to may not be NULL!"); 41 InsertAtEnd->getInstList().push_back(this); 42 } 43 44 45 // Out of line virtual method, so the vtable, etc has a home. 46 Instruction::~Instruction() { 47 assert(!Parent && "Instruction still linked in the program!"); 48 if (hasMetadataHashEntry()) 49 clearMetadataHashEntries(); 50 } 51 52 53 void Instruction::setParent(BasicBlock *P) { 54 Parent = P; 55 } 56 57 const Module *Instruction::getModule() const { 58 return getParent()->getModule(); 59 } 60 61 Module *Instruction::getModule() { 62 return getParent()->getModule(); 63 } 64 65 66 void Instruction::removeFromParent() { 67 getParent()->getInstList().remove(getIterator()); 68 } 69 70 iplist<Instruction>::iterator Instruction::eraseFromParent() { 71 return getParent()->getInstList().erase(getIterator()); 72 } 73 74 /// insertBefore - Insert an unlinked instructions into a basic block 75 /// immediately before the specified instruction. 76 void Instruction::insertBefore(Instruction *InsertPos) { 77 InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this); 78 } 79 80 /// insertAfter - Insert an unlinked instructions into a basic block 81 /// immediately after the specified instruction. 82 void Instruction::insertAfter(Instruction *InsertPos) { 83 InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(), 84 this); 85 } 86 87 /// moveBefore - Unlink this instruction from its current basic block and 88 /// insert it into the basic block that MovePos lives in, right before 89 /// MovePos. 90 void Instruction::moveBefore(Instruction *MovePos) { 91 MovePos->getParent()->getInstList().splice( 92 MovePos->getIterator(), getParent()->getInstList(), getIterator()); 93 } 94 95 /// Set or clear the unsafe-algebra flag on this instruction, which must be an 96 /// operator which supports this flag. See LangRef.html for the meaning of this 97 /// flag. 98 void Instruction::setHasUnsafeAlgebra(bool B) { 99 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 100 cast<FPMathOperator>(this)->setHasUnsafeAlgebra(B); 101 } 102 103 /// Set or clear the NoNaNs flag on this instruction, which must be an operator 104 /// which supports this flag. See LangRef.html for the meaning of this flag. 105 void Instruction::setHasNoNaNs(bool B) { 106 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 107 cast<FPMathOperator>(this)->setHasNoNaNs(B); 108 } 109 110 /// Set or clear the no-infs flag on this instruction, which must be an operator 111 /// which supports this flag. See LangRef.html for the meaning of this flag. 112 void Instruction::setHasNoInfs(bool B) { 113 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 114 cast<FPMathOperator>(this)->setHasNoInfs(B); 115 } 116 117 /// Set or clear the no-signed-zeros flag on this instruction, which must be an 118 /// operator which supports this flag. See LangRef.html for the meaning of this 119 /// flag. 120 void Instruction::setHasNoSignedZeros(bool B) { 121 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 122 cast<FPMathOperator>(this)->setHasNoSignedZeros(B); 123 } 124 125 /// Set or clear the allow-reciprocal flag on this instruction, which must be an 126 /// operator which supports this flag. See LangRef.html for the meaning of this 127 /// flag. 128 void Instruction::setHasAllowReciprocal(bool B) { 129 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 130 cast<FPMathOperator>(this)->setHasAllowReciprocal(B); 131 } 132 133 /// Convenience function for setting all the fast-math flags on this 134 /// instruction, which must be an operator which supports these flags. See 135 /// LangRef.html for the meaning of these flats. 136 void Instruction::setFastMathFlags(FastMathFlags FMF) { 137 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 138 cast<FPMathOperator>(this)->setFastMathFlags(FMF); 139 } 140 141 void Instruction::copyFastMathFlags(FastMathFlags FMF) { 142 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op"); 143 cast<FPMathOperator>(this)->copyFastMathFlags(FMF); 144 } 145 146 /// Determine whether the unsafe-algebra flag is set. 147 bool Instruction::hasUnsafeAlgebra() const { 148 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 149 return cast<FPMathOperator>(this)->hasUnsafeAlgebra(); 150 } 151 152 /// Determine whether the no-NaNs flag is set. 153 bool Instruction::hasNoNaNs() const { 154 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 155 return cast<FPMathOperator>(this)->hasNoNaNs(); 156 } 157 158 /// Determine whether the no-infs flag is set. 159 bool Instruction::hasNoInfs() const { 160 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 161 return cast<FPMathOperator>(this)->hasNoInfs(); 162 } 163 164 /// Determine whether the no-signed-zeros flag is set. 165 bool Instruction::hasNoSignedZeros() const { 166 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 167 return cast<FPMathOperator>(this)->hasNoSignedZeros(); 168 } 169 170 /// Determine whether the allow-reciprocal flag is set. 171 bool Instruction::hasAllowReciprocal() const { 172 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 173 return cast<FPMathOperator>(this)->hasAllowReciprocal(); 174 } 175 176 /// Convenience function for getting all the fast-math flags, which must be an 177 /// operator which supports these flags. See LangRef.html for the meaning of 178 /// these flags. 179 FastMathFlags Instruction::getFastMathFlags() const { 180 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 181 return cast<FPMathOperator>(this)->getFastMathFlags(); 182 } 183 184 /// Copy I's fast-math flags 185 void Instruction::copyFastMathFlags(const Instruction *I) { 186 copyFastMathFlags(I->getFastMathFlags()); 187 } 188 189 190 const char *Instruction::getOpcodeName(unsigned OpCode) { 191 switch (OpCode) { 192 // Terminators 193 case Ret: return "ret"; 194 case Br: return "br"; 195 case Switch: return "switch"; 196 case IndirectBr: return "indirectbr"; 197 case Invoke: return "invoke"; 198 case Resume: return "resume"; 199 case Unreachable: return "unreachable"; 200 case CleanupEndPad: return "cleanupendpad"; 201 case CleanupRet: return "cleanupret"; 202 case CatchEndPad: return "catchendpad"; 203 case CatchRet: return "catchret"; 204 case CatchPad: return "catchpad"; 205 case TerminatePad: return "terminatepad"; 206 207 // Standard binary operators... 208 case Add: return "add"; 209 case FAdd: return "fadd"; 210 case Sub: return "sub"; 211 case FSub: return "fsub"; 212 case Mul: return "mul"; 213 case FMul: return "fmul"; 214 case UDiv: return "udiv"; 215 case SDiv: return "sdiv"; 216 case FDiv: return "fdiv"; 217 case URem: return "urem"; 218 case SRem: return "srem"; 219 case FRem: return "frem"; 220 221 // Logical operators... 222 case And: return "and"; 223 case Or : return "or"; 224 case Xor: return "xor"; 225 226 // Memory instructions... 227 case Alloca: return "alloca"; 228 case Load: return "load"; 229 case Store: return "store"; 230 case AtomicCmpXchg: return "cmpxchg"; 231 case AtomicRMW: return "atomicrmw"; 232 case Fence: return "fence"; 233 case GetElementPtr: return "getelementptr"; 234 235 // Convert instructions... 236 case Trunc: return "trunc"; 237 case ZExt: return "zext"; 238 case SExt: return "sext"; 239 case FPTrunc: return "fptrunc"; 240 case FPExt: return "fpext"; 241 case FPToUI: return "fptoui"; 242 case FPToSI: return "fptosi"; 243 case UIToFP: return "uitofp"; 244 case SIToFP: return "sitofp"; 245 case IntToPtr: return "inttoptr"; 246 case PtrToInt: return "ptrtoint"; 247 case BitCast: return "bitcast"; 248 case AddrSpaceCast: return "addrspacecast"; 249 250 // Other instructions... 251 case ICmp: return "icmp"; 252 case FCmp: return "fcmp"; 253 case PHI: return "phi"; 254 case Select: return "select"; 255 case Call: return "call"; 256 case Shl: return "shl"; 257 case LShr: return "lshr"; 258 case AShr: return "ashr"; 259 case VAArg: return "va_arg"; 260 case ExtractElement: return "extractelement"; 261 case InsertElement: return "insertelement"; 262 case ShuffleVector: return "shufflevector"; 263 case ExtractValue: return "extractvalue"; 264 case InsertValue: return "insertvalue"; 265 case LandingPad: return "landingpad"; 266 case CleanupPad: return "cleanuppad"; 267 268 default: return "<Invalid operator> "; 269 } 270 } 271 272 /// Return true if both instructions have the same special state 273 /// This must be kept in sync with lib/Transforms/IPO/MergeFunctions.cpp. 274 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2, 275 bool IgnoreAlignment = false) { 276 assert(I1->getOpcode() == I2->getOpcode() && 277 "Can not compare special state of different instructions"); 278 279 if (const LoadInst *LI = dyn_cast<LoadInst>(I1)) 280 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() && 281 (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() || 282 IgnoreAlignment) && 283 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() && 284 LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope(); 285 if (const StoreInst *SI = dyn_cast<StoreInst>(I1)) 286 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() && 287 (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() || 288 IgnoreAlignment) && 289 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() && 290 SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope(); 291 if (const CmpInst *CI = dyn_cast<CmpInst>(I1)) 292 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate(); 293 if (const CallInst *CI = dyn_cast<CallInst>(I1)) 294 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() && 295 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() && 296 CI->getAttributes() == cast<CallInst>(I2)->getAttributes(); 297 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1)) 298 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() && 299 CI->getAttributes() == 300 cast<InvokeInst>(I2)->getAttributes(); 301 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) 302 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices(); 303 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) 304 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices(); 305 if (const FenceInst *FI = dyn_cast<FenceInst>(I1)) 306 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() && 307 FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope(); 308 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1)) 309 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() && 310 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() && 311 CXI->getSuccessOrdering() == 312 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() && 313 CXI->getFailureOrdering() == 314 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() && 315 CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope(); 316 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1)) 317 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() && 318 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() && 319 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() && 320 RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope(); 321 322 return true; 323 } 324 325 /// isIdenticalTo - Return true if the specified instruction is exactly 326 /// identical to the current one. This means that all operands match and any 327 /// extra information (e.g. load is volatile) agree. 328 bool Instruction::isIdenticalTo(const Instruction *I) const { 329 return isIdenticalToWhenDefined(I) && 330 SubclassOptionalData == I->SubclassOptionalData; 331 } 332 333 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it 334 /// ignores the SubclassOptionalData flags, which specify conditions 335 /// under which the instruction's result is undefined. 336 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const { 337 if (getOpcode() != I->getOpcode() || 338 getNumOperands() != I->getNumOperands() || 339 getType() != I->getType()) 340 return false; 341 342 // If both instructions have no operands, they are identical. 343 if (getNumOperands() == 0 && I->getNumOperands() == 0) 344 return haveSameSpecialState(this, I); 345 346 // We have two instructions of identical opcode and #operands. Check to see 347 // if all operands are the same. 348 if (!std::equal(op_begin(), op_end(), I->op_begin())) 349 return false; 350 351 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) { 352 const PHINode *otherPHI = cast<PHINode>(I); 353 return std::equal(thisPHI->block_begin(), thisPHI->block_end(), 354 otherPHI->block_begin()); 355 } 356 357 return haveSameSpecialState(this, I); 358 } 359 360 // isSameOperationAs 361 // This should be kept in sync with isEquivalentOperation in 362 // lib/Transforms/IPO/MergeFunctions.cpp. 363 bool Instruction::isSameOperationAs(const Instruction *I, 364 unsigned flags) const { 365 bool IgnoreAlignment = flags & CompareIgnoringAlignment; 366 bool UseScalarTypes = flags & CompareUsingScalarTypes; 367 368 if (getOpcode() != I->getOpcode() || 369 getNumOperands() != I->getNumOperands() || 370 (UseScalarTypes ? 371 getType()->getScalarType() != I->getType()->getScalarType() : 372 getType() != I->getType())) 373 return false; 374 375 // We have two instructions of identical opcode and #operands. Check to see 376 // if all operands are the same type 377 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 378 if (UseScalarTypes ? 379 getOperand(i)->getType()->getScalarType() != 380 I->getOperand(i)->getType()->getScalarType() : 381 getOperand(i)->getType() != I->getOperand(i)->getType()) 382 return false; 383 384 return haveSameSpecialState(this, I, IgnoreAlignment); 385 } 386 387 /// isUsedOutsideOfBlock - Return true if there are any uses of I outside of the 388 /// specified block. Note that PHI nodes are considered to evaluate their 389 /// operands in the corresponding predecessor block. 390 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const { 391 for (const Use &U : uses()) { 392 // PHI nodes uses values in the corresponding predecessor block. For other 393 // instructions, just check to see whether the parent of the use matches up. 394 const Instruction *I = cast<Instruction>(U.getUser()); 395 const PHINode *PN = dyn_cast<PHINode>(I); 396 if (!PN) { 397 if (I->getParent() != BB) 398 return true; 399 continue; 400 } 401 402 if (PN->getIncomingBlock(U) != BB) 403 return true; 404 } 405 return false; 406 } 407 408 /// mayReadFromMemory - Return true if this instruction may read memory. 409 /// 410 bool Instruction::mayReadFromMemory() const { 411 switch (getOpcode()) { 412 default: return false; 413 case Instruction::VAArg: 414 case Instruction::Load: 415 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory 416 case Instruction::AtomicCmpXchg: 417 case Instruction::AtomicRMW: 418 case Instruction::CatchPad: 419 case Instruction::CatchRet: 420 case Instruction::TerminatePad: 421 return true; 422 case Instruction::Call: 423 return !cast<CallInst>(this)->doesNotAccessMemory(); 424 case Instruction::Invoke: 425 return !cast<InvokeInst>(this)->doesNotAccessMemory(); 426 case Instruction::Store: 427 return !cast<StoreInst>(this)->isUnordered(); 428 } 429 } 430 431 /// mayWriteToMemory - Return true if this instruction may modify memory. 432 /// 433 bool Instruction::mayWriteToMemory() const { 434 switch (getOpcode()) { 435 default: return false; 436 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory 437 case Instruction::Store: 438 case Instruction::VAArg: 439 case Instruction::AtomicCmpXchg: 440 case Instruction::AtomicRMW: 441 case Instruction::CatchPad: 442 case Instruction::CatchRet: 443 case Instruction::TerminatePad: 444 return true; 445 case Instruction::Call: 446 return !cast<CallInst>(this)->onlyReadsMemory(); 447 case Instruction::Invoke: 448 return !cast<InvokeInst>(this)->onlyReadsMemory(); 449 case Instruction::Load: 450 return !cast<LoadInst>(this)->isUnordered(); 451 } 452 } 453 454 bool Instruction::isAtomic() const { 455 switch (getOpcode()) { 456 default: 457 return false; 458 case Instruction::AtomicCmpXchg: 459 case Instruction::AtomicRMW: 460 case Instruction::Fence: 461 return true; 462 case Instruction::Load: 463 return cast<LoadInst>(this)->getOrdering() != NotAtomic; 464 case Instruction::Store: 465 return cast<StoreInst>(this)->getOrdering() != NotAtomic; 466 } 467 } 468 469 bool Instruction::mayThrow() const { 470 if (const CallInst *CI = dyn_cast<CallInst>(this)) 471 return !CI->doesNotThrow(); 472 if (const auto *CRI = dyn_cast<CleanupReturnInst>(this)) 473 return CRI->unwindsToCaller(); 474 if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(this)) 475 return CEPI->unwindsToCaller(); 476 if (const auto *CEPI = dyn_cast<CatchEndPadInst>(this)) 477 return CEPI->unwindsToCaller(); 478 if (const auto *TPI = dyn_cast<TerminatePadInst>(this)) 479 return TPI->unwindsToCaller(); 480 return isa<ResumeInst>(this); 481 } 482 483 bool Instruction::mayReturn() const { 484 if (const CallInst *CI = dyn_cast<CallInst>(this)) 485 return !CI->doesNotReturn(); 486 return true; 487 } 488 489 /// isAssociative - Return true if the instruction is associative: 490 /// 491 /// Associative operators satisfy: x op (y op z) === (x op y) op z 492 /// 493 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative. 494 /// 495 bool Instruction::isAssociative(unsigned Opcode) { 496 return Opcode == And || Opcode == Or || Opcode == Xor || 497 Opcode == Add || Opcode == Mul; 498 } 499 500 bool Instruction::isAssociative() const { 501 unsigned Opcode = getOpcode(); 502 if (isAssociative(Opcode)) 503 return true; 504 505 switch (Opcode) { 506 case FMul: 507 case FAdd: 508 return cast<FPMathOperator>(this)->hasUnsafeAlgebra(); 509 default: 510 return false; 511 } 512 } 513 514 /// isCommutative - Return true if the instruction is commutative: 515 /// 516 /// Commutative operators satisfy: (x op y) === (y op x) 517 /// 518 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when 519 /// applied to any type. 520 /// 521 bool Instruction::isCommutative(unsigned op) { 522 switch (op) { 523 case Add: 524 case FAdd: 525 case Mul: 526 case FMul: 527 case And: 528 case Or: 529 case Xor: 530 return true; 531 default: 532 return false; 533 } 534 } 535 536 /// isIdempotent - Return true if the instruction is idempotent: 537 /// 538 /// Idempotent operators satisfy: x op x === x 539 /// 540 /// In LLVM, the And and Or operators are idempotent. 541 /// 542 bool Instruction::isIdempotent(unsigned Opcode) { 543 return Opcode == And || Opcode == Or; 544 } 545 546 /// isNilpotent - Return true if the instruction is nilpotent: 547 /// 548 /// Nilpotent operators satisfy: x op x === Id, 549 /// 550 /// where Id is the identity for the operator, i.e. a constant such that 551 /// x op Id === x and Id op x === x for all x. 552 /// 553 /// In LLVM, the Xor operator is nilpotent. 554 /// 555 bool Instruction::isNilpotent(unsigned Opcode) { 556 return Opcode == Xor; 557 } 558 559 Instruction *Instruction::cloneImpl() const { 560 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl"); 561 } 562 563 Instruction *Instruction::clone() const { 564 Instruction *New = nullptr; 565 switch (getOpcode()) { 566 default: 567 llvm_unreachable("Unhandled Opcode."); 568 #define HANDLE_INST(num, opc, clas) \ 569 case Instruction::opc: \ 570 New = cast<clas>(this)->cloneImpl(); \ 571 break; 572 #include "llvm/IR/Instruction.def" 573 #undef HANDLE_INST 574 } 575 576 New->SubclassOptionalData = SubclassOptionalData; 577 if (!hasMetadata()) 578 return New; 579 580 // Otherwise, enumerate and copy over metadata from the old instruction to the 581 // new one. 582 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs; 583 getAllMetadataOtherThanDebugLoc(TheMDs); 584 for (const auto &MD : TheMDs) 585 New->setMetadata(MD.first, MD.second); 586 587 New->setDebugLoc(getDebugLoc()); 588 return New; 589 } 590