Path: blob/main/contrib/llvm-project/llvm/lib/IR/Instruction.cpp
35233 views
//===-- Instruction.cpp - Implement the Instruction class -----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Instruction class for the IR library.9//10//===----------------------------------------------------------------------===//1112#include "llvm/IR/Instruction.h"13#include "llvm/ADT/DenseSet.h"14#include "llvm/IR/AttributeMask.h"15#include "llvm/IR/Attributes.h"16#include "llvm/IR/Constants.h"17#include "llvm/IR/InstrTypes.h"18#include "llvm/IR/Instructions.h"19#include "llvm/IR/IntrinsicInst.h"20#include "llvm/IR/Intrinsics.h"21#include "llvm/IR/MemoryModelRelaxationAnnotations.h"22#include "llvm/IR/Module.h"23#include "llvm/IR/Operator.h"24#include "llvm/IR/ProfDataUtils.h"25#include "llvm/IR/Type.h"26using namespace llvm;2728InsertPosition::InsertPosition(Instruction *InsertBefore)29: InsertAt(InsertBefore ? InsertBefore->getIterator()30: InstListType::iterator()) {}31InsertPosition::InsertPosition(BasicBlock *InsertAtEnd)32: InsertAt(InsertAtEnd ? InsertAtEnd->end() : InstListType::iterator()) {}3334Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,35InsertPosition InsertBefore)36: User(ty, Value::InstructionVal + it, Ops, NumOps) {37// When called with an iterator, there must be a block to insert into.38if (InstListType::iterator InsertIt = InsertBefore; InsertIt.isValid()) {39BasicBlock *BB = InsertIt.getNodeParent();40assert(BB && "Instruction to insert before is not in a basic block!");41insertInto(BB, InsertBefore);42}43}4445Instruction::~Instruction() {46assert(!getParent() && "Instruction still linked in the program!");4748// Replace any extant metadata uses of this instruction with undef to49// preserve debug info accuracy. Some alternatives include:50// - Treat Instruction like any other Value, and point its extant metadata51// uses to an empty ValueAsMetadata node. This makes extant dbg.value uses52// trivially dead (i.e. fair game for deletion in many passes), leading to53// stale dbg.values being in effect for too long.54// - Call salvageDebugInfoOrMarkUndef. Not needed to make instruction removal55// correct. OTOH results in wasted work in some common cases (e.g. when all56// instructions in a BasicBlock are deleted).57if (isUsedByMetadata())58ValueAsMetadata::handleRAUW(this, UndefValue::get(getType()));5960// Explicitly remove DIAssignID metadata to clear up ID -> Instruction(s)61// mapping in LLVMContext.62setMetadata(LLVMContext::MD_DIAssignID, nullptr);63}6465const Module *Instruction::getModule() const {66return getParent()->getModule();67}6869const Function *Instruction::getFunction() const {70return getParent()->getParent();71}7273const DataLayout &Instruction::getDataLayout() const {74return getModule()->getDataLayout();75}7677void Instruction::removeFromParent() {78// Perform any debug-info maintenence required.79handleMarkerRemoval();8081getParent()->getInstList().remove(getIterator());82}8384void Instruction::handleMarkerRemoval() {85if (!getParent()->IsNewDbgInfoFormat || !DebugMarker)86return;8788DebugMarker->removeMarker();89}9091BasicBlock::iterator Instruction::eraseFromParent() {92handleMarkerRemoval();93return getParent()->getInstList().erase(getIterator());94}9596void Instruction::insertBefore(Instruction *InsertPos) {97insertBefore(InsertPos->getIterator());98}99100/// Insert an unlinked instruction into a basic block immediately before the101/// specified instruction.102void Instruction::insertBefore(BasicBlock::iterator InsertPos) {103insertBefore(*InsertPos->getParent(), InsertPos);104}105106/// Insert an unlinked instruction into a basic block immediately after the107/// specified instruction.108void Instruction::insertAfter(Instruction *InsertPos) {109BasicBlock *DestParent = InsertPos->getParent();110111DestParent->getInstList().insertAfter(InsertPos->getIterator(), this);112}113114BasicBlock::iterator Instruction::insertInto(BasicBlock *ParentBB,115BasicBlock::iterator It) {116assert(getParent() == nullptr && "Expected detached instruction");117assert((It == ParentBB->end() || It->getParent() == ParentBB) &&118"It not in ParentBB");119insertBefore(*ParentBB, It);120return getIterator();121}122123extern cl::opt<bool> UseNewDbgInfoFormat;124125void Instruction::insertBefore(BasicBlock &BB,126InstListType::iterator InsertPos) {127assert(!DebugMarker);128129BB.getInstList().insert(InsertPos, this);130131if (!BB.IsNewDbgInfoFormat)132return;133134// We've inserted "this": if InsertAtHead is set then it comes before any135// DbgVariableRecords attached to InsertPos. But if it's not set, then any136// DbgRecords should now come before "this".137bool InsertAtHead = InsertPos.getHeadBit();138if (!InsertAtHead) {139DbgMarker *SrcMarker = BB.getMarker(InsertPos);140if (SrcMarker && !SrcMarker->empty()) {141// If this assertion fires, the calling code is about to insert a PHI142// after debug-records, which would form a sequence like:143// %0 = PHI144// #dbg_value145// %1 = PHI146// Which is de-normalised and undesired -- hence the assertion. To avoid147// this, you must insert at that position using an iterator, and it must148// be aquired by calling getFirstNonPHIIt / begin or similar methods on149// the block. This will signal to this behind-the-scenes debug-info150// maintenence code that you intend the PHI to be ahead of everything,151// including any debug-info.152assert(!isa<PHINode>(this) && "Inserting PHI after debug-records!");153adoptDbgRecords(&BB, InsertPos, false);154}155}156157// If we're inserting a terminator, check if we need to flush out158// TrailingDbgRecords. Inserting instructions at the end of an incomplete159// block is handled by the code block above.160if (isTerminator())161getParent()->flushTerminatorDbgRecords();162}163164/// Unlink this instruction from its current basic block and insert it into the165/// basic block that MovePos lives in, right before MovePos.166void Instruction::moveBefore(Instruction *MovePos) {167moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), false);168}169170void Instruction::moveBeforePreserving(Instruction *MovePos) {171moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), true);172}173174void Instruction::moveAfter(Instruction *MovePos) {175auto NextIt = std::next(MovePos->getIterator());176// We want this instruction to be moved to before NextIt in the instruction177// list, but before NextIt's debug value range.178NextIt.setHeadBit(true);179moveBeforeImpl(*MovePos->getParent(), NextIt, false);180}181182void Instruction::moveAfterPreserving(Instruction *MovePos) {183auto NextIt = std::next(MovePos->getIterator());184// We want this instruction and its debug range to be moved to before NextIt185// in the instruction list, but before NextIt's debug value range.186NextIt.setHeadBit(true);187moveBeforeImpl(*MovePos->getParent(), NextIt, true);188}189190void Instruction::moveBefore(BasicBlock &BB, InstListType::iterator I) {191moveBeforeImpl(BB, I, false);192}193194void Instruction::moveBeforePreserving(BasicBlock &BB,195InstListType::iterator I) {196moveBeforeImpl(BB, I, true);197}198199void Instruction::moveBeforeImpl(BasicBlock &BB, InstListType::iterator I,200bool Preserve) {201assert(I == BB.end() || I->getParent() == &BB);202bool InsertAtHead = I.getHeadBit();203204// If we've been given the "Preserve" flag, then just move the DbgRecords with205// the instruction, no more special handling needed.206if (BB.IsNewDbgInfoFormat && DebugMarker && !Preserve) {207if (I != this->getIterator() || InsertAtHead) {208// "this" is definitely moving in the list, or it's moving ahead of its209// attached DbgVariableRecords. Detach any existing DbgRecords.210handleMarkerRemoval();211}212}213214// Move this single instruction. Use the list splice method directly, not215// the block splicer, which will do more debug-info things.216BB.getInstList().splice(I, getParent()->getInstList(), getIterator());217218if (BB.IsNewDbgInfoFormat && !Preserve) {219DbgMarker *NextMarker = getParent()->getNextMarker(this);220221// If we're inserting at point I, and not in front of the DbgRecords222// attached there, then we should absorb the DbgRecords attached to I.223if (!InsertAtHead && NextMarker && !NextMarker->empty()) {224adoptDbgRecords(&BB, I, false);225}226}227228if (isTerminator())229getParent()->flushTerminatorDbgRecords();230}231232iterator_range<DbgRecord::self_iterator> Instruction::cloneDebugInfoFrom(233const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,234bool InsertAtHead) {235if (!From->DebugMarker)236return DbgMarker::getEmptyDbgRecordRange();237238assert(getParent()->IsNewDbgInfoFormat);239assert(getParent()->IsNewDbgInfoFormat ==240From->getParent()->IsNewDbgInfoFormat);241242if (!DebugMarker)243getParent()->createMarker(this);244245return DebugMarker->cloneDebugInfoFrom(From->DebugMarker, FromHere,246InsertAtHead);247}248249std::optional<DbgRecord::self_iterator>250Instruction::getDbgReinsertionPosition() {251// Is there a marker on the next instruction?252DbgMarker *NextMarker = getParent()->getNextMarker(this);253if (!NextMarker)254return std::nullopt;255256// Are there any DbgRecords in the next marker?257if (NextMarker->StoredDbgRecords.empty())258return std::nullopt;259260return NextMarker->StoredDbgRecords.begin();261}262263bool Instruction::hasDbgRecords() const { return !getDbgRecordRange().empty(); }264265void Instruction::adoptDbgRecords(BasicBlock *BB, BasicBlock::iterator It,266bool InsertAtHead) {267DbgMarker *SrcMarker = BB->getMarker(It);268auto ReleaseTrailingDbgRecords = [BB, It, SrcMarker]() {269if (BB->end() == It) {270SrcMarker->eraseFromParent();271BB->deleteTrailingDbgRecords();272}273};274275if (!SrcMarker || SrcMarker->StoredDbgRecords.empty()) {276ReleaseTrailingDbgRecords();277return;278}279280// If we have DbgMarkers attached to this instruction, we have to honour the281// ordering of DbgRecords between this and the other marker. Fall back to just282// absorbing from the source.283if (DebugMarker || It == BB->end()) {284// Ensure we _do_ have a marker.285getParent()->createMarker(this);286DebugMarker->absorbDebugValues(*SrcMarker, InsertAtHead);287288// Having transferred everything out of SrcMarker, we _could_ clean it up289// and free the marker now. However, that's a lot of heap-accounting for a290// small amount of memory with a good chance of re-use. Leave it for the291// moment. It will be released when the Instruction is freed in the worst292// case.293// However: if we transferred from a trailing marker off the end of the294// block, it's important to not leave the empty marker trailing. It will295// give a misleading impression that some debug records have been left296// trailing.297ReleaseTrailingDbgRecords();298} else {299// Optimisation: we're transferring all the DbgRecords from the source300// marker onto this empty location: just adopt the other instructions301// marker.302DebugMarker = SrcMarker;303DebugMarker->MarkedInstr = this;304It->DebugMarker = nullptr;305}306}307308void Instruction::dropDbgRecords() {309if (DebugMarker)310DebugMarker->dropDbgRecords();311}312313void Instruction::dropOneDbgRecord(DbgRecord *DVR) {314DebugMarker->dropOneDbgRecord(DVR);315}316317bool Instruction::comesBefore(const Instruction *Other) const {318assert(getParent() && Other->getParent() &&319"instructions without BB parents have no order");320assert(getParent() == Other->getParent() &&321"cross-BB instruction order comparison");322if (!getParent()->isInstrOrderValid())323const_cast<BasicBlock *>(getParent())->renumberInstructions();324return Order < Other->Order;325}326327std::optional<BasicBlock::iterator> Instruction::getInsertionPointAfterDef() {328assert(!getType()->isVoidTy() && "Instruction must define result");329BasicBlock *InsertBB;330BasicBlock::iterator InsertPt;331if (auto *PN = dyn_cast<PHINode>(this)) {332InsertBB = PN->getParent();333InsertPt = InsertBB->getFirstInsertionPt();334} else if (auto *II = dyn_cast<InvokeInst>(this)) {335InsertBB = II->getNormalDest();336InsertPt = InsertBB->getFirstInsertionPt();337} else if (isa<CallBrInst>(this)) {338// Def is available in multiple successors, there's no single dominating339// insertion point.340return std::nullopt;341} else {342assert(!isTerminator() && "Only invoke/callbr terminators return value");343InsertBB = getParent();344InsertPt = std::next(getIterator());345// Any instruction inserted immediately after "this" will come before any346// debug-info records take effect -- thus, set the head bit indicating that347// to debug-info-transfer code.348InsertPt.setHeadBit(true);349}350351// catchswitch blocks don't have any legal insertion point (because they352// are both an exception pad and a terminator).353if (InsertPt == InsertBB->end())354return std::nullopt;355return InsertPt;356}357358bool Instruction::isOnlyUserOfAnyOperand() {359return any_of(operands(), [](Value *V) { return V->hasOneUser(); });360}361362void Instruction::setHasNoUnsignedWrap(bool b) {363if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))364Inst->setHasNoUnsignedWrap(b);365else366cast<TruncInst>(this)->setHasNoUnsignedWrap(b);367}368369void Instruction::setHasNoSignedWrap(bool b) {370if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))371Inst->setHasNoSignedWrap(b);372else373cast<TruncInst>(this)->setHasNoSignedWrap(b);374}375376void Instruction::setIsExact(bool b) {377cast<PossiblyExactOperator>(this)->setIsExact(b);378}379380void Instruction::setNonNeg(bool b) {381assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");382SubclassOptionalData = (SubclassOptionalData & ~PossiblyNonNegInst::NonNeg) |383(b * PossiblyNonNegInst::NonNeg);384}385386bool Instruction::hasNoUnsignedWrap() const {387if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))388return Inst->hasNoUnsignedWrap();389390return cast<TruncInst>(this)->hasNoUnsignedWrap();391}392393bool Instruction::hasNoSignedWrap() const {394if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))395return Inst->hasNoSignedWrap();396397return cast<TruncInst>(this)->hasNoSignedWrap();398}399400bool Instruction::hasNonNeg() const {401assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");402return (SubclassOptionalData & PossiblyNonNegInst::NonNeg) != 0;403}404405bool Instruction::hasPoisonGeneratingFlags() const {406return cast<Operator>(this)->hasPoisonGeneratingFlags();407}408409void Instruction::dropPoisonGeneratingFlags() {410switch (getOpcode()) {411case Instruction::Add:412case Instruction::Sub:413case Instruction::Mul:414case Instruction::Shl:415cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);416cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);417break;418419case Instruction::UDiv:420case Instruction::SDiv:421case Instruction::AShr:422case Instruction::LShr:423cast<PossiblyExactOperator>(this)->setIsExact(false);424break;425426case Instruction::Or:427cast<PossiblyDisjointInst>(this)->setIsDisjoint(false);428break;429430case Instruction::GetElementPtr:431cast<GetElementPtrInst>(this)->setNoWrapFlags(GEPNoWrapFlags::none());432break;433434case Instruction::UIToFP:435case Instruction::ZExt:436setNonNeg(false);437break;438439case Instruction::Trunc:440cast<TruncInst>(this)->setHasNoUnsignedWrap(false);441cast<TruncInst>(this)->setHasNoSignedWrap(false);442break;443}444445if (isa<FPMathOperator>(this)) {446setHasNoNaNs(false);447setHasNoInfs(false);448}449450assert(!hasPoisonGeneratingFlags() && "must be kept in sync");451}452453bool Instruction::hasPoisonGeneratingMetadata() const {454return hasMetadata(LLVMContext::MD_range) ||455hasMetadata(LLVMContext::MD_nonnull) ||456hasMetadata(LLVMContext::MD_align);457}458459void Instruction::dropPoisonGeneratingMetadata() {460eraseMetadata(LLVMContext::MD_range);461eraseMetadata(LLVMContext::MD_nonnull);462eraseMetadata(LLVMContext::MD_align);463}464465bool Instruction::hasPoisonGeneratingReturnAttributes() const {466if (const auto *CB = dyn_cast<CallBase>(this)) {467AttributeSet RetAttrs = CB->getAttributes().getRetAttrs();468return RetAttrs.hasAttribute(Attribute::Range) ||469RetAttrs.hasAttribute(Attribute::Alignment) ||470RetAttrs.hasAttribute(Attribute::NonNull);471}472return false;473}474475void Instruction::dropPoisonGeneratingReturnAttributes() {476if (auto *CB = dyn_cast<CallBase>(this)) {477AttributeMask AM;478AM.addAttribute(Attribute::Range);479AM.addAttribute(Attribute::Alignment);480AM.addAttribute(Attribute::NonNull);481CB->removeRetAttrs(AM);482}483assert(!hasPoisonGeneratingReturnAttributes() && "must be kept in sync");484}485486void Instruction::dropUBImplyingAttrsAndUnknownMetadata(487ArrayRef<unsigned> KnownIDs) {488dropUnknownNonDebugMetadata(KnownIDs);489auto *CB = dyn_cast<CallBase>(this);490if (!CB)491return;492// For call instructions, we also need to drop parameter and return attributes493// that are can cause UB if the call is moved to a location where the494// attribute is not valid.495AttributeList AL = CB->getAttributes();496if (AL.isEmpty())497return;498AttributeMask UBImplyingAttributes =499AttributeFuncs::getUBImplyingAttributes();500for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)501CB->removeParamAttrs(ArgNo, UBImplyingAttributes);502CB->removeRetAttrs(UBImplyingAttributes);503}504505void Instruction::dropUBImplyingAttrsAndMetadata() {506// !annotation metadata does not impact semantics.507// !range, !nonnull and !align produce poison, so they are safe to speculate.508// !noundef and various AA metadata must be dropped, as it generally produces509// immediate undefined behavior.510unsigned KnownIDs[] = {LLVMContext::MD_annotation, LLVMContext::MD_range,511LLVMContext::MD_nonnull, LLVMContext::MD_align};512dropUBImplyingAttrsAndUnknownMetadata(KnownIDs);513}514515bool Instruction::isExact() const {516return cast<PossiblyExactOperator>(this)->isExact();517}518519void Instruction::setFast(bool B) {520assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");521cast<FPMathOperator>(this)->setFast(B);522}523524void Instruction::setHasAllowReassoc(bool B) {525assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");526cast<FPMathOperator>(this)->setHasAllowReassoc(B);527}528529void Instruction::setHasNoNaNs(bool B) {530assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");531cast<FPMathOperator>(this)->setHasNoNaNs(B);532}533534void Instruction::setHasNoInfs(bool B) {535assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");536cast<FPMathOperator>(this)->setHasNoInfs(B);537}538539void Instruction::setHasNoSignedZeros(bool B) {540assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");541cast<FPMathOperator>(this)->setHasNoSignedZeros(B);542}543544void Instruction::setHasAllowReciprocal(bool B) {545assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");546cast<FPMathOperator>(this)->setHasAllowReciprocal(B);547}548549void Instruction::setHasAllowContract(bool B) {550assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");551cast<FPMathOperator>(this)->setHasAllowContract(B);552}553554void Instruction::setHasApproxFunc(bool B) {555assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");556cast<FPMathOperator>(this)->setHasApproxFunc(B);557}558559void Instruction::setFastMathFlags(FastMathFlags FMF) {560assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");561cast<FPMathOperator>(this)->setFastMathFlags(FMF);562}563564void Instruction::copyFastMathFlags(FastMathFlags FMF) {565assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");566cast<FPMathOperator>(this)->copyFastMathFlags(FMF);567}568569bool Instruction::isFast() const {570assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");571return cast<FPMathOperator>(this)->isFast();572}573574bool Instruction::hasAllowReassoc() const {575assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");576return cast<FPMathOperator>(this)->hasAllowReassoc();577}578579bool Instruction::hasNoNaNs() const {580assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");581return cast<FPMathOperator>(this)->hasNoNaNs();582}583584bool Instruction::hasNoInfs() const {585assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");586return cast<FPMathOperator>(this)->hasNoInfs();587}588589bool Instruction::hasNoSignedZeros() const {590assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");591return cast<FPMathOperator>(this)->hasNoSignedZeros();592}593594bool Instruction::hasAllowReciprocal() const {595assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");596return cast<FPMathOperator>(this)->hasAllowReciprocal();597}598599bool Instruction::hasAllowContract() const {600assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");601return cast<FPMathOperator>(this)->hasAllowContract();602}603604bool Instruction::hasApproxFunc() const {605assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");606return cast<FPMathOperator>(this)->hasApproxFunc();607}608609FastMathFlags Instruction::getFastMathFlags() const {610assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");611return cast<FPMathOperator>(this)->getFastMathFlags();612}613614void Instruction::copyFastMathFlags(const Instruction *I) {615copyFastMathFlags(I->getFastMathFlags());616}617618void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {619// Copy the wrapping flags.620if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) {621if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {622setHasNoSignedWrap(OB->hasNoSignedWrap());623setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());624}625}626627if (auto *TI = dyn_cast<TruncInst>(V)) {628if (isa<TruncInst>(this)) {629setHasNoSignedWrap(TI->hasNoSignedWrap());630setHasNoUnsignedWrap(TI->hasNoUnsignedWrap());631}632}633634// Copy the exact flag.635if (auto *PE = dyn_cast<PossiblyExactOperator>(V))636if (isa<PossiblyExactOperator>(this))637setIsExact(PE->isExact());638639if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))640if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))641DestPD->setIsDisjoint(SrcPD->isDisjoint());642643// Copy the fast-math flags.644if (auto *FP = dyn_cast<FPMathOperator>(V))645if (isa<FPMathOperator>(this))646copyFastMathFlags(FP->getFastMathFlags());647648if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))649if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))650DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() |651DestGEP->getNoWrapFlags());652653if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))654if (isa<PossiblyNonNegInst>(this))655setNonNeg(NNI->hasNonNeg());656}657658void Instruction::andIRFlags(const Value *V) {659if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {660if (isa<OverflowingBinaryOperator>(this)) {661setHasNoSignedWrap(hasNoSignedWrap() && OB->hasNoSignedWrap());662setHasNoUnsignedWrap(hasNoUnsignedWrap() && OB->hasNoUnsignedWrap());663}664}665666if (auto *TI = dyn_cast<TruncInst>(V)) {667if (isa<TruncInst>(this)) {668setHasNoSignedWrap(hasNoSignedWrap() && TI->hasNoSignedWrap());669setHasNoUnsignedWrap(hasNoUnsignedWrap() && TI->hasNoUnsignedWrap());670}671}672673if (auto *PE = dyn_cast<PossiblyExactOperator>(V))674if (isa<PossiblyExactOperator>(this))675setIsExact(isExact() && PE->isExact());676677if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))678if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))679DestPD->setIsDisjoint(DestPD->isDisjoint() && SrcPD->isDisjoint());680681if (auto *FP = dyn_cast<FPMathOperator>(V)) {682if (isa<FPMathOperator>(this)) {683FastMathFlags FM = getFastMathFlags();684FM &= FP->getFastMathFlags();685copyFastMathFlags(FM);686}687}688689if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))690if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))691DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() &692DestGEP->getNoWrapFlags());693694if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))695if (isa<PossiblyNonNegInst>(this))696setNonNeg(hasNonNeg() && NNI->hasNonNeg());697}698699const char *Instruction::getOpcodeName(unsigned OpCode) {700switch (OpCode) {701// Terminators702case Ret: return "ret";703case Br: return "br";704case Switch: return "switch";705case IndirectBr: return "indirectbr";706case Invoke: return "invoke";707case Resume: return "resume";708case Unreachable: return "unreachable";709case CleanupRet: return "cleanupret";710case CatchRet: return "catchret";711case CatchPad: return "catchpad";712case CatchSwitch: return "catchswitch";713case CallBr: return "callbr";714715// Standard unary operators...716case FNeg: return "fneg";717718// Standard binary operators...719case Add: return "add";720case FAdd: return "fadd";721case Sub: return "sub";722case FSub: return "fsub";723case Mul: return "mul";724case FMul: return "fmul";725case UDiv: return "udiv";726case SDiv: return "sdiv";727case FDiv: return "fdiv";728case URem: return "urem";729case SRem: return "srem";730case FRem: return "frem";731732// Logical operators...733case And: return "and";734case Or : return "or";735case Xor: return "xor";736737// Memory instructions...738case Alloca: return "alloca";739case Load: return "load";740case Store: return "store";741case AtomicCmpXchg: return "cmpxchg";742case AtomicRMW: return "atomicrmw";743case Fence: return "fence";744case GetElementPtr: return "getelementptr";745746// Convert instructions...747case Trunc: return "trunc";748case ZExt: return "zext";749case SExt: return "sext";750case FPTrunc: return "fptrunc";751case FPExt: return "fpext";752case FPToUI: return "fptoui";753case FPToSI: return "fptosi";754case UIToFP: return "uitofp";755case SIToFP: return "sitofp";756case IntToPtr: return "inttoptr";757case PtrToInt: return "ptrtoint";758case BitCast: return "bitcast";759case AddrSpaceCast: return "addrspacecast";760761// Other instructions...762case ICmp: return "icmp";763case FCmp: return "fcmp";764case PHI: return "phi";765case Select: return "select";766case Call: return "call";767case Shl: return "shl";768case LShr: return "lshr";769case AShr: return "ashr";770case VAArg: return "va_arg";771case ExtractElement: return "extractelement";772case InsertElement: return "insertelement";773case ShuffleVector: return "shufflevector";774case ExtractValue: return "extractvalue";775case InsertValue: return "insertvalue";776case LandingPad: return "landingpad";777case CleanupPad: return "cleanuppad";778case Freeze: return "freeze";779780default: return "<Invalid operator> ";781}782}783784/// This must be kept in sync with FunctionComparator::cmpOperations in785/// lib/Transforms/IPO/MergeFunctions.cpp.786bool Instruction::hasSameSpecialState(const Instruction *I2,787bool IgnoreAlignment) const {788auto I1 = this;789assert(I1->getOpcode() == I2->getOpcode() &&790"Can not compare special state of different instructions");791792if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))793return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&794(AI->getAlign() == cast<AllocaInst>(I2)->getAlign() ||795IgnoreAlignment);796if (const LoadInst *LI = dyn_cast<LoadInst>(I1))797return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&798(LI->getAlign() == cast<LoadInst>(I2)->getAlign() ||799IgnoreAlignment) &&800LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&801LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID();802if (const StoreInst *SI = dyn_cast<StoreInst>(I1))803return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&804(SI->getAlign() == cast<StoreInst>(I2)->getAlign() ||805IgnoreAlignment) &&806SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&807SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID();808if (const CmpInst *CI = dyn_cast<CmpInst>(I1))809return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();810if (const CallInst *CI = dyn_cast<CallInst>(I1))811return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&812CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&813CI->getAttributes() == cast<CallInst>(I2)->getAttributes() &&814CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));815if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))816return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&817CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes() &&818CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));819if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1))820return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() &&821CI->getAttributes() == cast<CallBrInst>(I2)->getAttributes() &&822CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2));823if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))824return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();825if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))826return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();827if (const FenceInst *FI = dyn_cast<FenceInst>(I1))828return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&829FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID();830if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))831return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&832CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&833CXI->getSuccessOrdering() ==834cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&835CXI->getFailureOrdering() ==836cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&837CXI->getSyncScopeID() ==838cast<AtomicCmpXchgInst>(I2)->getSyncScopeID();839if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))840return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&841RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&842RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&843RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID();844if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I1))845return SVI->getShuffleMask() ==846cast<ShuffleVectorInst>(I2)->getShuffleMask();847if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I1))848return GEP->getSourceElementType() ==849cast<GetElementPtrInst>(I2)->getSourceElementType();850851return true;852}853854bool Instruction::isIdenticalTo(const Instruction *I) const {855return isIdenticalToWhenDefined(I) &&856SubclassOptionalData == I->SubclassOptionalData;857}858859bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {860if (getOpcode() != I->getOpcode() ||861getNumOperands() != I->getNumOperands() ||862getType() != I->getType())863return false;864865// If both instructions have no operands, they are identical.866if (getNumOperands() == 0 && I->getNumOperands() == 0)867return this->hasSameSpecialState(I);868869// We have two instructions of identical opcode and #operands. Check to see870// if all operands are the same.871if (!std::equal(op_begin(), op_end(), I->op_begin()))872return false;873874// WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()!875if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {876const PHINode *otherPHI = cast<PHINode>(I);877return std::equal(thisPHI->block_begin(), thisPHI->block_end(),878otherPHI->block_begin());879}880881return this->hasSameSpecialState(I);882}883884// Keep this in sync with FunctionComparator::cmpOperations in885// lib/Transforms/IPO/MergeFunctions.cpp.886bool Instruction::isSameOperationAs(const Instruction *I,887unsigned flags) const {888bool IgnoreAlignment = flags & CompareIgnoringAlignment;889bool UseScalarTypes = flags & CompareUsingScalarTypes;890891if (getOpcode() != I->getOpcode() ||892getNumOperands() != I->getNumOperands() ||893(UseScalarTypes ?894getType()->getScalarType() != I->getType()->getScalarType() :895getType() != I->getType()))896return false;897898// We have two instructions of identical opcode and #operands. Check to see899// if all operands are the same type900for (unsigned i = 0, e = getNumOperands(); i != e; ++i)901if (UseScalarTypes ?902getOperand(i)->getType()->getScalarType() !=903I->getOperand(i)->getType()->getScalarType() :904getOperand(i)->getType() != I->getOperand(i)->getType())905return false;906907return this->hasSameSpecialState(I, IgnoreAlignment);908}909910bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {911for (const Use &U : uses()) {912// PHI nodes uses values in the corresponding predecessor block. For other913// instructions, just check to see whether the parent of the use matches up.914const Instruction *I = cast<Instruction>(U.getUser());915const PHINode *PN = dyn_cast<PHINode>(I);916if (!PN) {917if (I->getParent() != BB)918return true;919continue;920}921922if (PN->getIncomingBlock(U) != BB)923return true;924}925return false;926}927928bool Instruction::mayReadFromMemory() const {929switch (getOpcode()) {930default: return false;931case Instruction::VAArg:932case Instruction::Load:933case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory934case Instruction::AtomicCmpXchg:935case Instruction::AtomicRMW:936case Instruction::CatchPad:937case Instruction::CatchRet:938return true;939case Instruction::Call:940case Instruction::Invoke:941case Instruction::CallBr:942return !cast<CallBase>(this)->onlyWritesMemory();943case Instruction::Store:944return !cast<StoreInst>(this)->isUnordered();945}946}947948bool Instruction::mayWriteToMemory() const {949switch (getOpcode()) {950default: return false;951case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory952case Instruction::Store:953case Instruction::VAArg:954case Instruction::AtomicCmpXchg:955case Instruction::AtomicRMW:956case Instruction::CatchPad:957case Instruction::CatchRet:958return true;959case Instruction::Call:960case Instruction::Invoke:961case Instruction::CallBr:962return !cast<CallBase>(this)->onlyReadsMemory();963case Instruction::Load:964return !cast<LoadInst>(this)->isUnordered();965}966}967968bool Instruction::isAtomic() const {969switch (getOpcode()) {970default:971return false;972case Instruction::AtomicCmpXchg:973case Instruction::AtomicRMW:974case Instruction::Fence:975return true;976case Instruction::Load:977return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;978case Instruction::Store:979return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;980}981}982983bool Instruction::hasAtomicLoad() const {984assert(isAtomic());985switch (getOpcode()) {986default:987return false;988case Instruction::AtomicCmpXchg:989case Instruction::AtomicRMW:990case Instruction::Load:991return true;992}993}994995bool Instruction::hasAtomicStore() const {996assert(isAtomic());997switch (getOpcode()) {998default:999return false;1000case Instruction::AtomicCmpXchg:1001case Instruction::AtomicRMW:1002case Instruction::Store:1003return true;1004}1005}10061007bool Instruction::isVolatile() const {1008switch (getOpcode()) {1009default:1010return false;1011case Instruction::AtomicRMW:1012return cast<AtomicRMWInst>(this)->isVolatile();1013case Instruction::Store:1014return cast<StoreInst>(this)->isVolatile();1015case Instruction::Load:1016return cast<LoadInst>(this)->isVolatile();1017case Instruction::AtomicCmpXchg:1018return cast<AtomicCmpXchgInst>(this)->isVolatile();1019case Instruction::Call:1020case Instruction::Invoke:1021// There are a very limited number of intrinsics with volatile flags.1022if (auto *II = dyn_cast<IntrinsicInst>(this)) {1023if (auto *MI = dyn_cast<MemIntrinsic>(II))1024return MI->isVolatile();1025switch (II->getIntrinsicID()) {1026default: break;1027case Intrinsic::matrix_column_major_load:1028return cast<ConstantInt>(II->getArgOperand(2))->isOne();1029case Intrinsic::matrix_column_major_store:1030return cast<ConstantInt>(II->getArgOperand(3))->isOne();1031}1032}1033return false;1034}1035}10361037Type *Instruction::getAccessType() const {1038switch (getOpcode()) {1039case Instruction::Store:1040return cast<StoreInst>(this)->getValueOperand()->getType();1041case Instruction::Load:1042case Instruction::AtomicRMW:1043return getType();1044case Instruction::AtomicCmpXchg:1045return cast<AtomicCmpXchgInst>(this)->getNewValOperand()->getType();1046case Instruction::Call:1047case Instruction::Invoke:1048if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(this)) {1049switch (II->getIntrinsicID()) {1050case Intrinsic::masked_load:1051case Intrinsic::masked_gather:1052case Intrinsic::masked_expandload:1053case Intrinsic::vp_load:1054case Intrinsic::vp_gather:1055case Intrinsic::experimental_vp_strided_load:1056return II->getType();1057case Intrinsic::masked_store:1058case Intrinsic::masked_scatter:1059case Intrinsic::masked_compressstore:1060case Intrinsic::vp_store:1061case Intrinsic::vp_scatter:1062case Intrinsic::experimental_vp_strided_store:1063return II->getOperand(0)->getType();1064default:1065break;1066}1067}1068}10691070return nullptr;1071}10721073static bool canUnwindPastLandingPad(const LandingPadInst *LP,1074bool IncludePhaseOneUnwind) {1075// Because phase one unwinding skips cleanup landingpads, we effectively1076// unwind past this frame, and callers need to have valid unwind info.1077if (LP->isCleanup())1078return IncludePhaseOneUnwind;10791080for (unsigned I = 0; I < LP->getNumClauses(); ++I) {1081Constant *Clause = LP->getClause(I);1082// catch ptr null catches all exceptions.1083if (LP->isCatch(I) && isa<ConstantPointerNull>(Clause))1084return false;1085// filter [0 x ptr] catches all exceptions.1086if (LP->isFilter(I) && Clause->getType()->getArrayNumElements() == 0)1087return false;1088}10891090// May catch only some subset of exceptions, in which case other exceptions1091// will continue unwinding.1092return true;1093}10941095bool Instruction::mayThrow(bool IncludePhaseOneUnwind) const {1096switch (getOpcode()) {1097case Instruction::Call:1098return !cast<CallInst>(this)->doesNotThrow();1099case Instruction::CleanupRet:1100return cast<CleanupReturnInst>(this)->unwindsToCaller();1101case Instruction::CatchSwitch:1102return cast<CatchSwitchInst>(this)->unwindsToCaller();1103case Instruction::Resume:1104return true;1105case Instruction::Invoke: {1106// Landingpads themselves don't unwind -- however, an invoke of a skipped1107// landingpad may continue unwinding.1108BasicBlock *UnwindDest = cast<InvokeInst>(this)->getUnwindDest();1109Instruction *Pad = UnwindDest->getFirstNonPHI();1110if (auto *LP = dyn_cast<LandingPadInst>(Pad))1111return canUnwindPastLandingPad(LP, IncludePhaseOneUnwind);1112return false;1113}1114case Instruction::CleanupPad:1115// Treat the same as cleanup landingpad.1116return IncludePhaseOneUnwind;1117default:1118return false;1119}1120}11211122bool Instruction::mayHaveSideEffects() const {1123return mayWriteToMemory() || mayThrow() || !willReturn();1124}11251126bool Instruction::isSafeToRemove() const {1127return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) &&1128!this->isTerminator() && !this->isEHPad();1129}11301131bool Instruction::willReturn() const {1132// Volatile store isn't guaranteed to return; see LangRef.1133if (auto *SI = dyn_cast<StoreInst>(this))1134return !SI->isVolatile();11351136if (const auto *CB = dyn_cast<CallBase>(this))1137return CB->hasFnAttr(Attribute::WillReturn);1138return true;1139}11401141bool Instruction::isLifetimeStartOrEnd() const {1142auto *II = dyn_cast<IntrinsicInst>(this);1143if (!II)1144return false;1145Intrinsic::ID ID = II->getIntrinsicID();1146return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;1147}11481149bool Instruction::isLaunderOrStripInvariantGroup() const {1150auto *II = dyn_cast<IntrinsicInst>(this);1151if (!II)1152return false;1153Intrinsic::ID ID = II->getIntrinsicID();1154return ID == Intrinsic::launder_invariant_group ||1155ID == Intrinsic::strip_invariant_group;1156}11571158bool Instruction::isDebugOrPseudoInst() const {1159return isa<DbgInfoIntrinsic>(this) || isa<PseudoProbeInst>(this);1160}11611162const Instruction *1163Instruction::getNextNonDebugInstruction(bool SkipPseudoOp) const {1164for (const Instruction *I = getNextNode(); I; I = I->getNextNode())1165if (!isa<DbgInfoIntrinsic>(I) && !(SkipPseudoOp && isa<PseudoProbeInst>(I)))1166return I;1167return nullptr;1168}11691170const Instruction *1171Instruction::getPrevNonDebugInstruction(bool SkipPseudoOp) const {1172for (const Instruction *I = getPrevNode(); I; I = I->getPrevNode())1173if (!isa<DbgInfoIntrinsic>(I) && !(SkipPseudoOp && isa<PseudoProbeInst>(I)))1174return I;1175return nullptr;1176}11771178const DebugLoc &Instruction::getStableDebugLoc() const {1179if (isa<DbgInfoIntrinsic>(this))1180if (const Instruction *Next = getNextNonDebugInstruction())1181return Next->getDebugLoc();1182return getDebugLoc();1183}11841185bool Instruction::isAssociative() const {1186if (auto *II = dyn_cast<IntrinsicInst>(this))1187return II->isAssociative();1188unsigned Opcode = getOpcode();1189if (isAssociative(Opcode))1190return true;11911192switch (Opcode) {1193case FMul:1194case FAdd:1195return cast<FPMathOperator>(this)->hasAllowReassoc() &&1196cast<FPMathOperator>(this)->hasNoSignedZeros();1197default:1198return false;1199}1200}12011202bool Instruction::isCommutative() const {1203if (auto *II = dyn_cast<IntrinsicInst>(this))1204return II->isCommutative();1205// TODO: Should allow icmp/fcmp?1206return isCommutative(getOpcode());1207}12081209unsigned Instruction::getNumSuccessors() const {1210switch (getOpcode()) {1211#define HANDLE_TERM_INST(N, OPC, CLASS) \1212case Instruction::OPC: \1213return static_cast<const CLASS *>(this)->getNumSuccessors();1214#include "llvm/IR/Instruction.def"1215default:1216break;1217}1218llvm_unreachable("not a terminator");1219}12201221BasicBlock *Instruction::getSuccessor(unsigned idx) const {1222switch (getOpcode()) {1223#define HANDLE_TERM_INST(N, OPC, CLASS) \1224case Instruction::OPC: \1225return static_cast<const CLASS *>(this)->getSuccessor(idx);1226#include "llvm/IR/Instruction.def"1227default:1228break;1229}1230llvm_unreachable("not a terminator");1231}12321233void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {1234switch (getOpcode()) {1235#define HANDLE_TERM_INST(N, OPC, CLASS) \1236case Instruction::OPC: \1237return static_cast<CLASS *>(this)->setSuccessor(idx, B);1238#include "llvm/IR/Instruction.def"1239default:1240break;1241}1242llvm_unreachable("not a terminator");1243}12441245void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) {1246for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors();1247Idx != NumSuccessors; ++Idx)1248if (getSuccessor(Idx) == OldBB)1249setSuccessor(Idx, NewBB);1250}12511252Instruction *Instruction::cloneImpl() const {1253llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");1254}12551256void Instruction::swapProfMetadata() {1257MDNode *ProfileData = getBranchWeightMDNode(*this);1258if (!ProfileData)1259return;1260unsigned FirstIdx = getBranchWeightOffset(ProfileData);1261if (ProfileData->getNumOperands() != 2 + FirstIdx)1262return;12631264unsigned SecondIdx = FirstIdx + 1;1265SmallVector<Metadata *, 4> Ops;1266// If there are more weights past the second, we can't swap them1267if (ProfileData->getNumOperands() > SecondIdx + 1)1268return;1269for (unsigned Idx = 0; Idx < FirstIdx; ++Idx) {1270Ops.push_back(ProfileData->getOperand(Idx));1271}1272// Switch the order of the weights1273Ops.push_back(ProfileData->getOperand(SecondIdx));1274Ops.push_back(ProfileData->getOperand(FirstIdx));1275setMetadata(LLVMContext::MD_prof,1276MDNode::get(ProfileData->getContext(), Ops));1277}12781279void Instruction::copyMetadata(const Instruction &SrcInst,1280ArrayRef<unsigned> WL) {1281if (!SrcInst.hasMetadata())1282return;12831284SmallDenseSet<unsigned, 4> WLS(WL.begin(), WL.end());12851286// Otherwise, enumerate and copy over metadata from the old instruction to the1287// new one.1288SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;1289SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);1290for (const auto &MD : TheMDs) {1291if (WL.empty() || WLS.count(MD.first))1292setMetadata(MD.first, MD.second);1293}1294if (WL.empty() || WLS.count(LLVMContext::MD_dbg))1295setDebugLoc(SrcInst.getDebugLoc());1296}12971298Instruction *Instruction::clone() const {1299Instruction *New = nullptr;1300switch (getOpcode()) {1301default:1302llvm_unreachable("Unhandled Opcode.");1303#define HANDLE_INST(num, opc, clas) \1304case Instruction::opc: \1305New = cast<clas>(this)->cloneImpl(); \1306break;1307#include "llvm/IR/Instruction.def"1308#undef HANDLE_INST1309}13101311New->SubclassOptionalData = SubclassOptionalData;1312New->copyMetadata(*this);1313return New;1314}131513161317