LLVM 20.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"
16#include "llvm/IR/Attributes.h"
17#include "llvm/IR/Constants.h"
18#include "llvm/IR/InstrTypes.h"
21#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
26#include "llvm/IR/Type.h"
27using namespace llvm;
28
30 : InsertAt(InsertBefore ? InsertBefore->getIterator()
31 : InstListType::iterator()) {}
33 : InsertAt(InsertAtEnd ? InsertAtEnd->end() : InstListType::iterator()) {}
34
35Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
36 InsertPosition InsertBefore)
37 : User(ty, Value::InstructionVal + it, Ops, NumOps) {
38 // When called with an iterator, there must be a block to insert into.
39 if (InstListType::iterator InsertIt = InsertBefore; InsertIt.isValid()) {
40 BasicBlock *BB = InsertIt.getNodeParent();
41 assert(BB && "Instruction to insert before is not in a basic block!");
42 insertInto(BB, InsertBefore);
43 }
44}
45
47 assert(!getParent() && "Instruction still linked in the program!");
48
49 // Replace any extant metadata uses of this instruction with undef to
50 // preserve debug info accuracy. Some alternatives include:
51 // - Treat Instruction like any other Value, and point its extant metadata
52 // uses to an empty ValueAsMetadata node. This makes extant dbg.value uses
53 // trivially dead (i.e. fair game for deletion in many passes), leading to
54 // stale dbg.values being in effect for too long.
55 // - Call salvageDebugInfoOrMarkUndef. Not needed to make instruction removal
56 // correct. OTOH results in wasted work in some common cases (e.g. when all
57 // instructions in a BasicBlock are deleted).
58 if (isUsedByMetadata())
60
61 // Explicitly remove DIAssignID metadata to clear up ID -> Instruction(s)
62 // mapping in LLVMContext.
63 setMetadata(LLVMContext::MD_DIAssignID, nullptr);
64}
65
67 return getParent()->getModule();
68}
69
71 return getParent()->getParent();
72}
73
75 return getModule()->getDataLayout();
76}
77
79 // Perform any debug-info maintenence required.
81
82 getParent()->getInstList().remove(getIterator());
83}
84
86 if (!getParent()->IsNewDbgInfoFormat || !DebugMarker)
87 return;
88
90}
91
94 return getParent()->getInstList().erase(getIterator());
95}
96
98 insertBefore(InsertPos->getIterator());
99}
100
101/// Insert an unlinked instruction into a basic block immediately before the
102/// specified instruction.
104 insertBefore(*InsertPos->getParent(), InsertPos);
105}
106
107/// Insert an unlinked instruction into a basic block immediately after the
108/// specified instruction.
110 BasicBlock *DestParent = InsertPos->getParent();
111
112 DestParent->getInstList().insertAfter(InsertPos->getIterator(), this);
113}
114
117 assert(getParent() == nullptr && "Expected detached instruction");
118 assert((It == ParentBB->end() || It->getParent() == ParentBB) &&
119 "It not in ParentBB");
120 insertBefore(*ParentBB, It);
121 return getIterator();
122}
123
125
127 InstListType::iterator InsertPos) {
129
130 BB.getInstList().insert(InsertPos, this);
131
132 if (!BB.IsNewDbgInfoFormat)
133 return;
134
135 // We've inserted "this": if InsertAtHead is set then it comes before any
136 // DbgVariableRecords attached to InsertPos. But if it's not set, then any
137 // DbgRecords should now come before "this".
138 bool InsertAtHead = InsertPos.getHeadBit();
139 if (!InsertAtHead) {
140 DbgMarker *SrcMarker = BB.getMarker(InsertPos);
141 if (SrcMarker && !SrcMarker->empty()) {
142 // If this assertion fires, the calling code is about to insert a PHI
143 // after debug-records, which would form a sequence like:
144 // %0 = PHI
145 // #dbg_value
146 // %1 = PHI
147 // Which is de-normalised and undesired -- hence the assertion. To avoid
148 // this, you must insert at that position using an iterator, and it must
149 // be aquired by calling getFirstNonPHIIt / begin or similar methods on
150 // the block. This will signal to this behind-the-scenes debug-info
151 // maintenence code that you intend the PHI to be ahead of everything,
152 // including any debug-info.
153 assert(!isa<PHINode>(this) && "Inserting PHI after debug-records!");
154 adoptDbgRecords(&BB, InsertPos, false);
155 }
156 }
157
158 // If we're inserting a terminator, check if we need to flush out
159 // TrailingDbgRecords. Inserting instructions at the end of an incomplete
160 // block is handled by the code block above.
161 if (isTerminator())
162 getParent()->flushTerminatorDbgRecords();
163}
164
165/// Unlink this instruction from its current basic block and insert it into the
166/// basic block that MovePos lives in, right before MovePos.
168 moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), false);
169}
170
172 moveBeforeImpl(*MovePos->getParent(), MovePos->getIterator(), true);
173}
174
176 auto NextIt = std::next(MovePos->getIterator());
177 // We want this instruction to be moved to before NextIt in the instruction
178 // list, but before NextIt's debug value range.
179 NextIt.setHeadBit(true);
180 moveBeforeImpl(*MovePos->getParent(), NextIt, false);
181}
182
184 auto NextIt = std::next(MovePos->getIterator());
185 // We want this instruction and its debug range to be moved to before NextIt
186 // in the instruction list, but before NextIt's debug value range.
187 NextIt.setHeadBit(true);
188 moveBeforeImpl(*MovePos->getParent(), NextIt, true);
189}
190
192 moveBeforeImpl(BB, I, false);
193}
194
197 moveBeforeImpl(BB, I, true);
198}
199
200void Instruction::moveBeforeImpl(BasicBlock &BB, InstListType::iterator I,
201 bool Preserve) {
202 assert(I == BB.end() || I->getParent() == &BB);
203 bool InsertAtHead = I.getHeadBit();
204
205 // If we've been given the "Preserve" flag, then just move the DbgRecords with
206 // the instruction, no more special handling needed.
207 if (BB.IsNewDbgInfoFormat && DebugMarker && !Preserve) {
208 if (I != this->getIterator() || InsertAtHead) {
209 // "this" is definitely moving in the list, or it's moving ahead of its
210 // attached DbgVariableRecords. Detach any existing DbgRecords.
212 }
213 }
214
215 // Move this single instruction. Use the list splice method directly, not
216 // the block splicer, which will do more debug-info things.
217 BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
218
219 if (BB.IsNewDbgInfoFormat && !Preserve) {
220 DbgMarker *NextMarker = getParent()->getNextMarker(this);
221
222 // If we're inserting at point I, and not in front of the DbgRecords
223 // attached there, then we should absorb the DbgRecords attached to I.
224 if (!InsertAtHead && NextMarker && !NextMarker->empty()) {
225 adoptDbgRecords(&BB, I, false);
226 }
227 }
228
229 if (isTerminator())
230 getParent()->flushTerminatorDbgRecords();
231}
232
234 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
235 bool InsertAtHead) {
236 if (!From->DebugMarker)
238
239 assert(getParent()->IsNewDbgInfoFormat);
240 assert(getParent()->IsNewDbgInfoFormat ==
241 From->getParent()->IsNewDbgInfoFormat);
242
243 if (!DebugMarker)
244 getParent()->createMarker(this);
245
246 return DebugMarker->cloneDebugInfoFrom(From->DebugMarker, FromHere,
247 InsertAtHead);
248}
249
250std::optional<DbgRecord::self_iterator>
252 // Is there a marker on the next instruction?
253 DbgMarker *NextMarker = getParent()->getNextMarker(this);
254 if (!NextMarker)
255 return std::nullopt;
256
257 // Are there any DbgRecords in the next marker?
258 if (NextMarker->StoredDbgRecords.empty())
259 return std::nullopt;
260
261 return NextMarker->StoredDbgRecords.begin();
262}
263
264bool Instruction::hasDbgRecords() const { return !getDbgRecordRange().empty(); }
265
267 bool InsertAtHead) {
268 DbgMarker *SrcMarker = BB->getMarker(It);
269 auto ReleaseTrailingDbgRecords = [BB, It, SrcMarker]() {
270 if (BB->end() == It) {
271 SrcMarker->eraseFromParent();
273 }
274 };
275
276 if (!SrcMarker || SrcMarker->StoredDbgRecords.empty()) {
277 ReleaseTrailingDbgRecords();
278 return;
279 }
280
281 // If we have DbgMarkers attached to this instruction, we have to honour the
282 // ordering of DbgRecords between this and the other marker. Fall back to just
283 // absorbing from the source.
284 if (DebugMarker || It == BB->end()) {
285 // Ensure we _do_ have a marker.
286 getParent()->createMarker(this);
287 DebugMarker->absorbDebugValues(*SrcMarker, InsertAtHead);
288
289 // Having transferred everything out of SrcMarker, we _could_ clean it up
290 // and free the marker now. However, that's a lot of heap-accounting for a
291 // small amount of memory with a good chance of re-use. Leave it for the
292 // moment. It will be released when the Instruction is freed in the worst
293 // case.
294 // However: if we transferred from a trailing marker off the end of the
295 // block, it's important to not leave the empty marker trailing. It will
296 // give a misleading impression that some debug records have been left
297 // trailing.
298 ReleaseTrailingDbgRecords();
299 } else {
300 // Optimisation: we're transferring all the DbgRecords from the source
301 // marker onto this empty location: just adopt the other instructions
302 // marker.
303 DebugMarker = SrcMarker;
304 DebugMarker->MarkedInstr = this;
305 It->DebugMarker = nullptr;
306 }
307}
308
310 if (DebugMarker)
312}
313
316}
317
319 assert(getParent() && Other->getParent() &&
320 "instructions without BB parents have no order");
321 assert(getParent() == Other->getParent() &&
322 "cross-BB instruction order comparison");
323 if (!getParent()->isInstrOrderValid())
324 const_cast<BasicBlock *>(getParent())->renumberInstructions();
325 return Order < Other->Order;
326}
327
328std::optional<BasicBlock::iterator> Instruction::getInsertionPointAfterDef() {
329 assert(!getType()->isVoidTy() && "Instruction must define result");
330 BasicBlock *InsertBB;
331 BasicBlock::iterator InsertPt;
332 if (auto *PN = dyn_cast<PHINode>(this)) {
333 InsertBB = PN->getParent();
334 InsertPt = InsertBB->getFirstInsertionPt();
335 } else if (auto *II = dyn_cast<InvokeInst>(this)) {
336 InsertBB = II->getNormalDest();
337 InsertPt = InsertBB->getFirstInsertionPt();
338 } else if (isa<CallBrInst>(this)) {
339 // Def is available in multiple successors, there's no single dominating
340 // insertion point.
341 return std::nullopt;
342 } else {
343 assert(!isTerminator() && "Only invoke/callbr terminators return value");
344 InsertBB = getParent();
345 InsertPt = std::next(getIterator());
346 // Any instruction inserted immediately after "this" will come before any
347 // debug-info records take effect -- thus, set the head bit indicating that
348 // to debug-info-transfer code.
349 InsertPt.setHeadBit(true);
350 }
351
352 // catchswitch blocks don't have any legal insertion point (because they
353 // are both an exception pad and a terminator).
354 if (InsertPt == InsertBB->end())
355 return std::nullopt;
356 return InsertPt;
357}
358
360 return any_of(operands(), [](Value *V) { return V->hasOneUser(); });
361}
362
364 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
365 Inst->setHasNoUnsignedWrap(b);
366 else
367 cast<TruncInst>(this)->setHasNoUnsignedWrap(b);
368}
369
371 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
372 Inst->setHasNoSignedWrap(b);
373 else
374 cast<TruncInst>(this)->setHasNoSignedWrap(b);
375}
376
378 cast<PossiblyExactOperator>(this)->setIsExact(b);
379}
380
382 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
385}
386
388 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
389 return Inst->hasNoUnsignedWrap();
390
391 return cast<TruncInst>(this)->hasNoUnsignedWrap();
392}
393
395 if (auto *Inst = dyn_cast<OverflowingBinaryOperator>(this))
396 return Inst->hasNoSignedWrap();
397
398 return cast<TruncInst>(this)->hasNoSignedWrap();
399}
400
402 assert(isa<PossiblyNonNegInst>(this) && "Must be zext/uitofp");
404}
405
407 return cast<Operator>(this)->hasPoisonGeneratingFlags();
408}
409
411 switch (getOpcode()) {
412 case Instruction::Add:
413 case Instruction::Sub:
414 case Instruction::Mul:
415 case Instruction::Shl:
416 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);
417 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);
418 break;
419
420 case Instruction::UDiv:
421 case Instruction::SDiv:
422 case Instruction::AShr:
423 case Instruction::LShr:
424 cast<PossiblyExactOperator>(this)->setIsExact(false);
425 break;
426
427 case Instruction::Or:
428 cast<PossiblyDisjointInst>(this)->setIsDisjoint(false);
429 break;
430
431 case Instruction::GetElementPtr:
432 cast<GetElementPtrInst>(this)->setNoWrapFlags(GEPNoWrapFlags::none());
433 break;
434
435 case Instruction::UIToFP:
436 case Instruction::ZExt:
437 setNonNeg(false);
438 break;
439
440 case Instruction::Trunc:
441 cast<TruncInst>(this)->setHasNoUnsignedWrap(false);
442 cast<TruncInst>(this)->setHasNoSignedWrap(false);
443 break;
444 }
445
446 if (isa<FPMathOperator>(this)) {
447 setHasNoNaNs(false);
448 setHasNoInfs(false);
449 }
450
451 assert(!hasPoisonGeneratingFlags() && "must be kept in sync");
452}
453
455 return hasMetadata(LLVMContext::MD_range) ||
456 hasMetadata(LLVMContext::MD_nonnull) ||
457 hasMetadata(LLVMContext::MD_align);
458}
459
461 eraseMetadata(LLVMContext::MD_range);
462 eraseMetadata(LLVMContext::MD_nonnull);
463 eraseMetadata(LLVMContext::MD_align);
464}
465
467 if (const auto *CB = dyn_cast<CallBase>(this)) {
468 AttributeSet RetAttrs = CB->getAttributes().getRetAttrs();
469 return RetAttrs.hasAttribute(Attribute::Range) ||
470 RetAttrs.hasAttribute(Attribute::Alignment) ||
471 RetAttrs.hasAttribute(Attribute::NonNull);
472 }
473 return false;
474}
475
477 if (auto *CB = dyn_cast<CallBase>(this)) {
478 AttributeMask AM;
479 AM.addAttribute(Attribute::Range);
480 AM.addAttribute(Attribute::Alignment);
481 AM.addAttribute(Attribute::NonNull);
482 CB->removeRetAttrs(AM);
483 }
484 assert(!hasPoisonGeneratingReturnAttributes() && "must be kept in sync");
485}
486
488 ArrayRef<unsigned> KnownIDs) {
490 auto *CB = dyn_cast<CallBase>(this);
491 if (!CB)
492 return;
493 // For call instructions, we also need to drop parameter and return attributes
494 // that are can cause UB if the call is moved to a location where the
495 // attribute is not valid.
496 AttributeList AL = CB->getAttributes();
497 if (AL.isEmpty())
498 return;
499 AttributeMask UBImplyingAttributes =
501 for (unsigned ArgNo = 0; ArgNo < CB->arg_size(); ArgNo++)
502 CB->removeParamAttrs(ArgNo, UBImplyingAttributes);
503 CB->removeRetAttrs(UBImplyingAttributes);
504}
505
507 // !annotation metadata does not impact semantics.
508 // !range, !nonnull and !align produce poison, so they are safe to speculate.
509 // !noundef and various AA metadata must be dropped, as it generally produces
510 // immediate undefined behavior.
511 unsigned KnownIDs[] = {LLVMContext::MD_annotation, LLVMContext::MD_range,
512 LLVMContext::MD_nonnull, LLVMContext::MD_align};
514}
515
517 return cast<PossiblyExactOperator>(this)->isExact();
518}
519
521 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
522 cast<FPMathOperator>(this)->setFast(B);
523}
524
526 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
527 cast<FPMathOperator>(this)->setHasAllowReassoc(B);
528}
529
531 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
532 cast<FPMathOperator>(this)->setHasNoNaNs(B);
533}
534
536 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
537 cast<FPMathOperator>(this)->setHasNoInfs(B);
538}
539
541 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
542 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
543}
544
546 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
547 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
548}
549
551 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
552 cast<FPMathOperator>(this)->setHasAllowContract(B);
553}
554
556 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
557 cast<FPMathOperator>(this)->setHasApproxFunc(B);
558}
559
561 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
562 cast<FPMathOperator>(this)->setFastMathFlags(FMF);
563}
564
566 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
567 cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
568}
569
571 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
572 return cast<FPMathOperator>(this)->isFast();
573}
574
576 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
577 return cast<FPMathOperator>(this)->hasAllowReassoc();
578}
579
581 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
582 return cast<FPMathOperator>(this)->hasNoNaNs();
583}
584
586 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
587 return cast<FPMathOperator>(this)->hasNoInfs();
588}
589
591 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
592 return cast<FPMathOperator>(this)->hasNoSignedZeros();
593}
594
596 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
597 return cast<FPMathOperator>(this)->hasAllowReciprocal();
598}
599
601 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
602 return cast<FPMathOperator>(this)->hasAllowContract();
603}
604
606 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
607 return cast<FPMathOperator>(this)->hasApproxFunc();
608}
609
611 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
612 return cast<FPMathOperator>(this)->getFastMathFlags();
613}
614
616 copyFastMathFlags(I->getFastMathFlags());
617}
618
619void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
620 // Copy the wrapping flags.
621 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) {
622 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
623 setHasNoSignedWrap(OB->hasNoSignedWrap());
624 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
625 }
626 }
627
628 if (auto *TI = dyn_cast<TruncInst>(V)) {
629 if (isa<TruncInst>(this)) {
630 setHasNoSignedWrap(TI->hasNoSignedWrap());
631 setHasNoUnsignedWrap(TI->hasNoUnsignedWrap());
632 }
633 }
634
635 // Copy the exact flag.
636 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
637 if (isa<PossiblyExactOperator>(this))
638 setIsExact(PE->isExact());
639
640 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))
641 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))
642 DestPD->setIsDisjoint(SrcPD->isDisjoint());
643
644 // Copy the fast-math flags.
645 if (auto *FP = dyn_cast<FPMathOperator>(V))
646 if (isa<FPMathOperator>(this))
647 copyFastMathFlags(FP->getFastMathFlags());
648
649 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
650 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
651 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() |
652 DestGEP->getNoWrapFlags());
653
654 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))
655 if (isa<PossiblyNonNegInst>(this))
656 setNonNeg(NNI->hasNonNeg());
657}
658
660 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
661 if (isa<OverflowingBinaryOperator>(this)) {
662 setHasNoSignedWrap(hasNoSignedWrap() && OB->hasNoSignedWrap());
663 setHasNoUnsignedWrap(hasNoUnsignedWrap() && OB->hasNoUnsignedWrap());
664 }
665 }
666
667 if (auto *TI = dyn_cast<TruncInst>(V)) {
668 if (isa<TruncInst>(this)) {
669 setHasNoSignedWrap(hasNoSignedWrap() && TI->hasNoSignedWrap());
670 setHasNoUnsignedWrap(hasNoUnsignedWrap() && TI->hasNoUnsignedWrap());
671 }
672 }
673
674 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
675 if (isa<PossiblyExactOperator>(this))
676 setIsExact(isExact() && PE->isExact());
677
678 if (auto *SrcPD = dyn_cast<PossiblyDisjointInst>(V))
679 if (auto *DestPD = dyn_cast<PossiblyDisjointInst>(this))
680 DestPD->setIsDisjoint(DestPD->isDisjoint() && SrcPD->isDisjoint());
681
682 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
683 if (isa<FPMathOperator>(this)) {
685 FM &= FP->getFastMathFlags();
687 }
688 }
689
690 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
691 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
692 DestGEP->setNoWrapFlags(SrcGEP->getNoWrapFlags() &
693 DestGEP->getNoWrapFlags());
694
695 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(V))
696 if (isa<PossiblyNonNegInst>(this))
697 setNonNeg(hasNonNeg() && NNI->hasNonNeg());
698}
699
700const char *Instruction::getOpcodeName(unsigned OpCode) {
701 switch (OpCode) {
702 // Terminators
703 case Ret: return "ret";
704 case Br: return "br";
705 case Switch: return "switch";
706 case IndirectBr: return "indirectbr";
707 case Invoke: return "invoke";
708 case Resume: return "resume";
709 case Unreachable: return "unreachable";
710 case CleanupRet: return "cleanupret";
711 case CatchRet: return "catchret";
712 case CatchPad: return "catchpad";
713 case CatchSwitch: return "catchswitch";
714 case CallBr: return "callbr";
715
716 // Standard unary operators...
717 case FNeg: return "fneg";
718
719 // Standard binary operators...
720 case Add: return "add";
721 case FAdd: return "fadd";
722 case Sub: return "sub";
723 case FSub: return "fsub";
724 case Mul: return "mul";
725 case FMul: return "fmul";
726 case UDiv: return "udiv";
727 case SDiv: return "sdiv";
728 case FDiv: return "fdiv";
729 case URem: return "urem";
730 case SRem: return "srem";
731 case FRem: return "frem";
732
733 // Logical operators...
734 case And: return "and";
735 case Or : return "or";
736 case Xor: return "xor";
737
738 // Memory instructions...
739 case Alloca: return "alloca";
740 case Load: return "load";
741 case Store: return "store";
742 case AtomicCmpXchg: return "cmpxchg";
743 case AtomicRMW: return "atomicrmw";
744 case Fence: return "fence";
745 case GetElementPtr: return "getelementptr";
746
747 // Convert instructions...
748 case Trunc: return "trunc";
749 case ZExt: return "zext";
750 case SExt: return "sext";
751 case FPTrunc: return "fptrunc";
752 case FPExt: return "fpext";
753 case FPToUI: return "fptoui";
754 case FPToSI: return "fptosi";
755 case UIToFP: return "uitofp";
756 case SIToFP: return "sitofp";
757 case IntToPtr: return "inttoptr";
758 case PtrToInt: return "ptrtoint";
759 case BitCast: return "bitcast";
760 case AddrSpaceCast: return "addrspacecast";
761
762 // Other instructions...
763 case ICmp: return "icmp";
764 case FCmp: return "fcmp";
765 case PHI: return "phi";
766 case Select: return "select";
767 case Call: return "call";
768 case Shl: return "shl";
769 case LShr: return "lshr";
770 case AShr: return "ashr";
771 case VAArg: return "va_arg";
772 case ExtractElement: return "extractelement";
773 case InsertElement: return "insertelement";
774 case ShuffleVector: return "shufflevector";
775 case ExtractValue: return "extractvalue";
776 case InsertValue: return "insertvalue";
777 case LandingPad: return "landingpad";
778 case CleanupPad: return "cleanuppad";
779 case Freeze: return "freeze";
780
781 default: return "<Invalid operator> ";
782 }
783}
784
785/// This must be kept in sync with FunctionComparator::cmpOperations in
786/// lib/Transforms/IPO/MergeFunctions.cpp.
788 bool IgnoreAlignment) const {
789 auto I1 = this;
790 assert(I1->getOpcode() == I2->getOpcode() &&
791 "Can not compare special state of different instructions");
792
793 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))
794 return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&
795 (AI->getAlign() == cast<AllocaInst>(I2)->getAlign() ||
796 IgnoreAlignment);
797 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
798 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
799 (LI->getAlign() == cast<LoadInst>(I2)->getAlign() ||
800 IgnoreAlignment) &&
801 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
802 LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID();
803 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
804 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
805 (SI->getAlign() == cast<StoreInst>(I2)->getAlign() ||
806 IgnoreAlignment) &&
807 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
808 SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID();
809 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
810 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
811 if (const CallInst *CI = dyn_cast<CallInst>(I1))
812 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
813 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
814 CI->getAttributes() == cast<CallInst>(I2)->getAttributes() &&
815 CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
816 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
817 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
818 CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes() &&
819 CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
820 if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1))
821 return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() &&
822 CI->getAttributes() == cast<CallBrInst>(I2)->getAttributes() &&
823 CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2));
824 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
825 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
826 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
827 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
828 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
829 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
830 FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID();
831 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
832 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
833 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
834 CXI->getSuccessOrdering() ==
835 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
836 CXI->getFailureOrdering() ==
837 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
838 CXI->getSyncScopeID() ==
839 cast<AtomicCmpXchgInst>(I2)->getSyncScopeID();
840 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
841 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
842 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
843 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
844 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID();
845 if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I1))
846 return SVI->getShuffleMask() ==
847 cast<ShuffleVectorInst>(I2)->getShuffleMask();
848 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I1))
849 return GEP->getSourceElementType() ==
850 cast<GetElementPtrInst>(I2)->getSourceElementType();
851
852 return true;
853}
854
856 return isIdenticalToWhenDefined(I) &&
857 SubclassOptionalData == I->SubclassOptionalData;
858}
859
861 if (getOpcode() != I->getOpcode() ||
862 getNumOperands() != I->getNumOperands() ||
863 getType() != I->getType())
864 return false;
865
866 // If both instructions have no operands, they are identical.
867 if (getNumOperands() == 0 && I->getNumOperands() == 0)
868 return this->hasSameSpecialState(I);
869
870 // We have two instructions of identical opcode and #operands. Check to see
871 // if all operands are the same.
872 if (!std::equal(op_begin(), op_end(), I->op_begin()))
873 return false;
874
875 // WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()!
876 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
877 const PHINode *otherPHI = cast<PHINode>(I);
878 return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
879 otherPHI->block_begin());
880 }
881
882 return this->hasSameSpecialState(I);
883}
884
885// Keep this in sync with FunctionComparator::cmpOperations in
886// lib/Transforms/IPO/MergeFunctions.cpp.
888 unsigned flags) const {
889 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
890 bool UseScalarTypes = flags & CompareUsingScalarTypes;
891
892 if (getOpcode() != I->getOpcode() ||
893 getNumOperands() != I->getNumOperands() ||
894 (UseScalarTypes ?
895 getType()->getScalarType() != I->getType()->getScalarType() :
896 getType() != I->getType()))
897 return false;
898
899 // We have two instructions of identical opcode and #operands. Check to see
900 // if all operands are the same type
901 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
902 if (UseScalarTypes ?
903 getOperand(i)->getType()->getScalarType() !=
904 I->getOperand(i)->getType()->getScalarType() :
905 getOperand(i)->getType() != I->getOperand(i)->getType())
906 return false;
907
908 return this->hasSameSpecialState(I, IgnoreAlignment);
909}
910
912 for (const Use &U : uses()) {
913 // PHI nodes uses values in the corresponding predecessor block. For other
914 // instructions, just check to see whether the parent of the use matches up.
915 const Instruction *I = cast<Instruction>(U.getUser());
916 const PHINode *PN = dyn_cast<PHINode>(I);
917 if (!PN) {
918 if (I->getParent() != BB)
919 return true;
920 continue;
921 }
922
923 if (PN->getIncomingBlock(U) != BB)
924 return true;
925 }
926 return false;
927}
928
930 switch (getOpcode()) {
931 default: return false;
932 case Instruction::VAArg:
933 case Instruction::Load:
934 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
935 case Instruction::AtomicCmpXchg:
936 case Instruction::AtomicRMW:
937 case Instruction::CatchPad:
938 case Instruction::CatchRet:
939 return true;
940 case Instruction::Call:
941 case Instruction::Invoke:
942 case Instruction::CallBr:
943 return !cast<CallBase>(this)->onlyWritesMemory();
944 case Instruction::Store:
945 return !cast<StoreInst>(this)->isUnordered();
946 }
947}
948
950 switch (getOpcode()) {
951 default: return false;
952 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
953 case Instruction::Store:
954 case Instruction::VAArg:
955 case Instruction::AtomicCmpXchg:
956 case Instruction::AtomicRMW:
957 case Instruction::CatchPad:
958 case Instruction::CatchRet:
959 return true;
960 case Instruction::Call:
961 case Instruction::Invoke:
962 case Instruction::CallBr:
963 return !cast<CallBase>(this)->onlyReadsMemory();
964 case Instruction::Load:
965 return !cast<LoadInst>(this)->isUnordered();
966 }
967}
968
970 switch (getOpcode()) {
971 default:
972 return false;
973 case Instruction::AtomicCmpXchg:
974 case Instruction::AtomicRMW:
975 case Instruction::Fence:
976 return true;
977 case Instruction::Load:
978 return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
979 case Instruction::Store:
980 return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
981 }
982}
983
985 assert(isAtomic());
986 switch (getOpcode()) {
987 default:
988 return false;
989 case Instruction::AtomicCmpXchg:
990 case Instruction::AtomicRMW:
991 case Instruction::Load:
992 return true;
993 }
994}
995
997 assert(isAtomic());
998 switch (getOpcode()) {
999 default:
1000 return false;
1001 case Instruction::AtomicCmpXchg:
1002 case Instruction::AtomicRMW:
1003 case Instruction::Store:
1004 return true;
1005 }
1006}
1007
1009 switch (getOpcode()) {
1010 default:
1011 return false;
1012 case Instruction::AtomicRMW:
1013 return cast<AtomicRMWInst>(this)->isVolatile();
1014 case Instruction::Store:
1015 return cast<StoreInst>(this)->isVolatile();
1016 case Instruction::Load:
1017 return cast<LoadInst>(this)->isVolatile();
1018 case Instruction::AtomicCmpXchg:
1019 return cast<AtomicCmpXchgInst>(this)->isVolatile();
1020 case Instruction::Call:
1021 case Instruction::Invoke:
1022 // There are a very limited number of intrinsics with volatile flags.
1023 if (auto *II = dyn_cast<IntrinsicInst>(this)) {
1024 if (auto *MI = dyn_cast<MemIntrinsic>(II))
1025 return MI->isVolatile();
1026 switch (II->getIntrinsicID()) {
1027 default: break;
1028 case Intrinsic::matrix_column_major_load:
1029 return cast<ConstantInt>(II->getArgOperand(2))->isOne();
1030 case Intrinsic::matrix_column_major_store:
1031 return cast<ConstantInt>(II->getArgOperand(3))->isOne();
1032 }
1034 return false;
1035 }
1036}
1037
1039 switch (getOpcode()) {
1040 case Instruction::Store:
1041 return cast<StoreInst>(this)->getValueOperand()->getType();
1042 case Instruction::Load:
1043 case Instruction::AtomicRMW:
1044 return getType();
1045 case Instruction::AtomicCmpXchg:
1046 return cast<AtomicCmpXchgInst>(this)->getNewValOperand()->getType();
1047 case Instruction::Call:
1048 case Instruction::Invoke:
1049 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(this)) {
1050 switch (II->getIntrinsicID()) {
1051 case Intrinsic::masked_load:
1052 case Intrinsic::masked_gather:
1053 case Intrinsic::masked_expandload:
1054 case Intrinsic::vp_load:
1055 case Intrinsic::vp_gather:
1056 case Intrinsic::experimental_vp_strided_load:
1057 return II->getType();
1058 case Intrinsic::masked_store:
1059 case Intrinsic::masked_scatter:
1060 case Intrinsic::masked_compressstore:
1061 case Intrinsic::vp_store:
1062 case Intrinsic::vp_scatter:
1063 case Intrinsic::experimental_vp_strided_store:
1064 return II->getOperand(0)->getType();
1065 default:
1066 break;
1067 }
1068 }
1069 }
1070
1071 return nullptr;
1072}
1073
1075 bool IncludePhaseOneUnwind) {
1076 // Because phase one unwinding skips cleanup landingpads, we effectively
1077 // unwind past this frame, and callers need to have valid unwind info.
1078 if (LP->isCleanup())
1079 return IncludePhaseOneUnwind;
1080
1081 for (unsigned I = 0; I < LP->getNumClauses(); ++I) {
1082 Constant *Clause = LP->getClause(I);
1083 // catch ptr null catches all exceptions.
1084 if (LP->isCatch(I) && isa<ConstantPointerNull>(Clause))
1085 return false;
1086 // filter [0 x ptr] catches all exceptions.
1087 if (LP->isFilter(I) && Clause->getType()->getArrayNumElements() == 0)
1088 return false;
1089 }
1090
1091 // May catch only some subset of exceptions, in which case other exceptions
1092 // will continue unwinding.
1093 return true;
1094}
1095
1096bool Instruction::mayThrow(bool IncludePhaseOneUnwind) const {
1097 switch (getOpcode()) {
1098 case Instruction::Call:
1099 return !cast<CallInst>(this)->doesNotThrow();
1100 case Instruction::CleanupRet:
1101 return cast<CleanupReturnInst>(this)->unwindsToCaller();
1102 case Instruction::CatchSwitch:
1103 return cast<CatchSwitchInst>(this)->unwindsToCaller();
1104 case Instruction::Resume:
1105 return true;
1106 case Instruction::Invoke: {
1107 // Landingpads themselves don't unwind -- however, an invoke of a skipped
1108 // landingpad may continue unwinding.
1109 BasicBlock *UnwindDest = cast<InvokeInst>(this)->getUnwindDest();
1110 Instruction *Pad = UnwindDest->getFirstNonPHI();
1111 if (auto *LP = dyn_cast<LandingPadInst>(Pad))
1112 return canUnwindPastLandingPad(LP, IncludePhaseOneUnwind);
1113 return false;
1114 }
1115 case Instruction::CleanupPad:
1116 // Treat the same as cleanup landingpad.
1117 return IncludePhaseOneUnwind;
1118 default:
1119 return false;
1120 }
1121}
1122
1124 return mayWriteToMemory() || mayThrow() || !willReturn();
1125}
1126
1128 return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) &&
1129 !this->isTerminator() && !this->isEHPad();
1130}
1131
1133 // Volatile store isn't guaranteed to return; see LangRef.
1134 if (auto *SI = dyn_cast<StoreInst>(this))
1135 return !SI->isVolatile();
1136
1137 if (const auto *CB = dyn_cast<CallBase>(this))
1138 return CB->hasFnAttr(Attribute::WillReturn);
1139 return true;
1140}
1141
1143 auto *II = dyn_cast<IntrinsicInst>(this);
1144 if (!II)
1145 return false;
1146 Intrinsic::ID ID = II->getIntrinsicID();
1147 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
1148}
1149
1151 auto *II = dyn_cast<IntrinsicInst>(this);
1152 if (!II)
1153 return false;
1154 Intrinsic::ID ID = II->getIntrinsicID();
1155 return ID == Intrinsic::launder_invariant_group ||
1156 ID == Intrinsic::strip_invariant_group;
1157}
1158
1160 return isa<DbgInfoIntrinsic>(this) || isa<PseudoProbeInst>(this);
1161}
1162
1163const Instruction *
1165 for (const Instruction *I = getNextNode(); I; I = I->getNextNode())
1166 if (!isa<DbgInfoIntrinsic>(I) && !(SkipPseudoOp && isa<PseudoProbeInst>(I)))
1167 return I;
1168 return nullptr;
1169}
1170
1171const Instruction *
1173 for (const Instruction *I = getPrevNode(); I; I = I->getPrevNode())
1174 if (!isa<DbgInfoIntrinsic>(I) && !(SkipPseudoOp && isa<PseudoProbeInst>(I)))
1175 return I;
1176 return nullptr;
1177}
1178
1180 if (isa<DbgInfoIntrinsic>(this))
1181 if (const Instruction *Next = getNextNonDebugInstruction())
1182 return Next->getDebugLoc();
1183 return getDebugLoc();
1184}
1185
1187 if (auto *II = dyn_cast<IntrinsicInst>(this))
1188 return II->isAssociative();
1189 unsigned Opcode = getOpcode();
1190 if (isAssociative(Opcode))
1191 return true;
1192
1193 switch (Opcode) {
1194 case FMul:
1195 case FAdd:
1196 return cast<FPMathOperator>(this)->hasAllowReassoc() &&
1197 cast<FPMathOperator>(this)->hasNoSignedZeros();
1198 default:
1199 return false;
1200 }
1201}
1202
1204 if (auto *II = dyn_cast<IntrinsicInst>(this))
1205 return II->isCommutative();
1206 // TODO: Should allow icmp/fcmp?
1207 return isCommutative(getOpcode());
1208}
1209
1211 switch (getOpcode()) {
1212#define HANDLE_TERM_INST(N, OPC, CLASS) \
1213 case Instruction::OPC: \
1214 return static_cast<const CLASS *>(this)->getNumSuccessors();
1215#include "llvm/IR/Instruction.def"
1216 default:
1217 break;
1218 }
1219 llvm_unreachable("not a terminator");
1220}
1221
1223 switch (getOpcode()) {
1224#define HANDLE_TERM_INST(N, OPC, CLASS) \
1225 case Instruction::OPC: \
1226 return static_cast<const CLASS *>(this)->getSuccessor(idx);
1227#include "llvm/IR/Instruction.def"
1228 default:
1229 break;
1230 }
1231 llvm_unreachable("not a terminator");
1232}
1233
1235 switch (getOpcode()) {
1236#define HANDLE_TERM_INST(N, OPC, CLASS) \
1237 case Instruction::OPC: \
1238 return static_cast<CLASS *>(this)->setSuccessor(idx, B);
1239#include "llvm/IR/Instruction.def"
1240 default:
1241 break;
1242 }
1243 llvm_unreachable("not a terminator");
1244}
1245
1247 for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors();
1248 Idx != NumSuccessors; ++Idx)
1249 if (getSuccessor(Idx) == OldBB)
1250 setSuccessor(Idx, NewBB);
1251}
1252
1253Instruction *Instruction::cloneImpl() const {
1254 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
1255}
1256
1258 MDNode *ProfileData = getBranchWeightMDNode(*this);
1259 if (!ProfileData)
1260 return;
1261 unsigned FirstIdx = getBranchWeightOffset(ProfileData);
1262 if (ProfileData->getNumOperands() != 2 + FirstIdx)
1263 return;
1264
1265 unsigned SecondIdx = FirstIdx + 1;
1267 // If there are more weights past the second, we can't swap them
1268 if (ProfileData->getNumOperands() > SecondIdx + 1)
1269 return;
1270 for (unsigned Idx = 0; Idx < FirstIdx; ++Idx) {
1271 Ops.push_back(ProfileData->getOperand(Idx));
1272 }
1273 // Switch the order of the weights
1274 Ops.push_back(ProfileData->getOperand(SecondIdx));
1275 Ops.push_back(ProfileData->getOperand(FirstIdx));
1276 setMetadata(LLVMContext::MD_prof,
1277 MDNode::get(ProfileData->getContext(), Ops));
1278}
1279
1281 ArrayRef<unsigned> WL) {
1282 if (!SrcInst.hasMetadata())
1283 return;
1284
1285 SmallDenseSet<unsigned, 4> WLS(WL.begin(), WL.end());
1286
1287 // Otherwise, enumerate and copy over metadata from the old instruction to the
1288 // new one.
1290 SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);
1291 for (const auto &MD : TheMDs) {
1292 if (WL.empty() || WLS.count(MD.first))
1293 setMetadata(MD.first, MD.second);
1294 }
1295 if (WL.empty() || WLS.count(LLVMContext::MD_dbg))
1296 setDebugLoc(SrcInst.getDebugLoc());
1297}
1298
1300 Instruction *New = nullptr;
1301 switch (getOpcode()) {
1302 default:
1303 llvm_unreachable("Unhandled Opcode.");
1304#define HANDLE_INST(num, opc, clas) \
1305 case Instruction::opc: \
1306 New = cast<clas>(this)->cloneImpl(); \
1307 break;
1308#include "llvm/IR/Instruction.def"
1309#undef HANDLE_INST
1310 }
1311
1312 New->SubclassOptionalData = SubclassOptionalData;
1313 New->copyMetadata(*this);
1314 return New;
1315}
amdgpu AMDGPU Register Bank Select
Rewrite undef for PHI
This file contains the simple types necessary to represent the attributes associated with functions a...
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
This file defines the DenseSet and SmallDenseSet classes.
Hexagon Common GEP
IRTranslator LLVM IR MI
static bool canUnwindPastLandingPad(const LandingPadInst *LP, bool IncludePhaseOneUnwind)
#define I(x, y, z)
Definition: MD5.cpp:58
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
Module.h This file contains the declarations for the Module class.
uint64_t IntrinsicInst * II
llvm::cl::opt< bool > UseNewDbgInfoFormat
This file contains the declarations for profiling metadata utility functions.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
an instruction to allocate memory on the stack
Definition: Instructions.h:61
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:154
iterator begin() const
Definition: ArrayRef.h:153
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:495
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:696
AttributeMask & addAttribute(Attribute::AttrKind Val)
Add an attribute to the mask.
Definition: AttributeMask.h:44
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition: Attributes.cpp:910
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator end()
Definition: BasicBlock.h:461
void deleteTrailingDbgRecords()
Delete any trailing DbgRecords at the end of this block, see setTrailingDbgRecords.
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:416
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:367
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:219
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:177
bool IsNewDbgInfoFormat
Flag recording whether or not this block stores debug-info in the form of intrinsic instructions (fal...
Definition: BasicBlock.h:67
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:747
This is an important base class in LLVM.
Definition: Constant.h:42
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.
static iterator_range< simple_ilist< DbgRecord >::iterator > getEmptyDbgRecordRange()
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(DbgMarker *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere, bool InsertAtHead=false)
Clone all DbgMarkers from From into this marker.
void removeMarker()
Handle the removal of a marker: the position of debug-info has gone away, but the stored debug record...
void absorbDebugValues(DbgMarker &Src, bool InsertAtHead)
Transfer any DbgRecords from Src into this DbgMarker.
void dropDbgRecords()
Erase all DbgRecords in this DbgMarker.
void dropOneDbgRecord(DbgRecord *DR)
Erase a single DbgRecord from this marker.
simple_ilist< DbgRecord > StoredDbgRecords
List of DbgRecords, the non-instruction equivalent of llvm.dbg.
Base class for non-instruction debug metadata records that have positions within IR.
A debug info location.
Definition: DebugLoc.h:33
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:20
An instruction for ordering other memory operations.
Definition: Instructions.h:420
static GEPNoWrapFlags none()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:915
bool isValid() const
Definition: Instruction.h:61
InsertPosition(std::nullptr_t)
Definition: Instruction.h:54
This instruction inserts a struct field of array element value into an aggregate value.
const DebugLoc & getStableDebugLoc() const
Fetch the debug location for this node, unless this is a debug intrinsic, in which case fetch the deb...
DbgMarker * DebugMarker
Optional marker recording the position for debugging information that takes effect immediately before...
Definition: Instruction.h:84
bool mayThrow(bool IncludePhaseOneUnwind=false) const LLVM_READONLY
Return true if this instruction may throw an exception.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
Definition: Instruction.cpp:78
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
bool isLifetimeStartOrEnd() const LLVM_READONLY
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction,...
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const LLVM_READONLY
This function determines if the specified instruction executes the same operation as the current one.
void setHasNoSignedZeros(bool B)
Set or clear the no-signed-zeros flag on this instruction, which must be an operator which supports t...
void moveBeforePreserving(Instruction *MovePos)
Perform a moveBefore operation, while signalling that the caller intends to preserve the original ord...
bool hasNoSignedZeros() const LLVM_READONLY
Determine whether the no-signed-zeros flag is set.
iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
bool hasPoisonGeneratingReturnAttributes() const LLVM_READONLY
Return true if this instruction has poison-generating attribute.
bool isDebugOrPseudoInst() const LLVM_READONLY
Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
void setHasAllowContract(bool B)
Set or clear the allow-contract flag on this instruction, which must be an operator which supports th...
bool hasAtomicStore() const LLVM_READONLY
Return true if this atomic instruction stores to memory.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
bool isOnlyUserOfAnyOperand()
It checks if this instruction is the only user of at least one of its operands.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
Definition: Instruction.h:104
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
Definition: Instruction.cpp:97
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:466
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:66
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
void setHasNoNaNs(bool B)
Set or clear the no-nans flag on this instruction, which must be an operator which supports this flag...
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
const Instruction * getPrevNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the previous non-debug instruction in the same basic block as 'this',...
void setHasApproxFunc(bool B)
Set or clear the approximate-math-functions flag on this instruction, which must be an operator which...
void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
Definition: Instruction.h:363
bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
void setHasAllowReassoc(bool B)
Set or clear the reassociation flag on this instruction, which must be an operator which supports thi...
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Definition: Instruction.h:824
void dropPoisonGeneratingReturnAttributes()
Drops return attributes that may generate poison.
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:92
bool isFast() const LLVM_READONLY
Determine whether all fast-math-flags are set.
void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
bool isIdenticalToWhenDefined(const Instruction *I) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:70
void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
void dropOneDbgRecord(DbgRecord *I)
Erase a single DbgRecord I that is attached to this instruction.
void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
Definition: Instruction.h:277
Type * getAccessType() const LLVM_READONLY
Return the type this instruction accesses in memory, if any.
bool hasSameSpecialState(const Instruction *I2, bool IgnoreAlignment=false) const LLVM_READONLY
This function determines if the speficied instruction has the same "special" characteristics as the c...
bool hasAllowReciprocal() const LLVM_READONLY
Determine whether the allow-reciprocal flag is set.
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
void dropUBImplyingAttrsAndMetadata()
Drop any attributes or metadata that can cause immediate undefined behavior.
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs=std::nullopt)
Drop all unknown metadata except for debug locations.
Definition: Metadata.cpp:1596
bool hasNonNeg() const LLVM_READONLY
Determine whether the the nneg flag is set.
bool hasPoisonGeneratingFlags() const LLVM_READONLY
Return true if this operator has flags which may cause this instruction to evaluate to poison despite...
bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
const Instruction * getNextNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the next non-debug instruction in the same basic block as 'this',...
bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY
Return true if there are any uses of this instruction in blocks other than the specified block.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1642
bool isVolatile() const LLVM_READONLY
Return true if this instruction has a volatile memory access.
void setHasNoInfs(bool B)
Set or clear the no-infs flag on this instruction, which must be an operator which supports this flag...
void adoptDbgRecords(BasicBlock *BB, InstListType::iterator It, bool InsertAtHead)
Transfer any DbgRecords on the position It onto this instruction, by simply adopting the sequence of ...
FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
const char * getOpcodeName() const
Definition: Instruction.h:276
bool willReturn() const LLVM_READONLY
Return true if the instruction will return (unwinding is considered as a form of returning control fl...
bool hasApproxFunc() const LLVM_READONLY
Determine whether the approximate-math-functions flag is set.
@ CompareIgnoringAlignment
Check for equivalence ignoring load/store alignment.
Definition: Instruction.h:890
@ CompareUsingScalarTypes
Check for equivalence treating a type and a vector of that type as equivalent.
Definition: Instruction.h:893
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:406
void moveAfterPreserving(Instruction *MovePos)
See moveBeforePreserving .
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:274
bool hasAtomicLoad() const LLVM_READONLY
Return true if this atomic instruction loads from memory.
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
void dropPoisonGeneratingMetadata()
Drops metadata that may generate poison.
void setHasAllowReciprocal(bool B)
Set or clear the allow-reciprocal flag on this instruction, which must be an operator which supports ...
void handleMarkerRemoval()
Handle the debug-info implications of this instruction being removed.
Definition: Instruction.cpp:85
std::optional< InstListType::iterator > getInsertionPointAfterDef()
Get the first insertion point at which the result of this instruction is defined.
void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void dropUBImplyingAttrsAndUnknownMetadata(ArrayRef< unsigned > KnownIDs={})
This function drops non-debug unknown metadata (through dropUnknownNonDebugMetadata).
bool isIdenticalTo(const Instruction *I) const LLVM_READONLY
Return true if the specified instruction is exactly identical to the current one.
std::optional< simple_ilist< DbgRecord >::iterator > getDbgReinsertionPosition()
Return an iterator to the position of the "Next" DbgRecord after this instruction,...
bool isLaunderOrStripInvariantGroup() const LLVM_READONLY
Return true if the instruction is a llvm.launder.invariant.group or llvm.strip.invariant....
bool hasAllowContract() const LLVM_READONLY
Determine whether the allow-contract flag is set.
bool hasPoisonGeneratingMetadata() const LLVM_READONLY
Return true if this instruction has poison-generating metadata.
Instruction(const Instruction &)=delete
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:463
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
void setFast(bool B)
Set or clear all fast-math-flags on this instruction, which must be an operator which supports this f...
bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
void dropDbgRecords()
Erase any DbgRecords attached to this instruction.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Definition: Instruction.cpp:74
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool isSafeToRemove() const LLVM_READONLY
Return true if the instruction can be removed if the result is unused.
InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
bool hasDbgRecords() const
Returns true if any DbgRecords are attached to this instruction.
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
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:174
Metadata node.
Definition: Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1430
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1542
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1436
LLVMContext & getContext() const
Definition: Metadata.h:1233
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:291
const_block_iterator block_begin() const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Instruction that can have a nneg flag (zext/uitofp).
Definition: InstrTypes.h:722
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:290
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:290
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1833
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
op_range operands()
Definition: User.h:242
op_iterator op_begin()
Definition: User.h:234
Value * getOperand(unsigned i) const
Definition: User.h:169
unsigned getNumOperands() const
Definition: User.h:191
op_iterator op_end()
Definition: User.h:236
static void handleRAUW(Value *From, Value *To)
Definition: Metadata.cpp:544
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
unsigned char SubclassOptionalData
Hold subclass data that can be dropped.
Definition: Value.h:84
bool isUsedByMetadata() const
Return true if there is metadata referencing this value.
Definition: Value.h:557
bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
Definition: Metadata.cpp:1539
iterator_range< use_iterator > uses()
Definition: Value.h:376
const ParentTy * getParent() const
Definition: ilist_node.h:32
void splice(iterator where, iplist_impl &L2)
Definition: ilist.h:266
base_list_type::iterator iterator
Definition: ilist.h:121
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.
AttributeMask getUBImplyingAttributes()
Get param/return attributes which imply immediate undefined behavior if an invalid value is passed.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
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:1729
@ Other
Any other memory.
@ Or
Bitwise or logical OR of integers.
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
@ FMul
Product of floats.
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.