46#define LV_NAME "loop-vectorize"
47#define DEBUG_TYPE LV_NAME
52 return cast<VPExpressionRecipe>(
this)->mayReadOrWriteMemory();
54 return cast<VPInstruction>(
this)->opcodeMayReadOrWriteFromMemory();
56 return cast<VPInterleaveRecipe>(
this)->getNumStoreOperands() > 0;
57 case VPWidenStoreEVLSC:
64 return !cast<VPWidenCallRecipe>(
this)
65 ->getCalledScalarFunction()
67 case VPWidenIntrinsicSC:
68 return cast<VPWidenIntrinsicRecipe>(
this)->mayWriteToMemory();
69 case VPCanonicalIVPHISC:
70 case VPBranchOnMaskSC:
71 case VPFirstOrderRecurrencePHISC:
72 case VPReductionPHISC:
73 case VPScalarIVStepsSC:
77 case VPReductionEVLSC:
79 case VPVectorPointerSC:
80 case VPWidenCanonicalIVSC:
83 case VPWidenIntOrFpInductionSC:
84 case VPWidenLoadEVLSC:
88 case VPWidenSelectSC: {
92 assert((!
I || !
I->mayWriteToMemory()) &&
93 "underlying instruction may write to memory");
104 return cast<VPExpressionRecipe>(
this)->mayReadOrWriteMemory();
105 case VPInstructionSC:
106 return cast<VPInstruction>(
this)->opcodeMayReadOrWriteFromMemory();
107 case VPWidenLoadEVLSC:
112 ->mayReadFromMemory();
114 return !cast<VPWidenCallRecipe>(
this)
115 ->getCalledScalarFunction()
116 ->onlyWritesMemory();
117 case VPWidenIntrinsicSC:
118 return cast<VPWidenIntrinsicRecipe>(
this)->mayReadFromMemory();
119 case VPBranchOnMaskSC:
120 case VPFirstOrderRecurrencePHISC:
121 case VPPredInstPHISC:
122 case VPScalarIVStepsSC:
123 case VPWidenStoreEVLSC:
127 case VPReductionEVLSC:
129 case VPVectorPointerSC:
130 case VPWidenCanonicalIVSC:
133 case VPWidenIntOrFpInductionSC:
136 case VPWidenSelectSC: {
140 assert((!
I || !
I->mayReadFromMemory()) &&
141 "underlying instruction may read from memory");
152 return cast<VPExpressionRecipe>(
this)->mayHaveSideEffects();
154 case VPFirstOrderRecurrencePHISC:
155 case VPPredInstPHISC:
156 case VPVectorEndPointerSC:
158 case VPInstructionSC:
160 case VPWidenCallSC: {
161 Function *Fn = cast<VPWidenCallRecipe>(
this)->getCalledScalarFunction();
164 case VPWidenIntrinsicSC:
165 return cast<VPWidenIntrinsicRecipe>(
this)->mayHaveSideEffects();
167 case VPReductionEVLSC:
169 case VPScalarIVStepsSC:
170 case VPVectorPointerSC:
171 case VPWidenCanonicalIVSC:
174 case VPWidenIntOrFpInductionSC:
176 case VPWidenPointerInductionSC:
178 case VPWidenSelectSC: {
182 assert((!
I || !
I->mayHaveSideEffects()) &&
183 "underlying instruction has side-effects");
188 case VPWidenLoadEVLSC:
190 case VPWidenStoreEVLSC:
195 "mayHaveSideffects result for ingredient differs from this "
198 case VPReplicateSC: {
199 auto *R = cast<VPReplicateRecipe>(
this);
200 return R->getUnderlyingInstr()->mayHaveSideEffects();
208 assert(!Parent &&
"Recipe already in some VPBasicBlock");
210 "Insertion position not in any VPBasicBlock");
216 assert(!Parent &&
"Recipe already in some VPBasicBlock");
222 assert(!Parent &&
"Recipe already in some VPBasicBlock");
224 "Insertion position not in any VPBasicBlock");
256 if (
auto *S = dyn_cast<VPSingleDefRecipe>(
this))
257 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
258 else if (
auto *IG = dyn_cast<VPInterleaveRecipe>(
this))
259 UI = IG->getInsertPos();
260 else if (
auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(
this))
261 UI = &WidenMem->getIngredient();
274 dbgs() <<
"Cost of " << RecipeCost <<
" for VF " << VF <<
": ";
287 isa<VPPhi, VPIRPhi>(
this);
291 auto *VPI = dyn_cast<VPInstruction>(
this);
298 std::optional<unsigned> Opcode;
305 OpR =
Op->getDefiningRecipe();
308 Type *InputTypeA =
nullptr, *InputTypeB =
nullptr;
315 auto *WidenCastR = dyn_cast<VPWidenCastRecipe>(R);
318 if (WidenCastR->getOpcode() == Instruction::CastOps::ZExt)
320 if (WidenCastR->getOpcode() == Instruction::CastOps::SExt)
329 Widen = dyn_cast<VPWidenRecipe>(
Op->getDefiningRecipe());
338 ExtAType = GetExtendKind(ExtAR);
339 ExtBType = GetExtendKind(ExtBR);
342 if (isa<VPWidenCastRecipe>(OpR)) {
344 ExtAType = GetExtendKind(OpR);
345 }
else if (isa<VPReductionPHIRecipe>(OpR)) {
347 if (isa<VPWidenCastRecipe>(RedPhiOp1R)) {
349 ExtAType = GetExtendKind(RedPhiOp1R);
350 }
else if (
auto Widen = dyn_cast<VPWidenRecipe>(RedPhiOp1R))
352 }
else if (
auto Widen = dyn_cast<VPWidenRecipe>(OpR)) {
354 }
else if (
auto Reduction = dyn_cast<VPPartialReductionRecipe>(OpR)) {
359 PhiType, VF, ExtAType, ExtBType,
367 "Unhandled partial reduction opcode");
371 assert(PhiVal && BinOpVal &&
"Phi and Mul must be set");
375 CallInst *V = Builder.CreateIntrinsic(
376 RetTy, Intrinsic::experimental_vector_partial_reduce_add,
377 {PhiVal, BinOpVal},
nullptr,
"partial.reduce");
382#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
385 O << Indent <<
"PARTIAL-REDUCE ";
393 assert(OpType == OperationType::FPMathOp &&
394 "recipe doesn't have fast math flags");
406#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
410template <
unsigned PartOpIdx>
413 if (U.getNumOperands() == PartOpIdx + 1)
414 return U.getOperand(PartOpIdx);
418template <
unsigned PartOpIdx>
420 if (
auto *UnrollPartOp = getUnrollPartOperand(U))
421 return cast<ConstantInt>(UnrollPartOp->getLiveInIRValue())->getZExtValue();
437 "Set flags not supported for the provided opcode");
438 assert((getNumOperandsForOpcode(Opcode) == -1u ||
440 "number of operands does not match opcode");
444unsigned VPInstruction::getNumOperandsForOpcode(
unsigned Opcode) {
455 case Instruction::Alloca:
456 case Instruction::ExtractValue:
457 case Instruction::Freeze:
458 case Instruction::Load:
471 case Instruction::ICmp:
472 case Instruction::FCmp:
473 case Instruction::Store:
483 case Instruction::Select:
489 case Instruction::Call:
490 case Instruction::GetElementPtr:
491 case Instruction::PHI:
492 case Instruction::Switch:
500bool VPInstruction::doesGeneratePerAllLanes()
const {
504bool VPInstruction::canGenerateScalarForFirstLane()
const {
510 case Instruction::Freeze:
511 case Instruction::ICmp:
512 case Instruction::PHI:
513 case Instruction::Select:
533 "only PtrAdd opcodes are supported for now");
567 if (
auto *
I = dyn_cast<Instruction>(Res))
578 case Instruction::ExtractElement: {
581 unsigned IdxToExtract =
589 case Instruction::Freeze: {
593 case Instruction::FCmp:
594 case Instruction::ICmp: {
600 case Instruction::PHI: {
603 case Instruction::Select: {
626 {VIVElem0, ScalarTC},
nullptr, Name);
642 if (!V1->getType()->isVectorTy())
662 "Requested vector length should be an integer.");
669 {AVL, VFArg, State.Builder.getTrue()});
675 assert(Part != 0 &&
"Must have a positive part");
706 for (
unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
744 auto *PhiR = cast<VPReductionPHIRecipe>(
getOperand(0));
745 auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
758 auto *PhiR = cast<VPReductionPHIRecipe>(
getOperand(0));
760 RecurKind RK = PhiR->getRecurrenceKind();
762 "Unexpected reduction kind");
763 assert(!PhiR->isInLoop() &&
764 "In-loop FindLastIV reduction is not supported yet");
776 for (
unsigned Part = 1; Part <
UF; ++Part)
777 ReducedPartRdx =
createMinMaxOp(Builder, MinMaxKind, ReducedPartRdx,
788 auto *PhiR = cast<VPReductionPHIRecipe>(
getOperand(0));
791 RecurKind RK = PhiR->getRecurrenceKind();
793 "should be handled by ComputeFindIVResult");
799 for (
unsigned Part = 0; Part <
UF; ++Part)
800 RdxParts[Part] = State.
get(
getOperand(1 + Part), PhiR->isInLoop());
807 Value *ReducedPartRdx = RdxParts[0];
808 if (PhiR->isOrdered()) {
809 ReducedPartRdx = RdxParts[
UF - 1];
812 for (
unsigned Part = 1; Part <
UF; ++Part) {
813 Value *RdxPart = RdxParts[Part];
815 ReducedPartRdx =
createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
821 Opcode = Instruction::Add;
826 Builder.
CreateBinOp(Opcode, RdxPart, ReducedPartRdx,
"bin.rdx");
833 if (State.
VF.
isVector() && !PhiR->isInLoop()) {
840 return ReducedPartRdx;
848 "invalid offset to extract from");
852 assert(
Offset <= 1 &&
"invalid offset to extract from");
855 if (isa<ExtractElementInst>(Res))
866 "can only generate first lane for PtrAdd");
886 Value *Res =
nullptr;
891 Builder.
CreateMul(RuntimeVF, ConstantInt::get(IdxTy,
Idx - 1));
894 : Builder.
CreateSub(LaneToExtract, VectorStart);
920 Value *Res =
nullptr;
922 Value *TrailingZeros =
955 case Instruction::FNeg:
957 case Instruction::UDiv:
958 case Instruction::SDiv:
959 case Instruction::SRem:
960 case Instruction::URem:
961 case Instruction::Add:
962 case Instruction::FAdd:
963 case Instruction::Sub:
964 case Instruction::FSub:
965 case Instruction::Mul:
966 case Instruction::FMul:
967 case Instruction::FDiv:
968 case Instruction::FRem:
969 case Instruction::Shl:
970 case Instruction::LShr:
971 case Instruction::AShr:
972 case Instruction::And:
973 case Instruction::Or:
974 case Instruction::Xor: {
995 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
998 case Instruction::Freeze:
1002 case Instruction::ExtractValue:
1005 case Instruction::ICmp:
1006 case Instruction::FCmp: {
1012 Ctx.
CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1013 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1016 return std::nullopt;
1028 assert(!doesGeneratePerAllLanes() &&
1029 "Should only generate a vector value or single scalar, not scalars "
1037 case Instruction::Select: {
1050 case Instruction::ExtractElement:
1066 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.
CostKind);
1078 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1088 cast<VectorType>(VectorTy),
1089 cast<VectorType>(VectorTy), Mask,
1104 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1121 "unexpected VPInstruction witht underlying value");
1129 getOpcode() == Instruction::ExtractElement ||
1140 case Instruction::PHI:
1151 assert(!State.
Lane &&
"VPInstruction executing an Lane");
1154 "Set flags not supported for the provided opcode");
1157 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1160 bool GeneratesPerAllLanes = doesGeneratePerAllLanes();
1161 if (GeneratesPerAllLanes) {
1163 Lane != NumLanes; ++Lane) {
1164 Value *GeneratedValue = generatePerLane(State,
VPLane(Lane));
1165 assert(GeneratedValue &&
"generatePerLane must produce a value");
1166 State.
set(
this, GeneratedValue,
VPLane(Lane));
1171 Value *GeneratedValue = generate(State);
1174 assert(GeneratedValue &&
"generate must produce a value");
1177 !GeneratesPerFirstLaneOnly) ||
1179 "scalar value but not only first lane defined");
1180 State.
set(
this, GeneratedValue,
1181 GeneratesPerFirstLaneOnly);
1188 case Instruction::ExtractElement:
1189 case Instruction::Freeze:
1190 case Instruction::FCmp:
1191 case Instruction::ICmp:
1192 case Instruction::Select:
1193 case Instruction::PHI:
1226 case Instruction::ExtractElement:
1228 case Instruction::PHI:
1230 case Instruction::FCmp:
1231 case Instruction::ICmp:
1232 case Instruction::Select:
1233 case Instruction::Or:
1234 case Instruction::Freeze:
1268 case Instruction::FCmp:
1269 case Instruction::ICmp:
1270 case Instruction::Select:
1280#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1288 O << Indent <<
"EMIT" << (
isSingleScalar() ?
"-SCALAR" :
"") <<
" ";
1300 O <<
"combined load";
1303 O <<
"combined store";
1306 O <<
"active lane mask";
1309 O <<
"EXPLICIT-VECTOR-LENGTH";
1312 O <<
"first-order splice";
1315 O <<
"branch-on-cond";
1318 O <<
"TC > VF ? TC - VF : 0";
1324 O <<
"branch-on-count";
1330 O <<
"buildstructvector";
1336 O <<
"extract-lane";
1339 O <<
"extract-last-element";
1342 O <<
"extract-penultimate-element";
1345 O <<
"compute-anyof-result";
1348 O <<
"compute-find-iv-result";
1351 O <<
"compute-reduction-result";
1366 O <<
"first-active-lane";
1369 O <<
"reduction-start-vector";
1372 O <<
"resume-for-epilogue";
1415#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1418 O << Indent <<
"EMIT" << (
isSingleScalar() ?
"-SCALAR" :
"") <<
" ";
1424 O <<
"wide-iv-step ";
1428 O <<
"step-vector " << *ResultTy;
1431 O <<
"vscale " << *ResultTy;
1437 O <<
" to " << *ResultTy;
1452 for (
unsigned Idx = 0;
Idx != NumIncoming; ++
Idx) {
1460#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1463 O << Indent <<
"EMIT" << (
isSingleScalar() ?
"-SCALAR" :
"") <<
" ";
1471 if (
auto *Phi = dyn_cast<PHINode>(&
I))
1478 "PHINodes must be handled by VPIRPhi");
1493 "can only update exiting operands to phi nodes");
1503#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1506 O << Indent <<
"IR " << I;
1526 if (Phi->getBasicBlockIndex(PredBB) == -1)
1527 Phi->addIncoming(V, PredBB);
1529 Phi->setIncomingValueForBlock(PredBB, V);
1539 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1540 "Number of phi operands must match number of predecessors");
1541 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1542 R->removeOperand(Position);
1545#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1559#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1565 O <<
" (extra operand" << (
getNumOperands() > 1 ?
"s" :
"") <<
": ";
1570 std::get<1>(
Op)->printAsOperand(O);
1579 if (!LVer || !isa<LoadInst, StoreInst>(&
I))
1583 Metadata.emplace_back(LLVMContext::MD_alias_scope, AliasScopeMD);
1585 Metadata.emplace_back(LLVMContext::MD_noalias, NoAliasMD);
1589 for (
const auto &[Kind, Node] :
Metadata)
1590 I.setMetadata(Kind, Node);
1595 for (
const auto &[KindA, MDA] :
Metadata) {
1596 for (
const auto &[KindB, MDB] :
Other.Metadata) {
1597 if (KindA == KindB && MDA == MDB) {
1603 Metadata = std::move(MetadataIntersection);
1608 assert(Variant !=
nullptr &&
"Can't create vector function.");
1622 Args.push_back(Arg);
1628 CI->getOperandBundlesAsDefs(OpBundles);
1635 if (!V->getType()->isVoidTy())
1646#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1649 O << Indent <<
"WIDEN-CALL ";
1661 O <<
" @" << CalledFn->
getName() <<
"(";
1667 O <<
" (using library function";
1669 O <<
": " << Variant->
getName();
1694 Args.push_back(Arg);
1702 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1707 CI->getOperandBundlesAsDefs(OpBundles);
1714 if (!V->getType()->isVoidTy())
1731 auto *V =
Op->getUnderlyingValue();
1733 if (
auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1754 R.hasFastMathFlags() ? R.getFastMathFlags() :
FastMathFlags();
1757 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1781#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1784 O << Indent <<
"WIDEN-INTRINSIC ";
1813 Value *Mask =
nullptr;
1815 Mask = State.
get(VPMask);
1822 if (Opcode == Instruction::Sub)
1825 assert(Opcode == Instruction::Add &&
"only add or sub supported for now");
1861 {PtrTy, IncTy, MaskTy});
1868#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1871 O << Indent <<
"WIDEN-HISTOGRAM buckets: ";
1874 if (Opcode == Instruction::Sub)
1877 assert(Opcode == Instruction::Add);
1890 O << Indent <<
"WIDEN-SELECT ";
1915 State.
set(
this, Sel);
1916 if (
auto *
I = dyn_cast<Instruction>(Sel)) {
1917 if (isa<FPMathOperator>(
I))
1942 [](
VPValue *
Op) {
return Op->getUnderlyingValue(); }))
1943 Operands.append(SI->op_begin(), SI->op_end());
1944 bool IsLogicalOr =
match(
this,
m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1946 IsLogicalOr ? Instruction::Or : Instruction::And, VectorTy,
1955 if (
auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
1956 Pred = Cmp->getPredicate();
1958 Instruction::Select, VectorTy, CondTy, Pred, Ctx.
CostKind,
1959 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1962VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(
const FastMathFlags &FMF) {
1975 case OperationType::OverflowingBinOp:
1976 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
1977 Opcode == Instruction::Mul ||
1978 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
1979 case OperationType::Trunc:
1980 return Opcode == Instruction::Trunc;
1981 case OperationType::DisjointOp:
1982 return Opcode == Instruction::Or;
1983 case OperationType::PossiblyExactOp:
1984 return Opcode == Instruction::AShr;
1985 case OperationType::GEPOp:
1986 return Opcode == Instruction::GetElementPtr ||
1989 case OperationType::FPMathOp:
1990 return Opcode == Instruction::FAdd || Opcode == Instruction::FMul ||
1991 Opcode == Instruction::FSub || Opcode == Instruction::FNeg ||
1992 Opcode == Instruction::FDiv || Opcode == Instruction::FRem ||
1993 Opcode == Instruction::FCmp || Opcode == Instruction::Select ||
1997 case OperationType::NonNegOp:
1998 return Opcode == Instruction::ZExt;
2000 case OperationType::Cmp:
2001 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2002 case OperationType::Other:
2009#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2012 case OperationType::Cmp:
2015 case OperationType::DisjointOp:
2019 case OperationType::PossiblyExactOp:
2023 case OperationType::OverflowingBinOp:
2029 case OperationType::Trunc:
2035 case OperationType::FPMathOp:
2038 case OperationType::GEPOp:
2046 case OperationType::NonNegOp:
2050 case OperationType::Other:
2058 auto &Builder = State.
Builder;
2060 case Instruction::Call:
2061 case Instruction::Br:
2062 case Instruction::PHI:
2063 case Instruction::GetElementPtr:
2064 case Instruction::Select:
2066 case Instruction::UDiv:
2067 case Instruction::SDiv:
2068 case Instruction::SRem:
2069 case Instruction::URem:
2070 case Instruction::Add:
2071 case Instruction::FAdd:
2072 case Instruction::Sub:
2073 case Instruction::FSub:
2074 case Instruction::FNeg:
2075 case Instruction::Mul:
2076 case Instruction::FMul:
2077 case Instruction::FDiv:
2078 case Instruction::FRem:
2079 case Instruction::Shl:
2080 case Instruction::LShr:
2081 case Instruction::AShr:
2082 case Instruction::And:
2083 case Instruction::Or:
2084 case Instruction::Xor: {
2092 if (
auto *VecOp = dyn_cast<Instruction>(V)) {
2101 case Instruction::ExtractValue: {
2106 State.
set(
this, Extract);
2109 case Instruction::Freeze: {
2112 State.
set(
this, Freeze);
2115 case Instruction::ICmp:
2116 case Instruction::FCmp: {
2118 bool FCmp = Opcode == Instruction::FCmp;
2130 if (
auto *
I = dyn_cast<Instruction>(
C))
2147 "inferred type and type from generated instructions do not match");
2154 case Instruction::UDiv:
2155 case Instruction::SDiv:
2156 case Instruction::SRem:
2157 case Instruction::URem:
2162 case Instruction::FNeg:
2163 case Instruction::Add:
2164 case Instruction::FAdd:
2165 case Instruction::Sub:
2166 case Instruction::FSub:
2167 case Instruction::Mul:
2168 case Instruction::FMul:
2169 case Instruction::FDiv:
2170 case Instruction::FRem:
2171 case Instruction::Shl:
2172 case Instruction::LShr:
2173 case Instruction::AShr:
2174 case Instruction::And:
2175 case Instruction::Or:
2176 case Instruction::Xor:
2177 case Instruction::Freeze:
2178 case Instruction::ExtractValue:
2179 case Instruction::ICmp:
2180 case Instruction::FCmp:
2187#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2190 O << Indent <<
"WIDEN ";
2199 auto &Builder = State.
Builder;
2206 State.
set(
this, Cast);
2207 if (
auto *CastOp = dyn_cast<Instruction>(Cast)) {
2224 if (isa<VPInterleaveRecipe>(R))
2226 if (
const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R))
2229 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
2230 if (WidenMemoryRecipe ==
nullptr)
2232 if (!WidenMemoryRecipe->isConsecutive())
2234 if (WidenMemoryRecipe->isReverse())
2236 if (WidenMemoryRecipe->isMasked())
2244 if ((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) &&
2246 if (
auto *StoreRecipe = dyn_cast<VPRecipeBase>(*
user_begin()))
2247 CCH = ComputeCCH(StoreRecipe);
2250 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
2251 Opcode == Instruction::FPExt) {
2263 Opcode, DestTy, SrcTy, CCH, Ctx.
CostKind,
2267#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2270 O << Indent <<
"WIDEN-CAST ";
2288 : ConstantFP::get(Ty,
C);
2291#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2296 O <<
" = WIDEN-INDUCTION ";
2300 O <<
" (truncated to " << *TI->getType() <<
")";
2312 auto *CanIV = cast<VPCanonicalIVPHIRecipe>(&*
getParent()->begin());
2313 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2317#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2322 O <<
" = DERIVED-IV ";
2346 assert(BaseIVTy == Step->
getType() &&
"Types of BaseIV and Step must match!");
2353 AddOp = Instruction::Add;
2354 MulOp = Instruction::Mul;
2356 AddOp = InductionOpcode;
2357 MulOp = Instruction::FMul;
2366 Type *VecIVTy =
nullptr;
2367 Value *UnitStepVec =
nullptr, *SplatStep =
nullptr, *SplatIV =
nullptr;
2376 unsigned StartLane = 0;
2379 StartLane = State.
Lane->getKnownLane();
2380 EndLane = StartLane + 1;
2384 StartIdx0 = ConstantInt::get(IntStepTy, 0);
2397 auto *InitVec = Builder.
CreateAdd(SplatStartIdx, UnitStepVec);
2411 for (
unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2417 "Expected StartIdx to be folded to a constant when VF is not "
2425#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2430 O <<
" = SCALAR-STEPS ";
2444 if (areAllOperandsInvariant()) {
2479 if (isIndexLoopInvariant(
I - 1))
2490 "NewGEP is not a pointer vector");
2491 State.
set(
this, NewGEP);
2495#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2498 O << Indent <<
"WIDEN-GEP ";
2499 O << (isPointerLoopInvariant() ?
"Inv" :
"Var");
2501 O <<
"[" << (isIndexLoopInvariant(
I) ?
"Inv" :
"Var") <<
"]";
2505 O <<
" = getelementptr";
2516 return !IsUnitStride || (IsScalable && (IsReverse || CurrentPart > 0))
2522 auto &Builder = State.
Builder;
2524 bool IsUnitStride = Stride == 1 || Stride == -1;
2526 IsUnitStride, CurrentPart, Builder);
2530 if (IndexTy != RunTimeVF->
getType())
2534 ConstantInt::get(IndexTy, Stride * (int64_t)CurrentPart), RunTimeVF);
2536 Value *LastLane = Builder.
CreateSub(RunTimeVF, ConstantInt::get(IndexTy, 1));
2538 LastLane = Builder.
CreateMul(ConstantInt::get(IndexTy, Stride), LastLane);
2542 ResultPtr = Builder.
CreateGEP(IndexedTy, ResultPtr, LastLane,
"",
2545 State.
set(
this, ResultPtr,
true);
2548#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2553 O <<
" = vector-end-pointer";
2560 auto &Builder = State.
Builder;
2563 true, CurrentPart, Builder);
2570 State.
set(
this, ResultPtr,
true);
2573#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2578 O <<
" = vector-pointer ";
2598#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2601 O << Indent <<
"BLEND ";
2623 assert(!State.
Lane &&
"Reduction being replicated.");
2627 "In-loop AnyOf reductions aren't currently supported");
2653 PrevInChain, NewVecOp);
2654 PrevInChain = NewRed;
2655 NextInChain = NewRed;
2664 PrevInChain, NewRed);
2666 State.
set(
this, NextInChain,
true);
2670 assert(!State.
Lane &&
"Reduction being replicated.");
2672 auto &Builder = State.
Builder;
2684 Mask = State.
get(CondOp);
2700 State.
set(
this, NewRed,
true);
2707 auto *VectorTy = cast<VectorType>(
toVectorTy(ElementTy, VF));
2710 std::optional<FastMathFlags> OptionalFMF =
2717 "Any-of reduction not implemented in VPlan-based cost model currently.");
2733 ExpressionTypes ExpressionType,
2737 ExpressionRecipes.begin(), ExpressionRecipes.end())
2740 assert(!ExpressionRecipes.empty() &&
"Nothing to combine?");
2744 "expression cannot contain recipes with side-effects");
2748 for (
auto *R : ExpressionRecipes)
2749 ExpressionRecipesAsSetOfUsers.
insert(R);
2755 if (R != ExpressionRecipes.back() &&
2756 any_of(
R->users(), [&ExpressionRecipesAsSetOfUsers](
VPUser *U) {
2757 return !ExpressionRecipesAsSetOfUsers.contains(U);
2762 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2764 return !ExpressionRecipesAsSetOfUsers.
contains(&U);
2769 R->removeFromParent();
2776 for (
auto *R : ExpressionRecipes) {
2778 auto *
Def =
Op->getDefiningRecipe();
2782 LiveInPlaceholders.push_back(
new VPValue());
2783 R->setOperand(
Idx, LiveInPlaceholders.back());
2789 for (
auto *R : ExpressionRecipes)
2790 R->insertBefore(
this);
2793 LiveInPlaceholders[
Idx]->replaceAllUsesWith(
Op);
2796 ExpressionRecipes.clear();
2802 auto *SrcVecTy = cast<VectorType>(
2805 "VPExpressionRecipe only supports integer types currently.");
2806 switch (ExpressionType) {
2807 case ExpressionTypes::ExtendedReduction: {
2809 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
2812 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
2814 RedTy, SrcVecTy, std::nullopt, Ctx.
CostKind);
2816 case ExpressionTypes::MulAccReduction:
2819 case ExpressionTypes::ExtMulAccReduction:
2821 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
2830 return R->mayReadFromMemory() || R->mayWriteToMemory();
2838 "expression cannot contain recipes with side-effects");
2842#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2846 O << Indent <<
"EXPRESSION ";
2849 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
2852 switch (ExpressionType) {
2853 case ExpressionTypes::ExtendedReduction: {
2860 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2862 << *Ext0->getResultType();
2863 if (Red->isConditional()) {
2870 case ExpressionTypes::MulAccReduction:
2871 case ExpressionTypes::ExtMulAccReduction: {
2879 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
2880 auto *
Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
2881 : ExpressionRecipes[0]);
2887 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2889 << *Ext0->getResultType() <<
"), (";
2895 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2897 << *Ext1->getResultType() <<
")";
2899 if (Red->isConditional()) {
2911 O << Indent <<
"REDUCE ";
2931 O << Indent <<
"REDUCE ";
2959 assert((!Instr->getType()->isAggregateType() ||
2961 "Expected vectorizable or non-aggregate type.");
2964 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2968 Cloned->
setName(Instr->getName() +
".cloned");
2973 if (ResultTy != Cloned->
getType())
2981 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->
getPredicate());
2989 auto InputLane = Lane;
2999 State.
set(RepRecipe, Cloned, Lane);
3002 if (
auto *
II = dyn_cast<AssumeInst>(Cloned))
3009 [](
VPValue *
Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3010 "Expected a recipe is either within a region or all of its operands "
3011 "are defined outside the vectorized region.");
3018 assert(IsSingleScalar &&
"VPReplicateRecipes outside replicate regions "
3019 "must have already been unrolled");
3025 "uniform recipe shouldn't be predicated");
3031 State.
Lane->isFirstLane()
3043 if (
auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3057 case Instruction::GetElementPtr:
3063 case Instruction::Call: {
3069 for (
const VPValue *ArgOp : ArgOps)
3072 if (CalledFn->isIntrinsic())
3075 switch (CalledFn->getIntrinsicID()) {
3076 case Intrinsic::assume:
3077 case Intrinsic::lifetime_end:
3078 case Intrinsic::lifetime_start:
3079 case Intrinsic::sideeffect:
3080 case Intrinsic::pseudoprobe:
3081 case Intrinsic::experimental_noalias_scope_decl: {
3084 "scalarizing intrinsic should be free");
3095 if (CalledFn->isIntrinsic())
3096 ScalarCallCost = std::min(
3100 return ScalarCallCost;
3110 for (
Type *VectorTy :
3122 for (
auto *
Op : ArgOps) {
3123 if (
Op->isLiveIn() || isa<VPReplicateRecipe, VPPredInstPHIRecipe>(
Op) ||
3128 ScalarizationCost +=
3132 return ScalarCallCost * VF.
getFixedValue() + ScalarizationCost;
3134 case Instruction::Add:
3135 case Instruction::Sub:
3136 case Instruction::FAdd:
3137 case Instruction::FSub:
3138 case Instruction::Mul:
3139 case Instruction::FMul:
3140 case Instruction::FDiv:
3141 case Instruction::FRem:
3142 case Instruction::Shl:
3143 case Instruction::LShr:
3144 case Instruction::AShr:
3145 case Instruction::And:
3146 case Instruction::Or:
3147 case Instruction::Xor:
3148 case Instruction::ICmp:
3149 case Instruction::FCmp:
3158#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3161 O << Indent << (IsSingleScalar ?
"CLONE " :
"REPLICATE ");
3170 O <<
"@" << CB->getCalledFunction()->getName() <<
"(";
3188 assert(State.
Lane &&
"Branch on Mask works only on single instance.");
3191 Value *ConditionBit = State.
get(BlockInMask, *State.
Lane);
3196 assert(isa<UnreachableInst>(CurrentTerminator) &&
3197 "Expected to replace unreachable terminator with conditional branch.");
3201 CurrentTerminator->eraseFromParent();
3213 assert(State.
Lane &&
"Predicated instruction PHI works per instance.");
3218 assert(PredicatingBB &&
"Predicated block has no single predecessor.");
3220 "operand must be VPReplicateRecipe");
3235 State.
reset(
this, VPhi);
3237 State.
set(
this, VPhi);
3249 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3253 State.
set(
this, Phi, *State.
Lane);
3260#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3263 O << Indent <<
"PHI-PREDICATED-INSTRUCTION ";
3275 ->getAddressSpace();
3276 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(
this)
3278 : Instruction::Store;
3285 "Inconsecutive memory access should not have the order.");
3307 isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(
this) ?
getOperand(0)
3317 cast<VectorType>(Ty), {}, Ctx.
CostKind, 0);
3326 auto &Builder = State.
Builder;
3327 Value *Mask =
nullptr;
3328 if (
auto *VPMask =
getMask()) {
3331 Mask = State.
get(VPMask);
3340 "wide.masked.gather");
3351 State.
set(
this, NewLI);
3354#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3357 O << Indent <<
"WIDEN ";
3369 Value *AllTrueMask =
3371 return Builder.
CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3372 {Operand, AllTrueMask, EVL},
nullptr,
Name);
3381 auto &Builder = State.
Builder;
3385 Value *Mask =
nullptr;
3387 Mask = State.
get(VPMask);
3397 nullptr,
"wide.masked.gather");
3400 {
Addr, Mask, EVL},
nullptr,
"vp.op.load");
3408 State.
set(
this, Res);
3425 Instruction::Load, Ty, Alignment, AS, Ctx.
CostKind);
3431 cast<VectorType>(Ty), {}, Ctx.
CostKind, 0);
3434#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3437 O << Indent <<
"WIDEN ";
3449 auto &Builder = State.
Builder;
3451 Value *Mask =
nullptr;
3452 if (
auto *VPMask =
getMask()) {
3455 Mask = State.
get(VPMask);
3460 Value *StoredVal = State.
get(StoredVPValue);
3479#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3482 O << Indent <<
"WIDEN store ";
3492 auto &Builder = State.
Builder;
3495 Value *StoredVal = State.
get(StoredValue);
3499 Value *Mask =
nullptr;
3501 Mask = State.
get(VPMask);
3508 if (CreateScatter) {
3510 Intrinsic::vp_scatter,
3511 {StoredVal, Addr, Mask, EVL});
3514 Intrinsic::vp_store,
3515 {StoredVal, Addr, Mask, EVL});
3536 Instruction::Store, Ty, Alignment, AS, Ctx.
CostKind);
3542 cast<VectorType>(Ty), {}, Ctx.
CostKind, 0);
3545#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3548 O << Indent <<
"WIDEN vp.store ";
3556 auto VF = DstVTy->getElementCount();
3557 auto *SrcVecTy = cast<VectorType>(V->getType());
3558 assert(VF == SrcVecTy->getElementCount() &&
"Vector dimensions do not match");
3559 Type *SrcElemTy = SrcVecTy->getElementType();
3560 Type *DstElemTy = DstVTy->getElementType();
3561 assert((
DL.getTypeSizeInBits(SrcElemTy) ==
DL.getTypeSizeInBits(DstElemTy)) &&
3562 "Vector elements must have same size");
3573 "Only one type should be a pointer type");
3575 "Only one type should be a floating point type");
3587 unsigned Factor = Vals.
size();
3588 assert(Factor > 1 &&
"Tried to interleave invalid number of vectors");
3592 for (
Value *Val : Vals)
3593 assert(Val->getType() == VecTy &&
"Tried to interleave mismatched types");
3598 if (VecTy->isScalableTy()) {
3599 assert(Factor <= 8 &&
"Unsupported interleave factor for scalable vectors");
3607 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
3641 assert(!State.
Lane &&
"Interleave group being replicated.");
3643 "Masking gaps for scalable vectors is not yet supported.");
3649 unsigned InterleaveFactor = Group->
getFactor();
3656 auto CreateGroupMask = [&BlockInMask, &State,
3657 &InterleaveFactor](
Value *MaskForGaps) ->
Value * {
3659 assert(!MaskForGaps &&
"Interleaved groups with gaps are not supported.");
3660 assert(InterleaveFactor <= 8 &&
3661 "Unsupported deinterleave factor for scalable vectors");
3662 auto *ResBlockInMask = State.
get(BlockInMask);
3670 Value *ResBlockInMask = State.
get(BlockInMask);
3674 "interleaved.mask");
3676 ShuffledMask, MaskForGaps)
3682 if (isa<LoadInst>(Instr)) {
3683 Value *MaskForGaps =
nullptr;
3684 if (NeedsMaskForGaps) {
3687 assert(MaskForGaps &&
"Mask for Gaps is required but it is null");
3691 if (BlockInMask || MaskForGaps) {
3692 Value *GroupMask = CreateGroupMask(MaskForGaps);
3696 PoisonVec,
"wide.masked.vec");
3705 if (VecTy->isScalableTy()) {
3708 assert(InterleaveFactor <= 8 &&
3709 "Unsupported deinterleave factor for scalable vectors");
3713 nullptr,
"strided.vec");
3716 auto CreateStridedVector = [&InterleaveFactor, &State,
3717 &NewLoad](
unsigned Index) ->
Value * {
3718 assert(Index < InterleaveFactor &&
"Illegal group index");
3719 if (State.VF.isScalable())
3720 return State.Builder.CreateExtractValue(NewLoad, Index);
3726 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
3730 for (
unsigned I = 0, J = 0;
I < InterleaveFactor; ++
I) {
3737 Value *StridedVec = CreateStridedVector(
I);
3740 if (Member->getType() != ScalarTy) {
3747 StridedVec = State.Builder.CreateVectorReverse(StridedVec,
"reverse");
3749 State.set(VPDefs[J], StridedVec);
3759 Value *MaskForGaps =
3761 assert(((MaskForGaps !=
nullptr) == NeedsMaskForGaps) &&
3762 "Mismatch between NeedsMaskForGaps and MaskForGaps");
3766 unsigned StoredIdx = 0;
3767 for (
unsigned i = 0; i < InterleaveFactor; i++) {
3769 "Fail to get a member from an interleaved store group");
3779 Value *StoredVec = State.
get(StoredValues[StoredIdx]);
3787 if (StoredVec->
getType() != SubVT)
3796 if (BlockInMask || MaskForGaps) {
3797 Value *GroupMask = CreateGroupMask(MaskForGaps);
3799 IVec, ResAddr, Group->
getAlign(), GroupMask);
3809#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3812 O << Indent <<
"INTERLEAVE-GROUP with factor " << IG->getFactor() <<
" at ";
3813 IG->getInsertPos()->printAsOperand(O,
false);
3823 for (
unsigned i = 0; i < IG->getFactor(); ++i) {
3824 if (!IG->getMember(i))
3827 O <<
"\n" << Indent <<
" store ";
3829 O <<
" to index " << i;
3831 O <<
"\n" << Indent <<
" ";
3833 O <<
" = load from index " << i;
3844 unsigned InsertPosIdx = 0;
3845 for (
unsigned Idx = 0; IG->getFactor(); ++
Idx)
3846 if (
auto *Member = IG->getMember(
Idx)) {
3847 if (Member == InsertPos)
3854 auto *VectorTy = cast<VectorType>(
toVectorTy(ValTy, VF));
3857 unsigned InterleaveFactor = IG->getFactor();
3862 for (
unsigned IF = 0; IF < InterleaveFactor; IF++)
3863 if (IG->getMember(IF))
3868 InsertPos->
getOpcode(), WideVecTy, IG->getFactor(), Indices,
3871 if (!IG->isReverse())
3874 return Cost + IG->getNumMembers() *
3876 VectorTy, VectorTy, {}, Ctx.
CostKind,
3880#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3883 O << Indent <<
"EMIT ";
3885 O <<
" = CANONICAL-INDUCTION ";
3891 return IsScalarAfterVectorization &&
3895#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3899 "unexpected number of operands");
3900 O << Indent <<
"EMIT ";
3902 O <<
" = WIDEN-POINTER-INDUCTION ";
3918 O << Indent <<
"EMIT ";
3920 O <<
" = EXPAND SCEV " << *Expr;
3938 Value *CanonicalVectorIV = Builder.
CreateAdd(VStart, VStep,
"vec.iv");
3939 State.
set(
this, CanonicalVectorIV);
3942#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3945 O << Indent <<
"EMIT ";
3947 O <<
" = WIDEN-CANONICAL-INDUCTION ";
3953 auto &Builder = State.
Builder;
3958 ? VectorInit->getType()
3965 auto *One = ConstantInt::get(IdxTy, 1);
3969 auto *LastIdx = Builder.
CreateSub(RuntimeVF, One);
3977 Phi->addIncoming(VectorInit, VectorPH);
3978 State.
set(
this, Phi);
3990#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3993 O << Indent <<
"FIRST-ORDER-RECURRENCE-PHI ";
4011 bool ScalarPHI = State.
VF.
isScalar() || IsInLoop;
4012 Value *StartV = State.
get(StartVPV, ScalarPHI);
4017 "recipe must be in the vector loop header");
4020 State.
set(
this, Phi, IsInLoop);
4022 Phi->addIncoming(StartV, VectorPH);
4025#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4028 O << Indent <<
"WIDEN-REDUCTION-PHI ";
4033 if (VFScaleFactor != 1)
4034 O <<
" (VF scaled by 1/" << VFScaleFactor <<
")";
4042 State.
set(
this, VecPhi);
4045#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4048 O << Indent <<
"WIDEN-PHI ";
4064 Phi->addIncoming(StartMask, VectorPH);
4065 State.
set(
this, Phi);
4068#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4071 O << Indent <<
"ACTIVE-LANE-MASK-PHI ";
4079#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4082 O << Indent <<
"EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI ";
static SDValue Widen(SelectionDAG *CurDAG, SDValue N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
loop Loop Strength Reduction
This file provides a LoopVectorizationPlanner class.
mir Rename Register Operands
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
This file contains the declarations of different VPlan-related auxiliary helpers.
static Instruction * createReverseEVL(IRBuilderBase &Builder, Value *Operand, Value *EVL, const Twine &Name)
Use all-true mask for reverse rather than actual mask, as it avoids a dependence w/o affecting the re...
static Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static InstructionCost getCostForIntrinsics(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost for the intrinsic ID with Operands, produced by R.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
static Type * getGEPIndexTy(bool IsScalable, bool IsReverse, bool IsUnitStride, unsigned CurrentPart, IRBuilderBase &Builder)
static void scalarizeInstruction(const Instruction *Instr, VPReplicateRecipe *RepRecipe, const VPLane &Lane, VPTransformState &State)
A helper function to scalarize a single Instruction in the innermost loop.
static Constant * getSignedIntOrFpConstant(Type *Ty, int64_t C)
A helper function that returns an integer or floating-point constant with value C.
static BranchInst * createCondBranch(Value *Cond, VPBasicBlock *VPBB, VPTransformState &State)
Create a conditional branch using Cond branching to the successors of VPBB.
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Conditional or Unconditional Branch instruction.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
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 Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_UGT
unsigned greater than
@ ICMP_ULT
unsigned less than
static LLVM_ABI StringRef getPredicateName(Predicate P)
This is the shared class of boolean and integer constants.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
This is an important base class in LLVM.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
constexpr bool isVector() const
One or more elements.
static constexpr ElementCount getScalable(ScalarTy MinVal)
static constexpr ElementCount getFixed(ScalarTy MinVal)
constexpr bool isScalar() const
Exactly one element.
Convenience struct for specifying and reasoning about fast-math flags.
void setAllowContract(bool B=true)
bool noSignedZeros() const
void setAllowReciprocal(bool B=true)
bool allowReciprocal() const
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
void setNoSignedZeros(bool B=true)
bool allowReassoc() const
Flag queries.
void setNoNaNs(bool B=true)
void setAllowReassoc(bool B=true)
Flag setters.
void setApproxFunc(bool B=true)
void setNoInfs(bool B=true)
bool allowContract() const
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
ArrayRef< Type * > params() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
bool willReturn() const
Determine if the function will return.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
bool doesNotThrow() const
Determine if the function cannot unwind.
Type * getReturnType() const
Returns the type of the ret val.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
Common base class shared among various IRBuilders.
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Value * CreateSIToFP(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
LLVM_ABI Value * CreateVectorSplice(Value *V1, Value *V2, int64_t Imm, const Twine &Name="")
Return a vector splice intrinsic if using scalable vectors, otherwise return a shufflevector.
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
ConstantInt * getTrue()
Get the constant value for i1 true.
LLVM_ABI CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFreeze(Value *V, const Twine &Name="")
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Value * CreateVScale(Type *Ty, const Twine &Name="")
Create a call to llvm.vscale.<Ty>().
BasicBlock * GetInsertBlock() const
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
LLVM_ABI Value * CreateVectorReverse(Value *V, const Twine &Name="")
Return a vector value that contains the vector V reversed.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateFCmpFMF(CmpInst::Predicate P, Value *LHS, Value *RHS, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
LLVM_ABI CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Value * CreateNot(Value *V, const Twine &Name="")
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
LLVM_ABI Value * CreateNAryOp(unsigned Opc, ArrayRef< Value * > Ops, const Twine &Name="", MDNode *FPMathTag=nullptr)
Create either a UnaryOperator or BinaryOperator depending on Opc.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
LLVMContext & getContext() const
LLVM_ABI CallInst * CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, Value *Mask)
Create a call to Masked Store intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
ConstantInt * getFalse()
Get the constant value for i1 false.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="")
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
LLVM_ABI Value * CreateVectorInterleave(ArrayRef< Value * > Ops, const Twine &Name="")
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
LLVM_ABI Value * CreateStepVector(Type *DstType, const Twine &Name="")
Creates a vector of type DstType with the linear sequence <0, 1, ...>
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
LLVM_ABI CallInst * CreateMaskedScatter(Value *Val, Value *Ptrs, Align Alignment, Value *Mask=nullptr)
Create a call to Masked Scatter intrinsic.
LLVM_ABI CallInst * CreateMaskedGather(Type *Ty, Value *Ptrs, Align Alignment, Value *Mask=nullptr, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Gather intrinsic.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This instruction inserts a single (scalar) element into a VectorType value.
VectorType * getType() const
Overload to return most specific vector type.
static InstructionCost getInvalid(CostType Val=0)
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const char * getOpcodeName() const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
InstTy * getInsertPos() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
BlockT * getHeader() const
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
std::pair< MDNode *, MDNode * > getNoAliasMetadataFor(const Instruction *OrigInst) const
Returns a pair containing the alias_scope and noalias metadata nodes for OrigInst,...
LLVM_ABI void print(raw_ostream &OS, const SlotIndexes *=nullptr, bool IsStandalone=true) const
A Module instance is used to store all the information related to an LLVM module.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static bool isSignedRecurrenceKind(RecurKind Kind)
Returns true if recurrece kind is a signed redux kind.
unsigned getOpcode() const
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindLastIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
const SDValue & getOperand(unsigned Num) const
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Vector takeVector()
Clear the SetVector and return the underlying vector.
This class provides computation of slot numbers for LLVM Assembly writing.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isPointerTy() const
True if this is an instance of PointerType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
bool isStructTy() const
True if this is an instance of StructType.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isVoidTy() const
Return true if this is 'void'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
value_op_iterator value_op_end()
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
value_op_iterator value_op_begin()
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
void insert(VPRecipeBase *Recipe, iterator InsertPt)
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenMemoryRecipe.
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
VPRegionBlock * getParent()
const VPBasicBlock * getExitingBasicBlock() const
const VPBlocksTy & getPredecessors() const
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
const VPBlocksTy & getSuccessors() const
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPBranchOnMaskRecipe.
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch.
VPlan-based builder utility analogous to IRBuilder.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
This class augments a recipe with a set of VPValues defined by the recipe.
void dump() const
Dump the VPDef to stderr (for debugging).
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
ArrayRef< VPValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
unsigned getVPDefID() const
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStepValue() const
VPValue * getStartValue() const
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void decompose()
Insert the recipes of the expression back into the VPlan, directly before the current recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool mayHaveSideEffects() const
Returns true if this expression contains recipes that may have side effects.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
bool mayReadOrWriteMemory() const
Returns true if this expression contains recipes that may read from or write to memory.
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHistogramRecipe.
VPValue * getMask() const
Return the mask operand if one was provided, or a null pointer if all lanes should be executed uncond...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Class to record and manage LLVM IR flags.
bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
CmpInst::Predicate getPredicate() const
bool hasNoSignedWrap() const
GEPNoWrapFlags getGEPNoWrapFlags() const
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
DisjointFlagsTy DisjointFlags
bool hasNoUnsignedWrap() const
NonNegFlagsTy NonNegFlags
void applyFlags(Instruction &I) const
Apply the IR flags to I.
A recipe to wrap on original IR instruction not to be modified during execution, except for PHIs.
Instruction & getInstruction() const
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void extractLastLaneOfFirstOperand(VPBuilder &Builder)
Update the recipes first operand to the last lane of the operand using Builder.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPIRInstruction.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the instruction.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
@ ExtractPenultimateElement
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
@ FirstOrderRecurrenceSplice
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
@ BuildVector
Creates a fixed-width vector containing all operands.
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
@ VScale
Returns the value for vscale.
@ CanonicalIVIncrementForPart
@ CalculateTripCountMinusVF
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
bool opcodeMayReadOrWriteFromMemory() const
Returns true if the underlying opcode may read from or write to memory.
LLVM_DUMP_METHOD void dump() const
Print the VPInstruction to dbgs() (for debugging).
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
unsigned getOpcode() const
bool onlyFirstPartUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the VPInstruction to O.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
bool isSingleScalar() const
Returns true if this VPInstruction's operands are single scalars and the result is also a single scal...
void execute(VPTransformState &State) override
Generate the instruction.
VPValue * getAddr() const
Return the address accessed by this recipe.
VPValue * getMask() const
Return the mask used by this recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Instruction * getInsertPos() const
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInterleaveRecipe.
unsigned getNumStoreOperands() const
Returns the number of stored operands of this interleave group.
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
static VPLane getLastLaneForVF(const ElementCount &VF)
static VPLane getLaneFromEnd(const ElementCount &VF, unsigned Offset)
static VPLane getFirstLane()
void execute(VPTransformState &State) override
Generate the reduction in the loop.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPPartialReductionRecipe.
unsigned getOpcode() const
Get the binary op's opcode.
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
void removeIncomingValueFor(VPBlockBase *IncomingBlock) const
Removes the incoming value for IncomingBlock, which must be a predecessor.
const VPBasicBlock * getIncomingBlock(unsigned Idx) const
Returns the incoming block with index Idx.
detail::zippy< llvm::detail::zip_first, VPUser::const_operand_range, const_incoming_blocks_range > incoming_values_and_blocks() const
Returns an iterator range over pairs of incoming values and corresponding incoming blocks.
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
void execute(VPTransformState &State) override
Generates phi nodes for live-outs (from a replicate region) as needed to retain SSA form.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
bool isPhi() const
Returns true for PHI-like recipes.
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
virtual InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
VPBasicBlock * getParent()
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this recipe, taking into account if the cost computation should be skipped and the...
bool isScalarCast() const
Return true if the recipe is a scalar cast.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
void execute(VPTransformState &State) override
Generate the reduction in the loop.
VPValue * getEVL() const
The VPValue of the explicit vector length.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool isConditional() const
Return true if the in-loop reduction is conditional.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of VPReductionRecipe.
VPValue * getVecOp() const
The VPValue of the vector value to be reduced.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getCondOp() const
The VPValue of the condition for the block.
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
bool isOrdered() const
Return true if the in-loop reduction is ordered.
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
void execute(VPTransformState &State) override
Generate the reduction in the loop.
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPReplicateRecipe.
unsigned getOpcode() const
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStepValue() const
void execute(VPTransformState &State) override
Generate the scalarized versions of the phi node as needed by their users.
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
This class can be used to assign names to VPValues.
LLVMContext & getContext()
Return the LLVMContext used by the analysis.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
Helper to access the operand that contains the unroll part for this recipe after unrolling.
VPValue * getUnrollPartOperand(const VPUser &U) const
Return the VPValue operand containing the unroll part or null if there is no such operand.
unsigned getUnrollPart(const VPUser &U) const
Return the unroll part.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
void setOperand(unsigned I, VPValue *New)
unsigned getNumOperands() const
operand_iterator op_begin()
VPValue * getOperand(unsigned N) const
virtual bool onlyFirstLaneUsed(const VPValue *Op) const
Returns true if the VPUser only uses the first lane of operand Op.
void addOperand(VPValue *Operand)
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
friend class VPExpressionRecipe
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
bool hasMoreThanOneUniqueUser() const
Returns true if the value has more than one unique user.
Value * getLiveInIRValue() const
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
void replaceAllUsesWith(VPValue *New)
user_iterator user_begin()
unsigned getNumUsers() const
bool isLiveIn() const
Returns true if this VPValue is a live-in, i.e. defined outside the VPlan.
VPDef * Def
Pointer to the VPDef that defines this VPValue.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Function * getCalledScalarFunction() const
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCallRecipe.
void execute(VPTransformState &State) override
Produce a widened version of the call instruction.
void execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with start = {<Part*VF,...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getResultType() const
Returns the result type of the cast.
void execute(VPTransformState &State) override
Produce widened copies of the cast.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
VPValue * getStepValue()
Returns the step value of the induction.
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Type * getScalarType() const
Returns the scalar type of the induction.
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
StringRef getIntrinsicName() const
Return to name of the intrinsic as string.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getResultType() const
Return the scalar return type of the intrinsic.
void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector intrinsic.
bool IsMasked
Whether the memory access is masked.
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
VPValue * getMask() const
Return the mask used by this recipe.
VPValue * getAddr() const
Return the address accessed by this recipe.
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenRecipe.
void execute(VPTransformState &State) override
Produce a widened instruction using the opcode and operands of the recipe, processing State....
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getOpcode() const
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
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.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
const ParentTy * getParent() const
self_iterator getIterator()
base_list_type::iterator iterator
iterator erase(iterator where)
pointer remove(iterator &IT)
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ C
The default llvm calling convention, compatible with C.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
LLVM_ABI Value * createFindLastIVReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind, Value *Start, Value *Sentinel)
Create a reduction of the given vector Src for a reduction of the kind RecurKind::FindLastIV.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
LLVM_ABI Value * createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
LLVM_ABI llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Type * toVectorizedTy(Type *Ty, ElementCount EC)
A helper for converting to vectorized types.
cl::opt< unsigned > ForceTargetInstructionCost
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
DWARFExpression::Operation Op
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI Value * createOrderedReduction(IRBuilderBase &B, RecurKind RdxKind, Value *Src, Value *Start)
Create an ordered reduction intrinsic using the given recurrence kind RdxKind.
ArrayRef< Type * > getContainedTypes(Type *const &Ty)
Returns the types contained in Ty.
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
LLVM_ABI Value * createAnyOfReduction(IRBuilderBase &B, Value *Src, Value *InitVal, PHINode *OrigPhi)
Create a reduction of the given vector Src for a reduction of kind RecurKind::AnyOf.
LLVM_ABI bool isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Struct to hold various analysis needed for cost computations.
TargetTransformInfo::OperandValueInfo getOperandInfo(VPValue *V) const
Returns the OperandInfo for V, if it is a live-in.
bool skipCostComputation(Instruction *UI, bool IsVector) const
Return true if the cost for UI shouldn't be computed, e.g.
InstructionCost getLegacyCost(Instruction *UI, ElementCount VF) const
Return the cost for UI with VF using the legacy cost model as fallback until computing the cost of al...
TargetTransformInfo::TargetCostKind CostKind
const TargetLibraryInfo & TLI
const TargetTransformInfo & TTI
SmallPtrSet< Instruction *, 8 > SkipCostComputation
void execute(VPTransformState &State) override
Generate the phi nodes.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this first-order recurrence phi recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use cast/dyn_cast/isa and exec...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the instruction.
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
std::optional< InstructionCost > getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
void execute(VPTransformState &State) override
Generate the wide load or gather.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate a wide load or gather.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool isInvariantCond() const
VPValue * getCond() const
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenSelectRecipe.
void execute(VPTransformState &State) override
Produce a widened version of the select instruction.
VPValue * getStoredValue() const
Return the address accessed by this recipe.
void execute(VPTransformState &State) override
Generate the wide store or scatter.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
void execute(VPTransformState &State) override
Generate a wide store or scatter.
VPValue * getStoredValue() const
Return the value stored by this recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.