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 VPValue *Stride;
159 m_VPValue(Addr), m_VPValue(Stride),
160 m_RemoveMask(HeaderMask, Mask),
161 m_TruncOrSelf(m_Specific(&Plan->getVF()))))) {
162 if (!Mask)
163 Mask = Plan->getTrue();
164 auto *NewLoad = cast<VPWidenMemIntrinsicRecipe>(&CurRecipe)->clone();
165 NewLoad->setOperand(2, Mask);
166 NewLoad->setOperand(3, &EVL);
167 return NewLoad;
168 }
169
170 VPValue *StoredVal;
171 if (match(&CurRecipe, m_MaskedStore(m_VPValue(Addr), m_VPValue(StoredVal),
172 m_RemoveMask(HeaderMask, Mask))))
173 return new VPWidenStoreEVLRecipe(cast<VPWidenStoreRecipe>(CurRecipe), Addr,
174 StoredVal, EVL, Mask);
175
176 if (match(&CurRecipe,
177 m_MaskedStore(m_VPValue(EndPtr), m_VPValue(StoredVal),
178 m_Reverse(m_RemoveMask(HeaderMask, Mask)))) &&
179 match(EndPtr, m_VecEndPtr(m_VPValue(), m_Specific(&Plan->getVF())))) {
180 Mask = GetVPReverse(Mask);
181 Addr = AdjustEndPtr(EndPtr);
182 VPValue *Poison = Plan->getPoison(StoredVal->getScalarType());
183 auto *SpliceR = new VPWidenIntrinsicRecipe(
184 Intrinsic::vector_splice_right, {StoredVal, Poison, &EVL},
185 StoredVal->getScalarType(), {}, {}, DL);
186 SpliceR->insertBefore(&CurRecipe);
187 return new VPWidenStoreEVLRecipe(cast<VPWidenStoreRecipe>(CurRecipe), Addr,
188 SpliceR, EVL, Mask);
189 }
190
191 if (auto *Rdx = dyn_cast<VPReductionRecipe>(&CurRecipe))
192 if (Rdx->isConditional() &&
193 match(Rdx->getCondOp(), m_RemoveMask(HeaderMask, Mask)))
194 return new VPReductionEVLRecipe(*Rdx, EVL, Mask);
195
196 if (auto *Interleave = dyn_cast<VPInterleaveRecipe>(&CurRecipe))
197 if (Interleave->getMask() &&
198 match(Interleave->getMask(), m_RemoveMask(HeaderMask, Mask)))
199 return new VPInterleaveEVLRecipe(*Interleave, EVL, Mask);
200
201 VPValue *LHS, *RHS;
202 if (match(&CurRecipe, m_SelectLike(m_RemoveMask(HeaderMask, Mask),
204 return new VPWidenIntrinsicRecipe(
205 Intrinsic::vp_merge, {Mask ? Mask : Plan->getTrue(), LHS, RHS, &EVL},
206 LHS->getScalarType(), {}, {}, DL);
207
208 if (match(&CurRecipe, m_LastActiveLane(m_Specific(HeaderMask)))) {
209 Type *Ty = CurRecipe.getVPSingleValue()->getScalarType();
210 VPValue *ZExt = VPBuilder(&CurRecipe).createScalarZExtOrTrunc(&EVL, Ty, DL);
211 return new VPInstruction(
212 Instruction::Sub, {ZExt, Plan->getConstantInt(Ty, 1)},
213 VPIRFlags::getDefaultFlags(Instruction::Sub), {}, DL);
214 }
215
216 // lhs | (headermask && rhs) -> vp.merge rhs, true, lhs, evl
217 if (match(&CurRecipe,
219 m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(RHS)))))
220 return new VPWidenIntrinsicRecipe(Intrinsic::vp_merge,
221 {RHS, Plan->getTrue(), LHS, &EVL},
222 LHS->getScalarType(), {}, {}, DL);
223
224 if (auto *IntrR = dyn_cast<VPWidenIntrinsicRecipe>(&CurRecipe))
225 if (auto VPID = getVPDivRemIntrinsic(IntrR->getVectorIntrinsicID()))
226 if (match(IntrR->getOperand(2), m_RemoveMask(HeaderMask, Mask)))
227 return new VPWidenIntrinsicRecipe(*VPID,
228 {IntrR->getOperand(0),
229 IntrR->getOperand(1),
230 Mask ? Mask : Plan->getTrue(), &EVL},
231 IntrR->getScalarType(), {}, {}, DL);
232
233 return nullptr;
234}
235
236/// Optimize away any EVL-based header masks to VP intrinsic based recipes.
237/// The transforms here need to preserve the original semantics.
239 // Find the EVL-based header mask if it exists: icmp ult step-vector, EVL
240 VPValue *HeaderMask = nullptr, *EVL = nullptr;
243 m_VPValue(EVL))) &&
244 match(EVL, m_EVL(m_VPValue()))) {
245 HeaderMask = R.getVPSingleValue();
246 break;
247 }
248 }
249 if (!HeaderMask)
250 return;
251
253 for (VPUser *U : vputils::collectUsersRecursively(HeaderMask)) {
255 if (auto *NewR = optimizeMaskToEVL(HeaderMask, *R, *EVL)) {
256 NewR->insertBefore(R);
257 for (auto [Old, New] :
258 zip_equal(R->definedValues(), NewR->definedValues()))
259 Old->replaceAllUsesWith(New);
260 OldRecipes.push_back(R);
261 }
262 }
263
264 // Replace remaining (HeaderMask && Mask) with vp.merge (True, Mask,
265 // False, EVL)
266 for (VPUser *U : vputils::collectUsersRecursively(HeaderMask)) {
267 VPValue *Mask;
268 if (match(U, m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(Mask)))) {
269 auto *LogicalAnd = cast<VPInstruction>(U);
270 auto *Merge = new VPWidenIntrinsicRecipe(
271 Intrinsic::vp_merge, {Plan.getTrue(), Mask, Plan.getFalse(), EVL},
272 Mask->getScalarType(), {}, {}, LogicalAnd->getDebugLoc());
273 Merge->insertBefore(LogicalAnd);
274 LogicalAnd->replaceAllUsesWith(Merge);
275 OldRecipes.push_back(LogicalAnd);
276 }
277 }
278
279 // Pull out left splices from any elementwise op.
280 // binop(splice.left(poison, x, evl), live-in)
281 // -> splice.left(poison, binop(x,live-in), evl)
283 Plan,
284 [&EVL](VPValue *&X) {
286 m_Poison(), m_VPValue(X), m_Specific(EVL));
287 },
288 [&Plan, &EVL](auto *X) {
289 return new VPWidenIntrinsicRecipe(
290 Intrinsic::vector_splice_left,
291 {Plan.getPoison(X->getScalarType()), X, EVL}, X->getScalarType(),
292 {}, {}, X->getDebugLoc());
293 });
294
295 // Fold the following splice patterns:
296 // splice.right(splice.left(poison, x, evl), poison, evl) -> x
297 // vector.reverse(splice.left(poison, x, evl)) -> vp.reverse(x, true, evl)
298 // splice.right(vector.reverse(x), poison, evl) -> vp.reverse(x, true, evl)
300 auto *R = cast<VPRecipeBase>(U);
301 // Remove potentially dead left splices from the transform above.
303 R->getVPSingleValue()->getNumUsers() == 0) {
304 OldRecipes.push_back(R);
305 continue;
306 }
307
308 VPValue *X;
311 m_Poison(), m_VPValue(X), m_Specific(EVL)),
312 m_Poison(), m_Specific(EVL)))) {
313 R->getVPSingleValue()->replaceAllUsesWith(X);
314 OldRecipes.push_back(R);
315 continue;
316 }
317
318 if (!match(U,
321 m_Poison(), m_VPValue(X), m_Specific(EVL))),
324 continue;
325
326 auto *VPReverse = new VPWidenIntrinsicRecipe(
327 Intrinsic::experimental_vp_reverse, {X, Plan.getTrue(), EVL},
328 X->getScalarType(), {}, {}, R->getDebugLoc());
329 VPReverse->insertBefore(R);
330 R->getVPSingleValue()->replaceAllUsesWith(VPReverse);
331 OldRecipes.push_back(R);
332 }
333
334 for (VPRecipeBase *R : reverse(OldRecipes)) {
335 SmallVector<VPValue *> PossiblyDead(R->operands());
336 R->eraseFromParent();
337 for (VPValue *Op : PossiblyDead)
339 }
340}
341
342/// After replacing the canonical IV with a EVL-based IV, fixup recipes that use
343/// VF to use the EVL instead to avoid incorrect updates on the penultimate
344/// iteration.
345static void fixupVFUsersForEVL(VPlan &Plan, VPValue &EVL) {
346 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
347 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
348
349 // EVL is i32 but VF/VFxUF are IdxTy. Convert as needed.
350 VPValue *EVLAsIdx =
354
355 assert(all_of(Plan.getVF().users(),
356 [&Plan](VPUser *U) {
357 auto IsAllowedUser =
358 IsaPred<VPVectorEndPointerRecipe, VPScalarIVStepsRecipe,
359 VPWidenIntOrFpInductionRecipe,
360 VPWidenMemIntrinsicRecipe>;
361 if (match(U, m_Trunc(m_Specific(&Plan.getVF()))))
362 return all_of(cast<VPSingleDefRecipe>(U)->users(),
363 IsAllowedUser);
364 return IsAllowedUser(U);
365 }) &&
366 "User of VF that we can't transform to EVL.");
367 Plan.getVF().replaceUsesWithIf(EVLAsIdx, [](VPUser &U, unsigned Idx) {
369 });
370
371 assert(all_of(Plan.getVFxUF().users(),
373 m_c_Add(m_Specific(LoopRegion->getCanonicalIV()),
374 m_Specific(&Plan.getVFxUF())),
376 "Only users of VFxUF should be VPWidenPointerInductionRecipe and the "
377 "increment of the canonical induction.");
378 Plan.getVFxUF().replaceUsesWithIf(EVLAsIdx, [](VPUser &U, unsigned Idx) {
379 // Only replace uses in VPWidenPointerInductionRecipe; The increment of the
380 // canonical induction must not be updated.
382 });
383
384 // Create a scalar phi to track the previous EVL if fixed-order recurrence is
385 // contained.
386 bool ContainsFORs =
388 if (ContainsFORs) {
389 // TODO: Use VPInstruction::ExplicitVectorLength to get maximum EVL.
390 VPValue *MaxEVL = &Plan.getVF();
391 // Emit VPScalarCastRecipe in preheader if VF is not a 32 bits integer.
392 VPBuilder Builder(LoopRegion->getPreheaderVPBB());
393 MaxEVL = Builder.createScalarZExtOrTrunc(
395
396 Builder.setInsertPoint(Header, Header->getFirstNonPhi());
397 VPValue *PrevEVL = Builder.createScalarPhi(
398 {MaxEVL, &EVL}, DebugLoc::getUnknown(), "prev.evl");
399
402 for (VPRecipeBase &R : *VPBB) {
403 VPValue *V1, *V2;
404 if (!match(&R,
406 m_VPValue(V1), m_VPValue(V2))))
407 continue;
408 VPValue *Imm = Plan.getOrAddLiveIn(
411 Intrinsic::experimental_vp_splice,
412 {V1, V2, Imm, Plan.getTrue(), PrevEVL, &EVL},
413 R.getVPSingleValue()->getScalarType(), {}, {}, R.getDebugLoc());
414 VPSplice->insertBefore(&R);
415 R.getVPSingleValue()->replaceAllUsesWith(VPSplice);
416 }
417 }
418 }
419
420 VPValue *HeaderMask = LoopRegion->getHeaderMask();
421 if (!HeaderMask)
422 return;
423
424 // Ensure that any reduction that uses a select to mask off tail lanes does so
425 // in the vector loop, not the middle block, since EVL tail folding can have
426 // tail elements in the penultimate iteration.
427 assert(all_of(*Plan.getMiddleBlock(), [&Plan, HeaderMask](VPRecipeBase &R) {
428 if (match(&R, m_ComputeReductionResult(m_Select(m_Specific(HeaderMask),
429 m_VPValue(), m_VPValue()))))
430 return R.getOperand(0)->getDefiningRecipe()->getRegion() ==
431 Plan.getVectorLoopRegion();
432 return true;
433 }));
434
435 // Replace the abstract header mask with a mask equivalent to predicating by
436 // EVL: icmp ult step-vector, EVL
437 VPRecipeBase *EVLR = EVL.getDefiningRecipe();
438 VPBuilder Builder(EVLR->getParent(), std::next(EVLR->getIterator()));
439 Type *EVLType = EVL.getScalarType();
440 VPValue *EVLMask = Builder.createICmp(
442 Builder.createNaryOp(VPInstruction::StepVector, {}, EVLType), &EVL);
443 HeaderMask->replaceAllUsesWith(EVLMask);
444}
445
446/// Converts a tail folded vector loop region to step by
447/// VPInstruction::ExplicitVectorLength elements instead of VF elements each
448/// iteration.
449///
450/// - Add a VPCurrentIterationPHIRecipe and related recipes to \p Plan and
451/// replaces all uses of the canonical IV except for the canonical IV
452/// increment with a VPCurrentIterationPHIRecipe. The canonical IV is used
453/// only for loop iterations counting after this transformation.
454///
455/// - The header mask is replaced with a header mask based on the EVL.
456///
457/// - Plans with FORs have a new phi added to keep track of the EVL of the
458/// previous iteration, and VPFirstOrderRecurrencePHIRecipes are replaced with
459/// @llvm.vp.splice.
460///
461/// The function uses the following definitions:
462/// %StartV is the canonical induction start value.
463///
464/// The function adds the following recipes:
465///
466/// vector.ph:
467/// ...
468///
469/// vector.body:
470/// ...
471/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
472/// [ %NextIter, %vector.body ]
473/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
474/// %VPEVL = EXPLICIT-VECTOR-LENGTH %AVL
475/// ...
476/// %OpEVL = cast i32 %VPEVL to IVSize
477/// %NextIter = add IVSize %OpEVL, %CurrentIter
478/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
479/// ...
480///
481/// If MaxSafeElements is provided, the function adds the following recipes:
482/// vector.ph:
483/// ...
484///
485/// vector.body:
486/// ...
487/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
488/// [ %NextIter, %vector.body ]
489/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
490/// %cmp = cmp ult %AVL, MaxSafeElements
491/// %SAFE_AVL = select %cmp, %AVL, MaxSafeElements
492/// %VPEVL = EXPLICIT-VECTOR-LENGTH %SAFE_AVL
493/// ...
494/// %OpEVL = cast i32 %VPEVL to IVSize
495/// %NextIter = add IVSize %OpEVL, %CurrentIter
496/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
497/// ...
498///
500 VPlan &Plan, const std::optional<unsigned> &MaxSafeElements) {
501 if (Plan.hasScalarVFOnly())
502 return;
503 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
504 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
505
506 auto *CanonicalIV = LoopRegion->getCanonicalIV();
507 auto *CanIVTy = LoopRegion->getCanonicalIVType();
508 VPValue *StartV = Plan.getZero(CanIVTy);
509 auto *CanonicalIVIncrement = LoopRegion->getOrCreateCanonicalIVIncrement();
510
511 // Create the CurrentIteration recipe in the vector loop.
512 auto *CurrentIteration =
514 CurrentIteration->insertBefore(*Header, Header->begin());
515 VPBuilder Builder(Header, Header->getFirstNonPhi());
516 // Create the AVL (application vector length), starting from TC -> 0 in steps
517 // of EVL.
518 VPPhi *AVLPhi = Builder.createScalarPhi(
520 VPValue *AVL = AVLPhi;
521
522 if (MaxSafeElements) {
523 // Support for MaxSafeDist for correct loop emission.
524 VPValue *AVLSafe = Plan.getConstantInt(CanIVTy, *MaxSafeElements);
525 VPValue *Cmp = Builder.createICmp(ICmpInst::ICMP_ULT, AVL, AVLSafe);
526 AVL = Builder.createSelect(Cmp, AVL, AVLSafe, DebugLoc::getUnknown(),
527 "safe_avl");
528 }
529 auto *VPEVL = Builder.createNaryOp(VPInstruction::ExplicitVectorLength, AVL,
530 DebugLoc::getUnknown(), "evl");
531
532 Builder.setInsertPoint(CanonicalIVIncrement);
533 VPValue *OpVPEVL = VPEVL;
534
535 OpVPEVL = Builder.createScalarZExtOrTrunc(
536 OpVPEVL, CanIVTy, CanonicalIVIncrement->getDebugLoc());
537
538 auto *NextIter = Builder.createAdd(
539 OpVPEVL, CurrentIteration, CanonicalIVIncrement->getDebugLoc(),
540 "current.iteration.next", CanonicalIVIncrement->getNoWrapFlags());
541 CurrentIteration->addBackedgeValue(NextIter);
542
543 VPValue *NextAVL =
544 Builder.createSub(AVLPhi, OpVPEVL, DebugLoc::getCompilerGenerated(),
545 "avl.next", {/*NUW=*/true, /*NSW=*/false});
546 AVLPhi->addIncoming(NextAVL);
547
548 fixupVFUsersForEVL(Plan, *VPEVL);
549 removeDeadRecipes(Plan);
550
551 // Replace all uses of the canonical IV with VPCurrentIterationPHIRecipe
552 // except for the canonical IV increment.
553 CanonicalIV->replaceUsesWithIf(CurrentIteration,
554 [CanonicalIVIncrement](VPUser &U, unsigned) {
555 return &U != CanonicalIVIncrement;
556 });
557 // TODO: support unroll factor > 1.
558 Plan.setUF(1);
559}
560
562 // Find the vector loop entry by locating VPCurrentIterationPHIRecipe.
563 // There should be only one VPCurrentIteration in the entire plan.
564 VPCurrentIterationPHIRecipe *CurrentIteration = nullptr;
565
568 for (VPRecipeBase &R : VPBB->phis())
569 if (auto *PhiR = dyn_cast<VPCurrentIterationPHIRecipe>(&R)) {
570 assert(!CurrentIteration &&
571 "Found multiple CurrentIteration. Only one expected");
572 CurrentIteration = PhiR;
573 }
574
575 // Early return if it is not variable-length stepping.
576 if (!CurrentIteration)
577 return;
578
579 VPBasicBlock *HeaderVPBB = CurrentIteration->getParent();
580 VPValue *CurrentIterationIncr = CurrentIteration->getBackedgeValue();
581
582 // Convert CurrentIteration to concrete recipe.
583 auto *ScalarR =
584 VPBuilder(CurrentIteration)
586 {CurrentIteration->getStartValue(), CurrentIterationIncr},
587 CurrentIteration->getDebugLoc(), "current.iteration.iv");
588 CurrentIteration->replaceAllUsesWith(ScalarR);
589 CurrentIteration->eraseFromParent();
590
591 // Replace CanonicalIVInc with CurrentIteration increment if it exists.
592 auto *CanonicalIV = cast<VPPhi>(&*HeaderVPBB->begin());
593 if (auto *CanIVInc = findUserOf(
594 CanonicalIV, m_c_Add(m_VPValue(), m_Specific(&Plan.getVFxUF())))) {
595 cast<VPInstruction>(CanIVInc)->replaceAllUsesWith(CurrentIterationIncr);
596 CanIVInc->eraseFromParent();
597 }
598}
599
601 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
602 if (!LoopRegion)
603 return;
604 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
605 if (Header->empty())
606 return;
607 // The EVL IV is always at the beginning.
608 auto *EVLPhi = dyn_cast<VPCurrentIterationPHIRecipe>(&Header->front());
609 if (!EVLPhi)
610 return;
611
612 // Bail if not an EVL tail folded loop.
613 VPValue *AVL;
614 if (!match(EVLPhi->getBackedgeValue(),
616 return;
617
618 // The AVL may be capped to a safe distance.
619 VPValue *SafeAVL, *UnsafeAVL;
620 if (match(AVL,
622 m_VPValue(SafeAVL)),
623 m_Deferred(UnsafeAVL), m_Deferred(SafeAVL))))
624 AVL = UnsafeAVL;
625
626 VPValue *AVLNext;
627 [[maybe_unused]] bool FoundAVLNext =
629 m_Specific(Plan.getTripCount()), m_VPValue(AVLNext)));
630 assert(FoundAVLNext && "Didn't find AVL backedge?");
631
632 VPBasicBlock *Latch = LoopRegion->getExitingBasicBlock();
633 auto *LatchBr = cast<VPInstruction>(Latch->getTerminator());
634 if (match(LatchBr, m_BranchOnCond(m_True())))
635 return;
636
637 VPValue *CanIVInc;
638 [[maybe_unused]] bool FoundIncrement = match(
639 LatchBr,
641 m_Specific(&Plan.getVectorTripCount()))));
642 assert(FoundIncrement &&
643 match(CanIVInc, m_Add(m_Specific(LoopRegion->getCanonicalIV()),
644 m_Specific(&Plan.getVFxUF()))) &&
645 "Expected BranchOnCond with ICmp comparing CanIV + VFxUF with vector "
646 "trip count");
647
648 Type *AVLTy = AVLNext->getScalarType();
649 VPBuilder Builder(LatchBr);
650 LatchBr->setOperand(
651 0, Builder.createICmp(CmpInst::ICMP_EQ, AVLNext, Plan.getZero(AVLTy)));
652}
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.
LLVM_ABI 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:4365
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4400
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:643
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:379
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:360
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:4059
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:2474
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2463
static VPIRFlags getDefaultFlags(unsigned Opcode)
Returns default flags for Opcode for opcodes that support it, asserts otherwise.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1224
A recipe for interleaved memory operations with vector-predication intrinsics.
Definition VPlan.h:3159
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1657
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:402
VPBasicBlock * getParent()
Definition VPlan.h:474
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:552
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:3329
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4590
const VPBlockBase * getEntry() const
Definition VPlan.h:4634
VPInstruction * getOrCreateCanonicalIVIncrement()
Get the canonical IV increment instruction if it exists.
Definition VPlan.cpp:868
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4710
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4702
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4659
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4715
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:1473
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:1479
user_range users()
Definition VPlanValue.h:157
A recipe for widening vector intrinsics.
Definition VPlan.h:1917
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4769
const DataLayout & getDataLayout() const
Definition VPlan.h:4976
LLVMContext & getContext() const
Definition VPlan.h:4972
VPBasicBlock * getEntry()
Definition VPlan.h:4865
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4930
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5067
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:4970
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5095
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4960
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:5044
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5070
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1065
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4900
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5064
bool hasScalarVFOnly() const
Definition VPlan.h:5012
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4963
void setUF(unsigned UF)
Definition VPlan.h:5027
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:5078
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:212
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:3835
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:3938
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...