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