1//===-- Instruction.cpp - Implement the Instruction class -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Instruction class for the IR library.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Instruction.h"
14#include "llvm/ADT/DenseSet.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/IR/AttributeMask.h"
17#include "llvm/IR/Attributes.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/InstrTypes.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/IntrinsicInst.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/LLVMContext.h"
24#include "llvm/IR/MemoryModelRelaxationAnnotations.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/Operator.h"
27#include "llvm/IR/ProfDataUtils.h"
28#include "llvm/IR/Type.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Compiler.h"
31using namespace llvm;
32
33namespace llvm {
34
35// FIXME: Flag used for an ablation performance test, Issue #147390. Placing it
36// here because referencing IR should be feasible from anywhere. Will be
37// removed after the ablation test.
38cl::opt<bool> ProfcheckDisableMetadataFixes(
39 "profcheck-disable-metadata-fixes", cl::Hidden, cl::init(Val: false),
40 cl::desc(
41 "Disable metadata propagation fixes discovered through Issue #147390"));
42
43} // end namespace llvm
44
45InsertPosition::InsertPosition(BasicBlock *InsertAtEnd)
46 : InsertAt(InsertAtEnd ? InsertAtEnd->end() : InstListType::iterator()) {}
47
48Instruction::Instruction(Type *ty, unsigned it, AllocInfo AllocInfo,
49 InsertPosition InsertBefore)
50 : User(ty, Value::InstructionVal + it, AllocInfo) {
51 // When called with an iterator, there must be a block to insert into.
52 if (InstListType::iterator InsertIt = InsertBefore; InsertIt.isValid()) {
53 BasicBlock *BB = InsertIt.getNodeParent();
54 assert(BB && "Instruction to insert before is not in a basic block!");
55 insertInto(ParentBB: BB, It: InsertBefore);
56 }
57}
58
59Instruction::~Instruction() {
60 assert(!getParent() && "Instruction still linked in the program!");
61
62 // Replace any extant metadata uses of this instruction with poison to
63 // preserve debug info accuracy. Some alternatives include:
64 // - Treat Instruction like any other Value, and point its extant metadata
65 // uses to an empty ValueAsMetadata node. This makes extant dbg.value uses
66 // trivially dead (i.e. fair game for deletion in many passes), leading to
67 // stale dbg.values being in effect for too long.
68 // - Call salvageDebugInfoOrMarkUndef. Not needed to make instruction removal
69 // correct. OTOH results in wasted work in some common cases (e.g. when all
70 // instructions in a BasicBlock are deleted).
71 if (isUsedByMetadata())
72 ValueAsMetadata::handleRAUW(From: this, To: PoisonValue::get(T: getType()));
73
74 // Remove associated metadata from context.
75 if (hasMetadata()) {
76 // Explicitly remove DIAssignID metadata to clear up ID -> Instruction(s)
77 // mapping in LLVMContext.
78 updateDIAssignIDMapping(ID: nullptr);
79 clearMetadata();
80 }
81}
82
83const Module *Instruction::getModule() const {
84 return getParent()->getModule();
85}
86
87const Function *Instruction::getFunction() const {
88 return getParent()->getParent();
89}
90
91const DataLayout &Instruction::getDataLayout() const {
92 return getModule()->getDataLayout();
93}
94
95void Instruction::removeFromParent() {
96 // Perform any debug-info maintenence required.
97 handleMarkerRemoval();
98
99 getParent()->getInstList().remove(IT: getIterator());
100}
101
102void Instruction::handleMarkerRemoval() {
103 if (!DebugMarker)
104 return;
105
106 DebugMarker->removeMarker();
107}
108
109BasicBlock::iterator Instruction::eraseFromParent() {
110 handleMarkerRemoval();
111 return getParent()->getInstList().erase(where: getIterator());
112}
113
114/// Insert an unlinked instruction into a basic block immediately before the
115/// specified instruction.
116void Instruction::insertBefore(BasicBlock::iterator InsertPos) {
117 insertBefore(BB&: *InsertPos->getParent(), InsertPos);
118}
119
120/// Insert an unlinked instruction into a basic block immediately after the
121/// specified instruction.
122void Instruction::insertAfter(Instruction *InsertPos) {
123 BasicBlock *DestParent = InsertPos->getParent();
124
125 DestParent->getInstList().insertAfter(where: InsertPos->getIterator(), New: this);
126}
127
128void Instruction::insertAfter(BasicBlock::iterator InsertPos) {
129 BasicBlock *DestParent = InsertPos->getParent();
130
131 DestParent->getInstList().insertAfter(where: InsertPos, New: this);
132}
133
134BasicBlock::iterator Instruction::insertInto(BasicBlock *ParentBB,
135 BasicBlock::iterator It) {
136 assert(getParent() == nullptr && "Expected detached instruction");
137 assert((It == ParentBB->end() || It->getParent() == ParentBB) &&
138 "It not in ParentBB");
139 insertBefore(BB&: *ParentBB, InsertPos: It);
140 return getIterator();
141}
142
143void Instruction::insertBefore(BasicBlock &BB,
144 InstListType::iterator InsertPos) {
145 assert(!DebugMarker);
146
147 BB.getInstList().insert(where: InsertPos, New: this);
148
149 // We've inserted "this": if InsertAtHead is set then it comes before any
150 // DbgVariableRecords attached to InsertPos. But if it's not set, then any
151 // DbgRecords should now come before "this".
152 bool InsertAtHead = InsertPos.getHeadBit();
153 if (!InsertAtHead) {
154 DbgMarker *SrcMarker = BB.getMarker(It: InsertPos);
155 if (SrcMarker && !SrcMarker->empty()) {
156 // If this assertion fires, the calling code is about to insert a PHI
157 // after debug-records, which would form a sequence like:
158 // %0 = PHI
159 // #dbg_value
160 // %1 = PHI
161 // Which is de-normalised and undesired -- hence the assertion. To avoid
162 // this, you must insert at that position using an iterator, and it must
163 // be aquired by calling getFirstNonPHIIt / begin or similar methods on
164 // the block. This will signal to this behind-the-scenes debug-info
165 // maintenence code that you intend the PHI to be ahead of everything,
166 // including any debug-info.
167 assert(!isa<PHINode>(this) && "Inserting PHI after debug-records!");
168 adoptDbgRecords(BB: &BB, It: InsertPos, InsertAtHead: false);
169 }
170 }
171
172 // If we're inserting a terminator, check if we need to flush out
173 // TrailingDbgRecords. Inserting instructions at the end of an incomplete
174 // block is handled by the code block above.
175 if (isTerminator())
176 getParent()->flushTerminatorDbgRecords();
177}
178
179/// Unlink this instruction from its current basic block and insert it into the
180/// basic block that MovePos lives in, right before MovePos.
181void Instruction::moveBefore(BasicBlock::iterator MovePos) {
182 moveBeforeImpl(BB&: *MovePos->getParent(), I: MovePos, Preserve: false);
183}
184
185void Instruction::moveBeforePreserving(BasicBlock::iterator MovePos) {
186 moveBeforeImpl(BB&: *MovePos->getParent(), I: MovePos, Preserve: true);
187}
188
189void Instruction::moveAfter(Instruction *MovePos) {
190 auto NextIt = std::next(x: MovePos->getIterator());
191 // We want this instruction to be moved to after NextIt in the instruction
192 // list, but before NextIt's debug value range.
193 NextIt.setHeadBit(true);
194 moveBeforeImpl(BB&: *MovePos->getParent(), I: NextIt, Preserve: false);
195}
196
197void Instruction::moveAfter(InstListType::iterator MovePos) {
198 // We want this instruction to be moved to after NextIt in the instruction
199 // list, but before NextIt's debug value range.
200 MovePos.setHeadBit(true);
201 moveBeforeImpl(BB&: *MovePos->getParent(), I: MovePos, Preserve: false);
202}
203
204void Instruction::moveAfterPreserving(Instruction *MovePos) {
205 auto NextIt = std::next(x: MovePos->getIterator());
206 // We want this instruction and its debug range to be moved to after NextIt
207 // in the instruction list, but before NextIt's debug value range.
208 NextIt.setHeadBit(true);
209 moveBeforeImpl(BB&: *MovePos->getParent(), I: NextIt, Preserve: true);
210}
211
212void Instruction::moveBefore(BasicBlock &BB, InstListType::iterator I) {
213 moveBeforeImpl(BB, I, Preserve: false);
214}
215
216void Instruction::moveBeforePreserving(BasicBlock &BB,
217 InstListType::iterator I) {
218 moveBeforeImpl(BB, I, Preserve: true);
219}
220
221void Instruction::moveBeforeImpl(BasicBlock &BB, InstListType::iterator I,
222 bool Preserve) {
223 assert(I == BB.end() || I->getParent() == &BB);
224 bool InsertAtHead = I.getHeadBit();
225
226 // If we've been given the "Preserve" flag, then just move the DbgRecords with
227 // the instruction, no more special handling needed.
228 if (DebugMarker && !Preserve) {
229 if (I != this->getIterator() || InsertAtHead) {
230 // "this" is definitely moving in the list, or it's moving ahead of its
231 // attached DbgVariableRecords. Detach any existing DbgRecords.
232 handleMarkerRemoval();
233 }
234 }
235
236 // Move this single instruction. Use the list splice method directly, not
237 // the block splicer, which will do more debug-info things.
238 BB.getInstList().splice(where: I, L2&: getParent()->getInstList(), first: getIterator());
239
240 if (!Preserve) {
241 DbgMarker *NextMarker = getParent()->getNextMarker(I: this);
242
243 // If we're inserting at point I, and not in front of the DbgRecords
244 // attached there, then we should absorb the DbgRecords attached to I.
245 if (!InsertAtHead && NextMarker && !NextMarker->empty()) {
246 adoptDbgRecords(BB: &BB, It: I, InsertAtHead: false);
247 }
248 }
249
250 if (isTerminator())
251 getParent()->flushTerminatorDbgRecords();
252}
253
254iterator_range<DbgRecord::self_iterator> Instruction::cloneDebugInfoFrom(
255 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
256 bool InsertAtHead) {
257 if (!From->DebugMarker)
258 return DbgMarker::getEmptyDbgRecordRange();
259
260 if (!DebugMarker)
261 getParent()->createMarker(I: this);
262
263 return DebugMarker->cloneDebugInfoFrom(From: From->DebugMarker, FromHere,
264 InsertAtHead);
265}
266
267std::optional<DbgRecord::self_iterator>
268Instruction::getDbgReinsertionPosition() {
269 // Is there a marker on the next instruction?
270 DbgMarker *NextMarker = getParent()->getNextMarker(I: this);
271 if (!NextMarker)
272 return std::nullopt;
273
274 // Are there any DbgRecords in the next marker?
275 if (NextMarker->StoredDbgRecords.empty())
276 return std::nullopt;
277
278 return NextMarker->StoredDbgRecords.begin();
279}
280
281bool Instruction::hasDbgRecords() const { return !getDbgRecordRange().empty(); }
282
283void Instruction::adoptDbgRecords(BasicBlock *BB, BasicBlock::iterator It,
284 bool InsertAtHead) {
285 DbgMarker *SrcMarker = BB->getMarker(It);
286 auto ReleaseTrailingDbgRecords = [BB, It, SrcMarker]() {
287 if (BB->end() == It) {
288 SrcMarker->eraseFromParent();
289 BB->deleteTrailingDbgRecords();
290 }
291 };
292
293 if (!SrcMarker || SrcMarker->StoredDbgRecords.empty()) {
294 ReleaseTrailingDbgRecords();
295 return;
296 }
297
298 // If we have DbgMarkers attached to this instruction, we have to honour the
299 // ordering of DbgRecords between this and the other marker. Fall back to just
300 // absorbing from the source.
301 if (DebugMarker || It == BB->end()) {
302 // Ensure we _do_ have a marker.
303 getParent()->createMarker(I: this);
304 DebugMarker->absorbDebugValues(Src&: *SrcMarker, InsertAtHead);
305
306 // Having transferred everything out of SrcMarker, we _could_ clean it up
307 // and free the marker now. However, that's a lot of heap-accounting for a
308 // small amount of memory with a good chance of re-use. Leave it for the
309 // moment. It will be released when the Instruction is freed in the worst
310 // case.
311 // However: if we transferred from a trailing marker off the end of the
312 // block, it's important to not leave the empty marker trailing. It will
313 // give a misleading impression that some debug records have been left
314 // trailing.
315 ReleaseTrailingDbgRecords();
316 } else {
317 // Optimisation: we're transferring all the DbgRecords from the source
318 // marker onto this empty location: just adopt the other instructions
319 // marker.
320 DebugMarker = SrcMarker;
321 DebugMarker->MarkedInstr = this;
322 It->DebugMarker = nullptr;
323 }
324}
325
326void Instruction::dropDbgRecords() {
327 if (DebugMarker)
328 DebugMarker->dropDbgRecords();
329}
330
331void Instruction::dropOneDbgRecord(DbgRecord *DVR) {
332 DebugMarker->dropOneDbgRecord(DR: DVR);
333}
334
335bool Instruction::comesBefore(const Instruction *Other) const {
336 assert(getParent() && Other->getParent() &&
337 "instructions without BB parents have no order");
338 assert(getParent() == Other->getParent() &&
339 "cross-BB instruction order comparison");
340 if (!getParent()->isInstrOrderValid())
341 const_cast<BasicBlock *>(getParent())->renumberInstructions();
342 return Order < Other->Order;
343}
344
345std::optional<BasicBlock::iterator> Instruction::getInsertionPointAfterDef() {
346 assert(!getType()->isVoidTy() && "Instruction must define result");
347 BasicBlock *InsertBB;
348 BasicBlock::iterator InsertPt;
349 if (auto *PN = dyn_cast<PHINode>(Val: this)) {
350 InsertBB = PN->getParent();
351 InsertPt = InsertBB->getFirstInsertionPt();
352 } else if (auto *II = dyn_cast<InvokeInst>(Val: this)) {
353 InsertBB = II->getNormalDest();
354 InsertPt = InsertBB->getFirstInsertionPt();
355 } else if (isa<CallBrInst>(Val: this)) {
356 // Def is available in multiple successors, there's no single dominating
357 // insertion point.
358 return std::nullopt;
359 } else {
360 assert(!isTerminator() && "Only invoke/callbr terminators return value");
361 InsertBB = getParent();
362 InsertPt = std::next(x: getIterator());
363 // Any instruction inserted immediately after "this" will come before any
364 // debug-info records take effect -- thus, set the head bit indicating that
365 // to debug-info-transfer code.
366 InsertPt.setHeadBit(true);
367 }
368
369 // catchswitch blocks don't have any legal insertion point (because they
370 // are both an exception pad and a terminator).
371 if (InsertPt == InsertBB->end())
372 return std::nullopt;
373 return InsertPt;
374}
375
376bool Instruction::isOnlyUserOfAnyOperand() {
377 return any_of(Range: operands(), P: [](const Value *V) { return V->hasOneUser(); });
378}
379
380void Instruction::setHasNoUnsignedWrap(bool b) {
381 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(Val: this))
382 Inst->setHasNoUnsignedWrap(b);
383 else
384 cast<TruncInst>(Val: this)->setHasNoUnsignedWrap(b);
385}
386
387void Instruction::setHasNoSignedWrap(bool b) {
388 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(Val: this))
389 Inst->setHasNoSignedWrap(b);
390 else
391 cast<TruncInst>(Val: this)->setHasNoSignedWrap(b);
392}
393
394void Instruction::setIsExact(bool b) {
395 cast<PossiblyExactOperator>(Val: this)->setIsExact(b);
396}
397
398void Instruction::setNonNeg(bool b) {
399 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
400 SubclassOptionalData = (SubclassOptionalData & ~PossiblyNonNegInst::NonNeg) |
401 (b * PossiblyNonNegInst::NonNeg);
402}
403
404bool Instruction::hasNoUnsignedWrap() const {
405 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(Val: this))
406 return Inst->hasNoUnsignedWrap();
407
408 return cast<TruncInst>(Val: this)->hasNoUnsignedWrap();
409}
410
411bool Instruction::hasNoSignedWrap() const {
412 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(Val: this))
413 return Inst->hasNoSignedWrap();
414
415 return cast<TruncInst>(Val: this)->hasNoSignedWrap();
416}
417
418bool Instruction::hasNonNeg() const {
419 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
420 return (SubclassOptionalData & PossiblyNonNegInst::NonNeg) != 0;
421}
422
423bool Instruction::hasPoisonGeneratingFlags() const {
424 return cast<Operator>(Val: this)->hasPoisonGeneratingFlags();
425}
426
427void Instruction::dropPoisonGeneratingFlags() {
428 switch (getOpcode()) {
429 case Instruction::Add:
430 case Instruction::Sub:
431 case Instruction::Mul:
432 case Instruction::Shl:
433 cast<OverflowingBinaryOperator>(Val: this)->setHasNoUnsignedWrap(false);
434 cast<OverflowingBinaryOperator>(Val: this)->setHasNoSignedWrap(false);
435 break;
436
437 case Instruction::UDiv:
438 case Instruction::SDiv:
439 case Instruction::AShr:
440 case Instruction::LShr:
441 cast<PossiblyExactOperator>(Val: this)->setIsExact(false);
442 break;
443
444 case Instruction::Or:
445 cast<PossiblyDisjointInst>(Val: this)->setIsDisjoint(false);
446 break;
447
448 case Instruction::GetElementPtr:
449 cast<GetElementPtrInst>(Val: this)->setNoWrapFlags(GEPNoWrapFlags::none());
450 break;
451
452 case Instruction::UIToFP:
453 case Instruction::ZExt:
454 setNonNeg(false);
455 break;
456
457 case Instruction::Trunc:
458 cast<TruncInst>(Val: this)->setHasNoUnsignedWrap(false);
459 cast<TruncInst>(Val: this)->setHasNoSignedWrap(false);
460 break;
461
462 case Instruction::ICmp:
463 cast<ICmpInst>(Val: this)->setSameSign(false);
464 break;
465
466 case Instruction::AddrSpaceCast:
467 cast<AddrSpaceCastInst>(Val: this)->setNonNull(false);
468 break;
469
470 case Instruction::Call: {
471 if (auto *II = dyn_cast<IntrinsicInst>(Val: this)) {
472 switch (II->getIntrinsicID()) {
473 case Intrinsic::ctlz:
474 case Intrinsic::cttz:
475 case Intrinsic::abs:
476 II->setOperand(i_nocapture: 1, Val_nocapture: ConstantInt::getFalse(Context&: getContext()));
477 break;
478 }
479 }
480 break;
481 }
482 }
483
484 if (isa<FPMathOperator>(Val: this)) {
485 setHasNoNaNs(false);
486 setHasNoInfs(false);
487 }
488
489 assert(!hasPoisonGeneratingFlags() && "must be kept in sync");
490}
491
492bool Instruction::hasPoisonGeneratingMetadata() const {
493 return any_of(Range: Metadata::PoisonGeneratingIDs,
494 P: [this](unsigned ID) { return hasMetadata(KindID: ID); });
495}
496
497bool Instruction::hasNonDebugLocLoopMetadata() const {
498 // If there is no loop metadata at all, we also don't have
499 // non-debug loop metadata, obviously.
500 if (!hasMetadata(KindID: LLVMContext::MD_loop))
501 return false;
502
503 // If we do have loop metadata, retrieve it.
504 MDNode *LoopMD = getMetadata(KindID: LLVMContext::MD_loop);
505
506 // Check if the existing operands are debug locations. This loop
507 // should terminate after at most three iterations. Skip
508 // the first item because it is a self-reference.
509 for (const MDOperand &Op : llvm::drop_begin(RangeOrContainer: LoopMD->operands())) {
510 // check for debug location type by attempting a cast.
511 if (!isa<DILocation>(Val: Op)) {
512 return true;
513 }
514 }
515
516 // If we get here, then all we have is debug locations in the loop metadata.
517 return false;
518}
519
520void Instruction::dropPoisonGeneratingMetadata() {
521 for (unsigned ID : Metadata::PoisonGeneratingIDs)
522 eraseMetadata(KindID: ID);
523}
524
525bool Instruction::hasPoisonGeneratingAttributes() const {
526 if (const auto *CB = dyn_cast<CallBase>(Val: this)) {
527 auto HasPoisonGeneratingAttributes = [](AttributeSet Attrs) {
528 return Attrs.hasAttribute(Kind: Attribute::Range) ||
529 Attrs.hasAttribute(Kind: Attribute::Alignment) ||
530 Attrs.hasAttribute(Kind: Attribute::NonNull) ||
531 Attrs.hasAttribute(Kind: Attribute::NoFPClass);
532 };
533 if (HasPoisonGeneratingAttributes(CB->getRetAttributes()))
534 return true;
535 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
536 if (HasPoisonGeneratingAttributes(CB->getParamAttributes(ArgNo)))
537 return true;
538 }
539 return false;
540}
541
542void Instruction::dropPoisonGeneratingAttributes() {
543 if (auto *CB = dyn_cast<CallBase>(Val: this)) {
544 AttributeMask AM;
545 AM.addAttribute(Val: Attribute::Range);
546 AM.addAttribute(Val: Attribute::Alignment);
547 AM.addAttribute(Val: Attribute::NonNull);
548 AM.addAttribute(Val: Attribute::NoFPClass);
549 CB->removeRetAttrs(AttrsToRemove: AM);
550 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
551 CB->removeParamAttrs(ArgNo, AttrsToRemove: AM);
552 }
553 assert(!hasPoisonGeneratingAttributes() && "must be kept in sync");
554}
555
556void Instruction::dropUBImplyingAttrsAndUnknownMetadata(
557 ArrayRef<unsigned> KnownIDs) {
558 dropUnknownNonDebugMetadata(KnownIDs);
559 auto *CB = dyn_cast<CallBase>(Val: this);
560 if (!CB)
561 return;
562 // For call instructions, we also need to drop parameter and return attributes
563 // that can cause UB if the call is moved to a location where the attribute is
564 // not valid.
565 AttributeList AL = CB->getAttributes();
566 if (AL.isEmpty())
567 return;
568 AttributeMask UBImplyingAttributes =
569 AttributeFuncs::getUBImplyingAttributes();
570 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
571 CB->removeParamAttrs(ArgNo, AttrsToRemove: UBImplyingAttributes);
572 CB->removeRetAttrs(AttrsToRemove: UBImplyingAttributes);
573}
574
575void Instruction::dropUBImplyingAttrsAndMetadata(ArrayRef<unsigned> Keep) {
576 // !annotation and !prof metadata does not impact semantics.
577 // !range, !nonnull, !align and !nofpclass produce poison, so they are safe to
578 // speculate.
579 // !fpmath specifies floating-point precision and does not imply UB.
580 // !mem.cache_hint is a performance hint and does not imply UB.
581 // !noundef and various AA metadata must be dropped, as it generally produces
582 // immediate undefined behavior.
583 static const unsigned KnownIDs[] = {
584 LLVMContext::MD_annotation, LLVMContext::MD_range,
585 LLVMContext::MD_nonnull, LLVMContext::MD_align,
586 LLVMContext::MD_fpmath, LLVMContext::MD_prof,
587 LLVMContext::MD_mem_cache_hint, LLVMContext::MD_nofpclass};
588 SmallVector<unsigned> KeepIDs;
589 KeepIDs.reserve(N: Keep.size() + std::size(KnownIDs));
590 append_range(C&: KeepIDs, R: KnownIDs);
591 append_range(C&: KeepIDs, R&: Keep);
592 dropUBImplyingAttrsAndUnknownMetadata(KnownIDs: KeepIDs);
593}
594
595bool Instruction::hasUBImplyingAttrs() const {
596 auto *CB = dyn_cast<CallBase>(Val: this);
597 if (!CB)
598 return false;
599 // For call instructions, we also need to check parameter and return
600 // attributes that can cause UB.
601 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
602 if (CB->isPassingUndefUB(ArgNo))
603 return true;
604 return CB->hasRetAttr(Kind: Attribute::NoUndef) ||
605 CB->hasRetAttr(Kind: Attribute::Dereferenceable) ||
606 CB->hasRetAttr(Kind: Attribute::DereferenceableOrNull);
607}
608
609bool Instruction::isExact() const {
610 return cast<PossiblyExactOperator>(Val: this)->isExact();
611}
612
613void Instruction::setFast(bool B) {
614 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
615 cast<FPMathOperator>(Val: this)->setFast(B);
616}
617
618void Instruction::setHasAllowReassoc(bool B) {
619 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
620 cast<FPMathOperator>(Val: this)->setHasAllowReassoc(B);
621}
622
623void Instruction::setHasNoNaNs(bool B) {
624 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
625 cast<FPMathOperator>(Val: this)->setHasNoNaNs(B);
626}
627
628void Instruction::setHasNoInfs(bool B) {
629 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
630 cast<FPMathOperator>(Val: this)->setHasNoInfs(B);
631}
632
633void Instruction::setHasNoSignedZeros(bool B) {
634 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
635 cast<FPMathOperator>(Val: this)->setHasNoSignedZeros(B);
636}
637
638void Instruction::setHasAllowReciprocal(bool B) {
639 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
640 cast<FPMathOperator>(Val: this)->setHasAllowReciprocal(B);
641}
642
643void Instruction::setHasAllowContract(bool B) {
644 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
645 cast<FPMathOperator>(Val: this)->setHasAllowContract(B);
646}
647
648void Instruction::setHasApproxFunc(bool B) {
649 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
650 cast<FPMathOperator>(Val: this)->setHasApproxFunc(B);
651}
652
653void Instruction::setFastMathFlags(FastMathFlags FMF) {
654 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
655 cast<FPMathOperator>(Val: this)->setFastMathFlags(FMF);
656}
657
658void Instruction::copyFastMathFlags(FastMathFlags FMF) {
659 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
660 cast<FPMathOperator>(Val: this)->copyFastMathFlags(FMF);
661}
662
663bool Instruction::isFast() const {
664 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
665 return cast<FPMathOperator>(Val: this)->isFast();
666}
667
668bool Instruction::hasAllowReassoc() const {
669 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
670 return cast<FPMathOperator>(Val: this)->hasAllowReassoc();
671}
672
673bool Instruction::hasNoNaNs() const {
674 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
675 return cast<FPMathOperator>(Val: this)->hasNoNaNs();
676}
677
678bool Instruction::hasNoInfs() const {
679 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
680 return cast<FPMathOperator>(Val: this)->hasNoInfs();
681}
682
683bool Instruction::hasNoSignedZeros() const {
684 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
685 return cast<FPMathOperator>(Val: this)->hasNoSignedZeros();
686}
687
688bool Instruction::hasAllowReciprocal() const {
689 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
690 return cast<FPMathOperator>(Val: this)->hasAllowReciprocal();
691}
692
693bool Instruction::hasAllowContract() const {
694 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
695 return cast<FPMathOperator>(Val: this)->hasAllowContract();
696}
697
698bool Instruction::hasApproxFunc() const {
699 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
700 return cast<FPMathOperator>(Val: this)->hasApproxFunc();
701}
702
703FastMathFlags Instruction::getFastMathFlags() const {
704 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
705 return cast<FPMathOperator>(Val: this)->getFastMathFlags();
706}
707
708FastMathFlags Instruction::getFastMathFlagsOrNone() const {
709 if (!isa<FPMathOperator>(Val: this))
710 return {};
711 return cast<FPMathOperator>(Val: this)->getFastMathFlags();
712}
713
714void Instruction::copyFastMathFlags(const Instruction *I) {
715 copyFastMathFlags(FMF: I->getFastMathFlags());
716}
717
718void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
719 // Copy the wrapping flags.
720 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(Val: this)) {
721 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(Val: V)) {
722 setHasNoSignedWrap(OB->hasNoSignedWrap());
723 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
724 }
725 }
726
727 if (auto *TI = dyn_cast<TruncInst>(Val: V)) {
728 if (isa<TruncInst>(Val: this)) {
729 setHasNoSignedWrap(TI->hasNoSignedWrap());
730 setHasNoUnsignedWrap(TI->hasNoUnsignedWrap());
731 }
732 }
733
734 // Copy the exact flag.
735 if (auto *PE = dyn_cast<PossiblyExactOperator>(Val: V))
736 if (isa<PossiblyExactOperator>(Val: this))
737 setIsExact(PE->isExact());
738
739 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(Val: V))
740 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(Val: this))
741 DestPD->setIsDisjoint(SrcPD->isDisjoint());
742
743 // Copy the fast-math flags.
744 if (auto *FP = dyn_cast<FPMathOperator>(Val: V))
745 if (isa<FPMathOperator>(Val: this))
746 copyFastMathFlags(FMF: FP->getFastMathFlags());
747
748 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(Val: V))
749 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(Val: this))
750 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() |
751 DestGEP->getNoWrapFlags());
752
753 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(Val: V))
754 if (isa<PossiblyNonNegInst>(Val: this))
755 setNonNeg(NNI->hasNonNeg());
756
757 if (auto *SrcICmp = dyn_cast<ICmpInst>(Val: V))
758 if (auto *DestICmp = dyn_cast<ICmpInst>(Val: this))
759 DestICmp->setSameSign(SrcICmp->hasSameSign());
760
761 if (auto *SrcASC = dyn_cast<AddrSpaceCastInst>(Val: V))
762 if (auto *DestASC = dyn_cast<AddrSpaceCastInst>(Val: this)) {
763 assert(DestASC->getSrcAddressSpace() == SrcASC->getSrcAddressSpace() &&
764 "nonull flag cannot be safely preserved with different source "
765 "address spaces");
766 DestASC->setNonNull(SrcASC->hasNonNull());
767 }
768}
769
770void Instruction::andIRFlags(const Value *V) {
771 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(Val: V)) {
772 if (isa<OverflowingBinaryOperator>(Val: this)) {
773 setHasNoSignedWrap(hasNoSignedWrap() && OB->hasNoSignedWrap());
774 setHasNoUnsignedWrap(hasNoUnsignedWrap() && OB->hasNoUnsignedWrap());
775 }
776 }
777
778 if (auto *TI = dyn_cast<TruncInst>(Val: V)) {
779 if (isa<TruncInst>(Val: this)) {
780 setHasNoSignedWrap(hasNoSignedWrap() && TI->hasNoSignedWrap());
781 setHasNoUnsignedWrap(hasNoUnsignedWrap() && TI->hasNoUnsignedWrap());
782 }
783 }
784
785 if (auto *PE = dyn_cast<PossiblyExactOperator>(Val: V))
786 if (isa<PossiblyExactOperator>(Val: this))
787 setIsExact(isExact() && PE->isExact());
788
789 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(Val: V))
790 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(Val: this))
791 DestPD->setIsDisjoint(DestPD->isDisjoint() && SrcPD->isDisjoint());
792
793 if (auto *FP = dyn_cast<FPMathOperator>(Val: V)) {
794 if (isa<FPMathOperator>(Val: this)) {
795 FastMathFlags FM = getFastMathFlags();
796 FM &= FP->getFastMathFlags();
797 copyFastMathFlags(FMF: FM);
798 }
799 }
800
801 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(Val: V))
802 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(Val: this))
803 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() &
804 DestGEP->getNoWrapFlags());
805
806 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(Val: V))
807 if (isa<PossiblyNonNegInst>(Val: this))
808 setNonNeg(hasNonNeg() && NNI->hasNonNeg());
809
810 if (auto *SrcICmp = dyn_cast<ICmpInst>(Val: V))
811 if (auto *DestICmp = dyn_cast<ICmpInst>(Val: this))
812 DestICmp->setSameSign(DestICmp->hasSameSign() && SrcICmp->hasSameSign());
813
814 if (auto *SrcASC = dyn_cast<AddrSpaceCastInst>(Val: V))
815 if (auto *DestASC = dyn_cast<AddrSpaceCastInst>(Val: this)) {
816 assert(DestASC->getSrcAddressSpace() == SrcASC->getSrcAddressSpace() &&
817 "nonull flag cannot be safely preserved with different source "
818 "address spaces");
819 DestASC->setNonNull(DestASC->hasNonNull() && SrcASC->hasNonNull());
820 }
821}
822
823const char *Instruction::getOpcodeName(unsigned OpCode) {
824 // clang-format off
825 switch (OpCode) {
826 // Terminators
827 case Ret: return "ret";
828 case UncondBr: return "br";
829 case CondBr: return "br";
830 case Switch: return "switch";
831 case IndirectBr: return "indirectbr";
832 case Invoke: return "invoke";
833 case Resume: return "resume";
834 case Unreachable: return "unreachable";
835 case CleanupRet: return "cleanupret";
836 case CatchRet: return "catchret";
837 case CatchPad: return "catchpad";
838 case CatchSwitch: return "catchswitch";
839 case CallBr: return "callbr";
840
841 // Standard unary operators...
842 case FNeg: return "fneg";
843
844 // Standard binary operators...
845 case Add: return "add";
846 case FAdd: return "fadd";
847 case Sub: return "sub";
848 case FSub: return "fsub";
849 case Mul: return "mul";
850 case FMul: return "fmul";
851 case UDiv: return "udiv";
852 case SDiv: return "sdiv";
853 case FDiv: return "fdiv";
854 case URem: return "urem";
855 case SRem: return "srem";
856 case FRem: return "frem";
857
858 // Logical operators...
859 case And: return "and";
860 case Or : return "or";
861 case Xor: return "xor";
862
863 // Memory instructions...
864 case Alloca: return "alloca";
865 case Load: return "load";
866 case Store: return "store";
867 case AtomicCmpXchg: return "cmpxchg";
868 case AtomicRMW: return "atomicrmw";
869 case Fence: return "fence";
870 case GetElementPtr: return "getelementptr";
871
872 // Convert instructions...
873 case Trunc: return "trunc";
874 case ZExt: return "zext";
875 case SExt: return "sext";
876 case FPTrunc: return "fptrunc";
877 case FPExt: return "fpext";
878 case FPToUI: return "fptoui";
879 case FPToSI: return "fptosi";
880 case UIToFP: return "uitofp";
881 case SIToFP: return "sitofp";
882 case IntToPtr: return "inttoptr";
883 case PtrToAddr: return "ptrtoaddr";
884 case PtrToInt: return "ptrtoint";
885 case BitCast: return "bitcast";
886 case AddrSpaceCast: return "addrspacecast";
887
888 // Other instructions...
889 case ICmp: return "icmp";
890 case FCmp: return "fcmp";
891 case PHI: return "phi";
892 case Select: return "select";
893 case Call: return "call";
894 case Shl: return "shl";
895 case LShr: return "lshr";
896 case AShr: return "ashr";
897 case VAArg: return "va_arg";
898 case ExtractElement: return "extractelement";
899 case InsertElement: return "insertelement";
900 case ShuffleVector: return "shufflevector";
901 case ExtractValue: return "extractvalue";
902 case InsertValue: return "insertvalue";
903 case LandingPad: return "landingpad";
904 case CleanupPad: return "cleanuppad";
905 case Freeze: return "freeze";
906 case BitInsert: return "bitinsert";
907 case BitExtract: return "bitextract";
908
909 default: return "<Invalid operator> ";
910 }
911 // clang-format on
912}
913
914/// This must be kept in sync with FunctionComparator::cmpOperations in
915/// lib/Transforms/Utils/FunctionComparator.cpp.
916bool Instruction::hasSameSpecialState(const Instruction *I2,
917 bool IgnoreAlignment,
918 bool IntersectAttrs) const {
919 const auto *I1 = this;
920 assert(I1->getOpcode() == I2->getOpcode() &&
921 "Can not compare special state of different instructions");
922
923 auto CheckAttrsSame = [IntersectAttrs](const CallBase *CB0,
924 const CallBase *CB1) {
925 return IntersectAttrs
926 ? CB0->getAttributes()
927 .intersectWith(C&: CB0->getContext(), Other: CB1->getAttributes())
928 .has_value()
929 : CB0->getAttributes() == CB1->getAttributes();
930 };
931
932 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: I1))
933 return AI->getAllocatedType() == cast<AllocaInst>(Val: I2)->getAllocatedType() &&
934 (AI->getAlign() == cast<AllocaInst>(Val: I2)->getAlign() ||
935 IgnoreAlignment);
936 if (const LoadInst *LI = dyn_cast<LoadInst>(Val: I1))
937 return LI->isVolatile() == cast<LoadInst>(Val: I2)->isVolatile() &&
938 LI->isElementwise() == cast<LoadInst>(Val: I2)->isElementwise() &&
939 (LI->getAlign() == cast<LoadInst>(Val: I2)->getAlign() ||
940 IgnoreAlignment) &&
941 LI->getOrdering() == cast<LoadInst>(Val: I2)->getOrdering() &&
942 LI->getSyncScopeID() == cast<LoadInst>(Val: I2)->getSyncScopeID();
943 if (const StoreInst *SI = dyn_cast<StoreInst>(Val: I1))
944 return SI->isVolatile() == cast<StoreInst>(Val: I2)->isVolatile() &&
945 SI->isElementwise() == cast<StoreInst>(Val: I2)->isElementwise() &&
946 (SI->getAlign() == cast<StoreInst>(Val: I2)->getAlign() ||
947 IgnoreAlignment) &&
948 SI->getOrdering() == cast<StoreInst>(Val: I2)->getOrdering() &&
949 SI->getSyncScopeID() == cast<StoreInst>(Val: I2)->getSyncScopeID();
950 if (const CmpInst *CI = dyn_cast<CmpInst>(Val: I1))
951 return CI->getPredicate() == cast<CmpInst>(Val: I2)->getPredicate();
952 if (const CallInst *CI = dyn_cast<CallInst>(Val: I1))
953 return CI->isTailCall() == cast<CallInst>(Val: I2)->isTailCall() &&
954 CI->getCallingConv() == cast<CallInst>(Val: I2)->getCallingConv() &&
955 CI->getFunctionType() == cast<CallInst>(Val: I2)->getFunctionType() &&
956 CheckAttrsSame(CI, cast<CallInst>(Val: I2)) &&
957 CI->hasIdenticalOperandBundleSchema(Other: *cast<CallInst>(Val: I2));
958 if (const InvokeInst *CI = dyn_cast<InvokeInst>(Val: I1))
959 return CI->getCallingConv() == cast<InvokeInst>(Val: I2)->getCallingConv() &&
960 CI->getFunctionType() == cast<InvokeInst>(Val: I2)->getFunctionType() &&
961 CheckAttrsSame(CI, cast<InvokeInst>(Val: I2)) &&
962 CI->hasIdenticalOperandBundleSchema(Other: *cast<InvokeInst>(Val: I2));
963 if (const CallBrInst *CI = dyn_cast<CallBrInst>(Val: I1))
964 return CI->getCallingConv() == cast<CallBrInst>(Val: I2)->getCallingConv() &&
965 CI->getFunctionType() == cast<CallBrInst>(Val: I2)->getFunctionType() &&
966 CheckAttrsSame(CI, cast<CallBrInst>(Val: I2)) &&
967 CI->hasIdenticalOperandBundleSchema(Other: *cast<CallBrInst>(Val: I2));
968 if (const SwitchInst *SI = dyn_cast<SwitchInst>(Val: I1)) {
969 for (auto [Case1, Case2] : zip(t: SI->cases(), u: cast<SwitchInst>(Val: I2)->cases()))
970 if (Case1.getCaseValue() != Case2.getCaseValue())
971 return false;
972 return true;
973 }
974 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Val: I1))
975 return IVI->getIndices() == cast<InsertValueInst>(Val: I2)->getIndices();
976 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val: I1))
977 return EVI->getIndices() == cast<ExtractValueInst>(Val: I2)->getIndices();
978 if (const FenceInst *FI = dyn_cast<FenceInst>(Val: I1))
979 return FI->getOrdering() == cast<FenceInst>(Val: I2)->getOrdering() &&
980 FI->getSyncScopeID() == cast<FenceInst>(Val: I2)->getSyncScopeID();
981 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(Val: I1))
982 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(Val: I2)->isVolatile() &&
983 (CXI->getAlign() == cast<AtomicCmpXchgInst>(Val: I2)->getAlign() ||
984 IgnoreAlignment) &&
985 CXI->isWeak() == cast<AtomicCmpXchgInst>(Val: I2)->isWeak() &&
986 CXI->getSuccessOrdering() ==
987 cast<AtomicCmpXchgInst>(Val: I2)->getSuccessOrdering() &&
988 CXI->getFailureOrdering() ==
989 cast<AtomicCmpXchgInst>(Val: I2)->getFailureOrdering() &&
990 CXI->getSyncScopeID() ==
991 cast<AtomicCmpXchgInst>(Val: I2)->getSyncScopeID();
992 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(Val: I1))
993 return RMWI->getOperation() == cast<AtomicRMWInst>(Val: I2)->getOperation() &&
994 RMWI->isElementwise() == cast<AtomicRMWInst>(Val: I2)->isElementwise() &&
995 RMWI->isVolatile() == cast<AtomicRMWInst>(Val: I2)->isVolatile() &&
996 (RMWI->getAlign() == cast<AtomicRMWInst>(Val: I2)->getAlign() ||
997 IgnoreAlignment) &&
998 RMWI->getOrdering() == cast<AtomicRMWInst>(Val: I2)->getOrdering() &&
999 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(Val: I2)->getSyncScopeID();
1000 if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Val: I1))
1001 return SVI->getShuffleMask() ==
1002 cast<ShuffleVectorInst>(Val: I2)->getShuffleMask();
1003 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: I1))
1004 return GEP->getSourceElementType() ==
1005 cast<GetElementPtrInst>(Val: I2)->getSourceElementType();
1006 if (const LandingPadInst *LP = dyn_cast<LandingPadInst>(Val: I1))
1007 return LP->isCleanup() == cast<LandingPadInst>(Val: I2)->isCleanup();
1008
1009 return true;
1010}
1011
1012bool Instruction::isIdenticalTo(const Instruction *I) const {
1013 if (!isIdenticalToWhenDefined(I) ||
1014 SubclassOptionalData != I->SubclassOptionalData)
1015 return false;
1016
1017 if (isa<FPMathOperator>(Val: this))
1018 return getFastMathFlags() == I->getFastMathFlags();
1019
1020 return true;
1021}
1022
1023bool Instruction::isIdenticalToWhenDefined(const Instruction *I,
1024 bool IntersectAttrs) const {
1025 if (getOpcode() != I->getOpcode() ||
1026 getNumOperands() != I->getNumOperands() || getType() != I->getType())
1027 return false;
1028
1029 // If both instructions have no operands, they are identical.
1030 if (getNumOperands() == 0 && I->getNumOperands() == 0)
1031 return this->hasSameSpecialState(I2: I, /*IgnoreAlignment=*/false,
1032 IntersectAttrs);
1033
1034 // We have two instructions of identical opcode and #operands. Check to see
1035 // if all operands are the same.
1036 if (!equal(LRange: operands(), RRange: I->operands()))
1037 return false;
1038
1039 // WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()!
1040 if (const PHINode *Phi = dyn_cast<PHINode>(Val: this)) {
1041 const PHINode *OtherPhi = cast<PHINode>(Val: I);
1042 return equal(LRange: Phi->blocks(), RRange: OtherPhi->blocks());
1043 }
1044
1045 return this->hasSameSpecialState(I2: I, /*IgnoreAlignment=*/false,
1046 IntersectAttrs);
1047}
1048
1049// Keep this in sync with FunctionComparator::cmpOperations in
1050// lib/Transforms/IPO/MergeFunctions.cpp.
1051bool Instruction::isSameOperationAs(const Instruction *I,
1052 unsigned flags) const {
1053 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
1054 bool UseScalarTypes = flags & CompareUsingScalarTypes;
1055 bool IntersectAttrs = flags & CompareUsingIntersectedAttrs;
1056 bool CheckCallTargets = flags & CompareCallTargets;
1057
1058 if (getOpcode() != I->getOpcode() ||
1059 getNumOperands() != I->getNumOperands() ||
1060 (UseScalarTypes ?
1061 getType()->getScalarType() != I->getType()->getScalarType() :
1062 getType() != I->getType()))
1063 return false;
1064
1065 // We have two instructions of identical opcode and #operands. Check to see
1066 // if all operands are the same type
1067 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1068 if (UseScalarTypes ?
1069 getOperand(i)->getType()->getScalarType() !=
1070 I->getOperand(i)->getType()->getScalarType() :
1071 getOperand(i)->getType() != I->getOperand(i)->getType())
1072 return false;
1073
1074 if (CheckCallTargets)
1075 if (const auto *CB = dyn_cast<CallBase>(Val: this))
1076 if (CB->getCalledOperand() != cast<CallBase>(Val: I)->getCalledOperand())
1077 return false;
1078
1079 return this->hasSameSpecialState(I2: I, IgnoreAlignment, IntersectAttrs);
1080}
1081
1082bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
1083 for (const Use &U : uses()) {
1084 // PHI nodes uses values in the corresponding predecessor block. For other
1085 // instructions, just check to see whether the parent of the use matches up.
1086 const Instruction *I = cast<Instruction>(Val: U.getUser());
1087 const PHINode *PN = dyn_cast<PHINode>(Val: I);
1088 if (!PN) {
1089 if (I->getParent() != BB)
1090 return true;
1091 continue;
1092 }
1093
1094 if (PN->getIncomingBlock(U) != BB)
1095 return true;
1096 }
1097 return false;
1098}
1099
1100MemoryEffects Instruction::getMemoryEffects() const {
1101 auto GetEffects = [](ModRefInfo BaseMR, AtomicOrdering Ordering,
1102 bool IsVolatile) {
1103 if (isStrongerThanMonotonic(AO: Ordering))
1104 return MemoryEffects::unknown();
1105
1106 if (IsVolatile)
1107 return MemoryEffects::inaccessibleOrArgMemOnly();
1108
1109 if (isStrongerThanUnordered(AO: Ordering))
1110 return MemoryEffects::argMemOnly();
1111
1112 return MemoryEffects::argMemOnly(MR: BaseMR);
1113 };
1114 switch (getOpcode()) {
1115 default:
1116 return MemoryEffects::none();
1117 case Instruction::VAArg:
1118 return MemoryEffects::argMemOnly();
1119 case Instruction::CatchPad:
1120 case Instruction::CatchRet:
1121 case Instruction::Fence:
1122 return MemoryEffects::unknown();
1123 case Instruction::Call:
1124 case Instruction::Invoke:
1125 case Instruction::CallBr:
1126 return cast<CallBase>(Val: this)->getMemoryEffects();
1127 case Instruction::Load: {
1128 auto *LI = cast<LoadInst>(Val: this);
1129 return GetEffects(ModRefInfo::Ref, LI->getOrdering(), LI->isVolatile());
1130 }
1131 case Instruction::Store: {
1132 auto *SI = cast<StoreInst>(Val: this);
1133 return GetEffects(ModRefInfo::Mod, SI->getOrdering(), SI->isVolatile());
1134 }
1135 case Instruction::AtomicRMW: {
1136 auto *RMW = cast<AtomicRMWInst>(Val: this);
1137 return GetEffects(ModRefInfo::ModRef, RMW->getOrdering(),
1138 RMW->isVolatile());
1139 }
1140 case Instruction::AtomicCmpXchg: {
1141 auto *CX = cast<AtomicCmpXchgInst>(Val: this);
1142 return GetEffects(ModRefInfo::ModRef, CX->getMergedOrdering(),
1143 CX->isVolatile());
1144 }
1145 }
1146}
1147
1148// This is duplicating the logic from getMemoryEffects() for performance
1149// reasons. Computing the full MemoryEffects just to perform a Mod/Ref check
1150// is expensive.
1151
1152bool Instruction::mayReadFromMemory() const {
1153 switch (getOpcode()) {
1154 default: return false;
1155 case Instruction::VAArg:
1156 case Instruction::Load:
1157 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
1158 case Instruction::AtomicCmpXchg:
1159 case Instruction::AtomicRMW:
1160 case Instruction::CatchPad:
1161 case Instruction::CatchRet:
1162 return true;
1163 case Instruction::Call:
1164 case Instruction::Invoke:
1165 case Instruction::CallBr:
1166 return !cast<CallBase>(Val: this)->onlyWritesMemory();
1167 case Instruction::Store:
1168 return !cast<StoreInst>(Val: this)->isUnordered();
1169 }
1170}
1171
1172bool Instruction::mayWriteToMemory() const {
1173 switch (getOpcode()) {
1174 default: return false;
1175 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
1176 case Instruction::Store:
1177 case Instruction::VAArg:
1178 case Instruction::AtomicCmpXchg:
1179 case Instruction::AtomicRMW:
1180 case Instruction::CatchPad:
1181 case Instruction::CatchRet:
1182 return true;
1183 case Instruction::Call:
1184 case Instruction::Invoke:
1185 case Instruction::CallBr:
1186 return !cast<CallBase>(Val: this)->onlyReadsMemory();
1187 case Instruction::Load:
1188 return !cast<LoadInst>(Val: this)->isUnordered();
1189 }
1190}
1191
1192bool Instruction::isAtomic() const {
1193 switch (getOpcode()) {
1194 default:
1195 return false;
1196 case Instruction::AtomicCmpXchg:
1197 case Instruction::AtomicRMW:
1198 case Instruction::Fence:
1199 return true;
1200 case Instruction::Load:
1201 return cast<LoadInst>(Val: this)->getOrdering() != AtomicOrdering::NotAtomic;
1202 case Instruction::Store:
1203 return cast<StoreInst>(Val: this)->getOrdering() != AtomicOrdering::NotAtomic;
1204 }
1205}
1206
1207bool Instruction::hasAtomicLoad() const {
1208 assert(isAtomic());
1209 switch (getOpcode()) {
1210 default:
1211 return false;
1212 case Instruction::AtomicCmpXchg:
1213 case Instruction::AtomicRMW:
1214 case Instruction::Load:
1215 return true;
1216 }
1217}
1218
1219bool Instruction::hasAtomicStore() const {
1220 assert(isAtomic());
1221 switch (getOpcode()) {
1222 default:
1223 return false;
1224 case Instruction::AtomicCmpXchg:
1225 case Instruction::AtomicRMW:
1226 case Instruction::Store:
1227 return true;
1228 }
1229}
1230
1231bool Instruction::isVolatile() const {
1232 switch (getOpcode()) {
1233 default:
1234 return false;
1235 case Instruction::AtomicRMW:
1236 return cast<AtomicRMWInst>(Val: this)->isVolatile();
1237 case Instruction::Store:
1238 return cast<StoreInst>(Val: this)->isVolatile();
1239 case Instruction::Load:
1240 return cast<LoadInst>(Val: this)->isVolatile();
1241 case Instruction::AtomicCmpXchg:
1242 return cast<AtomicCmpXchgInst>(Val: this)->isVolatile();
1243 case Instruction::Call:
1244 case Instruction::Invoke:
1245 // There are a very limited number of intrinsics with volatile flags.
1246 if (auto *II = dyn_cast<IntrinsicInst>(Val: this)) {
1247 if (auto *MI = dyn_cast<MemIntrinsic>(Val: II))
1248 return MI->isVolatile();
1249 switch (II->getIntrinsicID()) {
1250 default: break;
1251 case Intrinsic::matrix_column_major_load:
1252 return cast<ConstantInt>(Val: II->getArgOperand(i: 2))->isOne();
1253 case Intrinsic::matrix_column_major_store:
1254 return cast<ConstantInt>(Val: II->getArgOperand(i: 3))->isOne();
1255 }
1256 }
1257 return false;
1258 }
1259}
1260
1261bool Instruction::maySynchronize() const {
1262 switch (getOpcode()) {
1263 default:
1264 assert(!isAtomic() && "Unhandled atomic instruction");
1265 return false;
1266 case Instruction::Fence: {
1267 // All legal orderings for fence are stronger than monotonic.
1268 auto *FI = cast<FenceInst>(Val: this);
1269 return FI->getSyncScopeID() != SyncScope::SingleThread;
1270 }
1271 case Instruction::AtomicRMW:
1272 return isStrongerThanMonotonic(AO: cast<AtomicRMWInst>(Val: this)->getOrdering());
1273 case Instruction::AtomicCmpXchg: {
1274 auto *ACXI = cast<AtomicCmpXchgInst>(Val: this);
1275 return isStrongerThanMonotonic(AO: ACXI->getSuccessOrdering()) ||
1276 isStrongerThanMonotonic(AO: ACXI->getFailureOrdering());
1277 }
1278 case Instruction::Store:
1279 return isStrongerThanMonotonic(AO: cast<StoreInst>(Val: this)->getOrdering());
1280 case Instruction::Load:
1281 return isStrongerThanMonotonic(AO: cast<LoadInst>(Val: this)->getOrdering());
1282 case Instruction::Call:
1283 case Instruction::Invoke:
1284 case Instruction::CallBr:
1285 return !cast<CallBase>(Val: this)->hasFnAttr(Kind: Attribute::NoSync);
1286 }
1287}
1288
1289Type *Instruction::getAccessType() const {
1290 switch (getOpcode()) {
1291 case Instruction::Store:
1292 return cast<StoreInst>(Val: this)->getValueOperand()->getType();
1293 case Instruction::Load:
1294 case Instruction::AtomicRMW:
1295 return getType();
1296 case Instruction::AtomicCmpXchg:
1297 return cast<AtomicCmpXchgInst>(Val: this)->getNewValOperand()->getType();
1298 case Instruction::Call:
1299 case Instruction::Invoke:
1300 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: this)) {
1301 switch (II->getIntrinsicID()) {
1302 case Intrinsic::masked_load:
1303 case Intrinsic::masked_gather:
1304 case Intrinsic::masked_expandload:
1305 case Intrinsic::vp_load:
1306 case Intrinsic::vp_gather:
1307 case Intrinsic::experimental_vp_strided_load:
1308 return II->getType();
1309 case Intrinsic::masked_store:
1310 case Intrinsic::masked_scatter:
1311 case Intrinsic::masked_compressstore:
1312 case Intrinsic::vp_store:
1313 case Intrinsic::vp_scatter:
1314 case Intrinsic::experimental_vp_strided_store:
1315 return II->getOperand(i_nocapture: 0)->getType();
1316 default:
1317 break;
1318 }
1319 }
1320 }
1321
1322 return nullptr;
1323}
1324
1325static bool canUnwindPastLandingPad(const LandingPadInst *LP,
1326 bool IncludePhaseOneUnwind) {
1327 // Because phase one unwinding skips cleanup landingpads, we effectively
1328 // unwind past this frame, and callers need to have valid unwind info.
1329 if (LP->isCleanup())
1330 return IncludePhaseOneUnwind;
1331
1332 for (unsigned I = 0; I < LP->getNumClauses(); ++I) {
1333 Constant *Clause = LP->getClause(Idx: I);
1334 // catch ptr null catches all exceptions.
1335 if (LP->isCatch(Idx: I) && isa<ConstantPointerNull>(Val: Clause))
1336 return false;
1337 // filter [0 x ptr] catches all exceptions.
1338 if (LP->isFilter(Idx: I) && Clause->getType()->getArrayNumElements() == 0)
1339 return false;
1340 }
1341
1342 // May catch only some subset of exceptions, in which case other exceptions
1343 // will continue unwinding.
1344 return true;
1345}
1346
1347bool Instruction::mayThrow(bool IncludePhaseOneUnwind) const {
1348 switch (getOpcode()) {
1349 case Instruction::Call:
1350 return !cast<CallInst>(Val: this)->doesNotThrow();
1351 case Instruction::CleanupRet:
1352 return cast<CleanupReturnInst>(Val: this)->unwindsToCaller();
1353 case Instruction::CatchSwitch:
1354 return cast<CatchSwitchInst>(Val: this)->unwindsToCaller();
1355 case Instruction::Resume:
1356 return true;
1357 case Instruction::Invoke: {
1358 // Landingpads themselves don't unwind -- however, an invoke of a skipped
1359 // landingpad may continue unwinding.
1360 BasicBlock *UnwindDest = cast<InvokeInst>(Val: this)->getUnwindDest();
1361 BasicBlock::iterator Pad = UnwindDest->getFirstNonPHIIt();
1362 if (auto *LP = dyn_cast<LandingPadInst>(Val&: Pad))
1363 return canUnwindPastLandingPad(LP, IncludePhaseOneUnwind);
1364 return false;
1365 }
1366 case Instruction::CleanupPad:
1367 // Treat the same as cleanup landingpad.
1368 return IncludePhaseOneUnwind;
1369 default:
1370 return false;
1371 }
1372}
1373
1374bool Instruction::mayHaveSideEffects() const {
1375 return mayWriteToMemory() || mayThrow() || !willReturn();
1376}
1377
1378bool Instruction::isSafeToRemove() const {
1379 return (!isa<CallInst>(Val: this) || !this->mayHaveSideEffects()) &&
1380 !this->isTerminator() && !this->isEHPad();
1381}
1382
1383bool Instruction::willReturn() const {
1384 // Volatile operations are not guaranteed to return.
1385 if (isVolatile())
1386 return false;
1387
1388 if (const auto *CB = dyn_cast<CallBase>(Val: this))
1389 return CB->hasFnAttr(Kind: Attribute::WillReturn);
1390 return true;
1391}
1392
1393bool Instruction::isLifetimeStartOrEnd() const {
1394 auto *II = dyn_cast<IntrinsicInst>(Val: this);
1395 if (!II)
1396 return false;
1397 Intrinsic::ID ID = II->getIntrinsicID();
1398 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
1399}
1400
1401const DebugLoc &Instruction::getStableDebugLoc() const {
1402 return getDebugLoc();
1403}
1404
1405bool Instruction::isAssociative() const {
1406 if (auto *II = dyn_cast<IntrinsicInst>(Val: this))
1407 return II->isAssociative();
1408 unsigned Opcode = getOpcode();
1409 if (isAssociative(Opcode))
1410 return true;
1411
1412 switch (Opcode) {
1413 case FMul:
1414 return cast<FPMathOperator>(Val: this)->hasAllowReassoc();
1415 case FAdd:
1416 return cast<FPMathOperator>(Val: this)->hasAllowReassoc() &&
1417 cast<FPMathOperator>(Val: this)->hasNoSignedZeros();
1418 default:
1419 return false;
1420 }
1421}
1422
1423bool Instruction::isCommutative() const {
1424 if (auto *II = dyn_cast<IntrinsicInst>(Val: this))
1425 return II->isCommutative();
1426 // TODO: Should allow icmp/fcmp?
1427 return isCommutative(Opcode: getOpcode());
1428}
1429
1430bool Instruction::isCommutableOperand(unsigned Op) const {
1431 if (auto *II = dyn_cast<IntrinsicInst>(Val: this))
1432 return II->isCommutableOperand(Op);
1433 // TODO: Should allow icmp/fcmp?
1434 return isCommutative(Opcode: getOpcode());
1435}
1436
1437unsigned Instruction::getNumSuccessors() const {
1438 switch (getOpcode()) {
1439#define HANDLE_TERM_INST(N, OPC, CLASS) \
1440 case Instruction::OPC: \
1441 return static_cast<const CLASS *>(this)->getNumSuccessors();
1442#include "llvm/IR/Instruction.def"
1443 default:
1444 break;
1445 }
1446 llvm_unreachable("not a terminator");
1447}
1448
1449BasicBlock *Instruction::getSuccessor(unsigned idx) const {
1450 switch (getOpcode()) {
1451#define HANDLE_TERM_INST(N, OPC, CLASS) \
1452 case Instruction::OPC: \
1453 return static_cast<const CLASS *>(this)->getSuccessor(idx);
1454#include "llvm/IR/Instruction.def"
1455 default:
1456 break;
1457 }
1458 llvm_unreachable("not a terminator");
1459}
1460
1461void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {
1462 switch (getOpcode()) {
1463#define HANDLE_TERM_INST(N, OPC, CLASS) \
1464 case Instruction::OPC: \
1465 return static_cast<CLASS *>(this)->setSuccessor(idx, B);
1466#include "llvm/IR/Instruction.def"
1467 default:
1468 break;
1469 }
1470 llvm_unreachable("not a terminator");
1471}
1472
1473iterator_range<Instruction::const_succ_iterator>
1474Instruction::successors() const {
1475 switch (getOpcode()) {
1476#define HANDLE_TERM_INST(N, OPC, CLASS) \
1477 case Instruction::OPC: \
1478 return static_cast<const CLASS *>(this)->successors();
1479#include "llvm/IR/Instruction.def"
1480 default:
1481 break;
1482 }
1483 llvm_unreachable("not a terminator");
1484}
1485
1486void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) {
1487 auto Succs = successors();
1488 for (auto I = Succs.begin(), E = Succs.end(); I != E; ++I)
1489 if (*I == OldBB)
1490 I.getUse()->set(NewBB);
1491}
1492
1493Instruction *Instruction::cloneImpl() const {
1494 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
1495}
1496
1497void Instruction::swapProfMetadata() {
1498 MDNode *ProfileData = getBranchWeightMDNode(I: *this);
1499 if (!ProfileData)
1500 return;
1501 unsigned FirstIdx = getBranchWeightOffset(ProfileData);
1502 if (ProfileData->getNumOperands() != 2 + FirstIdx)
1503 return;
1504
1505 unsigned SecondIdx = FirstIdx + 1;
1506 SmallVector<Metadata *, 4> Ops;
1507 // If there are more weights past the second, we can't swap them
1508 if (ProfileData->getNumOperands() > SecondIdx + 1)
1509 return;
1510 for (unsigned Idx = 0; Idx < FirstIdx; ++Idx) {
1511 Ops.push_back(Elt: ProfileData->getOperand(I: Idx));
1512 }
1513 // Switch the order of the weights
1514 Ops.push_back(Elt: ProfileData->getOperand(I: SecondIdx));
1515 Ops.push_back(Elt: ProfileData->getOperand(I: FirstIdx));
1516 setMetadata(KindID: LLVMContext::MD_prof,
1517 Node: MDNode::get(Context&: ProfileData->getContext(), MDs: Ops));
1518}
1519
1520void Instruction::copyProfileAndDebugMetadata(const Instruction &SrcInst) {
1521 // TODO: Include additional metadata in the future if appropriate.
1522 static const unsigned SafeIDs[] = {
1523 LLVMContext::MD_dbg, LLVMContext::MD_prof, LLVMContext::MD_memprof,
1524 LLVMContext::MD_callsite};
1525 copyMetadata(SrcInst, WL: SafeIDs);
1526}
1527
1528void Instruction::copyMetadata(const Instruction &SrcInst,
1529 ArrayRef<unsigned> WL) {
1530 if (WL.empty() || is_contained(Range&: WL, Element: LLVMContext::MD_dbg))
1531 setDebugLoc(SrcInst.getDebugLoc().orElse(Other: getDebugLoc()));
1532
1533 if (!SrcInst.hasMetadata())
1534 return;
1535
1536 SmallDenseSet<unsigned, 4> WLS(WL.begin(), WL.end());
1537
1538 // Otherwise, enumerate and copy over metadata from the old instruction to the
1539 // new one.
1540 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
1541 SrcInst.getAllMetadataOtherThanDebugLoc(MDs&: TheMDs);
1542 for (const auto &MD : TheMDs) {
1543 if (WL.empty() || WLS.count(V: MD.first))
1544 setMetadata(KindID: MD.first, Node: MD.second);
1545 }
1546}
1547
1548Instruction *Instruction::clone() const {
1549 Instruction *New = nullptr;
1550 switch (getOpcode()) {
1551 default:
1552 llvm_unreachable("Unhandled Opcode.");
1553#define HANDLE_INST(num, opc, clas) \
1554 case Instruction::opc: \
1555 New = cast<clas>(this)->cloneImpl(); \
1556 break;
1557#include "llvm/IR/Instruction.def"
1558#undef HANDLE_INST
1559 }
1560
1561 New->SubclassOptionalData = SubclassOptionalData;
1562 New->copyMetadata(SrcInst: *this);
1563 return New;
1564}
1565