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
188 if (auto *Rdx = dyn_cast<VPReductionRecipe>(&CurRecipe))
189 if (Rdx->isConditional() &&
190 match(Rdx->getCondOp(), m_RemoveMask(HeaderMask, Mask)))
191 return new VPReductionEVLRecipe(*Rdx, EVL, Mask);
192
193 if (auto *Interleave = dyn_cast<VPInterleaveRecipe>(&CurRecipe))
194 if (Interleave->getMask() &&
195 match(Interleave->getMask(), m_RemoveMask(HeaderMask, Mask)))
196 return new VPInterleaveEVLRecipe(*Interleave, EVL, Mask);
197
198 VPValue *LHS, *RHS;
199 if (match(&CurRecipe, m_SelectLike(m_RemoveMask(HeaderMask, Mask),
201 return new VPWidenIntrinsicRecipe(
202 Intrinsic::vp_merge, {Mask ? Mask : Plan->getTrue(), LHS, RHS, &EVL},
203 LHS->getScalarType(), {}, {}, DL);
204
205 if (match(&CurRecipe, m_LastActiveLane(m_Specific(HeaderMask)))) {
206 Type *Ty = CurRecipe.getVPSingleValue()->getScalarType();
207 VPValue *ZExt = VPBuilder(&CurRecipe).createScalarZExtOrTrunc(&EVL, Ty, DL);
208 return new VPInstruction(
209 Instruction::Sub, {ZExt, Plan->getConstantInt(Ty, 1)},
210 VPIRFlags::getDefaultFlags(Instruction::Sub), {}, DL);
211 }
212
213 // lhs | (headermask && rhs) -> vp.merge rhs, true, lhs, evl
214 if (match(&CurRecipe,
216 m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(RHS)))))
217 return new VPWidenIntrinsicRecipe(Intrinsic::vp_merge,
218 {RHS, Plan->getTrue(), LHS, &EVL},
219 LHS->getScalarType(), {}, {}, DL);
220
221 if (auto *IntrR = dyn_cast<VPWidenIntrinsicRecipe>(&CurRecipe))
222 if (auto VPID = getVPDivRemIntrinsic(IntrR->getVectorIntrinsicID()))
223 if (match(IntrR->getOperand(2), m_RemoveMask(HeaderMask, Mask)))
224 return new VPWidenIntrinsicRecipe(*VPID,
225 {IntrR->getOperand(0),
226 IntrR->getOperand(1),
227 Mask ? Mask : Plan->getTrue(), &EVL},
228 IntrR->getScalarType(), {}, {}, DL);
229
230 return nullptr;
231}
232
233/// Optimize away any EVL-based header masks to VP intrinsic based recipes.
234/// The transforms here need to preserve the original semantics.
236 // Find the EVL-based header mask if it exists: icmp ult step-vector, EVL
237 VPValue *HeaderMask = nullptr, *EVL = nullptr;
240 m_VPValue(EVL))) &&
241 match(EVL, m_EVL(m_VPValue()))) {
242 HeaderMask = R.getVPSingleValue();
243 break;
244 }
245 }
246 if (!HeaderMask)
247 return;
248
250 for (VPUser *U : vputils::collectUsersRecursively(HeaderMask)) {
252 if (auto *NewR = optimizeMaskToEVL(HeaderMask, *R, *EVL)) {
253 NewR->insertBefore(R);
254 for (auto [Old, New] :
255 zip_equal(R->definedValues(), NewR->definedValues()))
256 Old->replaceAllUsesWith(New);
257 OldRecipes.push_back(R);
258 }
259 }
260
261 // Replace remaining (HeaderMask && Mask) with vp.merge (True, Mask,
262 // False, EVL)
263 for (VPUser *U : vputils::collectUsersRecursively(HeaderMask)) {
264 VPValue *Mask;
265 if (match(U, m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(Mask)))) {
266 auto *LogicalAnd = cast<VPInstruction>(U);
267 auto *Merge = new VPWidenIntrinsicRecipe(
268 Intrinsic::vp_merge, {Plan.getTrue(), Mask, Plan.getFalse(), EVL},
269 Mask->getScalarType(), {}, {}, LogicalAnd->getDebugLoc());
270 Merge->insertBefore(LogicalAnd);
271 LogicalAnd->replaceAllUsesWith(Merge);
272 OldRecipes.push_back(LogicalAnd);
273 }
274 }
275
276 // Pull out left splices from any elementwise op.
277 // binop(splice.left(poison, x, evl), live-in)
278 // -> splice.left(poison, binop(x,live-in), evl)
280 Plan,
281 [&EVL](VPValue *&X) {
283 m_Poison(), m_VPValue(X), m_Specific(EVL));
284 },
285 [&Plan, &EVL](auto *X) {
286 return new VPWidenIntrinsicRecipe(
287 Intrinsic::vector_splice_left,
288 {Plan.getPoison(X->getScalarType()), X, EVL}, X->getScalarType(),
289 {}, {}, X->getDebugLoc());
290 });
291
292 // Fold the following splice patterns:
293 // splice.right(splice.left(poison, x, evl), poison, evl) -> x
294 // vector.reverse(splice.left(poison, x, evl)) -> vp.reverse(x, true, evl)
295 // splice.right(vector.reverse(x), poison, evl) -> vp.reverse(x, true, evl)
297 auto *R = cast<VPRecipeBase>(U);
298 // Remove potentially dead left splices from the transform above.
300 R->getVPSingleValue()->getNumUsers() == 0) {
301 OldRecipes.push_back(R);
302 continue;
303 }
304
305 VPValue *X;
308 m_Poison(), m_VPValue(X), m_Specific(EVL)),
309 m_Poison(), m_Specific(EVL)))) {
310 R->getVPSingleValue()->replaceAllUsesWith(X);
311 OldRecipes.push_back(R);
312 continue;
313 }
314
315 if (!match(U,
318 m_Poison(), m_VPValue(X), m_Specific(EVL))),
321 continue;
322
323 auto *VPReverse = new VPWidenIntrinsicRecipe(
324 Intrinsic::experimental_vp_reverse, {X, Plan.getTrue(), EVL},
325 X->getScalarType(), {}, {}, R->getDebugLoc());
326 VPReverse->insertBefore(R);
327 R->getVPSingleValue()->replaceAllUsesWith(VPReverse);
328 OldRecipes.push_back(R);
329 }
330
331 for (VPRecipeBase *R : reverse(OldRecipes)) {
332 SmallVector<VPValue *> PossiblyDead(R->operands());
333 R->eraseFromParent();
334 for (VPValue *Op : PossiblyDead)
336 }
337}
338
339/// After replacing the canonical IV with a EVL-based IV, fixup recipes that use
340/// VF to use the EVL instead to avoid incorrect updates on the penultimate
341/// iteration.
342static void fixupVFUsersForEVL(VPlan &Plan, VPValue &EVL) {
343 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
344 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
345
346 // EVL is i32 but VF/VFxUF are IdxTy. Convert as needed.
347 VPValue *EVLAsIdx =
351
352 assert(all_of(Plan.getVF().users(),
353 [&Plan](VPUser *U) {
354 auto IsAllowedUser =
355 IsaPred<VPVectorEndPointerRecipe, VPScalarIVStepsRecipe,
356 VPWidenIntOrFpInductionRecipe,
357 VPWidenMemIntrinsicRecipe>;
358 if (match(U, m_Trunc(m_Specific(&Plan.getVF()))))
359 return all_of(cast<VPSingleDefRecipe>(U)->users(),
360 IsAllowedUser);
361 return IsAllowedUser(U);
362 }) &&
363 "User of VF that we can't transform to EVL.");
364 Plan.getVF().replaceUsesWithIf(EVLAsIdx, [](VPUser &U, unsigned Idx) {
366 });
367
368 assert(all_of(Plan.getVFxUF().users(),
370 m_c_Add(m_Specific(LoopRegion->getCanonicalIV()),
371 m_Specific(&Plan.getVFxUF())),
373 "Only users of VFxUF should be VPWidenPointerInductionRecipe and the "
374 "increment of the canonical induction.");
375 Plan.getVFxUF().replaceUsesWithIf(EVLAsIdx, [](VPUser &U, unsigned Idx) {
376 // Only replace uses in VPWidenPointerInductionRecipe; The increment of the
377 // canonical induction must not be updated.
379 });
380
381 // Create a scalar phi to track the previous EVL if fixed-order recurrence is
382 // contained.
383 bool ContainsFORs =
385 if (ContainsFORs) {
386 // TODO: Use VPInstruction::ExplicitVectorLength to get maximum EVL.
387 VPValue *MaxEVL = &Plan.getVF();
388 // Emit VPScalarCastRecipe in preheader if VF is not a 32 bits integer.
389 VPBuilder Builder(LoopRegion->getPreheaderVPBB());
390 MaxEVL = Builder.createScalarZExtOrTrunc(
392
393 Builder.setInsertPoint(Header, Header->getFirstNonPhi());
394 VPValue *PrevEVL = Builder.createScalarPhi(
395 {MaxEVL, &EVL}, DebugLoc::getUnknown(), "prev.evl");
396
399 for (VPRecipeBase &R : *VPBB) {
400 VPValue *V1, *V2;
401 if (!match(&R,
403 m_VPValue(V1), m_VPValue(V2))))
404 continue;
405 VPValue *Imm = Plan.getOrAddLiveIn(
408 Intrinsic::experimental_vp_splice,
409 {V1, V2, Imm, Plan.getTrue(), PrevEVL, &EVL},
410 R.getVPSingleValue()->getScalarType(), {}, {}, R.getDebugLoc());
411 VPSplice->insertBefore(&R);
412 R.getVPSingleValue()->replaceAllUsesWith(VPSplice);
413 }
414 }
415 }
416
417 VPValue *HeaderMask = LoopRegion->getHeaderMask();
418 if (!HeaderMask)
419 return;
420
421 // Ensure that any reduction that uses a select to mask off tail lanes does so
422 // in the vector loop, not the middle block, since EVL tail folding can have
423 // tail elements in the penultimate iteration.
424 assert(all_of(*Plan.getMiddleBlock(), [&Plan, HeaderMask](VPRecipeBase &R) {
425 if (match(&R, m_ComputeReductionResult(m_Select(m_Specific(HeaderMask),
426 m_VPValue(), m_VPValue()))))
427 return R.getOperand(0)->getDefiningRecipe()->getRegion() ==
428 Plan.getVectorLoopRegion();
429 return true;
430 }));
431
432 // Replace the abstract header mask with a mask equivalent to predicating by
433 // EVL: icmp ult step-vector, EVL
434 VPRecipeBase *EVLR = EVL.getDefiningRecipe();
435 VPBuilder Builder(EVLR->getParent(), std::next(EVLR->getIterator()));
436 Type *EVLType = EVL.getScalarType();
437 VPValue *EVLMask = Builder.createICmp(
439 Builder.createNaryOp(VPInstruction::StepVector, {}, EVLType), &EVL);
440 HeaderMask->replaceAllUsesWith(EVLMask);
441}
442
443/// Converts a tail folded vector loop region to step by
444/// VPInstruction::ExplicitVectorLength elements instead of VF elements each
445/// iteration.
446///
447/// - Add a VPCurrentIterationPHIRecipe and related recipes to \p Plan and
448/// replaces all uses of the canonical IV except for the canonical IV
449/// increment with a VPCurrentIterationPHIRecipe. The canonical IV is used
450/// only for loop iterations counting after this transformation.
451///
452/// - The header mask is replaced with a header mask based on the EVL.
453///
454/// - Plans with FORs have a new phi added to keep track of the EVL of the
455/// previous iteration, and VPFirstOrderRecurrencePHIRecipes are replaced with
456/// @llvm.vp.splice.
457///
458/// The function uses the following definitions:
459/// %StartV is the canonical induction start value.
460///
461/// The function adds the following recipes:
462///
463/// vector.ph:
464/// ...
465///
466/// vector.body:
467/// ...
468/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
469/// [ %NextIter, %vector.body ]
470/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
471/// %VPEVL = EXPLICIT-VECTOR-LENGTH %AVL
472/// ...
473/// %OpEVL = cast i32 %VPEVL to IVSize
474/// %NextIter = add IVSize %OpEVL, %CurrentIter
475/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
476/// ...
477///
478/// If MaxSafeElements is provided, the function adds the following recipes:
479/// vector.ph:
480/// ...
481///
482/// vector.body:
483/// ...
484/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
485/// [ %NextIter, %vector.body ]
486/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
487/// %cmp = cmp ult %AVL, MaxSafeElements
488/// %SAFE_AVL = select %cmp, %AVL, MaxSafeElements
489/// %VPEVL = EXPLICIT-VECTOR-LENGTH %SAFE_AVL
490/// ...
491/// %OpEVL = cast i32 %VPEVL to IVSize
492/// %NextIter = add IVSize %OpEVL, %CurrentIter
493/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
494/// ...
495///
497 VPlan &Plan, const std::optional<unsigned> &MaxSafeElements) {
498 if (Plan.hasScalarVFOnly())
499 return;
500 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
501 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
502
503 auto *CanonicalIV = LoopRegion->getCanonicalIV();
504 auto *CanIVTy = LoopRegion->getCanonicalIVType();
505 VPValue *StartV = Plan.getZero(CanIVTy);
506 auto *CanonicalIVIncrement = LoopRegion->getOrCreateCanonicalIVIncrement();
507
508 // Create the CurrentIteration recipe in the vector loop.
509 auto *CurrentIteration =
511 CurrentIteration->insertBefore(*Header, Header->begin());
512 VPBuilder Builder(Header, Header->getFirstNonPhi());
513 // Create the AVL (application vector length), starting from TC -> 0 in steps
514 // of EVL.
515 VPPhi *AVLPhi = Builder.createScalarPhi(
517 VPValue *AVL = AVLPhi;
518
519 if (MaxSafeElements) {
520 // Support for MaxSafeDist for correct loop emission.
521 VPValue *AVLSafe = Plan.getConstantInt(CanIVTy, *MaxSafeElements);
522 VPValue *Cmp = Builder.createICmp(ICmpInst::ICMP_ULT, AVL, AVLSafe);
523 AVL = Builder.createSelect(Cmp, AVL, AVLSafe, DebugLoc::getUnknown(),
524 "safe_avl");
525 }
526 auto *VPEVL = Builder.createNaryOp(VPInstruction::ExplicitVectorLength, AVL,
527 DebugLoc::getUnknown(), "evl");
528
529 Builder.setInsertPoint(CanonicalIVIncrement);
530 VPValue *OpVPEVL = VPEVL;
531
532 OpVPEVL = Builder.createScalarZExtOrTrunc(
533 OpVPEVL, CanIVTy, CanonicalIVIncrement->getDebugLoc());
534
535 auto *NextIter = Builder.createAdd(
536 OpVPEVL, CurrentIteration, CanonicalIVIncrement->getDebugLoc(),
537 "current.iteration.next", CanonicalIVIncrement->getNoWrapFlags());
538 CurrentIteration->addBackedgeValue(NextIter);
539
540 VPValue *NextAVL =
541 Builder.createSub(AVLPhi, OpVPEVL, DebugLoc::getCompilerGenerated(),
542 "avl.next", {/*NUW=*/true, /*NSW=*/false});
543 AVLPhi->addIncoming(NextAVL);
544
545 fixupVFUsersForEVL(Plan, *VPEVL);
546 removeDeadRecipes(Plan);
547
548 // Replace all uses of the canonical IV with VPCurrentIterationPHIRecipe
549 // except for the canonical IV increment.
550 CanonicalIV->replaceUsesWithIf(CurrentIteration,
551 [CanonicalIVIncrement](VPUser &U, unsigned) {
552 return &U != CanonicalIVIncrement;
553 });
554 // TODO: support unroll factor > 1.
555 Plan.setUF(1);
556}
557
559 // Find the vector loop entry by locating VPCurrentIterationPHIRecipe.
560 // There should be only one VPCurrentIteration in the entire plan.
561 VPCurrentIterationPHIRecipe *CurrentIteration = nullptr;
562
565 for (VPRecipeBase &R : VPBB->phis())
566 if (auto *PhiR = dyn_cast<VPCurrentIterationPHIRecipe>(&R)) {
567 assert(!CurrentIteration &&
568 "Found multiple CurrentIteration. Only one expected");
569 CurrentIteration = PhiR;
570 }
571
572 // Early return if it is not variable-length stepping.
573 if (!CurrentIteration)
574 return;
575
576 VPBasicBlock *HeaderVPBB = CurrentIteration->getParent();
577 VPValue *CurrentIterationIncr = CurrentIteration->getBackedgeValue();
578
579 // Convert CurrentIteration to concrete recipe.
580 auto *ScalarR =
581 VPBuilder(CurrentIteration)
583 {CurrentIteration->getStartValue(), CurrentIterationIncr},
584 CurrentIteration->getDebugLoc(), "current.iteration.iv");
585 CurrentIteration->replaceAllUsesWith(ScalarR);
586 CurrentIteration->eraseFromParent();
587
588 // Replace CanonicalIVInc with CurrentIteration increment if it exists.
589 auto *CanonicalIV = cast<VPPhi>(&*HeaderVPBB->begin());
590 if (auto *CanIVInc = findUserOf(
591 CanonicalIV, m_c_Add(m_VPValue(), m_Specific(&Plan.getVFxUF())))) {
592 cast<VPInstruction>(CanIVInc)->replaceAllUsesWith(CurrentIterationIncr);
593 CanIVInc->eraseFromParent();
594 }
595}
596
598 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
599 if (!LoopRegion)
600 return;
601 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
602 if (Header->empty())
603 return;
604 // The EVL IV is always at the beginning.
605 auto *EVLPhi = dyn_cast<VPCurrentIterationPHIRecipe>(&Header->front());
606 if (!EVLPhi)
607 return;
608
609 // Bail if not an EVL tail folded loop.
610 VPValue *AVL;
611 if (!match(EVLPhi->getBackedgeValue(),
613 return;
614
615 // The AVL may be capped to a safe distance.
616 VPValue *SafeAVL, *UnsafeAVL;
617 if (match(AVL,
619 m_VPValue(SafeAVL)),
620 m_Deferred(UnsafeAVL), m_Deferred(SafeAVL))))
621 AVL = UnsafeAVL;
622
623 VPValue *AVLNext;
624 [[maybe_unused]] bool FoundAVLNext =
626 m_Specific(Plan.getTripCount()), m_VPValue(AVLNext)));
627 assert(FoundAVLNext && "Didn't find AVL backedge?");
628
629 VPBasicBlock *Latch = LoopRegion->getExitingBasicBlock();
630 auto *LatchBr = cast<VPInstruction>(Latch->getTerminator());
631 if (match(LatchBr, m_BranchOnCond(m_True())))
632 return;
633
634 VPValue *CanIVInc;
635 [[maybe_unused]] bool FoundIncrement = match(
636 LatchBr,
638 m_Specific(&Plan.getVectorTripCount()))));
639 assert(FoundIncrement &&
640 match(CanIVInc, m_Add(m_Specific(LoopRegion->getCanonicalIV()),
641 m_Specific(&Plan.getVFxUF()))) &&
642 "Expected BranchOnCond with ICmp comparing CanIV + VFxUF with vector "
643 "trip count");
644
645 Type *AVLTy = AVLNext->getScalarType();
646 VPBuilder Builder(LatchBr);
647 LatchBr->setOperand(
648 0, Builder.createICmp(CmpInst::ICMP_EQ, AVLNext, Plan.getZero(AVLTy)));
649}
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:4380
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4415
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:4073
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:2484
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2473
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:3173
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1667
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:3343
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4605
const VPBlockBase * getEntry() const
Definition VPlan.h:4649
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:4733
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4725
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4674
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4738
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:1927
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4792
const DataLayout & getDataLayout() const
Definition VPlan.h:4999
LLVMContext & getContext() const
Definition VPlan.h:4995
VPBasicBlock * getEntry()
Definition VPlan.h:4888
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4953
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5090
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:4993
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5118
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4983
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:5067
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5093
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:4923
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5087
bool hasScalarVFOnly() const
Definition VPlan.h:5035
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4986
void setUF(unsigned UF)
Definition VPlan.h:5050
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:5101
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:3849
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:3952
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...