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