LLVM 24.0.0git
WebAssemblyTargetTransformInfo.cpp
Go to the documentation of this file.
1//===-- WebAssemblyTargetTransformInfo.cpp - WebAssembly-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///
9/// \file
10/// This file defines the WebAssembly-specific TargetTransformInfo
11/// implementation.
12///
13//===----------------------------------------------------------------------===//
14
17#include "llvm/IR/IntrinsicsWebAssembly.h"
19
21using namespace llvm;
22
23#define DEBUG_TYPE "wasmtti"
24
25unsigned WebAssemblyTTIImpl::getNumberOfRegisters(unsigned ClassID) const {
26 unsigned Result = BaseT::getNumberOfRegisters(ClassID);
27
28 // For SIMD, use at least 16 registers, as a rough guess.
29 bool Vector = (ClassID == 1);
30 if (Vector)
31 Result = std::max(Result, 16u);
32
33 return Result;
34}
35
38 switch (K) {
40 return TypeSize::getFixed(64);
42 return TypeSize::getFixed(getST()->hasSIMD128() ? 128 : 64);
44 return TypeSize::getScalable(0);
45 }
46
47 llvm_unreachable("Unsupported register kind");
48}
49
51 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
53 ArrayRef<const Value *> Args, const Instruction *CtxI,
54 const TargetLibraryInfo *TLibInfo, ArrayRef<const Value *> Scalars) const {
55
56 if (ST->hasSIMD128()) {
57 static const CostTblEntry ArithCostTbl[]{
58 // extmul + (maybe awkward) shuffle
59 {ISD::MUL, MVT::v8i8, 4},
60 // 2x extmul + (okay) shuffle
61 {ISD::MUL, MVT::v16i8, 4},
62 // extmul
63 {ISD::MUL, MVT::v4i16, 1},
64 // extmul
65 {ISD::MUL, MVT::v2i32, 1},
66 };
67 EVT DstVT = TLI->getValueType(DL, Ty);
68 if (DstVT.isSimple()) {
69 int ISD = TLI->InstructionOpcodeToISD(Opcode);
70 if (const auto *Entry =
71 CostTableLookup(ArithCostTbl, ISD, DstVT.getSimpleVT()))
72 return Entry->Cost;
73 }
74 }
75
78 Opcode, Ty, CostKind, Op1Info, Op2Info);
79
80 if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
81 switch (Opcode) {
82 case Instruction::LShr:
83 case Instruction::AShr:
84 case Instruction::Shl:
85 // SIMD128's shifts currently only accept a scalar shift count. For each
86 // element, we'll need to extract, op, insert. The following is a rough
87 // approximation.
88 if (!Op2Info.isUniform())
89 Cost =
90 VTy->getNumElements() *
92 getArithmeticInstrCost(Opcode, VTy->getElementType(), CostKind) +
94 break;
95 }
96 }
97 return Cost;
98}
99
101 unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH,
102 TTI::TargetCostKind CostKind, const Instruction *I) const {
103 int ISD = TLI->InstructionOpcodeToISD(Opcode);
104 auto SrcTy = TLI->getValueType(DL, Src);
105 auto DstTy = TLI->getValueType(DL, Dst);
106
107 if (!SrcTy.isSimple() || !DstTy.isSimple()) {
108 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
109 }
110
111 if (!ST->hasSIMD128()) {
112 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
113 }
114
115 auto DstVT = DstTy.getSimpleVT();
116 auto SrcVT = SrcTy.getSimpleVT();
117
118 if (I && I->hasOneUser()) {
119 auto *SingleUser = *I->user_begin();
120 int UserISD = TLI->InstructionOpcodeToISD(SingleUser->getOpcode());
121
122 // extmul_low support
123 if (UserISD == ISD::MUL &&
125 // Free low extensions.
126 if ((SrcVT == MVT::v8i8 && DstVT == MVT::v8i16) ||
127 (SrcVT == MVT::v4i16 && DstVT == MVT::v4i32) ||
128 (SrcVT == MVT::v2i32 && DstVT == MVT::v2i64)) {
129 return 0;
130 }
131 // Will require an additional extlow operation for the intermediate
132 // i16/i32 value.
133 if ((SrcVT == MVT::v4i8 && DstVT == MVT::v4i32) ||
134 (SrcVT == MVT::v2i16 && DstVT == MVT::v2i64)) {
135 return 1;
136 }
137 }
138 }
139
140 static constexpr TypeConversionCostTblEntry ConversionTbl[] = {
141 // extend_low
142 {ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1},
143 {ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1},
144 {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1},
145 {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1},
146 {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1},
147 {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1},
148 // 2 x extend_low
149 {ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 2},
150 {ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2},
151 {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2},
152 {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2},
153 // extend_low, extend_high
154 {ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 2},
155 {ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 2},
156 {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 2},
157 {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 2},
158 {ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2},
159 {ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2},
160 // 2x extend_low, extend_high
161 {ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i32, 4},
162 {ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i32, 4},
163 {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 4},
164 {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 4},
165 // 6x extend_low, extend_high
166 {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6},
167 {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6},
168 // shuffle
169 {ISD::TRUNCATE, MVT::v2i16, MVT::v2i32, 2},
170 {ISD::TRUNCATE, MVT::v2i8, MVT::v2i32, 4},
171 // narrow, and
172 {ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 2},
173 // 2x narrow, and
174 {ISD::TRUNCATE, MVT::v4i8, MVT::v4i32, 3},
175 // narrow, and
176 {ISD::TRUNCATE, MVT::v4i8, MVT::v4i16, 2},
177 {ISD::TRUNCATE, MVT::v8i8, MVT::v8i16, 2},
178 // narrow, 2x and
179 {ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 3},
180 {ISD::TRUNCATE, MVT::v16i8, MVT::v16i16, 3},
181 // 2x narrow, 2x and
182 {ISD::TRUNCATE, MVT::v4i16, MVT::v4i64, 4},
183 {ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 4},
184 // 3x narrow, 2x and
185 {ISD::TRUNCATE, MVT::v4i8, MVT::v4i64, 5},
186 // 2x narrow, 4x and
187 {ISD::TRUNCATE, MVT::v16i16, MVT::v16i32, 6},
188 // 3x narrow, 4x and
189 {ISD::TRUNCATE, MVT::v8i16, MVT::v8i64, 7},
190 {ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 7},
191 // 4x narrow, 4x and
192 {ISD::TRUNCATE, MVT::v8i8, MVT::v8i64, 8},
193 // 6x narrow, 8x and
194 {ISD::TRUNCATE, MVT::v16i16, MVT::v16i64, 14},
195 // 7x narrow, 8x and
196 {ISD::TRUNCATE, MVT::v16i8, MVT::v16i64, 15},
197 // convert_i32x4
198 {ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1},
199 {ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1},
200 {ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1},
201 {ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1},
202 // extend_low, convert
203 {ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 2},
204 {ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 2},
205 {ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2},
206 {ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2},
207 // extend_low x 2, convert
208 {ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3},
209 {ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3},
210 {ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 3},
211 {ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3},
212 // several shuffles
213 {ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 10},
214 {ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 10},
215 {ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 10},
216 {ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 10},
217 // trunc_sat, const, and, 2x narrow
218 {ISD::FP_TO_SINT, MVT::v2i8, MVT::v2f32, 5},
219 {ISD::FP_TO_UINT, MVT::v2i8, MVT::v2f32, 5},
220 // trunc_sat, const, and, 2x narrow
221 {ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 5},
222 {ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 5},
223 // trunc_sat, const, and, narrow
224 {ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f32, 4},
225 {ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f32, 4},
226 {ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 4},
227 {ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 4},
228 // 2x trunc_sat, const, 2x and, 2x narrow
229 {ISD::FP_TO_SINT, MVT::v8i8, MVT::v8f32, 7},
230 {ISD::FP_TO_UINT, MVT::v8i8, MVT::v8f32, 7},
231 // 2x trunc_sat, const, 2x and, narrow
232 {ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f32, 6},
233 {ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f32, 6},
234 };
235
236 if (const auto *Entry =
237 ConvertCostTableLookup(ConversionTbl, ISD, DstVT, SrcVT)) {
238 return Entry->Cost;
239 }
240
241 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
242}
243
245WebAssemblyTTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
247
248 Options.AllowOverlappingLoads = true;
249
250 if (ST->hasSIMD128())
251 Options.LoadSizes.push_back(16);
252
253 Options.LoadSizes.append({8, 4, 2, 1});
254 Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
255 Options.NumLoadsPerBlock = IsZeroCmp ? Options.MaxNumLoads : 1;
256
257 return Options;
258}
259
261 unsigned Opcode, Type *Ty, Align Alignment, unsigned AddressSpace,
263 const Instruction *I) const {
264 // FIXME: Load latency isn't handled here
265 if (!ST->hasSIMD128() || !isa<FixedVectorType>(Ty) ||
266 (Opcode == Instruction::Load && CostKind == TTI::TCK_Latency)) {
267 return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace,
268 CostKind);
269 }
270
271 EVT VT = TLI->getValueType(DL, Ty, true);
272 // Type legalization can't handle structs
273 if (VT == MVT::Other)
274 return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace,
275 CostKind);
276
277 auto LT = getTypeLegalizationCost(Ty);
278 if (!LT.first.isValid())
280
281 int ISD = TLI->InstructionOpcodeToISD(Opcode);
282 unsigned width = VT.getSizeInBits();
283 if (ISD == ISD::LOAD) {
284 // 128-bit loads are a single instruction. 32-bit and 64-bit vector loads
285 // can be lowered to load32_zero and load64_zero respectively. Assume SIMD
286 // loads are twice as expensive as scalar.
287 switch (width) {
288 default:
289 break;
290 case 32:
291 case 64:
292 case 128:
293 return 2;
294 }
295 } else if (ISD == ISD::STORE) {
296 // For stores, we can use store lane operations.
297 switch (width) {
298 default:
299 break;
300 case 8:
301 case 16:
302 case 32:
303 case 64:
304 case 128:
305 return 2;
306 }
307 }
308
309 return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace, CostKind);
310}
311
313 TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy,
314 TTI::TargetCostKind CostKind, ArrayRef<int> Mask, int Index,
315 VectorType *SubTp, ArrayRef<const Value *> Args, const Instruction *CtxI,
316 TTI::VectorInstrContext VIC) const {
317 // Canonicalize the ShuffleKind in case optimizations didn't.
318 // Otherwise, we might end up with the wrong ShuffleKind to match against.
319
320 Kind = improveShuffleKindFromMask(Kind, Mask, SrcTy, Index, SubTp);
321
322 // Wasm SIMD128 has native splat instructions for all lane types.
323 if (ST->hasSIMD128() && Kind == TTI::SK_Broadcast &&
325 return 1;
326
327 return BaseT::getShuffleCost(Kind, DstTy, SrcTy, CostKind, Mask, Index, SubTp,
328 Args, CtxI);
329}
330
332 unsigned Opcode, Type *Ty, unsigned Factor, ArrayRef<unsigned> Indices,
333 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
334 bool UseMaskForCond, bool UseMaskForGaps) const {
335 assert(Factor >= 2 && "Invalid interleave factor");
336
337 auto *VecTy = cast<VectorType>(Ty);
338 if (!ST->hasSIMD128() || !isa<FixedVectorType>(VecTy)) {
340 }
341
342 if (UseMaskForCond || UseMaskForGaps)
343 return BaseT::getInterleavedMemoryOpCost(Opcode, Ty, Factor, Indices,
344 Alignment, AddressSpace, CostKind,
345 UseMaskForCond, UseMaskForGaps);
346
347 constexpr unsigned MaxInterleaveFactor = 4;
348 if (Factor <= MaxInterleaveFactor) {
349 unsigned MinElts = VecTy->getElementCount().getKnownMinValue();
350 // Ensure the number of vector elements is greater than 1.
351 if (MinElts < 2 || MinElts % Factor != 0)
353
354 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
355 // Ensure the element type is legal.
356 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
358
359 if (Factor != 2 && Factor != 4)
361
362 auto *SubVecTy =
363 VectorType::get(VecTy->getElementType(),
364 VecTy->getElementCount().divideCoefficientBy(Factor));
365 InstructionCost MemCost =
366 getMemoryOpCost(Opcode, SubVecTy, Alignment, AddressSpace, CostKind);
367
368 unsigned VecSize = DL.getTypeSizeInBits(SubVecTy);
369 unsigned MaxVecSize = 128;
370 unsigned NumAccesses =
371 std::max<unsigned>(1, (MinElts * ElSize + MaxVecSize - 1) / VecSize);
372
373 // A stride of two is commonly supported via dedicated instructions, so it
374 // should be relatively cheap for all element sizes. A stride of four is
375 // more expensive as it will likely require more shuffles. Using two
376 // simd128 inputs is considered more expensive and we mainly account for
377 // shuffling two inputs (32 bytes), but we do model 4 x v4i32 to enable
378 // arithmetic kernels with smaller (i8/i16) inputs.
379 static const CostTblEntry ShuffleCostTbl[] = {
380 // One reg.
381 {2, MVT::v2i8, 1}, // interleave 2 x 2i8 into 4i8
382 {2, MVT::v4i8, 1}, // interleave 2 x 4i8 into 8i8
383 {2, MVT::v8i8, 1}, // interleave 2 x 8i8 into 16i8
384 {2, MVT::v2i16, 1}, // interleave 2 x 2i16 into 4i16
385 {2, MVT::v4i16, 1}, // interleave 2 x 4i16 into 8i16
386 {2, MVT::v2i32, 1}, // interleave 2 x 2i32 into 4i32
387 {2, MVT::v2f32, 1}, // interleave 2 x 2f32 into 4f32
388
389 // Two regs.
390 {2, MVT::v16i8, 2}, // interleave 2 x 16i8 into 32i8
391 {2, MVT::v8i16, 2}, // interleave 2 x 8i16 into 16i16
392 {2, MVT::v4i32, 2}, // interleave 2 x 4i32 into 8i32
393 {2, MVT::v4f32, 2}, // interleave 2 x 4f32 into 8f32
394
395 // One reg.
396 {4, MVT::v2i8, 4}, // interleave 4 x 2i8 into 8i8
397 {4, MVT::v4i8, 4}, // interleave 4 x 4i8 into 16i8
398 {4, MVT::v2i16, 4}, // interleave 4 x 2i16 into 8i16
399
400 // Two regs.
401 {4, MVT::v8i8, 16}, // interleave 4 x 8i8 into 32i8
402 {4, MVT::v4i16, 8}, // interleave 4 x 4i16 into 16i16
403 {4, MVT::v2i32, 4}, // interleave 4 x 2i32 into 8i32
404 {4, MVT::v2f32, 4}, // interleave 4 x 2f32 into 8f32
405
406 // Four regs.
407 {4, MVT::v4i32, 16}, // interleave 4 x 4i32 into 16i32
408 };
409
410 EVT ETy = TLI->getValueType(DL, SubVecTy);
411 if (const auto *Entry =
412 CostTableLookup(ShuffleCostTbl, Factor, ETy.getSimpleVT()))
413 return Entry->Cost + (NumAccesses * MemCost);
414 }
415
416 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
417 Alignment, AddressSpace, CostKind,
418 UseMaskForCond, UseMaskForGaps);
419}
420
422 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index,
423 const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC) const {
425 Opcode, Val, CostKind, Index, Op0, Op1, VIC);
426
427 // SIMD128's insert/extract currently only take constant indices.
428 if (Index == -1u)
430
431 return Cost;
432}
433
435 unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType,
437 TTI::PartialReductionExtendKind OpBExtend, std::optional<unsigned> BinOp,
438 TTI::TargetCostKind CostKind, std::optional<FastMathFlags> FMF) const {
440 if (!VF.isFixed() || !ST->hasSIMD128())
441 return Invalid;
442
443 if (CostKind != TTI::TCK_RecipThroughput)
444 return Invalid;
445
446 if (Opcode != Instruction::Add)
447 return Invalid;
448
449 EVT AccumEVT = EVT::getEVT(AccumType);
450 // TODO: Add i64 accumulator.
451 if (AccumEVT != MVT::i32)
452 return Invalid;
453
454 // Possible options:
455 // - i16x8.extadd_pairwise_i8x16_sx
456 // - i32x4.extadd_pairwise_i16x8_sx
457 // - i32x4.dot_i16x8_s
458 // Only try to support dot, for now.
459
460 EVT InputEVT = EVT::getEVT(InputTypeA);
461 if (!((InputEVT == MVT::i16 && VF.getFixedValue() == 8) ||
462 (InputEVT == MVT::i8 && VF.getFixedValue() == 16))) {
463 return Invalid;
464 }
465
466 if (OpAExtend == TTI::PR_None)
467 return Invalid;
468
470 if (!BinOp)
471 return Cost;
472
473 if (OpAExtend != OpBExtend)
474 return Invalid;
475
476 if (*BinOp != Instruction::Mul)
477 return Invalid;
478
479 if (InputTypeA != InputTypeB)
480 return Invalid;
481
482 // Signed inputs can lower to dot
483 if (InputEVT == MVT::i16 && VF.getFixedValue() == 8)
484 return OpAExtend == TTI::PR_SignExtend ? Cost : Cost * 2;
485
486 // Double the size of the lowered sequence.
487 if (InputEVT == MVT::i8 && VF.getFixedValue() == 16)
488 return OpAExtend == TTI::PR_SignExtend ? Cost * 2 : Cost * 4;
489
490 return Invalid;
491}
492
494 const IntrinsicInst *II) const {
495
496 switch (II->getIntrinsicID()) {
497 default:
498 break;
499 case Intrinsic::vector_reduce_fadd:
501 }
503}
504
507 OptimizationRemarkEmitter *ORE) const {
508 // Scan the loop: don't unroll loops with calls. This is a standard approach
509 // for most (all?) targets.
510 for (BasicBlock *BB : L->blocks())
511 for (Instruction &I : *BB)
514 if (isLoweredToCall(F))
515 return;
516
517 // The chosen threshold is within the range of 'LoopMicroOpBufferSize' of
518 // the various microarchitectures that use the BasicTTI implementation and
519 // has been selected through heuristics across multiple cores and runtimes.
520 UP.Partial = UP.Runtime = UP.UpperBound = true;
521 UP.PartialThreshold = 30;
522
523 // Avoid unrolling when optimizing for size.
524 UP.OptSizeThreshold = 0;
526
527 // Set number of instructions optimized when "back edge"
528 // becomes "fall through" to default value of 2.
529 UP.BEInsns = 2;
530}
531
533 return getST()->hasTailCall();
534}
535
538 using namespace llvm::PatternMatch;
539
540 if (!I->getType()->isVectorTy() || !I->isShift())
541 return false;
542
543 Value *V = I->getOperand(1);
544 // We dont need to sink constant splat.
545 if (isa<Constant>(V))
546 return false;
547
549 m_Value(), m_ZeroMask()))) {
550 // Sink insert
551 Ops.push_back(&cast<Instruction>(V)->getOperandUse(0));
552 // Sink shuffle
553 Ops.push_back(&I->getOperandUse(1));
554 return true;
555 }
556
557 return false;
558}
559
560/// Attempt to convert [relaxed_]swizzle to shufflevector if the mask is
561/// constant.
564 bool IsRelaxed) {
565 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
566 if (!V)
567 return nullptr;
568
569 auto *VecTy = cast<FixedVectorType>(II.getType());
570 unsigned NumElts = VecTy->getNumElements();
571 assert(NumElts == 16);
572
573 // Construct a shuffle mask from constant integers or UNDEFs.
574 int Indexes[16];
575 bool AnyOutOfBounds = false;
576
577 for (unsigned I = 0; I < NumElts; ++I) {
578 Constant *COp = V->getAggregateElement(I);
579 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
580 return nullptr;
581
582 if (isa<UndefValue>(COp)) {
583 Indexes[I] = -1;
584 continue;
585 }
586
587 if (IsRelaxed && cast<ConstantInt>(COp)->getSExtValue() >= NumElts) {
588 // The relaxed_swizzle operation always returns 0 if the lane index is
589 // less than 0 when interpreted as a signed value. For lane indices above
590 // 15, however, it can choose between returning 0 or the lane at `Index %
591 // 16`. However, the choice must be made consistently. As the WebAssembly
592 // spec states:
593 //
594 // "The result of relaxed operators are implementation-dependent, because
595 // the set of possible results may depend on properties of the host
596 // environment, such as its hardware. Technically, their behaviour is
597 // controlled by a set of global parameters to the semantics that an
598 // implementation can instantiate in different ways. These choices are
599 // fixed, that is, parameters are constant during the execution of any
600 // given program."
601 //
602 // The WebAssembly runtime may choose differently from us, so we can't
603 // optimize a relaxed swizzle with lane indices above 15.
604 return nullptr;
605 }
606
607 uint64_t Index = cast<ConstantInt>(COp)->getZExtValue();
608 if (Index >= NumElts) {
609 AnyOutOfBounds = true;
610 // If there are out-of-bounds indices, the swizzle instruction returns
611 // zeroes in those lanes. We'll provide an all-zeroes vector as the
612 // second argument to shufflevector and read the first element from it.
613 Indexes[I] = NumElts;
614 continue;
615 }
616
617 Indexes[I] = Index;
618 }
619
620 auto *V1 = II.getArgOperand(0);
621 auto *V2 =
622 AnyOutOfBounds ? Constant::getNullValue(VecTy) : PoisonValue::get(VecTy);
623
624 return Builder.CreateShuffleVector(V1, V2, ArrayRef(Indexes, NumElts));
625}
626
627std::optional<Instruction *>
629 IntrinsicInst &II) const {
630 Intrinsic::ID IID = II.getIntrinsicID();
631 switch (IID) {
632 case Intrinsic::wasm_swizzle:
633 case Intrinsic::wasm_relaxed_swizzle:
634 if (Value *V = simplifyWasmSwizzle(
635 II, IC.Builder, IID == Intrinsic::wasm_relaxed_swizzle)) {
636 return IC.replaceInstUsesWith(II, V);
637 }
638 break;
639 }
640
641 return std::nullopt;
642}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Cost tables and simple lookup functions.
static const int MaxVecSize
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
static const unsigned MaxInterleaveFactor
Maximum vectorization interleave count.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const Function * getCalledFunction(const MachineInstr &MI)
uint64_t IntrinsicInst * II
static Value * simplifyWasmSwizzle(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder, bool IsRelaxed)
Attempt to convert [relaxed_]swizzle to shufflevector if the mask is constant.
This file a TargetTransformInfoImplBase conforming object specific to the WebAssembly target machine.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:61
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
TTI::ShuffleKind improveShuffleKindFromMask(TTI::ShuffleKind Kind, ArrayRef< int > Mask, VectorType *SrcTy, int &Index, VectorType *&SubTy) const
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 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
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
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
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
The core instruction combiner logic.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
static InstructionCost getInvalid(CostType Val=0)
A wrapper class for inspecting calls to intrinsic functions.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
The optimization diagnostic interface.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
The main scalar evolution driver.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Provides information about what library functions are available for the current target.
virtual unsigned getNumberOfRegisters(unsigned ClassID) const
virtual bool isLoweredToCall(const Function *F) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_Latency
The latency of instruction.
llvm::VectorInstrContext VectorInstrContext
@ TCC_Expensive
The cost of a 'div' instruction on x86.
@ TCC_Basic
The cost of a typical 'add' instruction.
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_Broadcast
Broadcast element 0 to all other elements.
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
LLVM Value Representation.
Definition Value.h:75
Base class of all SIMD vector types.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *Ty, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond, bool UseMaskForGaps) const override
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
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 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
std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const override
TypeSize getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const override
bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops) const override
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
TTI::ReductionShuffle getPreferredExpandedReductionShuffle(const IntrinsicInst *II) const override
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const override
TTI::MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) 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
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
unsigned getNumberOfRegisters(unsigned ClassID) const override
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:172
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:26
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
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.
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.
This is an optimization pass for GlobalISel generic memory operations.
const CostTblEntryT< CostType > * CostTableLookup(ArrayRef< CostTblEntryT< CostType > > Tbl, int ISD, MVT Ty)
Find in cost table.
Definition CostTable.h:36
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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
ArrayRef(const T &OneElt) -> ArrayRef< T >
TypeConversionCostTblEntryT< uint16_t > TypeConversionCostTblEntry
Definition CostTable.h:62
CostTblEntryT< uint16_t > CostTblEntry
Definition CostTable.h:31
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
const TypeConversionCostTblEntryT< CostType > * ConvertCostTableLookup(ArrayRef< TypeConversionCostTblEntryT< CostType > > Tbl, int ISD, MVT Dst, MVT Src)
Find in type conversion cost table.
Definition CostTable.h:67
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
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
Returns options for expansion of memcmp. IsZeroCmp is.
Parameters that control the generic loop unrolling transformation.
bool UpperBound
Allow using trip count upper bound to unroll loops.
unsigned PartialOptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size, like OptSizeThreshold,...
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).