LLVM 24.0.0git
Instructions.cpp
Go to the documentation of this file.
1//===- Instructions.cpp - Implement the LLVM instructions -----------------===//
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 all of the non-inline methods for the LLVM instruction
10// classes.
11//
12//===----------------------------------------------------------------------===//
13
15#include "IROptions.h"
16#include "LLVMContextImpl.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/IR/Attributes.h"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/Constant.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/MDBuilder.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/Operator.h"
39#include "llvm/IR/Type.h"
40#include "llvm/IR/Value.h"
48#include "llvm/Support/ModRef.h"
50#include <algorithm>
51#include <cassert>
52#include <cstdint>
53#include <optional>
54#include <vector>
55
56using namespace llvm;
57
58//===----------------------------------------------------------------------===//
59// AllocaInst Class
60//===----------------------------------------------------------------------===//
61
63 return DL.getTypeAllocSize(getAllocatedType());
64}
65
66std::optional<TypeSize>
69 // Zero-sized types can return early since 0 * N = 0 for any array size N.
70 if (Size.isZero())
71 return Size;
72 if (isArrayAllocation()) {
74 if (!C)
75 return std::nullopt;
76 std::optional<uint64_t> NumElements = C->getValue().tryZExtValue();
77 if (!NumElements)
78 return std::nullopt;
79 assert(!Size.isScalable() && "Array elements cannot have a scalable size");
80 auto CheckedProd =
81 checkedMulUnsigned(Size.getKnownMinValue(), *NumElements);
82 if (!CheckedProd)
83 return std::nullopt;
84 return TypeSize::getFixed(*CheckedProd);
85 }
86 return Size;
87}
88
89std::optional<TypeSize>
91 std::optional<TypeSize> Size = getAllocationSize(DL);
92 if (!Size)
93 return std::nullopt;
94 auto CheckedProd = checkedMulUnsigned(Size->getKnownMinValue(),
95 static_cast<TypeSize::ScalarTy>(8));
96 if (!CheckedProd)
97 return std::nullopt;
98 return TypeSize::get(*CheckedProd, Size->isScalable());
99}
100
101//===----------------------------------------------------------------------===//
102// SelectInst Class
103//===----------------------------------------------------------------------===//
104
105/// areInvalidOperands - Return a string if the specified operands are invalid
106/// for a select operation, otherwise return null.
107const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
108 if (Op1->getType() != Op2->getType())
109 return "both values to select must have same type";
110
111 if (Op1->getType()->isTokenTy())
112 return "select values cannot have token type";
113
114 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
115 // Vector select.
116 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
117 return "vector select condition element type must be i1";
119 if (!ET)
120 return "selected values for vector select must be vectors";
121 if (ET->getElementCount() != VT->getElementCount())
122 return "vector select requires selected vectors to have "
123 "the same vector length as select condition";
124 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
125 return "select condition must be i1 or <n x i1>";
126 }
127 return nullptr;
128}
129
130//===----------------------------------------------------------------------===//
131// PHINode Class
132//===----------------------------------------------------------------------===//
133
134PHINode::PHINode(const PHINode &PN)
135 : Instruction(PN.getType(), Instruction::PHI, AllocMarker),
136 ReservedSpace(PN.getNumOperands()) {
139 std::copy(PN.op_begin(), PN.op_end(), op_begin());
140 copyIncomingBlocks(make_range(PN.block_begin(), PN.block_end()));
141 FMF = PN.FMF;
142}
143
144// removeIncomingValue - Remove an incoming value. This is useful if a
145// predecessor basic block is deleted.
146Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
147 Value *Removed = getIncomingValue(Idx);
148 // Swap with the end of the list.
149 unsigned Last = getNumOperands() - 1;
150 if (Idx != Last) {
153 }
154
155 // Nuke the last value.
156 Op<-1>().set(nullptr);
158
159 // If the PHI node is dead, because it has zero entries, nuke it now.
160 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
161 // If anyone is using this PHI, make them use a dummy value instead...
164 }
165 return Removed;
166}
167
168void PHINode::removeIncomingValueIf(function_ref<bool(unsigned)> Predicate,
169 bool DeletePHIIfEmpty) {
170 unsigned NumOps = getNumIncomingValues();
171
172 // Loop backwards in case the predicate is purely index based.
173 for (unsigned Idx = NumOps; Idx-- > 0;) {
174 if (Predicate(Idx)) {
175 unsigned LastIdx = NumOps - 1;
176 if (Idx != LastIdx) {
177 setIncomingValue(Idx, getIncomingValue(LastIdx));
178 setIncomingBlock(Idx, getIncomingBlock(LastIdx));
179 }
180 getOperandUse(LastIdx).set(nullptr);
181 NumOps--;
182 }
183 }
184
186
187 // If the PHI node is dead, because it has zero entries, nuke it now.
188 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
189 // If anyone is using this PHI, make them use a dummy value instead...
192 }
193}
194
195/// growOperands - grow operands - This grows the operand list in response
196/// to a push_back style of operation. This grows the number of ops by 1.5
197/// times.
198///
199void PHINode::growOperands() {
200 unsigned e = getNumOperands();
201 unsigned NumOps = e + e / 2;
202 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
203
204 ReservedSpace = NumOps;
205 growHungoffUses(ReservedSpace, /*WithExtraValues=*/true);
206}
207
208/// hasConstantValue - If the specified PHI node always merges together the same
209/// value, return the value, otherwise return null.
211 // Exploit the fact that phi nodes always have at least one entry.
212 Value *ConstantValue = getIncomingValue(0);
213 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
214 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
215 if (ConstantValue != this)
216 return nullptr; // Incoming values not all the same.
217 // The case where the first value is this PHI.
218 ConstantValue = getIncomingValue(i);
219 }
220 if (ConstantValue == this)
221 return PoisonValue::get(getType());
222 return ConstantValue;
223}
224
225/// hasConstantOrUndefValue - Whether the specified PHI node always merges
226/// together the same value, assuming that undefs result in the same value as
227/// non-undefs.
228/// Unlike \ref hasConstantValue, this does not return a value because the
229/// unique non-undef incoming value need not dominate the PHI node.
231 Value *ConstantValue = nullptr;
232 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
233 Value *Incoming = getIncomingValue(i);
234 if (Incoming != this && !isa<UndefValue>(Incoming)) {
235 if (ConstantValue && ConstantValue != Incoming)
236 return false;
237 ConstantValue = Incoming;
238 }
239 }
240 return true;
241}
242
243//===----------------------------------------------------------------------===//
244// LandingPadInst Implementation
245//===----------------------------------------------------------------------===//
246
247LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
248 const Twine &NameStr,
249 InsertPosition InsertBefore)
250 : Instruction(RetTy, Instruction::LandingPad, AllocMarker, InsertBefore) {
251 init(NumReservedValues, NameStr);
252}
253
254LandingPadInst::LandingPadInst(const LandingPadInst &LP)
255 : Instruction(LP.getType(), Instruction::LandingPad, AllocMarker),
256 ReservedSpace(LP.getNumOperands()) {
259 Use *OL = getOperandList();
260 const Use *InOL = LP.getOperandList();
261 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
262 OL[I] = InOL[I];
263
264 setCleanup(LP.isCleanup());
265}
266
267LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
268 const Twine &NameStr,
269 InsertPosition InsertBefore) {
270 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
271}
272
273void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
274 ReservedSpace = NumReservedValues;
275 allocHungoffUses(ReservedSpace);
277 setName(NameStr);
278 setCleanup(false);
279}
280
281/// growOperands - grow operands - This grows the operand list in response to a
282/// push_back style of operation. This grows the number of ops by 2 times.
283void LandingPadInst::growOperands(unsigned Size) {
284 unsigned e = getNumOperands();
285 if (ReservedSpace >= e + Size) return;
286 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
287 growHungoffUses(ReservedSpace);
288}
289
291 unsigned OpNo = getNumOperands();
292 growOperands(1);
293 assert(OpNo < ReservedSpace && "Growing didn't work!");
295 getOperandList()[OpNo] = Val;
296}
297
298//===----------------------------------------------------------------------===//
299// CallBase Implementation
300//===----------------------------------------------------------------------===//
301
303 InsertPosition InsertPt) {
304 switch (CB->getOpcode()) {
305 case Instruction::Call:
306 return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt);
307 case Instruction::Invoke:
308 return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt);
309 case Instruction::CallBr:
310 return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt);
311 default:
312 llvm_unreachable("Unknown CallBase sub-class!");
313 }
314}
315
317 InsertPosition InsertPt) {
319 for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) {
320 auto ChildOB = CI->getOperandBundleAt(i);
321 if (ChildOB.getTagName() != OpB.getTag())
322 OpDefs.emplace_back(ChildOB);
323 }
324 OpDefs.emplace_back(OpB);
325 return CallBase::Create(CI, OpDefs, InsertPt);
326}
327
329
331 assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
332 return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
333}
334
336 const Value *V = getCalledOperand();
337 if (isa<Function>(V) || isa<Constant>(V))
338 return false;
339 return !isInlineAsm();
340}
341
342/// Tests if this call site must be tail call optimized. Only a CallInst can
343/// be tail call optimized.
345 if (auto *CI = dyn_cast<CallInst>(this))
346 return CI->isMustTailCall();
347 return false;
348}
349
350/// Tests if this call site is marked as a tail call.
352 if (auto *CI = dyn_cast<CallInst>(this))
353 return CI->isTailCall();
354 return false;
355}
356
359 return F->getIntrinsicID();
361}
362
364 FPClassTest Mask = Attrs.getRetNoFPClass();
365
366 if (const Function *F = getCalledFunction())
367 Mask |= F->getAttributes().getRetNoFPClass();
368 return Mask;
369}
370
372 FPClassTest Mask = Attrs.getParamNoFPClass(i);
373
374 if (const Function *F = getCalledFunction())
375 Mask |= F->getAttributes().getParamNoFPClass(i);
376 return Mask;
377}
378
379std::optional<ConstantRange> CallBase::getRange() const {
380 Attribute CallAttr = Attrs.getRetAttr(Attribute::Range);
382 if (const Function *F = getCalledFunction())
383 FnAttr = F->getRetAttribute(Attribute::Range);
384
385 if (CallAttr.isValid() && FnAttr.isValid())
386 return CallAttr.getRange().intersectWith(FnAttr.getRange());
387 if (CallAttr.isValid())
388 return CallAttr.getRange();
389 if (FnAttr.isValid())
390 return FnAttr.getRange();
391 return std::nullopt;
392}
393
395 if (hasRetAttr(Attribute::NonNull))
396 return true;
397
398 if (getRetDereferenceableBytes() > 0 &&
400 return true;
401
402 return false;
403}
404
406 unsigned Index;
407
408 if (Attrs.hasAttrSomewhere(Kind, &Index))
409 return getArgOperand(Index - AttributeList::FirstArgIndex);
410 if (const Function *F = getCalledFunction())
411 if (F->getAttributes().hasAttrSomewhere(Kind, &Index))
412 return getArgOperand(Index - AttributeList::FirstArgIndex);
413
414 return nullptr;
415}
416
417/// Determine whether the argument or parameter has the given attribute.
418bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
419 assert(ArgNo < arg_size() && "Param index out of bounds!");
420
421 if (Attrs.hasParamAttr(ArgNo, Kind))
422 return true;
423
424 const Function *F = getCalledFunction();
425 if (!F)
426 return false;
427
428 if (!F->getAttributes().hasParamAttr(ArgNo, Kind))
429 return false;
430
431 // Take into account mod/ref by operand bundles.
432 switch (Kind) {
433 case Attribute::ReadNone:
435 case Attribute::ReadOnly:
437 case Attribute::WriteOnly:
438 return !hasReadingOperandBundles();
439 default:
440 return true;
441 }
442}
443
445 bool AllowUndefOrPoison) const {
447 "Argument must be a pointer");
448 if (paramHasAttr(ArgNo, Attribute::NonNull) &&
449 (AllowUndefOrPoison || paramHasAttr(ArgNo, Attribute::NoUndef)))
450 return true;
451
452 if (paramHasAttr(ArgNo, Attribute::Dereferenceable) &&
454 getCaller(),
456 return true;
457
458 return false;
459}
460
462 if (Attrs.hasFnAttr(Attribute::NoInline))
463 return true;
464 if (const auto *F = dyn_cast<Function>(getCalledOperand()))
465 return F->isNoInline();
466 return false;
467}
468
469bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
471 return F->getAttributes().hasFnAttr(Kind);
472
473 return false;
474}
475
476bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
478 return F->getAttributes().hasFnAttr(Kind);
479
480 return false;
481}
482
483template <typename AK>
484Attribute CallBase::getFnAttrOnCalledFunction(AK Kind) const {
485 if constexpr (std::is_same_v<AK, Attribute::AttrKind>) {
486 // getMemoryEffects() correctly combines memory effects from the call-site,
487 // operand bundles and function.
488 assert(Kind != Attribute::Memory && "Use getMemoryEffects() instead");
489 }
490
492 return F->getAttributes().getFnAttr(Kind);
493
494 return Attribute();
495}
496
497template LLVM_ABI Attribute
498CallBase::getFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
499template LLVM_ABI Attribute
500CallBase::getFnAttrOnCalledFunction(StringRef Kind) const;
501
502template <typename AK>
503Attribute CallBase::getParamAttrOnCalledFunction(unsigned ArgNo,
504 AK Kind) const {
506
507 if (auto *F = dyn_cast<Function>(V))
508 return F->getAttributes().getParamAttr(ArgNo, Kind);
509
510 return Attribute();
511}
512template LLVM_ABI Attribute CallBase::getParamAttrOnCalledFunction(
513 unsigned ArgNo, Attribute::AttrKind Kind) const;
514template LLVM_ABI Attribute
515CallBase::getParamAttrOnCalledFunction(unsigned ArgNo, StringRef Kind) const;
516
519 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
521}
522
525 const unsigned BeginIndex) {
526 auto It = op_begin() + BeginIndex;
527 for (auto &B : Bundles)
528 It = std::copy(B.input_begin(), B.input_end(), It);
529
530 auto *ContextImpl = getContext().pImpl;
531 auto BI = Bundles.begin();
532 unsigned CurrentIndex = BeginIndex;
533
534 for (auto &BOI : bundle_op_infos()) {
535 assert(BI != Bundles.end() && "Incorrect allocation?");
536
537 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
538 BOI.Begin = CurrentIndex;
539 BOI.End = CurrentIndex + BI->input_size();
540 CurrentIndex = BOI.End;
541 BI++;
542 }
543
544 assert(BI == Bundles.end() && "Incorrect allocation?");
545
546 return It;
547}
548
550 /// When there isn't many bundles, we do a simple linear search.
551 /// Else fallback to a binary-search that use the fact that bundles usually
552 /// have similar number of argument to get faster convergence.
554 for (auto &BOI : bundle_op_infos())
555 if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
556 return BOI;
557
558 llvm_unreachable("Did not find operand bundle for operand!");
559 }
560
561 assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles");
563 OpIdx < std::prev(bundle_op_info_end())->End &&
564 "The Idx isn't in the operand bundle");
565
566 /// We need a decimal number below and to prevent using floating point numbers
567 /// we use an intergal value multiplied by this constant.
568 constexpr unsigned NumberScaling = 1024;
569
572 bundle_op_iterator Current = Begin;
573
574 while (Begin != End) {
575 unsigned ScaledOperandPerBundle =
576 NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin);
577 Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) /
578 ScaledOperandPerBundle);
579 if (Current >= End)
580 Current = std::prev(End);
581 assert(Current < End && Current >= Begin &&
582 "the operand bundle doesn't cover every value in the range");
583 if (OpIdx >= Current->Begin && OpIdx < Current->End)
584 break;
585 if (OpIdx >= Current->End)
586 Begin = Current + 1;
587 else
588 End = Current;
589 }
590
591 assert(OpIdx >= Current->Begin && OpIdx < Current->End &&
592 "the operand bundle doesn't cover every value in the range");
593 return *Current;
594}
595
598 InsertPosition InsertPt) {
599 if (CB->getOperandBundle(ID))
600 return CB;
601
603 CB->getOperandBundlesAsDefs(Bundles);
604 Bundles.push_back(OB);
605 return Create(CB, Bundles, InsertPt);
606}
607
609 InsertPosition InsertPt) {
611 bool CreateNew = false;
612
613 for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) {
614 auto Bundle = CB->getOperandBundleAt(I);
615 if (Bundle.getTagID() == ID) {
616 CreateNew = true;
617 continue;
618 }
619 Bundles.emplace_back(Bundle);
620 }
621
622 return CreateNew ? Create(CB, Bundles, InsertPt) : CB;
623}
624
626 InsertPosition InsertPt) {
627 auto OpBundleCount = CB->getNumOperandBundles();
628 assert(Offset < OpBundleCount &&
629 "Trying to remove non-existant operand bundle");
631 Bundles.reserve(OpBundleCount - 1);
632 size_t I = 0;
633 for (; I != Offset; ++I)
634 Bundles.emplace_back(CB->getOperandBundleAt(I));
635 ++I;
636 for (; I != OpBundleCount; ++I)
637 Bundles.emplace_back(CB->getOperandBundleAt(I));
638 return Create(CB, Bundles, InsertPt);
639}
640
642 // Implementation note: this is a conservative implementation of operand
643 // bundle semantics, where *any* non-assume operand bundle (other than
644 // ptrauth) forces a callsite to be at least readonly.
649 getIntrinsicID() != Intrinsic::assume;
650}
651
660
662 // There are a very limited number of intrinsics with volatile flags.
663 if (const auto *MI = dyn_cast<MemIntrinsic>(this))
664 return MI->isVolatile();
665
666 switch (getIntrinsicID()) {
667 case Intrinsic::matrix_column_major_load:
668 return cast<ConstantInt>(getArgOperand(2))->isOne();
669 case Intrinsic::matrix_column_major_store:
670 return cast<ConstantInt>(getArgOperand(3))->isOne();
671 default:
672 return false;
673 }
674}
675
677 MemoryEffects ME = getAttributes().getMemoryEffects();
678 if (auto *Fn = dyn_cast<Function>(getCalledOperand())) {
679 MemoryEffects FnME = Fn->getMemoryEffects();
680 if (hasOperandBundles()) {
681 // TODO: Add a method to get memory effects for operand bundles instead.
683 FnME |= MemoryEffects::readOnly();
685 FnME |= MemoryEffects::writeOnly();
686 }
687 if (isVolatile()) {
688 // Volatile operations also access inaccessible memory.
690 }
691 ME &= FnME;
692 }
693 return ME;
694}
698
699/// Determine if the function does not access memory.
706
707/// Determine if the function does not access or only reads memory.
714
715/// Determine if the function does not access or only writes memory.
722
723/// Determine if the call can access memmory only using pointers based
724/// on its arguments.
731
732/// Determine if the function may only access memory that is
733/// inaccessible from the IR.
740
741/// Determine if the function may only access memory that is
742/// either inaccessible from the IR or pointed to by its arguments.
750
752 if (OpNo < arg_size()) {
753 // If the argument is passed byval, the callee does not have access to the
754 // original pointer and thus cannot capture it.
755 if (isByValArgument(OpNo))
756 return CaptureInfo::none();
757
759 if (auto *Fn = dyn_cast<Function>(getCalledOperand()))
760 CI &= Fn->getAttributes().getParamAttrs(OpNo).getCaptureInfo();
761 return CI;
762 }
763
764 // Bundles on assumes are captures(none).
765 if (getIntrinsicID() == Intrinsic::assume)
766 return CaptureInfo::none();
767
768 // deopt operand bundles are captures(none)
769 auto &BOI = getBundleOpInfoForOperand(OpNo);
770 auto OBU = operandBundleFromBundleOpInfo(BOI);
771 return OBU.isDeoptOperandBundle() ? CaptureInfo::none() : CaptureInfo::all();
772}
773
775 for (unsigned I = 0, E = arg_size(); I < E; ++I) {
777 continue;
778
780 if (auto *Fn = dyn_cast<Function>(getCalledOperand()))
781 CI &= Fn->getAttributes().getParamAttrs(I).getCaptureInfo();
783 return true;
784 }
785 return false;
786}
787
788//===----------------------------------------------------------------------===//
789// CallInst Implementation
790//===----------------------------------------------------------------------===//
791
792void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
793 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
794 this->FTy = FTy;
795 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
796 "NumOperands not set up?");
797
798#ifndef NDEBUG
799 assert((Args.size() == FTy->getNumParams() ||
800 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
801 "Calling a function with bad signature!");
802
803 for (unsigned i = 0; i != Args.size(); ++i)
804 assert((i >= FTy->getNumParams() ||
805 FTy->getParamType(i) == Args[i]->getType()) &&
806 "Calling a function with a bad signature!");
807#endif
808
809 // Set operands in order of their index to match use-list-order
810 // prediction.
811 llvm::copy(Args, op_begin());
812 setCalledOperand(Func);
813
814 auto It = populateBundleOperandInfos(Bundles, Args.size());
815 (void)It;
816 assert(It + 1 == op_end() && "Should add up!");
817
818 setName(NameStr);
819}
820
821void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
822 this->FTy = FTy;
823 assert(getNumOperands() == 1 && "NumOperands not set up?");
824 setCalledOperand(Func);
825
826 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
827
828 setName(NameStr);
829}
830
831CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
832 AllocInfo AllocInfo, InsertPosition InsertBefore)
833 : CallBase(Ty->getReturnType(), Instruction::Call, AllocInfo,
834 InsertBefore) {
835 init(Ty, Func, Name);
836}
837
838CallInst::CallInst(const CallInst &CI, AllocInfo AllocInfo)
839 : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call, AllocInfo) {
841 "Wrong number of operands allocated");
842 setTailCallKind(CI.getTailCallKind());
844
845 std::copy(CI.op_begin(), CI.op_end(), op_begin());
846 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
848 FMF = CI.FMF;
849}
850
852 InsertPosition InsertPt) {
853 std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
854
855 auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(),
856 Args, OpB, CI->getName(), InsertPt);
857 NewCI->setTailCallKind(CI->getTailCallKind());
858 NewCI->setCallingConv(CI->getCallingConv());
859 NewCI->FMF = CI->FMF;
860 NewCI->setAttributes(CI->getAttributes());
861 NewCI->setDebugLoc(CI->getDebugLoc());
862 return NewCI;
863}
864
865// Update profile weight for call instruction by scaling it using the ratio
866// of S/T. The meaning of "branch_weights" meta data for call instruction is
867// transfered to represent call count.
868void CallInst::updateProfWeight(uint64_t S, uint64_t T) {
869 if (T == 0) {
870 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
871 "div by 0. Ignoring. Likely the function "
872 << getParent()->getParent()->getName()
873 << " has 0 entry count, and contains call instructions "
874 "with non-zero prof info.");
875 return;
876 }
877 scaleProfData(*this, S, T);
878}
879
880//===----------------------------------------------------------------------===//
881// InvokeInst Implementation
882//===----------------------------------------------------------------------===//
883
884void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
885 BasicBlock *IfException, ArrayRef<Value *> Args,
887 const Twine &NameStr) {
888 this->FTy = FTy;
889
891 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
892 "NumOperands not set up?");
893
894#ifndef NDEBUG
895 assert(((Args.size() == FTy->getNumParams()) ||
896 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
897 "Invoking a function with bad signature");
898
899 for (unsigned i = 0, e = Args.size(); i != e; i++)
900 assert((i >= FTy->getNumParams() ||
901 FTy->getParamType(i) == Args[i]->getType()) &&
902 "Invoking a function with a bad signature!");
903#endif
904
905 // Set operands in order of their index to match use-list-order
906 // prediction.
907 llvm::copy(Args, op_begin());
908 setNormalDest(IfNormal);
909 setUnwindDest(IfException);
911
912 auto It = populateBundleOperandInfos(Bundles, Args.size());
913 (void)It;
914 assert(It + 3 == op_end() && "Should add up!");
915
916 setName(NameStr);
917}
918
919InvokeInst::InvokeInst(const InvokeInst &II, AllocInfo AllocInfo)
920 : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke, AllocInfo) {
921 assert(getNumOperands() == II.getNumOperands() &&
922 "Wrong number of operands allocated");
923 setCallingConv(II.getCallingConv());
924 std::copy(II.op_begin(), II.op_end(), op_begin());
925 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
927 SubclassOptionalData = II.SubclassOptionalData;
928}
929
931 InsertPosition InsertPt) {
932 std::vector<Value *> Args(II->arg_begin(), II->arg_end());
933
934 auto *NewII = InvokeInst::Create(
935 II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(),
936 II->getUnwindDest(), Args, OpB, II->getName(), InsertPt);
937 NewII->setCallingConv(II->getCallingConv());
938 NewII->SubclassOptionalData = II->SubclassOptionalData;
939 NewII->setAttributes(II->getAttributes());
940 NewII->setDebugLoc(II->getDebugLoc());
941 return NewII;
942}
943
945 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHIIt());
946}
947
948void InvokeInst::updateProfWeight(uint64_t S, uint64_t T) {
949 if (T == 0) {
950 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
951 "div by 0. Ignoring. Likely the function "
952 << getParent()->getParent()->getName()
953 << " has 0 entry count, and contains call instructions "
954 "with non-zero prof info.");
955 return;
956 }
957 scaleProfData(*this, S, T);
958}
959
960//===----------------------------------------------------------------------===//
961// CallBrInst Implementation
962//===----------------------------------------------------------------------===//
963
964void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
965 ArrayRef<BasicBlock *> IndirectDests,
968 const Twine &NameStr) {
969 this->FTy = FTy;
970
971 assert(getNumOperands() == ComputeNumOperands(Args.size(),
972 IndirectDests.size(),
973 CountBundleInputs(Bundles)) &&
974 "NumOperands not set up?");
975
976#ifndef NDEBUG
977 assert(((Args.size() == FTy->getNumParams()) ||
978 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
979 "Calling a function with bad signature");
980
981 for (unsigned i = 0, e = Args.size(); i != e; i++)
982 assert((i >= FTy->getNumParams() ||
983 FTy->getParamType(i) == Args[i]->getType()) &&
984 "Calling a function with a bad signature!");
985#endif
986
987 // Set operands in order of their index to match use-list-order
988 // prediction.
989 llvm::copy(Args, op_begin());
990 NumIndirectDests = IndirectDests.size();
991 setDefaultDest(Fallthrough);
992 for (unsigned i = 0; i != NumIndirectDests; ++i)
993 setIndirectDest(i, IndirectDests[i]);
995
996 auto It = populateBundleOperandInfos(Bundles, Args.size());
997 (void)It;
998 assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
999
1000 setName(NameStr);
1001}
1002
1003CallBrInst::CallBrInst(const CallBrInst &CBI, AllocInfo AllocInfo)
1004 : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
1005 AllocInfo) {
1007 "Wrong number of operands allocated");
1009 std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
1010 std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
1013 NumIndirectDests = CBI.NumIndirectDests;
1014}
1015
1016CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
1017 InsertPosition InsertPt) {
1018 std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
1019
1020 auto *NewCBI = CallBrInst::Create(
1021 CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(),
1022 CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt);
1023 NewCBI->setCallingConv(CBI->getCallingConv());
1024 NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
1025 NewCBI->setAttributes(CBI->getAttributes());
1026 NewCBI->setDebugLoc(CBI->getDebugLoc());
1027 NewCBI->NumIndirectDests = CBI->NumIndirectDests;
1028 return NewCBI;
1029}
1030
1031//===----------------------------------------------------------------------===//
1032// ReturnInst Implementation
1033//===----------------------------------------------------------------------===//
1034
1035ReturnInst::ReturnInst(const ReturnInst &RI, AllocInfo AllocInfo)
1036 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
1037 AllocInfo) {
1039 "Wrong number of operands allocated");
1040 if (RI.getNumOperands())
1041 Op<0>() = RI.Op<0>();
1043}
1044
1045ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, AllocInfo AllocInfo,
1046 InsertPosition InsertBefore)
1047 : Instruction(Type::getVoidTy(C), Instruction::Ret, AllocInfo,
1048 InsertBefore) {
1049 if (retVal)
1050 Op<0>() = retVal;
1051}
1052
1053//===----------------------------------------------------------------------===//
1054// ResumeInst Implementation
1055//===----------------------------------------------------------------------===//
1056
1057ResumeInst::ResumeInst(const ResumeInst &RI)
1058 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
1059 AllocMarker) {
1060 Op<0>() = RI.Op<0>();
1061}
1062
1063ResumeInst::ResumeInst(Value *Exn, InsertPosition InsertBefore)
1064 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
1065 AllocMarker, InsertBefore) {
1066 Op<0>() = Exn;
1067}
1068
1069//===----------------------------------------------------------------------===//
1070// CleanupReturnInst Implementation
1071//===----------------------------------------------------------------------===//
1072
1073CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI,
1075 : Instruction(CRI.getType(), Instruction::CleanupRet, AllocInfo) {
1077 "Wrong number of operands allocated");
1078 setSubclassData<Instruction::OpaqueField>(
1080 Op<0>() = CRI.Op<0>();
1081 if (CRI.hasUnwindDest())
1082 Op<1>() = CRI.Op<1>();
1083}
1084
1085void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
1086 if (UnwindBB)
1087 setSubclassData<UnwindDestField>(true);
1088
1089 Op<0>() = CleanupPad;
1090 if (UnwindBB)
1091 Op<1>() = UnwindBB;
1092}
1093
1094CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
1096 InsertPosition InsertBefore)
1097 : Instruction(Type::getVoidTy(CleanupPad->getContext()),
1098 Instruction::CleanupRet, AllocInfo, InsertBefore) {
1099 init(CleanupPad, UnwindBB);
1100}
1101
1102//===----------------------------------------------------------------------===//
1103// CatchReturnInst Implementation
1104//===----------------------------------------------------------------------===//
1105void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
1106 Op<0>() = CatchPad;
1107 Op<1>() = BB;
1108}
1109
1110CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
1111 : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
1112 AllocMarker) {
1113 Op<0>() = CRI.Op<0>();
1114 Op<1>() = CRI.Op<1>();
1115}
1116
1117CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
1118 InsertPosition InsertBefore)
1119 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
1120 AllocMarker, InsertBefore) {
1121 init(CatchPad, BB);
1122}
1123
1124//===----------------------------------------------------------------------===//
1125// CatchSwitchInst Implementation
1126//===----------------------------------------------------------------------===//
1127
1128CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
1129 unsigned NumReservedValues,
1130 const Twine &NameStr,
1131 InsertPosition InsertBefore)
1132 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, AllocMarker,
1133 InsertBefore) {
1134 if (UnwindDest)
1135 ++NumReservedValues;
1136 init(ParentPad, UnwindDest, NumReservedValues + 1);
1137 setName(NameStr);
1138}
1139
1140CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
1141 : Instruction(CSI.getType(), Instruction::CatchSwitch, AllocMarker) {
1143 init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
1144 setNumHungOffUseOperands(ReservedSpace);
1145 Use *OL = getOperandList();
1146 const Use *InOL = CSI.getOperandList();
1147 for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
1148 OL[I] = InOL[I];
1149}
1150
1151void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
1152 unsigned NumReservedValues) {
1153 assert(ParentPad && NumReservedValues);
1154
1155 ReservedSpace = NumReservedValues;
1156 allocHungoffUses(ReservedSpace);
1157 setNumHungOffUseOperands(UnwindDest ? 2 : 1);
1158
1159 Op<0>() = ParentPad;
1160 if (UnwindDest) {
1162 setUnwindDest(UnwindDest);
1163 }
1164}
1165
1166/// growOperands - grow operands - This grows the operand list in response to a
1167/// push_back style of operation. This grows the number of ops by 2 times.
1168void CatchSwitchInst::growOperands(unsigned Size) {
1169 unsigned NumOperands = getNumOperands();
1170 assert(NumOperands >= 1);
1171 if (ReservedSpace >= NumOperands + Size)
1172 return;
1173 ReservedSpace = (NumOperands + Size / 2) * 2;
1174 growHungoffUses(ReservedSpace);
1175}
1176
1178 unsigned OpNo = getNumOperands();
1179 growOperands(1);
1180 assert(OpNo < ReservedSpace && "Growing didn't work!");
1182 getOperandList()[OpNo] = Handler;
1183}
1184
1186 // Move all subsequent handlers up one.
1187 Use *EndDst = op_end() - 1;
1188 for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
1189 *CurDst = *(CurDst + 1);
1190 // Null out the last handler use.
1191 *EndDst = nullptr;
1192
1194}
1195
1196//===----------------------------------------------------------------------===//
1197// FuncletPadInst Implementation
1198//===----------------------------------------------------------------------===//
1199void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
1200 const Twine &NameStr) {
1201 assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
1202 llvm::copy(Args, op_begin());
1203 setParentPad(ParentPad);
1204 setName(NameStr);
1205}
1206
1207FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI, AllocInfo AllocInfo)
1208 : Instruction(FPI.getType(), FPI.getOpcode(), AllocInfo) {
1210 "Wrong number of operands allocated");
1211 std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
1213}
1214
1215FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1217 const Twine &NameStr,
1218 InsertPosition InsertBefore)
1219 : Instruction(ParentPad->getType(), Op, AllocInfo, InsertBefore) {
1220 init(ParentPad, Args, NameStr);
1221}
1222
1223//===----------------------------------------------------------------------===//
1224// UnreachableInst Implementation
1225//===----------------------------------------------------------------------===//
1226
1228 InsertPosition InsertBefore)
1229 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable,
1230 AllocMarker, InsertBefore) {}
1231
1232//===----------------------------------------------------------------------===//
1233// UncondBrInst Implementation
1234//===----------------------------------------------------------------------===//
1235
1236UncondBrInst::UncondBrInst(BasicBlock *Target, InsertPosition InsertBefore)
1237 : Instruction(Type::getVoidTy(Target->getContext()), Instruction::UncondBr,
1238 AllocMarker, InsertBefore) {
1239 Op<-1>() = Target;
1240}
1241
1242UncondBrInst::UncondBrInst(const UncondBrInst &BI)
1243 : Instruction(Type::getVoidTy(BI.getContext()), Instruction::UncondBr,
1244 AllocMarker) {
1245 Op<-1>() = BI.Op<-1>();
1247}
1248
1249//===----------------------------------------------------------------------===//
1250// CondBrInst Implementation
1251//===----------------------------------------------------------------------===//
1252
1253void CondBrInst::AssertOK() {
1254 assert(getCondition()->getType()->isIntegerTy(1) &&
1255 "May only branch on boolean predicates!");
1256}
1257
1258CondBrInst::CondBrInst(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse,
1259 InsertPosition InsertBefore)
1260 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::CondBr,
1261 AllocMarker, InsertBefore) {
1262 // Assign in order of operand index to make use-list order predictable.
1263 Op<-3>() = Cond;
1264 Op<-2>() = IfTrue;
1265 Op<-1>() = IfFalse;
1266#ifndef NDEBUG
1267 AssertOK();
1268#endif
1269}
1270
1271CondBrInst::CondBrInst(const CondBrInst &BI)
1272 : Instruction(Type::getVoidTy(BI.getContext()), Instruction::CondBr,
1273 AllocMarker) {
1274 // Assign in order of operand index to make use-list order predictable.
1275 Op<-3>() = BI.Op<-3>();
1276 Op<-2>() = BI.Op<-2>();
1277 Op<-1>() = BI.Op<-1>();
1279}
1280
1282 Op<-1>().swap(Op<-2>());
1283
1284 // Update profile metadata if present and it matches our structural
1285 // expectations.
1287}
1288
1289//===----------------------------------------------------------------------===//
1290// AllocaInst Implementation
1291//===----------------------------------------------------------------------===//
1292
1293static Value *getAISize(LLVMContext &Context, Value *Amt) {
1294 if (!Amt)
1295 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1296 else {
1297 assert(!isa<BasicBlock>(Amt) &&
1298 "Passed basic block into allocation size parameter! Use other ctor");
1299 assert(Amt->getType()->isIntegerTy() &&
1300 "Allocation array size is not an integer!");
1301 }
1302 return Amt;
1303}
1304
1306 assert(Pos.isValid() &&
1307 "Insertion position cannot be null when alignment not provided!");
1308 BasicBlock *BB = Pos.getBasicBlock();
1309 assert(BB->getParent() &&
1310 "BB must be in a Function when alignment not provided!");
1311 const DataLayout &DL = BB->getDataLayout();
1312 return DL.getPrefTypeAlign(Ty);
1313}
1314
1315AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1316 InsertPosition InsertBefore)
1317 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1318
1319AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1320 const Twine &Name, InsertPosition InsertBefore)
1321 : AllocaInst(Ty, AddrSpace, ArraySize,
1322 computeAllocaDefaultAlign(Ty, InsertBefore), Name,
1323 InsertBefore) {}
1324
1325AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1326 Align Align, const Twine &Name,
1327 InsertPosition InsertBefore)
1328 : UnaryInstruction(PointerType::get(Ty->getContext(), AddrSpace), Alloca,
1329 getAISize(Ty->getContext(), ArraySize), InsertBefore),
1330 AllocatedType(Ty) {
1332 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1333 setName(Name);
1334}
1335
1338 return !CI->isOne();
1339 return true;
1340}
1341
1342/// isStaticAlloca - Return true if this alloca is in the entry block of the
1343/// function and is a constant size. If so, the code generator will fold it
1344/// into the prolog/epilog code, so it is basically free.
1346 // Must be constant size.
1347 if (!isa<ConstantInt>(getArraySize())) return false;
1348
1349 // Must be in the entry block.
1350 const BasicBlock *Parent = getParent();
1351 return Parent->isEntryBlock() && !isUsedWithInAlloca();
1352}
1353
1354//===----------------------------------------------------------------------===//
1355// LoadInst Implementation
1356//===----------------------------------------------------------------------===//
1357
1358void LoadInst::AssertOK() {
1360 "Ptr must have pointer type.");
1361}
1362
1364 assert(Pos.isValid() &&
1365 "Insertion position cannot be null when alignment not provided!");
1366 BasicBlock *BB = Pos.getBasicBlock();
1367 assert(BB->getParent() &&
1368 "BB must be in a Function when alignment not provided!");
1369 const DataLayout &DL = BB->getDataLayout();
1370 return DL.getABITypeAlign(Ty);
1371}
1372
1373LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1374 InsertPosition InsertBef)
1375 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1376
1377LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1378 InsertPosition InsertBef)
1379 : LoadInst(Ty, Ptr, Name, isVolatile,
1380 computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {}
1381
1382LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1383 Align Align, InsertPosition InsertBef)
1384 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1385 SyncScope::System, InsertBef) {}
1386
1387LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1388 const LoadStoreInstProperties &Props,
1389 InsertPosition InsertBef)
1390 : LoadInst(Ty, Ptr, Name, Props.IsVolatile, Props.Alignment, Props.Ordering,
1391 Props.SSID, InsertBef) {
1393}
1394
1395LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1397 InsertPosition InsertBef)
1398 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1401 setAtomic(Order, SSID);
1402 AssertOK();
1403 setName(Name);
1404}
1405
1406//===----------------------------------------------------------------------===//
1407// StoreInst Implementation
1408//===----------------------------------------------------------------------===//
1409
1410void StoreInst::AssertOK() {
1411 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1413 "Ptr must have pointer type!");
1414}
1415
1417 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1418
1420 InsertPosition InsertBefore)
1421 : StoreInst(val, addr, isVolatile,
1422 computeLoadStoreDefaultAlign(val->getType(), InsertBefore),
1423 InsertBefore) {}
1424
1426 InsertPosition InsertBefore)
1428 SyncScope::System, InsertBefore) {}
1429
1431 const LoadStoreInstProperties &Props,
1432 InsertPosition InsertBefore)
1433 : StoreInst(Val, Ptr, Props.IsVolatile, Props.Alignment, Props.Ordering,
1434 Props.SSID, InsertBefore) {
1436}
1437
1439 AtomicOrdering Order, SyncScope::ID SSID,
1440 InsertPosition InsertBefore)
1441 : Instruction(Type::getVoidTy(val->getContext()), Store, AllocMarker,
1442 InsertBefore) {
1443 Op<0>() = val;
1444 Op<1>() = addr;
1447 setAtomic(Order, SSID);
1448 AssertOK();
1449}
1450
1451//===----------------------------------------------------------------------===//
1452// AtomicCmpXchgInst Implementation
1453//===----------------------------------------------------------------------===//
1454
1455void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1456 Align Alignment, AtomicOrdering SuccessOrdering,
1457 AtomicOrdering FailureOrdering,
1458 SyncScope::ID SSID) {
1459 Op<0>() = Ptr;
1460 Op<1>() = Cmp;
1461 Op<2>() = NewVal;
1462 setSuccessOrdering(SuccessOrdering);
1463 setFailureOrdering(FailureOrdering);
1464 setSyncScopeID(SSID);
1465 setAlignment(Alignment);
1466
1467 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1468 "All operands must be non-null!");
1470 "Ptr must have pointer type!");
1471 assert(getOperand(1)->getType() == getOperand(2)->getType() &&
1472 "Cmp type and NewVal type must be same!");
1473}
1474
1476 Align Alignment,
1477 AtomicOrdering SuccessOrdering,
1478 AtomicOrdering FailureOrdering,
1479 SyncScope::ID SSID,
1480 InsertPosition InsertBefore)
1481 : Instruction(
1482 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1483 AtomicCmpXchg, AllocMarker, InsertBefore) {
1484 Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
1485}
1486
1487//===----------------------------------------------------------------------===//
1488// AtomicRMWInst Implementation
1489//===----------------------------------------------------------------------===//
1490
1491void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1492 Align Alignment, AtomicOrdering Ordering,
1493 SyncScope::ID SSID, bool Elementwise) {
1494 assert(Ordering != AtomicOrdering::NotAtomic &&
1495 "atomicrmw instructions can only be atomic.");
1496 assert(Ordering != AtomicOrdering::Unordered &&
1497 "atomicrmw instructions cannot be unordered.");
1498 Op<0>() = Ptr;
1499 Op<1>() = Val;
1500 setOperation(Operation);
1501 setOrdering(Ordering);
1502 setSyncScopeID(SSID);
1503 setElementwise(Elementwise);
1504 setAlignment(Alignment);
1505
1506 assert(getOperand(0) && getOperand(1) && "All operands must be non-null!");
1508 "Ptr must have pointer type!");
1509 assert(Ordering != AtomicOrdering::NotAtomic &&
1510 "AtomicRMW instructions must be atomic!");
1511}
1512
1514 Align Alignment, AtomicOrdering Ordering,
1515 SyncScope::ID SSID, bool Elementwise,
1516 InsertPosition InsertBefore)
1517 : Instruction(Val->getType(), AtomicRMW, AllocMarker, InsertBefore) {
1518 Init(Operation, Ptr, Val, Alignment, Ordering, SSID, Elementwise);
1519}
1520
1522 switch (Op) {
1524 return "xchg";
1525 case AtomicRMWInst::Add:
1526 return "add";
1527 case AtomicRMWInst::Sub:
1528 return "sub";
1529 case AtomicRMWInst::And:
1530 return "and";
1532 return "nand";
1533 case AtomicRMWInst::Or:
1534 return "or";
1535 case AtomicRMWInst::Xor:
1536 return "xor";
1537 case AtomicRMWInst::Max:
1538 return "max";
1539 case AtomicRMWInst::Min:
1540 return "min";
1542 return "umax";
1544 return "umin";
1546 return "fadd";
1548 return "fsub";
1550 return "fmax";
1552 return "fmin";
1554 return "fmaximum";
1556 return "fminimum";
1558 return "fmaximumnum";
1560 return "fminimumnum";
1562 return "uinc_wrap";
1564 return "udec_wrap";
1566 return "usub_cond";
1568 return "usub_sat";
1570 return "<invalid operation>";
1571 }
1572
1573 llvm_unreachable("invalid atomicrmw operation");
1574}
1575
1576//===----------------------------------------------------------------------===//
1577// FenceInst Implementation
1578//===----------------------------------------------------------------------===//
1579
1581 SyncScope::ID SSID, InsertPosition InsertBefore)
1582 : Instruction(Type::getVoidTy(C), Fence, AllocMarker, InsertBefore) {
1583 setOrdering(Ordering);
1584 setSyncScopeID(SSID);
1585}
1586
1587//===----------------------------------------------------------------------===//
1588// GetElementPtrInst Implementation
1589//===----------------------------------------------------------------------===//
1590
1591void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1592 const Twine &Name) {
1593 assert(getNumOperands() == 1 + IdxList.size() &&
1594 "NumOperands not initialized?");
1595 Op<0>() = Ptr;
1596 llvm::copy(IdxList, op_begin() + 1);
1597 setName(Name);
1598}
1599
1600GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI,
1602 : Instruction(GEPI.getType(), GetElementPtr, AllocInfo),
1603 SourceElementType(GEPI.SourceElementType),
1604 ResultElementType(GEPI.ResultElementType) {
1605 assert(getNumOperands() == GEPI.getNumOperands() &&
1606 "Wrong number of operands allocated");
1607 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1609}
1610
1612 if (auto *Struct = dyn_cast<StructType>(Ty)) {
1613 if (!Struct->indexValid(Idx))
1614 return nullptr;
1615 return Struct->getTypeAtIndex(Idx);
1616 }
1617 if (!Idx->getType()->isIntOrIntVectorTy())
1618 return nullptr;
1619 if (auto *Array = dyn_cast<ArrayType>(Ty))
1620 return Array->getElementType();
1621 if (auto *Vector = dyn_cast<VectorType>(Ty))
1622 return Vector->getElementType();
1623 return nullptr;
1624}
1625
1627 if (auto *Struct = dyn_cast<StructType>(Ty)) {
1628 if (Idx >= Struct->getNumElements())
1629 return nullptr;
1630 return Struct->getElementType(Idx);
1631 }
1632 if (auto *Array = dyn_cast<ArrayType>(Ty))
1633 return Array->getElementType();
1634 if (auto *Vector = dyn_cast<VectorType>(Ty))
1635 return Vector->getElementType();
1636 return nullptr;
1637}
1638
1639template <typename IndexTy>
1641 if (IdxList.empty())
1642 return Ty;
1643 for (IndexTy V : IdxList.slice(1)) {
1645 if (!Ty)
1646 return Ty;
1647 }
1648 return Ty;
1649}
1650
1654
1656 ArrayRef<Constant *> IdxList) {
1657 return getIndexedTypeInternal(Ty, IdxList);
1658}
1659
1663
1664/// hasAllZeroIndices - Return true if all of the indices of this GEP are
1665/// zeros. If so, the result pointer and the first operand have the same
1666/// value, just potentially different types.
1668 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1670 if (!CI->isZero()) return false;
1671 } else {
1672 return false;
1673 }
1674 }
1675 return true;
1676}
1677
1678/// hasAllConstantIndices - Return true if all of the indices of this GEP are
1679/// constant integers. If so, the result pointer and the first operand have
1680/// a constant offset between them.
1682 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1684 return false;
1685 }
1686 return true;
1687}
1688
1692
1694 GEPNoWrapFlags NW = cast<GEPOperator>(this)->getNoWrapFlags();
1695 if (B)
1697 else
1698 NW = NW.withoutInBounds();
1699 setNoWrapFlags(NW);
1700}
1701
1703 return cast<GEPOperator>(this)->getNoWrapFlags();
1704}
1705
1707 return cast<GEPOperator>(this)->isInBounds();
1708}
1709
1711 return cast<GEPOperator>(this)->hasNoUnsignedSignedWrap();
1712}
1713
1715 return cast<GEPOperator>(this)->hasNoUnsignedWrap();
1716}
1717
1719 APInt &Offset) const {
1720 // Delegate to the generic GEPOperator implementation.
1721 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1722}
1723
1725 const DataLayout &DL, unsigned BitWidth,
1726 SmallMapVector<Value *, APInt, 4> &VariableOffsets,
1727 APInt &ConstantOffset) const {
1728 // Delegate to the generic GEPOperator implementation.
1729 return cast<GEPOperator>(this)->collectOffset(DL, BitWidth, VariableOffsets,
1730 ConstantOffset);
1731}
1732
1733//===----------------------------------------------------------------------===//
1734// ExtractElementInst Implementation
1735//===----------------------------------------------------------------------===//
1736
1737ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1738 const Twine &Name,
1739 InsertPosition InsertBef)
1740 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1741 ExtractElement, AllocMarker, InsertBef) {
1742 assert(isValidOperands(Val, Index) &&
1743 "Invalid extractelement instruction operands!");
1744 Op<0>() = Val;
1745 Op<1>() = Index;
1746 setName(Name);
1747}
1748
1749bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1750 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1751 return false;
1752 return true;
1753}
1754
1755//===----------------------------------------------------------------------===//
1756// InsertElementInst Implementation
1757//===----------------------------------------------------------------------===//
1758
1759InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1760 const Twine &Name,
1761 InsertPosition InsertBef)
1762 : Instruction(Vec->getType(), InsertElement, AllocMarker, InsertBef) {
1763 assert(isValidOperands(Vec, Elt, Index) &&
1764 "Invalid insertelement instruction operands!");
1765 Op<0>() = Vec;
1766 Op<1>() = Elt;
1767 Op<2>() = Index;
1768 setName(Name);
1769}
1770
1772 const Value *Index) {
1773 if (!Vec->getType()->isVectorTy())
1774 return false; // First operand of insertelement must be vector type.
1775
1776 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1777 return false;// Second operand of insertelement must be vector element type.
1778
1779 if (!Index->getType()->isIntegerTy())
1780 return false; // Third operand of insertelement must be an integer.
1781 return true;
1782}
1783
1784//===----------------------------------------------------------------------===//
1785// ShuffleVectorInst Implementation
1786//===----------------------------------------------------------------------===//
1787
1789 assert(V && "Cannot create placeholder of nullptr V");
1790 return PoisonValue::get(V->getType());
1791}
1792
1794 InsertPosition InsertBefore)
1796 InsertBefore) {}
1797
1799 const Twine &Name,
1800 InsertPosition InsertBefore)
1802 InsertBefore) {}
1803
1805 const Twine &Name,
1806 InsertPosition InsertBefore)
1807 : Instruction(
1808 VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1809 cast<VectorType>(Mask->getType())->getElementCount()),
1810 ShuffleVector, AllocMarker, InsertBefore) {
1811 assert(isValidOperands(V1, V2, Mask) &&
1812 "Invalid shuffle vector instruction operands!");
1813
1814 Op<0>() = V1;
1815 Op<1>() = V2;
1816 SmallVector<int, 16> MaskArr;
1817 getShuffleMask(cast<Constant>(Mask), MaskArr);
1818 setShuffleMask(MaskArr);
1819 setName(Name);
1820}
1821
1823 const Twine &Name,
1824 InsertPosition InsertBefore)
1825 : Instruction(
1826 VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1827 Mask.size(), isa<ScalableVectorType>(V1->getType())),
1828 ShuffleVector, AllocMarker, InsertBefore) {
1829 assert(isValidOperands(V1, V2, Mask) &&
1830 "Invalid shuffle vector instruction operands!");
1831 Op<0>() = V1;
1832 Op<1>() = V2;
1833 setShuffleMask(Mask);
1834 setName(Name);
1835}
1836
1838 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
1839 int NumMaskElts = ShuffleMask.size();
1840 SmallVector<int, 16> NewMask(NumMaskElts);
1841 for (int i = 0; i != NumMaskElts; ++i) {
1842 int MaskElt = getMaskValue(i);
1843 if (MaskElt == PoisonMaskElem) {
1844 NewMask[i] = PoisonMaskElem;
1845 continue;
1846 }
1847 assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
1848 MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
1849 NewMask[i] = MaskElt;
1850 }
1851 setShuffleMask(NewMask);
1852 Op<0>().swap(Op<1>());
1853}
1854
1856 ArrayRef<int> Mask) {
1857 // V1 and V2 must be vectors of the same type.
1858 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1859 return false;
1860
1861 if (isa<ScalableVectorType>(V1->getType()))
1862 return (Mask[0] == 0 || Mask[0] == PoisonMaskElem) && all_equal(Mask);
1863
1864 // Make sure the mask elements make sense.
1865 int64_t MaxMaskSz =
1866 cast<FixedVectorType>(V1->getType())->getNumElements() * 2LL;
1867 for (int Elem : Mask)
1868 if (Elem != PoisonMaskElem && Elem >= MaxMaskSz)
1869 return false;
1870 return true;
1871}
1872
1874 const Value *Mask) {
1875 // V1 and V2 must be vectors of the same type.
1876 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1877 return false;
1878
1879 // Mask must be vector of i32, and must be the same kind of vector as the
1880 // input vectors
1881 auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
1882 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) ||
1883 isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType()))
1884 return false;
1885
1886 // Check to see if Mask is valid.
1888 return true;
1889
1890 // NOTE: Through vector ConstantInt we have the potential to support more
1891 // than just zero splat masks but that requires a LangRef change.
1892 if (isa<ScalableVectorType>(MaskTy))
1893 return false;
1894
1895 unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
1896
1897 if (const auto *CI = dyn_cast<ConstantInt>(Mask))
1898 return !CI->uge(V1Size * 2);
1899
1900 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
1901 for (Value *Op : MV->operands()) {
1902 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1903 if (CI->uge(V1Size*2))
1904 return false;
1905 } else if (!isa<UndefValue>(Op)) {
1906 return false;
1907 }
1908 }
1909 return true;
1910 }
1911
1912 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1913 for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements();
1914 i != e; ++i)
1915 if (CDS->getElementAsInteger(i) >= V1Size*2)
1916 return false;
1917 return true;
1918 }
1919
1920 return false;
1921}
1922
1924 SmallVectorImpl<int> &Result) {
1925 ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount();
1926
1927 if (isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) {
1928 int MaskVal = isa<UndefValue>(Mask) ? -1 : 0;
1929 Result.append(EC.getKnownMinValue(), MaskVal);
1930 return;
1931 }
1932
1933 assert(!EC.isScalable() &&
1934 "Scalable vector shuffle mask must be undef or zeroinitializer");
1935
1936 unsigned NumElts = EC.getFixedValue();
1937
1938 Result.reserve(NumElts);
1939
1940 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1941 for (unsigned i = 0; i != NumElts; ++i)
1942 Result.push_back(CDS->getElementAsInteger(i));
1943 return;
1944 }
1945 for (unsigned i = 0; i != NumElts; ++i) {
1946 Constant *C = Mask->getAggregateElement(i);
1947 Result.push_back(isa<UndefValue>(C) ? -1 :
1948 cast<ConstantInt>(C)->getZExtValue());
1949 }
1950}
1951
1953 ShuffleMask.assign(Mask.begin(), Mask.end());
1954 ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType());
1955}
1956
1958 Type *ResultTy) {
1959 Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext());
1960 if (isa<ScalableVectorType>(ResultTy)) {
1961 assert(all_equal(Mask) && "Unexpected shuffle");
1962 Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true);
1963 if (Mask[0] == 0)
1964 return Constant::getNullValue(VecTy);
1965 return PoisonValue::get(VecTy);
1966 }
1968 for (int Elem : Mask) {
1969 if (Elem == PoisonMaskElem)
1970 MaskConst.push_back(PoisonValue::get(Int32Ty));
1971 else
1972 MaskConst.push_back(ConstantInt::get(Int32Ty, Elem));
1973 }
1974 return ConstantVector::get(MaskConst);
1975}
1976
1977static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int64_t NumOpElts) {
1978 assert(!Mask.empty() && "Shuffle mask must contain elements");
1979 bool UsesLHS = false;
1980 bool UsesRHS = false;
1981 for (int I : Mask) {
1982 if (I == -1)
1983 continue;
1984 assert(I >= 0 && I < (NumOpElts * 2) &&
1985 "Out-of-bounds shuffle mask element");
1986 UsesLHS |= (I < NumOpElts);
1987 UsesRHS |= (I >= NumOpElts);
1988 if (UsesLHS && UsesRHS)
1989 return false;
1990 }
1991 // Allow for degenerate case: completely undef mask means neither source is used.
1992 return UsesLHS || UsesRHS;
1993}
1994
1996 // We don't have vector operand size information, so assume operands are the
1997 // same size as the mask.
1998 return isSingleSourceMaskImpl(Mask, NumSrcElts);
1999}
2000
2001static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
2002 if (!isSingleSourceMaskImpl(Mask, NumOpElts))
2003 return false;
2004 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
2005 if (Mask[i] == -1)
2006 continue;
2007 if (Mask[i] != i && Mask[i] != (NumOpElts + i))
2008 return false;
2009 }
2010 return true;
2011}
2012
2014 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2015 return false;
2016 // We don't have vector operand size information, so assume operands are the
2017 // same size as the mask.
2018 return isIdentityMaskImpl(Mask, NumSrcElts);
2019}
2020
2022 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2023 return false;
2024 if (!isSingleSourceMask(Mask, NumSrcElts))
2025 return false;
2026
2027 // The number of elements in the mask must be at least 2.
2028 if (NumSrcElts < 2)
2029 return false;
2030
2031 for (int I = 0, E = Mask.size(); I < E; ++I) {
2032 if (Mask[I] == -1)
2033 continue;
2034 if (Mask[I] != (NumSrcElts - 1 - I) &&
2035 Mask[I] != (NumSrcElts + NumSrcElts - 1 - I))
2036 return false;
2037 }
2038 return true;
2039}
2040
2042 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2043 return false;
2044 if (!isSingleSourceMask(Mask, NumSrcElts))
2045 return false;
2046 for (int I = 0, E = Mask.size(); I < E; ++I) {
2047 if (Mask[I] == -1)
2048 continue;
2049 if (Mask[I] != 0 && Mask[I] != NumSrcElts)
2050 return false;
2051 }
2052 return true;
2053}
2054
2056 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2057 return false;
2058 // Select is differentiated from identity. It requires using both sources.
2059 if (isSingleSourceMask(Mask, NumSrcElts))
2060 return false;
2061 for (int I = 0, E = Mask.size(); I < E; ++I) {
2062 if (Mask[I] == -1)
2063 continue;
2064 if (Mask[I] != I && Mask[I] != (NumSrcElts + I))
2065 return false;
2066 }
2067 return true;
2068}
2069
2071 // Example masks that will return true:
2072 // v1 = <a, b, c, d>
2073 // v2 = <e, f, g, h>
2074 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
2075 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
2076
2077 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2078 return false;
2079 // 1. The number of elements in the mask must be a power-of-2 and at least 2.
2080 int Sz = Mask.size();
2081 if (Sz < 2 || !isPowerOf2_32(Sz))
2082 return false;
2083
2084 // 2. The first element of the mask must be either a 0 or a 1.
2085 if (Mask[0] != 0 && Mask[0] != 1)
2086 return false;
2087
2088 // 3. The difference between the first 2 elements must be equal to the
2089 // number of elements in the mask.
2090 if ((Mask[1] - Mask[0]) != NumSrcElts)
2091 return false;
2092
2093 // 4. The difference between consecutive even-numbered and odd-numbered
2094 // elements must be equal to 2.
2095 for (int I = 2; I < Sz; ++I) {
2096 int MaskEltVal = Mask[I];
2097 if (MaskEltVal == -1)
2098 return false;
2099 int MaskEltPrevVal = Mask[I - 2];
2100 if (MaskEltVal - MaskEltPrevVal != 2)
2101 return false;
2102 }
2103 return true;
2104}
2105
2107 int &Index) {
2108 if (Mask.size() != static_cast<unsigned>(NumSrcElts))
2109 return false;
2110 // Example: shufflevector <4 x n> A, <4 x n> B, <1,2,3,4>
2111 int StartIndex = -1;
2112 for (int I = 0, E = Mask.size(); I != E; ++I) {
2113 int MaskEltVal = Mask[I];
2114 if (MaskEltVal == -1)
2115 continue;
2116
2117 if (StartIndex == -1) {
2118 // Don't support a StartIndex that begins in the second input, or if the
2119 // first non-undef index would access below the StartIndex.
2120 if (MaskEltVal < I || NumSrcElts <= (MaskEltVal - I))
2121 return false;
2122
2123 StartIndex = MaskEltVal - I;
2124 continue;
2125 }
2126
2127 // Splice is sequential starting from StartIndex.
2128 if (MaskEltVal != (StartIndex + I))
2129 return false;
2130 }
2131
2132 if (StartIndex == -1)
2133 return false;
2134
2135 // NOTE: This accepts StartIndex == 0 (COPY).
2136 Index = StartIndex;
2137 return true;
2138}
2139
2141 int NumSrcElts, int &Index) {
2142 // Must extract from a single source.
2143 if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
2144 return false;
2145
2146 // Must be smaller (else this is an Identity shuffle).
2147 if (NumSrcElts <= (int)Mask.size())
2148 return false;
2149
2150 // Find start of extraction, accounting that we may start with an UNDEF.
2151 int SubIndex = -1;
2152 for (int i = 0, e = Mask.size(); i != e; ++i) {
2153 int M = Mask[i];
2154 if (M < 0)
2155 continue;
2156 int Offset = (M % NumSrcElts) - i;
2157 if (0 <= SubIndex && SubIndex != Offset)
2158 return false;
2159 SubIndex = Offset;
2160 }
2161
2162 if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
2163 Index = SubIndex;
2164 return true;
2165 }
2166 return false;
2167}
2168
2170 int NumSrcElts, int &NumSubElts,
2171 int &Index) {
2172 int NumMaskElts = Mask.size();
2173
2174 // Don't try to match if we're shuffling to a smaller size.
2175 if (NumMaskElts < NumSrcElts)
2176 return false;
2177
2178 // TODO: We don't recognize self-insertion/widening.
2179 if (isSingleSourceMaskImpl(Mask, NumSrcElts))
2180 return false;
2181
2182 // Determine which mask elements are attributed to which source.
2183 APInt UndefElts = APInt::getZero(NumMaskElts);
2184 APInt Src0Elts = APInt::getZero(NumMaskElts);
2185 APInt Src1Elts = APInt::getZero(NumMaskElts);
2186 bool Src0Identity = true;
2187 bool Src1Identity = true;
2188
2189 for (int i = 0; i != NumMaskElts; ++i) {
2190 int M = Mask[i];
2191 if (M < 0) {
2192 UndefElts.setBit(i);
2193 continue;
2194 }
2195 if (M < NumSrcElts) {
2196 Src0Elts.setBit(i);
2197 Src0Identity &= (M == i);
2198 continue;
2199 }
2200 Src1Elts.setBit(i);
2201 Src1Identity &= (M == (i + NumSrcElts));
2202 }
2203 assert((Src0Elts | Src1Elts | UndefElts).isAllOnes() &&
2204 "unknown shuffle elements");
2205 assert(!Src0Elts.isZero() && !Src1Elts.isZero() &&
2206 "2-source shuffle not found");
2207
2208 // Determine lo/hi span ranges.
2209 // TODO: How should we handle undefs at the start of subvector insertions?
2210 int Src0Lo = Src0Elts.countr_zero();
2211 int Src1Lo = Src1Elts.countr_zero();
2212 int Src0Hi = NumMaskElts - Src0Elts.countl_zero();
2213 int Src1Hi = NumMaskElts - Src1Elts.countl_zero();
2214
2215 // If src0 is in place, see if the src1 elements is inplace within its own
2216 // span.
2217 if (Src0Identity) {
2218 int NumSub1Elts = Src1Hi - Src1Lo;
2219 ArrayRef<int> Sub1Mask = Mask.slice(Src1Lo, NumSub1Elts);
2220 if (isIdentityMaskImpl(Sub1Mask, NumSrcElts)) {
2221 NumSubElts = NumSub1Elts;
2222 Index = Src1Lo;
2223 return true;
2224 }
2225 }
2226
2227 // If src1 is in place, see if the src0 elements is inplace within its own
2228 // span.
2229 if (Src1Identity) {
2230 int NumSub0Elts = Src0Hi - Src0Lo;
2231 ArrayRef<int> Sub0Mask = Mask.slice(Src0Lo, NumSub0Elts);
2232 if (isIdentityMaskImpl(Sub0Mask, NumSrcElts)) {
2233 NumSubElts = NumSub0Elts;
2234 Index = Src0Lo;
2235 return true;
2236 }
2237 }
2238
2239 return false;
2240}
2241
2243 // FIXME: Not currently possible to express a shuffle mask for a scalable
2244 // vector for this case.
2246 return false;
2247
2248 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2249 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2250 if (NumMaskElts <= NumOpElts)
2251 return false;
2252
2253 // The first part of the mask must choose elements from exactly 1 source op.
2255 if (!isIdentityMaskImpl(Mask, NumOpElts))
2256 return false;
2257
2258 // All extending must be with undef elements.
2259 for (int i = NumOpElts; i < NumMaskElts; ++i)
2260 if (Mask[i] != -1)
2261 return false;
2262
2263 return true;
2264}
2265
2267 // FIXME: Not currently possible to express a shuffle mask for a scalable
2268 // vector for this case.
2270 return false;
2271
2272 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2273 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2274 if (NumMaskElts >= NumOpElts)
2275 return false;
2276
2277 return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
2278}
2279
2281 // Vector concatenation is differentiated from identity with padding.
2283 return false;
2284
2285 // FIXME: Not currently possible to express a shuffle mask for a scalable
2286 // vector for this case.
2288 return false;
2289
2290 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2291 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2292 if (NumMaskElts != NumOpElts * 2)
2293 return false;
2294
2295 // Use the mask length rather than the operands' vector lengths here. We
2296 // already know that the shuffle returns a vector twice as long as the inputs,
2297 // and neither of the inputs are undef vectors. If the mask picks consecutive
2298 // elements from both inputs, then this is a concatenation of the inputs.
2299 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
2300}
2301
2303 int ReplicationFactor, int VF) {
2304 assert(Mask.size() == (unsigned)ReplicationFactor * VF &&
2305 "Unexpected mask size.");
2306
2307 for (int CurrElt : seq(VF)) {
2308 ArrayRef<int> CurrSubMask = Mask.take_front(ReplicationFactor);
2309 assert(CurrSubMask.size() == (unsigned)ReplicationFactor &&
2310 "Run out of mask?");
2311 Mask = Mask.drop_front(ReplicationFactor);
2312 if (!all_of(CurrSubMask, [CurrElt](int MaskElt) {
2313 return MaskElt == PoisonMaskElem || MaskElt == CurrElt;
2314 }))
2315 return false;
2316 }
2317 assert(Mask.empty() && "Did not consume the whole mask?");
2318
2319 return true;
2320}
2321
2323 int &ReplicationFactor, int &VF) {
2324 // undef-less case is trivial.
2325 if (!llvm::is_contained(Mask, PoisonMaskElem)) {
2326 ReplicationFactor =
2327 Mask.take_while([](int MaskElt) { return MaskElt == 0; }).size();
2328 if (ReplicationFactor == 0 || Mask.size() % ReplicationFactor != 0)
2329 return false;
2330 VF = Mask.size() / ReplicationFactor;
2331 return isReplicationMaskWithParams(Mask, ReplicationFactor, VF);
2332 }
2333
2334 // However, if the mask contains undef's, we have to enumerate possible tuples
2335 // and pick one. There are bounds on replication factor: [1, mask size]
2336 // (where RF=1 is an identity shuffle, RF=mask size is a broadcast shuffle)
2337 // Additionally, mask size is a replication factor multiplied by vector size,
2338 // which further significantly reduces the search space.
2339
2340 // Before doing that, let's perform basic correctness checking first.
2341 int Largest = -1;
2342 for (int MaskElt : Mask) {
2343 if (MaskElt == PoisonMaskElem)
2344 continue;
2345 // Elements must be in non-decreasing order.
2346 if (MaskElt < Largest)
2347 return false;
2348 Largest = std::max(Largest, MaskElt);
2349 }
2350
2351 // Prefer larger replication factor if all else equal.
2352 for (int PossibleReplicationFactor :
2353 reverse(seq_inclusive<unsigned>(1, Mask.size()))) {
2354 if (Mask.size() % PossibleReplicationFactor != 0)
2355 continue;
2356 int PossibleVF = Mask.size() / PossibleReplicationFactor;
2357 if (!isReplicationMaskWithParams(Mask, PossibleReplicationFactor,
2358 PossibleVF))
2359 continue;
2360 ReplicationFactor = PossibleReplicationFactor;
2361 VF = PossibleVF;
2362 return true;
2363 }
2364
2365 return false;
2366}
2367
2368bool ShuffleVectorInst::isReplicationMask(int &ReplicationFactor,
2369 int &VF) const {
2370 // Not possible to express a shuffle mask for a scalable vector for this
2371 // case.
2373 return false;
2374
2375 VF = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2376 if (ShuffleMask.size() % VF != 0)
2377 return false;
2378 ReplicationFactor = ShuffleMask.size() / VF;
2379
2380 return isReplicationMaskWithParams(ShuffleMask, ReplicationFactor, VF);
2381}
2382
2384 if (VF <= 0 || Mask.size() < static_cast<unsigned>(VF) ||
2385 Mask.size() % VF != 0)
2386 return false;
2387 for (unsigned K = 0, Sz = Mask.size(); K < Sz; K += VF) {
2388 ArrayRef<int> SubMask = Mask.slice(K, VF);
2389 if (all_of(SubMask, equal_to(PoisonMaskElem)))
2390 continue;
2391 SmallBitVector Used(VF, false);
2392 for (int Idx : SubMask) {
2393 if (Idx != PoisonMaskElem && Idx < VF)
2394 Used.set(Idx);
2395 }
2396 if (!Used.all())
2397 return false;
2398 }
2399 return true;
2400}
2401
2402/// Return true if this shuffle mask is a replication mask.
2404 // Not possible to express a shuffle mask for a scalable vector for this
2405 // case.
2407 return false;
2408 if (!isSingleSourceMask(ShuffleMask, VF))
2409 return false;
2410
2411 return isOneUseSingleSourceMask(ShuffleMask, VF);
2412}
2413
2414bool ShuffleVectorInst::isInterleave(unsigned Factor) {
2416 // shuffle_vector can only interleave fixed length vectors - for scalable
2417 // vectors, see the @llvm.vector.interleave2 intrinsic
2418 if (!OpTy)
2419 return false;
2420 unsigned OpNumElts = OpTy->getNumElements();
2421
2422 return isInterleaveMask(ShuffleMask, Factor, OpNumElts * 2);
2423}
2424
2426 ArrayRef<int> Mask, unsigned Factor, unsigned NumInputElts,
2427 SmallVectorImpl<unsigned> &StartIndexes) {
2428 unsigned NumElts = Mask.size();
2429 if (NumElts % Factor)
2430 return false;
2431
2432 unsigned LaneLen = NumElts / Factor;
2433 if (!isPowerOf2_32(LaneLen))
2434 return false;
2435
2436 StartIndexes.resize(Factor);
2437
2438 // Check whether each element matches the general interleaved rule.
2439 // Ignore undef elements, as long as the defined elements match the rule.
2440 // Outer loop processes all factors (x, y, z in the above example)
2441 unsigned I = 0, J;
2442 for (; I < Factor; I++) {
2443 unsigned SavedLaneValue;
2444 unsigned SavedNoUndefs = 0;
2445
2446 // Inner loop processes consecutive accesses (x, x+1... in the example)
2447 for (J = 0; J < LaneLen - 1; J++) {
2448 // Lane computes x's position in the Mask
2449 unsigned Lane = J * Factor + I;
2450 unsigned NextLane = Lane + Factor;
2451 int LaneValue = Mask[Lane];
2452 int NextLaneValue = Mask[NextLane];
2453
2454 // If both are defined, values must be sequential
2455 if (LaneValue >= 0 && NextLaneValue >= 0 &&
2456 LaneValue + 1 != NextLaneValue)
2457 break;
2458
2459 // If the next value is undef, save the current one as reference
2460 if (LaneValue >= 0 && NextLaneValue < 0) {
2461 SavedLaneValue = LaneValue;
2462 SavedNoUndefs = 1;
2463 }
2464
2465 // Undefs are allowed, but defined elements must still be consecutive:
2466 // i.e.: x,..., undef,..., x + 2,..., undef,..., undef,..., x + 5, ....
2467 // Verify this by storing the last non-undef followed by an undef
2468 // Check that following non-undef masks are incremented with the
2469 // corresponding distance.
2470 if (SavedNoUndefs > 0 && LaneValue < 0) {
2471 SavedNoUndefs++;
2472 if (NextLaneValue >= 0 &&
2473 SavedLaneValue + SavedNoUndefs != (unsigned)NextLaneValue)
2474 break;
2475 }
2476 }
2477
2478 if (J < LaneLen - 1)
2479 return false;
2480
2481 int StartMask = 0;
2482 if (Mask[I] >= 0) {
2483 // Check that the start of the I range (J=0) is greater than 0
2484 StartMask = Mask[I];
2485 } else if (Mask[(LaneLen - 1) * Factor + I] >= 0) {
2486 // StartMask defined by the last value in lane
2487 StartMask = Mask[(LaneLen - 1) * Factor + I] - J;
2488 } else if (SavedNoUndefs > 0) {
2489 // StartMask defined by some non-zero value in the j loop
2490 StartMask = SavedLaneValue - (LaneLen - 1 - SavedNoUndefs);
2491 }
2492 // else StartMask remains set to 0, i.e. all elements are undefs
2493
2494 if (StartMask < 0)
2495 return false;
2496 // We must stay within the vectors; This case can happen with undefs.
2497 if (StartMask + LaneLen > NumInputElts)
2498 return false;
2499
2500 StartIndexes[I] = StartMask;
2501 }
2502
2503 return true;
2504}
2505
2506/// Check if the mask is a DE-interleave mask of the given factor
2507/// \p Factor like:
2508/// <Index, Index+Factor, ..., Index+(NumElts-1)*Factor>
2510 unsigned Factor,
2511 unsigned &Index) {
2512 // Check all potential start indices from 0 to (Factor - 1).
2513 for (unsigned Idx = 0; Idx < Factor; Idx++) {
2514 unsigned I = 0;
2515
2516 // Check that elements are in ascending order by Factor. Ignore undef
2517 // elements.
2518 for (; I < Mask.size(); I++)
2519 if (Mask[I] >= 0 && static_cast<unsigned>(Mask[I]) != Idx + I * Factor)
2520 break;
2521
2522 if (I == Mask.size()) {
2523 Index = Idx;
2524 return true;
2525 }
2526 }
2527
2528 return false;
2529}
2530
2531/// Try to lower a vector shuffle as a bit rotation.
2532///
2533/// Look for a repeated rotation pattern in each sub group.
2534/// Returns an element-wise left bit rotation amount or -1 if failed.
2535static int matchShuffleAsBitRotate(ArrayRef<int> Mask, int NumSubElts) {
2536 int NumElts = Mask.size();
2537 assert((NumElts % NumSubElts) == 0 && "Illegal shuffle mask");
2538
2539 int RotateAmt = -1;
2540 for (int i = 0; i != NumElts; i += NumSubElts) {
2541 for (int j = 0; j != NumSubElts; ++j) {
2542 int M = Mask[i + j];
2543 if (M < 0)
2544 continue;
2545 if (M < i || M >= i + NumSubElts)
2546 return -1;
2547 int Offset = (NumSubElts - (M - (i + j))) % NumSubElts;
2548 if (0 <= RotateAmt && Offset != RotateAmt)
2549 return -1;
2550 RotateAmt = Offset;
2551 }
2552 }
2553 return RotateAmt;
2554}
2555
2557 ArrayRef<int> Mask, unsigned EltSizeInBits, unsigned MinSubElts,
2558 unsigned MaxSubElts, unsigned &NumSubElts, unsigned &RotateAmt) {
2559 for (NumSubElts = MinSubElts; NumSubElts <= MaxSubElts; NumSubElts *= 2) {
2560 int EltRotateAmt = matchShuffleAsBitRotate(Mask, NumSubElts);
2561 if (EltRotateAmt < 0)
2562 continue;
2563 RotateAmt = EltRotateAmt * EltSizeInBits;
2564 return true;
2565 }
2566
2567 return false;
2568}
2569
2570//===----------------------------------------------------------------------===//
2571// InsertValueInst Class
2572//===----------------------------------------------------------------------===//
2573
2574void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2575 const Twine &Name) {
2576 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2577
2578 // There's no fundamental reason why we require at least one index
2579 // (other than weirdness with &*IdxBegin being invalid; see
2580 // getelementptr's init routine for example). But there's no
2581 // present need to support it.
2582 assert(!Idxs.empty() && "InsertValueInst must have at least one index");
2583
2585 Val->getType() && "Inserted value must match indexed type!");
2586 Op<0>() = Agg;
2587 Op<1>() = Val;
2588
2589 Indices.append(Idxs.begin(), Idxs.end());
2590 setName(Name);
2591}
2592
2593InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
2594 : Instruction(IVI.getType(), InsertValue, AllocMarker),
2595 Indices(IVI.Indices) {
2596 Op<0>() = IVI.getOperand(0);
2597 Op<1>() = IVI.getOperand(1);
2599}
2600
2601//===----------------------------------------------------------------------===//
2602// ExtractValueInst Class
2603//===----------------------------------------------------------------------===//
2604
2605void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
2606 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2607
2608 // There's no fundamental reason why we require at least one index.
2609 // But there's no present need to support it.
2610 assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
2611
2612 Indices.append(Idxs.begin(), Idxs.end());
2613 setName(Name);
2614}
2615
2616ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
2617 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0),
2618 (BasicBlock *)nullptr),
2619 Indices(EVI.Indices) {
2621}
2622
2623// getIndexedType - Returns the type of the element that would be extracted
2624// with an extractvalue instruction with the specified parameters.
2625//
2626// A null type is returned if the indices are invalid for the specified
2627// pointer type.
2628//
2630 ArrayRef<unsigned> Idxs) {
2631 for (unsigned Index : Idxs) {
2632 // We can't use CompositeType::indexValid(Index) here.
2633 // indexValid() always returns true for arrays because getelementptr allows
2634 // out-of-bounds indices. Since we don't allow those for extractvalue and
2635 // insertvalue we need to check array indexing manually.
2636 // Since the only other types we can index into are struct types it's just
2637 // as easy to check those manually as well.
2638 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
2639 if (Index >= AT->getNumElements())
2640 return nullptr;
2641 Agg = AT->getElementType();
2642 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
2643 if (Index >= ST->getNumElements())
2644 return nullptr;
2645 Agg = ST->getElementType(Index);
2646 } else {
2647 // Not a valid type to index into.
2648 return nullptr;
2649 }
2650 }
2651 return Agg;
2652}
2653
2654//===----------------------------------------------------------------------===//
2655// BitInsert Class
2656//===----------------------------------------------------------------------===//
2657BitInsertInst::BitInsertInst(Value *Base, Value *Val, Value *Offset,
2658 const Twine &Name, InsertPosition InsertBef)
2659 : Instruction(Base->getType(), BitInsert, AllocMarker, InsertBef) {
2660 assert(!areInvalidOperands(Base, Val, Offset) &&
2661 "Invalid bitinsert instruction operands!");
2662 Op<0>() = Base;
2663 Op<1>() = Val;
2664 Op<2>() = Offset;
2665 setName(Name);
2666}
2667
2669 Value *Offset) {
2670 Type *BaseTy = Base->getType();
2671 if (!BaseTy->isByteOrByteVectorTy())
2672 return "bitinsert base must be a byte type or a vector of byte type";
2673 Type *ValTy = Val->getType()->getScalarType();
2674 if (!(ValTy->isFloatingPointTy() || ValTy->isIntegerTy() ||
2675 ValTy->isPointerTy() || ValTy->isByteTy()))
2676 return "bitinsert value must be an integer, floating-point, pointer, or "
2677 "byte type, or a vector of those types";
2678 if (!Offset->getType()->isIntOrIntVectorTy(32))
2679 return "bitinsert offset must be i32 or a vector of i32";
2680 if (BaseTy->getWithNewType(ValTy) != Val->getType() ||
2681 BaseTy->getWithNewType(Offset->getType()->getScalarType()) !=
2682 Offset->getType())
2683 return "bitinsert operands must all be scalars or all be vectors with the "
2684 "same number of elements";
2685 return nullptr;
2686}
2687
2688//===----------------------------------------------------------------------===//
2689// BitExtract Class
2690//===----------------------------------------------------------------------===//
2691BitExtractInst::BitExtractInst(Type *Ty, Value *Src, Value *Offset,
2692 const Twine &Name, InsertPosition InsertBef)
2693 : Instruction(Ty, BitExtract, AllocMarker, InsertBef) {
2694 assert(!areInvalidOperands(Ty, Src, Offset) &&
2695 "Invalid bitextract instruction operands!");
2696 Op<0>() = Src;
2697 Op<1>() = Offset;
2698 setName(Name);
2699}
2700
2702 Value *Offset) {
2703 const Type *EltTy = Ty->getScalarType();
2704 if (!(EltTy->isFloatingPointTy() || EltTy->isIntegerTy() ||
2705 EltTy->isPointerTy() || EltTy->isByteTy()))
2706 return "bitextract result must be an integer, floating-point, pointer, or "
2707 "byte type, or a vector of those types";
2708 if (!Src->getType()->isByteOrByteVectorTy())
2709 return "bitextract source must be a byte type or a vector of byte type";
2710 if (!Offset->getType()->isIntOrIntVectorTy(32))
2711 return "bitextract offset must be i32 or a vector of i32";
2712 if (Ty->getWithNewType(Src->getType()->getScalarType()) != Src->getType() ||
2713 Ty->getWithNewType(Offset->getType()->getScalarType()) !=
2714 Offset->getType())
2715 return "bitextract operands must all be scalars or all be vectors with the "
2716 "same number of elements";
2717 return nullptr;
2718}
2719
2720//===----------------------------------------------------------------------===//
2721// UnaryOperator Class
2722//===----------------------------------------------------------------------===//
2723
2725 const Twine &Name, InsertPosition InsertBefore)
2726 : UnaryInstruction(Ty, iType, S, InsertBefore) {
2727 Op<0>() = S;
2728 setName(Name);
2729 AssertOK();
2730}
2731
2733 InsertPosition InsertBefore) {
2734 switch (Op) {
2735 case UnaryOps::FNeg:
2736 return new FPUnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2737 default:
2738 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2739 }
2740}
2741
2742void UnaryOperator::AssertOK() {
2743 Value *LHS = getOperand(0);
2744 (void)LHS; // Silence warnings.
2745#ifndef NDEBUG
2746 switch (getOpcode()) {
2747 case FNeg:
2748 assert(getType() == LHS->getType() &&
2749 "Unary operation should return same type as operand!");
2750 assert(getType()->isFPOrFPVectorTy() &&
2751 "Tried to create a floating-point operation on a "
2752 "non-floating-point type!");
2753 break;
2754 default: llvm_unreachable("Invalid opcode provided");
2755 }
2756#endif
2757}
2758
2759//===----------------------------------------------------------------------===//
2760// BinaryOperator Class
2761//===----------------------------------------------------------------------===//
2762
2764 const Twine &Name, InsertPosition InsertBefore)
2765 : Instruction(Ty, iType, AllocMarker, InsertBefore) {
2766 Op<0>() = S1;
2767 Op<1>() = S2;
2768 setName(Name);
2769 AssertOK();
2770}
2771
2772void BinaryOperator::AssertOK() {
2773 Value *LHS = getOperand(0), *RHS = getOperand(1);
2774 (void)LHS; (void)RHS; // Silence warnings.
2775 assert(LHS->getType() == RHS->getType() &&
2776 "Binary operator operand types must match!");
2777#ifndef NDEBUG
2778 switch (getOpcode()) {
2779 case Add: case Sub:
2780 case Mul:
2781 assert(getType() == LHS->getType() &&
2782 "Arithmetic operation should return same type as operands!");
2783 assert(getType()->isIntOrIntVectorTy() &&
2784 "Tried to create an integer operation on a non-integer type!");
2785 break;
2786 case FAdd: case FSub:
2787 case FMul:
2788 assert(getType() == LHS->getType() &&
2789 "Arithmetic operation should return same type as operands!");
2790 assert(getType()->isFPOrFPVectorTy() &&
2791 "Tried to create a floating-point operation on a "
2792 "non-floating-point type!");
2793 break;
2794 case UDiv:
2795 case SDiv:
2796 assert(getType() == LHS->getType() &&
2797 "Arithmetic operation should return same type as operands!");
2798 assert(getType()->isIntOrIntVectorTy() &&
2799 "Incorrect operand type (not integer) for S/UDIV");
2800 break;
2801 case FDiv:
2802 assert(getType() == LHS->getType() &&
2803 "Arithmetic operation should return same type as operands!");
2804 assert(getType()->isFPOrFPVectorTy() &&
2805 "Incorrect operand type (not floating point) for FDIV");
2806 break;
2807 case URem:
2808 case SRem:
2809 assert(getType() == LHS->getType() &&
2810 "Arithmetic operation should return same type as operands!");
2811 assert(getType()->isIntOrIntVectorTy() &&
2812 "Incorrect operand type (not integer) for S/UREM");
2813 break;
2814 case FRem:
2815 assert(getType() == LHS->getType() &&
2816 "Arithmetic operation should return same type as operands!");
2817 assert(getType()->isFPOrFPVectorTy() &&
2818 "Incorrect operand type (not floating point) for FREM");
2819 break;
2820 case Shl:
2821 case LShr:
2822 case AShr:
2823 assert(getType() == LHS->getType() &&
2824 "Shift operation should return same type as operands!");
2825 assert(getType()->isIntOrIntVectorTy() &&
2826 "Tried to create a shift operation on a non-integral type!");
2827 break;
2828 case And: case Or:
2829 case Xor:
2830 assert(getType() == LHS->getType() &&
2831 "Logical operation should return same type as operands!");
2832 assert(getType()->isIntOrIntVectorTy() &&
2833 "Tried to create a logical operation on a non-integral type!");
2834 break;
2835 default: llvm_unreachable("Invalid opcode provided");
2836 }
2837#endif
2838}
2839
2841 const Twine &Name,
2842 InsertPosition InsertBefore) {
2843 assert(S1->getType() == S2->getType() &&
2844 "Cannot create binary operator with two operands of differing type!");
2845 switch (Op) {
2846 case BinaryOps::FAdd:
2847 case BinaryOps::FSub:
2848 case BinaryOps::FMul:
2849 case BinaryOps::FDiv:
2850 case BinaryOps::FRem:
2851 return new FPBinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2852 default:
2853 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2854 }
2855}
2856
2858 InsertPosition InsertBefore) {
2859 Value *Zero = ConstantInt::get(Op->getType(), 0);
2860 return new BinaryOperator(Instruction::Sub, Zero, Op, Op->getType(), Name,
2861 InsertBefore);
2862}
2863
2865 InsertPosition InsertBefore) {
2866 Value *Zero = ConstantInt::get(Op->getType(), 0);
2867 return BinaryOperator::CreateNSWSub(Zero, Op, Name, InsertBefore);
2868}
2869
2871 InsertPosition InsertBefore) {
2872 Constant *C = Constant::getAllOnesValue(Op->getType());
2873 return new BinaryOperator(Instruction::Xor, Op, C,
2874 Op->getType(), Name, InsertBefore);
2875}
2876
2877// Exchange the two operands to this instruction. This instruction is safe to
2878// use on any binary instruction and does not modify the semantics of the
2879// instruction.
2881 if (!isCommutative())
2882 return true; // Can't commute operands
2883 Op<0>().swap(Op<1>());
2884 return false;
2885}
2886
2887//===----------------------------------------------------------------------===//
2888// FPMathOperator Class
2889//===----------------------------------------------------------------------===//
2890
2892 const MDNode *MD =
2893 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2894 if (!MD)
2895 return 0.0;
2897 return Accuracy->getValueAPF().convertToFloat();
2898}
2899
2900//===----------------------------------------------------------------------===//
2901// CastInst Class
2902//===----------------------------------------------------------------------===//
2903
2904// Just determine if this cast only deals with integral->integral conversion.
2906 switch (getOpcode()) {
2907 default: return false;
2908 case Instruction::ZExt:
2909 case Instruction::SExt:
2910 case Instruction::Trunc:
2911 return true;
2912 case Instruction::BitCast:
2913 return getOperand(0)->getType()->isIntegerTy() &&
2914 getType()->isIntegerTy();
2915 }
2916}
2917
2918/// This function determines if the CastInst does not require any bits to be
2919/// changed in order to effect the cast. Essentially, it identifies cases where
2920/// no code gen is necessary for the cast, hence the name no-op cast. For
2921/// example, the following are all no-op casts:
2922/// # bitcast i32* %x to i8*
2923/// # bitcast <2 x i32> %x to <4 x i16>
2924/// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2925/// Determine if the described cast is a no-op.
2927 Type *SrcTy,
2928 Type *DestTy,
2929 const DataLayout &DL) {
2930 assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition");
2931 switch (Opcode) {
2932 default: llvm_unreachable("Invalid CastOp");
2933 case Instruction::Trunc:
2934 case Instruction::ZExt:
2935 case Instruction::SExt:
2936 case Instruction::FPTrunc:
2937 case Instruction::FPExt:
2938 case Instruction::UIToFP:
2939 case Instruction::SIToFP:
2940 case Instruction::FPToUI:
2941 case Instruction::FPToSI:
2942 case Instruction::AddrSpaceCast:
2943 // TODO: Target informations may give a more accurate answer here.
2944 return false;
2945 case Instruction::BitCast:
2946 return true; // BitCast never modifies bits.
2947 case Instruction::PtrToAddr:
2948 case Instruction::PtrToInt:
2949 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
2950 DestTy->getScalarSizeInBits();
2951 case Instruction::IntToPtr:
2952 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
2953 SrcTy->getScalarSizeInBits();
2954 }
2955}
2956
2958 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
2959}
2960
2961/// This function determines if a pair of casts can be eliminated and what
2962/// opcode should be used in the elimination. This assumes that there are two
2963/// instructions like this:
2964/// * %F = firstOpcode SrcTy %x to MidTy
2965/// * %S = secondOpcode MidTy %F to DstTy
2966/// The function returns a resultOpcode so these two casts can be replaced with:
2967/// * %Replacement = resultOpcode %SrcTy %x to DstTy
2968/// If no such cast is permitted, the function returns 0.
2970 Instruction::CastOps secondOp,
2971 Type *SrcTy, Type *MidTy, Type *DstTy,
2972 const DataLayout *DL) {
2973 // Define the 144 possibilities for these two cast instructions. The values
2974 // in this matrix determine what to do in a given situation and select the
2975 // case in the switch below. The rows correspond to firstOp, the columns
2976 // correspond to secondOp. In looking at the table below, keep in mind
2977 // the following cast properties:
2978 //
2979 // Size Compare Source Destination
2980 // Operator Src ? Size Type Sign Type Sign
2981 // -------- ------------ ------------------- ---------------------
2982 // TRUNC > Integer Any Integral Any
2983 // ZEXT < Integral Unsigned Integer Any
2984 // SEXT < Integral Signed Integer Any
2985 // FPTOUI n/a FloatPt n/a Integral Unsigned
2986 // FPTOSI n/a FloatPt n/a Integral Signed
2987 // UITOFP n/a Integral Unsigned FloatPt n/a
2988 // SITOFP n/a Integral Signed FloatPt n/a
2989 // FPTRUNC > FloatPt n/a FloatPt n/a
2990 // FPEXT < FloatPt n/a FloatPt n/a
2991 // PTRTOINT n/a Pointer n/a Integral Unsigned
2992 // PTRTOADDR n/a Pointer n/a Integral Unsigned
2993 // INTTOPTR n/a Integral Unsigned Pointer n/a
2994 // BITCAST = FirstClass n/a FirstClass n/a
2995 // ADDRSPCST n/a Pointer n/a Pointer n/a
2996 //
2997 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2998 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2999 // into "fptoui double to i64", but this loses information about the range
3000 // of the produced value (we no longer know the top-part is all zeros).
3001 // Further this conversion is often much more expensive for typical hardware,
3002 // and causes issues when building libgcc. We disallow fptosi+sext for the
3003 // same reason.
3004 const unsigned numCastOps =
3005 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
3006 // clang-format off
3007 static const uint8_t CastResults[numCastOps][numCastOps] = {
3008 // T F F U S F F P P I B A -+
3009 // R Z S P P I I T P 2 2 N T S |
3010 // U E E 2 2 2 2 R E I A T C C +- secondOp
3011 // N X X U S F F N X N D 2 V V |
3012 // C T T I I P P C T T R P T T -+
3013 { 1, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // Trunc -+
3014 { 8, 1, 9,99,99, 2,17,99,99,99,99, 2, 3, 0}, // ZExt |
3015 { 8, 0, 1,99,99, 0, 2,99,99,99,99, 0, 3, 0}, // SExt |
3016 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // FPToUI |
3017 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // FPToSI |
3018 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // UIToFP +- firstOp
3019 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // SIToFP |
3020 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // FPTrunc |
3021 { 99,99,99, 2, 2,99,99, 8, 2,99,99,99, 4, 0}, // FPExt |
3022 { 1, 0, 0,99,99, 0, 0,99,99,99,99, 7, 3, 0}, // PtrToInt |
3023 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // PtrToAddr |
3024 { 99,99,99,99,99,99,99,99,99,11,11,99,15, 0}, // IntToPtr |
3025 { 5, 5, 5, 0, 0, 5, 5, 0, 0,16,16, 5,18,14}, // BitCast |
3026 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
3027 };
3028 // clang-format on
3029
3030 // TODO: This logic could be encoded into the table above and handled in the
3031 // switch below.
3032 // If either of the casts are a bitcast from scalar to vector, disallow the
3033 // merging. However, any pair of bitcasts are allowed.
3034 bool IsFirstBitcast = (firstOp == Instruction::BitCast);
3035 bool IsSecondBitcast = (secondOp == Instruction::BitCast);
3036 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
3037
3038 // Check if any of the casts convert scalars <-> vectors.
3039 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
3040 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
3041 if (!AreBothBitcasts)
3042 return 0;
3043
3044 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
3045 [secondOp-Instruction::CastOpsBegin];
3046 switch (ElimCase) {
3047 case 0:
3048 // Categorically disallowed.
3049 return 0;
3050 case 1:
3051 // Allowed, use first cast's opcode.
3052 return firstOp;
3053 case 2:
3054 // Allowed, use second cast's opcode.
3055 return secondOp;
3056 case 3:
3057 // No-op cast in second op implies firstOp as long as the DestTy
3058 // is integer and we are not converting between a vector and a
3059 // non-vector type.
3060 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
3061 return firstOp;
3062 return 0;
3063 case 4:
3064 // No-op cast in second op implies firstOp as long as the DestTy
3065 // matches MidTy.
3066 if (DstTy == MidTy)
3067 return firstOp;
3068 return 0;
3069 case 5:
3070 // No-op cast in first op implies secondOp as long as the SrcTy
3071 // is an integer.
3072 if (SrcTy->isIntegerTy())
3073 return secondOp;
3074 return 0;
3075 case 7: {
3076 // Skip the inttoptr/ptrtoint optimization if disabled.
3077 if (!getIROptions(SrcTy->getContext()).i2p_p2i_opt)
3078 return 0;
3079
3080 // Cannot simplify if address spaces are different!
3081 if (SrcTy != DstTy)
3082 return 0;
3083
3084 // Cannot simplify if the intermediate integer size is smaller than the
3085 // pointer size.
3086 unsigned MidSize = MidTy->getScalarSizeInBits();
3087 if (!DL || MidSize < DL->getPointerTypeSizeInBits(SrcTy))
3088 return 0;
3089
3090 return Instruction::BitCast;
3091 }
3092 case 8: {
3093 // ext, trunc -> bitcast, if the SrcTy and DstTy are the same
3094 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
3095 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
3096 unsigned SrcSize = SrcTy->getScalarSizeInBits();
3097 unsigned DstSize = DstTy->getScalarSizeInBits();
3098 if (SrcTy == DstTy)
3099 return Instruction::BitCast;
3100 if (SrcSize < DstSize)
3101 return firstOp;
3102 if (SrcSize > DstSize)
3103 return secondOp;
3104 return 0;
3105 }
3106 case 9:
3107 // zext, sext -> zext, because sext can't sign extend after zext
3108 return Instruction::ZExt;
3109 case 11: {
3110 // inttoptr, ptrtoint/ptrtoaddr -> integer cast
3111 if (!DL)
3112 return 0;
3113 unsigned MidSize = secondOp == Instruction::PtrToAddr
3114 ? DL->getAddressSizeInBits(MidTy)
3115 : DL->getPointerTypeSizeInBits(MidTy);
3116 unsigned SrcSize = SrcTy->getScalarSizeInBits();
3117 unsigned DstSize = DstTy->getScalarSizeInBits();
3118 // If the middle size is smaller than both source and destination,
3119 // an additional masking operation would be required.
3120 if (MidSize < SrcSize && MidSize < DstSize)
3121 return 0;
3122 if (DstSize < SrcSize)
3123 return Instruction::Trunc;
3124 if (DstSize > SrcSize)
3125 return Instruction::ZExt;
3126 return Instruction::BitCast;
3127 }
3128 case 12:
3129 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
3130 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
3131 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
3132 return Instruction::AddrSpaceCast;
3133 return Instruction::BitCast;
3134 case 13:
3135 // FIXME: this state can be merged with (1), but the following assert
3136 // is useful to check the correcteness of the sequence due to semantic
3137 // change of bitcast.
3138 // addrspacecast can only fold through a bitcast if the result remains a
3139 // pointer. A pointer-to-byte bitcast must stay as a separate bitcast.
3140 if (!DstTy->isPtrOrPtrVectorTy())
3141 return 0;
3142 assert(
3143 SrcTy->isPtrOrPtrVectorTy() &&
3144 MidTy->isPtrOrPtrVectorTy() &&
3145 DstTy->isPtrOrPtrVectorTy() &&
3146 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
3147 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
3148 "Illegal addrspacecast, bitcast sequence!");
3149 // Allowed, use first cast's opcode
3150 return firstOp;
3151 case 14:
3152 // bitcast, addrspacecast -> addrspacecast
3153 // addrspacecast can only fold through a bitcast if the source was already
3154 // a pointer. A byte-to-pointer bitcast must stay as a separate bitcast.
3155 if (!SrcTy->isPtrOrPtrVectorTy())
3156 return 0;
3157 return Instruction::AddrSpaceCast;
3158 case 15:
3159 // FIXME: this state can be merged with (1), but the following assert
3160 // is useful to check the correcteness of the sequence due to semantic
3161 // change of bitcast.
3162 // inttoptr can only fold through a bitcast if the result remains a
3163 // pointer. A pointer-to-byte bitcast must stay as a separate bitcast.
3164 if (!DstTy->isPtrOrPtrVectorTy())
3165 return 0;
3166 assert(
3167 SrcTy->isIntOrIntVectorTy() &&
3168 MidTy->isPtrOrPtrVectorTy() &&
3169 DstTy->isPtrOrPtrVectorTy() &&
3170 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
3171 "Illegal inttoptr, bitcast sequence!");
3172 // Allowed, use first cast's opcode
3173 return firstOp;
3174 case 16:
3175 // FIXME: this state can be merged with (2), but the following assert
3176 // is useful to check the correcteness of the sequence due to semantic
3177 // change of bitcast.
3178 // bitcast, ptrtoaddr -> bitcast, if SrcTy is a byte and the address is
3179 // the whole pointer
3180 // ptrtoint can only fold through a bitcast if the source was already a
3181 // pointer, as ptrtoint exposes the provenance.
3182 if (!SrcTy->isPtrOrPtrVectorTy()) {
3183 // ptrtoaddr yields the address width, so the sizes only match if the
3184 // address is the whole pointer.
3185 if (secondOp == Instruction::PtrToAddr &&
3186 SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3187 return Instruction::BitCast;
3188 return 0;
3189 }
3190 assert(
3191 SrcTy->isPtrOrPtrVectorTy() &&
3192 MidTy->isPtrOrPtrVectorTy() &&
3193 DstTy->isIntOrIntVectorTy() &&
3194 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
3195 "Illegal bitcast, ptrtoint sequence!");
3196 // Allowed, use second cast's opcode
3197 return secondOp;
3198 case 17:
3199 // (sitofp (zext x)) -> (uitofp x)
3200 return Instruction::UIToFP;
3201 case 18:
3202 // bitcast, bitcast -> bitcast, if neither SrcTy nor DstTy is a pointer,
3203 // both are pointers in the same addrspace,
3204 // or one is a pointer and the other a byte
3205 // bitcast, bitcast -> ptrtoint, if a pointer goes through a byte to an
3206 // integer of the pointer width
3207 // bitcast, bitcast -> inttoptr, if an integer of the pointer width goes
3208 // through a byte to a pointer
3209 // A pair of bitcasts through a byte must stay separate otherwise.
3210 if (!SrcTy->isPtrOrPtrVectorTy() && !DstTy->isPtrOrPtrVectorTy())
3211 return Instruction::BitCast;
3212 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
3213 SrcTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace())
3214 return Instruction::BitCast;
3215 if (SrcTy->isByteOrByteVectorTy() || DstTy->isByteOrByteVectorTy())
3216 return Instruction::BitCast;
3217 if (SrcTy->isVectorTy() == DstTy->isVectorTy() && DL) {
3218 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy() &&
3219 DL->getPointerTypeSizeInBits(SrcTy) == DstTy->getScalarSizeInBits())
3220 return Instruction::PtrToInt;
3221 if (SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
3222 SrcTy->getScalarSizeInBits() == DL->getPointerTypeSizeInBits(DstTy))
3223 return Instruction::IntToPtr;
3224 }
3225 return 0;
3226 case 99:
3227 // Cast combination can't happen (error in input). This is for all cases
3228 // where the MidTy is not the same for the two cast instructions.
3229 llvm_unreachable("Invalid Cast Combination");
3230 default:
3231 llvm_unreachable("Error in CastResults table!!!");
3232 }
3233}
3234
3236 const Twine &Name, InsertPosition InsertBefore) {
3237 assert(castIsValid(op, S, Ty) && "Invalid cast!");
3238 // Construct and return the appropriate CastInst subclass
3239 switch (op) {
3240 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
3241 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
3242 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
3243 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
3244 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
3245 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
3246 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
3247 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
3248 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
3249 case PtrToAddr: return new PtrToAddrInst (S, Ty, Name, InsertBefore);
3250 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
3251 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
3252 case BitCast:
3253 return new BitCastInst(S, Ty, Name, InsertBefore);
3254 case AddrSpaceCast:
3255 return new AddrSpaceCastInst(S, Ty, Name, InsertBefore);
3256 default:
3257 llvm_unreachable("Invalid opcode provided");
3258 }
3259}
3260
3262 InsertPosition InsertBefore) {
3263 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3264 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3265 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
3266}
3267
3269 InsertPosition InsertBefore) {
3270 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3271 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3272 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
3273}
3274
3276 InsertPosition InsertBefore) {
3277 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3278 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3279 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
3280}
3281
3282/// Create a BitCast or a PtrToInt cast instruction
3284 InsertPosition InsertBefore) {
3285 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3286 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
3287 "Invalid cast");
3288 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
3289 assert((!Ty->isVectorTy() ||
3290 cast<VectorType>(Ty)->getElementCount() ==
3291 cast<VectorType>(S->getType())->getElementCount()) &&
3292 "Invalid cast");
3293
3294 if (Ty->isIntOrIntVectorTy())
3295 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3296
3297 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
3298}
3299
3301 Value *S, Type *Ty, const Twine &Name, InsertPosition InsertBefore) {
3302 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3303 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
3304
3305 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
3306 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
3307
3308 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3309}
3310
3312 const Twine &Name,
3313 InsertPosition InsertBefore) {
3314 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
3315 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3316 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
3317 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
3318
3319 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3320}
3321
3323 const Twine &Name,
3324 InsertPosition InsertBefore) {
3325 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
3326 "Invalid integer cast");
3327 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3328 unsigned DstBits = Ty->getScalarSizeInBits();
3329 Instruction::CastOps opcode =
3330 (SrcBits == DstBits ? Instruction::BitCast :
3331 (SrcBits > DstBits ? Instruction::Trunc :
3332 (isSigned ? Instruction::SExt : Instruction::ZExt)));
3333 return Create(opcode, C, Ty, Name, InsertBefore);
3334}
3335
3337 InsertPosition InsertBefore) {
3338 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
3339 "Invalid cast");
3340 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3341 unsigned DstBits = Ty->getScalarSizeInBits();
3342 assert((C->getType() == Ty || SrcBits != DstBits) && "Invalid cast");
3343 Instruction::CastOps opcode =
3344 (SrcBits == DstBits ? Instruction::BitCast :
3345 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
3346 return Create(opcode, C, Ty, Name, InsertBefore);
3347}
3348
3349bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
3350 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
3351 return false;
3352
3353 if (SrcTy == DestTy)
3354 return true;
3355
3356 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3357 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
3358 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3359 // An element by element cast. Valid if casting the elements is valid.
3360 SrcTy = SrcVecTy->getElementType();
3361 DestTy = DestVecTy->getElementType();
3362 }
3363 }
3364 }
3365
3366 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
3367 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
3368 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
3369 }
3370 }
3371
3372 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3373 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3374
3375 // Could still have vectors of pointers if the number of elements doesn't
3376 // match
3377 if (SrcBits.getKnownMinValue() == 0 || DestBits.getKnownMinValue() == 0)
3378 return false;
3379
3380 if (SrcBits != DestBits)
3381 return false;
3382
3383 return true;
3384}
3385
3387 const DataLayout &DL) {
3388 // ptrtoint and inttoptr are not allowed on non-integral pointers
3389 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
3390 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
3391 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3392 !DL.isNonIntegralPointerType(PtrTy));
3393 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
3394 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
3395 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3396 !DL.isNonIntegralPointerType(PtrTy));
3397
3398 return isBitCastable(SrcTy, DestTy);
3399}
3400
3401// Provide a way to get a "cast" where the cast opcode is inferred from the
3402// types and size of the operand. This, basically, is a parallel of the
3403// logic in the castIsValid function below. This axiom should hold:
3404// castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3405// should not assert in castIsValid. In other words, this produces a "correct"
3406// casting opcode for the arguments passed to it.
3409 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
3410 Type *SrcTy = Src->getType();
3411
3412 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
3413 "Only first class types are castable!");
3414
3415 if (SrcTy == DestTy)
3416 return BitCast;
3417
3418 // FIXME: Check address space sizes here
3419 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3420 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3421 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3422 // An element by element cast. Find the appropriate opcode based on the
3423 // element types.
3424 SrcTy = SrcVecTy->getElementType();
3425 DestTy = DestVecTy->getElementType();
3426 }
3427
3428 // Get the bit sizes, we'll need these
3429 // FIXME: This doesn't work for scalable vector types with different element
3430 // counts that don't call getElementType above.
3431 unsigned SrcBits =
3432 SrcTy->getPrimitiveSizeInBits().getFixedValue(); // 0 for ptr
3433 unsigned DestBits =
3434 DestTy->getPrimitiveSizeInBits().getFixedValue(); // 0 for ptr
3435
3436 // Run through the possibilities ...
3437 if (DestTy->isByteTy()) { // Casting to byte
3438 if (SrcTy->isIntegerTy()) { // Casting from integral
3439 assert(DestBits == SrcBits && "Illegal cast from integer to byte type");
3440 return BitCast;
3441 } else if (SrcTy->isPointerTy()) { // Casting from pointer
3442 assert(DestBits == SrcBits && "Illegal cast from pointer to byte type");
3443 return BitCast;
3444 }
3445 llvm_unreachable("Illegal cast to byte type");
3446 } else if (DestTy->isIntegerTy()) { // Casting to integral
3447 if (SrcTy->isIntegerTy()) { // Casting from integral
3448 if (DestBits < SrcBits)
3449 return Trunc; // int -> smaller int
3450 else if (DestBits > SrcBits) { // its an extension
3451 if (SrcIsSigned)
3452 return SExt; // signed -> SEXT
3453 else
3454 return ZExt; // unsigned -> ZEXT
3455 } else {
3456 return BitCast; // Same size, No-op cast
3457 }
3458 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3459 if (DestIsSigned)
3460 return FPToSI; // FP -> sint
3461 else
3462 return FPToUI; // FP -> uint
3463 } else if (SrcTy->isVectorTy()) {
3464 assert(DestBits == SrcBits &&
3465 "Casting vector to integer of different width");
3466 return BitCast; // Same size, no-op cast
3467 } else {
3468 assert(SrcTy->isPointerTy() &&
3469 "Casting from a value that is not first-class type");
3470 return PtrToInt; // ptr -> int
3471 }
3472 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3473 if (SrcTy->isIntegerTy()) { // Casting from integral
3474 if (SrcIsSigned)
3475 return SIToFP; // sint -> FP
3476 else
3477 return UIToFP; // uint -> FP
3478 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3479 if (DestBits < SrcBits) {
3480 return FPTrunc; // FP -> smaller FP
3481 } else if (DestBits > SrcBits) {
3482 return FPExt; // FP -> larger FP
3483 } else {
3484 return BitCast; // same size, no-op cast
3485 }
3486 } else if (SrcTy->isVectorTy()) {
3487 assert(DestBits == SrcBits &&
3488 "Casting vector to floating point of different width");
3489 return BitCast; // same size, no-op cast
3490 }
3491 llvm_unreachable("Casting pointer or non-first class to float");
3492 } else if (DestTy->isVectorTy()) {
3493 assert(DestBits == SrcBits &&
3494 "Illegal cast to vector (wrong type or size)");
3495 return BitCast;
3496 } else if (DestTy->isPointerTy()) {
3497 if (SrcTy->isPointerTy()) {
3498 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3499 return AddrSpaceCast;
3500 return BitCast; // ptr -> ptr
3501 } else if (SrcTy->isIntegerTy()) {
3502 return IntToPtr; // int -> ptr
3503 }
3504 llvm_unreachable("Casting pointer to other than pointer or int");
3505 }
3506 llvm_unreachable("Casting to type that is not first-class");
3507}
3508
3509//===----------------------------------------------------------------------===//
3510// CastInst SubClass Constructors
3511//===----------------------------------------------------------------------===//
3512
3513/// Check that the construction parameters for a CastInst are correct. This
3514/// could be broken out into the separate constructors but it is useful to have
3515/// it in one place and to eliminate the redundant code for getting the sizes
3516/// of the types involved.
3517bool
3519 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3520 SrcTy->isAggregateType() || DstTy->isAggregateType())
3521 return false;
3522
3523 // Get the size of the types in bits, and whether we are dealing
3524 // with vector types, we'll need this later.
3525 bool SrcIsVec = isa<VectorType>(SrcTy);
3526 bool DstIsVec = isa<VectorType>(DstTy);
3527 unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits();
3528 unsigned DstScalarBitSize = DstTy->getScalarSizeInBits();
3529
3530 // If these are vector types, get the lengths of the vectors (using zero for
3531 // scalar types means that checking that vector lengths match also checks that
3532 // scalars are not being converted to vectors or vectors to scalars).
3533 ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount()
3535 ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount()
3537
3538 // Switch on the opcode provided
3539 switch (op) {
3540 default: return false; // This is an input error
3541 case Instruction::Trunc:
3542 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3543 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3544 case Instruction::ZExt:
3545 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3546 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3547 case Instruction::SExt:
3548 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3549 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3550 case Instruction::FPTrunc:
3551 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3552 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3553 case Instruction::FPExt:
3554 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3555 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3556 case Instruction::UIToFP:
3557 case Instruction::SIToFP:
3558 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3559 SrcEC == DstEC;
3560 case Instruction::FPToUI:
3561 case Instruction::FPToSI:
3562 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3563 SrcEC == DstEC;
3564 case Instruction::PtrToAddr:
3565 case Instruction::PtrToInt:
3566 if (SrcEC != DstEC)
3567 return false;
3568 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
3569 case Instruction::IntToPtr:
3570 if (SrcEC != DstEC)
3571 return false;
3572 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
3573 case Instruction::BitCast: {
3574 Type *SrcScalarTy = SrcTy->getScalarType();
3575 if (SrcScalarTy->isTargetExtTy() || !SrcScalarTy->isSingleValueType())
3576 return false;
3577 Type *DstScalarTy = DstTy->getScalarType();
3578 if (DstScalarTy->isTargetExtTy() || !DstScalarTy->isSingleValueType())
3579 return false;
3580
3581 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcScalarTy);
3582 PointerType *DstPtrTy = dyn_cast<PointerType>(DstScalarTy);
3583
3584 // BitCast implies a no-op cast of type only. No bits change.
3585 // However, you can't cast pointers to anything but pointers/bytes.
3586 if ((SrcPtrTy && DstTy->isByteOrByteVectorTy()) ||
3587 (SrcTy->isByteOrByteVectorTy() && DstPtrTy))
3588 return true;
3589 if (!SrcPtrTy != !DstPtrTy)
3590 return false;
3591
3592 // For non-pointer cases, the cast is okay if the source and destination bit
3593 // widths are identical.
3594 if (!SrcPtrTy)
3595 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3596
3597 // If both are pointers then the address spaces must match.
3598 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3599 return false;
3600
3601 // A vector of pointers must have the same number of elements.
3602 if (SrcIsVec && DstIsVec)
3603 return SrcEC == DstEC;
3604 if (SrcIsVec)
3605 return SrcEC == ElementCount::getFixed(1);
3606 if (DstIsVec)
3607 return DstEC == ElementCount::getFixed(1);
3608
3609 return true;
3610 }
3611 case Instruction::AddrSpaceCast: {
3612 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3613 if (!SrcPtrTy)
3614 return false;
3615
3616 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3617 if (!DstPtrTy)
3618 return false;
3619
3620 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3621 return false;
3622
3623 return SrcEC == DstEC;
3624 }
3625 }
3626}
3627
3629 InsertPosition InsertBefore)
3630 : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3631 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3632}
3633
3634ZExtInst::ZExtInst(Value *S, Type *Ty, const Twine &Name,
3635 InsertPosition InsertBefore)
3636 : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3637 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3638}
3639
3640SExtInst::SExtInst(Value *S, Type *Ty, const Twine &Name,
3641 InsertPosition InsertBefore)
3642 : CastInst(Ty, SExt, S, Name, InsertBefore) {
3643 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3644}
3645
3647 InsertPosition InsertBefore)
3648 : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3649 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3650}
3651
3653 InsertPosition InsertBefore)
3654 : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3655 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3656}
3657
3659 InsertPosition InsertBefore)
3660 : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3661 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3662}
3663
3665 InsertPosition InsertBefore)
3666 : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3667 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3668}
3669
3671 InsertPosition InsertBefore)
3672 : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3673 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3674}
3675
3677 InsertPosition InsertBefore)
3678 : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3679 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3680}
3681
3683 InsertPosition InsertBefore)
3684 : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3685 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3686}
3687
3689 InsertPosition InsertBefore)
3690 : CastInst(Ty, PtrToAddr, S, Name, InsertBefore) {
3691 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToAddr");
3692}
3693
3695 InsertPosition InsertBefore)
3696 : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3697 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3698}
3699
3701 InsertPosition InsertBefore)
3702 : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3703 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3704}
3705
3707 InsertPosition InsertBefore)
3708 : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3709 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3710}
3711
3712//===----------------------------------------------------------------------===//
3713// CmpInst Classes
3714//===----------------------------------------------------------------------===//
3715
3717 Value *RHS, const Twine &Name, InsertPosition InsertBefore)
3718 : Instruction(ty, op, AllocMarker, InsertBefore) {
3719 Op<0>() = LHS;
3720 Op<1>() = RHS;
3721 setPredicate(predicate);
3722 setName(Name);
3723}
3724
3726 const Twine &Name, InsertPosition InsertBefore) {
3727 if (Op == Instruction::ICmp) {
3728 if (InsertBefore.isValid())
3729 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3730 S1, S2, Name);
3731 else
3732 return new ICmpInst(CmpInst::Predicate(predicate),
3733 S1, S2, Name);
3734 }
3735
3736 if (InsertBefore.isValid())
3737 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3738 S1, S2, Name);
3739 else
3740 return new FCmpInst(CmpInst::Predicate(predicate),
3741 S1, S2, Name);
3742}
3743
3745 Value *S2,
3746 const Instruction *FlagsSource,
3747 const Twine &Name,
3748 InsertPosition InsertBefore) {
3749 CmpInst *Inst = Create(Op, Pred, S1, S2, Name, InsertBefore);
3750 Inst->copyIRFlags(FlagsSource);
3751 return Inst;
3752}
3753
3755 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3756 IC->swapOperands();
3757 else
3758 cast<FCmpInst>(this)->swapOperands();
3759}
3760
3762 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3763 return IC->isCommutative();
3764 return cast<FCmpInst>(this)->isCommutative();
3765}
3766
3769 return ICmpInst::isEquality(P);
3771 return FCmpInst::isEquality(P);
3772 llvm_unreachable("Unsupported predicate kind");
3773}
3774
3775// Returns true if either operand of CmpInst is a provably non-zero
3776// floating-point constant.
3777static bool hasNonZeroFPOperands(const CmpInst *Cmp) {
3778 auto *LHS = dyn_cast<Constant>(Cmp->getOperand(0));
3779 auto *RHS = dyn_cast<Constant>(Cmp->getOperand(1));
3780 if (auto *Const = LHS ? LHS : RHS) {
3781 using namespace llvm::PatternMatch;
3782 return match(Const, m_NonZeroNotDenormalFP());
3783 }
3784 return false;
3785}
3786
3787// Floating-point equality is not an equivalence when comparing +0.0 with
3788// -0.0, when comparing NaN with another value, or when flushing
3789// denormals-to-zero.
3790bool CmpInst::isEquivalence(bool Invert) const {
3791 switch (Invert ? getInversePredicate() : getPredicate()) {
3793 return true;
3795 if (!hasNoNaNs())
3796 return false;
3797 [[fallthrough]];
3799 return hasNonZeroFPOperands(this);
3800 default:
3801 return false;
3802 }
3803}
3804
3806 switch (pred) {
3807 default: llvm_unreachable("Unknown cmp predicate!");
3808 case ICMP_EQ: return ICMP_NE;
3809 case ICMP_NE: return ICMP_EQ;
3810 case ICMP_UGT: return ICMP_ULE;
3811 case ICMP_ULT: return ICMP_UGE;
3812 case ICMP_UGE: return ICMP_ULT;
3813 case ICMP_ULE: return ICMP_UGT;
3814 case ICMP_SGT: return ICMP_SLE;
3815 case ICMP_SLT: return ICMP_SGE;
3816 case ICMP_SGE: return ICMP_SLT;
3817 case ICMP_SLE: return ICMP_SGT;
3818
3819 case FCMP_OEQ: return FCMP_UNE;
3820 case FCMP_ONE: return FCMP_UEQ;
3821 case FCMP_OGT: return FCMP_ULE;
3822 case FCMP_OLT: return FCMP_UGE;
3823 case FCMP_OGE: return FCMP_ULT;
3824 case FCMP_OLE: return FCMP_UGT;
3825 case FCMP_UEQ: return FCMP_ONE;
3826 case FCMP_UNE: return FCMP_OEQ;
3827 case FCMP_UGT: return FCMP_OLE;
3828 case FCMP_ULT: return FCMP_OGE;
3829 case FCMP_UGE: return FCMP_OLT;
3830 case FCMP_ULE: return FCMP_OGT;
3831 case FCMP_ORD: return FCMP_UNO;
3832 case FCMP_UNO: return FCMP_ORD;
3833 case FCMP_TRUE: return FCMP_FALSE;
3834 case FCMP_FALSE: return FCMP_TRUE;
3835 }
3836}
3837
3839 switch (Pred) {
3840 default: return "unknown";
3841 case FCmpInst::FCMP_FALSE: return "false";
3842 case FCmpInst::FCMP_OEQ: return "oeq";
3843 case FCmpInst::FCMP_OGT: return "ogt";
3844 case FCmpInst::FCMP_OGE: return "oge";
3845 case FCmpInst::FCMP_OLT: return "olt";
3846 case FCmpInst::FCMP_OLE: return "ole";
3847 case FCmpInst::FCMP_ONE: return "one";
3848 case FCmpInst::FCMP_ORD: return "ord";
3849 case FCmpInst::FCMP_UNO: return "uno";
3850 case FCmpInst::FCMP_UEQ: return "ueq";
3851 case FCmpInst::FCMP_UGT: return "ugt";
3852 case FCmpInst::FCMP_UGE: return "uge";
3853 case FCmpInst::FCMP_ULT: return "ult";
3854 case FCmpInst::FCMP_ULE: return "ule";
3855 case FCmpInst::FCMP_UNE: return "une";
3856 case FCmpInst::FCMP_TRUE: return "true";
3857 case ICmpInst::ICMP_EQ: return "eq";
3858 case ICmpInst::ICMP_NE: return "ne";
3859 case ICmpInst::ICMP_SGT: return "sgt";
3860 case ICmpInst::ICMP_SGE: return "sge";
3861 case ICmpInst::ICMP_SLT: return "slt";
3862 case ICmpInst::ICMP_SLE: return "sle";
3863 case ICmpInst::ICMP_UGT: return "ugt";
3864 case ICmpInst::ICMP_UGE: return "uge";
3865 case ICmpInst::ICMP_ULT: return "ult";
3866 case ICmpInst::ICMP_ULE: return "ule";
3867 }
3868}
3869
3871 OS << CmpInst::getPredicateName(Pred);
3872 return OS;
3873}
3874
3876 switch (pred) {
3877 default: llvm_unreachable("Unknown icmp predicate!");
3878 case ICMP_EQ: case ICMP_NE:
3879 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3880 return pred;
3881 case ICMP_UGT: return ICMP_SGT;
3882 case ICMP_ULT: return ICMP_SLT;
3883 case ICMP_UGE: return ICMP_SGE;
3884 case ICMP_ULE: return ICMP_SLE;
3885 }
3886}
3887
3889 switch (pred) {
3890 default: llvm_unreachable("Unknown icmp predicate!");
3891 case ICMP_EQ: case ICMP_NE:
3892 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3893 return pred;
3894 case ICMP_SGT: return ICMP_UGT;
3895 case ICMP_SLT: return ICMP_ULT;
3896 case ICMP_SGE: return ICMP_UGE;
3897 case ICMP_SLE: return ICMP_ULE;
3898 }
3899}
3900
3902 switch (pred) {
3903 default: llvm_unreachable("Unknown cmp predicate!");
3904 case ICMP_EQ: case ICMP_NE:
3905 return pred;
3906 case ICMP_SGT: return ICMP_SLT;
3907 case ICMP_SLT: return ICMP_SGT;
3908 case ICMP_SGE: return ICMP_SLE;
3909 case ICMP_SLE: return ICMP_SGE;
3910 case ICMP_UGT: return ICMP_ULT;
3911 case ICMP_ULT: return ICMP_UGT;
3912 case ICMP_UGE: return ICMP_ULE;
3913 case ICMP_ULE: return ICMP_UGE;
3914
3915 case FCMP_FALSE: case FCMP_TRUE:
3916 case FCMP_OEQ: case FCMP_ONE:
3917 case FCMP_UEQ: case FCMP_UNE:
3918 case FCMP_ORD: case FCMP_UNO:
3919 return pred;
3920 case FCMP_OGT: return FCMP_OLT;
3921 case FCMP_OLT: return FCMP_OGT;
3922 case FCMP_OGE: return FCMP_OLE;
3923 case FCMP_OLE: return FCMP_OGE;
3924 case FCMP_UGT: return FCMP_ULT;
3925 case FCMP_ULT: return FCMP_UGT;
3926 case FCMP_UGE: return FCMP_ULE;
3927 case FCMP_ULE: return FCMP_UGE;
3928 }
3929}
3930
3932 switch (pred) {
3933 case ICMP_SGE:
3934 case ICMP_SLE:
3935 case ICMP_UGE:
3936 case ICMP_ULE:
3937 case FCMP_OGE:
3938 case FCMP_OLE:
3939 case FCMP_UGE:
3940 case FCMP_ULE:
3941 return true;
3942 default:
3943 return false;
3944 }
3945}
3946
3948 switch (pred) {
3949 case ICMP_SGT:
3950 case ICMP_SLT:
3951 case ICMP_UGT:
3952 case ICMP_ULT:
3953 case FCMP_OGT:
3954 case FCMP_OLT:
3955 case FCMP_UGT:
3956 case FCMP_ULT:
3957 return true;
3958 default:
3959 return false;
3960 }
3961}
3962
3964 switch (pred) {
3965 case ICMP_SGE:
3966 return ICMP_SGT;
3967 case ICMP_SLE:
3968 return ICMP_SLT;
3969 case ICMP_UGE:
3970 return ICMP_UGT;
3971 case ICMP_ULE:
3972 return ICMP_ULT;
3973 case FCMP_OGE:
3974 return FCMP_OGT;
3975 case FCMP_OLE:
3976 return FCMP_OLT;
3977 case FCMP_UGE:
3978 return FCMP_UGT;
3979 case FCMP_ULE:
3980 return FCMP_ULT;
3981 default:
3982 return pred;
3983 }
3984}
3985
3987 switch (pred) {
3988 case ICMP_SGT:
3989 return ICMP_SGE;
3990 case ICMP_SLT:
3991 return ICMP_SLE;
3992 case ICMP_UGT:
3993 return ICMP_UGE;
3994 case ICMP_ULT:
3995 return ICMP_ULE;
3996 case FCMP_OGT:
3997 return FCMP_OGE;
3998 case FCMP_OLT:
3999 return FCMP_OLE;
4000 case FCMP_UGT:
4001 return FCMP_UGE;
4002 case FCMP_ULT:
4003 return FCMP_ULE;
4004 default:
4005 return pred;
4006 }
4007}
4008
4010 assert(CmpInst::isRelational(pred) && "Call only with relational predicate!");
4011
4012 if (isStrictPredicate(pred))
4013 return getNonStrictPredicate(pred);
4014 if (isNonStrictPredicate(pred))
4015 return getStrictPredicate(pred);
4016
4017 llvm_unreachable("Unknown predicate!");
4018}
4019
4020bool ICmpInst::compare(const APInt &LHS, const APInt &RHS,
4021 ICmpInst::Predicate Pred) {
4022 assert(ICmpInst::isIntPredicate(Pred) && "Only for integer predicates!");
4023 switch (Pred) {
4025 return LHS.eq(RHS);
4027 return LHS.ne(RHS);
4029 return LHS.ugt(RHS);
4031 return LHS.uge(RHS);
4033 return LHS.ult(RHS);
4035 return LHS.ule(RHS);
4037 return LHS.sgt(RHS);
4039 return LHS.sge(RHS);
4041 return LHS.slt(RHS);
4043 return LHS.sle(RHS);
4044 default:
4045 llvm_unreachable("Unexpected non-integer predicate.");
4046 };
4047}
4048
4049bool FCmpInst::compare(const APFloat &LHS, const APFloat &RHS,
4050 FCmpInst::Predicate Pred) {
4051 APFloat::cmpResult R = LHS.compare(RHS);
4052 switch (Pred) {
4053 default:
4054 llvm_unreachable("Invalid FCmp Predicate");
4056 return false;
4058 return true;
4059 case FCmpInst::FCMP_UNO:
4060 return R == APFloat::cmpUnordered;
4061 case FCmpInst::FCMP_ORD:
4062 return R != APFloat::cmpUnordered;
4063 case FCmpInst::FCMP_UEQ:
4064 return R == APFloat::cmpUnordered || R == APFloat::cmpEqual;
4065 case FCmpInst::FCMP_OEQ:
4066 return R == APFloat::cmpEqual;
4067 case FCmpInst::FCMP_UNE:
4068 return R != APFloat::cmpEqual;
4069 case FCmpInst::FCMP_ONE:
4071 case FCmpInst::FCMP_ULT:
4072 return R == APFloat::cmpUnordered || R == APFloat::cmpLessThan;
4073 case FCmpInst::FCMP_OLT:
4074 return R == APFloat::cmpLessThan;
4075 case FCmpInst::FCMP_UGT:
4077 case FCmpInst::FCMP_OGT:
4078 return R == APFloat::cmpGreaterThan;
4079 case FCmpInst::FCMP_ULE:
4080 return R != APFloat::cmpGreaterThan;
4081 case FCmpInst::FCMP_OLE:
4082 return R == APFloat::cmpLessThan || R == APFloat::cmpEqual;
4083 case FCmpInst::FCMP_UGE:
4084 return R != APFloat::cmpLessThan;
4085 case FCmpInst::FCMP_OGE:
4086 return R == APFloat::cmpGreaterThan || R == APFloat::cmpEqual;
4087 }
4088}
4089
4090std::optional<bool> ICmpInst::compare(const KnownBits &LHS,
4091 const KnownBits &RHS,
4092 ICmpInst::Predicate Pred) {
4093 switch (Pred) {
4094 case ICmpInst::ICMP_EQ:
4095 return KnownBits::eq(LHS, RHS);
4096 case ICmpInst::ICMP_NE:
4097 return KnownBits::ne(LHS, RHS);
4098 case ICmpInst::ICMP_UGE:
4099 return KnownBits::uge(LHS, RHS);
4100 case ICmpInst::ICMP_UGT:
4101 return KnownBits::ugt(LHS, RHS);
4102 case ICmpInst::ICMP_ULE:
4103 return KnownBits::ule(LHS, RHS);
4104 case ICmpInst::ICMP_ULT:
4105 return KnownBits::ult(LHS, RHS);
4106 case ICmpInst::ICMP_SGE:
4107 return KnownBits::sge(LHS, RHS);
4108 case ICmpInst::ICMP_SGT:
4109 return KnownBits::sgt(LHS, RHS);
4110 case ICmpInst::ICMP_SLE:
4111 return KnownBits::sle(LHS, RHS);
4112 case ICmpInst::ICMP_SLT:
4113 return KnownBits::slt(LHS, RHS);
4114 default:
4115 llvm_unreachable("Unexpected non-integer predicate.");
4116 }
4117}
4118
4120 if (CmpInst::isEquality(pred))
4121 return pred;
4122 if (isSigned(pred))
4123 return getUnsignedPredicate(pred);
4124 if (isUnsigned(pred))
4125 return getSignedPredicate(pred);
4126
4127 llvm_unreachable("Unknown predicate!");
4128}
4129
4131 switch (predicate) {
4132 default: return false;
4135 case FCmpInst::FCMP_ORD: return true;
4136 }
4137}
4138
4140 switch (predicate) {
4141 default: return false;
4144 case FCmpInst::FCMP_UNO: return true;
4145 }
4146}
4147
4149 switch(predicate) {
4150 default: return false;
4151 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
4152 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
4153 }
4154}
4155
4157 switch(predicate) {
4158 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
4159 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
4160 default: return false;
4161 }
4162}
4163
4165 // If the predicates match, then we know the first condition implies the
4166 // second is true.
4167 if (CmpPredicate::getMatching(Pred1, Pred2))
4168 return true;
4169
4170 if (Pred1.hasSameSign() && CmpInst::isSigned(Pred2))
4172 else if (Pred2.hasSameSign() && CmpInst::isSigned(Pred1))
4174
4175 switch (Pred1) {
4176 default:
4177 break;
4178 case CmpInst::ICMP_EQ:
4179 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
4180 return Pred2 == CmpInst::ICMP_UGE || Pred2 == CmpInst::ICMP_ULE ||
4181 Pred2 == CmpInst::ICMP_SGE || Pred2 == CmpInst::ICMP_SLE;
4182 case CmpInst::ICMP_UGT: // A >u B implies A != B and A >=u B are true.
4183 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_UGE;
4184 case CmpInst::ICMP_ULT: // A <u B implies A != B and A <=u B are true.
4185 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_ULE;
4186 case CmpInst::ICMP_SGT: // A >s B implies A != B and A >=s B are true.
4187 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_SGE;
4188 case CmpInst::ICMP_SLT: // A <s B implies A != B and A <=s B are true.
4189 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_SLE;
4190 }
4191 return false;
4192}
4193
4195 CmpPredicate Pred2) {
4196 return isImpliedTrueByMatchingCmp(Pred1,
4198}
4199
4201 CmpPredicate Pred2) {
4202 if (isImpliedTrueByMatchingCmp(Pred1, Pred2))
4203 return true;
4204 if (isImpliedFalseByMatchingCmp(Pred1, Pred2))
4205 return false;
4206 return std::nullopt;
4207}
4208
4209//===----------------------------------------------------------------------===//
4210// CmpPredicate Implementation
4211//===----------------------------------------------------------------------===//
4212
4213std::optional<CmpPredicate> CmpPredicate::getMatching(CmpPredicate A,
4214 CmpPredicate B) {
4215 if (A.Pred == B.Pred)
4216 return A.HasSameSign == B.HasSameSign ? A : CmpPredicate(A.Pred);
4218 return {};
4219 if (A.HasSameSign &&
4221 return B.Pred;
4222 if (B.HasSameSign &&
4224 return A.Pred;
4225 return {};
4226}
4227
4231
4233 if (auto *ICI = dyn_cast<ICmpInst>(Cmp))
4234 return ICI->getCmpPredicate();
4235 return Cmp->getPredicate();
4236}
4237
4241
4245
4247 return getSwapped(get(Cmp));
4248}
4249
4250//===----------------------------------------------------------------------===//
4251// SwitchInst Implementation
4252//===----------------------------------------------------------------------===//
4253
4254void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
4255 assert(Value && Default && NumReserved);
4256 ReservedSpace = NumReserved;
4257 allocHungoffUses(ReservedSpace);
4259
4260 Op<0>() = Value;
4261 Op<1>() = Default;
4262}
4263
4264/// SwitchInst ctor - Create a new switch instruction, specifying a value to
4265/// switch on and a default destination. The number of additional cases can
4266/// be specified here to make memory allocation more efficient. This
4267/// constructor can also autoinsert before another instruction.
4268SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
4269 InsertPosition InsertBefore)
4270 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
4271 AllocMarker, InsertBefore) {
4272 init(Value, Default, 2 + NumCases);
4273}
4274
4275SwitchInst::SwitchInst(const SwitchInst &SI)
4276 : Instruction(SI.getType(), Instruction::Switch, AllocMarker) {
4277 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
4278 setNumHungOffUseOperands(SI.getNumOperands());
4279 Use *OL = getOperandList();
4280 ConstantInt **VL = case_values();
4281 const Use *InOL = SI.getOperandList();
4282 ConstantInt *const *InVL = SI.case_values();
4283 for (unsigned i = 2, E = SI.getNumOperands(); i != E; ++i) {
4284 OL[i] = InOL[i];
4285 VL[i - 2] = InVL[i - 2];
4286 }
4287 SubclassOptionalData = SI.SubclassOptionalData;
4288}
4289
4290/// addCase - Add an entry to the switch instruction...
4291///
4293 unsigned NewCaseIdx = getNumCases();
4294 unsigned OpNo = getNumOperands();
4295 if (OpNo + 1 > ReservedSpace)
4296 growOperands(); // Get more space!
4297 // Initialize some new operands.
4298 assert(OpNo < ReservedSpace && "Growing didn't work!");
4299 setNumHungOffUseOperands(OpNo + 1);
4300 CaseHandle Case(this, NewCaseIdx);
4301 Case.setValue(OnVal);
4302 Case.setSuccessor(Dest);
4303}
4304
4305/// removeCase - This method removes the specified case and its successor
4306/// from the switch instruction.
4308 unsigned idx = I->getCaseIndex();
4309
4310 assert(2 + idx < getNumOperands() && "Case index out of range!!!");
4311
4312 unsigned NumOps = getNumOperands();
4313 Use *OL = getOperandList();
4314 ConstantInt **VL = case_values();
4315
4316 // Overwrite this case with the end of the list.
4317 if (2 + idx + 1 != NumOps) {
4318 OL[2 + idx] = OL[NumOps - 1];
4319 VL[idx] = VL[NumOps - 2 - 1];
4320 }
4321
4322 // Nuke the last value.
4323 OL[NumOps - 1].set(nullptr);
4324 VL[NumOps - 2 - 1] = nullptr;
4326
4327 return CaseIt(this, idx);
4328}
4329
4330/// growOperands - grow operands - This grows the operand list in response
4331/// to a push_back style of operation. This grows the number of ops by 3 times.
4332///
4333void SwitchInst::growOperands() {
4334 unsigned e = getNumOperands();
4335 unsigned NumOps = e*3;
4336
4337 ReservedSpace = NumOps;
4338 growHungoffUses(ReservedSpace, /*WithExtraValues=*/true);
4339}
4340
4342 MDNode *ProfileData = getBranchWeightMDNode(SI);
4343 if (!ProfileData)
4344 return;
4345
4346 if (getNumBranchWeights(*ProfileData) != SI.getNumSuccessors()) {
4347 llvm_unreachable("number of prof branch_weights metadata operands does "
4348 "not correspond to number of succesors");
4349 }
4350
4352 if (!extractBranchWeights(ProfileData, Weights))
4353 return;
4354 this->Weights = std::move(Weights);
4355}
4356
4359 if (Weights) {
4360 assert(SI.getNumSuccessors() == Weights->size() &&
4361 "num of prof branch_weights must accord with num of successors");
4362 Changed = true;
4363 // Copy the last case to the place of the removed one and shrink.
4364 // This is tightly coupled with the way SwitchInst::removeCase() removes
4365 // the cases in SwitchInst::removeCase(CaseIt).
4366 (*Weights)[I->getCaseIndex() + 1] = Weights->back();
4367 Weights->pop_back();
4368 }
4369 return SI.removeCase(I);
4370}
4371
4373 auto *DestBlock = I->getCaseSuccessor();
4374 if (Weights) {
4375 auto Weight = getSuccessorWeight(I->getCaseIndex() + 1);
4376 (*Weights)[0] = Weight.value();
4377 }
4378
4379 SI.setDefaultDest(DestBlock);
4380}
4381
4383 ConstantInt *OnVal, BasicBlock *Dest,
4385 SI.addCase(OnVal, Dest);
4386
4387 if (!Weights && W && *W) {
4388 Changed = true;
4389 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4390 (*Weights)[SI.getNumSuccessors() - 1] = *W;
4391 } else if (Weights) {
4392 Changed = true;
4393 Weights->push_back(W.value_or(0));
4394 }
4395 if (Weights)
4396 assert(SI.getNumSuccessors() == Weights->size() &&
4397 "num of prof branch_weights must accord with num of successors");
4398}
4399
4402 // Instruction is erased. Mark as unchanged to not touch it in the destructor.
4403 Changed = false;
4404 if (Weights)
4405 Weights->resize(0);
4406 return SI.eraseFromParent();
4407}
4408
4411 if (!Weights)
4412 return std::nullopt;
4413 return (*Weights)[idx];
4414}
4415
4418 if (!W)
4419 return;
4420
4421 if (!Weights && *W)
4422 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4423
4424 if (Weights) {
4425 auto &OldW = (*Weights)[idx];
4426 if (*W != OldW) {
4427 Changed = true;
4428 OldW = *W;
4429 }
4430 }
4431}
4432
4435 unsigned idx) {
4436 if (MDNode *ProfileData = getValidBranchWeightMDNode(SI)) {
4437 SmallVector<uint32_t> Weights;
4438 extractFromBranchWeightMD32(ProfileData, Weights);
4439 return Weights[idx];
4440 }
4441
4442 return std::nullopt;
4443}
4444
4445//===----------------------------------------------------------------------===//
4446// IndirectBrInst Implementation
4447//===----------------------------------------------------------------------===//
4448
4449void IndirectBrInst::init(Value *Address, unsigned NumDests) {
4450 assert(Address && Address->getType()->isPointerTy() &&
4451 "Address of indirectbr must be a pointer");
4452 ReservedSpace = 1 + NumDests;
4453 allocHungoffUses(ReservedSpace);
4455
4456 Op<0>() = Address;
4457}
4458
4459
4460/// growOperands - grow operands - This grows the operand list in response
4461/// to a push_back style of operation. This grows the number of ops by 2 times.
4462///
4463void IndirectBrInst::growOperands() {
4464 unsigned e = getNumOperands();
4465 unsigned NumOps = e*2;
4466
4467 ReservedSpace = NumOps;
4468 growHungoffUses(ReservedSpace);
4469}
4470
4471IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4472 InsertPosition InsertBefore)
4473 : Instruction(Type::getVoidTy(Address->getContext()),
4474 Instruction::IndirectBr, AllocMarker, InsertBefore) {
4475 init(Address, NumCases);
4476}
4477
4478IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
4479 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
4480 AllocMarker) {
4481 allocHungoffUses(IBI.getNumOperands());
4482 setNumHungOffUseOperands(IBI.NumUserOperands);
4483 Use *OL = getOperandList();
4484 const Use *InOL = IBI.getOperandList();
4485 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
4486 OL[i] = InOL[i];
4487 SubclassOptionalData = IBI.SubclassOptionalData;
4488}
4489
4490/// addDestination - Add a destination.
4491///
4493 unsigned OpNo = getNumOperands();
4494 if (OpNo+1 > ReservedSpace)
4495 growOperands(); // Get more space!
4496 // Initialize some new operands.
4497 assert(OpNo < ReservedSpace && "Growing didn't work!");
4499 getOperandList()[OpNo] = DestBB;
4500}
4501
4502/// removeDestination - This method removes the specified successor from the
4503/// indirectbr instruction.
4505 assert(idx < getNumOperands()-1 && "Successor index out of range!");
4506
4507 unsigned NumOps = getNumOperands();
4508 Use *OL = getOperandList();
4509
4510 // Replace this value with the last one.
4511 OL[idx+1] = OL[NumOps-1];
4512
4513 // Nuke the last value.
4514 OL[NumOps-1].set(nullptr);
4516}
4517
4518//===----------------------------------------------------------------------===//
4519// FreezeInst Implementation
4520//===----------------------------------------------------------------------===//
4521
4522FreezeInst::FreezeInst(Value *S, const Twine &Name, InsertPosition InsertBefore)
4523 : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) {
4524 setName(Name);
4525}
4526
4527//===----------------------------------------------------------------------===//
4528// cloneImpl() implementations
4529//===----------------------------------------------------------------------===//
4530
4531// Define these methods here so vtables don't get emitted into every translation
4532// unit that uses these classes.
4533
4534GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
4536 return new (AllocMarker) GetElementPtrInst(*this, AllocMarker);
4537}
4538
4542
4544 auto *I = static_cast<FPUnaryOperator *>(Create(getOpcode(), Op<0>()));
4545 I->FMF = FMF;
4546 return I;
4547}
4548
4551 "Should call FPBinaryOperator::cloneImpl!");
4552 return Create(getOpcode(), Op<0>(), Op<1>());
4553}
4554
4556 auto *I =
4557 static_cast<FPBinaryOperator *>(Create(getOpcode(), Op<0>(), Op<1>()));
4558 I->FMF = FMF;
4559 return I;
4560}
4561
4563 auto *I = new FCmpInst(getPredicate(), Op<0>(), Op<1>());
4564 I->FMF = FMF;
4565 return I;
4566}
4567
4569 auto *Result = new ICmpInst(getPredicate(), Op<0>(), Op<1>());
4570 Result->setSameSign(hasSameSign());
4571 return Result;
4572}
4573
4574ExtractValueInst *ExtractValueInst::cloneImpl() const {
4575 return new ExtractValueInst(*this);
4576}
4577
4578InsertValueInst *InsertValueInst::cloneImpl() const {
4579 return new InsertValueInst(*this);
4580}
4581
4584 getOperand(0), getAlign());
4585 Result->setUsedWithInAlloca(isUsedWithInAlloca());
4586 Result->setSwiftError(isSwiftError());
4587 return Result;
4588}
4589
4591 return new LoadInst(getType(), getOperand(0), Twine(), getProperties(),
4592 /*InsertBefore=*/nullptr);
4593}
4594
4596 return new StoreInst(getOperand(0), getOperand(1), getProperties(),
4597 /*InsertBefore=*/nullptr);
4598}
4599
4604 Result->setVolatile(isVolatile());
4605 Result->setWeak(isWeak());
4606 return Result;
4607}
4608
4610 AtomicRMWInst *Result = new AtomicRMWInst(
4613 Result->setVolatile(isVolatile());
4614 return Result;
4615}
4616
4620
4622 return new TruncInst(getOperand(0), getType());
4623}
4624
4626 return new ZExtInst(getOperand(0), getType());
4627}
4628
4630 return new SExtInst(getOperand(0), getType());
4631}
4632
4634 auto *I = new FPTruncInst(getOperand(0), getType());
4635 I->FMF = FMF;
4636 return I;
4637}
4638
4640 auto *I = new FPExtInst(getOperand(0), getType());
4641 I->FMF = FMF;
4642 return I;
4643}
4644
4646 auto *Result = new UIToFPInst(getOperand(0), getType());
4647 Result->FMF = FMF;
4648 return Result;
4649}
4650
4652 auto *Result = new SIToFPInst(getOperand(0), getType());
4653 Result->FMF = FMF;
4654 return Result;
4655}
4656
4658 return new FPToUIInst(getOperand(0), getType());
4659}
4660
4662 return new FPToSIInst(getOperand(0), getType());
4663}
4664
4666 return new PtrToIntInst(getOperand(0), getType());
4667}
4668
4672
4674 return new IntToPtrInst(getOperand(0), getType());
4675}
4676
4678 return new BitCastInst(getOperand(0), getType());
4679}
4680
4684
4685CallInst *CallInst::cloneImpl() const {
4686 if (hasOperandBundles()) {
4690 return new (AllocMarker) CallInst(*this, AllocMarker);
4691 }
4693 return new (AllocMarker) CallInst(*this, AllocMarker);
4694}
4695
4696SelectInst *SelectInst::cloneImpl() const {
4698 I->FMF = FMF;
4699 return I;
4700}
4701
4703 return new VAArgInst(getOperand(0), getType());
4704}
4705
4706ExtractElementInst *ExtractElementInst::cloneImpl() const {
4708}
4709
4710InsertElementInst *InsertElementInst::cloneImpl() const {
4712}
4713
4714BitInsertInst *BitInsertInst::cloneImpl() const {
4716}
4717
4718BitExtractInst *BitExtractInst::cloneImpl() const {
4720}
4721
4725
4726PHINode *PHINode::cloneImpl() const { return new (AllocMarker) PHINode(*this); }
4727
4728LandingPadInst *LandingPadInst::cloneImpl() const {
4729 return new LandingPadInst(*this);
4730}
4731
4732ReturnInst *ReturnInst::cloneImpl() const {
4734 return new (AllocMarker) ReturnInst(*this, AllocMarker);
4735}
4736
4737UncondBrInst *UncondBrInst::cloneImpl() const {
4738 return new (AllocMarker) UncondBrInst(*this);
4739}
4740
4741CondBrInst *CondBrInst::cloneImpl() const {
4742 return new (AllocMarker) CondBrInst(*this);
4743}
4744
4745SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4746
4747IndirectBrInst *IndirectBrInst::cloneImpl() const {
4748 return new IndirectBrInst(*this);
4749}
4750
4751InvokeInst *InvokeInst::cloneImpl() const {
4752 if (hasOperandBundles()) {
4756 return new (AllocMarker) InvokeInst(*this, AllocMarker);
4757 }
4759 return new (AllocMarker) InvokeInst(*this, AllocMarker);
4760}
4761
4762CallBrInst *CallBrInst::cloneImpl() const {
4763 if (hasOperandBundles()) {
4767 return new (AllocMarker) CallBrInst(*this, AllocMarker);
4768 }
4770 return new (AllocMarker) CallBrInst(*this, AllocMarker);
4771}
4772
4773ResumeInst *ResumeInst::cloneImpl() const {
4774 return new (AllocMarker) ResumeInst(*this);
4775}
4776
4777CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4779 return new (AllocMarker) CleanupReturnInst(*this, AllocMarker);
4780}
4781
4782CatchReturnInst *CatchReturnInst::cloneImpl() const {
4783 return new (AllocMarker) CatchReturnInst(*this);
4784}
4785
4786CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
4787 return new CatchSwitchInst(*this);
4788}
4789
4790FuncletPadInst *FuncletPadInst::cloneImpl() const {
4792 return new (AllocMarker) FuncletPadInst(*this, AllocMarker);
4793}
4794
4796 LLVMContext &Context = getContext();
4797 return new UnreachableInst(Context);
4798}
4799
4800bool UnreachableInst::shouldLowerToTrap(bool TrapUnreachable,
4801 bool NoTrapAfterNoreturn) const {
4802 if (!TrapUnreachable)
4803 return false;
4804
4805 // We may be able to ignore unreachable behind a noreturn call.
4807 Call && Call->doesNotReturn()) {
4808 if (NoTrapAfterNoreturn)
4809 return false;
4810 // Do not emit an additional trap instruction.
4811 if (Call->isNonContinuableTrap())
4812 return false;
4813 }
4814
4815 if (getFunction()->hasFnAttribute(Attribute::Naked))
4816 return false;
4817
4818 return true;
4819}
4820
4822 return new FreezeInst(getOperand(0));
4823}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT S1
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
@ FnAttr
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
This file contains the declarations for the subclasses of Constant, which represent the different fla...
@ Default
static bool isSigned(unsigned Opcode)
#define op(i)
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
static Align computeLoadStoreDefaultAlign(Type *Ty, InsertPosition Pos)
static bool isImpliedFalseByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
static Value * createPlaceholderForShuffleVector(Value *V)
static Align computeAllocaDefaultAlign(Type *Ty, InsertPosition Pos)
static bool hasNonZeroFPOperands(const CmpInst *Cmp)
static int matchShuffleAsBitRotate(ArrayRef< int > Mask, int NumSubElts)
Try to lower a vector shuffle as a bit rotation.
static Type * getIndexedTypeInternal(Type *Ty, ArrayRef< IndexTy > IdxList)
static bool isReplicationMaskWithParams(ArrayRef< int > Mask, int ReplicationFactor, int VF)
static bool isIdentityMaskImpl(ArrayRef< int > Mask, int NumOpElts)
static Value * getAISize(LLVMContext &Context, Value *Amt)
static bool isImpliedTrueByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
static bool isSingleSourceMaskImpl(ArrayRef< int > Mask, int64_t NumOpElts)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
#define T
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file implements the SmallBitVector class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:351
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
Definition APFloat.cpp:6306
Class for arbitrary precision integers.
Definition APInt.h:78
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
This class represents a conversion between pointers from one address space to another.
LLVM_ABI AddrSpaceCastInst * cloneImpl() const
Clone an identical AddrSpaceCastInst.
LLVM_ABI AddrSpaceCastInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI std::optional< TypeSize > getAllocationSizeInBits(const DataLayout &DL) const
Get allocation size in bits.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI TypeSize getAllocationBaseSize(const DataLayout &DL) const
Get the size of the allocated type.
LLVM_ABI AllocaInst * cloneImpl() const
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
void setAlignment(Align Align)
const Value * getArraySize() const
Get the number of elements allocated.
LLVM_ABI AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, const Twine &Name, InsertPosition InsertBefore)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
void setSyncScopeID(SyncScope::ID SSID)
Sets the synchronization scope ID of this cmpxchg instruction.
bool isVolatile() const
Return true if this is a cmpxchg from a volatile memory location.
void setFailureOrdering(AtomicOrdering Ordering)
Sets the failure ordering constraint of this cmpxchg instruction.
AtomicOrdering getFailureOrdering() const
Returns the failure ordering constraint of this cmpxchg instruction.
void setSuccessOrdering(AtomicOrdering Ordering)
Sets the success ordering constraint of this cmpxchg instruction.
LLVM_ABI AtomicCmpXchgInst * cloneImpl() const
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
bool isWeak() const
Return true if this cmpxchg may spuriously fail.
void setAlignment(Align Align)
AtomicOrdering getSuccessOrdering() const
Returns the success ordering constraint of this cmpxchg instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this cmpxchg instruction.
LLVM_ABI AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, SyncScope::ID SSID, InsertPosition InsertBefore=nullptr)
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI AtomicRMWInst * cloneImpl() const
bool isVolatile() const
Return true if this is a RMW on a volatile memory location.
LLVM_ABI AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, AtomicOrdering Ordering, SyncScope::ID SSID, bool Elementwise=false, InsertPosition InsertBefore=nullptr)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
void setSyncScopeID(SyncScope::ID SSID)
Sets the synchronization scope ID of this rmw instruction.
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this rmw instruction.
void setOperation(BinOp Operation)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
BinOp getOperation() const
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this rmw instruction.
void setAlignment(Align Align)
void setElementwise(bool V)
Specify whether this RMW has elementwise vector semantics.
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
LLVM_ABI CaptureInfo getCaptureInfo() const
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:107
LLVM_ABI const ConstantRange & getRange() const
Returns the value of the range attribute.
static LLVM_ABI Attribute getWithMemoryEffects(LLVMContext &Context, MemoryEffects ME)
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:263
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:126
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
static LLVM_ABI BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
Definition InstrTypes.h:409
LLVM_ABI bool swapOperands()
Exchange the two operands to this instruction.
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition InstrTypes.h:216
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
LLVM_ABI BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty, const Twine &Name, InsertPosition InsertBefore)
static LLVM_ABI BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
LLVM_ABI BinaryOperator * cloneImpl() const
This class represents a no-op cast from one type to another.
LLVM_ABI BitCastInst * cloneImpl() const
Clone an identical BitCastInst.
LLVM_ABI BitCastInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI BitExtractInst * cloneImpl() const
Clone an identical BitExtractInst.
static LLVM_ABI const char * areInvalidOperands(const Type *Ty, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitextract operation, otherwise return nu...
static BitExtractInst * Create(Type *Ty, Value *Src, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
static BitInsertInst * Create(Value *Base, Value *Val, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI BitInsertInst * cloneImpl() const
Clone an identical BitInsertInst.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI FPClassTest getParamNoFPClass(unsigned i) const
Extract a test mask for disallowed floating-point value classes for the parameter.
bool isInlineAsm() const
Check if this call is an inline asm statement.
LLVM_ABI BundleOpInfo & getBundleOpInfoForOperand(unsigned OpIdx)
Return the BundleOpInfo for the operand at index OpIdx.
void setCallingConv(CallingConv::ID CC)
LLVM_ABI FPClassTest getRetNoFPClass() const
Extract a test mask for disallowed floating-point value classes for the return value.
bundle_op_iterator bundle_op_info_begin()
Return the start of the list of BundleOpInfo instances associated with this OperandBundleUser.
LLVM_ABI bool paramHasNonNullAttr(unsigned ArgNo, bool AllowUndefOrPoison) const
Return true if this argument has the nonnull attribute on either the CallBase instruction or the call...
LLVM_ABI MemoryEffects getMemoryEffects() const
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
LLVM_ABI bool doesNotAccessMemory() const
Determine if the call does not access memory.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
LLVM_ABI void setOnlyAccessesArgMemory()
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
OperandBundleUse operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const
Simple helper function to map a BundleOpInfo to an OperandBundleUse.
LLVM_ABI void setOnlyAccessesInaccessibleMemOrArgMem()
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI void setDoesNotAccessMemory()
AttributeSet getParamAttributes(unsigned ArgNo) const
Return the param attributes for this call.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
LLVM_ABI bool onlyAccessesInaccessibleMemory() const
Determine if the function may only access memory that is inaccessible from the IR.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
bundle_op_iterator bundle_op_info_end()
Return the end of the list of BundleOpInfo instances associated with this OperandBundleUser.
LLVM_ABI unsigned getNumSubclassExtraOperandsDynamic() const
Get the number of extra operands for instructions that don't have a fixed number of extra operands.
BundleOpInfo * bundle_op_iterator
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
LLVM_ABI bool onlyReadsMemory() const
Determine if the call does not access or only reads memory.
LLVM_ABI bool isNoInline() const
Return true if the call should not be inlined, either because the call site is marked noinline or bec...
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
iterator_range< bundle_op_iterator > bundle_op_infos()
Return the range [bundle_op_info_begin, bundle_op_info_end).
LLVM_ABI void setOnlyReadsMemory()
static LLVM_ABI CallBase * addOperandBundle(CallBase *CB, uint32_t ID, OperandBundleDef OB, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle OB added.
LLVM_ABI bool onlyAccessesInaccessibleMemOrArgMem() const
Determine if the function may only access memory that is either inaccessible from the IR or pointed t...
static LLVM_ABI CallBase * removeOperandBundleAt(CallBase *CB, size_t Offset, InsertPosition InsertPtr=nullptr)
LLVM_ABI CaptureInfo getCaptureInfo(unsigned OpNo) const
Return which pointer components this operand may capture.
LLVM_ABI bool hasArgumentWithAdditionalReturnCaptureComponents() const
Returns whether the call has an argument that has an attribute like captures(ret: address,...
CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args)
Value * getCalledOperand() const
LLVM_ABI void setOnlyWritesMemory()
LLVM_ABI op_iterator populateBundleOperandInfos(ArrayRef< OperandBundleDef > Bundles, const unsigned BeginIndex)
Populate the BundleOpInfo instances and the Use& vector from Bundles.
AttributeList Attrs
parameter attributes for callable
bool hasOperandBundlesOtherThan(ArrayRef< uint32_t > IDs) const
Return true if this operand bundle user contains operand bundles with tags other than those specified...
LLVM_ABI bool isVolatile() const
Return true if this is a call to an intrinsic with a volatile flag that is set, e....
LLVM_ABI std::optional< ConstantRange > getRange() const
If this return value has a range attribute, return the value range of the argument.
LLVM_ABI bool isReturnNonNull() const
Return true if the return value is known to be not null.
Value * getArgOperand(unsigned i) const
FunctionType * FTy
uint64_t getRetDereferenceableBytes() const
Extract the number of dereferenceable bytes for a call or parameter (0=unknown).
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
static unsigned CountBundleInputs(ArrayRef< OperandBundleDef > Bundles)
Return the total number of values used in Bundles.
LLVM_ABI Value * getArgOperandWithAttribute(Attribute::AttrKind Kind) const
If one of the arguments has the specified attribute, returns its operand value.
LLVM_ABI void setOnlyAccessesInaccessibleMemory()
static LLVM_ABI CallBase * Create(CallBase *CB, ArrayRef< OperandBundleDef > Bundles, InsertPosition InsertPt=nullptr)
Create a clone of CB with a different set of operand bundles and insert it before InsertPt.
LLVM_ABI bool onlyWritesMemory() const
Determine if the call does not access or only writes memory.
LLVM_ABI bool hasClobberingOperandBundles() const
Return true if this operand bundle user has operand bundles that may write to the heap.
void setCalledOperand(Value *V)
static LLVM_ABI CallBase * removeOperandBundle(CallBase *CB, uint32_t ID, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle ID removed.
LLVM_ABI bool hasReadingOperandBundles() const
Return true if this operand bundle user has operand bundles that may read from the heap.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI void setMemoryEffects(MemoryEffects ME)
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI bool isTailCall() const
Tests if this call site is marked as a tail call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
SmallVector< BasicBlock *, 16 > getIndirectDests() const
void setDefaultDest(BasicBlock *B)
void setIndirectDest(unsigned i, BasicBlock *B)
BasicBlock * getDefaultDest() const
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
LLVM_ABI CallBrInst * cloneImpl() const
This class represents a function call, abstracting a target machine's calling convention.
LLVM_ABI void updateProfWeight(uint64_t S, uint64_t T)
Updates profile metadata by scaling it by S / T.
TailCallKind getTailCallKind() const
LLVM_ABI CallInst * cloneImpl() const
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Represents which components of the pointer may be captured in which location.
Definition ModRef.h:414
CaptureComponents getOtherComponents() const
Get components potentially captured through locations other than the return value.
Definition ModRef.h:446
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
static CaptureInfo all()
Create CaptureInfo that may capture all components of the pointer.
Definition ModRef.h:430
CaptureComponents getRetComponents() const
Get components potentially captured by the return value.
Definition ModRef.h:442
static LLVM_ABI Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
static LLVM_ABI CastInst * CreatePointerBitCastOrAddrSpaceCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast or an AddrSpaceCast cast instruction.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
static LLVM_ABI unsigned isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type *SrcTy, Type *MidTy, Type *DstTy, const DataLayout *DL)
Determine how a pair of casts can be eliminated, if they can be at all.
static LLVM_ABI CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
static LLVM_ABI CastInst * CreateFPCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create an FPExt, BitCast, or FPTrunc for fp -> fp casts.
CastInst(Type *Ty, unsigned iType, Value *S, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics for subclasses.
Definition InstrTypes.h:515
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static LLVM_ABI bool isBitCastable(Type *SrcTy, Type *DestTy)
Check whether a bitcast between these types is valid.
static LLVM_ABI CastInst * CreateTruncOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a Trunc or BitCast cast instruction.
static LLVM_ABI CastInst * CreatePointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
static LLVM_ABI CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static LLVM_ABI bool isNoopCast(Instruction::CastOps Opcode, Type *SrcTy, Type *DstTy, const DataLayout &DL)
A no-op cast is one that can be effected without changing any bits.
static LLVM_ABI CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt or BitCast cast instruction.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
LLVM_ABI bool isIntegerCast() const
There are several places where we need to know if a cast instruction only deals with integer source a...
static LLVM_ABI CastInst * CreateSExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a SExt or BitCast cast instruction.
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
LLVM_ABI CatchReturnInst * cloneImpl() const
void setUnwindDest(BasicBlock *UnwindDest)
LLVM_ABI void addHandler(BasicBlock *Dest)
Add an entry to the switch instruction... Note: This action invalidates handler_end().
LLVM_ABI CatchSwitchInst * cloneImpl() const
mapped_iterator< op_iterator, DerefFnTy > handler_iterator
Value * getParentPad() const
void setParentPad(Value *ParentPad)
BasicBlock * getUnwindDest() const
LLVM_ABI void removeHandler(handler_iterator HI)
LLVM_ABI CleanupReturnInst * cloneImpl() const
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:921
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition InstrTypes.h:831
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
LLVM_ABI bool isEquivalence(bool Invert=false) const
Determine if one operand of this compare can always be replaced by the other operand,...
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
static LLVM_ABI CmpInst * CreateWithCopiedFlags(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Instruction *FlagsSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate, the two operands and the instructio...
LLVM_ABI CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred, Value *LHS, Value *RHS, const Twine &Name="", InsertPosition InsertBefore=nullptr)
bool isNonStrictPredicate() const
Definition InstrTypes.h:915
LLVM_ABI void swapOperands()
This is just a convenience that dispatches to the subclasses.
static bool isRelational(Predicate P)
Return true if the predicate is relational (not EQ or NE).
Definition InstrTypes.h:986
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
static LLVM_ABI StringRef getPredicateName(Predicate P)
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
bool isStrictPredicate() const
Definition InstrTypes.h:906
static LLVM_ABI bool isUnordered(Predicate predicate)
Determine if the predicate is an unordered operation.
Predicate getFlippedStrictnessPredicate() const
For predicate of kind "is X or equal to 0" returns the predicate "is X".
Definition InstrTypes.h:956
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
LLVM_ABI bool isCommutative() const
This is just a convenience that dispatches to the subclasses.
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
static LLVM_ABI CmpPredicate getInverse(CmpPredicate P)
Get the inverse predicate of a CmpPredicate.
CmpPredicate()
Default constructor.
static LLVM_ABI CmpPredicate get(const CmpInst *Cmp)
Do a ICmpInst::getCmpPredicate() or CmpInst::getPredicate(), as appropriate.
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
bool hasSameSign() const
Query samesign information, for optimizations.
static LLVM_ABI CmpPredicate getSwapped(CmpPredicate P)
Get the swapped predicate of a CmpPredicate.
Conditional Branch instruction.
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
LLVM_ABI CondBrInst * cloneImpl() const
Value * getCondition() const
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
LLVM_ABI ExtractElementInst * cloneImpl() const
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
This instruction extracts a struct member or array element value from an aggregate value.
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
LLVM_ABI ExtractValueInst * cloneImpl() const
This instruction compares its operands according to the predicate given to the constructor.
bool isEquality() const
static LLVM_ABI bool compare(const APFloat &LHS, const APFloat &RHS, FCmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
LLVM_ABI FCmpInst * cloneImpl() const
Clone an identical FCmpInst.
FCmpInst(InsertPosition InsertBefore, Predicate pred, Value *LHS, Value *RHS, const Twine &NameStr="")
Constructor with insertion semantics.
Binary operators support fast-math flags, users should not use this class directly,...
Definition InstrTypes.h:476
This class represents an extension of floating point types.
LLVM_ABI FPExtInst * cloneImpl() const
Clone an identical FPExtInst.
LLVM_ABI FPExtInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI float getFPAccuracy() const
Get the maximum error permitted by this operation in ULPs.
This class represents a cast from floating point to signed integer.
LLVM_ABI FPToSIInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI FPToSIInst * cloneImpl() const
Clone an identical FPToSIInst.
This class represents a cast from floating point to unsigned integer.
LLVM_ABI FPToUIInst * cloneImpl() const
Clone an identical FPToUIInst.
LLVM_ABI FPToUIInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
This class represents a truncation of floating point types.
LLVM_ABI FPTruncInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI FPTruncInst * cloneImpl() const
Clone an identical FPTruncInst.
Unary operators support fast-math flags, users should not use this class directly,...
Definition InstrTypes.h:179
LLVM_ABI FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System, InsertPosition InsertBefore=nullptr)
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this fence instruction.
void setSyncScopeID(SyncScope::ID SSID)
Sets the synchronization scope ID of this fence instruction.
LLVM_ABI FenceInst * cloneImpl() const
friend class Instruction
Iterator for Instructions in a `BasicBlock.
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this fence instruction.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
Class to represent fixed width SIMD vectors.
LLVM_ABI FreezeInst(Value *S, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI FreezeInst * cloneImpl() const
Clone an identical FreezeInst.
void setParentPad(Value *ParentPad)
Value * getParentPad() const
Convenience accessors.
LLVM_ABI FuncletPadInst * cloneImpl() const
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Type * getParamType(unsigned i) const
Parameter type accessors.
bool isVarArg() const
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
GEPNoWrapFlags withoutInBounds() const
unsigned getRaw() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI bool isInBounds() const
Determine whether the GEP has the inbounds flag.
LLVM_ABI bool hasNoUnsignedSignedWrap() const
Determine whether the GEP has the nusw flag.
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
LLVM_ABI bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
LLVM_ABI bool hasNoUnsignedWrap() const
Determine whether the GEP has the nuw flag.
LLVM_ABI bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
LLVM_ABI void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
LLVM_ABI bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
LLVM_ABI GetElementPtrInst * cloneImpl() const
LLVM_ABI bool collectOffset(const DataLayout &DL, unsigned BitWidth, SmallMapVector< Value *, APInt, 4 > &VariableOffsets, APInt &ConstantOffset) const
LLVM_ABI void setNoWrapFlags(GEPNoWrapFlags NW)
Set nowrap flags for GEP instruction.
LLVM_ABI GEPNoWrapFlags getNoWrapFlags() const
Get the nowrap flags for the GEP instruction.
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
bool hasSameSign() const
An icmp instruction, which can be marked as "samesign", indicating that the two operands have the sam...
ICmpInst(InsertPosition InsertBefore, Predicate pred, Value *LHS, Value *RHS, const Twine &NameStr="")
Constructor with insertion semantics.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
LLVM_ABI ICmpInst * cloneImpl() const
Clone an identical ICmpInst.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
static CmpPredicate getInverseCmpPredicate(CmpPredicate Pred)
bool isEquality() const
Return true if this predicate is either EQ or NE.
static LLVM_ABI Predicate getFlippedSignednessPredicate(Predicate Pred)
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
Indirect Branch Instruction.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
LLVM_ABI void removeDestination(unsigned i)
This method removes the specified successor from the indirectbr instruction.
LLVM_ABI IndirectBrInst * cloneImpl() const
LLVM_ABI InsertElementInst * cloneImpl() const
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
bool isValid() const
Definition Instruction.h:59
BasicBlock * getBasicBlock()
Definition Instruction.h:60
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI InsertValueInst * cloneImpl() const
BitfieldElement::Type getSubclassData() const
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Bitfield::Element< uint16_t, 0, 16 > OpaqueField
Instruction(const Instruction &)=delete
friend class Value
friend class BasicBlock
Various leaf nodes.
void setSubclassData(typename BitfieldElement::Type Value)
This class represents a cast from an integer to a pointer.
LLVM_ABI IntToPtrInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI IntToPtrInst * cloneImpl() const
Clone an identical IntToPtrInst.
Invoke instruction.
BasicBlock * getUnwindDest() const
void setNormalDest(BasicBlock *B)
LLVM_ABI InvokeInst * cloneImpl() const
LLVM_ABI LandingPadInst * getLandingPadInst() const
Get the landingpad instruction from the landing pad block (the unwind destination).
void setUnwindDest(BasicBlock *B)
LLVM_ABI void updateProfWeight(uint64_t S, uint64_t T)
Updates profile metadata by scaling it by S / T.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVMContextImpl *const pImpl
Definition LLVMContext.h:78
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.
LLVM_ABI LandingPadInst * cloneImpl() const
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
void setElementwise(bool V)
Specify whether this is an elementwise atomic load or not.
void setAlignment(Align Align)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
LLVM_ABI LoadInst * cloneImpl() const
void setVolatile(bool V)
Specify whether this is a volatile load or not.
LoadStoreInstProperties getProperties() const
Returns the properties of this load instruction.
LLVM_ABI LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, InsertPosition InsertBefore)
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
bool onlyWritesMemory() const
Whether this function only (at most) writes memory.
Definition ModRef.h:252
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
bool onlyAccessesInaccessibleMem() const
Whether this function only (at most) accesses inaccessible memory.
Definition ModRef.h:265
bool onlyAccessesArgPointees() const
Whether this function only (at most) accesses argument memory.
Definition ModRef.h:255
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:249
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
bool onlyAccessesInaccessibleOrArgMem() const
Whether this function only (at most) accesses argument and inaccessible memory.
Definition ModRef.h:305
StringRef getTag() const
void allocHungoffUses(unsigned N)
const_block_iterator block_begin() const
LLVM_ABI void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
void setIncomingBlock(unsigned i, BasicBlock *BB)
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
LLVM_ABI bool hasConstantOrUndefValue() const
Whether the specified PHI node always merges together the same value, assuming undefs are equal to a ...
void setIncomingValue(unsigned i, Value *V)
const_block_iterator block_end() const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
LLVM_ABI Value * hasConstantValue() const
If the specified PHI node always merges together the same value, return the value,...
LLVM_ABI PHINode * cloneImpl() const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Class to represent pointers.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
LLVM_ABI PtrToAddrInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI PtrToAddrInst * cloneImpl() const
Clone an identical PtrToAddrInst.
This class represents a cast from a pointer to an integer.
LLVM_ABI PtrToIntInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI PtrToIntInst * cloneImpl() const
Clone an identical PtrToIntInst.
Resume the propagation of an exception.
LLVM_ABI ResumeInst * cloneImpl() const
Return a value (possibly void), from a function.
LLVM_ABI ReturnInst * cloneImpl() const
This class represents a sign extension of integer types.
LLVM_ABI SExtInst * cloneImpl() const
Clone an identical SExtInst.
LLVM_ABI SExtInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
This class represents a cast from signed integer to floating point.
LLVM_ABI SIToFPInst * cloneImpl() const
Clone an identical SIToFPInst.
LLVM_ABI SIToFPInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
Class to represent scalable SIMD vectors.
LLVM_ABI SelectInst * cloneImpl() const
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
static LLVM_ABI bool isZeroEltSplatMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses all elements with the same value as the first element of exa...
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isSpliceMask(ArrayRef< int > Mask, int NumSrcElts, int &Index)
Return true if this shuffle mask is a splice mask, concatenating the two inputs together and then ext...
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
LLVM_ABI ShuffleVectorInst(Value *V1, Value *Mask, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI bool isSelectMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from its source vectors without lane crossings.
static LLVM_ABI bool isBitRotateMask(ArrayRef< int > Mask, unsigned EltSizeInBits, unsigned MinSubElts, unsigned MaxSubElts, unsigned &NumSubElts, unsigned &RotateAmt)
Checks if the shuffle is a bit rotation of the first operand across multiple subelements,...
VectorType * getType() const
Overload to return most specific vector type.
LLVM_ABI bool isIdentityWithExtract() const
Return true if this shuffle extracts the first N elements of exactly one source vector.
static LLVM_ABI bool isOneUseSingleSourceMask(ArrayRef< int > Mask, int VF)
Return true if this shuffle mask represents "clustered" mask of size VF, i.e.
LLVM_ABI bool isIdentityWithPadding() const
Return true if this shuffle lengthens exactly one source vector with undefs in the high elements.
static LLVM_ABI bool isSingleSourceMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector.
LLVM_ABI bool isConcat() const
Return true if this shuffle concatenates its 2 source vectors.
static LLVM_ABI bool isDeInterleaveMaskOfFactor(ArrayRef< int > Mask, unsigned Factor, unsigned &Index)
Check if the mask is a DE-interleave mask of the given factor Factor like: <Index,...
LLVM_ABI ShuffleVectorInst * cloneImpl() const
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
static LLVM_ABI bool isExtractSubvectorMask(ArrayRef< int > Mask, int NumSrcElts, int &Index)
Return true if this shuffle mask is an extract subvector mask.
LLVM_ABI void setShuffleMask(ArrayRef< int > Mask)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI bool isInterleave(unsigned Factor)
Return if this shuffle interleaves its two input vectors together.
static LLVM_ABI bool isReverseMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask swaps the order of elements from exactly one source vector.
static LLVM_ABI bool isTransposeMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask is a transpose mask.
LLVM_ABI void commute()
Swap the operands and adjust the mask to preserve the semantics of the instruction.
static LLVM_ABI bool isInsertSubvectorMask(ArrayRef< int > Mask, int NumSrcElts, int &NumSubElts, int &Index)
Return true if this shuffle mask is an insert subvector mask.
static LLVM_ABI Constant * convertShuffleMaskForBitcode(ArrayRef< int > Mask, Type *ResultTy)
static LLVM_ABI bool isReplicationMask(ArrayRef< int > Mask, int &ReplicationFactor, int &VF)
Return true if this shuffle mask replicates each of the VF elements in a vector ReplicationFactor tim...
static LLVM_ABI bool isInterleaveMask(ArrayRef< int > Mask, unsigned Factor, unsigned NumInputElts, SmallVectorImpl< unsigned > &StartIndexes)
Return true if the mask interleaves one or more input vectors together.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void setVolatile(bool V)
Specify whether this is a volatile store or not.
void setAlignment(Align Align)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LoadStoreInstProperties getProperties() const
Returns the properties of this store instruction.
LLVM_ABI StoreInst * cloneImpl() const
void setElementwise(bool V)
Specify whether this is an elementwise atomic store or not.
LLVM_ABI StoreInst(Value *Val, Value *Ptr, InsertPosition InsertBefore)
bool isVolatile() const
Return true if this is a store to a volatile memory location.
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Class to represent struct types.
LLVM_ABI void setSuccessorWeight(unsigned idx, CaseWeightOpt W)
LLVM_ABI Instruction::InstListType::iterator eraseFromParent()
Delegate the call to the underlying SwitchInst::eraseFromParent() and mark this object to not touch t...
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W)
Delegate the call to the underlying SwitchInst::addCase() and set the specified branch weight for the...
LLVM_ABI CaseWeightOpt getSuccessorWeight(unsigned idx)
LLVM_ABI void replaceDefaultDest(SwitchInst::CaseIt I)
Replace the default destination by given case.
std::optional< uint32_t > CaseWeightOpt
LLVM_ABI SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight.
void setValue(ConstantInt *V) const
Sets the new value for current case.
void setSuccessor(BasicBlock *S) const
Sets the new successor for current case.
Multiway switch.
void allocHungoffUses(unsigned N)
LLVM_ABI SwitchInst * cloneImpl() const
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
CaseIteratorImpl< CaseHandle > CaseIt
ConstantInt *const * case_values() const
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
LLVM_ABI CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
Target - Wrapper for Target specific information.
This class represents a truncation of integer types.
LLVM_ABI TruncInst * cloneImpl() const
Clone an identical TruncInst.
LLVM_ABI TruncInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
static constexpr TypeSize get(ScalarTy Quantity, bool Scalable)
Definition TypeSize.h:349
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:306
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition Type.cpp:241
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
Definition Type.h:243
bool isTargetExtTy() const
Return true if this is a target extension type.
Definition Type.h:205
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
LLVM_ABI Type * getWithNewType(Type *EltTy) const
Given vector type, change the element type, whilst keeping the old number of elements.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:231
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
This class represents a cast unsigned integer to floating point.
LLVM_ABI UIToFPInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI UIToFPInst * cloneImpl() const
Clone an identical UIToFPInst.
UnaryInstruction(Type *Ty, unsigned iType, Value *V, InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:71
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
LLVM_ABI UnaryOperator(UnaryOps iType, Value *S, Type *Ty, const Twine &Name, InsertPosition InsertBefore)
LLVM_ABI UnaryOperator * cloneImpl() const
UnaryOps getOpcode() const
Definition InstrTypes.h:163
Unconditional Branch instruction.
LLVM_ABI UncondBrInst * cloneImpl() const
LLVM_ABI UnreachableInst(LLVMContext &C, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool shouldLowerToTrap(bool TrapUnreachable, bool NoTrapAfterNoreturn) const
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI UnreachableInst * cloneImpl() const
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
Use * op_iterator
Definition User.h:254
const Use * getOperandList() const
Definition User.h:200
op_iterator op_begin()
Definition User.h:259
LLVM_ABI void allocHungoffUses(unsigned N, bool WithExtraValues=false)
Allocate the array of Uses, followed by a pointer (with bottom bit set) to the User.
Definition User.cpp:48
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setNumHungOffUseOperands(unsigned NumOps)
Subclasses with hung off uses need to manage the operand count themselves.
Definition User.h:240
Use & Op()
Definition User.h:171
LLVM_ABI void growHungoffUses(unsigned N, bool WithExtraValues=false)
Grow the number of hung off uses.
Definition User.cpp:65
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
op_iterator op_end()
Definition User.h:261
VAArgInst(Value *List, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI VAArgInst * cloneImpl() const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
unsigned char SubclassOptionalData
Hold arbitary subclass data.
Definition Value.h:85
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
unsigned NumUserOperands
Definition Value.h:109
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
This class represents zero extension of integer types.
LLVM_ABI ZExtInst(Value *S, Type *Ty, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructor with insert-before-instruction semantics.
LLVM_ABI ZExtInst * cloneImpl() const
Clone an identical ZExtInst.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
typename base_list_type::iterator iterator
Definition ilist.h:121
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
bool match(Val *V, const Pattern &P)
cstfp_pred_ty< is_non_zero_not_denormal_fp > m_NonZeroNotDenormalFP()
Match a floating-point non-zero that is not a denormal.
initializer< Ty > init(const Ty &Val)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:385
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr auto seq_inclusive(T Begin, T End)
Iterate over an integral type from Begin to End inclusive.
Definition Sequence.h:361
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
std::enable_if_t< std::is_unsigned_v< T >, std::optional< T > > checkedMulUnsigned(T LHS, T RHS)
Multiply two unsigned integers LHS and RHS.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:373
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr int PoisonMaskElem
LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData)
AtomicOrdering
Atomic ordering for LLVM's memory model.
LLVM_ABI void extractFromBranchWeightMD32(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:35
@ Mul
Product of integers.
@ FSub
Subtraction of floats.
@ Xor
Bitwise or logical XOR of integers.
@ FMul
Product of floats.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
const IROptions & getIROptions(const LLVMContext &C)
Definition IROptions.h:27
constexpr unsigned BitWidth
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool capturesAnything(CaptureComponents CC)
Definition ModRef.h:379
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void scaleProfData(Instruction &I, uint64_t S, uint64_t T)
Scaling the profile data attached to 'I' using the ratio of S/T.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Summary of memprof metadata on allocations.
Used to keep track of an operand bundle.
uint32_t End
The index in the Use& vector where operands for this operand bundle ends.
uint32_t Begin
The index in the Use& vector where operands for this operand bundle starts.
static LLVM_ABI std::optional< bool > eq(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_EQ result.
static LLVM_ABI std::optional< bool > ne(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_NE result.
static LLVM_ABI std::optional< bool > sge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGE result.
static LLVM_ABI std::optional< bool > ugt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGT result.
static LLVM_ABI std::optional< bool > slt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLT result.
static LLVM_ABI std::optional< bool > ult(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULT result.
static LLVM_ABI std::optional< bool > ule(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULE result.
static LLVM_ABI std::optional< bool > sle(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLE result.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
A structure representing the properties of a load or store instruction.
Matching combinators.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344
Indicates this User has operands co-allocated.
Definition User.h:60
Indicates this User has operands and a descriptor co-allocated .
Definition User.h:66