LLVM 24.0.0git
VPlanTransforms.cpp
Go to the documentation of this file.
1//===-- VPlanTransforms.cpp - Utility VPlan to VPlan 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 a set of utility VPlan to VPlan transformations.
11///
12//===----------------------------------------------------------------------===//
13
14#include "VPlanTransforms.h"
15#include "VPRecipeBuilder.h"
16#include "VPlan.h"
17#include "VPlanAnalysis.h"
18#include "VPlanCFG.h"
19#include "VPlanDominatorTree.h"
20#include "VPlanHelpers.h"
21#include "VPlanPatternMatch.h"
22#include "VPlanUtils.h"
23#include "VectorizeOptions.h"
24#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/TypeSwitch.h"
31#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Intrinsics.h"
38#include "llvm/IR/MDBuilder.h"
39#include "llvm/IR/Metadata.h"
42#include "llvm/Support/Regex.h"
45
46using namespace llvm;
47using namespace LoopVectorizationUtils;
48using namespace VPlanPatternMatch;
49using namespace SCEVPatternMatch;
50
52 const VectorizeOptions &Opts = getVectorizeOptions(Plan.getContext());
53 if (Opts.vplan_verify_each && !verifyVPlanIsValid(Plan))
54 report_fatal_error("Broken VPlan found, compilation aborted!");
55}
56
57#ifndef NDEBUG
59 const VectorizeOptions &Opts = getVectorizeOptions(Plan.getContext());
60 return Opts.vplan_print_before_all || Opts.vplan_print_after_all ||
61 !Opts.vplan_print_before.empty() || !Opts.vplan_print_after.empty();
62}
63
65 StringRef NumberedPassName, bool After) {
66 const VectorizeOptions &Opts = getVectorizeOptions(Plan.getContext());
67 bool All = After ? Opts.vplan_print_after_all : Opts.vplan_print_before_all;
69 After ? Opts.vplan_print_after : Opts.vplan_print_before;
70 if (!All && none_of(Passes, [&](StringRef Entry) {
71 return Regex(Entry).match(NumberedPassName);
72 }))
73 return;
74 dbgs() << "VPlan for loop in '" << Fn->getName() << "' "
75 << (After ? "after" : "before") << " " << NumberedPassName << '\n';
76 if (Opts.vplan_print_vector_region_scope && Plan.getVectorLoopRegion())
78 else
79 dbgs() << Plan << '\n';
80}
81#endif
82
83/// Returns the metadata attached to \p R, or an empty set for a recipe that
84/// does not carry any.
86 if (auto *MD = dyn_cast<VPIRMetadata>(R))
87 return *MD;
88 return {};
89}
90
93 Loop *OuterLoop) {
94
95 // Returns true if the access of \p AccessTy at \p Addr can be widened to a
96 // consecutive vector access.
97 auto IsConsecutiveAccess = [&](VPValue *Addr, Type *AccessTy) {
98 return vputils::getConstantStride(Addr, AccessTy, PSE, OuterLoop) == 1;
99 };
100
102 Plan.getVectorLoopRegion());
104 // Skip blocks outside region
105 if (!VPBB->getParent())
106 break;
107 VPRecipeBase *Term = VPBB->getTerminator();
108 auto EndIter = Term ? Term->getIterator() : VPBB->end();
109 // Introduce each ingredient into VPlan.
110 for (VPRecipeBase &Ingredient :
111 make_early_inc_range(make_range(VPBB->begin(), EndIter))) {
112
113 VPValue *VPV = Ingredient.getVPSingleValue();
114 if (!VPV->getUnderlyingValue())
115 continue;
116
118
119 VPRecipeBase *NewRecipe = nullptr;
120 if (auto *PhiR = dyn_cast<VPPhi>(&Ingredient)) {
121 auto *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
122 NewRecipe = new VPWidenPHIRecipe(PhiR->operands(), PhiR->getDebugLoc(),
123 Phi->getName());
124 } else if (auto *VPI = dyn_cast<VPInstruction>(&Ingredient)) {
125 assert(!isa<PHINode>(Inst) && "phis should be handled above");
126 // Create VPWidenMemoryRecipe for loads and stores.
127 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
128 bool IsConsecutive =
129 IsConsecutiveAccess(VPI->getOperand(0), VPI->getScalarType());
130 NewRecipe = new VPWidenLoadRecipe(
131 *Load, Ingredient.getOperand(0), nullptr /*Mask*/, IsConsecutive,
132 Load->getAlign(), *VPI, Ingredient.getDebugLoc());
133 } else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
134 bool IsConsecutive = IsConsecutiveAccess(
135 VPI->getOperand(1), VPI->getOperand(0)->getScalarType());
136 NewRecipe = new VPWidenStoreRecipe(
137 *Store, Ingredient.getOperand(1), Ingredient.getOperand(0),
138 nullptr /*Mask*/, IsConsecutive, Store->getAlign(), *VPI,
139 Ingredient.getDebugLoc());
141 NewRecipe = new VPWidenGEPRecipe(GEP->getSourceElementType(),
142 Ingredient.operands(), *VPI,
143 Ingredient.getDebugLoc(), GEP);
144 } else if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
146 if (VectorID == Intrinsic::not_intrinsic)
147 return false;
148
149 // The noalias.scope.decl intrinsic declares a noalias scope that
150 // is valid for a single iteration. Emitting it as a single-scalar
151 // replicate would incorrectly extend the scope across multiple
152 // original iterations packed into one vector iteration.
153 // FIXME: If we want to vectorize this loop, then we have to drop
154 // all the associated !alias.scope and !noalias.
155 if (VectorID == Intrinsic::experimental_noalias_scope_decl)
156 return false;
157
158 // These intrinsics are recognized by getVectorIntrinsicIDForCall
159 // but are not widenable. Emit them as replicate instead of widening.
160 if (VectorID == Intrinsic::assume ||
161 VectorID == Intrinsic::lifetime_end ||
162 VectorID == Intrinsic::lifetime_start ||
163 VectorID == Intrinsic::sideeffect ||
164 VectorID == Intrinsic::pseudoprobe) {
165 // If the operand of llvm.assume holds before vectorization, it will
166 // also hold per lane.
167 // llvm.pseudoprobe requires to be duplicated per lane for accurate
168 // sample count.
169 const bool IsSingleScalar = VectorID != Intrinsic::assume &&
170 VectorID != Intrinsic::pseudoprobe;
171 NewRecipe = new VPReplicateRecipe(CI, Ingredient.operands(),
172 /*IsSingleScalar=*/IsSingleScalar,
173 /*Mask=*/nullptr, *VPI, *VPI,
174 Ingredient.getDebugLoc());
175 } else {
176 assert(!CI->hasOperandBundles() &&
177 "calls with operand bundles must not be widened");
178 NewRecipe = new VPWidenIntrinsicRecipe(
179 *CI, VectorID, drop_end(Ingredient.operands()), CI->getType(),
180 VPIRFlags(*CI), *VPI, CI->getDebugLoc());
181 }
182 } else if (auto *CI = dyn_cast<CastInst>(Inst)) {
183 NewRecipe = new VPWidenCastRecipe(
184 CI->getOpcode(), Ingredient.getOperand(0), CI->getType(), CI,
185 VPIRFlags(*CI), VPIRMetadata(*CI));
186 } else {
187 NewRecipe = new VPWidenRecipe(*Inst, Ingredient.operands(), *VPI,
188 *VPI, Ingredient.getDebugLoc());
189 }
190 } else {
191 assert(isa<VPWidenInductionRecipe>(&Ingredient) &&
192 "inductions must be created earlier");
193 continue;
194 }
195
196 NewRecipe->insertBefore(&Ingredient);
197 if (NewRecipe->getNumDefinedValues() == 1)
198 VPV->replaceAllUsesWith(NewRecipe->getVPSingleValue());
199 else
200 assert(NewRecipe->getNumDefinedValues() == 0 &&
201 "Only recpies with zero or one defined values expected");
202 Ingredient.eraseFromParent();
203 }
204 }
205 return true;
206}
207
208/// Helper for extra no-alias checks via known-safe recipe and SCEV.
211 VPReplicateRecipe &GroupLeader;
212 PredicatedScalarEvolution *PSE = nullptr;
213 const Loop *L = nullptr;
214
215 // Return true if \p A and \p B are known to not alias for all VFs in the
216 // plan, checked via the distance between the accesses
217 bool isNoAliasViaDistance(VPReplicateRecipe *A, VPReplicateRecipe *B) const {
218 if (A->getOpcode() != Instruction::Store ||
219 B->getOpcode() != Instruction::Store)
220 return false;
221
222 if (!PSE || !L)
223 return A == B;
224
225 VPValue *AddrA = A->getOperand(1);
226 const SCEV *SCEVA = vputils::getSCEVExprForVPValue(AddrA, *PSE, L);
227 VPValue *AddrB = B->getOperand(1);
228 const SCEV *SCEVB = vputils::getSCEVExprForVPValue(AddrB, *PSE, L);
230 return false;
231
232 const APInt *Distance;
233 ScalarEvolution &SE = *PSE->getSE();
234 if (!match(SE.getMinusSCEV(SCEVA, SCEVB), m_scev_APInt(Distance)))
235 return false;
236
237 const DataLayout &DL = SE.getDataLayout();
238 Type *TyA = A->getOperand(0)->getScalarType();
239 uint64_t SizeA = DL.getTypeStoreSize(TyA);
240 Type *TyB = B->getOperand(0)->getScalarType();
241 uint64_t SizeB = DL.getTypeStoreSize(TyB);
242
243 // Use the maximum store size to ensure no overlap from either direction.
244 // Currently only handles fixed sizes, as it is only used for
245 // replicating VPReplicateRecipes.
246 uint64_t MaxStoreSize = std::max(SizeA, SizeB);
247
248 auto VFs = B->getParent()->getPlan()->vectorFactors();
250 if (MaxVF.isScalable())
251 return false;
252 return Distance->abs().uge(MaxVF.getFixedValue() * MaxStoreSize);
253 }
254
255public:
258 const Loop &L)
259 : ExcludeRecipes(ExcludeRecipes.begin(), ExcludeRecipes.end()),
260 GroupLeader(GroupLeader), PSE(&PSE), L(&L) {}
261
262 SinkStoreInfo(VPReplicateRecipe &GroupLeader) : GroupLeader(GroupLeader) {}
263
264 /// Return true if \p R should be skipped during alias checking, either
265 /// because it's in the exclude set or because no-alias can be proven via
266 /// SCEV.
267 bool shouldSkip(VPRecipeBase &R) const {
269 return ExcludeRecipes.contains(Store) ||
270 (Store && isNoAliasViaDistance(Store, &GroupLeader));
271 }
272};
273
274/// Check if a memory operation doesn't alias with memory operations using
275/// scoped noalias metadata, in blocks in the single-successor chain between \p
276/// FirstBB and \p LastBB. If \p SinkInfo is std::nullopt, only recipes that may
277/// write to memory are checked (for load hoisting). Otherwise recipes that both
278/// read and write memory are checked, and SCEV is used to prove no-alias
279/// between the group leader and other replicate recipes (for store sinking).
280static bool
282 VPBasicBlock *FirstBB, VPBasicBlock *LastBB,
283 std::optional<SinkStoreInfo> SinkInfo = {}) {
284 bool CheckReads = SinkInfo.has_value();
285 ScopedNoAliasAAResult ScopedNoAlias(FirstBB->getPlan()->getContext());
286 for (VPBasicBlock *VPBB :
288 for (VPRecipeBase &R : *VPBB) {
289 if (SinkInfo && SinkInfo->shouldSkip(R))
290 continue;
291
292 // Skip recipes that don't need checking.
293 if (!R.mayWriteToMemory() && !(CheckReads && R.mayReadFromMemory()))
294 continue;
295
297 if (!Loc)
298 // Conservatively assume aliasing for memory operations without
299 // location.
300 return false;
301
302 if (ScopedNoAlias.alias(*Loc, MemLoc) != AliasResult::NoAlias)
303 return false;
304 }
305 }
306 return true;
307}
308
309/// Collect either replicated Loads or Stores grouped by their address SCEV and
310/// their load-store type, in a deep-traversal of the vector loop region in \p
311/// Plan.
312template <unsigned Opcode>
315 VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L,
316 function_ref<bool(VPReplicateRecipe *)> FilterFn) {
317 static_assert(Opcode == Instruction::Load || Opcode == Instruction::Store,
318 "Only Load and Store opcodes supported");
319 constexpr bool IsLoad = (Opcode == Instruction::Load);
322 RecipesByAddressAndType;
326 if (RepR.getOpcode() != Opcode || !FilterFn(&RepR))
327 continue;
328
329 // For loads, operand 0 is address; for stores, operand 1 is address.
330 VPValue *Addr = RepR.getOperand(IsLoad ? 0 : 1);
331 const Type *LoadStoreTy = vputils::getLoadStoreValueType(&RepR);
332 const SCEV *AddrSCEV = vputils::getSCEVExprForVPValue(Addr, PSE, L);
333 if (!isa<SCEVCouldNotCompute>(AddrSCEV))
334 RecipesByAddressAndType[{AddrSCEV, LoadStoreTy}].push_back(&RepR);
335 }
336 }
337 auto Groups = to_vector(RecipesByAddressAndType.values());
338 VPDominatorTree VPDT(Plan);
339 for (auto &Group : Groups) {
340 // Sort mem ops by dominance order, with earliest (most dominating) first.
342 return VPDT.properlyDominates(A, B);
343 });
344 }
345 return Groups;
346}
347
348static bool sinkScalarOperands(VPlan &Plan) {
349 auto Iter = vp_depth_first_deep(Plan.getEntry());
350 bool ScalarVFOnly = Plan.hasScalarVFOnly();
351 bool Changed = false;
352
354 auto InsertIfValidSinkCandidate = [ScalarVFOnly, &WorkList](
355 VPBasicBlock *SinkTo, VPValue *Op) {
356 auto *Candidate = dyn_cast<VPSingleDefRecipe>(Op);
358 VPInstruction>(Candidate))
359 return;
360
361 if (Candidate->getParent() == SinkTo ||
362 all_of(Candidate->operands(),
363 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); }) ||
364 vputils::cannotHoistOrSinkRecipe(*Candidate, /*Sinking=*/true))
365 return;
366
367 if (!ScalarVFOnly && !vputils::doesGeneratePerAllLanes(Candidate))
368 return;
369
370 // Only single-scalar VPInstructions can be sunk.
371 if (auto *VPI = dyn_cast<VPInstruction>(Candidate))
372 if (!vputils::isSingleScalar(VPI))
373 return;
374
375 WorkList.insert({SinkTo, Candidate});
376 };
377
378 // First, collect the operands of all recipes in replicate blocks as seeds for
379 // sinking.
381 VPBasicBlock *EntryVPBB = VPR->getEntryBasicBlock();
382 if (!VPR->isReplicator() || EntryVPBB->getSuccessors().size() != 2)
383 continue;
384 VPBasicBlock *VPBB = cast<VPBasicBlock>(EntryVPBB->getSuccessors().front());
385 if (VPBB->getSingleSuccessor() != VPR->getExitingBasicBlock())
386 continue;
387 for (auto &Recipe : *VPBB)
388 for (VPValue *Op : Recipe.operands())
389 InsertIfValidSinkCandidate(VPBB, Op);
390 }
391
392 // Try to sink each replicate or scalar IV steps recipe in the worklist.
393 for (unsigned I = 0; I != WorkList.size(); ++I) {
394 VPBasicBlock *SinkTo;
395 VPSingleDefRecipe *SinkCandidate;
396 std::tie(SinkTo, SinkCandidate) = WorkList[I];
397
398 // All recipe users of SinkCandidate must be in the same block SinkTo or all
399 // users outside of SinkTo must only use the first lane of SinkCandidate. In
400 // the latter case, we need to duplicate SinkCandidate.
401 auto UsersOutsideSinkTo =
402 make_filter_range(SinkCandidate->users(), [SinkTo](VPUser *U) {
403 return cast<VPRecipeBase>(U)->getParent() != SinkTo;
404 });
405 if (any_of(UsersOutsideSinkTo, [SinkCandidate](VPUser *U) {
406 return !U->usesFirstLaneOnly(SinkCandidate);
407 }))
408 continue;
409 bool NeedsDuplicating = !UsersOutsideSinkTo.empty();
410
411 if (NeedsDuplicating) {
412 if (ScalarVFOnly)
413 continue;
414 VPSingleDefRecipe *Clone;
415 if (auto *SinkCandidateRepR =
416 dyn_cast<VPReplicateRecipe>(SinkCandidate)) {
417 // TODO: Handle converting to uniform recipes as separate transform,
418 // then cloning should be sufficient here.
420 SinkCandidateRepR->getOpcode(), SinkCandidate->operands(),
421 /*Mask=*/nullptr, *SinkCandidateRepR, *SinkCandidateRepR,
422 SinkCandidate->getDebugLoc(), SinkCandidate->getScalarType(),
423 SinkCandidate->getUnderlyingInstr());
424 // TODO: add ".cloned" suffix to name of Clone's VPValue.
425 } else {
426 Clone = SinkCandidate->clone();
427 }
428
429 Clone->insertBefore(SinkCandidate);
430 SinkCandidate->replaceUsesWithIf(Clone, [SinkTo](VPUser *U) {
431 return cast<VPRecipeBase>(U)->getParent() != SinkTo;
432 });
433 }
434 SinkCandidate->moveBefore(SinkTo->getFirstNonPhi());
435 for (VPValue *Op : SinkCandidate->operands())
436 InsertIfValidSinkCandidate(SinkTo, Op);
437 Changed = true;
438 }
439 return Changed;
440}
441
442/// If \p R is a triangle region, return the 'then' block of the triangle.
444 auto *EntryBB = cast<VPBasicBlock>(R->getEntry());
445 if (EntryBB->getNumSuccessors() != 2)
446 return nullptr;
447
448 auto *Succ0 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[0]);
449 auto *Succ1 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[1]);
450 if (!Succ0 || !Succ1)
451 return nullptr;
452
453 if (Succ0->getNumSuccessors() + Succ1->getNumSuccessors() != 1)
454 return nullptr;
455 if (Succ0->getSingleSuccessor() == Succ1)
456 return Succ0;
457 if (Succ1->getSingleSuccessor() == Succ0)
458 return Succ1;
459 return nullptr;
460}
461
462// Merge replicate regions in their successor region, if a replicate region
463// is connected to a successor replicate region with the same predicate by a
464// single, empty VPBasicBlock.
466 SmallPtrSet<VPRegionBlock *, 4> TransformedRegions;
467
468 // Collect replicate regions followed by an empty block, followed by another
469 // replicate region with matching masks to process front. This is to avoid
470 // iterator invalidation issues while merging regions.
473 vp_depth_first_deep(Plan.getEntry()))) {
474 if (!Region1->isReplicator())
475 continue;
476 auto *MiddleBasicBlock =
477 dyn_cast_or_null<VPBasicBlock>(Region1->getSingleSuccessor());
478 if (!MiddleBasicBlock || !MiddleBasicBlock->empty())
479 continue;
480
481 auto *Region2 =
482 dyn_cast_or_null<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
483 if (!Region2 || !Region2->isReplicator())
484 continue;
485
486 VPValue *Mask1 = Region1->getEntryBranchOnMask()->getOperand(0);
487 VPValue *Mask2 = Region2->getEntryBranchOnMask()->getOperand(0);
488 if (!Mask1 || Mask1 != Mask2)
489 continue;
490
491 assert(Mask1 && Mask2 && "both region must have conditions");
492 WorkList.push_back(Region1);
493 }
494
495 // Move recipes from Region1 to its successor region, if both are triangles.
496 for (VPRegionBlock *Region1 : WorkList) {
497 if (TransformedRegions.contains(Region1))
498 continue;
499 auto *MiddleBasicBlock = cast<VPBasicBlock>(Region1->getSingleSuccessor());
500 auto *Region2 = cast<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
501
502 VPBasicBlock *Then1 = getPredicatedThenBlock(Region1);
503 VPBasicBlock *Then2 = getPredicatedThenBlock(Region2);
504 if (!Then1 || !Then2)
505 continue;
506
507 // The merged region is entered whenever either of the original regions was,
508 // so use the higher, i.e. more conservative, of their entry frequencies.
509 // If only one of the two is known, the higher one is unknown, so the
510 // result must be unknown too.
511 VPBranchOnMaskRecipe *Guard2 = Region2->getEntryBranchOnMask();
512 std::optional<VPExecutionFrequency> Freq1 =
513 Region1->getEntryBranchOnMask()->getExecutionFrequency();
514 std::optional<VPExecutionFrequency> Freq2 = Guard2->getExecutionFrequency();
515 if (Freq1 && Freq2) {
516 if (Freq2->Freq < Freq1->Freq) {
517 // Freq1's frequency is taken, but it is only as trustworthy as the
518 // less trustworthy of the two.
519 Freq1.emplace(Freq1->Freq, Freq1->IsEstimated || Freq2->IsEstimated);
520 Guard2->setExecutionFrequency(Freq1, Plan.getContext());
521 }
522 } else if (Freq2) {
523 Guard2->clearExecutionFrequency();
524 }
525
526 // Note: No fusion-preventing memory dependencies are expected in either
527 // region. Such dependencies should be rejected during earlier dependence
528 // checks, which guarantee accesses can be re-ordered for vectorization.
529 //
530 // Move recipes to the successor region.
531 for (VPRecipeBase &ToMove : make_early_inc_range(reverse(*Then1)))
532 ToMove.moveBefore(Then2->getFirstNonPhi());
533
534 auto *Merge1 = cast<VPBasicBlock>(Then1->getSingleSuccessor());
535 auto *Merge2 = cast<VPBasicBlock>(Then2->getSingleSuccessor());
536
537 // Move VPPredInstPHIRecipes from the merge block to the successor region's
538 // merge block. Update all users inside the successor region to use the
539 // original values.
540 for (VPRecipeBase &Phi1ToMove : make_early_inc_range(reverse(*Merge1))) {
541 VPValue *PredInst1 =
542 cast<VPPredInstPHIRecipe>(&Phi1ToMove)->getOperand(0);
543 VPValue *Phi1ToMoveV = Phi1ToMove.getVPSingleValue();
544 Phi1ToMoveV->replaceUsesWithIf(PredInst1, [Then2](VPUser *U) {
545 return cast<VPRecipeBase>(U)->getParent() == Then2;
546 });
547
548 // Remove phi recipes that are unused after merging the regions.
549 if (Phi1ToMove.getVPSingleValue()->user_empty()) {
550 Phi1ToMove.eraseFromParent();
551 continue;
552 }
553 Phi1ToMove.moveBefore(Merge2->begin());
554 }
555
556 // Remove the dead recipes in Region1's entry block.
557 for (VPRecipeBase &R :
558 make_early_inc_range(reverse(*Region1->getEntryBasicBlock())))
559 R.eraseFromParent();
560
561 // Finally, remove the first region.
562 for (VPBlockBase *Pred : make_early_inc_range(Region1->getPredecessors())) {
564 VPBlockUtils::connectBlocks(Pred, MiddleBasicBlock);
565 }
566 VPBlockUtils::disconnectBlocks(Region1, MiddleBasicBlock);
567 TransformedRegions.insert(Region1);
568 }
569
570 return !TransformedRegions.empty();
571}
572
574 VPRegionBlock *ParentRegion,
575 VPlan &Plan) {
576 Instruction *Instr = PredRecipe->getUnderlyingInstr();
577 // Build the triangular if-then region.
578 std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
579 assert(Instr->getParent() && "Predicated instruction not in any basic block");
580 auto *BlockInMask = PredRecipe->getMask();
581 auto *MaskDef = BlockInMask->getDefiningRecipe();
582 auto *BOMRecipe = new VPBranchOnMaskRecipe(
583 BlockInMask, MaskDef ? MaskDef->getDebugLoc() : DebugLoc::getUnknown());
584 auto *Entry =
585 Plan.createVPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
586
587 // Replace predicated replicate recipe with a replicate recipe without a
588 // mask but in the replicate region.
589 auto *RecipeWithoutMask = new VPReplicateRecipe(
590 PredRecipe->getUnderlyingInstr(), PredRecipe->operandsWithoutMask(),
591 PredRecipe->isSingleScalar(), nullptr /*Mask*/, *PredRecipe, *PredRecipe,
592 PredRecipe->getDebugLoc());
593 // The predicated recipe executes exactly when the guarding branch-on-mask is
594 // taken, so move its execution frequency there.
595 BOMRecipe->setExecutionFrequency(RecipeWithoutMask->getExecutionFrequency(),
596 Plan.getContext());
597 RecipeWithoutMask->clearExecutionFrequency();
598 auto *Pred =
599 Plan.createVPBasicBlock(Twine(RegionName) + ".if", RecipeWithoutMask);
600 auto *Exiting = Plan.createVPBasicBlock(Twine(RegionName) + ".continue");
602 Plan.createReplicateRegion(Entry, Exiting, RegionName);
603
604 // Note: first set Entry as region entry and then connect successors starting
605 // from it in order, to propagate the "parent" of each VPBasicBlock.
606 Region->setParent(ParentRegion);
609
610 PredRecipe->replaceAllUsesWith(RecipeWithoutMask);
611 // Move the extracts of a struct result into the region, so only scalars
612 // leave it.
613 SmallVector<VPUser *> Defs = {RecipeWithoutMask};
614 if (RecipeWithoutMask->getScalarType()->isStructTy())
615 Defs = to_vector(RecipeWithoutMask->users());
617 assert((Def == RecipeWithoutMask ||
618 Def->getOpcode() == Instruction::ExtractValue) &&
619 "only extracts can use a predicated struct");
620 Def->moveBefore(Pred->end());
621 if (Def->user_empty())
622 continue;
623 auto *PHIRecipe = new VPPredInstPHIRecipe(Def, Def->getDebugLoc());
624 Exiting->appendRecipe(PHIRecipe);
625 Def->replaceAllUsesWith(PHIRecipe);
626 PHIRecipe->setOperand(0, Def);
627 }
628 PredRecipe->eraseFromParent();
629 return Region;
630}
631
632static void addReplicateRegions(VPlan &Plan) {
635 vp_depth_first_deep(Plan.getEntry()))) {
637 if (RepR.isPredicated())
638 WorkList.push_back(&RepR);
639 }
640
641 unsigned BBNum = 0;
642 for (VPReplicateRecipe *RepR : WorkList) {
643 VPBasicBlock *CurrentBlock = RepR->getParent();
644 VPBasicBlock *SplitBlock = CurrentBlock->splitAt(RepR->getIterator());
645
646 BasicBlock *OrigBB = RepR->getUnderlyingInstr()->getParent();
647 SplitBlock->setName(
648 OrigBB->hasName() ? OrigBB->getName() + "." + Twine(BBNum++) : "");
649 // Record predicated instructions for above packing optimizations.
651 createReplicateRegion(RepR, CurrentBlock->getParent(), Plan);
653
654 VPRegionBlock *ParentRegion = Region->getParent();
655 if (ParentRegion && ParentRegion->getExiting() == CurrentBlock)
656 ParentRegion->setExiting(SplitBlock);
657 }
658}
659
662
663 // Collect single-successor chains in the loop region.
664 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
666 vp_depth_first_deep(LoopRegion->getEntry()))) {
667 if (!VPBB->getParent())
668 continue;
669 VPBlockBase *PredBlock = VPBB->getSinglePredecessor();
670 if (!isa_and_nonnull<VPBasicBlock>(PredBlock) ||
671 !PredBlock->getSingleSuccessor())
672 continue;
673 WorkList.push_back(VPBB);
674 }
675
676 for (VPBasicBlock *VPBB : WorkList) {
677 VPBasicBlock *PredVPBB = cast<VPBasicBlock>(VPBB->getSinglePredecessor());
678 for (VPRecipeBase &R : make_early_inc_range(*VPBB))
679 R.moveBefore(PredVPBB->end());
680 VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
681 auto *ParentRegion = VPBB->getParent();
682 if (ParentRegion && ParentRegion->getExiting() == VPBB)
683 ParentRegion->setExiting(PredVPBB);
684 VPBlockUtils::transferSuccessors(VPBB, PredVPBB);
685 // VPBB is now dead and will be cleaned up when the plan gets destroyed.
686 }
687 return !WorkList.empty();
688}
689
691 // Convert masked VPReplicateRecipes to if-then region blocks.
693
694 bool ShouldSimplify = true;
695 while (ShouldSimplify) {
696 ShouldSimplify = sinkScalarOperands(Plan);
697 ShouldSimplify |= mergeReplicateRegionsIntoSuccessors(Plan);
698 ShouldSimplify |= mergeBlocksIntoPredecessors(Plan);
699 }
700}
701
702/// Remove redundant casts of inductions.
703///
704/// Such redundant casts are casts of induction variables that can be ignored,
705/// because we already proved that the casted phi is equal to the uncasted phi
706/// in the vectorized loop. There is no need to vectorize the cast - the same
707/// value can be used for both the phi and casts in the vector loop.
712 if (IV.isTruncated())
713 continue;
714
715 // A sequence of IR Casts has potentially been recorded for IV, which
716 // *must be bypassed* when the IV is vectorized, because the vectorized IV
717 // will produce the desired casted value. This sequence forms a def-use
718 // chain and is provided in reverse order, ending with the cast that uses
719 // the IV phi. Search for the recipe of the last cast in the chain and
720 // replace it with the original IV. Note that only the final cast is
721 // expected to have users outside the cast-chain and the dead casts left
722 // over will be cleaned up later.
723 ArrayRef<Instruction *> Casts = IV.getInductionDescriptor().getCastInsts();
724 VPValue *FindMyCast = &IV;
725 for (Instruction *IRCast : reverse(Casts)) {
726 VPSingleDefRecipe *FoundUserCast = nullptr;
727 for (auto *U : FindMyCast->users()) {
728 auto *UserCast = dyn_cast<VPSingleDefRecipe>(U);
729 if (UserCast && UserCast->getUnderlyingValue() == IRCast) {
730 FoundUserCast = UserCast;
731 break;
732 }
733 }
734 // A cast recipe in the chain may have been removed by earlier DCE.
735 if (!FoundUserCast)
736 break;
737 FindMyCast = FoundUserCast;
738 }
739 if (FindMyCast != &IV)
740 FindMyCast->replaceAllUsesWith(&IV);
741 }
742}
743
744/// If R is a phi-like recipe starting a dead cycle of recipes, erase all
745/// reachable recipes of the dead cycle and return true. Otherwise leave the
746/// plan unchanged and return false.
748 auto *PhiR = dyn_cast<VPSingleDefRecipe>(R);
749 if (!PhiR || !isa<VPPhi, VPReductionPHIRecipe>(R))
750 return false;
751
752 // The transitive users of PhiR are closed under users, so the cycle is dead
753 // if every one of them can be erased.
755 auto *R = cast<VPRecipeBase>(U);
756 // Bail out if a user must be retained, or if it is a phi-like recipe other
757 // than PhiR;
758 if (R->mayHaveSideEffects() || (R != PhiR && isa<VPPhiAccessors>(R)))
759 return false;
760 }
761
762 // Break the cycle by replacing PhiR with its first incoming value, which is
763 // defined outside the cycle. That leaves the rest of the cycle dead.
764 PhiR->replaceAllUsesWith(PhiR->getOperand(0));
765 SmallVector<VPValue *> Incoming(PhiR->operands());
766 PhiR->eraseFromParent();
767 for (VPValue *Op : Incoming)
769 return true;
770}
771
774 Plan.getEntry());
776 // The recipes in the block are processed in reverse order, to catch chains
777 // of dead recipes.
778 for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB)))
780 R.eraseFromParent();
781
782 // Erase dead cycles starting at one of VPBB's phi-like recipes. Erasing a
783 // cycle may also erase other phi-like recipes of VPBB, so restart the scan
784 // of the phi section after each removal. This terminates, as each removal
785 // erases the cycle's phi.
786 bool Changed = true;
787 while (Changed) {
788 Changed = false;
789 for (VPRecipeBase &R : VPBB->phis()) {
790 if (tryToRemoveDeadCycle(&R)) {
791 Changed = true;
792 break;
793 }
794 }
795 }
796 }
797}
798
799/// Legalize VPWidenPointerInductionRecipe, by replacing it with a PtrAdd
800/// (IndStart, ScalarIVSteps (0, Step)) if only its scalar values are used, as
801/// VPWidenPointerInductionRecipe will generate vectors only. If some users
802/// require vectors while other require scalars, the scalar uses need to extract
803/// the scalars from the generated vectors (Note that this is different to how
804/// int/fp inductions are handled). Legalize extract-from-ends using uniform
805/// VPReplicateRecipe of wide inductions to use regular VPReplicateRecipe, so
806/// the correct end value is available. Also optimize
807/// VPWidenIntOrFpInductionRecipe, if any of its users needs scalar values, by
808/// providing them scalar steps built on the canonical scalar IV and update the
809/// original IV's users. This is an optional optimization to reduce the needs of
810/// vector extracts.
813 bool HasOnlyVectorVFs = !Plan.hasScalarVFOnly();
814
816 for (VPWidenInductionRecipe &PhiR :
818 WideIVs.push_back(&PhiR);
819
820 // Try to narrow wide and replicating recipes to uniform recipes, based on
821 // VPlan analysis.
822 // TODO: Apply to all recipes in the future, to replace legacy uniformity
823 // analysis.
824 for (VPWidenInductionRecipe *PhiR : WideIVs) {
826 for (VPUser *U : reverse(Users)) {
827 auto *Def = dyn_cast<VPRecipeWithIRFlags>(U);
828 auto *RepR = dyn_cast<VPReplicateRecipe>(U);
829 // Skip recipes that shouldn't be narrowed.
830 if (!Def ||
832 Def->user_empty() || !Def->getUnderlyingValue() ||
833 (RepR && (RepR->isSingleScalar() || RepR->isPredicated())))
834 continue;
835
836 // Skip recipes that may have other lanes than their first used.
838 continue;
839
840 // TODO: Support scalarizing ExtractValue.
841 if (match(Def,
843 continue;
844
846 Def->getUnderlyingInstr()->getOpcode(), Def->operands(),
847 /*Mask=*/nullptr, *Def, getMetadataOf(Def), DebugLoc::getUnknown(),
848 Def->getScalarType(), Def->getUnderlyingInstr());
849 Clone->insertAfter(Def);
850 Def->replaceAllUsesWith(Clone);
851 Def->eraseFromParent();
852 }
853 }
854
855 VPBuilder Builder(HeaderVPBB->getFirstNonPhi());
856 for (VPWidenInductionRecipe *PhiR : WideIVs) {
857 // Replace wide pointer inductions which have only their scalars used by
858 // PtrAdd(IndStart, ScalarIVSteps (0, Step)).
859 if (auto *PtrIV = dyn_cast<VPWidenPointerInductionRecipe>(PhiR)) {
860 if (!Plan.hasScalarVFOnly() &&
861 !PtrIV->onlyScalarsGenerated(Plan.hasScalableVF()))
862 continue;
863
864 VPValue *PtrAdd =
865 vputils::scalarizeVPWidenPointerInduction(PtrIV, Plan, Builder);
866 PtrIV->replaceAllUsesWith(PtrAdd);
867 continue;
868 }
869
870 // Replace widened induction with scalar steps for users that only use
871 // scalars.
872 auto *WideIV = cast<VPWidenIntOrFpInductionRecipe>(PhiR);
873 if (HasOnlyVectorVFs && none_of(WideIV->users(), [WideIV](VPUser *U) {
874 return U->usesScalars(WideIV);
875 }))
876 continue;
877
878 const InductionDescriptor &ID = WideIV->getInductionDescriptor();
879 VPIRFlags::WrapFlagsTy WrapFlags;
880 // We can preserve nuw when the step is non-negative.
881 const APInt *Step;
882 if (match(WideIV->getStepValue(), m_APInt(Step)) && Step->isNonNegative())
883 WrapFlags = WideIV->getNoWrapFlagsOrNone().withoutNoSignedWrap();
885 Plan, ID.getKind(), ID.getInductionOpcode(),
886 dyn_cast_or_null<FPMathOperator>(ID.getInductionBinOp()),
887 WideIV->getScalarType(), WideIV->getStartValue(),
888 WideIV->getStepValue(), WideIV->getDebugLoc(), Builder, WrapFlags);
889
890 // Update scalar users of IV to use Step instead.
891 if (!HasOnlyVectorVFs) {
892 assert(!Plan.hasScalableVF() &&
893 "plans containing a scalar VF cannot also include scalable VFs");
894 WideIV->replaceAllUsesWith(Steps);
895 } else {
896 bool HasScalableVF = Plan.hasScalableVF();
897 WideIV->replaceUsesWithIf(Steps, [WideIV, HasScalableVF](VPUser *U) {
898 if (HasScalableVF)
899 return U->usesFirstLaneOnly(WideIV);
900 return U->usesScalars(WideIV);
901 });
902 }
903 }
904}
905
906/// Check if \p VPV is an untruncated wide induction, either before or after the
907/// increment. If so return the header IV (before the increment), otherwise
908/// return null.
911 auto *WideIV = dyn_cast<VPWidenInductionRecipe>(VPV);
912 if (WideIV) {
913 // VPV itself is a wide induction, separately compute the end value for exit
914 // users if it is not a truncated IV.
915 auto *IntOrFpIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(WideIV);
916 return (IntOrFpIV && IntOrFpIV->isTruncated()) ? nullptr : WideIV;
917 }
918
919 // Check if VPV is an optimizable induction increment.
920 VPRecipeBase *Def = VPV->getDefiningRecipe();
921 if (!Def || Def->getNumOperands() != 2)
922 return nullptr;
923 WideIV = dyn_cast<VPWidenInductionRecipe>(Def->getOperand(0));
924 if (!WideIV)
925 WideIV = dyn_cast<VPWidenInductionRecipe>(Def->getOperand(1));
926 if (!WideIV)
927 return nullptr;
928
929 auto IsWideIVInc = [&]() {
930 auto &ID = WideIV->getInductionDescriptor();
931
932 // Check if VPV increments the induction by the induction step.
933 VPValue *IVStep = WideIV->getStepValue();
934 switch (ID.getInductionOpcode()) {
935 case Instruction::Add:
936 return match(VPV, m_c_Add(m_Specific(WideIV), m_Specific(IVStep)));
937 case Instruction::FAdd:
938 return match(VPV, m_c_FAdd(m_Specific(WideIV), m_Specific(IVStep)));
939 case Instruction::FSub:
940 return match(VPV, m_Binary<Instruction::FSub>(m_Specific(WideIV),
941 m_Specific(IVStep)));
942 case Instruction::Sub: {
943 // IVStep will be the negated step of the subtraction. Check if Step == -1
944 // * IVStep.
945 VPValue *Step;
946 if (!match(VPV, m_Sub(m_VPValue(), m_VPValue(Step))))
947 return false;
948 const SCEV *IVStepSCEV = vputils::getSCEVExprForVPValue(IVStep, PSE);
949 const SCEV *StepSCEV = vputils::getSCEVExprForVPValue(Step, PSE);
950 ScalarEvolution &SE = *PSE.getSE();
951 return !isa<SCEVCouldNotCompute>(IVStepSCEV) &&
952 !isa<SCEVCouldNotCompute>(StepSCEV) &&
953 IVStepSCEV == SE.getNegativeSCEV(StepSCEV);
954 }
955 default:
956 return ID.getKind() == InductionDescriptor::IK_PtrInduction &&
957 match(VPV, m_GetElementPtr(m_Specific(WideIV),
958 m_Specific(WideIV->getStepValue())));
959 }
960 llvm_unreachable("should have been covered by switch above");
961 };
962 return IsWideIVInc() ? WideIV : nullptr;
963}
964
965/// Attempts to optimize the induction variable exit values for users in the
966/// early exit block.
969 VPValue *Incoming, *Mask;
971 m_VPValue(Incoming))))
972 return nullptr;
973
974 auto *WideIV = getOptimizableIVOf(Incoming, PSE);
975 if (!WideIV)
976 return nullptr;
977
978 // Calculate the final index.
979 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
980 auto *CanonicalIV = LoopRegion->getCanonicalIV();
981 Type *CanonicalIVType = LoopRegion->getCanonicalIVType();
982 auto *ExtractR = cast<VPInstruction>(Op);
983 VPBuilder B(ExtractR);
984
985 DebugLoc DL = ExtractR->getDebugLoc();
986 VPValue *FirstActiveLane = B.createFirstActiveLane(Mask, DL);
987 FirstActiveLane =
988 B.createScalarZExtOrTrunc(FirstActiveLane, CanonicalIVType, DL);
989 VPValue *EndValue = B.createAdd(CanonicalIV, FirstActiveLane, DL);
990
991 // `getOptimizableIVOf()` always returns the pre-incremented IV, so if it
992 // changed it means the exit is using the incremented value, so we need to
993 // add the step.
994 if (Incoming != WideIV) {
995 VPValue *One = Plan.getConstantInt(CanonicalIVType, 1);
996 EndValue = B.createAdd(EndValue, One, DL);
997 }
998
999 if (!match(WideIV, m_CanonicalWidenIV())) {
1000 const InductionDescriptor &ID = WideIV->getInductionDescriptor();
1001 VPValue *Start = WideIV->getStartValue();
1002 VPValue *Step = WideIV->getStepValue();
1003 EndValue = B.createDerivedIV(
1004 ID.getKind(), dyn_cast_or_null<FPMathOperator>(ID.getInductionBinOp()),
1005 Start, EndValue, Step);
1006 }
1007
1008 return EndValue;
1009}
1010
1011/// Compute the end value for \p WideIV, unless it is truncated. Creates a
1012/// VPDerivedIVRecipe for non-canonical inductions.
1014 VPBuilder &VectorPHBuilder,
1015 VPValue *VectorTC) {
1016 auto *WideIntOrFp = dyn_cast<VPWidenIntOrFpInductionRecipe>(WideIV);
1017 // Truncated wide inductions resume from the last lane of their vector value
1018 // in the last vector iteration which is handled elsewhere.
1019 if (WideIntOrFp && WideIntOrFp->isTruncated())
1020 return nullptr;
1021
1022 VPValue *Start = WideIV->getStartValue();
1023 VPValue *Step = WideIV->getStepValue();
1024 const InductionDescriptor &ID = WideIV->getInductionDescriptor();
1025 VPValue *EndValue = VectorTC;
1026 if (!match(WideIV, m_CanonicalWidenIV())) {
1027 EndValue = VectorPHBuilder.createDerivedIV(
1028 ID.getKind(), dyn_cast_or_null<FPMathOperator>(ID.getInductionBinOp()),
1029 Start, VectorTC, Step);
1030 }
1031
1032 // EndValue is derived from the vector trip count (which has the same type as
1033 // the widest induction) and thus may be wider than the induction here.
1034 Type *ScalarTypeOfWideIV = WideIV->getScalarType();
1035 if (ScalarTypeOfWideIV != EndValue->getScalarType()) {
1036 EndValue = VectorPHBuilder.createScalarCast(Instruction::Trunc, EndValue,
1037 ScalarTypeOfWideIV,
1038 WideIV->getDebugLoc());
1039 }
1040
1041 return EndValue;
1042}
1043
1044/// Attempts to optimize the induction variable exit values for users in the
1045/// exit block coming from the latch in the original scalar loop.
1046static VPValue *
1050 VPValue *Incoming;
1053 m_VPValue(Incoming)))))
1054 return nullptr;
1055
1056 VPWidenInductionRecipe *WideIV = getOptimizableIVOf(Incoming, PSE);
1057 if (!WideIV)
1058 return nullptr;
1059
1060 VPValue *EndValue = EndValues.lookup(WideIV);
1061 assert(EndValue && "Must have computed the end value up front");
1062
1063 // `getOptimizableIVOf()` always returns the pre-incremented IV, so if it
1064 // changed it means the exit is using the incremented value, so we don't
1065 // need to subtract the step.
1066 if (Incoming != WideIV)
1067 return EndValue;
1068
1069 // Otherwise, subtract the step from the EndValue.
1070 auto *ExtractR = cast<VPInstruction>(Op);
1071 VPBuilder B(ExtractR);
1072 VPValue *Step = WideIV->getStepValue();
1073 Type *ScalarTy = WideIV->getScalarType();
1074 if (ScalarTy->isIntegerTy())
1075 return B.createSub(EndValue, Step, DebugLoc::getUnknown(), "ind.escape");
1076 if (ScalarTy->isPointerTy()) {
1077 Type *StepTy = Step->getScalarType();
1078 auto *Zero = Plan.getZero(StepTy);
1079 return B.createPtrAdd(EndValue, B.createSub(Zero, Step),
1080 DebugLoc::getUnknown(), "ind.escape");
1081 }
1082 if (ScalarTy->isFloatingPointTy()) {
1083 const auto &ID = WideIV->getInductionDescriptor();
1084 return B.createNaryOp(
1085 ID.getInductionBinOp()->getOpcode() == Instruction::FAdd
1086 ? Instruction::FSub
1087 : Instruction::FAdd,
1088 {EndValue, Step}, {ID.getInductionBinOp()->getFastMathFlags()});
1089 }
1090 llvm_unreachable("all possible induction types must be handled");
1091 return nullptr;
1092}
1093
1096 VPValue *ResumeTC,
1097 const Loop *L) {
1098 VPValue *Incoming;
1101 m_VPValue(Incoming)))))
1102 return nullptr;
1103
1104 const SCEV *IncomingSCEV = vputils::getSCEVExprForVPValue(Incoming, PSE, L);
1105 const SCEV *Start, *Step;
1106 if (!match(IncomingSCEV, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step),
1107 m_SpecificLoop(L))))
1108 return nullptr;
1109
1110 auto *ExtractR = cast<VPInstruction>(Op);
1111 DebugLoc DL = ExtractR->getDebugLoc();
1112 VPBuilder Builder(ExtractR);
1113 VPSCEVExpander Expander(Builder, *PSE.getSE(), DL);
1114 VPValue *StartVPV = Expander.expand(Start);
1115 VPValue *StepVPV = Expander.expand(Step);
1116
1117 Type *StartTy = StartVPV->getScalarType();
1118 assert(StartTy->isIntOrPtrTy() && "The type must be SCEVable");
1122 Type *TCTy = ResumeTC->getScalarType();
1123 VPValue *ExitCount = Builder.createOverflowingOp(
1124 Instruction::Sub, {ResumeTC, Plan.getConstantInt(TCTy, 1)},
1125 {/*HasNUW=*/true, /*HasNSW=*/false}, DebugLoc::getUnknown());
1126 return Builder.createDerivedIV(Kind, /*FPBinOp=*/nullptr, StartVPV, ExitCount,
1127 StepVPV);
1128}
1129
1131 VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L) {
1132 // Compute end values for all inductions.
1133 VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
1134 auto *VectorPH = cast<VPBasicBlock>(VectorRegion->getSinglePredecessor());
1135 VPBuilder VectorPHBuilder(VectorPH->getFirstNonPhi());
1137 VPValue *ResumeTC =
1138 Plan.hasTailFolded() ? Plan.getTripCount() : &Plan.getVectorTripCount();
1140 VectorRegion->getEntryBasicBlock()->phis())) {
1142 &WideIV, VectorPHBuilder, ResumeTC))
1143 EndValues[&WideIV] = EndValue;
1144 }
1145
1146 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
1147 for (VPRecipeBase &R : make_early_inc_range(*MiddleVPBB)) {
1148 VPValue *Op;
1149 if (!match(&R, m_ExitingIVValue(m_VPValue(Op))))
1150 continue;
1151 auto *WideIV = cast<VPWidenInductionRecipe>(Op);
1152 if (VPValue *EndValue = EndValues.lookup(WideIV)) {
1153 R.getVPSingleValue()->replaceAllUsesWith(EndValue);
1154 R.eraseFromParent();
1155 }
1156 }
1157
1158 // Then, optimize exit block users.
1159 for (VPIRBasicBlock *ExitVPBB : Plan.getExitBlocks()) {
1160 for (VPIRPhi &ExitIRI : map_range(ExitVPBB->phis(), CastTo<VPIRPhi>)) {
1161 for (auto [Idx, PredVPBB] : enumerate(ExitVPBB->getPredecessors())) {
1162 VPValue *Escape = nullptr;
1163 if (PredVPBB == MiddleVPBB) {
1164 Escape = optimizeLatchExitInductionUser(Plan, ExitIRI.getOperand(Idx),
1165 EndValues, PSE);
1166 if (!Escape)
1168 Plan, ExitIRI.getOperand(Idx), PSE, ResumeTC, L);
1169 } else {
1170 Escape = optimizeEarlyExitInductionUser(Plan, ExitIRI.getOperand(Idx),
1171 PSE);
1172 }
1173 if (Escape)
1174 ExitIRI.setOperand(Idx, Escape);
1175 }
1176 }
1177 }
1178}
1179
1180/// Try to simplify logical and bitwise recipes in \p Def.
1182 VPValue *X;
1183
1184 // X | AllOnes -> AllOnes
1185 if (match(Def, m_c_BinaryOr(m_VPValue(X), m_AllOnes())))
1186 return Plan.getAllOnesValue(Def->getScalarType());
1187
1188 // X | 0 -> X
1189 if (match(Def, m_c_BinaryOr(m_VPValue(X), m_ZeroInt())))
1190 return X;
1191
1192 // X | !X -> AllOnes
1194 return Plan.getAllOnesValue(Def->getScalarType());
1195
1196 // X & 0 -> 0
1197 if (match(Def, m_c_BinaryAnd(m_VPValue(X), m_ZeroInt())))
1198 return Plan.getZero(Def->getScalarType());
1199
1200 // X & AllOnes -> X
1201 if (match(Def, m_c_BinaryAnd(m_VPValue(X), m_AllOnes())))
1202 return X;
1203
1204 // X && false -> false
1205 if (match(Def, m_c_LogicalAnd(m_VPValue(X), m_False())))
1206 return Plan.getFalse();
1207
1208 // X && true -> X
1209 if (match(Def, m_c_LogicalAnd(m_VPValue(X), m_True())))
1210 return X;
1211
1212 // X && (X && Y) -> X && Y
1213 if (match(Def, m_LogicalAnd(m_VPValue(X),
1215 return Def->getOperand(1);
1216
1217 // X && !X -> 0
1219 return Plan.getFalse();
1220
1221 if (match(Def, m_Select(m_VPValue(), m_VPValue(X), m_Deferred(X))))
1222 return X;
1223
1224 // X != false -> X
1226 assert(X->getScalarType()->isIntegerTy(1) && "must have boolean operands");
1227 return X;
1228 }
1229
1230 return nullptr;
1231}
1232
1233/// Swap the branch weights recorded for \p R, a select whose two selected
1234/// operands are being swapped,
1236 auto *MD = dyn_cast<VPIRMetadata>(&R);
1237 if (!MD)
1238 return;
1240 if (!extractBranchWeights(MD->getMetadata(LLVMContext::MD_prof), Weights))
1241 return;
1242 assert(Weights.size() == 2 && "unexpected branch weights");
1243 MD->setMetadata(
1244 LLVMContext::MD_prof,
1245 MDBuilder(Plan.getContext()).createBranchWeights(Weights[1], Weights[0]));
1246}
1247
1248/// Return an existing value or a live in for VPSingleDefRecipe \p Def if
1249/// possible. This shouldn't create or modify recipes.
1251 // Simplification of live-in IR values for SingleDef recipes using
1252 // InstSimplifyFolder.
1253 const DataLayout &DL = Plan.getDataLayout();
1254 if (VPValue *V = vputils::tryToFoldLiveIns(*Def, Def->operands(), DL))
1255 return V;
1256
1257 // Fold PredPHI LiveIn -> LiveIn.
1258 if (auto *PredPHI = dyn_cast<VPPredInstPHIRecipe>(Def)) {
1259 VPValue *Op = PredPHI->getOperand(0);
1260 if (isa<VPIRValue>(Op))
1261 return Op;
1262 }
1263
1264 if (VPValue *V = simplifyLogicalRecipe(Plan, Def))
1265 return V;
1266
1267 VPValue *A, *B;
1268
1269 // icmp Pred X, X -> true if Pred is true when equal, false otherwise.
1271 if (match(Def, m_ICmp(Pred, m_VPValue(A), m_Deferred(A))))
1272 return ICmpInst::isTrueWhenEqual(Pred) ? Plan.getTrue() : Plan.getFalse();
1273
1274 if (match(Def, m_c_Add(m_VPValue(A), m_ZeroInt())))
1275 return A;
1276
1277 if (match(Def, m_c_Mul(m_VPValue(A), m_One())))
1278 return A;
1279
1280 if (match(Def, m_c_Mul(m_VPValue(), m_ZeroInt())))
1281 return Plan.getZero(Def->getScalarType());
1282
1283 // A bitcast to the same type is a no-op.
1284 if (match(Def, m_BitCast(m_VPValue(A))) &&
1285 Def->getScalarType() == A->getScalarType())
1286 return A;
1287
1288 // Shifting by zero is a no-op.
1291 m_AShr(m_VPValue(A), m_ZeroInt())))))
1292 return A;
1293
1294 if (match(Def, m_Trunc(m_ZExtOrSExt(m_VPValue(A)))))
1295 if (Def->getScalarType() == A->getScalarType())
1296 return A;
1297
1298 if (match(Def, m_Not(m_Not(m_VPValue(A)))))
1299 return A;
1300
1301 // Remove redundant DerviedIVs, that is 0 + A * 1 -> A and 0 + 0 * x -> 0.
1302 if ((match(Def, m_DerivedIV(m_ZeroInt(), m_VPValue(A), m_One())) ||
1304 m_VPValue()))) &&
1305 A->getScalarType() == Def->getScalarType())
1306 return A;
1307
1308 // Look through ExtractLastLane.
1309 if (match(Def, m_ExtractLastLane(m_VPValue(A)))) {
1310 if (match(A, m_BuildVector())) {
1311 auto *BuildVector = cast<VPInstruction>(A);
1312 return BuildVector->getLastOperand();
1313 }
1314
1315 if (match(A, m_Broadcast(m_VPValue(B))))
1316 return B;
1317
1320 return A;
1321
1322 if (Plan.hasScalarVFOnly())
1323 return A;
1324 }
1325
1326 // Look through ExtractPenultimateElement (BuildVector ....).
1328 auto *BuildVector = cast<VPInstruction>(Def->getOperand(0));
1329 return BuildVector->getOperand(BuildVector->getNumOperands() - 2);
1330 }
1331
1332 uint64_t Idx;
1334 auto *BuildVector = cast<VPInstruction>(Def->getOperand(0));
1335 return BuildVector->getOperand(Idx);
1336 }
1337
1339 if (Def->getNumOperands() == 1) {
1340 return Def->getOperand(0);
1341 }
1342 if (auto *Phi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(Def)) {
1343 if (all_equal(Phi->incoming_values()))
1344 return Phi->getOperand(0);
1345 }
1346 return nullptr;
1347 }
1348
1349 VPIRValue *IRV;
1350 if (Def->getNumOperands() == 1 &&
1352 return IRV;
1353
1355 m_One())) &&
1356 A->getScalarType() == Def->getScalarType())
1357 return A;
1358
1359 // Replace extract-lane(0, canonical-WIDEN-INDUCTION) with the region's
1360 // scalar canonical IV.
1362 if (match(Def, m_ExtractLane(m_ZeroInt(), m_CanonicalWidenIV(WidenIV))))
1363 return WidenIV->getRegion()->getCanonicalIV();
1364
1365 // Some simplifications can only be applied after unrolling. Perform them
1366 // below.
1367 if (!Plan.isUnrolled())
1368 return nullptr;
1369
1370 // Simplify extracts of the same single-scalar.
1372 all_equal(drop_begin(Def->operands())) &&
1373 vputils::isSingleScalar(Def->getOperand(1)))
1374 return Def->getOperand(1);
1375
1376 // Simplify unrolled VectorPointer without offset, or with zero offset, to
1377 // just the pointer operand.
1378 if (auto *VPR = dyn_cast<VPVectorPointerRecipe>(Def))
1379 if (!VPR->getVFxPart() || match(VPR->getVFxPart(), m_ZeroInt()))
1380 return VPR->getOperand(0);
1381
1382 // VPScalarIVSteps after unrolling can be replaced by their start value, if
1383 // the start index is zero and only the first lane 0 is demanded.
1384 if (auto *Steps = dyn_cast<VPScalarIVStepsRecipe>(Def))
1385 if (!Steps->getStartIndex() && vputils::onlyFirstLaneUsed(Steps))
1386 return Steps->getOperand(0);
1387
1388 return nullptr;
1389}
1390
1391/// Returns true if \p V is available at the end of \p VPBB, i.e. it either is a
1392/// live-in from the original IR or defined in \p VPBB.
1393static bool isAvailableAtEndOf(VPValue *V, const VPBasicBlock *VPBB) {
1394 VPRecipeBase *DefR = V->getDefiningRecipe();
1395 return DefR ? DefR->getParent() == VPBB : isa<VPIRValue>(V);
1396}
1397
1398namespace {
1399/// Inserter for VPBuilderBase which appends all created VPSingleDefRecipes to a
1400/// worklist, so they get combined as well.
1401struct VPCombineInserter {
1402 SmallVectorImpl<VPSingleDefRecipe *> &Worklist;
1403
1404 void insertHelper(VPRecipeBase *R, VPBasicBlock::iterator It) {
1405 R->insertBefore(It);
1406 if (auto *Def = dyn_cast<VPSingleDefRecipe>(R))
1407 Worklist.push_back(Def);
1408 }
1409};
1410
1411using VPCombineBuilder = VPBuilderBase<VPCombineInserter>;
1412} // namespace
1413
1414/// Combine \p Def into a simpler recipe. May modify or create new recipes via
1415/// \p Builder.
1417 VPCombineBuilder &Builder) {
1418 if (auto *V = simplifyRecipe(Plan, Def)) {
1419 Def->replaceAllUsesWith(V);
1420 return Def;
1421 }
1422
1423 // Drop the mask of a predicated store masked by the header mask (which is
1424 // guaranteed to be true at least for the first lane) and both the stored
1425 // value and the address are uniform across VF and UF. The header mask is
1426 // still the abstract region value here.
1427 if (auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
1428 RepR && RepR->isPredicated() && RepR->getOpcode() == Instruction::Store &&
1429 all_of(RepR->operandsWithoutMask(), vputils::isUniformAcrossVFsAndUFs) &&
1430 match(RepR->getMask(), m_HeaderMask())) {
1431 auto *Unmasked = new VPReplicateRecipe(
1432 RepR->getUnderlyingInstr(), RepR->operandsWithoutMask(),
1433 RepR->isSingleScalar(), /*Mask=*/nullptr, *RepR, *RepR,
1434 RepR->getDebugLoc());
1435 Builder.insert(Unmasked);
1436 return Unmasked;
1437 }
1438
1439 // Avoid replacing VPInstructions with underlying values with new
1440 // VPInstructions, as we would fail to create widen/replicate recpes from the
1441 // new VPInstructions without an underlying value, and miss out on some
1442 // transformations that only apply to widened/replicated recipes later, by
1443 // doing so.
1444 // TODO: We should also not replace non-VPInstructions like VPWidenRecipe with
1445 // VPInstructions without underlying values, as those will get skipped during
1446 // cost computation.
1447 bool CanCreateNewRecipe =
1448 !isa<VPInstruction>(Def) || !Def->getUnderlyingValue();
1449
1450 VPValue *X, *Y, *Z;
1451
1452 // X && (Y && X) -> X && Y
1453 if (CanCreateNewRecipe &&
1456 return Builder.createLogicalAnd(X, Y);
1457
1458 // (X && Y) | (X && Z) -> X && (Y | Z)
1459 if (CanCreateNewRecipe &&
1462 // Simplify only if one of the operands has one use to avoid creating an
1463 // extra recipe.
1464 (!Def->getOperand(0)->hasMoreThanOneUniqueUser() ||
1465 !Def->getOperand(1)->hasMoreThanOneUniqueUser()))
1466 return Builder.createLogicalAnd(X, Builder.createOr(Y, Z));
1467
1468 // (X && Y) | !X -> !X || Y
1469 if (CanCreateNewRecipe &&
1470 match(Def,
1472 m_VPValue(Z, m_Not(m_Deferred(X))))))
1473 return Builder.createLogicalOr(Z, Y);
1474
1475 // (headermask && X) && Y -> headermask && (X && Y)
1476 // Keep the header mask outermost, so it can be simplified further when tail
1477 // folding, e.g. in optimizeEVLMasks.
1478 VPValue *HeaderMask;
1479 if (CanCreateNewRecipe &&
1480 match(Def,
1482 m_VPValue(X)),
1483 m_VPValue(Y))))
1484 return Builder.createLogicalAnd(HeaderMask, Builder.createLogicalAnd(X, Y));
1485
1486 // select C, false, true -> not C
1487 VPValue *C;
1488 if (CanCreateNewRecipe &&
1489 match(Def, m_Select(m_VPValue(C), m_False(), m_True())))
1490 return Builder.createNot(C);
1491
1492 // select !C, X, Y -> select C, Y, X
1493 if (match(Def, m_Select(m_Not(m_VPValue(C)), m_VPValue(X), m_VPValue(Y)))) {
1494 Def->setOperand(0, C);
1495 Def->setOperand(1, Y);
1496 Def->setOperand(2, X);
1497 swapSelectBranchWeights(*Def, Plan);
1498 return Def;
1499 }
1500
1501 // select X, (i1 Y | Z), Y -> Y | (X && Z)
1502 if (CanCreateNewRecipe &&
1503 match(Def, m_Select(m_VPValue(X),
1505 m_Deferred(Y))) &&
1506 Y->getScalarType()->isIntegerTy(1))
1507 return Builder.createOr(Y, Builder.createLogicalAnd(X, Z));
1508
1509 // select M0, (select M1, X, Y), Y -> select (M0 && M1), X, Y
1510 VPValue *Mask0, *Mask1;
1511 if (CanCreateNewRecipe &&
1512 match(Def,
1513 m_SelectLike(m_VPValue(Mask0),
1515 m_VPValue(Y))),
1516 m_Deferred(Y))))
1517 return Builder.createSelect(Builder.createLogicalAnd(Mask0, Mask1), X, Y,
1518 Def->getDebugLoc());
1519
1520 if (match(Def, m_Trunc(m_VPValue(Y, m_ZExtOrSExt(m_VPValue(X)))))) {
1521 // Don't replace a non-widened cast recipe with a widened cast.
1522 if (!isa<VPWidenCastRecipe>(Def))
1523 return nullptr;
1524 Type *TruncTy = Def->getScalarType();
1525 Type *XTy = X->getScalarType();
1526 if (XTy->getScalarSizeInBits() < TruncTy->getScalarSizeInBits()) {
1527
1528 unsigned ExtOpcode =
1529 match(Y, m_SExt(m_VPValue())) ? Instruction::SExt : Instruction::ZExt;
1530 auto *Ext =
1531 Builder.createWidenCast(Instruction::CastOps(ExtOpcode), X, TruncTy);
1532 if (auto *UnderlyingExt = Y->getUnderlyingValue()) {
1533 // UnderlyingExt has distinct return type, used to retain legacy cost.
1534 Ext->setUnderlyingValue(UnderlyingExt);
1535 }
1536 return Ext;
1537 } else if (XTy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits()) {
1538 auto *Trunc = Builder.createWidenCast(Instruction::Trunc, X, TruncTy);
1539 return Trunc;
1540 }
1541 }
1542
1543 if (CanCreateNewRecipe && match(Def, m_c_Mul(m_VPValue(X), m_AllOnes()))) {
1544 // Preserve nsw from the Mul on the new Sub.
1546 false, cast<VPRecipeWithIRFlags>(Def)->hasNoSignedWrap()};
1547 return Builder.createSub(Plan.getZero(X->getScalarType()), X,
1548 Def->getDebugLoc(), "", NW);
1549 }
1550
1551 if (CanCreateNewRecipe &&
1552 match(Def, m_c_Add(m_VPValue(X),
1553 m_VPValue(Z, m_Sub(m_ZeroInt(), m_VPValue(Y)))))) {
1554 // Preserve nsw from the Add and the Sub, if it's present on both, on the
1555 // new Sub.
1557 false, cast<VPRecipeWithIRFlags>(Def)->hasNoSignedWrap() &&
1558 cast<VPRecipeWithIRFlags>(Z)->hasNoSignedWrap()};
1559 return Builder.createSub(X, Y, Def->getDebugLoc(), "", NW);
1560 }
1561
1562 const APInt *APC;
1563 if (CanCreateNewRecipe && match(Def, m_URem(m_VPValue(X), m_APInt(APC))) &&
1564 APC->isPowerOf2())
1565 return Builder.createAnd(X, Plan.getConstantInt(*APC - 1),
1566 Def->getDebugLoc());
1567
1568 if (CanCreateNewRecipe && match(Def, m_c_Mul(m_VPValue(X), m_APInt(APC))) &&
1569 APC->isPowerOf2()) {
1570 auto *MulR = cast<VPRecipeWithIRFlags>(Def);
1571 unsigned ShiftAmt = APC->exactLogBase2();
1572 VPIRFlags::WrapFlagsTy NW(MulR->hasNoUnsignedWrap(),
1573 MulR->hasNoSignedWrap() &&
1574 ShiftAmt != APC->getBitWidth() - 1);
1575 return Builder.createNaryOp(
1576 Instruction::Shl,
1577 {X, Plan.getConstantInt(APC->getBitWidth(), ShiftAmt)}, NW,
1578 Def->getDebugLoc());
1579 }
1580
1581 if (CanCreateNewRecipe && match(Def, m_UDiv(m_VPValue(X), m_APInt(APC))) &&
1582 APC->isPowerOf2())
1583 return Builder.createNaryOp(
1584 Instruction::LShr,
1585 {X, Plan.getConstantInt(APC->getBitWidth(), APC->exactLogBase2())},
1586 *cast<VPRecipeWithIRFlags>(Def), Def->getDebugLoc());
1587
1588 // (X >> C) << C -> X & (-1 << C).
1589 if (CanCreateNewRecipe &&
1590 match(Def, m_Shl(m_LShr(m_VPValue(X), m_VPValue(Y, m_APInt(APC))),
1591 m_Deferred(Y))))
1592 return Builder.createAnd(
1593 X, Plan.getConstantInt(APInt::getAllOnes(APC->getBitWidth()) << *APC),
1594 Def->getDebugLoc());
1595
1596 if (match(Def, m_Not(m_VPValue(X)))) {
1597 // Try to fold Not into compares by adjusting the predicate in-place.
1599 if (match(X, m_Cmp(Pred, m_VPValue(), m_VPValue()))) {
1600 auto *Cmp = cast<VPRecipeWithIRFlags>(X);
1601 // Only fold if every user is a Not of the cmp, or a select using the cmp
1602 // solely as its condition.
1603 if (all_of(Cmp->users(), [Cmp](VPUser *U) {
1604 return match(U, m_Not(m_Specific(Cmp))) ||
1605 (match(U, m_Select(m_Specific(Cmp), m_VPValue(),
1606 m_VPValue())) &&
1607 U->getOperand(1) != Cmp && U->getOperand(2) != Cmp);
1608 })) {
1609 Cmp->setPredicate(CmpInst::getInversePredicate(Pred));
1610 for (VPSingleDefRecipe *R :
1612 if (match(R, m_Select(m_Specific(Cmp), m_VPValue(X), m_VPValue(Y)))) {
1613 // select (cmp pred), X, Y -> select (cmp inv_pred), Y, X
1614 R->setOperand(1, Y);
1615 R->setOperand(2, X);
1616 swapSelectBranchWeights(*R, Plan);
1617 } else {
1618 // not (cmp pred) -> cmp inv_pred
1619 assert(match(R, m_Not(m_Specific(Cmp))) && "Unexpected user");
1620 R->replaceAllUsesWith(Cmp);
1621 }
1622 }
1623 // If Cmp doesn't have a debug location, use the one from the negation,
1624 // to preserve the location.
1625 if (!Cmp->getDebugLoc() && Def->getDebugLoc())
1626 Cmp->setDebugLoc(Def->getDebugLoc());
1627 return Def;
1628 }
1629 }
1630 }
1631
1632 // Fold any-of (fcmp uno A, A), (fcmp uno B, B), ... ->
1633 // any-of (fcmp uno A, B), ...
1634 if (match(Def, m_AnyOf())) {
1636 VPRecipeBase *UnpairedCmp = nullptr;
1637 for (VPValue *Op : Def->operands()) {
1638 VPValue *X;
1639 if (Op->getNumUsers() > 1 ||
1641 m_Deferred(X)))) {
1642 NewOps.push_back(Op);
1643 } else if (!UnpairedCmp) {
1644 UnpairedCmp = Op->getDefiningRecipe();
1645 } else {
1646 NewOps.push_back(Builder.createFCmp(CmpInst::FCMP_UNO,
1647 UnpairedCmp->getOperand(0), X));
1648 UnpairedCmp = nullptr;
1649 }
1650 }
1651
1652 if (UnpairedCmp)
1653 NewOps.push_back(UnpairedCmp->getVPSingleValue());
1654
1655 if (NewOps.size() < Def->getNumOperands())
1656 return Builder.createNaryOp(VPInstruction::AnyOf, NewOps);
1657 }
1658
1659 // Fold (fcmp uno X, X) | (fcmp uno Y, Y) -> fcmp uno X, Y
1660 // This is useful for fmax/fmin without fast-math flags, where we need to
1661 // check if any operand is NaN.
1662 if (CanCreateNewRecipe &&
1664 m_Deferred(X)),
1666 m_Deferred(Y)))) &&
1667 X->getScalarType() == Y->getScalarType())
1668 return Builder.createFCmp(CmpInst::FCMP_UNO, X, Y);
1669
1671 m_One())) &&
1672 X->getScalarType() != Def->getScalarType())
1673 return Builder.createWidenCast(Instruction::Trunc, X, Def->getScalarType());
1674
1675 // For i1 vp.merges produced by AnyOf reductions:
1676 // vp.merge true, (or X, Y), X, evl -> vp.merge Y, true, X, evl
1678 m_VPValue(X), m_VPValue())) &&
1680 Def->getScalarType()->isIntegerTy(1)) {
1681 Def->setOperand(1, Plan.getTrue());
1682 Def->setOperand(0, Y);
1683 return Def;
1684 }
1685
1686 if (match(Def, m_BuildVector()) && all_equal(Def->operands()))
1687 return Builder.createNaryOp(VPInstruction::Broadcast, Def->getOperand(0));
1688
1689 // Replace uses of a BuildVector by users that only use its first lane with
1690 // its first operand directly.
1691 if (match(Def, m_BuildVector())) {
1692 Def->replaceUsesWithIf(Def->getOperand(0), [Def](VPUser *U) {
1693 return U->usesFirstLaneOnly(Def);
1694 });
1695 return Def;
1696 }
1697
1698 // Look through broadcast of single-scalar when used as select conditions; in
1699 // that case the scalar condition can be used directly.
1700 if (match(Def,
1703 "broadcast operand must be single-scalar");
1704 Def->setOperand(0, Z);
1705 return Def;
1706 }
1707
1708 if (match(Def, m_Broadcast(m_VPValue(X)))) {
1709 Def->replaceUsesWithIf(
1710 X, [Def](const VPUser *U) { return U->usesScalars(Def); });
1711 return Def;
1712 }
1713
1714 // Some simplifications can only be applied after unrolling. Perform them
1715 // below.
1716 if (!Plan.isUnrolled())
1717 return nullptr;
1718
1719 // Simplify extract-lane with single source to extract-element.
1720 VPValue *LaneToExtract;
1721 if (match(Def, m_ExtractLane(m_VPValue(LaneToExtract), m_VPValue(X))))
1722 return Builder.createNaryOp(Instruction::ExtractElement, {X, LaneToExtract},
1723 Def->getDebugLoc());
1724
1725 // Look for cycles where Def is of the form:
1726 // X = phi(0, IVInc) ; used only by IVInc, or by IVInc and Inc = X + Y
1727 // IVInc = X + Step ; used by X and Def
1728 // Def = IVInc + Y
1729 // Fold the increment Y into the phi's start value, replace Def with IVInc,
1730 // and if Inc exists, replace it with X.
1731 VPValue *IVInc;
1732 if (match(Def, m_Add(m_VPValue(IVInc, m_Add(m_VPValue(X), m_VPValue())),
1733 m_VPValue(Y))) &&
1734 match(X, m_VPPhi(m_ZeroInt(), m_Specific(IVInc))) &&
1735 IVInc->getNumUsers() == 2) {
1736 auto *Phi = cast<VPPhi>(X);
1737 // If Phi has a second user (besides IVInc's defining recipe), it must be
1738 // Inc = Phi + Y for the fold to apply.
1740 Phi, m_Add(m_Specific(Phi), m_Specific(Y)));
1741 if ((Phi->getNumUsers() == 1 || (Phi->getNumUsers() == 2 && Inc)) &&
1742 isAvailableAtEndOf(Y, Phi->getIncomingBlock(0))) {
1743 Def->replaceAllUsesWith(IVInc);
1744 if (Inc)
1745 Inc->replaceAllUsesWith(Phi);
1746 Phi->setOperand(0, Y);
1747 return Def;
1748 }
1749 }
1750
1751 // Simplify redundant ReductionStartVector recipes after unrolling.
1752 VPValue *StartV;
1754 m_VPValue(StartV), m_VPValue(), m_VPValue()))) {
1755 Def->replaceUsesWithIf(StartV, [](const VPUser *U) {
1756 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(U);
1757 return PhiR && PhiR->isInLoop();
1758 });
1759 return Def;
1760 }
1761
1762 return nullptr;
1763}
1764
1768 Plan.getEntry());
1770 for (VPSingleDefRecipe &Def :
1772 Worklist.push_back(&Def);
1773
1774 [[maybe_unused]] unsigned InitWorklistSize = Worklist.size();
1775
1776 VPCombineBuilder Builder({Worklist});
1777 while (!Worklist.empty()) {
1778 assert(Worklist.size() < InitWorklistSize * 2 &&
1779 "Worklist is growing large, possible cycle?");
1780 VPSingleDefRecipe *Def = Worklist.pop_back_val();
1781 Builder.setInsertPoint(Def);
1782 VPSingleDefRecipe *New = combineRecipe(Plan, Def, Builder);
1783 if (!New)
1784 continue;
1785 if (New != Def) {
1786 // Replace the recipe with a new one.
1787 Def->replaceAllUsesWith(New);
1788 Def->eraseFromParent();
1789 // TODO: Append users to the worklist (might need a setvector)
1790 } else if (vputils::isDeadRecipe(*Def)) {
1791 // Recipe was modified - it may be dead now.
1792 Def->eraseFromParent();
1793 }
1794 }
1795}
1796
1798 // Pull out reverses from any elementwise op.
1799 // binop(reverse(x), reverse(y)) -> reverse(binop(x,y))
1801 Plan, [](VPValue *&X) { return m_Reverse(m_VPValue(X)); },
1802 [](auto *X) { return new VPInstruction(VPInstruction::Reverse, X); });
1803
1804 // reverse(reverse(x)) -> x
1805 VPValue *X;
1808 for (VPRecipeBase &R : make_early_inc_range(*VPBB))
1809 if (match(&R, m_Reverse(m_Reverse(m_VPValue(X)))))
1810 R.getVPSingleValue()->replaceAllUsesWith(X);
1811}
1812
1813static std::optional<Instruction::BinaryOps>
1815 switch (ID) {
1816 case Intrinsic::masked_udiv:
1817 return Instruction::UDiv;
1818 case Intrinsic::masked_sdiv:
1819 return Instruction::SDiv;
1820 case Intrinsic::masked_urem:
1821 return Instruction::URem;
1822 case Intrinsic::masked_srem:
1823 return Instruction::SRem;
1824 default:
1825 return {};
1826 }
1827}
1828
1830 if (Plan.hasScalarVFOnly())
1831 return;
1832
1834 vp_depth_first_deep(Plan.getEntry()))) {
1835 for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB))) {
1838 continue;
1839 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
1840 if (RepR && (RepR->isSingleScalar() || RepR->isPredicated()))
1841 continue;
1842
1843 auto *RepOrWidenR = cast<VPRecipeWithIRFlags>(&R);
1844 if (RepR && RepR->getOpcode() == Instruction::Store &&
1845 vputils::isSingleScalar(RepR->getOperand(1))) {
1846 auto *Clone = new VPReplicateRecipe(
1847 RepOrWidenR->getUnderlyingInstr(), RepOrWidenR->operands(),
1848 true /*IsSingleScalar*/, nullptr /*Mask*/, *RepR /*Flags*/,
1849 *RepR /*Metadata*/, RepR->getDebugLoc());
1850 Clone->insertBefore(RepOrWidenR);
1851 VPBuilder Builder(Clone);
1852 VPValue *ExtractOp = Clone->getOperand(0);
1853 if (vputils::isUniformAcrossVFsAndUFs(RepR->getOperand(1)))
1854 ExtractOp =
1855 Builder.createNaryOp(VPInstruction::ExtractLastPart, ExtractOp);
1856 ExtractOp =
1857 Builder.createNaryOp(VPInstruction::ExtractLastLane, ExtractOp);
1858 Clone->setOperand(0, ExtractOp);
1859 RepR->eraseFromParent();
1860 continue;
1861 }
1862
1863 // Narrow llvm.masked.{u,s}{div,rem} intrinsics with a safe divisor.
1864 if (auto *IntrR = dyn_cast<VPWidenIntrinsicRecipe>(RepOrWidenR)) {
1865 if (!vputils::onlyFirstLaneUsed(IntrR))
1866 continue;
1867 auto Opc = getUnmaskedDivRemOpcode(IntrR->getVectorIntrinsicID());
1868 if (!Opc)
1869 continue;
1870 VPBuilder Builder(IntrR);
1871 VPValue *SafeDivisor = Builder.createSelect(
1872 IntrR->getOperand(2), IntrR->getOperand(1),
1873 Plan.getConstantInt(IntrR->getScalarType(), 1));
1874 VPValue *Clone = Builder.createNaryOp(
1875 *Opc, {IntrR->getOperand(0), SafeDivisor},
1876 VPIRFlags::getDefaultFlags(*Opc), IntrR->getDebugLoc());
1877 IntrR->replaceAllUsesWith(Clone);
1878 IntrR->eraseFromParent();
1879 continue;
1880 }
1881
1882 // Skip recipes that aren't single scalars or have no underlying
1883 // instruction to create a single-scalar recipe from.
1884 if (!RepOrWidenR->getUnderlyingValue() ||
1885 !vputils::isSingleScalar(RepOrWidenR))
1886 continue;
1887
1888 // Predicate to check if a user of Op introduces extra broadcasts.
1889 auto IntroducesBCastOf = [](const VPValue *Op) {
1890 return [Op](const VPUser *U) {
1891 if (auto *VPI = dyn_cast<VPInstruction>(U)) {
1895 VPI->getOpcode()))
1896 return false;
1897 }
1898 return !U->usesScalars(Op);
1899 };
1900 };
1901
1902 if (any_of(RepOrWidenR->users(), IntroducesBCastOf(RepOrWidenR)) &&
1903 none_of(RepOrWidenR->operands(), [&](VPValue *Op) {
1904 if (any_of(
1905 make_filter_range(Op->users(), not_equal_to(RepOrWidenR)),
1906 IntroducesBCastOf(Op)))
1907 return false;
1908 // Non-constant live-ins require broadcasts, while constants do not
1909 // need explicit broadcasts.
1910 bool LiveInNeedsBroadcast =
1911 isa<VPIRValue>(Op) && !isa<VPConstant>(Op);
1912 auto *OpR = dyn_cast<VPReplicateRecipe>(Op);
1913 return LiveInNeedsBroadcast || (OpR && OpR->isSingleScalar());
1914 }))
1915 continue;
1916
1917 auto *Clone = VPBuilder::createSingleScalarOp(
1918 vputils::getOpcode(RepOrWidenR), RepOrWidenR->operands(),
1919 /*Mask=*/nullptr, *RepOrWidenR, getMetadataOf(RepOrWidenR),
1920 DebugLoc::getUnknown(), RepOrWidenR->getScalarType(),
1921 RepOrWidenR->getUnderlyingInstr());
1922 Clone->insertBefore(RepOrWidenR);
1923 RepOrWidenR->replaceAllUsesWith(Clone);
1924 if (vputils::isDeadRecipe(*RepOrWidenR))
1925 RepOrWidenR->eraseFromParent();
1926 }
1927 }
1928}
1929
1930/// Try to see if all of \p Blend's masks share a common value logically and'ed
1931/// and remove it from the masks.
1933 if (Blend->isNormalized())
1934 return;
1935 VPValue *CommonEdgeMask;
1936 if (!match(Blend->getMask(0),
1937 m_LogicalAnd(m_VPValue(CommonEdgeMask), m_VPValue())))
1938 return;
1939 for (unsigned I = 0; I < Blend->getNumIncomingValues(); I++)
1940 if (!match(Blend->getMask(I),
1941 m_LogicalAnd(m_Specific(CommonEdgeMask), m_VPValue())))
1942 return;
1943 for (unsigned I = 0; I < Blend->getNumIncomingValues(); I++)
1944 Blend->setMask(I, Blend->getMask(I)->getDefiningRecipe()->getOperand(1));
1945}
1946
1947/// Normalize and simplify VPBlendRecipes. Should be run after combineRecipes
1948/// to make sure the masks are simplified.
1949static void simplifyBlends(VPlan &Plan) {
1952 for (VPBlendRecipe &Blend :
1954 removeCommonBlendMask(&Blend);
1955
1956 // Try to remove redundant blend recipes.
1957 SmallPtrSet<VPValue *, 4> UniqueValues;
1958 if (Blend.isNormalized() || !match(Blend.getMask(0), m_False()))
1959 UniqueValues.insert(Blend.getIncomingValue(0));
1960 for (unsigned I = 1; I != Blend.getNumIncomingValues(); ++I)
1961 if (!match(Blend.getMask(I), m_False()))
1962 UniqueValues.insert(Blend.getIncomingValue(I));
1963
1964 if (UniqueValues.size() == 1) {
1965 Blend.replaceAllUsesWith(*UniqueValues.begin());
1966 Blend.eraseFromParent();
1967 continue;
1968 }
1969
1970 if (Blend.isNormalized())
1971 continue;
1972
1973 // Normalize the blend so its first incoming value is used as the initial
1974 // value with the others blended into it.
1975
1976 unsigned StartIndex = 0;
1977 for (unsigned I = 0; I != Blend.getNumIncomingValues(); ++I) {
1978 // If a value's mask is used only by the blend then is can be deadcoded.
1979 // TODO: Find the most expensive mask that can be deadcoded, or a mask
1980 // that's used by multiple blends where it can be removed from them all.
1981 VPValue *Mask = Blend.getMask(I);
1982 if (Mask->hasOneUse() && !match(Mask, m_False())) {
1983 StartIndex = I;
1984 break;
1985 }
1986 }
1987
1988 SmallVector<VPValue *, 4> OperandsWithMask;
1989 OperandsWithMask.push_back(Blend.getIncomingValue(StartIndex));
1990
1991 for (unsigned I = 0; I != Blend.getNumIncomingValues(); ++I) {
1992 if (I == StartIndex)
1993 continue;
1994 OperandsWithMask.push_back(Blend.getIncomingValue(I));
1995 OperandsWithMask.push_back(Blend.getMask(I));
1996 }
1997
1998 auto *NewBlend =
1999 new VPBlendRecipe(cast_or_null<PHINode>(Blend.getUnderlyingValue()),
2000 OperandsWithMask, Blend, Blend.getDebugLoc());
2001 NewBlend->insertBefore(&Blend);
2002
2003 VPValue *DeadMask = Blend.getMask(StartIndex);
2004 Blend.replaceAllUsesWith(NewBlend);
2005 Blend.eraseFromParent();
2007
2008 /// Simplify BLEND %a, %b, Not(%mask) -> BLEND %b, %a, %mask.
2009 VPValue *NewMask;
2010 if (NewBlend->getNumOperands() == 3 &&
2011 match(NewBlend->getMask(1), m_Not(m_VPValue(NewMask)))) {
2012 VPValue *Inc0 = NewBlend->getOperand(0);
2013 VPValue *Inc1 = NewBlend->getOperand(1);
2014 VPValue *OldMask = NewBlend->getOperand(2);
2015 NewBlend->setOperand(0, Inc1);
2016 NewBlend->setOperand(1, Inc0);
2017 NewBlend->setOperand(2, NewMask);
2018 if (OldMask->user_empty())
2019 cast<VPInstruction>(OldMask)->eraseFromParent();
2020 }
2021 }
2022 }
2023}
2024
2025/// Optimize the width of vector induction variables in \p Plan based on a known
2026/// constant Trip Count, \p BestVF and \p BestUF.
2028 ElementCount BestVF,
2029 unsigned BestUF) {
2030 // Only proceed if we have not completely removed the vector region.
2031 if (!Plan.getVectorLoopRegion())
2032 return false;
2033
2034 const APInt *TC;
2035 if (!BestVF.isFixed() || !match(Plan.getTripCount(), m_APInt(TC)))
2036 return false;
2037
2038 // Calculate the minimum power-of-2 bit width that can fit the known TC, VF
2039 // and UF. Returns at least 8.
2040 auto ComputeBitWidth = [](APInt TC, uint64_t Align) {
2041 APInt AlignedTC =
2044 APInt MaxVal = AlignedTC - 1;
2045 return std::max<unsigned>(PowerOf2Ceil(MaxVal.getActiveBits()), 8);
2046 };
2047 unsigned NewBitWidth =
2048 ComputeBitWidth(*TC, BestVF.getKnownMinValue() * BestUF);
2049
2050 LLVMContext &Ctx = Plan.getContext();
2051 auto *NewIVTy = IntegerType::get(Ctx, NewBitWidth);
2052
2053 bool MadeChange = false;
2054
2055 VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
2056 for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
2057 // Currently only handle canonical IVs as it is trivial to replace the start
2058 // and stop values, and we currently only perform the optimization when the
2059 // IV has a single use.
2061 if (!match(&Phi, m_CanonicalWidenIV(WideIV)))
2062 continue;
2063 if (WideIV->hasMoreThanOneUniqueUser() ||
2064 NewIVTy == WideIV->getScalarType())
2065 continue;
2066
2067 // Currently only handle cases where the single user is a header-mask
2068 // comparison with the backedge-taken-count, TC - 1.
2069 VPUser *SingleUser = WideIV->getSingleUser();
2070 VPValue *BTC;
2071 if (!SingleUser ||
2072 !match(
2073 SingleUser,
2074 m_ICmp(m_Specific(WideIV),
2076 BTC, m_Sub(m_Specific(Plan.getTripCount()), m_One()))))))
2077 continue;
2078
2079 // Update IV operands and comparison bound to use new narrower type.
2080 assert(!WideIV->isTruncated() &&
2081 "canonical IV is not expected to have a truncation");
2082 auto *NewWideIV = new VPWidenIntOrFpInductionRecipe(
2083 WideIV->getPHINode(), Plan.getZero(NewIVTy),
2084 Plan.getConstantInt(NewIVTy, 1), WideIV->getVFValue(),
2085 WideIV->getInductionDescriptor(), *WideIV, WideIV->getDebugLoc());
2086 NewWideIV->insertBefore(WideIV);
2087
2088 auto *NewBTC =
2089 new VPWidenCastRecipe(Instruction::Trunc, BTC, NewIVTy, nullptr,
2090 VPIRFlags::getDefaultFlags(Instruction::Trunc));
2091 Plan.getVectorPreheader()->appendRecipe(NewBTC);
2092 auto *Cmp = cast<VPInstruction>(WideIV->getSingleUser());
2093 Cmp->replaceAllUsesWith(
2094 VPBuilder(Cmp).createICmp(Cmp->getPredicate(), NewWideIV, NewBTC));
2095
2096 MadeChange = true;
2097 }
2098
2099 return MadeChange;
2100}
2101
2102/// Return true if \p Cond is known to be true for given \p BestVF and \p
2103/// BestUF.
2105 ElementCount BestVF, unsigned BestUF,
2108 return any_of(Cond->getDefiningRecipe()->operands(), [&Plan, BestVF, BestUF,
2109 &PSE](VPValue *C) {
2110 return isConditionTrueViaVFAndUF(C, Plan, BestVF, BestUF, PSE);
2111 });
2112
2113 auto *CanIV = Plan.getVectorLoopRegion()->getCanonicalIV();
2116 m_c_Add(m_Specific(CanIV), m_Specific(&Plan.getVFxUF())),
2117 m_Specific(&Plan.getVectorTripCount()))))
2118 return false;
2119
2120 // The compare checks CanIV + VFxUF == vector trip count. The vector trip
2121 // count is not conveniently available as SCEV so far, so we compare directly
2122 // against the original trip count. This is stricter than necessary, as we
2123 // will only return true if the trip count == vector trip count.
2124 const SCEV *VectorTripCount =
2126 if (isa<SCEVCouldNotCompute>(VectorTripCount))
2127 VectorTripCount = vputils::getSCEVExprForVPValue(Plan.getTripCount(), PSE);
2128 assert(!isa<SCEVCouldNotCompute>(VectorTripCount) &&
2129 "Trip count SCEV must be computable");
2130 ScalarEvolution &SE = *PSE.getSE();
2131 ElementCount NumElements = BestVF * BestUF;
2132 const SCEV *C = SE.getElementCount(VectorTripCount->getType(), NumElements);
2133 return SE.isKnownPredicate(CmpInst::ICMP_EQ, VectorTripCount, C);
2134}
2135
2136// Replaces ExtractVectorForPart instructions with ICMP when the VF is scalar
2137// and the source is a WideActiveLaneMask. The unused mask is removed later
2138// when removing dead recipes.
2140 ElementCount BestVF) {
2141 if (!BestVF.isScalar())
2142 return false;
2143
2144 bool MadeChange = false;
2145 VPBuilder Builder;
2146
2147 VPValue *Start, *TC;
2148 uint64_t Idx;
2150 vp_depth_first_deep(Plan.getEntry()))) {
2151 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
2154 m_VPValue()),
2155 m_ConstantInt(Idx))))
2156 continue;
2157
2158 auto *Extract = cast<VPInstruction>(&R);
2159 Builder.setInsertPoint(Extract);
2160
2161 if (Idx > 0)
2162 Start = Builder.createAdd(
2163 Start, Plan.getConstantInt(Start->getScalarType(), Idx));
2164
2165 VPValue *ICmp = Builder.createICmp(CmpInst::ICMP_ULT, Start, TC);
2166 Extract->replaceAllUsesWith(ICmp);
2167 Extract->eraseFromParent();
2168 MadeChange = true;
2169 }
2170 }
2171
2172 return MadeChange;
2173}
2174
2175/// Return true if the branch \p Term with condition \p Cond (null if \p Term
2176/// has no condition operand) is the vector loop's latch check.
2177static bool isVectorLatchCheck(VPRecipeBase *Term, VPValue *Cond, VPlan &Plan) {
2178 // BranchOnCount compares the canonical IV increment against the vector trip
2179 // count, plus an offset for epilogue loops.
2180 VPValue *Offset = nullptr;
2181 auto m_CanIVInc = m_Add(m_VPValue(), m_Specific(&Plan.getVFxUF()));
2182 if (match(Term,
2184 m_CombineOr(m_CanIVInc, m_c_Add(m_CanIVInc, m_VPValue(Offset))),
2185 m_VPValue())))
2186 return !Offset || Offset->isDefinedOutsideLoopRegions();
2187
2188 if (!Cond)
2189 return false;
2190
2191 // The active-lane-mask form used when the tail is folded by masking.
2192 return match(Cond,
2195 m_ZeroInt()))));
2196}
2197
2198/// Try to simplify the branch condition of \p Plan. This may restrict the
2199/// resulting plan to \p BestVF and \p BestUF.
2201 unsigned BestUF,
2203 VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
2204 VPBasicBlock *ExitingVPBB = VectorRegion->getExitingBasicBlock();
2205 auto *Term = &ExitingVPBB->back();
2206
2207 // Find the branch condition, if there is one.
2208 VPValue *Cond = nullptr;
2209 if (!match(Term, m_BranchOnCond(m_VPValue(Cond))))
2211
2212 if (isVectorLatchCheck(Term, Cond, Plan)) {
2213 // Try to simplify the branch condition if VectorTC <= VF * UF when the
2214 // latch terminator is BranchOnCount or
2215 // BranchOnCond(Not(ExtractVectorForPart(WideActiveLaneMask), 0))
2216 const SCEV *VectorTripCount =
2218 if (isa<SCEVCouldNotCompute>(VectorTripCount))
2219 VectorTripCount =
2221 assert(!isa<SCEVCouldNotCompute>(VectorTripCount) &&
2222 "Trip count SCEV must be computable");
2223 ScalarEvolution &SE = *PSE.getSE();
2224 ElementCount NumElements = BestVF * BestUF;
2225 const SCEV *C = SE.getElementCount(VectorTripCount->getType(), NumElements);
2226 if (!SE.isKnownPredicate(CmpInst::ICMP_ULE, VectorTripCount, C))
2227 return false;
2228 } else if (!Cond ||
2229 !isConditionTrueViaVFAndUF(Cond, Plan, BestVF, BestUF, PSE)) {
2230 return false;
2231 }
2232
2233 // The vector loop region only executes once. Convert terminator of the
2234 // exiting block to exit in the first iteration.
2235 if (match(Term, m_BranchOnTwoConds())) {
2236 Term->setOperand(1, Plan.getTrue());
2237 return true;
2238 }
2239
2240 auto *BOC = new VPInstruction(VPInstruction::BranchOnCond, Plan.getTrue(), {},
2241 {}, Term->getDebugLoc());
2242 ExitingVPBB->appendRecipe(BOC);
2243 Term->eraseFromParent();
2244
2245 return true;
2246}
2247
2249 unsigned BestUF,
2251 assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
2252 assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
2253
2254 bool MadeChange =
2255 simplifyBranchConditionForVFAndUF(Plan, BestVF, BestUF, PSE);
2256 MadeChange |= replaceMaskWithCompareForScalarPlan(Plan, BestVF);
2257 MadeChange |= optimizeVectorInductionWidthForTCAndVFUF(Plan, BestVF, BestUF);
2258
2259 if (MadeChange) {
2260 Plan.setVF(BestVF);
2261 assert(Plan.getConcreteUF() == BestUF && "BestUF must match the Plan's UF");
2262 }
2263}
2264
2268 RecurKind RK = PhiR.getRecurrenceKind();
2269 if (RK != RecurKind::Add && RK != RecurKind::Mul && RK != RecurKind::Sub &&
2271 continue;
2272
2274 if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(U)) {
2275 RecWithFlags->dropPoisonGeneratingFlags();
2276 }
2277 }
2278}
2279
2281 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(R))
2282 return MemR->getAlign();
2283 return cast<LoadInst>(R->getUnderlyingInstr())->getAlign();
2284}
2285
2286namespace {
2287struct VPCSEDenseMapInfo : public DenseMapInfo<VPSingleDefRecipe *> {
2288 /// If recipe \p R will lower to a GEP with a non-i8 source element type,
2289 /// return that source element type.
2290 static Type *getGEPSourceElementType(const VPSingleDefRecipe *R) {
2291 // All VPInstructions that lower to GEPs must have the i8 source element
2292 // type (as they are PtrAdds), so we omit it.
2293 return TypeSwitch<const VPSingleDefRecipe *, Type *>(R)
2294 .Case([](const VPReplicateRecipe *I) -> Type * {
2295 if (auto *GEP = dyn_cast<GetElementPtrInst>(I->getUnderlyingValue()))
2296 return GEP->getSourceElementType();
2297 return nullptr;
2298 })
2299 .Case<VPVectorPointerRecipe, VPWidenGEPRecipe>(
2300 [](auto *I) { return I->getSourceElementType(); })
2301 .Default([](auto *) { return nullptr; });
2302 }
2303
2304 /// Returns true if recipe \p Def can be safely handed for CSE.
2305 static bool canHandle(const VPSingleDefRecipe *Def) {
2306 // We can extend the list of handled recipes in the future,
2307 // provided we account for the data embedded in them while checking for
2308 // equality or hashing.
2310
2311 // Allocas must not be merged, as each creates a distinct allocation.
2312 if (!C || (!C->first && C->second == Instruction::Alloca))
2313 return false;
2314
2315 // Loads are handled as cse() only reuses them within a block with no
2316 // intervening memory write. Any other memory access is rejected.
2317 if (Def->mayWriteToMemory())
2318 return false;
2319 return !Def->mayReadFromMemory() ||
2320 (!C->first && C->second == Instruction::Load);
2321 }
2322
2323 /// Hash the underlying data of \p Def.
2324 static unsigned getHashValue(const VPSingleDefRecipe *Def) {
2325 hash_code Result = hash_combine(
2326 Def->getVPRecipeID(), vputils::getOpcodeOrIntrinsicID(Def),
2327 getGEPSourceElementType(Def), Def->getScalarType(),
2329 if (auto *RFlags = dyn_cast<VPRecipeWithIRFlags>(Def))
2330 if (RFlags->hasPredicate())
2331 return hash_combine(Result, RFlags->getPredicate());
2332 if (auto *SIVSteps = dyn_cast<VPScalarIVStepsRecipe>(Def))
2333 return hash_combine(Result, SIVSteps->getInductionOpcode());
2334 if (auto *DIV = dyn_cast<VPDerivedIVRecipe>(Def))
2335 return hash_combine(Result, DIV->getInductionKind(), DIV->getFPBinOp());
2336 // Fold in the separately stored consecutive flag. Alignment is left out and
2337 // handled by cse.
2338 if (auto *Load = dyn_cast<VPWidenMemoryRecipe>(Def))
2339 return hash_combine(Result, Load->isConsecutive());
2340 if (auto *ExpSCEV = dyn_cast<VPExpandSCEVRecipe>(Def))
2341 return hash_combine(Result, ExpSCEV->getSCEV());
2342 return Result;
2343 }
2344
2345 /// Check equality of underlying data of \p L and \p R.
2346 static bool isEqual(const VPSingleDefRecipe *L, const VPSingleDefRecipe *R) {
2347 if (L->getVPRecipeID() != R->getVPRecipeID() ||
2350 getGEPSourceElementType(L) != getGEPSourceElementType(R) ||
2352 !equal(L->operands(), R->operands()))
2353 return false;
2356 "must have valid opcode info for both recipes");
2357 if (auto *LFlags = dyn_cast<VPRecipeWithIRFlags>(L))
2358 if (LFlags->hasPredicate() &&
2359 LFlags->getPredicate() !=
2360 cast<VPRecipeWithIRFlags>(R)->getPredicate())
2361 return false;
2362 if (auto *LSIV = dyn_cast<VPScalarIVStepsRecipe>(L))
2363 if (LSIV->getInductionOpcode() !=
2364 cast<VPScalarIVStepsRecipe>(R)->getInductionOpcode())
2365 return false;
2366 if (auto *LDIV = dyn_cast<VPDerivedIVRecipe>(L)) {
2367 auto *RDIV = cast<VPDerivedIVRecipe>(R);
2368 if (LDIV->getInductionKind() != RDIV->getInductionKind() ||
2369 LDIV->getFPBinOp() != RDIV->getFPBinOp())
2370 return false;
2371 }
2372 // Compare the separately stored consecutive flag. Alignment is left out and
2373 // handled by cse.
2374 if (auto *LL = dyn_cast<VPWidenMemoryRecipe>(L))
2375 if (LL->isConsecutive() != cast<VPWidenMemoryRecipe>(R)->isConsecutive())
2376 return false;
2377 // Whether to expand in IR is left out and handled by cse.
2378 if (auto *LExp = dyn_cast<VPExpandSCEVRecipe>(L))
2379 if (LExp->getSCEV() != cast<VPExpandSCEVRecipe>(R)->getSCEV())
2380 return false;
2381 // Phi recipes can only be equal if they are in the same VPBB, as they
2382 // implicitly depend on their predecessors.
2383 if (isa<VPWidenPHIRecipe>(L) && L->getParent() != R->getParent())
2384 return false;
2385 // Recipes in replicate regions implicitly depend on predicate. If either
2386 // recipe is in a replicate region, only consider them equal if both have
2387 // the same parent.
2388 const VPRegionBlock *RegionL = L->getRegion();
2389 const VPRegionBlock *RegionR = R->getRegion();
2390 if (((RegionL && RegionL->isReplicator()) ||
2391 (RegionR && RegionR->isReplicator())) &&
2392 L->getParent() != R->getParent())
2393 return false;
2394 return L->getScalarType() == R->getScalarType();
2395 }
2396};
2397} // end anonymous namespace
2398
2399/// Perform a common-subexpression-elimination of VPSingleDefRecipes on the \p
2400/// Plan.
2403 // CSE map for loads. Must be cleared on recipes that may write to memory, and
2404 // at the end of each VPBB.
2406 LoadCSEMap;
2407
2409 Plan.getEntry());
2411 for (VPRecipeBase &R : *VPBB) {
2412 if (R.mayWriteToMemory())
2413 LoadCSEMap.clear();
2414 auto *Def = dyn_cast<VPSingleDefRecipe>(&R);
2415 if (!Def || !VPCSEDenseMapInfo::canHandle(Def))
2416 continue;
2417 bool IsLoad = vputils::getOpcode(Def) == Instruction::Load;
2418 auto [It, Inserted] =
2419 (IsLoad ? LoadCSEMap : CSEMap).try_emplace(Def, Def);
2420 if (Inserted)
2421 continue;
2422 VPSingleDefRecipe *V = It->second;
2423 // V must dominate Def for a valid replacement.
2424 if (!VPDT.dominates(V->getParent(), VPBB))
2425 continue;
2426 if (IsLoad) {
2427 if (getLoadAlign(V) < getLoadAlign(Def)) {
2428 // Record Def as the candidate for subsequent loads, as it may be
2429 // reusable where V is not.
2430 It->second = Def;
2431 continue;
2432 }
2433 // Keep only metadata common to both loads on the survivor.
2434 cast<VPIRMetadata>(V)->intersect(*cast<VPIRMetadata>(Def));
2435 }
2436 // Only expansions in IR can replace expansions in IR.
2437 auto *DefExp = dyn_cast<VPExpandSCEVRecipe>(Def);
2438 if (DefExp && DefExp->expandInIR() &&
2439 !cast<VPExpandSCEVRecipe>(V)->expandInIR()) {
2440 It->second = Def;
2441 continue;
2442 }
2443 // Only keep flags present on both V and Def.
2444 if (auto *RFlags = dyn_cast<VPRecipeWithIRFlags>(V))
2445 RFlags->intersectFlags(*cast<VPRecipeWithIRFlags>(Def));
2446 // Only keep call attributes valid for both V and Def.
2447 if (auto *Call = dyn_cast<VPWidenCallRecipe>(V))
2448 Call->intersectAttrs(*cast<VPWidenCallRecipe>(Def), Plan.getContext());
2449 Def->replaceAllUsesWith(V);
2450 // Reset Plan's TC when TC expressions are CSE'd.
2451 if (Def == Plan.getTripCount())
2452 Plan.resetTripCount(V);
2453 }
2454 LoadCSEMap.clear();
2455 }
2456}
2457
2458/// Return true if we do not know how to (mechanically) hoist or sink a
2459/// non-memory or memory recipe \p R out of a loop region. When sinking, passing
2460/// \p Sinking = true ensures that assumes aren't sunk.
2462 VPBasicBlock *LastBB,
2463 bool Sinking = false) {
2464 if (!isa<VPReplicateRecipe>(R) || !R.mayReadOrWriteMemory() ||
2466 return vputils::cannotHoistOrSinkRecipe(R, Sinking);
2467
2468 // TODO: Support outer-loop plans. Their loop region need not form a
2469 // single-successor chain, which the alias check below expects, and sinking
2470 // only supports stores with an invariant address.
2471 if (FirstBB->getPlan()->isOuterLoop())
2472 return true;
2473
2474 // Check that the memory operation doesn't alias between FirstBB and LastBB.
2475 auto MemLoc = vputils::getMemoryLocation(R);
2476
2477 // TODO: Could make use of SinkStoreInfo::isNoAliasViaDistance by collecting
2478 // stores upfront, and constructing a full SinkStoreInfo.
2479 auto SinkInfo =
2480 Sinking ? std::make_optional(SinkStoreInfo(cast<VPReplicateRecipe>(R)))
2481 : std::nullopt;
2482
2483 return !MemLoc ||
2484 !canHoistOrSinkWithNoAliasCheck(*MemLoc, FirstBB, LastBB, SinkInfo);
2485}
2486
2487/// Move loop-invariant recipes out of the vector loop region in \p Plan.
2488static void licm(VPlan &Plan, const VPDominatorTree &VPDT) {
2489 VPBasicBlock *Preheader = Plan.getVectorPreheader();
2490
2491 // Hoist any loop invariant recipes from the vector loop region to the
2492 // preheader. Perform a shallow traversal of the vector loop region, to
2493 // exclude recipes in replicate regions. Only hoist from blocks dominating the
2494 // exiting block, which are guaranteed to execute if the vector pre-header is,
2495 // so we don't need to check speculation safety.
2496 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
2497 assert(Preheader->getSingleSuccessor() == LoopRegion &&
2498 "Expected vector prehader's successor to be the vector loop region");
2499 VPBasicBlock *ExitingVPBB = LoopRegion->getExitingBasicBlock();
2501 vp_depth_first_shallow(LoopRegion->getEntry()))) {
2502 if (!VPDT.dominates(VPBB, ExitingVPBB))
2503 continue;
2504 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
2505 if (any_of(R.operands(), [](VPValue *Op) {
2506 return !Op->isDefinedOutsideLoopRegions();
2507 }))
2508 continue;
2509 if (cannotHoistOrSinkRecipe(R, LoopRegion->getEntryBasicBlock(),
2510 LoopRegion->getExitingBasicBlock()))
2511 continue;
2512 R.moveBefore(Preheader->end());
2513 }
2514 }
2515
2516 // Sink recipes with no users inside the vector loop region if all users are
2517 // in the same exit block of the region.
2518 // TODO: Extend to sink recipes from inner loops.
2520 LoopRegion->getEntry());
2522 for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB))) {
2523 // TODO: Use R.definedValues() instead of casting to VPSingleDefRecipe to
2524 // support recipes with multiple defined values (e.g., interleaved loads).
2525 auto *Def = dyn_cast<VPSingleDefRecipe>(&R);
2526 if (!Def)
2527 continue;
2528
2529 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
2530 assert(!RepR->isPredicated() &&
2531 "Expected prior transformation of predicated replicates to "
2532 "replicate regions");
2533 // narrowToSingleScalarRecipes should have already maximally narrowed
2534 // replicates to single-scalar replicates.
2535 // TODO: When unrolling, replicateByVF doesn't handle sunk
2536 // non-single-scalar replicates correctly.
2537 if (!RepR->isSingleScalar())
2538 continue;
2539
2540 // The pointer operand of stores must be loop-invariant.
2541 if (RepR->getOpcode() == Instruction::Store &&
2542 !RepR->getOperand(1)->isDefinedOutsideLoopRegions())
2543 continue;
2544 }
2545
2546 // Cannot sink the recipe if the user is defined in a loop region or a
2547 // non-successor of the vector loop region. Cannot sink if user is a phi
2548 // either.
2549 VPBasicBlock *SinkBB = nullptr;
2550 if (any_of(Def->users(), [&SinkBB, &LoopRegion](VPUser *U) {
2551 auto *UserR = cast<VPRecipeBase>(U);
2552 VPBasicBlock *Parent = UserR->getParent();
2553 // TODO: Support sinking when users are in multiple blocks.
2554 if (SinkBB && SinkBB != Parent)
2555 return true;
2556 SinkBB = Parent;
2557 // TODO: If the user is a PHI node, we should check the block of
2558 // incoming value. Support PHI node users if needed.
2559 return UserR->isPhi() || Parent->getEnclosingLoopRegion() ||
2560 Parent->getSinglePredecessor() != LoopRegion;
2561 }))
2562 continue;
2563
2564 if (cannotHoistOrSinkRecipe(R, LoopRegion->getEntryBasicBlock(),
2565 LoopRegion->getExitingBasicBlock(),
2566 /*Sinking=*/true))
2567 continue;
2568
2569 [[maybe_unused]] auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
2570 assert((!R.mayWriteToMemory() ||
2571 (RepR && RepR->getOpcode() == Instruction::Store &&
2572 RepR->getOperand(1)->isDefinedOutsideLoopRegions())) &&
2573 "The only recipes that may write to memory are expected to be "
2574 "stores with invariant pointer-operand");
2575
2576 if (!SinkBB)
2577 SinkBB = cast<VPBasicBlock>(LoopRegion->getSingleSuccessor());
2578
2579 // TODO: This will need to be a check instead of a assert after
2580 // conditional branches in vectorized loops are supported.
2581 assert(VPDT.properlyDominates(VPBB, SinkBB) &&
2582 "Defining block must dominate sink block");
2583 // TODO: Clone the recipe if users are on multiple exit paths, instead of
2584 // just moving.
2585 Def->moveBefore(SinkBB->getFirstNonPhi());
2586 }
2587 }
2588}
2589
2591 VPlan &Plan, const MapVector<Instruction *, uint64_t> &MinBWs) {
2592 if (Plan.hasScalarVFOnly())
2593 return;
2594 // Keep track of created truncates, so they can be re-used. Note that we
2595 // cannot use RAUW after creating a new truncate, as this would could make
2596 // other uses have different types for their operands, making them invalidly
2597 // typed.
2598 // An operand may be shared by recipes narrowed to different widths, so the
2599 // truncates are keyed by operand and narrowed type.
2601 VPBasicBlock *PH = Plan.getVectorPreheader();
2604 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
2607 continue;
2608
2609 VPValue *ResultVPV = R.getVPSingleValue();
2610 auto *UI = cast_or_null<Instruction>(ResultVPV->getUnderlyingValue());
2611 unsigned NewResSizeInBits = MinBWs.lookup(UI);
2612 if (!NewResSizeInBits)
2613 continue;
2614
2615 // If the value wasn't vectorized, we must maintain the original scalar
2616 // type. Skip those here, after incrementing NumProcessedRecipes. Also
2617 // skip casts which do not need to be handled explicitly here, as
2618 // redundant casts will be removed during recipe simplification.
2620 continue;
2621
2622 Type *OldResTy = ResultVPV->getScalarType();
2623 unsigned OldResSizeInBits = OldResTy->getScalarSizeInBits();
2624 assert(OldResTy->isIntegerTy() && "only integer types supported");
2625 (void)OldResSizeInBits;
2626
2627 auto *NewResTy = IntegerType::get(Plan.getContext(), NewResSizeInBits);
2628
2629 // Any wrapping introduced by shrinking this operation shouldn't be
2630 // considered undefined behavior. So, we can't unconditionally copy
2631 // arithmetic wrapping flags to VPW.
2632 if (auto *VPW = dyn_cast<VPRecipeWithIRFlags>(&R))
2633 VPW->dropPoisonGeneratingFlags();
2634
2635 assert((OldResSizeInBits != NewResSizeInBits ||
2636 match(&R, m_ICmp(m_VPValue(), m_VPValue()))) &&
2637 "Only ICmps should not need extending the result.");
2638 assert(!isa<VPWidenStoreRecipe>(&R) && "stores cannot be narrowed");
2639
2640 // Loads/intrinsics are not recreated; they keep producing their original
2641 // wide result and narrowed users will truncate it as needed below.
2643 continue;
2644
2645 // Shrink operands by introducing truncates as needed.
2646 unsigned StartIdx =
2647 match(&R, m_Select(m_VPValue(), m_VPValue(), m_VPValue())) ? 1 : 0;
2648 SmallVector<VPValue *> NewOperands(R.operands());
2649 for (VPValue *&Op : drop_begin(NewOperands, StartIdx)) {
2650 unsigned OpSizeInBits = Op->getScalarType()->getScalarSizeInBits();
2651 if (OpSizeInBits == NewResSizeInBits)
2652 continue;
2653 assert(OpSizeInBits > NewResSizeInBits && "nothing to truncate");
2654 auto [ProcessedIter, Inserted] =
2655 ProcessedTruncs.try_emplace({Op, NewResTy});
2656 if (Inserted) {
2657 VPBuilder Builder;
2658 if (isa<VPIRValue>(Op))
2659 Builder.setInsertPoint(PH);
2660 else
2661 Builder.setInsertPoint(&R);
2662 ProcessedIter->second =
2663 Builder.createWidenCast(Instruction::Trunc, Op, NewResTy);
2664 }
2665 Op = ProcessedIter->second;
2666 }
2667
2668 auto *NWR = cast<VPWidenRecipe>(&R)->cloneWithOperands(NewOperands);
2669 NWR->insertBefore(&R);
2670
2671 // Wrap NWR in a ZExt to preserve the original wide type for downstream
2672 // users. Not needed for ICmps, whose result type is i1 irrespective of
2673 // the narrowing of their operands.
2674 VPValue *Replacement = NWR->getVPSingleValue();
2675 if (Replacement->getScalarType() != OldResTy)
2676 Replacement =
2678 .createWidenCast(Instruction::ZExt, Replacement, OldResTy)
2679 ->getVPSingleValue();
2680 ResultVPV->replaceAllUsesWith(Replacement);
2681 R.eraseFromParent();
2682 }
2683 }
2684}
2685
2686bool VPlanTransforms::removeBranchOnConst(VPlan &Plan, bool OnlyLatches) {
2687 std::optional<VPDominatorTree> VPDT;
2688 if (OnlyLatches)
2689 VPDT.emplace(Plan);
2690
2691 // Collect all blocks before modifying the CFG so we can identify unreachable
2692 // ones after constant branch removal.
2694
2695 bool SimplifiedPhi = false;
2696 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(AllBlocks)) {
2697 VPValue *Cond;
2698 // Skip blocks that are not terminated by BranchOnCond.
2699 if (VPBB->empty() || !match(&VPBB->back(), m_BranchOnCond(m_VPValue(Cond))))
2700 continue;
2701
2702 if (OnlyLatches && !VPBlockUtils::isLatch(VPBB, *VPDT))
2703 continue;
2704
2705 assert(VPBB->getNumSuccessors() == 2 &&
2706 "Two successors expected for BranchOnCond");
2707 unsigned RemovedIdx;
2708 if (match(Cond, m_True()))
2709 RemovedIdx = 1;
2710 else if (match(Cond, m_False()))
2711 RemovedIdx = 0;
2712 else
2713 continue;
2714
2715 VPBasicBlock *RemovedSucc =
2716 cast<VPBasicBlock>(VPBB->getSuccessors()[RemovedIdx]);
2717 assert(count(RemovedSucc->getPredecessors(), VPBB) == 1 &&
2718 "There must be a single edge between VPBB and its successor");
2719 // Values coming from VPBB into phi recipes of RemovedSucc are removed from
2720 // these recipes and single-entry header phis are removed.
2721 for (VPRecipeBase &R : make_early_inc_range(RemovedSucc->phis())) {
2722 cast<VPPhiAccessors>(&R)->removeIncomingValueFor(VPBB);
2723 SimplifiedPhi = true;
2724 // Remove now invalid header phis that are left single-entry after
2725 // removing their backedges.
2726 auto *PhiR = dyn_cast<VPHeaderPHIRecipe>(&R);
2727 if (!PhiR || PhiR->getNumIncoming() != 1)
2728 continue;
2729 PhiR->replaceAllUsesWith(PhiR->getOperand(0));
2730 PhiR->eraseFromParent();
2731 }
2732
2733 // Disconnect blocks and remove the terminator.
2734 VPBlockUtils::disconnectBlocks(VPBB, RemovedSucc);
2735 VPBB->back().eraseFromParent();
2736 }
2737
2738 // Compute which blocks are still reachable from the entry after constant
2739 // branch removal.
2742
2743 // Detach all unreachable blocks from their successors, removing their recipes
2744 // and incoming values from phi recipes.
2745 VPSymbolicValue Tmp(nullptr);
2746 for (VPBlockBase *B : AllBlocks) {
2747 if (Reachable.contains(B))
2748 continue;
2749 for (VPBlockBase *Succ : to_vector(B->successors())) {
2750 if (auto *SuccBB = dyn_cast<VPBasicBlock>(Succ))
2751 for (VPRecipeBase &R : SuccBB->phis())
2752 cast<VPPhiAccessors>(&R)->removeIncomingValueFor(B);
2754 }
2755 for (VPBasicBlock *DeadBB :
2757 for (VPRecipeBase &R : make_early_inc_range(*DeadBB)) {
2758 for (VPValue *Def : R.definedValues())
2759 Def->replaceAllUsesWith(&Tmp);
2760 R.eraseFromParent();
2761 }
2762 }
2763 }
2764 return SimplifiedPhi;
2765}
2766
2787
2790 auto GetSimplifiedLiveInViaSCEV = [&](VPValue *VPV) -> VPValue * {
2791 const SCEV *Expr = vputils::getSCEVExprForVPValue(VPV, PSE);
2792 const APInt *C;
2793 if (match(Expr, m_scev_APInt(C)))
2794 return Plan.getConstantInt(*C);
2795 return nullptr;
2796 };
2797
2798 for (VPValue *LiveIn : to_vector(Plan.getLiveIns())) {
2799 if (VPValue *SimplifiedLiveIn = GetSimplifiedLiveInViaSCEV(LiveIn))
2800 LiveIn->replaceAllUsesWith(SimplifiedLiveIn);
2801 }
2802}
2803
2805 VPlan &Plan, PredicatedScalarEvolution &PSE,
2806 const SymbolicStrideMap &StridesMap, const VPDominatorTree &VPDT) {
2807 // Replace VPValues for known constant strides guaranteed by predicated scalar
2808 // evolution that are guaranteed to be guarded by the runtime checks; that is,
2809 // blocks dominated by the vector header.
2810 assert(!Plan.getVectorLoopRegion() &&
2811 "expected to run before loop regions are created");
2812 const auto &[Header, _] = VPBlockUtils::getPlainCFGHeaderAndLatch(Plan);
2813 auto CanUseVersionedStride = [&VPDT, Header = Header, &Plan](VPUser *U) {
2814 auto *R = cast<VPRecipeBase>(U);
2815 // Skip phis if the loop if loop is not yet guarded.
2816 if (isa<VPPhiAccessors>(R) &&
2817 Header == Plan.getEntry()->getSingleSuccessor())
2818 return false;
2819 return VPDT.dominates(Header, R->getParent());
2820 };
2821 ValueToSCEVMapTy RewriteMap;
2822 for (const SCEVUnknown *Stride : StridesMap.values()) {
2823 Value *StrideV = Stride->getValue();
2824 const APInt *StrideConst;
2825 const SCEV *StrideExpr = PSE.getSCEV(StrideV);
2826 if (!match(StrideExpr, m_scev_APInt(StrideConst)))
2827 // Only handle constant strides for now.
2828 continue;
2829 if (VPValue *StrideVPV = Plan.getLiveIn(StrideV))
2830 StrideVPV->replaceUsesWithIf(Plan.getConstantInt(*StrideConst),
2831 CanUseVersionedStride);
2832
2833 // The versioned value may not be used in the loop directly but through an
2834 // integral cast (sext/zext/trunc). Add new live-ins in those cases.
2835 for (Value *U : StrideV->users()) {
2837 continue;
2838 VPValue *StrideVPV = Plan.getLiveIn(U);
2839 if (!StrideVPV)
2840 continue;
2841 unsigned BW = U->getType()->getScalarSizeInBits();
2842 APInt C = isa<SExtInst>(U) ? StrideConst->sext(BW)
2843 : StrideConst->zextOrTrunc(BW);
2844 StrideVPV->replaceUsesWithIf(Plan.getConstantInt(C),
2845 CanUseVersionedStride);
2846 }
2847 RewriteMap[StrideV] = StrideExpr;
2848 }
2849
2850 ScalarEvolution &SE = *PSE.getSE();
2851 for (VPExpandSCEVRecipe &ExpSCEV :
2853 const SCEV *ScevExpr = ExpSCEV.getSCEV();
2854 const SCEV *NewSCEV =
2855 SCEVParameterRewriter::rewrite(ScevExpr, SE, RewriteMap);
2856 if (NewSCEV == ScevExpr || !SE.isGuaranteedNotToCauseUB(NewSCEV))
2857 continue;
2858 VPValue *NewExp = vputils::getOrCreateVPValueForSCEVExpr(Plan, NewSCEV);
2859 ExpSCEV.replaceAllUsesWith(NewExp);
2860 if (Plan.getTripCount() == &ExpSCEV)
2861 Plan.resetTripCount(NewExp);
2862 }
2863}
2864
2866 // Collect recipes in the backward slice of `Root` that may generate a poison
2867 // value that is used after vectorization.
2869 auto CollectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
2871 Worklist.push_back(Root);
2872
2873 // Traverse the backward slice of Root through its use-def chain.
2874 while (!Worklist.empty()) {
2875 VPRecipeBase *CurRec = Worklist.pop_back_val();
2876
2877 if (!Visited.insert(CurRec).second)
2878 continue;
2879
2880 // Prune search if we find another recipe generating a widen memory
2881 // instruction. Widen memory instructions involved in address computation
2882 // will lead to gather/scatter instructions, which don't need to be
2883 // handled.
2885 VPHeaderPHIRecipe>(CurRec))
2886 continue;
2887
2888 // This recipe contributes to the address computation of a widen
2889 // load/store. If the underlying instruction has poison-generating flags,
2890 // drop them directly.
2891 if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(CurRec)) {
2892 VPValue *A, *B;
2893 // Dropping disjoint from an OR may yield incorrect results, as some
2894 // analysis may have converted it to an Add implicitly (e.g. SCEV used
2895 // for dependence analysis). Instead, replace it with an equivalent Add.
2896 // This is possible as all users of the disjoint OR only access lanes
2897 // where the operands are disjoint or poison otherwise.
2898 if (match(RecWithFlags, m_BinaryOr(m_VPValue(A), m_VPValue(B))) &&
2899 RecWithFlags->isDisjoint()) {
2900 VPBuilder Builder(RecWithFlags);
2901 VPInstruction *New =
2902 Builder.createAdd(A, B, RecWithFlags->getDebugLoc());
2903 New->setUnderlyingValue(RecWithFlags->getUnderlyingValue());
2904 RecWithFlags->replaceAllUsesWith(New);
2905 RecWithFlags->eraseFromParent();
2906 CurRec = New;
2907 } else
2908 RecWithFlags->dropPoisonGeneratingFlags();
2909 } else {
2912 (void)Instr;
2913 assert((!Instr || !Instr->hasPoisonGeneratingFlags()) &&
2914 "found instruction with poison generating flags not covered by "
2915 "VPRecipeWithIRFlags");
2916 }
2917
2918 // Add new definitions to the worklist.
2919 for (VPValue *Operand : CurRec->operands())
2920 if (VPRecipeBase *OpDef = Operand->getDefiningRecipe())
2921 Worklist.push_back(OpDef);
2922 }
2923 });
2924
2925 // We want to exclude the tail folding case, as we don't need to drop flags
2926 // for operations computing the first lane in this case: the first lane of the
2927 // header mask must always be true. For reverse memory accesses, the mask is
2928 // wrapped in a Reverse, which is just a permutation of the header mask, so
2929 // peel it off before checking. The header mask is still the abstract region
2930 // value at this point (materialization happens later).
2931 auto m_UnlessHdrMask = m_Unless( // NOLINT
2933
2934 // Traverse all the recipes in the VPlan and collect the poison-generating
2935 // recipes in the backward slice starting at the address of a VPWidenRecipe or
2936 // VPInterleaveRecipe.
2937 auto Iter =
2940 for (VPRecipeBase &Recipe : *VPBB) {
2941 if (auto *WidenRec = dyn_cast<VPWidenMemoryRecipe>(&Recipe)) {
2942 VPRecipeBase *AddrDef = WidenRec->getAddr()->getDefiningRecipe();
2943 if (AddrDef && WidenRec->isConsecutive() && WidenRec->getMask() &&
2944 match(WidenRec->getMask(), m_UnlessHdrMask))
2945 CollectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
2946 } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
2947 VPRecipeBase *AddrDef = InterleaveRec->getAddr()->getDefiningRecipe();
2948 if (AddrDef && InterleaveRec->getMask() &&
2949 match(InterleaveRec->getMask(), m_UnlessHdrMask))
2950 CollectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
2951 }
2952 }
2953 }
2954}
2955
2957 VPlan &Plan,
2959 &InterleaveGroups,
2960 const bool &EpilogueAllowed) {
2961 if (InterleaveGroups.empty())
2962 return;
2963
2965 for (VPBasicBlock *VPBB :
2968 for (VPWidenMemoryRecipe *MemR :
2970 IRMemberToRecipe[&MemR->getIngredient()] = MemR;
2971
2972 // Interleave memory: for each Interleave Group we marked earlier as relevant
2973 // for this VPlan, replace the Recipes widening its memory instructions with a
2974 // single VPInterleaveRecipe at its insertion point.
2975 VPDominatorTree VPDT(Plan);
2976 for (const auto *IG : InterleaveGroups) {
2977 VPWidenMemoryRecipe *Start = nullptr;
2978 Instruction *StartMember = nullptr;
2979 for (auto *Member : IG->members())
2980 if (VPWidenMemoryRecipe *R = IRMemberToRecipe.lookup(Member)) {
2981 StartMember = Member;
2982 Start = R;
2983 break;
2984 }
2985 if (!StartMember) // All member recipes are dead, so the group is dead.
2986 continue;
2987 VPIRMetadata InterleaveMD(*Start);
2988 SmallVector<VPValue *, 4> StoredValues;
2989 for (unsigned I = 0; I < IG->getFactor(); ++I) {
2990 Instruction *MemberI = IG->getMember(I);
2991 if (!MemberI)
2992 continue;
2993 if (VPWidenMemoryRecipe *MemoryR = IRMemberToRecipe.lookup(MemberI)) {
2994 if (auto *StoreR = dyn_cast<VPWidenStoreRecipe>(MemoryR->getAsRecipe()))
2995 StoredValues.push_back(StoreR->getStoredValue());
2996 InterleaveMD.intersect(*MemoryR);
2997 } else {
2998 InterleaveMD.intersect(VPIRMetadata(*MemberI));
2999 }
3000 }
3001
3002 bool NeedsMaskForGaps =
3003 (IG->requiresScalarEpilogue() && !EpilogueAllowed) ||
3004 (!StoredValues.empty() && !IG->isFull());
3005
3006 Instruction *IRInsertPos = IG->getInsertPos();
3007 auto *InsertPos = IRMemberToRecipe.lookup(IRInsertPos);
3008 if (!InsertPos) {
3009 // InsertPos member is dead: find a new member that is alive.
3010 assert(isa<VPWidenLoadRecipe>(Start->getAsRecipe()) &&
3011 "Dead member in non-load group?");
3012 InsertPos = Start;
3013 for (Instruction *Member : IG->members())
3014 if (VPWidenMemoryRecipe *MemberR = IRMemberToRecipe.lookup(Member))
3015 if (VPDT.properlyDominates(MemberR->getAsRecipe(),
3016 InsertPos->getAsRecipe()))
3017 InsertPos = MemberR;
3018 IRInsertPos = &InsertPos->getIngredient();
3019 }
3020 VPRecipeBase *InsertPosR = InsertPos->getAsRecipe();
3021
3023 if (auto *Gep = dyn_cast<GetElementPtrInst>(
3024 getLoadStorePointerOperand(IRInsertPos)->stripPointerCasts()))
3025 NW = Gep->getNoWrapFlags().withoutNoUnsignedWrap();
3026
3027 // Get or create the start address for the interleave group.
3028 VPValue *Addr = Start->getAddr();
3029 VPRecipeBase *AddrDef = Addr->getDefiningRecipe();
3030 if (IG->getIndex(StartMember) != 0 ||
3031 (AddrDef && !VPDT.properlyDominates(AddrDef, InsertPosR))) {
3032 // Either member zero's recipe is dead, or we cannot re-use the address of
3033 // member zero because it does not dominate the insert position. Instead,
3034 // use the address of the insert position and create a PtrAdd adjusting it
3035 // to the address of member zero.
3036 // TODO: Hoist Addr's defining recipe (and any operands as needed) to
3037 // InsertPos or sink loads above zero members to join it.
3038 assert(IG->getIndex(IRInsertPos) != 0 &&
3039 "index of insert position shouldn't be zero");
3040 auto &DL = IRInsertPos->getDataLayout();
3041 APInt Offset(32,
3042 DL.getTypeAllocSize(getLoadStoreType(IRInsertPos)) *
3043 IG->getIndex(IRInsertPos),
3044 /*IsSigned=*/true);
3045 VPValue *OffsetVPV = Plan.getConstantInt(-Offset);
3046 VPBuilder B(InsertPosR);
3047 Addr = B.createNoWrapPtrAdd(InsertPos->getAddr(), OffsetVPV, NW);
3048 }
3049 // If the group is reverse, adjust the index to refer to the last vector
3050 // lane instead of the first. We adjust the index from the first vector
3051 // lane, rather than directly getting the pointer for lane VF - 1, because
3052 // the pointer operand of the interleaved access is supposed to be uniform.
3053 if (IG->isReverse()) {
3054 auto *ReversePtr = new VPVectorEndPointerRecipe(
3055 Addr, &Plan.getVF(), getLoadStoreType(IRInsertPos),
3056 -(int64_t)IG->getFactor(), NW, InsertPosR->getDebugLoc());
3057 ReversePtr->insertBefore(InsertPosR);
3058 Addr = ReversePtr;
3059 }
3060 auto *VPIG = new VPInterleaveRecipe(
3061 IG, Addr, StoredValues, InsertPos->getMask(), NeedsMaskForGaps,
3062 InterleaveMD, InsertPosR->getDebugLoc());
3063 VPIG->insertBefore(InsertPosR);
3064
3065 unsigned J = 0;
3066 for (unsigned i = 0; i < IG->getFactor(); ++i)
3067 if (Instruction *Member = IG->getMember(i)) {
3068 VPWidenMemoryRecipe *MemberR = IRMemberToRecipe.lookup(Member);
3069 if (!Member->getType()->isVoidTy()) {
3070 if (MemberR) {
3071 VPValue *OriginalV = MemberR->getAsRecipe()->getVPSingleValue();
3072 OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
3073 }
3074 J++;
3075 }
3076 if (MemberR)
3077 MemberR->getAsRecipe()->eraseFromParent();
3078 }
3079 }
3080}
3081
3082/// Matches an exit condition formed by comparing a value loaded from memory
3083/// with a loop-invariant term. Binds the comparison for the condition.
3089
3090namespace {
3091struct CountableConditionMatch {
3092 VPValue *&Cmp;
3093 PredicatedScalarEvolution &PSE;
3094 Loop *L;
3095
3096 CountableConditionMatch(VPValue *&Cmp, PredicatedScalarEvolution &PSE,
3097 Loop *L)
3098 : Cmp(Cmp), PSE(PSE), L(L) {}
3099
3100 template <typename ITy> bool match(ITy *V) const {
3101 VPValue *Update;
3103 V, m_VPValue(Cmp, m_c_ICmp(m_VPValue(Update, m_Add(m_VPValue(),
3104 m_VPValue())),
3105 m_LiveIn()))))
3106 return false;
3107
3108 const SCEV *S = vputils::getSCEVExprForVPValue(Update, PSE, L);
3111 }
3112};
3113} // end anonymous namespace
3114
3115/// Matches an exit condition formed by comparing the current value of a
3116/// affine add recurrence in the given loop with a stride of 1 against a
3117/// loop-invariant term. Binds the comparison for the condition.
3119 Loop *L) {
3120 return CountableConditionMatch(Cmp, PSE, L);
3121}
3122
3125 Loop *L) {
3126 // Check for a single combined exit in the latch block.
3127 // TODO: Generalize to other blocks besides the latch.
3128 // If we don't find a combined condition in the latch, just return true
3129 // to proceed with vectorization.
3130 auto [_, LatchVPBB] = VPBlockUtils::getPlainCFGHeaderAndLatch(Plan);
3131
3132 // We're looking for a conditional branch...
3133 auto *Term = dyn_cast<VPInstruction>(LatchVPBB->getTerminator());
3134 if (!Term || Term->getOpcode() != VPInstruction::BranchOnCond)
3135 return true;
3136
3137 // ...where the condition is a combination of both a countable and an
3138 // uncountable comparison.
3139 VPValue *Uncountable = nullptr;
3140 VPValue *Countable = nullptr;
3141 VPValue *Cond = Term->getOperand(0);
3143 m_Countable(Countable, PSE, L)),
3144 m_c_BinaryOr(m_Uncountable(Uncountable),
3145 m_Countable(Countable, PSE, L)))))
3146 return true;
3147
3148 // If the conditions are combined with a logical or (select), then we'll
3149 // need to freeze the individual terms when splitting.
3150 bool NeedsFreeze = match(Cond, m_LogicalOr(m_VPValue(), m_VPValue()));
3151
3152 // If we do have a combined exit condition, bail out if there's more than
3153 // one exit block.
3154 // TODO: Support additional exits.
3155 ArrayRef<VPIRBasicBlock *> ExitBlocks = Plan.getExitBlocks();
3156 if (ExitBlocks.size() != 1)
3157 return false;
3158
3159 // If there are any live-outs, bail out. The exit block is an existing IR
3160 // block, and if we split the exiting block then the incoming blocks and
3161 // values won't be correct.
3162 // TODO: Support live-outs with combined exits.
3163 if (!ExitBlocks.front()->phis().empty())
3164 return false;
3165
3166 // Split the latch block just before the terminator.
3167 VPBasicBlock *NewLatch = LatchVPBB->splitAt(Term->getIterator());
3168
3169 // Create new terminator for uncountable condition.
3170 VPBuilder EEBuilder(LatchVPBB);
3171 if (NeedsFreeze)
3172 Uncountable = EEBuilder.createFreeze(Uncountable);
3173 EEBuilder.createNaryOp(VPInstruction::BranchOnCond, {Uncountable});
3174
3175 // We need to connect the uncountable exit to the sole exit block. The
3176 // latch is expected to connect to the middle block instead.
3177 // In canonical form, the backedge is the last successor for the latch. So
3178 // the first successor (true path) should be the exit for both conditions.
3179 LatchVPBB->clearSuccessors();
3180 NewLatch->clearPredecessors();
3181 VPBlockUtils::connectBlocks(LatchVPBB, ExitBlocks.front());
3182 VPBlockUtils::connectBlocks(LatchVPBB, NewLatch);
3183
3184 // Set condition for latch block to countable condition.
3185 if (NeedsFreeze) {
3186 VPBuilder NewLatchBuilder(Term);
3187 Countable = NewLatchBuilder.createFreeze(Countable);
3188 }
3189 Term->setOperand(0, Countable);
3190
3191 return true;
3192}
3193
3194/// Returns the VPValue representing the uncountable exit comparison used by
3195/// AnyOf if the recipes it depends on can be traced back to live-ins and
3196/// the addresses (in GEP/PtrAdd form) of any (non-masked) load used in
3197/// generating the values for the comparison. The recipes are stored in
3198/// \p Recipes.
3199static VPValue *
3201 VPBasicBlock *LatchVPBB) {
3202 // Given a plain CFG VPlan loop with countable latch exiting block
3203 // \p LatchVPBB, we're looking to match the recipes contributing to the
3204 // uncountable exit condition comparison (here, vp<%4>) back to either
3205 // live-ins or the address nodes for the load used as part of the uncountable
3206 // exit comparison so that we can either move them within the loop, or copy
3207 // them to the preheader depending on the chosen method for dealing with
3208 // stores in uncountable exit loops.
3209 //
3210 // Currently, the address of the load is restricted to a GEP with 2 operands
3211 // and a live-in base address. This constraint may be relaxed later.
3212 //
3213 // VPlan ' for UF>=1' {
3214 // Live-in vp<%0> = VF * UF
3215 // Live-in vp<%1> = vector-trip-count
3216 // Live-in ir<20> = original trip-count
3217 //
3218 // ir-bb<entry>:
3219 // Successor(s): scalar.ph, vector.ph
3220 //
3221 // vector.ph:
3222 // Successor(s): for.body
3223 //
3224 // for.body:
3225 // EMIT vp<%2> = phi ir<0>, vp<%index.next>
3226 // EMIT-SCALAR ir<%iv> = phi [ ir<0>, vector.ph ], [ ir<%iv.next>, for.inc ]
3227 // EMIT ir<%uncountable.addr> = getelementptr inbounds nuw ir<%pred>,ir<%iv>
3228 // EMIT ir<%uncountable.val> = load ir<%uncountable.addr>
3229 // EMIT ir<%uncountable.cond> = icmp sgt ir<%uncountable.val>, ir<500>
3230 // EMIT vp<%3> = masked-cond ir<%uncountable.cond>
3231 // Successor(s): for.inc
3232 //
3233 // for.inc:
3234 // EMIT ir<%iv.next> = add nuw nsw ir<%iv>, ir<1>
3235 // EMIT ir<%countable.cond> = icmp eq ir<%iv.next>, ir<20>
3236 // EMIT vp<%index.next> = add nuw vp<%2>, vp<%0>
3237 // EMIT vp<%freeze> = freeze ir<%3>
3238 // EMIT vp<%4> = any-of ir<%freeze>
3239 // EMIT vp<%5> = icmp eq vp<%index.next>, vp<%1>
3240 // EMIT branch-on-two-conds vp<%4>, vp<%5>
3241 // Successor(s): vector.early.exit, middle.block, for.body
3242 //
3243 // middle.block:
3244 // Successor(s): ir-bb<exit>, scalar.ph
3245 //
3246 // ir-bb<exit>:
3247 // No successors
3248 //
3249 // scalar.ph:
3250 // }
3251
3252 // Find the uncountable loop exit condition.
3253 VPValue *UncountableCondition = nullptr;
3254 if (!match(LatchVPBB->getTerminator(),
3255 m_BranchOnTwoConds(m_AnyOf(m_VPValue(UncountableCondition)),
3256 m_VPValue())))
3257 return nullptr;
3258
3260 Worklist.push_back(UncountableCondition);
3261 while (!Worklist.empty()) {
3262 VPValue *V = Worklist.pop_back_val();
3263
3264 // Any value defined outside the loop does not need to be copied.
3265 if (V->isDefinedOutsideLoopRegions())
3266 continue;
3267
3268 VPValue *Op1, *Op2;
3269 // Walk back through recipes until we find at least one load from memory.
3270 if (match(V, m_Cmp(m_VPValue(Op1), m_VPValue(Op2)))) {
3271 Worklist.push_back(Op1);
3272 Worklist.push_back(Op2);
3273 Recipes.push_back(cast<VPInstruction>(V->getDefiningRecipe()));
3275 VPRecipeBase *GepR = Op1->getDefiningRecipe();
3276 // Only matching base + single offset term for now.
3277 if (GepR->getNumOperands() != 2)
3278 return nullptr;
3279 // Matching a GEP with a loop-invariant base ptr.
3281 m_LiveIn(), m_VPValue())))
3282 return nullptr;
3283 Recipes.push_back(cast<VPInstruction>(V->getDefiningRecipe()));
3284 Recipes.push_back(cast<VPInstruction>(GepR));
3285 } else if (match(V, m_Freeze(m_VPValue(Op1)))) {
3286 Worklist.push_back(Op1);
3287 Recipes.push_back(cast<VPInstruction>(V->getDefiningRecipe()));
3289 m_VPValue(Op1)))) {
3290 Worklist.push_back(Op1);
3291 Recipes.push_back(cast<VPInstruction>(V->getDefiningRecipe()));
3292 } else
3293 return nullptr;
3294 }
3295
3296 // If we couldn't match anything, don't return the condition. It may be
3297 // defined outside the loop.
3298 if (Recipes.empty() ||
3300 return nullptr;
3301
3302 return UncountableCondition;
3303}
3304
3310
3311/// Update \p Plan to mask memory operations in the loop based on whether the
3312/// early exit is taken or not.
3313///
3314/// We're currently expecting to find a loop with properties similar to the
3315/// following:
3316///
3317/// for.body:
3318/// ir<%indvars.iv> = WIDEN-INDUCTION nuw nsw ir<0>, ir<1>, vp<%0>
3319/// EMIT ir<%arrayidx> = getelementptr inbounds nuw ir<@c>, ir<%indvars.iv>
3320/// EMIT-SCALAR ir<%0> = load ir<%arrayidx>
3321/// EMIT ir<%cmp1> = icmp sgt ir<%0>, ir<5>
3322/// EMIT vp<%1> = masked-cond ir<%cmp1>
3323/// Successor(s): if.end
3324///
3325/// if.end:
3326/// EMIT ir<%arrayidx3> = getelementptr inbounds nuw ir<@src>, ir<%indvars.iv>
3327/// EMIT-SCALAR ir<%2> = load ir<%arrayidx3>
3328/// EMIT ir<%add> = add nsw ir<%2>, ir<42>
3329/// EMIT ir<%arrayidx5> = getelementptr inbounds nuw ir<@dst>, ir<%indvars.iv>
3330/// EMIT store ir<%add>, ir<%arrayidx5>
3331/// EMIT ir<%indvars.iv.next> = add nuw nsw ir<%indvars.iv>, ir<1>
3332/// EMIT vp<%freeze> = freeze ir<%1>
3333/// EMIT vp<%3> = any-of ir<%freeze>
3334/// EMIT ir<%exitcond.not> = icmp eq ir<%indvars.iv.next>, ir<10000>
3335/// EMIT branch-on-two-conds vp<%3>, ir<%exitcond.not>
3336/// Successor(s): vector.early.exit, middle.block, for.body
3337///
3338/// We currently expect LoopVectorizationLegality to ensure that:
3339/// * There must also be a counted exit. We will need to support speculative
3340/// or first-faulting loads before we can remove this restriction.
3341/// * Any stores within the loop must not alias with the load used for the
3342/// uncountable exit. We can relax this a bit with runtime aliasing checks.
3343/// * Other memory operations in the loop can take place before or after the
3344/// uncountable exit, but must also be unconditional. We need to support
3345/// combining the conditions in VPlanPredicator.
3346/// * The loop must have a single unconditional load contributing to the
3347/// uncountable exit comparison, and the other term must be loop-invariant.
3348/// Improving upon this requires work in getRecipesForUncountableExit to
3349/// handle more complex recipe graphs.
3352 VPBasicBlock *HeaderVPBB, VPBasicBlock *LatchVPBB, VPBasicBlock *MiddleVPBB,
3353 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
3355 VPBasicBlock *VectorEarlyExitVPBB =
3356 Plan.createVPBasicBlock("vector.early.exit");
3357 LatchVPBB->setSuccessors({VectorEarlyExitVPBB, MiddleVPBB, HeaderVPBB});
3358 VectorEarlyExitVPBB->setPredecessors({LatchVPBB});
3359
3360 // Disconnect early exiting blocks from successors, remove branches.
3361 for (auto &Exit : Exits) {
3362 if (Exit.EarlyExitingVPBB == LatchVPBB)
3363 continue;
3364
3365 for (VPIRPhi &ExitIRI :
3366 map_range(Exit.EarlyExitVPBB->phis(), CastTo<VPIRPhi>))
3367 ExitIRI.removeIncomingValueFor(Exit.EarlyExitingVPBB);
3368 Exit.EarlyExitingVPBB->getTerminator()->eraseFromParent();
3369 VPBlockUtils::disconnectBlocks(Exit.EarlyExitingVPBB, Exit.EarlyExitVPBB);
3370 }
3371
3372 VPDominatorTree VPDT(Plan);
3373
3374 // We can abandon a VPlan entirely if we return false here, so we shouldn't
3375 // crash if some earlier assumptions on scalar IR don't hold for the vplan
3376 // version of the loop.
3377 SmallVector<VPInstruction *, 8> ConditionRecipes;
3378
3379 VPValue *Cond = getRecipesForUncountableExit(ConditionRecipes, LatchVPBB);
3380 if (!Cond) {
3381 reportVectorizationFailure("Unable to determine early exit condition for "
3382 "loop with side effects",
3383 "EarlyExitSideEffectsCond", ORE, TheLoop);
3384 return false;
3385 }
3386
3387 // Find load contributing to condition.
3388 // At the moment LoopVectorizationLegality only supports a single
3389 // early-exit expression with a compare and a single load that must
3390 // be unconditional.
3391 // TODO: Support more than one load.
3392 auto *Load =
3393 find_singleton<VPInstruction>(ConditionRecipes, [](auto *I, bool _) {
3395 ? I
3396 : nullptr;
3397 });
3398 assert(Load && "Couldn't find exactly one load");
3399 // TODO: Support conditional loads for uncountable exits.
3400 assert(VPDT.dominates(Load->getParent(), LatchVPBB) &&
3401 "Uncountable exit condition load is conditional.");
3402 VPInstruction *Ptr = cast<VPInstruction>(Load->getOperand(0));
3403
3404 // Ensure that we are guaranteed to be able to dereference the memory used
3405 // for determining the uncountable exit for the maximum possible number of
3406 // scalar iterations of the loop.
3407 //
3408 // TODO: Support first-faulting loads in cases where we don't know whether
3409 // all possible addresses are dereferenceable.
3410 {
3412 const SCEV *PtrSCEV = vputils::getSCEVExprForVPValue(Ptr, PSE, TheLoop);
3413 const DataLayout &DL = Plan.getDataLayout();
3414 APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getScalarType()),
3415 DL.getTypeStoreSize(Load->getScalarType()).getFixedValue());
3417 PtrSCEV, cast<LoadInst>(Load->getUnderlyingInstr())->getAlign(),
3418 PSE.getSE()->getConstant(EltSize), TheLoop, *PSE.getSE(), DT, AC,
3419 &Predicates)) {
3420 reportVectorizationFailure("Early exit loop with side effects contains "
3421 "load used by the exit condition that may "
3422 "fault",
3423 "EarlyExitSideEffectsFaultingLoad", ORE,
3424 TheLoop);
3425 return false;
3426 }
3427 }
3428
3429 // Check for a single GEP for the condition load to see if we can link it to
3430 // a widen IV recipe with a step of 1; we're only interested in contiguous
3431 // accesses for the condition load right now.
3432 VPValue *Idx;
3433 VPWidenInductionRecipe *IV = nullptr;
3435 m_VPValue(Idx))))
3437 if (!IV || !match(IV->getStartValue(), m_SpecificInt(0)) ||
3438 !match(IV->getStepValue(), m_SpecificInt(1))) {
3439 reportVectorizationFailure("Early exit loop with side effects contains "
3440 "load used by the exit condition with an "
3441 "unsupported memory access pattern",
3442 "EarlyExitSideEffectsBadLoadAccessPattern", ORE,
3443 TheLoop);
3444 return false;
3445 }
3446
3447 // We want to guarantee that the uncountable exit condition (and the mask
3448 // we will generate from it) are available for all operations in the loop
3449 // that need to be masked. If the condition recipes are not already the first
3450 // recipes in the header after the last phi, move them there.
3451 auto InsertIt = HeaderVPBB->getFirstNonPhi();
3452 while (InsertIt != HeaderVPBB->end() &&
3453 is_contained(ConditionRecipes, &*InsertIt)) {
3454 erase(ConditionRecipes, &*InsertIt);
3455 InsertIt++;
3456 }
3457 for (auto *Recipe : reverse(ConditionRecipes))
3458 Recipe->moveBefore(InsertIt);
3459
3460 // Create a mask to represent all lanes that fully execute in the vector loop,
3461 // stopping short of any early exit.
3462 VPBuilder MaskBuilder(InsertIt);
3463 VPValue *Mask = MaskBuilder.createWidenIntrinsic(Intrinsic::mask_beforefirst,
3464 Cond, Cond->getScalarType());
3465
3466 // Convert all other memory operations to use the mask.
3467 for (VPBasicBlock *VPBB : vp_rpo_plain_cfg_loop_body(HeaderVPBB))
3468 for (VPRecipeBase &R : *VPBB)
3469 if (R.mayReadOrWriteMemory() && &R != Load) {
3470 // TODO: Handle conditional memory operations in the loop.
3471 if (!VPDT.dominates(R.getParent(), LatchVPBB)) {
3473 "Early exit loop with side effects contains unsupported "
3474 "conditional memory operations",
3475 "EarlyExitSideEffectsUnsupportedConditionalMemOps", ORE, TheLoop);
3476 return false;
3477 }
3478 cast<VPInstruction>(&R)->addMask(Mask);
3479 }
3480
3481 // The early exit resumes the scalar loop at the first exiting lane.
3482 VPBuilder EarlyExitBuilder(VectorEarlyExitVPBB);
3483 Type *IVScalarTy = IV->getScalarType();
3484 VPValue *Zero = Plan.getZero(IVScalarTy);
3485 VPValue *FirstActive = EarlyExitBuilder.createScalarZExtOrTrunc(
3486 EarlyExitBuilder.createFirstActiveLane(Cond), IVScalarTy, DebugLoc());
3487 VPValue *ScalarIV = EarlyExitBuilder.createNaryOp(VPInstruction::ExtractLane,
3488 {Zero, IV}, DebugLoc());
3489 VPValue *ExitIV = EarlyExitBuilder.createAdd(ScalarIV, FirstActive);
3490
3491 // Update resume phi in scalar.ph.
3492 VPBasicBlock *ScalarPH = Plan.getScalarPreheader();
3493 auto Phis = ScalarPH->phis();
3494 // TODO: Handle more than one Phi; re-derive from IV.
3495 // TODO: Handle reductions.
3496 if (range_size(Phis) != 1) {
3498 "Early exit loop with side effects contains "
3499 "unsupported reductions, inductions or recurrences",
3500 "EarlyExitSideEffectsReductions", ORE, TheLoop);
3501 return false;
3502 }
3503 VPPhi *ContinueIV = cast<VPPhi>(Phis.begin());
3504 // Make sure we're referring to the same IV.
3505 assert(
3506 match(ContinueIV->getOperand(0),
3508 "Continuing from different IV");
3509 assert(ContinueIV->getNumIncoming() == 2 && "expected middle and entry");
3510 ContinueIV->addIncoming(ContinueIV->getOperand(1));
3511 ContinueIV->setOperand(1, ExitIV);
3512 ScalarPH->getPredecessors().insert(
3513 std::next(ScalarPH->getPredecessors().begin()), VectorEarlyExitVPBB);
3514 VectorEarlyExitVPBB->setOneSuccessor(ScalarPH);
3515 return true;
3516}
3517
3518// Returns true if the loop contains stores, the only writes legality accepts in
3519// early-exit loops.
3520static bool loopHasStores(VPBasicBlock *HeaderVPBB) {
3521 return any_of(vp_rpo_plain_cfg_loop_body(HeaderVPBB), [](VPBasicBlock *VPBB) {
3522 return any_of(*VPBB, [VPBB](VPRecipeBase &R) {
3523 (void)VPBB;
3525 return false;
3526 if (!R.mayWriteToMemory()) {
3527 assert((!R.mayHaveSideEffects() || &R == VPBB->getTerminator() ||
3528 R.isSafeToSpeculativelyExecute()) &&
3529 "legality only accepts recipes with side effects that are "
3530 "safe to speculate");
3531 return false;
3532 }
3534 "legality only accepts stores as writes in early-exit loops");
3535 return true;
3536 });
3537 });
3538}
3539
3541 VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop,
3543#ifndef NDEBUG
3544 VPDominatorTree VPDT(Plan);
3545#endif
3546
3547 auto *MiddleVPBB = VPBlockUtils::getPlainCFGMiddleBlock(Plan);
3548 auto [HeaderVPBB, LatchVPBB] = VPBlockUtils::getPlainCFGHeaderAndLatch(Plan);
3549
3550 bool ReadOnly = !loopHasStores(HeaderVPBB);
3551
3552 // Dereferenceability is checked separately for uncountable exit loops with
3553 // stores, as only the loads contributing to the exit condition need to
3554 // be checked.
3555 if (ReadOnly &&
3556 !areAllLoadsDereferenceable(HeaderVPBB, TheLoop, PSE, DT, AC)) {
3558 "Auto-vectorization of early exit loops with potentially "
3559 "faulting loads is not supported",
3560 "EarlyExitFaultingLoads", ORE, TheLoop);
3561 return false;
3562 }
3563
3564 VPBuilder LatchBuilder(LatchVPBB->getTerminator());
3566 for (auto [EarlyExitingVPBB, ExitBlock] :
3567 vputils::getEarlyExits(Plan, MiddleVPBB)) {
3568 // The final value of a reduction is computed in the middle block, which is
3569 // only reached when leaving the vector loop via the latch. On early exits,
3570 // it is computed from the accumulators of the exiting iteration.
3571 // TODO: Support more reductions used on early exits.
3572 for (VPIRPhi &ExitIRI : map_range(ExitBlock->phis(), CastTo<VPIRPhi>)) {
3573 VPValue *ExitV = ExitIRI.getIncomingValueForBlock(EarlyExitingVPBB);
3574 for (VPReductionPHIRecipe &PhiR :
3575 make_isa_range<VPReductionPHIRecipe>(HeaderVPBB->phis())) {
3576 if (ExitV != PhiR.getBackedgeValue())
3577 continue;
3578 RecurKind Kind = PhiR.getRecurrenceKind();
3579 if (PhiR.isOrdered() || PhiR.hasUsesOutsideReductionChain() ||
3583 "Found reduction used on an early exit",
3584 "Cannot vectorize early exit loop with reduction used on an "
3585 "early exit",
3586 "ReductionUsedOnEarlyExit", ORE, TheLoop);
3587 return false;
3588 }
3589 }
3590 }
3591
3592 // Collect condition for this early exit.
3593 VPBlockBase *TrueSucc = EarlyExitingVPBB->getSuccessors()[0];
3594 VPValue *CondOfEarlyExitingVPBB;
3595 [[maybe_unused]] bool Matched =
3596 match(EarlyExitingVPBB->getTerminator(),
3597 m_BranchOnCond(m_VPValue(CondOfEarlyExitingVPBB)));
3598 assert(Matched && "Terminator must be BranchOnCond");
3599
3600 // Insert the MaskedCond in the EarlyExitingVPBB so the predicator adds
3601 // the correct block mask.
3602 VPBuilder EarlyExitingBuilder(EarlyExitingVPBB->getTerminator());
3603 auto *CondToEarlyExit = EarlyExitingBuilder.createNaryOp(
3605 TrueSucc == ExitBlock
3606 ? CondOfEarlyExitingVPBB
3607 : EarlyExitingBuilder.createNot(CondOfEarlyExitingVPBB));
3608 assert((isa<VPIRValue>(CondOfEarlyExitingVPBB) ||
3609 !VPDT.properlyDominates(EarlyExitingVPBB, LatchVPBB) ||
3610 VPDT.properlyDominates(
3611 CondOfEarlyExitingVPBB->getDefiningRecipe()->getParent(),
3612 LatchVPBB)) &&
3613 "exit condition must dominate the latch");
3614 Exits.push_back({
3615 EarlyExitingVPBB,
3616 ExitBlock,
3617 CondToEarlyExit,
3618 });
3619 }
3620
3621 assert(!Exits.empty() && "must have at least one early exit");
3622 // Sort exits by RPO order to get correct program order. RPO gives a
3623 // topological ordering of the CFG, ensuring upstream exits are checked
3624 // before downstream exits in the dispatch chain.
3626 HeaderVPBB);
3628 for (const auto &[Num, VPB] : enumerate(RPOT))
3629 RPOIdx[VPB] = Num;
3630 llvm::sort(Exits, [&RPOIdx](const EarlyExitInfo &A, const EarlyExitInfo &B) {
3631 return RPOIdx[A.EarlyExitingVPBB] < RPOIdx[B.EarlyExitingVPBB];
3632 });
3633#ifndef NDEBUG
3634 // After RPO sorting, verify that for any pair where one exit dominates
3635 // another, the dominating exit comes first. This is guaranteed by RPO
3636 // (topological order) and is required for the dispatch chain correctness.
3637 for (unsigned I = 0; I + 1 < Exits.size(); ++I)
3638 for (unsigned J = I + 1; J < Exits.size(); ++J)
3639 assert(!VPDT.properlyDominates(Exits[J].EarlyExitingVPBB,
3640 Exits[I].EarlyExitingVPBB) &&
3641 "RPO sort must place dominating exits before dominated ones");
3642#endif
3643
3644 // Build the AnyOf condition for the latch terminator using logical OR
3645 // to avoid poison propagation from later exit conditions when an earlier
3646 // exit is taken.
3647 VPValue *Combined = Exits[0].CondToExit;
3648 for (const EarlyExitInfo &Info : drop_begin(Exits))
3649 Combined = LatchBuilder.createLogicalOr(Combined, Info.CondToExit);
3650 Combined = LatchBuilder.createFreeze(Combined);
3651
3652 // Even though the logical or prevents posion propagation, we need to freeze
3653 // Combined to prevent poisoning the entire AnyOf result:
3654 //
3655 // Exits[0].CondToExit = [0,1,0,0]
3656 // Exits[1].CondToExit = [0,0,p,p]
3657 // Combined = [0,1,p,p]
3658 // freeze(Combined) = [0,1,?,?]
3659 // AnyOf = 1
3660 VPValue *IsAnyExitTaken =
3661 LatchBuilder.createNaryOp(VPInstruction::AnyOf, Combined);
3662
3663 // Create a comparison for the latch exit condition and replace the
3664 // BranchOnCond with a BranchOnTwoConds. The original BranchOnCond's condition
3665 // is used as the latch-exit condition; canonical IV recipes have not been
3666 // introduced yet, so there is no BranchOnCount to derive the condition from.
3667 auto *LatchExitingBranch = cast<VPInstruction>(LatchVPBB->getTerminator());
3668 assert(LatchExitingBranch->getOpcode() == VPInstruction::BranchOnCond &&
3669 "Unexpected terminator");
3670 VPValue *IsLatchExitTaken = LatchExitingBranch->getOperand(0);
3671 DebugLoc LatchDL = LatchExitingBranch->getDebugLoc();
3672 LatchExitingBranch->eraseFromParent();
3673 LatchBuilder.setInsertPoint(LatchVPBB);
3675 {IsAnyExitTaken, IsLatchExitTaken}, LatchDL);
3676 LatchVPBB->clearSuccessors();
3677
3678 if (!ReadOnly)
3679 return handleUncountableExitsWithSideEffects(Plan, Exits, HeaderVPBB,
3680 LatchVPBB, MiddleVPBB, ORE,
3681 TheLoop, PSE, DT, AC);
3682
3683 // Create the vector.early.exit blocks.
3684 SmallVector<VPBasicBlock *> VectorEarlyExitVPBBs(Exits.size());
3685 for (unsigned Idx = 0; Idx != Exits.size(); ++Idx) {
3686 Twine BlockSuffix = Exits.size() == 1 ? "" : Twine(".") + Twine(Idx);
3687 VPBasicBlock *VectorEarlyExitVPBB =
3688 Plan.createVPBasicBlock("vector.early.exit" + BlockSuffix);
3689 VectorEarlyExitVPBBs[Idx] = VectorEarlyExitVPBB;
3690 }
3691
3692 // Create the dispatch block (or reuse the single exit block if only one
3693 // exit). The dispatch block computes the first active lane of the combined
3694 // condition and, for multiple exits, chains through conditions to determine
3695 // which exit to take.
3696 VPBasicBlock *DispatchVPBB =
3697 Exits.size() == 1 ? VectorEarlyExitVPBBs[0]
3698 : Plan.createVPBasicBlock("vector.early.exit.check");
3699 DispatchVPBB->setPredecessors({LatchVPBB});
3700 LatchVPBB->setSuccessors({DispatchVPBB, MiddleVPBB, HeaderVPBB});
3701 VPBuilder DispatchBuilder(DispatchVPBB->begin());
3702 VPValue *FirstActiveLane = DispatchBuilder.createFirstActiveLane(
3703 {Combined}, DebugLoc::getUnknown(), "first.active.lane");
3704
3705 // For each early exit, disconnect the original exiting block
3706 // (early.exiting.I) from the exit block (ir-bb<exit.I>) and route through a
3707 // new vector.early.exit block. Update ir-bb<exit.I>'s phis to extract their
3708 // values at the first active lane:
3709 //
3710 // Input:
3711 // early.exiting.I:
3712 // ...
3713 // EMIT branch-on-cond vp<%cond.I>
3714 // Successor(s): in.loop.succ, ir-bb<exit.I>
3715 //
3716 // ir-bb<exit.I>:
3717 // IR %phi = phi [ vp<%incoming.I>, early.exiting.I ], ...
3718 //
3719 // Output:
3720 // early.exiting.I:
3721 // ...
3722 // Successor(s): in.loop.succ
3723 //
3724 // vector.early.exit.I:
3725 // EMIT vp<%exit.val> = extract-lane vp<%first.lane>, vp<%incoming.I>
3726 // Successor(s): ir-bb<exit.I>
3727 //
3728 // ir-bb<exit.I>:
3729 // IR %phi = phi ... (extra operand: vp<%exit.val> from
3730 // vector.early.exit.I)
3731 //
3732 for (auto [Exit, VectorEarlyExitVPBB] :
3733 zip_equal(Exits, VectorEarlyExitVPBBs)) {
3734 auto &[EarlyExitingVPBB, EarlyExitVPBB, _] = Exit;
3735 // Adjust the phi nodes in EarlyExitVPBB.
3736 // 1. remove incoming values from EarlyExitingVPBB,
3737 // 2. extract the incoming value at FirstActiveLane
3738 // 3. add back the extracts as last operands for the phis
3739 // Then adjust the CFG, removing the edge between EarlyExitingVPBB and
3740 // EarlyExitVPBB and adding a new edge between VectorEarlyExitVPBB and
3741 // EarlyExitVPBB. The extracts at FirstActiveLane are now the incoming
3742 // values from VectorEarlyExitVPBB.
3743 for (VPIRPhi &ExitIRI : map_range(EarlyExitVPBB->phis(), CastTo<VPIRPhi>)) {
3744 VPValue *IncomingVal = ExitIRI.getIncomingValueForBlock(EarlyExitingVPBB);
3745 VPValue *NewIncoming = IncomingVal;
3746 if (!isa<VPIRValue>(IncomingVal)) {
3747 VPBuilder EarlyExitBuilder(VectorEarlyExitVPBB);
3748 NewIncoming = EarlyExitBuilder.createNaryOp(
3749 VPInstruction::ExtractLane, {FirstActiveLane, IncomingVal},
3750 DebugLoc::getUnknown(), "early.exit.value");
3751 }
3752 ExitIRI.removeIncomingValueFor(EarlyExitingVPBB);
3753 ExitIRI.addIncoming(NewIncoming);
3754 }
3755
3756 EarlyExitingVPBB->getTerminator()->eraseFromParent();
3757 VPBlockUtils::disconnectBlocks(EarlyExitingVPBB, EarlyExitVPBB);
3758 VPBlockUtils::connectBlocks(VectorEarlyExitVPBB, EarlyExitVPBB);
3759 }
3760
3761 // Chain through exits: for each exit, check if its condition is true at
3762 // the first active lane. If so, take that exit; otherwise, try the next.
3763 // The last exit needs no check since it must be taken if all others fail.
3764 //
3765 // For 3 exits (cond.0, cond.1, cond.2), this creates:
3766 //
3767 // latch:
3768 // ...
3769 // EMIT vp<%combined> = logical-or vp<%cond.0>, vp<%cond.1>, vp<%cond.2>
3770 // EMIT vp<%combined.freeze> = freeze vp<%combined>
3771 // ...
3772 //
3773 // vector.early.exit.check:
3774 // EMIT vp<%first.lane> = first-active-lane vp<%combined.freeze>
3775 // EMIT vp<%at.cond.0> = extract-lane vp<%first.lane>, vp<%cond.0>
3776 // EMIT branch-on-cond vp<%at.cond.0>
3777 // Successor(s): vector.early.exit.0, vector.early.exit.check.0
3778 //
3779 // vector.early.exit.check.0:
3780 // EMIT vp<%at.cond.1> = extract-lane vp<%first.lane>, vp<%cond.1>
3781 // EMIT branch-on-cond vp<%at.cond.1>
3782 // Successor(s): vector.early.exit.1, vector.early.exit.2
3783 VPBasicBlock *CurrentBB = DispatchVPBB;
3784 for (auto [I, Exit] : enumerate(ArrayRef(Exits).drop_back())) {
3785 VPValue *LaneVal = DispatchBuilder.createNaryOp(
3786 VPInstruction::ExtractLane, {FirstActiveLane, Exit.CondToExit},
3787 DebugLoc::getUnknown(), "exit.cond.at.lane");
3788
3789 // For the last dispatch, branch directly to the last exit on false;
3790 // otherwise, create a new check block.
3791 bool IsLastDispatch = (I + 2 == Exits.size());
3792 VPBasicBlock *FalseBB =
3793 IsLastDispatch ? VectorEarlyExitVPBBs.back()
3794 : Plan.createVPBasicBlock(
3795 Twine("vector.early.exit.check.") + Twine(I));
3796
3797 DispatchBuilder.createNaryOp(VPInstruction::BranchOnCond, {LaneVal});
3798 CurrentBB->setSuccessors({VectorEarlyExitVPBBs[I], FalseBB});
3799 VectorEarlyExitVPBBs[I]->setPredecessors({CurrentBB});
3800 FalseBB->setPredecessors({CurrentBB});
3801
3802 CurrentBB = FalseBB;
3803 DispatchBuilder.setInsertPoint(CurrentBB);
3804 }
3805
3806 return true;
3807}
3808
3809/// This function tries convert extended in-loop reductions to
3810/// VPExpressionRecipe and clamp the \p Range if it is beneficial and
3811/// valid. The created recipe must be decomposed to its constituent
3812/// recipes before execution.
3813static VPExpressionRecipe *
3815 VFRange &Range) {
3816 Type *RedTy = Red->getScalarType();
3817 VPValue *VecOp = Red->getVecOp();
3818
3819 // We don't handle partial reductions here.
3820 if (Red->isPartialReduction())
3821 return nullptr;
3822
3823 // Clamp the range if using extended-reduction is profitable.
3824 auto IsExtendedRedValidAndClampRange =
3825 [&](unsigned Opcode, Instruction::CastOps ExtOpc, Type *SrcTy) -> bool {
3827 [&](ElementCount VF) {
3828 auto *SrcVecTy = cast<VectorType>(toVectorTy(SrcTy, VF));
3830
3832 InstructionCost ExtCost =
3833 cast<VPWidenCastRecipe>(VecOp)->computeCost(VF, Ctx);
3834 InstructionCost RedCost = Red->computeCost(VF, Ctx);
3835
3836 assert(!RedTy->isFloatingPointTy() &&
3837 "getExtendedReductionCost only supports integer types");
3838 ExtRedCost = Ctx.TTI.getExtendedReductionCost(
3839 Opcode, ExtOpc == Instruction::CastOps::ZExt, RedTy, SrcVecTy,
3840 Red->getFastMathFlagsOrNone(), CostKind);
3841 return ExtRedCost.isValid() && ExtRedCost < ExtCost + RedCost;
3842 },
3843 Range);
3844 };
3845
3846 VPValue *A;
3847 // Match reduce(ext)).
3849 IsExtendedRedValidAndClampRange(
3850 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()),
3851 cast<VPWidenCastRecipe>(VecOp)->getOpcode(), A->getScalarType()))
3852 return new VPExpressionRecipe(cast<VPWidenCastRecipe>(VecOp), Red);
3853
3854 return nullptr;
3855}
3856
3858
3862
3863/// Returns true if the narrow \p Mul in ext(mul(ext(A), ext(B))) or
3864/// ext(mul(ext(A), C)) cannot wrap. The kind of the inner extends selects
3865/// whether nuw (zext) or nsw (sext) is required on \p Mul.
3867 auto *LHS = cast<VPWidenCastRecipe>(Mul->getOperand(0));
3868 auto *RHS = dyn_cast<VPWidenCastRecipe>(Mul->getOperand(1));
3869 Type *LHSSrcTy = LHS->getOperand(0)->getScalarType();
3870 // A constant RHS must fit in the source type of the LHS.
3871 Type *RHSSrcTy = RHS ? RHS->getOperand(0)->getScalarType() : LHSSrcTy;
3873 if (Mul->getScalarType()->getScalarSizeInBits() >=
3874 LHSSrcTy->getScalarSizeInBits() + RHSSrcTy->getScalarSizeInBits())
3875 return true;
3876 if (ExtKind == ExtendKind::PR_ZeroExtend)
3877 return Mul->hasNoUnsignedWrap();
3878 return ExtKind == ExtendKind::PR_SignExtend && Mul->hasNoSignedWrap();
3879}
3880
3881/// This function tries convert extended in-loop reductions to
3882/// VPExpressionRecipe and clamp the \p Range if it is beneficial
3883/// and valid. The created VPExpressionRecipe must be decomposed to its
3884/// constituent recipes before execution. Patterns of the
3885/// VPExpressionRecipe:
3886/// reduce.add(mul(...)),
3887/// reduce.add(mul(ext(A), ext(B))),
3888/// reduce.add(ext(mul(ext(A), ext(B)))).
3889/// reduce.fadd(fmul(ext(A), ext(B)))
3890static VPExpressionRecipe *
3892 VPCostContext &Ctx, VFRange &Range) {
3893 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3894 if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
3895 Opcode != Instruction::FAdd)
3896 return nullptr;
3897
3898 // We don't handle partial reductions here.
3899 if (Red->isPartialReduction())
3900 return nullptr;
3901
3902 Type *RedTy = Red->getScalarType();
3903
3904 // Clamp the range if using multiply-accumulate-reduction is profitable.
3905 auto IsMulAccValidAndClampRange =
3907 VPWidenCastRecipe *OuterExt) -> bool {
3909 [&](ElementCount VF) {
3911 Type *SrcTy = Ext0 ? Ext0->getOperand(0)->getScalarType() : RedTy;
3912 InstructionCost MulAccCost;
3913
3914 // getMulAccReductionCost for in-loop reductions does not support
3915 // mixed or floating-point extends.
3916 if (Ext0 && Ext1 &&
3917 (Ext0->getOpcode() != Ext1->getOpcode() ||
3918 Ext0->getOpcode() == Instruction::CastOps::FPExt))
3919 return false;
3920
3921 bool IsZExt =
3922 !Ext0 || Ext0->getOpcode() == Instruction::CastOps::ZExt;
3923 auto *SrcVecTy = cast<VectorType>(toVectorTy(SrcTy, VF));
3924 MulAccCost = Ctx.TTI.getMulAccReductionCost(IsZExt, Opcode, RedTy,
3925 SrcVecTy, CostKind);
3926
3927 InstructionCost MulCost = Mul->computeCost(VF, Ctx);
3928 InstructionCost RedCost = Red->computeCost(VF, Ctx);
3929 InstructionCost ExtCost = 0;
3930 if (Ext0)
3931 ExtCost += Ext0->computeCost(VF, Ctx);
3932 if (Ext1)
3933 ExtCost += Ext1->computeCost(VF, Ctx);
3934 if (OuterExt)
3935 ExtCost += OuterExt->computeCost(VF, Ctx);
3936
3937 return MulAccCost.isValid() &&
3938 MulAccCost < ExtCost + MulCost + RedCost;
3939 },
3940 Range);
3941 };
3942
3943 VPValue *VecOp = Red->getVecOp();
3944 VPRecipeBase *Sub = nullptr;
3945 VPValue *A, *B;
3946 VPValue *Tmp = nullptr;
3947
3948 if (RedTy->isFloatingPointTy())
3949 return nullptr;
3950
3951 // Sub reductions could have a sub between the add reduction and vec op.
3952 if (match(VecOp, m_Sub(m_ZeroInt(), m_VPValue(Tmp)))) {
3953 Sub = VecOp->getDefiningRecipe();
3954 VecOp = Tmp;
3955 }
3956
3957 // If ValB is a constant and can be safely extended, truncate it to the same
3958 // type as ExtA's operand, then extend it to the same type as ExtA. This
3959 // creates two uniform extends that can more easily be matched by the rest of
3960 // the bundling code. The ExtB reference, ValB and operand 1 of Mul are all
3961 // replaced with the new extend of the constant.
3962 auto ExtendAndReplaceConstantOp = [](VPWidenCastRecipe *ExtA,
3963 VPWidenCastRecipe *&ExtB, VPValue *&ValB,
3964 VPWidenRecipe *Mul) {
3965 if (!ExtA || ExtB || !isa<VPIRValue>(ValB) ||
3966 !match(ExtA, m_ZExtOrSExt(m_VPValue())))
3967 return;
3968 Type *NarrowTy = ExtA->getOperand(0)->getScalarType();
3969 Instruction::CastOps ExtOpc = ExtA->getOpcode();
3970 const APInt *Const;
3971 if (!match(ValB, m_APInt(Const)) ||
3973 Const, NarrowTy, TTI::getPartialReductionExtendKind(ExtOpc)))
3974 return;
3975 // The truncate ensures that the type of each extended operand is the
3976 // same, and it's been proven that the constant can be extended from
3977 // NarrowTy safely. Necessary since ExtA's extended operand would be
3978 // e.g. an i8, while the const will likely be an i32. This will be
3979 // elided by later optimisations.
3980 VPBuilder Builder(Mul);
3981 auto *Trunc =
3982 Builder.createWidenCast(Instruction::CastOps::Trunc, ValB, NarrowTy);
3983 Type *WideTy = ExtA->getScalarType();
3984 ValB = ExtB = Builder.createWidenCast(ExtOpc, Trunc, WideTy);
3985 Mul->setOperand(1, ExtB);
3986 };
3987
3988 // Try to match reduce.add(mul(...)).
3989 if (match(VecOp, m_Mul(m_VPValue(A), m_VPValue(B)))) {
3990 auto *RecipeA = dyn_cast<VPWidenCastRecipe>(A);
3991 auto *RecipeB = dyn_cast<VPWidenCastRecipe>(B);
3992 auto *Mul = cast<VPWidenRecipe>(VecOp);
3993
3994 // Convert reduce.add(mul(ext, const)) to reduce.add(mul(ext, ext(const)))
3995 ExtendAndReplaceConstantOp(RecipeA, RecipeB, B, Mul);
3996
3997 // Match reduce.add/sub(mul(ext, ext)).
3998 if (RecipeA && RecipeB && match(RecipeA, m_ZExtOrSExt(m_VPValue())) &&
3999 match(RecipeB, m_ZExtOrSExt(m_VPValue())) &&
4000 IsMulAccValidAndClampRange(Mul, RecipeA, RecipeB, nullptr)) {
4001 if (Sub)
4002 return new VPExpressionRecipe(RecipeA, RecipeB, Mul,
4003 cast<VPWidenRecipe>(Sub), Red);
4004 return new VPExpressionRecipe(RecipeA, RecipeB, Mul, Red);
4005 }
4006 // TODO: Add an expression type for this variant with a negated mul
4007 if (!Sub && IsMulAccValidAndClampRange(Mul, nullptr, nullptr, nullptr))
4008 return new VPExpressionRecipe(Mul, Red);
4009 }
4010 // TODO: Add an expression type for negated versions of other expression
4011 // variants.
4012 if (Sub)
4013 return nullptr;
4014
4015 // Match reduce.add(ext(mul(A, B))).
4016 if (match(VecOp, m_ZExtOrSExt(m_Mul(m_VPValue(A), m_VPValue(B))))) {
4017 auto *Ext = cast<VPWidenCastRecipe>(VecOp);
4018 auto *Mul = cast<VPWidenRecipe>(Ext->getOperand(0));
4019 auto *Ext0 = dyn_cast<VPWidenCastRecipe>(A);
4020 auto *Ext1 = dyn_cast<VPWidenCastRecipe>(B);
4021
4022 // reduce.add(ext(mul(ext, const)))
4023 // -> reduce.add(ext(mul(ext, ext(const))))
4024 ExtendAndReplaceConstantOp(Ext0, Ext1, B, Mul);
4025
4026 // reduce.add(ext(mul(ext(A), ext(B))))
4027 // -> reduce.add(mul(wider_ext(A), wider_ext(B)))
4028 // The inner extends must either have the same opcode as the outer extend or
4029 // be the same sext, in which case the multiply cannot result in a negative
4030 // value without wrapping. If the narrow mul cannot wrap, the outer extend
4031 // can be folded away by doing wider extends for the operands of the mul.
4032 if (Ext0 && Ext1 &&
4033 (Ext->getOpcode() == Ext0->getOpcode() ||
4034 (Ext0 == Ext1 && Ext0->getOpcode() == Instruction::SExt)) &&
4035 Ext0->getOpcode() == Ext1->getOpcode() && Mul->hasOneUse() &&
4037 IsMulAccValidAndClampRange(Mul, Ext0, Ext1, Ext)) {
4038 auto *NewExt0 = new VPWidenCastRecipe(
4039 Ext0->getOpcode(), Ext0->getOperand(0), Ext->getScalarType(), nullptr,
4040 *Ext0, *Ext0, Ext0->getDebugLoc());
4041 NewExt0->insertBefore(Ext0);
4042
4043 VPWidenCastRecipe *NewExt1 = NewExt0;
4044 if (Ext0 != Ext1) {
4045 NewExt1 = new VPWidenCastRecipe(Ext1->getOpcode(), Ext1->getOperand(0),
4046 Ext->getScalarType(), nullptr, *Ext1,
4047 *Ext1, Ext1->getDebugLoc());
4048 NewExt1->insertBefore(Ext1);
4049 }
4050 auto *NewMul = Mul->cloneWithOperands({NewExt0, NewExt1});
4051 NewMul->insertBefore(Mul);
4052 Ext->replaceAllUsesWith(NewMul);
4053 Ext->eraseFromParent();
4054 Mul->eraseFromParent();
4055 return new VPExpressionRecipe(NewExt0, NewExt1, NewMul, Red);
4056 }
4057 }
4058 return nullptr;
4059}
4060
4061/// This function tries to create abstract recipes from the reduction recipe for
4062/// following optimizations and cost estimation.
4064 VPCostContext &Ctx,
4065 VFRange &Range) {
4066 // Creation of VPExpressions for partial reductions is entirely handled in
4067 // transformToPartialReduction.
4068 if (Red->isPartialReduction())
4069 return;
4070
4071 VPExpressionRecipe *AbstractR = nullptr;
4072 auto IP = std::next(Red->getIterator());
4073 if (auto *MulAcc = tryToMatchAndCreateMulAccumulateReduction(Red, Ctx, Range))
4074 AbstractR = MulAcc;
4075 else if (auto *ExtRed = tryToMatchAndCreateExtendedReduction(Red, Ctx, Range))
4076 AbstractR = ExtRed;
4077 // Cannot create abstract inloop reduction recipes.
4078 if (!AbstractR)
4079 return;
4080
4081 AbstractR->insertBefore(IP);
4082 Red->replaceAllUsesWith(AbstractR);
4083}
4084
4094
4095// Collect common metadata from a group of replicate recipes by intersecting
4096// metadata from all recipes in the group.
4098 VPIRMetadata CommonMetadata = *Recipes.front();
4099 for (VPReplicateRecipe *Recipe : drop_begin(Recipes))
4100 CommonMetadata.intersect(*Recipe);
4101 // The recipe using the common metadata is not predicated, so it does not
4102 // share the group's execution frequency.
4103 CommonMetadata.clearExecutionFrequency();
4104 return CommonMetadata;
4105}
4106
4107template <unsigned Opcode>
4111 const Loop *L) {
4112 static_assert(Opcode == Instruction::Load || Opcode == Instruction::Store,
4113 "Only Load and Store opcodes supported");
4114
4115 // For each address, collect operations with the same or complementary masks.
4118 Plan, PSE, L,
4119 [](VPReplicateRecipe *RepR) { return RepR->isPredicated(); });
4120 for (auto Recipes : Groups) {
4121 if (Recipes.size() < 2)
4122 continue;
4123
4125 "Expected all recipes in group to have the same load-store type");
4126
4127 // Collect groups with the same or complementary masks.
4128 for (VPReplicateRecipe *&RecipeI : Recipes) {
4129 if (!RecipeI)
4130 continue;
4131
4132 VPValue *MaskI = RecipeI->getMask();
4134 Group.push_back(RecipeI);
4135 RecipeI = nullptr;
4136
4137 // Find all operations with the same or complementary masks.
4138 bool HasComplementaryMask = false;
4139 for (VPReplicateRecipe *&RecipeJ : Recipes) {
4140 if (!RecipeJ)
4141 continue;
4142
4143 VPValue *MaskJ = RecipeJ->getMask();
4144 // Check if any operation in the group has a complementary mask with
4145 // another, that is M1 == NOT(M2) or M2 == NOT(M1).
4146 HasComplementaryMask |= match(MaskI, m_Not(m_Specific(MaskJ))) ||
4147 match(MaskJ, m_Not(m_Specific(MaskI)));
4148 Group.push_back(RecipeJ);
4149 RecipeJ = nullptr;
4150 }
4151
4152 if (HasComplementaryMask) {
4153 assert(Group.size() >= 2 && "must have at least 2 entries");
4154 AllGroups.push_back(std::move(Group));
4155 }
4156 }
4157 }
4158
4159 return AllGroups;
4160}
4161
4162// Find the recipe with minimum alignment in the group.
4163template <typename InstType>
4164static VPReplicateRecipe *
4166 return *min_element(Group, [](VPReplicateRecipe *A, VPReplicateRecipe *B) {
4167 return cast<InstType>(A->getUnderlyingInstr())->getAlign() <
4168 cast<InstType>(B->getUnderlyingInstr())->getAlign();
4169 });
4170}
4171
4174 const Loop *L) {
4175 auto Groups =
4177 if (Groups.empty())
4178 return;
4179
4180 // Process each group of loads.
4181 for (auto &Group : Groups) {
4182 // Try to use the earliest (most dominating) load to replace all others.
4183 VPReplicateRecipe *EarliestLoad = Group[0];
4184 VPBasicBlock *FirstBB = EarliestLoad->getParent();
4185 VPBasicBlock *LastBB = Group.back()->getParent();
4186
4187 // Check that the load doesn't alias with stores between first and last.
4188 auto LoadLoc = vputils::getMemoryLocation(*EarliestLoad);
4189 if (!LoadLoc || !canHoistOrSinkWithNoAliasCheck(*LoadLoc, FirstBB, LastBB))
4190 continue;
4191
4192 // Collect common metadata from all loads in the group.
4193 VPIRMetadata CommonMetadata = getCommonMetadata(Group);
4194
4195 // Find the load with minimum alignment to use.
4196 auto *LoadWithMinAlign = findRecipeWithMinAlign<LoadInst>(Group);
4197
4198 bool IsSingleScalar = EarliestLoad->isSingleScalar();
4199 assert(all_of(Group,
4200 [IsSingleScalar](VPReplicateRecipe *R) {
4201 return R->isSingleScalar() == IsSingleScalar;
4202 }) &&
4203 "all members in group must agree on IsSingleScalar");
4204
4205 // The address is used for the lanes of all loads in the group, so only
4206 // keep flags valid for all their addresses.
4207 if (auto *AddrR =
4208 dyn_cast<VPRecipeWithIRFlags>(EarliestLoad->getOperand(0))) {
4209 for (VPReplicateRecipe *Load : drop_begin(Group)) {
4210 auto *OtherR = dyn_cast<VPRecipeWithIRFlags>(Load->getOperand(0));
4211 if (OtherR && OtherR->getVPRecipeID() == AddrR->getVPRecipeID() &&
4212 vputils::getOpcode(OtherR) == vputils::getOpcode(AddrR))
4213 AddrR->intersectFlags(*OtherR);
4214 else
4215 AddrR->dropPoisonGeneratingFlags();
4216 }
4217 }
4218
4219 // Create an unpredicated version of the earliest load with common
4220 // metadata.
4221 auto *UnpredicatedLoad = new VPReplicateRecipe(
4222 LoadWithMinAlign->getUnderlyingInstr(), {EarliestLoad->getOperand(0)},
4223 IsSingleScalar, /*Mask=*/nullptr, *EarliestLoad, CommonMetadata);
4224
4225 UnpredicatedLoad->insertBefore(EarliestLoad);
4226
4227 // Replace all loads in the group with the unpredicated load.
4228 for (VPReplicateRecipe *Load : Group) {
4229 Load->replaceAllUsesWith(UnpredicatedLoad);
4230 Load->eraseFromParent();
4231 }
4232 }
4233}
4234
4235static bool
4237 PredicatedScalarEvolution &PSE, const Loop &L) {
4238 auto StoreLoc = vputils::getMemoryLocation(*StoresToSink.front());
4239 if (!StoreLoc || !StoreLoc->AATags.Scope)
4240 return false;
4241
4242 // When sinking a group of stores, all members of the group alias each other.
4243 // Skip them during the alias checks.
4244 VPBasicBlock *FirstBB = StoresToSink.front()->getParent();
4245 VPBasicBlock *LastBB = StoresToSink.back()->getParent();
4246 SinkStoreInfo SinkInfo(StoresToSink, *StoresToSink[0], PSE, L);
4247 return canHoistOrSinkWithNoAliasCheck(*StoreLoc, FirstBB, LastBB, SinkInfo);
4248}
4249
4252 const Loop *L) {
4253 auto Groups =
4255 if (Groups.empty())
4256 return;
4257
4258 for (auto &Group : Groups) {
4259 if (!canSinkStoreWithNoAliasCheck(Group, PSE, *L))
4260 continue;
4261
4262 // Use the last (most dominated) store's location for the unconditional
4263 // store.
4264 VPReplicateRecipe *LastStore = Group.back();
4265
4266 // Collect common alias metadata from all stores in the group.
4267 VPIRMetadata CommonMetadata = getCommonMetadata(Group);
4268
4269 // Build select chain for stored values.
4270 VPValue *SelectedValue = Group[0]->getOperand(0);
4271 VPBuilder Builder(LastStore);
4272
4273 bool IsSingleScalar = Group[0]->isSingleScalar();
4274 for (unsigned I = 1; I < Group.size(); ++I) {
4275 assert(IsSingleScalar == Group[I]->isSingleScalar() &&
4276 "all members in group must agree on IsSingleScalar");
4277 VPValue *Mask = Group[I]->getMask();
4278 VPValue *Value = Group[I]->getOperand(0);
4279 SelectedValue = Builder.createSelect(
4280 Mask, Value, SelectedValue, Group[I]->getDebugLoc(), "",
4281 VPIRFlags::getDefaultFlags(Instruction::Select,
4282 Value->getScalarType()));
4283 }
4284
4285 // Find the store with minimum alignment to use.
4286 auto *StoreWithMinAlign = findRecipeWithMinAlign<StoreInst>(Group);
4287
4288 // Create unconditional store with selected value and common metadata.
4289 auto *UnpredicatedStore = new VPReplicateRecipe(
4290 StoreWithMinAlign->getUnderlyingInstr(),
4291 {SelectedValue, LastStore->getOperand(1)}, IsSingleScalar,
4292 /*Mask=*/nullptr, *LastStore, CommonMetadata);
4293 UnpredicatedStore->insertBefore(LastStore);
4294
4295 // Remove all predicated stores from the group.
4296 for (VPReplicateRecipe *Store : Group)
4297 Store->eraseFromParent();
4298 }
4299}
4300
4302 unsigned UF,
4303 const TargetTransformInfo &TTI) {
4304 assert(UF > 1 && "Expected plan to have an UF > 1");
4305
4306 auto m_ContiguousVecPtr = m_VecPtr(m_VPValue(), m_One());
4307 VPValue *Multiplier = Plan.getConstantInt(64, 1);
4308
4309 VPActiveLaneMaskPHIRecipe *MaskPhi = nullptr;
4312 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
4313 VPValue *Mask = nullptr;
4314 VPValue *StoredValue = nullptr;
4315 if (!match(&R,
4317 m_WidenLoad(m_ContiguousVecPtr),
4318 m_WidenStore(m_ContiguousVecPtr, m_VPValue(StoredValue)),
4319 m_MaskedLoad(m_ContiguousVecPtr, m_VPValue(Mask)),
4320 m_MaskedStore(m_ContiguousVecPtr, m_VPValue(StoredValue),
4321 m_VPValue(Mask)))))
4322 continue;
4323
4324 auto *MemOp = cast<VPWidenMemoryRecipe>(&R);
4325 assert(MemOp->isConsecutive() && "Expected consecutive load/store");
4326
4327 // If there's a mask, ensure it's a wide active-lane-mask.
4330 continue;
4331
4332 auto MaskSource = MemOp->isMasked()
4335
4336 Type *AccessType = StoredValue ? StoredValue->getScalarType()
4337 : R.getVPSingleValue()->getScalarType();
4338 bool IsStore = isa<VPWidenStoreRecipe>(MemOp->getAsRecipe());
4339 std::optional<Instruction::CastOps> CastHint;
4340 VPUser *MaybeCast = IsStore ? StoredValue->getDefiningRecipe()
4341 : R.getVPSingleValue()->getSingleUser();
4342 if (auto *Cast = dyn_cast_if_present<VPWidenCastRecipe>(MaybeCast))
4343 CastHint = Cast->getOpcode();
4344
4345 VectorType *VectorAccessType = VectorType::get(AccessType, VF);
4346 if (!TTI.hasMultiVectorLoadStore(/*NumVectors=*/UF, MaskSource,
4347 VectorAccessType, IsStore, CastHint))
4348 continue;
4349
4350 DebugLoc DL = R.getDebugLoc();
4351 VPValue *Ptr = MemOp->getAddr();
4352 VPValue *Align = Plan.getConstantInt(64, MemOp->getAlign().value());
4353
4354 VPBuilder Builder(&R);
4355 VPInstruction *NewMemOp;
4356 if (IsStore) {
4357 VPValue *WideStoredValue = Builder.createNaryOp(
4358 VPInstruction::ConcatVectors, {StoredValue}, DL);
4359 NewMemOp = Builder.createNaryOp(
4361 {Multiplier, Ptr, Align, WideStoredValue}, nullptr, {}, *MemOp, DL);
4362 } else {
4363 VPValue *OldLoad = R.getVPSingleValue();
4364 NewMemOp = Builder.createNaryOp(
4365 VPInstruction::WideVectorLoad, {Multiplier, Ptr, Align}, nullptr,
4366 {}, *MemOp, DL, "", OldLoad->getScalarType());
4367 VPValue *Extract =
4368 Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
4369 {NewMemOp, Plan.getConstantInt(64, 0)}, DL);
4370 OldLoad->replaceAllUsesWith(Extract);
4371 }
4372
4373 R.eraseFromParent();
4374 if (Mask) {
4375 assert((!MaskPhi || Mask == MaskPhi) && "Expected a single mask phi");
4376 NewMemOp->addMask(Mask);
4377 MaskPhi = cast<VPActiveLaneMaskPHIRecipe>(Mask);
4378 }
4379 }
4380 }
4381
4382 if (!MaskPhi)
4383 return;
4384
4385 // Widen the mask phi to match the width of the masked loads/stores. This
4386 // effectively means removing the `extract-vector-for-part` from the preheader
4387 // and latch instead placing a single extract in the header. The
4388 // wide-vector-load/store operations can use the mask phi directly.
4389 auto *EntryMask = cast<VPInstruction>(MaskPhi->getStartValue());
4390 auto *LoopMask = cast<VPInstruction>(MaskPhi->getBackedgeValue());
4391 auto *EntryALM = cast<VPInstruction>(EntryMask->getOperand(0));
4392 auto *LoopALM = cast<VPInstruction>(LoopMask->getOperand(0));
4393
4394 assert((EntryALM->getOpcode() == VPInstruction::WideActiveLaneMask &&
4395 LoopALM->getOpcode() == VPInstruction::WideActiveLaneMask) &&
4396 "Expected incoming values of Phi to be WideActiveLaneMask");
4397
4398 auto Builder = VPBuilder(&*MaskPhi->getParent()->getFirstNonPhi());
4399 auto *MaskPart = Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
4400 {MaskPhi, Plan.getConstantInt(64, 0)});
4401
4402 MaskPhi->replaceUsesWithIf(
4403 MaskPart, match_fn(m_Unless(m_CombineOr(
4404 m_Specific(MaskPart),
4407
4408 // Remove extra ExtractVectorForPart operations.
4409 assert(EntryMask->getOpcode() == VPInstruction::ExtractVectorForPart &&
4410 LoopMask->getOpcode() == VPInstruction::ExtractVectorForPart &&
4411 "Expected entry/loop extract-vector-for-part ops");
4412 EntryMask->replaceAllUsesWith(EntryALM);
4413 LoopMask->replaceAllUsesWith(LoopALM);
4414}
4415
4416/// Returns true if \p V is VPWidenLoadRecipe or VPInterleaveRecipe that can be
4417/// converted to a narrower recipe. \p V is used by a wide recipe that feeds a
4418/// store interleave group at index \p Idx, \p WideMember0 is the recipe feeding
4419/// the same interleave group at index 0. A VPWidenLoadRecipe can be narrowed to
4420/// an index-independent load if it feeds all wide ops at all indices (\p OpV
4421/// must be the operand at index \p OpIdx for both the recipe at lane 0, \p
4422/// WideMember0). A VPInterleaveRecipe can be narrowed to a wide load, if \p V
4423/// is defined at \p Idx of a load interleave group.
4424/// A live-in or recipe defined outside the loop region can be converted, if it
4425/// is the same across all lanes, or we can create a BuildVector for it.
4426static bool canNarrowLoad(VPSingleDefRecipe *WideMember0, unsigned OpIdx,
4427 VPValue *OpV, unsigned Idx, bool IsScalable) {
4428 VPValue *Member0Op = WideMember0->getOperand(OpIdx);
4429 if (Member0Op->isDefinedOutsideLoopRegions()) {
4430 // Operand matches Member0, broadcast across all fields for both live-ins
4431 // and recipes.
4432 if (Member0Op == OpV)
4433 return true;
4434 // Otherwise distinct per-field VPValues are assembled into a BuildVector.
4435 return !IsScalable && OpV->isDefinedOutsideLoopRegions() &&
4436 OpV->getScalarType() == Member0Op->getScalarType();
4437 }
4438 VPRecipeBase *Member0OpR = Member0Op->getDefiningRecipe();
4439 if (auto *W = dyn_cast<VPWidenLoadRecipe>(Member0OpR))
4440 // For scalable VFs, the narrowed plan processes vscale iterations at once,
4441 // so a shared wide load cannot be narrowed to a uniform scalar; bail out.
4442 return !IsScalable && !W->getMask() && W->isConsecutive() &&
4443 Member0Op == OpV;
4444 if (auto *IR = dyn_cast<VPInterleaveRecipe>(Member0OpR))
4445 return IR->getInterleaveGroup()->isFull() && IR->getVPValue(Idx) == OpV;
4446 return false;
4447}
4448
4449/// Returns true if the wide recipes in \p Ops and their operand trees can be
4450/// narrowed. \p FirstMembersOf maps each in-loop value to the first member
4451/// list it was seen in, across all store groups.
4452static bool
4454 DenseMap<VPValue *, SmallVector<VPValue *>> &FirstMembersOf) {
4455 auto *WideMember0 = dyn_cast<VPRecipeWithIRFlags>(Ops[0]);
4456 if (!WideMember0)
4457 return false;
4458 for (VPValue *V : Ops) {
4460 return false;
4461 auto *R = cast<VPRecipeWithIRFlags>(V);
4462 if (vputils::getOpcode(R) != vputils::getOpcode(WideMember0))
4463 return false;
4464 if (R->getScalarType() != WideMember0->getScalarType())
4465 return false;
4466 if (R->hasPredicate() && R->getPredicate() != WideMember0->getPredicate())
4467 return false;
4468 }
4469
4470 // The first member is narrowed in place using the other members' operands.
4471 // Bail out if a value is the first member of one list and also part of a
4472 // different list.
4473 for (VPValue *V : Ops) {
4474 if (V->isDefinedOutsideLoopRegions())
4475 continue;
4476 auto [It, Inserted] = FirstMembersOf.try_emplace(V, Ops);
4477 if (!Inserted && (It->second.front() == V || V == WideMember0) &&
4478 !equal(It->second, Ops))
4479 return false;
4480 }
4481
4482 for (unsigned Idx = 0; Idx != WideMember0->getNumOperands(); ++Idx) {
4484 for (VPValue *Op : Ops)
4485 OpsI.push_back(Op->getDefiningRecipe()->getOperand(Idx));
4486
4487 if (canNarrowOps(OpsI, IsScalable, FirstMembersOf))
4488 continue;
4489
4490 if (any_of(enumerate(OpsI), [WideMember0, Idx, IsScalable](const auto &P) {
4491 const auto &[OpIdx, OpV] = P;
4492 return !canNarrowLoad(WideMember0, Idx, OpV, OpIdx, IsScalable);
4493 }))
4494 return false;
4495 }
4496
4497 return true;
4498}
4499
4500/// Returns VF from \p VFs if \p IR is a full interleave group with factor and
4501/// number of members both equal to VF. The interleave group must also access
4502/// the full vector width.
4503static std::optional<ElementCount>
4506 const TargetTransformInfo &TTI) {
4507 if (!InterleaveR || InterleaveR->getMask())
4508 return std::nullopt;
4509
4510 Type *GroupElementTy = nullptr;
4511 if (InterleaveR->getStoredValues().empty()) {
4512 GroupElementTy = InterleaveR->getVPValue(0)->getScalarType();
4513 if (!all_of(InterleaveR->definedValues(), [GroupElementTy](VPValue *Op) {
4514 return Op->getScalarType() == GroupElementTy;
4515 }))
4516 return std::nullopt;
4517 } else {
4518 GroupElementTy = InterleaveR->getStoredValues()[0]->getScalarType();
4519 if (!all_of(InterleaveR->getStoredValues(), [GroupElementTy](VPValue *Op) {
4520 return Op->getScalarType() == GroupElementTy;
4521 }))
4522 return std::nullopt;
4523 }
4524
4525 auto IG = InterleaveR->getInterleaveGroup();
4526 if (IG->getFactor() != IG->getNumMembers() || IG->isReverse())
4527 return std::nullopt;
4528
4529 auto GetVectorBitWidthForVF = [&TTI](ElementCount VF) {
4530 TypeSize Size = TTI.getRegisterBitWidth(
4533 assert(Size.isScalable() == VF.isScalable() &&
4534 "if Size is scalable, VF must be scalable and vice versa");
4535 return Size.getKnownMinValue();
4536 };
4537
4538 for (ElementCount VF : VFs) {
4539 unsigned MinVal = VF.getKnownMinValue();
4540 unsigned GroupSize = GroupElementTy->getScalarSizeInBits() * MinVal;
4541 if (IG->getFactor() == MinVal && GroupSize == GetVectorBitWidthForVF(VF))
4542 return {VF};
4543 }
4544 return std::nullopt;
4545}
4546
4547/// Returns true if \p VPValue is a narrow VPValue.
4548static bool isAlreadyNarrow(VPValue *VPV) {
4549 if (isa<VPIRValue>(VPV))
4550 return true;
4551 auto *RepR = dyn_cast<VPReplicateRecipe>(VPV);
4552 return RepR && RepR->isSingleScalar();
4553}
4554
4555// Convert the wide recipes defining the VPValues in \p Members feeding an
4556// interleave group to a single narrow variant. The first member is reused as
4557// the narrowed recipe. BuildVectors for live-in operands are inserted into \p
4558// Preheader.
4560 SmallPtrSetImpl<VPValue *> &NarrowedOps,
4561 VPBasicBlock *Preheader) {
4562 VPValue *V = Members.front();
4563 if (NarrowedOps.contains(V))
4564 return V;
4565
4566 if (V->isDefinedOutsideLoopRegions()) {
4567 assert(all_of(Members,
4568 [V](VPValue *M) {
4569 return M->isDefinedOutsideLoopRegions() &&
4570 M->getScalarType() == V->getScalarType();
4571 }) &&
4572 "expected distinct loop-invariant values of matching scalar type");
4573 auto *BV = new VPInstruction(VPInstruction::BuildVector, Members);
4574 Preheader->appendRecipe(BV);
4575 NarrowedOps.insert(BV);
4576 return BV;
4577 }
4578
4579 if (isAlreadyNarrow(V))
4580 return V;
4581
4582 VPRecipeBase *R = V->getDefiningRecipe();
4584 auto *WideMember0 = cast<VPRecipeWithIRFlags>(R);
4585 for (VPValue *Member : Members.drop_front())
4586 WideMember0->intersectFlags(*cast<VPRecipeWithIRFlags>(Member));
4587 for (unsigned Idx = 0, E = WideMember0->getNumOperands(); Idx != E; ++Idx) {
4589 for (VPValue *Member : Members)
4590 OpsI.push_back(Member->getDefiningRecipe()->getOperand(Idx));
4591 WideMember0->setOperand(
4592 Idx, narrowInterleaveGroupOp(OpsI, NarrowedOps, Preheader));
4593 }
4594 return V;
4595 }
4596
4597 if (auto *LoadGroup = dyn_cast<VPInterleaveRecipe>(R)) {
4598 // Narrow interleave group to wide load, as transformed VPlan will only
4599 // process one original iteration.
4600 const InterleaveGroup<Instruction> *IG = LoadGroup->getInterleaveGroup();
4601 auto *LI = cast<LoadInst>(IG->getInsertPos());
4602 auto *L = VPBuilder(LoadGroup).createWidenLoad(
4603 *LI, LoadGroup->getAddr(), LoadGroup->getMask(), /*Consecutive=*/true,
4604 IG->getAlign(), *LoadGroup, LoadGroup->getDebugLoc());
4605 NarrowedOps.insert(L);
4606 return L;
4607 }
4608
4609 auto *WideLoad = cast<VPWidenLoadRecipe>(R);
4610 VPValue *PtrOp = WideLoad->getAddr();
4611 if (auto *VecPtr = dyn_cast<VPVectorPointerRecipe>(PtrOp))
4612 PtrOp = VecPtr->getOperand(0);
4613 // Narrow wide load to uniform scalar load, as transformed VPlan will only
4614 // process one original iteration.
4615 auto *N = new VPReplicateRecipe(&WideLoad->getIngredient(), {PtrOp},
4616 /*IsUniform*/ true,
4617 /*Mask*/ nullptr, {}, *WideLoad);
4618 N->insertBefore(WideLoad);
4619 NarrowedOps.insert(N);
4620 return N;
4621}
4622
4623std::unique_ptr<VPlan>
4625 const TargetTransformInfo &TTI) {
4626 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
4627
4628 if (!VectorLoop)
4629 return nullptr;
4630
4631 // Only handle single-block loops for now.
4632 if (VectorLoop->getEntryBasicBlock() != VectorLoop->getExitingBasicBlock())
4633 return nullptr;
4634
4635 // Skip plans when we may not be able to properly narrow.
4636 VPBasicBlock *Exiting = VectorLoop->getExitingBasicBlock();
4637 if (!match(&Exiting->back(), m_BranchOnCount()))
4638 return nullptr;
4639
4640 assert(match(&Exiting->back(),
4642 m_Specific(&Plan.getVectorTripCount()))) &&
4643 "unexpected branch-on-count");
4644
4647 std::optional<ElementCount> VFToOptimize;
4648 for (auto &R : *VectorLoop->getEntryBasicBlock()) {
4651 continue;
4652
4653 // Bail out on recipes not supported at the moment:
4654 // * phi recipes other than the canonical induction
4655 // * recipes writing to memory except interleave groups
4656 // Only support plans with a canonical induction phi.
4657 if (R.isPhi())
4658 return nullptr;
4659
4660 auto *InterleaveR = dyn_cast<VPInterleaveRecipe>(&R);
4661 if (R.mayWriteToMemory() && !InterleaveR)
4662 return nullptr;
4663
4664 // Bail out if any recipe defines a vector value used outside the
4665 // vector loop region.
4666 if (any_of(R.definedValues(), [&](VPValue *V) {
4667 return any_of(V->users(), [&](VPUser *U) {
4668 auto *UR = cast<VPRecipeBase>(U);
4669 return UR->getParent()->getParent() != VectorLoop;
4670 });
4671 }))
4672 return nullptr;
4673
4674 // All other ops are allowed, but we reject uses that cannot be converted
4675 // when checking all allowed consumers (store interleave groups) below.
4676 if (!InterleaveR)
4677 continue;
4678
4679 // Try to find a single VF, where all interleave groups are consecutive and
4680 // saturate the full vector width. If we already have a candidate VF, check
4681 // if it is applicable for the current InterleaveR, otherwise look for a
4682 // suitable VF across the Plan's VFs.
4684 VFToOptimize ? SmallVector<ElementCount>({*VFToOptimize})
4685 : to_vector(Plan.vectorFactors());
4686 std::optional<ElementCount> NarrowedVF =
4687 isConsecutiveInterleaveGroup(InterleaveR, VFs, TTI);
4688 if (!NarrowedVF || (VFToOptimize && NarrowedVF != VFToOptimize))
4689 return nullptr;
4690 VFToOptimize = NarrowedVF;
4691
4692 // Skip read interleave groups.
4693 if (InterleaveR->getStoredValues().empty())
4694 continue;
4695
4696 // Narrow interleave groups, if all operands are already matching narrow
4697 // ops.
4698 auto *Member0 = InterleaveR->getStoredValues()[0];
4699 if (isAlreadyNarrow(Member0) &&
4700 all_of(InterleaveR->getStoredValues(), equal_to(Member0))) {
4701 StoreGroups.push_back(InterleaveR);
4702 continue;
4703 }
4704
4705 // For now, we only support full interleave groups storing a single full
4706 // load interleave group in order.
4707 auto *LoadGroup =
4708 dyn_cast_or_null<VPInterleaveRecipe>(Member0->getDefiningRecipe());
4709 if (LoadGroup && LoadGroup->getInterleaveGroup()->isFull() &&
4710 all_of(enumerate(InterleaveR->getStoredValues()), [LoadGroup](auto Op) {
4711 return LoadGroup->getVPValue(Op.index()) == Op.value();
4712 })) {
4713 StoreGroups.push_back(InterleaveR);
4714 continue;
4715 }
4716
4717 // Check if all values feeding InterleaveR are matching wide recipes whose
4718 // operands can be narrowed, without conflicting uses across groups.
4719 if (!canNarrowOps(InterleaveR->getStoredValues(),
4720 VFToOptimize->isScalable(), FirstMembersOf))
4721 return nullptr;
4722 StoreGroups.push_back(InterleaveR);
4723 }
4724
4725 if (StoreGroups.empty())
4726 return nullptr;
4727
4728 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
4729 bool RequiresScalarEpilogue =
4730 MiddleVPBB->getNumSuccessors() == 1 &&
4731 MiddleVPBB->getSingleSuccessor() == Plan.getScalarPreheader();
4732 // Bail out for tail-folding (middle block with a single successor to exit).
4733 if (MiddleVPBB->getNumSuccessors() != 2 && !RequiresScalarEpilogue)
4734 return nullptr;
4735
4736 // All interleave groups in Plan can be narrowed for VFToOptimize. Split the
4737 // original Plan into 2: a) a new clone which contains all VFs of Plan, except
4738 // VFToOptimize, and b) the original Plan with VFToOptimize as single VF.
4739 // TODO: Handle cases where only some interleave groups can be narrowed.
4740 std::unique_ptr<VPlan> NewPlan;
4741 if (size(Plan.vectorFactors()) != 1) {
4742 NewPlan = std::unique_ptr<VPlan>(Plan.duplicate());
4743 Plan.setVF(*VFToOptimize);
4744 NewPlan->removeVF(*VFToOptimize);
4745 }
4746
4747 // Convert InterleaveGroup \p R to a single VPWidenLoadRecipe.
4748 SmallPtrSet<VPValue *, 4> NarrowedOps;
4749 VPBasicBlock *Preheader = Plan.getVectorPreheader();
4750 // Narrow operation tree rooted at store groups.
4751 for (auto *StoreGroup : StoreGroups) {
4752 VPValue *Res = narrowInterleaveGroupOp(StoreGroup->getStoredValues(),
4753 NarrowedOps, Preheader);
4754 const InterleaveGroup<Instruction> *IG = StoreGroup->getInterleaveGroup();
4755 auto *SI = cast<StoreInst>(IG->getInsertPos());
4756 VPBuilder(StoreGroup)
4757 .createWidenStore(*SI, StoreGroup->getAddr(), Res, nullptr,
4758 /*Consecutive=*/true, IG->getAlign(), *StoreGroup,
4759 StoreGroup->getDebugLoc());
4760 StoreGroup->eraseFromParent();
4761 }
4762
4763 // Adjust induction to reflect that the transformed plan only processes one
4764 // original iteration.
4766 Type *CanIVTy = VectorLoop->getCanonicalIVType();
4767 VPBasicBlock *VectorPH = Plan.getVectorPreheader();
4768 VPBuilder PHBuilder(VectorPH->getFirstNonPhi());
4769
4770 VPValue *UF = &Plan.getUF();
4771 VPValue *Step;
4772 if (VFToOptimize->isScalable()) {
4773 VPValue *VScale =
4774 PHBuilder.createElementCount(CanIVTy, ElementCount::getScalable(1));
4775 Step = PHBuilder.createOverflowingOp(Instruction::Mul, {VScale, UF},
4776 {true, false});
4777 Plan.getVF().replaceAllUsesWith(VScale);
4778 } else {
4779 Step = UF;
4780 Plan.getVF().replaceAllUsesWith(Plan.getConstantInt(CanIVTy, 1));
4781 }
4782 // Materialize vector trip count with the narrowed step.
4783 materializeVectorTripCount(Plan, VectorPH, /*TailByMasking=*/false,
4784 RequiresScalarEpilogue, Step);
4785
4786 CanIVInc->setOperand(1, Step);
4787 Plan.getVFxUF().replaceAllUsesWith(Step);
4788
4789 removeDeadRecipes(Plan);
4790 assert(none_of(*VectorLoop->getEntryBasicBlock(),
4792 "All VPVectorPointerRecipes should have been removed");
4793 return NewPlan;
4794}
4795
4797 VFRange &Range) {
4798 VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
4799 auto *MiddleVPBB = Plan.getMiddleBlock();
4800 VPBuilder MiddleBuilder(MiddleVPBB->getFirstNonPhi());
4801
4802 auto IsScalableOne = [](ElementCount VF) -> bool {
4803 return VF == ElementCount::getScalable(1);
4804 };
4805
4808 VectorRegion->getEntryBasicBlock()->phis())) {
4809 assert(VectorRegion->getSingleSuccessor() == Plan.getMiddleBlock() &&
4810 "Cannot handle loops with uncountable early exits");
4811
4812 // Find the existing splice for this FOR, created in
4813 // createHeaderPhiRecipes. All uses of FOR have already been replaced with
4814 // RecurSplice there; only RecurSplice itself still references FOR.
4815 auto *RecurSplice =
4817 assert(RecurSplice && "expected FirstOrderRecurrenceSplice");
4818
4819 // For VF vscale x 1, if vscale = 1, we are unable to extract the
4820 // penultimate value of the recurrence. Instead we rely on the existing
4821 // extract of the last element from the result of
4822 // VPInstruction::FirstOrderRecurrenceSplice.
4823 // TODO: Consider vscale_range info and UF.
4824 if (any_of(RecurSplice->users(),
4825 [](VPUser *U) { return !cast<VPRecipeBase>(U)->getRegion(); }) &&
4827 Range))
4828 return;
4829
4830 // This is the second phase of vectorizing first-order recurrences, creating
4831 // extracts for users outside the loop. An overview of the transformation is
4832 // described below. Suppose we have the following loop with some use after
4833 // the loop of the last a[i-1],
4834 //
4835 // for (int i = 0; i < n; ++i) {
4836 // t = a[i - 1];
4837 // b[i] = a[i] - t;
4838 // }
4839 // use t;
4840 //
4841 // There is a first-order recurrence on "a". For this loop, the shorthand
4842 // scalar IR looks like:
4843 //
4844 // scalar.ph:
4845 // s.init = a[-1]
4846 // br scalar.body
4847 //
4848 // scalar.body:
4849 // i = phi [0, scalar.ph], [i+1, scalar.body]
4850 // s1 = phi [s.init, scalar.ph], [s2, scalar.body]
4851 // s2 = a[i]
4852 // b[i] = s2 - s1
4853 // br cond, scalar.body, exit.block
4854 //
4855 // exit.block:
4856 // use = lcssa.phi [s1, scalar.body]
4857 //
4858 // In this example, s1 is a recurrence because it's value depends on the
4859 // previous iteration. In the first phase of vectorization, we created a
4860 // VPFirstOrderRecurrencePHIRecipe v1 for s1. Now we create the extracts
4861 // for users in the scalar preheader and exit block.
4862 //
4863 // vector.ph:
4864 // v_init = vector(..., ..., ..., a[-1])
4865 // br vector.body
4866 //
4867 // vector.body
4868 // i = phi [0, vector.ph], [i+4, vector.body]
4869 // v1 = phi [v_init, vector.ph], [v2, vector.body]
4870 // v2 = a[i, i+1, i+2, i+3]
4871 // v1' = splice(v1(3), v2(0, 1, 2))
4872 // b[i, i+1, i+2, i+3] = v2 - v1'
4873 // br cond, vector.body, middle.block
4874 //
4875 // middle.block:
4876 // vector.recur.extract.for.phi = v2(2)
4877 // vector.recur.extract = v2(3)
4878 // br cond, scalar.ph, exit.block
4879 //
4880 // scalar.ph:
4881 // scalar.recur.init = phi [vector.recur.extract, middle.block],
4882 // [s.init, otherwise]
4883 // br scalar.body
4884 //
4885 // scalar.body:
4886 // i = phi [0, scalar.ph], [i+1, scalar.body]
4887 // s1 = phi [scalar.recur.init, scalar.ph], [s2, scalar.body]
4888 // s2 = a[i]
4889 // b[i] = s2 - s1
4890 // br cond, scalar.body, exit.block
4891 //
4892 // exit.block:
4893 // lo = lcssa.phi [s1, scalar.body],
4894 // [vector.recur.extract.for.phi, middle.block]
4895 //
4896 // Update extracts of the splice in the middle block: they extract the
4897 // penultimate element of the recurrence.
4899 make_range(MiddleVPBB->getFirstNonPhi(), MiddleVPBB->end()))) {
4900 if (!match(&R, m_ExtractLastLaneOfLastPart(m_Specific(RecurSplice))))
4901 continue;
4902
4903 auto *ExtractR = cast<VPInstruction>(&R);
4904 VPValue *PenultimateElement = MiddleBuilder.createNaryOp(
4905 VPInstruction::ExtractPenultimateElement, RecurSplice->getOperand(1),
4906 {}, "vector.recur.extract.for.phi");
4907 for (VPUser *ExitU : to_vector(ExtractR->users())) {
4908 if (auto *ExitPhi = dyn_cast<VPIRPhi>(ExitU))
4909 ExitPhi->replaceUsesOfWith(ExtractR, PenultimateElement);
4910 }
4911 }
4912 }
4913}
4914
4915/// Check if \p V is a binary expression of a widened IV and a loop-invariant
4916/// value. Returns the widened IV if found, nullptr otherwise.
4918 auto *BinOp = dyn_cast<VPWidenRecipe>(V);
4919 if (!BinOp || !Instruction::isBinaryOp(BinOp->getOpcode()) ||
4920 Instruction::isIntDivRem(BinOp->getOpcode()))
4921 return nullptr;
4922
4923 VPValue *WidenIVCandidate = BinOp->getOperand(0);
4924 VPValue *InvariantCandidate = BinOp->getOperand(1);
4925 if (!isa<VPWidenIntOrFpInductionRecipe>(WidenIVCandidate))
4926 std::swap(WidenIVCandidate, InvariantCandidate);
4927
4928 if (!InvariantCandidate->isDefinedOutsideLoopRegions())
4929 return nullptr;
4930
4931 return dyn_cast<VPWidenIntOrFpInductionRecipe>(WidenIVCandidate);
4932}
4933
4934/// Create a scalar version of \p BinOp, with its \p WidenIV operand replaced
4935/// by \p ScalarIV, and place it after \p ScalarIV's defining recipe.
4939 BinOp->getNumOperands() == 2 && "BinOp must have 2 operands");
4940 auto *ClonedOp = BinOp->clone();
4941 if (ClonedOp->getOperand(0) == WidenIV) {
4942 ClonedOp->setOperand(0, ScalarIV);
4943 } else {
4944 assert(ClonedOp->getOperand(1) == WidenIV && "one operand must be WideIV");
4945 ClonedOp->setOperand(1, ScalarIV);
4946 }
4947 ClonedOp->insertAfter(ScalarIV->getDefiningRecipe());
4948 return ClonedOp;
4949}
4950
4951/// If \p S is an affine AddRec, returns true if its step is known to be
4952/// positive and false if it is known to be negative. Returns std::nullopt if
4953/// \p S is not an affine AddRec, or if the sign of its step cannot be
4954/// determined.
4955static std::optional<bool> getStepDirection(const SCEV *S,
4956 ScalarEvolution &SE) {
4957 const SCEV *Step;
4958 if (!match(S, m_scev_AffineAddRec(m_SCEV(), m_SCEV(Step))))
4959 return std::nullopt;
4960 if (SE.isKnownPositive(Step))
4961 return true;
4962 if (SE.isKnownNegative(Step))
4963 return false;
4964 return std::nullopt;
4965}
4966
4969 Loop &L) {
4970 ScalarEvolution &SE = *PSE.getSE();
4971 VPRegionBlock *VectorLoopRegion = Plan.getVectorLoopRegion();
4972
4973 // Helper lambda to check if the IV range excludes the sentinel value. Try
4974 // signed first, then unsigned. Return an excluded sentinel if found,
4975 // otherwise return std::nullopt.
4976 auto CheckSentinel = [&SE](const SCEV *IVSCEV,
4977 bool UseMax) -> std::optional<APSInt> {
4978 unsigned BW = IVSCEV->getType()->getScalarSizeInBits();
4979 for (bool Signed : {true, false}) {
4980 APSInt Sentinel = UseMax ? APSInt::getMinValue(BW, /*Unsigned=*/!Signed)
4981 : APSInt::getMaxValue(BW, /*Unsigned=*/!Signed);
4982
4983 ConstantRange IVRange =
4984 Signed ? SE.getSignedRange(IVSCEV) : SE.getUnsignedRange(IVSCEV);
4985 if (!IVRange.contains(Sentinel))
4986 return Sentinel;
4987 }
4988 return std::nullopt;
4989 };
4990
4991 VPValue *HeaderMask = VectorLoopRegion->getHeaderMask();
4992 for (VPRecipeBase &Phi :
4993 make_early_inc_range(VectorLoopRegion->getEntryBasicBlock()->phis())) {
4994 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&Phi);
4996 PhiR->getRecurrenceKind()))
4997 continue;
4998
4999 Type *PhiTy = PhiR->getScalarType();
5000 if (PhiTy->isPointerTy() || PhiTy->isFloatingPointTy())
5001 continue;
5002
5003 // If there's a header mask, the backedge select will not be the find-last
5004 // select.
5005 VPValue *BackedgeVal = PhiR->getBackedgeValue();
5006 auto *FindLastSelect = cast<VPSingleDefRecipe>(BackedgeVal);
5007 if (HeaderMask &&
5008 !match(BackedgeVal,
5009 m_Select(m_Specific(HeaderMask),
5010 m_VPSingleDefRecipe(FindLastSelect), m_Specific(PhiR))))
5011 continue;
5012
5013 // Get the find-last expression from the find-last select of the reduction
5014 // phi. The find-last select should be a select between the phi and the
5015 // find-last expression.
5016 VPValue *Cond, *FindLastExpression;
5017 if (!match(FindLastSelect, m_SelectLike(m_VPValue(Cond), m_Specific(PhiR),
5018 m_VPValue(FindLastExpression))) &&
5019 !match(FindLastSelect,
5020 m_SelectLike(m_VPValue(Cond), m_VPValue(FindLastExpression),
5021 m_Specific(PhiR))))
5022 continue;
5023
5024 // Check if FindLastExpression is a simple expression of a widened IV. If
5025 // so, we can track the underlying IV instead and sink the expression.
5026 auto *IVOfExpressionToSink = getExpressionIV(FindLastExpression);
5027 const SCEV *IVSCEV = vputils::getSCEVExprForVPValue(
5028 IVOfExpressionToSink ? IVOfExpressionToSink : FindLastExpression, PSE,
5029 &L);
5030 if (!match(IVSCEV, m_scev_AffineAddRec(m_SCEV(), m_SCEV()))) {
5031 assert(!match(vputils::getSCEVExprForVPValue(FindLastExpression, PSE, &L),
5033 "IVOfExpressionToSink not being an AddRec must imply "
5034 "FindLastExpression not being an AddRec.");
5035 continue;
5036 }
5037
5038 // Determine direction from the step of IVSCEV, if possible.
5039 std::optional<bool> StepDirection = getStepDirection(IVSCEV, SE);
5040 if (!StepDirection)
5041 continue;
5042
5043 bool UseMax = *StepDirection;
5044 std::optional<APSInt> SentinelVal = CheckSentinel(IVSCEV, UseMax);
5045 bool UseSigned = SentinelVal && SentinelVal->isSigned();
5046
5047 // Sinking an expression will disable epilogue vectorization. Only use it,
5048 // if FindLastExpression cannot be vectorized via a sentinel. Sinking may
5049 // also prevent vectorizing using a sentinel (e.g., if the expression is a
5050 // multiply or divide by large constant, respectively), which also makes
5051 // sinking undesirable.
5052 if (IVOfExpressionToSink) {
5053 const SCEV *FindLastExpressionSCEV =
5054 vputils::getSCEVExprForVPValue(FindLastExpression, PSE, &L);
5055 if (std::optional<bool> NewUseMax =
5056 getStepDirection(FindLastExpressionSCEV, SE)) {
5057 if (auto NewSentinel =
5058 CheckSentinel(FindLastExpressionSCEV, *NewUseMax)) {
5059 // The original expression already has a sentinel, so prefer not
5060 // sinking to keep epilogue vectorization possible.
5061 SentinelVal = *NewSentinel;
5062 UseSigned = NewSentinel->isSigned();
5063 UseMax = *NewUseMax;
5064 IVSCEV = FindLastExpressionSCEV;
5065 IVOfExpressionToSink = nullptr;
5066 }
5067 }
5068 }
5069
5070 // If no sentinel was found, fall back to a boolean AnyOf reduction to track
5071 // if the condition was ever true. Requires the IV to not wrap, otherwise we
5072 // cannot use min/max.
5073 if (!SentinelVal) {
5074 auto *AR = cast<SCEVAddRecExpr>(IVSCEV);
5075 if (AR->hasNoSignedWrap())
5076 UseSigned = true;
5077 else if (AR->hasNoUnsignedWrap())
5078 UseSigned = false;
5079 else
5080 continue;
5081 }
5082
5083 VPInstruction *RdxResult =
5085 VPValue *NewFindLastSelect = BackedgeVal;
5086 VPValue *SelectCond = Cond;
5087 if (!SentinelVal || IVOfExpressionToSink) {
5088 // When we need to create a new select, normalize the condition so that
5089 // PhiR is the last operand and include the header mask if needed.
5090 DebugLoc DL = FindLastSelect->getDefiningRecipe()->getDebugLoc();
5091 VPBuilder LoopBuilder(FindLastSelect->getDefiningRecipe());
5092 if (match(FindLastSelect,
5094 SelectCond = LoopBuilder.createNot(SelectCond);
5095
5096 // When tail folding, mask the condition with the header mask to prevent
5097 // propagating poison from inactive lanes in the last vector iteration.
5098 if (HeaderMask)
5099 SelectCond = LoopBuilder.createLogicalAnd(HeaderMask, SelectCond);
5100
5101 if (SelectCond != Cond || IVOfExpressionToSink) {
5102 NewFindLastSelect = LoopBuilder.createSelect(
5103 SelectCond,
5104 IVOfExpressionToSink ? IVOfExpressionToSink : FindLastExpression,
5105 PhiR, DL);
5106 }
5107 }
5108
5109 // Create the reduction result in the middle block using sentinel directly.
5110 RecurKind MinMaxKind =
5111 UseMax ? (UseSigned ? RecurKind::SMax : RecurKind::UMax)
5112 : (UseSigned ? RecurKind::SMin : RecurKind::UMin);
5113 VPIRFlags Flags(MinMaxKind, /*IsOrdered=*/false, /*IsInLoop=*/false,
5114 FastMathFlags());
5115 DebugLoc ExitDL = RdxResult->getDebugLoc();
5116 VPBuilder MiddleBuilder(RdxResult);
5117 VPValue *ReducedIV =
5119 NewFindLastSelect, Flags, ExitDL);
5120
5121 // If IVOfExpressionToSink is an expression to sink, sink it now.
5122 VPValue *VectorRegionExitingVal = ReducedIV;
5123 bool SunkExpression = false;
5124 if (IVOfExpressionToSink) {
5125 VectorRegionExitingVal =
5126 cloneBinOpForScalarIV(cast<VPWidenRecipe>(FindLastExpression),
5127 ReducedIV, IVOfExpressionToSink);
5128 SunkExpression = true;
5129 }
5130
5131 VPValue *NewRdxResult;
5132 VPValue *StartVPV = PhiR->getStartValue();
5133 if (SentinelVal) {
5134 // Sentinel-based approach: reduce IVs with min/max, compare against
5135 // sentinel to detect if condition was ever true, select accordingly.
5136 VPValue *Sentinel = Plan.getConstantInt(*SentinelVal);
5137 auto *Cmp = MiddleBuilder.createICmp(CmpInst::ICMP_NE, ReducedIV,
5138 Sentinel, ExitDL);
5139 NewRdxResult = MiddleBuilder.createSelect(Cmp, VectorRegionExitingVal,
5140 StartVPV, ExitDL);
5141 StartVPV = Sentinel;
5142 } else {
5143 // Introduce a boolean AnyOf reduction to track if the condition was ever
5144 // true in the loop. Use it to select the initial start value, if it was
5145 // never true.
5146 auto *AnyOfPhi = new VPReductionPHIRecipe(
5147 /*Phi=*/nullptr, RecurKind::Or, *Plan.getFalse(), *Plan.getFalse(),
5148 RdxUnordered{1}, {}, /*HasUsesOutsideReductionChain=*/false);
5149 AnyOfPhi->insertAfter(PhiR);
5150
5151 VPBuilder LoopBuilder(BackedgeVal->getDefiningRecipe());
5152 VPValue *OrVal = LoopBuilder.createOr(AnyOfPhi, SelectCond);
5153 AnyOfPhi->setOperand(1, OrVal);
5154
5155 NewRdxResult = MiddleBuilder.createAnyOfReduction(
5156 OrVal, VectorRegionExitingVal, StartVPV, ExitDL);
5157
5158 // Initialize the IV reduction phi with the neutral element, not the
5159 // original start value, to ensure correct min/max reduction results.
5160 StartVPV = Plan.getOrAddLiveIn(
5161 getRecurrenceIdentity(MinMaxKind, IVSCEV->getType(), {}));
5162 }
5163 RdxResult->replaceAllUsesWith(NewRdxResult);
5164 RdxResult->eraseFromParent();
5165
5166 auto *NewPhiR = new VPReductionPHIRecipe(
5167 cast<PHINode>(PhiR->getUnderlyingInstr()), RecurKind::FindIV, *StartVPV,
5168 *NewFindLastSelect, RdxUnordered{1}, {},
5169 PhiR->hasUsesOutsideReductionChain());
5170 if (SunkExpression)
5171 NewPhiR->setExpressionSunk();
5172 NewPhiR->insertBefore(PhiR);
5173 PhiR->replaceAllUsesWith(NewPhiR);
5174 PhiR->eraseFromParent();
5175 }
5176}
5177
5178namespace {
5179
5180struct ReductionExtend {
5181 Type *SrcType = nullptr;
5182 ExtendKind Kind = ExtendKind::PR_None;
5183};
5184
5185/// Describes the extends used to compute the extended reduction operand.
5186/// ExtendB is optional. If ExtendB is present, ExtendsUser is a binary
5187/// operation.
5188struct ExtendedReductionOperand {
5189 /// The recipe that consumes the extends.
5190 VPWidenRecipe *ExtendsUser = nullptr;
5191 /// Extend descriptions (inputs to getPartialReductionCost).
5192 ReductionExtend ExtendA, ExtendB;
5193};
5194
5195/// A collection of recipes that describe a partial reduction. Matches either
5196/// reduction_bin_op (extended op, accumulator), or
5197/// reduction_bin_op (accumulator, extended op).
5198/// The possible forms of the "extended op" are listed in
5199/// matchExtendedReductionOperand.
5200struct PartialReductionDescriptor {
5201 /// The top-level binary operation that forms the reduction to a scalar
5202 /// after the loop body.
5203 VPWidenRecipe *ReductionBinOp = nullptr;
5204 /// The user of the extends that is then reduced.
5205 ExtendedReductionOperand ExtendedOp;
5206 /// The recurrence kind for the entire partial reduction chain.
5207 /// This allows distinguishing between Sub and AddWithSub recurrences,
5208 /// when the ReductionBinOp is a Instruction::Sub.
5209 RecurKind RK;
5210 /// The index of the accumulator operand of ReductionBinOp. The extended op
5211 /// is `1 - AccumulatorOpIdx`.
5212 unsigned AccumulatorOpIdx;
5213 unsigned ScaleFactor;
5214 /// Optional blend to represent predication for the block that updates the
5215 /// reduction.
5216 VPBlendRecipe *Blend = nullptr;
5217};
5218
5219// Return the incoming index of the single-use value in the blend, which is
5220// expected to be the predicated reduction update.
5221static std::optional<unsigned>
5222getBlendReductionUpdateValueIdx(VPBlendRecipe *Blend) {
5223 assert(Blend && !Blend->isNormalized() &&
5224 Blend->getNumIncomingValues() == 2 &&
5225 "Expected a non-normalized blend with two incoming values");
5226 bool FirstIncomingHasOneUse = Blend->getIncomingValue(0)->hasOneUse();
5227
5228 // Only the update value should have one use (the blend). The previous
5229 // value should always have at least two uses, the blend and the reduction.
5230 if (FirstIncomingHasOneUse == Blend->getIncomingValue(1)->hasOneUse())
5231 return std::nullopt;
5232 return FirstIncomingHasOneUse ? 0 : 1;
5233}
5234
5235static VPSingleDefRecipe *
5236optimizeExtendsForPartialReduction(VPSingleDefRecipe *Op) {
5237 // reduce.add(mul(ext(A), C))
5238 // -> reduce.add(mul(ext(A), ext(trunc(C))))
5239 const APInt *Const;
5240 if (match(Op, m_Mul(m_ZExtOrSExt(m_VPValue()), m_APInt(Const)))) {
5241 auto *ExtA = cast<VPWidenCastRecipe>(Op->getOperand(0));
5242 Instruction::CastOps ExtOpc = ExtA->getOpcode();
5243 Type *NarrowTy = ExtA->getOperand(0)->getScalarType();
5244 if (!Op->hasOneUse() ||
5246 Const, NarrowTy, TTI::getPartialReductionExtendKind(ExtOpc)))
5247 return Op;
5248
5249 VPBuilder Builder(Op);
5250 auto *Trunc = Builder.createWidenCast(Instruction::CastOps::Trunc,
5251 Op->getOperand(1), NarrowTy);
5252 Type *WideTy = ExtA->getScalarType();
5253 Op->setOperand(1, Builder.createWidenCast(ExtOpc, Trunc, WideTy));
5254 return Op;
5255 }
5256
5257 // reduce.add(abs(sub(ext(A), ext(B))))
5258 // -> reduce.add(ext(absolute-difference(A, B)))
5259 VPValue *X, *Y;
5262 auto *Sub = Op->getOperand(0)->getDefiningRecipe();
5263 auto *Ext = cast<VPWidenCastRecipe>(Sub->getOperand(0));
5264 assert(Ext->getOpcode() ==
5265 cast<VPWidenCastRecipe>(Sub->getOperand(1))->getOpcode() &&
5266 "Expected both the LHS and RHS extends to be the same");
5267 bool IsSigned = Ext->getOpcode() == Instruction::SExt;
5268 VPBuilder Builder(Op);
5269 Type *SrcTy = X->getScalarType();
5270 auto *FreezeX = Builder.insert(new VPWidenRecipe(Instruction::Freeze, {X}));
5271 auto *FreezeY = Builder.insert(new VPWidenRecipe(Instruction::Freeze, {Y}));
5272 auto *Max = Builder.insert(
5273 new VPWidenIntrinsicRecipe(IsSigned ? Intrinsic::smax : Intrinsic::umax,
5274 {FreezeX, FreezeY}, SrcTy));
5275 auto *Min = Builder.insert(
5276 new VPWidenIntrinsicRecipe(IsSigned ? Intrinsic::smin : Intrinsic::umin,
5277 {FreezeX, FreezeY}, SrcTy));
5278 auto *AbsDiff = Builder.insert(
5279 new VPWidenRecipe(Instruction::Sub, {Max, Min},
5280 VPIRFlags::getDefaultFlags(Instruction::Sub)));
5281 return Builder.createWidenCast(Instruction::CastOps::ZExt, AbsDiff,
5282 Op->getScalarType());
5283 }
5284
5285 // reduce.add(ext(mul(ext(A), ext(B))))
5286 // -> reduce.add(mul(wider_ext(A), wider_ext(B)))
5287 // TODO: Support this optimization for float types.
5289 m_ZExtOrSExt(m_VPValue()))))) {
5290 auto *Ext = cast<VPWidenCastRecipe>(Op);
5291 auto *Mul = cast<VPWidenRecipe>(Ext->getOperand(0));
5292 auto *MulLHS = cast<VPWidenCastRecipe>(Mul->getOperand(0));
5293 auto *MulRHS = cast<VPWidenCastRecipe>(Mul->getOperand(1));
5294 assert(Mul->hasOneUse() && Ext->getOpcode() == MulLHS->getOpcode() &&
5295 MulLHS->getOpcode() == MulRHS->getOpcode() &&
5297 "Expected the outer extend to be foldable");
5298 VPBuilder Builder(Mul);
5299 auto *NewLHS = Builder.createWidenCast(
5300 MulLHS->getOpcode(), MulLHS->getOperand(0), Ext->getScalarType());
5301 auto *NewRHS = MulLHS == MulRHS
5302 ? NewLHS
5303 : Builder.createWidenCast(MulRHS->getOpcode(),
5304 MulRHS->getOperand(0),
5305 Ext->getScalarType());
5306 auto *NewMul = Mul->cloneWithOperands({NewLHS, NewRHS});
5307 Builder.insert(NewMul);
5308 Op->replaceAllUsesWith(NewMul);
5309 Op->eraseFromParent();
5310 Mul->eraseFromParent();
5311 return NewMul;
5312 }
5313
5314 return Op;
5315}
5316
5317static VPExpressionRecipe *
5318createPartialReductionExpression(VPReductionRecipe *Red) {
5319 VPValue *VecOp = Red->getVecOp();
5320
5321 // reduce.[f]add(ext(op))
5322 // -> VPExpressionRecipe(op, red)
5323 if (match(VecOp, m_WidenAnyExtend(m_VPValue())))
5324 return new VPExpressionRecipe(cast<VPWidenCastRecipe>(VecOp), Red);
5325
5326 // reduce.[f]add(neg(ext(op)))
5327 // -> VPExpressionRecipe(op, sub/neg, red)
5328 if (match(VecOp, m_AnyNeg(m_WidenAnyExtend(m_VPValue())))) {
5329 auto *Neg = cast<VPWidenRecipe>(VecOp);
5330 auto *Ext = cast<VPWidenCastRecipe>(Neg->getLastOperand());
5331 return new VPExpressionRecipe(Ext, Neg, Red);
5332 }
5333
5334 // reduce.[f]add([f]mul(ext(a), ext(b)))
5335 // -> VPExpressionRecipe(a, b, mul, red)
5336 if (match(VecOp, m_FMul(m_FPExt(m_VPValue()), m_FPExt(m_VPValue()))) ||
5337 match(VecOp,
5339 auto *Mul = cast<VPWidenRecipe>(VecOp);
5340 auto *ExtA = cast<VPWidenCastRecipe>(Mul->getOperand(0));
5341 auto *ExtB = cast<VPWidenCastRecipe>(Mul->getOperand(1));
5342 return new VPExpressionRecipe(ExtA, ExtB, Mul, Red);
5343 }
5344
5345 // reduce.fadd(fneg(fmul(fpext(a), fpext(b))))
5346 // -> VPExpressionRecipe(a, b, fmul, fsub, red)
5347 if (match(VecOp,
5349 auto *FNeg = cast<VPWidenRecipe>(VecOp);
5350 auto *FMul = cast<VPWidenRecipe>(FNeg->getOperand(0));
5351 auto *ExtA = cast<VPWidenCastRecipe>(FMul->getOperand(0));
5352 auto *ExtB = cast<VPWidenCastRecipe>(FMul->getOperand(1));
5353 return new VPExpressionRecipe(ExtA, ExtB, FMul, FNeg, Red);
5354 }
5355
5356 // reduce.add(neg(mul(ext(a), ext(b))))
5357 // -> VPExpressionRecipe(a, b, mul, sub, red)
5359 m_ZExtOrSExt(m_VPValue()))))) {
5360 auto *Sub = cast<VPWidenRecipe>(VecOp);
5361 auto *Mul = cast<VPWidenRecipe>(Sub->getOperand(1));
5362 auto *ExtA = cast<VPWidenCastRecipe>(Mul->getOperand(0));
5363 auto *ExtB = cast<VPWidenCastRecipe>(Mul->getOperand(1));
5364 return new VPExpressionRecipe(ExtA, ExtB, Mul, Sub, Red);
5365 }
5366
5367 llvm_unreachable("Unsupported expression");
5368}
5369
5370// Helper to transform a PartialReductionDescriptor into a partial reduction
5371// recipe. Assumes profitability has been checked.
5372static void transformToPartialReduction(const PartialReductionDescriptor &Link,
5373 VPlan &Plan,
5374 VPReductionPHIRecipe *RdxPhi) {
5375 VPWidenRecipe *WidenRecipe = Link.ReductionBinOp;
5376 assert(WidenRecipe->getNumOperands() == 2 && "Expected binary operation");
5377 assert(is_contained({Instruction::Add, Instruction::Sub, Instruction::FAdd,
5378 Instruction::FSub},
5379 WidenRecipe->getOpcode()) &&
5380 "Partial reductions can only be formed from add and sub links");
5381
5382 VPValue *Accumulator = WidenRecipe->getOperand(Link.AccumulatorOpIdx);
5383 auto *ExtendedOp = cast<VPSingleDefRecipe>(
5384 WidenRecipe->getOperand(1 - Link.AccumulatorOpIdx));
5385
5386 // FIXME: Do these transforms before invoking the cost-model.
5387 ExtendedOp = optimizeExtendsForPartialReduction(ExtendedOp);
5388
5389 // Sub-reductions can be implemented in two ways:
5390 // (1) negate the operand in the vector loop (the default way).
5391 // (2) subtract the reduced value from the init value in the middle block.
5392 // Both ways keep the reduction itself as an 'add' reduction.
5393 //
5394 // The ISD nodes for partial reductions don't support folding the
5395 // sub/negation into its operands because the following is not a valid
5396 // transformation:
5397 // sub(0, mul(ext(a), ext(b)))
5398 // -> mul(ext(a), ext(sub(0, b)))
5399 //
5400 // It's therefore better to choose option (2) such that the partial
5401 // reduction is always positive (starting at '0') and to do a final
5402 // subtract in the middle block.
5403 if ((WidenRecipe->getOpcode() == Instruction::Sub &&
5404 Link.RK != RecurKind::Sub) ||
5405 (WidenRecipe->getOpcode() == Instruction::FSub &&
5406 Link.RK != RecurKind::FSub)) {
5407 VPBuilder Builder(WidenRecipe);
5408 Type *ElemTy = ExtendedOp->getScalarType();
5409 VPWidenRecipe *NegRecipe;
5410 if (WidenRecipe->getOpcode() == Instruction::FSub) {
5411 NegRecipe =
5412 new VPWidenRecipe(Instruction::FNeg, {ExtendedOp},
5413 VPIRFlags::getDefaultFlags(Instruction::FNeg),
5415 } else {
5416 auto *Zero = Plan.getZero(ElemTy);
5417 NegRecipe =
5418 new VPWidenRecipe(Instruction::Sub, {Zero, ExtendedOp},
5419 VPIRFlags::getDefaultFlags(Instruction::Sub),
5421 }
5422 Builder.insert(NegRecipe);
5423 ExtendedOp = NegRecipe;
5424 }
5425
5426 // Check if WidenRecipe is the final result of the reduction. If so, look
5427 // through the Select recipe introduced by tail-folding, otherwise look
5428 // through any Blend recipe introduced by predication for the block.
5429 VPValue *ExitSearch =
5430 Link.Blend ? cast<VPValue>(Link.Blend) : cast<VPValue>(WidenRecipe);
5431
5432 VPValue *Cond = nullptr;
5434 ExitSearch,
5435 m_Select(m_VPValue(Cond), m_Specific(ExitSearch), m_Specific(RdxPhi)));
5436
5437 VPBuilder Builder(WidenRecipe);
5438 if (Link.Blend) {
5439 // Link.Blend selects between WidenRecipe and the previous value, so
5440 // Accumulator, ExtendedOp, and Cond are all defined at this point.
5441 Builder.setInsertPoint(Link.Blend);
5442 std::optional<unsigned> BlendReductionIdx =
5443 getBlendReductionUpdateValueIdx(Link.Blend);
5444 assert(BlendReductionIdx &&
5445 Link.Blend->getIncomingValue(*BlendReductionIdx) == WidenRecipe &&
5446 "Expected blend to contain the reduction update");
5447 VPValue *BlendCond = Link.Blend->getMask(*BlendReductionIdx);
5448 Cond = ExitValue ? Builder.createLogicalAnd(Cond, BlendCond,
5449 WidenRecipe->getDebugLoc())
5450 : BlendCond;
5451 }
5452
5453 // When folding the tail, the inactive lanes of the reduction update are
5454 // computed from values that do not correspond to any scalar iteration
5455 // and must not be accumulated.
5456 if (!Cond)
5458
5459 [[maybe_unused]] bool IsLastInChain =
5460 RdxPhi->getBackedgeValue() == WidenRecipe ||
5461 RdxPhi->getBackedgeValue() == ExitValue ||
5462 RdxPhi->getBackedgeValue() == Link.Blend;
5463 assert((!ExitValue || IsLastInChain) &&
5464 "if we found ExitValue, it must match RdxPhi's backedge value");
5465
5466 Type *PhiType = RdxPhi->getScalarType();
5467 RecurKind RdxKind =
5469 auto *PartialRed = Builder.insert(new VPReductionRecipe(
5470 RdxKind,
5471 RdxKind == RecurKind::FAdd ? WidenRecipe->getFastMathFlagsOrNone()
5472 : FastMathFlags(),
5473 WidenRecipe->getUnderlyingInstr(), Accumulator, ExtendedOp, Cond,
5474 RdxUnordered{/*VFScaleFactor=*/Link.ScaleFactor}));
5475
5476 if (ExitValue)
5477 ExitValue->replaceAllUsesWith(PartialRed);
5478 if (Link.Blend)
5479 Link.Blend->replaceAllUsesWith(PartialRed);
5480 WidenRecipe->replaceAllUsesWith(PartialRed);
5481
5482 // For cost-model purposes, fold this into a VPExpression.
5484 Builder.insert(createPartialReductionExpression(PartialRed));
5485 PartialRed->replaceAllUsesWith(E);
5486}
5487
5488/// Returns the cost of a link in a partial-reduction chain for a given VF.
5489static InstructionCost
5490getPartialReductionLinkCost(VPCostContext &CostCtx,
5491 const PartialReductionDescriptor &Link,
5492 ElementCount VF) {
5493 Type *RdxType = Link.ReductionBinOp->getScalarType();
5494 const ExtendedReductionOperand &ExtendedOp = Link.ExtendedOp;
5495 std::optional<unsigned> BinOpc = std::nullopt;
5496 // If ExtendB is not none, then the "ExtendsUser" is the binary operation.
5497 if (ExtendedOp.ExtendB.Kind != ExtendKind::PR_None)
5498 BinOpc = ExtendedOp.ExtendsUser->getOpcode();
5499
5500 std::optional<llvm::FastMathFlags> Flags;
5501 if (RdxType->isFloatingPointTy())
5502 Flags = Link.ReductionBinOp->getFastMathFlagsOrNone();
5503
5504 auto GetLinkOpcode = [&Link]() -> unsigned {
5505 switch (Link.RK) {
5506 case RecurKind::Sub:
5507 return Instruction::Add;
5508 case RecurKind::FSub:
5509 return Instruction::FAdd;
5510 default:
5511 return Link.ReductionBinOp->getOpcode();
5512 }
5513 };
5514
5515 return CostCtx.TTI.getPartialReductionCost(
5516 GetLinkOpcode(), ExtendedOp.ExtendA.SrcType, ExtendedOp.ExtendB.SrcType,
5517 RdxType, VF, ExtendedOp.ExtendA.Kind, ExtendedOp.ExtendB.Kind, BinOpc,
5518 CostCtx.CostKind, Flags);
5519}
5520
5521/// Checks if \p Op (which is an operand of \p UpdateR) is an extended reduction
5522/// operand. This is an operand where the source of the value (e.g. a load) has
5523/// been extended (sext, zext, or fpext) before it is used in the reduction.
5524///
5525/// Possible forms matched by this function:
5526/// - UpdateR(PrevValue, ext(...))
5527/// - UpdateR(PrevValue, mul(ext(...), ext(...)))
5528/// - UpdateR(PrevValue, mul(ext(...), Constant))
5529/// - UpdateR(PrevValue, ext(mul(ext(...), ext(...))))
5530/// - UpdateR(PrevValue, ext(mul(ext(...), Constant)))
5531/// - UpdateR(PrevValue, abs(sub(ext(...), ext(...)))
5532///
5533/// Note: The second operand of UpdateR corresponds to \p Op in the examples.
5534static std::optional<ExtendedReductionOperand>
5535matchExtendedReductionOperand(VPWidenRecipe *UpdateR, VPValue *Op) {
5536 assert(is_contained(UpdateR->operands(), Op) &&
5537 "Op should be operand of UpdateR");
5538
5539 // Try matching an absolute difference operand of the form
5540 // `abs(sub(ext(A), ext(B)))`. This will be later transformed into
5541 // `ext(absolute-difference(A, B))`. This allows us to perform the absolute
5542 // difference on a wider type and get the extend for "free" from the partial
5543 // reduction.
5544 VPValue *X, *Y;
5545 if (Op->hasOneUse() &&
5549 auto *Abs = cast<VPWidenIntrinsicRecipe>(Op);
5550 auto *Sub = cast<VPWidenRecipe>(Abs->getOperand(0));
5551 auto *LHSExt = cast<VPWidenCastRecipe>(Sub->getOperand(0));
5552 auto *RHSExt = cast<VPWidenCastRecipe>(Sub->getOperand(1));
5553 Type *LHSInputType = X->getScalarType();
5554 Type *RHSInputType = Y->getScalarType();
5555 if (LHSInputType != RHSInputType ||
5556 LHSExt->getOpcode() != RHSExt->getOpcode())
5557 return std::nullopt;
5558 // Note: This is essentially the same as matching ext(...) as we will
5559 // rewrite this operand to ext(absolute-difference(A, B)).
5560 return ExtendedReductionOperand{
5561 Sub,
5562 /*ExtendA=*/{LHSInputType, getPartialReductionExtendKind(LHSExt)},
5563 /*ExtendB=*/{}};
5564 }
5565
5566 std::optional<TTI::PartialReductionExtendKind> OuterExtKind;
5568 auto *CastRecipe = cast<VPWidenCastRecipe>(Op);
5569 VPValue *CastSource = CastRecipe->getOperand(0);
5570 OuterExtKind = getPartialReductionExtendKind(CastRecipe);
5571 if (match(CastSource, m_Mul(m_VPValue(), m_VPValue())) ||
5572 match(CastSource, m_FMul(m_VPValue(), m_VPValue()))) {
5573 // Match: ext(mul(...))
5574 // Record the outer extend kind and set `Op` to the mul. We can then match
5575 // this as a binary operation. Note: We can optimize out the outer extend
5576 // by widening the inner extends to match it. See
5577 // optimizeExtendsForPartialReduction.
5578 Op = CastSource;
5579 } else {
5580 return ExtendedReductionOperand{
5581 UpdateR,
5582 /*ExtendA=*/{CastSource->getScalarType(), *OuterExtKind},
5583 /*ExtendB=*/{}};
5584 }
5585 }
5586
5587 if (!Op->hasOneUse())
5588 return std::nullopt;
5589
5591 if (!MulOp ||
5592 !is_contained({Instruction::Mul, Instruction::FMul}, MulOp->getOpcode()))
5593 return std::nullopt;
5594
5595 // The rest of the matching assumes `Op` is a (possibly extended) mul
5596 // operation.
5597
5598 VPValue *LHS = MulOp->getOperand(0);
5599 VPValue *RHS = MulOp->getOperand(1);
5600
5601 // The LHS of the operation must always be an extend.
5603 return std::nullopt;
5604
5605 auto *LHSCast = cast<VPWidenCastRecipe>(LHS);
5606 Type *LHSInputType = LHSCast->getOperand(0)->getScalarType();
5607 ExtendKind LHSExtendKind = getPartialReductionExtendKind(LHSCast);
5608
5609 // The RHS of the operation can be an extend or a constant integer.
5610 const APInt *RHSConst = nullptr;
5611 VPWidenCastRecipe *RHSCast = nullptr;
5613 RHSCast = cast<VPWidenCastRecipe>(RHS);
5614 else if (!match(RHS, m_APInt(RHSConst)) ||
5615 !canConstantBeExtended(RHSConst, LHSInputType, LHSExtendKind))
5616 return std::nullopt;
5617
5618 // The outer extend kind must match the inner extends for folding.
5619 for (VPWidenCastRecipe *Cast : {LHSCast, RHSCast})
5620 if (Cast && OuterExtKind &&
5621 getPartialReductionExtendKind(Cast) != OuterExtKind)
5622 return std::nullopt;
5623
5624 Type *RHSInputType = LHSInputType;
5625 ExtendKind RHSExtendKind = LHSExtendKind;
5626 if (RHSCast) {
5627 RHSInputType = RHSCast->getOperand(0)->getScalarType();
5628 RHSExtendKind = getPartialReductionExtendKind(RHSCast);
5629 }
5630
5631 // The outer extend can only be treated as extending the operands of the mul
5632 // if the narrow mul cannot wrap.
5633 if (OuterExtKind && MulOp->getOpcode() == Instruction::Mul &&
5635 return std::nullopt;
5636
5637 return ExtendedReductionOperand{
5638 MulOp, {LHSInputType, LHSExtendKind}, {RHSInputType, RHSExtendKind}};
5639}
5640
5641/// Examines each operation in the reduction chain corresponding to \p RedPhiR,
5642/// and determines if the target can use a cheaper operation with a wider
5643/// per-iteration input VF and narrower PHI VF. If successful, returns the chain
5644/// of partial reduction descriptors (that are links in the reduction chain).
5645static std::optional<SmallVector<PartialReductionDescriptor>>
5646getScaledReductionChain(VPReductionPHIRecipe *RedPhiR) {
5647 // Get the backedge value from the reduction PHI and find the
5648 // ComputeReductionResult that uses it (directly or through a select for
5649 // predicated reductions).
5650 auto *RdxResult = vputils::findComputeReductionResult(RedPhiR);
5651 if (!RdxResult)
5652 return std::nullopt;
5653 VPValue *ExitValue = RdxResult->getOperand(0);
5654 match(ExitValue, m_Select(m_VPValue(), m_VPValue(ExitValue), m_VPValue()));
5655
5656 // Each link is lowered to a partial add reduction, so only recurrences made
5657 // up of add and sub links can be handled.
5658 RecurKind RK = RedPhiR->getRecurrenceKind();
5662 RK))
5663 return std::nullopt;
5664
5666 Type *PhiType = RedPhiR->getScalarType();
5667 TypeSize PHISize = PhiType->getPrimitiveSizeInBits();
5668
5669 // Work backwards from the ExitValue examining each reduction operation.
5670 VPValue *CurrentValue = ExitValue;
5671 while (CurrentValue != RedPhiR) {
5672 VPBlendRecipe *Blend = dyn_cast<VPBlendRecipe>(CurrentValue);
5673 std::optional<unsigned> BlendReductionIdx;
5674 if (Blend) {
5675 assert(!Blend->isNormalized() && "Expect Blend not to be normalized.");
5676 if (Blend->getNumIncomingValues() != 2)
5677 return std::nullopt;
5678
5679 BlendReductionIdx = getBlendReductionUpdateValueIdx(Blend);
5680 if (!BlendReductionIdx)
5681 return std::nullopt;
5682
5683 CurrentValue = Blend->getIncomingValue(*BlendReductionIdx);
5684 }
5685
5686 auto *UpdateR = dyn_cast<VPWidenRecipe>(CurrentValue);
5687 if (!UpdateR)
5688 return std::nullopt;
5689
5690 VPValue *Op = UpdateR->getOperand(1);
5691 VPValue *PrevValue = UpdateR->getOperand(0);
5692
5693 // Find the extended operand. The other operand (PrevValue) is the next link
5694 // in the reduction chain.
5695 std::optional<ExtendedReductionOperand> ExtendedOp =
5696 matchExtendedReductionOperand(UpdateR, Op);
5697 if (!ExtendedOp) {
5698 ExtendedOp = matchExtendedReductionOperand(UpdateR, PrevValue);
5699 if (!ExtendedOp)
5700 return std::nullopt;
5701 std::swap(Op, PrevValue);
5702 }
5703
5704 // Look for VPBlend(reduce(PrevValue, Op), PrevValue), where
5705 // reduce is equal to CurrentValue. This can be lowered as
5706 // a conditional reduction by hoisting the select to the inputs.
5707 if (Blend && Blend->getIncomingValue(1 - *BlendReductionIdx) != PrevValue)
5708 return std::nullopt;
5709
5710 Type *ExtSrcType = ExtendedOp->ExtendA.SrcType;
5711 TypeSize ExtSrcSize = ExtSrcType->getPrimitiveSizeInBits();
5712 if (!PHISize.hasKnownScalarFactor(ExtSrcSize))
5713 return std::nullopt;
5714
5715 PartialReductionDescriptor Link(
5716 {UpdateR, *ExtendedOp, RK,
5717 PrevValue == UpdateR->getOperand(0) ? 0U : 1U,
5718 static_cast<unsigned>(PHISize.getKnownScalarFactor(ExtSrcSize)),
5719 Blend});
5720 Chain.push_back(Link);
5721 CurrentValue = PrevValue;
5722 }
5723
5724 // The chain links were collected by traversing backwards from the exit value.
5725 // Reverse the chain so the links follow program order.
5726 std::reverse(Chain.begin(), Chain.end());
5727 return Chain;
5728}
5729} // namespace
5730
5731// Scale the PHI and ReductionStartVector by \p Factor and if the recurrence is
5732// a sub-recurrence, negate the reduction result.
5735 unsigned Factor, RecurKind RK) {
5736 assert(Phi->getVFScaleFactor() == 1 && "scale factor must not be set");
5737 Phi->setVFScaleFactor(Factor);
5738
5739 auto *StartInst = cast<VPInstruction>(Phi->getStartValue());
5740 assert(StartInst->getOpcode() == VPInstruction::ReductionStartVector);
5741 auto *NewScaleFactor = Plan.getConstantInt(32, Factor);
5742 StartInst->setOperand(2, NewScaleFactor);
5743
5744 if (RK != RecurKind::Sub && RK != RecurKind::FSub)
5745 return;
5746
5747 // Update the PHI node to start at `0` and update the reduction-result
5748 // to subtract from the PHI's start value.
5749 VPValue *OldStartValue = StartInst->getOperand(0);
5750 StartInst->setOperand(0, StartInst->getOperand(1));
5751
5752 // Replace reduction_result by 'sub (startval, reductionresult)'.
5754 assert(RdxResult && "Could not find reduction result");
5755
5756 VPBuilder Builder = VPBuilder::getToInsertAfter(RdxResult);
5757 unsigned SubOpc = RK == RecurKind::FSub ? Instruction::BinaryOps::FSub
5758 : Instruction::BinaryOps::Sub;
5759 VPInstruction *NewResult = Builder.createNaryOp(
5760 SubOpc, {OldStartValue, RdxResult}, VPIRFlags::getDefaultFlags(SubOpc),
5761 Phi->getDebugLoc());
5762 RdxResult->replaceUsesWithIf(NewResult, not_equal_to(NewResult));
5763}
5764
5766 VPCostContext &CostCtx,
5767 VFRange &Range) {
5768 // Find all possible valid partial reductions, grouping chains by their PHI.
5769 // This grouping allows invalidating the whole chain, if any link is not a
5770 // valid partial reduction.
5772 PhiToChain;
5773 VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
5774 SmallVector<VPReductionPHIRecipe *, 4> UnorderedReductions;
5775 for (VPReductionPHIRecipe &RedPhiR :
5777 // Skip reductions used outside the loop region, e.g. on early exits.
5778 if (any_of(RedPhiR.users(),
5779 [](VPUser *U) { return !cast<VPRecipeBase>(U)->getRegion(); }))
5780 continue;
5781 if (auto Chain = getScaledReductionChain(&RedPhiR))
5782 PhiToChain.try_emplace(&RedPhiR, std::move(*Chain));
5783 else if (CostCtx.Opts.use_partial_reductions_by_default &&
5784 (RedPhiR.getRecurrenceKind() == RecurKind::Add ||
5785 (RedPhiR.getRecurrenceKind() == RecurKind::FAdd &&
5786 !RedPhiR.isOrdered() && !RedPhiR.isInLoop())))
5787 UnorderedReductions.push_back(&RedPhiR);
5788 }
5789
5790 // For general unordered reductions which aren't part of a candidate chain for
5791 // a scaled partial reduction, we can still use the intrinsic to allow for
5792 // more optimization later on.
5793 for (auto *Rdx : UnorderedReductions) {
5794 auto *Backedge = dyn_cast<VPWidenRecipe>(Rdx->getBackedgeValue());
5795 VPValue *OtherOp;
5796 if (!Backedge ||
5797 !match(Backedge,
5798 m_CombineOr(m_c_FAdd(m_Specific(Rdx), m_VPValue(OtherOp)),
5799 m_c_Add(m_Specific(Rdx), m_VPValue(OtherOp)))))
5800 continue;
5801
5802 // If the target indicates that the intrinsic is as cheap as (or cheaper
5803 // than) the add, then prefer the intrinsic.
5805 [&CostCtx, Rdx, Backedge](ElementCount VF) {
5806 InstructionCost CurrentCost = Backedge->computeCost(VF, CostCtx);
5807 Type *ScalarTy = Backedge->getScalarType();
5808 auto FMF = ScalarTy->isFloatingPointTy()
5809 ? std::make_optional(Rdx->getFastMathFlagsOrNone())
5810 : std::nullopt;
5811
5813 Backedge->getOpcode(), ScalarTy, /*InputTypeB=*/nullptr,
5814 ScalarTy, VF, TTI::PR_None, TTI::PR_None,
5815 /*BinOp=*/std::nullopt, CostCtx.CostKind, FMF);
5816 return PRCost <= CurrentCost;
5817 },
5818 Range))
5819 continue;
5820
5821 auto *Partial = new VPReductionRecipe(
5822 Rdx->getRecurrenceKind(), Rdx->getFastMathFlagsOrNone(),
5823 Backedge->getUnderlyingInstr(), Rdx, OtherOp, nullptr,
5824 getReductionStyle(/*InLoop=*/false, /*Ordered=*/false,
5825 /*ScaleFactor=*/1));
5826 Partial->insertBefore(Backedge);
5827 Backedge->replaceAllUsesWith(Partial);
5828 Backedge->eraseFromParent();
5829 }
5830
5831 if (PhiToChain.empty())
5832 return;
5833
5834 // Build set of partial reduction operations and blends for user validation
5835 // and a map of reduction bin ops to their scale factors for scale validation.
5836 SmallPtrSet<VPRecipeBase *, 4> PartialReductionOps;
5837 SmallPtrSet<VPBlendRecipe *, 4> PartialReductionBlends;
5838 DenseMap<VPSingleDefRecipe *, unsigned> ScaledReductionMap;
5839 for (auto &[_, Chain] : PhiToChain)
5840 for (const PartialReductionDescriptor &Link : Chain) {
5841 PartialReductionOps.insert(Link.ExtendedOp.ExtendsUser);
5842 if (Link.Blend)
5843 PartialReductionBlends.insert(Link.Blend);
5844 ScaledReductionMap[Link.ReductionBinOp] = Link.ScaleFactor;
5845 }
5846
5847 // A partial reduction is invalid if any of its extends are used by
5848 // something that isn't another partial reduction. This is because the
5849 // extends are intended to be lowered along with the reduction itself.
5850 auto ExtendUsersValid = [&](VPValue *Ext) {
5851 return !isa<VPWidenCastRecipe>(Ext) || all_of(Ext->users(), [&](VPUser *U) {
5852 return PartialReductionOps.contains(cast<VPRecipeBase>(U));
5853 });
5854 };
5855
5856 auto IsProfitablePartialReductionChainForVF =
5857 [&](ArrayRef<PartialReductionDescriptor> Chain, ElementCount VF) -> bool {
5858 InstructionCost PartialCost = 0, RegularCost = 0;
5859
5860 // The chain is a profitable partial reduction chain if the cost of handling
5861 // the entire chain is cheaper when using partial reductions than when
5862 // handling the entire chain using regular reductions.
5863 for (const PartialReductionDescriptor &Link : Chain) {
5864 const ExtendedReductionOperand &ExtendedOp = Link.ExtendedOp;
5865 InstructionCost LinkCost = getPartialReductionLinkCost(CostCtx, Link, VF);
5866 if (!LinkCost.isValid())
5867 return false;
5868
5869 PartialCost += LinkCost;
5870 RegularCost += Link.ReductionBinOp->computeCost(VF, CostCtx);
5871 // If ExtendB is not none, then the "ExtendsUser" is the binary operation.
5872 if (ExtendedOp.ExtendB.Kind != ExtendKind::PR_None)
5873 RegularCost += ExtendedOp.ExtendsUser->computeCost(VF, CostCtx);
5874 for (VPValue *Op : ExtendedOp.ExtendsUser->operands())
5875 if (auto *Extend = dyn_cast<VPWidenCastRecipe>(Op))
5876 RegularCost += Extend->computeCost(VF, CostCtx);
5877 }
5878 return PartialCost.isValid() && PartialCost < RegularCost;
5879 };
5880
5881 // Validate chains: check that extends are only used by partial reductions,
5882 // and that reduction bin ops are only used by other partial reductions with
5883 // matching scale factors, are outside the loop region or the select
5884 // introduced by tail-folding. Otherwise we would create users of scaled
5885 // reductions where the types of the other operands don't match.
5886 for (auto &[RedPhiR, Chain] : PhiToChain) {
5887 for (const PartialReductionDescriptor &Link : Chain) {
5888 if (!all_of(Link.ExtendedOp.ExtendsUser->operands(), ExtendUsersValid)) {
5889 Chain.clear();
5890 break;
5891 }
5892 auto UseIsValid = [&, RedPhiR = RedPhiR](VPUser *U) {
5893 if (auto *PhiR = dyn_cast<VPReductionPHIRecipe>(U))
5894 return PhiR == RedPhiR;
5895 auto *R = cast<VPSingleDefRecipe>(U);
5896
5897 if (auto *Blend = dyn_cast<VPBlendRecipe>(R))
5898 return Blend == Link.Blend || PartialReductionBlends.contains(Blend);
5899
5900 return Link.ScaleFactor == ScaledReductionMap.lookup_or(R, 0) ||
5902 m_Specific(Link.ReductionBinOp))) ||
5903 match(R, m_Select(m_VPValue(), m_Specific(Link.ReductionBinOp),
5904 m_Specific(RedPhiR)));
5905 };
5906 if (!all_of(Link.ReductionBinOp->users(), UseIsValid)) {
5907 Chain.clear();
5908 break;
5909 }
5910
5911 // Check if the compute-reduction-result is used by a sunk store.
5912 // TODO: Also form partial reductions in those cases.
5913 if (auto *RdxResult = vputils::findComputeReductionResult(RedPhiR)) {
5914 if (any_of(RdxResult->users(), [](VPUser *U) {
5915 auto *RepR = dyn_cast<VPReplicateRecipe>(U);
5916 return RepR && RepR->getOpcode() == Instruction::Store;
5917 })) {
5918 Chain.clear();
5919 break;
5920 }
5921 }
5922 }
5923
5924 // Clear the chain if it is not profitable.
5926 [&, &Chain = Chain](ElementCount VF) {
5927 return IsProfitablePartialReductionChainForVF(Chain, VF);
5928 },
5929 Range))
5930 Chain.clear();
5931 }
5932
5933 for (auto &[Phi, Chain] : PhiToChain) {
5934 if (Chain.empty())
5935 continue;
5936
5937 for (const PartialReductionDescriptor &Link : Chain)
5938 transformToPartialReduction(Link, Plan, Phi);
5939
5940 // After transforming all links in the chain, the PHI node and result need
5941 // updating. Note that we can pick any link in the chain for this, as the
5942 // ScaleFactor and RecurKind must match for all links in the chain.
5943 const PartialReductionDescriptor &Link = Chain[0];
5944 updatePartialReductionPhiAndResult(Plan, Phi, Link.ScaleFactor, Link.RK);
5945 }
5946}
5947
5949 VPRecipeBuilder &RecipeBuilder,
5950 VPCostContext &CostCtx) {
5951 // Collect all loads/stores first. We will start with ones having simpler
5952 // decisions followed by more complex ones that are potentially
5953 // guided/dependent on the simpler ones.
5955 for (VPBasicBlock *VPBB :
5958 for (VPInstruction &VPI : make_isa_range<VPInstruction>(*VPBB)) {
5959 if (VPI.getUnderlyingValue() &&
5960 is_contained({Instruction::Load, Instruction::Store},
5961 VPI.getOpcode()))
5962 MemOps.push_back(&VPI);
5963 }
5964 }
5965
5966 // Few helpers to process different kinds of memory operations.
5967
5968 // To be used as argument to `VPlanTransforms::runPass` which explicitly
5969 // specified pass name, hence `VPlan &` parameter.
5970 auto ProcessSubset = [&](VPlan &, auto ProcessVPInst) {
5971 SmallVector<VPInstruction *> RemainingMemOps;
5972 for (VPInstruction *VPI : MemOps) {
5973 if (!ProcessVPInst(VPI))
5974 RemainingMemOps.push_back(VPI);
5975 }
5976
5977 MemOps.clear();
5978 std::swap(MemOps, RemainingMemOps);
5979 };
5980
5981 auto ReplaceWith = [&](VPInstruction *VPI, VPRecipeBase *New) {
5982 assert(New->getParent() && "New recipe must have been inserted");
5983 if (VPI->getOpcode() == Instruction::Load)
5984 VPI->replaceAllUsesWith(New->getVPSingleValue());
5985 VPI->eraseFromParent();
5986
5987 // VPI has been processed.
5988 return true;
5989 };
5990
5991 auto Scalarize = [&](VPInstruction *VPI) {
5992 return ReplaceWith(VPI, VPBuilder(VPI).insert(
5993 RecipeBuilder.handleReplication(VPI, Range)));
5994 };
5995
5996 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
5997 VPBuilder FinalRedStoresBuilder(MiddleVPBB->getFirstNonPhi());
5999 "lowerMemoryIdioms", ProcessSubset, Plan, [&](VPInstruction *VPI) {
6000 if (RecipeBuilder.replaceWithFinalIfReductionStore(
6001 VPI, FinalRedStoresBuilder))
6002 return true;
6003
6004 // Filter out scalar VPlan for the remaining idioms.
6006 [](ElementCount VF) { return VF.isScalar(); }, Range))
6007 return false;
6008
6009 if (VPHistogramRecipe *Histogram = RecipeBuilder.widenIfHistogram(VPI))
6010 return ReplaceWith(VPI, VPBuilder(VPI).insert(Histogram));
6011
6012 return false;
6013 });
6014
6015 // Filter out scalar VPlan for the remaining memory operations.
6017 [](ElementCount VF) { return VF.isScalar(); }, Range))
6018 return;
6019
6020 // If the instruction's allocated size doesn't equal it's type size, it
6021 // requires padding and will be scalarized.
6023 "scalarizeMemOpsWithIrregularTypes", ProcessSubset, Plan,
6024 [&](VPInstruction *VPI) {
6026 Plan.getDataLayout()))
6027 return Scalarize(VPI);
6028
6029 return false;
6030 });
6031
6032 if (!RecipeBuilder.prefersVectorizedAddressing()) {
6034 "makeVPlanMemOpDecision", ProcessSubset, Plan, [&](VPInstruction *VPI) {
6036 bool IsLoad = VPI->getOpcode() == Instruction::Load;
6037 if (RecipeBuilder.isPredicatedInst(I) || !IsLoad ||
6039 return false;
6040
6041 // Scalarize loads used as addresses, matching the legacy CM. The load
6042 // is single-scalar if the pointer is loop-invariant, otherwise it is
6043 // replicated per-lane. No mask is needed as the load is not
6044 // predicated.
6045 VPValue *Ptr = VPI->getOperand(0);
6046 const SCEV *PtrSCEV =
6047 vputils::getSCEVExprForVPValue(Ptr, CostCtx.PSE, CostCtx.L);
6048 bool IsSingleScalarLoad =
6049 !isa<SCEVCouldNotCompute>(PtrSCEV) &&
6050 CostCtx.PSE.getSE()->isLoopInvariant(PtrSCEV, CostCtx.L);
6051
6052 ReplaceWith(VPI,
6053 VPBuilder(VPI).insert(new VPReplicateRecipe(
6054 I, Ptr, /*IsSingleScalar=*/IsSingleScalarLoad,
6055 /*Mask=*/nullptr, *VPI, *VPI, VPI->getDebugLoc())));
6056 return true;
6057 });
6058 }
6059
6060 // Widen unit-stride consecutive accesses, matching the legacy CM. Both
6061 // forward (stride +1) and reverse (stride -1) accesses are handled.
6063 "widenConsecutiveMemOps", ProcessSubset, Plan, [&](VPInstruction *VPI) {
6065 bool IsLoad = VPI->getOpcode() == Instruction::Load;
6066 VPValue *Ptr = VPI->getOperand(!IsLoad);
6067 Type *ScalarTy = vputils::getLoadStoreValueType(VPI);
6068 std::optional<int64_t> Stride =
6069 vputils::getConstantStride(Ptr, ScalarTy, CostCtx.PSE, CostCtx.L);
6070 if (Stride != 1 && Stride != -1)
6071 return false;
6072 bool Reverse = Stride == -1;
6073
6074 // A predicated access can only be widened (rather than scalarized) if
6075 // the target supports a masked load/store for it.
6076 // TODO: Determine if a load/store needs predication directly in VPlan.
6077 bool IsPredicated = RecipeBuilder.isPredicatedInst(I);
6078 Align Alignment = getLoadStoreAlignment(I);
6079 if (IsPredicated &&
6081 IsLoad, ScalarTy, Alignment, getLoadStoreAddressSpace(I)))
6082 return false;
6083
6084 VPBuilder Builder(VPI);
6085 VPSingleDefRecipe *VectorPtr = Builder.createConsecutiveVectorPointer(
6086 Ptr, ScalarTy, Reverse, VPI->getDebugLoc());
6087
6088 VPValue *Mask = IsPredicated ? VPI->getMask() : nullptr;
6089 // Reverse the mask so it matches the reversed access order.
6090 if (Reverse && Mask)
6091 Mask = Builder.createNaryOp(VPInstruction::Reverse, Mask,
6092 VPI->getDebugLoc());
6093
6094 if (IsLoad) {
6095 VPSingleDefRecipe *Load = Builder.createWidenLoad(
6096 *cast<LoadInst>(I), VectorPtr, Mask,
6097 /*Consecutive=*/true, Alignment, *VPI, VPI->getDebugLoc());
6098 // Reverse the loaded values back into program order.
6099 if (Reverse)
6100 Load = Builder.createNaryOp(VPInstruction::Reverse, Load,
6101 VPI->getDebugLoc());
6102 return ReplaceWith(VPI, Load);
6103 }
6104
6105 VPValue *StoredVal = VPI->getOperand(0);
6106 if (Reverse)
6107 // Reverse the stored values so they are written in descending order.
6108 StoredVal = Builder.createNaryOp(VPInstruction::Reverse, StoredVal,
6109 VPI->getDebugLoc());
6110
6111 auto *StoreR = Builder.createWidenStore(
6112 *cast<StoreInst>(I), VectorPtr, StoredVal, Mask,
6113 /*Consecutive=*/true, Alignment, *VPI, VPI->getDebugLoc());
6114 return ReplaceWith(VPI, StoreR);
6115 });
6116
6117 VPlanTransforms::runPass("delegateMemOpWideningToLegacyCM", ProcessSubset,
6118 Plan, [&](VPInstruction *VPI) {
6119 if (VPRecipeBase *Recipe =
6120 RecipeBuilder.tryToWidenMemory(VPI, Range))
6121 return ReplaceWith(VPI, Recipe);
6122
6123 return Scalarize(VPI);
6124 });
6125}
6126
6129 [&](ElementCount VF) { return VF.isScalar(); }, Range))
6130 return;
6131
6133 Plan.getEntry());
6135 for (VPInstruction &VPI :
6137 auto *I = cast_or_null<Instruction>(VPI.getUnderlyingValue());
6138 // Wouldn't be able to create a `VPReplicateRecipe` anyway.
6139 if (!I)
6140 continue;
6141
6142 // If executing other lanes produces side-effects we can't avoid them.
6143 if (VPI.mayHaveSideEffects())
6144 continue;
6145
6146 // ExtractValue takes the shape of its aggregate, decided in
6147 // tryToCreateWidenNonPhiRecipe.
6148 if (VPI.getOpcode() == Instruction::ExtractValue)
6149 continue;
6150
6151 // We want to drop the mask operand, verify we can safely do that.
6152 if (VPI.isMasked() && !VPI.isSafeToSpeculativelyExecute())
6153 continue;
6154
6155 // Other lanes are needed - can't drop them.
6156 if (!vputils::onlyFirstLaneUsed(&VPI))
6157 continue;
6158
6159 auto *Recipe = VPBuilder::createSingleScalarOp(
6160 VPI.getOpcode(), VPI.operandsWithoutMask(), /*Mask=*/nullptr, VPI,
6161 VPI, VPI.getDebugLoc(), VPI.getScalarType(), I);
6162 Recipe->insertBefore(&VPI);
6163 VPI.replaceAllUsesWith(Recipe);
6164 VPI.eraseFromParent();
6165 }
6166 }
6167}
6168
6169/// Returns true if \p Info's parameter kinds are compatible with \p Args.
6170static bool areVFParamsOk(const VFInfo &Info, ArrayRef<VPValue *> Args,
6171 PredicatedScalarEvolution &PSE, const Loop *L) {
6172 ScalarEvolution *SE = PSE.getSE();
6173 return all_of(Info.Shape.Parameters, [&](VFParameter Param) {
6174 switch (Param.ParamKind) {
6175 case VFParamKind::Vector:
6176 case VFParamKind::GlobalPredicate:
6177 return true;
6178 case VFParamKind::OMP_Uniform:
6179 return SE->isSCEVable(Args[Param.ParamPos]->getScalarType()) &&
6180 SE->isLoopInvariant(
6181 vputils::getSCEVExprForVPValue(Args[Param.ParamPos], PSE, L),
6182 L);
6183 case VFParamKind::OMP_Linear:
6184 return match(vputils::getSCEVExprForVPValue(Args[Param.ParamPos], PSE, L),
6185 m_scev_AffineAddRec(
6186 m_SCEV(), m_scev_SpecificSInt(Param.LinearStepOrPos),
6187 m_SpecificLoop(L)));
6188 default:
6189 return false;
6190 }
6191 });
6192}
6193
6194/// Find a vector variant of \p CI for \p VF, respecting \p MaskRequired.
6195/// Returns the variant function, or nullptr. Masked variants are assumed to
6196/// take the mask as a trailing parameter.
6198 ElementCount VF, bool MaskRequired,
6200 const Loop *L) {
6201 if (CI->isNoBuiltin())
6202 return nullptr;
6203 auto Mappings = VFDatabase::getMappings(*CI);
6204 const auto *It = find_if(Mappings, [&](const VFInfo &Info) {
6205 return Info.Shape.VF == VF && (!MaskRequired || Info.isMasked()) &&
6206 areVFParamsOk(Info, Args, PSE, L);
6207 });
6208 if (It == Mappings.end())
6209 return nullptr;
6210 return CI->getModule()->getFunction(It->VectorName);
6211}
6212
6213namespace {
6214/// The outcome of choosing how to widen a call at a given VF.
6215struct CallWideningDecision {
6216 enum class KindTy { Scalarize, Intrinsic, VectorVariant };
6217 CallWideningDecision(KindTy Kind, Function *Variant = nullptr)
6218 : Kind(Kind), Variant(Variant) {}
6219 KindTy Kind;
6220
6221 /// Set when Kind == VectorVariant.
6223
6224 bool operator==(const CallWideningDecision &Other) const {
6225 return Kind == Other.Kind && Variant == Other.Variant;
6226 }
6227};
6228} // namespace
6229
6230/// Pick the cheapest widening for the call \p VPI at \p VF among scalarization,
6231/// vector intrinsic, and vector library variant.
6232static CallWideningDecision decideCallWidening(VPInstruction &VPI,
6234 ElementCount VF,
6235 VPCostContext &CostCtx) {
6236 auto *CI = cast<CallInst>(VPI.getUnderlyingInstr());
6237
6238 // Scalar VFs and calls forced or known to scalarize always replicate.
6239 if (VF.isScalar() || CostCtx.willBeScalarized(CI, VF))
6240 return CallWideningDecision::KindTy::Scalarize;
6241
6242 auto *CalledFn = cast<Function>(
6244 Type *ResultTy = VPI.getScalarType();
6246 bool MaskRequired = CostCtx.isMaskRequired(CI);
6247
6248 // Pseudo intrinsics (assume, lifetime, ...) are always scalarized.
6250 return CallWideningDecision::KindTy::Scalarize;
6251
6252 InstructionCost ScalarCost =
6253 VPReplicateRecipe::computeCallCost(CalledFn, ResultTy, Ops,
6254 /*IsSingleScalar=*/false, VF, CostCtx);
6255
6256 Function *VecFunc =
6257 findVectorVariant(CI, Ops, VF, MaskRequired, CostCtx.PSE, CostCtx.L);
6259 if (VecFunc)
6260 VecCallCost = VPWidenCallRecipe::computeCallCost(VecFunc, CostCtx);
6261
6262 // Prefer the intrinsic if it is at least as cheap as scalarizing and any
6263 // available vector variant.
6264 if (ID) {
6266 VPWidenIntrinsicRecipe::computeCallCost(ID, Ops, VPI, VF, CostCtx);
6267 if (IntrinsicCost.isValid() && ScalarCost >= IntrinsicCost &&
6268 (!VecFunc || VecCallCost >= IntrinsicCost))
6269 return CallWideningDecision::KindTy::Intrinsic;
6270 }
6271
6272 // Otherwise, use a vector library variant when it beats scalarizing.
6273 if (VecFunc && ScalarCost >= VecCallCost)
6274 return {CallWideningDecision::KindTy::VectorVariant, VecFunc};
6275
6276 return CallWideningDecision::KindTy::Scalarize;
6277}
6278
6280 VPRecipeBuilder &RecipeBuilder,
6281 VPCostContext &CostCtx) {
6282 bool Widened = false;
6285 for (VPInstruction &VPI :
6287 if (!VPI.getUnderlyingValue() || VPI.getOpcode() != Instruction::Call)
6288 continue;
6289
6290 auto *CI = cast<CallInst>(VPI.getUnderlyingInstr());
6291 SmallVector<VPValue *, 4> Ops(VPI.op_begin(),
6292 VPI.op_begin() + CI->arg_size());
6293
6294 CallWideningDecision Decision =
6295 decideCallWidening(VPI, Ops, Range.Start, CostCtx);
6297 [&](ElementCount VF) {
6298 return Decision == decideCallWidening(VPI, Ops, VF, CostCtx);
6299 },
6300 Range);
6301
6302 assert((Decision.Kind == CallWideningDecision::KindTy::Scalarize ||
6303 !CI->hasOperandBundles()) &&
6304 "calls with operand bundles must not be widened");
6305 VPSingleDefRecipe *Replacement = nullptr;
6306 switch (Decision.Kind) {
6307 case CallWideningDecision::KindTy::Intrinsic: {
6309 Type *ResultTy = VPI.getScalarType();
6310 Replacement = new VPWidenIntrinsicRecipe(*CI, ID, Ops, ResultTy, VPI,
6311 VPI, VPI.getDebugLoc());
6312 Widened = true;
6313 break;
6314 }
6315 case CallWideningDecision::KindTy::VectorVariant: {
6316 // Masked variants take the mask as a trailing parameter, so they have
6317 // one more parameter than the original call's arguments.
6318 if (Decision.Variant->arg_size() > Ops.size()) {
6319 VPValue *Mask = VPI.isMasked() ? VPI.getMask() : Plan.getTrue();
6320 Ops.push_back(Mask);
6321 }
6322 Ops.push_back(VPI.getOperand(VPI.getNumOperandsWithoutMask() - 1));
6323 VPIRAttributes Attrs(VPI, Decision.Variant->getFunctionType());
6324 Replacement = new VPWidenCallRecipe(CI, Decision.Variant, Ops, VPI, VPI,
6325 Attrs, VPI.getDebugLoc());
6326 Widened = true;
6327 break;
6328 }
6329 case CallWideningDecision::KindTy::Scalarize:
6330 Replacement = RecipeBuilder.handleReplication(&VPI, Range);
6331 break;
6332 }
6333
6334 Replacement->insertBefore(&VPI);
6335 VPI.replaceAllUsesWith(Replacement);
6336 VPI.eraseFromParent();
6337 }
6338 }
6339 return Widened;
6340}
6341
6343 const TargetTransformInfo &TTI) {
6344 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
6345 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
6347 vp_depth_first_shallow(LoopRegion->getEntry()))) {
6348 for (VPInstruction &VPI :
6350 // Only truncates are handled, as sext/zext may wrap, FP conversions lose
6351 // precision and other casts depend on the pointer size.
6352 if (VPI.getOpcode() != Instruction::Trunc)
6353 continue;
6354
6355 VPValue *Op = VPI.getOperand(0);
6356
6357 // Also handle the IV plus a loop-invariant %c, e.g. %iv.c below:
6358 //
6359 // %iv = phi i64 [ %start, %entry ], [ %iv.next, %loop ]
6360 // %iv.c = add i64 %iv, %c
6361 // %iv.next = add i64 %iv, %step
6362 //
6363 // %iv.c is an induction with the same step as %iv, but starting at
6364 // %start + %c, which is computed once in the vector preheader. This also
6365 // covers the increment %iv.next, with %c == %step.
6367 VPValue *Offset = nullptr;
6368 auto MatchIV = match_bind<VPWidenIntOrFpInductionRecipe>(WideIV);
6369 bool IsSub = match(Op, m_Sub(MatchIV, m_VPValue(Offset)));
6370 if (!IsSub && !match(Op, MatchIV) &&
6371 !match(Op, m_c_Add(MatchIV, m_VPValue(Offset))))
6372 continue;
6373
6374 // An IV that is already truncated is not narrowed further.
6375 if (WideIV->isTruncated())
6376 continue;
6377
6378 // The IV plus a value that changes in the loop is not an induction.
6379 if (Offset && !Offset->isDefinedOutsideLoopRegions())
6380 continue;
6381
6382 // A truncate that is not widened is left to the scalarization decisions
6383 // made earlier.
6385 continue;
6386
6387 // Replacing a free truncate would add an induction update instruction to
6388 // each iteration of the loop. The canonical induction is exempt, as it
6389 // needs an update instruction regardless.
6390 auto IsNarrowingProfitable = [&](ElementCount VF) {
6391 return match(WideIV, m_CanonicalWidenIV()) ||
6392 !TTI.isTruncateFree(
6393 toVectorTy(VPI.getOperand(0)->getScalarType(), VF),
6394 toVectorTy(VPI.getScalarType(), VF));
6395 };
6397 IsNarrowingProfitable, Range))
6398 continue;
6399
6400 VPValue *Start = WideIV->getStartValue();
6401 if (Offset) {
6402 VPBuilder PHBuilder(Plan.getVectorPreheader());
6403 Start = IsSub ? PHBuilder.createSub(Start, Offset)
6404 : PHBuilder.createAdd(Start, Offset);
6405 }
6406 // Wrap flags of the original induction do not hold in the truncated
6407 // type, so do not propagate them.
6408 auto *NarrowIV = new VPWidenIntOrFpInductionRecipe(
6409 WideIV->getPHINode(), Start, WideIV->getStepValue(),
6410 WideIV->getVFValue(), WideIV->getInductionDescriptor(),
6411 VPI.getScalarType(), VPIRFlags::WrapFlagsTy(false, false),
6412 VPI.getDebugLoc());
6413 NarrowIV->insertBefore(HeaderVPBB->getFirstNonPhi());
6414 VPI.replaceAllUsesWith(NarrowIV);
6415 VPI.eraseFromParent();
6416 }
6417 }
6418}
6419
6422 Loop &L, VPCostContext &Ctx,
6423 VFRange &Range) {
6424 if (Plan.hasScalarVFOnly())
6425 return;
6426
6427 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
6428 VPValue *I32VF = nullptr;
6430 vp_depth_first_shallow(VectorLoop->getEntry()))) {
6431 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
6432 auto *MemR = dyn_cast<VPWidenMemoryRecipe>(&R);
6433 // TODO: Transform reverse access into strided access with -1 stride.
6434 // TODO: Transform gather/scatter with uniform address into strided access
6435 // with 0 stride.
6436 // TODO: Transform interleave access into multiple strided accesses.
6437 if (!MemR || MemR->isConsecutive())
6438 continue;
6439
6440 VPValue *Ptr = MemR->getAddr();
6441 // Check if this is a strided access by analyzing the address SCEV for an
6442 // affine addRec.
6443 const SCEV *PtrSCEV = vputils::getSCEVExprForVPValue(Ptr, PSE, &L);
6444 const SCEV *Start;
6445 const SCEVConstant *Step;
6446 // TODO: Support non-constant loop invariant stride.
6447 if (!match(PtrSCEV,
6449 m_SpecificLoop(&L))))
6450 continue;
6451
6452 VPValue *StoredValue = nullptr;
6453 Type *DataTy;
6454 Intrinsic::ID IntrinID;
6455 if (auto *StoreR = dyn_cast<VPWidenStoreRecipe>(&R)) {
6456 StoredValue = StoreR->getStoredValue();
6457 DataTy = StoredValue->getScalarType();
6458 IntrinID = Intrinsic::experimental_vp_strided_store;
6459 } else {
6460 auto *LoadR = cast<VPWidenLoadRecipe>(&R);
6461 DataTy = LoadR->getScalarType();
6462 IntrinID = Intrinsic::experimental_vp_strided_load;
6463 }
6464
6465 Align Alignment = MemR->getAlign();
6466 auto IsProfitable = [&](ElementCount VF) {
6467 Type *VectorTy = toVectorTy(DataTy, VF);
6468 if (!Ctx.TTI.isLegalStridedLoadStore(VectorTy, Alignment))
6469 return false;
6470 const InstructionCost CurrentCost = MemR->computeCost(VF, Ctx);
6471 const InstructionCost StridedLoadStoreCost =
6473 IntrinID, VectorTy, MemR->isMasked(), Alignment, Ctx);
6474 return StridedLoadStoreCost < CurrentCost;
6475 };
6476
6478 Range))
6479 continue;
6480
6481 // Invalidate the legacy widening decision so the cost of replaced load is
6482 // not counted during precomputeCosts.
6483 // TODO: Remove once the legacy exit cost computation is retired.
6484 for (ElementCount VF : Range)
6485 Ctx.invalidateWideningDecision(&MemR->getIngredient(), VF);
6486
6487 // Get VF as i32 for the vector length operand.
6488 if (!I32VF) {
6489 VPBuilder Builder(Plan.getVectorPreheader());
6490 I32VF = Builder.createScalarZExtOrTrunc(
6491 &Plan.getVF(), Type::getInt32Ty(Plan.getContext()),
6493 }
6494
6495 VPBuilder Builder(&R);
6496 // Create the base pointer of strided access. The access may be
6497 // predicated, so the original loop may never evaluate divisions in Start.
6498 // TODO: reuse VPDerivedIVRecipe for base pointer computation when it
6499 // supports a general VPValue as the start value.
6500 VPValue *StartVPV =
6501 VPSCEVExpander(Builder, *PSE.getSE(), R.getDebugLoc(),
6502 /*HoistOutOf=*/nullptr, /*SafeUDivMode=*/true)
6503 .expand(Start);
6504 VPValue *StrideInBytes = Plan.getOrAddLiveIn(Step->getValue());
6505 Type *IndexTy = Plan.getDataLayout().getIndexType(Ptr->getScalarType());
6506 assert(IndexTy == StrideInBytes->getScalarType() &&
6507 "Stride type from SCEV must match the index type");
6508 VPValue *CanIV = Builder.createScalarZExtOrTrunc(
6509 VectorLoop->getCanonicalIV(), IndexTy, DebugLoc::getUnknown());
6510 auto *AddRecPtr = cast<SCEVAddRecExpr>(PtrSCEV);
6511 auto *Offset = Builder.createOverflowingOp(
6512 Instruction::Mul, {CanIV, StrideInBytes},
6513 {AddRecPtr->hasNoUnsignedWrap(), /*HasNSW=*/false});
6514 GEPNoWrapFlags NWFlags = AddRecPtr->hasNoUnsignedWrap()
6517 VPValue *BasePtr = Builder.createNoWrapPtrAdd(StartVPV, Offset, NWFlags);
6518
6519 // Create a new vector pointer for strided access.
6520 VPValue *NewPtr = Builder.createVectorPointer(
6521 BasePtr, Type::getInt8Ty(Plan.getContext()), StrideInBytes, NWFlags,
6522 R.getDebugLoc());
6523
6524 VPValue *Mask = MemR->getMask();
6525 if (!Mask)
6526 Mask = Plan.getTrue();
6528 if (StoredValue)
6529 Ops.push_back(StoredValue);
6530 Ops.append({NewPtr, StrideInBytes, Mask, I32VF});
6531
6532 auto *StridedR = Builder.createWidenMemIntrinsic(
6533 IntrinID, Ops,
6534 StoredValue ? Type::getVoidTy(Plan.getContext()) : DataTy, Alignment,
6535 *MemR, R.getDebugLoc());
6536 if (!StoredValue)
6537 cast<VPWidenLoadRecipe>(&R)->replaceAllUsesWith(StridedR);
6538 R.eraseFromParent();
6539 }
6540 }
6541}
6542
6544 VFRange &Range) {
6547 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
6548 VPValue *X;
6549 if (!match(&R,
6551 continue;
6552 auto *BeforeFirst = cast<VPWidenIntrinsicRecipe>(&R);
6553 Type *Ty = Plan.getVF().getScalarType();
6554 auto IsCheap = [&](ElementCount VF) {
6555 Type *MaskTy = toVectorTy(X->getScalarType(), VF);
6556 Type *IdxTy = Plan.getDataLayout().getIndexType(Plan.getContext(), 0);
6557 IntrinsicCostAttributes CttzElts(
6558 Intrinsic::experimental_cttz_elts, IdxTy,
6559 {MaskTy, Type::getInt1Ty(Ctx.LLVMCtx)});
6560 IntrinsicCostAttributes ActiveLaneMask(Intrinsic::get_active_lane_mask,
6561 MaskTy, {Ty, Ty});
6562 return BeforeFirst->computeCost(VF, Ctx) <
6563 Ctx.TTI.getIntrinsicInstrCost(CttzElts, Ctx.CostKind) +
6564 Ctx.TTI.getIntrinsicInstrCost(ActiveLaneMask, Ctx.CostKind);
6565 };
6566 if (!Range.Start.isScalar() &&
6568 continue;
6569
6570 VPBuilder Builder(BeforeFirst);
6571 DebugLoc DL = BeforeFirst->getDebugLoc();
6572 VPValue *FirstActive = Builder.createScalarZExtOrTrunc(
6573 Builder.createFirstActiveLane(X, DL), Ty, DL);
6574 VPValue *PartStart = Builder.createOverflowingOp(
6576 {Plan.getZero(Ty), &Plan.getVF()});
6577 BeforeFirst->replaceAllUsesWith(Builder.createNaryOp(
6578 VPInstruction::ActiveLaneMask, {PartStart, FirstActive}, DL));
6579 BeforeFirst->eraseFromParent();
6580 }
6581 }
6582}
6583
6585 VPRecipeBuilder &RecipeBuilder,
6586 ScalarEvolution &SE) {
6587 VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
6590 vp_depth_first_shallow(HeaderVPBB))) {
6591 for (VPInstruction &VPI : make_isa_range<VPInstruction>(*VPBB)) {
6592 if (std::optional<CompressedPtrInfo> Info =
6593 RecipeBuilder.getCompressedPtrInfo(&VPI))
6594 CondIndToMemOps[Info->ConditionalInductionPHI].push_back(&VPI);
6595 }
6596 }
6597
6598 VPBuilder Builder;
6599 for (auto &CondIndPhi :
6601 // Obtain the mask for the conditional update from the VPBlendRecipe.
6602 VPValue *Mask = nullptr;
6603 auto *BlendR = cast<VPBlendRecipe>(CondIndPhi.getBackedgeValue());
6604 assert(!BlendR->isNormalized() && "Expected to run before simpifyBlends");
6605 for (unsigned ValIdx : seq(BlendR->getNumIncomingValues()))
6606 if (VPValue *IncomingValue = BlendR->getIncomingValue(ValIdx);
6607 IncomingValue != &CondIndPhi) {
6608 Mask = BlendR->getMask(ValIdx);
6609 break;
6610 }
6611 assert(Mask && "Expected mask for conditional induction update");
6612
6613 // Replace all "compressed" loads and stores with expandload and
6614 // compressstore respectively.
6615 for (VPInstruction *VPI : CondIndToMemOps[CondIndPhi.getPHINode()]) {
6616 // Bail out if the mask for the memory op does not match the condition
6617 // used to update the conditional induction.
6618 if (VPI->getMask() != Mask)
6619 return false;
6620
6621 Builder.setInsertPoint(VPI);
6622 auto *CompressedMemOp =
6623 Builder.insert(RecipeBuilder.widenCompressedLoadOrStore(VPI));
6624
6625 VPI->replaceAllUsesWith(CompressedMemOp);
6626 VPI->eraseFromParent();
6627 }
6628
6629 // Update the conditional induction to increment by the number of active
6630 // lanes in the mask.
6631 Type *UpdateType = CondIndPhi.getScalarType();
6632 if (UpdateType->isPointerTy())
6633 UpdateType = Plan.getDataLayout().getIndexType(UpdateType);
6634
6635 DebugLoc DL = CondIndPhi.getDebugLoc();
6636 const SCEV *StepSCEV = CondIndPhi.getStepSCEV();
6637
6638 Builder.setInsertPoint(BlendR);
6639 VPValue *HandledLanes =
6640 Builder.createNaryOp(VPInstruction::NumActiveLanes, Mask, UpdateType,
6641 {}, DL, "handled.lanes");
6642 VPValue *Step = VPSCEVExpander(Builder, SE, DL).expand(StepSCEV);
6643 if (!isa<VPConstantInt>(Step))
6644 Step = Builder.createFreeze(Step);
6645
6646 VPValue *Offset = Builder.createOverflowingOp(
6647 Instruction::Mul, {Step, HandledLanes}, {false, false}, DL);
6648 VPValue *Update =
6649 CondIndPhi.getScalarType()->isPointerTy()
6650 ? Builder.createPtrAdd(&CondIndPhi, Offset, DL, "conditional.step")
6651 : Builder.createAdd(&CondIndPhi, Offset, DL, "conditional.step");
6652 CondIndPhi.getBackedgeValue()->replaceAllUsesWith(Update);
6653 }
6654
6655 return true;
6656}
bool IsScalable
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(AttributeSet CallerAttrs, AttributeSet CalleeAttrs)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
@ Default
Hexagon Common GEP
#define _
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
licm
Definition LICM.cpp:343
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:85
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
Function const char * Passes
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains the declarations for profiling metadata utility functions.
Func MI getDebugLoc()))
This file contains some templates that are useful if you are working with the STL at all.
This is the interface for a metadata-based scoped no-alias analysis.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file implements the TypeSwitch template, which mimics a switch() statement whose cases are type ...
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of different VPlan-related auxiliary helpers.
static SmallVector< SmallVector< VPReplicateRecipe *, 4 > > collectComplementaryPredicatedMemOps(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
static void removeCommonBlendMask(VPBlendRecipe *Blend)
Try to see if all of Blend's masks share a common value logically and'ed and remove it from the masks...
static void tryToCreateAbstractReductionRecipe(VPReductionRecipe *Red, VPCostContext &Ctx, VFRange &Range)
This function tries to create abstract recipes from the reduction recipe for following optimizations ...
static VPReplicateRecipe * findRecipeWithMinAlign(ArrayRef< VPReplicateRecipe * > Group)
static CallWideningDecision decideCallWidening(VPInstruction &VPI, ArrayRef< VPValue * > Ops, ElementCount VF, VPCostContext &CostCtx)
Pick the cheapest widening for the call VPI at VF among scalarization, vector intrinsic,...
static bool areVFParamsOk(const VFInfo &Info, ArrayRef< VPValue * > Args, PredicatedScalarEvolution &PSE, const Loop *L)
Returns true if Info's parameter kinds are compatible with Args.
static bool sinkScalarOperands(VPlan &Plan)
static bool isVectorLatchCheck(VPRecipeBase *Term, VPValue *Cond, VPlan &Plan)
Return true if the branch Term with condition Cond (null if Term has no condition operand) is the vec...
static bool simplifyBranchConditionForVFAndUF(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
Try to simplify the branch condition of Plan.
static Align getLoadAlign(const VPSingleDefRecipe *R)
static void swapSelectBranchWeights(VPRecipeBase &R, VPlan &Plan)
Swap the branch weights recorded for R, a select whose two selected operands are being swapped,...
static VPValue * simplifyLogicalRecipe(VPlan &Plan, VPSingleDefRecipe *Def)
Try to simplify logical and bitwise recipes in Def.
static auto m_Countable(VPValue *&Cmp, PredicatedScalarEvolution &PSE, Loop *L)
Matches an exit condition formed by comparing the current value of a affine add recurrence in the giv...
static VPValue * cloneBinOpForScalarIV(VPWidenRecipe *BinOp, VPValue *ScalarIV, VPWidenIntOrFpInductionRecipe *WidenIV)
Create a scalar version of BinOp, with its WidenIV operand replaced by ScalarIV, and place it after S...
static VPWidenIntOrFpInductionRecipe * getExpressionIV(VPValue *V)
Check if V is a binary expression of a widened IV and a loop-invariant value.
static void removeRedundantInductionCasts(VPlan &Plan)
Remove redundant casts of inductions.
static bool isConditionTrueViaVFAndUF(VPValue *Cond, VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
Return true if Cond is known to be true for given BestVF and BestUF.
static VPExpressionRecipe * tryToMatchAndCreateExtendedReduction(VPReductionRecipe *Red, VPCostContext &Ctx, VFRange &Range)
This function tries convert extended in-loop reductions to VPExpressionRecipe and clamp the Range if ...
static bool isAvailableAtEndOf(VPValue *V, const VPBasicBlock *VPBB)
Returns true if V is available at the end of VPBB, i.e.
static std::optional< ElementCount > isConsecutiveInterleaveGroup(VPInterleaveRecipe *InterleaveR, ArrayRef< ElementCount > VFs, const TargetTransformInfo &TTI)
Returns VF from VFs if IR is a full interleave group with factor and number of members both equal to ...
static VPIRMetadata getCommonMetadata(ArrayRef< VPReplicateRecipe * > Recipes)
static bool mergeReplicateRegionsIntoSuccessors(VPlan &Plan)
static Function * findVectorVariant(CallInst *CI, ArrayRef< VPValue * > Args, ElementCount VF, bool MaskRequired, PredicatedScalarEvolution &PSE, const Loop *L)
Find a vector variant of CI for VF, respecting MaskRequired.
static bool canNarrowOps(ArrayRef< VPValue * > Ops, bool IsScalable, DenseMap< VPValue *, SmallVector< VPValue * > > &FirstMembersOf)
Returns true if the wide recipes in Ops and their operand trees can be narrowed.
TTI::PartialReductionExtendKind ExtendKind
static VPValue * getRecipesForUncountableExit(SmallVectorImpl< VPInstruction * > &Recipes, VPBasicBlock *LatchVPBB)
Returns the VPValue representing the uncountable exit comparison used by AnyOf if the recipes it depe...
static VPWidenInductionRecipe * getOptimizableIVOf(VPValue *VPV, PredicatedScalarEvolution &PSE)
Check if VPV is an untruncated wide induction, either before or after the increment.
static bool canNarrowLoad(VPSingleDefRecipe *WideMember0, unsigned OpIdx, VPValue *OpV, unsigned Idx, bool IsScalable)
Returns true if V is VPWidenLoadRecipe or VPInterleaveRecipe that can be converted to a narrower reci...
static bool handleUncountableExitsWithSideEffects(VPlan &Plan, SmallVectorImpl< EarlyExitInfo > &Exits, VPBasicBlock *HeaderVPBB, VPBasicBlock *LatchVPBB, VPBasicBlock *MiddleVPBB, OptimizationRemarkEmitter *ORE, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC)
Update Plan to mask memory operations in the loop based on whether the early exit is taken or not.
static void legalizeAndOptimizeInductions(VPlan &Plan)
Legalize VPWidenPointerInductionRecipe, by replacing it with a PtrAdd (IndStart, ScalarIVSteps (0,...
static void addReplicateRegions(VPlan &Plan)
static VPValue * optimizeLatchExitIVUserViaSCEV(VPlan &Plan, VPValue *Op, PredicatedScalarEvolution &PSE, VPValue *ResumeTC, const Loop *L)
static ExtendKind getPartialReductionExtendKind(VPWidenCastRecipe *Cast)
static SmallVector< SmallVector< VPReplicateRecipe *, 4 > > collectGroupedReplicateMemOps(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L, function_ref< bool(VPReplicateRecipe *)> FilterFn)
Collect either replicated Loads or Stores grouped by their address SCEV and their load-store type,...
static VPValue * tryToComputeEndValueForInduction(VPWidenInductionRecipe *WideIV, VPBuilder &VectorPHBuilder, VPValue *VectorTC)
Compute the end value for WideIV, unless it is truncated.
static bool loopHasStores(VPBasicBlock *HeaderVPBB)
static bool replaceMaskWithCompareForScalarPlan(VPlan &Plan, ElementCount BestVF)
static VPValue * simplifyRecipe(VPlan &Plan, VPSingleDefRecipe *Def)
Return an existing value or a live in for VPSingleDefRecipe Def if possible.
static VPValue * optimizeEarlyExitInductionUser(VPlan &Plan, VPValue *Op, PredicatedScalarEvolution &PSE)
Attempts to optimize the induction variable exit values for users in the early exit block.
static bool canFoldOuterExtendIntoMul(VPWidenRecipe *Mul)
Returns true if the narrow Mul in ext(mul(ext(A), ext(B))) or ext(mul(ext(A), C)) cannot wrap.
static VPValue * narrowInterleaveGroupOp(ArrayRef< VPValue * > Members, SmallPtrSetImpl< VPValue * > &NarrowedOps, VPBasicBlock *Preheader)
static VPValue * optimizeLatchExitInductionUser(VPlan &Plan, VPValue *Op, DenseMap< VPValue *, VPValue * > &EndValues, PredicatedScalarEvolution &PSE)
Attempts to optimize the induction variable exit values for users in the exit block coming from the l...
static void updatePartialReductionPhiAndResult(VPlan &Plan, VPReductionPHIRecipe *Phi, unsigned Factor, RecurKind RK)
static VPSingleDefRecipe * combineRecipe(VPlan &Plan, VPSingleDefRecipe *Def, VPCombineBuilder &Builder)
Combine Def into a simpler recipe.
static VPBasicBlock * getPredicatedThenBlock(VPRegionBlock *R)
If R is a triangle region, return the 'then' block of the triangle.
static bool tryToRemoveDeadCycle(VPRecipeBase *R)
If R is a phi-like recipe starting a dead cycle of recipes, erase all reachable recipes of the dead c...
static bool canHoistOrSinkWithNoAliasCheck(const MemoryLocation &MemLoc, VPBasicBlock *FirstBB, VPBasicBlock *LastBB, std::optional< SinkStoreInfo > SinkInfo={})
Check if a memory operation doesn't alias with memory operations using scoped noalias metadata,...
static VPRegionBlock * createReplicateRegion(VPReplicateRecipe *PredRecipe, VPRegionBlock *ParentRegion, VPlan &Plan)
static void simplifyBlends(VPlan &Plan)
Normalize and simplify VPBlendRecipes.
static bool cannotHoistOrSinkRecipe(VPRecipeBase &R, VPBasicBlock *FirstBB, VPBasicBlock *LastBB, bool Sinking=false)
Return true if we do not know how to (mechanically) hoist or sink a non-memory or memory recipe R out...
static auto m_Uncountable(VPValue *&Cond)
Matches an exit condition formed by comparing a value loaded from memory with a loop-invariant term.
static std::optional< Instruction::BinaryOps > getUnmaskedDivRemOpcode(Intrinsic::ID ID)
static bool isAlreadyNarrow(VPValue *VPV)
Returns true if VPValue is a narrow VPValue.
static bool optimizeVectorInductionWidthForTCAndVFUF(VPlan &Plan, ElementCount BestVF, unsigned BestUF)
Optimize the width of vector induction variables in Plan based on a known constant Trip Count,...
static VPExpressionRecipe * tryToMatchAndCreateMulAccumulateReduction(VPReductionRecipe *Red, VPCostContext &Ctx, VFRange &Range)
This function tries convert extended in-loop reductions to VPExpressionRecipe and clamp the Range if ...
static bool canSinkStoreWithNoAliasCheck(ArrayRef< VPReplicateRecipe * > StoresToSink, PredicatedScalarEvolution &PSE, const Loop &L)
static std::optional< bool > getStepDirection(const SCEV *S, ScalarEvolution &SE)
If S is an affine AddRec, returns true if its step is known to be positive and false if it is known t...
static VPIRMetadata getMetadataOf(VPRecipeBase *R)
Returns the metadata attached to R, or an empty set for a recipe that does not carry any.
static void narrowToSingleScalarRecipes(VPlan &Plan)
This file provides utility VPlan to VPlan transformations.
#define RUN_VPLAN_PASS(PASS,...)
This file contains the declarations of the Vectorization Plan base classes:
static const X86InstrFMA3Group Groups[]
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
Helper for extra no-alias checks via known-safe recipe and SCEV.
SinkStoreInfo(ArrayRef< VPReplicateRecipe * > ExcludeRecipes, VPReplicateRecipe &GroupLeader, PredicatedScalarEvolution &PSE, const Loop &L)
SinkStoreInfo(VPReplicateRecipe &GroupLeader)
bool shouldSkip(VPRecipeBase &R) const
Return true if R should be skipped during alias checking, either because it's in the exclude set or b...
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
int32_t exactLogBase2() const
Definition APInt.h:1803
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
static APSInt getMinValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the minimum integer value with the given bit width and signedness.
Definition APSInt.h:310
static APSInt getMaxValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the maximum integer value with the given bit width and signedness.
Definition APSInt.h:302
@ NoAlias
The two locations do not alias at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
This class represents a function call, abstracting a target machine's calling convention.
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
This class represents a range of values.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getUnknown()
Definition DebugLoc.h:153
ValueT lookup_or(const_arg_type_t< KeyT > Val, U &&Default) const
Definition DenseMap.h:803
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:309
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
size_t arg_size() const
Definition Function.h:895
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags noUnsignedWrap()
bool hasNoUnsignedWrap() const
GEPNoWrapFlags withoutNoUnsignedWrap() const
static GEPNoWrapFlags none()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
A struct for saving information about induction variables.
InductionKind
This enum represents the kinds of inductions that we support.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
static InstructionCost getInvalid(CostType Val=0)
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool isBinaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
bool isIntDivRem() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
The group of interleaved loads/stores sharing the same stride and close to each other.
InstTy * getInsertPos() const
Align getAlign() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
static bool getDecisionAndClampRange(const std::function< bool(ElementCount)> &Predicate, VFRange &Range)
Test a Predicate on a Range of VF's.
Definition VPlan.cpp:1639
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
ValueT lookup(const KeyT &Key) const
Definition MapVector.h:111
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:119
bool empty() const
Definition MapVector.h:80
Representation for a specific memory location.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:254
The optimization diagnostic interface.
Post-order traversal of a graph.
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.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static bool isFindLastRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cond,x,y) where one of (x,...
static bool isFindRecurrenceKind(RecurKind Kind)
LLVM_ABI bool match(StringRef String, SmallVectorImpl< StringRef > *Matches=nullptr, std::string *Error=nullptr) const
matches - Match the regex against a given String.
Definition Regex.cpp:84
RegionT * getParent() const
Get the parent of the Region.
Definition RegionInfo.h:365
This class represents a constant integer value.
ConstantInt * getValue() const
static const SCEV * rewrite(SCEVUse Scev, ScalarEvolution &SE, ValueToSCEVMapTy &Map)
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
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.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI bool isGuaranteedNotToCauseUB(const SCEV *Op)
Returns true if Op is guaranteed not to cause immediate UB.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, unsigned Depth=0)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
A simple AA result which uses scoped-noalias metadata to answer queries.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static LLVM_ABI PartialReductionExtendKind getPartialReductionExtendKind(Instruction *I)
Get the kind of extension that an instruction represents.
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ ActiveLaneMask
The operation is masked with a contiguous active lane mask.
LLVM_ABI InstructionCost getPartialReductionCost(unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType, ElementCount VF, PartialReductionExtendKind OpAExtend, PartialReductionExtendKind OpBExtend, std::optional< unsigned > BinOp, TTI::TargetCostKind CostKind, std::optional< FastMathFlags > FMF) const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
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:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
op_range operands()
Definition User.h:267
static SmallVector< VFInfo, 8 > getMappings(const CallInst &CI)
Retrieve all the VFInfo instances associated to the CallInst CI.
Definition VectorUtils.h:76
bool isLegalMaskedLoadOrStore(bool IsLoad, Type *ScalarTy, Align Alignment, unsigned AddressSpace) const
Returns true if the target machine supports a masked load (if IsLoad) or masked store of scalar type ...
A recipe for generating the active lane mask for the vector loop that is used to predicate the vector...
Definition VPlan.h:4150
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4512
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4593
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4543
iterator end()
Definition VPlan.h:4553
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4551
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4606
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:225
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
Definition VPlan.cpp:524
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:603
const VPRecipeBase & back() const
Definition VPlan.h:4565
A recipe for vectorizing a phi-node as a sequence of mask-based select instructions.
Definition VPlan.h:3021
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition VPlan.h:3068
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
Definition VPlan.h:3073
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:3063
void setMask(unsigned Idx, VPValue *V)
Set mask number Idx to V.
Definition VPlan.h:3079
bool isNormalized() const
A normalized blend is one that has an odd number of operands, whereby the first operand does not have...
Definition VPlan.h:3059
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:80
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:290
VPRegionBlock * getParent()
Definition VPlan.h:178
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:195
size_t getNumSuccessors() const
Definition VPlan.h:228
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition VPlan.h:281
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:213
VPlan * getPlan()
Definition VPlan.h:182
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:224
void clearPredecessors()
Remove all the predecessor of this block.
Definition VPlan.h:297
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:180
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
Definition VPlan.h:261
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:218
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:202
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:467
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
Definition VPlanUtils.h:482
static bool isLatch(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop latch, using isHeader().
static VPBasicBlock * getPlainCFGMiddleBlock(const VPlan &Plan)
Returns the middle block of Plan in plain CFG form (before regions are formed).
static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBases IfTrue and IfFalse after BlockPtr.
Definition VPlanUtils.h:376
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:394
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:412
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:460
static std::pair< VPBasicBlock *, VPBasicBlock * > getPlainCFGHeaderAndLatch(const VPlan &Plan)
Returns the header and latch of the outermost loop of Plan in plain CFG form (before regions are form...
static void transferSuccessors(VPBlockBase *Old, VPBlockBase *New)
Transfer successors from Old to New. New must have no successors.
Definition VPlanUtils.h:444
static SmallVector< VPBasicBlock * > blocksInSingleSuccessorChainBetween(VPBasicBlock *FirstBB, VPBasicBlock *LastBB)
Returns the blocks between FirstBB and LastBB, where FirstBB to LastBB forms a single-sucessor chain.
A recipe for generating conditional branches on the bits of a mask.
Definition VPlan.h:3568
VPlan-based builder utility similar to IRBuilder.
VPInstruction * createFreeze(VPValue *Op, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPWidenIntrinsicRecipe * createWidenIntrinsic(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
static VPBuilderBase getToInsertAfter(VPRecipeBase *R)
VPInstruction * createLogicalAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createAnyOfReduction(VPValue *ChainOp, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown())
Create an AnyOf reduction pattern: or-reduce ChainOp, freeze the result, then select between TrueVal ...
VPDerivedIVRecipe * createDerivedIV(InductionDescriptor::InductionKind Kind, FPMathOperator *FPBinOp, VPValue *Start, VPValue *Current, VPValue *Step, const VPIRFlags::WrapFlagsTy &Flags={})
Convert Current to Start + Current * Step.
VPWidenCastRecipe * createWidenCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy)
VPInstruction * createAdd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", VPRecipeWithIRFlags::WrapFlagsTy WrapFlags={false, false})
VPInstruction * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt)
Create a select of TrueVal and FalseVal based on Cond, using the default flags for the result type,...
VPValue * createScalarZExtOrTrunc(VPValue *Op, Type *ResultTy, DebugLoc DL)
static VPSingleDefRecipe * createSingleScalarOp(unsigned Opcode, ArrayRef< VPValue * > Operands, VPValue *Mask, const VPIRFlags &Flags, const VPIRMetadata &Metadata, DebugLoc DL, Type *ResultTy, Instruction *UV)
VPWidenLoadRecipe * createWidenLoad(LoadInst &Load, VPValue *Addr, VPValue *Mask, bool Consecutive, Align Alignment, const VPIRMetadata &Metadata, DebugLoc DL)
Create a recipe widening Load, loading from Addr with Mask (may be null).
VPInstruction * createLogicalOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createScalarCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, DebugLoc DL, std::optional< VPIRFlags > Flags=std::nullopt, const VPIRMetadata &Metadata={})
VPInstruction * createNot(VPValue *Operand, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
void setInsertPoint(const VPInsertPoint &IP)
Set the current insert point.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr, const VPIRAttributes &Attrs={})
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
VPInstruction * createSub(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", VPRecipeWithIRFlags::WrapFlagsTy WrapFlags={false, false})
VPInstruction * createFirstActiveLane(ArrayRef< VPValue * > Masks, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPWidenStoreRecipe * createWidenStore(StoreInst &Store, VPValue *Addr, VPValue *StoredVal, VPValue *Mask, bool Consecutive, Align Alignment, const VPIRMetadata &Metadata, DebugLoc DL)
Create a recipe widening Store, storing StoredVal to Addr with Mask (may be null).
VPInstruction * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new ICmp VPInstruction with predicate Pred and operands A and B.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:572
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:545
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:557
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:567
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
LLVM_ABI_FOR_TEST bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B) const
Recipe to expand a SCEV expression.
Definition VPlan.h:4107
A recipe to combine multiple recipes into a single 'expression' recipe, which should be considered a ...
Definition VPlan.h:3615
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2476
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2516
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2505
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition VPlan.h:2191
Manage IR attributes for call recipes.
Definition VPlan.h:1258
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4671
Class to record and manage LLVM IR flags.
Definition VPlan.h:668
static LLVM_ABI_FOR_TEST VPIRFlags getDefaultFlags(unsigned Opcode, Type *ResultTy=nullptr)
Returns default flags for Opcode and scalar ResultTy for opcodes that support it, asserts otherwise.
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
Helper to manage IR metadata for recipes.
Definition VPlan.h:1141
std::optional< VPExecutionFrequency > getExecutionFrequency() const
Returns the frequency recorded by setExecutionFrequency, if any.
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetadata object with MD, keeping only metadata nodes that are common to both.
void clearExecutionFrequency()
Drop the frequency recorded by setExecutionFrequency, if any.
void setExecutionFrequency(std::optional< VPExecutionFrequency > Freq, LLVMContext &Ctx)
Record that the recipe executes with frequency Freq, relative to the entry of the loop region.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1311
unsigned getNumOperandsWithoutMask() const
Returns the number of operands, excluding the mask if the VPInstruction is masked.
Definition VPlan.h:1551
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1415
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1411
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1361
@ CanonicalIVIncrementForPart
Definition VPlan.h:1347
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1369
void addMask(VPValue *Mask)
Add mask Mask to an unmasked VPInstruction, if it needs masking.
Definition VPlan.h:1556
unsigned getOpcode() const
Definition VPlan.h:1520
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1567
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3174
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3166
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3191
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:3201
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1676
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1642
VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when control converges back from ...
Definition VPlan.h:3790
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:387
void moveBefore(RecipeListTy::iterator I)
Unlink this recipe and insert it before I.
VPRegionBlock * getRegion()
Definition VPlan.h:4917
RecipeListTy::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:532
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
Helper class to create VPRecipies from IR instructions.
VPHistogramRecipe * widenIfHistogram(VPInstruction *VPI)
If VPI represents a histogram operation (as determined by LoopVectorizationLegality) make that safe f...
std::optional< CompressedPtrInfo > getCompressedPtrInfo(VPInstruction *VPI)
Returns the CompressedPtrInfo for VPI if it is a compressed load or store (as determined by LoopVecto...
bool prefersVectorizedAddressing() const
Returns true if the target prefers vectorized addressing.
VPRecipeBase * tryToWidenMemory(VPInstruction *VPI, VFRange &Range)
Check if the load or store instruction VPI should widened for Range.Start and potentially masked.
bool replaceWithFinalIfReductionStore(VPInstruction *VPI, VPBuilder &FinalRedStoresBuilder)
If VPI is a store of a reduction into an invariant address, delete it.
VPSingleDefRecipe * handleReplication(VPInstruction *VPI, VFRange &Range)
Build a replicating or single-scalar recipe for VPI.
VPWidenMemIntrinsicRecipe * widenCompressedLoadOrStore(VPInstruction *VPI)
Build a llvm.masked.expandload or llvm.masked.compressstore intrinsic for VPI.
bool isPredicatedInst(Instruction *I) const
Returns true if I needs to be predicated (i.e.
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:349
A recipe for handling reduction phis.
Definition VPlan.h:2867
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2939
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2942
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2936
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3294
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4743
const VPBlockBase * getEntry() const
Definition VPlan.h:4787
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4819
void setExiting(VPBlockBase *ExitingBlock)
Set ExitingBlock as the exiting VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4804
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print this VPRegionBlock to O (recursively), prefixing all lines with Indent.
Definition VPlan.cpp:831
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4871
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4863
const VPBlockBase * getExiting() const
Definition VPlan.h:4799
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4876
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3461
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
Definition VPlan.h:3518
static InstructionCost computeCallCost(Function *CalledFn, Type *ResultTy, ArrayRef< const VPValue * > ArgOps, bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx)
Return the cost of scalarizing a call to CalledFn with argument operands ArgOps for a given VF.
operand_range operandsWithoutMask()
Return the recipe's operands, excluding the mask of a predicated recipe.
Definition VPlan.h:3546
bool isPredicated() const
Definition VPlan.h:3523
VPValue * getMask()
Return the mask of a predicated VPReplicateRecipe.
Definition VPlan.h:3540
Lightweight SCEV-to-VPlan expander.
Definition VPlanUtils.h:286
VPValue * expand(const SCEV *S)
Expand S into recipes and live-ins using the builder.
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition VPlan.h:4344
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:590
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:653
VPSingleDefRecipe * clone() override=0
Clone the current recipe.
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:212
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
operand_range operands()
Definition VPlanValue.h:472
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:445
unsigned getNumOperands() const
Definition VPlanValue.h:436
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:437
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:139
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:133
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1465
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:120
bool hasMoreThanOneUniqueUser() const
Returns true if the value has more than one unique user.
Definition VPlanValue.h:164
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser *U)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1474
bool user_empty() const
Definition VPlanValue.h:161
bool hasOneUse() const
Definition VPlanValue.h:175
VPUser * getSingleUser()
Return the single user of this value, or nullptr if there is not exactly one user.
Definition VPlanValue.h:179
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1468
user_range users()
Definition VPlanValue.h:157
A recipe to compute a pointer to the last element of each part of a widened memory access for widened...
Definition VPlan.h:2310
A recipe for widening Call instructions using library calls.
Definition VPlan.h:2125
static InstructionCost computeCallCost(Function *Variant, VPCostContext &Ctx)
Return the cost of widening a call using the vector function Variant.
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1892
Instruction::CastOps getOpcode() const
Definition VPlan.h:1928
A recipe for handling GEP instructions.
Definition VPlan.h:2250
Base class for widened induction (VPWidenIntOrFpInductionRecipe and VPWidenPointerInductionRecipe),...
Definition VPlan.h:2534
PHINode * getPHINode() const
Returns the underlying PHINode if one exists, or null otherwise.
Definition VPlan.h:2586
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2574
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2591
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2620
bool isTruncated() const
Returns true if this induction is evaluated in a narrower type than the start value.
Definition VPlan.h:2673
A recipe for widening vector intrinsics.
Definition VPlan.h:1940
static InstructionCost computeCallCost(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost of a vector intrinsic with ID and Operands.
static InstructionCost computeMemIntrinsicCost(Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment, VPCostContext &Ctx)
Helper function for computing the cost of vector memory intrinsic.
A common mixin class for widening memory operations.
Definition VPlan.h:3826
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
A recipe for widened phis.
Definition VPlan.h:2754
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1825
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenRecipe.
VPWidenRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1851
unsigned getOpcode() const
Definition VPlan.h:1870
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4930
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:5260
bool hasVF(ElementCount VF) const
Definition VPlan.h:5153
const DataLayout & getDataLayout() const
Definition VPlan.h:5131
LLVMContext & getContext() const
Definition VPlan.h:5127
VPBasicBlock * getEntry()
Definition VPlan.h:5022
bool hasScalableVF() const
Definition VPlan.h:5154
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5094
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition VPlan.h:5160
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5226
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5125
VPIRValue * getAllOnesValue(Type *Ty)
Return a VPIRValue wrapping the AllOnes value of type Ty.
Definition VPlan.h:5232
VPRegionBlock * createReplicateRegion(VPBlockBase *Entry, VPBlockBase *Exiting, const std::string &Name="")
Create a new replicate region with Entry, Exiting and Name.
Definition VPlan.h:5313
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:5263
bool hasUF(unsigned UF) const
Definition VPlan.h:5178
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5088
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5115
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:5203
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5229
void setVF(ElementCount VF)
Definition VPlan.h:5141
bool isUnrolled() const
Returns true if the VPlan already has been unrolled, i.e.
Definition VPlan.h:5194
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1058
LLVM_ABI_FOR_TEST bool isOuterLoop() const
Returns true if this VPlan is for an outer loop, i.e., its vector loop region contains a nested loop ...
Definition VPlan.cpp:1083
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:5181
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:5108
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:5064
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5286
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5223
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:5027
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:5122
bool hasScalarVFOnly() const
Definition VPlan.h:5171
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5078
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:5043
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5118
LLVM_ABI_FOR_TEST VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
Definition VPlan.cpp:1218
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:5237
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:428
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
Base class of all SIMD vector types.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS*X will result in a value whose quantity matches our ...
Definition TypeSize.h:266
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr ScalarTy getKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns a value X where RHS*X will result in a value whose quantity matches our own.
Definition TypeSize.h:274
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:217
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:172
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2810
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Definition DwarfDebug.h:190
void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_unless< Pattern > m_Unless(const Pattern &P)
Match if the inner matcher does NOT match.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
FNeg_match< OpTy, false > m_FNeg(const OpTy &X)
Match fneg X only.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
OneOps_match< OpTy, Instruction::Freeze > m_Freeze(const OpTy &Op)
Matches FreezeInst.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
LogicalOp_match< LHS, RHS, Instruction::And > m_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R either in the form of L & R or L ?
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
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.
CmpClass_match< LHS, RHS, CmpInst, true > m_c_Cmp(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
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)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(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.
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
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.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::FAdd, true > m_c_FAdd(const LHS &L, const RHS &R)
Matches FAdd with LHS and RHS in either order.
LogicalOp_match< LHS, RHS, Instruction::And, true > m_c_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
LogicalOp_match< LHS, RHS, Instruction::Or, true > m_c_LogicalOr(const LHS &L, const RHS &R)
Matches L || R with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
bool match(const SCEV *S, const Pattern &P)
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::ExtractLastLane, VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > > m_ExtractLastLaneOfLastPart(const Op0_t &Op0)
AllRecipe_commutative_match< Instruction::And, Op0_t, Op1_t > m_c_BinaryAnd(const Op0_t &Op0, const Op1_t &Op1)
Match a binary AND operation.
AllRecipe_match< Instruction::Or, Op0_t, Op1_t > m_BinaryOr(const Op0_t &Op0, const Op1_t &Op1)
Match a binary OR operation.
VPInstruction_match< VPInstruction::AnyOf > m_AnyOf()
RecipeTy * findSingleUser(VPValue *V, const MatchT &P)
Return the sole user of V matching pattern P, casting it to RecipeTy, or nullptr.
AllRecipe_commutative_match< Instruction::Or, Op0_t, Op1_t > m_c_BinaryOr(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::ComputeReductionResult, Op0_t > m_ComputeReductionResult(const Op0_t &Op0)
auto m_WidenAnyExtend(const Op0_t &Op0)
match_bind< VPIRValue > m_VPIRValue(VPIRValue *&V)
Match a VPIRValue.
auto m_VPPhi(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::BranchOnTwoConds > m_BranchOnTwoConds()
VPWidenStoreRecipe_match< Op0_t, Op1_t > m_WidenStore(const Op0_t &Op0, const Op1_t &Op1)
AllRecipe_match< Opcode, Op0_t, Op1_t > m_Binary(const Op0_t &Op0, const Op1_t &Op1)
VPWidenLoadRecipe_match< Op0_t > m_WidenLoad(const Op0_t &Op0)
VPInstruction_match< VPInstruction::LastActiveLane, Op0_t > m_LastActiveLane(const Op0_t &Op0)
auto m_WidenIntrinsic(const T &...Ops)
canonical_widen_iv_match m_CanonicalWidenIV()
VPInstruction_match< VPInstruction::ExitingIVValue, Op0_t > m_ExitingIVValue(const Op0_t &Op0)
VPInstruction_match< Instruction::ExtractElement, Op0_t, Op1_t > m_ExtractElement(const Op0_t &Op0, const Op1_t &Op1)
ActiveLaneMaskPHIRecipe_match< Op0_t, Op1_t > m_ActiveLaneMaskPhi(const Op0_t &Op0, const Op1_t &Op1)
VectorPointerRecipe_match< Op0_t, Op1_t > m_VecPtr(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::ExtractLastLane, Op0_t > m_ExtractLastLane(const Op0_t &Op0)
int_pred_ty< is_zero_int, 1 > m_False()
match_bind< VPSingleDefRecipe > m_VPSingleDefRecipe(VPSingleDefRecipe *&V)
Match a VPSingleDefRecipe, capturing if we match.
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
auto m_GetElementPtr(const Op0_t &Op0, const Op1_t &Op1)
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::Broadcast, Op0_t > m_Broadcast(const Op0_t &Op0)
bool match(Val *V, const Pattern &P)
header_mask_match m_HeaderMask()
VPInstruction_match< VPInstruction::BuildVector > m_BuildVector()
BuildVector is matches only its opcode, w/o matching its operands as the number of operands is not fi...
VPInstruction_match< VPInstruction::ExtractPenultimateElement, Op0_t > m_ExtractPenultimateElement(const Op0_t &Op0)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::FirstActiveLane, Op0_t > m_FirstActiveLane(const Op0_t &Op0)
int_pred_ty< is_one, 1 > m_True()
VPInstruction_match< VPInstruction::WideActiveLaneMask, Op_t... > m_WideActiveLaneMask(const Op_t &...Op)
VPInstruction_match< VPInstruction::ExtractVectorForPart, Op_t... > m_ExtractVectorForPart(const Op_t &...Op)
auto m_DerivedIV(const Op0_t &Op0, const Op1_t &Op1, const Op2_t &Op2)
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
VPInstruction_match< VPInstruction::ExtractLane, Op0_t, Op1_t > m_ExtractLane(const Op0_t &Op0, const Op1_t &Op1)
auto m_AnyNeg(const Op0_t &Op0)
VPInstruction_match< VPInstruction::Reverse, Op0_t > m_Reverse(const Op0_t &Op0)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
bool cannotHoistOrSinkRecipe(const VPRecipeBase &R, bool Sinking=false)
Return true if we do not know how to (mechanically) hoist or sink R.
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
std::optional< int64_t > getConstantStride(VPValue *Addr, Type *AccessTy, PredicatedScalarEvolution &PSE, const Loop *L)
If the pointer operand Addr of a memory access is an affine AddRec w.r.t.
VPInstruction * findComputeReductionResult(VPReductionPHIRecipe *PhiR)
Find the ComputeReductionResult recipe for PhiR, looking through selects inserted for predicated redu...
VPInstruction * findCanonicalIVIncrement(VPlan &Plan)
Find the canonical IV increment of Plan's vector loop region.
std::optional< MemoryLocation > getMemoryLocation(const VPRecipeBase &R)
Return a MemoryLocation for R with noalias metadata populated from R, if the recipe is supported and ...
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used by all users.
VPIRValue * tryToFoldLiveIns(VPSingleDefRecipe &R, ArrayRef< VPValue * > Operands, const DataLayout &DL)
Try to fold R using InstSimplifyFolder.
SmallVector< std::pair< VPBasicBlock *, VPIRBasicBlock * > > getEarlyExits(const VPlan &Plan, const VPBlockBase *MiddleVPBB)
Returns the (early exiting block, exit block) pairs of Plan, i.e.
VPScalarIVStepsRecipe * createScalarIVSteps(VPlan &Plan, InductionDescriptor::InductionKind Kind, Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp, Type *ResultTy, VPValue *StartV, VPValue *Step, DebugLoc DL, VPBuilder &Builder, const VPIRFlags::WrapFlagsTy &Flags={})
Create a scalar-iv-steps recipe over Plan's canonical IV for an induction of Kind with InductionOpcod...
void recursivelyDeleteDeadRecipes(VPValue *V)
Recursively delete V and any of its operands that become dead.
bool doesGeneratePerAllLanes(const VPRecipeBase *R)
Returns true if R produces scalar values for all VF lanes.
Type * getLoadStoreValueType(const VPSingleDefRecipe *R)
Get the value type of a VPInstruction or VPReplicateRecipe load or store.
Definition VPlanUtils.h:253
bool isDeadRecipe(VPRecipeBase &R)
Returns true if R is dead, i.e.
LLVM_ABI_FOR_TEST bool isUniformAcrossVFsAndUFs(const VPValue *V)
Checks if V is uniform across all VF lanes and UF parts.
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, bool ExpandInIR=false)
Get or create a VPValue that corresponds to the expansion of Expr.
bool isUsedByLoadStoreAddress(const VPValue *V)
Returns true if V is used as part of the address of another load or store.
std::optional< std::pair< bool, unsigned > > getOpcodeOrIntrinsicID(const VPValue *V)
Get the instruction opcode or intrinsic ID for the recipe defining V.
VPValue * scalarizeVPWidenPointerInduction(VPWidenPointerInductionRecipe *PtrIV, VPlan &Plan, VPBuilder &Builder)
Scalarize a VPWidenPointerInductionRecipe by replacing it with a PtrAdd (IndStart,...
LLVM_ABI_FOR_TEST 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:270
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.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
SmallVector< VPBasicBlock * > vp_rpo_plain_cfg_loop_body(VPBasicBlock *Header)
Returns the VPBasicBlocks forming the loop body of a plain (pre-region) VPlan in reverse post-order s...
Definition VPlanCFG.h:262
@ Offset
Definition DWP.cpp:577
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
void stable_sort(R &&Range)
Definition STLExtras.h:2132
auto min_element(R &&Range)
Provide wrappers to std::min_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2094
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:1755
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
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:856
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
Definition VPlan.h:2854
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
VPBuilderBase<> VPBuilder
Definition VPlan.h:66
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
auto cast_or_null(const Y &Val)
Definition Casting.h:714
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
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
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
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:286
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
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:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr size_t range_size(R &&Range)
Returns the size of the Range, i.e., the number of elements.
Definition STLExtras.h:1710
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
DenseMap< Value *, const SCEVUnknown * > SymbolicStrideMap
Maps a pointer to its symbolic (non-constant) stride.
bool hasIrregularType(Type *Ty, const DataLayout &DL)
A helper function that returns true if the given type is irregular.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
bool canConstantBeExtended(const APInt *C, Type *NarrowType, TTI::PartialReductionExtendKind ExtKind)
Check if a constant CI can be safely treated as having been extended from a narrower type with the gi...
Definition VPlan.cpp:1821
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
Definition STLExtras.h:1853
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FindIV
FindIV reduction with select(icmp(),x,y) where one of (x,y) is a loop induction variable (increasing ...
@ Or
Bitwise or logical OR of integers.
@ Mul
Product of integers.
@ FSub
Subtraction of floats.
@ FAddChainWithSubs
A chain of fadds and fsubs.
@ FMul
Product of floats.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FAdd
Sum of floats.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DenseMap< const Value *, SCEVUse > ValueToSCEVMapTy
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
const VectorizeOptions & getVectorizeOptions(const LLVMContext &C)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
LLVM_ABI bool isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC=nullptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return true if we can prove that the given load (which is assumed to be within the specified loop) wo...
Definition Loads.cpp:307
constexpr detail::CastFunc< To > CastTo
Definition Casting.h:884
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI_FOR_TEST bool verifyVPlanIsValid(const VPlan &Plan)
Verify invariants for general VPlans.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
VPBasicBlock * EarlyExitingVPBB
VPIRBasicBlock * EarlyExitVPBB
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
An information struct used to provide DenseMap with the various necessary components for a given valu...
Matcher to bind the captured value.
This reduction is unordered with the partial result scaled down by some factor.
Definition VPlan.h:2849
Holds the VFShape for a specific scalar to vector function mapping.
Encapsulates information needed to describe a parameter.
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
Struct to hold various analysis needed for cost computations.
const VFSelectionContext & Config
static bool isFreeScalarIntrinsic(Intrinsic::ID ID)
Returns true if ID is a pseudo intrinsic that is dropped via scalarization rather than widened.
Definition VPlan.cpp:1925
bool isMaskRequired(Instruction *I) const
Forwards to LoopVectorizationCostModel::isMaskRequired.
PredicatedScalarEvolution & PSE
bool willBeScalarized(Instruction *I, ElementCount VF) const
Returns true if I is known to be scalarized at VF.
TargetTransformInfo::TargetCostKind CostKind
const TargetLibraryInfo & TLI
const TargetTransformInfo & TTI
const VectorizeOptions & Opts
A recipe for handling first-order recurrence phis.
Definition VPlan.h:2805
WrapFlagsTy withoutNoSignedWrap()
Definition VPlan.h:690
An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use cast/dyn_cast/isa and exec...
Definition VPlan.h:1793
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:274
Type * getType() const
Returns the type of the underlying IR value.
Definition VPlan.cpp:137
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3890
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:3998
static LLVM_ABI_FOR_TEST void printIfRequested(VPlan &Plan, Function *Fn, StringRef NumberedPassName, bool After)
Print Plan of Fn before or after the pass NumberedPassName if requested.
static void simplifyLiveInsWithSCEV(VPlan &Plan, PredicatedScalarEvolution &PSE)
Check Plan's live-ins and replace them with constants, if they can be simplified via SCEV.
static bool makeCallWideningDecisions(VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder, VPCostContext &CostCtx)
Convert call VPInstructions in Plan into widened call, vector intrinsic or replicate recipes based on...
static decltype(auto) runPass(StringRef PassName, PassTy &&Pass, VPlan &Plan, ArgsTy &&...Args)
Helper to run a VPlan pass Pass on VPlan, forwarding extra arguments to the pass.
static void createInterleaveGroups(VPlan &Plan, const SmallPtrSetImpl< const InterleaveGroup< Instruction > * > &InterleaveGroups, const bool &EpilogueAllowed)
static LLVM_ABI_FOR_TEST bool tryToConvertVPInstructionsToVPRecipes(VPlan &Plan, const TargetLibraryInfo &TLI, PredicatedScalarEvolution &PSE, Loop *OuterLoop)
Replaces the VPInstructions in Plan with corresponding widen recipes.
static void createAndOptimizeReplicateRegions(VPlan &Plan)
Wrap predicated VPReplicateRecipes with a mask operand in an if-then region block and remove the mask...
static std::unique_ptr< VPlan > narrowInterleaveGroups(VPlan &Plan, const TargetTransformInfo &TTI)
Try to find a single VF among Plan's VFs for which all interleave groups (with known minimum VF eleme...
static LLVM_ABI_FOR_TEST bool handleUncountableExits(VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC)
Update Plan to account for uncountable early exits by introducing appropriate branching logic in the ...
static void makeMemOpWideningDecisions(VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder, VPCostContext &CostCtx)
Convert load/store VPInstructions in Plan into widened or replicate recipes.
static void hoistPredicatedLoads(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
Hoist predicated loads from the same address to the loop entry block, if they are guaranteed to execu...
static bool mergeBlocksIntoPredecessors(VPlan &Plan)
Remove redundant VPBasicBlocks by merging them into their single predecessor if the latter has a sing...
static void expandMaskBeforeFirst(VPlan &Plan, VPCostContext &Ctx, VFRange &Range)
Expand mask.beforefirst into an active-lane-mask of its first active lane for the VFs in Range where ...
static void optimizeFindIVReductions(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &L)
Optimize FindLast reductions selecting IVs (or expressions of IVs) by converting them to FindIV reduc...
static void convertToAbstractRecipes(VPlan &Plan, VPCostContext &Ctx, VFRange &Range)
This function converts initial recipes to the abstract recipes and clamps Range based on cost model f...
static void makeScalarizationDecisions(VPlan &Plan, VFRange &Range)
Make VPlan-based scalarization decision prior to delegating to the ones made by the legacy CM.
static bool areAllLoadsDereferenceable(VPBasicBlock *HeaderVPBB, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC)
Check if all loads in the loop are dereferenceable.
static LLVM_ABI_FOR_TEST void verifyIfRequested(VPlan &Plan)
Abort if -vplan-verify-each is set and Plan is invalid.
static void optimizeInductionLiveOutUsers(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
If there's a single exit block, optimize its phi recipes that use exiting IV values by feeding them p...
static void simplifyReverses(VPlan &Plan)
Cancel out redundant reverses in Plan, e.g. reverse(reverse(x)) -> x.
static void adjustFirstOrderRecurrenceMiddleUsers(VPlan &Plan, VFRange &Range)
Adjust first-order recurrence users in the middle block: create penultimate element extracts for LCSS...
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void sinkPredicatedStores(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
Sink predicated stores to the same address with complementary predicates (P and NOT P) to an uncondit...
static bool removeBranchOnConst(VPlan &Plan, bool OnlyLatches=false)
Remove BranchOnCond recipes with true or false conditions together with removing dead edges to their ...
static void convertToStridedAccesses(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &L, VPCostContext &Ctx, VFRange &Range)
Transform widen memory recipes into strided access recipes when legal and profitable.
static void clearReductionWrapFlags(VPlan &Plan)
Clear NSW/NUW flags from reduction instructions if necessary.
static LLVM_ABI_FOR_TEST bool isPrintingRequested(const VPlan &Plan)
static void createPartialReductions(VPlan &Plan, VPCostContext &CostCtx, VFRange &Range)
Detect and create partial reduction recipes for scaled or unordered reductions in Plan.
static bool widenCompressingPatterns(VPlan &Plan, VPRecipeBuilder &RecipeBuilder, ScalarEvolution &SE)
Widens compressing memory loads/stores.
static void cse(VPlan &Plan, const VPDominatorTree &VPDT)
Perform common-subexpression-elimination on Plan.
static void replaceSymbolicStrides(VPlan &Plan, PredicatedScalarEvolution &PSE, const SymbolicStrideMap &StridesMap, const VPDominatorTree &VPDT)
Replace symbolic strides from StridesMap in Plan with constants when possible.
static LLVM_ABI_FOR_TEST void optimize(VPlan &Plan)
Apply VPlan-to-VPlan optimizations to Plan, including induction recipe optimizations,...
static void truncateToMinimalBitwidths(VPlan &Plan, const MapVector< Instruction *, uint64_t > &MinBWs)
Insert truncates and extends for any truncated recipe.
static void narrowInductionTruncates(VPlan &Plan, VFRange &Range, const TargetTransformInfo &TTI)
Replace truncates of a wide induction, or of that induction's increment, by a VPWidenIntOrFpInduction...
static void dropPoisonGeneratingRecipes(VPlan &Plan)
Drop poison flags from recipes that may generate a poison value that is used after vectorization,...
static void optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
Optimize Plan based on BestVF and BestUF.
static void widenMemoryAccessesByUF(VPlan &Plan, ElementCount VF, unsigned UF, const TargetTransformInfo &TTI)
Widens memory operations by a factor of UF based on a target hook.
static bool splitCombinedExits(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop *TheLoop)
If a single exit has multiple conditions combined together, split them and create new exiting blocks.
static void combineRecipes(VPlan &Plan)
Perform instcombine-like simplifications on recipes in Plan.