1 //===-- Instruction.cpp - Implement the Instruction class -----------------===// 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 implements the Instruction class for the IR library. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/Instruction.h" 14 #include "llvm/IR/IntrinsicInst.h" 15 #include "llvm/ADT/DenseSet.h" 16 #include "llvm/IR/Constants.h" 17 #include "llvm/IR/Instructions.h" 18 #include "llvm/IR/MDBuilder.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 Instruction::~Instruction() { 45 assert(!Parent && "Instruction still linked in the program!"); 46 47 // Replace any extant metadata uses of this instruction with undef to 48 // preserve debug info accuracy. Some alternatives include: 49 // - Treat Instruction like any other Value, and point its extant metadata 50 // uses to an empty ValueAsMetadata node. This makes extant dbg.value uses 51 // trivially dead (i.e. fair game for deletion in many passes), leading to 52 // stale dbg.values being in effect for too long. 53 // - Call salvageDebugInfoOrMarkUndef. Not needed to make instruction removal 54 // correct. OTOH results in wasted work in some common cases (e.g. when all 55 // instructions in a BasicBlock are deleted). 56 if (isUsedByMetadata()) 57 ValueAsMetadata::handleRAUW(this, UndefValue::get(getType())); 58 } 59 60 61 void Instruction::setParent(BasicBlock *P) { 62 Parent = P; 63 } 64 65 const Module *Instruction::getModule() const { 66 return getParent()->getModule(); 67 } 68 69 const Function *Instruction::getFunction() const { 70 return getParent()->getParent(); 71 } 72 73 void Instruction::removeFromParent() { 74 getParent()->getInstList().remove(getIterator()); 75 } 76 77 iplist<Instruction>::iterator Instruction::eraseFromParent() { 78 return getParent()->getInstList().erase(getIterator()); 79 } 80 81 /// Insert an unlinked instruction into a basic block immediately before the 82 /// specified instruction. 83 void Instruction::insertBefore(Instruction *InsertPos) { 84 InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this); 85 } 86 87 /// Insert an unlinked instruction into a basic block immediately after the 88 /// specified instruction. 89 void Instruction::insertAfter(Instruction *InsertPos) { 90 InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(), 91 this); 92 } 93 94 /// Unlink this instruction from its current basic block and insert it into the 95 /// basic block that MovePos lives in, right before MovePos. 96 void Instruction::moveBefore(Instruction *MovePos) { 97 moveBefore(*MovePos->getParent(), MovePos->getIterator()); 98 } 99 100 void Instruction::moveAfter(Instruction *MovePos) { 101 moveBefore(*MovePos->getParent(), ++MovePos->getIterator()); 102 } 103 104 void Instruction::moveBefore(BasicBlock &BB, 105 SymbolTableList<Instruction>::iterator I) { 106 assert(I == BB.end() || I->getParent() == &BB); 107 BB.getInstList().splice(I, getParent()->getInstList(), getIterator()); 108 } 109 110 bool Instruction::comesBefore(const Instruction *Other) const { 111 assert(Parent && Other->Parent && 112 "instructions without BB parents have no order"); 113 assert(Parent == Other->Parent && "cross-BB instruction order comparison"); 114 if (!Parent->isInstrOrderValid()) 115 Parent->renumberInstructions(); 116 return Order < Other->Order; 117 } 118 119 void Instruction::setHasNoUnsignedWrap(bool b) { 120 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b); 121 } 122 123 void Instruction::setHasNoSignedWrap(bool b) { 124 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b); 125 } 126 127 void Instruction::setIsExact(bool b) { 128 cast<PossiblyExactOperator>(this)->setIsExact(b); 129 } 130 131 bool Instruction::hasNoUnsignedWrap() const { 132 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap(); 133 } 134 135 bool Instruction::hasNoSignedWrap() const { 136 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap(); 137 } 138 139 void Instruction::dropPoisonGeneratingFlags() { 140 switch (getOpcode()) { 141 case Instruction::Add: 142 case Instruction::Sub: 143 case Instruction::Mul: 144 case Instruction::Shl: 145 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false); 146 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false); 147 break; 148 149 case Instruction::UDiv: 150 case Instruction::SDiv: 151 case Instruction::AShr: 152 case Instruction::LShr: 153 cast<PossiblyExactOperator>(this)->setIsExact(false); 154 break; 155 156 case Instruction::GetElementPtr: 157 cast<GetElementPtrInst>(this)->setIsInBounds(false); 158 break; 159 } 160 // TODO: FastMathFlags! 161 } 162 163 164 bool Instruction::isExact() const { 165 return cast<PossiblyExactOperator>(this)->isExact(); 166 } 167 168 void Instruction::setFast(bool B) { 169 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 170 cast<FPMathOperator>(this)->setFast(B); 171 } 172 173 void Instruction::setHasAllowReassoc(bool B) { 174 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 175 cast<FPMathOperator>(this)->setHasAllowReassoc(B); 176 } 177 178 void Instruction::setHasNoNaNs(bool B) { 179 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 180 cast<FPMathOperator>(this)->setHasNoNaNs(B); 181 } 182 183 void Instruction::setHasNoInfs(bool B) { 184 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 185 cast<FPMathOperator>(this)->setHasNoInfs(B); 186 } 187 188 void Instruction::setHasNoSignedZeros(bool B) { 189 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 190 cast<FPMathOperator>(this)->setHasNoSignedZeros(B); 191 } 192 193 void Instruction::setHasAllowReciprocal(bool B) { 194 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 195 cast<FPMathOperator>(this)->setHasAllowReciprocal(B); 196 } 197 198 void Instruction::setHasAllowContract(bool B) { 199 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 200 cast<FPMathOperator>(this)->setHasAllowContract(B); 201 } 202 203 void Instruction::setHasApproxFunc(bool B) { 204 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 205 cast<FPMathOperator>(this)->setHasApproxFunc(B); 206 } 207 208 void Instruction::setFastMathFlags(FastMathFlags FMF) { 209 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 210 cast<FPMathOperator>(this)->setFastMathFlags(FMF); 211 } 212 213 void Instruction::copyFastMathFlags(FastMathFlags FMF) { 214 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op"); 215 cast<FPMathOperator>(this)->copyFastMathFlags(FMF); 216 } 217 218 bool Instruction::isFast() const { 219 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 220 return cast<FPMathOperator>(this)->isFast(); 221 } 222 223 bool Instruction::hasAllowReassoc() const { 224 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 225 return cast<FPMathOperator>(this)->hasAllowReassoc(); 226 } 227 228 bool Instruction::hasNoNaNs() const { 229 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 230 return cast<FPMathOperator>(this)->hasNoNaNs(); 231 } 232 233 bool Instruction::hasNoInfs() const { 234 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 235 return cast<FPMathOperator>(this)->hasNoInfs(); 236 } 237 238 bool Instruction::hasNoSignedZeros() const { 239 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 240 return cast<FPMathOperator>(this)->hasNoSignedZeros(); 241 } 242 243 bool Instruction::hasAllowReciprocal() const { 244 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 245 return cast<FPMathOperator>(this)->hasAllowReciprocal(); 246 } 247 248 bool Instruction::hasAllowContract() const { 249 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 250 return cast<FPMathOperator>(this)->hasAllowContract(); 251 } 252 253 bool Instruction::hasApproxFunc() const { 254 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 255 return cast<FPMathOperator>(this)->hasApproxFunc(); 256 } 257 258 FastMathFlags Instruction::getFastMathFlags() const { 259 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 260 return cast<FPMathOperator>(this)->getFastMathFlags(); 261 } 262 263 void Instruction::copyFastMathFlags(const Instruction *I) { 264 copyFastMathFlags(I->getFastMathFlags()); 265 } 266 267 void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) { 268 // Copy the wrapping flags. 269 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) { 270 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) { 271 setHasNoSignedWrap(OB->hasNoSignedWrap()); 272 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap()); 273 } 274 } 275 276 // Copy the exact flag. 277 if (auto *PE = dyn_cast<PossiblyExactOperator>(V)) 278 if (isa<PossiblyExactOperator>(this)) 279 setIsExact(PE->isExact()); 280 281 // Copy the fast-math flags. 282 if (auto *FP = dyn_cast<FPMathOperator>(V)) 283 if (isa<FPMathOperator>(this)) 284 copyFastMathFlags(FP->getFastMathFlags()); 285 286 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V)) 287 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this)) 288 DestGEP->setIsInBounds(SrcGEP->isInBounds() | DestGEP->isInBounds()); 289 } 290 291 void Instruction::andIRFlags(const Value *V) { 292 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) { 293 if (isa<OverflowingBinaryOperator>(this)) { 294 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap()); 295 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap()); 296 } 297 } 298 299 if (auto *PE = dyn_cast<PossiblyExactOperator>(V)) 300 if (isa<PossiblyExactOperator>(this)) 301 setIsExact(isExact() & PE->isExact()); 302 303 if (auto *FP = dyn_cast<FPMathOperator>(V)) { 304 if (isa<FPMathOperator>(this)) { 305 FastMathFlags FM = getFastMathFlags(); 306 FM &= FP->getFastMathFlags(); 307 copyFastMathFlags(FM); 308 } 309 } 310 311 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V)) 312 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this)) 313 DestGEP->setIsInBounds(SrcGEP->isInBounds() & DestGEP->isInBounds()); 314 } 315 316 const char *Instruction::getOpcodeName(unsigned OpCode) { 317 switch (OpCode) { 318 // Terminators 319 case Ret: return "ret"; 320 case Br: return "br"; 321 case Switch: return "switch"; 322 case IndirectBr: return "indirectbr"; 323 case Invoke: return "invoke"; 324 case Resume: return "resume"; 325 case Unreachable: return "unreachable"; 326 case CleanupRet: return "cleanupret"; 327 case CatchRet: return "catchret"; 328 case CatchPad: return "catchpad"; 329 case CatchSwitch: return "catchswitch"; 330 case CallBr: return "callbr"; 331 332 // Standard unary operators... 333 case FNeg: return "fneg"; 334 335 // Standard binary operators... 336 case Add: return "add"; 337 case FAdd: return "fadd"; 338 case Sub: return "sub"; 339 case FSub: return "fsub"; 340 case Mul: return "mul"; 341 case FMul: return "fmul"; 342 case UDiv: return "udiv"; 343 case SDiv: return "sdiv"; 344 case FDiv: return "fdiv"; 345 case URem: return "urem"; 346 case SRem: return "srem"; 347 case FRem: return "frem"; 348 349 // Logical operators... 350 case And: return "and"; 351 case Or : return "or"; 352 case Xor: return "xor"; 353 354 // Memory instructions... 355 case Alloca: return "alloca"; 356 case Load: return "load"; 357 case Store: return "store"; 358 case AtomicCmpXchg: return "cmpxchg"; 359 case AtomicRMW: return "atomicrmw"; 360 case Fence: return "fence"; 361 case GetElementPtr: return "getelementptr"; 362 363 // Convert instructions... 364 case Trunc: return "trunc"; 365 case ZExt: return "zext"; 366 case SExt: return "sext"; 367 case FPTrunc: return "fptrunc"; 368 case FPExt: return "fpext"; 369 case FPToUI: return "fptoui"; 370 case FPToSI: return "fptosi"; 371 case UIToFP: return "uitofp"; 372 case SIToFP: return "sitofp"; 373 case IntToPtr: return "inttoptr"; 374 case PtrToInt: return "ptrtoint"; 375 case BitCast: return "bitcast"; 376 case AddrSpaceCast: return "addrspacecast"; 377 378 // Other instructions... 379 case ICmp: return "icmp"; 380 case FCmp: return "fcmp"; 381 case PHI: return "phi"; 382 case Select: return "select"; 383 case Call: return "call"; 384 case Shl: return "shl"; 385 case LShr: return "lshr"; 386 case AShr: return "ashr"; 387 case VAArg: return "va_arg"; 388 case ExtractElement: return "extractelement"; 389 case InsertElement: return "insertelement"; 390 case ShuffleVector: return "shufflevector"; 391 case ExtractValue: return "extractvalue"; 392 case InsertValue: return "insertvalue"; 393 case LandingPad: return "landingpad"; 394 case CleanupPad: return "cleanuppad"; 395 case Freeze: return "freeze"; 396 397 default: return "<Invalid operator> "; 398 } 399 } 400 401 /// Return true if both instructions have the same special state. This must be 402 /// kept in sync with FunctionComparator::cmpOperations in 403 /// lib/Transforms/IPO/MergeFunctions.cpp. 404 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2, 405 bool IgnoreAlignment = false) { 406 assert(I1->getOpcode() == I2->getOpcode() && 407 "Can not compare special state of different instructions"); 408 409 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1)) 410 return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() && 411 (AI->getAlignment() == cast<AllocaInst>(I2)->getAlignment() || 412 IgnoreAlignment); 413 if (const LoadInst *LI = dyn_cast<LoadInst>(I1)) 414 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() && 415 (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() || 416 IgnoreAlignment) && 417 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() && 418 LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID(); 419 if (const StoreInst *SI = dyn_cast<StoreInst>(I1)) 420 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() && 421 (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() || 422 IgnoreAlignment) && 423 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() && 424 SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID(); 425 if (const CmpInst *CI = dyn_cast<CmpInst>(I1)) 426 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate(); 427 if (const CallInst *CI = dyn_cast<CallInst>(I1)) 428 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() && 429 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() && 430 CI->getAttributes() == cast<CallInst>(I2)->getAttributes() && 431 CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2)); 432 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1)) 433 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() && 434 CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes() && 435 CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2)); 436 if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1)) 437 return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() && 438 CI->getAttributes() == cast<CallBrInst>(I2)->getAttributes() && 439 CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2)); 440 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) 441 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices(); 442 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) 443 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices(); 444 if (const FenceInst *FI = dyn_cast<FenceInst>(I1)) 445 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() && 446 FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID(); 447 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1)) 448 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() && 449 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() && 450 CXI->getSuccessOrdering() == 451 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() && 452 CXI->getFailureOrdering() == 453 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() && 454 CXI->getSyncScopeID() == 455 cast<AtomicCmpXchgInst>(I2)->getSyncScopeID(); 456 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1)) 457 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() && 458 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() && 459 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() && 460 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID(); 461 if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I1)) 462 return SVI->getShuffleMask() == 463 cast<ShuffleVectorInst>(I2)->getShuffleMask(); 464 465 return true; 466 } 467 468 bool Instruction::isIdenticalTo(const Instruction *I) const { 469 return isIdenticalToWhenDefined(I) && 470 SubclassOptionalData == I->SubclassOptionalData; 471 } 472 473 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const { 474 if (getOpcode() != I->getOpcode() || 475 getNumOperands() != I->getNumOperands() || 476 getType() != I->getType()) 477 return false; 478 479 // If both instructions have no operands, they are identical. 480 if (getNumOperands() == 0 && I->getNumOperands() == 0) 481 return haveSameSpecialState(this, I); 482 483 // We have two instructions of identical opcode and #operands. Check to see 484 // if all operands are the same. 485 if (!std::equal(op_begin(), op_end(), I->op_begin())) 486 return false; 487 488 // WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()! 489 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) { 490 const PHINode *otherPHI = cast<PHINode>(I); 491 return std::equal(thisPHI->block_begin(), thisPHI->block_end(), 492 otherPHI->block_begin()); 493 } 494 495 return haveSameSpecialState(this, I); 496 } 497 498 // Keep this in sync with FunctionComparator::cmpOperations in 499 // lib/Transforms/IPO/MergeFunctions.cpp. 500 bool Instruction::isSameOperationAs(const Instruction *I, 501 unsigned flags) const { 502 bool IgnoreAlignment = flags & CompareIgnoringAlignment; 503 bool UseScalarTypes = flags & CompareUsingScalarTypes; 504 505 if (getOpcode() != I->getOpcode() || 506 getNumOperands() != I->getNumOperands() || 507 (UseScalarTypes ? 508 getType()->getScalarType() != I->getType()->getScalarType() : 509 getType() != I->getType())) 510 return false; 511 512 // We have two instructions of identical opcode and #operands. Check to see 513 // if all operands are the same type 514 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 515 if (UseScalarTypes ? 516 getOperand(i)->getType()->getScalarType() != 517 I->getOperand(i)->getType()->getScalarType() : 518 getOperand(i)->getType() != I->getOperand(i)->getType()) 519 return false; 520 521 return haveSameSpecialState(this, I, IgnoreAlignment); 522 } 523 524 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const { 525 for (const Use &U : uses()) { 526 // PHI nodes uses values in the corresponding predecessor block. For other 527 // instructions, just check to see whether the parent of the use matches up. 528 const Instruction *I = cast<Instruction>(U.getUser()); 529 const PHINode *PN = dyn_cast<PHINode>(I); 530 if (!PN) { 531 if (I->getParent() != BB) 532 return true; 533 continue; 534 } 535 536 if (PN->getIncomingBlock(U) != BB) 537 return true; 538 } 539 return false; 540 } 541 542 bool Instruction::mayReadFromMemory() const { 543 switch (getOpcode()) { 544 default: return false; 545 case Instruction::VAArg: 546 case Instruction::Load: 547 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory 548 case Instruction::AtomicCmpXchg: 549 case Instruction::AtomicRMW: 550 case Instruction::CatchPad: 551 case Instruction::CatchRet: 552 return true; 553 case Instruction::Call: 554 case Instruction::Invoke: 555 case Instruction::CallBr: 556 return !cast<CallBase>(this)->doesNotReadMemory(); 557 case Instruction::Store: 558 return !cast<StoreInst>(this)->isUnordered(); 559 } 560 } 561 562 bool Instruction::mayWriteToMemory() const { 563 switch (getOpcode()) { 564 default: return false; 565 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory 566 case Instruction::Store: 567 case Instruction::VAArg: 568 case Instruction::AtomicCmpXchg: 569 case Instruction::AtomicRMW: 570 case Instruction::CatchPad: 571 case Instruction::CatchRet: 572 return true; 573 case Instruction::Call: 574 case Instruction::Invoke: 575 case Instruction::CallBr: 576 return !cast<CallBase>(this)->onlyReadsMemory(); 577 case Instruction::Load: 578 return !cast<LoadInst>(this)->isUnordered(); 579 } 580 } 581 582 bool Instruction::isAtomic() const { 583 switch (getOpcode()) { 584 default: 585 return false; 586 case Instruction::AtomicCmpXchg: 587 case Instruction::AtomicRMW: 588 case Instruction::Fence: 589 return true; 590 case Instruction::Load: 591 return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic; 592 case Instruction::Store: 593 return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic; 594 } 595 } 596 597 bool Instruction::hasAtomicLoad() const { 598 assert(isAtomic()); 599 switch (getOpcode()) { 600 default: 601 return false; 602 case Instruction::AtomicCmpXchg: 603 case Instruction::AtomicRMW: 604 case Instruction::Load: 605 return true; 606 } 607 } 608 609 bool Instruction::hasAtomicStore() const { 610 assert(isAtomic()); 611 switch (getOpcode()) { 612 default: 613 return false; 614 case Instruction::AtomicCmpXchg: 615 case Instruction::AtomicRMW: 616 case Instruction::Store: 617 return true; 618 } 619 } 620 621 bool Instruction::mayThrow() const { 622 if (const CallInst *CI = dyn_cast<CallInst>(this)) 623 return !CI->doesNotThrow(); 624 if (const auto *CRI = dyn_cast<CleanupReturnInst>(this)) 625 return CRI->unwindsToCaller(); 626 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(this)) 627 return CatchSwitch->unwindsToCaller(); 628 return isa<ResumeInst>(this); 629 } 630 631 bool Instruction::isSafeToRemove() const { 632 return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) && 633 !this->isTerminator(); 634 } 635 636 bool Instruction::willReturn() const { 637 if (const auto *CB = dyn_cast<CallBase>(this)) 638 // FIXME: Temporarily assume that all side-effect free intrinsics will 639 // return. Remove this workaround once all intrinsics are appropriately 640 // annotated. 641 return CB->hasFnAttr(Attribute::WillReturn) || 642 (isa<IntrinsicInst>(CB) && CB->onlyReadsMemory()); 643 return true; 644 } 645 646 bool Instruction::isLifetimeStartOrEnd() const { 647 auto II = dyn_cast<IntrinsicInst>(this); 648 if (!II) 649 return false; 650 Intrinsic::ID ID = II->getIntrinsicID(); 651 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end; 652 } 653 654 bool Instruction::isDebugOrPseudoInst() const { 655 return isa<DbgInfoIntrinsic>(this) || isa<PseudoProbeInst>(this); 656 } 657 658 const Instruction * 659 Instruction::getNextNonDebugInstruction(bool SkipPseudoOp) const { 660 for (const Instruction *I = getNextNode(); I; I = I->getNextNode()) 661 if (!isa<DbgInfoIntrinsic>(I) && !(SkipPseudoOp && isa<PseudoProbeInst>(I))) 662 return I; 663 return nullptr; 664 } 665 666 const Instruction * 667 Instruction::getPrevNonDebugInstruction(bool SkipPseudoOp) const { 668 for (const Instruction *I = getPrevNode(); I; I = I->getPrevNode()) 669 if (!isa<DbgInfoIntrinsic>(I) && !(SkipPseudoOp && isa<PseudoProbeInst>(I))) 670 return I; 671 return nullptr; 672 } 673 674 bool Instruction::isAssociative() const { 675 unsigned Opcode = getOpcode(); 676 if (isAssociative(Opcode)) 677 return true; 678 679 switch (Opcode) { 680 case FMul: 681 case FAdd: 682 return cast<FPMathOperator>(this)->hasAllowReassoc() && 683 cast<FPMathOperator>(this)->hasNoSignedZeros(); 684 default: 685 return false; 686 } 687 } 688 689 bool Instruction::isCommutative() const { 690 if (auto *II = dyn_cast<IntrinsicInst>(this)) 691 return II->isCommutative(); 692 // TODO: Should allow icmp/fcmp? 693 return isCommutative(getOpcode()); 694 } 695 696 unsigned Instruction::getNumSuccessors() const { 697 switch (getOpcode()) { 698 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 699 case Instruction::OPC: \ 700 return static_cast<const CLASS *>(this)->getNumSuccessors(); 701 #include "llvm/IR/Instruction.def" 702 default: 703 break; 704 } 705 llvm_unreachable("not a terminator"); 706 } 707 708 BasicBlock *Instruction::getSuccessor(unsigned idx) const { 709 switch (getOpcode()) { 710 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 711 case Instruction::OPC: \ 712 return static_cast<const CLASS *>(this)->getSuccessor(idx); 713 #include "llvm/IR/Instruction.def" 714 default: 715 break; 716 } 717 llvm_unreachable("not a terminator"); 718 } 719 720 void Instruction::setSuccessor(unsigned idx, BasicBlock *B) { 721 switch (getOpcode()) { 722 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 723 case Instruction::OPC: \ 724 return static_cast<CLASS *>(this)->setSuccessor(idx, B); 725 #include "llvm/IR/Instruction.def" 726 default: 727 break; 728 } 729 llvm_unreachable("not a terminator"); 730 } 731 732 void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) { 733 for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors(); 734 Idx != NumSuccessors; ++Idx) 735 if (getSuccessor(Idx) == OldBB) 736 setSuccessor(Idx, NewBB); 737 } 738 739 Instruction *Instruction::cloneImpl() const { 740 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl"); 741 } 742 743 void Instruction::swapProfMetadata() { 744 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof); 745 if (!ProfileData || ProfileData->getNumOperands() != 3 || 746 !isa<MDString>(ProfileData->getOperand(0))) 747 return; 748 749 MDString *MDName = cast<MDString>(ProfileData->getOperand(0)); 750 if (MDName->getString() != "branch_weights") 751 return; 752 753 // The first operand is the name. Fetch them backwards and build a new one. 754 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2), 755 ProfileData->getOperand(1)}; 756 setMetadata(LLVMContext::MD_prof, 757 MDNode::get(ProfileData->getContext(), Ops)); 758 } 759 760 void Instruction::copyMetadata(const Instruction &SrcInst, 761 ArrayRef<unsigned> WL) { 762 if (!SrcInst.hasMetadata()) 763 return; 764 765 DenseSet<unsigned> WLS; 766 for (unsigned M : WL) 767 WLS.insert(M); 768 769 // Otherwise, enumerate and copy over metadata from the old instruction to the 770 // new one. 771 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs; 772 SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs); 773 for (const auto &MD : TheMDs) { 774 if (WL.empty() || WLS.count(MD.first)) 775 setMetadata(MD.first, MD.second); 776 } 777 if (WL.empty() || WLS.count(LLVMContext::MD_dbg)) 778 setDebugLoc(SrcInst.getDebugLoc()); 779 } 780 781 Instruction *Instruction::clone() const { 782 Instruction *New = nullptr; 783 switch (getOpcode()) { 784 default: 785 llvm_unreachable("Unhandled Opcode."); 786 #define HANDLE_INST(num, opc, clas) \ 787 case Instruction::opc: \ 788 New = cast<clas>(this)->cloneImpl(); \ 789 break; 790 #include "llvm/IR/Instruction.def" 791 #undef HANDLE_INST 792 } 793 794 New->SubclassOptionalData = SubclassOptionalData; 795 New->copyMetadata(*this); 796 return New; 797 } 798