LLVM 24.0.0git
RISCVTargetTransformInfo.cpp
Go to the documentation of this file.
1//===-- RISCVTargetTransformInfo.cpp - RISC-V specific TTI ----------------===//
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
11#include "RISCVVectorUtils.h"
12#include "llvm/ADT/STLExtras.h"
19#include "llvm/IR/IntrinsicsRISCV.h"
22#include <cmath>
23#include <limits>
24#include <optional>
25using namespace llvm;
26using namespace llvm::PatternMatch;
27
28#define DEBUG_TYPE "riscvtti"
29
31RISCVTTIImpl::getRISCVInstructionCost(ArrayRef<unsigned> OpCodes, MVT VT,
32 TTI::TargetCostKind CostKind) const {
33 // Check if the type is valid for all CostKind
34 if (!VT.isVector())
36 size_t NumInstr = OpCodes.size();
37 if (CostKind == TTI::TCK_CodeSize)
38 return NumInstr;
39 InstructionCost LMULCost = TLI->getLMULCost(VT);
40 if ((CostKind != TTI::TCK_RecipThroughput) && (CostKind != TTI::TCK_Latency))
41 return LMULCost * NumInstr;
42 InstructionCost Cost = 0;
43 for (auto Op : OpCodes) {
44 switch (Op) {
45 case RISCV::VRGATHER_VI:
46 Cost += TLI->getVRGatherVICost(VT);
47 break;
48 case RISCV::VRGATHER_VV:
49 Cost += TLI->getVRGatherVVCost(VT);
50 break;
51 case RISCV::VSLIDEUP_VI:
52 case RISCV::VSLIDEDOWN_VI:
53 Cost += TLI->getVSlideVICost(VT);
54 break;
55 case RISCV::VSLIDEUP_VX:
56 case RISCV::VSLIDEDOWN_VX:
57 Cost += TLI->getVSlideVXCost(VT);
58 break;
59 case RISCV::VREDMAX_VS:
60 case RISCV::VREDMIN_VS:
61 case RISCV::VREDMAXU_VS:
62 case RISCV::VREDMINU_VS:
63 case RISCV::VREDSUM_VS:
64 case RISCV::VREDAND_VS:
65 case RISCV::VREDOR_VS:
66 case RISCV::VREDXOR_VS:
67 case RISCV::VFREDMAX_VS:
68 case RISCV::VFREDMIN_VS:
69 case RISCV::VFREDUSUM_VS: {
70 unsigned VL = VT.getVectorMinNumElements();
71 if (!VT.isFixedLengthVector())
72 VL *= *getVScaleForTuning();
73 Cost += Log2_32_Ceil(VL);
74 break;
75 }
76 case RISCV::VFREDOSUM_VS: {
77 unsigned VL = VT.getVectorMinNumElements();
78 if (!VT.isFixedLengthVector())
79 VL *= *getVScaleForTuning();
80 Cost += VL;
81 break;
82 }
83 case RISCV::VMV_X_S:
84 case RISCV::VFMV_F_S:
85 // Domain crossings from vector -> scalar are usually more expensive.
86 Cost += 2;
87 break;
88 case RISCV::VMV_S_X:
89 case RISCV::VFMV_S_F:
90 case RISCV::VMOR_MM:
91 case RISCV::VMXOR_MM:
92 case RISCV::VMAND_MM:
93 case RISCV::VMANDN_MM:
94 case RISCV::VMNAND_MM:
95 case RISCV::VCPOP_M:
96 case RISCV::VFIRST_M:
97 Cost += 1;
98 break;
99 case RISCV::VDIV_VV:
100 case RISCV::VREM_VV:
101 Cost += LMULCost * TTI::TCC_Expensive;
102 break;
103 default:
104 Cost += LMULCost;
105 }
106 }
107 return Cost;
108}
109
111 const RISCVSubtarget *ST,
112 const APInt &Imm, Type *Ty,
113 TTI::TargetCostKind CostKind,
114 bool FreeZeroes) {
115 assert(Ty->isIntegerTy() &&
116 "getIntImmCost can only estimate cost of materialising integers");
117
118 // We have a Zero register, so 0 is always free.
119 if (Imm == 0)
120 return TTI::TCC_Free;
121
122 // Otherwise, we check how many instructions it will take to materialise.
123 return RISCVMatInt::getIntMatCost(Imm, DL.getTypeSizeInBits(Ty), *ST,
124 /*CompressionCost=*/false, FreeZeroes);
125}
126
129 TTI::TargetCostKind CostKind) const {
130 return getIntImmCostImpl(getDataLayout(), getST(), Imm, Ty, CostKind, false);
131}
132
133// Look for patterns of shift followed by AND that can be turned into a pair of
134// shifts. We won't need to materialize an immediate for the AND so these can
135// be considered free.
136static bool canUseShiftPair(Instruction *Inst, const APInt &Imm) {
137 uint64_t Mask = Imm.getZExtValue();
138 auto *BO = dyn_cast<BinaryOperator>(Inst->getOperand(0));
139 if (!BO || !BO->hasOneUse())
140 return false;
141
142 if (BO->getOpcode() != Instruction::Shl)
143 return false;
144
145 if (!isa<ConstantInt>(BO->getOperand(1)))
146 return false;
147
148 unsigned ShAmt = cast<ConstantInt>(BO->getOperand(1))->getZExtValue();
149 // (and (shl x, c2), c1) will be matched to (srli (slli x, c2+c3), c3) if c1
150 // is a mask shifted by c2 bits with c3 leading zeros.
151 if (isShiftedMask_64(Mask)) {
152 unsigned Trailing = llvm::countr_zero(Mask);
153 if (ShAmt == Trailing)
154 return true;
155 }
156
157 return false;
158}
159
160// If this is i64 AND is part of (X & -(1 << C1) & 0xffffffff) == C2 << C1),
161// DAGCombiner can convert this to (sraiw X, C1) == sext(C2) for RV64. On RV32,
162// the type will be split so only the lower 32 bits need to be compared using
163// (srai/srli X, C) == C2.
164static bool canUseShiftCmp(Instruction *Inst, const APInt &Imm) {
165 if (!Inst->hasOneUse())
166 return false;
167
168 // Look for equality comparison.
169 auto *Cmp = dyn_cast<ICmpInst>(*Inst->user_begin());
170 if (!Cmp || !Cmp->isEquality())
171 return false;
172
173 // Right hand side of comparison should be a constant.
174 auto *C = dyn_cast<ConstantInt>(Cmp->getOperand(1));
175 if (!C)
176 return false;
177
178 uint64_t Mask = Imm.getZExtValue();
179
180 // Mask should be of the form -(1 << C) in the lower 32 bits.
181 if (!isUInt<32>(Mask) || !isPowerOf2_32(-uint32_t(Mask)))
182 return false;
183
184 // Comparison constant should be a subset of Mask.
185 uint64_t CmpC = C->getZExtValue();
186 if ((CmpC & Mask) != CmpC)
187 return false;
188
189 // We'll need to sign extend the comparison constant and shift it right. Make
190 // sure the new constant can use addi/xori+seqz/snez.
191 unsigned ShiftBits = llvm::countr_zero(Mask);
192 int64_t NewCmpC = SignExtend64<32>(CmpC) >> ShiftBits;
193 return NewCmpC >= -2048 && NewCmpC <= 2048;
194}
195
197 const APInt &Imm, Type *Ty,
198 TTI::TargetCostKind CostKind,
199 Instruction *Inst) const {
200 assert(Ty->isIntegerTy() &&
201 "getIntImmCost can only estimate cost of materialising integers");
202
203 // We have a Zero register, so 0 is always free.
204 if (Imm == 0)
205 return TTI::TCC_Free;
206
207 // Some instructions in RISC-V can take a 12-bit immediate. Some of these are
208 // commutative, in others the immediate comes from a specific argument index.
209 bool Takes12BitImm = false;
210 unsigned ImmArgIdx = ~0U;
211
212 switch (Opcode) {
213 case Instruction::GetElementPtr:
214 // Never hoist any arguments to a GetElementPtr. CodeGenPrepare will
215 // split up large offsets in GEP into better parts than ConstantHoisting
216 // can.
217 return TTI::TCC_Free;
218 case Instruction::Store: {
219 // Use the materialization cost regardless of if it's the address or the
220 // value that is constant, except for if the store is misaligned and
221 // misaligned accesses are not legal (experience shows constant hoisting
222 // can sometimes be harmful in such cases).
223 if (Idx == 1 || !Inst)
224 return getIntImmCostImpl(getDataLayout(), getST(), Imm, Ty, CostKind,
225 /*FreeZeroes=*/true);
226
227 StoreInst *ST = cast<StoreInst>(Inst);
228 if (!getTLI()->allowsMemoryAccessForAlignment(
229 Ty->getContext(), DL, getTLI()->getValueType(DL, Ty),
230 ST->getPointerAddressSpace(), ST->getAlign()))
231 return TTI::TCC_Free;
232
233 return getIntImmCostImpl(getDataLayout(), getST(), Imm, Ty, CostKind,
234 /*FreeZeroes=*/true);
235 }
236 case Instruction::Load:
237 // If the address is a constant, use the materialization cost.
238 return getIntImmCost(Imm, Ty, CostKind);
239 case Instruction::And:
240 // zext.h
241 if (Imm == UINT64_C(0xffff) && ST->hasStdExtZbb())
242 return TTI::TCC_Free;
243 // zext.w
244 if (Imm == UINT64_C(0xffffffff) && (!ST->is64Bit() || ST->hasStdExtZba()))
245 return TTI::TCC_Free;
246 // bclri
247 if (ST->hasStdExtZbs() && (~Imm).isPowerOf2())
248 return TTI::TCC_Free;
249 if (Inst && Idx == 1 && Imm.getBitWidth() <= ST->getXLen() &&
250 canUseShiftPair(Inst, Imm))
251 return TTI::TCC_Free;
252 if (Inst && Idx == 1 && Imm.getBitWidth() == 64 &&
253 canUseShiftCmp(Inst, Imm))
254 return TTI::TCC_Free;
255 Takes12BitImm = true;
256 break;
257 case Instruction::Add:
258 Takes12BitImm = true;
259 break;
260 case Instruction::Or:
261 case Instruction::Xor:
262 // bseti/binvi
263 if (ST->hasStdExtZbs() && Imm.isPowerOf2())
264 return TTI::TCC_Free;
265 Takes12BitImm = true;
266 break;
267 case Instruction::Mul:
268 // Power of 2 is a shift. Negated power of 2 is a shift and a negate.
269 if (Imm.isPowerOf2() || Imm.isNegatedPowerOf2())
270 return TTI::TCC_Free;
271 // One more or less than a power of 2 can use SLLI+ADD/SUB.
272 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2())
273 return TTI::TCC_Free;
274 // FIXME: There is no MULI instruction.
275 Takes12BitImm = true;
276 break;
277 case Instruction::Sub:
278 case Instruction::Shl:
279 case Instruction::LShr:
280 case Instruction::AShr:
281 Takes12BitImm = true;
282 ImmArgIdx = 1;
283 break;
284 default:
285 break;
286 }
287
288 if (Takes12BitImm) {
289 // Check immediate is the correct argument...
290 if (Instruction::isCommutative(Opcode) || Idx == ImmArgIdx) {
291 // ... and fits into the 12-bit immediate.
292 if (Imm.getSignificantBits() <= 64 &&
293 getTLI()->isLegalAddImmediate(Imm.getSExtValue())) {
294 return TTI::TCC_Free;
295 }
296 }
297
298 // Otherwise, use the full materialisation cost.
299 return getIntImmCost(Imm, Ty, CostKind);
300 }
301
302 // By default, prevent hoisting.
303 return TTI::TCC_Free;
304}
305
307 const ICmpInst &Cond, const APInt &PostIncExitValue) const {
308 if (!ST->hasStdExtZibi())
309 return false;
310
311 // Relational comparisons against zero and some adjacent constants can
312 // already lower to a single branch against x0.
313 const auto Pred = Cond.getPredicate();
314 const auto *C = dyn_cast<ConstantInt>(Cond.getOperand(1));
315 if (C && (C->isZero() ||
316 (C->isMinusOne() &&
317 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE)) ||
318 (C->isOne() &&
319 (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE ||
320 Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))))
321 return false;
322
323 int64_t Imm = PostIncExitValue.getSExtValue();
324 return Imm == -1 || (Imm >= 1 && Imm <= 31);
325}
326
329 const APInt &Imm, Type *Ty,
330 TTI::TargetCostKind CostKind) const {
331 // Prevent hoisting in unknown cases.
332 return TTI::TCC_Free;
333}
334
336 return ST->hasVInstructions();
337}
338
340 unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType,
342 TTI::PartialReductionExtendKind OpBExtend, std::optional<unsigned> BinOp,
343 TTI::TargetCostKind CostKind, std::optional<FastMathFlags> FMF) const {
344 if (Opcode == Instruction::FAdd)
346
347 // zve32x is broken for partial_reduce_umla, but let's make sure we
348 // don't generate them.
349 // vdot4a* reduces four i8 products into an i32 result; an i64 accumulator is
350 // additionally supported by widening the i32 partial sums to i64 (see
351 // lowerPARTIAL_REDUCE_MLA). VF is the number of i8 input elements, so the
352 // reduction factor is AccumBits / 8 (4 for i32, 8 for i64).
353 if (!ST->hasStdExtZvdot4a8i() || ST->getELen() < 64 ||
354 Opcode != Instruction::Add || !BinOp || *BinOp != Instruction::Mul ||
355 InputTypeA != InputTypeB || !InputTypeA->isIntegerTy(8) ||
356 (!AccumType->isIntegerTy(32) && !AccumType->isIntegerTy(64)))
358
359 unsigned Ratio = AccumType->getScalarSizeInBits() / 8;
360 if (!VF.isKnownMultipleOf(Ratio))
362
363 // Cost of the vdot4a* itself, which operates on the i32 intermediate type
364 // holding VF/4 elements.
365 Type *DotTp = VectorType::get(Type::getInt32Ty(AccumType->getContext()),
366 VF.divideCoefficientBy(4));
367 std::pair<InstructionCost, MVT> DotLT = getTypeLegalizationCost(DotTp);
368 // Note: Asuming all vdot4a* variants are equal cost
370 DotLT.first *
371 getRISCVInstructionCost(RISCV::VDOT4A_VV, DotLT.second, CostKind);
372
373 // Account for reducing the i32 partial sums down to the i64 accumulator's
374 // element count and accumulating into it (see lowerPARTIAL_REDUCE_MLA), which
375 // has two shapes depending on the accumulator's LMUL.
376 if (AccumType->isIntegerTy(64)) {
377 LLVMContext &Ctx = AccumType->getContext();
378 Type *I32Ty = Type::getInt32Ty(Ctx);
379 ElementCount AccVF = VF.divideCoefficientBy(Ratio);
380 std::pair<InstructionCost, MVT> AccLT =
381 getTypeLegalizationCost(VectorType::get(AccumType, AccVF));
382
383 // When the i32 subvectors of a single-vector scalable accumulator are a
384 // fractional LMUL, extracting the high subvector would need a vslidedown,
385 // so instead the i32 dot result is widened to i64 first (vsext.vf2 /
386 // vzext.vf2) and then reduced and accumulated with register-aligned i64
387 // vadd.vv.
388 bool WidenFirst = false;
389 if (VF.isScalable() && AccLT.second.isScalableVector()) {
390 MVT NarrowMVT = AccLT.second.changeVectorElementType(MVT::i32);
391 WidenFirst =
393 .second;
394 }
395
396 if (WidenFirst) {
397 // The widened i64 dot result has VF/4 elements, i.e. twice the
398 // accumulator's element count, so the reduction plus the accumulate are
399 // two i64 vadd.vv.
400 std::pair<InstructionCost, MVT> WideLT = getTypeLegalizationCost(
401 VectorType::get(AccumType, VF.divideCoefficientBy(4)));
402 Cost +=
403 WideLT.first * getRISCVInstructionCost(RISCV::VSEXT_VF2,
404 WideLT.second, CostKind) +
405 2 * AccLT.first *
406 getRISCVInstructionCost(RISCV::VADD_VV, AccLT.second, CostKind);
407 } else {
408 // Otherwise the scale-4 i32 sums are halved with a single i32 vadd.vv,
409 // then widened and added into the i64 result with a vwadd.wv.
410 std::pair<InstructionCost, MVT> RedLT =
412 Cost += RedLT.first * getRISCVInstructionCost(RISCV::VADD_VV,
413 RedLT.second, CostKind) +
414 AccLT.first * getRISCVInstructionCost(RISCV::VWADD_WV,
415 AccLT.second, CostKind);
416 // Fixed-length vectors extract the high i32 subvector with a vslidedown.
417 if (VF.isFixed())
418 Cost += DotLT.first * getRISCVInstructionCost(RISCV::VSLIDEDOWN_VI,
419 DotLT.second, CostKind);
420 }
421 }
422
423 return Cost;
424}
425
427 // Currently, the ExpandReductions pass can't expand scalable-vector
428 // reductions, but we still request expansion as RVV doesn't support certain
429 // reductions and the SelectionDAG can't legalize them either.
430 switch (II->getIntrinsicID()) {
431 default:
432 return false;
433 // These reductions have no equivalent in RVV
434 case Intrinsic::vector_reduce_mul:
435 case Intrinsic::vector_reduce_fmul:
436 return true;
437 }
438}
439
440std::optional<unsigned> RISCVTTIImpl::getVScaleForTuning() const {
441 if (ST->hasVInstructions())
442 if (unsigned MinVLen = ST->getRealMinVLen();
443 MinVLen >= RISCV::RVVBitsPerBlock)
444 return MinVLen / RISCV::RVVBitsPerBlock;
446}
447
450 unsigned LMUL = llvm::bit_floor(
451 std::clamp<unsigned>(ST->getCLOpts().v_register_bit_width_lmul, 1, 8));
452 switch (K) {
454 return TypeSize::getFixed(ST->getXLen());
456 return TypeSize::getFixed(
457 ST->useRVVForFixedLengthVectors() ? LMUL * ST->getRealMinVLen() : 0);
460 (ST->hasVInstructions() &&
461 ST->getRealMinVLen() >= RISCV::RVVBitsPerBlock)
463 : 0);
464 }
465
466 llvm_unreachable("Unsupported register kind");
467}
468
469InstructionCost RISCVTTIImpl::getStaticDataAddrGenerationCost(
470 const TTI::TargetCostKind CostKind) const {
471 switch (CostKind) {
474 // Always 2 instructions
475 return 2;
476 case TTI::TCK_Latency:
478 // Depending on the memory model the address generation will
479 // require AUIPC + ADDI (medany) or LUI + ADDI (medlow). Don't
480 // have a way of getting this information here, so conservatively
481 // require both.
482 // In practice, these are generally implemented together.
483 return (ST->hasAUIPCADDIFusion() && ST->hasLUIADDIFusion()) ? 1 : 2;
484 }
485 llvm_unreachable("Unsupported cost kind");
486}
487
489RISCVTTIImpl::getConstantPoolLoadCost(Type *Ty,
490 TTI::TargetCostKind CostKind) const {
491 // Add a cost of address generation + the cost of the load. The address
492 // is expected to be a PC relative offset to a constant pool entry
493 // using auipc/addi.
495 Cost = getStaticDataAddrGenerationCost(CostKind) +
496 getMemoryOpCost(Instruction::Load, Ty, DL.getABITypeAlign(Ty),
497 /*AddressSpace=*/0, CostKind);
498 // Estimate the amount of 4 byte instructions that could fit
499 // instead of the constant pool, ignoring any extra padding.
500 if (CostKind == TTI::TCK_CodeSize)
501 Cost += ((InstructionCost)DL.getTypeAllocSize(Ty)) / 4;
502 return Cost;
503}
504
505static bool isRepeatedConcatMask(ArrayRef<int> Mask, int &SubVectorSize) {
506 unsigned Size = Mask.size();
507 if (!isPowerOf2_32(Size))
508 return false;
509 for (unsigned I = 0; I != Size; ++I) {
510 if (static_cast<unsigned>(Mask[I]) == I)
511 continue;
512 if (Mask[I] != 0)
513 return false;
514 if (Size % I != 0)
515 return false;
516 for (unsigned J = I + 1; J != Size; ++J)
517 // Check the pattern is repeated.
518 if (static_cast<unsigned>(Mask[J]) != J % I)
519 return false;
520 SubVectorSize = I;
521 return true;
522 }
523 // That means Mask is <0, 1, 2, 3>. This is not a concatenation.
524 return false;
525}
526
528 LLVMContext &C) {
529 assert((DataVT.getScalarSizeInBits() != 8 ||
530 DataVT.getVectorNumElements() <= 256) && "unhandled case in lowering");
531 MVT IndexVT = DataVT.changeTypeToInteger();
532 if (IndexVT.getScalarType().bitsGT(ST.getXLenVT()))
533 IndexVT = IndexVT.changeVectorElementType(MVT::i16);
534 return cast<VectorType>(EVT(IndexVT).getTypeForEVT(C));
535}
536
537/// Attempt to approximate the cost of a shuffle which will require splitting
538/// during legalization. Note that processShuffleMasks is not an exact proxy
539/// for the algorithm used in LegalizeVectorTypes, but hopefully it's a
540/// reasonably close upperbound.
542 MVT LegalVT, VectorType *Tp,
543 ArrayRef<int> Mask,
544 TTI::TargetCostKind CostKind) {
545 assert(LegalVT.isFixedLengthVector() && !Mask.empty() &&
546 "Expected fixed vector type and non-empty mask");
547 unsigned LegalNumElts = LegalVT.getVectorNumElements();
548 // Number of destination vectors after legalization:
549 unsigned NumOfDests = divideCeil(Mask.size(), LegalNumElts);
550 // We are going to permute multiple sources and the result will be in
551 // multiple destinations. Providing an accurate cost only for splits where
552 // the element type remains the same.
553 if (NumOfDests <= 1 ||
555 Tp->getElementType()->getPrimitiveSizeInBits() ||
556 LegalNumElts >= Tp->getElementCount().getFixedValue())
558
559 unsigned VecTySize = TTI.getDataLayout().getTypeStoreSize(Tp);
560 unsigned LegalVTSize = LegalVT.getStoreSize();
561 // Number of source vectors after legalization:
562 unsigned NumOfSrcs = divideCeil(VecTySize, LegalVTSize);
563
564 auto *SingleOpTy = FixedVectorType::get(Tp->getElementType(), LegalNumElts);
565
566 unsigned NormalizedVF = LegalNumElts * std::max(NumOfSrcs, NumOfDests);
567 unsigned NumOfSrcRegs = NormalizedVF / LegalNumElts;
568 unsigned NumOfDestRegs = NormalizedVF / LegalNumElts;
569 SmallVector<int> NormalizedMask(NormalizedVF, PoisonMaskElem);
570 assert(NormalizedVF >= Mask.size() &&
571 "Normalized mask expected to be not shorter than original mask.");
572 copy(Mask, NormalizedMask.begin());
573 InstructionCost Cost = 0;
574 SmallDenseSet<std::pair<ArrayRef<int>, unsigned>> ReusedSingleSrcShuffles;
576 NormalizedMask, NumOfSrcRegs, NumOfDestRegs, NumOfDestRegs, []() {},
577 [&](ArrayRef<int> RegMask, unsigned SrcReg, unsigned DestReg) {
578 if (ShuffleVectorInst::isIdentityMask(RegMask, RegMask.size()))
579 return;
580 if (!ReusedSingleSrcShuffles.insert(std::make_pair(RegMask, SrcReg))
581 .second)
582 return;
583 Cost += TTI.getShuffleCost(
585 FixedVectorType::get(SingleOpTy->getElementType(), RegMask.size()),
586 SingleOpTy, CostKind, RegMask, 0, nullptr);
587 },
588 [&](ArrayRef<int> RegMask, unsigned Idx1, unsigned Idx2, bool NewReg) {
589 Cost += TTI.getShuffleCost(
591 FixedVectorType::get(SingleOpTy->getElementType(), RegMask.size()),
592 SingleOpTy, CostKind, RegMask, 0, nullptr);
593 });
594 return Cost;
595}
596
597/// Try to perform better estimation of the permutation.
598/// 1. Split the source/destination vectors into real registers.
599/// 2. Do the mask analysis to identify which real registers are
600/// permuted. If more than 1 source registers are used for the
601/// destination register building, the cost for this destination register
602/// is (Number_of_source_register - 1) * Cost_PermuteTwoSrc. If only one
603/// source register is used, build mask and calculate the cost as a cost
604/// of PermuteSingleSrc.
605/// Also, for the single register permute we try to identify if the
606/// destination register is just a copy of the source register or the
607/// copy of the previous destination register (the cost is
608/// TTI::TCC_Basic). If the source register is just reused, the cost for
609/// this operation is 0.
610static InstructionCost
612 std::optional<unsigned> VLen, VectorType *Tp,
613 ArrayRef<int> Mask, TTI::TargetCostKind CostKind) {
614 assert(LegalVT.isFixedLengthVector());
615 if (!VLen || Mask.empty())
617 MVT ElemVT = LegalVT.getVectorElementType();
618 unsigned ElemsPerVReg = *VLen / ElemVT.getFixedSizeInBits();
619 LegalVT = TTI.getTypeLegalizationCost(
620 FixedVectorType::get(Tp->getElementType(), ElemsPerVReg))
621 .second;
622 // Number of destination vectors after legalization:
623 InstructionCost NumOfDests =
624 divideCeil(Mask.size(), LegalVT.getVectorNumElements());
625 if (NumOfDests <= 1 ||
627 Tp->getElementType()->getPrimitiveSizeInBits() ||
628 LegalVT.getVectorNumElements() >= Tp->getElementCount().getFixedValue())
630
631 unsigned VecTySize = TTI.getDataLayout().getTypeStoreSize(Tp);
632 unsigned LegalVTSize = LegalVT.getStoreSize();
633 // Number of source vectors after legalization:
634 unsigned NumOfSrcs = divideCeil(VecTySize, LegalVTSize);
635
636 auto *SingleOpTy = FixedVectorType::get(Tp->getElementType(),
637 LegalVT.getVectorNumElements());
638
639 unsigned E = NumOfDests.getValue();
640 unsigned NormalizedVF =
641 LegalVT.getVectorNumElements() * std::max(NumOfSrcs, E);
642 unsigned NumOfSrcRegs = NormalizedVF / LegalVT.getVectorNumElements();
643 unsigned NumOfDestRegs = NormalizedVF / LegalVT.getVectorNumElements();
644 SmallVector<int> NormalizedMask(NormalizedVF, PoisonMaskElem);
645 assert(NormalizedVF >= Mask.size() &&
646 "Normalized mask expected to be not shorter than original mask.");
647 copy(Mask, NormalizedMask.begin());
648 InstructionCost Cost = 0;
649 int NumShuffles = 0;
650 SmallDenseSet<std::pair<ArrayRef<int>, unsigned>> ReusedSingleSrcShuffles;
652 NormalizedMask, NumOfSrcRegs, NumOfDestRegs, NumOfDestRegs, []() {},
653 [&](ArrayRef<int> RegMask, unsigned SrcReg, unsigned DestReg) {
654 if (ShuffleVectorInst::isIdentityMask(RegMask, RegMask.size()))
655 return;
656 if (!ReusedSingleSrcShuffles.insert(std::make_pair(RegMask, SrcReg))
657 .second)
658 return;
659 ++NumShuffles;
660 Cost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, SingleOpTy,
661 SingleOpTy, CostKind, RegMask, 0, nullptr);
662 },
663 [&](ArrayRef<int> RegMask, unsigned Idx1, unsigned Idx2, bool NewReg) {
664 Cost += TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, SingleOpTy,
665 SingleOpTy, CostKind, RegMask, 0, nullptr);
666 NumShuffles += 2;
667 });
668 // Note: check that we do not emit too many shuffles here to prevent code
669 // size explosion.
670 // TODO: investigate, if it can be improved by extra analysis of the masks
671 // to check if the code is more profitable.
672 if ((NumOfDestRegs > 2 && NumShuffles <= static_cast<int>(NumOfDestRegs)) ||
673 (NumOfDestRegs <= 2 && NumShuffles < 4))
674 return Cost;
676}
677
678InstructionCost RISCVTTIImpl::getSlideCost(FixedVectorType *Tp,
679 ArrayRef<int> Mask,
680 TTI::TargetCostKind CostKind) const {
681 // Avoid missing masks and length changing shuffles
682 if (Mask.size() <= 2 || Mask.size() != Tp->getNumElements())
684
685 int NumElts = Tp->getNumElements();
686 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Tp);
687 // Avoid scalarization cases
688 if (!LT.second.isFixedLengthVector())
690
691 // Requires moving elements between parts, which requires additional
692 // unmodeled instructions.
693 if (LT.first != 1)
695
696 auto GetSlideOpcode = [&](int SlideAmt) {
697 assert(SlideAmt != 0);
698 bool IsVI = isUInt<5>(std::abs(SlideAmt));
699 if (SlideAmt < 0)
700 return IsVI ? RISCV::VSLIDEDOWN_VI : RISCV::VSLIDEDOWN_VX;
701 return IsVI ? RISCV::VSLIDEUP_VI : RISCV::VSLIDEUP_VX;
702 };
703
704 std::array<std::pair<int, int>, 2> SrcInfo;
705 if (!isMaskedSlidePair(Mask, NumElts, SrcInfo))
707
708 if (SrcInfo[1].second == 0)
709 std::swap(SrcInfo[0], SrcInfo[1]);
710
711 if (ST->hasStdExtZvzip() && LT.second.getScalarSizeInBits() != 1) {
712 unsigned Factor;
713 if (isPairEven(SrcInfo, Mask, Factor) && Factor == 1)
714 return getRISCVInstructionCost(RISCV::VPAIRE_VV, LT.second, CostKind);
715 if (isPairOdd(SrcInfo, Mask, Factor) && Factor == 1)
716 return getRISCVInstructionCost(RISCV::VPAIRO_VV, LT.second, CostKind);
717 }
718
719 InstructionCost FirstSlideCost = 0;
720 if (SrcInfo[0].second != 0) {
721 unsigned Opcode = GetSlideOpcode(SrcInfo[0].second);
722 FirstSlideCost = getRISCVInstructionCost(Opcode, LT.second, CostKind);
723 }
724
725 if (SrcInfo[1].first == -1)
726 return FirstSlideCost;
727
728 InstructionCost SecondSlideCost = 0;
729 if (SrcInfo[1].second != 0) {
730 unsigned Opcode = GetSlideOpcode(SrcInfo[1].second);
731 SecondSlideCost = getRISCVInstructionCost(Opcode, LT.second, CostKind);
732 } else {
733 SecondSlideCost =
734 getRISCVInstructionCost(RISCV::VMERGE_VVM, LT.second, CostKind);
735 }
736
737 auto EC = Tp->getElementCount();
738 VectorType *MaskTy =
740 InstructionCost MaskCost = getConstantPoolLoadCost(MaskTy, CostKind);
741 return FirstSlideCost + SecondSlideCost + MaskCost;
742}
743
744MVT RISCVTTIImpl::getZvzipVZIPCostVT(MVT InterleavedVT) const {
745 if (!InterleavedVT.getVectorElementCount().isKnownEven())
747
748 MVT CostVT = InterleavedVT;
749 if (InterleavedVT.isFixedLengthVector()) {
750 MVT SourceVT = InterleavedVT.getHalfNumVectorElementsVT();
751 CostVT = TLI->getContainerForFixedLengthVector(SourceVT)
753 }
754
755 unsigned EltBits = CostVT.getScalarSizeInBits();
756 unsigned MinSize = CostVT.getSizeInBits().getKnownMinValue();
757 unsigned LMULOctuple = MinSize / (RISCV::RVVBitsPerBlock / 8);
758 // Perform the 2 * SEW <= LMUL * min(ELEN, VLEN) check.
759 if (EltBits * 16 >
760 LMULOctuple * std::min(ST->getELen(), ST->getRealMinVLen()))
762 return CostVT;
763}
764
765MVT RISCVTTIImpl::getZvzipVUNZIPCostVT(MVT InterleavedVT) const {
766 if (!InterleavedVT.getVectorElementCount().isKnownEven())
768
769 MVT CostVT = InterleavedVT;
770 // lowerZvzipVUNZIP widens the source container if halving it would produce
771 // an illegal result type. Apply the same rule here so the cost uses the
772 // source LMUL selected by ISel.
773 if (InterleavedVT.isFixedLengthVector()) {
774 CostVT = TLI->getContainerForFixedLengthVector(InterleavedVT);
775 if (CostVT.getVectorMinNumElements() == 1 ||
776 !TLI->isTypeLegal(CostVT.getHalfNumVectorElementsVT()))
777 CostVT = CostVT.getDoubleNumVectorElementsVT();
778 }
779
780 MVT DeinterleavedVT = CostVT.getHalfNumVectorElementsVT();
781 if (RISCVTargetLowering::getLMUL(DeinterleavedVT) == RISCVVType::LMUL_8)
783 return CostVT;
784}
785
786InstructionCost RISCVTTIImpl::getVZIPCost(TTI::ShuffleKind Kind,
787 VectorType *DstTy, VectorType *SrcTy,
788 ArrayRef<int> Mask,
789 TTI::TargetCostKind CostKind) const {
790 assert(isa<FixedVectorType>(SrcTy) && "Expected fixed-length vector types");
791
792 if (!ST->hasStdExtZvzip() || Mask.size() < 2 ||
793 DstTy->getScalarSizeInBits() == 1)
795
796 unsigned NumSrcElts = SrcTy->getElementCount().getKnownMinValue();
797 unsigned NumDstElts = DstTy->getElementCount().getKnownMinValue();
798 unsigned NumInputElts;
799
800 if (Kind == TTI::SK_PermuteSingleSrc) {
801 // A single-source vzip shuffle interleaves two halves of the same vector,
802 // so its source and destination must have the same number of elements.
803 if (NumSrcElts != NumDstElts)
805 NumInputElts = NumSrcElts;
806 } else if (Kind == TTI::SK_PermuteTwoSrc) {
807 // Accept both forms that can be lowered with vzip.vv:
808 //
809 // 1. The destination has twice as many elements as each source, e.g.
810 // %r = shufflevector <4 x i32> %a, <4 x i32> %b,
811 // <8 x i32> <0, 4, 1, 5, 2, 6, 3, 7>
812 // The two operands are already the half-sized inputs of vzip.vv.
813 //
814 // 2. Each source has the same number of elements as the destination, e.g.
815 // %r = shufflevector <4 x i32> %a, <4 x i32> %b,
816 // <4 x i32> <0, 4, 1, 5>
817 // ISel first extracts a <2 x i32> half from each source and then uses
818 // those halves as the inputs of vzip.vv.
819 if (NumSrcElts != NumDstElts && NumSrcElts * 2 != NumDstElts)
821 NumInputElts = NumSrcElts * 2;
822 } else {
824 }
825
826 // ISel deliberately excludes the two-element single-source identity case.
827 if (Kind == TTI::SK_PermuteSingleSrc && Mask.size() == 2 &&
830
831 // A deinterleave shuffle for an interleaved load may have a mask such as
832 // %even = shufflevector <4 x i32> %wide, <4 x i32> poison,
833 // <4 x i32> <i32 0, i32 2, i32 poison, i32 poison>
834 // Because isInterleaveMask ignores poison lanes, this mask may also satisfy
835 // the interleave matcher. Do not cost it as vzip.vv.
836 unsigned DeinterleaveIndex;
838 DeinterleaveIndex) &&
839 count_if(Mask, [](int Idx) { return Idx >= 0; }) > 1)
841
842 // Require the two start indices found in the mask to be aligned to
843 // half-vector boundaries, with at least one equal to zero.
844 SmallVector<unsigned, 2> StartIndexes;
845 if (!ShuffleVectorInst::isInterleaveMask(Mask, 2, NumInputElts, StartIndexes))
847
848 unsigned HalfNumElts = Mask.size() / 2;
849 if ((StartIndexes[0] != 0 && StartIndexes[1] != 0) ||
850 StartIndexes[0] % HalfNumElts != 0 || StartIndexes[1] % HalfNumElts != 0)
852
853 std::pair<InstructionCost, MVT> DstLT = getTypeLegalizationCost(DstTy);
854 MVT CostVT = getZvzipVZIPCostVT(DstLT.second);
855 if (!CostVT.isValid())
857
859 DstLT.first * getRISCVInstructionCost(RISCV::VZIP_VV, CostVT, CostKind);
860
861 // For a shuffle such as
862 // %r = shufflevector <4 x i32> %v, <4 x i32> poison,
863 // <4 x i32> <i32 0, i32 2, i32 1, i32 3>
864 // vzip.vv needs two <2 x i32> inputs. Include the cost of extracting each
865 // upper half; extracting a low half is free.
866 if (NumSrcElts == NumDstElts) {
868 cast<FixedVectorType>(SrcTy));
869 for (unsigned Start : StartIndexes) {
870 unsigned ExtractIndex = Start % NumSrcElts;
871 if (ExtractIndex != 0)
872 Cost += getShuffleCost(TTI::SK_ExtractSubvector, HalfSrcTy, SrcTy,
873 CostKind, {}, ExtractIndex, HalfSrcTy);
874 }
875 }
876
877 return Cost;
878}
879
881 TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy,
882 TTI::TargetCostKind CostKind, ArrayRef<int> Mask, int Index,
883 VectorType *SubTp, ArrayRef<const Value *> Args, const Instruction *CtxI,
884 TTI::VectorInstrContext VIC) const {
885 assert((Mask.empty() || DstTy->isScalableTy() ||
886 Mask.size() == DstTy->getElementCount().getKnownMinValue()) &&
887 "Expected the Mask to match the return size if given");
888 assert(SrcTy->getScalarType() == DstTy->getScalarType() &&
889 "Expected the same scalar types");
890
891 Kind = improveShuffleKindFromMask(Kind, Mask, SrcTy, Index, SubTp);
892 if (VIC == TTI::VectorInstrContext::SplatOpFolded &&
893 ST->sinkSplatOperands() && Kind == TTI::SK_Broadcast)
894 return TTI::TCC_Free;
895
896 // TODO: Add proper cost model for P extension fixed vectors (e.g., v4i16)
897 // For now, skip all fixed vector cost analysis when P extension is available
898 // to avoid crashes in getMinRVVVectorSizeInBits()
899 if (ST->hasStdExtP() && isa<FixedVectorType>(SrcTy))
900 return 1;
901
902 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(SrcTy);
903
904 // First, handle cases where having a fixed length vector enables us to
905 // give a more accurate cost than falling back to generic scalable codegen.
906 // TODO: Each of these cases hints at a modeling gap around scalable vectors.
907 if (auto *FVTp = dyn_cast<FixedVectorType>(SrcTy);
908 FVTp && ST->hasVInstructions() && LT.second.isFixedLengthVector()) {
910 *this, LT.second, ST->getRealVLen(),
911 Kind == TTI::SK_InsertSubvector ? DstTy : SrcTy, Mask, CostKind);
912 if (VRegSplittingCost.isValid())
913 return VRegSplittingCost;
914 switch (Kind) {
915 default:
916 break;
918 if (Mask.size() >= 2) {
919 MVT EltTp = LT.second.getVectorElementType();
920
921 // Try the vzip.vv cost first, otherwise model the shuffle as a
922 // vwaddu.vv/vwmaccu.vx sequence below if the element size < ELEN.
923 if (InstructionCost VZipCost =
924 getVZIPCost(Kind, DstTy, SrcTy, Mask, CostKind);
925 VZipCost.isValid())
926 return VZipCost;
927
928 unsigned Index;
929 if (ST->hasStdExtZvzip() && EltTp.getScalarSizeInBits() != 1 &&
931 unsigned Opcode = Index == 0 ? RISCV::VUNZIPE_V : RISCV::VUNZIPO_V;
932 if (MVT CostVT = getZvzipVUNZIPCostVT(LT.second); CostVT.isValid())
933 return LT.first * getRISCVInstructionCost(Opcode, CostVT, CostKind);
934 }
935
936 // If the size of the element is < ELEN then shuffles of interleaves and
937 // deinterleaves of 2 vectors can be lowered into the following
938 // sequences
939 if (EltTp.getScalarSizeInBits() < ST->getELen()) {
940 // Example sequence:
941 // vsetivli zero, 4, e8, mf4, ta, ma (ignored)
942 // vwaddu.vv v10, v8, v9
943 // li a0, -1 (ignored)
944 // vwmaccu.vx v10, a0, v9
945 if (ShuffleVectorInst::isInterleaveMask(Mask, 2, Mask.size()))
946 return 2 * LT.first * TLI->getLMULCost(LT.second);
947
948 if (Mask[0] == 0 || Mask[0] == 1) {
949 auto DeinterleaveMask = createStrideMask(Mask[0], 2, Mask.size());
950 // Example sequence:
951 // vnsrl.wi v10, v8, 0
952 if (equal(DeinterleaveMask, Mask))
953 return LT.first * getRISCVInstructionCost(RISCV::VNSRL_WI,
954 LT.second, CostKind);
955 }
956 }
957
958 int SubVectorSize;
959 if (LT.second.getScalarSizeInBits() != 1 &&
960 isRepeatedConcatMask(Mask, SubVectorSize)) {
962 unsigned NumSlides = Log2_32(Mask.size() / SubVectorSize);
963 // The cost of extraction from a subvector is 0 if the index is 0.
964 for (unsigned I = 0; I != NumSlides; ++I) {
965 unsigned InsertIndex = SubVectorSize * (1 << I);
966 FixedVectorType *SubTp =
967 FixedVectorType::get(SrcTy->getElementType(), InsertIndex);
968 FixedVectorType *DestTp =
970 std::pair<InstructionCost, MVT> DestLT =
972 // Add the cost of whole vector register move because the
973 // destination vector register group for vslideup cannot overlap the
974 // source.
975 Cost += DestLT.first * TLI->getLMULCost(DestLT.second);
977 CostKind, {}, InsertIndex, SubTp);
978 }
979 return Cost;
980 }
981 }
982
983 if (InstructionCost SlideCost = getSlideCost(FVTp, Mask, CostKind);
984 SlideCost.isValid())
985 return SlideCost;
986
987 // vrgather + cost of generating the mask constant.
988 // We model this for an unknown mask with a single vrgather.
989 if (LT.first == 1 && (LT.second.getScalarSizeInBits() != 8 ||
990 LT.second.getVectorNumElements() <= 256)) {
991 VectorType *IdxTy =
992 getVRGatherIndexType(LT.second, *ST, SrcTy->getContext());
993 InstructionCost IndexCost = getConstantPoolLoadCost(IdxTy, CostKind);
994 return IndexCost +
995 getRISCVInstructionCost(RISCV::VRGATHER_VV, LT.second, CostKind);
996 }
997 break;
998 }
1000 case TTI::SK_PermuteTwoSrc: {
1001
1002 if (InstructionCost SlideCost = getSlideCost(FVTp, Mask, CostKind);
1003 SlideCost.isValid())
1004 return SlideCost;
1005
1006 if (InstructionCost VZipCost =
1007 getVZIPCost(Kind, DstTy, SrcTy, Mask, CostKind);
1008 VZipCost.isValid())
1009 return VZipCost;
1010 // 2 x (vrgather + cost of generating the mask constant) + cost of mask
1011 // register for the second vrgather. We model this for an unknown
1012 // (shuffle) mask.
1013 if (LT.first == 1 && (LT.second.getScalarSizeInBits() != 8 ||
1014 LT.second.getVectorNumElements() <= 256)) {
1015 auto &C = SrcTy->getContext();
1016 auto EC = SrcTy->getElementCount();
1017 VectorType *IdxTy = getVRGatherIndexType(LT.second, *ST, C);
1019 InstructionCost IndexCost = getConstantPoolLoadCost(IdxTy, CostKind);
1020 InstructionCost MaskCost = getConstantPoolLoadCost(MaskTy, CostKind);
1021 return 2 * IndexCost +
1022 getRISCVInstructionCost({RISCV::VRGATHER_VV, RISCV::VRGATHER_VV},
1023 LT.second, CostKind) +
1024 MaskCost;
1025 }
1026 break;
1027 }
1028 }
1029
1030 auto shouldSplit = [](TTI::ShuffleKind Kind) {
1031 switch (Kind) {
1032 default:
1033 return false;
1035 case TTI::SK_Transpose:
1037 return true;
1038 }
1039 };
1040
1041 if (!Mask.empty() && LT.first.isValid() && LT.first != 1 &&
1042 shouldSplit(Kind)) {
1043 InstructionCost SplitCost =
1044 costShuffleViaSplitting(*this, LT.second, FVTp, Mask, CostKind);
1045 if (SplitCost.isValid())
1046 return SplitCost;
1047 }
1048 }
1049
1050 // Handle scalable vectors (and fixed vectors legalized to scalable vectors).
1051 switch (Kind) {
1052 default:
1053 // Fallthrough to generic handling.
1054 // TODO: Most of these cases will return getInvalid in generic code, and
1055 // must be implemented here.
1056 break;
1058 // Extract at zero is always a subregister extract
1059 if (Index == 0)
1060 return TTI::TCC_Free;
1061
1062 // If we're extracting a subvector of at most m1 size at a sub-register
1063 // boundary - which unfortunately we need exact vlen to identify - this is
1064 // a subregister extract at worst and thus won't require a vslidedown.
1065 // TODO: Extend for aligned m2, m4 subvector extracts
1066 // TODO: Extend for misalgined (but contained) extracts
1067 // TODO: Extend for scalable subvector types
1068 if (std::pair<InstructionCost, MVT> SubLT = getTypeLegalizationCost(SubTp);
1069 SubLT.second.isValid() && SubLT.second.isFixedLengthVector()) {
1070 if (std::optional<unsigned> VLen = ST->getRealVLen();
1071 VLen && SubLT.second.getScalarSizeInBits() * Index % *VLen == 0 &&
1072 SubLT.second.getSizeInBits() <= *VLen)
1073 return TTI::TCC_Free;
1074 }
1075
1076 // Example sequence:
1077 // vsetivli zero, 4, e8, mf2, tu, ma (ignored)
1078 // vslidedown.vi v8, v9, 2
1079 return LT.first *
1080 getRISCVInstructionCost(RISCV::VSLIDEDOWN_VI, LT.second, CostKind);
1082 // Example sequence:
1083 // vsetivli zero, 4, e8, mf2, tu, ma (ignored)
1084 // vslideup.vi v8, v9, 2
1085 LT = getTypeLegalizationCost(DstTy);
1086 return LT.first *
1087 getRISCVInstructionCost(RISCV::VSLIDEUP_VI, LT.second, CostKind);
1088 case TTI::SK_Select: {
1089 // Example sequence:
1090 // li a0, 90
1091 // vsetivli zero, 8, e8, mf2, ta, ma (ignored)
1092 // vmv.s.x v0, a0
1093 // vmerge.vvm v8, v9, v8, v0
1094 // We use 2 for the cost of the mask materialization as this is the true
1095 // cost for small masks and most shuffles are small. At worst, this cost
1096 // should be a very small constant for the constant pool load. As such,
1097 // we may bias towards large selects slightly more than truly warranted.
1098 return LT.first *
1099 (1 + getRISCVInstructionCost({RISCV::VMV_S_X, RISCV::VMERGE_VVM},
1100 LT.second, CostKind));
1101 }
1102 case TTI::SK_Broadcast: {
1103 // Check for broadcast loads, which are synthesized by optimized zero-stride
1104 // loads (this is checked in RISCVTTIImpl::isLegalBroadcastLoad).
1105 bool IsLoad = !Args.empty() && isa<LoadInst>(Args[0]);
1106 if (IsLoad && LT.second.isVector() &&
1107 isLegalBroadcastLoad(SrcTy->getElementType(),
1108 LT.second.getVectorElementCount()))
1109 return 0;
1110
1111 bool HasScalar = (Args.size() > 0) && (Operator::getOpcode(Args[0]) ==
1112 Instruction::InsertElement);
1113 if (LT.second.getScalarSizeInBits() == 1) {
1114 if (HasScalar) {
1115 // Example sequence:
1116 // andi a0, a0, 1
1117 // vsetivli zero, 2, e8, mf8, ta, ma (ignored)
1118 // vmv.v.x v8, a0
1119 // vmsne.vi v0, v8, 0
1120 return LT.first *
1121 (1 + getRISCVInstructionCost({RISCV::VMV_V_X, RISCV::VMSNE_VI},
1122 LT.second, CostKind));
1123 }
1124 // Example sequence:
1125 // vsetivli zero, 2, e8, mf8, ta, mu (ignored)
1126 // vmv.v.i v8, 0
1127 // vmerge.vim v8, v8, 1, v0
1128 // vmv.x.s a0, v8
1129 // andi a0, a0, 1
1130 // vmv.v.x v8, a0
1131 // vmsne.vi v0, v8, 0
1132
1133 return LT.first *
1134 (1 + getRISCVInstructionCost({RISCV::VMV_V_I, RISCV::VMERGE_VIM,
1135 RISCV::VMV_X_S, RISCV::VMV_V_X,
1136 RISCV::VMSNE_VI},
1137 LT.second, CostKind));
1138 }
1139
1140 if (HasScalar) {
1141 // Example sequence:
1142 // vmv.v.x v8, a0
1143 return LT.first *
1144 getRISCVInstructionCost(RISCV::VMV_V_X, LT.second, CostKind);
1145 }
1146
1147 // Example sequence:
1148 // vrgather.vi v9, v8, 0
1149 return LT.first *
1150 getRISCVInstructionCost(RISCV::VRGATHER_VI, LT.second, CostKind);
1151 }
1152 case TTI::SK_Splice: {
1153 // vslidedown+vslideup.
1154 // TODO: Multiplying by LT.first implies this legalizes into multiple copies
1155 // of similar code, but I think we expand through memory.
1156 unsigned Opcodes[2] = {RISCV::VSLIDEDOWN_VX, RISCV::VSLIDEUP_VX};
1157 if (Index >= 0 && Index < 32)
1158 Opcodes[0] = RISCV::VSLIDEDOWN_VI;
1159 else if (Index < 0 && Index > -32)
1160 Opcodes[1] = RISCV::VSLIDEUP_VI;
1161 return LT.first * getRISCVInstructionCost(Opcodes, LT.second, CostKind);
1162 }
1163 case TTI::SK_Reverse: {
1164
1165 if (!LT.second.isVector())
1167
1168 // TODO: Cases to improve here:
1169 // * Illegal vector types
1170 // * i64 on RV32
1171 if (SrcTy->getElementType()->isIntegerTy(1)) {
1172 VectorType *WideTy =
1173 VectorType::get(IntegerType::get(SrcTy->getContext(), 8),
1174 cast<VectorType>(SrcTy)->getElementCount());
1175 return getCastInstrCost(Instruction::ZExt, WideTy, SrcTy,
1176 TTI::CastContextHint::None, CostKind) +
1177 getShuffleCost(TTI::SK_Reverse, WideTy, WideTy, CostKind, {}, 0,
1178 nullptr) +
1179 getCastInstrCost(Instruction::Trunc, SrcTy, WideTy,
1180 TTI::CastContextHint::None, CostKind);
1181 }
1182
1183 MVT ContainerVT = LT.second;
1184 if (LT.second.isFixedLengthVector())
1185 ContainerVT = TLI->getContainerForFixedLengthVector(LT.second);
1187 if (ContainerVT.bitsLE(M1VT)) {
1188 // Example sequence:
1189 // csrr a0, vlenb
1190 // srli a0, a0, 3
1191 // addi a0, a0, -1
1192 // vsetvli a1, zero, e8, mf8, ta, mu (ignored)
1193 // vid.v v9
1194 // vrsub.vx v10, v9, a0
1195 // vrgather.vv v9, v8, v10
1196 InstructionCost LenCost = 3;
1197 if (LT.second.isFixedLengthVector())
1198 // vrsub.vi has a 5 bit immediate field, otherwise an li suffices
1199 LenCost = isInt<5>(LT.second.getVectorNumElements() - 1) ? 0 : 1;
1200 unsigned Opcodes[] = {RISCV::VID_V, RISCV::VRSUB_VX, RISCV::VRGATHER_VV};
1201 if (LT.second.isFixedLengthVector() &&
1202 isInt<5>(LT.second.getVectorNumElements() - 1))
1203 Opcodes[1] = RISCV::VRSUB_VI;
1204 InstructionCost GatherCost =
1205 getRISCVInstructionCost(Opcodes, LT.second, CostKind);
1206 return LT.first * (LenCost + GatherCost);
1207 }
1208
1209 // At high LMUL, we split into a series of M1 reverses (see
1210 // lowerVECTOR_REVERSE) and then do a single slide at the end to eliminate
1211 // the resulting gap at the bottom (for fixed vectors only). The important
1212 // bit is that the cost scales linearly, not quadratically with LMUL.
1213 unsigned M1Opcodes[] = {RISCV::VID_V, RISCV::VRSUB_VX};
1214 InstructionCost FixedCost =
1215 getRISCVInstructionCost(M1Opcodes, M1VT, CostKind) + 3;
1216 unsigned Ratio =
1217 ContainerVT.getVectorMinNumElements() / M1VT.getVectorMinNumElements();
1218 InstructionCost GatherCost =
1219 getRISCVInstructionCost({RISCV::VRGATHER_VV}, M1VT, CostKind) * Ratio;
1220 InstructionCost SlideCost = !LT.second.isFixedLengthVector() ? 0 :
1221 getRISCVInstructionCost({RISCV::VSLIDEDOWN_VX}, LT.second, CostKind);
1222 return FixedCost + LT.first * (GatherCost + SlideCost);
1223 }
1224 }
1225 return BaseT::getShuffleCost(Kind, DstTy, SrcTy, CostKind, Mask, Index,
1226 SubTp);
1227}
1228
1229static unsigned isM1OrSmaller(MVT VT) {
1231 return (LMUL == RISCVVType::VLMUL::LMUL_F8 ||
1235}
1236
1238 VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract,
1239 TTI::TargetCostKind CostKind, bool ForPoisonSrc, ArrayRef<Value *> VL,
1240 TTI::VectorInstrContext VIC) const {
1243
1244 // TODO: Add proper cost model for P extension fixed vectors (e.g., v4i16)
1245 // For now, skip all fixed vector cost analysis when P extension is available
1246 // to avoid crashes in getMinRVVVectorSizeInBits()
1247 if (ST->hasStdExtP() && isa<FixedVectorType>(Ty)) {
1248 return 1; // Treat as single instruction cost for now
1249 }
1250
1251 // A build_vector (which is m1 sized or smaller) can be done in no
1252 // worse than one vslide1down.vx per element in the type. We could
1253 // in theory do an explode_vector in the inverse manner, but our
1254 // lowering today does not have a first class node for this pattern.
1256 Ty, DemandedElts, Insert, Extract, CostKind);
1257 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
1258 if (Insert && !Extract && LT.first.isValid() && LT.second.isVector()) {
1259 if (Ty->getScalarSizeInBits() == 1) {
1260 auto *WideVecTy = cast<VectorType>(Ty->getWithNewBitWidth(8));
1261 // Note: Implicit scalar anyextend is assumed to be free since the i1
1262 // must be stored in a GPR.
1263 return getScalarizationOverhead(WideVecTy, DemandedElts, Insert, Extract,
1264 CostKind) +
1265 getCastInstrCost(Instruction::Trunc, Ty, WideVecTy,
1266 TTI::CastContextHint::None, CostKind, nullptr);
1267 }
1268
1269 assert(LT.second.isFixedLengthVector());
1270 MVT ContainerVT = TLI->getContainerForFixedLengthVector(LT.second);
1272 InstructionCost BV =
1273 cast<FixedVectorType>(Ty)->getNumElements() *
1274 getRISCVInstructionCost(RISCV::VSLIDE1DOWN_VX, LT.second, CostKind);
1275 if (BV < Cost)
1276 Cost = BV;
1277 }
1278 }
1279 return Cost;
1280}
1281
1284 TTI::TargetCostKind CostKind) const {
1285 Type *DataTy = MICA.getDataType();
1286 Align Alignment = MICA.getAlignment();
1287 switch (MICA.getID()) {
1288 case Intrinsic::vp_load_ff: {
1289 EVT DataTypeVT = TLI->getValueType(DL, DataTy);
1290 if (!TLI->isLegalFirstFaultLoad(DataTypeVT, Alignment))
1291 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
1292
1293 unsigned AS = MICA.getAddressSpace();
1294 return getMemoryOpCost(Instruction::Load, DataTy, Alignment, AS, CostKind,
1295 {TTI::OK_AnyValue, TTI::OP_None}, nullptr);
1296 }
1297 case Intrinsic::experimental_vp_strided_load:
1298 case Intrinsic::experimental_vp_strided_store:
1299 return getStridedMemoryOpCost(MICA, CostKind);
1300 case Intrinsic::masked_compressstore:
1301 case Intrinsic::masked_expandload:
1302 return getExpandCompressMemoryOpCost(MICA, CostKind);
1303 case Intrinsic::vp_scatter:
1304 case Intrinsic::vp_gather:
1305 case Intrinsic::masked_scatter:
1306 case Intrinsic::masked_gather:
1307 return getGatherScatterOpCost(MICA, CostKind);
1308 case Intrinsic::vp_load:
1309 case Intrinsic::vp_store:
1310 case Intrinsic::masked_load:
1311 case Intrinsic::masked_store:
1312 return getMaskedMemoryOpCost(MICA, CostKind);
1313 }
1314 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
1315}
1316
1319 TTI::TargetCostKind CostKind) const {
1320 unsigned Opcode = MICA.getID() == Intrinsic::masked_load ? Instruction::Load
1321 : Instruction::Store;
1322 Type *Src = MICA.getDataType();
1323 Align Alignment = MICA.getAlignment();
1324 unsigned AddressSpace = MICA.getAddressSpace();
1325
1326 if (!isLegalMaskedLoadStore(Src, Alignment) ||
1327 CostKind != TTI::TCK_RecipThroughput)
1328 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
1329
1330 // Splitting involves additional evl arithmetic and vl toggles.
1331 InstructionCost SplitCost = 0;
1332 if (MICA.getID() == Intrinsic::vp_load ||
1333 MICA.getID() == Intrinsic::vp_store) {
1334 auto LT = getTypeLegalizationCost(Src);
1335 if (LT.first > 1)
1336 SplitCost += LT.first * TTI::TCC_Expensive;
1337 }
1338
1339 return getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, CostKind);
1340}
1341
1343 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1344 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1345 bool UseMaskForCond, bool UseMaskForGaps) const {
1346
1347 // The interleaved memory access pass will lower (de)interleave ops combined
1348 // with an adjacent appropriate memory to vlseg/vsseg intrinsics. vlseg/vsseg
1349 // only support masking per-iteration (i.e. condition), not per-segment (i.e.
1350 // gap).
1351 if (!UseMaskForGaps && Factor <= TLI->getMaxSupportedInterleaveFactor()) {
1352 auto *VTy = cast<VectorType>(VecTy);
1353 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VTy);
1354 // Need to make sure type has't been scalarized
1355 if (LT.second.isVector()) {
1356 if (CostKind == TTI::TCK_CodeSize)
1357 return LT.first * TTI::TCC_Basic;
1358
1359 auto *SubVecTy =
1360 VectorType::get(VTy->getElementType(),
1361 VTy->getElementCount().divideCoefficientBy(Factor));
1362 if (VTy->getElementCount().isKnownMultipleOf(Factor) &&
1363 TLI->isLegalInterleavedAccessType(SubVecTy, Factor, Alignment,
1364 AddressSpace, DL)) {
1365
1366 // Some processors optimize segment loads/stores as N * DLEN sized
1367 // load ops + Factor * LMUL shuffle ops.
1368 if (ST->hasOptimizedSegmentLoadStore(Factor)) {
1369 unsigned VecSizeInBits =
1370 getEstimatedVLFor(VTy) * VTy->getScalarSizeInBits();
1371 unsigned VLENForTuning =
1373 unsigned DLENForTuning = VLENForTuning / ST->getDLenFactor();
1374 InstructionCost Cost = divideCeil(VecSizeInBits, DLENForTuning);
1375 MVT SubVecVT = getTLI()->getValueType(DL, SubVecTy).getSimpleVT();
1376 Cost += Factor * TLI->getLMULCost(SubVecVT);
1377 return Cost;
1378 }
1379
1380 // Otherwise, the cost is proportional to the number of elements (VL *
1381 // Factor ops).
1382 unsigned NumLoads = getEstimatedVLFor(VTy);
1383 return NumLoads * TTI::TCC_Basic;
1384 }
1385 }
1386 }
1387
1388 // TODO: Return the cost of interleaved accesses for scalable vector when
1389 // unable to convert to segment accesses instructions.
1390 if (isa<ScalableVectorType>(VecTy))
1392
1393 auto *FVTy = cast<FixedVectorType>(VecTy);
1394 // When gaps are only at the tail, for interleaved load, we can emit a wide
1395 // masked load and shufflevectors. For interleaved store, we can emit
1396 // shufflevectors and a wide masked store. The interleaved memory access pass
1397 // will lower them into vlsseg/vssseg intrinsics.
1398 if (UseMaskForGaps) {
1399 assert(llvm::is_sorted(Indices) && "Indices must be sorted");
1400 assert(llvm::adjacent_find(Indices) == Indices.end() &&
1401 "Indices should not contain duplicate elements");
1402 unsigned NumOfFields = Indices.size();
1403 bool IsTailGapOnly = NumOfFields > 1 && (NumOfFields == Indices.back() + 1);
1404 if (IsTailGapOnly &&
1405 NumOfFields <= TLI->getMaxSupportedInterleaveFactor()) {
1406 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(FVTy);
1407 if (LT.second.isVector() &&
1408 FVTy->getElementCount().isKnownMultipleOf(Factor)) {
1409 auto *SubVecTy = VectorType::get(
1410 FVTy->getElementType(),
1411 FVTy->getElementCount().divideCoefficientBy(Factor));
1412 if (TLI->isLegalInterleavedAccessType(SubVecTy, NumOfFields, Alignment,
1413 AddressSpace, DL)) {
1414 // The cost is proportional to the total number of element accesses.
1415 unsigned NumAccesses = getEstimatedVLFor(FVTy);
1416 return NumAccesses * TTI::TCC_Basic;
1417 }
1418 }
1419 }
1420 }
1421
1422 InstructionCost MemCost =
1423 getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace, CostKind);
1424 unsigned VF = FVTy->getNumElements() / Factor;
1425
1426 // An interleaved load will look like this for Factor=3:
1427 // %wide.vec = load <12 x i32>, ptr %3, align 4
1428 // %strided.vec = shufflevector %wide.vec, poison, <4 x i32> <stride mask>
1429 // %strided.vec1 = shufflevector %wide.vec, poison, <4 x i32> <stride mask>
1430 // %strided.vec2 = shufflevector %wide.vec, poison, <4 x i32> <stride mask>
1431 if (Opcode == Instruction::Load) {
1432 InstructionCost Cost = MemCost;
1433 for (unsigned Index : Indices) {
1434 FixedVectorType *VecTy =
1435 FixedVectorType::get(FVTy->getElementType(), VF * Factor);
1436 auto Mask = createStrideMask(Index, Factor, VF);
1437 Mask.resize(VF * Factor, -1);
1438 InstructionCost ShuffleCost =
1440 CostKind, Mask, 0, nullptr, {});
1441 Cost += ShuffleCost;
1442 }
1443 return Cost;
1444 }
1445
1446 // TODO: Model for NF > 2
1447 // We'll need to enhance getShuffleCost to model shuffles that are just
1448 // inserts and extracts into subvectors, since they won't have the full cost
1449 // of a vrgather.
1450 // An interleaved store for 3 vectors of 4 lanes will look like
1451 // %11 = shufflevector <4 x i32> %4, <4 x i32> %6, <8 x i32> <0...7>
1452 // %12 = shufflevector <4 x i32> %9, <4 x i32> poison, <8 x i32> <0...3>
1453 // %13 = shufflevector <8 x i32> %11, <8 x i32> %12, <12 x i32> <0...11>
1454 // %interleaved.vec = shufflevector %13, poison, <12 x i32> <interleave mask>
1455 // store <12 x i32> %interleaved.vec, ptr %10, align 4
1456 if (Factor != 2)
1457 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1458 Alignment, AddressSpace, CostKind,
1459 UseMaskForCond, UseMaskForGaps);
1460
1461 assert(Opcode == Instruction::Store && "Opcode must be a store");
1462 // For an interleaving store of 2 vectors, we perform one large interleaving
1463 // shuffle that goes into the wide store
1464 auto Mask = createInterleaveMask(VF, Factor);
1465 InstructionCost ShuffleCost =
1467 CostKind, Mask, 0, nullptr, {});
1468 return MemCost + ShuffleCost;
1469}
1470
1473 TTI::TargetCostKind CostKind) const {
1474
1475 bool IsLoad = MICA.getID() == Intrinsic::masked_gather ||
1476 MICA.getID() == Intrinsic::vp_gather;
1477 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
1478 Type *DataTy = MICA.getDataType();
1479 Type *PtrTy = DataTy->getWithNewType(
1480 DL.getAddressType(DataTy->getContext(), MICA.getAddressSpace()));
1481 Align Alignment = MICA.getAlignment();
1482 if (CostKind != TTI::TCK_RecipThroughput)
1483 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
1484
1485 if ((Opcode == Instruction::Load &&
1486 !isLegalMaskedGather(DataTy, Align(Alignment))) ||
1487 (Opcode == Instruction::Store &&
1488 !isLegalMaskedScatter(DataTy, Align(Alignment))))
1489 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
1490
1491 // Splitting vp intrinsics involves additional evl arithmetic and vl toggles.
1492 InstructionCost SplitCost = 0;
1493 if (MICA.getID() == Intrinsic::vp_gather ||
1494 MICA.getID() == Intrinsic::vp_scatter) {
1495 auto DataLT = getTypeLegalizationCost(DataTy);
1496 auto PtrLT = getTypeLegalizationCost(PtrTy);
1497 if (DataLT.first > 1)
1498 SplitCost += DataLT.first * TTI::TCC_Expensive;
1499 if (PtrLT.first > 1)
1500 SplitCost += PtrLT.first * TTI::TCC_Expensive;
1501 }
1502
1503 // Cost is proportional to the number of memory operations implied. For
1504 // scalable vectors, we use an estimate on that number since we don't
1505 // know exactly what VL will be.
1506 auto &VTy = *cast<VectorType>(DataTy);
1507 unsigned NumLoads = getEstimatedVLFor(&VTy);
1508 return SplitCost + NumLoads * TTI::TCC_Basic;
1509}
1510
1512 const MemIntrinsicCostAttributes &MICA,
1513 TTI::TargetCostKind CostKind) const {
1514 unsigned Opcode = MICA.getID() == Intrinsic::masked_expandload
1515 ? Instruction::Load
1516 : Instruction::Store;
1517 Type *DataTy = MICA.getDataType();
1518 bool VariableMask = MICA.getVariableMask();
1519 Align Alignment = MICA.getAlignment();
1520 bool IsLegal = (Opcode == Instruction::Store &&
1521 isLegalMaskedCompressStore(DataTy, Alignment)) ||
1522 (Opcode == Instruction::Load &&
1523 isLegalMaskedExpandLoad(DataTy, Alignment));
1524 if (!IsLegal || CostKind != TTI::TCK_RecipThroughput)
1525 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
1526 // Example compressstore sequence:
1527 // vsetivli zero, 8, e32, m2, ta, ma (ignored)
1528 // vcompress.vm v10, v8, v0
1529 // vcpop.m a1, v0
1530 // vsetvli zero, a1, e32, m2, ta, ma
1531 // vse32.v v10, (a0)
1532 // Example expandload sequence:
1533 // vsetivli zero, 8, e8, mf2, ta, ma (ignored)
1534 // vcpop.m a1, v0
1535 // vsetvli zero, a1, e32, m2, ta, ma
1536 // vle32.v v10, (a0)
1537 // vsetivli zero, 8, e32, m2, ta, ma
1538 // viota.m v12, v0
1539 // vrgather.vv v8, v10, v12, v0.t
1540 auto MemOpCost =
1541 getMemoryOpCost(Opcode, DataTy, Alignment, /*AddressSpace*/ 0, CostKind);
1542 auto LT = getTypeLegalizationCost(DataTy);
1543 SmallVector<unsigned, 4> Opcodes{RISCV::VSETVLI};
1544 if (VariableMask)
1545 Opcodes.push_back(RISCV::VCPOP_M);
1546 if (Opcode == Instruction::Store)
1547 Opcodes.append({RISCV::VCOMPRESS_VM});
1548 else
1549 Opcodes.append({RISCV::VSETIVLI, RISCV::VIOTA_M, RISCV::VRGATHER_VV});
1550 return MemOpCost +
1551 LT.first * getRISCVInstructionCost(Opcodes, LT.second, CostKind);
1552}
1553
1556 TTI::TargetCostKind CostKind) const {
1557 Type *DataTy = MICA.getDataType();
1558 Align Alignment = MICA.getAlignment();
1559
1560 if (!isLegalStridedLoadStore(DataTy, Alignment))
1561 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
1562
1563 if (CostKind == TTI::TCK_CodeSize)
1564 return TTI::TCC_Basic;
1565
1566 // Splitting vp intrinsics involves additional evl arithmetic and vl toggles.
1567 InstructionCost SplitCost = 0;
1568 auto LT = getTypeLegalizationCost(DataTy);
1569 if (LT.first > 1)
1570 SplitCost += LT.first * TTI::TCC_Expensive;
1571
1572 // Cost is proportional to the number of memory operations implied. For
1573 // scalable vectors, we use an estimate on that number since we don't
1574 // know exactly what VL will be.
1575 auto &VTy = *cast<VectorType>(DataTy);
1576 unsigned NumLoads = getEstimatedVLFor(&VTy);
1577 // Performant implementations of the vector extension will coalesce
1578 // elements if they fall on the same cache line
1579 uint64_t CacheLineBytes = ST->getCacheLineSize();
1580 if (!CacheLineBytes) // If no value, use default value of 64
1581 CacheLineBytes = 64;
1582 if (const ConstantInt *StrideCI =
1584 int64_t Stride = StrideCI->getSExtValue();
1585 // Bail early to avoid UB with std:abs() call
1586 if (Stride != std::numeric_limits<int64_t>::min() && Stride != 0) {
1587 uint64_t AbsStride = (uint64_t)std::abs(Stride);
1588 if (AbsStride < CacheLineBytes) {
1589 uint64_t MaxCombines = ST->getMaxVectorCoalesceElts();
1590 if ((CacheLineBytes / AbsStride) >= MaxCombines)
1591 NumLoads = divideCeil(NumLoads, MaxCombines);
1592 else
1593 // If we were to calculate CacheLineBytes / AbsStride first, would
1594 // lose accuracy
1595 NumLoads = divideCeil((NumLoads * AbsStride), CacheLineBytes);
1596 }
1597 }
1598 }
1599 return SplitCost + NumLoads * TTI::TCC_Basic;
1600}
1601
1604 // FIXME: This is a property of the default vector convention, not
1605 // all possible calling conventions. Fixing that will require
1606 // some TTI API and SLP rework.
1609 for (auto *Ty : Tys) {
1610 if (!Ty->isVectorTy())
1611 continue;
1612 Align A = DL.getPrefTypeAlign(Ty);
1613 Cost += getMemoryOpCost(Instruction::Store, Ty, A, 0, CostKind) +
1614 getMemoryOpCost(Instruction::Load, Ty, A, 0, CostKind);
1615 }
1616 return Cost;
1617}
1618
1619// Currently, these represent both throughput and codesize costs
1620// for the respective intrinsics. The costs in this table are simply
1621// instruction counts with the following adjustments made:
1622// * One vsetvli is considered free.
1624 {Intrinsic::floor, MVT::f32, 9},
1625 {Intrinsic::floor, MVT::f64, 9},
1626 {Intrinsic::ceil, MVT::f32, 9},
1627 {Intrinsic::ceil, MVT::f64, 9},
1628 {Intrinsic::trunc, MVT::f32, 7},
1629 {Intrinsic::trunc, MVT::f64, 7},
1630 {Intrinsic::round, MVT::f32, 9},
1631 {Intrinsic::round, MVT::f64, 9},
1632 {Intrinsic::roundeven, MVT::f32, 9},
1633 {Intrinsic::roundeven, MVT::f64, 9},
1634 {Intrinsic::rint, MVT::f32, 7},
1635 {Intrinsic::rint, MVT::f64, 7},
1636 {Intrinsic::nearbyint, MVT::f32, 9},
1637 {Intrinsic::nearbyint, MVT::f64, 9},
1638 {Intrinsic::bswap, MVT::i16, 3},
1639 {Intrinsic::bswap, MVT::i32, 12},
1640 {Intrinsic::bswap, MVT::i64, 31},
1641 {Intrinsic::bitreverse, MVT::i8, 17},
1642 {Intrinsic::bitreverse, MVT::i16, 24},
1643 {Intrinsic::bitreverse, MVT::i32, 33},
1644 {Intrinsic::bitreverse, MVT::i64, 52},
1645 {Intrinsic::ctpop, MVT::i8, 12},
1646 {Intrinsic::ctpop, MVT::i16, 19},
1647 {Intrinsic::ctpop, MVT::i32, 20},
1648 {Intrinsic::ctpop, MVT::i64, 21},
1649 {Intrinsic::ctlz, MVT::i8, 19},
1650 {Intrinsic::ctlz, MVT::i16, 28},
1651 {Intrinsic::ctlz, MVT::i32, 31},
1652 {Intrinsic::ctlz, MVT::i64, 35},
1653 {Intrinsic::cttz, MVT::i8, 16},
1654 {Intrinsic::cttz, MVT::i16, 23},
1655 {Intrinsic::cttz, MVT::i32, 24},
1656 {Intrinsic::cttz, MVT::i64, 25},
1657};
1658
1661 TTI::TargetCostKind CostKind) const {
1662 auto *RetTy = ICA.getReturnType();
1663 switch (ICA.getID()) {
1664 case Intrinsic::lrint:
1665 case Intrinsic::llrint:
1666 case Intrinsic::lround:
1667 case Intrinsic::llround: {
1668 auto LT = getTypeLegalizationCost(RetTy);
1669 Type *SrcTy = ICA.getArgTypes().front();
1670 auto SrcLT = getTypeLegalizationCost(SrcTy);
1671 if (ST->hasVInstructions() && LT.second.isVector()) {
1673 unsigned SrcEltSz = DL.getTypeSizeInBits(SrcTy->getScalarType());
1674 unsigned DstEltSz = DL.getTypeSizeInBits(RetTy->getScalarType());
1675 if (LT.second.getVectorElementType() == MVT::bf16) {
1676 if (!ST->hasVInstructionsBF16Minimal())
1678 if (DstEltSz == 32)
1679 Ops = {RISCV::VFWCVTBF16_F_F_V, RISCV::VFCVT_X_F_V};
1680 else
1681 Ops = {RISCV::VFWCVTBF16_F_F_V, RISCV::VFWCVT_X_F_V};
1682 } else if (LT.second.getVectorElementType() == MVT::f16 &&
1683 !ST->hasVInstructionsF16()) {
1684 if (!ST->hasVInstructionsF16Minimal())
1686 if (DstEltSz == 32)
1687 Ops = {RISCV::VFWCVT_F_F_V, RISCV::VFCVT_X_F_V};
1688 else
1689 Ops = {RISCV::VFWCVT_F_F_V, RISCV::VFWCVT_X_F_V};
1690
1691 } else if (SrcEltSz > DstEltSz) {
1692 Ops = {RISCV::VFNCVT_X_F_W};
1693 } else if (SrcEltSz < DstEltSz) {
1694 Ops = {RISCV::VFWCVT_X_F_V};
1695 } else {
1696 Ops = {RISCV::VFCVT_X_F_V};
1697 }
1698
1699 // We need to use the source LMUL in the case of a narrowing op, and the
1700 // destination LMUL otherwise.
1701 if (SrcEltSz > DstEltSz)
1702 return SrcLT.first *
1703 getRISCVInstructionCost(Ops, SrcLT.second, CostKind);
1704 return LT.first * getRISCVInstructionCost(Ops, LT.second, CostKind);
1705 }
1706 break;
1707 }
1708 case Intrinsic::ceil:
1709 case Intrinsic::floor:
1710 case Intrinsic::trunc:
1711 case Intrinsic::rint:
1712 case Intrinsic::round:
1713 case Intrinsic::roundeven: {
1714 // These all use the same code.
1715 auto LT = getTypeLegalizationCost(RetTy);
1716 if (!LT.second.isVector() && TLI->isOperationCustom(ISD::FCEIL, LT.second))
1717 return LT.first * 8;
1718 break;
1719 }
1720 case Intrinsic::minimum:
1721 case Intrinsic::maximum: {
1722 // Without Zfa, scalar fminimum/fmaximum are lowered to fmin/fmax plus a
1723 // NaN check and select.
1724 auto LT = getTypeLegalizationCost(RetTy);
1725 if (!LT.second.isVector() && LT.second.isFloatingPoint() &&
1726 !TLI->isOperationLegal(ISD::FMINIMUM, LT.second) &&
1727 TLI->isOperationLegal(ISD::FMINIMUMNUM, LT.second)) {
1728 Type *ScalarTy = RetTy->getScalarType();
1730 if (!ICA.getFlags().noNaNs()) {
1731 Type *CondTy = Type::getInt1Ty(RetTy->getContext());
1732 Cost += getCmpSelInstrCost(Instruction::FCmp, ScalarTy, CondTy,
1733 CmpInst::FCMP_UNO, CostKind) +
1734 getCmpSelInstrCost(Instruction::Select, ScalarTy, CondTy,
1735 CmpInst::BAD_FCMP_PREDICATE, CostKind);
1736 }
1737 return Cost * LT.first;
1738 }
1739 break;
1740 }
1741 case Intrinsic::umin:
1742 case Intrinsic::umax:
1743 case Intrinsic::smin:
1744 case Intrinsic::smax: {
1745 auto LT = getTypeLegalizationCost(RetTy);
1746 if (LT.second.isScalarInteger() && ST->hasStdExtZbb())
1747 return LT.first;
1748
1749 if (ST->hasVInstructions() && LT.second.isVector()) {
1750 unsigned Op;
1751 switch (ICA.getID()) {
1752 case Intrinsic::umin:
1753 Op = RISCV::VMINU_VV;
1754 break;
1755 case Intrinsic::umax:
1756 Op = RISCV::VMAXU_VV;
1757 break;
1758 case Intrinsic::smin:
1759 Op = RISCV::VMIN_VV;
1760 break;
1761 case Intrinsic::smax:
1762 Op = RISCV::VMAX_VV;
1763 break;
1764 }
1765 return LT.first * getRISCVInstructionCost(Op, LT.second, CostKind);
1766 }
1767 break;
1768 }
1769 case Intrinsic::sadd_sat:
1770 case Intrinsic::ssub_sat:
1771 case Intrinsic::uadd_sat:
1772 case Intrinsic::usub_sat: {
1773 auto LT = getTypeLegalizationCost(RetTy);
1774 if (ST->hasVInstructions() && LT.second.isVector()) {
1775 unsigned Op;
1776 switch (ICA.getID()) {
1777 case Intrinsic::sadd_sat:
1778 Op = RISCV::VSADD_VV;
1779 break;
1780 case Intrinsic::ssub_sat:
1781 Op = RISCV::VSSUB_VV;
1782 break;
1783 case Intrinsic::uadd_sat:
1784 Op = RISCV::VSADDU_VV;
1785 break;
1786 case Intrinsic::usub_sat:
1787 Op = RISCV::VSSUBU_VV;
1788 break;
1789 }
1790 return LT.first * getRISCVInstructionCost(Op, LT.second, CostKind);
1791 }
1792 break;
1793 }
1794 case Intrinsic::fma:
1795 case Intrinsic::fmuladd: {
1796 // TODO: handle promotion with f16/bf16 with zvfhmin/zvfbfmin
1797 auto LT = getTypeLegalizationCost(RetTy);
1798 if (ST->hasVInstructions() && LT.second.isVector())
1799 return LT.first *
1800 getRISCVInstructionCost(RISCV::VFMADD_VV, LT.second, CostKind);
1801 break;
1802 }
1803 case Intrinsic::fabs: {
1804 auto LT = getTypeLegalizationCost(RetTy);
1805 if (ST->hasVInstructions() && LT.second.isVector()) {
1806 // lui a0, 8
1807 // addi a0, a0, -1
1808 // vsetvli a1, zero, e16, m1, ta, ma
1809 // vand.vx v8, v8, a0
1810 // f16 with zvfhmin and bf16 with zvfhbmin
1811 if (LT.second.getVectorElementType() == MVT::bf16 ||
1812 (LT.second.getVectorElementType() == MVT::f16 &&
1813 !ST->hasVInstructionsF16()))
1814 return LT.first * getRISCVInstructionCost(RISCV::VAND_VX, LT.second,
1815 CostKind) +
1816 2;
1817 else
1818 return LT.first *
1819 getRISCVInstructionCost(RISCV::VFSGNJX_VV, LT.second, CostKind);
1820 }
1821 break;
1822 }
1823 case Intrinsic::sqrt: {
1824 auto LT = getTypeLegalizationCost(RetTy);
1825 if (ST->hasVInstructions() && LT.second.isVector()) {
1828 MVT ConvType = LT.second;
1829 MVT FsqrtType = LT.second;
1830 // f16 with zvfhmin and bf16 with zvfbfmin and the type of nxv32[b]f16
1831 // will be spilt.
1832 if (LT.second.getVectorElementType() == MVT::bf16) {
1833 if (LT.second == MVT::nxv32bf16) {
1834 ConvOp = {RISCV::VFWCVTBF16_F_F_V, RISCV::VFWCVTBF16_F_F_V,
1835 RISCV::VFNCVTBF16_F_F_W, RISCV::VFNCVTBF16_F_F_W};
1836 FsqrtOp = {RISCV::VFSQRT_V, RISCV::VFSQRT_V};
1837 ConvType = MVT::nxv16f16;
1838 FsqrtType = MVT::nxv16f32;
1839 } else {
1840 ConvOp = {RISCV::VFWCVTBF16_F_F_V, RISCV::VFNCVTBF16_F_F_W};
1841 FsqrtOp = {RISCV::VFSQRT_V};
1842 FsqrtType = TLI->getTypeToPromoteTo(ISD::FSQRT, FsqrtType);
1843 }
1844 } else if (LT.second.getVectorElementType() == MVT::f16 &&
1845 !ST->hasVInstructionsF16()) {
1846 if (LT.second == MVT::nxv32f16) {
1847 ConvOp = {RISCV::VFWCVT_F_F_V, RISCV::VFWCVT_F_F_V,
1848 RISCV::VFNCVT_F_F_W, RISCV::VFNCVT_F_F_W};
1849 FsqrtOp = {RISCV::VFSQRT_V, RISCV::VFSQRT_V};
1850 ConvType = MVT::nxv16f16;
1851 FsqrtType = MVT::nxv16f32;
1852 } else {
1853 ConvOp = {RISCV::VFWCVT_F_F_V, RISCV::VFNCVT_F_F_W};
1854 FsqrtOp = {RISCV::VFSQRT_V};
1855 FsqrtType = TLI->getTypeToPromoteTo(ISD::FSQRT, FsqrtType);
1856 }
1857 } else {
1858 FsqrtOp = {RISCV::VFSQRT_V};
1859 }
1860
1861 return LT.first * (getRISCVInstructionCost(FsqrtOp, FsqrtType, CostKind) +
1862 getRISCVInstructionCost(ConvOp, ConvType, CostKind));
1863 }
1864 break;
1865 }
1866 case Intrinsic::cttz:
1867 case Intrinsic::ctlz:
1868 case Intrinsic::ctpop: {
1869 auto LT = getTypeLegalizationCost(RetTy);
1870 if (ST->hasStdExtZvbb() && LT.second.isVector()) {
1871 unsigned Op;
1872 switch (ICA.getID()) {
1873 case Intrinsic::cttz:
1874 Op = RISCV::VCTZ_V;
1875 break;
1876 case Intrinsic::ctlz:
1877 Op = RISCV::VCLZ_V;
1878 break;
1879 case Intrinsic::ctpop:
1880 Op = RISCV::VCPOP_V;
1881 break;
1882 }
1883 return LT.first * getRISCVInstructionCost(Op, LT.second, CostKind);
1884 }
1885 break;
1886 }
1887 case Intrinsic::abs: {
1888 auto LT = getTypeLegalizationCost(RetTy);
1889 if (ST->hasVInstructions() && LT.second.isVector()) {
1890 // vabs.v v10, v8 (alias for vabd.vx v10, v8, zero)
1891 if (ST->hasStdExtZvabd())
1892 return LT.first *
1893 getRISCVInstructionCost({RISCV::VABD_VX}, LT.second, CostKind);
1894
1895 // vrsub.vi v10, v8, 0
1896 // vmax.vv v8, v8, v10
1897 return LT.first *
1898 getRISCVInstructionCost({RISCV::VRSUB_VI, RISCV::VMAX_VV},
1899 LT.second, CostKind);
1900 }
1901 break;
1902 }
1903 case Intrinsic::fshl:
1904 case Intrinsic::fshr: {
1905 if (ICA.getArgs().empty())
1906 break;
1907
1908 // Funnel-shifts are ROTL/ROTR when the first and second operand are equal.
1909 // When Zbb/Zbkb is enabled we can use a single ROL(W)/ROR(I)(W)
1910 // instruction.
1911 if ((ST->hasStdExtZbb() || ST->hasStdExtZbkb()) && RetTy->isIntegerTy() &&
1912 ICA.getArgs()[0] == ICA.getArgs()[1] &&
1913 (RetTy->getIntegerBitWidth() == 32 ||
1914 RetTy->getIntegerBitWidth() == 64) &&
1915 RetTy->getIntegerBitWidth() <= ST->getXLen()) {
1916 return 1;
1917 }
1918 break;
1919 }
1920 case Intrinsic::clmul: {
1921 auto LT = getTypeLegalizationCost(RetTy);
1922 if (!LT.second.isVector() && ST->hasStdExtZvbc() && !ST->hasStdExtZbkc()) {
1923 // TODO: Once custom lowering in this case for RV32 is added, this guard
1924 // should be removed and the cost model should be updated.
1925 if (!ST->is64Bit() || LT.second != MVT::i64)
1926 break;
1927 // vmv.s.x v8, a0
1928 // vclmul.vx v8, v8, a1
1929 // vmv.x.s a0, v8
1930 MVT VecVT = MVT::getScalableVectorVT(LT.second, 1);
1931 return LT.first * getRISCVInstructionCost(
1932 {RISCV::VMV_S_X, RISCV::VCLMUL_VX, RISCV::VMV_X_S},
1933 VecVT, CostKind);
1934 }
1935 break;
1936 }
1937 case Intrinsic::masked_udiv:
1938 return getArithmeticInstrCost(Instruction::UDiv, ICA.getReturnType(),
1939 CostKind);
1940 case Intrinsic::masked_sdiv:
1941 return getArithmeticInstrCost(Instruction::SDiv, ICA.getReturnType(),
1942 CostKind);
1943 case Intrinsic::masked_urem:
1944 return getArithmeticInstrCost(Instruction::URem, ICA.getReturnType(),
1945 CostKind);
1946 case Intrinsic::masked_srem:
1947 return getArithmeticInstrCost(Instruction::SRem, ICA.getReturnType(),
1948 CostKind);
1949 case Intrinsic::get_active_lane_mask: {
1950 if (ST->hasVInstructions()) {
1951 Type *ExpRetTy = VectorType::get(
1952 ICA.getArgTypes()[0], cast<VectorType>(RetTy)->getElementCount());
1953 auto LT = getTypeLegalizationCost(ExpRetTy);
1954
1955 // vid.v v8 // considered hoisted
1956 // vsaddu.vx v8, v8, a0
1957 // vmsltu.vx v0, v8, a1
1958 return LT.first *
1959 getRISCVInstructionCost({RISCV::VSADDU_VX, RISCV::VMSLTU_VX},
1960 LT.second, CostKind);
1961 }
1962 break;
1963 }
1964 // TODO: add more intrinsic
1965 case Intrinsic::stepvector: {
1966 auto LT = getTypeLegalizationCost(RetTy);
1967 // Legalisation of illegal types involves an `index' instruction plus
1968 // (LT.first - 1) vector adds.
1969 if (ST->hasVInstructions())
1970 return getRISCVInstructionCost(RISCV::VID_V, LT.second, CostKind) +
1971 (LT.first - 1) *
1972 getRISCVInstructionCost(RISCV::VADD_VX, LT.second, CostKind);
1973 return 1 + (LT.first - 1);
1974 }
1975 case Intrinsic::vector_splice_left:
1976 case Intrinsic::vector_splice_right: {
1977 auto LT = getTypeLegalizationCost(RetTy);
1978 // Constant offsets fall through to getShuffleCost.
1979 if (!ICA.isTypeBasedOnly() && isa<ConstantInt>(ICA.getArgs()[2]))
1980 break;
1981 if (ST->hasVInstructions() && LT.second.isVector()) {
1982 return LT.first *
1983 getRISCVInstructionCost({RISCV::VSLIDEDOWN_VX, RISCV::VSLIDEUP_VX},
1984 LT.second, CostKind);
1985 }
1986 break;
1987 }
1988 case Intrinsic::experimental_cttz_elts: {
1989 if (!ST->hasVInstructions())
1990 break;
1992 Type *ArgTy = ICA.getArgTypes()[0];
1993 auto LT = getTypeLegalizationCost(ArgTy);
1994 if (!LT.second.isVector())
1995 break;
1996
1997 // If the element type is not i1, do a comparison with all-zeros.
1998 if (LT.second.getVectorElementType() != MVT::i1)
1999 Cost += getRISCVInstructionCost(RISCV::VMSNE_VI, LT.second, CostKind);
2000
2001 Cost += getRISCVInstructionCost(RISCV::VFIRST_M, LT.second, CostKind);
2002
2003 // If zero_is_poison is false, then we will generate additional
2004 // cmp + select instructions to convert -1 to EVL.
2005 Type *BoolTy = Type::getInt1Ty(RetTy->getContext());
2006 if (ICA.getArgs().size() > 1 &&
2007 cast<ConstantInt>(ICA.getArgs()[1])->isZero())
2008 Cost += getCmpSelInstrCost(Instruction::ICmp, BoolTy, RetTy,
2009 CmpInst::ICMP_SLT, CostKind) +
2010 getCmpSelInstrCost(Instruction::Select, RetTy, BoolTy,
2011 CmpInst::BAD_ICMP_PREDICATE, CostKind);
2012
2013 return LT.first * Cost;
2014 }
2015 case Intrinsic::experimental_vp_splice: {
2016 // To support type-based query from vectorizer, set the index to 0.
2017 // Note that index only change the cost from vslide.vx to vslide.vi and in
2018 // current implementations they have same costs.
2020 cast<VectorType>(ICA.getArgTypes()[0]), CostKind, {},
2022 }
2023 case Intrinsic::vp_merge: {
2024 // If an operand is a binary op and the type is legal, RISCVVectorPeephole
2025 // will likely fold the resulting vmerge.vvm away.
2027 getTypeLegalizationCost(RetTy).first == 1)
2028 return TTI::TCC_Free;
2029 break;
2030 }
2031 case Intrinsic::fptoui_sat:
2032 case Intrinsic::fptosi_sat: {
2034 bool IsSigned = ICA.getID() == Intrinsic::fptosi_sat;
2035 Type *SrcTy = ICA.getArgTypes()[0];
2036
2037 auto SrcLT = getTypeLegalizationCost(SrcTy);
2038 auto DstLT = getTypeLegalizationCost(RetTy);
2039 if (!SrcTy->isVectorTy())
2040 break;
2041
2042 if (!SrcLT.first.isValid() || !DstLT.first.isValid())
2044
2045 Cost +=
2046 getCastInstrCost(IsSigned ? Instruction::FPToSI : Instruction::FPToUI,
2047 RetTy, SrcTy, TTI::CastContextHint::None, CostKind);
2048
2049 // Handle NaN.
2050 // vmfne v0, v8, v8 # If v8[i] is NaN set v0[i] to 1.
2051 // vmerge.vim v8, v8, 0, v0 # Convert NaN to 0.
2052 Type *CondTy = RetTy->getWithNewBitWidth(1);
2053 Cost += getCmpSelInstrCost(BinaryOperator::FCmp, SrcTy, CondTy,
2054 CmpInst::FCMP_UNO, CostKind);
2055 Cost += getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
2056 CmpInst::FCMP_UNO, CostKind);
2057 return Cost;
2058 }
2059 case Intrinsic::experimental_vector_extract_last_active: {
2060 auto *ValTy = cast<VectorType>(ICA.getArgTypes()[0]);
2061 auto *MaskTy = cast<VectorType>(ICA.getArgTypes()[1]);
2062
2063 auto ValLT = getTypeLegalizationCost(ValTy);
2064 auto MaskLT = getTypeLegalizationCost(MaskTy);
2065
2066 // TODO: Return cheaper cost when the entire lane is inactive.
2067 // The expected asm sequence is:
2068 // vcpop.m a0, v0
2069 // beqz a0, exit # Return passthru when the entire lane is inactive.
2070 // vid v10, v0.t
2071 // vredmaxu.vs v10, v10, v10
2072 // vmv.x.s a0, v10
2073 // zext.b a0, a0
2074 // vslidedown.vx v8, v8, a0
2075 // vmv.x.s a0, v8
2076 // exit:
2077 // ...
2078
2079 // Find a suitable type for a stepvector.
2080 ConstantRange VScaleRange(APInt(64, 1), APInt::getZero(64));
2081 unsigned EltWidth = getTLI()->getBitWidthForCttzElements(
2082 TLI->getVectorIdxTy(getDataLayout()), MaskTy->getElementCount(),
2083 /*ZeroIsPoison=*/true, &VScaleRange);
2084 EltWidth = std::max(EltWidth, MaskTy->getScalarSizeInBits());
2085 Type *StepTy = Type::getIntNTy(MaskTy->getContext(), EltWidth);
2086 auto *StepVecTy = VectorType::get(StepTy, ValTy->getElementCount());
2087 auto StepLT = getTypeLegalizationCost(StepVecTy);
2088
2089 // Currently expandVectorFindLastActive cannot handle step vector split.
2090 // So return invalid when the type needs split.
2091 // FIXME: Remove this if expandVectorFindLastActive supports split vector.
2092 if (StepLT.first > 1)
2094
2096 unsigned Opcodes[] = {RISCV::VID_V, RISCV::VREDMAXU_VS, RISCV::VMV_X_S};
2097
2098 Cost += MaskLT.first *
2099 getRISCVInstructionCost(RISCV::VCPOP_M, MaskLT.second, CostKind);
2100 Cost += getCFInstrCost(Instruction::CondBr, CostKind, nullptr);
2101 Cost += StepLT.first *
2102 getRISCVInstructionCost(Opcodes, StepLT.second, CostKind);
2103 Cost += getCastInstrCost(Instruction::ZExt,
2104 Type::getInt64Ty(ValTy->getContext()), StepTy,
2105 TTI::CastContextHint::None, CostKind, nullptr);
2106 Cost += ValLT.first *
2107 getRISCVInstructionCost({RISCV::VSLIDEDOWN_VI, RISCV::VMV_X_S},
2108 ValLT.second, CostKind);
2109 return Cost;
2110 }
2111 case Intrinsic::vector_interleave2:
2112 case Intrinsic::vector_deinterleave2: {
2113 if (!ST->hasStdExtZvzip())
2114 break;
2115
2116 bool IsInterleave = ICA.getID() == Intrinsic::vector_interleave2;
2117 Type *InterleavedTy = IsInterleave ? RetTy : ICA.getArgTypes().front();
2118 // ISel does not select vzip.vv if either interleave2 input is undef.
2119 if (IsInterleave && !ICA.isTypeBasedOnly() &&
2120 any_of(ICA.getArgs(),
2121 [](const Value *Arg) { return isa<UndefValue>(Arg); }))
2122 break;
2123 if (InterleavedTy->getScalarSizeInBits() == 1)
2124 break;
2125
2126 if (auto *FVT = dyn_cast<FixedVectorType>(InterleavedTy)) {
2127 auto *HalfFVT = FixedVectorType::getHalfElementsVectorType(FVT);
2128 unsigned HalfVF = HalfFVT->getNumElements();
2129 if (IsInterleave)
2130 return getShuffleCost(TTI::SK_PermuteTwoSrc, FVT, HalfFVT, CostKind,
2131 createInterleaveMask(HalfVF, 2), 0, nullptr);
2133 for (unsigned Start = 0; Start != 2; ++Start)
2134 Cost += getShuffleCost(TTI::SK_PermuteSingleSrc, HalfFVT, FVT, CostKind,
2135 createStrideMask(Start, 2, HalfVF), 0, nullptr);
2136 return Cost;
2137 }
2138
2139 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(InterleavedTy);
2140 if (!LT.second.isScalableVector())
2141 break;
2142 if (IsInterleave) {
2143 if (MVT CostVT = getZvzipVZIPCostVT(LT.second); CostVT.isValid())
2144 return LT.first *
2145 getRISCVInstructionCost(RISCV::VZIP_VV, CostVT, CostKind);
2146 } else if (MVT CostVT = getZvzipVUNZIPCostVT(LT.second); CostVT.isValid()) {
2147 return LT.first *
2148 getRISCVInstructionCost({RISCV::VUNZIPE_V, RISCV::VUNZIPO_V},
2149 CostVT, CostKind);
2150 }
2151 break;
2152 }
2153 }
2154
2155 if (ST->hasVInstructions() && RetTy->isVectorTy()) {
2156 if (auto LT = getTypeLegalizationCost(RetTy);
2157 LT.second.isVector()) {
2158 MVT EltTy = LT.second.getVectorElementType();
2159 if (const auto *Entry = CostTableLookup(VectorIntrinsicCostTable,
2160 ICA.getID(), EltTy))
2161 return LT.first * Entry->Cost;
2162 }
2163 }
2164
2165 return BaseT::getIntrinsicInstrCost(ICA, CostKind);
2166}
2167
2170 const SCEV *Ptr,
2171 TTI::TargetCostKind CostKind) const {
2172 // Address computations for vector indexed load/store likely require an offset
2173 // and/or scaling.
2174 if (ST->hasVInstructions() && PtrTy->isVectorTy())
2175 return getArithmeticInstrCost(Instruction::Add, PtrTy, CostKind);
2176
2177 return BaseT::getAddressComputationCost(PtrTy, SE, Ptr, CostKind);
2178}
2179
2181 Type *Src,
2183 TTI::TargetCostKind CostKind,
2184 const Instruction *I) const {
2185 bool IsVectorType = isa<VectorType>(Dst) && isa<VectorType>(Src);
2186 if (!IsVectorType)
2187 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
2188
2189 // TODO: Add proper cost model for P extension fixed vectors (e.g., v4i16)
2190 // For now, skip all fixed vector cost analysis when P extension is available
2191 // to avoid crashes in getMinRVVVectorSizeInBits()
2192 if (ST->hasStdExtP() &&
2194 return 1; // Treat as single instruction cost for now
2195 }
2196
2197 // FIXME: Need to compute legalizing cost for illegal types. The current
2198 // code handles only legal types and those which can be trivially
2199 // promoted to legal.
2200 if (!ST->hasVInstructions() || Src->getScalarSizeInBits() > ST->getELen() ||
2201 Dst->getScalarSizeInBits() > ST->getELen())
2202 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
2203
2204 int ISD = TLI->InstructionOpcodeToISD(Opcode);
2205 assert(ISD && "Invalid opcode");
2206 std::pair<InstructionCost, MVT> SrcLT = getTypeLegalizationCost(Src);
2207 std::pair<InstructionCost, MVT> DstLT = getTypeLegalizationCost(Dst);
2208
2209 // Handle i1 source and dest cases *before* calling logic in BasicTTI.
2210 // The shared implementation doesn't model vector widening during legalization
2211 // and instead assumes scalarization. In order to scalarize an <N x i1>
2212 // vector, we need to extend/trunc to/from i8. If we don't special case
2213 // this, we can get an infinite recursion cycle.
2214 switch (ISD) {
2215 default:
2216 break;
2217 case ISD::SIGN_EXTEND:
2218 case ISD::ZERO_EXTEND:
2219 if (Src->getScalarSizeInBits() == 1) {
2220 // We do not use vsext/vzext to extend from mask vector.
2221 // Instead we use the following instructions to extend from mask vector:
2222 // vmv.v.i v8, 0
2223 // vmerge.vim v8, v8, -1, v0 (repeated per split)
2224 return getRISCVInstructionCost(RISCV::VMV_V_I, DstLT.second, CostKind) +
2225 DstLT.first * getRISCVInstructionCost(RISCV::VMERGE_VIM,
2226 DstLT.second, CostKind) +
2227 DstLT.first - 1;
2228 }
2229 break;
2230 case ISD::TRUNCATE:
2231 if (Dst->getScalarSizeInBits() == 1) {
2232 // We do not use several vncvt to truncate to mask vector. So we could
2233 // not use PowDiff to calculate it.
2234 // Instead we use the following instructions to truncate to mask vector:
2235 // vand.vi v8, v8, 1
2236 // vmsne.vi v0, v8, 0
2237 return SrcLT.first *
2238 getRISCVInstructionCost({RISCV::VAND_VI, RISCV::VMSNE_VI},
2239 SrcLT.second, CostKind) +
2240 SrcLT.first - 1;
2241 }
2242 break;
2243 };
2244
2245 // Our actual lowering for the case where a wider legal type is available
2246 // uses promotion to the wider type. This is reflected in the result of
2247 // getTypeLegalizationCost, but BasicTTI assumes the widened cases are
2248 // scalarized if the legalized Src and Dst are not equal sized.
2249 const DataLayout &DL = this->getDataLayout();
2250 if (!SrcLT.second.isVector() || !DstLT.second.isVector() ||
2251 !SrcLT.first.isValid() || !DstLT.first.isValid() ||
2252 !TypeSize::isKnownLE(DL.getTypeSizeInBits(Src),
2253 SrcLT.second.getSizeInBits()) ||
2254 !TypeSize::isKnownLE(DL.getTypeSizeInBits(Dst),
2255 DstLT.second.getSizeInBits()) ||
2256 SrcLT.first > 1 || DstLT.first > 1)
2257 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
2258
2259 // The split cost is handled by the base getCastInstrCost
2260 assert((SrcLT.first == 1) && (DstLT.first == 1) && "Illegal type");
2261
2262 int PowDiff = (int)Log2_32(DstLT.second.getScalarSizeInBits()) -
2263 (int)Log2_32(SrcLT.second.getScalarSizeInBits());
2264 switch (ISD) {
2265 case ISD::SIGN_EXTEND:
2266 case ISD::ZERO_EXTEND: {
2267 if ((PowDiff < 1) || (PowDiff > 3))
2268 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
2269 unsigned SExtOp[] = {RISCV::VSEXT_VF2, RISCV::VSEXT_VF4, RISCV::VSEXT_VF8};
2270 unsigned ZExtOp[] = {RISCV::VZEXT_VF2, RISCV::VZEXT_VF4, RISCV::VZEXT_VF8};
2271 unsigned Op =
2272 (ISD == ISD::SIGN_EXTEND) ? SExtOp[PowDiff - 1] : ZExtOp[PowDiff - 1];
2273 return getRISCVInstructionCost(Op, DstLT.second, CostKind);
2274 }
2275 case ISD::TRUNCATE:
2276 case ISD::FP_EXTEND:
2277 case ISD::FP_ROUND: {
2278 // Counts of narrow/widen instructions.
2279 unsigned SrcEltSize = SrcLT.second.getScalarSizeInBits();
2280 unsigned DstEltSize = DstLT.second.getScalarSizeInBits();
2281
2282 unsigned Op = (ISD == ISD::TRUNCATE) ? RISCV::VNSRL_WI
2283 : (ISD == ISD::FP_EXTEND) ? RISCV::VFWCVT_F_F_V
2284 : RISCV::VFNCVT_F_F_W;
2286 for (; SrcEltSize != DstEltSize;) {
2287 MVT ElementMVT = (ISD == ISD::TRUNCATE)
2288 ? MVT::getIntegerVT(DstEltSize)
2289 : MVT::getFloatingPointVT(DstEltSize);
2290 MVT DstMVT = DstLT.second.changeVectorElementType(ElementMVT);
2291 DstEltSize =
2292 (DstEltSize > SrcEltSize) ? DstEltSize >> 1 : DstEltSize << 1;
2293 Cost += getRISCVInstructionCost(Op, DstMVT, CostKind);
2294 }
2295 return Cost;
2296 }
2297 case ISD::FP_TO_SINT:
2298 case ISD::FP_TO_UINT: {
2299 unsigned IsSigned = ISD == ISD::FP_TO_SINT;
2300 unsigned FCVT = IsSigned ? RISCV::VFCVT_RTZ_X_F_V : RISCV::VFCVT_RTZ_XU_F_V;
2301 unsigned FWCVT =
2302 IsSigned ? RISCV::VFWCVT_RTZ_X_F_V : RISCV::VFWCVT_RTZ_XU_F_V;
2303 unsigned FNCVT =
2304 IsSigned ? RISCV::VFNCVT_RTZ_X_F_W : RISCV::VFNCVT_RTZ_XU_F_W;
2305 unsigned SrcEltSize = Src->getScalarSizeInBits();
2306 unsigned DstEltSize = Dst->getScalarSizeInBits();
2308 if ((SrcEltSize == 16) &&
2309 (!ST->hasVInstructionsF16() || ((DstEltSize / 2) > SrcEltSize))) {
2310 // If the target only supports zvfhmin or it is fp16-to-i64 conversion
2311 // pre-widening to f32 and then convert f32 to integer
2312 VectorType *VecF32Ty =
2313 VectorType::get(Type::getFloatTy(Dst->getContext()),
2314 cast<VectorType>(Dst)->getElementCount());
2315 std::pair<InstructionCost, MVT> VecF32LT =
2316 getTypeLegalizationCost(VecF32Ty);
2317 Cost +=
2318 VecF32LT.first * getRISCVInstructionCost(RISCV::VFWCVT_F_F_V,
2319 VecF32LT.second, CostKind);
2320 Cost += getCastInstrCost(Opcode, Dst, VecF32Ty, CCH, CostKind, I);
2321 return Cost;
2322 }
2323 if (DstEltSize == SrcEltSize)
2324 Cost += getRISCVInstructionCost(FCVT, DstLT.second, CostKind);
2325 else if (DstEltSize > SrcEltSize)
2326 Cost += getRISCVInstructionCost(FWCVT, DstLT.second, CostKind);
2327 else { // (SrcEltSize > DstEltSize)
2328 // First do a narrowing conversion to an integer half the size, then
2329 // truncate if needed.
2330 MVT ElementVT = MVT::getIntegerVT(SrcEltSize / 2);
2331 MVT VecVT = DstLT.second.changeVectorElementType(ElementVT);
2332 Cost += getRISCVInstructionCost(FNCVT, VecVT, CostKind);
2333 if ((SrcEltSize / 2) > DstEltSize) {
2334 Type *VecTy = EVT(VecVT).getTypeForEVT(Dst->getContext());
2335 Cost +=
2336 getCastInstrCost(Instruction::Trunc, Dst, VecTy, CCH, CostKind, I);
2337 }
2338 }
2339 return Cost;
2340 }
2341 case ISD::SINT_TO_FP:
2342 case ISD::UINT_TO_FP: {
2343 unsigned IsSigned = ISD == ISD::SINT_TO_FP;
2344 unsigned FCVT = IsSigned ? RISCV::VFCVT_F_X_V : RISCV::VFCVT_F_XU_V;
2345 unsigned FWCVT = IsSigned ? RISCV::VFWCVT_F_X_V : RISCV::VFWCVT_F_XU_V;
2346 unsigned FNCVT = IsSigned ? RISCV::VFNCVT_F_X_W : RISCV::VFNCVT_F_XU_W;
2347 unsigned SrcEltSize = Src->getScalarSizeInBits();
2348 unsigned DstEltSize = Dst->getScalarSizeInBits();
2349
2351 if ((DstEltSize == 16) &&
2352 (!ST->hasVInstructionsF16() || ((SrcEltSize / 2) > DstEltSize))) {
2353 // If the target only supports zvfhmin or it is i64-to-fp16 conversion
2354 // it is converted to f32 and then converted to f16
2355 VectorType *VecF32Ty =
2356 VectorType::get(Type::getFloatTy(Dst->getContext()),
2357 cast<VectorType>(Dst)->getElementCount());
2358 std::pair<InstructionCost, MVT> VecF32LT =
2359 getTypeLegalizationCost(VecF32Ty);
2360 Cost += getCastInstrCost(Opcode, VecF32Ty, Src, CCH, CostKind, I);
2361 Cost += VecF32LT.first * getRISCVInstructionCost(RISCV::VFNCVT_F_F_W,
2362 DstLT.second, CostKind);
2363 return Cost;
2364 }
2365
2366 if (DstEltSize == SrcEltSize)
2367 Cost += getRISCVInstructionCost(FCVT, DstLT.second, CostKind);
2368 else if (DstEltSize > SrcEltSize) {
2369 if ((DstEltSize / 2) > SrcEltSize) {
2370 VectorType *VecTy =
2371 VectorType::get(IntegerType::get(Dst->getContext(), DstEltSize / 2),
2372 cast<VectorType>(Dst)->getElementCount());
2373 unsigned Op = IsSigned ? Instruction::SExt : Instruction::ZExt;
2374 Cost += getCastInstrCost(Op, VecTy, Src, CCH, CostKind, I);
2375 }
2376 Cost += getRISCVInstructionCost(FWCVT, DstLT.second, CostKind);
2377 } else
2378 Cost += getRISCVInstructionCost(FNCVT, DstLT.second, CostKind);
2379 return Cost;
2380 }
2381 }
2382 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
2383}
2384
2385unsigned RISCVTTIImpl::getEstimatedVLFor(VectorType *Ty) const {
2386 if (isa<ScalableVectorType>(Ty)) {
2387 const unsigned EltSize = DL.getTypeSizeInBits(Ty->getElementType());
2388 const unsigned MinSize = DL.getTypeSizeInBits(Ty).getKnownMinValue();
2389 const unsigned VectorBits = *getVScaleForTuning() * RISCV::RVVBitsPerBlock;
2390 return RISCVTargetLowering::computeVLMAX(VectorBits, EltSize, MinSize);
2391 }
2392 return cast<FixedVectorType>(Ty)->getNumElements();
2393}
2394
2397 FastMathFlags FMF,
2398 TTI::TargetCostKind CostKind) const {
2399 if (isa<FixedVectorType>(Ty) && !ST->useRVVForFixedLengthVectors())
2400 return BaseT::getMinMaxReductionCost(IID, Ty, FMF, CostKind);
2401
2402 // Skip if scalar size of Ty is bigger than ELEN.
2403 if (Ty->getScalarSizeInBits() > ST->getELen())
2404 return BaseT::getMinMaxReductionCost(IID, Ty, FMF, CostKind);
2405
2406 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
2407 if (Ty->getElementType()->isIntegerTy(1)) {
2408 // SelectionDAGBuilder does following transforms:
2409 // vector_reduce_{smin,umax}(<n x i1>) --> vector_reduce_or(<n x i1>)
2410 // vector_reduce_{smax,umin}(<n x i1>) --> vector_reduce_and(<n x i1>)
2411 if (IID == Intrinsic::umax || IID == Intrinsic::smin)
2412 return getArithmeticReductionCost(Instruction::Or, Ty, FMF, CostKind);
2413 else
2414 return getArithmeticReductionCost(Instruction::And, Ty, FMF, CostKind);
2415 }
2416
2417 if (IID == Intrinsic::maximum || IID == Intrinsic::minimum) {
2419 InstructionCost ExtraCost = 0;
2420 switch (IID) {
2421 case Intrinsic::maximum:
2422 if (FMF.noNaNs()) {
2423 Opcodes = {RISCV::VFREDMAX_VS, RISCV::VFMV_F_S};
2424 } else {
2425 Opcodes = {RISCV::VMFNE_VV, RISCV::VCPOP_M, RISCV::VFREDMAX_VS,
2426 RISCV::VFMV_F_S};
2427 // Cost of Canonical Nan + branch
2428 // lui a0, 523264
2429 // fmv.w.x fa0, a0
2430 Type *DstTy = Ty->getScalarType();
2431 const unsigned EltTyBits = DstTy->getScalarSizeInBits();
2432 Type *SrcTy = IntegerType::getIntNTy(DstTy->getContext(), EltTyBits);
2433 ExtraCost = 1 +
2434 getCastInstrCost(Instruction::UIToFP, DstTy, SrcTy,
2435 TTI::CastContextHint::None, CostKind) +
2436 getCFInstrCost(Instruction::CondBr, CostKind);
2437 }
2438 break;
2439
2440 case Intrinsic::minimum:
2441 if (FMF.noNaNs()) {
2442 Opcodes = {RISCV::VFREDMIN_VS, RISCV::VFMV_F_S};
2443 } else {
2444 Opcodes = {RISCV::VMFNE_VV, RISCV::VCPOP_M, RISCV::VFREDMIN_VS,
2445 RISCV::VFMV_F_S};
2446 // Cost of Canonical Nan + branch
2447 // lui a0, 523264
2448 // fmv.w.x fa0, a0
2449 Type *DstTy = Ty->getScalarType();
2450 const unsigned EltTyBits = DL.getTypeSizeInBits(DstTy);
2451 Type *SrcTy = IntegerType::getIntNTy(DstTy->getContext(), EltTyBits);
2452 ExtraCost = 1 +
2453 getCastInstrCost(Instruction::UIToFP, DstTy, SrcTy,
2454 TTI::CastContextHint::None, CostKind) +
2455 getCFInstrCost(Instruction::CondBr, CostKind);
2456 }
2457 break;
2458 }
2459 return ExtraCost + getRISCVInstructionCost(Opcodes, LT.second, CostKind);
2460 }
2461
2462 // IR Reduction is composed by one rvv reduction instruction and vmv
2463 unsigned SplitOp;
2465 switch (IID) {
2466 default:
2467 llvm_unreachable("Unsupported intrinsic");
2468 case Intrinsic::smax:
2469 SplitOp = RISCV::VMAX_VV;
2470 Opcodes = {RISCV::VREDMAX_VS, RISCV::VMV_X_S};
2471 break;
2472 case Intrinsic::smin:
2473 SplitOp = RISCV::VMIN_VV;
2474 Opcodes = {RISCV::VREDMIN_VS, RISCV::VMV_X_S};
2475 break;
2476 case Intrinsic::umax:
2477 SplitOp = RISCV::VMAXU_VV;
2478 Opcodes = {RISCV::VREDMAXU_VS, RISCV::VMV_X_S};
2479 break;
2480 case Intrinsic::umin:
2481 SplitOp = RISCV::VMINU_VV;
2482 Opcodes = {RISCV::VREDMINU_VS, RISCV::VMV_X_S};
2483 break;
2484 case Intrinsic::maxnum:
2485 SplitOp = RISCV::VFMAX_VV;
2486 Opcodes = {RISCV::VFREDMAX_VS, RISCV::VFMV_F_S};
2487 break;
2488 case Intrinsic::minnum:
2489 SplitOp = RISCV::VFMIN_VV;
2490 Opcodes = {RISCV::VFREDMIN_VS, RISCV::VFMV_F_S};
2491 break;
2492 }
2493 // Add a cost for data larger than LMUL8
2494 InstructionCost SplitCost =
2495 (LT.first > 1) ? (LT.first - 1) *
2496 getRISCVInstructionCost(SplitOp, LT.second, CostKind)
2497 : 0;
2498 return SplitCost + getRISCVInstructionCost(Opcodes, LT.second, CostKind);
2499}
2500
2503 std::optional<FastMathFlags> FMF,
2504 TTI::TargetCostKind CostKind) const {
2505 if (isa<FixedVectorType>(Ty) && !ST->useRVVForFixedLengthVectors())
2506 return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
2507
2508 // Skip if scalar size of Ty is bigger than ELEN.
2509 if (Ty->getScalarSizeInBits() > ST->getELen())
2510 return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
2511
2512 int ISD = TLI->InstructionOpcodeToISD(Opcode);
2513 assert(ISD && "Invalid opcode");
2514
2515 if (ISD != ISD::ADD && ISD != ISD::OR && ISD != ISD::XOR && ISD != ISD::AND &&
2516 ISD != ISD::FADD)
2517 return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
2518
2519 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
2520 Type *ElementTy = Ty->getElementType();
2521 if (ElementTy->isIntegerTy(1)) {
2522 // Example sequences:
2523 // vfirst.m a0, v0
2524 // seqz a0, a0
2525 if (LT.second == MVT::v1i1)
2526 return getRISCVInstructionCost(RISCV::VFIRST_M, LT.second, CostKind) +
2527 getCmpSelInstrCost(Instruction::ICmp, ElementTy, ElementTy,
2528 CmpInst::ICMP_EQ, CostKind);
2529
2530 if (ISD == ISD::AND) {
2531 // Example sequences:
2532 // vmand.mm v8, v9, v8 ; needed every time type is split
2533 // vmnot.m v8, v0 ; alias for vmnand
2534 // vcpop.m a0, v8
2535 // seqz a0, a0
2536
2537 // See the discussion: https://github.com/llvm/llvm-project/pull/119160
2538 // For LMUL <= 8, there is no splitting,
2539 // the sequences are vmnot, vcpop and seqz.
2540 // When LMUL > 8 and split = 1,
2541 // the sequences are vmnand, vcpop and seqz.
2542 // When LMUL > 8 and split > 1,
2543 // the sequences are (LT.first-2) * vmand, vmnand, vcpop and seqz.
2544 return ((LT.first > 2) ? (LT.first - 2) : 0) *
2545 getRISCVInstructionCost(RISCV::VMAND_MM, LT.second, CostKind) +
2546 getRISCVInstructionCost(RISCV::VMNAND_MM, LT.second, CostKind) +
2547 getRISCVInstructionCost(RISCV::VCPOP_M, LT.second, CostKind) +
2548 getCmpSelInstrCost(Instruction::ICmp, ElementTy, ElementTy,
2549 CmpInst::ICMP_EQ, CostKind);
2550 } else if (ISD == ISD::XOR || ISD == ISD::ADD) {
2551 // Example sequences:
2552 // vsetvli a0, zero, e8, mf8, ta, ma
2553 // vmxor.mm v8, v0, v8 ; needed every time type is split
2554 // vcpop.m a0, v8
2555 // andi a0, a0, 1
2556 return (LT.first - 1) *
2557 getRISCVInstructionCost(RISCV::VMXOR_MM, LT.second, CostKind) +
2558 getRISCVInstructionCost(RISCV::VCPOP_M, LT.second, CostKind) + 1;
2559 } else {
2560 assert(ISD == ISD::OR);
2561 // Example sequences:
2562 // vsetvli a0, zero, e8, mf8, ta, ma
2563 // vmor.mm v8, v9, v8 ; needed every time type is split
2564 // vcpop.m a0, v0
2565 // snez a0, a0
2566 return (LT.first - 1) *
2567 getRISCVInstructionCost(RISCV::VMOR_MM, LT.second, CostKind) +
2568 getRISCVInstructionCost(RISCV::VCPOP_M, LT.second, CostKind) +
2569 getCmpSelInstrCost(Instruction::ICmp, ElementTy, ElementTy,
2570 CmpInst::ICMP_NE, CostKind);
2571 }
2572 }
2573
2574 // IR Reduction of or/and is composed by one vmv and one rvv reduction
2575 // instruction, and others is composed by two vmv and one rvv reduction
2576 // instruction
2577 unsigned SplitOp;
2579 switch (ISD) {
2580 case ISD::ADD:
2581 SplitOp = RISCV::VADD_VV;
2582 Opcodes = {RISCV::VMV_S_X, RISCV::VREDSUM_VS, RISCV::VMV_X_S};
2583 break;
2584 case ISD::OR:
2585 SplitOp = RISCV::VOR_VV;
2586 Opcodes = {RISCV::VREDOR_VS, RISCV::VMV_X_S};
2587 break;
2588 case ISD::XOR:
2589 SplitOp = RISCV::VXOR_VV;
2590 Opcodes = {RISCV::VMV_S_X, RISCV::VREDXOR_VS, RISCV::VMV_X_S};
2591 break;
2592 case ISD::AND:
2593 SplitOp = RISCV::VAND_VV;
2594 Opcodes = {RISCV::VREDAND_VS, RISCV::VMV_X_S};
2595 break;
2596 case ISD::FADD:
2597 // We can't promote f16/bf16 fadd reductions.
2598 if ((LT.second.getScalarType() == MVT::f16 && !ST->hasVInstructionsF16()) ||
2599 LT.second.getScalarType() == MVT::bf16)
2600 return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
2602 Opcodes.push_back(RISCV::VFMV_S_F);
2603 for (unsigned i = 0; i < LT.first.getValue(); i++)
2604 Opcodes.push_back(RISCV::VFREDOSUM_VS);
2605 Opcodes.push_back(RISCV::VFMV_F_S);
2606 return getRISCVInstructionCost(Opcodes, LT.second, CostKind);
2607 }
2608 SplitOp = RISCV::VFADD_VV;
2609 Opcodes = {RISCV::VFMV_S_F, RISCV::VFREDUSUM_VS, RISCV::VFMV_F_S};
2610 break;
2611 }
2612 // Add a cost for data larger than LMUL8
2613 InstructionCost SplitCost =
2614 (LT.first > 1) ? (LT.first - 1) *
2615 getRISCVInstructionCost(SplitOp, LT.second, CostKind)
2616 : 0;
2617 return SplitCost + getRISCVInstructionCost(Opcodes, LT.second, CostKind);
2618}
2619
2621 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *ValTy,
2622 std::optional<FastMathFlags> FMF, TTI::TargetCostKind CostKind) const {
2623 if (isa<FixedVectorType>(ValTy) && !ST->useRVVForFixedLengthVectors())
2624 return BaseT::getExtendedReductionCost(Opcode, IsUnsigned, ResTy, ValTy,
2625 FMF, CostKind);
2626
2627 // Skip if scalar size of ResTy is bigger than ELEN.
2628 if (ResTy->getScalarSizeInBits() > ST->getELen())
2629 return BaseT::getExtendedReductionCost(Opcode, IsUnsigned, ResTy, ValTy,
2630 FMF, CostKind);
2631
2632 if (Opcode != Instruction::Add && Opcode != Instruction::FAdd)
2633 return BaseT::getExtendedReductionCost(Opcode, IsUnsigned, ResTy, ValTy,
2634 FMF, CostKind);
2635
2636 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
2637
2638 if (IsUnsigned && Opcode == Instruction::Add && LT.first == 1 &&
2639 LT.second.isVectorOf(MVT::i1)) {
2640 // Represent vector_reduce_add(ZExt(<i1 vector>)) as
2641 // ZExtOrTrunc(ctpop(bitcast <i1 vector> to in)).
2642 return getRISCVInstructionCost(RISCV::VCPOP_M, LT.second, CostKind);
2643 }
2644
2645 if (ResTy->getScalarSizeInBits() != 2 * LT.second.getScalarSizeInBits())
2646 return BaseT::getExtendedReductionCost(Opcode, IsUnsigned, ResTy, ValTy,
2647 FMF, CostKind);
2648
2649 return (LT.first - 1) +
2650 getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
2651}
2652
2655 TTI::TargetCostKind CostKind) const {
2656 assert(OpInfo.isConstant() && "non constant operand?");
2657 if (!isa<VectorType>(Ty))
2658 // FIXME: We need to account for immediate materialization here, but doing
2659 // a decent job requires more knowledge about the immediate than we
2660 // currently have here.
2661 return 0;
2662
2663 if (OpInfo.isUniform())
2664 // vmv.v.i, vmv.v.x, or vfmv.v.f
2665 // We ignore the cost of the scalar constant materialization to be consistent
2666 // with how we treat scalar constants themselves just above.
2667 return 1;
2668
2669 return getConstantPoolLoadCost(Ty, CostKind);
2670}
2671
2673 Align Alignment,
2674 unsigned AddressSpace,
2675 TTI::TargetCostKind CostKind,
2676 TTI::OperandValueInfo OpInfo,
2677 const Instruction *I) const {
2678 EVT VT = TLI->getValueType(DL, Src, true);
2679 // Type legalization can't handle structs, and load latency isn't handled here
2680 if (VT == MVT::Other ||
2681 (Opcode == Instruction::Load && CostKind == TTI::TCK_Latency))
2682 return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
2683 CostKind, OpInfo, I);
2684
2686 if (Opcode == Instruction::Store && OpInfo.isConstant())
2687 Cost += getStoreImmCost(Src, OpInfo, CostKind);
2688
2689 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Src);
2690
2691 InstructionCost BaseCost = [&]() {
2692 InstructionCost Cost = LT.first;
2693 if (CostKind != TTI::TCK_RecipThroughput)
2694 return Cost;
2695
2696 // Our actual lowering for the case where a wider legal type is available
2697 // uses the a VL predicated load on the wider type. This is reflected in
2698 // the result of getTypeLegalizationCost, but BasicTTI assumes the
2699 // widened cases are scalarized.
2700 const DataLayout &DL = this->getDataLayout();
2701 if (Src->isVectorTy() && LT.second.isVector() &&
2702 TypeSize::isKnownLT(DL.getTypeStoreSizeInBits(Src),
2703 LT.second.getSizeInBits()))
2704 return Cost;
2705
2706 return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
2707 CostKind, OpInfo, I);
2708 }();
2709
2710 // Assume memory ops cost scale with the number of vector registers
2711 // possible accessed by the instruction. Note that BasicTTI already
2712 // handles the LT.first term for us.
2713 if (ST->hasVInstructions() && LT.second.isVector() &&
2714 CostKind != TTI::TCK_CodeSize)
2715 BaseCost *= TLI->getLMULCost(LT.second);
2716 return Cost + BaseCost;
2717}
2718
2720 unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred,
2722 TTI::OperandValueInfo Op2Info, const Instruction *I) const {
2723 if (CostKind != TTI::TCK_RecipThroughput)
2724 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
2725 Op1Info, Op2Info, I);
2726
2727 if (isa<FixedVectorType>(ValTy) && !ST->useRVVForFixedLengthVectors())
2728 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
2729 Op1Info, Op2Info, I);
2730
2731 // Skip if scalar size of ValTy is bigger than ELEN.
2732 if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() > ST->getELen())
2733 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
2734 Op1Info, Op2Info, I);
2735
2736 auto GetConstantMatCost =
2737 [&](TTI::OperandValueInfo OpInfo) -> InstructionCost {
2738 if (OpInfo.isUniform())
2739 // We return 0 we currently ignore the cost of materializing scalar
2740 // constants in GPRs.
2741 return 0;
2742
2743 return getConstantPoolLoadCost(ValTy, CostKind);
2744 };
2745
2746 InstructionCost ConstantMatCost;
2747 if (Op1Info.isConstant())
2748 ConstantMatCost += GetConstantMatCost(Op1Info);
2749 if (Op2Info.isConstant())
2750 ConstantMatCost += GetConstantMatCost(Op2Info);
2751
2752 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
2753 if (Opcode == Instruction::Select && LT.second.isVector()) {
2754 if (CondTy->isVectorTy()) {
2755 if (ValTy->getScalarSizeInBits() == 1) {
2756 // vmandn.mm v8, v8, v9
2757 // vmand.mm v9, v0, v9
2758 // vmor.mm v0, v9, v8
2759 return ConstantMatCost +
2760 LT.first *
2761 getRISCVInstructionCost(
2762 {RISCV::VMANDN_MM, RISCV::VMAND_MM, RISCV::VMOR_MM},
2763 LT.second, CostKind);
2764 }
2765 // vselect and max/min are supported natively.
2766 return ConstantMatCost +
2767 LT.first * getRISCVInstructionCost(RISCV::VMERGE_VVM, LT.second,
2768 CostKind);
2769 }
2770
2771 if (ValTy->getScalarSizeInBits() == 1) {
2772 // vmv.v.x v9, a0
2773 // vmsne.vi v9, v9, 0
2774 // vmandn.mm v8, v8, v9
2775 // vmand.mm v9, v0, v9
2776 // vmor.mm v0, v9, v8
2777 MVT InterimVT = LT.second.changeVectorElementType(MVT::i8);
2778 return ConstantMatCost +
2779 LT.first *
2780 getRISCVInstructionCost({RISCV::VMV_V_X, RISCV::VMSNE_VI},
2781 InterimVT, CostKind) +
2782 LT.first * getRISCVInstructionCost(
2783 {RISCV::VMANDN_MM, RISCV::VMAND_MM, RISCV::VMOR_MM},
2784 LT.second, CostKind);
2785 }
2786
2787 // vmv.v.x v10, a0
2788 // vmsne.vi v0, v10, 0
2789 // vmerge.vvm v8, v9, v8, v0
2790 return ConstantMatCost +
2791 LT.first * getRISCVInstructionCost(
2792 {RISCV::VMV_V_X, RISCV::VMSNE_VI, RISCV::VMERGE_VVM},
2793 LT.second, CostKind);
2794 }
2795
2796 if ((Opcode == Instruction::ICmp) && ValTy->isVectorTy() &&
2797 CmpInst::isIntPredicate(VecPred)) {
2798 // Use VMSLT_VV to represent VMSEQ, VMSNE, VMSLTU, VMSLEU, VMSLT, VMSLE
2799 // provided they incur the same cost across all implementations
2800 return ConstantMatCost + LT.first * getRISCVInstructionCost(RISCV::VMSLT_VV,
2801 LT.second,
2802 CostKind);
2803 }
2804
2805 if ((Opcode == Instruction::FCmp) && ValTy->isVectorTy() &&
2806 CmpInst::isFPPredicate(VecPred)) {
2807
2808 // Use VMXOR_MM and VMXNOR_MM to generate all true/false mask
2809 if ((VecPred == CmpInst::FCMP_FALSE) || (VecPred == CmpInst::FCMP_TRUE))
2810 return ConstantMatCost +
2811 getRISCVInstructionCost(RISCV::VMXOR_MM, LT.second, CostKind);
2812
2813 // If we do not support the input floating point vector type, use the base
2814 // one which will calculate as:
2815 // ScalarizeCost + Num * Cost for fixed vector,
2816 // InvalidCost for scalable vector.
2817 if ((ValTy->getScalarSizeInBits() == 16 && !ST->hasVInstructionsF16()) ||
2818 (ValTy->getScalarSizeInBits() == 32 && !ST->hasVInstructionsF32()) ||
2819 (ValTy->getScalarSizeInBits() == 64 && !ST->hasVInstructionsF64()))
2820 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
2821 Op1Info, Op2Info, I);
2822
2823 // Assuming vector fp compare and mask instructions are all the same cost
2824 // until a need arises to differentiate them.
2825 switch (VecPred) {
2826 case CmpInst::FCMP_ONE: // vmflt.vv + vmflt.vv + vmor.mm
2827 case CmpInst::FCMP_ORD: // vmfeq.vv + vmfeq.vv + vmand.mm
2828 case CmpInst::FCMP_UNO: // vmfne.vv + vmfne.vv + vmor.mm
2829 case CmpInst::FCMP_UEQ: // vmflt.vv + vmflt.vv + vmnor.mm
2830 return ConstantMatCost +
2831 LT.first * getRISCVInstructionCost(
2832 {RISCV::VMFLT_VV, RISCV::VMFLT_VV, RISCV::VMOR_MM},
2833 LT.second, CostKind);
2834
2835 case CmpInst::FCMP_UGT: // vmfle.vv + vmnot.m
2836 case CmpInst::FCMP_UGE: // vmflt.vv + vmnot.m
2837 case CmpInst::FCMP_ULT: // vmfle.vv + vmnot.m
2838 case CmpInst::FCMP_ULE: // vmflt.vv + vmnot.m
2839 return ConstantMatCost +
2840 LT.first *
2841 getRISCVInstructionCost({RISCV::VMFLT_VV, RISCV::VMNAND_MM},
2842 LT.second, CostKind);
2843
2844 case CmpInst::FCMP_OEQ: // vmfeq.vv
2845 case CmpInst::FCMP_OGT: // vmflt.vv
2846 case CmpInst::FCMP_OGE: // vmfle.vv
2847 case CmpInst::FCMP_OLT: // vmflt.vv
2848 case CmpInst::FCMP_OLE: // vmfle.vv
2849 case CmpInst::FCMP_UNE: // vmfne.vv
2850 return ConstantMatCost +
2851 LT.first *
2852 getRISCVInstructionCost(RISCV::VMFLT_VV, LT.second, CostKind);
2853 default:
2854 break;
2855 }
2856 }
2857
2858 // With ShortForwardBranchOpt or ConditionalMoveFusion, scalar icmp + select
2859 // instructions will lower to SELECT_CC and lower to PseudoCCMOVGPR which will
2860 // generate a conditional branch + mv. The cost of scalar (icmp + select) will
2861 // be (0 + select instr cost).
2862 if (ST->hasConditionalMoveFusion() && I && isa<ICmpInst>(I) &&
2863 ValTy->isIntegerTy() && !I->user_empty()) {
2864 if (all_of(I->users(), [&](const User *U) {
2865 return match(U, m_Select(m_Specific(I), m_Value(), m_Value())) &&
2866 U->getType()->isIntegerTy() &&
2867 !isa<ConstantData>(U->getOperand(1)) &&
2868 !isa<ConstantData>(U->getOperand(2));
2869 }))
2870 return 0;
2871 }
2872
2873 // TODO: Add cost for scalar type.
2874
2875 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
2876 Op1Info, Op2Info, I);
2877}
2878
2880 TTI::TargetCostKind CostKind,
2881 const Instruction *I) const {
2882 if (CostKind != TTI::TCK_RecipThroughput)
2883 return Opcode == Instruction::PHI ? 0 : 1;
2884 // Branches are assumed to be predicted.
2885 return 0;
2886}
2887
2889 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index,
2890 const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC) const {
2891 assert(Val->isVectorTy() && "This must be a vector type");
2892
2893 // TODO: Add proper cost model for P extension fixed vectors (e.g., v4i16)
2894 // For now, skip all fixed vector cost analysis when P extension is available
2895 // to avoid crashes in getMinRVVVectorSizeInBits()
2896 if (ST->hasStdExtP() && isa<FixedVectorType>(Val)) {
2897 return 1; // Treat as single instruction cost for now
2898 }
2899
2900 if (Opcode != Instruction::ExtractElement &&
2901 Opcode != Instruction::InsertElement)
2902 return BaseT::getVectorInstrCost(Opcode, Val, CostKind, Index, Op0, Op1,
2903 VIC);
2904
2905 // Scalar splat operand can be folded for vector ops that support splatting
2906 // the scalar operand, so the explicit insertelement is free in this context.
2907 if (Opcode == Instruction::InsertElement &&
2908 VIC == TTI::VectorInstrContext::SplatOpFolded &&
2909 ST->sinkSplatOperands() && Index == 0)
2910 return TTI::TCC_Free;
2911
2912 // Legalize the type.
2913 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Val);
2914
2915 // This type is legalized to a scalar type.
2916 if (!LT.second.isVector()) {
2917 auto *FixedVecTy = cast<FixedVectorType>(Val);
2918 // If Index is a known constant, cost is zero.
2919 if (Index != -1U)
2920 return 0;
2921 // Extract/InsertElement with non-constant index is very costly when
2922 // scalarized; estimate cost of loads/stores sequence via the stack:
2923 // ExtractElement cost: store vector to stack, load scalar;
2924 // InsertElement cost: store vector to stack, store scalar, load vector.
2925 Type *ElemTy = FixedVecTy->getElementType();
2926 auto NumElems = FixedVecTy->getNumElements();
2927 auto Align = DL.getPrefTypeAlign(ElemTy);
2928 InstructionCost LoadCost =
2929 getMemoryOpCost(Instruction::Load, ElemTy, Align, 0, CostKind);
2930 InstructionCost StoreCost =
2931 getMemoryOpCost(Instruction::Store, ElemTy, Align, 0, CostKind);
2932 return Opcode == Instruction::ExtractElement
2933 ? StoreCost * NumElems + LoadCost
2934 : (StoreCost + LoadCost) * NumElems + StoreCost;
2935 }
2936
2937 // For unsupported scalable vector.
2938 if (LT.second.isScalableVector() && !LT.first.isValid())
2939 return LT.first;
2940
2941 // Mask vector extract/insert is expanded via e8.
2942 if (Val->getScalarSizeInBits() == 1) {
2943 VectorType *WideTy =
2945 cast<VectorType>(Val)->getElementCount());
2946 if (Opcode == Instruction::ExtractElement) {
2947 InstructionCost ExtendCost
2948 = getCastInstrCost(Instruction::ZExt, WideTy, Val,
2949 TTI::CastContextHint::None, CostKind);
2950 InstructionCost ExtractCost
2951 = getVectorInstrCost(Opcode, WideTy, CostKind, Index, nullptr, nullptr);
2952 return ExtendCost + ExtractCost;
2953 }
2954 InstructionCost ExtendCost
2955 = getCastInstrCost(Instruction::ZExt, WideTy, Val,
2956 TTI::CastContextHint::None, CostKind);
2957 InstructionCost InsertCost
2958 = getVectorInstrCost(Opcode, WideTy, CostKind, Index, nullptr, nullptr);
2959 InstructionCost TruncCost
2960 = getCastInstrCost(Instruction::Trunc, Val, WideTy,
2961 TTI::CastContextHint::None, CostKind);
2962 return ExtendCost + InsertCost + TruncCost;
2963 }
2964
2965
2966 // In RVV, we could use vslidedown + vmv.x.s to extract element from vector
2967 // and vslideup + vmv.s.x to insert element to vector.
2968 unsigned MoveOpc;
2969 if (LT.second.isFloatingPoint())
2970 MoveOpc = Opcode == Instruction::InsertElement ? RISCV::VFMV_S_F
2971 : RISCV::VFMV_F_S;
2972 else
2973 MoveOpc =
2974 Opcode == Instruction::InsertElement ? RISCV::VMV_S_X : RISCV::VMV_X_S;
2975 InstructionCost BaseCost =
2976 getRISCVInstructionCost(MoveOpc, LT.second, CostKind);
2977 // When insertelement we should add the index with 1 as the input of vslideup.
2978 InstructionCost SlideCost = Opcode == Instruction::InsertElement ? 2 : 1;
2979
2980 if (Index != -1U) {
2981 // The type may be split. For fixed-width vectors we can normalize the
2982 // index to the new type.
2983 if (LT.second.isFixedLengthVector()) {
2984 unsigned Width = LT.second.getVectorNumElements();
2985 Index = Index % Width;
2986 }
2987
2988 // If exact VLEN is known, we will insert/extract into the appropriate
2989 // subvector with no additional subvector insert/extract cost.
2990 if (auto VLEN = ST->getRealVLen()) {
2991 unsigned EltSize = LT.second.getScalarSizeInBits();
2992 unsigned M1Max = *VLEN / EltSize;
2993 Index = Index % M1Max;
2994 }
2995
2996 if (Index == 0)
2997 // We can extract/insert the first element without vslidedown/vslideup.
2998 SlideCost = 0;
2999 else if (Opcode == Instruction::InsertElement)
3000 SlideCost = 1; // With a constant index, we do not need to use addi.
3001 }
3002
3003 // When the vector needs to split into multiple register groups and the index
3004 // exceeds single vector register group, we need to insert/extract the element
3005 // via stack.
3006 if (LT.first > 1 &&
3007 ((Index == -1U) || (Index >= LT.second.getVectorMinNumElements() &&
3008 LT.second.isScalableVector()))) {
3009 Type *ScalarType = Val->getScalarType();
3010 Align VecAlign = DL.getPrefTypeAlign(Val);
3011 Align SclAlign = DL.getPrefTypeAlign(ScalarType);
3012 // Extra addi for unknown index.
3013 InstructionCost IdxCost = Index == -1U ? 1 : 0;
3014
3015 // Store all split vectors into stack and load the target element.
3016 if (Opcode == Instruction::ExtractElement)
3017 return getMemoryOpCost(Instruction::Store, Val, VecAlign, 0, CostKind) +
3018 getMemoryOpCost(Instruction::Load, ScalarType, SclAlign, 0,
3019 CostKind) +
3020 IdxCost;
3021
3022 // Store all split vectors into stack and store the target element and load
3023 // vectors back.
3024 return getMemoryOpCost(Instruction::Store, Val, VecAlign, 0, CostKind) +
3025 getMemoryOpCost(Instruction::Load, Val, VecAlign, 0, CostKind) +
3026 getMemoryOpCost(Instruction::Store, ScalarType, SclAlign, 0,
3027 CostKind) +
3028 IdxCost;
3029 }
3030
3031 // Extract i64 in the target that has XLEN=32 need more instruction.
3032 if (Val->getScalarType()->isIntegerTy() &&
3033 ST->getXLen() < Val->getScalarSizeInBits()) {
3034 // For extractelement, we need the following instructions:
3035 // vsetivli zero, 1, e64, m1, ta, mu (not count)
3036 // vslidedown.vx v8, v8, a0
3037 // vmv.x.s a0, v8
3038 // li a1, 32
3039 // vsrl.vx v8, v8, a1
3040 // vmv.x.s a1, v8
3041
3042 // For insertelement, we need the following instructions:
3043 // vsetivli zero, 2, e32, m4, ta, ma (don't count)
3044 // vslide1down.vx v12, v8, a0
3045 // vslide1down.vx v12, v12, a1
3046 // addi a0, a2, 1
3047 // vsetvli zero, a0, e64, m4, tu, ma (don't count)
3048 // vslideup.vx v8, v12, a2
3049
3050 // TODO: should we count these special vsetvlis?
3051 BaseCost =
3052 Opcode == Instruction::InsertElement
3053 ? getRISCVInstructionCost({RISCV::VSLIDE1DOWN_VX,
3054 RISCV::VSLIDE1DOWN_VX,
3055 RISCV::VSLIDEUP_VX},
3056 LT.second, CostKind)
3057 : getRISCVInstructionCost({RISCV::VSLIDEDOWN_VX, RISCV::VMV_X_S,
3058 RISCV::VSRL_VX, RISCV::VMV_X_S},
3059 LT.second, CostKind);
3060 }
3061 return BaseCost + SlideCost;
3062}
3063
3066 TTI::TargetCostKind CostKind,
3067 unsigned Index) const {
3068 if (isa<FixedVectorType>(Val))
3069 return BaseT::getIndexedVectorInstrCostFromEnd(Opcode, Val, CostKind,
3070 Index);
3071
3072 // TODO: This code replicates what LoopVectorize.cpp used to do when asking
3073 // for the cost of extracting the last lane of a scalable vector. It probably
3074 // needs a more accurate cost.
3075 ElementCount EC = cast<VectorType>(Val)->getElementCount();
3076 assert(Index < EC.getKnownMinValue() && "Unexpected reverse index");
3077 return getVectorInstrCost(Opcode, Val, CostKind,
3078 EC.getKnownMinValue() - 1 - Index, nullptr,
3079 nullptr);
3080}
3081
3082/// Check to see if this instruction is expected to be combined to a simpler
3083/// operation during/before lowering. If so return the cost of the combined
3084/// operation rather than provided one. For instance, `udiv i16 %X, 2` is likely
3085/// to be combined to `lshr i16 %X, 1`, so return the cost of a `lshr` rather
3086/// than the cost of a `udiv`
3087std::optional<InstructionCost>
3089 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
3091 ArrayRef<const Value *> Args, const Instruction *CtxI) const {
3092 // Vector unsigned division/remainder will be simplified to shifts/masks.
3093 if ((Opcode == Instruction::UDiv || Opcode == Instruction::URem) &&
3094 Opd2Info.isConstant() && Opd2Info.isPowerOf2()) {
3095 if (Opcode == Instruction::UDiv)
3096 return getArithmeticInstrCost(Instruction::LShr, Ty, CostKind, Opd1Info,
3097 Opd2Info.getNoProps());
3098 // UREM
3099 return getArithmeticInstrCost(Instruction::And, Ty, CostKind, Opd1Info,
3100 Opd2Info.getNoProps());
3101 }
3102 return std::nullopt;
3103}
3104
3106 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
3108 ArrayRef<const Value *> Args, const Instruction *CtxI,
3109 const TargetLibraryInfo *TLibInfo, ArrayRef<const Value *> Scalars) const {
3110
3111 // TODO: Handle more cost kinds.
3112 if (CostKind != TTI::TCK_RecipThroughput)
3113 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
3114 Args, CtxI, TLibInfo, Scalars);
3115
3116 if (isa<FixedVectorType>(Ty) && !ST->useRVVForFixedLengthVectors())
3117 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
3118 Args, CtxI, TLibInfo, Scalars);
3119
3120 // Skip if scalar size of Ty is bigger than ELEN.
3121 if (isa<VectorType>(Ty) && Ty->getScalarSizeInBits() > ST->getELen())
3122 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
3123 Args, CtxI, TLibInfo, Scalars);
3124
3125 if (std::optional<InstructionCost> CombinedCost =
3126 getCombinedArithmeticInstructionCost(Opcode, Ty, CostKind, Op1Info,
3127 Op2Info, Args, CtxI))
3128 return *CombinedCost;
3129
3130 // Legalize the type.
3131 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
3132 unsigned ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
3133
3134 // TODO: Handle scalar type.
3135 if (!LT.second.isVector()) {
3136 if (ISDOpcode == ISD::MUL && !ST->hasStdExtZmmul())
3137 return TTI::TCC_Expensive * LT.first;
3138
3139 static const CostTblEntry DivTbl[]{
3140 {ISD::UDIV, MVT::i32, TTI::TCC_Expensive},
3141 {ISD::UDIV, MVT::i64, TTI::TCC_Expensive},
3142 {ISD::SDIV, MVT::i32, TTI::TCC_Expensive},
3143 {ISD::SDIV, MVT::i64, TTI::TCC_Expensive},
3144 {ISD::UREM, MVT::i32, TTI::TCC_Expensive},
3145 {ISD::UREM, MVT::i64, TTI::TCC_Expensive},
3146 {ISD::SREM, MVT::i32, TTI::TCC_Expensive},
3147 {ISD::SREM, MVT::i64, TTI::TCC_Expensive}};
3148 if (TLI->isOperationLegalOrPromote(ISDOpcode, LT.second))
3149 if (const auto *Entry = CostTableLookup(DivTbl, ISDOpcode, LT.second))
3150 return Entry->Cost * LT.first;
3151
3152 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
3153 Args, CtxI, TLibInfo, Scalars);
3154 }
3155
3156 // f16 with zvfhmin and bf16 will be promoted to f32.
3157 // FIXME: nxv32[b]f16 will be custom lowered and split.
3158 InstructionCost CastCost = 0;
3159 if ((LT.second.getVectorElementType() == MVT::f16 ||
3160 LT.second.getVectorElementType() == MVT::bf16) &&
3161 TLI->getOperationAction(ISDOpcode, LT.second) ==
3163 MVT PromotedVT = TLI->getTypeToPromoteTo(ISDOpcode, LT.second);
3164 Type *PromotedTy = EVT(PromotedVT).getTypeForEVT(Ty->getContext());
3165 Type *LegalTy = EVT(LT.second).getTypeForEVT(Ty->getContext());
3166 // Add cost of extending arguments
3167 CastCost += LT.first * Args.size() *
3168 getCastInstrCost(Instruction::FPExt, PromotedTy, LegalTy,
3169 TTI::CastContextHint::None, CostKind);
3170 // Add cost of truncating result
3171 CastCost +=
3172 LT.first * getCastInstrCost(Instruction::FPTrunc, LegalTy, PromotedTy,
3173 TTI::CastContextHint::None, CostKind);
3174 // Compute cost of op in promoted type
3175 LT.second = PromotedVT;
3176 }
3177
3178 auto getConstantMatCost =
3179 [&](unsigned Operand, TTI::OperandValueInfo OpInfo) -> InstructionCost {
3180 if (OpInfo.isUniform() &&
3181 canSplatOperand(Opcode, Operand, Intrinsic::not_intrinsic))
3182 // Two sub-cases:
3183 // * Has a 5 bit immediate operand which can be splatted.
3184 // * Has a larger immediate which must be materialized in scalar register
3185 // We return 0 for both as we currently ignore the cost of materializing
3186 // scalar constants in GPRs.
3187 return 0;
3188
3189 return getConstantPoolLoadCost(Ty, CostKind);
3190 };
3191
3192 // Add the cost of materializing any constant vectors required.
3193 InstructionCost ConstantMatCost = 0;
3194 if (Op1Info.isConstant())
3195 ConstantMatCost += getConstantMatCost(0, Op1Info);
3196 if (Op2Info.isConstant())
3197 ConstantMatCost += getConstantMatCost(1, Op2Info);
3198
3199 unsigned Op;
3200 switch (ISDOpcode) {
3201 case ISD::ADD:
3202 case ISD::SUB:
3203 Op = RISCV::VADD_VV;
3204 break;
3205 case ISD::SHL:
3206 case ISD::SRL:
3207 case ISD::SRA:
3208 Op = RISCV::VSLL_VV;
3209 break;
3210 case ISD::AND:
3211 case ISD::OR:
3212 case ISD::XOR:
3213 Op = (Ty->getScalarSizeInBits() == 1) ? RISCV::VMAND_MM : RISCV::VAND_VV;
3214 break;
3215 case ISD::MUL:
3216 case ISD::MULHS:
3217 case ISD::MULHU:
3218 Op = RISCV::VMUL_VV;
3219 break;
3220 case ISD::SDIV:
3221 case ISD::UDIV:
3222 Op = RISCV::VDIV_VV;
3223 break;
3224 case ISD::SREM:
3225 case ISD::UREM:
3226 Op = RISCV::VREM_VV;
3227 break;
3228 case ISD::FADD:
3229 case ISD::FSUB:
3230 Op = RISCV::VFADD_VV;
3231 break;
3232 case ISD::FMUL:
3233 Op = RISCV::VFMUL_VV;
3234 break;
3235 case ISD::FDIV:
3236 Op = RISCV::VFDIV_VV;
3237 break;
3238 case ISD::FNEG:
3239 Op = RISCV::VFSGNJN_VV;
3240 break;
3241 default:
3242 // Assuming all other instructions have the same cost until a need arises to
3243 // differentiate them.
3244 return CastCost + ConstantMatCost +
3245 BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info,
3246 Args, CtxI, TLibInfo, Scalars);
3247 }
3248
3249 InstructionCost InstrCost = getRISCVInstructionCost(Op, LT.second, CostKind);
3250 // We use BasicTTIImpl to calculate scalar costs, which assumes floating point
3251 // ops are twice as expensive as integer ops. Do the same for vectors so
3252 // scalar floating point ops aren't cheaper than their vector equivalents.
3253 if (Ty->isFPOrFPVectorTy())
3254 InstrCost *= 2;
3255 return CastCost + ConstantMatCost + LT.first * InstrCost;
3256}
3257
3258// TODO: Deduplicate from TargetTransformInfoImplCRTPBase.
3260 ArrayRef<const Value *> Ptrs, const Value *Base,
3261 const TTI::PointersChainInfo &Info, Type *AccessTy,
3262 const TTI::TargetCostKind CostKind) const {
3264 // In the basic model we take into account GEP instructions only
3265 // (although here can come alloca instruction, a value, constants and/or
3266 // constant expressions, PHIs, bitcasts ... whatever allowed to be used as a
3267 // pointer). Typically, if Base is a not a GEP-instruction and all the
3268 // pointers are relative to the same base address, all the rest are
3269 // either GEP instructions, PHIs, bitcasts or constants. When we have same
3270 // base, we just calculate cost of each non-Base GEP as an ADD operation if
3271 // any their index is a non-const.
3272 // If no known dependencies between the pointers cost is calculated as a sum
3273 // of costs of GEP instructions.
3274 for (auto [I, V] : enumerate(Ptrs)) {
3275 const auto *GEP = dyn_cast<GetElementPtrInst>(V);
3276 if (!GEP)
3277 continue;
3278 if (Info.isSameBase() && V != Base) {
3279 if (GEP->hasAllConstantIndices())
3280 continue;
3281 // If the chain is unit-stride and BaseReg + stride*i is a legal
3282 // addressing mode, then presume the base GEP is sitting around in a
3283 // register somewhere and check if we can fold the offset relative to
3284 // it.
3285 unsigned Stride = DL.getTypeStoreSize(AccessTy);
3286 if (Info.isUnitStride() &&
3287 isLegalAddressingMode(AccessTy,
3288 /* BaseGV */ nullptr,
3289 /* BaseOffset */ Stride * I,
3290 /* HasBaseReg */ true,
3291 /* Scale */ 0,
3292 GEP->getType()->getPointerAddressSpace()))
3293 continue;
3294 Cost += getArithmeticInstrCost(Instruction::Add, GEP->getType(), CostKind,
3295 {TTI::OK_AnyValue, TTI::OP_None},
3296 {TTI::OK_AnyValue, TTI::OP_None}, {});
3297 } else {
3298 SmallVector<const Value *> Indices(GEP->indices());
3299 Cost += getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(),
3300 Indices, CostKind, AccessTy);
3301 }
3302 }
3303 return Cost;
3304}
3305
3308 OptimizationRemarkEmitter *ORE) const {
3309 // TODO: More tuning on benchmarks and metrics with changes as needed
3310 // would apply to all settings below to enable performance.
3311
3312 if (ST->enableDefaultUnroll())
3313 return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP, ORE);
3314
3315 // Unrolling an outer loop duplicates its inner loops while removing only
3316 // the outer backedge. Use the smaller code-growth budget for these loops,
3317 // even when aggressive full unrolling is enabled at O3.
3318 if (!L->isInnermost()) {
3319 UP.Threshold = std::min(UP.Threshold, UP.PartialThreshold);
3320 // If the loop cannot be fully unrolled within that budget, do not
3321 // partially unroll it either, as that would still duplicate the inner
3322 // loops. Loops with an unknown trip count are left unchanged.
3323 if (SE.getSmallConstantTripCount(L))
3324 UP.PartialThreshold = 0;
3325 }
3326
3327 // Enable Upper bound unrolling universally, not dependent upon the conditions
3328 // below.
3329 UP.UpperBound = true;
3330
3331 // Disable loop unrolling for Oz and Os.
3332 UP.OptSizeThreshold = 0;
3334 if (L->getHeader()->getParent()->hasOptSize())
3335 return;
3336
3337 SmallVector<BasicBlock *, 4> ExitingBlocks;
3338 L->getExitingBlocks(ExitingBlocks);
3339 LLVM_DEBUG(dbgs() << "Loop has:\n"
3340 << "Blocks: " << L->getNumBlocks() << "\n"
3341 << "Exit blocks: " << ExitingBlocks.size() << "\n");
3342
3343 // Only allow another exit other than the latch. This acts as an early exit
3344 // as it mirrors the profitability calculation of the runtime unroller.
3345 if (ExitingBlocks.size() > 2)
3346 return;
3347
3348 // Limit the CFG of the loop body for targets with a branch predictor.
3349 // Allowing 4 blocks permits if-then-else diamonds in the body.
3350 if (L->getNumBlocks() > 4)
3351 return;
3352
3353 // Scan the loop: don't unroll loops with calls as this could prevent
3354 // inlining. Don't unroll auto-vectorized loops either, though do allow
3355 // unrolling of the scalar remainder.
3356 bool IsVectorized = getBooleanLoopAttribute(L, "llvm.loop.isvectorized");
3358 for (auto *BB : L->getBlocks()) {
3359 for (auto &I : *BB) {
3360 // Both auto-vectorized loops and the scalar remainder have the
3361 // isvectorized attribute, so differentiate between them by the presence
3362 // of vector instructions.
3363 if (IsVectorized && (I.getType()->isVectorTy() ||
3364 llvm::any_of(I.operand_values(), [](Value *V) {
3365 return V->getType()->isVectorTy();
3366 })))
3367 return;
3368
3369 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
3370 const Function *F = cast<CallBase>(I).getCalledFunction();
3371 if (!F || isLoweredToCall(F))
3372 return;
3373 }
3374
3375 SmallVector<const Value *> Operands(I.operand_values());
3378 }
3379 }
3380
3381 LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
3382
3383 UP.Partial = true;
3384 UP.Runtime = true;
3385 UP.UnrollRemainder = true;
3386 UP.UnrollAndJam = true;
3387
3388 // Force unrolling small loops can be very useful because of the branch
3389 // taken cost of the backedge.
3390 if (Cost < 12)
3391 UP.Force = true;
3392}
3393
3398
3400 MemIntrinsicInfo &Info) const {
3401 const DataLayout &DL = getDataLayout();
3402 Intrinsic::ID IID = Inst->getIntrinsicID();
3403 LLVMContext &C = Inst->getContext();
3404 bool HasMask = false;
3405
3406 auto getSegNum = [](const IntrinsicInst *II, unsigned PtrOperandNo,
3407 bool IsWrite) -> int64_t {
3408 if (auto *TarExtTy =
3409 dyn_cast<TargetExtType>(II->getArgOperand(0)->getType()))
3410 return TarExtTy->getIntParameter(0);
3411
3412 return 1;
3413 };
3414
3415 switch (IID) {
3416 case Intrinsic::riscv_vle_mask:
3417 case Intrinsic::riscv_vse_mask:
3418 case Intrinsic::riscv_vlseg2_mask:
3419 case Intrinsic::riscv_vlseg3_mask:
3420 case Intrinsic::riscv_vlseg4_mask:
3421 case Intrinsic::riscv_vlseg5_mask:
3422 case Intrinsic::riscv_vlseg6_mask:
3423 case Intrinsic::riscv_vlseg7_mask:
3424 case Intrinsic::riscv_vlseg8_mask:
3425 case Intrinsic::riscv_vsseg2_mask:
3426 case Intrinsic::riscv_vsseg3_mask:
3427 case Intrinsic::riscv_vsseg4_mask:
3428 case Intrinsic::riscv_vsseg5_mask:
3429 case Intrinsic::riscv_vsseg6_mask:
3430 case Intrinsic::riscv_vsseg7_mask:
3431 case Intrinsic::riscv_vsseg8_mask:
3432 HasMask = true;
3433 [[fallthrough]];
3434 case Intrinsic::riscv_vle:
3435 case Intrinsic::riscv_vse:
3436 case Intrinsic::riscv_vlseg2:
3437 case Intrinsic::riscv_vlseg3:
3438 case Intrinsic::riscv_vlseg4:
3439 case Intrinsic::riscv_vlseg5:
3440 case Intrinsic::riscv_vlseg6:
3441 case Intrinsic::riscv_vlseg7:
3442 case Intrinsic::riscv_vlseg8:
3443 case Intrinsic::riscv_vsseg2:
3444 case Intrinsic::riscv_vsseg3:
3445 case Intrinsic::riscv_vsseg4:
3446 case Intrinsic::riscv_vsseg5:
3447 case Intrinsic::riscv_vsseg6:
3448 case Intrinsic::riscv_vsseg7:
3449 case Intrinsic::riscv_vsseg8: {
3450 // Intrinsic interface:
3451 // riscv_vle(merge, ptr, vl)
3452 // riscv_vle_mask(merge, ptr, mask, vl, policy)
3453 // riscv_vse(val, ptr, vl)
3454 // riscv_vse_mask(val, ptr, mask, vl, policy)
3455 // riscv_vlseg#(merge, ptr, vl, sew)
3456 // riscv_vlseg#_mask(merge, ptr, mask, vl, policy, sew)
3457 // riscv_vsseg#(val, ptr, vl, sew)
3458 // riscv_vsseg#_mask(val, ptr, mask, vl, sew)
3459 bool IsWrite = Inst->getType()->isVoidTy();
3460 Type *Ty = IsWrite ? Inst->getArgOperand(0)->getType() : Inst->getType();
3461 // The results of segment loads are TargetExtType.
3462 if (auto *TarExtTy = dyn_cast<TargetExtType>(Ty)) {
3463 unsigned SEW =
3464 1 << cast<ConstantInt>(Inst->getArgOperand(Inst->arg_size() - 1))
3465 ->getZExtValue();
3466 Ty = TarExtTy->getTypeParameter(0U);
3468 IntegerType::get(C, SEW),
3469 cast<ScalableVectorType>(Ty)->getMinNumElements() * 8 / SEW);
3470 }
3471 const auto *RVVIInfo = RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IID);
3472 unsigned VLIndex = RVVIInfo->VLOperand;
3473 unsigned PtrOperandNo = VLIndex - 1 - HasMask;
3474 MaybeAlign Alignment =
3475 Inst->getArgOperand(PtrOperandNo)->getPointerAlignment(DL);
3476 Type *MaskType = Ty->getWithNewType(Type::getInt1Ty(C));
3477 Value *Mask = ConstantInt::getTrue(MaskType);
3478 if (HasMask)
3479 Mask = Inst->getArgOperand(VLIndex - 1);
3480 Value *EVL = Inst->getArgOperand(VLIndex);
3481 unsigned SegNum = getSegNum(Inst, PtrOperandNo, IsWrite);
3482 // RVV uses contiguous elements as a segment.
3483 if (SegNum > 1) {
3484 unsigned ElemSize = Ty->getScalarSizeInBits();
3485 auto *SegTy = IntegerType::get(C, ElemSize * SegNum);
3486 Ty = VectorType::get(SegTy, cast<VectorType>(Ty));
3487 }
3488 Info.InterestingOperands.emplace_back(Inst, PtrOperandNo, IsWrite, Ty,
3489 Alignment, Mask, EVL);
3490 return true;
3491 }
3492 case Intrinsic::riscv_vlse_mask:
3493 case Intrinsic::riscv_vsse_mask:
3494 case Intrinsic::riscv_vlsseg2_mask:
3495 case Intrinsic::riscv_vlsseg3_mask:
3496 case Intrinsic::riscv_vlsseg4_mask:
3497 case Intrinsic::riscv_vlsseg5_mask:
3498 case Intrinsic::riscv_vlsseg6_mask:
3499 case Intrinsic::riscv_vlsseg7_mask:
3500 case Intrinsic::riscv_vlsseg8_mask:
3501 case Intrinsic::riscv_vssseg2_mask:
3502 case Intrinsic::riscv_vssseg3_mask:
3503 case Intrinsic::riscv_vssseg4_mask:
3504 case Intrinsic::riscv_vssseg5_mask:
3505 case Intrinsic::riscv_vssseg6_mask:
3506 case Intrinsic::riscv_vssseg7_mask:
3507 case Intrinsic::riscv_vssseg8_mask:
3508 HasMask = true;
3509 [[fallthrough]];
3510 case Intrinsic::riscv_vlse:
3511 case Intrinsic::riscv_vsse:
3512 case Intrinsic::riscv_vlsseg2:
3513 case Intrinsic::riscv_vlsseg3:
3514 case Intrinsic::riscv_vlsseg4:
3515 case Intrinsic::riscv_vlsseg5:
3516 case Intrinsic::riscv_vlsseg6:
3517 case Intrinsic::riscv_vlsseg7:
3518 case Intrinsic::riscv_vlsseg8:
3519 case Intrinsic::riscv_vssseg2:
3520 case Intrinsic::riscv_vssseg3:
3521 case Intrinsic::riscv_vssseg4:
3522 case Intrinsic::riscv_vssseg5:
3523 case Intrinsic::riscv_vssseg6:
3524 case Intrinsic::riscv_vssseg7:
3525 case Intrinsic::riscv_vssseg8: {
3526 // Intrinsic interface:
3527 // riscv_vlse(merge, ptr, stride, vl)
3528 // riscv_vlse_mask(merge, ptr, stride, mask, vl, policy)
3529 // riscv_vsse(val, ptr, stride, vl)
3530 // riscv_vsse_mask(val, ptr, stride, mask, vl, policy)
3531 // riscv_vlsseg#(merge, ptr, offset, vl, sew)
3532 // riscv_vlsseg#_mask(merge, ptr, offset, mask, vl, policy, sew)
3533 // riscv_vssseg#(val, ptr, offset, vl, sew)
3534 // riscv_vssseg#_mask(val, ptr, offset, mask, vl, sew)
3535 bool IsWrite = Inst->getType()->isVoidTy();
3536 Type *Ty = IsWrite ? Inst->getArgOperand(0)->getType() : Inst->getType();
3537 // The results of segment loads are TargetExtType.
3538 if (auto *TarExtTy = dyn_cast<TargetExtType>(Ty)) {
3539 unsigned SEW =
3540 1 << cast<ConstantInt>(Inst->getArgOperand(Inst->arg_size() - 1))
3541 ->getZExtValue();
3542 Ty = TarExtTy->getTypeParameter(0U);
3544 IntegerType::get(C, SEW),
3545 cast<ScalableVectorType>(Ty)->getMinNumElements() * 8 / SEW);
3546 }
3547 const auto *RVVIInfo = RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IID);
3548 unsigned VLIndex = RVVIInfo->VLOperand;
3549 unsigned PtrOperandNo = VLIndex - 2 - HasMask;
3550 MaybeAlign Alignment =
3551 Inst->getArgOperand(PtrOperandNo)->getPointerAlignment(DL);
3552
3553 Value *Stride = Inst->getArgOperand(PtrOperandNo + 1);
3554 // Use the pointer alignment as the element alignment if the stride is a
3555 // multiple of the pointer alignment. Otherwise, the element alignment
3556 // should be the greatest common divisor of pointer alignment and stride.
3557 // For simplicity, just consider unalignment for elements.
3558 unsigned PointerAlign = Alignment.valueOrOne().value();
3559 if (!isa<ConstantInt>(Stride) ||
3560 cast<ConstantInt>(Stride)->getZExtValue() % PointerAlign != 0)
3561 Alignment = Align(1);
3562
3563 Type *MaskType = Ty->getWithNewType(Type::getInt1Ty(C));
3564 Value *Mask = ConstantInt::getTrue(MaskType);
3565 if (HasMask)
3566 Mask = Inst->getArgOperand(VLIndex - 1);
3567 Value *EVL = Inst->getArgOperand(VLIndex);
3568 unsigned SegNum = getSegNum(Inst, PtrOperandNo, IsWrite);
3569 // RVV uses contiguous elements as a segment.
3570 if (SegNum > 1) {
3571 unsigned ElemSize = Ty->getScalarSizeInBits();
3572 auto *SegTy = IntegerType::get(C, ElemSize * SegNum);
3573 Ty = VectorType::get(SegTy, cast<VectorType>(Ty));
3574 }
3575 Info.InterestingOperands.emplace_back(Inst, PtrOperandNo, IsWrite, Ty,
3576 Alignment, Mask, EVL, Stride);
3577 return true;
3578 }
3579 case Intrinsic::riscv_vloxei_mask:
3580 case Intrinsic::riscv_vluxei_mask:
3581 case Intrinsic::riscv_vsoxei_mask:
3582 case Intrinsic::riscv_vsuxei_mask:
3583 case Intrinsic::riscv_vloxseg2_mask:
3584 case Intrinsic::riscv_vloxseg3_mask:
3585 case Intrinsic::riscv_vloxseg4_mask:
3586 case Intrinsic::riscv_vloxseg5_mask:
3587 case Intrinsic::riscv_vloxseg6_mask:
3588 case Intrinsic::riscv_vloxseg7_mask:
3589 case Intrinsic::riscv_vloxseg8_mask:
3590 case Intrinsic::riscv_vluxseg2_mask:
3591 case Intrinsic::riscv_vluxseg3_mask:
3592 case Intrinsic::riscv_vluxseg4_mask:
3593 case Intrinsic::riscv_vluxseg5_mask:
3594 case Intrinsic::riscv_vluxseg6_mask:
3595 case Intrinsic::riscv_vluxseg7_mask:
3596 case Intrinsic::riscv_vluxseg8_mask:
3597 case Intrinsic::riscv_vsoxseg2_mask:
3598 case Intrinsic::riscv_vsoxseg3_mask:
3599 case Intrinsic::riscv_vsoxseg4_mask:
3600 case Intrinsic::riscv_vsoxseg5_mask:
3601 case Intrinsic::riscv_vsoxseg6_mask:
3602 case Intrinsic::riscv_vsoxseg7_mask:
3603 case Intrinsic::riscv_vsoxseg8_mask:
3604 case Intrinsic::riscv_vsuxseg2_mask:
3605 case Intrinsic::riscv_vsuxseg3_mask:
3606 case Intrinsic::riscv_vsuxseg4_mask:
3607 case Intrinsic::riscv_vsuxseg5_mask:
3608 case Intrinsic::riscv_vsuxseg6_mask:
3609 case Intrinsic::riscv_vsuxseg7_mask:
3610 case Intrinsic::riscv_vsuxseg8_mask:
3611 HasMask = true;
3612 [[fallthrough]];
3613 case Intrinsic::riscv_vloxei:
3614 case Intrinsic::riscv_vluxei:
3615 case Intrinsic::riscv_vsoxei:
3616 case Intrinsic::riscv_vsuxei:
3617 case Intrinsic::riscv_vloxseg2:
3618 case Intrinsic::riscv_vloxseg3:
3619 case Intrinsic::riscv_vloxseg4:
3620 case Intrinsic::riscv_vloxseg5:
3621 case Intrinsic::riscv_vloxseg6:
3622 case Intrinsic::riscv_vloxseg7:
3623 case Intrinsic::riscv_vloxseg8:
3624 case Intrinsic::riscv_vluxseg2:
3625 case Intrinsic::riscv_vluxseg3:
3626 case Intrinsic::riscv_vluxseg4:
3627 case Intrinsic::riscv_vluxseg5:
3628 case Intrinsic::riscv_vluxseg6:
3629 case Intrinsic::riscv_vluxseg7:
3630 case Intrinsic::riscv_vluxseg8:
3631 case Intrinsic::riscv_vsoxseg2:
3632 case Intrinsic::riscv_vsoxseg3:
3633 case Intrinsic::riscv_vsoxseg4:
3634 case Intrinsic::riscv_vsoxseg5:
3635 case Intrinsic::riscv_vsoxseg6:
3636 case Intrinsic::riscv_vsoxseg7:
3637 case Intrinsic::riscv_vsoxseg8:
3638 case Intrinsic::riscv_vsuxseg2:
3639 case Intrinsic::riscv_vsuxseg3:
3640 case Intrinsic::riscv_vsuxseg4:
3641 case Intrinsic::riscv_vsuxseg5:
3642 case Intrinsic::riscv_vsuxseg6:
3643 case Intrinsic::riscv_vsuxseg7:
3644 case Intrinsic::riscv_vsuxseg8: {
3645 // Intrinsic interface (only listed ordered version):
3646 // riscv_vloxei(merge, ptr, index, vl)
3647 // riscv_vloxei_mask(merge, ptr, index, mask, vl, policy)
3648 // riscv_vsoxei(val, ptr, index, vl)
3649 // riscv_vsoxei_mask(val, ptr, index, mask, vl, policy)
3650 // riscv_vloxseg#(merge, ptr, index, vl, sew)
3651 // riscv_vloxseg#_mask(merge, ptr, index, mask, vl, policy, sew)
3652 // riscv_vsoxseg#(val, ptr, index, vl, sew)
3653 // riscv_vsoxseg#_mask(val, ptr, index, mask, vl, sew)
3654 bool IsWrite = Inst->getType()->isVoidTy();
3655 Type *Ty = IsWrite ? Inst->getArgOperand(0)->getType() : Inst->getType();
3656 // The results of segment loads are TargetExtType.
3657 if (auto *TarExtTy = dyn_cast<TargetExtType>(Ty)) {
3658 unsigned SEW =
3659 1 << cast<ConstantInt>(Inst->getArgOperand(Inst->arg_size() - 1))
3660 ->getZExtValue();
3661 Ty = TarExtTy->getTypeParameter(0U);
3663 IntegerType::get(C, SEW),
3664 cast<ScalableVectorType>(Ty)->getMinNumElements() * 8 / SEW);
3665 }
3666 const auto *RVVIInfo = RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IID);
3667 unsigned VLIndex = RVVIInfo->VLOperand;
3668 unsigned PtrOperandNo = VLIndex - 2 - HasMask;
3669 Value *Mask;
3670 if (HasMask) {
3671 Mask = Inst->getArgOperand(VLIndex - 1);
3672 } else {
3673 // Mask cannot be nullptr here: vector GEP produces <vscale x N x ptr>,
3674 // and casting that to scalar i64 triggers a vector/scalar mismatch
3675 // assertion in CreatePointerCast. Use an all-true mask so ASan lowers it
3676 // via extractelement instead.
3677 Type *MaskType = Ty->getWithNewType(Type::getInt1Ty(C));
3678 Mask = ConstantInt::getTrue(MaskType);
3679 }
3680 Value *EVL = Inst->getArgOperand(VLIndex);
3681 unsigned SegNum = getSegNum(Inst, PtrOperandNo, IsWrite);
3682 // RVV uses contiguous elements as a segment.
3683 if (SegNum > 1) {
3684 unsigned ElemSize = Ty->getScalarSizeInBits();
3685 auto *SegTy = IntegerType::get(C, ElemSize * SegNum);
3686 Ty = VectorType::get(SegTy, cast<VectorType>(Ty));
3687 }
3688 Value *OffsetOp = Inst->getArgOperand(PtrOperandNo + 1);
3689 Info.InterestingOperands.emplace_back(Inst, PtrOperandNo, IsWrite, Ty,
3690 Align(1), Mask, EVL,
3691 /* Stride */ nullptr, OffsetOp);
3692 return true;
3693 }
3694 }
3695 return false;
3696}
3697
3699 if (Ty->isVectorTy()) {
3700 // f16 with only zvfhmin and bf16 will be promoted to f32
3701 Type *EltTy = cast<VectorType>(Ty)->getElementType();
3702 if ((EltTy->isHalfTy() && !ST->hasVInstructionsF16()) ||
3703 EltTy->isBFloatTy())
3704 Ty = VectorType::get(Type::getFloatTy(Ty->getContext()),
3705 cast<VectorType>(Ty));
3706
3707 TypeSize Size = DL.getTypeSizeInBits(Ty);
3708 if (Size.isScalable() && ST->hasVInstructions())
3709 return divideCeil(Size.getKnownMinValue(), RISCV::RVVBitsPerBlock);
3710
3711 if (ST->useRVVForFixedLengthVectors())
3712 return divideCeil(Size, ST->getRealMinVLen());
3713 }
3714
3715 return BaseT::getRegUsageForType(Ty);
3716}
3717
3718unsigned RISCVTTIImpl::getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
3719 if (std::optional<unsigned> MaxVF = ST->getCLOpts().v_slp_max_vf)
3720 return *MaxVF;
3721
3722 // Return how many elements can fit in getRegisterBitwidth. This is the
3723 // same routine as used in LoopVectorizer. We should probably be
3724 // accounting for whether we actually have instructions with the right
3725 // lane type, but we don't have enough information to do that without
3726 // some additional plumbing which hasn't been justified yet.
3727 TypeSize RegWidth =
3729 // If no vector registers, or absurd element widths, disable
3730 // vectorization by returning 1.
3731 return std::max<unsigned>(1U, RegWidth.getFixedValue() / ElemWidth);
3732}
3733
3735 return ST->getCLOpts().v_min_trip_count;
3736}
3737
3739 return ST->enableUnalignedVectorMem();
3740}
3741
3744 ScalarEvolution *SE) const {
3745 if (ST->hasVendorXCVmem() && !ST->is64Bit())
3746 return TTI::AMK_PostIndexed;
3747
3749}
3750
3752 const TargetTransformInfo::LSRCost &C2) const {
3753 // RISC-V specific here are "instruction number 1st priority".
3754 // If we need to emit adds inside the loop to add up base registers, then
3755 // we need at least one extra temporary register.
3756 unsigned C1NumRegs = C1.NumRegs + (C1.NumBaseAdds != 0);
3757 unsigned C2NumRegs = C2.NumRegs + (C2.NumBaseAdds != 0);
3758 return std::tie(C1.Insns, C1NumRegs, C1.AddRecCost,
3759 C1.NumIVMuls, C1.NumBaseAdds,
3760 C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
3761 std::tie(C2.Insns, C2NumRegs, C2.AddRecCost,
3762 C2.NumIVMuls, C2.NumBaseAdds,
3763 C2.ScaleCost, C2.ImmCost, C2.SetupCost);
3764}
3765
3767 Align Alignment) const {
3768 auto *VTy = dyn_cast<VectorType>(DataTy);
3769 if (!VTy)
3770 return false;
3771
3772 if (!isLegalMaskedLoadStore(DataTy, Alignment))
3773 return false;
3774
3775 // FIXME: If it is an i8 vector and the element count exceeds 256, we should
3776 // scalarize these types with LMUL >= maximum fixed-length LMUL.
3777 if (VTy->getElementType()->isIntegerTy(8)) {
3778 uint64_t MaxEltCount = VTy->getElementCount().getKnownMinValue();
3779 if (VTy->isScalableTy())
3780 MaxEltCount *= ST->getRealMaxVLen() / RISCV::RVVBitsPerBlock;
3781 // We can't yet split any widened indices type.
3782 if (MaxEltCount > 256)
3784 VTy->getWithNewType(Type::getInt16Ty(VTy->getContext())))
3785 .first == 1;
3786 }
3787 return true;
3788}
3789
3791 Align Alignment) const {
3792 return isLegalMaskedLoadStore(DataTy, Alignment);
3793}
3794
3796 ElementCount NumElements) const {
3797 // Optimized zero-stride loads can be treated as broadcasts.
3798 if (!ST->hasVInstructions() || !ST->hasOptimizedZeroStrideLoad())
3799 return false;
3800
3801 return TLI->isLegalElementTypeForRVV(TLI->getValueType(DL, ElementTy));
3802}
3803
3804/// See if \p I should be considered for address type promotion. We check if \p
3805/// I is a sext with right type and used in memory accesses. If it used in a
3806/// "complex" getelementptr, we allow it to be promoted without finding other
3807/// sext instructions that sign extended the same initial value. A getelementptr
3808/// is considered as "complex" if it has more than 2 operands.
3810 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const {
3811 bool Considerable = false;
3812 AllowPromotionWithoutCommonHeader = false;
3813 if (!isa<SExtInst>(&I))
3814 return false;
3815 Type *ConsideredSExtType =
3816 Type::getInt64Ty(I.getParent()->getParent()->getContext());
3817 if (I.getType() != ConsideredSExtType)
3818 return false;
3819 // See if the sext is the one with the right type and used in at least one
3820 // GetElementPtrInst.
3821 for (const User *U : I.users()) {
3822 if (const GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
3823 Considerable = true;
3824 // A getelementptr is considered as "complex" if it has more than 2
3825 // operands. We will promote a SExt used in such complex GEP as we
3826 // expect some computation to be merged if they are done on 64 bits.
3827 if (GEPInst->getNumOperands() > 2) {
3828 AllowPromotionWithoutCommonHeader = true;
3829 break;
3830 }
3831 }
3832 }
3833 return Considerable;
3834}
3835
3836bool RISCVTTIImpl::canSplatOperand(unsigned Opcode, int Operand,
3837 Intrinsic::ID IntrinsicID) const {
3838 switch (Opcode) {
3839 case Instruction::Add:
3840 case Instruction::Sub:
3841 case Instruction::Mul:
3842 case Instruction::And:
3843 case Instruction::Or:
3844 case Instruction::Xor:
3845 case Instruction::FAdd:
3846 case Instruction::FSub:
3847 case Instruction::FMul:
3848 case Instruction::FDiv:
3849 case Instruction::ICmp:
3850 case Instruction::FCmp:
3851 return true;
3852 case Instruction::Shl:
3853 case Instruction::LShr:
3854 case Instruction::AShr:
3855 case Instruction::UDiv:
3856 case Instruction::SDiv:
3857 case Instruction::URem:
3858 case Instruction::SRem:
3859 case Instruction::Select:
3860 return Operand == 1;
3861 case Instruction::Call:
3862 switch (IntrinsicID) {
3863 case Intrinsic::fma:
3864 case Intrinsic::fmuladd:
3865 return Operand == 0 || Operand == 1;
3866 case Intrinsic::vp_udiv:
3867 case Intrinsic::vp_sdiv:
3868 case Intrinsic::vp_urem:
3869 case Intrinsic::vp_srem:
3870 case Intrinsic::ssub_sat:
3871 case Intrinsic::usub_sat:
3872 return Operand == 1;
3873 // These intrinsics are commutative.
3874 case Intrinsic::smin:
3875 case Intrinsic::umin:
3876 case Intrinsic::smax:
3877 case Intrinsic::umax:
3878 case Intrinsic::sadd_sat:
3879 case Intrinsic::uadd_sat:
3880 return Operand == 0 || Operand == 1;
3881 default:
3882 return false;
3883 }
3884 default:
3885 return false;
3886 }
3887}
3888
3890 if (!I->getType()->isVectorTy() || !ST->hasVInstructions())
3891 return false;
3892
3893 auto *II = dyn_cast<IntrinsicInst>(I);
3895 if (II)
3896 IntrinsicID = II->getIntrinsicID();
3897
3898 return canSplatOperand(I->getOpcode(), Operand, IntrinsicID);
3899}
3900
3902 ArrayRef<int> Mask, ArrayRef<Value *> Scalars,
3904 GatherUseOps) const {
3905 if (Scalars.empty() || !ST->hasVInstructions() || !ST->sinkSplatOperands() ||
3906 !ShuffleVectorInst::isZeroEltSplatMask(Mask, Mask.size()))
3908
3909 const auto *SplatIt = find_if_not(Scalars, IsaPred<UndefValue>);
3910 if (SplatIt == Scalars.end() || (*SplatIt)->getType()->isIntegerTy(1) ||
3911 isa<VectorType>((*SplatIt)->getType()) ||
3912 isa<ExtractElementInst>(*SplatIt))
3914
3916 if (!GatherUseOps(UserOps) || UserOps.empty())
3918
3919 if (all_of(UserOps,
3920 [this](const TargetTransformInfo::BuildVectorUseOp &UserOp) {
3921 return canSplatOperand(UserOp.Opcode, UserOp.OperandIndex,
3922 UserOp.IntrinsicID);
3923 }))
3925
3927}
3928
3929/// Check if sinking \p I's operands to I's basic block is profitable, because
3930/// the operands can be folded into a target instruction, e.g.
3931/// splats of scalars can fold into vector instructions.
3934 using namespace llvm::PatternMatch;
3935
3936 if (I->isBitwiseLogicOp()) {
3937 if (!I->getType()->isVectorTy()) {
3938 if (ST->hasStdExtZbb() || ST->hasStdExtZbkb()) {
3939 for (auto &Op : I->operands()) {
3940 // (and/or/xor X, (not Y)) -> (andn/orn/xnor X, Y)
3941 if (match(Op.get(), m_Not(m_Value()))) {
3942 Ops.push_back(&Op);
3943 return true;
3944 }
3945 }
3946 }
3947 } else if (I->getOpcode() == Instruction::And && ST->hasStdExtZvkb()) {
3948 for (auto &Op : I->operands()) {
3949 // (and X, (not Y)) -> (vandn.vv X, Y)
3950 if (match(Op.get(), m_Not(m_Value()))) {
3951 Ops.push_back(&Op);
3952 return true;
3953 }
3954 // (and X, (splat (not Y))) -> (vandn.vx X, Y)
3956 m_ZeroInt()),
3957 m_Value(), m_ZeroMask()))) {
3958 Use &InsertElt = cast<Instruction>(Op)->getOperandUse(0);
3959 Use &Not = cast<Instruction>(InsertElt)->getOperandUse(1);
3960 Ops.push_back(&Not);
3961 Ops.push_back(&InsertElt);
3962 Ops.push_back(&Op);
3963 return true;
3964 }
3965 }
3966 }
3967 }
3968
3969 if (!I->getType()->isVectorTy() || !ST->hasVInstructions())
3970 return false;
3971
3972 // Don't sink splat operands if the target prefers it. Some targets requires
3973 // S2V transfer buffers and we can run out of them copying the same value
3974 // repeatedly.
3975 // FIXME: It could still be worth doing if it would improve vector register
3976 // pressure and prevent a vector spill.
3977 if (!ST->sinkSplatOperands())
3978 return false;
3979
3980 for (auto OpIdx : enumerate(I->operands())) {
3981 if (!canSplatOperand(I, OpIdx.index()))
3982 continue;
3983
3984 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
3985 // Make sure we are not already sinking this operand
3986 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
3987 continue;
3988
3989 // We are looking for a splat that can be sunk.
3991 m_Value(), m_ZeroMask())))
3992 continue;
3993
3994 // Don't sink i1 splats.
3995 if (cast<VectorType>(Op->getType())->getElementType()->isIntegerTy(1))
3996 continue;
3997
3998 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
3999 // and vector registers
4000 for (Use &U : Op->uses()) {
4001 Instruction *Insn = cast<Instruction>(U.getUser());
4002 if (!canSplatOperand(Insn, U.getOperandNo()))
4003 return false;
4004 }
4005
4006 // Sink any fpexts since they might be used in a widening fp pattern.
4007 Use *InsertEltUse = &Op->getOperandUse(0);
4008 auto *InsertElt = cast<InsertElementInst>(InsertEltUse);
4009 if (isa<FPExtInst>(InsertElt->getOperand(1)))
4010 Ops.push_back(&InsertElt->getOperandUse(1));
4011 Ops.push_back(InsertEltUse);
4012 Ops.push_back(&OpIdx.value());
4013 }
4014 return true;
4015}
4016
4018RISCVTTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
4020
4021 if (!ST->hasStdExtZbb() && !ST->hasStdExtZbkb() && !IsZeroCmp)
4022 return Options;
4023
4024 Options.AllowOverlappingLoads = true;
4025 Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
4026 Options.NumLoadsPerBlock = IsZeroCmp ? Options.MaxNumLoads : 1;
4027 if (ST->is64Bit()) {
4028 Options.LoadSizes = {8, 4, 2, 1};
4029 Options.AllowedTailExpansions = {3, 5, 6};
4030 } else {
4031 Options.LoadSizes = {4, 2, 1};
4032 Options.AllowedTailExpansions = {3};
4033 }
4034
4035 if (IsZeroCmp && ST->hasVInstructions()) {
4036 unsigned VLenB = ST->getRealMinVLen() / 8;
4037 // The minimum size should be `XLen / 8 + 1`, and the maxinum size should be
4038 // `VLenB * MaxLMUL` so that it fits in a single register group.
4039 unsigned MinSize = ST->getXLen() / 8 + 1;
4040 unsigned MaxSize = VLenB * 8;
4041 for (unsigned Size = MinSize; Size <= MaxSize; Size++)
4042 Options.LoadSizes.insert(Options.LoadSizes.begin(), Size);
4043 }
4044 return Options;
4045}
4046
4048 const Instruction *I) const {
4049 if (ST->getCLOpts().or_like_select) {
4050 // For the binary operators (e.g. or) we need to be more careful than
4051 // selects, here we only transform them if they are already at a natural
4052 // break point in the code - the end of a block with an unconditional
4053 // terminator.
4054 if (I->getOpcode() == Instruction::Or &&
4055 isa<UncondBrInst>(I->getNextNode()))
4056 return true;
4057
4058 if (I->getOpcode() == Instruction::Add ||
4059 I->getOpcode() == Instruction::Sub)
4060 return true;
4061 }
4063}
4064
4066 const Function *Caller, const Attribute &Attr) const {
4067 // "interrupt" controls the prolog/epilog of interrupt handlers (and includes
4068 // restrictions on their signatures). We can outline from the bodies of these
4069 // handlers, but when we do we need to make sure we don't mark the outlined
4070 // function as an interrupt handler too.
4071 if (Attr.isStringAttribute() && Attr.getKindAsString() == "interrupt")
4072 return false;
4073
4075}
4076
4077std::optional<Instruction *>
4079 // Attach a range return attribute describing the result of vsetvli/vsetvlimax
4080 // so generic value analyses can reason about it. The verifier guarantees an
4081 // XLen result and constant VSEW/VLMUL encoding a valid vtype, so no defensive
4082 // validation is needed here.
4083 if (is_contained({Intrinsic::riscv_vsetvli, Intrinsic::riscv_vsetvlimax},
4084 II.getIntrinsicID())) {
4085 // These intrinsics require the V extension; without it the VLEN queries
4086 // below would assert. Such IR would fail isel anyway, so just bail out.
4087 if (!ST->hasVInstructions())
4088 return {};
4089
4090 bool HasAVL = II.getIntrinsicID() == Intrinsic::riscv_vsetvli;
4091 unsigned Offset = HasAVL ? 1 : 0;
4092 unsigned BitWidth = II.getType()->getIntegerBitWidth();
4093 ConstantRange VLenRange(APInt(BitWidth, ST->getRealMinVLen()),
4094 APInt(BitWidth, ST->getRealMaxVLen()) + 1);
4095
4096 uint64_t VSEW = cast<ConstantInt>(II.getArgOperand(Offset))->getZExtValue();
4097 auto VLMUL = static_cast<RISCVVType::VLMUL>(
4098 cast<ConstantInt>(II.getArgOperand(Offset + 1))->getZExtValue());
4099 unsigned SEW = RISCVVType::decodeVSEW(VSEW);
4100 unsigned Ratio = RISCVVType::getSEWLMULRatio(SEW, VLMUL);
4101
4102 // VLMAX = VLEN / (SEW / LMUL), clamped to >= 1 for any usable vtype.
4103 ConstantRange VLMAXRange =
4104 VLenRange.udiv(ConstantRange(APInt(BitWidth, Ratio)))
4106
4107 // vsetvlimax returns exactly VLMAX; vsetvli returns vl with
4108 // 0 <= vl <= min(AVL, VLMAX). vl == AVL only when AVL <= the smallest
4109 // possible VLMAX; otherwise vl can shrink below VLMAX (to 0 at runtime), so
4110 // only the VLMAX upper bound is sound.
4111 ConstantRange VLRange = VLMAXRange;
4112 if (HasAVL) {
4113 // vl ≤ VLMAX
4114 VLRange =
4116
4117 Value *AVL = II.getArgOperand(0);
4119 AVL, /*ForSigned=*/false,
4121
4122 // vl = AVL if AVL ≤ VLMAX
4123 if (AVLRange.icmp(CmpInst::ICMP_ULE, VLMAXRange))
4124 return IC.replaceInstUsesWith(II, AVL);
4125
4126 // vl ≤ AVL
4127 VLRange = VLRange.umin(AVLRange.getUnsignedMax());
4128
4129 // vl > 0 if AVL > 0
4131 VLRange = VLRange.umax(APInt(BitWidth, 1));
4132
4133 // vl = VLMAX if AVL ≥ (2 * VLMAX)
4134 ConstantRange TwoVLMAX = VLMAXRange.multiply(APInt(BitWidth, 2));
4135 if (AVLRange.icmp(CmpInst::ICMP_UGE, TwoVLMAX))
4136 VLRange = VLRange.intersectWith(VLMAXRange);
4137
4138 // ceil(AVL / 2) ≤ vl ≤ VLMAX if AVL < (2 * VLMAX)
4139 if (AVLRange.icmp(CmpInst::ICMP_ULT, TwoVLMAX))
4140 VLRange = VLRange.umax(APIntOps::RoundingUDiv(AVLRange.getUnsignedMin(),
4141 APInt(BitWidth, 2),
4143 }
4144
4145 ConstantRange OldRange =
4146 II.getRange().value_or(ConstantRange::getFull(BitWidth));
4147 ConstantRange NewRange = VLRange.intersectWith(OldRange);
4148 if (NewRange != OldRange) {
4149 II.addRangeRetAttr(NewRange);
4150 return &II;
4151 }
4152 return {};
4153 }
4154
4155 // If all operands of a vmv.v.x are constant, fold a bitcast(vmv.v.x) to scale
4156 // the vmv.v.x, enabling removal of the bitcast. The transform helps avoid
4157 // creating redundant masks.
4158 const DataLayout &DL = IC.getDataLayout();
4159 if (II.user_empty())
4160 return {};
4161 auto *TargetVecTy = dyn_cast<ScalableVectorType>(II.user_back()->getType());
4162 if (!TargetVecTy)
4163 return {};
4164 const APInt *Scalar;
4165 uint64_t VL;
4167 m_Poison(), m_APInt(Scalar), m_ConstantInt(VL))) ||
4168 !all_of(II.users(), [TargetVecTy](User *U) {
4169 return U->getType() == TargetVecTy && match(U, m_BitCast(m_Value()));
4170 }))
4171 return {};
4172 auto *SourceVecTy = cast<ScalableVectorType>(II.getType());
4173 unsigned TargetEltBW = DL.getTypeSizeInBits(TargetVecTy->getElementType());
4174 unsigned SourceEltBW = DL.getTypeSizeInBits(SourceVecTy->getElementType());
4175 if (TargetEltBW % SourceEltBW)
4176 return {};
4177 unsigned TargetScale = TargetEltBW / SourceEltBW;
4178 if (VL % TargetScale || TargetScale == 1)
4179 return {};
4180 Type *VLTy = II.getOperand(2)->getType();
4181 ElementCount SourceEC = SourceVecTy->getElementCount();
4182 unsigned NewEltBW = SourceEltBW * TargetScale;
4183 if (!SourceEC.isKnownMultipleOf(TargetScale) ||
4184 !DL.fitsInLegalInteger(NewEltBW))
4185 return {};
4186 auto *NewEltTy = IntegerType::get(II.getContext(), NewEltBW);
4187 if (!TLI->isLegalElementTypeForRVV(TLI->getValueType(DL, NewEltTy)))
4188 return {};
4189 ElementCount NewEC = SourceEC.divideCoefficientBy(TargetScale);
4190 Type *RetTy = VectorType::get(NewEltTy, NewEC);
4191 assert(SourceVecTy->canLosslesslyBitCastTo(RetTy) &&
4192 "Lossless bitcast between types expected");
4193 APInt NewScalar = APInt::getSplat(NewEltBW, *Scalar);
4194 return IC.replaceInstUsesWith(
4195 II,
4198 RetTy, Intrinsic::riscv_vmv_v_x,
4199 {PoisonValue::get(RetTy), ConstantInt::get(NewEltTy, NewScalar),
4200 ConstantInt::get(VLTy, VL / TargetScale)}),
4201 SourceVecTy));
4202}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
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 bool shouldSplit(Instruction *InsertPoint, DenseSet< Value * > &PrevConditionValues, DenseSet< Value * > &ConditionValues, DominatorTree &DT, DenseSet< Instruction * > &Unhoistables)
Cost tables and simple lookup functions.
Hexagon Common GEP
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
int64_t C1
static InstructionCost costShuffleViaVRegSplitting(const RISCVTTIImpl &TTI, MVT LegalVT, std::optional< unsigned > VLen, VectorType *Tp, ArrayRef< int > Mask, TTI::TargetCostKind CostKind)
Try to perform better estimation of the permutation.
static InstructionCost costShuffleViaSplitting(const RISCVTTIImpl &TTI, MVT LegalVT, VectorType *Tp, ArrayRef< int > Mask, TTI::TargetCostKind CostKind)
Attempt to approximate the cost of a shuffle which will require splitting during legalization.
static bool isRepeatedConcatMask(ArrayRef< int > Mask, int &SubVectorSize)
static unsigned isM1OrSmaller(MVT VT)
static InstructionCost getIntImmCostImpl(const DataLayout &DL, const RISCVSubtarget *ST, const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind, bool FreeZeroes)
static VectorType * getVRGatherIndexType(MVT DataVT, const RISCVSubtarget &ST, LLVMContext &C)
static const CostTblEntry VectorIntrinsicCostTable[]
static bool canUseShiftPair(Instruction *Inst, const APInt &Imm)
static bool canUseShiftCmp(Instruction *Inst, const APInt &Imm)
This file defines a TargetTransformInfoImplBase conforming object specific to the RISC-V target machi...
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
This pass exposes codegen information to IR-level passes.
Class for arbitrary precision integers.
Definition APInt.h:78
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
LLVM_ABI StringRef getKindAsString() const
Return the attribute's kind as a string.
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const override
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const override
TTI::ShuffleKind improveShuffleKindFromMask(TTI::ShuffleKind Kind, ArrayRef< int > Mask, VectorType *SrcTy, int &Index, VectorType *&SubTy) const
bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace, Instruction *I=nullptr, int64_t ScalableOffset=0) const override
InstructionCost getScalarizationOverhead(VectorType *InTy, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const override
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, TTI::PeelingPreferences &PP) const override
InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const override
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
std::pair< InstructionCost, MVT > getTypeLegalizationCost(Type *Ty) const
bool isLegalAddImmediate(int64_t imm) const override
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index, const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
std::optional< unsigned > getVScaleForTuning() const override
InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const override
InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *, const SCEV *, TTI::TargetCostKind) const override
InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands, TTI::TargetCostKind CostKind, Type *AccessType) const override
unsigned getRegUsageForType(Type *Ty) const override
InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const override
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, TTI::OperandValueInfo OpInfo={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const override
Value * getArgOperand(unsigned i) const
unsigned arg_size() const
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
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This class represents a range of values.
LLVM_ABI ConstantRange umin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned minimum of a value in ...
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
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.
LLVM_ABI ConstantRange udiv(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned division of a value in...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noNaNs() const
Definition FMF.h:65
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static FixedVectorType * getDoubleElementsVectorType(FixedVectorType *VTy)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
static FixedVectorType * getHalfElementsVectorType(FixedVectorType *VTy)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
The core instruction combiner logic.
const DataLayout & getDataLayout() const
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
const SimplifyQuery & getSimplifyQuery() const
static InstructionCost getInvalid(CostType Val=0)
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
user_iterator user_begin()
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
const SmallVectorImpl< Type * > & getArgTypes() const
const SmallVectorImpl< const Value * > & getArgs() const
VectorInstrContext getVectorInstrContext() const
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Machine Value Type.
static MVT getFloatingPointVT(unsigned BitWidth)
@ INVALID_SIMPLE_VALUE_TYPE
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
uint64_t getScalarSizeInBits() const
MVT changeVectorElementType(MVT EltVT) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element type...
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
static MVT getScalableVectorVT(MVT VT, unsigned NumElements)
MVT changeTypeToInteger()
Return the type converted to an equivalently sized integer or vector with integer element type.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
bool bitsGT(MVT VT) const
Return true if this has more bits than VT.
bool isFixedLengthVector() const
ElementCount getVectorElementCount() const
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
MVT getVectorElementType() const
bool isValid() const
Return true if this is a valid simple valuetype.
static MVT getIntegerVT(unsigned BitWidth)
MVT getDoubleNumVectorElementsVT() const
MVT getHalfNumVectorElementsVT() const
Return a VT for a vector type with the same element type but half the number of elements.
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
Information for memory intrinsic cost model.
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
The optimization diagnostic interface.
InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *ValTy, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
bool shouldCopyAttributeWhenOutliningFrom(const Function *Caller, const Attribute &Attr) const override
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index, const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment) const override
InstructionCost getStridedMemoryOpCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
bool isLegalMaskedLoadStore(Type *DataType, Align Alignment) const
TargetTransformInfo::VectorInstrContext getBuildVectorContextHint(ArrayRef< int > Mask, ArrayRef< Value * > Scalars, function_ref< bool(SmallVectorImpl< TargetTransformInfo::BuildVectorUseOp > &)> GatherUseOps) const override
InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind) const override
unsigned getMinTripCountTailFoldingThreshold() const override
bool preferLoopExitWithEqualityComparison(const ICmpInst &Cond, const APInt &PostIncExitValue) const override
TTI::AddressingModeKind getPreferredAddressingMode(const Loop *L, ScalarEvolution *SE) const override
InstructionCost getAddressComputationCost(Type *PTy, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const override
InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getStoreImmCost(Type *VecTy, TTI::OperandValueInfo OpInfo, TTI::TargetCostKind CostKind) const
Return the cost of materializing an immediate for a value operand of a store instruction.
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const override
bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const override
InstructionCost getCostOfKeepingLiveOverCall(ArrayRef< Type * > Tys) const override
bool hasActiveVectorLength() const override
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const override
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const override
bool isLegalBroadcastLoad(Type *ElementTy, ElementCount NumElements) const override
InstructionCost getIntImmCostInst(unsigned Opcode, unsigned Idx, const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind, Instruction *Inst=nullptr) const override
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const override
Try to calculate op costs for min/max reduction operations.
bool canSplatOperand(Instruction *I, int Operand) const
Return true if the (vector) instruction I will be lowered to an instruction with a scalar splat opera...
bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1, const TargetTransformInfo::LSRCost &C2) const override
bool isLegalStridedLoadStore(Type *DataType, Align Alignment) const override
unsigned getRegUsageForType(Type *Ty) const override
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const override
bool isLegalMaskedScatter(Type *DataType, Align Alignment) const override
bool isLegalMaskedCompressStore(Type *DataTy, Align Alignment) const override
InstructionCost getGatherScatterOpCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
InstructionCost getPartialReductionCost(unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType, ElementCount VF, TTI::PartialReductionExtendKind OpAExtend, TTI::PartialReductionExtendKind OpBExtend, std::optional< unsigned > BinOp, TTI::TargetCostKind CostKind, std::optional< FastMathFlags > FMF) const override
bool shouldTreatInstructionLikeSelect(const Instruction *I) const override
InstructionCost getExpandCompressMemoryOpCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
bool preferAlternateOpcodeVectorization() const override
bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops) const override
Check if sinking I's operands to I's basic block is profitable, because the operands can be folded in...
bool shouldExpandReduction(const IntrinsicInst *II) const override
std::optional< unsigned > getVScaleForTuning() const override
std::optional< InstructionCost > getCombinedArithmeticInstructionCost(unsigned ISDOpcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info, TTI::OperandValueInfo Opd2Info, ArrayRef< const Value * > Args, const Instruction *CtxI) const
Check to see if this instruction is expected to be combined to a simpler operation during/before lowe...
InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const override
Get memory intrinsic cost based on arguments.
bool isLegalMaskedGather(Type *DataType, Align Alignment) const override
InstructionCost getPointersChainCost(ArrayRef< const Value * > Ptrs, const Value *Base, const TTI::PointersChainInfo &Info, Type *AccessTy, const TTI::TargetCostKind CostKind) const override
unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const override
TTI::MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const override
InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
Estimate the overhead of scalarizing an instruction.
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, TTI::OperandValueInfo OpdInfo={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const override
Get intrinsic cost based on arguments.
InstructionCost getMaskedMemoryOpCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
TypeSize getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const override
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, TTI::PeelingPreferences &PP) const override
std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const override
bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const override
See if I should be considered for address type promotion.
InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind) const override
static MVT getM1VT(MVT VT)
Given a vector (either fixed or scalable), return the scalable vector corresponding to a vector regis...
static unsigned computeVLMAX(unsigned VectorBits, unsigned EltSize, unsigned MinSize)
static RISCVVType::VLMUL getLMUL(MVT VT)
This class represents an analyzed expression in the program.
static LLVM_ABI ScalableVectorType * get(Type *ElementType, unsigned MinNumElts)
Definition Type.cpp:860
The main scalar evolution driver.
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
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...
static LLVM_ABI bool isSingleSourceMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector.
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,...
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 isInterleaveMask(ArrayRef< int > Mask, unsigned Factor, unsigned NumInputElts, SmallVectorImpl< unsigned > &StartIndexes)
Return true if the mask interleaves one or more input vectors together.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:295
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Provides information about what library functions are available for the current target.
virtual const DataLayout & getDataLayout() const
virtual bool shouldTreatInstructionLikeSelect(const Instruction *I) const
virtual TTI::AddressingModeKind getPreferredAddressingMode(const Loop *L, ScalarEvolution *SE) const
virtual bool shouldCopyAttributeWhenOutliningFrom(const Function *Caller, const Attribute &Attr) const
virtual bool isLoweredToCall(const Function *F) const
InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TTI::TargetCostKind CostKind) const override
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
static bool requiresOrderedReduction(std::optional< FastMathFlags > FMF)
A helper function to determine the type of reduction algorithm used for a given Opcode and set of Fas...
llvm::VectorInstrContext VectorInstrContext
@ TCC_Expensive
The cost of a 'div' instruction on x86.
@ TCC_Free
Expected to fold away in lowering.
@ TCC_Basic
The cost of a typical 'add' instruction.
AddressingModeKind
Which addressing mode Loop Strength Reduction will try to generate.
@ AMK_PostIndexed
Prefer post-indexed addressing mode.
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_InsertSubvector
InsertSubvector. Index indicates start offset.
@ SK_Select
Selects elements from the corresponding lane of either source operand.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_Transpose
Transpose two vectors.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
@ SK_Reverse
Reverse the order of the vector.
@ SK_ExtractSubvector
ExtractSubvector Index indicates start offset.
CastContextHint
Represents a hint about the context in which a cast is used.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
static constexpr TypeSize getScalable(ScalarTy MinimumSize)
Definition TypeSize.h:355
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
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 isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
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 Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:293
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
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
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:271
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
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.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
constexpr bool isKnownMultipleOf(ScalarTy RHS) const
This function tells the caller whether the element count is known at compile time to be a multiple of...
Definition TypeSize.h:181
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:217
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr bool isKnownEven() const
A return value of true indicates we know at compile time that the number of elements (vscale * Min) i...
Definition TypeSize.h:177
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:172
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:253
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2810
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.
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:26
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
int getIntMatCost(const APInt &Val, unsigned Size, const MCSubtargetInfo &STI, bool CompressionCost, bool FreeZeroes)
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI std::pair< unsigned, bool > decodeVLMUL(VLMUL VLMul)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
This is an optimization pass for GlobalISel generic memory operations.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ 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
const CostTblEntryT< CostType > * CostTableLookup(ArrayRef< CostTblEntryT< CostType > > Tbl, int ISD, MVT Ty)
Find in cost table.
Definition CostTable.h:36
LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
InstructionCost Cost
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ None
The instruction is not folded.
@ BinaryOp
One of the operands is a binary op.
@ SplatOpFolded
All of the value's users support splatting the value.
auto adjacent_find(R &&Range)
Provide wrappers to std::adjacent_find which finds the first pair of adjacent elements that are equal...
Definition STLExtras.h:1834
bool isPairEven(const std::array< std::pair< int, int >, 2 > &SrcInfo, ArrayRef< int > Mask, unsigned &Factor)
Given a shuffle which can be represented as a pair of two slides, see if it is a pair-even idiom.
bool isPairOdd(const std::array< std::pair< int, int >, 2 > &SrcInfo, ArrayRef< int > Mask, unsigned &Factor)
Given a shuffle which can be represented as a pair of two slides, see if it is a pair-odd idiom.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition MathExtras.h:274
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
auto find_if_not(R &&Range, UnaryPredicate P)
Definition STLExtras.h:1793
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
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
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
TargetTransformInfo TTI
LLVM_ABI bool isMaskedSlidePair(ArrayRef< int > Mask, int NumElts, std::array< std::pair< int, int >, 2 > &SrcInfo)
Does this shuffle mask represent either one slide shuffle or a pair of two slide shuffles,...
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
DWARFExpression::Operation Op
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
constexpr unsigned BitWidth
CostTblEntryT< uint16_t > CostTblEntry
Definition CostTable.h:31
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
LLVM_ABI void processShuffleMasks(ArrayRef< int > Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs, unsigned NumOfUsedRegs, function_ref< void()> NoInputAction, function_ref< void(ArrayRef< int >, unsigned, unsigned)> SingleInputAction, function_ref< void(ArrayRef< int >, unsigned, unsigned, bool)> ManyInputsAction)
Splits and processes shuffle mask depending on the number of input and output registers.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Information about a load/store intrinsic defined by the target.
SimplifyQuery getWithInstruction(const Instruction *I) const
Stores information about the uses of a build vector.
unsigned Insns
TODO: Some of these could be merged.
Returns options for expansion of memcmp. IsZeroCmp is.
Describe known properties for a set of pointers.
Parameters that control the generic loop unrolling transformation.
bool UpperBound
Allow using trip count upper bound to unroll loops.
unsigned Threshold
The cost threshold for the unrolled loop.
bool Force
Apply loop unroll on any kind of loop (mainly to loops that fail runtime unrolling).
unsigned PartialOptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size, like OptSizeThreshold,...
bool UnrollAndJam
Allow unroll and jam. Used to enable unroll and jam for the target.
bool UnrollRemainder
Allow unrolling of all the iterations of the runtime loop remainder.
unsigned PartialThreshold
The cost threshold for the unrolled loop, like Threshold, but used for partial/runtime unrolling (set...
bool Runtime
Allow runtime unrolling (unrolling of loops to expand the size of the loop body even when the number ...
bool Partial
Allow partial unrolling (unrolling of loops to expand the size of the loop body, not only to eliminat...
unsigned OptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size (set to UINT_MAX to disable).