LLVM 23.0.0git
ExpandVectorPredication.cpp
Go to the documentation of this file.
1//===----- CodeGen/ExpandVectorPredication.cpp - Expand VP intrinsics -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements IR expansion for vector predication intrinsics, allowing
10// targets to enable vector predication until just before codegen.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/Statistic.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/Intrinsics.h"
27#include "llvm/Support/Debug.h"
29#include <optional>
30
31using namespace llvm;
32
35
36// Keep this in sync with TargetTransformInfo::VPLegalization.
37#define VPINTERNAL_VPLEGAL_CASES \
38 VPINTERNAL_CASE(Legal) \
39 VPINTERNAL_CASE(Discard) \
40 VPINTERNAL_CASE(Convert)
41
42#define VPINTERNAL_CASE(X) "|" #X
43
44// Override options.
46 "expandvp-override-evl-transform", cl::init(""), cl::Hidden,
47 cl::desc("Options: <empty>" VPINTERNAL_VPLEGAL_CASES
48 ". If non-empty, ignore "
49 "TargetTransformInfo and "
50 "always use this transformation for the %evl parameter (Used in "
51 "testing)."));
52
54 "expandvp-override-mask-transform", cl::init(""), cl::Hidden,
55 cl::desc("Options: <empty>" VPINTERNAL_VPLEGAL_CASES
56 ". If non-empty, Ignore "
57 "TargetTransformInfo and "
58 "always use this transformation for the %mask parameter (Used in "
59 "testing)."));
60
61#undef VPINTERNAL_CASE
62#define VPINTERNAL_CASE(X) .Case(#X, VPLegalization::X)
63
64static VPTransform parseOverrideOption(const std::string &TextOpt) {
66}
67
68#undef VPINTERNAL_VPLEGAL_CASES
69
70// Whether any override options are set.
72 return !EVLTransformOverride.empty() || !MaskTransformOverride.empty();
73}
74
75#define DEBUG_TYPE "expandvp"
76
77STATISTIC(NumFoldedVL, "Number of folded vector length params");
78STATISTIC(NumLoweredVPOps, "Number of folded vector predication operations");
79
80///// Helpers {
81
82/// \returns Whether the vector mask \p MaskVal has all lane bits set.
83static bool isAllTrueMask(Value *MaskVal) {
84 if (Value *SplattedVal = getSplatValue(MaskVal))
85 if (auto *ConstValue = dyn_cast<Constant>(SplattedVal))
86 return ConstValue->isAllOnesValue();
87
88 return false;
89}
90
91/// \returns A non-excepting divisor constant for this type.
92static Constant *getSafeDivisor(Type *DivTy) {
93 assert(DivTy->isIntOrIntVectorTy() && "Unsupported divisor type");
94 return ConstantInt::get(DivTy, 1u, false);
95}
96
97/// Transfer operation properties from \p OldVPI to \p NewVal.
98static void transferDecorations(Value &NewVal, VPIntrinsic &VPI) {
99 auto *NewInst = dyn_cast<Instruction>(&NewVal);
100 if (!NewInst || !isa<FPMathOperator>(NewVal))
101 return;
102
103 auto *OldFMOp = dyn_cast<FPMathOperator>(&VPI);
104 if (!OldFMOp)
105 return;
106
107 NewInst->setFastMathFlags(OldFMOp->getFastMathFlags());
108}
109
110/// Transfer all properties from \p OldOp to \p NewOp and replace all uses.
111/// OldVP gets erased.
112static void replaceOperation(Value &NewOp, VPIntrinsic &OldOp) {
113 transferDecorations(NewOp, OldOp);
114
115 if (isa<Instruction>(NewOp) && !NewOp.hasName() && OldOp.hasName())
116 NewOp.takeName(&OldOp);
117
118 OldOp.replaceAllUsesWith(&NewOp);
119 OldOp.eraseFromParent();
120}
121
123 // The result of VP reductions depends on the mask and evl.
125 return false;
126 // Fallback to whether the intrinsic is speculatable.
127 if (auto IntrID = VPI.getFunctionalIntrinsicID())
128 return Intrinsic::getFnAttributes(VPI.getContext(), *IntrID)
129 .hasAttribute(Attribute::AttrKind::Speculatable);
130 if (auto Opc = VPI.getFunctionalOpcode())
132 return false;
133}
134
135//// } Helpers
136
137namespace {
138
139// Expansion pass state at function scope.
140struct CachingVPExpander {
141 const TargetTransformInfo &TTI;
142
143 /// \returns A bitmask that is true where the lane position is less-than \p
144 /// EVLParam
145 ///
146 /// \p Builder
147 /// Used for instruction creation.
148 /// \p VLParam
149 /// The explicit vector length parameter to test against the lane
150 /// positions.
151 /// \p ElemCount
152 /// Static (potentially scalable) number of vector elements.
153 Value *convertEVLToMask(IRBuilder<> &Builder, Value *EVLParam,
154 ElementCount ElemCount);
155
156 /// If needed, folds the EVL in the mask operand and discards the EVL
157 /// parameter. Returns true if the mask was actually folded.
158 bool foldEVLIntoMask(VPIntrinsic &VPI);
159
160 /// "Remove" the %evl parameter of \p PI by setting it to the static vector
161 /// length of the operation. Returns true if the %evl (if any) was effectively
162 /// changed.
163 bool discardEVLParameter(VPIntrinsic &PI);
164
165 /// Lower this VP binary operator to a unpredicated binary operator.
166 bool expandPredicationInBinaryOperator(IRBuilder<> &Builder, VPIntrinsic &PI);
167
168 /// Lower this VP int call to a unpredicated int call.
169 bool expandPredicationToIntCall(IRBuilder<> &Builder, VPIntrinsic &PI);
170
171 /// Lower this VP fp call to a unpredicated fp call.
172 bool expandPredicationToFPCall(IRBuilder<> &Builder, VPIntrinsic &PI,
173 unsigned UnpredicatedIntrinsicID);
174
175 /// Lower this VP reduction to a call to an unpredicated reduction intrinsic.
176 bool expandPredicationInReduction(IRBuilder<> &Builder,
177 VPReductionIntrinsic &PI);
178
179 /// Lower this VP cast operation to a non-VP intrinsic.
180 bool expandPredicationToCastIntrinsic(IRBuilder<> &Builder, VPIntrinsic &VPI);
181
182 /// Lower this VP memory operation to a non-VP intrinsic.
183 bool expandPredicationInMemoryIntrinsic(IRBuilder<> &Builder,
184 VPIntrinsic &VPI);
185
186 /// Lower this VP comparison to a call to an unpredicated comparison.
187 bool expandPredicationInComparison(IRBuilder<> &Builder, VPCmpIntrinsic &PI);
188
189 /// Query TTI and expand the vector predication in \p P accordingly.
190 bool expandPredication(VPIntrinsic &PI);
191
192 /// Determine how and whether the VPIntrinsic \p VPI shall be expanded. This
193 /// overrides TTI with the cl::opts listed at the top of this file.
194 VPLegalization getVPLegalizationStrategy(const VPIntrinsic &VPI) const;
195 bool UsingTTIOverrides;
196
197public:
198 CachingVPExpander(const TargetTransformInfo &TTI)
199 : TTI(TTI), UsingTTIOverrides(anyExpandVPOverridesSet()) {}
200
201 /// Expand llvm.vp.* intrinsics as requested by \p TTI.
202 /// Returns the details of the expansion.
203 VPExpansionDetails expandVectorPredication(VPIntrinsic &VPI);
204};
205
206//// CachingVPExpander {
207
208Value *CachingVPExpander::convertEVLToMask(IRBuilder<> &Builder,
209 Value *EVLParam,
210 ElementCount ElemCount) {
211 // TODO add caching
212 // Scalable vector %evl conversion.
213 if (ElemCount.isScalable()) {
214 Type *BoolVecTy = VectorType::get(Builder.getInt1Ty(), ElemCount);
215 // `get_active_lane_mask` performs an implicit less-than comparison.
216 Value *ConstZero = Builder.getInt32(0);
217 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
218 {BoolVecTy, EVLParam->getType()},
219 {ConstZero, EVLParam});
220 }
221
222 // Fixed vector %evl conversion.
223 Type *LaneTy = EVLParam->getType();
224 unsigned NumElems = ElemCount.getFixedValue();
225 Value *VLSplat = Builder.CreateVectorSplat(NumElems, EVLParam);
226 Value *IdxVec = Builder.CreateStepVector(VectorType::get(LaneTy, ElemCount));
227 return Builder.CreateICmp(CmpInst::ICMP_ULT, IdxVec, VLSplat);
228}
229
230bool CachingVPExpander::expandPredicationInBinaryOperator(IRBuilder<> &Builder,
231 VPIntrinsic &VPI) {
233 "Implicitly dropping %evl in non-speculatable operator!");
234
235 auto OC = static_cast<Instruction::BinaryOps>(*VPI.getFunctionalOpcode());
237
238 Value *Op0 = VPI.getOperand(0);
239 Value *Op1 = VPI.getOperand(1);
240 Value *Mask = VPI.getMaskParam();
241
242 // Blend in safe operands.
243 if (Mask && !isAllTrueMask(Mask)) {
244 switch (OC) {
245 default:
246 // Can safely ignore the predicate.
247 break;
248
249 // Division operators need a safe divisor on masked-off lanes (1).
250 case Instruction::UDiv:
251 case Instruction::SDiv:
252 case Instruction::URem:
253 case Instruction::SRem:
254 // 2nd operand must not be zero.
255 Value *SafeDivisor = getSafeDivisor(VPI.getType());
256 Op1 = Builder.CreateSelect(Mask, Op1, SafeDivisor);
257 }
258 }
259
260 Value *NewBinOp = Builder.CreateBinOp(OC, Op0, Op1);
261
262 replaceOperation(*NewBinOp, VPI);
263 return true;
264}
265
266bool CachingVPExpander::expandPredicationToIntCall(IRBuilder<> &Builder,
267 VPIntrinsic &VPI) {
268 std::optional<unsigned> FID = VPI.getFunctionalIntrinsicID();
269 if (!FID)
270 return false;
271 SmallVector<Value *, 2> Argument;
272 for (unsigned i = 0; i < VPI.getNumOperands() - 3; i++) {
273 Argument.push_back(VPI.getOperand(i));
274 }
275 Value *NewOp =
276 Builder.CreateIntrinsic(FID.value(), {VPI.getType()}, Argument);
277 replaceOperation(*NewOp, VPI);
278 return true;
279}
280
281bool CachingVPExpander::expandPredicationToFPCall(
282 IRBuilder<> &Builder, VPIntrinsic &VPI, unsigned UnpredicatedIntrinsicID) {
284 "Implicitly dropping %evl in non-speculatable operator!");
285
286 switch (UnpredicatedIntrinsicID) {
287 case Intrinsic::fabs:
288 case Intrinsic::copysign:
289 case Intrinsic::sqrt:
290 case Intrinsic::maxnum:
291 case Intrinsic::minnum:
292 case Intrinsic::maximum:
293 case Intrinsic::minimum:
294 case Intrinsic::ceil:
295 case Intrinsic::floor:
296 case Intrinsic::round:
297 case Intrinsic::roundeven:
298 case Intrinsic::trunc:
299 case Intrinsic::rint:
300 case Intrinsic::nearbyint:
301 case Intrinsic::lrint:
302 case Intrinsic::llrint:
303 case Intrinsic::is_fpclass: {
304 SmallVector<Value *, 2> Argument;
305 for (unsigned i = 0; i < VPI.getNumOperands() - 3; i++) {
306 Argument.push_back(VPI.getOperand(i));
307 }
308 Value *NewOp = Builder.CreateIntrinsic(VPI.getType(),
309 UnpredicatedIntrinsicID, Argument);
310 replaceOperation(*NewOp, VPI);
311 return true;
312 }
313 case Intrinsic::fma:
314 case Intrinsic::fmuladd:
315 case Intrinsic::experimental_constrained_fma:
316 case Intrinsic::experimental_constrained_fmuladd: {
317 Value *Op0 = VPI.getOperand(0);
318 Value *Op1 = VPI.getOperand(1);
319 Value *Op2 = VPI.getOperand(2);
321 VPI.getModule(), UnpredicatedIntrinsicID, {VPI.getType()});
322 Value *NewOp;
323 if (Intrinsic::isConstrainedFPIntrinsic(UnpredicatedIntrinsicID))
324 NewOp = Builder.CreateConstrainedFPCall(Fn, {Op0, Op1, Op2});
325 else
326 NewOp = Builder.CreateCall(Fn, {Op0, Op1, Op2});
327 replaceOperation(*NewOp, VPI);
328 return true;
329 }
330 }
331
332 return false;
333}
334
335static Value *getNeutralReductionElement(const VPReductionIntrinsic &VPI,
336 Type *EltTy) {
338 FastMathFlags FMF;
339 if (isa<FPMathOperator>(VPI))
340 FMF = VPI.getFastMathFlags();
341 return getReductionIdentity(RdxID, EltTy, FMF);
342}
343
344bool CachingVPExpander::expandPredicationInReduction(
345 IRBuilder<> &Builder, VPReductionIntrinsic &VPI) {
347 "Implicitly dropping %evl in non-speculatable operator!");
348
349 Value *Mask = VPI.getMaskParam();
350 Value *RedOp = VPI.getOperand(VPI.getVectorParamPos());
351
352 // Insert neutral element in masked-out positions
353 if (Mask && !isAllTrueMask(Mask)) {
354 auto *NeutralElt = getNeutralReductionElement(VPI, VPI.getType());
355 auto *NeutralVector = Builder.CreateVectorSplat(
356 cast<VectorType>(RedOp->getType())->getElementCount(), NeutralElt);
357 RedOp = Builder.CreateSelect(Mask, RedOp, NeutralVector);
358 }
359
362
363 switch (VPI.getIntrinsicID()) {
364 default:
365 llvm_unreachable("Impossible reduction kind");
366 case Intrinsic::vp_reduce_add:
367 case Intrinsic::vp_reduce_mul:
368 case Intrinsic::vp_reduce_and:
369 case Intrinsic::vp_reduce_or:
370 case Intrinsic::vp_reduce_xor: {
372 unsigned Opc = getArithmeticReductionInstruction(RedID);
374 Reduction = Builder.CreateUnaryIntrinsic(RedID, RedOp);
375 Reduction =
377 break;
378 }
379 case Intrinsic::vp_reduce_smax:
380 case Intrinsic::vp_reduce_smin:
381 case Intrinsic::vp_reduce_umax:
382 case Intrinsic::vp_reduce_umin:
383 case Intrinsic::vp_reduce_fmax:
384 case Intrinsic::vp_reduce_fmin:
385 case Intrinsic::vp_reduce_fmaximum:
386 case Intrinsic::vp_reduce_fminimum: {
389 Reduction = Builder.CreateUnaryIntrinsic(RedID, RedOp);
391 Reduction = Builder.CreateBinaryIntrinsic(ScalarID, Reduction, Start);
392 break;
393 }
394 case Intrinsic::vp_reduce_fadd:
395 Reduction = Builder.CreateFAddReduce(Start, RedOp);
396 break;
397 case Intrinsic::vp_reduce_fmul:
398 Reduction = Builder.CreateFMulReduce(Start, RedOp);
399 break;
400 }
401
403 return true;
404}
405
406bool CachingVPExpander::expandPredicationToCastIntrinsic(IRBuilder<> &Builder,
407 VPIntrinsic &VPI) {
408 Intrinsic::ID VPID = VPI.getIntrinsicID();
409 unsigned CastOpcode = VPIntrinsic::getFunctionalOpcodeForVP(VPID).value();
410 assert(Instruction::isCast(CastOpcode));
411 Value *CastOp = Builder.CreateCast(Instruction::CastOps(CastOpcode),
412 VPI.getOperand(0), VPI.getType());
413
414 replaceOperation(*CastOp, VPI);
415 return true;
416}
417
418bool CachingVPExpander::expandPredicationInMemoryIntrinsic(IRBuilder<> &Builder,
419 VPIntrinsic &VPI) {
421
422 const auto &DL = VPI.getDataLayout();
423
424 Value *MaskParam = VPI.getMaskParam();
425 Value *PtrParam = VPI.getMemoryPointerParam();
426 Value *DataParam = VPI.getMemoryDataParam();
427 bool IsUnmasked = isAllTrueMask(MaskParam);
428
429 MaybeAlign AlignOpt = VPI.getPointerAlignment();
430
431 Value *NewMemoryInst = nullptr;
432 switch (VPI.getIntrinsicID()) {
433 default:
434 llvm_unreachable("Not a VP memory intrinsic");
435 case Intrinsic::vp_store:
436 if (IsUnmasked) {
437 StoreInst *NewStore =
438 Builder.CreateStore(DataParam, PtrParam, /*IsVolatile*/ false);
439 if (AlignOpt.has_value())
440 NewStore->setAlignment(*AlignOpt);
441 NewMemoryInst = NewStore;
442 } else
443 NewMemoryInst = Builder.CreateMaskedStore(
444 DataParam, PtrParam, AlignOpt.valueOrOne(), MaskParam);
445
446 break;
447 case Intrinsic::vp_load:
448 if (IsUnmasked) {
449 LoadInst *NewLoad =
450 Builder.CreateLoad(VPI.getType(), PtrParam, /*IsVolatile*/ false);
451 if (AlignOpt.has_value())
452 NewLoad->setAlignment(*AlignOpt);
453 NewMemoryInst = NewLoad;
454 } else
455 NewMemoryInst = Builder.CreateMaskedLoad(
456 VPI.getType(), PtrParam, AlignOpt.valueOrOne(), MaskParam);
457
458 break;
459 case Intrinsic::vp_scatter: {
460 auto *ElementType =
461 cast<VectorType>(DataParam->getType())->getElementType();
462 NewMemoryInst = Builder.CreateMaskedScatter(
463 DataParam, PtrParam,
464 AlignOpt.value_or(DL.getPrefTypeAlign(ElementType)), MaskParam);
465 break;
466 }
467 case Intrinsic::vp_gather: {
468 auto *ElementType = cast<VectorType>(VPI.getType())->getElementType();
469 NewMemoryInst = Builder.CreateMaskedGather(
470 VPI.getType(), PtrParam,
471 AlignOpt.value_or(DL.getPrefTypeAlign(ElementType)), MaskParam,
472 nullptr);
473 break;
474 }
475 }
476
477 assert(NewMemoryInst);
478 replaceOperation(*NewMemoryInst, VPI);
479 return true;
480}
481
482bool CachingVPExpander::expandPredicationInComparison(IRBuilder<> &Builder,
483 VPCmpIntrinsic &VPI) {
485 "Implicitly dropping %evl in non-speculatable operator!");
486
487 assert(*VPI.getFunctionalOpcode() == Instruction::ICmp ||
488 *VPI.getFunctionalOpcode() == Instruction::FCmp);
489
490 Value *Op0 = VPI.getOperand(0);
491 Value *Op1 = VPI.getOperand(1);
492 auto Pred = VPI.getPredicate();
493
494 auto *NewCmp = Builder.CreateCmp(Pred, Op0, Op1);
495
496 replaceOperation(*NewCmp, VPI);
497 return true;
498}
499
500bool CachingVPExpander::discardEVLParameter(VPIntrinsic &VPI) {
501 LLVM_DEBUG(dbgs() << "Discard EVL parameter in " << VPI << "\n");
502
504 return false;
505
506 Value *EVLParam = VPI.getVectorLengthParam();
507 if (!EVLParam)
508 return false;
509
510 ElementCount StaticElemCount = VPI.getStaticVectorLength();
511 Value *MaxEVL = nullptr;
512 Type *Int32Ty = Type::getInt32Ty(VPI.getContext());
513 if (StaticElemCount.isScalable()) {
514 // TODO add caching
515 IRBuilder<> Builder(VPI.getParent(), VPI.getIterator());
516 Value *FactorConst = Builder.getInt32(StaticElemCount.getKnownMinValue());
517 Value *VScale = Builder.CreateVScale(Int32Ty, "vscale");
518 MaxEVL = Builder.CreateNUWMul(VScale, FactorConst, "scalable_size");
519 } else {
520 MaxEVL = ConstantInt::get(Int32Ty, StaticElemCount.getFixedValue(), false);
521 }
522 VPI.setVectorLengthParam(MaxEVL);
523 return true;
524}
525
526bool CachingVPExpander::foldEVLIntoMask(VPIntrinsic &VPI) {
527 LLVM_DEBUG(dbgs() << "Folding vlen for " << VPI << '\n');
528
529 IRBuilder<> Builder(&VPI);
530
531 // Ineffective %evl parameter and so nothing to do here.
533 return false;
534
535 // Only VP intrinsics can have an %evl parameter.
536 Value *OldMaskParam = VPI.getMaskParam();
537 if (!OldMaskParam) {
538 assert((VPI.getIntrinsicID() == Intrinsic::vp_merge ||
539 VPI.getIntrinsicID() == Intrinsic::vp_select) &&
540 "Unexpected VP intrinsic without mask operand");
541 OldMaskParam = VPI.getArgOperand(0);
542 }
543
544 Value *OldEVLParam = VPI.getVectorLengthParam();
545 assert(OldMaskParam && "no mask param to fold the vl param into");
546 assert(OldEVLParam && "no EVL param to fold away");
547
548 LLVM_DEBUG(dbgs() << "OLD evl: " << *OldEVLParam << '\n');
549 LLVM_DEBUG(dbgs() << "OLD mask: " << *OldMaskParam << '\n');
550
551 // Convert the %evl predication into vector mask predication.
552 ElementCount ElemCount = VPI.getStaticVectorLength();
553 Value *VLMask = convertEVLToMask(Builder, OldEVLParam, ElemCount);
554 Value *NewMaskParam = Builder.CreateAnd(VLMask, OldMaskParam);
555 if (VPI.getIntrinsicID() == Intrinsic::vp_merge ||
556 VPI.getIntrinsicID() == Intrinsic::vp_select)
557 VPI.setArgOperand(0, NewMaskParam);
558 else
559 VPI.setMaskParam(NewMaskParam);
560
561 // Drop the %evl parameter.
562 discardEVLParameter(VPI);
564 "transformation did not render the evl param ineffective!");
565
566 // Reassess the modified instruction.
567 return true;
568}
569
570bool CachingVPExpander::expandPredication(VPIntrinsic &VPI) {
571 LLVM_DEBUG(dbgs() << "Lowering to unpredicated op: " << VPI << '\n');
572
573 IRBuilder<> Builder(&VPI);
574
575 // Try lowering to a LLVM instruction first.
576 auto OC = VPI.getFunctionalOpcode();
577
578 if (OC && Instruction::isBinaryOp(*OC))
579 return expandPredicationInBinaryOperator(Builder, VPI);
580
581 if (auto *VPRI = dyn_cast<VPReductionIntrinsic>(&VPI))
582 return expandPredicationInReduction(Builder, *VPRI);
583
584 if (auto *VPCmp = dyn_cast<VPCmpIntrinsic>(&VPI))
585 return expandPredicationInComparison(Builder, *VPCmp);
586
588 return expandPredicationToCastIntrinsic(Builder, VPI);
589
590 switch (VPI.getIntrinsicID()) {
591 default:
592 break;
593 case Intrinsic::vp_fneg: {
594 Value *NewNegOp = Builder.CreateFNeg(VPI.getOperand(0));
595 replaceOperation(*NewNegOp, VPI);
596 return NewNegOp;
597 }
598 case Intrinsic::vp_select:
599 case Intrinsic::vp_merge: {
601 Value *NewSelectOp = Builder.CreateSelect(
602 VPI.getOperand(0), VPI.getOperand(1), VPI.getOperand(2));
603 replaceOperation(*NewSelectOp, VPI);
604 return NewSelectOp;
605 }
606 case Intrinsic::vp_abs:
607 case Intrinsic::vp_smax:
608 case Intrinsic::vp_smin:
609 case Intrinsic::vp_umax:
610 case Intrinsic::vp_umin:
611 case Intrinsic::vp_bswap:
612 case Intrinsic::vp_bitreverse:
613 case Intrinsic::vp_ctpop:
614 case Intrinsic::vp_ctlz:
615 case Intrinsic::vp_cttz:
616 case Intrinsic::vp_sadd_sat:
617 case Intrinsic::vp_uadd_sat:
618 case Intrinsic::vp_ssub_sat:
619 case Intrinsic::vp_usub_sat:
620 case Intrinsic::vp_fshl:
621 case Intrinsic::vp_fshr:
622 return expandPredicationToIntCall(Builder, VPI);
623 case Intrinsic::vp_fabs:
624 case Intrinsic::vp_copysign:
625 case Intrinsic::vp_sqrt:
626 case Intrinsic::vp_maxnum:
627 case Intrinsic::vp_minnum:
628 case Intrinsic::vp_maximum:
629 case Intrinsic::vp_minimum:
630 case Intrinsic::vp_ceil:
631 case Intrinsic::vp_floor:
632 case Intrinsic::vp_round:
633 case Intrinsic::vp_roundeven:
634 case Intrinsic::vp_roundtozero:
635 case Intrinsic::vp_rint:
636 case Intrinsic::vp_nearbyint:
637 case Intrinsic::vp_lrint:
638 case Intrinsic::vp_llrint:
639 case Intrinsic::vp_fma:
640 case Intrinsic::vp_fmuladd:
641 case Intrinsic::vp_is_fpclass:
642 return expandPredicationToFPCall(Builder, VPI,
643 VPI.getFunctionalIntrinsicID().value());
644 case Intrinsic::vp_load:
645 case Intrinsic::vp_store:
646 case Intrinsic::vp_gather:
647 case Intrinsic::vp_scatter:
648 return expandPredicationInMemoryIntrinsic(Builder, VPI);
649 }
650
651 if (auto CID = VPI.getConstrainedIntrinsicID())
652 if (expandPredicationToFPCall(Builder, VPI, *CID))
653 return true;
654
655 return false;
656}
657
658//// } CachingVPExpander
659
660void sanitizeStrategy(VPIntrinsic &VPI, VPLegalization &LegalizeStrat) {
661 // Operations with speculatable lanes do not strictly need predication.
662 if (maySpeculateLanes(VPI)) {
663 // Converting a speculatable VP intrinsic means dropping %mask and %evl.
664 // No need to expand %evl into the %mask only to ignore that code.
665 if (LegalizeStrat.OpStrategy == VPLegalization::Convert)
667 return;
668 }
669
670 // We have to preserve the predicating effect of %evl for this
671 // non-speculatable VP intrinsic.
672 // 1) Never discard %evl.
673 // 2) If this VP intrinsic will be expanded to non-VP code, make sure that
674 // %evl gets folded into %mask.
675 if ((LegalizeStrat.EVLParamStrategy == VPLegalization::Discard) ||
676 (LegalizeStrat.OpStrategy == VPLegalization::Convert)) {
678 }
679}
680
682CachingVPExpander::getVPLegalizationStrategy(const VPIntrinsic &VPI) const {
683 auto VPStrat = TTI.getVPLegalizationStrategy(VPI);
684 if (LLVM_LIKELY(!UsingTTIOverrides)) {
685 // No overrides - we are in production.
686 return VPStrat;
687 }
688
689 // Overrides set - we are in testing, the following does not need to be
690 // efficient.
692 VPStrat.OpStrategy = parseOverrideOption(MaskTransformOverride);
693 return VPStrat;
694}
695
697CachingVPExpander::expandVectorPredication(VPIntrinsic &VPI) {
698 auto Strategy = getVPLegalizationStrategy(VPI);
699 sanitizeStrategy(VPI, Strategy);
700
701 VPExpansionDetails Changed = VPExpansionDetails::IntrinsicUnchanged;
702
703 // Transform the EVL parameter.
704 switch (Strategy.EVLParamStrategy) {
706 break;
708 if (discardEVLParameter(VPI))
709 Changed = VPExpansionDetails::IntrinsicUpdated;
710 break;
712 if (foldEVLIntoMask(VPI)) {
713 Changed = VPExpansionDetails::IntrinsicUpdated;
714 ++NumFoldedVL;
715 }
716 break;
717 }
718
719 // Replace with a non-predicated operation.
720 switch (Strategy.OpStrategy) {
722 break;
724 llvm_unreachable("Invalid strategy for operators.");
726 if (expandPredication(VPI)) {
727 ++NumLoweredVPOps;
728 Changed = VPExpansionDetails::IntrinsicReplaced;
729 }
730 break;
731 }
732
733 return Changed;
734}
735} // namespace
736
739 const TargetTransformInfo &TTI) {
740 return CachingVPExpander(TTI).expandVectorPredication(VPI);
741}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:335
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static VPTransform parseOverrideOption(const std::string &TextOpt)
static cl::opt< std::string > MaskTransformOverride("expandvp-override-mask-transform", cl::init(""), cl::Hidden, cl::desc("Options: <empty>" VPINTERNAL_VPLEGAL_CASES ". If non-empty, Ignore " "TargetTransformInfo and " "always use this transformation for the %mask parameter (Used in " "testing)."))
static cl::opt< std::string > EVLTransformOverride("expandvp-override-evl-transform", cl::init(""), cl::Hidden, cl::desc("Options: <empty>" VPINTERNAL_VPLEGAL_CASES ". If non-empty, ignore " "TargetTransformInfo and " "always use this transformation for the %evl parameter (Used in " "testing)."))
static void replaceOperation(Value &NewOp, VPIntrinsic &OldOp)
Transfer all properties from OldOp to NewOp and replace all uses.
static bool isAllTrueMask(Value *MaskVal)
static void transferDecorations(Value &NewVal, VPIntrinsic &VPI)
Transfer operation properties from OldVPI to NewVal.
TargetTransformInfo::VPLegalization VPLegalization
TargetTransformInfo::VPLegalization::VPTransform VPTransform
static bool anyExpandVPOverridesSet()
static bool maySpeculateLanes(VPIntrinsic &VPI)
static Constant * getSafeDivisor(Type *DivTy)
#define VPINTERNAL_VPLEGAL_CASES
loop Loop Strength Reduction
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
This pass exposes codegen information to IR-level passes.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
This is an important base class in LLVM.
Definition Constant.h:43
Value * CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1490
LLVM_ABI CallInst * CreateFAddReduce(Value *Acc, Value *Src)
Create a sequential vector fadd reduction intrinsic of the source vector.
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:571
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
LLVM_ABI CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
LLVM_ABI CallInst * CreateConstrainedFPCall(Function *Callee, ArrayRef< Value * > Args, const Twine &Name="", std::optional< RoundingMode > Rounding=std::nullopt, std::optional< fp::ExceptionBehavior > Except=std::nullopt)
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2269
Value * CreateVScale(Type *Ty, const Twine &Name="")
Create a call to llvm.vscale.<Ty>().
Definition IRBuilder.h:988
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
LLVM_ABI Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:529
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2501
LLVM_ABI CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1591
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1926
LLVM_ABI CallInst * CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, Value *Mask)
Create a call to Masked Store intrinsic.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2546
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1748
LLVM_ABI CallInst * CreateFMulReduce(Value *Acc, Value *Src)
Create a sequential vector fmul reduction intrinsic of the source vector.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2477
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1846
LLVM_ABI Value * CreateStepVector(Type *DstType, const Twine &Name="")
Creates a vector of type DstType with the linear sequence <0, 1, ...>
LLVM_ABI CallInst * CreateMaskedScatter(Value *Val, Value *Ptrs, Align Alignment, Value *Mask=nullptr)
Create a call to Masked Scatter intrinsic.
LLVM_ABI CallInst * CreateMaskedGather(Type *Ty, Value *Ptrs, Align Alignment, Value *Mask=nullptr, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Gather intrinsic.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2847
bool isCast() const
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
void setAlignment(Align Align)
void setAlignment(Align Align)
A switch()-like statement whose cases are string literals.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI VPLegalization getVPLegalizationStrategy(const VPIntrinsic &PI) const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
static LLVM_ABI bool isVPCast(Intrinsic::ID ID)
LLVM_ABI CmpInst::Predicate getPredicate() const
This is the common base class for vector predication intrinsics.
std::optional< unsigned > getFunctionalIntrinsicID() const
LLVM_ABI bool canIgnoreVectorLengthParam() const
LLVM_ABI void setMaskParam(Value *)
static LLVM_ABI std::optional< unsigned > getFunctionalOpcodeForVP(Intrinsic::ID ID)
LLVM_ABI Value * getVectorLengthParam() const
LLVM_ABI void setVectorLengthParam(Value *)
LLVM_ABI Value * getMemoryDataParam() const
LLVM_ABI Value * getMemoryPointerParam() const
std::optional< unsigned > getConstrainedIntrinsicID() const
LLVM_ABI MaybeAlign getPointerAlignment() const
LLVM_ABI Value * getMaskParam() const
LLVM_ABI ElementCount getStaticVectorLength() const
std::optional< unsigned > getFunctionalOpcode() const
LLVM_ABI unsigned getStartParamPos() const
LLVM_ABI unsigned getVectorParamPos() const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
bool hasName() const
Definition Value.h:261
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:399
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI bool isConstrainedFPIntrinsic(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics".
LLVM_ABI AttributeSet getFnAttributes(LLVMContext &C, ID id)
Return the function attributes for an intrinsic.
initializer< Ty > init(const Ty &Val)
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
Definition InstrProf.h:328
LLVM_ABI Value * getReductionIdentity(Intrinsic::ID RdxID, Type *Ty, FastMathFlags FMF)
Given information about an @llvm.vector.reduce.
LLVM_ABI unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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
VPExpansionDetails expandVectorPredicationIntrinsic(VPIntrinsic &VPI, const TargetTransformInfo &TTI)
Expand a vector predication intrinsic.
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
VPExpansionDetails
Represents the details the expansion of a VP intrinsic.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130