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