LLVM 22.0.0git
Instruction.cpp
Go to the documentation of this file.
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"
17#include "llvm/IR/Attributes.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/InstrTypes.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/Operator.h"
28#include "llvm/IR/Type.h"
31using namespace llvm;
32
33// FIXME: Flag used for an ablation performance test, Issue #147390. Placing it
34// here because referencing IR should be feasible from anywhere. Will be
35// removed after the ablation test.
37 "profcheck-disable-metadata-fixes", cl::Hidden, cl::init(false),
39 "Disable metadata propagation fixes discovered through Issue #147390"));
40
41InsertPosition::InsertPosition(Instruction *InsertBefore)
42 : InsertAt(InsertBefore ? InsertBefore->getIterator()
43 : InstListType::iterator()) {}
44InsertPosition::InsertPosition(BasicBlock *InsertAtEnd)
45 : InsertAt(InsertAtEnd ? InsertAtEnd->end() : InstListType::iterator()) {}
46
47Instruction::Instruction(Type *ty, unsigned it, AllocInfo AllocInfo,
48 InsertPosition InsertBefore)
49 : User(ty, Value::InstructionVal + it, AllocInfo) {
50 // When called with an iterator, there must be a block to insert into.
51 if (InstListType::iterator InsertIt = InsertBefore; InsertIt.isValid()) {
52 BasicBlock *BB = InsertIt.getNodeParent();
53 assert(BB && "Instruction to insert before is not in a basic block!");
54 insertInto(BB, InsertBefore);
55 }
56}
57
58Instruction::~Instruction() {
59 assert(!getParent() && "Instruction still linked in the program!");
60
61 // Replace any extant metadata uses of this instruction with poison to
62 // preserve debug info accuracy. Some alternatives include:
63 // - Treat Instruction like any other Value, and point its extant metadata
64 // uses to an empty ValueAsMetadata node. This makes extant dbg.value uses
65 // trivially dead (i.e. fair game for deletion in many passes), leading to
66 // stale dbg.values being in effect for too long.
67 // - Call salvageDebugInfoOrMarkUndef. Not needed to make instruction removal
68 // correct. OTOH results in wasted work in some common cases (e.g. when all
69 // instructions in a BasicBlock are deleted).
70 if (isUsedByMetadata())
71 ValueAsMetadata::handleRAUW(this, PoisonValue::get(getType()));
72
73 // Explicitly remove DIAssignID metadata to clear up ID -> Instruction(s)
74 // mapping in LLVMContext.
75 setMetadata(LLVMContext::MD_DIAssignID, nullptr);
76}
77
78const Module *Instruction::getModule() const {
79 return getParent()->getModule();
80}
81
82const Function *Instruction::getFunction() const {
83 return getParent()->getParent();
84}
85
86const DataLayout &Instruction::getDataLayout() const {
87 return getModule()->getDataLayout();
88}
89
90void Instruction::removeFromParent() {
91 // Perform any debug-info maintenence required.
92 handleMarkerRemoval();
93
94 getParent()->getInstList().remove(getIterator());
95}
96
97void Instruction::handleMarkerRemoval() {
98 if (!DebugMarker)
99 return;
100
101 DebugMarker->removeMarker();
102}
103
104BasicBlock::iterator Instruction::eraseFromParent() {
105 handleMarkerRemoval();
106 return getParent()->getInstList().erase(getIterator());
107}
108
109void Instruction::insertBefore(Instruction *InsertPos) {
110 insertBefore(InsertPos->getIterator());
111}
112
113/// Insert an unlinked instruction into a basic block immediately before the
114/// specified instruction.
115void Instruction::insertBefore(BasicBlock::iterator InsertPos) {
116 insertBefore(*InsertPos->getParent(), InsertPos);
117}
118
119/// Insert an unlinked instruction into a basic block immediately after the
120/// specified instruction.
121void Instruction::insertAfter(Instruction *InsertPos) {
122 BasicBlock *DestParent = InsertPos->getParent();
123
124 DestParent->getInstList().insertAfter(InsertPos->getIterator(), this);
125}
126
127void Instruction::insertAfter(BasicBlock::iterator InsertPos) {
128 BasicBlock *DestParent = InsertPos->getParent();
129
130 DestParent->getInstList().insertAfter(InsertPos, this);
131}
132
133BasicBlock::iterator Instruction::insertInto(BasicBlock *ParentBB,
135 assert(getParent() == nullptr && "Expected detached instruction");
136 assert((It == ParentBB->end() || It->getParent() == ParentBB) &&
137 "It not in ParentBB");
138 insertBefore(*ParentBB, It);
139 return getIterator();
140}
141
142void Instruction::insertBefore(BasicBlock &BB,
143 InstListType::iterator InsertPos) {
144 assert(!DebugMarker);
145
146 BB.getInstList().insert(InsertPos, this);
147
148 // We've inserted "this": if InsertAtHead is set then it comes before any
149 // DbgVariableRecords attached to InsertPos. But if it's not set, then any
150 // DbgRecords should now come before "this".
151 bool InsertAtHead = InsertPos.getHeadBit();
152 if (!InsertAtHead) {
153 DbgMarker *SrcMarker = BB.getMarker(InsertPos);
154 if (SrcMarker && !SrcMarker->empty()) {
155 // If this assertion fires, the calling code is about to insert a PHI
156 // after debug-records, which would form a sequence like:
157 // %0 = PHI
158 // #dbg_value
159 // %1 = PHI
160 // Which is de-normalised and undesired -- hence the assertion. To avoid
161 // this, you must insert at that position using an iterator, and it must
162 // be aquired by calling getFirstNonPHIIt / begin or similar methods on
163 // the block. This will signal to this behind-the-scenes debug-info
164 // maintenence code that you intend the PHI to be ahead of everything,
165 // including any debug-info.
166 assert(!isa<PHINode>(this) && "Inserting PHI after debug-records!");
167 adoptDbgRecords(&BB, InsertPos, false);
168 }
169 }
170
171 // If we're inserting a terminator, check if we need to flush out
172 // TrailingDbgRecords. Inserting instructions at the end of an incomplete
173 // block is handled by the code block above.
174 if (isTerminator())
175 getParent()->flushTerminatorDbgRecords();
176}
177
178/// Unlink this instruction from its current basic block and insert it into the
179/// basic block that MovePos lives in, right before MovePos.
180void Instruction::moveBefore(Instruction *MovePos) {
181 moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), false);
182}
183
184void Instruction::moveBefore(BasicBlock::iterator MovePos) {
185 moveBeforeImpl(*MovePos->getParent(), MovePos, false);
186}
187
188void Instruction::moveBeforePreserving(Instruction *MovePos) {
189 moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), true);
190}
191
192void Instruction::moveBeforePreserving(BasicBlock::iterator MovePos) {
193 moveBeforeImpl(*MovePos->getParent(), MovePos, true);
194}
195
196void Instruction::moveAfter(Instruction *MovePos) {
197 auto NextIt = std::next(MovePos->getIterator());
198 // We want this instruction to be moved to after NextIt in the instruction
199 // list, but before NextIt's debug value range.
200 NextIt.setHeadBit(true);
201 moveBeforeImpl(*MovePos->getParent(), NextIt, false);
202}
203
204void Instruction::moveAfter(InstListType::iterator MovePos) {
205 // We want this instruction to be moved to after NextIt in the instruction
206 // list, but before NextIt's debug value range.
207 MovePos.setHeadBit(true);
208 moveBeforeImpl(*MovePos->getParent(), MovePos, false);
209}
210
211void Instruction::moveAfterPreserving(Instruction *MovePos) {
212 auto NextIt = std::next(MovePos->getIterator());
213 // We want this instruction and its debug range to be moved to after NextIt
214 // in the instruction list, but before NextIt's debug value range.
215 NextIt.setHeadBit(true);
216 moveBeforeImpl(*MovePos->getParent(), NextIt, true);
217}
218
219void Instruction::moveBefore(BasicBlock &BB, InstListType::iterator I) {
220 moveBeforeImpl(BB, I, false);
221}
222
223void Instruction::moveBeforePreserving(BasicBlock &BB,
224 InstListType::iterator I) {
225 moveBeforeImpl(BB, I, true);
226}
227
228void Instruction::moveBeforeImpl(BasicBlock &BB, InstListType::iterator I,
229 bool Preserve) {
230 assert(I == BB.end() || I->getParent() == &BB);
231 bool InsertAtHead = I.getHeadBit();
232
233 // If we've been given the "Preserve" flag, then just move the DbgRecords with
234 // the instruction, no more special handling needed.
235 if (DebugMarker && !Preserve) {
236 if (I != this->getIterator() || InsertAtHead) {
237 // "this" is definitely moving in the list, or it's moving ahead of its
238 // attached DbgVariableRecords. Detach any existing DbgRecords.
239 handleMarkerRemoval();
240 }
241 }
242
243 // Move this single instruction. Use the list splice method directly, not
244 // the block splicer, which will do more debug-info things.
245 BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
246
247 if (!Preserve) {
248 DbgMarker *NextMarker = getParent()->getNextMarker(this);
249
250 // If we're inserting at point I, and not in front of the DbgRecords
251 // attached there, then we should absorb the DbgRecords attached to I.
252 if (!InsertAtHead && NextMarker && !NextMarker->empty()) {
253 adoptDbgRecords(&BB, I, false);
254 }
255 }
256
257 if (isTerminator())
258 getParent()->flushTerminatorDbgRecords();
259}
260
261iterator_range<DbgRecord::self_iterator> Instruction::cloneDebugInfoFrom(
262 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
263 bool InsertAtHead) {
264 if (!From->DebugMarker)
265 return DbgMarker::getEmptyDbgRecordRange();
266
267 if (!DebugMarker)
268 getParent()->createMarker(this);
269
270 return DebugMarker->cloneDebugInfoFrom(From->DebugMarker, FromHere,
271 InsertAtHead);
272}
273
274std::optional<DbgRecord::self_iterator>
275Instruction::getDbgReinsertionPosition() {
276 // Is there a marker on the next instruction?
277 DbgMarker *NextMarker = getParent()->getNextMarker(this);
278 if (!NextMarker)
279 return std::nullopt;
280
281 // Are there any DbgRecords in the next marker?
282 if (NextMarker->StoredDbgRecords.empty())
283 return std::nullopt;
284
285 return NextMarker->StoredDbgRecords.begin();
286}
287
288bool Instruction::hasDbgRecords() const { return !getDbgRecordRange().empty(); }
289
290void Instruction::adoptDbgRecords(BasicBlock *BB, BasicBlock::iterator It,
291 bool InsertAtHead) {
292 DbgMarker *SrcMarker = BB->getMarker(It);
293 auto ReleaseTrailingDbgRecords = [BB, It, SrcMarker]() {
294 if (BB->end() == It) {
295 SrcMarker->eraseFromParent();
297 }
298 };
299
300 if (!SrcMarker || SrcMarker->StoredDbgRecords.empty()) {
301 ReleaseTrailingDbgRecords();
302 return;
303 }
304
305 // If we have DbgMarkers attached to this instruction, we have to honour the
306 // ordering of DbgRecords between this and the other marker. Fall back to just
307 // absorbing from the source.
308 if (DebugMarker || It == BB->end()) {
309 // Ensure we _do_ have a marker.
310 getParent()->createMarker(this);
311 DebugMarker->absorbDebugValues(*SrcMarker, InsertAtHead);
312
313 // Having transferred everything out of SrcMarker, we _could_ clean it up
314 // and free the marker now. However, that's a lot of heap-accounting for a
315 // small amount of memory with a good chance of re-use. Leave it for the
316 // moment. It will be released when the Instruction is freed in the worst
317 // case.
318 // However: if we transferred from a trailing marker off the end of the
319 // block, it's important to not leave the empty marker trailing. It will
320 // give a misleading impression that some debug records have been left
321 // trailing.
322 ReleaseTrailingDbgRecords();
323 } else {
324 // Optimisation: we're transferring all the DbgRecords from the source
325 // marker onto this empty location: just adopt the other instructions
326 // marker.
327 DebugMarker = SrcMarker;
328 DebugMarker->MarkedInstr = this;
329 It->DebugMarker = nullptr;
330 }
331}
332
333void Instruction::dropDbgRecords() {
334 if (DebugMarker)
335 DebugMarker->dropDbgRecords();
336}
337
338void Instruction::dropOneDbgRecord(DbgRecord *DVR) {
339 DebugMarker->dropOneDbgRecord(DVR);
340}
341
342bool Instruction::comesBefore(const Instruction *Other) const {
343 assert(getParent() && Other->getParent() &&
344 "instructions without BB parents have no order");
345 assert(getParent() == Other->getParent() &&
346 "cross-BB instruction order comparison");
347 if (!getParent()->isInstrOrderValid())
348 const_cast<BasicBlock *>(getParent())->renumberInstructions();
349 return Order < Other->Order;
350}
351
352std::optional<BasicBlock::iterator> Instruction::getInsertionPointAfterDef() {
353 assert(!getType()->isVoidTy() && "Instruction must define result");
354 BasicBlock *InsertBB;
355 BasicBlock::iterator InsertPt;
356 if (auto *PN = dyn_cast<PHINode>(this)) {
357 InsertBB = PN->getParent();
358 InsertPt = InsertBB->getFirstInsertionPt();
359 } else if (auto *II = dyn_cast<InvokeInst>(this)) {
360 InsertBB = II->getNormalDest();
361 InsertPt = InsertBB->getFirstInsertionPt();
362 } else if (isa<CallBrInst>(this)) {
363 // Def is available in multiple successors, there's no single dominating
364 // insertion point.
365 return std::nullopt;
366 } else {
367 assert(!isTerminator() && "Only invoke/callbr terminators return value");
368 InsertBB = getParent();
369 InsertPt = std::next(getIterator());
370 // Any instruction inserted immediately after "this" will come before any
371 // debug-info records take effect -- thus, set the head bit indicating that
372 // to debug-info-transfer code.
373 InsertPt.setHeadBit(true);
374 }
375
376 // catchswitch blocks don't have any legal insertion point (because they
377 // are both an exception pad and a terminator).
378 if (InsertPt == InsertBB->end())
379 return std::nullopt;
380 return InsertPt;
381}
382
383bool Instruction::isOnlyUserOfAnyOperand() {
384 return any_of(operands(), [](const Value *V) { return V->hasOneUser(); });
385}
386
387void Instruction::setHasNoUnsignedWrap(bool b) {
388 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
389 Inst->setHasNoUnsignedWrap(b);
390 else
391 cast<TruncInst>(this)->setHasNoUnsignedWrap(b);
392}
393
394void Instruction::setHasNoSignedWrap(bool b) {
395 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
396 Inst->setHasNoSignedWrap(b);
397 else
398 cast<TruncInst>(this)->setHasNoSignedWrap(b);
399}
400
401void Instruction::setIsExact(bool b) {
402 cast<PossiblyExactOperator>(this)->setIsExact(b);
403}
404
405void Instruction::setNonNeg(bool b) {
406 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
407 SubclassOptionalData = (SubclassOptionalData & ~PossiblyNonNegInst::NonNeg) |
408 (b * PossiblyNonNegInst::NonNeg);
409}
410
411bool Instruction::hasNoUnsignedWrap() const {
412 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
413 return Inst->hasNoUnsignedWrap();
414
415 return cast<TruncInst>(this)->hasNoUnsignedWrap();
416}
417
418bool Instruction::hasNoSignedWrap() const {
419 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
420 return Inst->hasNoSignedWrap();
421
422 return cast<TruncInst>(this)->hasNoSignedWrap();
423}
424
425bool Instruction::hasNonNeg() const {
426 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
427 return (SubclassOptionalData & PossiblyNonNegInst::NonNeg) != 0;
428}
429
430bool Instruction::hasPoisonGeneratingFlags() const {
431 return cast<Operator>(this)->hasPoisonGeneratingFlags();
432}
433
434void Instruction::dropPoisonGeneratingFlags() {
435 switch (getOpcode()) {
436 case Instruction::Add:
437 case Instruction::Sub:
438 case Instruction::Mul:
439 case Instruction::Shl:
440 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);
441 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);
442 break;
443
444 case Instruction::UDiv:
445 case Instruction::SDiv:
446 case Instruction::AShr:
447 case Instruction::LShr:
448 cast<PossiblyExactOperator>(this)->setIsExact(false);
449 break;
450
451 case Instruction::Or:
452 cast<PossiblyDisjointInst>(this)->setIsDisjoint(false);
453 break;
454
455 case Instruction::GetElementPtr:
456 cast<GetElementPtrInst>(this)->setNoWrapFlags(GEPNoWrapFlags::none());
457 break;
458
459 case Instruction::UIToFP:
460 case Instruction::ZExt:
461 setNonNeg(false);
462 break;
463
464 case Instruction::Trunc:
465 cast<TruncInst>(this)->setHasNoUnsignedWrap(false);
466 cast<TruncInst>(this)->setHasNoSignedWrap(false);
467 break;
468
469 case Instruction::ICmp:
470 cast<ICmpInst>(this)->setSameSign(false);
471 break;
472 }
473
474 if (isa<FPMathOperator>(this)) {
475 setHasNoNaNs(false);
476 setHasNoInfs(false);
477 }
478
479 assert(!hasPoisonGeneratingFlags() && "must be kept in sync");
480}
481
482bool Instruction::hasPoisonGeneratingMetadata() const {
483 return any_of(Metadata::PoisonGeneratingIDs,
484 [this](unsigned ID) { return hasMetadata(ID); });
485}
486
487bool Instruction::hasNonDebugLocLoopMetadata() const {
488 // If there is no loop metadata at all, we also don't have
489 // non-debug loop metadata, obviously.
490 if (!hasMetadata(LLVMContext::MD_loop))
491 return false;
492
493 // If we do have loop metadata, retrieve it.
494 MDNode *LoopMD = getMetadata(LLVMContext::MD_loop);
495
496 // Check if the existing operands are debug locations. This loop
497 // should terminate after at most three iterations. Skip
498 // the first item because it is a self-reference.
499 for (const MDOperand &Op : llvm::drop_begin(LoopMD->operands())) {
500 // check for debug location type by attempting a cast.
501 if (!isa<DILocation>(Op)) {
502 return true;
503 }
504 }
505
506 // If we get here, then all we have is debug locations in the loop metadata.
507 return false;
508}
509
510void Instruction::dropPoisonGeneratingMetadata() {
511 for (unsigned ID : Metadata::PoisonGeneratingIDs)
512 eraseMetadata(ID);
513}
514
515bool Instruction::hasPoisonGeneratingReturnAttributes() const {
516 if (const auto *CB = dyn_cast<CallBase>(this)) {
517 AttributeSet RetAttrs = CB->getAttributes().getRetAttrs();
518 return RetAttrs.hasAttribute(Attribute::Range) ||
519 RetAttrs.hasAttribute(Attribute::Alignment) ||
520 RetAttrs.hasAttribute(Attribute::NonNull);
521 }
522 return false;
523}
524
525void Instruction::dropPoisonGeneratingReturnAttributes() {
526 if (auto *CB = dyn_cast<CallBase>(this)) {
527 AttributeMask AM;
528 AM.addAttribute(Attribute::Range);
529 AM.addAttribute(Attribute::Alignment);
530 AM.addAttribute(Attribute::NonNull);
531 CB->removeRetAttrs(AM);
532 }
533 assert(!hasPoisonGeneratingReturnAttributes() && "must be kept in sync");
534}
535
536void Instruction::dropUBImplyingAttrsAndUnknownMetadata(
537 ArrayRef<unsigned> KnownIDs) {
538 dropUnknownNonDebugMetadata(KnownIDs);
539 auto *CB = dyn_cast<CallBase>(this);
540 if (!CB)
541 return;
542 // For call instructions, we also need to drop parameter and return attributes
543 // that can cause UB if the call is moved to a location where the attribute is
544 // not valid.
545 AttributeList AL = CB->getAttributes();
546 if (AL.isEmpty())
547 return;
548 AttributeMask UBImplyingAttributes =
549 AttributeFuncs::getUBImplyingAttributes();
550 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
551 CB->removeParamAttrs(ArgNo, UBImplyingAttributes);
552 CB->removeRetAttrs(UBImplyingAttributes);
553}
554
555void Instruction::dropUBImplyingAttrsAndMetadata(ArrayRef<unsigned> Keep) {
556 // !annotation metadata does not impact semantics.
557 // !range, !nonnull and !align produce poison, so they are safe to speculate.
558 // !noundef and various AA metadata must be dropped, as it generally produces
559 // immediate undefined behavior.
560 static const unsigned KnownIDs[] = {
561 LLVMContext::MD_annotation, LLVMContext::MD_range,
562 LLVMContext::MD_nonnull, LLVMContext::MD_align};
563 SmallVector<unsigned> KeepIDs;
564 KeepIDs.reserve(Keep.size() + std::size(KnownIDs));
565 append_range(KeepIDs, KnownIDs);
566 append_range(KeepIDs, Keep);
567 dropUBImplyingAttrsAndUnknownMetadata(KeepIDs);
568}
569
570bool Instruction::hasUBImplyingAttrs() const {
571 auto *CB = dyn_cast<CallBase>(this);
572 if (!CB)
573 return false;
574 // For call instructions, we also need to check parameter and return
575 // attributes that can cause UB.
576 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
577 if (CB->isPassingUndefUB(ArgNo))
578 return true;
579 return CB->hasRetAttr(Attribute::NoUndef) ||
580 CB->hasRetAttr(Attribute::Dereferenceable) ||
581 CB->hasRetAttr(Attribute::DereferenceableOrNull);
582}
583
584bool Instruction::isExact() const {
585 return cast<PossiblyExactOperator>(this)->isExact();
586}
587
588void Instruction::setFast(bool B) {
589 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
590 cast<FPMathOperator>(this)->setFast(B);
591}
592
593void Instruction::setHasAllowReassoc(bool B) {
594 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
595 cast<FPMathOperator>(this)->setHasAllowReassoc(B);
596}
597
598void Instruction::setHasNoNaNs(bool B) {
599 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
600 cast<FPMathOperator>(this)->setHasNoNaNs(B);
601}
602
603void Instruction::setHasNoInfs(bool B) {
604 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
605 cast<FPMathOperator>(this)->setHasNoInfs(B);
606}
607
608void Instruction::setHasNoSignedZeros(bool B) {
609 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
610 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
611}
612
613void Instruction::setHasAllowReciprocal(bool B) {
614 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
615 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
616}
617
618void Instruction::setHasAllowContract(bool B) {
619 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
620 cast<FPMathOperator>(this)->setHasAllowContract(B);
621}
622
623void Instruction::setHasApproxFunc(bool B) {
624 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
625 cast<FPMathOperator>(this)->setHasApproxFunc(B);
626}
627
628void Instruction::setFastMathFlags(FastMathFlags FMF) {
629 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
630 cast<FPMathOperator>(this)->setFastMathFlags(FMF);
631}
632
633void Instruction::copyFastMathFlags(FastMathFlags FMF) {
634 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
635 cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
636}
637
638bool Instruction::isFast() const {
639 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
640 return cast<FPMathOperator>(this)->isFast();
641}
642
643bool Instruction::hasAllowReassoc() const {
644 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
645 return cast<FPMathOperator>(this)->hasAllowReassoc();
646}
647
648bool Instruction::hasNoNaNs() const {
649 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
650 return cast<FPMathOperator>(this)->hasNoNaNs();
651}
652
653bool Instruction::hasNoInfs() const {
654 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
655 return cast<FPMathOperator>(this)->hasNoInfs();
656}
657
658bool Instruction::hasNoSignedZeros() const {
659 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
660 return cast<FPMathOperator>(this)->hasNoSignedZeros();
661}
662
663bool Instruction::hasAllowReciprocal() const {
664 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
665 return cast<FPMathOperator>(this)->hasAllowReciprocal();
666}
667
668bool Instruction::hasAllowContract() const {
669 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
670 return cast<FPMathOperator>(this)->hasAllowContract();
671}
672
673bool Instruction::hasApproxFunc() const {
674 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
675 return cast<FPMathOperator>(this)->hasApproxFunc();
676}
677
678FastMathFlags Instruction::getFastMathFlags() const {
679 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
680 return cast<FPMathOperator>(this)->getFastMathFlags();
681}
682
683void Instruction::copyFastMathFlags(const Instruction *I) {
684 copyFastMathFlags(I->getFastMathFlags());
685}
686
687void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
688 // Copy the wrapping flags.
689 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) {
690 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
691 setHasNoSignedWrap(OB->hasNoSignedWrap());
692 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
693 }
694 }
695
696 if (auto *TI = dyn_cast<TruncInst>(V)) {
697 if (isa<TruncInst>(this)) {
698 setHasNoSignedWrap(TI->hasNoSignedWrap());
699 setHasNoUnsignedWrap(TI->hasNoUnsignedWrap());
700 }
701 }
702
703 // Copy the exact flag.
704 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
705 if (isa<PossiblyExactOperator>(this))
706 setIsExact(PE->isExact());
707
708 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))
709 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))
710 DestPD->setIsDisjoint(SrcPD->isDisjoint());
711
712 // Copy the fast-math flags.
713 if (auto *FP = dyn_cast<FPMathOperator>(V))
714 if (isa<FPMathOperator>(this))
715 copyFastMathFlags(FP->getFastMathFlags());
716
717 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
718 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
719 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() |
720 DestGEP->getNoWrapFlags());
721
722 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))
723 if (isa<PossiblyNonNegInst>(this))
724 setNonNeg(NNI->hasNonNeg());
725
726 if (auto *SrcICmp = dyn_cast<ICmpInst>(V))
727 if (auto *DestICmp = dyn_cast<ICmpInst>(this))
728 DestICmp->setSameSign(SrcICmp->hasSameSign());
729}
730
731void Instruction::andIRFlags(const Value *V) {
732 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
733 if (isa<OverflowingBinaryOperator>(this)) {
734 setHasNoSignedWrap(hasNoSignedWrap() && OB->hasNoSignedWrap());
735 setHasNoUnsignedWrap(hasNoUnsignedWrap() && OB->hasNoUnsignedWrap());
736 }
737 }
738
739 if (auto *TI = dyn_cast<TruncInst>(V)) {
740 if (isa<TruncInst>(this)) {
741 setHasNoSignedWrap(hasNoSignedWrap() && TI->hasNoSignedWrap());
742 setHasNoUnsignedWrap(hasNoUnsignedWrap() && TI->hasNoUnsignedWrap());
743 }
744 }
745
746 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
747 if (isa<PossiblyExactOperator>(this))
748 setIsExact(isExact() && PE->isExact());
749
750 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))
751 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))
752 DestPD->setIsDisjoint(DestPD->isDisjoint() && SrcPD->isDisjoint());
753
754 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
755 if (isa<FPMathOperator>(this)) {
756 FastMathFlags FM = getFastMathFlags();
757 FM &= FP->getFastMathFlags();
758 copyFastMathFlags(FM);
759 }
760 }
761
762 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
763 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
764 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() &
765 DestGEP->getNoWrapFlags());
766
767 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))
768 if (isa<PossiblyNonNegInst>(this))
769 setNonNeg(hasNonNeg() && NNI->hasNonNeg());
770
771 if (auto *SrcICmp = dyn_cast<ICmpInst>(V))
772 if (auto *DestICmp = dyn_cast<ICmpInst>(this))
773 DestICmp->setSameSign(DestICmp->hasSameSign() && SrcICmp->hasSameSign());
774}
775
776const char *Instruction::getOpcodeName(unsigned OpCode) {
777 switch (OpCode) {
778 // Terminators
779 case Ret: return "ret";
780 case Br: return "br";
781 case Switch: return "switch";
782 case IndirectBr: return "indirectbr";
783 case Invoke: return "invoke";
784 case Resume: return "resume";
785 case Unreachable: return "unreachable";
786 case CleanupRet: return "cleanupret";
787 case CatchRet: return "catchret";
788 case CatchPad: return "catchpad";
789 case CatchSwitch: return "catchswitch";
790 case CallBr: return "callbr";
791
792 // Standard unary operators...
793 case FNeg: return "fneg";
794
795 // Standard binary operators...
796 case Add: return "add";
797 case FAdd: return "fadd";
798 case Sub: return "sub";
799 case FSub: return "fsub";
800 case Mul: return "mul";
801 case FMul: return "fmul";
802 case UDiv: return "udiv";
803 case SDiv: return "sdiv";
804 case FDiv: return "fdiv";
805 case URem: return "urem";
806 case SRem: return "srem";
807 case FRem: return "frem";
808
809 // Logical operators...
810 case And: return "and";
811 case Or : return "or";
812 case Xor: return "xor";
813
814 // Memory instructions...
815 case Alloca: return "alloca";
816 case Load: return "load";
817 case Store: return "store";
818 case AtomicCmpXchg: return "cmpxchg";
819 case AtomicRMW: return "atomicrmw";
820 case Fence: return "fence";
821 case GetElementPtr: return "getelementptr";
822
823 // Convert instructions...
824 case Trunc: return "trunc";
825 case ZExt: return "zext";
826 case SExt: return "sext";
827 case FPTrunc: return "fptrunc";
828 case FPExt: return "fpext";
829 case FPToUI: return "fptoui";
830 case FPToSI: return "fptosi";
831 case UIToFP: return "uitofp";
832 case SIToFP: return "sitofp";
833 case IntToPtr: return "inttoptr";
834 case PtrToAddr: return "ptrtoaddr";
835 case PtrToInt: return "ptrtoint";
836 case BitCast: return "bitcast";
837 case AddrSpaceCast: return "addrspacecast";
838
839 // Other instructions...
840 case ICmp: return "icmp";
841 case FCmp: return "fcmp";
842 case PHI: return "phi";
843 case Select: return "select";
844 case Call: return "call";
845 case Shl: return "shl";
846 case LShr: return "lshr";
847 case AShr: return "ashr";
848 case VAArg: return "va_arg";
849 case ExtractElement: return "extractelement";
850 case InsertElement: return "insertelement";
851 case ShuffleVector: return "shufflevector";
852 case ExtractValue: return "extractvalue";
853 case InsertValue: return "insertvalue";
854 case LandingPad: return "landingpad";
855 case CleanupPad: return "cleanuppad";
856 case Freeze: return "freeze";
857
858 default: return "<Invalid operator> ";
859 }
860}
861
862/// This must be kept in sync with FunctionComparator::cmpOperations in
863/// lib/Transforms/IPO/MergeFunctions.cpp.
864bool Instruction::hasSameSpecialState(const Instruction *I2,
865 bool IgnoreAlignment,
866 bool IntersectAttrs) const {
867 auto I1 = this;
868 assert(I1->getOpcode() == I2->getOpcode() &&
869 "Can not compare special state of different instructions");
870
871 auto CheckAttrsSame = [IntersectAttrs](const CallBase *CB0,
872 const CallBase *CB1) {
873 return IntersectAttrs
874 ? CB0->getAttributes()
875 .intersectWith(CB0->getContext(), CB1->getAttributes())
876 .has_value()
877 : CB0->getAttributes() == CB1->getAttributes();
878 };
879
880 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))
881 return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&
882 (AI->getAlign() == cast<AllocaInst>(I2)->getAlign() ||
883 IgnoreAlignment);
884 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
885 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
886 (LI->getAlign() == cast<LoadInst>(I2)->getAlign() ||
887 IgnoreAlignment) &&
888 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
889 LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID();
890 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
891 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
892 (SI->getAlign() == cast<StoreInst>(I2)->getAlign() ||
893 IgnoreAlignment) &&
894 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
895 SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID();
896 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
897 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
898 if (const CallInst *CI = dyn_cast<CallInst>(I1))
899 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
900 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
901 CheckAttrsSame(CI, cast<CallInst>(I2)) &&
902 CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
903 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
904 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
905 CheckAttrsSame(CI, cast<InvokeInst>(I2)) &&
906 CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
907 if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1))
908 return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() &&
909 CheckAttrsSame(CI, cast<CallBrInst>(I2)) &&
910 CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2));
911 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
912 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
913 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
914 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
915 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
916 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
917 FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID();
918 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
919 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
920 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
921 CXI->getSuccessOrdering() ==
922 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
923 CXI->getFailureOrdering() ==
924 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
925 CXI->getSyncScopeID() ==
926 cast<AtomicCmpXchgInst>(I2)->getSyncScopeID();
927 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
928 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
929 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
930 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
931 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID();
932 if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I1))
933 return SVI->getShuffleMask() ==
934 cast<ShuffleVectorInst>(I2)->getShuffleMask();
935 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I1))
936 return GEP->getSourceElementType() ==
937 cast<GetElementPtrInst>(I2)->getSourceElementType();
938
939 return true;
940}
941
942bool Instruction::isIdenticalTo(const Instruction *I) const {
943 return isIdenticalToWhenDefined(I) &&
944 SubclassOptionalData == I->SubclassOptionalData;
945}
946
947bool Instruction::isIdenticalToWhenDefined(const Instruction *I,
948 bool IntersectAttrs) const {
949 if (getOpcode() != I->getOpcode() ||
950 getNumOperands() != I->getNumOperands() || getType() != I->getType())
951 return false;
952
953 // If both instructions have no operands, they are identical.
954 if (getNumOperands() == 0 && I->getNumOperands() == 0)
955 return this->hasSameSpecialState(I, /*IgnoreAlignment=*/false,
956 IntersectAttrs);
957
958 // We have two instructions of identical opcode and #operands. Check to see
959 // if all operands are the same.
960 if (!equal(operands(), I->operands()))
961 return false;
962
963 // WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()!
964 if (const PHINode *Phi = dyn_cast<PHINode>(this)) {
965 const PHINode *OtherPhi = cast<PHINode>(I);
966 return equal(Phi->blocks(), OtherPhi->blocks());
967 }
968
969 return this->hasSameSpecialState(I, /*IgnoreAlignment=*/false,
970 IntersectAttrs);
971}
972
973// Keep this in sync with FunctionComparator::cmpOperations in
974// lib/Transforms/IPO/MergeFunctions.cpp.
975bool Instruction::isSameOperationAs(const Instruction *I,
976 unsigned flags) const {
977 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
978 bool UseScalarTypes = flags & CompareUsingScalarTypes;
979 bool IntersectAttrs = flags & CompareUsingIntersectedAttrs;
980
981 if (getOpcode() != I->getOpcode() ||
982 getNumOperands() != I->getNumOperands() ||
983 (UseScalarTypes ?
984 getType()->getScalarType() != I->getType()->getScalarType() :
985 getType() != I->getType()))
986 return false;
987
988 // We have two instructions of identical opcode and #operands. Check to see
989 // if all operands are the same type
990 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
991 if (UseScalarTypes ?
992 getOperand(i)->getType()->getScalarType() !=
993 I->getOperand(i)->getType()->getScalarType() :
994 getOperand(i)->getType() != I->getOperand(i)->getType())
995 return false;
996
997 return this->hasSameSpecialState(I, IgnoreAlignment, IntersectAttrs);
998}
999
1000bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
1001 for (const Use &U : uses()) {
1002 // PHI nodes uses values in the corresponding predecessor block. For other
1003 // instructions, just check to see whether the parent of the use matches up.
1004 const Instruction *I = cast<Instruction>(U.getUser());
1005 const PHINode *PN = dyn_cast<PHINode>(I);
1006 if (!PN) {
1007 if (I->getParent() != BB)
1008 return true;
1009 continue;
1010 }
1011
1012 if (PN->getIncomingBlock(U) != BB)
1013 return true;
1014 }
1015 return false;
1016}
1017
1018bool Instruction::mayReadFromMemory() const {
1019 switch (getOpcode()) {
1020 default: return false;
1021 case Instruction::VAArg:
1022 case Instruction::Load:
1023 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
1024 case Instruction::AtomicCmpXchg:
1025 case Instruction::AtomicRMW:
1026 case Instruction::CatchPad:
1027 case Instruction::CatchRet:
1028 return true;
1029 case Instruction::Call:
1030 case Instruction::Invoke:
1031 case Instruction::CallBr:
1032 return !cast<CallBase>(this)->onlyWritesMemory();
1033 case Instruction::Store:
1034 return !cast<StoreInst>(this)->isUnordered();
1035 }
1036}
1037
1038bool Instruction::mayWriteToMemory() const {
1039 switch (getOpcode()) {
1040 default: return false;
1041 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
1042 case Instruction::Store:
1043 case Instruction::VAArg:
1044 case Instruction::AtomicCmpXchg:
1045 case Instruction::AtomicRMW:
1046 case Instruction::CatchPad:
1047 case Instruction::CatchRet:
1048 return true;
1049 case Instruction::Call:
1050 case Instruction::Invoke:
1051 case Instruction::CallBr:
1052 return !cast<CallBase>(this)->onlyReadsMemory();
1053 case Instruction::Load:
1054 return !cast<LoadInst>(this)->isUnordered();
1055 }
1056}
1057
1058bool Instruction::isAtomic() const {
1059 switch (getOpcode()) {
1060 default:
1061 return false;
1062 case Instruction::AtomicCmpXchg:
1063 case Instruction::AtomicRMW:
1064 case Instruction::Fence:
1065 return true;
1066 case Instruction::Load:
1067 return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
1068 case Instruction::Store:
1069 return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
1070 }
1071}
1072
1073bool Instruction::hasAtomicLoad() const {
1074 assert(isAtomic());
1075 switch (getOpcode()) {
1076 default:
1077 return false;
1078 case Instruction::AtomicCmpXchg:
1079 case Instruction::AtomicRMW:
1080 case Instruction::Load:
1081 return true;
1082 }
1083}
1084
1085bool Instruction::hasAtomicStore() const {
1086 assert(isAtomic());
1087 switch (getOpcode()) {
1088 default:
1089 return false;
1090 case Instruction::AtomicCmpXchg:
1091 case Instruction::AtomicRMW:
1092 case Instruction::Store:
1093 return true;
1094 }
1095}
1096
1097bool Instruction::isVolatile() const {
1098 switch (getOpcode()) {
1099 default:
1100 return false;
1101 case Instruction::AtomicRMW:
1102 return cast<AtomicRMWInst>(this)->isVolatile();
1103 case Instruction::Store:
1104 return cast<StoreInst>(this)->isVolatile();
1105 case Instruction::Load:
1106 return cast<LoadInst>(this)->isVolatile();
1107 case Instruction::AtomicCmpXchg:
1108 return cast<AtomicCmpXchgInst>(this)->isVolatile();
1109 case Instruction::Call:
1110 case Instruction::Invoke:
1111 // There are a very limited number of intrinsics with volatile flags.
1112 if (auto *II = dyn_cast<IntrinsicInst>(this)) {
1113 if (auto *MI = dyn_cast<MemIntrinsic>(II))
1114 return MI->isVolatile();
1115 switch (II->getIntrinsicID()) {
1116 default: break;
1117 case Intrinsic::matrix_column_major_load:
1118 return cast<ConstantInt>(II->getArgOperand(2))->isOne();
1119 case Intrinsic::matrix_column_major_store:
1120 return cast<ConstantInt>(II->getArgOperand(3))->isOne();
1121 }
1122 }
1123 return false;
1124 }
1125}
1126
1127Type *Instruction::getAccessType() const {
1128 switch (getOpcode()) {
1129 case Instruction::Store:
1130 return cast<StoreInst>(this)->getValueOperand()->getType();
1131 case Instruction::Load:
1132 case Instruction::AtomicRMW:
1133 return getType();
1134 case Instruction::AtomicCmpXchg:
1135 return cast<AtomicCmpXchgInst>(this)->getNewValOperand()->getType();
1136 case Instruction::Call:
1137 case Instruction::Invoke:
1138 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(this)) {
1139 switch (II->getIntrinsicID()) {
1140 case Intrinsic::masked_load:
1141 case Intrinsic::masked_gather:
1142 case Intrinsic::masked_expandload:
1143 case Intrinsic::vp_load:
1144 case Intrinsic::vp_gather:
1145 case Intrinsic::experimental_vp_strided_load:
1146 return II->getType();
1147 case Intrinsic::masked_store:
1148 case Intrinsic::masked_scatter:
1149 case Intrinsic::masked_compressstore:
1150 case Intrinsic::vp_store:
1151 case Intrinsic::vp_scatter:
1152 case Intrinsic::experimental_vp_strided_store:
1153 return II->getOperand(0)->getType();
1154 default:
1155 break;
1156 }
1157 }
1158 }
1159
1160 return nullptr;
1161}
1162
1163static bool canUnwindPastLandingPad(const LandingPadInst *LP,
1164 bool IncludePhaseOneUnwind) {
1165 // Because phase one unwinding skips cleanup landingpads, we effectively
1166 // unwind past this frame, and callers need to have valid unwind info.
1167 if (LP->isCleanup())
1168 return IncludePhaseOneUnwind;
1169
1170 for (unsigned I = 0; I < LP->getNumClauses(); ++I) {
1171 Constant *Clause = LP->getClause(I);
1172 // catch ptr null catches all exceptions.
1173 if (LP->isCatch(I) && isa<ConstantPointerNull>(Clause))
1174 return false;
1175 // filter [0 x ptr] catches all exceptions.
1176 if (LP->isFilter(I) && Clause->getType()->getArrayNumElements() == 0)
1177 return false;
1178 }
1179
1180 // May catch only some subset of exceptions, in which case other exceptions
1181 // will continue unwinding.
1182 return true;
1183}
1184
1185bool Instruction::mayThrow(bool IncludePhaseOneUnwind) const {
1186 switch (getOpcode()) {
1187 case Instruction::Call:
1188 return !cast<CallInst>(this)->doesNotThrow();
1189 case Instruction::CleanupRet:
1190 return cast<CleanupReturnInst>(this)->unwindsToCaller();
1191 case Instruction::CatchSwitch:
1192 return cast<CatchSwitchInst>(this)->unwindsToCaller();
1193 case Instruction::Resume:
1194 return true;
1195 case Instruction::Invoke: {
1196 // Landingpads themselves don't unwind -- however, an invoke of a skipped
1197 // landingpad may continue unwinding.
1198 BasicBlock *UnwindDest = cast<InvokeInst>(this)->getUnwindDest();
1199 BasicBlock::iterator Pad = UnwindDest->getFirstNonPHIIt();
1200 if (auto *LP = dyn_cast<LandingPadInst>(Pad))
1201 return canUnwindPastLandingPad(LP, IncludePhaseOneUnwind);
1202 return false;
1203 }
1204 case Instruction::CleanupPad:
1205 // Treat the same as cleanup landingpad.
1206 return IncludePhaseOneUnwind;
1207 default:
1208 return false;
1209 }
1210}
1211
1212bool Instruction::mayHaveSideEffects() const {
1213 return mayWriteToMemory() || mayThrow() || !willReturn();
1214}
1215
1216bool Instruction::isSafeToRemove() const {
1217 return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) &&
1218 !this->isTerminator() && !this->isEHPad();
1219}
1220
1221bool Instruction::willReturn() const {
1222 // Volatile store isn't guaranteed to return; see LangRef.
1223 if (auto *SI = dyn_cast<StoreInst>(this))
1224 return !SI->isVolatile();
1225
1226 if (const auto *CB = dyn_cast<CallBase>(this))
1227 return CB->hasFnAttr(Attribute::WillReturn);
1228 return true;
1229}
1230
1231bool Instruction::isLifetimeStartOrEnd() const {
1232 auto *II = dyn_cast<IntrinsicInst>(this);
1233 if (!II)
1234 return false;
1235 Intrinsic::ID ID = II->getIntrinsicID();
1236 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
1237}
1238
1239bool Instruction::isLaunderOrStripInvariantGroup() const {
1240 auto *II = dyn_cast<IntrinsicInst>(this);
1241 if (!II)
1242 return false;
1243 Intrinsic::ID ID = II->getIntrinsicID();
1244 return ID == Intrinsic::launder_invariant_group ||
1245 ID == Intrinsic::strip_invariant_group;
1246}
1247
1248bool Instruction::isDebugOrPseudoInst() const {
1249 return isa<DbgInfoIntrinsic>(this) || isa<PseudoProbeInst>(this);
1250}
1251
1252const DebugLoc &Instruction::getStableDebugLoc() const {
1253 return getDebugLoc();
1254}
1255
1256bool Instruction::isAssociative() const {
1257 if (auto *II = dyn_cast<IntrinsicInst>(this))
1258 return II->isAssociative();
1259 unsigned Opcode = getOpcode();
1260 if (isAssociative(Opcode))
1261 return true;
1262
1263 switch (Opcode) {
1264 case FMul:
1265 case FAdd:
1266 return cast<FPMathOperator>(this)->hasAllowReassoc() &&
1267 cast<FPMathOperator>(this)->hasNoSignedZeros();
1268 default:
1269 return false;
1270 }
1271}
1272
1273bool Instruction::isCommutative() const {
1274 if (auto *II = dyn_cast<IntrinsicInst>(this))
1275 return II->isCommutative();
1276 // TODO: Should allow icmp/fcmp?
1277 return isCommutative(getOpcode());
1278}
1279
1280unsigned Instruction::getNumSuccessors() const {
1281 switch (getOpcode()) {
1282#define HANDLE_TERM_INST(N, OPC, CLASS) \
1283 case Instruction::OPC: \
1284 return static_cast<const CLASS *>(this)->getNumSuccessors();
1285#include "llvm/IR/Instruction.def"
1286 default:
1287 break;
1288 }
1289 llvm_unreachable("not a terminator");
1290}
1291
1292BasicBlock *Instruction::getSuccessor(unsigned idx) const {
1293 switch (getOpcode()) {
1294#define HANDLE_TERM_INST(N, OPC, CLASS) \
1295 case Instruction::OPC: \
1296 return static_cast<const CLASS *>(this)->getSuccessor(idx);
1297#include "llvm/IR/Instruction.def"
1298 default:
1299 break;
1300 }
1301 llvm_unreachable("not a terminator");
1302}
1303
1304void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {
1305 switch (getOpcode()) {
1306#define HANDLE_TERM_INST(N, OPC, CLASS) \
1307 case Instruction::OPC: \
1308 return static_cast<CLASS *>(this)->setSuccessor(idx, B);
1309#include "llvm/IR/Instruction.def"
1310 default:
1311 break;
1312 }
1313 llvm_unreachable("not a terminator");
1314}
1315
1316void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) {
1317 for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors();
1318 Idx != NumSuccessors; ++Idx)
1319 if (getSuccessor(Idx) == OldBB)
1320 setSuccessor(Idx, NewBB);
1321}
1322
1323Instruction *Instruction::cloneImpl() const {
1324 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
1325}
1326
1327void Instruction::swapProfMetadata() {
1328 MDNode *ProfileData = getBranchWeightMDNode(*this);
1329 if (!ProfileData)
1330 return;
1331 unsigned FirstIdx = getBranchWeightOffset(ProfileData);
1332 if (ProfileData->getNumOperands() != 2 + FirstIdx)
1333 return;
1334
1335 unsigned SecondIdx = FirstIdx + 1;
1337 // If there are more weights past the second, we can't swap them
1338 if (ProfileData->getNumOperands() > SecondIdx + 1)
1339 return;
1340 for (unsigned Idx = 0; Idx < FirstIdx; ++Idx) {
1341 Ops.push_back(ProfileData->getOperand(Idx));
1342 }
1343 // Switch the order of the weights
1344 Ops.push_back(ProfileData->getOperand(SecondIdx));
1345 Ops.push_back(ProfileData->getOperand(FirstIdx));
1346 setMetadata(LLVMContext::MD_prof,
1347 MDNode::get(ProfileData->getContext(), Ops));
1348}
1349
1350void Instruction::copyMetadata(const Instruction &SrcInst,
1351 ArrayRef<unsigned> WL) {
1352 if (WL.empty() || is_contained(WL, LLVMContext::MD_dbg))
1353 setDebugLoc(SrcInst.getDebugLoc().orElse(getDebugLoc()));
1354
1355 if (!SrcInst.hasMetadata())
1356 return;
1357
1359
1360 // Otherwise, enumerate and copy over metadata from the old instruction to the
1361 // new one.
1363 SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);
1364 for (const auto &MD : TheMDs) {
1365 if (WL.empty() || WLS.count(MD.first))
1366 setMetadata(MD.first, MD.second);
1367 }
1368}
1369
1370Instruction *Instruction::clone() const {
1371 Instruction *New = nullptr;
1372 switch (getOpcode()) {
1373 default:
1374 llvm_unreachable("Unhandled Opcode.");
1375#define HANDLE_INST(num, opc, clas) \
1376 case Instruction::opc: \
1377 New = cast<clas>(this)->cloneImpl(); \
1378 break;
1379#include "llvm/IR/Instruction.def"
1380#undef HANDLE_INST
1381 }
1382
1383 New->SubclassOptionalData = SubclassOptionalData;
1384 New->copyMetadata(*this);
1385 return New;
1386}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
Rewrite undef for PHI
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live propagate it s liveness to any other values it uses(according to Uses). void DeadArgumentEliminationPass
This file defines the DenseSet and SmallDenseSet classes.
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1328
Hexagon Common GEP
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
static bool hasNoSignedWrap(BinaryOperator &I)
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define I(x, y, z)
Definition: MD5.cpp:58
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
uint64_t IntrinsicInst * II
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
This file contains the declarations for profiling metadata utility functions.
static bool mayHaveSideEffects(MachineInstr &MI)
static bool isCommutative(Instruction *I, Value *ValWithUses)
This file contains some templates that are useful if you are working with the STL at all.
static bool canUnwindPastLandingPad(const LandingPadInst *LP, bool IncludePhaseOneUnwind)
cl::opt< bool > ProfcheckDisableMetadataFixes("profcheck-disable-metadata-fixes", cl::Hidden, cl::init(false), cl::desc("Disable metadata propagation fixes discovered through Issue #147390"))
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:39
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:247
static bool isAssociative(const COFFSection &Section)
BinaryOperator * Mul
an instruction to allocate memory on the stack
Definition: Instructions.h:64
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:136
iterator begin() const
Definition: ArrayRef.h:135
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:142
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:506
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:709
LLVM_ABI AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
LLVM_ABI std::optional< AttributeList > intersectWith(LLVMContext &C, AttributeList Other) const
Try to intersect this AttributeList with Other.
AttributeMask & addAttribute(Attribute::AttrKind Val)
Add an attribute to the mask.
Definition: AttributeMask.h:44
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
iterator end()
Definition: BasicBlock.h:472
LLVM_ABI void deleteTrailingDbgRecords()
Delete any trailing DbgRecords at the end of this block, see setTrailingDbgRecords.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:393
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:337
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:213
LLVM_ABI DbgMarker * getMarker(InstListType::iterator It)
Return the DbgMarker for the position given by It, so that DbgRecords can be inserted there.
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:170
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1116
AttributeList getAttributes() const
Return the attributes for this call.
Definition: InstrTypes.h:1424
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:666
This is an important base class in LLVM.
Definition: Constant.h:43
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
Per-instruction record of debug-info.
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
LLVM_ABI void dropDbgRecords()
Erase all DbgRecords in this DbgMarker.
simple_ilist< DbgRecord > StoredDbgRecords
List of DbgRecords, the non-instruction equivalent of llvm.dbg.
LLVM_ABI void eraseFromParent()
Base class for non-instruction debug metadata records that have positions within IR.
A debug info location.
Definition: DebugLoc.h:124
DebugLoc orElse(DebugLoc Other) const
If this DebugLoc is non-empty, returns this DebugLoc; otherwise, selects Other.
Definition: DebugLoc.h:196
This instruction extracts a struct member or array element value from an aggregate value.
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:22
An instruction for ordering other memory operations.
Definition: Instructions.h:429
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:949
This instruction inserts a struct field of array element value into an aggregate value.
DbgMarker * DebugMarker
Optional marker recording the position for debugging information that takes effect immediately before...
Definition: Instruction.h:85
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:513
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
Definition: Instruction.h:406
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
Definition: Instruction.h:453
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:312
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:49
Invoke instruction.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
An instruction for reading from memory.
Definition: Instructions.h:180
Metadata node.
Definition: Metadata.h:1077
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1445
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1443
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1451
LLVMContext & getContext() const
Definition: Metadata.h:1241
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:899
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
iterator_range< const_block_iterator > blocks() const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Instruction that can have a nneg flag (zext/uitofp).
Definition: InstrTypes.h:641
This instruction constructs a fixed permutation of two input vectors.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:283
void reserve(size_type N)
Definition: SmallVector.h:664
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
An instruction for storing to memory.
Definition: Instructions.h:296
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
LLVM Value Representation.
Definition: Value.h:75
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1101
const ParentTy * getParent() const
Definition: ilist_node.h:34
self_iterator getIterator()
Definition: ilist_node.h:134
void splice(iterator where, iplist_impl &L2)
Definition: ilist.h:266
iterator insertAfter(iterator where, pointer New)
Definition: ilist.h:174
iterator insert(iterator where, pointer New)
Definition: ilist.h:165
A range adaptor for a pair of iterators.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool mayThrow(const MachineInstr &MI)
@ OB
OB - OneByte - Set if this instruction has a one byte opcode.
Definition: X86BaseInfo.h:732
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
constexpr double e
Definition: MathExtras.h:47
NodeAddr< PhiNode * > Phi
Definition: RDFGraph.h:390
LLVM_ABI const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
Definition: Path.cpp:235
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:338
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2155
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1751
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange(DbgMarker *DebugMarker)
Inline helper to return a range of DbgRecords attached to a marker.
@ Xor
Bitwise or logical XOR of integers.
@ FMul
Product of floats.
@ Sub
Subtraction of integers.
@ FAdd
Sum of floats.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1916
@ Keep
No function return thunk.
Summary of memprof metadata on allocations.
Matching combinators.