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