LLVM 24.0.0git
VPlanEVLTailFolding.cpp
Go to the documentation of this file.
1//===- VPlanEVLTailFolding.cpp - EVL tail folding transforms --------------===//
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 implements the VPlan-to-VPlan transforms related to explicit
11/// vector length (EVL) tail folding support.
12///
13//===----------------------------------------------------------------------===//
14
16#include "VPlan.h"
17#include "VPlanCFG.h"
18#include "VPlanHelpers.h"
19#include "VPlanPatternMatch.h"
20#include "VPlanTransforms.h"
21#include "VPlanUtils.h"
23#include "llvm/IR/Intrinsics.h"
24
25using namespace llvm;
26using namespace VPlanPatternMatch;
27
28/// From the definition of llvm.experimental.get.vector.length,
29/// VPInstruction::ExplicitVectorLength(%AVL) = %AVL when %AVL <= VF.
34 for (VPRecipeBase &R : *VPBB) {
35 VPValue *AVL;
36 if (!match(&R, m_EVL(m_VPValue(AVL))))
37 continue;
38
39 const SCEV *AVLSCEV = vputils::getSCEVExprForVPValue(AVL, PSE);
40 if (isa<SCEVCouldNotCompute>(AVLSCEV))
41 continue;
42 ScalarEvolution &SE = *PSE.getSE();
43 const SCEV *VFSCEV = SE.getElementCount(AVLSCEV->getType(), VF);
44 if (!SE.isKnownPredicate(CmpInst::ICMP_ULE, AVLSCEV, VFSCEV))
45 continue;
46
48 AVL, Type::getInt32Ty(Plan.getContext()), R.getDebugLoc());
49 if (Trunc != AVL) {
50 auto *TruncR = cast<VPSingleDefRecipe>(Trunc);
51 const DataLayout &DL = Plan.getDataLayout();
52 if (VPValue *Folded =
53 vputils::tryToFoldLiveIns(*TruncR, TruncR->operands(), DL))
54 Trunc = Folded;
55 }
56 R.getVPSingleValue()->replaceAllUsesWith(Trunc);
57 return true;
58 }
59 }
60 return false;
61}
62
63template <typename Op0_t, typename Op1_t> struct RemoveMask_match {
64 Op0_t In;
66
67 RemoveMask_match(const Op0_t &In, Op1_t &Out) : In(In), Out(Out) {}
68
69 template <typename OpTy> bool match(OpTy *V) const {
70 if (m_Specific(In).match(V)) {
71 Out = nullptr;
72 return true;
73 }
74 return m_LogicalAnd(m_Specific(In), m_VPValue(Out)).match(V);
75 }
76};
77
78/// Match a specific mask \p In, or a combination of it (logical-and In, Out).
79/// Returns the remaining part \p Out if so, or nullptr otherwise.
80template <typename Op0_t, typename Op1_t>
81static inline RemoveMask_match<Op0_t, Op1_t> m_RemoveMask(const Op0_t &In,
82 Op1_t &Out) {
83 return RemoveMask_match<Op0_t, Op1_t>(In, Out);
84}
85
86static std::optional<Intrinsic::ID> getVPDivRemIntrinsic(Intrinsic::ID IntrID) {
87 switch (IntrID) {
88 case Intrinsic::masked_udiv:
89 return Intrinsic::vp_udiv;
90 case Intrinsic::masked_sdiv:
91 return Intrinsic::vp_sdiv;
92 case Intrinsic::masked_urem:
93 return Intrinsic::vp_urem;
94 case Intrinsic::masked_srem:
95 return Intrinsic::vp_srem;
96 default:
97 return std::nullopt;
98 }
99}
100
101/// Try to optimize a \p CurRecipe masked by \p HeaderMask to a corresponding
102/// EVL-based recipe without the header mask. Returns nullptr if no EVL-based
103/// recipe could be created.
104/// \p HeaderMask Header Mask.
105/// \p CurRecipe Recipe to be transform.
106/// \p EVL The explicit vector length parameter of vector-predication
107/// intrinsics.
109 VPRecipeBase &CurRecipe, VPValue &EVL) {
110 VPlan *Plan = CurRecipe.getParent()->getPlan();
111 DebugLoc DL = CurRecipe.getDebugLoc();
112 VPValue *Addr, *Mask, *EndPtr;
113
114 /// Adjust any end pointers so that they point to the end of EVL lanes not VF.
115 auto AdjustEndPtr = [&CurRecipe, &EVL](VPValue *EndPtr) {
116 auto *EVLEndPtr = cast<VPVectorEndPointerRecipe>(EndPtr)->clone();
117 EVLEndPtr->insertBefore(&CurRecipe);
118 // Cast EVL (i32) to match the VF operand's type.
119 VPValue *EVLAsVF = VPBuilder(EVLEndPtr).createScalarZExtOrTrunc(
120 &EVL, EVLEndPtr->getOperand(1)->getScalarType(),
122 EVLEndPtr->setOperand(1, EVLAsVF);
123 return EVLEndPtr;
124 };
125
126 auto GetVPReverse = [&CurRecipe, &EVL, Plan,
128 if (!V)
129 return nullptr;
131 Intrinsic::experimental_vp_reverse, {V, Plan->getTrue(), &EVL},
132 V->getScalarType(), {}, {}, DL);
133 Reverse->insertBefore(&CurRecipe);
134 return Reverse;
135 };
136
137 if (match(&CurRecipe,
138 m_MaskedLoad(m_VPValue(Addr), m_RemoveMask(HeaderMask, Mask))))
139 return new VPWidenLoadEVLRecipe(cast<VPWidenLoadRecipe>(CurRecipe), Addr,
140 EVL, Mask);
141
142 if (match(&CurRecipe,
143 m_MaskedLoad(m_VPValue(EndPtr),
144 m_Reverse(m_RemoveMask(HeaderMask, Mask)))) &&
145 match(EndPtr, m_VecEndPtr(m_VPValue(), m_Specific(&Plan->getVF())))) {
146 Mask = GetVPReverse(Mask);
147 Addr = AdjustEndPtr(EndPtr);
148 auto *LoadR = new VPWidenLoadEVLRecipe(cast<VPWidenLoadRecipe>(CurRecipe),
149 Addr, EVL, Mask);
150 LoadR->insertBefore(&CurRecipe);
151 VPValue *Poison = Plan->getPoison(LoadR->getScalarType());
152 return new VPWidenIntrinsicRecipe(Intrinsic::vector_splice_left,
153 {Poison, LoadR, &EVL},
154 LoadR->getScalarType(), {}, {}, DL);
155 }
156
157 if (match(&CurRecipe,
159 m_VPValue(), m_VPValue(), m_RemoveMask(HeaderMask, Mask),
160 m_TruncOrSelf(m_Specific(&Plan->getVF()))))) {
161 auto *NewLoad = cast<VPWidenMemIntrinsicRecipe>(&CurRecipe)->clone();
162 NewLoad->setOperand(2, Mask ? Mask : Plan->getTrue());
163 NewLoad->setOperand(3, &EVL);
164 return NewLoad;
165 }
166
167 VPValue *StoredVal;
168 if (match(&CurRecipe, m_MaskedStore(m_VPValue(Addr), m_VPValue(StoredVal),
169 m_RemoveMask(HeaderMask, Mask))))
170 return new VPWidenStoreEVLRecipe(cast<VPWidenStoreRecipe>(CurRecipe), Addr,
171 StoredVal, EVL, Mask);
172
173 if (match(&CurRecipe,
174 m_MaskedStore(m_VPValue(EndPtr), m_VPValue(StoredVal),
175 m_Reverse(m_RemoveMask(HeaderMask, Mask)))) &&
176 match(EndPtr, m_VecEndPtr(m_VPValue(), m_Specific(&Plan->getVF())))) {
177 Mask = GetVPReverse(Mask);
178 Addr = AdjustEndPtr(EndPtr);
179 VPValue *Poison = Plan->getPoison(StoredVal->getScalarType());
180 auto *SpliceR = new VPWidenIntrinsicRecipe(
181 Intrinsic::vector_splice_right, {StoredVal, Poison, &EVL},
182 StoredVal->getScalarType(), {}, {}, DL);
183 SpliceR->insertBefore(&CurRecipe);
184 return new VPWidenStoreEVLRecipe(cast<VPWidenStoreRecipe>(CurRecipe), Addr,
185 SpliceR, EVL, Mask);
186 }
187
190 m_RemoveMask(HeaderMask, Mask),
191 m_TruncOrSelf(m_Specific(&Plan->getVF()))))) {
192 auto *NewStore = cast<VPWidenMemIntrinsicRecipe>(&CurRecipe)->clone();
193 NewStore->setOperand(3, Mask ? Mask : Plan->getTrue());
194 NewStore->setOperand(4, &EVL);
195 return NewStore;
196 }
197
198 if (auto *Rdx = dyn_cast<VPReductionRecipe>(&CurRecipe))
199 if (Rdx->isConditional() &&
200 match(Rdx->getCondOp(), m_RemoveMask(HeaderMask, Mask)))
201 return new VPReductionEVLRecipe(*Rdx, EVL, Mask);
202
203 if (auto *Interleave = dyn_cast<VPInterleaveRecipe>(&CurRecipe))
204 if (Interleave->getMask() &&
205 match(Interleave->getMask(), m_RemoveMask(HeaderMask, Mask)))
206 return new VPInterleaveEVLRecipe(*Interleave, EVL, Mask);
207
208 VPValue *LHS, *RHS;
209 if (match(&CurRecipe, m_SelectLike(m_RemoveMask(HeaderMask, Mask),
211 return new VPWidenIntrinsicRecipe(
212 Intrinsic::vp_merge, {Mask ? Mask : Plan->getTrue(), LHS, RHS, &EVL},
213 LHS->getScalarType(), {}, {}, DL);
214
215 if (match(&CurRecipe, m_LastActiveLane(m_Specific(HeaderMask)))) {
216 Type *Ty = CurRecipe.getVPSingleValue()->getScalarType();
217 VPValue *ZExt = VPBuilder(&CurRecipe).createScalarZExtOrTrunc(&EVL, Ty, DL);
218 return new VPInstruction(
219 Instruction::Sub, {ZExt, Plan->getConstantInt(Ty, 1)},
220 VPIRFlags::getDefaultFlags(Instruction::Sub), {}, DL);
221 }
222
223 // lhs | (headermask && rhs) -> vp.merge rhs, true, lhs, evl
224 if (match(&CurRecipe,
226 m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(RHS)))))
227 return new VPWidenIntrinsicRecipe(Intrinsic::vp_merge,
228 {RHS, Plan->getTrue(), LHS, &EVL},
229 LHS->getScalarType(), {}, {}, DL);
230
231 if (auto *IntrR = dyn_cast<VPWidenIntrinsicRecipe>(&CurRecipe))
232 if (auto VPID = getVPDivRemIntrinsic(IntrR->getVectorIntrinsicID()))
233 if (match(IntrR->getOperand(2), m_RemoveMask(HeaderMask, Mask)))
234 return new VPWidenIntrinsicRecipe(*VPID,
235 {IntrR->getOperand(0),
236 IntrR->getOperand(1),
237 Mask ? Mask : Plan->getTrue(), &EVL},
238 IntrR->getScalarType(), {}, {}, DL);
239
240 return nullptr;
241}
242
243/// Optimize away any EVL-based header masks to VP intrinsic based recipes.
244/// The transforms here need to preserve the original semantics.
246 // Find the EVL-based header mask if it exists: icmp ult step-vector, EVL
247 VPValue *HeaderMask = nullptr, *EVL = nullptr;
250 m_VPValue(EVL))) &&
251 match(EVL, m_EVL(m_VPValue()))) {
252 HeaderMask = R.getVPSingleValue();
253 break;
254 }
255 }
256 if (!HeaderMask)
257 return;
258
260 for (VPUser *U : vputils::collectUsersRecursively(HeaderMask)) {
262 if (auto *NewR = optimizeMaskToEVL(HeaderMask, *R, *EVL)) {
263 NewR->insertBefore(R);
264 for (auto [Old, New] :
265 zip_equal(R->definedValues(), NewR->definedValues()))
266 Old->replaceAllUsesWith(New);
267 OldRecipes.push_back(R);
268 }
269 }
270
271 // Replace remaining (HeaderMask && Mask) with vp.merge (True, Mask,
272 // False, EVL)
273 for (VPUser *U : vputils::collectUsersRecursively(HeaderMask)) {
274 VPValue *Mask;
275 if (match(U, m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(Mask)))) {
276 auto *LogicalAnd = cast<VPInstruction>(U);
277 auto *Merge = new VPWidenIntrinsicRecipe(
278 Intrinsic::vp_merge, {Plan.getTrue(), Mask, Plan.getFalse(), EVL},
279 Mask->getScalarType(), {}, {}, LogicalAnd->getDebugLoc());
280 Merge->insertBefore(LogicalAnd);
281 LogicalAnd->replaceAllUsesWith(Merge);
282 OldRecipes.push_back(LogicalAnd);
283 }
284 }
285
286 // Pull out left splices from any elementwise op.
287 // binop(splice.left(poison, x, evl), live-in)
288 // -> splice.left(poison, binop(x,live-in), evl)
290 Plan,
291 [&EVL](VPValue *&X) {
293 m_Poison(), m_VPValue(X), m_Specific(EVL));
294 },
295 [&Plan, &EVL](auto *X) {
296 return new VPWidenIntrinsicRecipe(
297 Intrinsic::vector_splice_left,
298 {Plan.getPoison(X->getScalarType()), X, EVL}, X->getScalarType(),
299 {}, {}, X->getDebugLoc());
300 });
301
302 // Fold the following splice patterns:
303 // splice.right(splice.left(poison, x, evl), poison, evl) -> x
304 // vector.reverse(splice.left(poison, x, evl)) -> vp.reverse(x, true, evl)
305 // splice.right(vector.reverse(x), poison, evl) -> vp.reverse(x, true, evl)
307 auto *R = cast<VPRecipeBase>(U);
308 // Remove potentially dead left splices from the transform above.
310 R->getVPSingleValue()->getNumUsers() == 0) {
311 OldRecipes.push_back(R);
312 continue;
313 }
314
315 VPValue *X;
318 m_Poison(), m_VPValue(X), m_Specific(EVL)),
319 m_Poison(), m_Specific(EVL)))) {
320 R->getVPSingleValue()->replaceAllUsesWith(X);
321 OldRecipes.push_back(R);
322 continue;
323 }
324
325 if (!match(U,
328 m_Poison(), m_VPValue(X), m_Specific(EVL))),
331 continue;
332
333 auto *VPReverse = new VPWidenIntrinsicRecipe(
334 Intrinsic::experimental_vp_reverse, {X, Plan.getTrue(), EVL},
335 X->getScalarType(), {}, {}, R->getDebugLoc());
336 VPReverse->insertBefore(R);
337 R->getVPSingleValue()->replaceAllUsesWith(VPReverse);
338 OldRecipes.push_back(R);
339 }
340
341 for (VPRecipeBase *R : reverse(OldRecipes)) {
342 SmallVector<VPValue *> PossiblyDead(R->operands());
343 R->eraseFromParent();
344 for (VPValue *Op : PossiblyDead)
346 }
347}
348
349/// After replacing the canonical IV with a EVL-based IV, fixup recipes that use
350/// VF to use the EVL instead to avoid incorrect updates on the penultimate
351/// iteration.
352static void fixupVFUsersForEVL(VPlan &Plan, VPValue &EVL) {
353 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
354 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
355
356 // EVL is i32 but VF/VFxUF are IdxTy. Convert as needed.
357 VPValue *EVLAsIdx =
361
362 assert(all_of(Plan.getVF().users(),
363 [&Plan](VPUser *U) {
364 auto IsAllowedUser =
365 IsaPred<VPVectorEndPointerRecipe, VPScalarIVStepsRecipe,
366 VPWidenIntOrFpInductionRecipe,
367 VPWidenMemIntrinsicRecipe>;
368 if (match(U, m_Trunc(m_Specific(&Plan.getVF()))))
369 return all_of(cast<VPSingleDefRecipe>(U)->users(),
370 IsAllowedUser);
371 return IsAllowedUser(U);
372 }) &&
373 "User of VF that we can't transform to EVL.");
374 Plan.getVF().replaceUsesWithIf(EVLAsIdx, [](VPUser &U, unsigned Idx) {
376 });
377
378 assert(all_of(Plan.getVFxUF().users(),
380 m_c_Add(m_Specific(LoopRegion->getCanonicalIV()),
381 m_Specific(&Plan.getVFxUF())),
383 "Only users of VFxUF should be VPWidenPointerInductionRecipe and the "
384 "increment of the canonical induction.");
385 Plan.getVFxUF().replaceUsesWithIf(EVLAsIdx, [](VPUser &U, unsigned Idx) {
386 // Only replace uses in VPWidenPointerInductionRecipe; The increment of the
387 // canonical induction must not be updated.
389 });
390
391 // Create a scalar phi to track the previous EVL if fixed-order recurrence is
392 // contained.
393 bool ContainsFORs =
395 if (ContainsFORs) {
396 // TODO: Use VPInstruction::ExplicitVectorLength to get maximum EVL.
397 VPValue *MaxEVL = &Plan.getVF();
398 // Emit VPScalarCastRecipe in preheader if VF is not a 32 bits integer.
399 VPBuilder Builder(LoopRegion->getPreheaderVPBB());
400 MaxEVL = Builder.createScalarZExtOrTrunc(
402
403 Builder.setInsertPoint(Header, Header->getFirstNonPhi());
404 VPValue *PrevEVL = Builder.createScalarPhi(
405 {MaxEVL, &EVL}, DebugLoc::getUnknown(), "prev.evl");
406
409 for (VPRecipeBase &R : *VPBB) {
410 VPValue *V1, *V2;
411 if (!match(&R,
413 m_VPValue(V1), m_VPValue(V2))))
414 continue;
415 VPValue *Imm = Plan.getOrAddLiveIn(
418 Intrinsic::experimental_vp_splice,
419 {V1, V2, Imm, Plan.getTrue(), PrevEVL, &EVL},
420 R.getVPSingleValue()->getScalarType(), {}, {}, R.getDebugLoc());
421 VPSplice->insertBefore(&R);
422 R.getVPSingleValue()->replaceAllUsesWith(VPSplice);
423 }
424 }
425 }
426
427 VPValue *HeaderMask = LoopRegion->getHeaderMask();
428 if (!HeaderMask)
429 return;
430
431 // Ensure that any reduction that uses a select to mask off tail lanes does so
432 // in the vector loop, not the middle block, since EVL tail folding can have
433 // tail elements in the penultimate iteration.
434 assert(all_of(*Plan.getMiddleBlock(), [&Plan, HeaderMask](VPRecipeBase &R) {
435 if (match(&R, m_ComputeReductionResult(m_Select(m_Specific(HeaderMask),
436 m_VPValue(), m_VPValue()))))
437 return R.getOperand(0)->getDefiningRecipe()->getRegion() ==
438 Plan.getVectorLoopRegion();
439 return true;
440 }));
441
442 // Replace the abstract header mask with a mask equivalent to predicating by
443 // EVL: icmp ult step-vector, EVL
444 VPRecipeBase *EVLR = EVL.getDefiningRecipe();
445 VPBuilder Builder(EVLR->getParent(), std::next(EVLR->getIterator()));
446 Type *EVLType = EVL.getScalarType();
447 VPValue *EVLMask = Builder.createICmp(
449 Builder.createNaryOp(VPInstruction::StepVector, {}, EVLType), &EVL);
450 HeaderMask->replaceAllUsesWith(EVLMask);
451}
452
453/// Converts a tail folded vector loop region to step by
454/// VPInstruction::ExplicitVectorLength elements instead of VF elements each
455/// iteration.
456///
457/// - Add a VPCurrentIterationPHIRecipe and related recipes to \p Plan and
458/// replaces all uses of the canonical IV except for the canonical IV
459/// increment with a VPCurrentIterationPHIRecipe. The canonical IV is used
460/// only for loop iterations counting after this transformation.
461///
462/// - The header mask is replaced with a header mask based on the EVL.
463///
464/// - Plans with FORs have a new phi added to keep track of the EVL of the
465/// previous iteration, and VPFirstOrderRecurrencePHIRecipes are replaced with
466/// @llvm.vp.splice.
467///
468/// The function uses the following definitions:
469/// %StartV is the canonical induction start value.
470///
471/// The function adds the following recipes:
472///
473/// vector.ph:
474/// ...
475///
476/// vector.body:
477/// ...
478/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
479/// [ %NextIter, %vector.body ]
480/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
481/// %VPEVL = EXPLICIT-VECTOR-LENGTH %AVL
482/// ...
483/// %OpEVL = cast i32 %VPEVL to IVSize
484/// %NextIter = add IVSize %OpEVL, %CurrentIter
485/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
486/// ...
487///
488/// If MaxSafeElements is provided, the function adds the following recipes:
489/// vector.ph:
490/// ...
491///
492/// vector.body:
493/// ...
494/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
495/// [ %NextIter, %vector.body ]
496/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
497/// %cmp = cmp ult %AVL, MaxSafeElements
498/// %SAFE_AVL = select %cmp, %AVL, MaxSafeElements
499/// %VPEVL = EXPLICIT-VECTOR-LENGTH %SAFE_AVL
500/// ...
501/// %OpEVL = cast i32 %VPEVL to IVSize
502/// %NextIter = add IVSize %OpEVL, %CurrentIter
503/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
504/// ...
505///
507 VPlan &Plan, const std::optional<unsigned> &MaxSafeElements) {
508 if (Plan.hasScalarVFOnly())
509 return;
510 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
511 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
512
513 auto *CanonicalIV = LoopRegion->getCanonicalIV();
514 auto *CanIVTy = LoopRegion->getCanonicalIVType();
515 VPValue *StartV = Plan.getZero(CanIVTy);
516 auto *CanonicalIVIncrement = LoopRegion->getOrCreateCanonicalIVIncrement();
517
518 // Create the CurrentIteration recipe in the vector loop.
519 auto *CurrentIteration =
521 CurrentIteration->insertBefore(*Header, Header->begin());
522 VPBuilder Builder(Header, Header->getFirstNonPhi());
523 // Create the AVL (application vector length), starting from TC -> 0 in steps
524 // of EVL.
525 VPPhi *AVLPhi = Builder.createScalarPhi(
527 VPValue *AVL = AVLPhi;
528
529 if (MaxSafeElements) {
530 // Support for MaxSafeDist for correct loop emission.
531 VPValue *AVLSafe = Plan.getConstantInt(CanIVTy, *MaxSafeElements);
532 VPValue *Cmp = Builder.createICmp(ICmpInst::ICMP_ULT, AVL, AVLSafe);
533 AVL = Builder.createSelect(Cmp, AVL, AVLSafe, DebugLoc::getUnknown(),
534 "safe_avl");
535 }
536 auto *VPEVL = Builder.createNaryOp(VPInstruction::ExplicitVectorLength, AVL,
537 DebugLoc::getUnknown(), "evl");
538
539 Builder.setInsertPoint(CanonicalIVIncrement);
540 VPValue *OpVPEVL = VPEVL;
541
542 OpVPEVL = Builder.createScalarZExtOrTrunc(
543 OpVPEVL, CanIVTy, CanonicalIVIncrement->getDebugLoc());
544
545 auto *NextIter = Builder.createAdd(
546 OpVPEVL, CurrentIteration, CanonicalIVIncrement->getDebugLoc(),
547 "current.iteration.next", CanonicalIVIncrement->getNoWrapFlags());
548 CurrentIteration->addBackedgeValue(NextIter);
549
550 VPValue *NextAVL =
551 Builder.createSub(AVLPhi, OpVPEVL, DebugLoc::getCompilerGenerated(),
552 "avl.next", {/*NUW=*/true, /*NSW=*/false});
553 AVLPhi->addIncoming(NextAVL);
554
555 fixupVFUsersForEVL(Plan, *VPEVL);
556 removeDeadRecipes(Plan);
557
558 // Replace all uses of the canonical IV with VPCurrentIterationPHIRecipe
559 // except for the canonical IV increment.
560 CanonicalIV->replaceUsesWithIf(CurrentIteration,
561 [CanonicalIVIncrement](VPUser &U, unsigned) {
562 return &U != CanonicalIVIncrement;
563 });
564 // TODO: support unroll factor > 1.
565 Plan.setUF(1);
566}
567
569 // Find the vector loop entry by locating VPCurrentIterationPHIRecipe.
570 // There should be only one VPCurrentIteration in the entire plan.
571 VPCurrentIterationPHIRecipe *CurrentIteration = nullptr;
572
575 for (VPRecipeBase &R : VPBB->phis())
576 if (auto *PhiR = dyn_cast<VPCurrentIterationPHIRecipe>(&R)) {
577 assert(!CurrentIteration &&
578 "Found multiple CurrentIteration. Only one expected");
579 CurrentIteration = PhiR;
580 }
581
582 // Early return if it is not variable-length stepping.
583 if (!CurrentIteration)
584 return;
585
586 VPBasicBlock *HeaderVPBB = CurrentIteration->getParent();
587 VPValue *CurrentIterationIncr = CurrentIteration->getBackedgeValue();
588
589 // Convert CurrentIteration to concrete recipe.
590 auto *ScalarR =
591 VPBuilder(CurrentIteration)
593 {CurrentIteration->getStartValue(), CurrentIterationIncr},
594 CurrentIteration->getDebugLoc(), "current.iteration.iv");
595 CurrentIteration->replaceAllUsesWith(ScalarR);
596 CurrentIteration->eraseFromParent();
597
598 // Replace CanonicalIVInc with CurrentIteration increment if it exists.
599 auto *CanonicalIV = cast<VPPhi>(&*HeaderVPBB->begin());
600 if (auto *CanIVInc = findUserOf(
601 CanonicalIV, m_c_Add(m_VPValue(), m_Specific(&Plan.getVFxUF())))) {
602 cast<VPInstruction>(CanIVInc)->replaceAllUsesWith(CurrentIterationIncr);
603 CanIVInc->eraseFromParent();
604 }
605}
606
608 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
609 if (!LoopRegion)
610 return;
611 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
612 if (Header->empty())
613 return;
614 // The EVL IV is always at the beginning.
615 auto *EVLPhi = dyn_cast<VPCurrentIterationPHIRecipe>(&Header->front());
616 if (!EVLPhi)
617 return;
618
619 // Bail if not an EVL tail folded loop.
620 VPValue *AVL;
621 if (!match(EVLPhi->getBackedgeValue(),
623 return;
624
625 // The AVL may be capped to a safe distance.
626 VPValue *SafeAVL, *UnsafeAVL;
627 if (match(AVL,
629 m_VPValue(SafeAVL)),
630 m_Deferred(UnsafeAVL), m_Deferred(SafeAVL))))
631 AVL = UnsafeAVL;
632
633 VPValue *AVLNext;
634 [[maybe_unused]] bool FoundAVLNext =
636 m_Specific(Plan.getTripCount()), m_VPValue(AVLNext)));
637 assert(FoundAVLNext && "Didn't find AVL backedge?");
638
639 VPBasicBlock *Latch = LoopRegion->getExitingBasicBlock();
640 auto *LatchBr = cast<VPInstruction>(Latch->getTerminator());
641 if (match(LatchBr, m_BranchOnCond(m_True())))
642 return;
643
644 VPValue *CanIVInc;
645 [[maybe_unused]] bool FoundIncrement = match(
646 LatchBr,
648 m_Specific(&Plan.getVectorTripCount()))));
649 assert(FoundIncrement &&
650 match(CanIVInc, m_Add(m_Specific(LoopRegion->getCanonicalIV()),
651 m_Specific(&Plan.getVFxUF()))) &&
652 "Expected BranchOnCond with ICmp comparing CanIV + VFxUF with vector "
653 "trip count");
654
655 Type *AVLTy = AVLNext->getScalarType();
656 VPBuilder Builder(LatchBr);
657 LatchBr->setOperand(
658 0, Builder.createICmp(CmpInst::ICMP_EQ, AVLNext, Plan.getZero(AVLTy)));
659}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
This file provides a LoopVectorizationPlanner class.
R600 Clause Merge
static RemoveMask_match< Op0_t, Op1_t > m_RemoveMask(const Op0_t &In, Op1_t &Out)
Match a specific mask In, or a combination of it (logical-and In, Out).
static void fixupVFUsersForEVL(VPlan &Plan, VPValue &EVL)
After replacing the canonical IV with a EVL-based IV, fixup recipes that use VF to use the EVL instea...
static std::optional< Intrinsic::ID > getVPDivRemIntrinsic(Intrinsic::ID IntrID)
static VPRecipeBase * optimizeMaskToEVL(VPValue *HeaderMask, VPRecipeBase &CurRecipe, VPValue &EVL)
Try to optimize a CurRecipe masked by HeaderMask to a corresponding EVL-based recipe without the head...
This file contains the declarations of different VPlan-related auxiliary helpers.
This file provides utility VPlan to VPlan transformations.
This file contains the declarations of the Vectorization Plan base classes:
Value * RHS
Value * LHS
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
static DebugLoc getUnknown()
Definition DebugLoc.h:153
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4389
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4424
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:663
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:236
VPlan * getPlan()
Definition VPlan.cpp:211
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:402
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:384
VPlan-based builder utility analogous to IRBuilder.
VPValue * createScalarZExtOrTrunc(VPValue *Op, Type *ResultTy, DebugLoc DL)
static VPBuilder getToInsertAfter(VPRecipeBase *R)
Create a VPBuilder to insert after R.
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", const VPIRFlags &Flags={}, Type *ResultTy=nullptr)
A recipe for generating the phi node tracking the current scalar iteration index.
Definition VPlan.h:4082
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:551
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2493
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2482
static VPIRFlags getDefaultFlags(unsigned Opcode, Type *ResultTy=nullptr)
Returns default flags for Opcode and scalar ResultTy for opcodes that support it, asserts otherwise.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1234
A recipe for interleaved memory operations with vector-predication intrinsics.
Definition VPlan.h:3182
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1676
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:411
VPBasicBlock * getParent()
Definition VPlan.h:483
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:561
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A recipe to represent inloop reduction operations with vector-predication intrinsics,...
Definition VPlan.h:3352
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4614
const VPBlockBase * getEntry() const
Definition VPlan.h:4658
VPInstruction * getOrCreateCanonicalIVIncrement()
Get the canonical IV increment instruction if it exists.
Definition VPlan.cpp:898
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4742
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4734
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4683
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4747
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:401
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:149
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:130
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1495
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser &U, unsigned Idx)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1501
user_range users()
Definition VPlanValue.h:157
A recipe for widening vector intrinsics.
Definition VPlan.h:1936
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4801
const DataLayout & getDataLayout() const
Definition VPlan.h:5008
LLVMContext & getContext() const
Definition VPlan.h:5004
VPBasicBlock * getEntry()
Definition VPlan.h:4897
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4962
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5099
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5002
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5127
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4992
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:5076
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5102
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1080
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4932
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5096
bool hasScalarVFOnly() const
Definition VPlan.h:5044
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4995
void setUF(unsigned UF)
Definition VPlan.h:5059
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:5110
self_iterator getIterator()
Definition ilist_node.h:123
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
auto m_Poison()
Match an arbitrary poison constant.
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
SpecificCmpClass_match< LHS, RHS, CmpInst > m_SpecificCmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
SelectLike_match< CondTy, LTy, RTy > m_SelectLike(const CondTy &C, const LTy &TrueC, const RTy &FalseC)
Matches a value that behaves like a boolean-controlled select, i.e.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_MaskedStore(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
Matches MaskedStore Intrinsic.
auto m_MaskedLoad(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
Matches MaskedLoad Intrinsic.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
AllRecipe_commutative_match< Instruction::Or, Op0_t, Op1_t > m_c_BinaryOr(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::StepVector > m_StepVector()
VPInstruction_match< VPInstruction::LastActiveLane, Op0_t > m_LastActiveLane(const Op0_t &Op0)
specific_intval< 1 > m_True()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VectorEndPointerRecipe_match< Op0_t, Op1_t > m_VecEndPtr(const Op0_t &Op0, const Op1_t &Op1)
VPRecipeBase * findUserOf(VPValue *V, const MatchT &P)
If V is used by a recipe matching pattern P, return it.
VPInstruction_match< VPInstruction::ExplicitVectorLength, Op0_t > m_EVL(const Op0_t &Op0)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
VPInstruction_match< VPInstruction::Reverse, Op0_t > m_Reverse(const Op0_t &Op0)
VPIRValue * tryToFoldLiveIns(VPSingleDefRecipe &R, ArrayRef< VPValue * > Operands, const DataLayout &DL)
Try to fold R using InstSimplifyFolder.
void recursivelyDeleteDeadRecipes(VPValue *V)
Recursively delete V and any of its operands that become dead.
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
void pullOutPermutations(VPlan &Plan, Match_t Perm, Builder Build)
Removes the permutation pattern Perm from any elementwise operations in the plan, by constructing a n...
Definition VPlanUtils.h:236
SmallVector< VPUser * > collectUsersRecursively(VPValue *V)
Collect all users of V, looking through recipes that define other values.
This is an optimization pass for GlobalISel generic memory operations.
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:1739
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
Definition VPlanCFG.h:250
iterator_range< df_iterator< VPBlockDeepTraversalWrapper< VPBlockBase * > > > vp_depth_first_deep(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order while traversing t...
Definition VPlanCFG.h:285
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:1746
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
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
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
RemoveMask_match(const Op0_t &In, Op1_t &Out)
bool match(OpTy *V) const
A recipe for widening load operations with vector-predication intrinsics, using the address to load f...
Definition VPlan.h:3858
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:3961
static bool simplifyKnownEVL(VPlan &Plan, ElementCount VF, PredicatedScalarEvolution &PSE)
Try to simplify VPInstruction::ExplicitVectorLength recipes when the AVL is known to be <= VF,...
static void convertToVariableLengthStep(VPlan &Plan)
Transform loops with variable-length stepping after region dissolution.
static void addExplicitVectorLength(VPlan &Plan, const std::optional< unsigned > &MaxEVLSafeElements)
Add a VPCurrentIterationPHIRecipe and related recipes to Plan and replaces all uses of the canonical ...
static void optimizeEVLMasks(VPlan &Plan)
Optimize recipes which use an EVL-based header mask to VP intrinsics, for example:
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void convertEVLExitCond(VPlan &Plan)
Replaces the exit condition from (branch-on-cond eq CanonicalIVInc, VectorTripCount) to (branch-on-co...