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
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
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
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
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
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
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
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,
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 (Offset < 0)
2158 return false;
2159 if (0 <= SubIndex && SubIndex != Offset)
2160 return false;
2161 SubIndex = Offset;
2162 }
2163
2164 if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
2165 Index = SubIndex;
2166 return true;
2167 }
2168 return false;
2169}
2170
2172 int NumSrcElts, int &NumSubElts,
2173 int &Index) {
2174 int NumMaskElts = Mask.size();
2175
2176 // Don't try to match if we're shuffling to a smaller size.
2177 if (NumMaskElts < NumSrcElts)
2178 return false;
2179
2180 // TODO: We don't recognize self-insertion/widening.
2181 if (isSingleSourceMaskImpl(Mask, NumSrcElts))
2182 return false;
2183
2184 // Determine which mask elements are attributed to which source.
2185 APInt UndefElts = APInt::getZero(NumMaskElts);
2186 APInt Src0Elts = APInt::getZero(NumMaskElts);
2187 APInt Src1Elts = APInt::getZero(NumMaskElts);
2188 bool Src0Identity = true;
2189 bool Src1Identity = true;
2190
2191 for (int i = 0; i != NumMaskElts; ++i) {
2192 int M = Mask[i];
2193 if (M < 0) {
2194 UndefElts.setBit(i);
2195 continue;
2196 }
2197 if (M < NumSrcElts) {
2198 Src0Elts.setBit(i);
2199 Src0Identity &= (M == i);
2200 continue;
2201 }
2202 Src1Elts.setBit(i);
2203 Src1Identity &= (M == (i + NumSrcElts));
2204 }
2205 assert((Src0Elts | Src1Elts | UndefElts).isAllOnes() &&
2206 "unknown shuffle elements");
2207 assert(!Src0Elts.isZero() && !Src1Elts.isZero() &&
2208 "2-source shuffle not found");
2209
2210 // Determine lo/hi span ranges.
2211 // TODO: How should we handle undefs at the start of subvector insertions?
2212 int Src0Lo = Src0Elts.countr_zero();
2213 int Src1Lo = Src1Elts.countr_zero();
2214 int Src0Hi = NumMaskElts - Src0Elts.countl_zero();
2215 int Src1Hi = NumMaskElts - Src1Elts.countl_zero();
2216
2217 // If src0 is in place, see if the src1 elements is inplace within its own
2218 // span.
2219 if (Src0Identity) {
2220 int NumSub1Elts = Src1Hi - Src1Lo;
2221 ArrayRef<int> Sub1Mask = Mask.slice(Src1Lo, NumSub1Elts);
2222 if (isIdentityMaskImpl(Sub1Mask, NumSrcElts)) {
2223 NumSubElts = NumSub1Elts;
2224 Index = Src1Lo;
2225 return true;
2226 }
2227 }
2228
2229 // If src1 is in place, see if the src0 elements is inplace within its own
2230 // span.
2231 if (Src1Identity) {
2232 int NumSub0Elts = Src0Hi - Src0Lo;
2233 ArrayRef<int> Sub0Mask = Mask.slice(Src0Lo, NumSub0Elts);
2234 if (isIdentityMaskImpl(Sub0Mask, NumSrcElts)) {
2235 NumSubElts = NumSub0Elts;
2236 Index = Src0Lo;
2237 return true;
2238 }
2239 }
2240
2241 return false;
2242}
2243
2245 // FIXME: Not currently possible to express a shuffle mask for a scalable
2246 // vector for this case.
2248 return false;
2249
2250 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2251 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2252 if (NumMaskElts <= NumOpElts)
2253 return false;
2254
2255 // The first part of the mask must choose elements from exactly 1 source op.
2257 if (!isIdentityMaskImpl(Mask, NumOpElts))
2258 return false;
2259
2260 // All extending must be with undef elements.
2261 for (int i = NumOpElts; i < NumMaskElts; ++i)
2262 if (Mask[i] != -1)
2263 return false;
2264
2265 return true;
2266}
2267
2269 // FIXME: Not currently possible to express a shuffle mask for a scalable
2270 // vector for this case.
2272 return false;
2273
2274 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2275 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2276 if (NumMaskElts >= NumOpElts)
2277 return false;
2278
2279 return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
2280}
2281
2283 // Vector concatenation is differentiated from identity with padding.
2285 return false;
2286
2287 // FIXME: Not currently possible to express a shuffle mask for a scalable
2288 // vector for this case.
2290 return false;
2291
2292 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2293 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2294 if (NumMaskElts != NumOpElts * 2)
2295 return false;
2296
2297 // Use the mask length rather than the operands' vector lengths here. We
2298 // already know that the shuffle returns a vector twice as long as the inputs,
2299 // and neither of the inputs are undef vectors. If the mask picks consecutive
2300 // elements from both inputs, then this is a concatenation of the inputs.
2301 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
2302}
2303
2305 int ReplicationFactor, int VF) {
2306 assert(Mask.size() == (unsigned)ReplicationFactor * VF &&
2307 "Unexpected mask size.");
2308
2309 for (int CurrElt : seq(VF)) {
2310 ArrayRef<int> CurrSubMask = Mask.take_front(ReplicationFactor);
2311 assert(CurrSubMask.size() == (unsigned)ReplicationFactor &&
2312 "Run out of mask?");
2313 Mask = Mask.drop_front(ReplicationFactor);
2314 if (!all_of(CurrSubMask, [CurrElt](int MaskElt) {
2315 return MaskElt == PoisonMaskElem || MaskElt == CurrElt;
2316 }))
2317 return false;
2318 }
2319 assert(Mask.empty() && "Did not consume the whole mask?");
2320
2321 return true;
2322}
2323
2325 int &ReplicationFactor, int &VF) {
2326 // undef-less case is trivial.
2327 if (!llvm::is_contained(Mask, PoisonMaskElem)) {
2328 ReplicationFactor =
2329 Mask.take_while([](int MaskElt) { return MaskElt == 0; }).size();
2330 if (ReplicationFactor == 0 || Mask.size() % ReplicationFactor != 0)
2331 return false;
2332 VF = Mask.size() / ReplicationFactor;
2333 return isReplicationMaskWithParams(Mask, ReplicationFactor, VF);
2334 }
2335
2336 // However, if the mask contains undef's, we have to enumerate possible tuples
2337 // and pick one. There are bounds on replication factor: [1, mask size]
2338 // (where RF=1 is an identity shuffle, RF=mask size is a broadcast shuffle)
2339 // Additionally, mask size is a replication factor multiplied by vector size,
2340 // which further significantly reduces the search space.
2341
2342 // Before doing that, let's perform basic correctness checking first.
2343 int Largest = -1;
2344 for (int MaskElt : Mask) {
2345 if (MaskElt == PoisonMaskElem)
2346 continue;
2347 // Elements must be in non-decreasing order.
2348 if (MaskElt < Largest)
2349 return false;
2350 Largest = std::max(Largest, MaskElt);
2351 }
2352
2353 // Prefer larger replication factor if all else equal.
2354 for (int PossibleReplicationFactor :
2355 reverse(seq_inclusive<unsigned>(1, Mask.size()))) {
2356 if (Mask.size() % PossibleReplicationFactor != 0)
2357 continue;
2358 int PossibleVF = Mask.size() / PossibleReplicationFactor;
2359 if (!isReplicationMaskWithParams(Mask, PossibleReplicationFactor,
2360 PossibleVF))
2361 continue;
2362 ReplicationFactor = PossibleReplicationFactor;
2363 VF = PossibleVF;
2364 return true;
2365 }
2366
2367 return false;
2368}
2369
2370bool ShuffleVectorInst::isReplicationMask(int &ReplicationFactor,
2371 int &VF) const {
2372 // Not possible to express a shuffle mask for a scalable vector for this
2373 // case.
2375 return false;
2376
2377 VF = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2378 if (ShuffleMask.size() % VF != 0)
2379 return false;
2380 ReplicationFactor = ShuffleMask.size() / VF;
2381
2382 return isReplicationMaskWithParams(ShuffleMask, ReplicationFactor, VF);
2383}
2384
2386 if (VF <= 0 || Mask.size() < static_cast<unsigned>(VF) ||
2387 Mask.size() % VF != 0)
2388 return false;
2389 for (unsigned K = 0, Sz = Mask.size(); K < Sz; K += VF) {
2390 ArrayRef<int> SubMask = Mask.slice(K, VF);
2391 if (all_of(SubMask, equal_to(PoisonMaskElem)))
2392 continue;
2393 SmallBitVector Used(VF, false);
2394 for (int Idx : SubMask) {
2395 if (Idx != PoisonMaskElem && Idx < VF)
2396 Used.set(Idx);
2397 }
2398 if (!Used.all())
2399 return false;
2400 }
2401 return true;
2402}
2403
2404/// Return true if this shuffle mask is a replication mask.
2406 // Not possible to express a shuffle mask for a scalable vector for this
2407 // case.
2409 return false;
2410 if (!isSingleSourceMask(ShuffleMask, VF))
2411 return false;
2412
2413 return isOneUseSingleSourceMask(ShuffleMask, VF);
2414}
2415
2416bool ShuffleVectorInst::isInterleave(unsigned Factor) {
2418 // shuffle_vector can only interleave fixed length vectors - for scalable
2419 // vectors, see the @llvm.vector.interleave2 intrinsic
2420 if (!OpTy)
2421 return false;
2422 unsigned OpNumElts = OpTy->getNumElements();
2423
2424 return isInterleaveMask(ShuffleMask, Factor, OpNumElts * 2);
2425}
2426
2428 ArrayRef<int> Mask, unsigned Factor, unsigned NumInputElts,
2429 SmallVectorImpl<unsigned> &StartIndexes) {
2430 unsigned NumElts = Mask.size();
2431 if (NumElts % Factor)
2432 return false;
2433
2434 unsigned LaneLen = NumElts / Factor;
2435 if (!isPowerOf2_32(LaneLen))
2436 return false;
2437
2438 StartIndexes.resize(Factor);
2439
2440 // Check whether each element matches the general interleaved rule.
2441 // Ignore undef elements, as long as the defined elements match the rule.
2442 // Outer loop processes all factors (x, y, z in the above example)
2443 unsigned I = 0, J;
2444 for (; I < Factor; I++) {
2445 unsigned SavedLaneValue;
2446 unsigned SavedNoUndefs = 0;
2447
2448 // Inner loop processes consecutive accesses (x, x+1... in the example)
2449 for (J = 0; J < LaneLen - 1; J++) {
2450 // Lane computes x's position in the Mask
2451 unsigned Lane = J * Factor + I;
2452 unsigned NextLane = Lane + Factor;
2453 int LaneValue = Mask[Lane];
2454 int NextLaneValue = Mask[NextLane];
2455
2456 // If both are defined, values must be sequential
2457 if (LaneValue >= 0 && NextLaneValue >= 0 &&
2458 LaneValue + 1 != NextLaneValue)
2459 break;
2460
2461 // If the next value is undef, save the current one as reference
2462 if (LaneValue >= 0 && NextLaneValue < 0) {
2463 SavedLaneValue = LaneValue;
2464 SavedNoUndefs = 1;
2465 }
2466
2467 // Undefs are allowed, but defined elements must still be consecutive:
2468 // i.e.: x,..., undef,..., x + 2,..., undef,..., undef,..., x + 5, ....
2469 // Verify this by storing the last non-undef followed by an undef
2470 // Check that following non-undef masks are incremented with the
2471 // corresponding distance.
2472 if (SavedNoUndefs > 0 && LaneValue < 0) {
2473 SavedNoUndefs++;
2474 if (NextLaneValue >= 0 &&
2475 SavedLaneValue + SavedNoUndefs != (unsigned)NextLaneValue)
2476 break;
2477 }
2478 }
2479
2480 if (J < LaneLen - 1)
2481 return false;
2482
2483 int StartMask = 0;
2484 if (Mask[I] >= 0) {
2485 // Check that the start of the I range (J=0) is greater than 0
2486 StartMask = Mask[I];
2487 } else if (Mask[(LaneLen - 1) * Factor + I] >= 0) {
2488 // StartMask defined by the last value in lane
2489 StartMask = Mask[(LaneLen - 1) * Factor + I] - J;
2490 } else if (SavedNoUndefs > 0) {
2491 // StartMask defined by some non-zero value in the j loop
2492 StartMask = SavedLaneValue - (LaneLen - 1 - SavedNoUndefs);
2493 }
2494 // else StartMask remains set to 0, i.e. all elements are undefs
2495
2496 if (StartMask < 0)
2497 return false;
2498 // We must stay within the vectors; This case can happen with undefs.
2499 if (StartMask + LaneLen > NumInputElts)
2500 return false;
2501
2502 StartIndexes[I] = StartMask;
2503 }
2504
2505 return true;
2506}
2507
2508/// Check if the mask is a DE-interleave mask of the given factor
2509/// \p Factor like:
2510/// <Index, Index+Factor, ..., Index+(NumElts-1)*Factor>
2512 unsigned Factor,
2513 unsigned &Index) {
2514 // Check all potential start indices from 0 to (Factor - 1).
2515 for (unsigned Idx = 0; Idx < Factor; Idx++) {
2516 unsigned I = 0;
2517
2518 // Check that elements are in ascending order by Factor. Ignore undef
2519 // elements.
2520 for (; I < Mask.size(); I++)
2521 if (Mask[I] >= 0 && static_cast<unsigned>(Mask[I]) != Idx + I * Factor)
2522 break;
2523
2524 if (I == Mask.size()) {
2525 Index = Idx;
2526 return true;
2527 }
2528 }
2529
2530 return false;
2531}
2532
2533/// Try to lower a vector shuffle as a bit rotation.
2534///
2535/// Look for a repeated rotation pattern in each sub group.
2536/// Returns an element-wise left bit rotation amount or -1 if failed.
2537static int matchShuffleAsBitRotate(ArrayRef<int> Mask, int NumSubElts) {
2538 int NumElts = Mask.size();
2539 assert((NumElts % NumSubElts) == 0 && "Illegal shuffle mask");
2540
2541 int RotateAmt = -1;
2542 for (int i = 0; i != NumElts; i += NumSubElts) {
2543 for (int j = 0; j != NumSubElts; ++j) {
2544 int M = Mask[i + j];
2545 if (M < 0)
2546 continue;
2547 if (M < i || M >= i + NumSubElts)
2548 return -1;
2549 int Offset = (NumSubElts - (M - (i + j))) % NumSubElts;
2550 if (0 <= RotateAmt && Offset != RotateAmt)
2551 return -1;
2552 RotateAmt = Offset;
2553 }
2554 }
2555 return RotateAmt;
2556}
2557
2559 ArrayRef<int> Mask, unsigned EltSizeInBits, unsigned MinSubElts,
2560 unsigned MaxSubElts, unsigned &NumSubElts, unsigned &RotateAmt) {
2561 for (NumSubElts = MinSubElts; NumSubElts <= MaxSubElts; NumSubElts *= 2) {
2562 int EltRotateAmt = matchShuffleAsBitRotate(Mask, NumSubElts);
2563 if (EltRotateAmt < 0)
2564 continue;
2565 RotateAmt = EltRotateAmt * EltSizeInBits;
2566 return true;
2567 }
2568
2569 return false;
2570}
2571
2572//===----------------------------------------------------------------------===//
2573// InsertValueInst Class
2574//===----------------------------------------------------------------------===//
2575
2576void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2577 const Twine &Name) {
2578 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2579
2580 // There's no fundamental reason why we require at least one index
2581 // (other than weirdness with &*IdxBegin being invalid; see
2582 // getelementptr's init routine for example). But there's no
2583 // present need to support it.
2584 assert(!Idxs.empty() && "InsertValueInst must have at least one index");
2585
2587 Val->getType() && "Inserted value must match indexed type!");
2588 Op<0>() = Agg;
2589 Op<1>() = Val;
2590
2591 Indices.append(Idxs.begin(), Idxs.end());
2592 setName(Name);
2593}
2594
2595InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
2596 : Instruction(IVI.getType(), InsertValue, AllocMarker),
2597 Indices(IVI.Indices) {
2598 Op<0>() = IVI.getOperand(0);
2599 Op<1>() = IVI.getOperand(1);
2601}
2602
2603//===----------------------------------------------------------------------===//
2604// ExtractValueInst Class
2605//===----------------------------------------------------------------------===//
2606
2607void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
2608 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2609
2610 // There's no fundamental reason why we require at least one index.
2611 // But there's no present need to support it.
2612 assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
2613
2614 Indices.append(Idxs.begin(), Idxs.end());
2615 setName(Name);
2616}
2617
2618ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
2619 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0),
2620 (BasicBlock *)nullptr),
2621 Indices(EVI.Indices) {
2623}
2624
2625// getIndexedType - Returns the type of the element that would be extracted
2626// with an extractvalue instruction with the specified parameters.
2627//
2628// A null type is returned if the indices are invalid for the specified
2629// pointer type.
2630//
2632 ArrayRef<unsigned> Idxs) {
2633 for (unsigned Index : Idxs) {
2634 // We can't use CompositeType::indexValid(Index) here.
2635 // indexValid() always returns true for arrays because getelementptr allows
2636 // out-of-bounds indices. Since we don't allow those for extractvalue and
2637 // insertvalue we need to check array indexing manually.
2638 // Since the only other types we can index into are struct types it's just
2639 // as easy to check those manually as well.
2640 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
2641 if (Index >= AT->getNumElements())
2642 return nullptr;
2643 Agg = AT->getElementType();
2644 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
2645 if (Index >= ST->getNumElements())
2646 return nullptr;
2647 Agg = ST->getElementType(Index);
2648 } else {
2649 // Not a valid type to index into.
2650 return nullptr;
2651 }
2652 }
2653 return Agg;
2654}
2655
2656//===----------------------------------------------------------------------===//
2657// BitInsert Class
2658//===----------------------------------------------------------------------===//
2659BitInsertInst::BitInsertInst(Value *Base, Value *Val, Value *Offset,
2660 const Twine &Name, InsertPosition InsertBef)
2661 : Instruction(Base->getType(), BitInsert, AllocMarker, InsertBef) {
2662 assert(!areInvalidOperands(Base, Val, Offset) &&
2663 "Invalid bitinsert instruction operands!");
2664 Op<0>() = Base;
2665 Op<1>() = Val;
2666 Op<2>() = Offset;
2667 setName(Name);
2668}
2669
2671 Value *Offset) {
2672 Type *BaseTy = Base->getType();
2673 if (!BaseTy->isByteOrByteVectorTy())
2674 return "bitinsert base must be a byte type or a vector of byte type";
2675 Type *ValTy = Val->getType()->getScalarType();
2676 if (!(ValTy->isFloatingPointTy() || ValTy->isIntegerTy() ||
2677 ValTy->isPointerTy() || ValTy->isByteTy()))
2678 return "bitinsert value must be an integer, floating-point, pointer, or "
2679 "byte type, or a vector of those types";
2680 if (!Offset->getType()->isIntOrIntVectorTy(32))
2681 return "bitinsert offset must be i32 or a vector of i32";
2682 if (BaseTy->getWithNewType(ValTy) != Val->getType() ||
2683 BaseTy->getWithNewType(Offset->getType()->getScalarType()) !=
2684 Offset->getType())
2685 return "bitinsert operands must all be scalars or all be vectors with the "
2686 "same number of elements";
2687 return nullptr;
2688}
2689
2690//===----------------------------------------------------------------------===//
2691// BitExtract Class
2692//===----------------------------------------------------------------------===//
2693BitExtractInst::BitExtractInst(Type *Ty, Value *Src, Value *Offset,
2694 const Twine &Name, InsertPosition InsertBef)
2695 : Instruction(Ty, BitExtract, AllocMarker, InsertBef) {
2696 assert(!areInvalidOperands(Ty, Src, Offset) &&
2697 "Invalid bitextract instruction operands!");
2698 Op<0>() = Src;
2699 Op<1>() = Offset;
2700 setName(Name);
2701}
2702
2704 Value *Offset) {
2705 const Type *EltTy = Ty->getScalarType();
2706 if (!(EltTy->isFloatingPointTy() || EltTy->isIntegerTy() ||
2707 EltTy->isPointerTy() || EltTy->isByteTy()))
2708 return "bitextract result must be an integer, floating-point, pointer, or "
2709 "byte type, or a vector of those types";
2710 if (!Src->getType()->isByteOrByteVectorTy())
2711 return "bitextract source must be a byte type or a vector of byte type";
2712 if (!Offset->getType()->isIntOrIntVectorTy(32))
2713 return "bitextract offset must be i32 or a vector of i32";
2714 if (Ty->getWithNewType(Src->getType()->getScalarType()) != Src->getType() ||
2715 Ty->getWithNewType(Offset->getType()->getScalarType()) !=
2716 Offset->getType())
2717 return "bitextract operands must all be scalars or all be vectors with the "
2718 "same number of elements";
2719 return nullptr;
2720}
2721
2722//===----------------------------------------------------------------------===//
2723// UnaryOperator Class
2724//===----------------------------------------------------------------------===//
2725
2727 const Twine &Name, InsertPosition InsertBefore)
2728 : UnaryInstruction(Ty, iType, S, InsertBefore) {
2729 Op<0>() = S;
2730 setName(Name);
2731 AssertOK();
2732}
2733
2735 InsertPosition InsertBefore) {
2736 switch (Op) {
2737 case UnaryOps::FNeg:
2738 return new FPUnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2739 default:
2740 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2741 }
2742}
2743
2744void UnaryOperator::AssertOK() {
2745 Value *LHS = getOperand(0);
2746 (void)LHS; // Silence warnings.
2747#ifndef NDEBUG
2748 switch (getOpcode()) {
2749 case FNeg:
2750 assert(getType() == LHS->getType() &&
2751 "Unary operation should return same type as operand!");
2752 assert(getType()->isFPOrFPVectorTy() &&
2753 "Tried to create a floating-point operation on a "
2754 "non-floating-point type!");
2755 break;
2756 default: llvm_unreachable("Invalid opcode provided");
2757 }
2758#endif
2759}
2760
2761//===----------------------------------------------------------------------===//
2762// BinaryOperator Class
2763//===----------------------------------------------------------------------===//
2764
2766 const Twine &Name, InsertPosition InsertBefore)
2767 : Instruction(Ty, iType, AllocMarker, InsertBefore) {
2768 Op<0>() = S1;
2769 Op<1>() = S2;
2770 setName(Name);
2771 AssertOK();
2772}
2773
2774void BinaryOperator::AssertOK() {
2775 Value *LHS = getOperand(0), *RHS = getOperand(1);
2776 (void)LHS; (void)RHS; // Silence warnings.
2777 assert(LHS->getType() == RHS->getType() &&
2778 "Binary operator operand types must match!");
2779#ifndef NDEBUG
2780 switch (getOpcode()) {
2781 case Add: case Sub:
2782 case Mul:
2783 assert(getType() == LHS->getType() &&
2784 "Arithmetic operation should return same type as operands!");
2785 assert(getType()->isIntOrIntVectorTy() &&
2786 "Tried to create an integer operation on a non-integer type!");
2787 break;
2788 case FAdd: case FSub:
2789 case FMul:
2790 assert(getType() == LHS->getType() &&
2791 "Arithmetic operation should return same type as operands!");
2792 assert(getType()->isFPOrFPVectorTy() &&
2793 "Tried to create a floating-point operation on a "
2794 "non-floating-point type!");
2795 break;
2796 case UDiv:
2797 case SDiv:
2798 assert(getType() == LHS->getType() &&
2799 "Arithmetic operation should return same type as operands!");
2800 assert(getType()->isIntOrIntVectorTy() &&
2801 "Incorrect operand type (not integer) for S/UDIV");
2802 break;
2803 case FDiv:
2804 assert(getType() == LHS->getType() &&
2805 "Arithmetic operation should return same type as operands!");
2806 assert(getType()->isFPOrFPVectorTy() &&
2807 "Incorrect operand type (not floating point) for FDIV");
2808 break;
2809 case URem:
2810 case SRem:
2811 assert(getType() == LHS->getType() &&
2812 "Arithmetic operation should return same type as operands!");
2813 assert(getType()->isIntOrIntVectorTy() &&
2814 "Incorrect operand type (not integer) for S/UREM");
2815 break;
2816 case FRem:
2817 assert(getType() == LHS->getType() &&
2818 "Arithmetic operation should return same type as operands!");
2819 assert(getType()->isFPOrFPVectorTy() &&
2820 "Incorrect operand type (not floating point) for FREM");
2821 break;
2822 case Shl:
2823 case LShr:
2824 case AShr:
2825 assert(getType() == LHS->getType() &&
2826 "Shift operation should return same type as operands!");
2827 assert(getType()->isIntOrIntVectorTy() &&
2828 "Tried to create a shift operation on a non-integral type!");
2829 break;
2830 case And: case Or:
2831 case Xor:
2832 assert(getType() == LHS->getType() &&
2833 "Logical operation should return same type as operands!");
2834 assert(getType()->isIntOrIntVectorTy() &&
2835 "Tried to create a logical operation on a non-integral type!");
2836 break;
2837 default: llvm_unreachable("Invalid opcode provided");
2838 }
2839#endif
2840}
2841
2843 const Twine &Name,
2844 InsertPosition InsertBefore) {
2845 assert(S1->getType() == S2->getType() &&
2846 "Cannot create binary operator with two operands of differing type!");
2847 switch (Op) {
2848 case BinaryOps::FAdd:
2849 case BinaryOps::FSub:
2850 case BinaryOps::FMul:
2851 case BinaryOps::FDiv:
2852 case BinaryOps::FRem:
2853 return new FPBinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2854 default:
2855 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2856 }
2857}
2858
2860 InsertPosition InsertBefore) {
2861 Value *Zero = ConstantInt::get(Op->getType(), 0);
2862 return new BinaryOperator(Instruction::Sub, Zero, Op, Op->getType(), Name,
2863 InsertBefore);
2864}
2865
2867 InsertPosition InsertBefore) {
2868 Value *Zero = ConstantInt::get(Op->getType(), 0);
2869 return BinaryOperator::CreateNSWSub(Zero, Op, Name, InsertBefore);
2870}
2871
2873 InsertPosition InsertBefore) {
2874 Constant *C = Constant::getAllOnesValue(Op->getType());
2875 return new BinaryOperator(Instruction::Xor, Op, C,
2876 Op->getType(), Name, InsertBefore);
2877}
2878
2879// Exchange the two operands to this instruction. This instruction is safe to
2880// use on any binary instruction and does not modify the semantics of the
2881// instruction.
2883 if (!isCommutative())
2884 return true; // Can't commute operands
2885 Op<0>().swap(Op<1>());
2886 return false;
2887}
2888
2889//===----------------------------------------------------------------------===//
2890// FPMathOperator Class
2891//===----------------------------------------------------------------------===//
2892
2894 const MDNode *MD =
2895 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2896 if (!MD)
2897 return 0.0;
2899 return Accuracy->getValueAPF().convertToFloat();
2900}
2901
2902//===----------------------------------------------------------------------===//
2903// CastInst Class
2904//===----------------------------------------------------------------------===//
2905
2906// Just determine if this cast only deals with integral->integral conversion.
2908 switch (getOpcode()) {
2909 default: return false;
2910 case Instruction::ZExt:
2911 case Instruction::SExt:
2912 case Instruction::Trunc:
2913 return true;
2914 case Instruction::BitCast:
2915 return getOperand(0)->getType()->isIntegerTy() &&
2916 getType()->isIntegerTy();
2917 }
2918}
2919
2920/// This function determines if the CastInst does not require any bits to be
2921/// changed in order to effect the cast. Essentially, it identifies cases where
2922/// no code gen is necessary for the cast, hence the name no-op cast. For
2923/// example, the following are all no-op casts:
2924/// # bitcast i32* %x to i8*
2925/// # bitcast <2 x i32> %x to <4 x i16>
2926/// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2927/// Determine if the described cast is a no-op.
2929 Type *SrcTy,
2930 Type *DestTy,
2931 const DataLayout &DL) {
2932 assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition");
2933 switch (Opcode) {
2934 default: llvm_unreachable("Invalid CastOp");
2935 case Instruction::Trunc:
2936 case Instruction::ZExt:
2937 case Instruction::SExt:
2938 case Instruction::FPTrunc:
2939 case Instruction::FPExt:
2940 case Instruction::UIToFP:
2941 case Instruction::SIToFP:
2942 case Instruction::FPToUI:
2943 case Instruction::FPToSI:
2944 case Instruction::AddrSpaceCast:
2945 // TODO: Target informations may give a more accurate answer here.
2946 return false;
2947 case Instruction::BitCast:
2948 return true; // BitCast never modifies bits.
2949 case Instruction::PtrToAddr:
2950 case Instruction::PtrToInt:
2951 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
2952 DestTy->getScalarSizeInBits();
2953 case Instruction::IntToPtr:
2954 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
2955 SrcTy->getScalarSizeInBits();
2956 }
2957}
2958
2960 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
2961}
2962
2963/// This function determines if a pair of casts can be eliminated and what
2964/// opcode should be used in the elimination. This assumes that there are two
2965/// instructions like this:
2966/// * %F = firstOpcode SrcTy %x to MidTy
2967/// * %S = secondOpcode MidTy %F to DstTy
2968/// The function returns a resultOpcode so these two casts can be replaced with:
2969/// * %Replacement = resultOpcode %SrcTy %x to DstTy
2970/// If no such cast is permitted, the function returns 0.
2972 Instruction::CastOps secondOp,
2973 Type *SrcTy, Type *MidTy, Type *DstTy,
2974 const DataLayout *DL) {
2975 // Define the 144 possibilities for these two cast instructions. The values
2976 // in this matrix determine what to do in a given situation and select the
2977 // case in the switch below. The rows correspond to firstOp, the columns
2978 // correspond to secondOp. In looking at the table below, keep in mind
2979 // the following cast properties:
2980 //
2981 // Size Compare Source Destination
2982 // Operator Src ? Size Type Sign Type Sign
2983 // -------- ------------ ------------------- ---------------------
2984 // TRUNC > Integer Any Integral Any
2985 // ZEXT < Integral Unsigned Integer Any
2986 // SEXT < Integral Signed Integer Any
2987 // FPTOUI n/a FloatPt n/a Integral Unsigned
2988 // FPTOSI n/a FloatPt n/a Integral Signed
2989 // UITOFP n/a Integral Unsigned FloatPt n/a
2990 // SITOFP n/a Integral Signed FloatPt n/a
2991 // FPTRUNC > FloatPt n/a FloatPt n/a
2992 // FPEXT < FloatPt n/a FloatPt n/a
2993 // PTRTOINT n/a Pointer n/a Integral Unsigned
2994 // PTRTOADDR n/a Pointer n/a Integral Unsigned
2995 // INTTOPTR n/a Integral Unsigned Pointer n/a
2996 // BITCAST = FirstClass n/a FirstClass n/a
2997 // ADDRSPCST n/a Pointer n/a Pointer n/a
2998 //
2999 // NOTE: some transforms are safe, but we consider them to be non-profitable.
3000 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
3001 // into "fptoui double to i64", but this loses information about the range
3002 // of the produced value (we no longer know the top-part is all zeros).
3003 // Further this conversion is often much more expensive for typical hardware,
3004 // and causes issues when building libgcc. We disallow fptosi+sext for the
3005 // same reason.
3006 const unsigned numCastOps =
3007 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
3008 // clang-format off
3009 static const uint8_t CastResults[numCastOps][numCastOps] = {
3010 // T F F U S F F P P I B A -+
3011 // R Z S P P I I T P 2 2 N T S |
3012 // U E E 2 2 2 2 R E I A T C C +- secondOp
3013 // N X X U S F F N X N D 2 V V |
3014 // C T T I I P P C T T R P T T -+
3015 { 1, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // Trunc -+
3016 { 8, 1, 9,99,99, 2,17,99,99,99,99, 2, 3, 0}, // ZExt |
3017 { 8, 0, 1,99,99, 0, 2,99,99,99,99, 0, 3, 0}, // SExt |
3018 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // FPToUI |
3019 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // FPToSI |
3020 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // UIToFP +- firstOp
3021 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // SIToFP |
3022 { 99,99,99, 0, 0,99,99, 0, 0,99,99,99, 4, 0}, // FPTrunc |
3023 { 99,99,99, 2, 2,99,99, 8, 2,99,99,99, 4, 0}, // FPExt |
3024 { 1, 0, 0,99,99, 0, 0,99,99,99,99, 7, 3, 0}, // PtrToInt |
3025 { 0, 0, 0,99,99, 0, 0,99,99,99,99, 0, 3, 0}, // PtrToAddr |
3026 { 99,99,99,99,99,99,99,99,99,11,11,99,15, 0}, // IntToPtr |
3027 { 5, 5, 5, 0, 0, 5, 5, 0, 0,16,16, 5,18,14}, // BitCast |
3028 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
3029 };
3030 // clang-format on
3031
3032 // TODO: This logic could be encoded into the table above and handled in the
3033 // switch below.
3034 // If either of the casts are a bitcast from scalar to vector, disallow the
3035 // merging. However, any pair of bitcasts are allowed.
3036 bool IsFirstBitcast = (firstOp == Instruction::BitCast);
3037 bool IsSecondBitcast = (secondOp == Instruction::BitCast);
3038 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
3039
3040 // Check if any of the casts convert scalars <-> vectors.
3041 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
3042 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
3043 if (!AreBothBitcasts)
3044 return 0;
3045
3046 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
3047 [secondOp-Instruction::CastOpsBegin];
3048 switch (ElimCase) {
3049 case 0:
3050 // Categorically disallowed.
3051 return 0;
3052 case 1:
3053 // Allowed, use first cast's opcode.
3054 return firstOp;
3055 case 2:
3056 // Allowed, use second cast's opcode.
3057 return secondOp;
3058 case 3:
3059 // No-op cast in second op implies firstOp as long as the DestTy
3060 // is integer and we are not converting between a vector and a
3061 // non-vector type.
3062 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
3063 return firstOp;
3064 return 0;
3065 case 4:
3066 // No-op cast in second op implies firstOp as long as the DestTy
3067 // matches MidTy.
3068 if (DstTy == MidTy)
3069 return firstOp;
3070 return 0;
3071 case 5:
3072 // No-op cast in first op implies secondOp as long as the SrcTy
3073 // is an integer.
3074 if (SrcTy->isIntegerTy())
3075 return secondOp;
3076 return 0;
3077 case 7: {
3078 // Skip the inttoptr/ptrtoint optimization if disabled.
3079 if (!getIROptions(SrcTy->getContext()).i2p_p2i_opt)
3080 return 0;
3081
3082 // Cannot simplify if address spaces are different!
3083 if (SrcTy != DstTy)
3084 return 0;
3085
3086 // Cannot simplify if the intermediate integer size is smaller than the
3087 // pointer size.
3088 unsigned MidSize = MidTy->getScalarSizeInBits();
3089 if (!DL || MidSize < DL->getPointerTypeSizeInBits(SrcTy))
3090 return 0;
3091
3092 return Instruction::BitCast;
3093 }
3094 case 8: {
3095 // ext, trunc -> bitcast, if the SrcTy and DstTy are the same
3096 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
3097 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
3098 unsigned SrcSize = SrcTy->getScalarSizeInBits();
3099 unsigned DstSize = DstTy->getScalarSizeInBits();
3100 if (SrcTy == DstTy)
3101 return Instruction::BitCast;
3102 if (SrcSize < DstSize)
3103 return firstOp;
3104 if (SrcSize > DstSize)
3105 return secondOp;
3106 return 0;
3107 }
3108 case 9:
3109 // zext, sext -> zext, because sext can't sign extend after zext
3110 return Instruction::ZExt;
3111 case 11: {
3112 // inttoptr, ptrtoint/ptrtoaddr -> integer cast
3113 if (!DL)
3114 return 0;
3115 unsigned MidSize = secondOp == Instruction::PtrToAddr
3116 ? DL->getAddressSizeInBits(MidTy)
3117 : DL->getPointerTypeSizeInBits(MidTy);
3118 unsigned SrcSize = SrcTy->getScalarSizeInBits();
3119 unsigned DstSize = DstTy->getScalarSizeInBits();
3120 // If the middle size is smaller than both source and destination,
3121 // an additional masking operation would be required.
3122 if (MidSize < SrcSize && MidSize < DstSize)
3123 return 0;
3124 if (DstSize < SrcSize)
3125 return Instruction::Trunc;
3126 if (DstSize > SrcSize)
3127 return Instruction::ZExt;
3128 return Instruction::BitCast;
3129 }
3130 case 12:
3131 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
3132 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
3133 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
3134 return Instruction::AddrSpaceCast;
3135 return Instruction::BitCast;
3136 case 13:
3137 // FIXME: this state can be merged with (1), but the following assert
3138 // is useful to check the correcteness of the sequence due to semantic
3139 // change of bitcast.
3140 // addrspacecast can only fold through a bitcast if the result remains a
3141 // pointer. A pointer-to-byte bitcast must stay as a separate bitcast.
3142 if (!DstTy->isPtrOrPtrVectorTy())
3143 return 0;
3144 assert(
3145 SrcTy->isPtrOrPtrVectorTy() &&
3146 MidTy->isPtrOrPtrVectorTy() &&
3147 DstTy->isPtrOrPtrVectorTy() &&
3148 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
3149 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
3150 "Illegal addrspacecast, bitcast sequence!");
3151 // Allowed, use first cast's opcode
3152 return firstOp;
3153 case 14:
3154 // bitcast, addrspacecast -> addrspacecast
3155 // addrspacecast can only fold through a bitcast if the source was already
3156 // a pointer. A byte-to-pointer bitcast must stay as a separate bitcast.
3157 if (!SrcTy->isPtrOrPtrVectorTy())
3158 return 0;
3159 return Instruction::AddrSpaceCast;
3160 case 15:
3161 // FIXME: this state can be merged with (1), but the following assert
3162 // is useful to check the correcteness of the sequence due to semantic
3163 // change of bitcast.
3164 // inttoptr can only fold through a bitcast if the result remains a
3165 // pointer. A pointer-to-byte bitcast must stay as a separate bitcast.
3166 if (!DstTy->isPtrOrPtrVectorTy())
3167 return 0;
3168 assert(
3169 SrcTy->isIntOrIntVectorTy() &&
3170 MidTy->isPtrOrPtrVectorTy() &&
3171 DstTy->isPtrOrPtrVectorTy() &&
3172 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
3173 "Illegal inttoptr, bitcast sequence!");
3174 // Allowed, use first cast's opcode
3175 return firstOp;
3176 case 16:
3177 // FIXME: this state can be merged with (2), but the following assert
3178 // is useful to check the correcteness of the sequence due to semantic
3179 // change of bitcast.
3180 // bitcast, ptrtoaddr -> bitcast, if SrcTy is a byte and the address is
3181 // the whole pointer
3182 // ptrtoint can only fold through a bitcast if the source was already a
3183 // pointer, as ptrtoint exposes the provenance.
3184 if (!SrcTy->isPtrOrPtrVectorTy()) {
3185 // ptrtoaddr yields the address width, so the sizes only match if the
3186 // address is the whole pointer.
3187 if (secondOp == Instruction::PtrToAddr &&
3188 SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3189 return Instruction::BitCast;
3190 return 0;
3191 }
3192 assert(
3193 SrcTy->isPtrOrPtrVectorTy() &&
3194 MidTy->isPtrOrPtrVectorTy() &&
3195 DstTy->isIntOrIntVectorTy() &&
3196 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
3197 "Illegal bitcast, ptrtoint sequence!");
3198 // Allowed, use second cast's opcode
3199 return secondOp;
3200 case 17:
3201 // (sitofp (zext x)) -> (uitofp x)
3202 return Instruction::UIToFP;
3203 case 18:
3204 // bitcast, bitcast -> bitcast, if neither SrcTy nor DstTy is a pointer,
3205 // both are pointers in the same addrspace,
3206 // or one is a pointer and the other a byte
3207 // bitcast, bitcast -> ptrtoint, if a pointer goes through a byte to an
3208 // integer of the pointer width
3209 // bitcast, bitcast -> inttoptr, if an integer of the pointer width goes
3210 // through a byte to a pointer
3211 // A pair of bitcasts through a byte must stay separate otherwise.
3212 if (!SrcTy->isPtrOrPtrVectorTy() && !DstTy->isPtrOrPtrVectorTy())
3213 return Instruction::BitCast;
3214 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
3215 SrcTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace())
3216 return Instruction::BitCast;
3217 if (SrcTy->isByteOrByteVectorTy() || DstTy->isByteOrByteVectorTy())
3218 return Instruction::BitCast;
3219 if (SrcTy->isVectorTy() == DstTy->isVectorTy() && DL) {
3220 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy() &&
3221 DL->getPointerTypeSizeInBits(SrcTy) == DstTy->getScalarSizeInBits())
3222 return Instruction::PtrToInt;
3223 if (SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
3224 SrcTy->getScalarSizeInBits() == DL->getPointerTypeSizeInBits(DstTy))
3225 return Instruction::IntToPtr;
3226 }
3227 return 0;
3228 case 99:
3229 // Cast combination can't happen (error in input). This is for all cases
3230 // where the MidTy is not the same for the two cast instructions.
3231 llvm_unreachable("Invalid Cast Combination");
3232 default:
3233 llvm_unreachable("Error in CastResults table!!!");
3234 }
3235}
3236
3238 const Twine &Name, InsertPosition InsertBefore) {
3239 assert(castIsValid(op, S, Ty) && "Invalid cast!");
3240 // Construct and return the appropriate CastInst subclass
3241 switch (op) {
3242 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
3243 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
3244 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
3245 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
3246 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
3247 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
3248 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
3249 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
3250 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
3251 case PtrToAddr: return new PtrToAddrInst (S, Ty, Name, InsertBefore);
3252 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
3253 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
3254 case BitCast:
3255 return new BitCastInst(S, Ty, Name, InsertBefore);
3256 case AddrSpaceCast:
3257 return new AddrSpaceCastInst(S, Ty, Name, InsertBefore);
3258 default:
3259 llvm_unreachable("Invalid opcode provided");
3260 }
3261}
3262
3264 InsertPosition InsertBefore) {
3265 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3266 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3267 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
3268}
3269
3271 InsertPosition InsertBefore) {
3272 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3273 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3274 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
3275}
3276
3278 InsertPosition InsertBefore) {
3279 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3280 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3281 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
3282}
3283
3284/// Create a BitCast or a PtrToInt cast instruction
3286 InsertPosition InsertBefore) {
3287 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3288 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
3289 "Invalid cast");
3290 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
3291 assert((!Ty->isVectorTy() ||
3292 cast<VectorType>(Ty)->getElementCount() ==
3293 cast<VectorType>(S->getType())->getElementCount()) &&
3294 "Invalid cast");
3295
3296 if (Ty->isIntOrIntVectorTy())
3297 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3298
3299 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
3300}
3301
3303 Value *S, Type *Ty, const Twine &Name, InsertPosition InsertBefore) {
3304 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3305 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
3306
3307 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
3308 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
3309
3310 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3311}
3312
3314 const Twine &Name,
3315 InsertPosition InsertBefore) {
3316 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
3317 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3318 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
3319 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
3320
3321 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3322}
3323
3325 const Twine &Name,
3326 InsertPosition InsertBefore) {
3327 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
3328 "Invalid integer cast");
3329 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3330 unsigned DstBits = Ty->getScalarSizeInBits();
3331 Instruction::CastOps opcode =
3332 (SrcBits == DstBits ? Instruction::BitCast :
3333 (SrcBits > DstBits ? Instruction::Trunc :
3334 (isSigned ? Instruction::SExt : Instruction::ZExt)));
3335 return Create(opcode, C, Ty, Name, InsertBefore);
3336}
3337
3339 InsertPosition InsertBefore) {
3340 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
3341 "Invalid cast");
3342 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3343 unsigned DstBits = Ty->getScalarSizeInBits();
3344 assert((C->getType() == Ty || SrcBits != DstBits) && "Invalid cast");
3345 Instruction::CastOps opcode =
3346 (SrcBits == DstBits ? Instruction::BitCast :
3347 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
3348 return Create(opcode, C, Ty, Name, InsertBefore);
3349}
3350
3351bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
3352 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
3353 return false;
3354
3355 if (SrcTy == DestTy)
3356 return true;
3357
3358 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3359 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
3360 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3361 // An element by element cast. Valid if casting the elements is valid.
3362 SrcTy = SrcVecTy->getElementType();
3363 DestTy = DestVecTy->getElementType();
3364 }
3365 }
3366 }
3367
3368 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
3369 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
3370 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
3371 }
3372 }
3373
3374 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3375 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3376
3377 // Could still have vectors of pointers if the number of elements doesn't
3378 // match
3379 if (SrcBits.getKnownMinValue() == 0 || DestBits.getKnownMinValue() == 0)
3380 return false;
3381
3382 if (SrcBits != DestBits)
3383 return false;
3384
3385 return true;
3386}
3387
3389 const DataLayout &DL) {
3390 // ptrtoint and inttoptr are not allowed on non-integral pointers
3391 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
3392 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
3393 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3394 !DL.isNonIntegralPointerType(PtrTy));
3395 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
3396 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
3397 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3398 !DL.isNonIntegralPointerType(PtrTy));
3399
3400 return isBitCastable(SrcTy, DestTy);
3401}
3402
3403// Provide a way to get a "cast" where the cast opcode is inferred from the
3404// types and size of the operand. This, basically, is a parallel of the
3405// logic in the castIsValid function below. This axiom should hold:
3406// castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3407// should not assert in castIsValid. In other words, this produces a "correct"
3408// casting opcode for the arguments passed to it.
3411 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
3412 Type *SrcTy = Src->getType();
3413
3414 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
3415 "Only first class types are castable!");
3416
3417 if (SrcTy == DestTy)
3418 return BitCast;
3419
3420 // FIXME: Check address space sizes here
3421 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3422 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3423 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3424 // An element by element cast. Find the appropriate opcode based on the
3425 // element types.
3426 SrcTy = SrcVecTy->getElementType();
3427 DestTy = DestVecTy->getElementType();
3428 }
3429
3430 // Get the bit sizes, we'll need these
3431 // FIXME: This doesn't work for scalable vector types with different element
3432 // counts that don't call getElementType above.
3433 unsigned SrcBits =
3434 SrcTy->getPrimitiveSizeInBits().getFixedValue(); // 0 for ptr
3435 unsigned DestBits =
3436 DestTy->getPrimitiveSizeInBits().getFixedValue(); // 0 for ptr
3437
3438 // Run through the possibilities ...
3439 if (DestTy->isByteTy()) { // Casting to byte
3440 if (SrcTy->isIntegerTy()) { // Casting from integral
3441 assert(DestBits == SrcBits && "Illegal cast from integer to byte type");
3442 return BitCast;
3443 } else if (SrcTy->isPointerTy()) { // Casting from pointer
3444 assert(DestBits == SrcBits && "Illegal cast from pointer to byte type");
3445 return BitCast;
3446 }
3447 llvm_unreachable("Illegal cast to byte type");
3448 } else if (DestTy->isIntegerTy()) { // Casting to integral
3449 if (SrcTy->isIntegerTy()) { // Casting from integral
3450 if (DestBits < SrcBits)
3451 return Trunc; // int -> smaller int
3452 else if (DestBits > SrcBits) { // its an extension
3453 if (SrcIsSigned)
3454 return SExt; // signed -> SEXT
3455 else
3456 return ZExt; // unsigned -> ZEXT
3457 } else {
3458 return BitCast; // Same size, No-op cast
3459 }
3460 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3461 if (DestIsSigned)
3462 return FPToSI; // FP -> sint
3463 else
3464 return FPToUI; // FP -> uint
3465 } else if (SrcTy->isVectorTy()) {
3466 assert(DestBits == SrcBits &&
3467 "Casting vector to integer of different width");
3468 return BitCast; // Same size, no-op cast
3469 } else {
3470 assert(SrcTy->isPointerTy() &&
3471 "Casting from a value that is not first-class type");
3472 return PtrToInt; // ptr -> int
3473 }
3474 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3475 if (SrcTy->isIntegerTy()) { // Casting from integral
3476 if (SrcIsSigned)
3477 return SIToFP; // sint -> FP
3478 else
3479 return UIToFP; // uint -> FP
3480 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3481 if (DestBits < SrcBits) {
3482 return FPTrunc; // FP -> smaller FP
3483 } else if (DestBits > SrcBits) {
3484 return FPExt; // FP -> larger FP
3485 } else {
3486 return BitCast; // same size, no-op cast
3487 }
3488 } else if (SrcTy->isVectorTy()) {
3489 assert(DestBits == SrcBits &&
3490 "Casting vector to floating point of different width");
3491 return BitCast; // same size, no-op cast
3492 }
3493 llvm_unreachable("Casting pointer or non-first class to float");
3494 } else if (DestTy->isVectorTy()) {
3495 assert(DestBits == SrcBits &&
3496 "Illegal cast to vector (wrong type or size)");
3497 return BitCast;
3498 } else if (DestTy->isPointerTy()) {
3499 if (SrcTy->isPointerTy()) {
3500 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3501 return AddrSpaceCast;
3502 return BitCast; // ptr -> ptr
3503 } else if (SrcTy->isIntegerTy()) {
3504 return IntToPtr; // int -> ptr
3505 }
3506 llvm_unreachable("Casting pointer to other than pointer or int");
3507 }
3508 llvm_unreachable("Casting to type that is not first-class");
3509}
3510
3511//===----------------------------------------------------------------------===//
3512// CastInst SubClass Constructors
3513//===----------------------------------------------------------------------===//
3514
3515/// Check that the construction parameters for a CastInst are correct. This
3516/// could be broken out into the separate constructors but it is useful to have
3517/// it in one place and to eliminate the redundant code for getting the sizes
3518/// of the types involved.
3519bool
3521 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3522 SrcTy->isAggregateType() || DstTy->isAggregateType())
3523 return false;
3524
3525 // Get the size of the types in bits, and whether we are dealing
3526 // with vector types, we'll need this later.
3527 bool SrcIsVec = isa<VectorType>(SrcTy);
3528 bool DstIsVec = isa<VectorType>(DstTy);
3529 unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits();
3530 unsigned DstScalarBitSize = DstTy->getScalarSizeInBits();
3531
3532 // If these are vector types, get the lengths of the vectors (using zero for
3533 // scalar types means that checking that vector lengths match also checks that
3534 // scalars are not being converted to vectors or vectors to scalars).
3535 ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount()
3537 ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount()
3539
3540 // Switch on the opcode provided
3541 switch (op) {
3542 default: return false; // This is an input error
3543 case Instruction::Trunc:
3544 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3545 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3546 case Instruction::ZExt:
3547 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3548 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3549 case Instruction::SExt:
3550 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3551 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3552 case Instruction::FPTrunc:
3553 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3554 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3555 case Instruction::FPExt:
3556 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3557 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3558 case Instruction::UIToFP:
3559 case Instruction::SIToFP:
3560 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3561 SrcEC == DstEC;
3562 case Instruction::FPToUI:
3563 case Instruction::FPToSI:
3564 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3565 SrcEC == DstEC;
3566 case Instruction::PtrToAddr:
3567 case Instruction::PtrToInt:
3568 if (SrcEC != DstEC)
3569 return false;
3570 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
3571 case Instruction::IntToPtr:
3572 if (SrcEC != DstEC)
3573 return false;
3574 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
3575 case Instruction::BitCast: {
3576 Type *SrcScalarTy = SrcTy->getScalarType();
3577 if (SrcScalarTy->isTargetExtTy() || !SrcScalarTy->isSingleValueType())
3578 return false;
3579 Type *DstScalarTy = DstTy->getScalarType();
3580 if (DstScalarTy->isTargetExtTy() || !DstScalarTy->isSingleValueType())
3581 return false;
3582
3583 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcScalarTy);
3584 PointerType *DstPtrTy = dyn_cast<PointerType>(DstScalarTy);
3585
3586 // BitCast implies a no-op cast of type only. No bits change.
3587 // However, you can't cast pointers to anything but pointers/bytes.
3588 if ((SrcPtrTy && DstTy->isByteOrByteVectorTy()) ||
3589 (SrcTy->isByteOrByteVectorTy() && DstPtrTy))
3590 return true;
3591 if (!SrcPtrTy != !DstPtrTy)
3592 return false;
3593
3594 // For non-pointer cases, the cast is okay if the source and destination bit
3595 // widths are identical.
3596 if (!SrcPtrTy)
3597 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3598
3599 // If both are pointers then the address spaces must match.
3600 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3601 return false;
3602
3603 // A vector of pointers must have the same number of elements.
3604 if (SrcIsVec && DstIsVec)
3605 return SrcEC == DstEC;
3606 if (SrcIsVec)
3607 return SrcEC == ElementCount::getFixed(1);
3608 if (DstIsVec)
3609 return DstEC == ElementCount::getFixed(1);
3610
3611 return true;
3612 }
3613 case Instruction::AddrSpaceCast: {
3614 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3615 if (!SrcPtrTy)
3616 return false;
3617
3618 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3619 if (!DstPtrTy)
3620 return false;
3621
3622 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3623 return false;
3624
3625 return SrcEC == DstEC;
3626 }
3627 }
3628}
3629
3631 InsertPosition InsertBefore)
3632 : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3633 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3634}
3635
3636ZExtInst::ZExtInst(Value *S, Type *Ty, const Twine &Name,
3637 InsertPosition InsertBefore)
3638 : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3639 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3640}
3641
3642SExtInst::SExtInst(Value *S, Type *Ty, const Twine &Name,
3643 InsertPosition InsertBefore)
3644 : CastInst(Ty, SExt, S, Name, InsertBefore) {
3645 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3646}
3647
3649 InsertPosition InsertBefore)
3650 : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3651 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3652}
3653
3655 InsertPosition InsertBefore)
3656 : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3657 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3658}
3659
3661 InsertPosition InsertBefore)
3662 : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3663 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3664}
3665
3667 InsertPosition InsertBefore)
3668 : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3669 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3670}
3671
3673 InsertPosition InsertBefore)
3674 : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3675 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3676}
3677
3679 InsertPosition InsertBefore)
3680 : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3681 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3682}
3683
3685 InsertPosition InsertBefore)
3686 : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3687 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3688}
3689
3691 InsertPosition InsertBefore)
3692 : CastInst(Ty, PtrToAddr, S, Name, InsertBefore) {
3693 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToAddr");
3694}
3695
3697 InsertPosition InsertBefore)
3698 : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3699 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3700}
3701
3703 InsertPosition InsertBefore)
3704 : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3705 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3706}
3707
3709 InsertPosition InsertBefore)
3710 : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3711 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3712}
3713
3714//===----------------------------------------------------------------------===//
3715// CmpInst Classes
3716//===----------------------------------------------------------------------===//
3717
3719 Value *RHS, const Twine &Name, InsertPosition InsertBefore)
3720 : Instruction(ty, op, AllocMarker, InsertBefore) {
3721 Op<0>() = LHS;
3722 Op<1>() = RHS;
3723 setPredicate(predicate);
3724 setName(Name);
3725}
3726
3728 const Twine &Name, InsertPosition InsertBefore) {
3729 if (Op == Instruction::ICmp) {
3730 if (InsertBefore.isValid())
3731 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3732 S1, S2, Name);
3733 else
3734 return new ICmpInst(CmpInst::Predicate(predicate),
3735 S1, S2, Name);
3736 }
3737
3738 if (InsertBefore.isValid())
3739 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3740 S1, S2, Name);
3741 else
3742 return new FCmpInst(CmpInst::Predicate(predicate),
3743 S1, S2, Name);
3744}
3745
3747 Value *S2,
3748 const Instruction *FlagsSource,
3749 const Twine &Name,
3750 InsertPosition InsertBefore) {
3751 CmpInst *Inst = Create(Op, Pred, S1, S2, Name, InsertBefore);
3752 Inst->copyIRFlags(FlagsSource);
3753 return Inst;
3754}
3755
3757 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3758 IC->swapOperands();
3759 else
3760 cast<FCmpInst>(this)->swapOperands();
3761}
3762
3764 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3765 return IC->isCommutative();
3766 return cast<FCmpInst>(this)->isCommutative();
3767}
3768
3771 return ICmpInst::isEquality(P);
3773 return FCmpInst::isEquality(P);
3774 llvm_unreachable("Unsupported predicate kind");
3775}
3776
3777// Returns true if either operand of CmpInst is a provably non-zero
3778// floating-point constant.
3779static bool hasNonZeroFPOperands(const CmpInst *Cmp) {
3780 auto *LHS = dyn_cast<Constant>(Cmp->getOperand(0));
3781 auto *RHS = dyn_cast<Constant>(Cmp->getOperand(1));
3782 if (auto *Const = LHS ? LHS : RHS) {
3783 using namespace llvm::PatternMatch;
3784 return match(Const, m_NonZeroNotDenormalFP());
3785 }
3786 return false;
3787}
3788
3789// Floating-point equality is not an equivalence when comparing +0.0 with
3790// -0.0, when comparing NaN with another value, or when flushing
3791// denormals-to-zero.
3792bool CmpInst::isEquivalence(bool Invert) const {
3793 switch (Invert ? getInversePredicate() : getPredicate()) {
3795 return true;
3797 if (!hasNoNaNs())
3798 return false;
3799 [[fallthrough]];
3801 return hasNonZeroFPOperands(this);
3802 default:
3803 return false;
3804 }
3805}
3806
3808 switch (pred) {
3809 default: llvm_unreachable("Unknown cmp predicate!");
3810 case ICMP_EQ: return ICMP_NE;
3811 case ICMP_NE: return ICMP_EQ;
3812 case ICMP_UGT: return ICMP_ULE;
3813 case ICMP_ULT: return ICMP_UGE;
3814 case ICMP_UGE: return ICMP_ULT;
3815 case ICMP_ULE: return ICMP_UGT;
3816 case ICMP_SGT: return ICMP_SLE;
3817 case ICMP_SLT: return ICMP_SGE;
3818 case ICMP_SGE: return ICMP_SLT;
3819 case ICMP_SLE: return ICMP_SGT;
3820
3821 case FCMP_OEQ: return FCMP_UNE;
3822 case FCMP_ONE: return FCMP_UEQ;
3823 case FCMP_OGT: return FCMP_ULE;
3824 case FCMP_OLT: return FCMP_UGE;
3825 case FCMP_OGE: return FCMP_ULT;
3826 case FCMP_OLE: return FCMP_UGT;
3827 case FCMP_UEQ: return FCMP_ONE;
3828 case FCMP_UNE: return FCMP_OEQ;
3829 case FCMP_UGT: return FCMP_OLE;
3830 case FCMP_ULT: return FCMP_OGE;
3831 case FCMP_UGE: return FCMP_OLT;
3832 case FCMP_ULE: return FCMP_OGT;
3833 case FCMP_ORD: return FCMP_UNO;
3834 case FCMP_UNO: return FCMP_ORD;
3835 case FCMP_TRUE: return FCMP_FALSE;
3836 case FCMP_FALSE: return FCMP_TRUE;
3837 }
3838}
3839
3841 switch (Pred) {
3842 default: return "unknown";
3843 case FCmpInst::FCMP_FALSE: return "false";
3844 case FCmpInst::FCMP_OEQ: return "oeq";
3845 case FCmpInst::FCMP_OGT: return "ogt";
3846 case FCmpInst::FCMP_OGE: return "oge";
3847 case FCmpInst::FCMP_OLT: return "olt";
3848 case FCmpInst::FCMP_OLE: return "ole";
3849 case FCmpInst::FCMP_ONE: return "one";
3850 case FCmpInst::FCMP_ORD: return "ord";
3851 case FCmpInst::FCMP_UNO: return "uno";
3852 case FCmpInst::FCMP_UEQ: return "ueq";
3853 case FCmpInst::FCMP_UGT: return "ugt";
3854 case FCmpInst::FCMP_UGE: return "uge";
3855 case FCmpInst::FCMP_ULT: return "ult";
3856 case FCmpInst::FCMP_ULE: return "ule";
3857 case FCmpInst::FCMP_UNE: return "une";
3858 case FCmpInst::FCMP_TRUE: return "true";
3859 case ICmpInst::ICMP_EQ: return "eq";
3860 case ICmpInst::ICMP_NE: return "ne";
3861 case ICmpInst::ICMP_SGT: return "sgt";
3862 case ICmpInst::ICMP_SGE: return "sge";
3863 case ICmpInst::ICMP_SLT: return "slt";
3864 case ICmpInst::ICMP_SLE: return "sle";
3865 case ICmpInst::ICMP_UGT: return "ugt";
3866 case ICmpInst::ICMP_UGE: return "uge";
3867 case ICmpInst::ICMP_ULT: return "ult";
3868 case ICmpInst::ICMP_ULE: return "ule";
3869 }
3870}
3871
3873 OS << CmpInst::getPredicateName(Pred);
3874 return OS;
3875}
3876
3878 switch (pred) {
3879 default: llvm_unreachable("Unknown icmp predicate!");
3880 case ICMP_EQ: case ICMP_NE:
3881 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3882 return pred;
3883 case ICMP_UGT: return ICMP_SGT;
3884 case ICMP_ULT: return ICMP_SLT;
3885 case ICMP_UGE: return ICMP_SGE;
3886 case ICMP_ULE: return ICMP_SLE;
3887 }
3888}
3889
3891 switch (pred) {
3892 default: llvm_unreachable("Unknown icmp predicate!");
3893 case ICMP_EQ: case ICMP_NE:
3894 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3895 return pred;
3896 case ICMP_SGT: return ICMP_UGT;
3897 case ICMP_SLT: return ICMP_ULT;
3898 case ICMP_SGE: return ICMP_UGE;
3899 case ICMP_SLE: return ICMP_ULE;
3900 }
3901}
3902
3904 switch (pred) {
3905 default: llvm_unreachable("Unknown cmp predicate!");
3906 case ICMP_EQ: case ICMP_NE:
3907 return pred;
3908 case ICMP_SGT: return ICMP_SLT;
3909 case ICMP_SLT: return ICMP_SGT;
3910 case ICMP_SGE: return ICMP_SLE;
3911 case ICMP_SLE: return ICMP_SGE;
3912 case ICMP_UGT: return ICMP_ULT;
3913 case ICMP_ULT: return ICMP_UGT;
3914 case ICMP_UGE: return ICMP_ULE;
3915 case ICMP_ULE: return ICMP_UGE;
3916
3917 case FCMP_FALSE: case FCMP_TRUE:
3918 case FCMP_OEQ: case FCMP_ONE:
3919 case FCMP_UEQ: case FCMP_UNE:
3920 case FCMP_ORD: case FCMP_UNO:
3921 return pred;
3922 case FCMP_OGT: return FCMP_OLT;
3923 case FCMP_OLT: return FCMP_OGT;
3924 case FCMP_OGE: return FCMP_OLE;
3925 case FCMP_OLE: return FCMP_OGE;
3926 case FCMP_UGT: return FCMP_ULT;
3927 case FCMP_ULT: return FCMP_UGT;
3928 case FCMP_UGE: return FCMP_ULE;
3929 case FCMP_ULE: return FCMP_UGE;
3930 }
3931}
3932
3934 switch (pred) {
3935 case ICMP_SGE:
3936 case ICMP_SLE:
3937 case ICMP_UGE:
3938 case ICMP_ULE:
3939 case FCMP_OGE:
3940 case FCMP_OLE:
3941 case FCMP_UGE:
3942 case FCMP_ULE:
3943 return true;
3944 default:
3945 return false;
3946 }
3947}
3948
3950 switch (pred) {
3951 case ICMP_SGT:
3952 case ICMP_SLT:
3953 case ICMP_UGT:
3954 case ICMP_ULT:
3955 case FCMP_OGT:
3956 case FCMP_OLT:
3957 case FCMP_UGT:
3958 case FCMP_ULT:
3959 return true;
3960 default:
3961 return false;
3962 }
3963}
3964
3966 switch (pred) {
3967 case ICMP_SGE:
3968 return ICMP_SGT;
3969 case ICMP_SLE:
3970 return ICMP_SLT;
3971 case ICMP_UGE:
3972 return ICMP_UGT;
3973 case ICMP_ULE:
3974 return ICMP_ULT;
3975 case FCMP_OGE:
3976 return FCMP_OGT;
3977 case FCMP_OLE:
3978 return FCMP_OLT;
3979 case FCMP_UGE:
3980 return FCMP_UGT;
3981 case FCMP_ULE:
3982 return FCMP_ULT;
3983 default:
3984 return pred;
3985 }
3986}
3987
3989 switch (pred) {
3990 case ICMP_SGT:
3991 return ICMP_SGE;
3992 case ICMP_SLT:
3993 return ICMP_SLE;
3994 case ICMP_UGT:
3995 return ICMP_UGE;
3996 case ICMP_ULT:
3997 return ICMP_ULE;
3998 case FCMP_OGT:
3999 return FCMP_OGE;
4000 case FCMP_OLT:
4001 return FCMP_OLE;
4002 case FCMP_UGT:
4003 return FCMP_UGE;
4004 case FCMP_ULT:
4005 return FCMP_ULE;
4006 default:
4007 return pred;
4008 }
4009}
4010
4012 assert(CmpInst::isRelational(pred) && "Call only with relational predicate!");
4013
4014 if (isStrictPredicate(pred))
4015 return getNonStrictPredicate(pred);
4016 if (isNonStrictPredicate(pred))
4017 return getStrictPredicate(pred);
4018
4019 llvm_unreachable("Unknown predicate!");
4020}
4021
4022bool ICmpInst::compare(const APInt &LHS, const APInt &RHS,
4023 ICmpInst::Predicate Pred) {
4024 assert(ICmpInst::isIntPredicate(Pred) && "Only for integer predicates!");
4025 switch (Pred) {
4027 return LHS.eq(RHS);
4029 return LHS.ne(RHS);
4031 return LHS.ugt(RHS);
4033 return LHS.uge(RHS);
4035 return LHS.ult(RHS);
4037 return LHS.ule(RHS);
4039 return LHS.sgt(RHS);
4041 return LHS.sge(RHS);
4043 return LHS.slt(RHS);
4045 return LHS.sle(RHS);
4046 default:
4047 llvm_unreachable("Unexpected non-integer predicate.");
4048 };
4049}
4050
4051bool FCmpInst::compare(const APFloat &LHS, const APFloat &RHS,
4052 FCmpInst::Predicate Pred) {
4053 APFloat::cmpResult R = LHS.compare(RHS);
4054 switch (Pred) {
4055 default:
4056 llvm_unreachable("Invalid FCmp Predicate");
4058 return false;
4060 return true;
4061 case FCmpInst::FCMP_UNO:
4062 return R == APFloat::cmpUnordered;
4063 case FCmpInst::FCMP_ORD:
4064 return R != APFloat::cmpUnordered;
4065 case FCmpInst::FCMP_UEQ:
4066 return R == APFloat::cmpUnordered || R == APFloat::cmpEqual;
4067 case FCmpInst::FCMP_OEQ:
4068 return R == APFloat::cmpEqual;
4069 case FCmpInst::FCMP_UNE:
4070 return R != APFloat::cmpEqual;
4071 case FCmpInst::FCMP_ONE:
4073 case FCmpInst::FCMP_ULT:
4074 return R == APFloat::cmpUnordered || R == APFloat::cmpLessThan;
4075 case FCmpInst::FCMP_OLT:
4076 return R == APFloat::cmpLessThan;
4077 case FCmpInst::FCMP_UGT:
4079 case FCmpInst::FCMP_OGT:
4080 return R == APFloat::cmpGreaterThan;
4081 case FCmpInst::FCMP_ULE:
4082 return R != APFloat::cmpGreaterThan;
4083 case FCmpInst::FCMP_OLE:
4084 return R == APFloat::cmpLessThan || R == APFloat::cmpEqual;
4085 case FCmpInst::FCMP_UGE:
4086 return R != APFloat::cmpLessThan;
4087 case FCmpInst::FCMP_OGE:
4088 return R == APFloat::cmpGreaterThan || R == APFloat::cmpEqual;
4089 }
4090}
4091
4092std::optional<bool> ICmpInst::compare(const KnownBits &LHS,
4093 const KnownBits &RHS,
4094 ICmpInst::Predicate Pred) {
4095 switch (Pred) {
4096 case ICmpInst::ICMP_EQ:
4097 return KnownBits::eq(LHS, RHS);
4098 case ICmpInst::ICMP_NE:
4099 return KnownBits::ne(LHS, RHS);
4100 case ICmpInst::ICMP_UGE:
4101 return KnownBits::uge(LHS, RHS);
4102 case ICmpInst::ICMP_UGT:
4103 return KnownBits::ugt(LHS, RHS);
4104 case ICmpInst::ICMP_ULE:
4105 return KnownBits::ule(LHS, RHS);
4106 case ICmpInst::ICMP_ULT:
4107 return KnownBits::ult(LHS, RHS);
4108 case ICmpInst::ICMP_SGE:
4109 return KnownBits::sge(LHS, RHS);
4110 case ICmpInst::ICMP_SGT:
4111 return KnownBits::sgt(LHS, RHS);
4112 case ICmpInst::ICMP_SLE:
4113 return KnownBits::sle(LHS, RHS);
4114 case ICmpInst::ICMP_SLT:
4115 return KnownBits::slt(LHS, RHS);
4116 default:
4117 llvm_unreachable("Unexpected non-integer predicate.");
4118 }
4119}
4120
4122 if (CmpInst::isEquality(pred))
4123 return pred;
4124 if (isSigned(pred))
4125 return getUnsignedPredicate(pred);
4126 if (isUnsigned(pred))
4127 return getSignedPredicate(pred);
4128
4129 llvm_unreachable("Unknown predicate!");
4130}
4131
4133 switch (predicate) {
4134 default: return false;
4137 case FCmpInst::FCMP_ORD: return true;
4138 }
4139}
4140
4142 switch (predicate) {
4143 default: return false;
4146 case FCmpInst::FCMP_UNO: return true;
4147 }
4148}
4149
4151 switch(predicate) {
4152 default: return false;
4153 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
4154 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
4155 }
4156}
4157
4159 switch(predicate) {
4160 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
4161 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
4162 default: return false;
4163 }
4164}
4165
4167 // If the predicates match, then we know the first condition implies the
4168 // second is true.
4169 if (CmpPredicate::getMatching(Pred1, Pred2))
4170 return true;
4171
4172 if (Pred1.hasSameSign() && CmpInst::isSigned(Pred2))
4174 else if (Pred2.hasSameSign() && CmpInst::isSigned(Pred1))
4176
4177 switch (Pred1) {
4178 default:
4179 break;
4180 case CmpInst::ICMP_EQ:
4181 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
4182 return Pred2 == CmpInst::ICMP_UGE || Pred2 == CmpInst::ICMP_ULE ||
4183 Pred2 == CmpInst::ICMP_SGE || Pred2 == CmpInst::ICMP_SLE;
4184 case CmpInst::ICMP_UGT: // A >u B implies A != B and A >=u B are true.
4185 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_UGE;
4186 case CmpInst::ICMP_ULT: // A <u B implies A != B and A <=u B are true.
4187 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_ULE;
4188 case CmpInst::ICMP_SGT: // A >s B implies A != B and A >=s B are true.
4189 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_SGE;
4190 case CmpInst::ICMP_SLT: // A <s B implies A != B and A <=s B are true.
4191 return Pred2 == CmpInst::ICMP_NE || Pred2 == CmpInst::ICMP_SLE;
4192 }
4193 return false;
4194}
4195
4197 CmpPredicate Pred2) {
4198 return isImpliedTrueByMatchingCmp(Pred1,
4200}
4201
4203 CmpPredicate Pred2) {
4204 if (isImpliedTrueByMatchingCmp(Pred1, Pred2))
4205 return true;
4206 if (isImpliedFalseByMatchingCmp(Pred1, Pred2))
4207 return false;
4208 return std::nullopt;
4209}
4210
4211//===----------------------------------------------------------------------===//
4212// CmpPredicate Implementation
4213//===----------------------------------------------------------------------===//
4214
4215std::optional<CmpPredicate> CmpPredicate::getMatching(CmpPredicate A,
4216 CmpPredicate B) {
4217 if (A.Pred == B.Pred)
4218 return A.HasSameSign == B.HasSameSign ? A : CmpPredicate(A.Pred);
4220 return {};
4221 if (A.HasSameSign &&
4223 return B.Pred;
4224 if (B.HasSameSign &&
4226 return A.Pred;
4227 return {};
4228}
4229
4233
4235 if (auto *ICI = dyn_cast<ICmpInst>(Cmp))
4236 return ICI->getCmpPredicate();
4237 return Cmp->getPredicate();
4238}
4239
4243
4247
4249 return getSwapped(get(Cmp));
4250}
4251
4252//===----------------------------------------------------------------------===//
4253// SwitchInst Implementation
4254//===----------------------------------------------------------------------===//
4255
4256void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
4257 assert(Value && Default && NumReserved);
4258 ReservedSpace = NumReserved;
4259 allocHungoffUses(ReservedSpace);
4261
4262 Op<0>() = Value;
4263 Op<1>() = Default;
4264}
4265
4266/// SwitchInst ctor - Create a new switch instruction, specifying a value to
4267/// switch on and a default destination. The number of additional cases can
4268/// be specified here to make memory allocation more efficient. This
4269/// constructor can also autoinsert before another instruction.
4270SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
4271 InsertPosition InsertBefore)
4272 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
4273 AllocMarker, InsertBefore) {
4274 init(Value, Default, 2 + NumCases);
4275}
4276
4277SwitchInst::SwitchInst(const SwitchInst &SI)
4278 : Instruction(SI.getType(), Instruction::Switch, AllocMarker) {
4279 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
4280 setNumHungOffUseOperands(SI.getNumOperands());
4281 Use *OL = getOperandList();
4282 ConstantInt **VL = case_values();
4283 const Use *InOL = SI.getOperandList();
4284 ConstantInt *const *InVL = SI.case_values();
4285 for (unsigned i = 2, E = SI.getNumOperands(); i != E; ++i) {
4286 OL[i] = InOL[i];
4287 VL[i - 2] = InVL[i - 2];
4288 }
4289 SubclassOptionalData = SI.SubclassOptionalData;
4290}
4291
4292/// addCase - Add an entry to the switch instruction...
4293///
4295 unsigned NewCaseIdx = getNumCases();
4296 unsigned OpNo = getNumOperands();
4297 if (OpNo + 1 > ReservedSpace)
4298 growOperands(); // Get more space!
4299 // Initialize some new operands.
4300 assert(OpNo < ReservedSpace && "Growing didn't work!");
4301 setNumHungOffUseOperands(OpNo + 1);
4302 CaseHandle Case(this, NewCaseIdx);
4303 Case.setValue(OnVal);
4304 Case.setSuccessor(Dest);
4305}
4306
4307/// removeCase - This method removes the specified case and its successor
4308/// from the switch instruction.
4310 unsigned idx = I->getCaseIndex();
4311
4312 assert(2 + idx < getNumOperands() && "Case index out of range!!!");
4313
4314 unsigned NumOps = getNumOperands();
4315 Use *OL = getOperandList();
4316 ConstantInt **VL = case_values();
4317
4318 // Overwrite this case with the end of the list.
4319 if (2 + idx + 1 != NumOps) {
4320 OL[2 + idx] = OL[NumOps - 1];
4321 VL[idx] = VL[NumOps - 2 - 1];
4322 }
4323
4324 // Nuke the last value.
4325 OL[NumOps - 1].set(nullptr);
4326 VL[NumOps - 2 - 1] = nullptr;
4328
4329 return CaseIt(this, idx);
4330}
4331
4332/// growOperands - grow operands - This grows the operand list in response
4333/// to a push_back style of operation. This grows the number of ops by 3 times.
4334///
4335void SwitchInst::growOperands() {
4336 unsigned e = getNumOperands();
4337 unsigned NumOps = e*3;
4338
4339 ReservedSpace = NumOps;
4340 growHungoffUses(ReservedSpace, /*WithExtraValues=*/true);
4341}
4342
4344 MDNode *ProfileData = getBranchWeightMDNode(SI);
4345 if (!ProfileData)
4346 return;
4347
4348 if (getNumBranchWeights(*ProfileData) != SI.getNumSuccessors()) {
4349 llvm_unreachable("number of prof branch_weights metadata operands does "
4350 "not correspond to number of succesors");
4351 }
4352
4354 if (!extractBranchWeights(ProfileData, Weights))
4355 return;
4356 this->Weights = std::move(Weights);
4357}
4358
4361 if (Weights) {
4362 assert(SI.getNumSuccessors() == Weights->size() &&
4363 "num of prof branch_weights must accord with num of successors");
4364 Changed = true;
4365 // Copy the last case to the place of the removed one and shrink.
4366 // This is tightly coupled with the way SwitchInst::removeCase() removes
4367 // the cases in SwitchInst::removeCase(CaseIt).
4368 (*Weights)[I->getCaseIndex() + 1] = Weights->back();
4369 Weights->pop_back();
4370 }
4371 return SI.removeCase(I);
4372}
4373
4375 auto *DestBlock = I->getCaseSuccessor();
4376 if (Weights) {
4377 auto Weight = getSuccessorWeight(I->getCaseIndex() + 1);
4378 (*Weights)[0] = Weight.value();
4379 }
4380
4381 SI.setDefaultDest(DestBlock);
4382}
4383
4385 ConstantInt *OnVal, BasicBlock *Dest,
4387 SI.addCase(OnVal, Dest);
4388
4389 if (!Weights && W && *W) {
4390 Changed = true;
4391 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4392 (*Weights)[SI.getNumSuccessors() - 1] = *W;
4393 } else if (Weights) {
4394 Changed = true;
4395 Weights->push_back(W.value_or(0));
4396 }
4397 if (Weights)
4398 assert(SI.getNumSuccessors() == Weights->size() &&
4399 "num of prof branch_weights must accord with num of successors");
4400}
4401
4404 // Instruction is erased. Mark as unchanged to not touch it in the destructor.
4405 Changed = false;
4406 if (Weights)
4407 Weights->resize(0);
4408 return SI.eraseFromParent();
4409}
4410
4413 if (!Weights)
4414 return std::nullopt;
4415 return (*Weights)[idx];
4416}
4417
4420 if (!W)
4421 return;
4422
4423 if (!Weights && *W)
4424 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4425
4426 if (Weights) {
4427 auto &OldW = (*Weights)[idx];
4428 if (*W != OldW) {
4429 Changed = true;
4430 OldW = *W;
4431 }
4432 }
4433}
4434
4437 unsigned idx) {
4438 if (MDNode *ProfileData = getValidBranchWeightMDNode(SI)) {
4439 SmallVector<uint32_t> Weights;
4440 extractFromBranchWeightMD32(ProfileData, Weights);
4441 return Weights[idx];
4442 }
4443
4444 return std::nullopt;
4445}
4446
4447//===----------------------------------------------------------------------===//
4448// IndirectBrInst Implementation
4449//===----------------------------------------------------------------------===//
4450
4451void IndirectBrInst::init(Value *Address, unsigned NumDests) {
4452 assert(Address && Address->getType()->isPointerTy() &&
4453 "Address of indirectbr must be a pointer");
4454 ReservedSpace = 1 + NumDests;
4455 allocHungoffUses(ReservedSpace);
4457
4458 Op<0>() = Address;
4459}
4460
4461
4462/// growOperands - grow operands - This grows the operand list in response
4463/// to a push_back style of operation. This grows the number of ops by 2 times.
4464///
4465void IndirectBrInst::growOperands() {
4466 unsigned e = getNumOperands();
4467 unsigned NumOps = e*2;
4468
4469 ReservedSpace = NumOps;
4470 growHungoffUses(ReservedSpace);
4471}
4472
4473IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4474 InsertPosition InsertBefore)
4475 : Instruction(Type::getVoidTy(Address->getContext()),
4476 Instruction::IndirectBr, AllocMarker, InsertBefore) {
4477 init(Address, NumCases);
4478}
4479
4480IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
4481 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
4482 AllocMarker) {
4483 allocHungoffUses(IBI.getNumOperands());
4484 setNumHungOffUseOperands(IBI.NumUserOperands);
4485 Use *OL = getOperandList();
4486 const Use *InOL = IBI.getOperandList();
4487 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
4488 OL[i] = InOL[i];
4489 SubclassOptionalData = IBI.SubclassOptionalData;
4490}
4491
4492/// addDestination - Add a destination.
4493///
4495 unsigned OpNo = getNumOperands();
4496 if (OpNo+1 > ReservedSpace)
4497 growOperands(); // Get more space!
4498 // Initialize some new operands.
4499 assert(OpNo < ReservedSpace && "Growing didn't work!");
4501 getOperandList()[OpNo] = DestBB;
4502}
4503
4504/// removeDestination - This method removes the specified successor from the
4505/// indirectbr instruction.
4507 assert(idx < getNumOperands()-1 && "Successor index out of range!");
4508
4509 unsigned NumOps = getNumOperands();
4510 Use *OL = getOperandList();
4511
4512 // Replace this value with the last one.
4513 OL[idx+1] = OL[NumOps-1];
4514
4515 // Nuke the last value.
4516 OL[NumOps-1].set(nullptr);
4518}
4519
4520//===----------------------------------------------------------------------===//
4521// FreezeInst Implementation
4522//===----------------------------------------------------------------------===//
4523
4524FreezeInst::FreezeInst(Value *S, const Twine &Name, InsertPosition InsertBefore)
4525 : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) {
4526 setName(Name);
4527}
4528
4529//===----------------------------------------------------------------------===//
4530// cloneImpl() implementations
4531//===----------------------------------------------------------------------===//
4532
4533// Define these methods here so vtables don't get emitted into every translation
4534// unit that uses these classes.
4535
4536GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
4538 return new (AllocMarker) GetElementPtrInst(*this, AllocMarker);
4539}
4540
4544
4546 auto *I = static_cast<FPUnaryOperator *>(Create(getOpcode(), Op<0>()));
4547 I->FMF = FMF;
4548 return I;
4549}
4550
4553 "Should call FPBinaryOperator::cloneImpl!");
4554 return Create(getOpcode(), Op<0>(), Op<1>());
4555}
4556
4558 auto *I =
4559 static_cast<FPBinaryOperator *>(Create(getOpcode(), Op<0>(), Op<1>()));
4560 I->FMF = FMF;
4561 return I;
4562}
4563
4565 auto *I = new FCmpInst(getPredicate(), Op<0>(), Op<1>());
4566 I->FMF = FMF;
4567 return I;
4568}
4569
4571 auto *Result = new ICmpInst(getPredicate(), Op<0>(), Op<1>());
4572 Result->setSameSign(hasSameSign());
4573 return Result;
4574}
4575
4576ExtractValueInst *ExtractValueInst::cloneImpl() const {
4577 return new ExtractValueInst(*this);
4578}
4579
4580InsertValueInst *InsertValueInst::cloneImpl() const {
4581 return new InsertValueInst(*this);
4582}
4583
4586 getOperand(0), getAlign());
4587 Result->setUsedWithInAlloca(isUsedWithInAlloca());
4588 Result->setSwiftError(isSwiftError());
4589 return Result;
4590}
4591
4593 return new LoadInst(getType(), getOperand(0), Twine(), getProperties(),
4594 /*InsertBefore=*/nullptr);
4595}
4596
4598 return new StoreInst(getOperand(0), getOperand(1), getProperties(),
4599 /*InsertBefore=*/nullptr);
4600}
4601
4606 Result->setVolatile(isVolatile());
4607 Result->setWeak(isWeak());
4608 return Result;
4609}
4610
4612 AtomicRMWInst *Result = new AtomicRMWInst(
4615 Result->setVolatile(isVolatile());
4616 return Result;
4617}
4618
4622
4624 return new TruncInst(getOperand(0), getType());
4625}
4626
4628 return new ZExtInst(getOperand(0), getType());
4629}
4630
4632 return new SExtInst(getOperand(0), getType());
4633}
4634
4636 auto *I = new FPTruncInst(getOperand(0), getType());
4637 I->FMF = FMF;
4638 return I;
4639}
4640
4642 auto *I = new FPExtInst(getOperand(0), getType());
4643 I->FMF = FMF;
4644 return I;
4645}
4646
4648 auto *Result = new UIToFPInst(getOperand(0), getType());
4649 Result->FMF = FMF;
4650 return Result;
4651}
4652
4654 auto *Result = new SIToFPInst(getOperand(0), getType());
4655 Result->FMF = FMF;
4656 return Result;
4657}
4658
4660 return new FPToUIInst(getOperand(0), getType());
4661}
4662
4664 return new FPToSIInst(getOperand(0), getType());
4665}
4666
4668 return new PtrToIntInst(getOperand(0), getType());
4669}
4670
4674
4676 return new IntToPtrInst(getOperand(0), getType());
4677}
4678
4680 return new BitCastInst(getOperand(0), getType());
4681}
4682
4686
4687CallInst *CallInst::cloneImpl() const {
4688 if (hasOperandBundles()) {
4692 return new (AllocMarker) CallInst(*this, AllocMarker);
4693 }
4695 return new (AllocMarker) CallInst(*this, AllocMarker);
4696}
4697
4698SelectInst *SelectInst::cloneImpl() const {
4700 I->FMF = FMF;
4701 return I;
4702}
4703
4705 return new VAArgInst(getOperand(0), getType());
4706}
4707
4708ExtractElementInst *ExtractElementInst::cloneImpl() const {
4710}
4711
4712InsertElementInst *InsertElementInst::cloneImpl() const {
4714}
4715
4716BitInsertInst *BitInsertInst::cloneImpl() const {
4718}
4719
4720BitExtractInst *BitExtractInst::cloneImpl() const {
4722}
4723
4727
4728PHINode *PHINode::cloneImpl() const { return new (AllocMarker) PHINode(*this); }
4729
4730LandingPadInst *LandingPadInst::cloneImpl() const {
4731 return new LandingPadInst(*this);
4732}
4733
4734ReturnInst *ReturnInst::cloneImpl() const {
4736 return new (AllocMarker) ReturnInst(*this, AllocMarker);
4737}
4738
4739UncondBrInst *UncondBrInst::cloneImpl() const {
4740 return new (AllocMarker) UncondBrInst(*this);
4741}
4742
4743CondBrInst *CondBrInst::cloneImpl() const {
4744 return new (AllocMarker) CondBrInst(*this);
4745}
4746
4747SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4748
4749IndirectBrInst *IndirectBrInst::cloneImpl() const {
4750 return new IndirectBrInst(*this);
4751}
4752
4753InvokeInst *InvokeInst::cloneImpl() const {
4754 if (hasOperandBundles()) {
4758 return new (AllocMarker) InvokeInst(*this, AllocMarker);
4759 }
4761 return new (AllocMarker) InvokeInst(*this, AllocMarker);
4762}
4763
4764CallBrInst *CallBrInst::cloneImpl() const {
4765 if (hasOperandBundles()) {
4769 return new (AllocMarker) CallBrInst(*this, AllocMarker);
4770 }
4772 return new (AllocMarker) CallBrInst(*this, AllocMarker);
4773}
4774
4775ResumeInst *ResumeInst::cloneImpl() const {
4776 return new (AllocMarker) ResumeInst(*this);
4777}
4778
4779CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4781 return new (AllocMarker) CleanupReturnInst(*this, AllocMarker);
4782}
4783
4784CatchReturnInst *CatchReturnInst::cloneImpl() const {
4785 return new (AllocMarker) CatchReturnInst(*this);
4786}
4787
4788CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
4789 return new CatchSwitchInst(*this);
4790}
4791
4792FuncletPadInst *FuncletPadInst::cloneImpl() const {
4794 return new (AllocMarker) FuncletPadInst(*this, AllocMarker);
4795}
4796
4801
4802bool UnreachableInst::shouldLowerToTrap(bool TrapUnreachable,
4803 bool NoTrapAfterNoreturn) const {
4804 if (!TrapUnreachable)
4805 return false;
4806
4807 // We may be able to ignore unreachable behind a noreturn call.
4809 Call && Call->doesNotReturn()) {
4810 if (NoTrapAfterNoreturn)
4811 return false;
4812 // Do not emit an additional trap instruction.
4813 if (Call->isNonContinuableTrap())
4814 return false;
4815 }
4816
4817 if (getFunction()->hasFnAttribute(Attribute::Naked))
4818 return false;
4819
4820 return true;
4821}
4822
4824 return new FreezeInst(getOperand(0));
4825}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
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
SmallVector< MachineOperand, 4 > Cond
#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.
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:369
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
Definition APFloat.cpp:6364
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:106
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:260
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
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:63
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:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
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:294
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:236
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
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
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
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:44
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:61
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)
@ Resume
Resume function, contains the coroutine body code.
Definition CodeView.h:646
@ 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:680
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:382
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:370
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