LLVM 23.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 "VPlanVerifier.h"
24#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/TypeSwitch.h"
38#include "llvm/IR/Intrinsics.h"
39#include "llvm/IR/MDBuilder.h"
40#include "llvm/IR/Metadata.h"
45
46using namespace llvm;
47using namespace VPlanPatternMatch;
48using namespace SCEVPatternMatch;
49
51 VPlan &Plan, const TargetLibraryInfo &TLI) {
52
54 Plan.getVectorLoopRegion());
56 // Skip blocks outside region
57 if (!VPBB->getParent())
58 break;
59 VPRecipeBase *Term = VPBB->getTerminator();
60 auto EndIter = Term ? Term->getIterator() : VPBB->end();
61 // Introduce each ingredient into VPlan.
62 for (VPRecipeBase &Ingredient :
63 make_early_inc_range(make_range(VPBB->begin(), EndIter))) {
64
65 VPValue *VPV = Ingredient.getVPSingleValue();
66 if (!VPV->getUnderlyingValue())
67 continue;
68
70
71 VPRecipeBase *NewRecipe = nullptr;
72 if (auto *PhiR = dyn_cast<VPPhi>(&Ingredient)) {
73 auto *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
74 NewRecipe = new VPWidenPHIRecipe(PhiR->operands(), PhiR->getDebugLoc(),
75 Phi->getName());
76 } else if (auto *VPI = dyn_cast<VPInstruction>(&Ingredient)) {
77 assert(!isa<PHINode>(Inst) && "phis should be handled above");
78 // Create VPWidenMemoryRecipe for loads and stores.
79 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
80 NewRecipe = new VPWidenLoadRecipe(
81 *Load, Ingredient.getOperand(0), nullptr /*Mask*/,
82 false /*Consecutive*/, *VPI, Ingredient.getDebugLoc());
83 } else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
84 NewRecipe = new VPWidenStoreRecipe(
85 *Store, Ingredient.getOperand(1), Ingredient.getOperand(0),
86 nullptr /*Mask*/, false /*Consecutive*/, *VPI,
87 Ingredient.getDebugLoc());
89 NewRecipe = new VPWidenGEPRecipe(GEP, Ingredient.operands(), *VPI,
90 Ingredient.getDebugLoc());
91 } else if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
92 Intrinsic::ID VectorID = getVectorIntrinsicIDForCall(CI, &TLI);
93 if (VectorID == Intrinsic::not_intrinsic)
94 return false;
95
96 // The noalias.scope.decl intrinsic declares a noalias scope that
97 // is valid for a single iteration. Emitting it as a single-scalar
98 // replicate would incorrectly extend the scope across multiple
99 // original iterations packed into one vector iteration.
100 // FIXME: If we want to vectorize this loop, then we have to drop
101 // all the associated !alias.scope and !noalias.
102 if (VectorID == Intrinsic::experimental_noalias_scope_decl)
103 return false;
104
105 // These intrinsics are recognized by getVectorIntrinsicIDForCall
106 // but are not widenable. Emit them as replicate instead of widening.
107 if (VectorID == Intrinsic::assume ||
108 VectorID == Intrinsic::lifetime_end ||
109 VectorID == Intrinsic::lifetime_start ||
110 VectorID == Intrinsic::sideeffect ||
111 VectorID == Intrinsic::pseudoprobe) {
112 // If the operand of llvm.assume holds before vectorization, it will
113 // also hold per lane.
114 // llvm.pseudoprobe requires to be duplicated per lane for accurate
115 // sample count.
116 const bool IsSingleScalar = VectorID != Intrinsic::assume &&
117 VectorID != Intrinsic::pseudoprobe;
118 NewRecipe = new VPReplicateRecipe(CI, Ingredient.operands(),
119 /*IsSingleScalar=*/IsSingleScalar,
120 /*Mask=*/nullptr, *VPI, *VPI,
121 Ingredient.getDebugLoc());
122 } else {
123 NewRecipe = new VPWidenIntrinsicRecipe(
124 *CI, VectorID, drop_end(Ingredient.operands()), CI->getType(),
125 VPIRFlags(*CI), *VPI, CI->getDebugLoc());
126 }
127 } else if (auto *CI = dyn_cast<CastInst>(Inst)) {
128 NewRecipe = new VPWidenCastRecipe(
129 CI->getOpcode(), Ingredient.getOperand(0), CI->getType(), CI,
130 VPIRFlags(*CI), VPIRMetadata(*CI));
131 } else {
132 NewRecipe = new VPWidenRecipe(*Inst, Ingredient.operands(), *VPI,
133 *VPI, Ingredient.getDebugLoc());
134 }
135 } else {
137 "inductions must be created earlier");
138 continue;
139 }
140
141 NewRecipe->insertBefore(&Ingredient);
142 if (NewRecipe->getNumDefinedValues() == 1)
143 VPV->replaceAllUsesWith(NewRecipe->getVPSingleValue());
144 else
145 assert(NewRecipe->getNumDefinedValues() == 0 &&
146 "Only recpies with zero or one defined values expected");
147 Ingredient.eraseFromParent();
148 }
149 }
150 return true;
151}
152
153/// Helper for extra no-alias checks via known-safe recipe and SCEV.
155 const SmallPtrSetImpl<VPRecipeBase *> &ExcludeRecipes;
156 VPReplicateRecipe &GroupLeader;
158 const Loop &L;
159 VPTypeAnalysis &TypeInfo;
160
161 // Return true if \p A and \p B are known to not alias for all VFs in the
162 // plan, checked via the distance between the accesses
163 bool isNoAliasViaDistance(VPReplicateRecipe *A, VPReplicateRecipe *B) const {
164 if (A->getOpcode() != Instruction::Store ||
165 B->getOpcode() != Instruction::Store)
166 return false;
167
168 VPValue *AddrA = A->getOperand(1);
169 const SCEV *SCEVA = vputils::getSCEVExprForVPValue(AddrA, PSE, &L);
170 VPValue *AddrB = B->getOperand(1);
171 const SCEV *SCEVB = vputils::getSCEVExprForVPValue(AddrB, PSE, &L);
173 return false;
174
175 const APInt *Distance;
176 ScalarEvolution &SE = *PSE.getSE();
177 if (!match(SE.getMinusSCEV(SCEVA, SCEVB), m_scev_APInt(Distance)))
178 return false;
179
180 const DataLayout &DL = SE.getDataLayout();
181 Type *TyA = TypeInfo.inferScalarType(A->getOperand(0));
182 uint64_t SizeA = DL.getTypeStoreSize(TyA);
183 Type *TyB = TypeInfo.inferScalarType(B->getOperand(0));
184 uint64_t SizeB = DL.getTypeStoreSize(TyB);
185
186 // Use the maximum store size to ensure no overlap from either direction.
187 // Currently only handles fixed sizes, as it is only used for
188 // replicating VPReplicateRecipes.
189 uint64_t MaxStoreSize = std::max(SizeA, SizeB);
190
191 auto VFs = B->getParent()->getPlan()->vectorFactors();
193 if (MaxVF.isScalable())
194 return false;
195 return Distance->abs().uge(
196 MaxVF.multiplyCoefficientBy(MaxStoreSize).getFixedValue());
197 }
198
199public:
202 const Loop &L, VPTypeAnalysis &TypeInfo)
203 : ExcludeRecipes(ExcludeRecipes), GroupLeader(GroupLeader), PSE(PSE),
204 L(L), TypeInfo(TypeInfo) {}
205
206 /// Return true if \p R should be skipped during alias checking, either
207 /// because it's in the exclude set or because no-alias can be proven via
208 /// SCEV.
209 bool shouldSkip(VPRecipeBase &R) const {
210 auto *Store = dyn_cast<VPReplicateRecipe>(&R);
211 return ExcludeRecipes.contains(&R) ||
212 (Store && isNoAliasViaDistance(Store, &GroupLeader));
213 }
214};
215
216/// Check if a memory operation doesn't alias with memory operations using
217/// scoped noalias metadata, in blocks in the single-successor chain between \p
218/// FirstBB and \p LastBB. If \p SinkInfo is std::nullopt, only recipes that may
219/// write to memory are checked (for load hoisting). Otherwise recipes that both
220/// read and write memory are checked, and SCEV is used to prove no-alias
221/// between the group leader and other replicate recipes (for store sinking).
222static bool
224 VPBasicBlock *FirstBB, VPBasicBlock *LastBB,
225 std::optional<SinkStoreInfo> SinkInfo = {}) {
226 bool CheckReads = SinkInfo.has_value();
227 if (!MemLoc.AATags.Scope)
228 return false;
229
230 for (VPBasicBlock *VPBB :
232 for (VPRecipeBase &R : *VPBB) {
233 if (SinkInfo && SinkInfo->shouldSkip(R))
234 continue;
235
236 // Skip recipes that don't need checking.
237 if (!R.mayWriteToMemory() && !(CheckReads && R.mayReadFromMemory()))
238 continue;
239
241 if (!Loc)
242 // Conservatively assume aliasing for memory operations without
243 // location.
244 return false;
245
247 return false;
248 }
249 }
250 return true;
251}
252
253/// Collect either replicated Loads or Stores grouped by their address SCEV, in
254/// a deep-traversal of the vector loop region in \p Plan.
255template <unsigned Opcode>
258 VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L,
259 function_ref<bool(VPReplicateRecipe *)> FilterFn) {
260 static_assert(Opcode == Instruction::Load || Opcode == Instruction::Store,
261 "Only Load and Store opcodes supported");
262 constexpr bool IsLoad = (Opcode == Instruction::Load);
264 RecipesByAddress;
267 for (VPRecipeBase &R : *VPBB) {
268 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
269 if (!RepR || RepR->getOpcode() != Opcode || !FilterFn(RepR))
270 continue;
271
272 // For loads, operand 0 is address; for stores, operand 1 is address.
273 VPValue *Addr = RepR->getOperand(IsLoad ? 0 : 1);
274 const SCEV *AddrSCEV = vputils::getSCEVExprForVPValue(Addr, PSE, L);
275 if (!isa<SCEVCouldNotCompute>(AddrSCEV))
276 RecipesByAddress[AddrSCEV].push_back(RepR);
277 }
278 }
279 auto Groups = to_vector(RecipesByAddress.values());
280 VPDominatorTree VPDT(Plan);
281 for (auto &Group : Groups) {
282 // Sort mem ops by dominance order, with earliest (most dominating) first.
284 return VPDT.properlyDominates(A, B);
285 });
286 }
287 return Groups;
288}
289
290static bool sinkScalarOperands(VPlan &Plan) {
291 auto Iter = vp_depth_first_deep(Plan.getEntry());
292 bool ScalarVFOnly = Plan.hasScalarVFOnly();
293 bool Changed = false;
294
296 auto InsertIfValidSinkCandidate = [ScalarVFOnly, &WorkList](
297 VPBasicBlock *SinkTo, VPValue *Op) {
298 auto *Candidate =
299 dyn_cast_or_null<VPSingleDefRecipe>(Op->getDefiningRecipe());
300 if (!Candidate)
301 return;
302
303 // We only know how to sink VPReplicateRecipes and VPScalarIVStepsRecipes
304 // for now.
306 return;
307
308 if (Candidate->getParent() == SinkTo ||
309 vputils::cannotHoistOrSinkRecipe(*Candidate, /*Sinking=*/true))
310 return;
311
312 if (auto *RepR = dyn_cast<VPReplicateRecipe>(Candidate))
313 if (!ScalarVFOnly && RepR->isSingleScalar())
314 return;
315
316 WorkList.insert({SinkTo, Candidate});
317 };
318
319 // First, collect the operands of all recipes in replicate blocks as seeds for
320 // sinking.
322 VPBasicBlock *EntryVPBB = VPR->getEntryBasicBlock();
323 if (!VPR->isReplicator() || EntryVPBB->getSuccessors().size() != 2)
324 continue;
325 VPBasicBlock *VPBB = cast<VPBasicBlock>(EntryVPBB->getSuccessors().front());
326 if (VPBB->getSingleSuccessor() != VPR->getExitingBasicBlock())
327 continue;
328 for (auto &Recipe : *VPBB)
329 for (VPValue *Op : Recipe.operands())
330 InsertIfValidSinkCandidate(VPBB, Op);
331 }
332
333 // Try to sink each replicate or scalar IV steps recipe in the worklist.
334 for (unsigned I = 0; I != WorkList.size(); ++I) {
335 VPBasicBlock *SinkTo;
336 VPSingleDefRecipe *SinkCandidate;
337 std::tie(SinkTo, SinkCandidate) = WorkList[I];
338
339 // All recipe users of SinkCandidate must be in the same block SinkTo or all
340 // users outside of SinkTo must only use the first lane of SinkCandidate. In
341 // the latter case, we need to duplicate SinkCandidate.
342 auto UsersOutsideSinkTo =
343 make_filter_range(SinkCandidate->users(), [SinkTo](VPUser *U) {
344 return cast<VPRecipeBase>(U)->getParent() != SinkTo;
345 });
346 if (any_of(UsersOutsideSinkTo, [SinkCandidate](VPUser *U) {
347 return !U->usesFirstLaneOnly(SinkCandidate);
348 }))
349 continue;
350 bool NeedsDuplicating = !UsersOutsideSinkTo.empty();
351
352 if (NeedsDuplicating) {
353 if (ScalarVFOnly)
354 continue;
355 VPSingleDefRecipe *Clone;
356 if (auto *SinkCandidateRepR =
357 dyn_cast<VPReplicateRecipe>(SinkCandidate)) {
358 // TODO: Handle converting to uniform recipes as separate transform,
359 // then cloning should be sufficient here.
360 Instruction *I = SinkCandidate->getUnderlyingInstr();
361 Clone = new VPReplicateRecipe(I, SinkCandidate->operands(), true,
362 nullptr /*Mask*/, *SinkCandidateRepR,
363 *SinkCandidateRepR);
364 // TODO: add ".cloned" suffix to name of Clone's VPValue.
365 } else {
366 Clone = SinkCandidate->clone();
367 }
368
369 Clone->insertBefore(SinkCandidate);
370 SinkCandidate->replaceUsesWithIf(Clone, [SinkTo](VPUser &U, unsigned) {
371 return cast<VPRecipeBase>(&U)->getParent() != SinkTo;
372 });
373 }
374 SinkCandidate->moveBefore(*SinkTo, SinkTo->getFirstNonPhi());
375 for (VPValue *Op : SinkCandidate->operands())
376 InsertIfValidSinkCandidate(SinkTo, Op);
377 Changed = true;
378 }
379 return Changed;
380}
381
382/// If \p R is a region with a VPBranchOnMaskRecipe in the entry block, return
383/// the mask.
385 auto *EntryBB = dyn_cast<VPBasicBlock>(R->getEntry());
386 if (!EntryBB || EntryBB->size() != 1 ||
387 !isa<VPBranchOnMaskRecipe>(EntryBB->begin()))
388 return nullptr;
389
390 return cast<VPBranchOnMaskRecipe>(&*EntryBB->begin())->getOperand(0);
391}
392
393/// If \p R is a triangle region, return the 'then' block of the triangle.
395 auto *EntryBB = cast<VPBasicBlock>(R->getEntry());
396 if (EntryBB->getNumSuccessors() != 2)
397 return nullptr;
398
399 auto *Succ0 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[0]);
400 auto *Succ1 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[1]);
401 if (!Succ0 || !Succ1)
402 return nullptr;
403
404 if (Succ0->getNumSuccessors() + Succ1->getNumSuccessors() != 1)
405 return nullptr;
406 if (Succ0->getSingleSuccessor() == Succ1)
407 return Succ0;
408 if (Succ1->getSingleSuccessor() == Succ0)
409 return Succ1;
410 return nullptr;
411}
412
413// Merge replicate regions in their successor region, if a replicate region
414// is connected to a successor replicate region with the same predicate by a
415// single, empty VPBasicBlock.
417 SmallPtrSet<VPRegionBlock *, 4> TransformedRegions;
418
419 // Collect replicate regions followed by an empty block, followed by another
420 // replicate region with matching masks to process front. This is to avoid
421 // iterator invalidation issues while merging regions.
424 vp_depth_first_deep(Plan.getEntry()))) {
425 if (!Region1->isReplicator())
426 continue;
427 auto *MiddleBasicBlock =
428 dyn_cast_or_null<VPBasicBlock>(Region1->getSingleSuccessor());
429 if (!MiddleBasicBlock || !MiddleBasicBlock->empty())
430 continue;
431
432 auto *Region2 =
433 dyn_cast_or_null<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
434 if (!Region2 || !Region2->isReplicator())
435 continue;
436
437 VPValue *Mask1 = getPredicatedMask(Region1);
438 VPValue *Mask2 = getPredicatedMask(Region2);
439 if (!Mask1 || Mask1 != Mask2)
440 continue;
441
442 assert(Mask1 && Mask2 && "both region must have conditions");
443 WorkList.push_back(Region1);
444 }
445
446 // Move recipes from Region1 to its successor region, if both are triangles.
447 for (VPRegionBlock *Region1 : WorkList) {
448 if (TransformedRegions.contains(Region1))
449 continue;
450 auto *MiddleBasicBlock = cast<VPBasicBlock>(Region1->getSingleSuccessor());
451 auto *Region2 = cast<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
452
453 VPBasicBlock *Then1 = getPredicatedThenBlock(Region1);
454 VPBasicBlock *Then2 = getPredicatedThenBlock(Region2);
455 if (!Then1 || !Then2)
456 continue;
457
458 // Note: No fusion-preventing memory dependencies are expected in either
459 // region. Such dependencies should be rejected during earlier dependence
460 // checks, which guarantee accesses can be re-ordered for vectorization.
461 //
462 // Move recipes to the successor region.
463 for (VPRecipeBase &ToMove : make_early_inc_range(reverse(*Then1)))
464 ToMove.moveBefore(*Then2, Then2->getFirstNonPhi());
465
466 auto *Merge1 = cast<VPBasicBlock>(Then1->getSingleSuccessor());
467 auto *Merge2 = cast<VPBasicBlock>(Then2->getSingleSuccessor());
468
469 // Move VPPredInstPHIRecipes from the merge block to the successor region's
470 // merge block. Update all users inside the successor region to use the
471 // original values.
472 for (VPRecipeBase &Phi1ToMove : make_early_inc_range(reverse(*Merge1))) {
473 VPValue *PredInst1 =
474 cast<VPPredInstPHIRecipe>(&Phi1ToMove)->getOperand(0);
475 VPValue *Phi1ToMoveV = Phi1ToMove.getVPSingleValue();
476 Phi1ToMoveV->replaceUsesWithIf(PredInst1, [Then2](VPUser &U, unsigned) {
477 return cast<VPRecipeBase>(&U)->getParent() == Then2;
478 });
479
480 // Remove phi recipes that are unused after merging the regions.
481 if (Phi1ToMove.getVPSingleValue()->getNumUsers() == 0) {
482 Phi1ToMove.eraseFromParent();
483 continue;
484 }
485 Phi1ToMove.moveBefore(*Merge2, Merge2->begin());
486 }
487
488 // Remove the dead recipes in Region1's entry block.
489 for (VPRecipeBase &R :
490 make_early_inc_range(reverse(*Region1->getEntryBasicBlock())))
491 R.eraseFromParent();
492
493 // Finally, remove the first region.
494 for (VPBlockBase *Pred : make_early_inc_range(Region1->getPredecessors())) {
495 VPBlockUtils::disconnectBlocks(Pred, Region1);
496 VPBlockUtils::connectBlocks(Pred, MiddleBasicBlock);
497 }
498 VPBlockUtils::disconnectBlocks(Region1, MiddleBasicBlock);
499 TransformedRegions.insert(Region1);
500 }
501
502 return !TransformedRegions.empty();
503}
504
506 VPRegionBlock *ParentRegion,
507 VPlan &Plan) {
508 Instruction *Instr = PredRecipe->getUnderlyingInstr();
509 // Build the triangular if-then region.
510 std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
511 assert(Instr->getParent() && "Predicated instruction not in any basic block");
512 auto *BlockInMask = PredRecipe->getMask();
513 auto *MaskDef = BlockInMask->getDefiningRecipe();
514 auto *BOMRecipe = new VPBranchOnMaskRecipe(
515 BlockInMask, MaskDef ? MaskDef->getDebugLoc() : DebugLoc::getUnknown());
516 auto *Entry =
517 Plan.createVPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
518
519 // Replace predicated replicate recipe with a replicate recipe without a
520 // mask but in the replicate region.
521 auto *RecipeWithoutMask = new VPReplicateRecipe(
522 PredRecipe->getUnderlyingInstr(), drop_end(PredRecipe->operands()),
523 PredRecipe->isSingleScalar(), nullptr /*Mask*/, *PredRecipe, *PredRecipe,
524 PredRecipe->getDebugLoc());
525 auto *Pred =
526 Plan.createVPBasicBlock(Twine(RegionName) + ".if", RecipeWithoutMask);
527 auto *Exiting = Plan.createVPBasicBlock(Twine(RegionName) + ".continue");
529 Plan.createReplicateRegion(Entry, Exiting, RegionName);
530
531 // Note: first set Entry as region entry and then connect successors starting
532 // from it in order, to propagate the "parent" of each VPBasicBlock.
533 Region->setParent(ParentRegion);
534 VPBlockUtils::insertTwoBlocksAfter(Pred, Exiting, Entry);
535 VPBlockUtils::connectBlocks(Pred, Exiting);
536
537 if (PredRecipe->getNumUsers() != 0) {
538 auto *PHIRecipe = new VPPredInstPHIRecipe(RecipeWithoutMask,
539 RecipeWithoutMask->getDebugLoc());
540 Exiting->appendRecipe(PHIRecipe);
541 PredRecipe->replaceAllUsesWith(PHIRecipe);
542 }
543 PredRecipe->eraseFromParent();
544 return Region;
545}
546
547static void addReplicateRegions(VPlan &Plan) {
550 vp_depth_first_deep(Plan.getEntry()))) {
551 for (VPRecipeBase &R : *VPBB)
552 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
553 if (RepR->isPredicated())
554 WorkList.push_back(RepR);
555 }
556 }
557
558 unsigned BBNum = 0;
559 for (VPReplicateRecipe *RepR : WorkList) {
560 VPBasicBlock *CurrentBlock = RepR->getParent();
561 VPBasicBlock *SplitBlock = CurrentBlock->splitAt(RepR->getIterator());
562
563 BasicBlock *OrigBB = RepR->getUnderlyingInstr()->getParent();
564 SplitBlock->setName(
565 OrigBB->hasName() ? OrigBB->getName() + "." + Twine(BBNum++) : "");
566 // Record predicated instructions for above packing optimizations.
568 createReplicateRegion(RepR, CurrentBlock->getParent(), Plan);
570
571 VPRegionBlock *ParentRegion = Region->getParent();
572 if (ParentRegion && ParentRegion->getExiting() == CurrentBlock)
573 ParentRegion->setExiting(SplitBlock);
574 }
575}
576
580 vp_depth_first_deep(Plan.getEntry()))) {
581 // Don't fold the blocks in the skeleton of the Plan into their single
582 // predecessors for now.
583 // TODO: Remove restriction once more of the skeleton is modeled in VPlan.
584 if (!VPBB->getParent())
585 continue;
586 auto *PredVPBB =
587 dyn_cast_or_null<VPBasicBlock>(VPBB->getSinglePredecessor());
588 if (!PredVPBB || PredVPBB->getNumSuccessors() != 1 ||
589 isa<VPIRBasicBlock>(PredVPBB))
590 continue;
591 WorkList.push_back(VPBB);
592 }
593
594 for (VPBasicBlock *VPBB : WorkList) {
595 VPBasicBlock *PredVPBB = cast<VPBasicBlock>(VPBB->getSinglePredecessor());
596 for (VPRecipeBase &R : make_early_inc_range(*VPBB))
597 R.moveBefore(*PredVPBB, PredVPBB->end());
598 VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
599 auto *ParentRegion = VPBB->getParent();
600 if (ParentRegion && ParentRegion->getExiting() == VPBB)
601 ParentRegion->setExiting(PredVPBB);
602 VPBlockUtils::transferSuccessors(VPBB, PredVPBB);
603 // VPBB is now dead and will be cleaned up when the plan gets destroyed.
604 }
605 return !WorkList.empty();
606}
607
609 // Convert masked VPReplicateRecipes to if-then region blocks.
611
612 bool ShouldSimplify = true;
613 while (ShouldSimplify) {
614 ShouldSimplify = sinkScalarOperands(Plan);
615 ShouldSimplify |= mergeReplicateRegionsIntoSuccessors(Plan);
616 ShouldSimplify |= mergeBlocksIntoPredecessors(Plan);
617 }
618}
619
620/// Remove redundant casts of inductions.
621///
622/// Such redundant casts are casts of induction variables that can be ignored,
623/// because we already proved that the casted phi is equal to the uncasted phi
624/// in the vectorized loop. There is no need to vectorize the cast - the same
625/// value can be used for both the phi and casts in the vector loop.
627 for (auto &Phi : Plan.getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
629 if (!IV || IV->getTruncInst())
630 continue;
631
632 // A sequence of IR Casts has potentially been recorded for IV, which
633 // *must be bypassed* when the IV is vectorized, because the vectorized IV
634 // will produce the desired casted value. This sequence forms a def-use
635 // chain and is provided in reverse order, ending with the cast that uses
636 // the IV phi. Search for the recipe of the last cast in the chain and
637 // replace it with the original IV. Note that only the final cast is
638 // expected to have users outside the cast-chain and the dead casts left
639 // over will be cleaned up later.
640 ArrayRef<Instruction *> Casts = IV->getInductionDescriptor().getCastInsts();
641 VPValue *FindMyCast = IV;
642 for (Instruction *IRCast : reverse(Casts)) {
643 VPSingleDefRecipe *FoundUserCast = nullptr;
644 for (auto *U : FindMyCast->users()) {
645 auto *UserCast = dyn_cast<VPSingleDefRecipe>(U);
646 if (UserCast && UserCast->getUnderlyingValue() == IRCast) {
647 FoundUserCast = UserCast;
648 break;
649 }
650 }
651 // A cast recipe in the chain may have been removed by earlier DCE.
652 if (!FoundUserCast)
653 break;
654 FindMyCast = FoundUserCast;
655 }
656 if (FindMyCast != IV)
657 FindMyCast->replaceAllUsesWith(IV);
658 }
659}
660
663 Instruction::BinaryOps InductionOpcode,
664 FPMathOperator *FPBinOp, Instruction *TruncI,
665 VPIRValue *StartV, VPValue *Step, DebugLoc DL,
666 VPBuilder &Builder) {
667 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
668 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
669 VPValue *CanonicalIV = LoopRegion->getCanonicalIV();
670 VPSingleDefRecipe *BaseIV =
671 Builder.createDerivedIV(Kind, FPBinOp, StartV, CanonicalIV, Step);
672
673 // Truncate base induction if needed.
674 VPTypeAnalysis TypeInfo(Plan);
675 Type *ResultTy = TypeInfo.inferScalarType(BaseIV);
676 if (TruncI) {
677 Type *TruncTy = TruncI->getType();
678 assert(ResultTy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits() &&
679 "Not truncating.");
680 assert(ResultTy->isIntegerTy() && "Truncation requires an integer type");
681 BaseIV = Builder.createScalarCast(Instruction::Trunc, BaseIV, TruncTy, DL);
682 ResultTy = TruncTy;
683 }
684
685 // Truncate step if needed.
686 Type *StepTy = TypeInfo.inferScalarType(Step);
687 if (ResultTy != StepTy) {
688 assert(StepTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits() &&
689 "Not truncating.");
690 assert(StepTy->isIntegerTy() && "Truncation requires an integer type");
691 auto *VecPreheader =
693 VPBuilder::InsertPointGuard Guard(Builder);
694 Builder.setInsertPoint(VecPreheader);
695 Step = Builder.createScalarCast(Instruction::Trunc, Step, ResultTy, DL);
696 }
697 return Builder.createScalarIVSteps(InductionOpcode, FPBinOp, BaseIV, Step,
698 &Plan.getVF(), DL);
699}
700
702 VPlan &Plan, ScalarEvolution &SE, const TargetTransformInfo &TTI,
704 const SmallPtrSetImpl<const Value *> &ValuesToIgnore) {
705 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
706 if (!LoopRegion)
707 return;
708
710 LoopRegion->getCanonicalIV());
711 if (!WideCanIV)
712 return;
713
714 Type *CanIVTy = LoopRegion->getCanonicalIVType();
715
716 // Replace the wide canonical IV with a scalar-iv-steps over the canonical
717 // IV.
718 if (Plan.hasScalarVFOnly() || vputils::onlyFirstLaneUsed(WideCanIV)) {
719 VPBuilder Builder(WideCanIV);
720 WideCanIV->replaceAllUsesWith(createScalarIVSteps(
721 Plan, InductionDescriptor::IK_IntInduction, Instruction::Add, nullptr,
722 nullptr, Plan.getZero(CanIVTy), Plan.getConstantInt(CanIVTy, 1),
723 WideCanIV->getDebugLoc(), Builder));
724 WideCanIV->eraseFromParent();
725 return;
726 }
727
728 if (vputils::onlyScalarValuesUsed(WideCanIV))
729 return;
730
731 // If a canonical VPWidenIntOrFpInductionRecipe already produces vector lanes
732 // in the header, reuse it instead of introducing another wide induction phi.
733 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
734 for (VPRecipeBase &Phi : Header->phis()) {
735 auto *WidenIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
736 if (!WidenIV || !WidenIV->isCanonical())
737 continue;
738 // The reused wide IV feeds the header mask, whose lanes may extend past
739 // the trip count; drop flags that only hold inside the scalar loop.
740 WidenIV->dropPoisonGeneratingFlags();
741 WideCanIV->replaceAllUsesWith(WidenIV);
742 WideCanIV->eraseFromParent();
743 return;
744 }
745
746 // Introduce a new VPWidenIntOrFpInductionRecipe if profitable.
747 auto *VecTy = VectorType::get(CanIVTy, VF);
748 InstructionCost BroadcastCost = TTI.getShuffleCost(
750 InstructionCost PHICost = TTI.getCFInstrCost(Instruction::PHI, CostKind);
751 if (PHICost > BroadcastCost)
752 return;
753
754 // Bail out if the additional wide induction phi increase the expected spill
755 // cost.
756 VPRegisterUsage UnrolledBase =
757 calculateRegisterUsageForPlan(Plan, VF, TTI, ValuesToIgnore)[0];
758 for (unsigned &NumUsers : make_second_range(UnrolledBase.MaxLocalUsers))
759 NumUsers *= UF;
760 unsigned RegClass = TTI.getRegisterClassForType(/*Vector=*/true, VecTy);
761 VPRegisterUsage Projected = UnrolledBase;
762 Projected.MaxLocalUsers[RegClass] += TTI.getRegUsageForType(VecTy);
763 if (Projected.spillCost(TTI, CostKind) >
764 UnrolledBase.spillCost(TTI, CostKind))
765 return;
766
769 VPValue *StepV = Plan.getConstantInt(CanIVTy, 1);
770 auto *NewWideIV = new VPWidenIntOrFpInductionRecipe(
771 /*IV=*/nullptr, Plan.getZero(CanIVTy), StepV, &Plan.getVF(), ID,
772 WideCanIV->getNoWrapFlags(), WideCanIV->getDebugLoc());
773 NewWideIV->insertBefore(&*Header->getFirstNonPhi());
774 WideCanIV->replaceAllUsesWith(NewWideIV);
775 WideCanIV->eraseFromParent();
776}
777
778/// Returns true if \p R is dead and can be removed.
779static bool isDeadRecipe(VPRecipeBase &R) {
780 // Do remove conditional assume instructions as their conditions may be
781 // flattened.
782 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
783 bool IsConditionalAssume = RepR && RepR->isPredicated() &&
785 if (IsConditionalAssume)
786 return true;
787
788 if (R.mayHaveSideEffects())
789 return false;
790
791 // Recipe is dead if no user keeps the recipe alive.
792 return all_of(R.definedValues(),
793 [](VPValue *V) { return V->getNumUsers() == 0; });
794}
795
798 Plan.getEntry());
800 // The recipes in the block are processed in reverse order, to catch chains
801 // of dead recipes.
802 for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB))) {
803 if (isDeadRecipe(R)) {
804 R.eraseFromParent();
805 continue;
806 }
807
808 // Check if R is a dead VPPhi <-> update cycle and remove it.
809 VPValue *Start, *Incoming;
810 if (!match(&R, m_VPPhi(m_VPValue(Start), m_VPValue(Incoming))))
811 continue;
812 auto *PhiR = cast<VPPhi>(&R);
813 VPUser *PhiUser = PhiR->getSingleUser();
814 if (!PhiUser)
815 continue;
816 if (PhiUser != Incoming->getDefiningRecipe() ||
817 Incoming->getNumUsers() != 1)
818 continue;
819 PhiR->replaceAllUsesWith(Start);
820 PhiR->eraseFromParent();
821 Incoming->getDefiningRecipe()->eraseFromParent();
822 }
823 }
824}
825
828 for (unsigned I = 0; I != Users.size(); ++I) {
830 for (VPValue *V : Cur->definedValues())
831 Users.insert_range(V->users());
832 }
833 return Users.takeVector();
834}
835
836/// Scalarize a VPWidenPointerInductionRecipe by replacing it with a PtrAdd
837/// (IndStart, ScalarIVSteps (0, Step)). This is used when the recipe only
838/// generates scalar values.
839static VPValue *
841 VPlan &Plan, VPBuilder &Builder) {
843 VPIRValue *StartV = Plan.getZero(ID.getStep()->getType());
844 VPValue *StepV = PtrIV->getOperand(1);
846 Plan, InductionDescriptor::IK_IntInduction, Instruction::Add, nullptr,
847 nullptr, StartV, StepV, PtrIV->getDebugLoc(), Builder);
848
849 return Builder.createPtrAdd(PtrIV->getStartValue(), Steps,
850 PtrIV->getDebugLoc(), "next.gep");
851}
852
853/// Legalize VPWidenPointerInductionRecipe, by replacing it with a PtrAdd
854/// (IndStart, ScalarIVSteps (0, Step)) if only its scalar values are used, as
855/// VPWidenPointerInductionRecipe will generate vectors only. If some users
856/// require vectors while other require scalars, the scalar uses need to extract
857/// the scalars from the generated vectors (Note that this is different to how
858/// int/fp inductions are handled). Legalize extract-from-ends using uniform
859/// VPReplicateRecipe of wide inductions to use regular VPReplicateRecipe, so
860/// the correct end value is available. Also optimize
861/// VPWidenIntOrFpInductionRecipe, if any of its users needs scalar values, by
862/// providing them scalar steps built on the canonical scalar IV and update the
863/// original IV's users. This is an optional optimization to reduce the needs of
864/// vector extracts.
867 bool HasOnlyVectorVFs = !Plan.hasScalarVFOnly();
868 VPBuilder Builder(HeaderVPBB, HeaderVPBB->getFirstNonPhi());
869 for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
870 auto *PhiR = dyn_cast<VPWidenInductionRecipe>(&Phi);
871 if (!PhiR)
872 continue;
873
874 // Try to narrow wide and replicating recipes to uniform recipes, based on
875 // VPlan analysis.
876 // TODO: Apply to all recipes in the future, to replace legacy uniformity
877 // analysis.
878 auto Users = collectUsersRecursively(PhiR);
879 for (VPUser *U : reverse(Users)) {
880 auto *Def = dyn_cast<VPRecipeWithIRFlags>(U);
881 auto *RepR = dyn_cast<VPReplicateRecipe>(U);
882 // Skip recipes that shouldn't be narrowed.
883 if (!Def || !isa<VPReplicateRecipe, VPWidenRecipe>(Def) ||
884 Def->getNumUsers() == 0 || !Def->getUnderlyingValue() ||
885 (RepR && (RepR->isSingleScalar() || RepR->isPredicated())))
886 continue;
887
888 // Skip recipes that may have other lanes than their first used.
890 continue;
891
892 // TODO: Support scalarizing ExtractValue.
893 if (match(Def,
895 continue;
896
897 auto *Clone = new VPReplicateRecipe(Def->getUnderlyingInstr(),
898 Def->operands(), /*IsUniform*/ true,
899 /*Mask*/ nullptr, /*Flags*/ *Def);
900 Clone->insertAfter(Def);
901 Def->replaceAllUsesWith(Clone);
902 }
903
904 // Replace wide pointer inductions which have only their scalars used by
905 // PtrAdd(IndStart, ScalarIVSteps (0, Step)).
906 if (auto *PtrIV = dyn_cast<VPWidenPointerInductionRecipe>(&Phi)) {
907 if (!Plan.hasScalarVFOnly() &&
908 !PtrIV->onlyScalarsGenerated(Plan.hasScalableVF()))
909 continue;
910
911 VPValue *PtrAdd = scalarizeVPWidenPointerInduction(PtrIV, Plan, Builder);
912 PtrIV->replaceAllUsesWith(PtrAdd);
913 continue;
914 }
915
916 // Replace widened induction with scalar steps for users that only use
917 // scalars.
918 auto *WideIV = cast<VPWidenIntOrFpInductionRecipe>(&Phi);
919 if (HasOnlyVectorVFs && none_of(WideIV->users(), [WideIV](VPUser *U) {
920 return U->usesScalars(WideIV);
921 }))
922 continue;
923
924 const InductionDescriptor &ID = WideIV->getInductionDescriptor();
926 Plan, ID.getKind(), ID.getInductionOpcode(),
927 dyn_cast_or_null<FPMathOperator>(ID.getInductionBinOp()),
928 WideIV->getTruncInst(), WideIV->getStartValue(), WideIV->getStepValue(),
929 WideIV->getDebugLoc(), Builder);
930
931 // Update scalar users of IV to use Step instead.
932 if (!HasOnlyVectorVFs) {
933 assert(!Plan.hasScalableVF() &&
934 "plans containing a scalar VF cannot also include scalable VFs");
935 WideIV->replaceAllUsesWith(Steps);
936 } else {
937 bool HasScalableVF = Plan.hasScalableVF();
938 WideIV->replaceUsesWithIf(Steps,
939 [WideIV, HasScalableVF](VPUser &U, unsigned) {
940 if (HasScalableVF)
941 return U.usesFirstLaneOnly(WideIV);
942 return U.usesScalars(WideIV);
943 });
944 }
945 }
946}
947
948/// Check if \p VPV is an untruncated wide induction, either before or after the
949/// increment. If so return the header IV (before the increment), otherwise
950/// return null.
953 auto *WideIV = dyn_cast<VPWidenInductionRecipe>(VPV);
954 if (WideIV) {
955 // VPV itself is a wide induction, separately compute the end value for exit
956 // users if it is not a truncated IV.
957 auto *IntOrFpIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(WideIV);
958 return (IntOrFpIV && IntOrFpIV->getTruncInst()) ? nullptr : WideIV;
959 }
960
961 // Check if VPV is an optimizable induction increment.
962 VPRecipeBase *Def = VPV->getDefiningRecipe();
963 if (!Def || Def->getNumOperands() != 2)
964 return nullptr;
965 WideIV = dyn_cast<VPWidenInductionRecipe>(Def->getOperand(0));
966 if (!WideIV)
967 WideIV = dyn_cast<VPWidenInductionRecipe>(Def->getOperand(1));
968 if (!WideIV)
969 return nullptr;
970
971 auto IsWideIVInc = [&]() {
972 auto &ID = WideIV->getInductionDescriptor();
973
974 // Check if VPV increments the induction by the induction step.
975 VPValue *IVStep = WideIV->getStepValue();
976 switch (ID.getInductionOpcode()) {
977 case Instruction::Add:
978 return match(VPV, m_c_Add(m_Specific(WideIV), m_Specific(IVStep)));
979 case Instruction::FAdd:
980 return match(VPV, m_c_FAdd(m_Specific(WideIV), m_Specific(IVStep)));
981 case Instruction::FSub:
982 return match(VPV, m_Binary<Instruction::FSub>(m_Specific(WideIV),
983 m_Specific(IVStep)));
984 case Instruction::Sub: {
985 // IVStep will be the negated step of the subtraction. Check if Step == -1
986 // * IVStep.
987 VPValue *Step;
988 if (!match(VPV, m_Sub(m_VPValue(), m_VPValue(Step))))
989 return false;
990 const SCEV *IVStepSCEV = vputils::getSCEVExprForVPValue(IVStep, PSE);
991 const SCEV *StepSCEV = vputils::getSCEVExprForVPValue(Step, PSE);
992 ScalarEvolution &SE = *PSE.getSE();
993 return !isa<SCEVCouldNotCompute>(IVStepSCEV) &&
994 !isa<SCEVCouldNotCompute>(StepSCEV) &&
995 IVStepSCEV == SE.getNegativeSCEV(StepSCEV);
996 }
997 default:
998 return ID.getKind() == InductionDescriptor::IK_PtrInduction &&
999 match(VPV, m_GetElementPtr(m_Specific(WideIV),
1000 m_Specific(WideIV->getStepValue())));
1001 }
1002 llvm_unreachable("should have been covered by switch above");
1003 };
1004 return IsWideIVInc() ? WideIV : nullptr;
1005}
1006
1007/// Attempts to optimize the induction variable exit values for users in the
1008/// early exit block.
1010 VPTypeAnalysis &TypeInfo,
1011 VPValue *Op,
1013 VPValue *Incoming, *Mask;
1015 m_VPValue(Incoming))))
1016 return nullptr;
1017
1018 auto *WideIV = getOptimizableIVOf(Incoming, PSE);
1019 if (!WideIV)
1020 return nullptr;
1021
1022 auto *WideIntOrFp = dyn_cast<VPWidenIntOrFpInductionRecipe>(WideIV);
1023 if (WideIntOrFp && WideIntOrFp->getTruncInst())
1024 return nullptr;
1025
1026 // Calculate the final index.
1027 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1028 auto *CanonicalIV = LoopRegion->getCanonicalIV();
1029 Type *CanonicalIVType = LoopRegion->getCanonicalIVType();
1030 auto *ExtractR = cast<VPInstruction>(Op);
1031 VPBuilder B(ExtractR);
1032
1033 DebugLoc DL = ExtractR->getDebugLoc();
1034 VPValue *FirstActiveLane = B.createFirstActiveLane(Mask, DL);
1035 Type *FirstActiveLaneType = TypeInfo.inferScalarType(FirstActiveLane);
1036 FirstActiveLane = B.createScalarZExtOrTrunc(FirstActiveLane, CanonicalIVType,
1037 FirstActiveLaneType, DL);
1038 VPValue *EndValue = B.createAdd(CanonicalIV, FirstActiveLane, DL);
1039
1040 // `getOptimizableIVOf()` always returns the pre-incremented IV, so if it
1041 // changed it means the exit is using the incremented value, so we need to
1042 // add the step.
1043 if (Incoming != WideIV) {
1044 VPValue *One = Plan.getConstantInt(CanonicalIVType, 1);
1045 EndValue = B.createAdd(EndValue, One, DL);
1046 }
1047
1048 if (!WideIntOrFp || !WideIntOrFp->isCanonical()) {
1049 const InductionDescriptor &ID = WideIV->getInductionDescriptor();
1050 VPIRValue *Start = WideIV->getStartValue();
1051 VPValue *Step = WideIV->getStepValue();
1052 EndValue = B.createDerivedIV(
1053 ID.getKind(), dyn_cast_or_null<FPMathOperator>(ID.getInductionBinOp()),
1054 Start, EndValue, Step);
1055 }
1056
1057 return EndValue;
1058}
1059
1060/// Compute the end value for \p WideIV, unless it is truncated. Creates a
1061/// VPDerivedIVRecipe for non-canonical inductions.
1063 VPBuilder &VectorPHBuilder,
1064 VPTypeAnalysis &TypeInfo,
1065 VPValue *VectorTC) {
1066 auto *WideIntOrFp = dyn_cast<VPWidenIntOrFpInductionRecipe>(WideIV);
1067 // Truncated wide inductions resume from the last lane of their vector value
1068 // in the last vector iteration which is handled elsewhere.
1069 if (WideIntOrFp && WideIntOrFp->getTruncInst())
1070 return nullptr;
1071
1072 VPIRValue *Start = WideIV->getStartValue();
1073 VPValue *Step = WideIV->getStepValue();
1075 VPValue *EndValue = VectorTC;
1076 if (!WideIntOrFp || !WideIntOrFp->isCanonical()) {
1077 EndValue = VectorPHBuilder.createDerivedIV(
1078 ID.getKind(), dyn_cast_or_null<FPMathOperator>(ID.getInductionBinOp()),
1079 Start, VectorTC, Step);
1080 }
1081
1082 // EndValue is derived from the vector trip count (which has the same type as
1083 // the widest induction) and thus may be wider than the induction here.
1084 Type *ScalarTypeOfWideIV = TypeInfo.inferScalarType(WideIV);
1085 if (ScalarTypeOfWideIV != TypeInfo.inferScalarType(EndValue)) {
1086 EndValue = VectorPHBuilder.createScalarCast(Instruction::Trunc, EndValue,
1087 ScalarTypeOfWideIV,
1088 WideIV->getDebugLoc());
1089 }
1090
1091 return EndValue;
1092}
1093
1094/// Attempts to optimize the induction variable exit values for users in the
1095/// exit block coming from the latch in the original scalar loop.
1097 VPlan &Plan, VPTypeAnalysis &TypeInfo, VPValue *Op,
1099 VPValue *Incoming;
1101 return nullptr;
1102
1103 VPWidenInductionRecipe *WideIV = getOptimizableIVOf(Incoming, PSE);
1104 if (!WideIV)
1105 return nullptr;
1106
1107 VPValue *EndValue = EndValues.lookup(WideIV);
1108 assert(EndValue && "Must have computed the end value up front");
1109
1110 // `getOptimizableIVOf()` always returns the pre-incremented IV, so if it
1111 // changed it means the exit is using the incremented value, so we don't
1112 // need to subtract the step.
1113 if (Incoming != WideIV)
1114 return EndValue;
1115
1116 // Otherwise, subtract the step from the EndValue.
1117 auto *ExtractR = cast<VPInstruction>(Op);
1118 VPBuilder B(ExtractR);
1119 VPValue *Step = WideIV->getStepValue();
1120 Type *ScalarTy = TypeInfo.inferScalarType(WideIV);
1121 if (ScalarTy->isIntegerTy())
1122 return B.createSub(EndValue, Step, DebugLoc::getUnknown(), "ind.escape");
1123 if (ScalarTy->isPointerTy()) {
1124 Type *StepTy = TypeInfo.inferScalarType(Step);
1125 auto *Zero = Plan.getZero(StepTy);
1126 return B.createPtrAdd(EndValue, B.createSub(Zero, Step),
1127 DebugLoc::getUnknown(), "ind.escape");
1128 }
1129 if (ScalarTy->isFloatingPointTy()) {
1130 const auto &ID = WideIV->getInductionDescriptor();
1131 return B.createNaryOp(
1132 ID.getInductionBinOp()->getOpcode() == Instruction::FAdd
1133 ? Instruction::FSub
1134 : Instruction::FAdd,
1135 {EndValue, Step}, {ID.getInductionBinOp()->getFastMathFlags()});
1136 }
1137 llvm_unreachable("all possible induction types must be handled");
1138 return nullptr;
1139}
1140
1142 VPlan &Plan, PredicatedScalarEvolution &PSE, bool FoldTail) {
1143 // Compute end values for all inductions.
1144 VPTypeAnalysis TypeInfo(Plan);
1145 VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
1146 auto *VectorPH = cast<VPBasicBlock>(VectorRegion->getSinglePredecessor());
1147 VPBuilder VectorPHBuilder(VectorPH, VectorPH->begin());
1149 VPValue *ResumeTC =
1150 FoldTail ? Plan.getTripCount() : &Plan.getVectorTripCount();
1151 for (auto &Phi : VectorRegion->getEntryBasicBlock()->phis()) {
1152 auto *WideIV = dyn_cast<VPWidenInductionRecipe>(&Phi);
1153 if (!WideIV)
1154 continue;
1156 WideIV, VectorPHBuilder, TypeInfo, ResumeTC))
1157 EndValues[WideIV] = EndValue;
1158 }
1159
1160 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
1161 for (VPRecipeBase &R : make_early_inc_range(*MiddleVPBB)) {
1162 VPValue *Op;
1163 if (!match(&R, m_ExitingIVValue(m_VPValue(Op))))
1164 continue;
1165 auto *WideIV = cast<VPWidenInductionRecipe>(Op);
1166 if (VPValue *EndValue = EndValues.lookup(WideIV)) {
1167 R.getVPSingleValue()->replaceAllUsesWith(EndValue);
1168 R.eraseFromParent();
1169 }
1170 }
1171
1172 // Then, optimize exit block users.
1173 for (VPIRBasicBlock *ExitVPBB : Plan.getExitBlocks()) {
1174 for (VPRecipeBase &R : ExitVPBB->phis()) {
1175 auto *ExitIRI = cast<VPIRPhi>(&R);
1176
1177 for (auto [Idx, PredVPBB] : enumerate(ExitVPBB->getPredecessors())) {
1178 VPValue *Escape = nullptr;
1179 if (PredVPBB == MiddleVPBB)
1181 Plan, TypeInfo, ExitIRI->getOperand(Idx), EndValues, PSE);
1182 else
1184 Plan, TypeInfo, ExitIRI->getOperand(Idx), PSE);
1185 if (Escape)
1186 ExitIRI->setOperand(Idx, Escape);
1187 }
1188 }
1189 }
1190}
1191
1192/// Remove redundant EpxandSCEVRecipes in \p Plan's entry block by replacing
1193/// them with already existing recipes expanding the same SCEV expression.
1196
1197 for (VPRecipeBase &R :
1199 auto *ExpR = dyn_cast<VPExpandSCEVRecipe>(&R);
1200 if (!ExpR)
1201 continue;
1202
1203 const auto &[V, Inserted] = SCEV2VPV.try_emplace(ExpR->getSCEV(), ExpR);
1204 if (Inserted)
1205 continue;
1206 ExpR->replaceAllUsesWith(V->second);
1207 ExpR->eraseFromParent();
1208 }
1209}
1210
1212 SmallVector<VPValue *> WorkList;
1214 WorkList.push_back(V);
1215
1216 while (!WorkList.empty()) {
1217 VPValue *Cur = WorkList.pop_back_val();
1218 if (!Seen.insert(Cur).second)
1219 continue;
1220 VPRecipeBase *R = Cur->getDefiningRecipe();
1221 if (!R)
1222 continue;
1223 if (!isDeadRecipe(*R))
1224 continue;
1225 append_range(WorkList, R->operands());
1226 R->eraseFromParent();
1227 }
1228}
1229
1230/// Get any instruction opcode or intrinsic ID data embedded in recipe \p R.
1231/// Returns an optional pair, where the first element indicates whether it is
1232/// an intrinsic ID.
1233static std::optional<std::pair<bool, unsigned>>
1235 return TypeSwitch<const VPSingleDefRecipe *,
1236 std::optional<std::pair<bool, unsigned>>>(R)
1239 [](auto *I) { return std::make_pair(false, I->getOpcode()); })
1240 .Case([](const VPWidenIntrinsicRecipe *I) {
1241 return std::make_pair(true, I->getVectorIntrinsicID());
1242 })
1243 .Case<VPVectorPointerRecipe, VPPredInstPHIRecipe, VPScalarIVStepsRecipe>(
1244 [](auto *I) {
1245 // For recipes that do not directly map to LLVM IR instructions,
1246 // assign opcodes after the last VPInstruction opcode (which is also
1247 // after the last IR Instruction opcode), based on the VPRecipeID.
1248 return std::make_pair(false, VPInstruction::OpsEnd + 1 +
1249 I->getVPRecipeID());
1250 })
1251 .Default([](auto *) { return std::nullopt; });
1252}
1253
1254/// Try to fold \p R using InstSimplifyFolder. Will succeed and return a
1255/// non-nullptr VPValue for a handled opcode or intrinsic ID if corresponding \p
1256/// Operands are foldable live-ins.
1258 ArrayRef<VPValue *> Operands,
1259 const DataLayout &DL,
1260 VPTypeAnalysis &TypeInfo) {
1261 auto OpcodeOrIID = getOpcodeOrIntrinsicID(&R);
1262 if (!OpcodeOrIID)
1263 return nullptr;
1264
1266 for (VPValue *Op : Operands) {
1267 if (!match(Op, m_LiveIn()))
1268 return nullptr;
1269 Value *V = Op->getUnderlyingValue();
1270 if (!V)
1271 return nullptr;
1272 Ops.push_back(V);
1273 }
1274
1275 auto FoldToIRValue = [&]() -> Value * {
1276 InstSimplifyFolder Folder(DL);
1277 if (OpcodeOrIID->first) {
1278 if (R.getNumOperands() != 2)
1279 return nullptr;
1280 unsigned ID = OpcodeOrIID->second;
1281 return Folder.FoldBinaryIntrinsic(ID, Ops[0], Ops[1],
1282 TypeInfo.inferScalarType(&R));
1283 }
1284 unsigned Opcode = OpcodeOrIID->second;
1285 if (Instruction::isBinaryOp(Opcode))
1286 return Folder.FoldBinOp(static_cast<Instruction::BinaryOps>(Opcode),
1287 Ops[0], Ops[1]);
1288 if (Instruction::isCast(Opcode))
1289 return Folder.FoldCast(static_cast<Instruction::CastOps>(Opcode), Ops[0],
1290 TypeInfo.inferScalarType(R.getVPSingleValue()));
1291 switch (Opcode) {
1293 return Folder.FoldSelect(Ops[0], Ops[1],
1295 case VPInstruction::Not:
1296 return Folder.FoldBinOp(Instruction::BinaryOps::Xor, Ops[0],
1298 case Instruction::Select:
1299 return Folder.FoldSelect(Ops[0], Ops[1], Ops[2]);
1300 case Instruction::ICmp:
1301 case Instruction::FCmp:
1302 return Folder.FoldCmp(cast<VPRecipeWithIRFlags>(R).getPredicate(), Ops[0],
1303 Ops[1]);
1304 case Instruction::GetElementPtr: {
1305 auto &RFlags = cast<VPRecipeWithIRFlags>(R);
1306 auto *GEP = cast<GetElementPtrInst>(RFlags.getUnderlyingInstr());
1307 return Folder.FoldGEP(GEP->getSourceElementType(), Ops[0],
1308 drop_begin(Ops), RFlags.getGEPNoWrapFlags());
1309 }
1312 return Folder.FoldGEP(IntegerType::getInt8Ty(TypeInfo.getContext()),
1313 Ops[0], Ops[1],
1314 cast<VPRecipeWithIRFlags>(R).getGEPNoWrapFlags());
1315 // An extract of a live-in is an extract of a broadcast, so return the
1316 // broadcasted element.
1317 case Instruction::ExtractElement:
1318 assert(!Ops[0]->getType()->isVectorTy() && "Live-ins should be scalar");
1319 return Ops[0];
1320 }
1321 return nullptr;
1322 };
1323
1324 if (Value *V = FoldToIRValue())
1325 return R.getParent()->getPlan()->getOrAddLiveIn(V);
1326 return nullptr;
1327}
1328
1329/// Try to simplify VPSingleDefRecipe \p Def.
1331 VPlan *Plan = Def->getParent()->getPlan();
1332
1333 // Simplification of live-in IR values for SingleDef recipes using
1334 // InstSimplifyFolder.
1335 const DataLayout &DL = Plan->getDataLayout();
1336 if (VPValue *V = tryToFoldLiveIns(*Def, Def->operands(), DL, TypeInfo))
1337 return Def->replaceAllUsesWith(V);
1338
1339 // Fold PredPHI LiveIn -> LiveIn.
1340 if (auto *PredPHI = dyn_cast<VPPredInstPHIRecipe>(Def)) {
1341 VPValue *Op = PredPHI->getOperand(0);
1342 if (isa<VPIRValue>(Op))
1343 PredPHI->replaceAllUsesWith(Op);
1344 }
1345
1346 VPBuilder Builder(Def);
1347
1348 // Avoid replacing VPInstructions with underlying values with new
1349 // VPInstructions, as we would fail to create widen/replicate recpes from the
1350 // new VPInstructions without an underlying value, and miss out on some
1351 // transformations that only apply to widened/replicated recipes later, by
1352 // doing so.
1353 // TODO: We should also not replace non-VPInstructions like VPWidenRecipe with
1354 // VPInstructions without underlying values, as those will get skipped during
1355 // cost computation.
1356 bool CanCreateNewRecipe =
1357 !isa<VPInstruction>(Def) || !Def->getUnderlyingValue();
1358
1359 VPValue *A;
1360 if (match(Def, m_Trunc(m_ZExtOrSExt(m_VPValue(A))))) {
1361 Type *TruncTy = TypeInfo.inferScalarType(Def);
1362 Type *ATy = TypeInfo.inferScalarType(A);
1363 if (TruncTy == ATy) {
1364 Def->replaceAllUsesWith(A);
1365 } else {
1366 // Don't replace a non-widened cast recipe with a widened cast.
1367 if (!isa<VPWidenCastRecipe>(Def))
1368 return;
1369 if (ATy->getScalarSizeInBits() < TruncTy->getScalarSizeInBits()) {
1370
1371 unsigned ExtOpcode = match(Def->getOperand(0), m_SExt(m_VPValue()))
1372 ? Instruction::SExt
1373 : Instruction::ZExt;
1374 auto *Ext = Builder.createWidenCast(Instruction::CastOps(ExtOpcode), A,
1375 TruncTy);
1376 if (auto *UnderlyingExt = Def->getOperand(0)->getUnderlyingValue()) {
1377 // UnderlyingExt has distinct return type, used to retain legacy cost.
1378 Ext->setUnderlyingValue(UnderlyingExt);
1379 }
1380 Def->replaceAllUsesWith(Ext);
1381 } else if (ATy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits()) {
1382 auto *Trunc = Builder.createWidenCast(Instruction::Trunc, A, TruncTy);
1383 Def->replaceAllUsesWith(Trunc);
1384 }
1385 }
1386#ifndef NDEBUG
1387 // Verify that the cached type info is for both A and its users is still
1388 // accurate by comparing it to freshly computed types.
1389 VPTypeAnalysis TypeInfo2(*Plan);
1390 assert(TypeInfo.inferScalarType(A) == TypeInfo2.inferScalarType(A));
1391 for (VPUser *U : A->users()) {
1392 auto *R = cast<VPRecipeBase>(U);
1393 for (VPValue *VPV : R->definedValues())
1394 assert(TypeInfo.inferScalarType(VPV) == TypeInfo2.inferScalarType(VPV));
1395 }
1396#endif
1397 }
1398
1399 // Simplify (X && Y) | (X && !Y) -> X.
1400 // TODO: Split up into simpler, modular combines: (X && Y) | (X && Z) into X
1401 // && (Y | Z) and (X | !X) into true. This requires queuing newly created
1402 // recipes to be visited during simplification.
1403 VPValue *X, *Y, *Z;
1404 if (match(Def,
1407 Def->replaceAllUsesWith(X);
1408 Def->eraseFromParent();
1409 return;
1410 }
1411
1412 // x | AllOnes -> AllOnes
1413 if (match(Def, m_c_BinaryOr(m_VPValue(X), m_AllOnes())))
1414 return Def->replaceAllUsesWith(
1415 Plan->getAllOnesValue(TypeInfo.inferScalarType(Def)));
1416
1417 // x | 0 -> x
1418 if (match(Def, m_c_BinaryOr(m_VPValue(X), m_ZeroInt())))
1419 return Def->replaceAllUsesWith(X);
1420
1421 // x | !x -> AllOnes
1423 return Def->replaceAllUsesWith(
1424 Plan->getAllOnesValue(TypeInfo.inferScalarType(Def)));
1425
1426 // x & 0 -> 0
1427 if (match(Def, m_c_BinaryAnd(m_VPValue(X), m_ZeroInt())))
1428 return Def->replaceAllUsesWith(
1429 Plan->getZero(TypeInfo.inferScalarType(Def)));
1430
1431 // x & AllOnes -> x
1432 if (match(Def, m_c_BinaryAnd(m_VPValue(X), m_AllOnes())))
1433 return Def->replaceAllUsesWith(X);
1434
1435 // x && false -> false
1436 if (match(Def, m_c_LogicalAnd(m_VPValue(X), m_False())))
1437 return Def->replaceAllUsesWith(Plan->getFalse());
1438
1439 // x && true -> x
1440 if (match(Def, m_c_LogicalAnd(m_VPValue(X), m_True())))
1441 return Def->replaceAllUsesWith(X);
1442
1443 // (x && y) | (x && z) -> x && (y | z)
1444 if (CanCreateNewRecipe &&
1447 // Simplify only if one of the operands has one use to avoid creating an
1448 // extra recipe.
1449 (!Def->getOperand(0)->hasMoreThanOneUniqueUser() ||
1450 !Def->getOperand(1)->hasMoreThanOneUniqueUser()))
1451 return Def->replaceAllUsesWith(
1452 Builder.createLogicalAnd(X, Builder.createOr(Y, Z)));
1453
1454 // x && (x && y) -> x && y
1455 if (match(Def, m_LogicalAnd(m_VPValue(X),
1457 return Def->replaceAllUsesWith(Def->getOperand(1));
1458
1459 // x && (y && x) -> x && y
1460 if (match(Def, m_LogicalAnd(m_VPValue(X),
1462 return Def->replaceAllUsesWith(Builder.createLogicalAnd(X, Y));
1463
1464 // x && !x -> 0
1466 return Def->replaceAllUsesWith(Plan->getFalse());
1467
1468 if (match(Def, m_Select(m_VPValue(), m_VPValue(X), m_Deferred(X))))
1469 return Def->replaceAllUsesWith(X);
1470
1471 // select c, false, true -> not c
1472 VPValue *C;
1473 if (CanCreateNewRecipe &&
1474 match(Def, m_Select(m_VPValue(C), m_False(), m_True())))
1475 return Def->replaceAllUsesWith(Builder.createNot(C));
1476
1477 // select !c, x, y -> select c, y, x
1478 if (match(Def, m_Select(m_Not(m_VPValue(C)), m_VPValue(X), m_VPValue(Y)))) {
1479 Def->setOperand(0, C);
1480 Def->setOperand(1, Y);
1481 Def->setOperand(2, X);
1482 return;
1483 }
1484
1485 // select x, (i1 y | z), y -> y | (x && z)
1486 if (CanCreateNewRecipe &&
1487 match(Def, m_Select(m_VPValue(X),
1489 m_Deferred(Y))) &&
1490 TypeInfo.inferScalarType(Y)->isIntegerTy(1))
1491 return Def->replaceAllUsesWith(
1492 Builder.createOr(Y, Builder.createLogicalAnd(X, Z)));
1493
1494 if (match(Def, m_c_Add(m_VPValue(A), m_ZeroInt())))
1495 return Def->replaceAllUsesWith(A);
1496
1497 if (match(Def, m_c_Mul(m_VPValue(A), m_One())))
1498 return Def->replaceAllUsesWith(A);
1499
1500 if (match(Def, m_c_Mul(m_VPValue(A), m_ZeroInt())))
1501 return Def->replaceAllUsesWith(
1502 Plan->getZero(TypeInfo.inferScalarType(Def)));
1503
1504 if (CanCreateNewRecipe && match(Def, m_c_Mul(m_VPValue(A), m_AllOnes()))) {
1505 // Preserve nsw from the Mul on the new Sub.
1507 false, cast<VPRecipeWithIRFlags>(Def)->hasNoSignedWrap()};
1508 return Def->replaceAllUsesWith(
1509 Builder.createSub(Plan->getZero(TypeInfo.inferScalarType(A)), A,
1510 Def->getDebugLoc(), "", NW));
1511 }
1512
1513 if (CanCreateNewRecipe &&
1515 // Preserve nsw from the Add and the Sub, if it's present on both, on the
1516 // new Sub.
1518 false,
1519 cast<VPRecipeWithIRFlags>(Def)->hasNoSignedWrap() &&
1520 cast<VPRecipeWithIRFlags>(Def->getOperand(Def->getOperand(0) == X))
1521 ->hasNoSignedWrap()};
1522 return Def->replaceAllUsesWith(
1523 Builder.createSub(X, Y, Def->getDebugLoc(), "", NW));
1524 }
1525
1526 const APInt *APC;
1527 if (CanCreateNewRecipe && match(Def, m_c_Mul(m_VPValue(A), m_APInt(APC))) &&
1528 APC->isPowerOf2())
1529 return Def->replaceAllUsesWith(Builder.createNaryOp(
1530 Instruction::Shl,
1531 {A, Plan->getConstantInt(APC->getBitWidth(), APC->exactLogBase2())},
1532 *cast<VPRecipeWithIRFlags>(Def), Def->getDebugLoc()));
1533
1534 if (CanCreateNewRecipe && match(Def, m_UDiv(m_VPValue(A), m_APInt(APC))) &&
1535 APC->isPowerOf2())
1536 return Def->replaceAllUsesWith(Builder.createNaryOp(
1537 Instruction::LShr,
1538 {A, Plan->getConstantInt(APC->getBitWidth(), APC->exactLogBase2())},
1539 *cast<VPRecipeWithIRFlags>(Def), Def->getDebugLoc()));
1540
1541 if (match(Def, m_Not(m_VPValue(A)))) {
1542 if (match(A, m_Not(m_VPValue(A))))
1543 return Def->replaceAllUsesWith(A);
1544
1545 // Try to fold Not into compares by adjusting the predicate in-place.
1546 CmpPredicate Pred;
1547 if (match(A, m_Cmp(Pred, m_VPValue(), m_VPValue()))) {
1548 auto *Cmp = cast<VPRecipeWithIRFlags>(A);
1549 if (all_of(Cmp->users(),
1551 m_Not(m_Specific(Cmp)),
1552 m_Select(m_Specific(Cmp), m_VPValue(), m_VPValue()))))) {
1553 Cmp->setPredicate(CmpInst::getInversePredicate(Pred));
1554 for (VPUser *U : to_vector(Cmp->users())) {
1555 auto *R = cast<VPSingleDefRecipe>(U);
1556 if (match(R, m_Select(m_Specific(Cmp), m_VPValue(X), m_VPValue(Y)))) {
1557 // select (cmp pred), x, y -> select (cmp inv_pred), y, x
1558 R->setOperand(1, Y);
1559 R->setOperand(2, X);
1560 } else {
1561 // not (cmp pred) -> cmp inv_pred
1562 assert(match(R, m_Not(m_Specific(Cmp))) && "Unexpected user");
1563 R->replaceAllUsesWith(Cmp);
1564 }
1565 }
1566 // If Cmp doesn't have a debug location, use the one from the negation,
1567 // to preserve the location.
1568 if (!Cmp->getDebugLoc() && Def->getDebugLoc())
1569 Cmp->setDebugLoc(Def->getDebugLoc());
1570 }
1571 }
1572 }
1573
1574 // Fold any-of (fcmp uno %A, %A), (fcmp uno %B, %B), ... ->
1575 // any-of (fcmp uno %A, %B), ...
1576 if (match(Def, m_AnyOf())) {
1578 VPRecipeBase *UnpairedCmp = nullptr;
1579 for (VPValue *Op : Def->operands()) {
1580 VPValue *X;
1581 if (Op->getNumUsers() > 1 ||
1583 m_Deferred(X)))) {
1584 NewOps.push_back(Op);
1585 } else if (!UnpairedCmp) {
1586 UnpairedCmp = Op->getDefiningRecipe();
1587 } else {
1588 NewOps.push_back(Builder.createFCmp(CmpInst::FCMP_UNO,
1589 UnpairedCmp->getOperand(0), X));
1590 UnpairedCmp = nullptr;
1591 }
1592 }
1593
1594 if (UnpairedCmp)
1595 NewOps.push_back(UnpairedCmp->getVPSingleValue());
1596
1597 if (NewOps.size() < Def->getNumOperands()) {
1598 VPValue *NewAnyOf = Builder.createNaryOp(VPInstruction::AnyOf, NewOps);
1599 return Def->replaceAllUsesWith(NewAnyOf);
1600 }
1601 }
1602
1603 // Fold (fcmp uno %X, %X) or (fcmp uno %Y, %Y) -> fcmp uno %X, %Y
1604 // This is useful for fmax/fmin without fast-math flags, where we need to
1605 // check if any operand is NaN.
1606 if (CanCreateNewRecipe &&
1608 m_Deferred(X)),
1610 m_Deferred(Y))))) {
1611 VPValue *NewCmp = Builder.createFCmp(CmpInst::FCMP_UNO, X, Y);
1612 return Def->replaceAllUsesWith(NewCmp);
1613 }
1614
1615 // Remove redundant DerviedIVs, that is 0 + A * 1 -> A and 0 + 0 * x -> 0.
1616 if ((match(Def, m_DerivedIV(m_ZeroInt(), m_VPValue(A), m_One())) ||
1617 match(Def, m_DerivedIV(m_ZeroInt(), m_ZeroInt(), m_VPValue()))) &&
1618 TypeInfo.inferScalarType(Def->getOperand(1)) ==
1619 TypeInfo.inferScalarType(Def))
1620 return Def->replaceAllUsesWith(Def->getOperand(1));
1621
1623 m_One()))) {
1624 Type *WideStepTy = TypeInfo.inferScalarType(Def);
1625 if (TypeInfo.inferScalarType(X) != WideStepTy)
1626 X = Builder.createWidenCast(Instruction::Trunc, X, WideStepTy);
1627 Def->replaceAllUsesWith(X);
1628 return;
1629 }
1630
1631 // For i1 vp.merges produced by AnyOf reductions:
1632 // vp.merge true, (or x, y), x, evl -> vp.merge y, true, x, evl
1634 m_VPValue(X), m_VPValue())) &&
1636 TypeInfo.inferScalarType(Def)->isIntegerTy(1)) {
1637 Def->setOperand(1, Def->getOperand(0));
1638 Def->setOperand(0, Y);
1639 return;
1640 }
1641
1642 // Simplify MaskedCond with no block mask to its single operand.
1644 !cast<VPInstruction>(Def)->isMasked())
1645 return Def->replaceAllUsesWith(Def->getOperand(0));
1646
1647 // Look through ExtractLastLane.
1648 if (match(Def, m_ExtractLastLane(m_VPValue(A)))) {
1649 if (match(A, m_BuildVector())) {
1650 auto *BuildVector = cast<VPInstruction>(A);
1651 Def->replaceAllUsesWith(
1652 BuildVector->getOperand(BuildVector->getNumOperands() - 1));
1653 return;
1654 }
1655
1656 if (match(A, m_Broadcast(m_VPValue(X))))
1657 return Def->replaceAllUsesWith(X);
1658
1660 return Def->replaceAllUsesWith(A);
1661
1662 if (Plan->hasScalarVFOnly())
1663 return Def->replaceAllUsesWith(A);
1664 }
1665
1666 // Look through ExtractPenultimateElement (BuildVector ....).
1668 auto *BuildVector = cast<VPInstruction>(Def->getOperand(0));
1669 Def->replaceAllUsesWith(
1670 BuildVector->getOperand(BuildVector->getNumOperands() - 2));
1671 return;
1672 }
1673
1674 uint64_t Idx;
1676 auto *BuildVector = cast<VPInstruction>(Def->getOperand(0));
1677 Def->replaceAllUsesWith(BuildVector->getOperand(Idx));
1678 return;
1679 }
1680
1681 if (match(Def, m_BuildVector()) && all_equal(Def->operands())) {
1682 Def->replaceAllUsesWith(
1683 Builder.createNaryOp(VPInstruction::Broadcast, Def->getOperand(0)));
1684 return;
1685 }
1686
1687 // Look through broadcast of single-scalar when used as select conditions; in
1688 // that case the scalar condition can be used directly.
1689 if (match(Def,
1692 "broadcast operand must be single-scalar");
1693 Def->setOperand(0, C);
1694 return;
1695 }
1696
1697 if (match(Def, m_Broadcast(m_VPValue(X))))
1698 return Def->replaceUsesWithIf(
1699 X, [Def](const VPUser &U, unsigned) { return U.usesScalars(Def); });
1700
1702 if (Def->getNumOperands() == 1) {
1703 Def->replaceAllUsesWith(Def->getOperand(0));
1704 return;
1705 }
1706 if (auto *Phi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(Def)) {
1707 if (all_equal(Phi->incoming_values()))
1708 Phi->replaceAllUsesWith(Phi->getOperand(0));
1709 }
1710 return;
1711 }
1712
1713 VPIRValue *IRV;
1714 if (Def->getNumOperands() == 1 &&
1716 return Def->replaceAllUsesWith(IRV);
1717
1718 // Some simplifications can only be applied after unrolling. Perform them
1719 // below.
1720 if (!Plan->isUnrolled())
1721 return;
1722
1723 // After unrolling, extract-lane may be used to extract values from multiple
1724 // scalar sources. Only simplify when extracting from a single scalar source.
1725 VPValue *LaneToExtract;
1726 if (match(Def, m_ExtractLane(m_VPValue(LaneToExtract), m_VPValue(A)))) {
1727 // Simplify extract-lane(%lane_num, %scalar_val) -> %scalar_val.
1729 return Def->replaceAllUsesWith(A);
1730
1731 // Simplify extract-lane with single source to extract-element.
1732 Def->replaceAllUsesWith(Builder.createNaryOp(
1733 Instruction::ExtractElement, {A, LaneToExtract}, Def->getDebugLoc()));
1734 return;
1735 }
1736
1737 // Look for cycles where Def is of the form:
1738 // X = phi(0, IVInc) ; used only by IVInc, or by IVInc and Inc = X + Y
1739 // IVInc = X + Step ; used by X and Def
1740 // Def = IVInc + Y
1741 // Fold the increment Y into the phi's start value, replace Def with IVInc,
1742 // and if Inc exists, replace it with X.
1743 if (match(Def, m_Add(m_Add(m_VPValue(X), m_VPValue()), m_VPValue(Y))) &&
1744 isa<VPIRValue>(Y) &&
1745 match(X, m_VPPhi(m_ZeroInt(), m_Specific(Def->getOperand(0))))) {
1746 auto *Phi = cast<VPPhi>(X);
1747 auto *IVInc = Def->getOperand(0);
1748 if (IVInc->getNumUsers() == 2) {
1749 // If Phi has a second user (besides IVInc's defining recipe), it must
1750 // be Inc = Phi + Y for the fold to apply.
1753 if (Phi->getNumUsers() == 1 || (Phi->getNumUsers() == 2 && Inc)) {
1754 Def->replaceAllUsesWith(IVInc);
1755 if (Inc)
1756 Inc->replaceAllUsesWith(Phi);
1757 Phi->setOperand(0, Y);
1758 return;
1759 }
1760 }
1761 }
1762
1763 // Simplify unrolled VectorPointer without offset, or with zero offset, to
1764 // just the pointer operand.
1765 if (auto *VPR = dyn_cast<VPVectorPointerRecipe>(Def))
1766 if (!VPR->getVFxPart() || match(VPR->getVFxPart(), m_ZeroInt()))
1767 return VPR->replaceAllUsesWith(VPR->getOperand(0));
1768
1769 // VPScalarIVSteps after unrolling can be replaced by their start value, if
1770 // the start index is zero and only the first lane 0 is demanded.
1771 if (auto *Steps = dyn_cast<VPScalarIVStepsRecipe>(Def)) {
1772 if (!Steps->getStartIndex() && vputils::onlyFirstLaneUsed(Steps)) {
1773 Steps->replaceAllUsesWith(Steps->getOperand(0));
1774 return;
1775 }
1776 }
1777 // Simplify redundant ReductionStartVector recipes after unrolling.
1778 VPValue *StartV;
1780 m_VPValue(StartV), m_VPValue(), m_VPValue()))) {
1781 Def->replaceUsesWithIf(StartV, [](const VPUser &U, unsigned Idx) {
1782 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&U);
1783 return PhiR && PhiR->isInLoop();
1784 });
1785 return;
1786 }
1787
1788 if (Plan->getConcreteUF() == 1 && match(Def, m_ExtractLastPart(m_VPValue(A))))
1789 return Def->replaceAllUsesWith(A);
1790}
1791
1794 Plan.getEntry());
1795 VPTypeAnalysis TypeInfo(Plan);
1797 for (VPRecipeBase &R : make_early_inc_range(*VPBB))
1798 if (auto *Def = dyn_cast<VPSingleDefRecipe>(&R))
1799 simplifyRecipe(Def, TypeInfo);
1800 }
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 = vputils::findHeaderMask(Plan);
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.
1900 if (!vputils::isSingleScalar(RepOrWidenR))
1901 continue;
1902
1903 // Predicate to check if a user of Op introduces extra broadcasts.
1904 auto IntroducesBCastOf = [](const VPValue *Op) {
1905 return [Op](const VPUser *U) {
1906 if (auto *VPI = dyn_cast<VPInstruction>(U)) {
1910 VPI->getOpcode()))
1911 return false;
1912 }
1913 return !U->usesScalars(Op);
1914 };
1915 };
1916
1917 if (any_of(RepOrWidenR->users(), IntroducesBCastOf(RepOrWidenR)) &&
1918 none_of(RepOrWidenR->operands(), [&](VPValue *Op) {
1919 if (any_of(
1920 make_filter_range(Op->users(), not_equal_to(RepOrWidenR)),
1921 IntroducesBCastOf(Op)))
1922 return false;
1923 // Non-constant live-ins require broadcasts, while constants do not
1924 // need explicit broadcasts.
1925 auto *IRV = dyn_cast<VPIRValue>(Op);
1926 bool LiveInNeedsBroadcast = IRV && !isa<Constant>(IRV->getValue());
1927 auto *OpR = dyn_cast<VPReplicateRecipe>(Op);
1928 return LiveInNeedsBroadcast || (OpR && OpR->isSingleScalar());
1929 }))
1930 continue;
1931
1932 auto *Clone = new VPReplicateRecipe(
1933 RepOrWidenR->getUnderlyingInstr(), RepOrWidenR->operands(),
1934 true /*IsSingleScalar*/, nullptr, *RepOrWidenR);
1935 Clone->insertBefore(RepOrWidenR);
1936 RepOrWidenR->replaceAllUsesWith(Clone);
1937 if (isDeadRecipe(*RepOrWidenR))
1938 RepOrWidenR->eraseFromParent();
1939 }
1940 }
1941}
1942
1943/// Try to see if all of \p Blend's masks share a common value logically and'ed
1944/// and remove it from the masks.
1946 if (Blend->isNormalized())
1947 return;
1948 VPValue *CommonEdgeMask;
1949 if (!match(Blend->getMask(0),
1950 m_LogicalAnd(m_VPValue(CommonEdgeMask), m_VPValue())))
1951 return;
1952 for (unsigned I = 0; I < Blend->getNumIncomingValues(); I++)
1953 if (!match(Blend->getMask(I),
1954 m_LogicalAnd(m_Specific(CommonEdgeMask), m_VPValue())))
1955 return;
1956 for (unsigned I = 0; I < Blend->getNumIncomingValues(); I++)
1957 Blend->setMask(I, Blend->getMask(I)->getDefiningRecipe()->getOperand(1));
1958}
1959
1960/// Normalize and simplify VPBlendRecipes. Should be run after simplifyRecipes
1961/// to make sure the masks are simplified.
1962static void simplifyBlends(VPlan &Plan) {
1965 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
1966 auto *Blend = dyn_cast<VPBlendRecipe>(&R);
1967 if (!Blend)
1968 continue;
1969
1970 removeCommonBlendMask(Blend);
1971
1972 // Try to remove redundant blend recipes.
1973 SmallPtrSet<VPValue *, 4> UniqueValues;
1974 if (Blend->isNormalized() || !match(Blend->getMask(0), m_False()))
1975 UniqueValues.insert(Blend->getIncomingValue(0));
1976 for (unsigned I = 1; I != Blend->getNumIncomingValues(); ++I)
1977 if (!match(Blend->getMask(I), m_False()))
1978 UniqueValues.insert(Blend->getIncomingValue(I));
1979
1980 if (UniqueValues.size() == 1) {
1981 Blend->replaceAllUsesWith(*UniqueValues.begin());
1982 Blend->eraseFromParent();
1983 continue;
1984 }
1985
1986 if (Blend->isNormalized())
1987 continue;
1988
1989 // Normalize the blend so its first incoming value is used as the initial
1990 // value with the others blended into it.
1991
1992 unsigned StartIndex = 0;
1993 for (unsigned I = 0; I != Blend->getNumIncomingValues(); ++I) {
1994 // If a value's mask is used only by the blend then is can be deadcoded.
1995 // TODO: Find the most expensive mask that can be deadcoded, or a mask
1996 // that's used by multiple blends where it can be removed from them all.
1997 VPValue *Mask = Blend->getMask(I);
1998 if (Mask->getNumUsers() == 1 && !match(Mask, m_False())) {
1999 StartIndex = I;
2000 break;
2001 }
2002 }
2003
2004 SmallVector<VPValue *, 4> OperandsWithMask;
2005 OperandsWithMask.push_back(Blend->getIncomingValue(StartIndex));
2006
2007 for (unsigned I = 0; I != Blend->getNumIncomingValues(); ++I) {
2008 if (I == StartIndex)
2009 continue;
2010 OperandsWithMask.push_back(Blend->getIncomingValue(I));
2011 OperandsWithMask.push_back(Blend->getMask(I));
2012 }
2013
2014 auto *NewBlend =
2015 new VPBlendRecipe(cast_or_null<PHINode>(Blend->getUnderlyingValue()),
2016 OperandsWithMask, *Blend, Blend->getDebugLoc());
2017 NewBlend->insertBefore(&R);
2018
2019 VPValue *DeadMask = Blend->getMask(StartIndex);
2020 Blend->replaceAllUsesWith(NewBlend);
2021 Blend->eraseFromParent();
2023
2024 /// Simplify BLEND %a, %b, Not(%mask) -> BLEND %b, %a, %mask.
2025 VPValue *NewMask;
2026 if (NewBlend->getNumOperands() == 3 &&
2027 match(NewBlend->getMask(1), m_Not(m_VPValue(NewMask)))) {
2028 VPValue *Inc0 = NewBlend->getOperand(0);
2029 VPValue *Inc1 = NewBlend->getOperand(1);
2030 VPValue *OldMask = NewBlend->getOperand(2);
2031 NewBlend->setOperand(0, Inc1);
2032 NewBlend->setOperand(1, Inc0);
2033 NewBlend->setOperand(2, NewMask);
2034 if (OldMask->getNumUsers() == 0)
2035 cast<VPInstruction>(OldMask)->eraseFromParent();
2036 }
2037 }
2038 }
2039}
2040
2041/// Optimize the width of vector induction variables in \p Plan based on a known
2042/// constant Trip Count, \p BestVF and \p BestUF.
2044 ElementCount BestVF,
2045 unsigned BestUF) {
2046 // Only proceed if we have not completely removed the vector region.
2047 if (!Plan.getVectorLoopRegion())
2048 return false;
2049
2050 const APInt *TC;
2051 if (!BestVF.isFixed() || !match(Plan.getTripCount(), m_APInt(TC)))
2052 return false;
2053
2054 // Calculate the minimum power-of-2 bit width that can fit the known TC, VF
2055 // and UF. Returns at least 8.
2056 auto ComputeBitWidth = [](APInt TC, uint64_t Align) {
2057 APInt AlignedTC =
2060 APInt MaxVal = AlignedTC - 1;
2061 return std::max<unsigned>(PowerOf2Ceil(MaxVal.getActiveBits()), 8);
2062 };
2063 unsigned NewBitWidth =
2064 ComputeBitWidth(*TC, BestVF.getKnownMinValue() * BestUF);
2065
2066 LLVMContext &Ctx = Plan.getContext();
2067 auto *NewIVTy = IntegerType::get(Ctx, NewBitWidth);
2068
2069 bool MadeChange = false;
2070
2071 VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
2072 for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
2073 auto *WideIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
2074
2075 // Currently only handle canonical IVs as it is trivial to replace the start
2076 // and stop values, and we currently only perform the optimization when the
2077 // IV has a single use.
2078 if (!WideIV || !WideIV->isCanonical() ||
2079 WideIV->hasMoreThanOneUniqueUser() ||
2080 NewIVTy == WideIV->getScalarType())
2081 continue;
2082
2083 // Currently only handle cases where the single user is a header-mask
2084 // comparison with the backedge-taken-count.
2085 VPUser *SingleUser = WideIV->getSingleUser();
2086 if (!SingleUser ||
2087 !match(SingleUser,
2088 m_ICmp(m_Specific(WideIV),
2090 continue;
2091
2092 // Update IV operands and comparison bound to use new narrower type.
2093 auto *NewStart = Plan.getZero(NewIVTy);
2094 WideIV->setStartValue(NewStart);
2095 auto *NewStep = Plan.getConstantInt(NewIVTy, 1);
2096 WideIV->setStepValue(NewStep);
2097
2098 auto *NewBTC = new VPWidenCastRecipe(
2099 Instruction::Trunc, Plan.getOrCreateBackedgeTakenCount(), NewIVTy,
2100 nullptr, VPIRFlags::getDefaultFlags(Instruction::Trunc));
2101 Plan.getVectorPreheader()->appendRecipe(NewBTC);
2102 auto *Cmp = cast<VPInstruction>(WideIV->getSingleUser());
2103 Cmp->setOperand(1, NewBTC);
2104
2105 MadeChange = true;
2106 }
2107
2108 return MadeChange;
2109}
2110
2111/// Return true if \p Cond is known to be true for given \p BestVF and \p
2112/// BestUF.
2114 ElementCount BestVF, unsigned BestUF,
2117 return any_of(Cond->getDefiningRecipe()->operands(), [&Plan, BestVF, BestUF,
2118 &PSE](VPValue *C) {
2119 return isConditionTrueViaVFAndUF(C, Plan, BestVF, BestUF, PSE);
2120 });
2121
2122 auto *CanIV = Plan.getVectorLoopRegion()->getCanonicalIV();
2125 m_c_Add(m_Specific(CanIV), m_Specific(&Plan.getVFxUF())),
2126 m_Specific(&Plan.getVectorTripCount()))))
2127 return false;
2128
2129 // The compare checks CanIV + VFxUF == vector trip count. The vector trip
2130 // count is not conveniently available as SCEV so far, so we compare directly
2131 // against the original trip count. This is stricter than necessary, as we
2132 // will only return true if the trip count == vector trip count.
2133 const SCEV *VectorTripCount =
2135 if (isa<SCEVCouldNotCompute>(VectorTripCount))
2136 VectorTripCount = vputils::getSCEVExprForVPValue(Plan.getTripCount(), PSE);
2137 assert(!isa<SCEVCouldNotCompute>(VectorTripCount) &&
2138 "Trip count SCEV must be computable");
2139 ScalarEvolution &SE = *PSE.getSE();
2140 ElementCount NumElements = BestVF.multiplyCoefficientBy(BestUF);
2141 const SCEV *C = SE.getElementCount(VectorTripCount->getType(), NumElements);
2142 return SE.isKnownPredicate(CmpInst::ICMP_EQ, VectorTripCount, C);
2143}
2144
2145/// Try to replace multiple active lane masks used for control flow with
2146/// a single, wide active lane mask instruction followed by multiple
2147/// extract subvector intrinsics. This applies to the active lane mask
2148/// instructions both in the loop and in the preheader.
2149/// Incoming values of all ActiveLaneMaskPHIs are updated to use the
2150/// new extracts from the first active lane mask, which has it's last
2151/// operand (multiplier) set to UF.
2153 unsigned UF) {
2154 if (!EnableWideActiveLaneMask || !VF.isVector() || UF == 1)
2155 return false;
2156
2157 VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
2158 VPBasicBlock *ExitingVPBB = VectorRegion->getExitingBasicBlock();
2159 auto *Term = &ExitingVPBB->back();
2160
2161 using namespace llvm::VPlanPatternMatch;
2163 m_VPValue(), m_VPValue(), m_VPValue())))))
2164 return false;
2165
2166 auto *Header = cast<VPBasicBlock>(VectorRegion->getEntry());
2167 LLVMContext &Ctx = Plan.getContext();
2168
2169 auto ExtractFromALM = [&](VPInstruction *ALM,
2170 SmallVectorImpl<VPValue *> &Extracts) {
2171 DebugLoc DL = ALM->getDebugLoc();
2172 for (unsigned Part = 0; Part < UF; ++Part) {
2174 Ops.append({ALM, Plan.getConstantInt(64, VF.getKnownMinValue() * Part)});
2175 auto *Ext =
2176 new VPWidenIntrinsicRecipe(Intrinsic::vector_extract, Ops,
2177 IntegerType::getInt1Ty(Ctx), {}, {}, DL);
2178 Extracts[Part] = Ext;
2179 Ext->insertAfter(ALM);
2180 }
2181 };
2182
2183 // Create a list of each active lane mask phi, ordered by unroll part.
2185 for (VPRecipeBase &R : Header->phis()) {
2187 if (!Phi)
2188 continue;
2189 VPValue *Index = nullptr;
2190 match(Phi->getBackedgeValue(),
2192 assert(Index && "Expected index from ActiveLaneMask instruction");
2193
2194 uint64_t Part;
2195 if (match(Index,
2197 m_VPValue(), m_Mul(m_VPValue(), m_ConstantInt(Part)))))
2198 Phis[Part] = Phi;
2199 else {
2200 // Anything other than a CanonicalIVIncrementForPart is part 0
2201 assert(!match(
2202 Index,
2204 Phis[0] = Phi;
2205 }
2206 }
2207
2208 assert(all_of(Phis, not_equal_to(nullptr)) &&
2209 "Expected one VPActiveLaneMaskPHIRecipe for each unroll part");
2210
2211 auto *EntryALM = cast<VPInstruction>(Phis[0]->getStartValue());
2212 auto *LoopALM = cast<VPInstruction>(Phis[0]->getBackedgeValue());
2213
2214 assert((EntryALM->getOpcode() == VPInstruction::ActiveLaneMask &&
2215 LoopALM->getOpcode() == VPInstruction::ActiveLaneMask) &&
2216 "Expected incoming values of Phi to be ActiveLaneMasks");
2217
2218 // When using wide lane masks, the return type of the get.active.lane.mask
2219 // intrinsic is VF x UF (last operand).
2220 VPValue *ALMMultiplier = Plan.getConstantInt(64, UF);
2221 EntryALM->setOperand(2, ALMMultiplier);
2222 LoopALM->setOperand(2, ALMMultiplier);
2223
2224 // Create UF x extract vectors and insert into preheader.
2225 SmallVector<VPValue *> EntryExtracts(UF);
2226 ExtractFromALM(EntryALM, EntryExtracts);
2227
2228 // Create UF x extract vectors and insert before the loop compare & branch,
2229 // updating the compare to use the first extract.
2230 SmallVector<VPValue *> LoopExtracts(UF);
2231 ExtractFromALM(LoopALM, LoopExtracts);
2232 VPInstruction *Not = cast<VPInstruction>(Term->getOperand(0));
2233 Not->setOperand(0, LoopExtracts[0]);
2234
2235 // Update the incoming values of active lane mask phis.
2236 for (unsigned Part = 0; Part < UF; ++Part) {
2237 Phis[Part]->setStartValue(EntryExtracts[Part]);
2238 Phis[Part]->setBackedgeValue(LoopExtracts[Part]);
2239 }
2240
2241 return true;
2242}
2243
2244/// Try to simplify the branch condition of \p Plan. This may restrict the
2245/// resulting plan to \p BestVF and \p BestUF.
2247 unsigned BestUF,
2249 VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
2250 VPBasicBlock *ExitingVPBB = VectorRegion->getExitingBasicBlock();
2251 auto *Term = &ExitingVPBB->back();
2252 VPValue *Cond;
2253 auto m_CanIVInc = m_Add(m_VPValue(), m_Specific(&Plan.getVFxUF()));
2254 // Check if the branch condition compares the canonical IV increment (for main
2255 // loop), or the canonical IV increment plus an offset (for epilog loop).
2256 if (match(Term, m_BranchOnCount(
2257 m_CombineOr(m_CanIVInc, m_c_Add(m_CanIVInc, m_LiveIn())),
2258 m_VPValue())) ||
2260 m_VPValue(), m_VPValue(), m_VPValue()))))) {
2261 // Try to simplify the branch condition if VectorTC <= VF * UF when the
2262 // latch terminator is BranchOnCount or BranchOnCond(Not(ActiveLaneMask)).
2263 const SCEV *VectorTripCount =
2265 if (isa<SCEVCouldNotCompute>(VectorTripCount))
2266 VectorTripCount =
2268 assert(!isa<SCEVCouldNotCompute>(VectorTripCount) &&
2269 "Trip count SCEV must be computable");
2270 ScalarEvolution &SE = *PSE.getSE();
2271 ElementCount NumElements = BestVF.multiplyCoefficientBy(BestUF);
2272 const SCEV *C = SE.getElementCount(VectorTripCount->getType(), NumElements);
2273 if (!SE.isKnownPredicate(CmpInst::ICMP_ULE, VectorTripCount, C))
2274 return false;
2275 } else if (match(Term, m_BranchOnCond(m_VPValue(Cond))) ||
2277 // For BranchOnCond, check if we can prove the condition to be true using VF
2278 // and UF.
2279 if (!isConditionTrueViaVFAndUF(Cond, Plan, BestVF, BestUF, PSE))
2280 return false;
2281 } else {
2282 return false;
2283 }
2284
2285 // The vector loop region only executes once. Convert terminator of the
2286 // exiting block to exit in the first iteration.
2287 if (match(Term, m_BranchOnTwoConds())) {
2288 Term->setOperand(1, Plan.getTrue());
2289 return true;
2290 }
2291
2292 auto *BOC = new VPInstruction(VPInstruction::BranchOnCond, Plan.getTrue(), {},
2293 {}, Term->getDebugLoc());
2294 ExitingVPBB->appendRecipe(BOC);
2295 Term->eraseFromParent();
2296
2297 return true;
2298}
2299
2300/// From the definition of llvm.experimental.get.vector.length,
2301/// VPInstruction::ExplicitVectorLength(%AVL) = %AVL when %AVL <= VF.
2305 vp_depth_first_deep(Plan.getEntry()))) {
2306 for (VPRecipeBase &R : *VPBB) {
2307 VPValue *AVL;
2308 if (!match(&R, m_EVL(m_VPValue(AVL))))
2309 continue;
2310
2311 const SCEV *AVLSCEV = vputils::getSCEVExprForVPValue(AVL, PSE);
2312 if (isa<SCEVCouldNotCompute>(AVLSCEV))
2313 continue;
2314 ScalarEvolution &SE = *PSE.getSE();
2315 const SCEV *VFSCEV = SE.getElementCount(AVLSCEV->getType(), VF);
2316 if (!SE.isKnownPredicate(CmpInst::ICMP_ULE, AVLSCEV, VFSCEV))
2317 continue;
2318
2320 AVL, Type::getInt32Ty(Plan.getContext()), AVLSCEV->getType(),
2321 R.getDebugLoc());
2322 if (Trunc != AVL) {
2323 auto *TruncR = cast<VPSingleDefRecipe>(Trunc);
2324 const DataLayout &DL = Plan.getDataLayout();
2325 VPTypeAnalysis TypeInfo(Plan);
2326 if (VPValue *Folded =
2327 tryToFoldLiveIns(*TruncR, TruncR->operands(), DL, TypeInfo))
2328 Trunc = Folded;
2329 }
2330 R.getVPSingleValue()->replaceAllUsesWith(Trunc);
2331 return true;
2332 }
2333 }
2334 return false;
2335}
2336
2338 unsigned BestUF,
2340 assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
2341 assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
2342
2343 bool MadeChange = tryToReplaceALMWithWideALM(Plan, BestVF, BestUF);
2344 MadeChange |= simplifyBranchConditionForVFAndUF(Plan, BestVF, BestUF, PSE);
2345 MadeChange |= optimizeVectorInductionWidthForTCAndVFUF(Plan, BestVF, BestUF);
2346
2347 if (MadeChange) {
2348 Plan.setVF(BestVF);
2349 assert(Plan.getConcreteUF() == BestUF && "BestUF must match the Plan's UF");
2350 }
2351}
2352
2354 for (VPRecipeBase &R :
2356 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
2357 if (!PhiR)
2358 continue;
2359 RecurKind RK = PhiR->getRecurrenceKind();
2360 if (RK != RecurKind::Add && RK != RecurKind::Mul && RK != RecurKind::Sub &&
2362 continue;
2363
2364 for (VPUser *U : collectUsersRecursively(PhiR))
2365 if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(U)) {
2366 RecWithFlags->dropPoisonGeneratingFlags();
2367 }
2368 }
2369}
2370
2371namespace {
2372struct VPCSEDenseMapInfo : public DenseMapInfo<VPSingleDefRecipe *> {
2373 static bool isSentinel(const VPSingleDefRecipe *Def) {
2374 return Def == getEmptyKey() || Def == getTombstoneKey();
2375 }
2376
2377 /// If recipe \p R will lower to a GEP with a non-i8 source element type,
2378 /// return that source element type.
2379 static Type *getGEPSourceElementType(const VPSingleDefRecipe *R) {
2380 // All VPInstructions that lower to GEPs must have the i8 source element
2381 // type (as they are PtrAdds), so we omit it.
2383 .Case([](const VPReplicateRecipe *I) -> Type * {
2384 if (auto *GEP = dyn_cast<GetElementPtrInst>(I->getUnderlyingValue()))
2385 return GEP->getSourceElementType();
2386 return nullptr;
2387 })
2388 .Case<VPVectorPointerRecipe, VPWidenGEPRecipe>(
2389 [](auto *I) { return I->getSourceElementType(); })
2390 .Default([](auto *) { return nullptr; });
2391 }
2392
2393 /// Returns true if recipe \p Def can be safely handed for CSE.
2394 static bool canHandle(const VPSingleDefRecipe *Def) {
2395 // We can extend the list of handled recipes in the future,
2396 // provided we account for the data embedded in them while checking for
2397 // equality or hashing.
2398 auto C = getOpcodeOrIntrinsicID(Def);
2399
2400 // The issue with (Insert|Extract)Value is that the index of the
2401 // insert/extract is not a proper operand in LLVM IR, and hence also not in
2402 // VPlan.
2403 if (!C || (!C->first && (C->second == Instruction::InsertValue ||
2404 C->second == Instruction::ExtractValue)))
2405 return false;
2406
2407 // During CSE, we can only handle recipes that don't read from memory: if
2408 // they read from memory, there could be an intervening write to memory
2409 // before the next instance is CSE'd, leading to an incorrect result.
2410 return !Def->mayReadFromMemory();
2411 }
2412
2413 /// Hash the underlying data of \p Def.
2414 static unsigned getHashValue(const VPSingleDefRecipe *Def) {
2415 const VPlan *Plan = Def->getParent()->getPlan();
2416 VPTypeAnalysis TypeInfo(*Plan);
2417 hash_code Result = hash_combine(
2418 Def->getVPRecipeID(), getOpcodeOrIntrinsicID(Def),
2419 getGEPSourceElementType(Def), TypeInfo.inferScalarType(Def),
2421 if (auto *RFlags = dyn_cast<VPRecipeWithIRFlags>(Def))
2422 if (RFlags->hasPredicate())
2423 return hash_combine(Result, RFlags->getPredicate());
2424 if (auto *SIVSteps = dyn_cast<VPScalarIVStepsRecipe>(Def))
2425 return hash_combine(Result, SIVSteps->getInductionOpcode());
2426 return Result;
2427 }
2428
2429 /// Check equality of underlying data of \p L and \p R.
2430 static bool isEqual(const VPSingleDefRecipe *L, const VPSingleDefRecipe *R) {
2431 if (isSentinel(L) || isSentinel(R))
2432 return L == R;
2433 if (L->getVPRecipeID() != R->getVPRecipeID() ||
2435 getGEPSourceElementType(L) != getGEPSourceElementType(R) ||
2437 !equal(L->operands(), R->operands()))
2438 return false;
2440 "must have valid opcode info for both recipes");
2441 if (auto *LFlags = dyn_cast<VPRecipeWithIRFlags>(L))
2442 if (LFlags->hasPredicate() &&
2443 LFlags->getPredicate() !=
2444 cast<VPRecipeWithIRFlags>(R)->getPredicate())
2445 return false;
2446 if (auto *LSIV = dyn_cast<VPScalarIVStepsRecipe>(L))
2447 if (LSIV->getInductionOpcode() !=
2448 cast<VPScalarIVStepsRecipe>(R)->getInductionOpcode())
2449 return false;
2450 // Recipes in replicate regions implicitly depend on predicate. If either
2451 // recipe is in a replicate region, only consider them equal if both have
2452 // the same parent.
2453 const VPRegionBlock *RegionL = L->getRegion();
2454 const VPRegionBlock *RegionR = R->getRegion();
2455 if (((RegionL && RegionL->isReplicator()) ||
2456 (RegionR && RegionR->isReplicator())) &&
2457 L->getParent() != R->getParent())
2458 return false;
2459 const VPlan *Plan = L->getParent()->getPlan();
2460 VPTypeAnalysis TypeInfo(*Plan);
2461 return TypeInfo.inferScalarType(L) == TypeInfo.inferScalarType(R);
2462 }
2463};
2464} // end anonymous namespace
2465
2466/// Perform a common-subexpression-elimination of VPSingleDefRecipes on the \p
2467/// Plan.
2469 VPDominatorTree VPDT(Plan);
2471
2473 Plan.getEntry());
2475 for (VPRecipeBase &R : *VPBB) {
2476 auto *Def = dyn_cast<VPSingleDefRecipe>(&R);
2477 if (!Def || !VPCSEDenseMapInfo::canHandle(Def))
2478 continue;
2479 if (VPSingleDefRecipe *V = CSEMap.lookup(Def)) {
2480 // V must dominate Def for a valid replacement.
2481 if (!VPDT.dominates(V->getParent(), VPBB))
2482 continue;
2483 // Only keep flags present on both V and Def.
2484 if (auto *RFlags = dyn_cast<VPRecipeWithIRFlags>(V))
2485 RFlags->intersectFlags(*cast<VPRecipeWithIRFlags>(Def));
2486 Def->replaceAllUsesWith(V);
2487 continue;
2488 }
2489 CSEMap[Def] = Def;
2490 }
2491 }
2492}
2493
2494/// Return true if we do not know how to (mechanically) hoist or sink a
2495/// non-memory or memory recipe \p R out of a loop region.
2497 VPBasicBlock *LastBB) {
2498 if (!isa<VPReplicateRecipe>(R) || !R.mayReadFromMemory())
2500
2501 // Check that the load doesn't alias with stores between FirstBB and LastBB.
2502 auto MemLoc = vputils::getMemoryLocation(R);
2503 return !MemLoc || !canHoistOrSinkWithNoAliasCheck(*MemLoc, FirstBB, LastBB);
2504}
2505
2506/// Move loop-invariant recipes out of the vector loop region in \p Plan.
2507static void licm(VPlan &Plan) {
2508 VPBasicBlock *Preheader = Plan.getVectorPreheader();
2509
2510 // Hoist any loop invariant recipes from the vector loop region to the
2511 // preheader. Preform a shallow traversal of the vector loop region, to
2512 // exclude recipes in replicate regions. Since the top-level blocks in the
2513 // vector loop region are guaranteed to execute if the vector pre-header is,
2514 // we don't need to check speculation safety.
2515 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
2516 assert(Preheader->getSingleSuccessor() == LoopRegion &&
2517 "Expected vector prehader's successor to be the vector loop region");
2519 vp_depth_first_shallow(LoopRegion->getEntry()))) {
2520 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
2521 if (cannotHoistOrSinkRecipe(R, LoopRegion->getEntryBasicBlock(),
2522 LoopRegion->getExitingBasicBlock()))
2523 continue;
2524 if (any_of(R.operands(), [](VPValue *Op) {
2525 return !Op->isDefinedOutsideLoopRegions();
2526 }))
2527 continue;
2528 R.moveBefore(*Preheader, Preheader->end());
2529 }
2530 }
2531
2532#ifndef NDEBUG
2533 VPDominatorTree VPDT(Plan);
2534#endif
2535 // Sink recipes with no users inside the vector loop region if all users are
2536 // in the same exit block of the region.
2537 // TODO: Extend to sink recipes from inner loops.
2539 LoopRegion->getEntry());
2541 for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB))) {
2542 if (vputils::cannotHoistOrSinkRecipe(R, /*Sinking=*/true))
2543 continue;
2544
2545 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
2546 assert(!RepR->isPredicated() &&
2547 "Expected prior transformation of predicated replicates to "
2548 "replicate regions");
2549 // narrowToSingleScalarRecipes should have already maximally narrowed
2550 // replicates to single-scalar replicates.
2551 // TODO: When unrolling, replicateByVF doesn't handle sunk
2552 // non-single-scalar replicates correctly.
2553 if (!RepR->isSingleScalar())
2554 continue;
2555 }
2556
2557 // TODO: Use R.definedValues() instead of casting to VPSingleDefRecipe to
2558 // support recipes with multiple defined values (e.g., interleaved loads).
2559 auto *Def = cast<VPSingleDefRecipe>(&R);
2560
2561 // Cannot sink the recipe if the user is defined in a loop region or a
2562 // non-successor of the vector loop region. Cannot sink if user is a phi
2563 // either.
2564 VPBasicBlock *SinkBB = nullptr;
2565 if (any_of(Def->users(), [&SinkBB, &LoopRegion](VPUser *U) {
2566 auto *UserR = cast<VPRecipeBase>(U);
2567 VPBasicBlock *Parent = UserR->getParent();
2568 // TODO: Support sinking when users are in multiple blocks.
2569 if (SinkBB && SinkBB != Parent)
2570 return true;
2571 SinkBB = Parent;
2572 // TODO: If the user is a PHI node, we should check the block of
2573 // incoming value. Support PHI node users if needed.
2574 return UserR->isPhi() || Parent->getEnclosingLoopRegion() ||
2575 Parent->getSinglePredecessor() != LoopRegion;
2576 }))
2577 continue;
2578
2579 if (!SinkBB)
2580 SinkBB = cast<VPBasicBlock>(LoopRegion->getSingleSuccessor());
2581
2582 // TODO: This will need to be a check instead of a assert after
2583 // conditional branches in vectorized loops are supported.
2584 assert(VPDT.properlyDominates(VPBB, SinkBB) &&
2585 "Defining block must dominate sink block");
2586 // TODO: Clone the recipe if users are on multiple exit paths, instead of
2587 // just moving.
2588 Def->moveBefore(*SinkBB, SinkBB->getFirstNonPhi());
2589 }
2590 }
2591}
2592
2594 VPlan &Plan, const MapVector<Instruction *, uint64_t> &MinBWs) {
2595 if (Plan.hasScalarVFOnly())
2596 return;
2597 // Keep track of created truncates, so they can be re-used. Note that we
2598 // cannot use RAUW after creating a new truncate, as this would could make
2599 // other uses have different types for their operands, making them invalidly
2600 // typed.
2602 VPTypeAnalysis TypeInfo(Plan);
2603 VPBasicBlock *PH = Plan.getVectorPreheader();
2606 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
2609 continue;
2610
2611 VPValue *ResultVPV = R.getVPSingleValue();
2612 auto *UI = cast_or_null<Instruction>(ResultVPV->getUnderlyingValue());
2613 unsigned NewResSizeInBits = MinBWs.lookup(UI);
2614 if (!NewResSizeInBits)
2615 continue;
2616
2617 // If the value wasn't vectorized, we must maintain the original scalar
2618 // type. Skip those here, after incrementing NumProcessedRecipes. Also
2619 // skip casts which do not need to be handled explicitly here, as
2620 // redundant casts will be removed during recipe simplification.
2622 continue;
2623
2624 Type *OldResTy = TypeInfo.inferScalarType(ResultVPV);
2625 unsigned OldResSizeInBits = OldResTy->getScalarSizeInBits();
2626 assert(OldResTy->isIntegerTy() && "only integer types supported");
2627 (void)OldResSizeInBits;
2628
2629 auto *NewResTy = IntegerType::get(Plan.getContext(), NewResSizeInBits);
2630
2631 // Any wrapping introduced by shrinking this operation shouldn't be
2632 // considered undefined behavior. So, we can't unconditionally copy
2633 // arithmetic wrapping flags to VPW.
2634 if (auto *VPW = dyn_cast<VPRecipeWithIRFlags>(&R))
2635 VPW->dropPoisonGeneratingFlags();
2636
2637 if (OldResSizeInBits != NewResSizeInBits &&
2638 !match(&R, m_ICmp(m_VPValue(), m_VPValue()))) {
2639 // Extend result to original width.
2640 auto *Ext = new VPWidenCastRecipe(
2641 Instruction::ZExt, ResultVPV, OldResTy, nullptr,
2642 VPIRFlags::getDefaultFlags(Instruction::ZExt));
2643 Ext->insertAfter(&R);
2644 ResultVPV->replaceAllUsesWith(Ext);
2645 Ext->setOperand(0, ResultVPV);
2646 assert(OldResSizeInBits > NewResSizeInBits && "Nothing to shrink?");
2647 } else {
2648 assert(match(&R, m_ICmp(m_VPValue(), m_VPValue())) &&
2649 "Only ICmps should not need extending the result.");
2650 }
2651
2652 assert(!isa<VPWidenStoreRecipe>(&R) && "stores cannot be narrowed");
2654 continue;
2655
2656 // Shrink operands by introducing truncates as needed.
2657 unsigned StartIdx =
2658 match(&R, m_Select(m_VPValue(), m_VPValue(), m_VPValue())) ? 1 : 0;
2659 for (unsigned Idx = StartIdx; Idx != R.getNumOperands(); ++Idx) {
2660 auto *Op = R.getOperand(Idx);
2661 unsigned OpSizeInBits =
2663 if (OpSizeInBits == NewResSizeInBits)
2664 continue;
2665 assert(OpSizeInBits > NewResSizeInBits && "nothing to truncate");
2666 auto [ProcessedIter, IterIsEmpty] = ProcessedTruncs.try_emplace(Op);
2667 if (!IterIsEmpty) {
2668 R.setOperand(Idx, ProcessedIter->second);
2669 continue;
2670 }
2671
2672 VPBuilder Builder;
2673 if (isa<VPIRValue>(Op))
2674 Builder.setInsertPoint(PH);
2675 else
2676 Builder.setInsertPoint(&R);
2677 VPWidenCastRecipe *NewOp =
2678 Builder.createWidenCast(Instruction::Trunc, Op, NewResTy);
2679 ProcessedIter->second = NewOp;
2680 R.setOperand(Idx, NewOp);
2681 }
2682
2683 }
2684 }
2685}
2686
2687void VPlanTransforms::removeBranchOnConst(VPlan &Plan, bool OnlyLatches) {
2688 std::optional<VPDominatorTree> VPDT;
2689 if (OnlyLatches)
2690 VPDT.emplace(Plan);
2691
2692 // Collect all blocks before modifying the CFG so we can identify unreachable
2693 // ones after constant branch removal.
2695
2696 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(AllBlocks)) {
2697 VPValue *Cond;
2698 // Skip blocks that are not terminated by BranchOnCond.
2699 if (VPBB->empty() || !match(&VPBB->back(), m_BranchOnCond(m_VPValue(Cond))))
2700 continue;
2701
2702 if (OnlyLatches && !VPBlockUtils::isLatch(VPBB, *VPDT))
2703 continue;
2704
2705 assert(VPBB->getNumSuccessors() == 2 &&
2706 "Two successors expected for BranchOnCond");
2707 unsigned RemovedIdx;
2708 if (match(Cond, m_True()))
2709 RemovedIdx = 1;
2710 else if (match(Cond, m_False()))
2711 RemovedIdx = 0;
2712 else
2713 continue;
2714
2715 VPBasicBlock *RemovedSucc =
2716 cast<VPBasicBlock>(VPBB->getSuccessors()[RemovedIdx]);
2717 assert(count(RemovedSucc->getPredecessors(), VPBB) == 1 &&
2718 "There must be a single edge between VPBB and its successor");
2719 // Values coming from VPBB into phi recipes of RemovedSucc are removed from
2720 // these recipes.
2721 for (VPRecipeBase &R : RemovedSucc->phis())
2722 cast<VPPhiAccessors>(&R)->removeIncomingValueFor(VPBB);
2723
2724 // Disconnect blocks and remove the terminator.
2725 VPBlockUtils::disconnectBlocks(VPBB, RemovedSucc);
2726 VPBB->back().eraseFromParent();
2727 }
2728
2729 // Compute which blocks are still reachable from the entry after constant
2730 // branch removal.
2733
2734 // Detach all unreachable blocks from their successors, removing their recipes
2735 // and incoming values from phi recipes.
2736 VPSymbolicValue Tmp(nullptr);
2737 for (VPBlockBase *B : AllBlocks) {
2738 if (Reachable.contains(B))
2739 continue;
2740 for (VPBlockBase *Succ : to_vector(B->successors())) {
2741 if (auto *SuccBB = dyn_cast<VPBasicBlock>(Succ))
2742 for (VPRecipeBase &R : SuccBB->phis())
2743 cast<VPPhiAccessors>(&R)->removeIncomingValueFor(B);
2745 }
2746 for (VPBasicBlock *DeadBB :
2748 for (VPRecipeBase &R : make_early_inc_range(*DeadBB)) {
2749 for (VPValue *Def : R.definedValues())
2750 Def->replaceAllUsesWith(&Tmp);
2751 R.eraseFromParent();
2752 }
2753 }
2754 }
2755}
2756
2776
2777// Add a VPActiveLaneMaskPHIRecipe and related recipes to \p Plan and replace
2778// the loop terminator with a branch-on-cond recipe with the negated
2779// active-lane-mask as operand. Note that this turns the loop into an
2780// uncountable one. Only the existing terminator is replaced, all other existing
2781// recipes/users remain unchanged, except for poison-generating flags being
2782// dropped from the canonical IV increment. Return the created
2783// VPActiveLaneMaskPHIRecipe.
2784//
2785// The function adds the following recipes:
2786//
2787// vector.ph:
2788// %EntryInc = canonical-iv-increment-for-part CanonicalIVStart
2789// %EntryALM = active-lane-mask %EntryInc, TC
2790//
2791// vector.body:
2792// ...
2793// %P = active-lane-mask-phi [ %EntryALM, %vector.ph ], [ %ALM, %vector.body ]
2794// ...
2795// %InLoopInc = canonical-iv-increment-for-part CanonicalIVIncrement
2796// %ALM = active-lane-mask %InLoopInc, TC
2797// %Negated = Not %ALM
2798// branch-on-cond %Negated
2799//
2802 VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
2803 VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
2804 VPValue *StartV = Plan.getZero(TopRegion->getCanonicalIVType());
2805 auto *CanonicalIVIncrement = TopRegion->getOrCreateCanonicalIVIncrement();
2806 // TODO: Check if dropping the flags is needed.
2807 TopRegion->clearCanonicalIVNUW(CanonicalIVIncrement);
2808 DebugLoc DL = CanonicalIVIncrement->getDebugLoc();
2809 // We can't use StartV directly in the ActiveLaneMask VPInstruction, since
2810 // we have to take unrolling into account. Each part needs to start at
2811 // Part * VF
2812 auto *VecPreheader = Plan.getVectorPreheader();
2813 VPBuilder Builder(VecPreheader);
2814
2815 // Create the ActiveLaneMask instruction using the correct start values.
2816 VPValue *TC = Plan.getTripCount();
2817 VPValue *VF = &Plan.getVF();
2818
2819 auto *EntryIncrement = Builder.createOverflowingOp(
2820 VPInstruction::CanonicalIVIncrementForPart, {StartV, VF}, {false, false},
2821 DL, "index.part.next");
2822
2823 // Create the active lane mask instruction in the VPlan preheader.
2824 VPValue *ALMMultiplier =
2825 Plan.getConstantInt(TopRegion->getCanonicalIVType(), 1);
2826 auto *EntryALM = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
2827 {EntryIncrement, TC, ALMMultiplier}, DL,
2828 "active.lane.mask.entry");
2829
2830 // Now create the ActiveLaneMaskPhi recipe in the main loop using the
2831 // preheader ActiveLaneMask instruction.
2832 auto *LaneMaskPhi =
2834 auto *HeaderVPBB = TopRegion->getEntryBasicBlock();
2835 LaneMaskPhi->insertBefore(*HeaderVPBB, HeaderVPBB->begin());
2836
2837 // Create the active lane mask for the next iteration of the loop before the
2838 // original terminator.
2839 VPRecipeBase *OriginalTerminator = EB->getTerminator();
2840 Builder.setInsertPoint(OriginalTerminator);
2841 auto *InLoopIncrement = Builder.createOverflowingOp(
2843 {CanonicalIVIncrement, &Plan.getVF()}, {false, false}, DL);
2844 auto *ALM = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
2845 {InLoopIncrement, TC, ALMMultiplier}, DL,
2846 "active.lane.mask.next");
2847 LaneMaskPhi->addOperand(ALM);
2848
2849 // Replace the original terminator with BranchOnCond. We have to invert the
2850 // mask here because a true condition means jumping to the exit block.
2851 auto *NotMask = Builder.createNot(ALM, DL);
2852 Builder.createNaryOp(VPInstruction::BranchOnCond, {NotMask}, DL);
2853 OriginalTerminator->eraseFromParent();
2854 return LaneMaskPhi;
2855}
2856
2858 bool UseActiveLaneMaskForControlFlow) {
2859 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
2860 auto *WideCanonicalIV = vputils::findUserOf<VPWidenCanonicalIVRecipe>(
2861 LoopRegion->getCanonicalIV());
2862 assert(WideCanonicalIV &&
2863 "Must have widened canonical IV when tail folding!");
2864 VPSingleDefRecipe *HeaderMask = vputils::findHeaderMask(Plan);
2865 VPSingleDefRecipe *LaneMask;
2866 if (UseActiveLaneMaskForControlFlow) {
2867 LaneMask = addVPLaneMaskPhiAndUpdateExitBranch(Plan);
2868 } else {
2869 VPBuilder B = VPBuilder::getToInsertAfter(WideCanonicalIV);
2870 VPValue *ALMMultiplier =
2871 Plan.getConstantInt(LoopRegion->getCanonicalIVType(), 1);
2872 LaneMask =
2873 B.createNaryOp(VPInstruction::ActiveLaneMask,
2874 {WideCanonicalIV, Plan.getTripCount(), ALMMultiplier},
2875 nullptr, "active.lane.mask");
2876 }
2877
2878 // Walk users of WideCanonicalIV and replace the header mask of the form
2879 // (ICMP_ULE, WideCanonicalIV, backedge-taken-count) with an active-lane-mask,
2880 // removing the old one to ensure there is always only a single header mask.
2881 HeaderMask->replaceAllUsesWith(LaneMask);
2882 HeaderMask->eraseFromParent();
2883}
2884
2885template <typename Op0_t, typename Op1_t> struct RemoveMask_match {
2886 Op0_t In;
2888
2889 RemoveMask_match(const Op0_t &In, Op1_t &Out) : In(In), Out(Out) {}
2890
2891 template <typename OpTy> bool match(OpTy *V) const {
2892 if (m_Specific(In).match(V)) {
2893 Out = nullptr;
2894 return true;
2895 }
2896 return m_LogicalAnd(m_Specific(In), m_VPValue(Out)).match(V);
2897 }
2898};
2899
2900/// Match a specific mask \p In, or a combination of it (logical-and In, Out).
2901/// Returns the remaining part \p Out if so, or nullptr otherwise.
2902template <typename Op0_t, typename Op1_t>
2903static inline RemoveMask_match<Op0_t, Op1_t> m_RemoveMask(const Op0_t &In,
2904 Op1_t &Out) {
2905 return RemoveMask_match<Op0_t, Op1_t>(In, Out);
2906}
2907
2908static std::optional<Intrinsic::ID> getVPDivRemIntrinsic(Intrinsic::ID IntrID) {
2909 switch (IntrID) {
2910 case Intrinsic::masked_udiv:
2911 return Intrinsic::vp_udiv;
2912 case Intrinsic::masked_sdiv:
2913 return Intrinsic::vp_sdiv;
2914 case Intrinsic::masked_urem:
2915 return Intrinsic::vp_urem;
2916 case Intrinsic::masked_srem:
2917 return Intrinsic::vp_srem;
2918 default:
2919 return std::nullopt;
2920 }
2921}
2922
2923/// Try to optimize a \p CurRecipe masked by \p HeaderMask to a corresponding
2924/// EVL-based recipe without the header mask. Returns nullptr if no EVL-based
2925/// recipe could be created.
2926/// \p HeaderMask Header Mask.
2927/// \p CurRecipe Recipe to be transform.
2928/// \p TypeInfo VPlan-based type analysis.
2929/// \p EVL The explicit vector length parameter of vector-predication
2930/// intrinsics.
2932 VPRecipeBase &CurRecipe,
2933 VPTypeAnalysis &TypeInfo, VPValue &EVL) {
2934 VPlan *Plan = CurRecipe.getParent()->getPlan();
2935 DebugLoc DL = CurRecipe.getDebugLoc();
2936 VPValue *Addr, *Mask, *EndPtr;
2937
2938 /// Adjust any end pointers so that they point to the end of EVL lanes not VF.
2939 auto AdjustEndPtr = [&CurRecipe, &EVL](VPValue *EndPtr) {
2940 auto *EVLEndPtr = cast<VPVectorEndPointerRecipe>(EndPtr)->clone();
2941 EVLEndPtr->insertBefore(&CurRecipe);
2942 EVLEndPtr->setOperand(1, &EVL);
2943 return EVLEndPtr;
2944 };
2945
2946 auto GetVPReverse = [&CurRecipe, &EVL, &TypeInfo, Plan,
2948 if (!V)
2949 return nullptr;
2950 auto *Reverse = new VPWidenIntrinsicRecipe(
2951 Intrinsic::experimental_vp_reverse, {V, Plan->getTrue(), &EVL},
2952 TypeInfo.inferScalarType(V), {}, {}, DL);
2953 Reverse->insertBefore(&CurRecipe);
2954 return Reverse;
2955 };
2956
2957 if (match(&CurRecipe,
2958 m_MaskedLoad(m_VPValue(Addr), m_RemoveMask(HeaderMask, Mask))))
2959 return new VPWidenLoadEVLRecipe(cast<VPWidenLoadRecipe>(CurRecipe), Addr,
2960 EVL, Mask);
2961
2962 VPValue *ReversedVal;
2963 if (match(&CurRecipe, m_Reverse(m_VPValue(ReversedVal))) &&
2964 match(ReversedVal,
2965 m_MaskedLoad(m_VPValue(EndPtr),
2966 m_Reverse(m_RemoveMask(HeaderMask, Mask)))) &&
2967 match(EndPtr, m_VecEndPtr(m_VPValue(), m_Specific(&Plan->getVF())))) {
2968 Mask = GetVPReverse(Mask);
2969 Addr = AdjustEndPtr(EndPtr);
2970 auto *LoadR = new VPWidenLoadEVLRecipe(
2971 *cast<VPWidenLoadRecipe>(ReversedVal), Addr, EVL, Mask);
2972 LoadR->insertBefore(&CurRecipe);
2973 return new VPWidenIntrinsicRecipe(
2974 Intrinsic::experimental_vp_reverse, {LoadR, Plan->getTrue(), &EVL},
2975 TypeInfo.inferScalarType(LoadR), {}, {}, DL);
2976 }
2977
2978 VPValue *Stride;
2980 m_VPValue(Addr), m_VPValue(Stride),
2981 m_RemoveMask(HeaderMask, Mask),
2982 m_TruncOrSelf(m_Specific(&Plan->getVF()))))) {
2983 if (!Mask)
2984 Mask = Plan->getTrue();
2985 auto *NewLoad = cast<VPWidenMemIntrinsicRecipe>(&CurRecipe)->clone();
2986 NewLoad->setOperand(2, Mask);
2987 NewLoad->setOperand(3, &EVL);
2988 return NewLoad;
2989 }
2990
2991 VPValue *StoredVal;
2992 if (match(&CurRecipe, m_MaskedStore(m_VPValue(Addr), m_VPValue(StoredVal),
2993 m_RemoveMask(HeaderMask, Mask))))
2994 return new VPWidenStoreEVLRecipe(cast<VPWidenStoreRecipe>(CurRecipe), Addr,
2995 StoredVal, EVL, Mask);
2996
2997 if (match(&CurRecipe,
2998 m_MaskedStore(m_VPValue(EndPtr), m_Reverse(m_VPValue(ReversedVal)),
2999 m_Reverse(m_RemoveMask(HeaderMask, Mask)))) &&
3000 match(EndPtr, m_VecEndPtr(m_VPValue(), m_Specific(&Plan->getVF())))) {
3001 Mask = GetVPReverse(Mask);
3002 Addr = AdjustEndPtr(EndPtr);
3003 StoredVal = GetVPReverse(ReversedVal);
3004 return new VPWidenStoreEVLRecipe(cast<VPWidenStoreRecipe>(CurRecipe), Addr,
3005 StoredVal, EVL, Mask);
3006 }
3007
3008 if (auto *Rdx = dyn_cast<VPReductionRecipe>(&CurRecipe))
3009 if (Rdx->isConditional() &&
3010 match(Rdx->getCondOp(), m_RemoveMask(HeaderMask, Mask)))
3011 return new VPReductionEVLRecipe(*Rdx, EVL, Mask);
3012
3013 if (auto *Interleave = dyn_cast<VPInterleaveRecipe>(&CurRecipe))
3014 if (Interleave->getMask() &&
3015 match(Interleave->getMask(), m_RemoveMask(HeaderMask, Mask)))
3016 return new VPInterleaveEVLRecipe(*Interleave, EVL, Mask);
3017
3018 VPValue *LHS, *RHS;
3019 if (match(&CurRecipe,
3020 m_Select(m_Specific(HeaderMask), m_VPValue(LHS), m_VPValue(RHS))))
3021 return new VPWidenIntrinsicRecipe(
3022 Intrinsic::vp_merge, {Plan->getTrue(), LHS, RHS, &EVL},
3023 TypeInfo.inferScalarType(LHS), {}, {}, DL);
3024
3025 if (match(&CurRecipe, m_Select(m_RemoveMask(HeaderMask, Mask), m_VPValue(LHS),
3026 m_VPValue(RHS))))
3027 return new VPWidenIntrinsicRecipe(
3028 Intrinsic::vp_merge, {Mask, LHS, RHS, &EVL},
3029 TypeInfo.inferScalarType(LHS), {}, {}, DL);
3030
3031 if (match(&CurRecipe, m_LastActiveLane(m_Specific(HeaderMask)))) {
3032 Type *Ty = TypeInfo.inferScalarType(CurRecipe.getVPSingleValue());
3033 VPValue *ZExt = VPBuilder(&CurRecipe)
3035 &EVL, Ty, TypeInfo.inferScalarType(&EVL), DL);
3036 return new VPInstruction(
3037 Instruction::Sub, {ZExt, Plan->getConstantInt(Ty, 1)},
3038 VPIRFlags::getDefaultFlags(Instruction::Sub), {}, DL);
3039 }
3040
3041 // lhs | (headermask && rhs) -> vp.merge rhs, true, lhs, evl
3042 if (match(&CurRecipe,
3044 m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(RHS)))))
3045 return new VPWidenIntrinsicRecipe(
3046 Intrinsic::vp_merge, {RHS, Plan->getTrue(), LHS, &EVL},
3047 TypeInfo.inferScalarType(LHS), {}, {}, DL);
3048
3049 if (auto *IntrR = dyn_cast<VPWidenIntrinsicRecipe>(&CurRecipe))
3050 if (auto VPID = getVPDivRemIntrinsic(IntrR->getVectorIntrinsicID()))
3051 if (match(IntrR->getOperand(2), m_RemoveMask(HeaderMask, Mask)))
3052 return new VPWidenIntrinsicRecipe(*VPID,
3053 {IntrR->getOperand(0),
3054 IntrR->getOperand(1),
3055 Mask ? Mask : Plan->getTrue(), &EVL},
3056 IntrR->getScalarType(), {}, {}, DL);
3057
3058 return nullptr;
3059}
3060
3061/// Optimize away any EVL-based header masks to VP intrinsic based recipes.
3062/// The transforms here need to preserve the original semantics.
3064 // Find the EVL-based header mask if it exists: icmp ult step-vector, EVL
3065 VPValue *HeaderMask = nullptr, *EVL = nullptr;
3068 m_VPValue(EVL))) &&
3069 match(EVL, m_EVL(m_VPValue()))) {
3070 HeaderMask = R.getVPSingleValue();
3071 break;
3072 }
3073 }
3074 if (!HeaderMask)
3075 return;
3076
3077 VPTypeAnalysis TypeInfo(Plan);
3078 SmallVector<VPRecipeBase *> OldRecipes;
3079 for (VPUser *U : collectUsersRecursively(HeaderMask)) {
3081 if (auto *NewR = optimizeMaskToEVL(HeaderMask, *R, TypeInfo, *EVL)) {
3082 NewR->insertBefore(R);
3083 for (auto [Old, New] :
3084 zip_equal(R->definedValues(), NewR->definedValues()))
3085 Old->replaceAllUsesWith(New);
3086 OldRecipes.push_back(R);
3087 }
3088 }
3089
3090 // Replace remaining (HeaderMask && Mask) with vp.merge (True, Mask,
3091 // False, EVL)
3092 for (VPUser *U : collectUsersRecursively(HeaderMask)) {
3093 VPValue *Mask;
3094 if (match(U, m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(Mask)))) {
3095 auto *LogicalAnd = cast<VPInstruction>(U);
3096 auto *Merge = new VPWidenIntrinsicRecipe(
3097 Intrinsic::vp_merge, {Plan.getTrue(), Mask, Plan.getFalse(), EVL},
3098 TypeInfo.inferScalarType(Mask), {}, {}, LogicalAnd->getDebugLoc());
3099 Merge->insertBefore(LogicalAnd);
3100 LogicalAnd->replaceAllUsesWith(Merge);
3101 OldRecipes.push_back(LogicalAnd);
3102 }
3103 }
3104
3105 // Erase old recipes at the end so we don't invalidate TypeInfo.
3106 for (VPRecipeBase *R : reverse(OldRecipes)) {
3107 SmallVector<VPValue *> PossiblyDead(R->operands());
3108 R->eraseFromParent();
3109 for (VPValue *Op : PossiblyDead)
3111 }
3112}
3113
3114/// After replacing the canonical IV with a EVL-based IV, fixup recipes that use
3115/// VF to use the EVL instead to avoid incorrect updates on the penultimate
3116/// iteration.
3117static void fixupVFUsersForEVL(VPlan &Plan, VPValue &EVL) {
3118 VPTypeAnalysis TypeInfo(Plan);
3119 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
3120 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
3121
3122 assert(all_of(Plan.getVF().users(),
3123 [&Plan](VPUser *U) {
3124 auto IsAllowedUser =
3125 IsaPred<VPVectorEndPointerRecipe, VPScalarIVStepsRecipe,
3126 VPWidenIntOrFpInductionRecipe,
3127 VPWidenMemIntrinsicRecipe>;
3128 if (match(U, m_Trunc(m_Specific(&Plan.getVF()))))
3129 return all_of(cast<VPSingleDefRecipe>(U)->users(),
3130 IsAllowedUser);
3131 return IsAllowedUser(U);
3132 }) &&
3133 "User of VF that we can't transform to EVL.");
3134 Plan.getVF().replaceUsesWithIf(&EVL, [](VPUser &U, unsigned Idx) {
3136 });
3137
3138 assert(all_of(Plan.getVFxUF().users(),
3140 m_c_Add(m_Specific(LoopRegion->getCanonicalIV()),
3141 m_Specific(&Plan.getVFxUF())),
3143 "Only users of VFxUF should be VPWidenPointerInductionRecipe and the "
3144 "increment of the canonical induction.");
3145 Plan.getVFxUF().replaceUsesWithIf(&EVL, [](VPUser &U, unsigned Idx) {
3146 // Only replace uses in VPWidenPointerInductionRecipe; The increment of the
3147 // canonical induction must not be updated.
3149 });
3150
3151 // Create a scalar phi to track the previous EVL if fixed-order recurrence is
3152 // contained.
3153 bool ContainsFORs =
3155 if (ContainsFORs) {
3156 // TODO: Use VPInstruction::ExplicitVectorLength to get maximum EVL.
3157 VPValue *MaxEVL = &Plan.getVF();
3158 // Emit VPScalarCastRecipe in preheader if VF is not a 32 bits integer.
3159 VPBuilder Builder(LoopRegion->getPreheaderVPBB());
3160 MaxEVL = Builder.createScalarZExtOrTrunc(
3161 MaxEVL, Type::getInt32Ty(Plan.getContext()),
3162 TypeInfo.inferScalarType(MaxEVL), DebugLoc::getUnknown());
3163
3164 Builder.setInsertPoint(Header, Header->getFirstNonPhi());
3165 VPValue *PrevEVL = Builder.createScalarPhi(
3166 {MaxEVL, &EVL}, DebugLoc::getUnknown(), "prev.evl");
3167
3170 for (VPRecipeBase &R : *VPBB) {
3171 VPValue *V1, *V2;
3172 if (!match(&R,
3174 m_VPValue(V1), m_VPValue(V2))))
3175 continue;
3176 VPValue *Imm = Plan.getOrAddLiveIn(
3179 Intrinsic::experimental_vp_splice,
3180 {V1, V2, Imm, Plan.getTrue(), PrevEVL, &EVL},
3181 TypeInfo.inferScalarType(R.getVPSingleValue()), {}, {},
3182 R.getDebugLoc());
3183 VPSplice->insertBefore(&R);
3184 R.getVPSingleValue()->replaceAllUsesWith(VPSplice);
3185 }
3186 }
3187 }
3188
3189 VPValue *HeaderMask = vputils::findHeaderMask(Plan);
3190 if (!HeaderMask)
3191 return;
3192
3193 // Ensure that any reduction that uses a select to mask off tail lanes does so
3194 // in the vector loop, not the middle block, since EVL tail folding can have
3195 // tail elements in the penultimate iteration.
3196 assert(all_of(*Plan.getMiddleBlock(), [&Plan, HeaderMask](VPRecipeBase &R) {
3197 if (match(&R, m_ComputeReductionResult(m_Select(m_Specific(HeaderMask),
3198 m_VPValue(), m_VPValue()))))
3199 return R.getOperand(0)->getDefiningRecipe()->getRegion() ==
3200 Plan.getVectorLoopRegion();
3201 return true;
3202 }));
3203
3204 // Replace header masks with a mask equivalent to predicating by EVL:
3205 //
3206 // icmp ule widen-canonical-iv backedge-taken-count
3207 // ->
3208 // icmp ult step-vector, EVL
3209 VPRecipeBase *EVLR = EVL.getDefiningRecipe();
3210 VPBuilder Builder(EVLR->getParent(), std::next(EVLR->getIterator()));
3211 Type *EVLType = TypeInfo.inferScalarType(&EVL);
3212 VPValue *EVLMask = Builder.createICmp(
3214 Builder.createNaryOp(VPInstruction::StepVector, {}, EVLType), &EVL);
3215 HeaderMask->replaceAllUsesWith(EVLMask);
3216}
3217
3218/// Converts a tail folded vector loop region to step by
3219/// VPInstruction::ExplicitVectorLength elements instead of VF elements each
3220/// iteration.
3221///
3222/// - Add a VPCurrentIterationPHIRecipe and related recipes to \p Plan and
3223/// replaces all uses of the canonical IV except for the canonical IV
3224/// increment with a VPCurrentIterationPHIRecipe. The canonical IV is used
3225/// only for loop iterations counting after this transformation.
3226///
3227/// - The header mask is replaced with a header mask based on the EVL.
3228///
3229/// - Plans with FORs have a new phi added to keep track of the EVL of the
3230/// previous iteration, and VPFirstOrderRecurrencePHIRecipes are replaced with
3231/// @llvm.vp.splice.
3232///
3233/// The function uses the following definitions:
3234/// %StartV is the canonical induction start value.
3235///
3236/// The function adds the following recipes:
3237///
3238/// vector.ph:
3239/// ...
3240///
3241/// vector.body:
3242/// ...
3243/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
3244/// [ %NextIter, %vector.body ]
3245/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
3246/// %VPEVL = EXPLICIT-VECTOR-LENGTH %AVL
3247/// ...
3248/// %OpEVL = cast i32 %VPEVL to IVSize
3249/// %NextIter = add IVSize %OpEVL, %CurrentIter
3250/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
3251/// ...
3252///
3253/// If MaxSafeElements is provided, the function adds the following recipes:
3254/// vector.ph:
3255/// ...
3256///
3257/// vector.body:
3258/// ...
3259/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
3260/// [ %NextIter, %vector.body ]
3261/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
3262/// %cmp = cmp ult %AVL, MaxSafeElements
3263/// %SAFE_AVL = select %cmp, %AVL, MaxSafeElements
3264/// %VPEVL = EXPLICIT-VECTOR-LENGTH %SAFE_AVL
3265/// ...
3266/// %OpEVL = cast i32 %VPEVL to IVSize
3267/// %NextIter = add IVSize %OpEVL, %CurrentIter
3268/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
3269/// ...
3270///
3272 VPlan &Plan, const std::optional<unsigned> &MaxSafeElements) {
3273 if (Plan.hasScalarVFOnly())
3274 return;
3275 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
3276 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
3277
3278 auto *CanonicalIV = LoopRegion->getCanonicalIV();
3279 auto *CanIVTy = LoopRegion->getCanonicalIVType();
3280 VPValue *StartV = Plan.getZero(CanIVTy);
3281 auto *CanonicalIVIncrement = LoopRegion->getOrCreateCanonicalIVIncrement();
3282
3283 // Create the CurrentIteration recipe in the vector loop.
3284 auto *CurrentIteration =
3286 CurrentIteration->insertBefore(*Header, Header->begin());
3287 VPBuilder Builder(Header, Header->getFirstNonPhi());
3288 // Create the AVL (application vector length), starting from TC -> 0 in steps
3289 // of EVL.
3290 VPPhi *AVLPhi = Builder.createScalarPhi(
3291 {Plan.getTripCount()}, DebugLoc::getCompilerGenerated(), "avl");
3292 VPValue *AVL = AVLPhi;
3293
3294 if (MaxSafeElements) {
3295 // Support for MaxSafeDist for correct loop emission.
3296 VPValue *AVLSafe = Plan.getConstantInt(CanIVTy, *MaxSafeElements);
3297 VPValue *Cmp = Builder.createICmp(ICmpInst::ICMP_ULT, AVL, AVLSafe);
3298 AVL = Builder.createSelect(Cmp, AVL, AVLSafe, DebugLoc::getUnknown(),
3299 "safe_avl");
3300 }
3301 auto *VPEVL = Builder.createNaryOp(VPInstruction::ExplicitVectorLength, AVL,
3302 DebugLoc::getUnknown(), "evl");
3303
3304 Builder.setInsertPoint(CanonicalIVIncrement);
3305 VPValue *OpVPEVL = VPEVL;
3306
3307 auto *I32Ty = Type::getInt32Ty(Plan.getContext());
3308 OpVPEVL = Builder.createScalarZExtOrTrunc(
3309 OpVPEVL, CanIVTy, I32Ty, CanonicalIVIncrement->getDebugLoc());
3310
3311 auto *NextIter = Builder.createAdd(
3312 OpVPEVL, CurrentIteration, CanonicalIVIncrement->getDebugLoc(),
3313 "current.iteration.next", CanonicalIVIncrement->getNoWrapFlags());
3314 CurrentIteration->addOperand(NextIter);
3315
3316 VPValue *NextAVL =
3317 Builder.createSub(AVLPhi, OpVPEVL, DebugLoc::getCompilerGenerated(),
3318 "avl.next", {/*NUW=*/true, /*NSW=*/false});
3319 AVLPhi->addOperand(NextAVL);
3320
3321 fixupVFUsersForEVL(Plan, *VPEVL);
3322 removeDeadRecipes(Plan);
3323
3324 // Replace all uses of the canonical IV with VPCurrentIterationPHIRecipe
3325 // except for the canonical IV increment.
3326 CanonicalIV->replaceAllUsesWith(CurrentIteration);
3327 CanonicalIVIncrement->setOperand(0, CanonicalIV);
3328 // TODO: support unroll factor > 1.
3329 Plan.setUF(1);
3330}
3331
3333 // Find the vector loop entry by locating VPCurrentIterationPHIRecipe.
3334 // There should be only one VPCurrentIteration in the entire plan.
3335 VPCurrentIterationPHIRecipe *CurrentIteration = nullptr;
3336
3339 for (VPRecipeBase &R : VPBB->phis())
3340 if (auto *PhiR = dyn_cast<VPCurrentIterationPHIRecipe>(&R)) {
3341 assert(!CurrentIteration &&
3342 "Found multiple CurrentIteration. Only one expected");
3343 CurrentIteration = PhiR;
3344 }
3345
3346 // Early return if it is not variable-length stepping.
3347 if (!CurrentIteration)
3348 return;
3349
3350 VPBasicBlock *HeaderVPBB = CurrentIteration->getParent();
3351 VPValue *CurrentIterationIncr = CurrentIteration->getBackedgeValue();
3352
3353 // Convert CurrentIteration to concrete recipe.
3354 auto *ScalarR =
3355 VPBuilder(CurrentIteration)
3357 {CurrentIteration->getStartValue(), CurrentIterationIncr},
3358 CurrentIteration->getDebugLoc(), "current.iteration.iv");
3359 CurrentIteration->replaceAllUsesWith(ScalarR);
3360 CurrentIteration->eraseFromParent();
3361
3362 // Replace CanonicalIVInc with CurrentIteration increment if it exists.
3363 auto *CanonicalIV = cast<VPPhi>(&*HeaderVPBB->begin());
3364 if (auto *CanIVInc = vputils::findUserOf(
3365 CanonicalIV, m_c_Add(m_VPValue(), m_Specific(&Plan.getVFxUF())))) {
3366 cast<VPInstruction>(CanIVInc)->replaceAllUsesWith(CurrentIterationIncr);
3367 CanIVInc->eraseFromParent();
3368 }
3369}
3370
3372 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
3373 if (!LoopRegion)
3374 return;
3375 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
3376 if (Header->empty())
3377 return;
3378 // The EVL IV is always at the beginning.
3379 auto *EVLPhi = dyn_cast<VPCurrentIterationPHIRecipe>(&Header->front());
3380 if (!EVLPhi)
3381 return;
3382
3383 // Bail if not an EVL tail folded loop.
3384 VPValue *AVL;
3385 if (!match(EVLPhi->getBackedgeValue(),
3386 m_c_Add(m_ZExtOrSelf(m_EVL(m_VPValue(AVL))), m_Specific(EVLPhi))))
3387 return;
3388
3389 // The AVL may be capped to a safe distance.
3390 VPValue *SafeAVL, *UnsafeAVL;
3391 if (match(AVL,
3393 m_VPValue(SafeAVL)),
3394 m_Deferred(UnsafeAVL), m_Deferred(SafeAVL))))
3395 AVL = UnsafeAVL;
3396
3397 VPValue *AVLNext;
3398 [[maybe_unused]] bool FoundAVLNext =
3400 m_Specific(Plan.getTripCount()), m_VPValue(AVLNext)));
3401 assert(FoundAVLNext && "Didn't find AVL backedge?");
3402
3403 VPBasicBlock *Latch = LoopRegion->getExitingBasicBlock();
3404 auto *LatchBr = cast<VPInstruction>(Latch->getTerminator());
3405 if (match(LatchBr, m_BranchOnCond(m_True())))
3406 return;
3407
3408 VPValue *CanIVInc;
3409 [[maybe_unused]] bool FoundIncrement = match(
3410 LatchBr,
3412 m_Specific(&Plan.getVectorTripCount()))));
3413 assert(FoundIncrement &&
3414 match(CanIVInc, m_Add(m_Specific(LoopRegion->getCanonicalIV()),
3415 m_Specific(&Plan.getVFxUF()))) &&
3416 "Expected BranchOnCond with ICmp comparing CanIV + VFxUF with vector "
3417 "trip count");
3418
3419 Type *AVLTy = VPTypeAnalysis(Plan).inferScalarType(AVLNext);
3420 VPBuilder Builder(LatchBr);
3421 LatchBr->setOperand(
3422 0, Builder.createICmp(CmpInst::ICMP_EQ, AVLNext, Plan.getZero(AVLTy)));
3423}
3424
3426 VPlan &Plan, PredicatedScalarEvolution &PSE,
3427 const DenseMap<Value *, const SCEV *> &StridesMap) {
3428 // Replace VPValues for known constant strides guaranteed by predicated scalar
3429 // evolution that are guaranteed to be guarded by the runtime checks; that is,
3430 // blocks dominated by the vector preheader.
3431 assert(!Plan.getVectorLoopRegion() &&
3432 "expected to run before loop regions are created");
3433 VPDominatorTree VPDT(Plan);
3434 VPBlockBase *Preheader = Plan.getEntry()->getSuccessors()[1];
3435 auto CanUseVersionedStride = [&VPDT, Preheader](VPUser &U, unsigned) {
3436 auto *R = cast<VPRecipeBase>(&U);
3437 VPBlockBase *Parent = R->getParent();
3438 return VPDT.dominates(Preheader, Parent);
3439 };
3440 ValueToSCEVMapTy RewriteMap;
3441 for (const SCEV *Stride : StridesMap.values()) {
3442 using namespace SCEVPatternMatch;
3443 auto *StrideV = cast<SCEVUnknown>(Stride)->getValue();
3444 const APInt *StrideConst;
3445 if (!match(PSE.getSCEV(StrideV), m_scev_APInt(StrideConst)))
3446 // Only handle constant strides for now.
3447 continue;
3448
3449 auto *CI = Plan.getConstantInt(*StrideConst);
3450 if (VPValue *StrideVPV = Plan.getLiveIn(StrideV))
3451 StrideVPV->replaceUsesWithIf(CI, CanUseVersionedStride);
3452
3453 // The versioned value may not be used in the loop directly but through a
3454 // sext/zext. Add new live-ins in those cases.
3455 for (Value *U : StrideV->users()) {
3457 continue;
3458 VPValue *StrideVPV = Plan.getLiveIn(U);
3459 if (!StrideVPV)
3460 continue;
3461 unsigned BW = U->getType()->getScalarSizeInBits();
3462 APInt C =
3463 isa<SExtInst>(U) ? StrideConst->sext(BW) : StrideConst->zext(BW);
3464 VPValue *CI = Plan.getConstantInt(C);
3465 StrideVPV->replaceUsesWithIf(CI, CanUseVersionedStride);
3466 }
3467 RewriteMap[StrideV] = PSE.getSCEV(StrideV);
3468 }
3469
3470 for (VPRecipeBase &R : *Plan.getEntry()) {
3471 auto *ExpSCEV = dyn_cast<VPExpandSCEVRecipe>(&R);
3472 if (!ExpSCEV)
3473 continue;
3474 const SCEV *ScevExpr = ExpSCEV->getSCEV();
3475 auto *NewSCEV =
3476 SCEVParameterRewriter::rewrite(ScevExpr, *PSE.getSE(), RewriteMap);
3477 if (NewSCEV != ScevExpr) {
3478 VPValue *NewExp = vputils::getOrCreateVPValueForSCEVExpr(Plan, NewSCEV);
3479 ExpSCEV->replaceAllUsesWith(NewExp);
3480 if (Plan.getTripCount() == ExpSCEV)
3481 Plan.resetTripCount(NewExp);
3482 }
3483 }
3484}
3485
3487 // Collect recipes in the backward slice of `Root` that may generate a poison
3488 // value that is used after vectorization.
3490 auto CollectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
3492 Worklist.push_back(Root);
3493
3494 // Traverse the backward slice of Root through its use-def chain.
3495 while (!Worklist.empty()) {
3496 VPRecipeBase *CurRec = Worklist.pop_back_val();
3497
3498 if (!Visited.insert(CurRec).second)
3499 continue;
3500
3501 // Prune search if we find another recipe generating a widen memory
3502 // instruction. Widen memory instructions involved in address computation
3503 // will lead to gather/scatter instructions, which don't need to be
3504 // handled.
3506 VPHeaderPHIRecipe>(CurRec))
3507 continue;
3508
3509 // This recipe contributes to the address computation of a widen
3510 // load/store. If the underlying instruction has poison-generating flags,
3511 // drop them directly.
3512 if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(CurRec)) {
3513 VPValue *A, *B;
3514 // Dropping disjoint from an OR may yield incorrect results, as some
3515 // analysis may have converted it to an Add implicitly (e.g. SCEV used
3516 // for dependence analysis). Instead, replace it with an equivalent Add.
3517 // This is possible as all users of the disjoint OR only access lanes
3518 // where the operands are disjoint or poison otherwise.
3519 if (match(RecWithFlags, m_BinaryOr(m_VPValue(A), m_VPValue(B))) &&
3520 RecWithFlags->isDisjoint()) {
3521 VPBuilder Builder(RecWithFlags);
3522 VPInstruction *New =
3523 Builder.createAdd(A, B, RecWithFlags->getDebugLoc());
3524 New->setUnderlyingValue(RecWithFlags->getUnderlyingValue());
3525 RecWithFlags->replaceAllUsesWith(New);
3526 RecWithFlags->eraseFromParent();
3527 CurRec = New;
3528 } else
3529 RecWithFlags->dropPoisonGeneratingFlags();
3530 } else {
3533 (void)Instr;
3534 assert((!Instr || !Instr->hasPoisonGeneratingFlags()) &&
3535 "found instruction with poison generating flags not covered by "
3536 "VPRecipeWithIRFlags");
3537 }
3538
3539 // Add new definitions to the worklist.
3540 for (VPValue *Operand : CurRec->operands())
3541 if (VPRecipeBase *OpDef = Operand->getDefiningRecipe())
3542 Worklist.push_back(OpDef);
3543 }
3544 });
3545
3546 // We want to exclude the tail folding case, as we don't need to drop flags
3547 // for operations computing the first lane in this case: the first lane of the
3548 // header mask must always be true.
3549 auto IsNotHeaderMask = [&Plan](VPValue *Mask) {
3550 return Mask && !vputils::isHeaderMask(Mask, Plan);
3551 };
3552
3553 // Traverse all the recipes in the VPlan and collect the poison-generating
3554 // recipes in the backward slice starting at the address of a VPWidenRecipe or
3555 // VPInterleaveRecipe.
3556 auto Iter =
3559 for (VPRecipeBase &Recipe : *VPBB) {
3560 if (auto *WidenRec = dyn_cast<VPWidenMemoryRecipe>(&Recipe)) {
3561 VPRecipeBase *AddrDef = WidenRec->getAddr()->getDefiningRecipe();
3562 if (AddrDef && WidenRec->isConsecutive() &&
3563 IsNotHeaderMask(WidenRec->getMask()))
3564 CollectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
3565 } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
3566 VPRecipeBase *AddrDef = InterleaveRec->getAddr()->getDefiningRecipe();
3567 if (AddrDef && IsNotHeaderMask(InterleaveRec->getMask()))
3568 CollectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
3569 }
3570 }
3571 }
3572}
3573
3575 VPlan &Plan,
3577 &InterleaveGroups,
3578 const bool &EpilogueAllowed) {
3579 if (InterleaveGroups.empty())
3580 return;
3581
3583 for (VPBasicBlock *VPBB :
3586 for (VPRecipeBase &R : make_filter_range(*VPBB, [](VPRecipeBase &R) {
3587 return isa<VPWidenMemoryRecipe>(&R);
3588 })) {
3589 auto *MemR = cast<VPWidenMemoryRecipe>(&R);
3590 IRMemberToRecipe[&MemR->getIngredient()] = MemR;
3591 }
3592
3593 // Interleave memory: for each Interleave Group we marked earlier as relevant
3594 // for this VPlan, replace the Recipes widening its memory instructions with a
3595 // single VPInterleaveRecipe at its insertion point.
3596 VPDominatorTree VPDT(Plan);
3597 for (const auto *IG : InterleaveGroups) {
3598 // Skip interleave groups where members don't have recipes. This can happen
3599 // when removeDeadRecipes removes recipes that are part of interleave groups
3600 // but have no users.
3601 if (llvm::any_of(IG->members(), [&IRMemberToRecipe](Instruction *Member) {
3602 return !IRMemberToRecipe.contains(Member);
3603 }))
3604 continue;
3605
3606 auto *Start = IRMemberToRecipe.lookup(IG->getMember(0));
3607 VPIRMetadata InterleaveMD(*Start);
3608 SmallVector<VPValue *, 4> StoredValues;
3609 if (auto *StoreR = dyn_cast<VPWidenStoreRecipe>(Start->getAsRecipe()))
3610 StoredValues.push_back(StoreR->getStoredValue());
3611 for (unsigned I = 1; I < IG->getFactor(); ++I) {
3612 Instruction *MemberI = IG->getMember(I);
3613 if (!MemberI)
3614 continue;
3615 VPWidenMemoryRecipe *MemoryR = IRMemberToRecipe.lookup(MemberI);
3616 if (auto *StoreR = dyn_cast<VPWidenStoreRecipe>(MemoryR->getAsRecipe()))
3617 StoredValues.push_back(StoreR->getStoredValue());
3618 InterleaveMD.intersect(*MemoryR);
3619 }
3620
3621 bool NeedsMaskForGaps =
3622 (IG->requiresScalarEpilogue() && !EpilogueAllowed) ||
3623 (!StoredValues.empty() && !IG->isFull());
3624
3625 Instruction *IRInsertPos = IG->getInsertPos();
3626 auto *InsertPos = IRMemberToRecipe.lookup(IRInsertPos);
3627 VPRecipeBase *InsertPosR = InsertPos->getAsRecipe();
3628
3630 if (auto *Gep = dyn_cast<GetElementPtrInst>(
3631 getLoadStorePointerOperand(IRInsertPos)->stripPointerCasts()))
3632 NW = Gep->getNoWrapFlags().withoutNoUnsignedWrap();
3633
3634 // Get or create the start address for the interleave group.
3635 VPValue *Addr = Start->getAddr();
3636 VPRecipeBase *AddrDef = Addr->getDefiningRecipe();
3637 if (AddrDef && !VPDT.properlyDominates(AddrDef, InsertPosR)) {
3638 // We cannot re-use the address of member zero because it does not
3639 // dominate the insert position. Instead, use the address of the insert
3640 // position and create a PtrAdd adjusting it to the address of member
3641 // zero.
3642 // TODO: Hoist Addr's defining recipe (and any operands as needed) to
3643 // InsertPos or sink loads above zero members to join it.
3644 assert(IG->getIndex(IRInsertPos) != 0 &&
3645 "index of insert position shouldn't be zero");
3646 auto &DL = IRInsertPos->getDataLayout();
3647 APInt Offset(32,
3648 DL.getTypeAllocSize(getLoadStoreType(IRInsertPos)) *
3649 IG->getIndex(IRInsertPos),
3650 /*IsSigned=*/true);
3651 VPValue *OffsetVPV = Plan.getConstantInt(-Offset);
3652 VPBuilder B(InsertPosR);
3653 Addr = B.createNoWrapPtrAdd(InsertPos->getAddr(), OffsetVPV, NW);
3654 }
3655 // If the group is reverse, adjust the index to refer to the last vector
3656 // lane instead of the first. We adjust the index from the first vector
3657 // lane, rather than directly getting the pointer for lane VF - 1, because
3658 // the pointer operand of the interleaved access is supposed to be uniform.
3659 if (IG->isReverse()) {
3660 auto *ReversePtr = new VPVectorEndPointerRecipe(
3661 Addr, &Plan.getVF(), getLoadStoreType(IRInsertPos),
3662 -(int64_t)IG->getFactor(), NW, InsertPosR->getDebugLoc());
3663 ReversePtr->insertBefore(InsertPosR);
3664 Addr = ReversePtr;
3665 }
3666 auto *VPIG = new VPInterleaveRecipe(
3667 IG, Addr, StoredValues, InsertPos->getMask(), NeedsMaskForGaps,
3668 InterleaveMD, InsertPosR->getDebugLoc());
3669 VPIG->insertBefore(InsertPosR);
3670
3671 unsigned J = 0;
3672 for (unsigned i = 0; i < IG->getFactor(); ++i)
3673 if (Instruction *Member = IG->getMember(i)) {
3674 VPRecipeBase *MemberR = IRMemberToRecipe.lookup(Member)->getAsRecipe();
3675 if (!Member->getType()->isVoidTy()) {
3676 VPValue *OriginalV = MemberR->getVPSingleValue();
3677 OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
3678 J++;
3679 }
3680 MemberR->eraseFromParent();
3681 }
3682 }
3683}
3684
3685/// Expand a VPWidenIntOrFpInduction into executable recipes, for the initial
3686/// value, phi and backedge value. In the following example:
3687///
3688/// vector.ph:
3689/// Successor(s): vector loop
3690///
3691/// <x1> vector loop: {
3692/// vector.body:
3693/// WIDEN-INDUCTION %i = phi %start, %step, %vf
3694/// ...
3695/// EMIT branch-on-count ...
3696/// No successors
3697/// }
3698///
3699/// WIDEN-INDUCTION will get expanded to:
3700///
3701/// vector.ph:
3702/// ...
3703/// vp<%induction.start> = ...
3704/// vp<%induction.increment> = ...
3705///
3706/// Successor(s): vector loop
3707///
3708/// <x1> vector loop: {
3709/// vector.body:
3710/// ir<%i> = WIDEN-PHI vp<%induction.start>, vp<%vec.ind.next>
3711/// ...
3712/// vp<%vec.ind.next> = add ir<%i>, vp<%induction.increment>
3713/// EMIT branch-on-count ...
3714/// No successors
3715/// }
3716static void
3718 VPTypeAnalysis &TypeInfo) {
3719 VPlan *Plan = WidenIVR->getParent()->getPlan();
3720 VPValue *Start = WidenIVR->getStartValue();
3721 VPValue *Step = WidenIVR->getStepValue();
3722 VPValue *VF = WidenIVR->getVFValue();
3723 DebugLoc DL = WidenIVR->getDebugLoc();
3724
3725 // The value from the original loop to which we are mapping the new induction
3726 // variable.
3727 Type *Ty = TypeInfo.inferScalarType(WidenIVR);
3728
3729 const InductionDescriptor &ID = WidenIVR->getInductionDescriptor();
3732 VPIRFlags Flags = *WidenIVR;
3733 if (ID.getKind() == InductionDescriptor::IK_IntInduction) {
3734 AddOp = Instruction::Add;
3735 MulOp = Instruction::Mul;
3736 } else {
3737 AddOp = ID.getInductionOpcode();
3738 MulOp = Instruction::FMul;
3739 }
3740
3741 // If the phi is truncated, truncate the start and step values.
3742 VPBuilder Builder(Plan->getVectorPreheader());
3743 Type *StepTy = TypeInfo.inferScalarType(Step);
3744 if (Ty->getScalarSizeInBits() < StepTy->getScalarSizeInBits()) {
3745 assert(StepTy->isIntegerTy() && "Truncation requires an integer type");
3746 Step = Builder.createScalarCast(Instruction::Trunc, Step, Ty, DL);
3747 Start = Builder.createScalarCast(Instruction::Trunc, Start, Ty, DL);
3748 StepTy = Ty;
3749 }
3750
3751 // Construct the initial value of the vector IV in the vector loop preheader.
3752 Type *IVIntTy =
3754 VPValue *Init = Builder.createNaryOp(VPInstruction::StepVector, {}, IVIntTy);
3755 if (StepTy->isFloatingPointTy())
3756 Init = Builder.createWidenCast(Instruction::UIToFP, Init, StepTy);
3757
3758 VPValue *SplatStart = Builder.createNaryOp(VPInstruction::Broadcast, Start);
3759 VPValue *SplatStep = Builder.createNaryOp(VPInstruction::Broadcast, Step);
3760
3761 Init = Builder.createNaryOp(MulOp, {Init, SplatStep}, Flags);
3762 Init = Builder.createNaryOp(AddOp, {SplatStart, Init}, Flags,
3763 DebugLoc::getUnknown(), "induction");
3764
3765 // Create the widened phi of the vector IV.
3766 auto *WidePHI = VPBuilder(WidenIVR).createWidenPhi(
3767 Init, WidenIVR->getDebugLoc(), "vec.ind");
3768
3769 // Create the backedge value for the vector IV.
3770 VPValue *Inc;
3771 VPValue *Prev;
3772 // If unrolled, use the increment and prev value from the operands.
3773 if (auto *SplatVF = WidenIVR->getSplatVFValue()) {
3774 Inc = SplatVF;
3775 Prev = WidenIVR->getLastUnrolledPartOperand();
3776 } else {
3777 if (VPRecipeBase *R = VF->getDefiningRecipe())
3778 Builder.setInsertPoint(R->getParent(), std::next(R->getIterator()));
3779 // Multiply the vectorization factor by the step using integer or
3780 // floating-point arithmetic as appropriate.
3781 if (StepTy->isFloatingPointTy())
3782 VF = Builder.createScalarCast(Instruction::CastOps::UIToFP, VF, StepTy,
3783 DL);
3784 else
3785 VF = Builder.createScalarZExtOrTrunc(VF, StepTy,
3786 TypeInfo.inferScalarType(VF), DL);
3787
3788 Inc = Builder.createNaryOp(MulOp, {Step, VF}, Flags);
3789 Inc = Builder.createNaryOp(VPInstruction::Broadcast, Inc);
3790 Prev = WidePHI;
3791 }
3792
3794 Builder.setInsertPoint(ExitingBB, ExitingBB->getTerminator()->getIterator());
3795 auto *Next = Builder.createNaryOp(AddOp, {Prev, Inc}, Flags,
3796 WidenIVR->getDebugLoc(), "vec.ind.next");
3797
3798 WidePHI->addOperand(Next);
3799
3800 WidenIVR->replaceAllUsesWith(WidePHI);
3801}
3802
3803/// Expand a VPWidenPointerInductionRecipe into executable recipes, for the
3804/// initial value, phi and backedge value. In the following example:
3805///
3806/// <x1> vector loop: {
3807/// vector.body:
3808/// EMIT ir<%ptr.iv> = WIDEN-POINTER-INDUCTION %start, %step, %vf
3809/// ...
3810/// EMIT branch-on-count ...
3811/// }
3812///
3813/// WIDEN-POINTER-INDUCTION will get expanded to:
3814///
3815/// <x1> vector loop: {
3816/// vector.body:
3817/// EMIT-SCALAR %pointer.phi = phi %start, %ptr.ind
3818/// EMIT %mul = mul %stepvector, %step
3819/// EMIT %vector.gep = wide-ptradd %pointer.phi, %mul
3820/// ...
3821/// EMIT %ptr.ind = ptradd %pointer.phi, %vf
3822/// EMIT branch-on-count ...
3823/// }
3825 VPTypeAnalysis &TypeInfo) {
3826 VPlan *Plan = R->getParent()->getPlan();
3827 VPValue *Start = R->getStartValue();
3828 VPValue *Step = R->getStepValue();
3829 VPValue *VF = R->getVFValue();
3830
3831 assert(R->getInductionDescriptor().getKind() ==
3833 "Not a pointer induction according to InductionDescriptor!");
3834 assert(TypeInfo.inferScalarType(R)->isPointerTy() && "Unexpected type.");
3835 assert(!R->onlyScalarsGenerated(Plan->hasScalableVF()) &&
3836 "Recipe should have been replaced");
3837
3838 VPBuilder Builder(R);
3839 DebugLoc DL = R->getDebugLoc();
3840
3841 // Build a scalar pointer phi.
3842 VPPhi *ScalarPtrPhi = Builder.createScalarPhi(Start, DL, "pointer.phi");
3843
3844 // Create actual address geps that use the pointer phi as base and a
3845 // vectorized version of the step value (<step*0, ..., step*N>) as offset.
3846 Builder.setInsertPoint(R->getParent(), R->getParent()->getFirstNonPhi());
3847 Type *StepTy = TypeInfo.inferScalarType(Step);
3848 VPValue *Offset = Builder.createNaryOp(VPInstruction::StepVector, {}, StepTy);
3849 Offset = Builder.createOverflowingOp(Instruction::Mul, {Offset, Step});
3850 VPValue *PtrAdd =
3851 Builder.createWidePtrAdd(ScalarPtrPhi, Offset, DL, "vector.gep");
3852 R->replaceAllUsesWith(PtrAdd);
3853
3854 // Create the backedge value for the scalar pointer phi.
3856 Builder.setInsertPoint(ExitingBB, ExitingBB->getTerminator()->getIterator());
3857 VF = Builder.createScalarZExtOrTrunc(VF, StepTy, TypeInfo.inferScalarType(VF),
3858 DL);
3859 VPValue *Inc = Builder.createOverflowingOp(Instruction::Mul, {Step, VF});
3860
3861 VPValue *InductionGEP =
3862 Builder.createPtrAdd(ScalarPtrPhi, Inc, DL, "ptr.ind");
3863 ScalarPtrPhi->addOperand(InductionGEP);
3864}
3865
3866/// Expand a VPDerivedIVRecipe into executable recipes.
3868 VPBuilder Builder(R);
3869 VPIRValue *Start = R->getStartValue();
3870 VPValue *Step = R->getStepValue();
3871 VPValue *Index = R->getIndex();
3872 Type *StepTy = TypeInfo.inferScalarType(Step);
3873 Type *IndexTy = TypeInfo.inferScalarType(Index);
3874 Index = StepTy->isIntegerTy()
3875 ? Builder.createScalarSExtOrTrunc(
3876 Index, StepTy, IndexTy, DebugLoc::getCompilerGenerated())
3877 : Builder.createScalarCast(Instruction::SIToFP, Index, StepTy,
3879 switch (R->getInductionKind()) {
3881 assert(TypeInfo.inferScalarType(Index) == TypeInfo.inferScalarType(Start) &&
3882 "Index type does not match StartValue type");
3883 return R->replaceAllUsesWith(Builder.createAdd(
3884 Start, Builder.createOverflowingOp(Instruction::Mul, {Index, Step})));
3885 }
3887 return R->replaceAllUsesWith(Builder.createPtrAdd(
3888 Start, Builder.createOverflowingOp(Instruction::Mul, {Index, Step})));
3890 assert(StepTy->isFloatingPointTy() && "Expected FP Step value");
3891 const FPMathOperator *FPBinOp = R->getFPBinOp();
3892 assert(FPBinOp &&
3893 (FPBinOp->getOpcode() == Instruction::FAdd ||
3894 FPBinOp->getOpcode() == Instruction::FSub) &&
3895 "Original BinOp should be defined for FP induction");
3896 FastMathFlags FMF = FPBinOp->getFastMathFlags();
3897 VPValue *FMul = Builder.createNaryOp(Instruction::FMul, {Step, Index}, FMF);
3898 return R->replaceAllUsesWith(
3899 Builder.createNaryOp(FPBinOp->getOpcode(), {Start, FMul}, FMF));
3900 }
3902 return;
3903 }
3904 llvm_unreachable("Unhandled induction kind");
3905}
3906
3908 // Replace loop regions with explicity CFG.
3909 SmallVector<VPRegionBlock *> LoopRegions;
3911 vp_depth_first_deep(Plan.getEntry()))) {
3912 if (!R->isReplicator())
3913 LoopRegions.push_back(R);
3914 }
3915 for (VPRegionBlock *R : LoopRegions)
3916 R->dissolveToCFGLoop();
3917}
3918
3921 // The transform runs after dissolving loop regions, so all VPBasicBlocks
3922 // terminated with BranchOnTwoConds are reached via a shallow traversal.
3925 if (!VPBB->empty() && match(&VPBB->back(), m_BranchOnTwoConds()))
3926 WorkList.push_back(cast<VPInstruction>(&VPBB->back()));
3927 }
3928
3929 // Expand BranchOnTwoConds instructions into explicit CFG with two new
3930 // single-condition branches:
3931 // 1. A branch that replaces BranchOnTwoConds, jumps to the first successor if
3932 // the first condition is true, and otherwise jumps to a new interim block.
3933 // 2. A branch that ends the interim block, jumps to the second successor if
3934 // the second condition is true, and otherwise jumps to the third
3935 // successor.
3936 for (VPInstruction *Br : WorkList) {
3937 assert(Br->getNumOperands() == 2 &&
3938 "BranchOnTwoConds must have exactly 2 conditions");
3939 DebugLoc DL = Br->getDebugLoc();
3940 VPBasicBlock *BrOnTwoCondsBB = Br->getParent();
3941 const auto Successors = to_vector(BrOnTwoCondsBB->getSuccessors());
3942 assert(Successors.size() == 3 &&
3943 "BranchOnTwoConds must have exactly 3 successors");
3944
3945 for (VPBlockBase *Succ : Successors)
3946 VPBlockUtils::disconnectBlocks(BrOnTwoCondsBB, Succ);
3947
3948 VPValue *Cond0 = Br->getOperand(0);
3949 VPValue *Cond1 = Br->getOperand(1);
3950 VPBlockBase *Succ0 = Successors[0];
3951 VPBlockBase *Succ1 = Successors[1];
3952 VPBlockBase *Succ2 = Successors[2];
3953 assert(!Succ0->getParent() && !Succ1->getParent() && !Succ2->getParent() &&
3954 !BrOnTwoCondsBB->getParent() && "regions must already be dissolved");
3955
3956 VPBasicBlock *InterimBB =
3957 Plan.createVPBasicBlock(BrOnTwoCondsBB->getName() + ".interim");
3958
3959 VPBuilder(BrOnTwoCondsBB)
3961 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ0);
3962 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, InterimBB);
3963
3965 VPBlockUtils::connectBlocks(InterimBB, Succ1);
3966 VPBlockUtils::connectBlocks(InterimBB, Succ2);
3967 Br->eraseFromParent();
3968 }
3969}
3970
3972 VPTypeAnalysis TypeInfo(Plan);
3975 vp_depth_first_deep(Plan.getEntry()))) {
3976 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
3977 VPBuilder Builder(&R);
3978 if (auto *WidenIVR = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R)) {
3979 expandVPWidenIntOrFpInduction(WidenIVR, TypeInfo);
3980 ToRemove.push_back(WidenIVR);
3981 continue;
3982 }
3983
3984 if (auto *WidenIVR = dyn_cast<VPWidenPointerInductionRecipe>(&R)) {
3985 // If the recipe only generates scalars, scalarize it instead of
3986 // expanding it.
3987 if (WidenIVR->onlyScalarsGenerated(Plan.hasScalableVF())) {
3988 VPValue *PtrAdd =
3989 scalarizeVPWidenPointerInduction(WidenIVR, Plan, Builder);
3990 WidenIVR->replaceAllUsesWith(PtrAdd);
3991 ToRemove.push_back(WidenIVR);
3992 continue;
3993 }
3994 expandVPWidenPointerInduction(WidenIVR, TypeInfo);
3995 ToRemove.push_back(WidenIVR);
3996 continue;
3997 }
3998
3999 if (auto *DerivedIVR = dyn_cast<VPDerivedIVRecipe>(&R)) {
4000 expandVPDerivedIV(DerivedIVR, TypeInfo);
4001 ToRemove.push_back(DerivedIVR);
4002 continue;
4003 }
4004
4005 if (auto *WideCanIV = dyn_cast<VPWidenCanonicalIVRecipe>(&R)) {
4006 VPValue *CanIV = WideCanIV->getCanonicalIV();
4007 Type *CanIVTy = TypeInfo.inferScalarType(CanIV);
4008 VPValue *Step = WideCanIV->getStepValue();
4009 if (!Step) {
4010 assert(Plan.getConcreteUF() == 1 &&
4011 "Expected unroller to have materialized step for UF != 1");
4012 Step = Plan.getZero(CanIVTy);
4013 }
4014 CanIV = Builder.createNaryOp(VPInstruction::Broadcast, CanIV);
4015 Step = Builder.createNaryOp(VPInstruction::Broadcast, Step);
4016 Step = Builder.createAdd(
4017 Step, Builder.createNaryOp(VPInstruction::StepVector, {}, CanIVTy));
4018 VPValue *CanVecIV =
4019 Builder.createAdd(CanIV, Step, WideCanIV->getDebugLoc(), "vec.iv",
4020 WideCanIV->getNoWrapFlags());
4021 WideCanIV->replaceAllUsesWith(CanVecIV);
4022 ToRemove.push_back(WideCanIV);
4023 continue;
4024 }
4025
4026 // Expand VPBlendRecipe into VPInstruction::Select.
4027 if (auto *Blend = dyn_cast<VPBlendRecipe>(&R)) {
4028 VPValue *Select = Blend->getIncomingValue(0);
4029 for (unsigned I = 1; I != Blend->getNumIncomingValues(); ++I)
4030 Select = Builder.createSelect(Blend->getMask(I),
4031 Blend->getIncomingValue(I), Select,
4032 R.getDebugLoc(), "predphi", *Blend);
4033 Blend->replaceAllUsesWith(Select);
4034 ToRemove.push_back(Blend);
4035 }
4036
4037 if (auto *VEPR = dyn_cast<VPVectorEndPointerRecipe>(&R)) {
4038 if (!VEPR->getOffset()) {
4039 assert(Plan.getConcreteUF() == 1 &&
4040 "Expected unroller to have materialized offset for UF != 1");
4041 VEPR->materializeOffset();
4042 }
4043 }
4044
4045 if (auto *Expr = dyn_cast<VPExpressionRecipe>(&R)) {
4046 Expr->decompose();
4047 ToRemove.push_back(Expr);
4048 }
4049
4050 // Expand LastActiveLane into Not + FirstActiveLane + Sub.
4051 auto *LastActiveL = dyn_cast<VPInstruction>(&R);
4052 if (LastActiveL &&
4053 LastActiveL->getOpcode() == VPInstruction::LastActiveLane) {
4054 // Create Not(Mask) for all operands.
4056 for (VPValue *Op : LastActiveL->operands()) {
4057 VPValue *NotMask = Builder.createNot(Op, LastActiveL->getDebugLoc());
4058 NotMasks.push_back(NotMask);
4059 }
4060
4061 // Create FirstActiveLane on the inverted masks.
4062 VPValue *FirstInactiveLane = Builder.createFirstActiveLane(
4063 NotMasks, LastActiveL->getDebugLoc(), "first.inactive.lane");
4064
4065 // Subtract 1 to get the last active lane.
4066 VPValue *One =
4067 Plan.getConstantInt(TypeInfo.inferScalarType(FirstInactiveLane), 1);
4068 VPValue *LastLane =
4069 Builder.createSub(FirstInactiveLane, One,
4070 LastActiveL->getDebugLoc(), "last.active.lane");
4071
4072 LastActiveL->replaceAllUsesWith(LastLane);
4073 ToRemove.push_back(LastActiveL);
4074 continue;
4075 }
4076
4077 // Lower MaskedCond with block mask to LogicalAnd.
4079 auto *VPI = cast<VPInstruction>(&R);
4080 assert(VPI->isMasked() &&
4081 "Unmasked MaskedCond should be simplified earlier");
4082 VPI->replaceAllUsesWith(Builder.createNaryOp(
4083 VPInstruction::LogicalAnd, {VPI->getMask(), VPI->getOperand(0)}));
4084 ToRemove.push_back(VPI);
4085 continue;
4086 }
4087
4088 // Lower CanonicalIVIncrementForPart to plain Add.
4089 if (match(
4090 &R,
4092 auto *VPI = cast<VPInstruction>(&R);
4093 VPValue *Add = Builder.createOverflowingOp(
4094 Instruction::Add, VPI->operands(), VPI->getNoWrapFlags(),
4095 VPI->getDebugLoc());
4096 VPI->replaceAllUsesWith(Add);
4097 ToRemove.push_back(VPI);
4098 continue;
4099 }
4100
4101 // Lower BranchOnCount to ICmp + BranchOnCond.
4102 VPValue *IV, *TC;
4103 if (match(&R, m_BranchOnCount(m_VPValue(IV), m_VPValue(TC)))) {
4104 auto *BranchOnCountInst = cast<VPInstruction>(&R);
4105 DebugLoc DL = BranchOnCountInst->getDebugLoc();
4106 VPValue *Cond = Builder.createICmp(CmpInst::ICMP_EQ, IV, TC, DL);
4107 Builder.createNaryOp(VPInstruction::BranchOnCond, Cond, DL);
4108 ToRemove.push_back(BranchOnCountInst);
4109 continue;
4110 }
4111
4112 VPValue *VectorStep;
4113 VPValue *ScalarStep;
4115 m_VPValue(VectorStep), m_VPValue(ScalarStep))))
4116 continue;
4117
4118 // Expand WideIVStep.
4119 auto *VPI = cast<VPInstruction>(&R);
4120 Type *IVTy = TypeInfo.inferScalarType(VPI);
4121 if (TypeInfo.inferScalarType(VectorStep) != IVTy) {
4123 ? Instruction::UIToFP
4124 : Instruction::Trunc;
4125 VectorStep = Builder.createWidenCast(CastOp, VectorStep, IVTy);
4126 }
4127
4128 assert(!match(ScalarStep, m_One()) && "Expected non-unit scalar-step");
4129 if (TypeInfo.inferScalarType(ScalarStep) != IVTy) {
4130 ScalarStep =
4131 Builder.createWidenCast(Instruction::Trunc, ScalarStep, IVTy);
4132 }
4133
4134 VPIRFlags Flags;
4135 unsigned MulOpc;
4136 if (IVTy->isFloatingPointTy()) {
4137 MulOpc = Instruction::FMul;
4138 Flags = VPI->getFastMathFlags();
4139 } else {
4140 MulOpc = Instruction::Mul;
4141 Flags = VPIRFlags::getDefaultFlags(MulOpc);
4142 }
4143
4144 VPInstruction *Mul = Builder.createNaryOp(
4145 MulOpc, {VectorStep, ScalarStep}, Flags, R.getDebugLoc());
4146 VectorStep = Mul;
4147 VPI->replaceAllUsesWith(VectorStep);
4148 ToRemove.push_back(VPI);
4149 }
4150 }
4151
4152 for (VPRecipeBase *R : ToRemove)
4153 R->eraseFromParent();
4154}
4155
4157 VPBasicBlock *HeaderVPBB,
4158 VPBasicBlock *LatchVPBB,
4159 VPBasicBlock *MiddleVPBB,
4160 UncountableExitStyle Style) {
4161 struct EarlyExitInfo {
4162 VPBasicBlock *EarlyExitingVPBB;
4163 VPIRBasicBlock *EarlyExitVPBB;
4164 VPValue *CondToExit;
4165 };
4166
4167 VPDominatorTree VPDT(Plan);
4168 VPBuilder Builder(LatchVPBB->getTerminator());
4170 for (VPIRBasicBlock *ExitBlock : Plan.getExitBlocks()) {
4171 for (VPBlockBase *Pred : to_vector(ExitBlock->getPredecessors())) {
4172 if (Pred == MiddleVPBB)
4173 continue;
4174 // Collect condition for this early exit.
4175 auto *EarlyExitingVPBB = cast<VPBasicBlock>(Pred);
4176 VPBlockBase *TrueSucc = EarlyExitingVPBB->getSuccessors()[0];
4177 VPValue *CondOfEarlyExitingVPBB;
4178 [[maybe_unused]] bool Matched =
4179 match(EarlyExitingVPBB->getTerminator(),
4180 m_BranchOnCond(m_VPValue(CondOfEarlyExitingVPBB)));
4181 assert(Matched && "Terminator must be BranchOnCond");
4182
4183 // Insert the MaskedCond in the EarlyExitingVPBB so the predicator adds
4184 // the correct block mask.
4185 VPBuilder EarlyExitingBuilder(EarlyExitingVPBB->getTerminator());
4186 auto *CondToEarlyExit = EarlyExitingBuilder.createNaryOp(
4188 TrueSucc == ExitBlock
4189 ? CondOfEarlyExitingVPBB
4190 : EarlyExitingBuilder.createNot(CondOfEarlyExitingVPBB));
4191 assert((isa<VPIRValue>(CondOfEarlyExitingVPBB) ||
4192 !VPDT.properlyDominates(EarlyExitingVPBB, LatchVPBB) ||
4193 VPDT.properlyDominates(
4194 CondOfEarlyExitingVPBB->getDefiningRecipe()->getParent(),
4195 LatchVPBB)) &&
4196 "exit condition must dominate the latch");
4197 Exits.push_back({
4198 EarlyExitingVPBB,
4199 ExitBlock,
4200 CondToEarlyExit,
4201 });
4202 }
4203 }
4204
4205 assert(!Exits.empty() && "must have at least one early exit");
4206 // Sort exits by RPO order to get correct program order. RPO gives a
4207 // topological ordering of the CFG, ensuring upstream exits are checked
4208 // before downstream exits in the dispatch chain.
4210 HeaderVPBB);
4212 for (const auto &[Num, VPB] : enumerate(RPOT))
4213 RPOIdx[VPB] = Num;
4214 llvm::sort(Exits, [&RPOIdx](const EarlyExitInfo &A, const EarlyExitInfo &B) {
4215 return RPOIdx[A.EarlyExitingVPBB] < RPOIdx[B.EarlyExitingVPBB];
4216 });
4217#ifndef NDEBUG
4218 // After RPO sorting, verify that for any pair where one exit dominates
4219 // another, the dominating exit comes first. This is guaranteed by RPO
4220 // (topological order) and is required for the dispatch chain correctness.
4221 for (unsigned I = 0; I + 1 < Exits.size(); ++I)
4222 for (unsigned J = I + 1; J < Exits.size(); ++J)
4223 assert(!VPDT.properlyDominates(Exits[J].EarlyExitingVPBB,
4224 Exits[I].EarlyExitingVPBB) &&
4225 "RPO sort must place dominating exits before dominated ones");
4226#endif
4227
4228 // Build the AnyOf condition for the latch terminator using logical OR
4229 // to avoid poison propagation from later exit conditions when an earlier
4230 // exit is taken.
4231 VPValue *Combined = Exits[0].CondToExit;
4232 for (const EarlyExitInfo &Info : drop_begin(Exits))
4233 Combined = Builder.createLogicalOr(Combined, Info.CondToExit);
4234
4235 VPValue *IsAnyExitTaken =
4236 Builder.createNaryOp(VPInstruction::AnyOf, {Combined});
4237
4239 "Early exit store masking not implemented");
4240
4241 // Create the vector.early.exit blocks.
4242 SmallVector<VPBasicBlock *> VectorEarlyExitVPBBs(Exits.size());
4243 for (unsigned Idx = 0; Idx != Exits.size(); ++Idx) {
4244 Twine BlockSuffix = Exits.size() == 1 ? "" : Twine(".") + Twine(Idx);
4245 VPBasicBlock *VectorEarlyExitVPBB =
4246 Plan.createVPBasicBlock("vector.early.exit" + BlockSuffix);
4247 VectorEarlyExitVPBBs[Idx] = VectorEarlyExitVPBB;
4248 }
4249
4250 // Create the dispatch block (or reuse the single exit block if only one
4251 // exit). The dispatch block computes the first active lane of the combined
4252 // condition and, for multiple exits, chains through conditions to determine
4253 // which exit to take.
4254 VPBasicBlock *DispatchVPBB =
4255 Exits.size() == 1 ? VectorEarlyExitVPBBs[0]
4256 : Plan.createVPBasicBlock("vector.early.exit.check");
4257 DispatchVPBB->setPredecessors({LatchVPBB});
4258 VPBuilder DispatchBuilder(DispatchVPBB, DispatchVPBB->begin());
4259 VPValue *FirstActiveLane = DispatchBuilder.createFirstActiveLane(
4260 {Combined}, DebugLoc::getUnknown(), "first.active.lane");
4261
4262 // For each early exit, disconnect the original exiting block
4263 // (early.exiting.I) from the exit block (ir-bb<exit.I>) and route through a
4264 // new vector.early.exit block. Update ir-bb<exit.I>'s phis to extract their
4265 // values at the first active lane:
4266 //
4267 // Input:
4268 // early.exiting.I:
4269 // ...
4270 // EMIT branch-on-cond vp<%cond.I>
4271 // Successor(s): in.loop.succ, ir-bb<exit.I>
4272 //
4273 // ir-bb<exit.I>:
4274 // IR %phi = phi [ vp<%incoming.I>, early.exiting.I ], ...
4275 //
4276 // Output:
4277 // early.exiting.I:
4278 // ...
4279 // Successor(s): in.loop.succ
4280 //
4281 // vector.early.exit.I:
4282 // EMIT vp<%exit.val> = extract-lane vp<%first.lane>, vp<%incoming.I>
4283 // Successor(s): ir-bb<exit.I>
4284 //
4285 // ir-bb<exit.I>:
4286 // IR %phi = phi ... (extra operand: vp<%exit.val> from
4287 // vector.early.exit.I)
4288 //
4289 for (auto [Exit, VectorEarlyExitVPBB] :
4290 zip_equal(Exits, VectorEarlyExitVPBBs)) {
4291 auto &[EarlyExitingVPBB, EarlyExitVPBB, _] = Exit;
4292 // Adjust the phi nodes in EarlyExitVPBB.
4293 // 1. remove incoming values from EarlyExitingVPBB,
4294 // 2. extract the incoming value at FirstActiveLane
4295 // 3. add back the extracts as last operands for the phis
4296 // Then adjust the CFG, removing the edge between EarlyExitingVPBB and
4297 // EarlyExitVPBB and adding a new edge between VectorEarlyExitVPBB and
4298 // EarlyExitVPBB. The extracts at FirstActiveLane are now the incoming
4299 // values from VectorEarlyExitVPBB.
4300 for (VPRecipeBase &R : EarlyExitVPBB->phis()) {
4301 auto *ExitIRI = cast<VPIRPhi>(&R);
4302 VPValue *IncomingVal =
4303 ExitIRI->getIncomingValueForBlock(EarlyExitingVPBB);
4304 VPValue *NewIncoming = IncomingVal;
4305 if (!isa<VPIRValue>(IncomingVal)) {
4306 VPBuilder EarlyExitBuilder(VectorEarlyExitVPBB);
4307 NewIncoming = EarlyExitBuilder.createNaryOp(
4308 VPInstruction::ExtractLane, {FirstActiveLane, IncomingVal},
4309 DebugLoc::getUnknown(), "early.exit.value");
4310 }
4311 ExitIRI->removeIncomingValueFor(EarlyExitingVPBB);
4312 ExitIRI->addOperand(NewIncoming);
4313 }
4314
4315 EarlyExitingVPBB->getTerminator()->eraseFromParent();
4316 VPBlockUtils::disconnectBlocks(EarlyExitingVPBB, EarlyExitVPBB);
4317 VPBlockUtils::connectBlocks(VectorEarlyExitVPBB, EarlyExitVPBB);
4318 }
4319
4320 // Chain through exits: for each exit, check if its condition is true at
4321 // the first active lane. If so, take that exit; otherwise, try the next.
4322 // The last exit needs no check since it must be taken if all others fail.
4323 //
4324 // For 3 exits (cond.0, cond.1, cond.2), this creates:
4325 //
4326 // latch:
4327 // ...
4328 // EMIT vp<%combined> = logical-or vp<%cond.0>, vp<%cond.1>, vp<%cond.2>
4329 // ...
4330 //
4331 // vector.early.exit.check:
4332 // EMIT vp<%first.lane> = first-active-lane vp<%combined>
4333 // EMIT vp<%at.cond.0> = extract-lane vp<%first.lane>, vp<%cond.0>
4334 // EMIT branch-on-cond vp<%at.cond.0>
4335 // Successor(s): vector.early.exit.0, vector.early.exit.check.0
4336 //
4337 // vector.early.exit.check.0:
4338 // EMIT vp<%at.cond.1> = extract-lane vp<%first.lane>, vp<%cond.1>
4339 // EMIT branch-on-cond vp<%at.cond.1>
4340 // Successor(s): vector.early.exit.1, vector.early.exit.2
4341 VPBasicBlock *CurrentBB = DispatchVPBB;
4342 for (auto [I, Exit] : enumerate(ArrayRef(Exits).drop_back())) {
4343 VPValue *LaneVal = DispatchBuilder.createNaryOp(
4344 VPInstruction::ExtractLane, {FirstActiveLane, Exit.CondToExit},
4345 DebugLoc::getUnknown(), "exit.cond.at.lane");
4346
4347 // For the last dispatch, branch directly to the last exit on false;
4348 // otherwise, create a new check block.
4349 bool IsLastDispatch = (I + 2 == Exits.size());
4350 VPBasicBlock *FalseBB =
4351 IsLastDispatch ? VectorEarlyExitVPBBs.back()
4352 : Plan.createVPBasicBlock(
4353 Twine("vector.early.exit.check.") + Twine(I));
4354
4355 DispatchBuilder.createNaryOp(VPInstruction::BranchOnCond, {LaneVal});
4356 CurrentBB->setSuccessors({VectorEarlyExitVPBBs[I], FalseBB});
4357 VectorEarlyExitVPBBs[I]->setPredecessors({CurrentBB});
4358 FalseBB->setPredecessors({CurrentBB});
4359
4360 CurrentBB = FalseBB;
4361 DispatchBuilder.setInsertPoint(CurrentBB);
4362 }
4363
4364 // Replace the latch terminator with the new branching logic.
4365 auto *LatchExitingBranch = cast<VPInstruction>(LatchVPBB->getTerminator());
4366 assert(LatchExitingBranch->getOpcode() == VPInstruction::BranchOnCount &&
4367 "Unexpected terminator");
4368 auto *IsLatchExitTaken =
4369 Builder.createICmp(CmpInst::ICMP_EQ, LatchExitingBranch->getOperand(0),
4370 LatchExitingBranch->getOperand(1));
4371
4372 DebugLoc LatchDL = LatchExitingBranch->getDebugLoc();
4373 LatchExitingBranch->eraseFromParent();
4374 Builder.setInsertPoint(LatchVPBB);
4375 Builder.createNaryOp(VPInstruction::BranchOnTwoConds,
4376 {IsAnyExitTaken, IsLatchExitTaken}, LatchDL);
4377 LatchVPBB->clearSuccessors();
4378 LatchVPBB->setSuccessors({DispatchVPBB, MiddleVPBB, HeaderVPBB});
4379}
4380
4381/// This function tries convert extended in-loop reductions to
4382/// VPExpressionRecipe and clamp the \p Range if it is beneficial and
4383/// valid. The created recipe must be decomposed to its constituent
4384/// recipes before execution.
4385static VPExpressionRecipe *
4387 VFRange &Range) {
4388 Type *RedTy = Ctx.Types.inferScalarType(Red);
4389 VPValue *VecOp = Red->getVecOp();
4390
4391 assert(!Red->isPartialReduction() &&
4392 "This path does not support partial reductions");
4393
4394 // Clamp the range if using extended-reduction is profitable.
4395 auto IsExtendedRedValidAndClampRange =
4396 [&](unsigned Opcode, Instruction::CastOps ExtOpc, Type *SrcTy) -> bool {
4398 [&](ElementCount VF) {
4399 auto *SrcVecTy = cast<VectorType>(toVectorTy(SrcTy, VF));
4401
4403 InstructionCost ExtCost =
4404 cast<VPWidenCastRecipe>(VecOp)->computeCost(VF, Ctx);
4405 InstructionCost RedCost = Red->computeCost(VF, Ctx);
4406
4407 assert(!RedTy->isFloatingPointTy() &&
4408 "getExtendedReductionCost only supports integer types");
4409 ExtRedCost = Ctx.TTI.getExtendedReductionCost(
4410 Opcode, ExtOpc == Instruction::CastOps::ZExt, RedTy, SrcVecTy,
4411 Red->getFastMathFlags(), CostKind);
4412 return ExtRedCost.isValid() && ExtRedCost < ExtCost + RedCost;
4413 },
4414 Range);
4415 };
4416
4417 VPValue *A;
4418 // Match reduce(ext)).
4420 IsExtendedRedValidAndClampRange(
4421 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()),
4422 cast<VPWidenCastRecipe>(VecOp)->getOpcode(),
4423 Ctx.Types.inferScalarType(A)))
4424 return new VPExpressionRecipe(cast<VPWidenCastRecipe>(VecOp), Red);
4425
4426 return nullptr;
4427}
4428
4429/// This function tries convert extended in-loop reductions to
4430/// VPExpressionRecipe and clamp the \p Range if it is beneficial
4431/// and valid. The created VPExpressionRecipe must be decomposed to its
4432/// constituent recipes before execution. Patterns of the
4433/// VPExpressionRecipe:
4434/// reduce.add(mul(...)),
4435/// reduce.add(mul(ext(A), ext(B))),
4436/// reduce.add(ext(mul(ext(A), ext(B)))).
4437/// reduce.fadd(fmul(ext(A), ext(B)))
4438static VPExpressionRecipe *
4440 VPCostContext &Ctx, VFRange &Range) {
4441 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
4442 if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
4443 Opcode != Instruction::FAdd)
4444 return nullptr;
4445
4446 assert(!Red->isPartialReduction() &&
4447 "This path does not support partial reductions");
4448 Type *RedTy = Ctx.Types.inferScalarType(Red);
4449
4450 // Clamp the range if using multiply-accumulate-reduction is profitable.
4451 auto IsMulAccValidAndClampRange =
4453 VPWidenCastRecipe *OuterExt) -> bool {
4455 [&](ElementCount VF) {
4457 Type *SrcTy =
4458 Ext0 ? Ctx.Types.inferScalarType(Ext0->getOperand(0)) : RedTy;
4459 InstructionCost MulAccCost;
4460
4461 // getMulAccReductionCost for in-loop reductions does not support
4462 // mixed or floating-point extends.
4463 if (Ext0 && Ext1 &&
4464 (Ext0->getOpcode() != Ext1->getOpcode() ||
4465 Ext0->getOpcode() == Instruction::CastOps::FPExt))
4466 return false;
4467
4468 bool IsZExt =
4469 !Ext0 || Ext0->getOpcode() == Instruction::CastOps::ZExt;
4470 auto *SrcVecTy = cast<VectorType>(toVectorTy(SrcTy, VF));
4471 MulAccCost = Ctx.TTI.getMulAccReductionCost(IsZExt, Opcode, RedTy,
4472 SrcVecTy, CostKind);
4473
4474 InstructionCost MulCost = Mul->computeCost(VF, Ctx);
4475 InstructionCost RedCost = Red->computeCost(VF, Ctx);
4476 InstructionCost ExtCost = 0;
4477 if (Ext0)
4478 ExtCost += Ext0->computeCost(VF, Ctx);
4479 if (Ext1)
4480 ExtCost += Ext1->computeCost(VF, Ctx);
4481 if (OuterExt)
4482 ExtCost += OuterExt->computeCost(VF, Ctx);
4483
4484 return MulAccCost.isValid() &&
4485 MulAccCost < ExtCost + MulCost + RedCost;
4486 },
4487 Range);
4488 };
4489
4490 VPValue *VecOp = Red->getVecOp();
4491 VPRecipeBase *Sub = nullptr;
4492 VPValue *A, *B;
4493 VPValue *Tmp = nullptr;
4494
4495 if (RedTy->isFloatingPointTy())
4496 return nullptr;
4497
4498 // Sub reductions could have a sub between the add reduction and vec op.
4499 if (match(VecOp, m_Sub(m_ZeroInt(), m_VPValue(Tmp)))) {
4500 Sub = VecOp->getDefiningRecipe();
4501 VecOp = Tmp;
4502 }
4503
4504 // If ValB is a constant and can be safely extended, truncate it to the same
4505 // type as ExtA's operand, then extend it to the same type as ExtA. This
4506 // creates two uniform extends that can more easily be matched by the rest of
4507 // the bundling code. The ExtB reference, ValB and operand 1 of Mul are all
4508 // replaced with the new extend of the constant.
4509 auto ExtendAndReplaceConstantOp = [&Ctx](VPWidenCastRecipe *ExtA,
4510 VPWidenCastRecipe *&ExtB,
4511 VPValue *&ValB, VPWidenRecipe *Mul) {
4512 if (!ExtA || ExtB || !isa<VPIRValue>(ValB))
4513 return;
4514 Type *NarrowTy = Ctx.Types.inferScalarType(ExtA->getOperand(0));
4515 Instruction::CastOps ExtOpc = ExtA->getOpcode();
4516 const APInt *Const;
4517 if (!match(ValB, m_APInt(Const)) ||
4519 Const, NarrowTy, TTI::getPartialReductionExtendKind(ExtOpc)))
4520 return;
4521 // The truncate ensures that the type of each extended operand is the
4522 // same, and it's been proven that the constant can be extended from
4523 // NarrowTy safely. Necessary since ExtA's extended operand would be
4524 // e.g. an i8, while the const will likely be an i32. This will be
4525 // elided by later optimisations.
4526 VPBuilder Builder(Mul);
4527 auto *Trunc =
4528 Builder.createWidenCast(Instruction::CastOps::Trunc, ValB, NarrowTy);
4529 Type *WideTy = Ctx.Types.inferScalarType(ExtA);
4530 ValB = ExtB = Builder.createWidenCast(ExtOpc, Trunc, WideTy);
4531 Mul->setOperand(1, ExtB);
4532 };
4533
4534 // Try to match reduce.add(mul(...)).
4535 if (match(VecOp, m_Mul(m_VPValue(A), m_VPValue(B)))) {
4536 auto *RecipeA = dyn_cast<VPWidenCastRecipe>(A);
4537 auto *RecipeB = dyn_cast<VPWidenCastRecipe>(B);
4538 auto *Mul = cast<VPWidenRecipe>(VecOp);
4539
4540 // Convert reduce.add(mul(ext, const)) to reduce.add(mul(ext, ext(const)))
4541 ExtendAndReplaceConstantOp(RecipeA, RecipeB, B, Mul);
4542
4543 // Match reduce.add/sub(mul(ext, ext)).
4544 if (RecipeA && RecipeB && match(RecipeA, m_ZExtOrSExt(m_VPValue())) &&
4545 match(RecipeB, m_ZExtOrSExt(m_VPValue())) &&
4546 IsMulAccValidAndClampRange(Mul, RecipeA, RecipeB, nullptr)) {
4547 if (Sub)
4548 return new VPExpressionRecipe(RecipeA, RecipeB, Mul,
4549 cast<VPWidenRecipe>(Sub), Red);
4550 return new VPExpressionRecipe(RecipeA, RecipeB, Mul, Red);
4551 }
4552 // TODO: Add an expression type for this variant with a negated mul
4553 if (!Sub && IsMulAccValidAndClampRange(Mul, nullptr, nullptr, nullptr))
4554 return new VPExpressionRecipe(Mul, Red);
4555 }
4556 // TODO: Add an expression type for negated versions of other expression
4557 // variants.
4558 if (Sub)
4559 return nullptr;
4560
4561 // Match reduce.add(ext(mul(A, B))).
4562 if (match(VecOp, m_ZExtOrSExt(m_Mul(m_VPValue(A), m_VPValue(B))))) {
4563 auto *Ext = cast<VPWidenCastRecipe>(VecOp);
4564 auto *Mul = cast<VPWidenRecipe>(Ext->getOperand(0));
4565 auto *Ext0 = dyn_cast<VPWidenCastRecipe>(A);
4566 auto *Ext1 = dyn_cast<VPWidenCastRecipe>(B);
4567
4568 // reduce.add(ext(mul(ext, const)))
4569 // -> reduce.add(ext(mul(ext, ext(const))))
4570 ExtendAndReplaceConstantOp(Ext0, Ext1, B, Mul);
4571
4572 // reduce.add(ext(mul(ext(A), ext(B))))
4573 // -> reduce.add(mul(wider_ext(A), wider_ext(B)))
4574 // The inner extends must either have the same opcode as the outer extend or
4575 // be the same, in which case the multiply can never result in a negative
4576 // value and the outer extend can be folded away by doing wider
4577 // extends for the operands of the mul.
4578 if (Ext0 && Ext1 &&
4579 (Ext->getOpcode() == Ext0->getOpcode() || Ext0 == Ext1) &&
4580 Ext0->getOpcode() == Ext1->getOpcode() &&
4581 IsMulAccValidAndClampRange(Mul, Ext0, Ext1, Ext) && Mul->hasOneUse()) {
4582 auto *NewExt0 = new VPWidenCastRecipe(
4583 Ext0->getOpcode(), Ext0->getOperand(0), Ext->getScalarType(), nullptr,
4584 *Ext0, *Ext0, Ext0->getDebugLoc());
4585 NewExt0->insertBefore(Ext0);
4586
4587 VPWidenCastRecipe *NewExt1 = NewExt0;
4588 if (Ext0 != Ext1) {
4589 NewExt1 = new VPWidenCastRecipe(Ext1->getOpcode(), Ext1->getOperand(0),
4590 Ext->getScalarType(), nullptr, *Ext1,
4591 *Ext1, Ext1->getDebugLoc());
4592 NewExt1->insertBefore(Ext1);
4593 }
4594 Mul->setOperand(0, NewExt0);
4595 Mul->setOperand(1, NewExt1);
4596 Red->setOperand(1, Mul);
4597 return new VPExpressionRecipe(NewExt0, NewExt1, Mul, Red);
4598 }
4599 }
4600 return nullptr;
4601}
4602
4603/// This function tries to create abstract recipes from the reduction recipe for
4604/// following optimizations and cost estimation.
4606 VPCostContext &Ctx,
4607 VFRange &Range) {
4608 // Creation of VPExpressions for partial reductions is entirely handled in
4609 // transformToPartialReduction.
4610 assert(!Red->isPartialReduction() &&
4611 "This path does not support partial reductions");
4612
4613 VPExpressionRecipe *AbstractR = nullptr;
4614 auto IP = std::next(Red->getIterator());
4615 auto *VPBB = Red->getParent();
4616 if (auto *MulAcc = tryToMatchAndCreateMulAccumulateReduction(Red, Ctx, Range))
4617 AbstractR = MulAcc;
4618 else if (auto *ExtRed = tryToMatchAndCreateExtendedReduction(Red, Ctx, Range))
4619 AbstractR = ExtRed;
4620 // Cannot create abstract inloop reduction recipes.
4621 if (!AbstractR)
4622 return;
4623
4624 AbstractR->insertBefore(*VPBB, IP);
4625 Red->replaceAllUsesWith(AbstractR);
4626}
4627
4638
4640 if (Plan.hasScalarVFOnly())
4641 return;
4642
4643#ifndef NDEBUG
4644 VPDominatorTree VPDT(Plan);
4645#endif
4646
4647 SmallVector<VPValue *> VPValues;
4648 if (VPValue *BTC = Plan.getBackedgeTakenCount())
4649 VPValues.push_back(BTC);
4650 append_range(VPValues, Plan.getLiveIns());
4651 for (VPRecipeBase &R : *Plan.getEntry())
4652 append_range(VPValues, R.definedValues());
4653
4654 auto *VectorPreheader = Plan.getVectorPreheader();
4655 for (VPValue *VPV : VPValues) {
4657 (isa<VPIRValue>(VPV) && isa<Constant>(VPV->getLiveInIRValue())))
4658 continue;
4659
4660 // Add explicit broadcast at the insert point that dominates all users.
4661 VPBasicBlock *HoistBlock = VectorPreheader;
4662 VPBasicBlock::iterator HoistPoint = VectorPreheader->end();
4663 for (VPUser *User : VPV->users()) {
4664 if (User->usesScalars(VPV))
4665 continue;
4666 if (cast<VPRecipeBase>(User)->getParent() == VectorPreheader)
4667 HoistPoint = HoistBlock->begin();
4668 else
4669 assert(VPDT.dominates(VectorPreheader,
4670 cast<VPRecipeBase>(User)->getParent()) &&
4671 "All users must be in the vector preheader or dominated by it");
4672 }
4673
4674 VPBuilder Builder(cast<VPBasicBlock>(HoistBlock), HoistPoint);
4675 auto *Broadcast = Builder.createNaryOp(VPInstruction::Broadcast, {VPV});
4676 VPV->replaceUsesWithIf(Broadcast,
4677 [VPV, Broadcast](VPUser &U, unsigned Idx) {
4678 return Broadcast != &U && !U.usesScalars(VPV);
4679 });
4680 }
4681}
4682
4683// Collect common metadata from a group of replicate recipes by intersecting
4684// metadata from all recipes in the group.
4686 VPIRMetadata CommonMetadata = *Recipes.front();
4687 for (VPReplicateRecipe *Recipe : drop_begin(Recipes))
4688 CommonMetadata.intersect(*Recipe);
4689 return CommonMetadata;
4690}
4691
4692template <unsigned Opcode>
4696 const Loop *L) {
4697 static_assert(Opcode == Instruction::Load || Opcode == Instruction::Store,
4698 "Only Load and Store opcodes supported");
4699 constexpr bool IsLoad = (Opcode == Instruction::Load);
4700 VPTypeAnalysis TypeInfo(Plan);
4701
4702 // For each address, collect operations with the same or complementary masks.
4704 auto GetLoadStoreValueType = [&](VPReplicateRecipe *Recipe) {
4705 return TypeInfo.inferScalarType(IsLoad ? Recipe : Recipe->getOperand(0));
4706 };
4708 Plan, PSE, L,
4709 [](VPReplicateRecipe *RepR) { return RepR->isPredicated(); });
4710 for (auto Recipes : Groups) {
4711 if (Recipes.size() < 2)
4712 continue;
4713
4714 // Collect groups with the same or complementary masks.
4715 for (VPReplicateRecipe *&RecipeI : Recipes) {
4716 if (!RecipeI)
4717 continue;
4718
4719 VPValue *MaskI = RecipeI->getMask();
4720 Type *TypeI = GetLoadStoreValueType(RecipeI);
4722 Group.push_back(RecipeI);
4723 RecipeI = nullptr;
4724
4725 // Find all operations with the same or complementary masks.
4726 bool HasComplementaryMask = false;
4727 for (VPReplicateRecipe *&RecipeJ : Recipes) {
4728 if (!RecipeJ)
4729 continue;
4730
4731 VPValue *MaskJ = RecipeJ->getMask();
4732 Type *TypeJ = GetLoadStoreValueType(RecipeJ);
4733 if (TypeI == TypeJ) {
4734 // Check if any operation in the group has a complementary mask with
4735 // another, that is M1 == NOT(M2) or M2 == NOT(M1).
4736 HasComplementaryMask |= match(MaskI, m_Not(m_Specific(MaskJ))) ||
4737 match(MaskJ, m_Not(m_Specific(MaskI)));
4738 Group.push_back(RecipeJ);
4739 RecipeJ = nullptr;
4740 }
4741 }
4742
4743 if (HasComplementaryMask) {
4744 assert(Group.size() >= 2 && "must have at least 2 entries");
4745 AllGroups.push_back(std::move(Group));
4746 }
4747 }
4748 }
4749
4750 return AllGroups;
4751}
4752
4753// Find the recipe with minimum alignment in the group.
4754template <typename InstType>
4755static VPReplicateRecipe *
4757 return *min_element(Group, [](VPReplicateRecipe *A, VPReplicateRecipe *B) {
4758 return cast<InstType>(A->getUnderlyingInstr())->getAlign() <
4759 cast<InstType>(B->getUnderlyingInstr())->getAlign();
4760 });
4761}
4762
4765 const Loop *L) {
4766 auto Groups =
4768 if (Groups.empty())
4769 return;
4770
4771 // Process each group of loads.
4772 for (auto &Group : Groups) {
4773 // Try to use the earliest (most dominating) load to replace all others.
4774 VPReplicateRecipe *EarliestLoad = Group[0];
4775 VPBasicBlock *FirstBB = EarliestLoad->getParent();
4776 VPBasicBlock *LastBB = Group.back()->getParent();
4777
4778 // Check that the load doesn't alias with stores between first and last.
4779 auto LoadLoc = vputils::getMemoryLocation(*EarliestLoad);
4780 if (!LoadLoc || !canHoistOrSinkWithNoAliasCheck(*LoadLoc, FirstBB, LastBB))
4781 continue;
4782
4783 // Collect common metadata from all loads in the group.
4784 VPIRMetadata CommonMetadata = getCommonMetadata(Group);
4785
4786 // Find the load with minimum alignment to use.
4787 auto *LoadWithMinAlign = findRecipeWithMinAlign<LoadInst>(Group);
4788
4789 bool IsSingleScalar = EarliestLoad->isSingleScalar();
4790 assert(all_of(Group,
4791 [IsSingleScalar](VPReplicateRecipe *R) {
4792 return R->isSingleScalar() == IsSingleScalar;
4793 }) &&
4794 "all members in group must agree on IsSingleScalar");
4795
4796 // Create an unpredicated version of the earliest load with common
4797 // metadata.
4798 auto *UnpredicatedLoad = new VPReplicateRecipe(
4799 LoadWithMinAlign->getUnderlyingInstr(), {EarliestLoad->getOperand(0)},
4800 IsSingleScalar, /*Mask=*/nullptr, *EarliestLoad, CommonMetadata);
4801
4802 UnpredicatedLoad->insertBefore(EarliestLoad);
4803
4804 // Replace all loads in the group with the unpredicated load.
4805 for (VPReplicateRecipe *Load : Group) {
4806 Load->replaceAllUsesWith(UnpredicatedLoad);
4807 Load->eraseFromParent();
4808 }
4809 }
4810}
4811
4812static bool
4814 PredicatedScalarEvolution &PSE, const Loop &L,
4815 VPTypeAnalysis &TypeInfo) {
4816 auto StoreLoc = vputils::getMemoryLocation(*StoresToSink.front());
4817 if (!StoreLoc || !StoreLoc->AATags.Scope)
4818 return false;
4819
4820 // When sinking a group of stores, all members of the group alias each other.
4821 // Skip them during the alias checks.
4822 SmallPtrSet<VPRecipeBase *, 4> StoresToSinkSet(StoresToSink.begin(),
4823 StoresToSink.end());
4824
4825 VPBasicBlock *FirstBB = StoresToSink.front()->getParent();
4826 VPBasicBlock *LastBB = StoresToSink.back()->getParent();
4827 SinkStoreInfo SinkInfo(StoresToSinkSet, *StoresToSink[0], PSE, L, TypeInfo);
4828 return canHoistOrSinkWithNoAliasCheck(*StoreLoc, FirstBB, LastBB, SinkInfo);
4829}
4830
4833 const Loop *L) {
4834 auto Groups =
4836 if (Groups.empty())
4837 return;
4838
4839 VPTypeAnalysis TypeInfo(Plan);
4840
4841 for (auto &Group : Groups) {
4842 if (!canSinkStoreWithNoAliasCheck(Group, PSE, *L, TypeInfo))
4843 continue;
4844
4845 // Use the last (most dominated) store's location for the unconditional
4846 // store.
4847 VPReplicateRecipe *LastStore = Group.back();
4848 VPBasicBlock *InsertBB = LastStore->getParent();
4849
4850 // Collect common alias metadata from all stores in the group.
4851 VPIRMetadata CommonMetadata = getCommonMetadata(Group);
4852
4853 // Build select chain for stored values.
4854 VPValue *SelectedValue = Group[0]->getOperand(0);
4855 VPBuilder Builder(InsertBB, LastStore->getIterator());
4856
4857 bool IsSingleScalar = Group[0]->isSingleScalar();
4858 for (unsigned I = 1; I < Group.size(); ++I) {
4859 assert(IsSingleScalar == Group[I]->isSingleScalar() &&
4860 "all members in group must agree on IsSingleScalar");
4861 VPValue *Mask = Group[I]->getMask();
4862 VPValue *Value = Group[I]->getOperand(0);
4863 SelectedValue = Builder.createSelect(Mask, Value, SelectedValue,
4864 Group[I]->getDebugLoc());
4865 }
4866
4867 // Find the store with minimum alignment to use.
4868 auto *StoreWithMinAlign = findRecipeWithMinAlign<StoreInst>(Group);
4869
4870 // Create unconditional store with selected value and common metadata.
4871 auto *UnpredicatedStore = new VPReplicateRecipe(
4872 StoreWithMinAlign->getUnderlyingInstr(),
4873 {SelectedValue, LastStore->getOperand(1)}, IsSingleScalar,
4874 /*Mask=*/nullptr, *LastStore, CommonMetadata);
4875 UnpredicatedStore->insertBefore(*InsertBB, LastStore->getIterator());
4876
4877 // Remove all predicated stores from the group.
4878 for (VPReplicateRecipe *Store : Group)
4879 Store->eraseFromParent();
4880 }
4881}
4882
4884 VPlan &Plan, ElementCount BestVF, unsigned BestUF,
4886 assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
4887 assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
4888
4889 VPValue *TC = Plan.getTripCount();
4890 if (TC->getNumUsers() == 0)
4891 return;
4892
4893 // Skip cases for which the trip count may be non-trivial to materialize.
4894 // I.e., when a scalar tail is absent - due to tail folding, or when a scalar
4895 // tail is required.
4896 if (!Plan.hasScalarTail() ||
4898 Plan.getScalarPreheader() ||
4899 !isa<VPIRValue>(TC))
4900 return;
4901
4902 // Materialize vector trip counts for constants early if it can simply
4903 // be computed as (Original TC / VF * UF) * VF * UF.
4904 // TODO: Compute vector trip counts for loops requiring a scalar epilogue and
4905 // tail-folded loops.
4906 ScalarEvolution &SE = *PSE.getSE();
4907 auto *TCScev = SE.getSCEV(TC->getLiveInIRValue());
4908 if (!isa<SCEVConstant>(TCScev))
4909 return;
4910 const SCEV *VFxUF = SE.getElementCount(TCScev->getType(), BestVF * BestUF);
4911 auto VecTCScev = SE.getMulExpr(SE.getUDivExpr(TCScev, VFxUF), VFxUF);
4912 if (auto *ConstVecTC = dyn_cast<SCEVConstant>(VecTCScev))
4913 Plan.getVectorTripCount().setUnderlyingValue(ConstVecTC->getValue());
4914}
4915
4917 VPBasicBlock *VectorPH) {
4919 if (BTC->getNumUsers() == 0)
4920 return;
4921
4922 VPBuilder Builder(VectorPH, VectorPH->begin());
4923 auto *TCTy = VPTypeAnalysis(Plan).inferScalarType(Plan.getTripCount());
4924 auto *TCMO =
4925 Builder.createSub(Plan.getTripCount(), Plan.getConstantInt(TCTy, 1),
4926 DebugLoc::getCompilerGenerated(), "trip.count.minus.1");
4927 BTC->replaceAllUsesWith(TCMO);
4928}
4929
4931 if (Plan.hasScalarVFOnly())
4932 return;
4933
4934 VPTypeAnalysis TypeInfo(Plan);
4935 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
4936 auto VPBBsOutsideLoopRegion = VPBlockUtils::blocksOnly<VPBasicBlock>(
4938 auto VPBBsInsideLoopRegion = VPBlockUtils::blocksOnly<VPBasicBlock>(
4939 vp_depth_first_shallow(LoopRegion->getEntry()));
4940 // Materialize Build(Struct)Vector for all replicating VPReplicateRecipes,
4941 // VPScalarIVStepsRecipe and VPInstructions, excluding ones in replicate
4942 // regions. Those are not materialized explicitly yet.
4943 // TODO: materialize build vectors for replicating recipes in replicating
4944 // regions.
4945 for (VPBasicBlock *VPBB :
4946 concat<VPBasicBlock *>(VPBBsOutsideLoopRegion, VPBBsInsideLoopRegion)) {
4947 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
4949 continue;
4950 auto *DefR = cast<VPSingleDefRecipe>(&R);
4951 auto UsesVectorOrInsideReplicateRegion = [DefR, LoopRegion](VPUser *U) {
4952 VPRegionBlock *ParentRegion = cast<VPRecipeBase>(U)->getRegion();
4953 return !U->usesScalars(DefR) || ParentRegion != LoopRegion;
4954 };
4955 if ((isa<VPReplicateRecipe>(DefR) &&
4956 cast<VPReplicateRecipe>(DefR)->isSingleScalar()) ||
4957 (isa<VPInstruction>(DefR) &&
4959 !cast<VPInstruction>(DefR)->doesGeneratePerAllLanes())) ||
4960 none_of(DefR->users(), UsesVectorOrInsideReplicateRegion))
4961 continue;
4962
4963 Type *ScalarTy = TypeInfo.inferScalarType(DefR);
4964 unsigned Opcode = ScalarTy->isStructTy()
4967 auto *BuildVector = new VPInstruction(Opcode, {DefR});
4968 BuildVector->insertAfter(DefR);
4969
4970 DefR->replaceUsesWithIf(
4971 BuildVector, [BuildVector, &UsesVectorOrInsideReplicateRegion](
4972 VPUser &U, unsigned) {
4973 return &U != BuildVector && UsesVectorOrInsideReplicateRegion(&U);
4974 });
4975 }
4976 }
4977
4978 // Create explicit VPInstructions to convert vectors to scalars. The current
4979 // implementation is conservative - it may miss some cases that may or may not
4980 // be vector values. TODO: introduce Unpacks speculatively - remove them later
4981 // if they are known to operate on scalar values.
4982 for (VPBasicBlock *VPBB : VPBBsInsideLoopRegion) {
4983 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
4985 VPDerivedIVRecipe>(&R))
4986 continue;
4987 for (VPValue *Def : R.definedValues()) {
4988 // Skip recipes that are single-scalar or only have their first lane
4989 // used.
4990 // TODO: The Defs skipped here may or may not be vector values.
4991 // Introduce Unpacks, and remove them later, if they are guaranteed to
4992 // produce scalar values.
4994 continue;
4995
4996 // At the moment, we create unpacks only for scalar users outside
4997 // replicate regions. Recipes inside replicate regions still extract the
4998 // required lanes implicitly.
4999 // TODO: Remove once replicate regions are unrolled completely.
5000 auto IsCandidateUnpackUser = [Def](VPUser *U) {
5001 VPRegionBlock *ParentRegion = cast<VPRecipeBase>(U)->getRegion();
5002 return U->usesScalars(Def) &&
5003 (!ParentRegion || !ParentRegion->isReplicator());
5004 };
5005 if (none_of(Def->users(), IsCandidateUnpackUser))
5006 continue;
5007
5008 auto *Unpack = new VPInstruction(VPInstruction::Unpack, {Def});
5009 if (R.isPhi())
5010 Unpack->insertBefore(*VPBB, VPBB->getFirstNonPhi());
5011 else
5012 Unpack->insertAfter(&R);
5013 Def->replaceUsesWithIf(Unpack,
5014 [&IsCandidateUnpackUser](VPUser &U, unsigned) {
5015 return IsCandidateUnpackUser(&U);
5016 });
5017 }
5018 }
5019 }
5020}
5021
5023 VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking,
5024 bool RequiresScalarEpilogue, VPValue *Step,
5025 std::optional<uint64_t> MaxRuntimeStep) {
5026 VPSymbolicValue &VectorTC = Plan.getVectorTripCount();
5027 // There's nothing to do if there are no users of the vector trip count or its
5028 // IR value has already been set.
5029 if (VectorTC.getNumUsers() == 0 || VectorTC.getUnderlyingValue())
5030 return;
5031
5032 VPValue *TC = Plan.getTripCount();
5033 Type *TCTy = VPTypeAnalysis(Plan).inferScalarType(TC);
5034 VPBasicBlock::iterator InsertPt = VectorPHVPBB->begin();
5035 if (auto *StepR = Step->getDefiningRecipe()) {
5036 assert(StepR->getParent() == VectorPHVPBB &&
5037 "Step must be defined in VectorPHVPBB");
5038 // Insert after Step's definition to maintain valid def-use ordering.
5039 InsertPt = std::next(StepR->getIterator());
5040 }
5041 VPBuilder Builder(VectorPHVPBB, InsertPt);
5042
5043 // For scalable steps, if TC is a constant and is divisible by the maximum
5044 // possible runtime step, then TC % Step == 0 for all valid vscale values
5045 // and the vector trip count equals TC directly.
5046 const APInt *TCVal;
5047 if (!RequiresScalarEpilogue && match(TC, m_APInt(TCVal)) && MaxRuntimeStep &&
5048 TCVal->getZExtValue() % *MaxRuntimeStep == 0) {
5049 VectorTC.replaceAllUsesWith(TC);
5050 return;
5051 }
5052
5053 // If the tail is to be folded by masking, round the number of iterations N
5054 // up to a multiple of Step instead of rounding down. This is done by first
5055 // adding Step-1 and then rounding down. Note that it's ok if this addition
5056 // overflows: the vector induction variable will eventually wrap to zero given
5057 // that it starts at zero and its Step is a power of two; the loop will then
5058 // exit, with the last early-exit vector comparison also producing all-true.
5059 if (TailByMasking) {
5060 TC = Builder.createAdd(
5061 TC, Builder.createSub(Step, Plan.getConstantInt(TCTy, 1)),
5062 DebugLoc::getCompilerGenerated(), "n.rnd.up");
5063 }
5064
5065 // Now we need to generate the expression for the part of the loop that the
5066 // vectorized body will execute. This is equal to N - (N % Step) if scalar
5067 // iterations are not required for correctness, or N - Step, otherwise. Step
5068 // is equal to the vectorization factor (number of SIMD elements) times the
5069 // unroll factor (number of SIMD instructions).
5070 VPValue *R =
5071 Builder.createNaryOp(Instruction::URem, {TC, Step},
5072 DebugLoc::getCompilerGenerated(), "n.mod.vf");
5073
5074 // There are cases where we *must* run at least one iteration in the remainder
5075 // loop. See the cost model for when this can happen. If the step evenly
5076 // divides the trip count, we set the remainder to be equal to the step. If
5077 // the step does not evenly divide the trip count, no adjustment is necessary
5078 // since there will already be scalar iterations. Note that the minimum
5079 // iterations check ensures that N >= Step.
5080 if (RequiresScalarEpilogue) {
5081 assert(!TailByMasking &&
5082 "requiring scalar epilogue is not supported with fail folding");
5083 VPValue *IsZero =
5084 Builder.createICmp(CmpInst::ICMP_EQ, R, Plan.getZero(TCTy));
5085 R = Builder.createSelect(IsZero, Step, R);
5086 }
5087
5088 VPValue *Res =
5089 Builder.createSub(TC, R, DebugLoc::getCompilerGenerated(), "n.vec");
5090 VectorTC.replaceAllUsesWith(Res);
5091}
5092
5094 ElementCount VFEC) {
5095 // If VF and VFxUF have already been materialized (no remaining users),
5096 // there's nothing more to do.
5097 if (Plan.getVF().isMaterialized()) {
5098 assert(Plan.getVFxUF().isMaterialized() &&
5099 "VF and VFxUF must be materialized together");
5100 return;
5101 }
5102
5103 VPBuilder Builder(VectorPH, VectorPH->begin());
5104 Type *TCTy = VPTypeAnalysis(Plan).inferScalarType(Plan.getTripCount());
5105 VPValue &VF = Plan.getVF();
5106 VPValue &VFxUF = Plan.getVFxUF();
5107 // If there are no users of the runtime VF, compute VFxUF by constant folding
5108 // the multiplication of VF and UF.
5109 if (VF.getNumUsers() == 0) {
5110 VPValue *RuntimeVFxUF =
5111 Builder.createElementCount(TCTy, VFEC * Plan.getConcreteUF());
5112 VFxUF.replaceAllUsesWith(RuntimeVFxUF);
5113 return;
5114 }
5115
5116 // For users of the runtime VF, compute it as VF * vscale, and VFxUF as (VF *
5117 // vscale) * UF.
5118 VPValue *RuntimeVF = Builder.createElementCount(TCTy, VFEC);
5120 VPValue *BC = Builder.createNaryOp(VPInstruction::Broadcast, RuntimeVF);
5122 BC, [&VF](VPUser &U, unsigned) { return !U.usesScalars(&VF); });
5123 }
5124 VF.replaceAllUsesWith(RuntimeVF);
5125
5126 VPValue *MulByUF = Builder.createOverflowingOp(
5127 Instruction::Mul,
5128 {RuntimeVF, Plan.getConstantInt(TCTy, Plan.getConcreteUF())},
5129 {true, false});
5130 VFxUF.replaceAllUsesWith(MulByUF);
5131}
5132
5135 SCEVExpander Expander(SE, "induction", /*PreserveLCSSA=*/false);
5136
5137 auto *Entry = cast<VPIRBasicBlock>(Plan.getEntry());
5138 BasicBlock *EntryBB = Entry->getIRBasicBlock();
5139 DenseMap<const SCEV *, Value *> ExpandedSCEVs;
5140 for (VPRecipeBase &R : make_early_inc_range(*Entry)) {
5142 continue;
5143 auto *ExpSCEV = dyn_cast<VPExpandSCEVRecipe>(&R);
5144 if (!ExpSCEV)
5145 break;
5146 const SCEV *Expr = ExpSCEV->getSCEV();
5147 Value *Res =
5148 Expander.expandCodeFor(Expr, Expr->getType(), EntryBB->getTerminator());
5149 ExpandedSCEVs[ExpSCEV->getSCEV()] = Res;
5150 VPValue *Exp = Plan.getOrAddLiveIn(Res);
5151 ExpSCEV->replaceAllUsesWith(Exp);
5152 if (Plan.getTripCount() == ExpSCEV)
5153 Plan.resetTripCount(Exp);
5154 ExpSCEV->eraseFromParent();
5155 }
5157 "VPExpandSCEVRecipes must be at the beginning of the entry block, "
5158 "before any VPIRInstructions");
5159 // Add IR instructions in the entry basic block but not in the VPIRBasicBlock
5160 // to the VPIRBasicBlock.
5161 auto EI = Entry->begin();
5162 for (Instruction &I : drop_end(*EntryBB)) {
5163 if (EI != Entry->end() && isa<VPIRInstruction>(*EI) &&
5164 &cast<VPIRInstruction>(&*EI)->getInstruction() == &I) {
5165 EI++;
5166 continue;
5167 }
5169 }
5170
5171 return ExpandedSCEVs;
5172}
5173
5174/// Returns true if \p V is VPWidenLoadRecipe or VPInterleaveRecipe that can be
5175/// converted to a narrower recipe. \p V is used by a wide recipe that feeds a
5176/// store interleave group at index \p Idx, \p WideMember0 is the recipe feeding
5177/// the same interleave group at index 0. A VPWidenLoadRecipe can be narrowed to
5178/// an index-independent load if it feeds all wide ops at all indices (\p OpV
5179/// must be the operand at index \p OpIdx for both the recipe at lane 0, \p
5180/// WideMember0). A VPInterleaveRecipe can be narrowed to a wide load, if \p V
5181/// is defined at \p Idx of a load interleave group.
5182static bool canNarrowLoad(VPSingleDefRecipe *WideMember0, unsigned OpIdx,
5183 VPValue *OpV, unsigned Idx, bool IsScalable) {
5184 VPValue *Member0Op = WideMember0->getOperand(OpIdx);
5185 VPRecipeBase *Member0OpR = Member0Op->getDefiningRecipe();
5186 if (!Member0OpR)
5187 return Member0Op == OpV;
5188 if (auto *W = dyn_cast<VPWidenLoadRecipe>(Member0OpR))
5189 // For scalable VFs, the narrowed plan processes vscale iterations at once,
5190 // so a shared wide load cannot be narrowed to a uniform scalar; bail out.
5191 return !IsScalable && !W->getMask() && W->isConsecutive() &&
5192 Member0Op == OpV;
5193 if (auto *IR = dyn_cast<VPInterleaveRecipe>(Member0OpR))
5194 return IR->getInterleaveGroup()->isFull() && IR->getVPValue(Idx) == OpV;
5195 return false;
5196}
5197
5198static bool canNarrowOps(ArrayRef<VPValue *> Ops, bool IsScalable) {
5200 auto *WideMember0 = dyn_cast<VPSingleDefRecipe>(Ops[0]);
5201 if (!WideMember0)
5202 return false;
5203 for (VPValue *V : Ops) {
5205 return false;
5206 auto *R = cast<VPSingleDefRecipe>(V);
5207 if (getOpcodeOrIntrinsicID(R) != getOpcodeOrIntrinsicID(WideMember0))
5208 return false;
5209 }
5210
5211 for (unsigned Idx = 0; Idx != WideMember0->getNumOperands(); ++Idx) {
5213 for (VPValue *Op : Ops)
5214 OpsI.push_back(Op->getDefiningRecipe()->getOperand(Idx));
5215
5216 if (canNarrowOps(OpsI, IsScalable))
5217 continue;
5218
5219 if (any_of(enumerate(OpsI), [WideMember0, Idx, IsScalable](const auto &P) {
5220 const auto &[OpIdx, OpV] = P;
5221 return !canNarrowLoad(WideMember0, Idx, OpV, OpIdx, IsScalable);
5222 }))
5223 return false;
5224 }
5225
5226 return true;
5227}
5228
5229/// Returns VF from \p VFs if \p IR is a full interleave group with factor and
5230/// number of members both equal to VF. The interleave group must also access
5231/// the full vector width.
5232static std::optional<ElementCount> isConsecutiveInterleaveGroup(
5234 VPTypeAnalysis &TypeInfo, const TargetTransformInfo &TTI) {
5235 if (!InterleaveR || InterleaveR->getMask())
5236 return std::nullopt;
5237
5238 Type *GroupElementTy = nullptr;
5239 if (InterleaveR->getStoredValues().empty()) {
5240 GroupElementTy = TypeInfo.inferScalarType(InterleaveR->getVPValue(0));
5241 if (!all_of(InterleaveR->definedValues(),
5242 [&TypeInfo, GroupElementTy](VPValue *Op) {
5243 return TypeInfo.inferScalarType(Op) == GroupElementTy;
5244 }))
5245 return std::nullopt;
5246 } else {
5247 GroupElementTy =
5248 TypeInfo.inferScalarType(InterleaveR->getStoredValues()[0]);
5249 if (!all_of(InterleaveR->getStoredValues(),
5250 [&TypeInfo, GroupElementTy](VPValue *Op) {
5251 return TypeInfo.inferScalarType(Op) == GroupElementTy;
5252 }))
5253 return std::nullopt;
5254 }
5255
5256 auto IG = InterleaveR->getInterleaveGroup();
5257 if (IG->getFactor() != IG->getNumMembers())
5258 return std::nullopt;
5259
5260 auto GetVectorBitWidthForVF = [&TTI](ElementCount VF) {
5261 TypeSize Size = TTI.getRegisterBitWidth(
5264 assert(Size.isScalable() == VF.isScalable() &&
5265 "if Size is scalable, VF must be scalable and vice versa");
5266 return Size.getKnownMinValue();
5267 };
5268
5269 for (ElementCount VF : VFs) {
5270 unsigned MinVal = VF.getKnownMinValue();
5271 unsigned GroupSize = GroupElementTy->getScalarSizeInBits() * MinVal;
5272 if (IG->getFactor() == MinVal && GroupSize == GetVectorBitWidthForVF(VF))
5273 return {VF};
5274 }
5275 return std::nullopt;
5276}
5277
5278/// Returns true if \p VPValue is a narrow VPValue.
5279static bool isAlreadyNarrow(VPValue *VPV) {
5280 if (isa<VPIRValue>(VPV))
5281 return true;
5282 auto *RepR = dyn_cast<VPReplicateRecipe>(VPV);
5283 return RepR && RepR->isSingleScalar();
5284}
5285
5286// Convert a wide recipe defining a VPValue \p V feeding an interleave group to
5287// a narrow variant.
5288static VPValue *
5290 auto *R = V->getDefiningRecipe();
5291 if (!R || NarrowedOps.contains(V))
5292 return V;
5293
5294 if (isAlreadyNarrow(V))
5295 return V;
5296
5298 auto *WideMember0 = cast<VPSingleDefRecipe>(R);
5299 for (unsigned Idx = 0, E = WideMember0->getNumOperands(); Idx != E; ++Idx)
5300 WideMember0->setOperand(
5301 Idx,
5302 narrowInterleaveGroupOp(WideMember0->getOperand(Idx), NarrowedOps));
5303 return V;
5304 }
5305
5306 if (auto *LoadGroup = dyn_cast<VPInterleaveRecipe>(R)) {
5307 // Narrow interleave group to wide load, as transformed VPlan will only
5308 // process one original iteration.
5309 auto *LI = cast<LoadInst>(LoadGroup->getInterleaveGroup()->getInsertPos());
5310 auto *L = new VPWidenLoadRecipe(*LI, LoadGroup->getAddr(),
5311 LoadGroup->getMask(), /*Consecutive=*/true,
5312 {}, LoadGroup->getDebugLoc());
5313 L->insertBefore(LoadGroup);
5314 NarrowedOps.insert(L);
5315 return L;
5316 }
5317
5318 if (auto *RepR = dyn_cast<VPReplicateRecipe>(R)) {
5319 assert(RepR->isSingleScalar() && RepR->getOpcode() == Instruction::Load &&
5320 "must be a single scalar load");
5321 NarrowedOps.insert(RepR);
5322 return RepR;
5323 }
5324
5325 auto *WideLoad = cast<VPWidenLoadRecipe>(R);
5326 VPValue *PtrOp = WideLoad->getAddr();
5327 if (auto *VecPtr = dyn_cast<VPVectorPointerRecipe>(PtrOp))
5328 PtrOp = VecPtr->getOperand(0);
5329 // Narrow wide load to uniform scalar load, as transformed VPlan will only
5330 // process one original iteration.
5331 auto *N = new VPReplicateRecipe(&WideLoad->getIngredient(), {PtrOp},
5332 /*IsUniform*/ true,
5333 /*Mask*/ nullptr, {}, *WideLoad);
5334 N->insertBefore(WideLoad);
5335 NarrowedOps.insert(N);
5336 return N;
5337}
5338
5339std::unique_ptr<VPlan>
5341 const TargetTransformInfo &TTI) {
5342 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
5343
5344 if (!VectorLoop)
5345 return nullptr;
5346
5347 // Only handle single-block loops for now.
5348 if (VectorLoop->getEntryBasicBlock() != VectorLoop->getExitingBasicBlock())
5349 return nullptr;
5350
5351 // Skip plans when we may not be able to properly narrow.
5352 VPBasicBlock *Exiting = VectorLoop->getExitingBasicBlock();
5353 if (!match(&Exiting->back(), m_BranchOnCount()))
5354 return nullptr;
5355
5356 assert(match(&Exiting->back(),
5358 m_Specific(&Plan.getVectorTripCount()))) &&
5359 "unexpected branch-on-count");
5360
5361 VPTypeAnalysis TypeInfo(Plan);
5363 std::optional<ElementCount> VFToOptimize;
5364 for (auto &R : *VectorLoop->getEntryBasicBlock()) {
5367 continue;
5368
5369 // Bail out on recipes not supported at the moment:
5370 // * phi recipes other than the canonical induction
5371 // * recipes writing to memory except interleave groups
5372 // Only support plans with a canonical induction phi.
5373 if (R.isPhi())
5374 return nullptr;
5375
5376 auto *InterleaveR = dyn_cast<VPInterleaveRecipe>(&R);
5377 if (R.mayWriteToMemory() && !InterleaveR)
5378 return nullptr;
5379
5380 // Bail out if any recipe defines a vector value used outside the
5381 // vector loop region.
5382 if (any_of(R.definedValues(), [&](VPValue *V) {
5383 return any_of(V->users(), [&](VPUser *U) {
5384 auto *UR = cast<VPRecipeBase>(U);
5385 return UR->getParent()->getParent() != VectorLoop;
5386 });
5387 }))
5388 return nullptr;
5389
5390 // All other ops are allowed, but we reject uses that cannot be converted
5391 // when checking all allowed consumers (store interleave groups) below.
5392 if (!InterleaveR)
5393 continue;
5394
5395 // Try to find a single VF, where all interleave groups are consecutive and
5396 // saturate the full vector width. If we already have a candidate VF, check
5397 // if it is applicable for the current InterleaveR, otherwise look for a
5398 // suitable VF across the Plan's VFs.
5400 VFToOptimize ? SmallVector<ElementCount>({*VFToOptimize})
5401 : to_vector(Plan.vectorFactors());
5402 std::optional<ElementCount> NarrowedVF =
5403 isConsecutiveInterleaveGroup(InterleaveR, VFs, TypeInfo, TTI);
5404 if (!NarrowedVF || (VFToOptimize && NarrowedVF != VFToOptimize))
5405 return nullptr;
5406 VFToOptimize = NarrowedVF;
5407
5408 // Skip read interleave groups.
5409 if (InterleaveR->getStoredValues().empty())
5410 continue;
5411
5412 // Narrow interleave groups, if all operands are already matching narrow
5413 // ops.
5414 auto *Member0 = InterleaveR->getStoredValues()[0];
5415 if (isAlreadyNarrow(Member0) &&
5416 all_of(InterleaveR->getStoredValues(), equal_to(Member0))) {
5417 StoreGroups.push_back(InterleaveR);
5418 continue;
5419 }
5420
5421 // For now, we only support full interleave groups storing load interleave
5422 // groups.
5423 if (all_of(enumerate(InterleaveR->getStoredValues()), [](auto Op) {
5424 VPRecipeBase *DefR = Op.value()->getDefiningRecipe();
5425 if (!DefR)
5426 return false;
5427 auto *IR = dyn_cast<VPInterleaveRecipe>(DefR);
5428 return IR && IR->getInterleaveGroup()->isFull() &&
5429 IR->getVPValue(Op.index()) == Op.value();
5430 })) {
5431 StoreGroups.push_back(InterleaveR);
5432 continue;
5433 }
5434
5435 // Check if all values feeding InterleaveR are matching wide recipes, which
5436 // operands that can be narrowed.
5437 if (!canNarrowOps(InterleaveR->getStoredValues(),
5438 VFToOptimize->isScalable()))
5439 return nullptr;
5440 StoreGroups.push_back(InterleaveR);
5441 }
5442
5443 if (StoreGroups.empty())
5444 return nullptr;
5445
5446 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
5447 bool RequiresScalarEpilogue =
5448 MiddleVPBB->getNumSuccessors() == 1 &&
5449 MiddleVPBB->getSingleSuccessor() == Plan.getScalarPreheader();
5450 // Bail out for tail-folding (middle block with a single successor to exit).
5451 if (MiddleVPBB->getNumSuccessors() != 2 && !RequiresScalarEpilogue)
5452 return nullptr;
5453
5454 // All interleave groups in Plan can be narrowed for VFToOptimize. Split the
5455 // original Plan into 2: a) a new clone which contains all VFs of Plan, except
5456 // VFToOptimize, and b) the original Plan with VFToOptimize as single VF.
5457 // TODO: Handle cases where only some interleave groups can be narrowed.
5458 std::unique_ptr<VPlan> NewPlan;
5459 if (size(Plan.vectorFactors()) != 1) {
5460 NewPlan = std::unique_ptr<VPlan>(Plan.duplicate());
5461 Plan.setVF(*VFToOptimize);
5462 NewPlan->removeVF(*VFToOptimize);
5463 }
5464
5465 // Convert InterleaveGroup \p R to a single VPWidenLoadRecipe.
5466 SmallPtrSet<VPValue *, 4> NarrowedOps;
5467 // Narrow operation tree rooted at store groups.
5468 for (auto *StoreGroup : StoreGroups) {
5469 VPValue *Res =
5470 narrowInterleaveGroupOp(StoreGroup->getStoredValues()[0], NarrowedOps);
5471 auto *SI =
5472 cast<StoreInst>(StoreGroup->getInterleaveGroup()->getInsertPos());
5473 auto *S = new VPWidenStoreRecipe(*SI, StoreGroup->getAddr(), Res, nullptr,
5474 /*Consecutive=*/true, {},
5475 StoreGroup->getDebugLoc());
5476 S->insertBefore(StoreGroup);
5477 StoreGroup->eraseFromParent();
5478 }
5479
5480 // Adjust induction to reflect that the transformed plan only processes one
5481 // original iteration.
5483 Type *CanIVTy = VectorLoop->getCanonicalIVType();
5484 VPBasicBlock *VectorPH = Plan.getVectorPreheader();
5485 VPBuilder PHBuilder(VectorPH, VectorPH->begin());
5486
5487 VPValue *UF = &Plan.getUF();
5488 VPValue *Step;
5489 if (VFToOptimize->isScalable()) {
5490 VPValue *VScale =
5491 PHBuilder.createElementCount(CanIVTy, ElementCount::getScalable(1));
5492 Step = PHBuilder.createOverflowingOp(Instruction::Mul, {VScale, UF},
5493 {true, false});
5494 Plan.getVF().replaceAllUsesWith(VScale);
5495 } else {
5496 Step = UF;
5497 Plan.getVF().replaceAllUsesWith(Plan.getConstantInt(CanIVTy, 1));
5498 }
5499 // Materialize vector trip count with the narrowed step.
5500 materializeVectorTripCount(Plan, VectorPH, /*TailByMasking=*/false,
5501 RequiresScalarEpilogue, Step);
5502
5503 CanIVInc->setOperand(1, Step);
5504 Plan.getVFxUF().replaceAllUsesWith(Step);
5505
5506 removeDeadRecipes(Plan);
5507 assert(none_of(*VectorLoop->getEntryBasicBlock(),
5509 "All VPVectorPointerRecipes should have been removed");
5510 return NewPlan;
5511}
5512
5513/// Add branch weight metadata, if the \p Plan's middle block is terminated by a
5514/// BranchOnCond recipe.
5516 VPlan &Plan, ElementCount VF, std::optional<unsigned> VScaleForTuning) {
5517 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
5518 auto *MiddleTerm =
5520 // Only add branch metadata if there is a (conditional) terminator.
5521 if (!MiddleTerm)
5522 return;
5523
5524 assert(MiddleTerm->getOpcode() == VPInstruction::BranchOnCond &&
5525 "must have a BranchOnCond");
5526 // Assume that `TripCount % VectorStep ` is equally distributed.
5527 unsigned VectorStep = Plan.getConcreteUF() * VF.getKnownMinValue();
5528 if (VF.isScalable() && VScaleForTuning.has_value())
5529 VectorStep *= *VScaleForTuning;
5530 assert(VectorStep > 0 && "trip count should not be zero");
5531 MDBuilder MDB(Plan.getContext());
5532 MDNode *BranchWeights =
5533 MDB.createBranchWeights({1, VectorStep - 1}, /*IsExpected=*/false);
5534 MiddleTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
5535}
5536
5538 VFRange &Range) {
5539 VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
5540 auto *MiddleVPBB = Plan.getMiddleBlock();
5541 VPBuilder MiddleBuilder(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
5542 VPTypeAnalysis TypeInfo(Plan);
5543
5544 auto IsScalableOne = [](ElementCount VF) -> bool {
5545 return VF == ElementCount::getScalable(1);
5546 };
5547
5548 for (auto &HeaderPhi : VectorRegion->getEntryBasicBlock()->phis()) {
5549 auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&HeaderPhi);
5550 if (!FOR)
5551 continue;
5552
5553 assert(VectorRegion->getSingleSuccessor() == Plan.getMiddleBlock() &&
5554 "Cannot handle loops with uncountable early exits");
5555
5556 // Find the existing splice for this FOR, created in
5557 // createHeaderPhiRecipes. All uses of FOR have already been replaced with
5558 // RecurSplice there; only RecurSplice itself still references FOR.
5559 auto *RecurSplice =
5561 assert(RecurSplice && "expected FirstOrderRecurrenceSplice");
5562
5563 // For VF vscale x 1, if vscale = 1, we are unable to extract the
5564 // penultimate value of the recurrence. Instead we rely on the existing
5565 // extract of the last element from the result of
5566 // VPInstruction::FirstOrderRecurrenceSplice.
5567 // TODO: Consider vscale_range info and UF.
5568 if (any_of(RecurSplice->users(),
5569 [](VPUser *U) { return !cast<VPRecipeBase>(U)->getRegion(); }) &&
5571 Range))
5572 return;
5573
5574 // This is the second phase of vectorizing first-order recurrences, creating
5575 // extracts for users outside the loop. An overview of the transformation is
5576 // described below. Suppose we have the following loop with some use after
5577 // the loop of the last a[i-1],
5578 //
5579 // for (int i = 0; i < n; ++i) {
5580 // t = a[i - 1];
5581 // b[i] = a[i] - t;
5582 // }
5583 // use t;
5584 //
5585 // There is a first-order recurrence on "a". For this loop, the shorthand
5586 // scalar IR looks like:
5587 //
5588 // scalar.ph:
5589 // s.init = a[-1]
5590 // br scalar.body
5591 //
5592 // scalar.body:
5593 // i = phi [0, scalar.ph], [i+1, scalar.body]
5594 // s1 = phi [s.init, scalar.ph], [s2, scalar.body]
5595 // s2 = a[i]
5596 // b[i] = s2 - s1
5597 // br cond, scalar.body, exit.block
5598 //
5599 // exit.block:
5600 // use = lcssa.phi [s1, scalar.body]
5601 //
5602 // In this example, s1 is a recurrence because it's value depends on the
5603 // previous iteration. In the first phase of vectorization, we created a
5604 // VPFirstOrderRecurrencePHIRecipe v1 for s1. Now we create the extracts
5605 // for users in the scalar preheader and exit block.
5606 //
5607 // vector.ph:
5608 // v_init = vector(..., ..., ..., a[-1])
5609 // br vector.body
5610 //
5611 // vector.body
5612 // i = phi [0, vector.ph], [i+4, vector.body]
5613 // v1 = phi [v_init, vector.ph], [v2, vector.body]
5614 // v2 = a[i, i+1, i+2, i+3]
5615 // v1' = splice(v1(3), v2(0, 1, 2))
5616 // b[i, i+1, i+2, i+3] = v2 - v1'
5617 // br cond, vector.body, middle.block
5618 //
5619 // middle.block:
5620 // vector.recur.extract.for.phi = v2(2)
5621 // vector.recur.extract = v2(3)
5622 // br cond, scalar.ph, exit.block
5623 //
5624 // scalar.ph:
5625 // scalar.recur.init = phi [vector.recur.extract, middle.block],
5626 // [s.init, otherwise]
5627 // br scalar.body
5628 //
5629 // scalar.body:
5630 // i = phi [0, scalar.ph], [i+1, scalar.body]
5631 // s1 = phi [scalar.recur.init, scalar.ph], [s2, scalar.body]
5632 // s2 = a[i]
5633 // b[i] = s2 - s1
5634 // br cond, scalar.body, exit.block
5635 //
5636 // exit.block:
5637 // lo = lcssa.phi [s1, scalar.body],
5638 // [vector.recur.extract.for.phi, middle.block]
5639 //
5640 // Update extracts of the splice in the middle block: they extract the
5641 // penultimate element of the recurrence.
5643 make_range(MiddleVPBB->getFirstNonPhi(), MiddleVPBB->end()))) {
5644 if (!match(&R, m_ExtractLastLaneOfLastPart(m_Specific(RecurSplice))))
5645 continue;
5646
5647 auto *ExtractR = cast<VPInstruction>(&R);
5648 VPValue *PenultimateElement = MiddleBuilder.createNaryOp(
5649 VPInstruction::ExtractPenultimateElement, RecurSplice->getOperand(1),
5650 {}, "vector.recur.extract.for.phi");
5651 for (VPUser *ExitU : to_vector(ExtractR->users())) {
5652 if (auto *ExitPhi = dyn_cast<VPIRPhi>(ExitU))
5653 ExitPhi->replaceUsesOfWith(ExtractR, PenultimateElement);
5654 }
5655 }
5656 }
5657}
5658
5659/// Check if \p V is a binary expression of a widened IV and a loop-invariant
5660/// value. Returns the widened IV if found, nullptr otherwise.
5662 auto *BinOp = dyn_cast<VPWidenRecipe>(V);
5663 if (!BinOp || !Instruction::isBinaryOp(BinOp->getOpcode()) ||
5664 Instruction::isIntDivRem(BinOp->getOpcode()))
5665 return nullptr;
5666
5667 VPValue *WidenIVCandidate = BinOp->getOperand(0);
5668 VPValue *InvariantCandidate = BinOp->getOperand(1);
5669 if (!isa<VPWidenIntOrFpInductionRecipe>(WidenIVCandidate))
5670 std::swap(WidenIVCandidate, InvariantCandidate);
5671
5672 if (!InvariantCandidate->isDefinedOutsideLoopRegions())
5673 return nullptr;
5674
5675 return dyn_cast<VPWidenIntOrFpInductionRecipe>(WidenIVCandidate);
5676}
5677
5678/// Create a scalar version of \p BinOp, with its \p WidenIV operand replaced
5679/// by \p ScalarIV, and place it after \p ScalarIV's defining recipe.
5683 BinOp->getNumOperands() == 2 && "BinOp must have 2 operands");
5684 auto *ClonedOp = BinOp->clone();
5685 if (ClonedOp->getOperand(0) == WidenIV) {
5686 ClonedOp->setOperand(0, ScalarIV);
5687 } else {
5688 assert(ClonedOp->getOperand(1) == WidenIV && "one operand must be WideIV");
5689 ClonedOp->setOperand(1, ScalarIV);
5690 }
5691 ClonedOp->insertAfter(ScalarIV->getDefiningRecipe());
5692 return ClonedOp;
5693}
5694
5697 Loop &L) {
5698 ScalarEvolution &SE = *PSE.getSE();
5699 VPRegionBlock *VectorLoopRegion = Plan.getVectorLoopRegion();
5700
5701 // Helper lambda to check if the IV range excludes the sentinel value. Try
5702 // signed first, then unsigned. Return an excluded sentinel if found,
5703 // otherwise return std::nullopt.
5704 auto CheckSentinel = [&SE](const SCEV *IVSCEV,
5705 bool UseMax) -> std::optional<APSInt> {
5706 unsigned BW = IVSCEV->getType()->getScalarSizeInBits();
5707 for (bool Signed : {true, false}) {
5708 APSInt Sentinel = UseMax ? APSInt::getMinValue(BW, /*Unsigned=*/!Signed)
5709 : APSInt::getMaxValue(BW, /*Unsigned=*/!Signed);
5710
5711 ConstantRange IVRange =
5712 Signed ? SE.getSignedRange(IVSCEV) : SE.getUnsignedRange(IVSCEV);
5713 if (!IVRange.contains(Sentinel))
5714 return Sentinel;
5715 }
5716 return std::nullopt;
5717 };
5718
5719 VPValue *HeaderMask = vputils::findHeaderMask(Plan);
5720 for (VPRecipeBase &Phi :
5721 make_early_inc_range(VectorLoopRegion->getEntryBasicBlock()->phis())) {
5722 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&Phi);
5724 PhiR->getRecurrenceKind()))
5725 continue;
5726
5727 Type *PhiTy = VPTypeAnalysis(Plan).inferScalarType(PhiR);
5728 if (PhiTy->isPointerTy() || PhiTy->isFloatingPointTy())
5729 continue;
5730
5731 // If there's a header mask, the backedge select will not be the find-last
5732 // select.
5733 VPValue *BackedgeVal = PhiR->getBackedgeValue();
5734 auto *FindLastSelect = cast<VPSingleDefRecipe>(BackedgeVal);
5735 if (HeaderMask &&
5736 !match(BackedgeVal,
5737 m_Select(m_Specific(HeaderMask),
5738 m_VPSingleDefRecipe(FindLastSelect), m_Specific(PhiR))))
5739 continue;
5740
5741 // Get the find-last expression from the find-last select of the reduction
5742 // phi. The find-last select should be a select between the phi and the
5743 // find-last expression.
5744 VPValue *Cond, *FindLastExpression;
5745 if (!match(FindLastSelect, m_Select(m_VPValue(Cond), m_Specific(PhiR),
5746 m_VPValue(FindLastExpression))) &&
5747 !match(FindLastSelect,
5748 m_Select(m_VPValue(Cond), m_VPValue(FindLastExpression),
5749 m_Specific(PhiR))))
5750 continue;
5751
5752 // Check if FindLastExpression is a simple expression of a widened IV. If
5753 // so, we can track the underlying IV instead and sink the expression.
5754 auto *IVOfExpressionToSink = getExpressionIV(FindLastExpression);
5755 const SCEV *IVSCEV = vputils::getSCEVExprForVPValue(
5756 IVOfExpressionToSink ? IVOfExpressionToSink : FindLastExpression, PSE,
5757 &L);
5758 const SCEV *Step;
5759 if (!match(IVSCEV, m_scev_AffineAddRec(m_SCEV(), m_SCEV(Step)))) {
5760 assert(!match(vputils::getSCEVExprForVPValue(FindLastExpression, PSE, &L),
5762 "IVOfExpressionToSink not being an AddRec must imply "
5763 "FindLastExpression not being an AddRec.");
5764 continue;
5765 }
5766
5767 // Determine direction from SCEV step.
5768 if (!SE.isKnownNonZero(Step))
5769 continue;
5770
5771 // Positive step means we need UMax/SMax to find the last IV value, and
5772 // UMin/SMin otherwise.
5773 bool UseMax = SE.isKnownPositive(Step);
5774 std::optional<APSInt> SentinelVal = CheckSentinel(IVSCEV, UseMax);
5775 bool UseSigned = SentinelVal && SentinelVal->isSigned();
5776
5777 // Sinking an expression will disable epilogue vectorization. Only use it,
5778 // if FindLastExpression cannot be vectorized via a sentinel. Sinking may
5779 // also prevent vectorizing using a sentinel (e.g., if the expression is a
5780 // multiply or divide by large constant, respectively), which also makes
5781 // sinking undesirable.
5782 if (IVOfExpressionToSink) {
5783 const SCEV *FindLastExpressionSCEV =
5784 vputils::getSCEVExprForVPValue(FindLastExpression, PSE, &L);
5785 if (match(FindLastExpressionSCEV,
5786 m_scev_AffineAddRec(m_SCEV(), m_SCEV(Step)))) {
5787 bool NewUseMax = SE.isKnownPositive(Step);
5788 if (auto NewSentinel =
5789 CheckSentinel(FindLastExpressionSCEV, NewUseMax)) {
5790 // The original expression already has a sentinel, so prefer not
5791 // sinking to keep epilogue vectorization possible.
5792 SentinelVal = *NewSentinel;
5793 UseSigned = NewSentinel->isSigned();
5794 UseMax = NewUseMax;
5795 IVSCEV = FindLastExpressionSCEV;
5796 IVOfExpressionToSink = nullptr;
5797 }
5798 }
5799 }
5800
5801 // If no sentinel was found, fall back to a boolean AnyOf reduction to track
5802 // if the condition was ever true. Requires the IV to not wrap, otherwise we
5803 // cannot use min/max.
5804 if (!SentinelVal) {
5805 auto *AR = cast<SCEVAddRecExpr>(IVSCEV);
5806 if (AR->hasNoSignedWrap())
5807 UseSigned = true;
5808 else if (AR->hasNoUnsignedWrap())
5809 UseSigned = false;
5810 else
5811 continue;
5812 }
5813
5815 BackedgeVal,
5817
5818 VPValue *NewFindLastSelect = BackedgeVal;
5819 VPValue *SelectCond = Cond;
5820 if (!SentinelVal || IVOfExpressionToSink) {
5821 // When we need to create a new select, normalize the condition so that
5822 // PhiR is the last operand and include the header mask if needed.
5823 DebugLoc DL = FindLastSelect->getDefiningRecipe()->getDebugLoc();
5824 VPBuilder LoopBuilder(FindLastSelect->getDefiningRecipe());
5825 if (FindLastSelect->getDefiningRecipe()->getOperand(1) == PhiR)
5826 SelectCond = LoopBuilder.createNot(SelectCond);
5827
5828 // When tail folding, mask the condition with the header mask to prevent
5829 // propagating poison from inactive lanes in the last vector iteration.
5830 if (HeaderMask)
5831 SelectCond = LoopBuilder.createLogicalAnd(HeaderMask, SelectCond);
5832
5833 if (SelectCond != Cond || IVOfExpressionToSink) {
5834 NewFindLastSelect = LoopBuilder.createSelect(
5835 SelectCond,
5836 IVOfExpressionToSink ? IVOfExpressionToSink : FindLastExpression,
5837 PhiR, DL);
5838 }
5839 }
5840
5841 // Create the reduction result in the middle block using sentinel directly.
5842 RecurKind MinMaxKind =
5843 UseMax ? (UseSigned ? RecurKind::SMax : RecurKind::UMax)
5844 : (UseSigned ? RecurKind::SMin : RecurKind::UMin);
5845 VPIRFlags Flags(MinMaxKind, /*IsOrdered=*/false, /*IsInLoop=*/false,
5846 FastMathFlags());
5847 DebugLoc ExitDL = RdxResult->getDebugLoc();
5848 VPBuilder MiddleBuilder(RdxResult);
5849 VPValue *ReducedIV =
5851 NewFindLastSelect, Flags, ExitDL);
5852
5853 // If IVOfExpressionToSink is an expression to sink, sink it now.
5854 VPValue *VectorRegionExitingVal = ReducedIV;
5855 if (IVOfExpressionToSink)
5856 VectorRegionExitingVal =
5857 cloneBinOpForScalarIV(cast<VPWidenRecipe>(FindLastExpression),
5858 ReducedIV, IVOfExpressionToSink);
5859
5860 VPValue *NewRdxResult;
5861 VPValue *StartVPV = PhiR->getStartValue();
5862 if (SentinelVal) {
5863 // Sentinel-based approach: reduce IVs with min/max, compare against
5864 // sentinel to detect if condition was ever true, select accordingly.
5865 VPValue *Sentinel = Plan.getConstantInt(*SentinelVal);
5866 auto *Cmp = MiddleBuilder.createICmp(CmpInst::ICMP_NE, ReducedIV,
5867 Sentinel, ExitDL);
5868 NewRdxResult = MiddleBuilder.createSelect(Cmp, VectorRegionExitingVal,
5869 StartVPV, ExitDL);
5870 StartVPV = Sentinel;
5871 } else {
5872 // Introduce a boolean AnyOf reduction to track if the condition was ever
5873 // true in the loop. Use it to select the initial start value, if it was
5874 // never true.
5875 auto *AnyOfPhi = new VPReductionPHIRecipe(
5876 /*Phi=*/nullptr, RecurKind::Or, *Plan.getFalse(), *Plan.getFalse(),
5877 RdxUnordered{1}, {}, /*HasUsesOutsideReductionChain=*/false);
5878 AnyOfPhi->insertAfter(PhiR);
5879
5880 VPBuilder LoopBuilder(BackedgeVal->getDefiningRecipe());
5881 VPValue *OrVal = LoopBuilder.createOr(AnyOfPhi, SelectCond);
5882 AnyOfPhi->setOperand(1, OrVal);
5883
5884 NewRdxResult = MiddleBuilder.createAnyOfReduction(
5885 OrVal, VectorRegionExitingVal, StartVPV, ExitDL);
5886
5887 // Initialize the IV reduction phi with the neutral element, not the
5888 // original start value, to ensure correct min/max reduction results.
5889 StartVPV = Plan.getOrAddLiveIn(
5890 getRecurrenceIdentity(MinMaxKind, IVSCEV->getType(), {}));
5891 }
5892 RdxResult->replaceAllUsesWith(NewRdxResult);
5893 RdxResult->eraseFromParent();
5894
5895 auto *NewPhiR = new VPReductionPHIRecipe(
5896 cast<PHINode>(PhiR->getUnderlyingInstr()), RecurKind::FindIV, *StartVPV,
5897 *NewFindLastSelect, RdxUnordered{1}, {},
5898 PhiR->hasUsesOutsideReductionChain());
5899 NewPhiR->insertBefore(PhiR);
5900 PhiR->replaceAllUsesWith(NewPhiR);
5901 PhiR->eraseFromParent();
5902 }
5903}
5904
5905namespace {
5906
5907using ExtendKind = TTI::PartialReductionExtendKind;
5908struct ReductionExtend {
5909 Type *SrcType = nullptr;
5910 ExtendKind Kind = ExtendKind::PR_None;
5911};
5912
5913/// Describes the extends used to compute the extended reduction operand.
5914/// ExtendB is optional. If ExtendB is present, ExtendsUser is a binary
5915/// operation.
5916struct ExtendedReductionOperand {
5917 /// The recipe that consumes the extends.
5918 VPWidenRecipe *ExtendsUser = nullptr;
5919 /// Extend descriptions (inputs to getPartialReductionCost).
5920 ReductionExtend ExtendA, ExtendB;
5921};
5922
5923/// A chain of recipes that form a partial reduction. Matches either
5924/// reduction_bin_op (extended op, accumulator), or
5925/// reduction_bin_op (accumulator, extended op).
5926/// The possible forms of the "extended op" are listed in
5927/// matchExtendedReductionOperand.
5928struct VPPartialReductionChain {
5929 /// The top-level binary operation that forms the reduction to a scalar
5930 /// after the loop body.
5931 VPWidenRecipe *ReductionBinOp = nullptr;
5932 /// The user of the extends that is then reduced.
5933 ExtendedReductionOperand ExtendedOp;
5934 /// The recurrence kind for the entire partial reduction chain.
5935 /// This allows distinguishing between Sub and AddWithSub recurrences,
5936 /// when the ReductionBinOp is a Instruction::Sub.
5937 RecurKind RK;
5938 /// The index of the accumulator operand of ReductionBinOp. The extended op
5939 /// is `1 - AccumulatorOpIdx`.
5940 unsigned AccumulatorOpIdx;
5941 unsigned ScaleFactor;
5942};
5943
5944static VPSingleDefRecipe *
5945optimizeExtendsForPartialReduction(VPSingleDefRecipe *Op,
5946 VPTypeAnalysis &TypeInfo) {
5947 // reduce.add(mul(ext(A), C))
5948 // -> reduce.add(mul(ext(A), ext(trunc(C))))
5949 const APInt *Const;
5950 if (match(Op, m_Mul(m_ZExtOrSExt(m_VPValue()), m_APInt(Const)))) {
5951 auto *ExtA = cast<VPWidenCastRecipe>(Op->getOperand(0));
5952 Instruction::CastOps ExtOpc = ExtA->getOpcode();
5953 Type *NarrowTy = TypeInfo.inferScalarType(ExtA->getOperand(0));
5954 if (!Op->hasOneUse() ||
5956 Const, NarrowTy, TTI::getPartialReductionExtendKind(ExtOpc)))
5957 return Op;
5958
5959 VPBuilder Builder(Op);
5960 auto *Trunc = Builder.createWidenCast(Instruction::CastOps::Trunc,
5961 Op->getOperand(1), NarrowTy);
5962 Type *WideTy = TypeInfo.inferScalarType(ExtA);
5963 Op->setOperand(1, Builder.createWidenCast(ExtOpc, Trunc, WideTy));
5964 return Op;
5965 }
5966
5967 // reduce.add(abs(sub(ext(A), ext(B))))
5968 // -> reduce.add(ext(absolute-difference(A, B)))
5969 VPValue *X, *Y;
5972 auto *Sub = Op->getOperand(0)->getDefiningRecipe();
5973 auto *Ext = cast<VPWidenCastRecipe>(Sub->getOperand(0));
5974 assert(Ext->getOpcode() ==
5975 cast<VPWidenCastRecipe>(Sub->getOperand(1))->getOpcode() &&
5976 "Expected both the LHS and RHS extends to be the same");
5977 bool IsSigned = Ext->getOpcode() == Instruction::SExt;
5978 VPBuilder Builder(Op);
5979 Type *SrcTy = TypeInfo.inferScalarType(X);
5980 auto *FreezeX = Builder.insert(new VPWidenRecipe(Instruction::Freeze, {X}));
5981 auto *FreezeY = Builder.insert(new VPWidenRecipe(Instruction::Freeze, {Y}));
5982 auto *Max = Builder.insert(
5983 new VPWidenIntrinsicRecipe(IsSigned ? Intrinsic::smax : Intrinsic::umax,
5984 {FreezeX, FreezeY}, SrcTy));
5985 auto *Min = Builder.insert(
5986 new VPWidenIntrinsicRecipe(IsSigned ? Intrinsic::smin : Intrinsic::umin,
5987 {FreezeX, FreezeY}, SrcTy));
5988 auto *AbsDiff =
5989 Builder.insert(new VPWidenRecipe(Instruction::Sub, {Max, Min}));
5990 return Builder.createWidenCast(Instruction::CastOps::ZExt, AbsDiff,
5991 TypeInfo.inferScalarType(Op));
5992 }
5993
5994 // reduce.add(ext(mul(ext(A), ext(B))))
5995 // -> reduce.add(mul(wider_ext(A), wider_ext(B)))
5996 // TODO: Support this optimization for float types.
5998 m_ZExtOrSExt(m_VPValue()))))) {
5999 auto *Ext = cast<VPWidenCastRecipe>(Op);
6000 auto *Mul = cast<VPWidenRecipe>(Ext->getOperand(0));
6001 auto *MulLHS = cast<VPWidenCastRecipe>(Mul->getOperand(0));
6002 auto *MulRHS = cast<VPWidenCastRecipe>(Mul->getOperand(1));
6003 if (!Mul->hasOneUse() ||
6004 (Ext->getOpcode() != MulLHS->getOpcode() && MulLHS != MulRHS) ||
6005 MulLHS->getOpcode() != MulRHS->getOpcode())
6006 return Op;
6007 VPBuilder Builder(Mul);
6008 Mul->setOperand(0, Builder.createWidenCast(MulLHS->getOpcode(),
6009 MulLHS->getOperand(0),
6010 Ext->getScalarType()));
6011 Mul->setOperand(1, MulLHS == MulRHS
6012 ? Mul->getOperand(0)
6013 : Builder.createWidenCast(MulRHS->getOpcode(),
6014 MulRHS->getOperand(0),
6015 Ext->getScalarType()));
6016 return Mul;
6017 }
6018
6019 return Op;
6020}
6021
6022static VPExpressionRecipe *
6023createPartialReductionExpression(VPReductionRecipe *Red) {
6024 VPValue *VecOp = Red->getVecOp();
6025
6026 // reduce.[f]add(ext(op))
6027 // -> VPExpressionRecipe(op, red)
6028 if (match(VecOp, m_WidenAnyExtend(m_VPValue())))
6029 return new VPExpressionRecipe(cast<VPWidenCastRecipe>(VecOp), Red);
6030
6031 // reduce.[f]add([f]mul(ext(a), ext(b)))
6032 // -> VPExpressionRecipe(a, b, mul, red)
6033 if (match(VecOp, m_FMul(m_FPExt(m_VPValue()), m_FPExt(m_VPValue()))) ||
6034 match(VecOp,
6036 auto *Mul = cast<VPWidenRecipe>(VecOp);
6037 auto *ExtA = cast<VPWidenCastRecipe>(Mul->getOperand(0));
6038 auto *ExtB = cast<VPWidenCastRecipe>(Mul->getOperand(1));
6039 return new VPExpressionRecipe(ExtA, ExtB, Mul, Red);
6040 }
6041
6042 // reduce.add(neg(mul(ext(a), ext(b))))
6043 // -> VPExpressionRecipe(a, b, mul, sub, red)
6045 m_ZExtOrSExt(m_VPValue()))))) {
6046 auto *Sub = cast<VPWidenRecipe>(VecOp);
6047 auto *Mul = cast<VPWidenRecipe>(Sub->getOperand(1));
6048 auto *ExtA = cast<VPWidenCastRecipe>(Mul->getOperand(0));
6049 auto *ExtB = cast<VPWidenCastRecipe>(Mul->getOperand(1));
6050 return new VPExpressionRecipe(ExtA, ExtB, Mul, Sub, Red);
6051 }
6052
6053 llvm_unreachable("Unsupported expression");
6054}
6055
6056// Helper to transform a partial reduction chain into a partial reduction
6057// recipe. Assumes profitability has been checked.
6058static void transformToPartialReduction(const VPPartialReductionChain &Chain,
6059 VPTypeAnalysis &TypeInfo, VPlan &Plan,
6060 VPReductionPHIRecipe *RdxPhi) {
6061 VPWidenRecipe *WidenRecipe = Chain.ReductionBinOp;
6062 assert(WidenRecipe->getNumOperands() == 2 && "Expected binary operation");
6063
6064 VPValue *Accumulator = WidenRecipe->getOperand(Chain.AccumulatorOpIdx);
6065 auto *ExtendedOp = cast<VPSingleDefRecipe>(
6066 WidenRecipe->getOperand(1 - Chain.AccumulatorOpIdx));
6067
6068 // Sub-reductions can be implemented in two ways:
6069 // (1) negate the operand in the vector loop (the default way).
6070 // (2) subtract the reduced value from the init value in the middle block.
6071 // Both ways keep the reduction itself as an 'add' reduction.
6072 //
6073 // The ISD nodes for partial reductions don't support folding the
6074 // sub/negation into its operands because the following is not a valid
6075 // transformation:
6076 // sub(0, mul(ext(a), ext(b)))
6077 // -> mul(ext(a), ext(sub(0, b)))
6078 //
6079 // It's therefore better to choose option (2) such that the partial
6080 // reduction is always positive (starting at '0') and to do a final
6081 // subtract in the middle block.
6082 if (WidenRecipe->getOpcode() == Instruction::Sub &&
6083 Chain.RK != RecurKind::Sub) {
6084 VPBuilder Builder(WidenRecipe);
6085 Type *ElemTy = TypeInfo.inferScalarType(ExtendedOp);
6086 auto *Zero = Plan.getZero(ElemTy);
6087 auto *NegRecipe =
6088 new VPWidenRecipe(Instruction::Sub, {Zero, ExtendedOp}, VPIRFlags(),
6090 Builder.insert(NegRecipe);
6091 ExtendedOp = NegRecipe;
6092 }
6093
6094 assert((Chain.RK != RecurKind::FAddChainWithSubs) &&
6095 "FSub chain reduction isn't supported");
6096
6097 // FIXME: Do these transforms before invoking the cost-model.
6098 ExtendedOp = optimizeExtendsForPartialReduction(ExtendedOp, TypeInfo);
6099
6100 // Check if WidenRecipe is the final result of the reduction. If so look
6101 // through selects for predicated reductions.
6102 VPValue *Cond = nullptr;
6104 WidenRecipe,
6105 m_Select(m_VPValue(Cond), m_Specific(WidenRecipe), m_Specific(RdxPhi))));
6106 bool IsLastInChain = RdxPhi->getBackedgeValue() == WidenRecipe ||
6107 RdxPhi->getBackedgeValue() == ExitValue;
6108 assert((!ExitValue || IsLastInChain) &&
6109 "if we found ExitValue, it must match RdxPhi's backedge value");
6110
6111 Type *PhiType = TypeInfo.inferScalarType(RdxPhi);
6112 RecurKind RdxKind =
6114 auto *PartialRed = new VPReductionRecipe(
6115 RdxKind,
6116 RdxKind == RecurKind::FAdd ? WidenRecipe->getFastMathFlags()
6117 : FastMathFlags(),
6118 WidenRecipe->getUnderlyingInstr(), Accumulator, ExtendedOp, Cond,
6119 RdxUnordered{/*VFScaleFactor=*/Chain.ScaleFactor});
6120 PartialRed->insertBefore(WidenRecipe);
6121
6122 if (Cond)
6123 ExitValue->replaceAllUsesWith(PartialRed);
6124 WidenRecipe->replaceAllUsesWith(PartialRed);
6125
6126 // For cost-model purposes, fold this into a VPExpression.
6127 VPExpressionRecipe *E = createPartialReductionExpression(PartialRed);
6128 E->insertBefore(WidenRecipe);
6129 PartialRed->replaceAllUsesWith(E);
6130
6131 // We only need to update the PHI node once, which is when we find the
6132 // last reduction in the chain.
6133 if (!IsLastInChain)
6134 return;
6135
6136 // Scale the PHI and ReductionStartVector by the VFScaleFactor
6137 assert(RdxPhi->getVFScaleFactor() == 1 && "scale factor must not be set");
6138 RdxPhi->setVFScaleFactor(Chain.ScaleFactor);
6139
6140 auto *StartInst = cast<VPInstruction>(RdxPhi->getStartValue());
6141 assert(StartInst->getOpcode() == VPInstruction::ReductionStartVector);
6142 auto *NewScaleFactor = Plan.getConstantInt(32, Chain.ScaleFactor);
6143 StartInst->setOperand(2, NewScaleFactor);
6144
6145 // If this is the last value in a sub-reduction chain, then update the PHI
6146 // node to start at `0` and update the reduction-result to subtract from
6147 // the PHI's start value.
6148 if (Chain.RK != RecurKind::Sub && Chain.RK != RecurKind::FSub)
6149 return;
6150
6151 VPValue *OldStartValue = StartInst->getOperand(0);
6152 StartInst->setOperand(0, StartInst->getOperand(1));
6153
6154 // Replace reduction_result by 'sub (startval, reductionresult)'.
6156 assert(RdxResult && "Could not find reduction result");
6157
6158 VPBuilder Builder = VPBuilder::getToInsertAfter(RdxResult);
6159 unsigned SubOpc = Chain.RK == RecurKind::FSub ? Instruction::BinaryOps::FSub
6160 : Instruction::BinaryOps::Sub;
6161 VPInstruction *NewResult = Builder.createNaryOp(
6162 SubOpc, {OldStartValue, RdxResult}, VPIRFlags::getDefaultFlags(SubOpc),
6163 RdxPhi->getDebugLoc());
6164 RdxResult->replaceUsesWithIf(
6165 NewResult,
6166 [&NewResult](VPUser &U, unsigned Idx) { return &U != NewResult; });
6167}
6168
6169/// Returns the cost of a link in a partial-reduction chain for a given VF.
6170static InstructionCost
6171getPartialReductionLinkCost(VPCostContext &CostCtx,
6172 const VPPartialReductionChain &Link,
6173 ElementCount VF) {
6174 Type *RdxType = CostCtx.Types.inferScalarType(Link.ReductionBinOp);
6175 const ExtendedReductionOperand &ExtendedOp = Link.ExtendedOp;
6176 std::optional<unsigned> BinOpc = std::nullopt;
6177 // If ExtendB is not none, then the "ExtendsUser" is the binary operation.
6178 if (ExtendedOp.ExtendB.Kind != ExtendKind::PR_None)
6179 BinOpc = ExtendedOp.ExtendsUser->getOpcode();
6180
6181 std::optional<llvm::FastMathFlags> Flags;
6182 if (RdxType->isFloatingPointTy())
6183 Flags = Link.ReductionBinOp->getFastMathFlags();
6184
6185 auto GetLinkOpcode = [&Link]() -> unsigned {
6186 switch (Link.RK) {
6187 case RecurKind::Sub:
6188 return Instruction::Add;
6189 case RecurKind::FSub:
6190 return Instruction::FAdd;
6191 default:
6192 return Link.ReductionBinOp->getOpcode();
6193 }
6194 };
6195
6196 return CostCtx.TTI.getPartialReductionCost(
6197 GetLinkOpcode(), ExtendedOp.ExtendA.SrcType, ExtendedOp.ExtendB.SrcType,
6198 RdxType, VF, ExtendedOp.ExtendA.Kind, ExtendedOp.ExtendB.Kind, BinOpc,
6199 CostCtx.CostKind, Flags);
6200}
6201
6202static ExtendKind getPartialReductionExtendKind(VPWidenCastRecipe *Cast) {
6204}
6205
6206/// Checks if \p Op (which is an operand of \p UpdateR) is an extended reduction
6207/// operand. This is an operand where the source of the value (e.g. a load) has
6208/// been extended (sext, zext, or fpext) before it is used in the reduction.
6209///
6210/// Possible forms matched by this function:
6211/// - UpdateR(PrevValue, ext(...))
6212/// - UpdateR(PrevValue, mul(ext(...), ext(...)))
6213/// - UpdateR(PrevValue, mul(ext(...), Constant))
6214/// - UpdateR(PrevValue, ext(mul(ext(...), ext(...))))
6215/// - UpdateR(PrevValue, ext(mul(ext(...), Constant)))
6216/// - UpdateR(PrevValue, abs(sub(ext(...), ext(...)))
6217///
6218/// Note: The second operand of UpdateR corresponds to \p Op in the examples.
6219static std::optional<ExtendedReductionOperand>
6220matchExtendedReductionOperand(VPWidenRecipe *UpdateR, VPValue *Op,
6221 VPTypeAnalysis &TypeInfo) {
6222 assert(is_contained(UpdateR->operands(), Op) &&
6223 "Op should be operand of UpdateR");
6224
6225 // Try matching an absolute difference operand of the form
6226 // `abs(sub(ext(A), ext(B)))`. This will be later transformed into
6227 // `ext(absolute-difference(A, B))`. This allows us to perform the absolute
6228 // difference on a wider type and get the extend for "free" from the partial
6229 // reduction.
6230 VPValue *X, *Y;
6231 if (Op->hasOneUse() &&
6235 auto *Abs = cast<VPWidenIntrinsicRecipe>(Op);
6236 auto *Sub = cast<VPWidenRecipe>(Abs->getOperand(0));
6237 auto *LHSExt = cast<VPWidenCastRecipe>(Sub->getOperand(0));
6238 auto *RHSExt = cast<VPWidenCastRecipe>(Sub->getOperand(1));
6239 Type *LHSInputType = TypeInfo.inferScalarType(X);
6240 Type *RHSInputType = TypeInfo.inferScalarType(Y);
6241 if (LHSInputType != RHSInputType ||
6242 LHSExt->getOpcode() != RHSExt->getOpcode())
6243 return std::nullopt;
6244 // Note: This is essentially the same as matching ext(...) as we will
6245 // rewrite this operand to ext(absolute-difference(A, B)).
6246 return ExtendedReductionOperand{
6247 Sub,
6248 /*ExtendA=*/{LHSInputType, getPartialReductionExtendKind(LHSExt)},
6249 /*ExtendB=*/{}};
6250 }
6251
6252 std::optional<TTI::PartialReductionExtendKind> OuterExtKind;
6254 auto *CastRecipe = cast<VPWidenCastRecipe>(Op);
6255 VPValue *CastSource = CastRecipe->getOperand(0);
6256 OuterExtKind = getPartialReductionExtendKind(CastRecipe);
6257 if (match(CastSource, m_Mul(m_VPValue(), m_VPValue())) ||
6258 match(CastSource, m_FMul(m_VPValue(), m_VPValue()))) {
6259 // Match: ext(mul(...))
6260 // Record the outer extend kind and set `Op` to the mul. We can then match
6261 // this as a binary operation. Note: We can optimize out the outer extend
6262 // by widening the inner extends to match it. See
6263 // optimizeExtendsForPartialReduction.
6264 Op = CastSource;
6265 // FIXME: createPartialReductionExpression can't handle sub(ext(mul(...)))
6266 if (UpdateR->getOpcode() == Instruction::Sub)
6267 return std::nullopt;
6268 } else if (UpdateR->getOpcode() == Instruction::Add ||
6269 UpdateR->getOpcode() == Instruction::FAdd) {
6270 // Match: UpdateR(PrevValue, ext(...))
6271 // TODO: Remove the add/fadd restriction (we should be able to handle this
6272 // case for sub reductions too).
6273 return ExtendedReductionOperand{
6274 UpdateR,
6275 /*ExtendA=*/{TypeInfo.inferScalarType(CastSource), *OuterExtKind},
6276 /*ExtendB=*/{}};
6277 }
6278 }
6279
6280 if (!Op->hasOneUse())
6281 return std::nullopt;
6282
6284 if (!MulOp ||
6285 !is_contained({Instruction::Mul, Instruction::FMul}, MulOp->getOpcode()))
6286 return std::nullopt;
6287
6288 // The rest of the matching assumes `Op` is a (possibly extended/negated)
6289 // binary operation.
6290
6291 VPValue *LHS = MulOp->getOperand(0);
6292 VPValue *RHS = MulOp->getOperand(1);
6293
6294 // The LHS of the operation must always be an extend.
6296 return std::nullopt;
6297
6298 auto *LHSCast = cast<VPWidenCastRecipe>(LHS);
6299 Type *LHSInputType = TypeInfo.inferScalarType(LHSCast->getOperand(0));
6300 ExtendKind LHSExtendKind = getPartialReductionExtendKind(LHSCast);
6301
6302 // The RHS of the operation can be an extend or a constant integer.
6303 const APInt *RHSConst = nullptr;
6304 VPWidenCastRecipe *RHSCast = nullptr;
6306 RHSCast = cast<VPWidenCastRecipe>(RHS);
6307 else if (!match(RHS, m_APInt(RHSConst)) ||
6308 !canConstantBeExtended(RHSConst, LHSInputType, LHSExtendKind))
6309 return std::nullopt;
6310
6311 // The outer extend kind must match the inner extends for folding.
6312 for (VPWidenCastRecipe *Cast : {LHSCast, RHSCast})
6313 if (Cast && OuterExtKind &&
6314 getPartialReductionExtendKind(Cast) != OuterExtKind)
6315 return std::nullopt;
6316
6317 Type *RHSInputType = LHSInputType;
6318 ExtendKind RHSExtendKind = LHSExtendKind;
6319 if (RHSCast) {
6320 RHSInputType = TypeInfo.inferScalarType(RHSCast->getOperand(0));
6321 RHSExtendKind = getPartialReductionExtendKind(RHSCast);
6322 }
6323
6324 return ExtendedReductionOperand{
6325 MulOp, {LHSInputType, LHSExtendKind}, {RHSInputType, RHSExtendKind}};
6326}
6327
6328/// Examines each operation in the reduction chain corresponding to \p RedPhiR,
6329/// and determines if the target can use a cheaper operation with a wider
6330/// per-iteration input VF and narrower PHI VF. If successful, returns the chain
6331/// of operations in the reduction.
6332static std::optional<SmallVector<VPPartialReductionChain>>
6333getScaledReductions(VPReductionPHIRecipe *RedPhiR, VPCostContext &CostCtx,
6334 VFRange &Range) {
6335 // Get the backedge value from the reduction PHI and find the
6336 // ComputeReductionResult that uses it (directly or through a select for
6337 // predicated reductions).
6338 auto *RdxResult = vputils::findComputeReductionResult(RedPhiR);
6339 if (!RdxResult)
6340 return std::nullopt;
6341 VPValue *ExitValue = RdxResult->getOperand(0);
6342 match(ExitValue, m_Select(m_VPValue(), m_VPValue(ExitValue), m_VPValue()));
6343
6344 VPTypeAnalysis &TypeInfo = CostCtx.Types;
6346 RecurKind RK = RedPhiR->getRecurrenceKind();
6347 Type *PhiType = TypeInfo.inferScalarType(RedPhiR);
6348 TypeSize PHISize = PhiType->getPrimitiveSizeInBits();
6349
6350 // Work backwards from the ExitValue examining each reduction operation.
6351 VPValue *CurrentValue = ExitValue;
6352 while (CurrentValue != RedPhiR) {
6353 auto *UpdateR = dyn_cast<VPWidenRecipe>(CurrentValue);
6354 if (!UpdateR || !Instruction::isBinaryOp(UpdateR->getOpcode()))
6355 return std::nullopt;
6356
6357 VPValue *Op = UpdateR->getOperand(1);
6358 VPValue *PrevValue = UpdateR->getOperand(0);
6359
6360 // Find the extended operand. The other operand (PrevValue) is the next link
6361 // in the reduction chain.
6362 std::optional<ExtendedReductionOperand> ExtendedOp =
6363 matchExtendedReductionOperand(UpdateR, Op, TypeInfo);
6364 if (!ExtendedOp) {
6365 ExtendedOp = matchExtendedReductionOperand(UpdateR, PrevValue, TypeInfo);
6366 if (!ExtendedOp)
6367 return std::nullopt;
6368 std::swap(Op, PrevValue);
6369 }
6370
6371 Type *ExtSrcType = ExtendedOp->ExtendA.SrcType;
6372 TypeSize ExtSrcSize = ExtSrcType->getPrimitiveSizeInBits();
6373 if (!PHISize.hasKnownScalarFactor(ExtSrcSize))
6374 return std::nullopt;
6375
6376 // Check if a partial reduction chain is supported by the target (i.e. does
6377 // not have an invalid cost) for the given VF range. Clamps the range and
6378 // returns true if feasible for any VF.
6379 VPPartialReductionChain Link(
6380 {UpdateR, *ExtendedOp, RK,
6381 PrevValue == UpdateR->getOperand(0) ? 0U : 1U,
6382 static_cast<unsigned>(PHISize.getKnownScalarFactor(ExtSrcSize))});
6383 Chain.push_back(Link);
6384 CurrentValue = PrevValue;
6385 }
6386
6387 // The chain links were collected by traversing backwards from the exit value.
6388 // Reverse the chains so they are in program order.
6389 std::reverse(Chain.begin(), Chain.end());
6390 return Chain;
6391}
6392} // namespace
6393
6395 VPCostContext &CostCtx,
6396 VFRange &Range) {
6397 // Find all possible valid partial reductions, grouping chains by their PHI.
6398 // This grouping allows invalidating the whole chain, if any link is not a
6399 // valid partial reduction.
6401 ChainsByPhi;
6402 VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
6403 for (VPRecipeBase &R : HeaderVPBB->phis()) {
6404 auto *RedPhiR = dyn_cast<VPReductionPHIRecipe>(&R);
6405 if (!RedPhiR)
6406 continue;
6407
6408 if (auto Chains = getScaledReductions(RedPhiR, CostCtx, Range))
6409 ChainsByPhi.try_emplace(RedPhiR, std::move(*Chains));
6410 }
6411
6412 if (ChainsByPhi.empty())
6413 return;
6414
6415 // Build set of partial reduction operations for extend user validation and
6416 // a map of reduction bin ops to their scale factors for scale validation.
6417 SmallPtrSet<VPRecipeBase *, 4> PartialReductionOps;
6418 DenseMap<VPSingleDefRecipe *, unsigned> ScaledReductionMap;
6419 for (const auto &[_, Chains] : ChainsByPhi)
6420 for (const VPPartialReductionChain &Chain : Chains) {
6421 PartialReductionOps.insert(Chain.ExtendedOp.ExtendsUser);
6422 ScaledReductionMap[Chain.ReductionBinOp] = Chain.ScaleFactor;
6423 }
6424
6425 // A partial reduction is invalid if any of its extends are used by
6426 // something that isn't another partial reduction. This is because the
6427 // extends are intended to be lowered along with the reduction itself.
6428 auto ExtendUsersValid = [&](VPValue *Ext) {
6429 return !isa<VPWidenCastRecipe>(Ext) || all_of(Ext->users(), [&](VPUser *U) {
6430 return PartialReductionOps.contains(cast<VPRecipeBase>(U));
6431 });
6432 };
6433
6434 auto IsProfitablePartialReductionChainForVF =
6435 [&](ArrayRef<VPPartialReductionChain> Chain, ElementCount VF) -> bool {
6436 InstructionCost PartialCost = 0, RegularCost = 0;
6437
6438 // The chain is a profitable partial reduction chain if the cost of handling
6439 // the entire chain is cheaper when using partial reductions than when
6440 // handling the entire chain using regular reductions.
6441 for (const VPPartialReductionChain &Link : Chain) {
6442 const ExtendedReductionOperand &ExtendedOp = Link.ExtendedOp;
6443 InstructionCost LinkCost = getPartialReductionLinkCost(CostCtx, Link, VF);
6444 if (!LinkCost.isValid())
6445 return false;
6446
6447 PartialCost += LinkCost;
6448 RegularCost += Link.ReductionBinOp->computeCost(VF, CostCtx);
6449 // If ExtendB is not none, then the "ExtendsUser" is the binary operation.
6450 if (ExtendedOp.ExtendB.Kind != ExtendKind::PR_None)
6451 RegularCost += ExtendedOp.ExtendsUser->computeCost(VF, CostCtx);
6452 for (VPValue *Op : ExtendedOp.ExtendsUser->operands())
6453 if (auto *Extend = dyn_cast<VPWidenCastRecipe>(Op))
6454 RegularCost += Extend->computeCost(VF, CostCtx);
6455 }
6456 return PartialCost.isValid() && PartialCost < RegularCost;
6457 };
6458
6459 // Validate chains: check that extends are only used by partial reductions,
6460 // and that reduction bin ops are only used by other partial reductions with
6461 // matching scale factors, are outside the loop region or the select
6462 // introduced by tail-folding. Otherwise we would create users of scaled
6463 // reductions where the types of the other operands don't match.
6464 for (auto &[RedPhiR, Chains] : ChainsByPhi) {
6465 for (const VPPartialReductionChain &Chain : Chains) {
6466 if (!all_of(Chain.ExtendedOp.ExtendsUser->operands(), ExtendUsersValid)) {
6467 Chains.clear();
6468 break;
6469 }
6470 auto UseIsValid = [&, RedPhiR = RedPhiR](VPUser *U) {
6471 if (auto *PhiR = dyn_cast<VPReductionPHIRecipe>(U))
6472 return PhiR == RedPhiR;
6473 auto *R = cast<VPSingleDefRecipe>(U);
6474 return Chain.ScaleFactor == ScaledReductionMap.lookup_or(R, 0) ||
6476 m_Specific(Chain.ReductionBinOp))) ||
6477 match(R, m_Select(m_VPValue(), m_Specific(Chain.ReductionBinOp),
6478 m_Specific(RedPhiR)));
6479 };
6480 if (!all_of(Chain.ReductionBinOp->users(), UseIsValid)) {
6481 Chains.clear();
6482 break;
6483 }
6484
6485 // Check if the compute-reduction-result is used by a sunk store.
6486 // TODO: Also form partial reductions in those cases.
6487 if (auto *RdxResult = vputils::findComputeReductionResult(RedPhiR)) {
6488 if (any_of(RdxResult->users(), [](VPUser *U) {
6489 auto *RepR = dyn_cast<VPReplicateRecipe>(U);
6490 return RepR && RepR->getOpcode() == Instruction::Store;
6491 })) {
6492 Chains.clear();
6493 break;
6494 }
6495 }
6496 }
6497
6498 // Clear the chain if it is not profitable.
6500 [&, &Chains = Chains](ElementCount VF) {
6501 return IsProfitablePartialReductionChainForVF(Chains, VF);
6502 },
6503 Range))
6504 Chains.clear();
6505 }
6506
6507 for (auto &[Phi, Chains] : ChainsByPhi)
6508 for (const VPPartialReductionChain &Chain : Chains)
6509 transformToPartialReduction(Chain, CostCtx.Types, Plan, Phi);
6510}
6511
6513 VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder) {
6514 // Collect all loads/stores first. We will start with ones having simpler
6515 // decisions followed by more complex ones that are potentially
6516 // guided/dependent on the simpler ones.
6518 for (VPBasicBlock *VPBB :
6521 for (VPRecipeBase &R : *VPBB) {
6522 auto *VPI = dyn_cast<VPInstruction>(&R);
6523 if (VPI && VPI->getUnderlyingValue() &&
6524 is_contained({Instruction::Load, Instruction::Store},
6525 VPI->getOpcode()))
6526 MemOps.push_back(VPI);
6527 }
6528 }
6529
6530 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
6531 VPBuilder FinalRedStoresBuilder(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
6532
6533 for (VPInstruction *VPI : MemOps) {
6534 auto ReplaceWith = [&](VPRecipeBase *New) {
6535 New->insertBefore(VPI);
6536 if (VPI->getOpcode() == Instruction::Load)
6537 VPI->replaceAllUsesWith(New->getVPSingleValue());
6538 VPI->eraseFromParent();
6539 };
6540
6541 // Note: we must do that for scalar VPlan as well.
6542 if (RecipeBuilder.replaceWithFinalIfReductionStore(VPI,
6543 FinalRedStoresBuilder))
6544 continue;
6545
6546 // Filter out scalar VPlan for the remaining memory operations.
6548 [](ElementCount VF) { return VF.isScalar(); }, Range))
6549 continue;
6550
6551 if (VPHistogramRecipe *Histogram = RecipeBuilder.widenIfHistogram(VPI)) {
6552 ReplaceWith(Histogram);
6553 continue;
6554 }
6555
6556 VPRecipeBase *Recipe = RecipeBuilder.tryToWidenMemory(VPI, Range);
6557 if (!Recipe)
6558 Recipe = RecipeBuilder.handleReplication(VPI, Range);
6559
6560 ReplaceWith(Recipe);
6561 }
6562}
6563
6566 [&](ElementCount VF) { return VF.isScalar(); }, Range))
6567 return;
6568
6570 Plan.getEntry());
6572 for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB))) {
6573 auto *VPI = dyn_cast<VPInstruction>(&R);
6574 if (!VPI)
6575 continue;
6576
6577 auto *I = cast_or_null<Instruction>(VPI->getUnderlyingValue());
6578 // Wouldn't be able to create a `VPReplicateRecipe` anyway.
6579 if (!I)
6580 continue;
6581
6582 // If executing other lanes produces side-effects we can't avoid them.
6583 if (VPI->mayHaveSideEffects())
6584 continue;
6585
6586 // We want to drop the mask operand, verify we can safely do that.
6587 if (VPI->isMasked() && !VPI->isSafeToSpeculativelyExecute())
6588 continue;
6589
6590 // Avoid rewriting IV increment as that interferes with
6591 // `removeRedundantCanonicalIVs`.
6592 if (VPI->getOpcode() == Instruction::Add &&
6594 continue;
6595
6596 // Other lanes are needed - can't drop them.
6598 continue;
6599
6600 auto *Recipe = new VPReplicateRecipe(
6601 I, VPI->operandsWithoutMask(), /*IsSingleScalar=*/true,
6602 /*Mask=*/nullptr, *VPI, *VPI, VPI->getDebugLoc());
6603 Recipe->insertBefore(VPI);
6604 VPI->replaceAllUsesWith(Recipe);
6605 VPI->eraseFromParent();
6606 }
6607 }
6608}
6609
6610/// Returns true if \p Info's parameter kinds are compatible with \p Args.
6611static bool areVFParamsOk(const VFInfo &Info, ArrayRef<VPValue *> Args,
6612 PredicatedScalarEvolution &PSE, const Loop *L,
6613 VPTypeAnalysis &Types) {
6614 ScalarEvolution *SE = PSE.getSE();
6615 return all_of(Info.Shape.Parameters, [&](VFParameter Param) {
6616 switch (Param.ParamKind) {
6617 case VFParamKind::Vector:
6618 case VFParamKind::GlobalPredicate:
6619 return true;
6620 case VFParamKind::OMP_Uniform:
6621 return SE->isSCEVable(Types.inferScalarType(Args[Param.ParamPos])) &&
6622 SE->isLoopInvariant(
6623 vputils::getSCEVExprForVPValue(Args[Param.ParamPos], PSE, L),
6624 L);
6625 case VFParamKind::OMP_Linear:
6626 return match(vputils::getSCEVExprForVPValue(Args[Param.ParamPos], PSE, L),
6627 m_scev_AffineAddRec(
6628 m_SCEV(), m_scev_SpecificSInt(Param.LinearStepOrPos),
6629 m_SpecificLoop(L)));
6630 default:
6631 return false;
6632 }
6633 });
6634}
6635
6636/// Find a vector variant of \p CI for \p VF, respecting \p MaskRequired.
6637/// Returns the variant function, or nullptr. Masked variants are assumed to
6638/// take the mask as a trailing parameter.
6640 ElementCount VF, bool MaskRequired,
6642 const Loop *L, VPTypeAnalysis &Types) {
6643 if (CI->isNoBuiltin())
6644 return nullptr;
6645 auto Mappings = VFDatabase::getMappings(*CI);
6646 const auto *It = find_if(Mappings, [&](const VFInfo &Info) {
6647 return Info.Shape.VF == VF && (!MaskRequired || Info.isMasked()) &&
6648 areVFParamsOk(Info, Args, PSE, L, Types);
6649 });
6650 if (It == Mappings.end())
6651 return nullptr;
6652 return CI->getModule()->getFunction(It->VectorName);
6653}
6654
6655namespace {
6656/// The outcome of choosing how to widen a call at a given VF.
6657struct CallWideningDecision {
6658 using KindTy = VPCostContext::CallWideningKind;
6659 CallWideningDecision(KindTy Kind, Function *Variant = nullptr)
6660 : Kind(Kind), Variant(Variant) {}
6661 KindTy Kind;
6662
6663 /// Set when Kind == VectorVariant.
6665
6666 bool operator==(const CallWideningDecision &Other) const {
6667 return Kind == Other.Kind && Variant == Other.Variant;
6668 }
6669};
6670} // namespace
6671
6672/// Pick the cheapest widening for the call \p VPI at \p VF among scalarization,
6673/// vector intrinsic, and vector library variant.
6674static CallWideningDecision decideCallWidening(VPInstruction &VPI,
6676 ElementCount VF,
6677 VPCostContext &CostCtx) {
6678 auto *CI = cast<CallInst>(VPI.getUnderlyingInstr());
6679
6680 // Scalar VFs and calls forced or known to scalarize always replicate.
6681 if (VF.isScalar() || CostCtx.willBeScalarized(CI, VF))
6682 return CallWideningDecision::KindTy::Scalarize;
6683
6684 auto *CalledFn = cast<Function>(
6686 Type *ResultTy = CostCtx.Types.inferScalarType(&VPI);
6688 bool MaskRequired = CostCtx.isMaskRequired(CI);
6689
6690 // Pseudo intrinsics (assume, lifetime, ...) are always scalarized.
6692 return CallWideningDecision::KindTy::Scalarize;
6693
6694 InstructionCost ScalarCost =
6695 VPReplicateRecipe::computeCallCost(CalledFn, ResultTy, Ops,
6696 /*IsSingleScalar=*/false, VF, CostCtx);
6697
6698 Function *VecFunc = findVectorVariant(CI, Ops, VF, MaskRequired, CostCtx.PSE,
6699 CostCtx.L, CostCtx.Types);
6701 if (VecFunc)
6702 VecCallCost = VPWidenCallRecipe::computeCallCost(VecFunc, CostCtx);
6703
6704 // Prefer the intrinsic if it is at least as cheap as scalarizing and any
6705 // available vector variant.
6706 if (ID) {
6709 if (IntrinsicCost.isValid() && ScalarCost >= IntrinsicCost &&
6710 (!VecFunc || VecCallCost >= IntrinsicCost))
6711 return CallWideningDecision::KindTy::Intrinsic;
6712 }
6713
6714 // Otherwise, use a vector library variant when it beats scalarizing.
6715 if (VecFunc && ScalarCost >= VecCallCost)
6716 return {CallWideningDecision::KindTy::VectorVariant, VecFunc};
6717
6718 return CallWideningDecision::KindTy::Scalarize;
6719}
6720
6722 VPRecipeBuilder &RecipeBuilder,
6723 VPCostContext &CostCtx) {
6727 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
6728 auto *VPI = dyn_cast<VPInstruction>(&R);
6729 if (!VPI || !VPI->getUnderlyingValue() ||
6730 VPI->getOpcode() != Instruction::Call)
6731 continue;
6732
6733 auto *CI = cast<CallInst>(VPI->getUnderlyingInstr());
6734 SmallVector<VPValue *, 4> Ops(VPI->op_begin(),
6735 VPI->op_begin() + CI->arg_size());
6736
6737 CallWideningDecision Decision =
6738 decideCallWidening(*VPI, Ops, Range.Start, CostCtx);
6740 [&](ElementCount VF) {
6741 return Decision == decideCallWidening(*VPI, Ops, VF, CostCtx);
6742 },
6743 Range);
6744
6745 VPSingleDefRecipe *Replacement = nullptr;
6746 switch (Decision.Kind) {
6747 case CallWideningDecision::KindTy::Intrinsic: {
6749 Type *ResultTy = CostCtx.Types.inferScalarType(VPI);
6750 Replacement = new VPWidenIntrinsicRecipe(*CI, ID, Ops, ResultTy, *VPI,
6751 *VPI, VPI->getDebugLoc());
6752 break;
6753 }
6754 case CallWideningDecision::KindTy::VectorVariant: {
6755 // Masked variants take the mask as a trailing parameter, so they have
6756 // one more parameter than the original call's arguments.
6757 if (Decision.Variant->arg_size() > Ops.size()) {
6758 VPValue *Mask = VPI->isMasked() ? VPI->getMask() : Plan.getTrue();
6759 Ops.push_back(Mask);
6760 }
6761 Ops.push_back(VPI->getOperand(VPI->getNumOperandsWithoutMask() - 1));
6762 Replacement = new VPWidenCallRecipe(CI, Decision.Variant, Ops, *VPI,
6763 *VPI, VPI->getDebugLoc());
6764 break;
6765 }
6766 case CallWideningDecision::KindTy::Scalarize:
6767 Replacement = RecipeBuilder.handleReplication(VPI, Range);
6768 break;
6769 }
6770
6772 [&](ElementCount VF) {
6773 Intrinsic::ID IID =
6774 getVectorIntrinsicIDForCall(CI, &CostCtx.TLI);
6776 return true;
6777 auto Legacy = CostCtx.getLegacyCallKind(CI, VF);
6778 return !Legacy || *Legacy == Decision.Kind;
6779 }) &&
6780 "VPlan call widening decision must match legacy decision");
6781
6782 Replacement->insertBefore(VPI);
6783 VPI->replaceAllUsesWith(Replacement);
6784 ToErase.push_back(VPI);
6785 }
6786 }
6787 for (VPInstruction *VPI : ToErase)
6788 VPI->eraseFromParent();
6789}
6790
6793 Loop &L, VPCostContext &Ctx,
6794 VFRange &Range) {
6795 if (Plan.hasScalarVFOnly())
6796 return;
6797
6798 VPTypeAnalysis TypeInfo(Plan);
6799 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
6800 VPValue *I32VF = nullptr;
6802 vp_depth_first_shallow(VectorLoop->getEntry()))) {
6803 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
6804 auto *LoadR = dyn_cast<VPWidenLoadRecipe>(&R);
6805 // TODO: Support strided store.
6806 // TODO: Transform reverse access into strided access with -1 stride.
6807 // TODO: Transform gather/scatter with uniform address into strided access
6808 // with 0 stride.
6809 // TODO: Transform interleave access into multiple strided accesses.
6810 if (!LoadR || LoadR->isConsecutive())
6811 continue;
6812
6813 auto *Ptr = dyn_cast<VPWidenGEPRecipe>(LoadR->getAddr());
6814 if (!Ptr)
6815 continue;
6816
6817 // Check if this is a strided access by analyzing the address SCEV for an
6818 // affine addRec.
6819 const SCEV *PtrSCEV = vputils::getSCEVExprForVPValue(Ptr, PSE, &L);
6820 const SCEV *Start;
6821 const APInt *Step;
6822 // TODO: Support non-constant loop invariant stride.
6823 if (!match(PtrSCEV, m_scev_AffineAddRec(m_SCEV(Start), m_scev_APInt(Step),
6824 m_SpecificLoop(&L))))
6825 continue;
6826
6827 Type *LoadTy = TypeInfo.inferScalarType(LoadR);
6828 Align Alignment = LoadR->getAlign();
6829 auto IsProfitable = [&](ElementCount VF) {
6830 Type *DataTy = toVectorTy(LoadTy, VF);
6831 if (!Ctx.TTI.isLegalStridedLoadStore(DataTy, Alignment))
6832 return false;
6833 const InstructionCost CurrentCost = LoadR->computeCost(VF, Ctx);
6834 const InstructionCost StridedLoadStoreCost =
6836 Intrinsic::experimental_vp_strided_load, DataTy,
6837 LoadR->isMasked(), Alignment, Ctx);
6838 return StridedLoadStoreCost < CurrentCost;
6839 };
6840
6842 Range))
6843 continue;
6844
6845 // Invalidate the legacy widening decision so the cost of replaced load is
6846 // not counted during precomputeCosts.
6847 // TODO: Remove once the legacy exit cost computation is retired.
6848 for (ElementCount VF : Range)
6849 Ctx.invalidateWideningDecision(&LoadR->getIngredient(), VF);
6850
6851 // Get VF as i32 for the vector length operand.
6852 if (!I32VF) {
6853 VPBuilder Builder(Plan.getVectorPreheader());
6854 I32VF = Builder.createScalarZExtOrTrunc(
6855 &Plan.getVF(), Type::getInt32Ty(Plan.getContext()),
6856 TypeInfo.inferScalarType(&Plan.getVF()), DebugLoc::getUnknown());
6857 }
6858
6859 VPBuilder Builder(LoadR);
6860 // Create the base pointer of strided access.
6861 VPValue *StartVPV = vputils::getOrCreateVPValueForSCEVExpr(Plan, Start);
6862 VPValue *StrideInBytes =
6863 Plan.getConstantInt(VectorLoop->getCanonicalIVType(),
6864 Step->getSExtValue(), /*IsSigned=*/true);
6865 auto *AddRecPtr = cast<SCEVAddRecExpr>(PtrSCEV);
6866 auto *Offset = Builder.createOverflowingOp(
6867 Instruction::Mul, {VectorLoop->getCanonicalIV(), StrideInBytes},
6868 {AddRecPtr->hasNoUnsignedWrap(), AddRecPtr->hasNoSignedWrap()});
6869 auto *BasePtr = Builder.createNoWrapPtrAdd(
6870 StartVPV, Offset,
6871 AddRecPtr->hasNoUnsignedWrap() ? GEPNoWrapFlags::noUnsignedWrap()
6873
6874 // Create a new vector pointer for strided access.
6875 VPValue *NewPtr = Builder.createVectorPointer(
6876 BasePtr, Type::getInt8Ty(Plan.getContext()), StrideInBytes,
6877 Ptr->getGEPNoWrapFlags(), Ptr->getDebugLoc());
6878
6879 VPValue *Mask = LoadR->getMask();
6880 if (!Mask)
6881 Mask = Plan.getTrue();
6882 auto *StridedLoad = Builder.createWidenMemIntrinsic(
6883 Intrinsic::experimental_vp_strided_load,
6884 {NewPtr, StrideInBytes, Mask, I32VF}, LoadTy, Alignment, *LoadR,
6885 LoadR->getDebugLoc());
6886 LoadR->replaceAllUsesWith(StridedLoad);
6887 }
6888 }
6889}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(const Function &Caller, const Function &Callee)
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:853
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")
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
static cl::opt< IntrinsicCostStrategy > IntrinsicCost("intrinsic-cost-strategy", cl::desc("Costing strategy for intrinsic instructions"), cl::init(IntrinsicCostStrategy::InstructionCost), cl::values(clEnumValN(IntrinsicCostStrategy::InstructionCost, "instruction-cost", "Use TargetTransformInfo::getInstructionCost"), clEnumValN(IntrinsicCostStrategy::IntrinsicCost, "intrinsic-cost", "Use TargetTransformInfo::getIntrinsicInstrCost"), clEnumValN(IntrinsicCostStrategy::TypeBasedIntrinsicCost, "type-based-intrinsic-cost", "Calculate the intrinsic cost based only on argument types")))
static bool isSentinel(const DWARFDebugNames::AttributeEncoding &AE)
@ 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:383
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:81
#define I(x, y, z)
Definition MD5.cpp:57
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first DebugLoc that has line number information, given a range of instructions.
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
MachineInstr unsigned OpIdx
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
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 defines generic set operations that may be used on set's of different types,...
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")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
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 sinkScalarOperands(VPlan &Plan)
static bool simplifyBranchConditionForVFAndUF(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
Try to simplify the branch condition of Plan.
static void simplifyRecipe(VPSingleDefRecipe *Def, VPTypeAnalysis &TypeInfo)
Try to simplify VPSingleDefRecipe Def.
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 bool tryToReplaceALMWithWideALM(VPlan &Plan, ElementCount VF, unsigned UF)
Try to replace multiple active lane masks used for control flow with a single, wide active lane mask ...
static std::optional< std::pair< bool, unsigned > > getOpcodeOrIntrinsicID(const VPSingleDefRecipe *R)
Get any instruction opcode or intrinsic ID data embedded in recipe R.
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 RemoveMask_match< Op0_t, Op1_t > m_RemoveMask(const Op0_t &In, Op1_t &Out)
Match a specific mask In, or a combination of it (logical-and In, Out).
static VPIRMetadata getCommonMetadata(ArrayRef< VPReplicateRecipe * > Recipes)
static Function * findVectorVariant(CallInst *CI, ArrayRef< VPValue * > Args, ElementCount VF, bool MaskRequired, PredicatedScalarEvolution &PSE, const Loop *L, VPTypeAnalysis &Types)
Find a vector variant of CI for VF, respecting MaskRequired.
static VPValue * getPredicatedMask(VPRegionBlock *R)
If R is a region with a VPBranchOnMaskRecipe in the entry block, return the mask.
static bool mergeReplicateRegionsIntoSuccessors(VPlan &Plan)
static VPScalarIVStepsRecipe * createScalarIVSteps(VPlan &Plan, InductionDescriptor::InductionKind Kind, Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp, Instruction *TruncI, VPIRValue *StartV, VPValue *Step, DebugLoc DL, VPBuilder &Builder)
static VPWidenInductionRecipe * getOptimizableIVOf(VPValue *VPV, PredicatedScalarEvolution &PSE)
Check if VPV is an untruncated wide induction, either before or after the increment.
static void fixupVFUsersForEVL(VPlan &Plan, VPValue &EVL)
After replacing the canonical IV with a EVL-based IV, fixup recipes that use VF to use the EVL instea...
static 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 void expandVPWidenPointerInduction(VPWidenPointerInductionRecipe *R, VPTypeAnalysis &TypeInfo)
Expand a VPWidenPointerInductionRecipe into executable recipes, for the initial value,...
static VPValue * optimizeLatchExitInductionUser(VPlan &Plan, VPTypeAnalysis &TypeInfo, 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 std::optional< ElementCount > isConsecutiveInterleaveGroup(VPInterleaveRecipe *InterleaveR, ArrayRef< ElementCount > VFs, VPTypeAnalysis &TypeInfo, const TargetTransformInfo &TTI)
Returns VF from VFs if IR is a full interleave group with factor and number of members both equal to ...
static bool isDeadRecipe(VPRecipeBase &R)
Returns true if R is dead and can be removed.
static void legalizeAndOptimizeInductions(VPlan &Plan)
Legalize VPWidenPointerInductionRecipe, by replacing it with a PtrAdd (IndStart, ScalarIVSteps (0,...
static void addReplicateRegions(VPlan &Plan)
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, in a deep-traversal of the v...
static VPIRValue * tryToFoldLiveIns(VPSingleDefRecipe &R, ArrayRef< VPValue * > Operands, const DataLayout &DL, VPTypeAnalysis &TypeInfo)
Try to fold R using InstSimplifyFolder.
static VPValue * tryToComputeEndValueForInduction(VPWidenInductionRecipe *WideIV, VPBuilder &VectorPHBuilder, VPTypeAnalysis &TypeInfo, VPValue *VectorTC)
Compute the end value for WideIV, unless it is truncated.
static std::optional< Intrinsic::ID > getVPDivRemIntrinsic(Intrinsic::ID IntrID)
static void removeRedundantExpandSCEVRecipes(VPlan &Plan)
Remove redundant EpxandSCEVRecipes in Plan's entry block by replacing them with already existing reci...
static VPValue * scalarizeVPWidenPointerInduction(VPWidenPointerInductionRecipe *PtrIV, VPlan &Plan, VPBuilder &Builder)
Scalarize a VPWidenPointerInductionRecipe by replacing it with a PtrAdd (IndStart,...
static SmallVector< VPUser * > collectUsersRecursively(VPValue *V)
static VPValue * optimizeEarlyExitInductionUser(VPlan &Plan, VPTypeAnalysis &TypeInfo, VPValue *Op, PredicatedScalarEvolution &PSE)
Attempts to optimize the induction variable exit values for users in the early exit block.
static void expandVPDerivedIV(VPDerivedIVRecipe *R, VPTypeAnalysis &TypeInfo)
Expand a VPDerivedIVRecipe into executable recipes.
static void recursivelyDeleteDeadRecipes(VPValue *V)
static void reassociateHeaderMask(VPlan &Plan)
Reassociate (headermask && x) && y -> headermask && (x && y) to allow the header mask to be simplifie...
static bool canSinkStoreWithNoAliasCheck(ArrayRef< VPReplicateRecipe * > StoresToSink, PredicatedScalarEvolution &PSE, const Loop &L, VPTypeAnalysis &TypeInfo)
static VPActiveLaneMaskPHIRecipe * addVPLaneMaskPhiAndUpdateExitBranch(VPlan &Plan)
static VPBasicBlock * getPredicatedThenBlock(VPRegionBlock *R)
If R is a triangle region, return the 'then' block of the triangle.
static bool areVFParamsOk(const VFInfo &Info, ArrayRef< VPValue * > Args, PredicatedScalarEvolution &PSE, const Loop *L, VPTypeAnalysis &Types)
Returns true if Info's parameter kinds are compatible with Args.
static VPValue * narrowInterleaveGroupOp(VPValue *V, SmallPtrSetImpl< VPValue * > &NarrowedOps)
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 std::optional< Instruction::BinaryOps > getUnmaskedDivRemOpcode(Intrinsic::ID ID)
static VPRecipeBase * optimizeMaskToEVL(VPValue *HeaderMask, VPRecipeBase &CurRecipe, VPTypeAnalysis &TypeInfo, VPValue &EVL)
Try to optimize a CurRecipe masked by HeaderMask to a corresponding EVL-based recipe without the head...
static bool isAlreadyNarrow(VPValue *VPV)
Returns true if VPValue is a narrow VPValue.
static bool cannotHoistOrSinkRecipe(VPRecipeBase &R, VPBasicBlock *FirstBB, VPBasicBlock *LastBB)
Return true if we do not know how to (mechanically) hoist or sink a non-memory or memory recipe R out...
static bool canNarrowOps(ArrayRef< VPValue * > Ops, bool IsScalable)
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 void expandVPWidenIntOrFpInduction(VPWidenIntOrFpInductionRecipe *WidenIVR, VPTypeAnalysis &TypeInfo)
Expand a VPWidenIntOrFpInduction into executable recipes, for the initial value, phi and backedge val...
static void narrowToSingleScalarRecipes(VPlan &Plan)
This file provides utility VPlan to VPlan transformations.
#define RUN_VPLAN_PASS(PASS,...)
This file declares the class VPlanVerifier, which contains utility functions to check the consistency...
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(const SmallPtrSetImpl< VPRecipeBase * > &ExcludeRecipes, VPReplicateRecipe &GroupLeader, PredicatedScalarEvolution &PSE, const Loop &L, VPTypeAnalysis &TypeInfo)
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
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1563
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1535
APInt abs() const
Get the absolute value.
Definition APInt.h:1818
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1511
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1028
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1585
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1228
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
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
iterator begin() const
Definition ArrayRef.h:129
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
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
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...
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
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.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:123
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:162
static DebugLoc getUnknown()
Definition DebugLoc.h:161
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:205
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:254
ValueT lookup_or(const_arg_type_t< KeyT > Val, U &&Default) const
Definition DenseMap.h:215
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:324
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:312
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:200
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
Definition Operator.h:289
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
size_t arg_size() const
Definition Function.h:901
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags noUnsignedWrap()
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.
static LLVM_ABI InductionDescriptor getCanonicalIntInduction(Type *Ty, ScalarEvolution &SE)
Returns the canonical integer induction for type Ty with start = 0 and step = 1.
InductionKind
This enum represents the kinds of inductions that we support.
@ IK_NoInduction
Not an induction variable.
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
static InstructionCost getInvalid(CostType Val=0)
bool isCast() const
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:354
The group of interleaved loads/stores sharing the same stride and close to each other.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
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:1698
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
Metadata node.
Definition Metadata.h:1080
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
ValueT lookup(const KeyT &Key) const
Definition MapVector.h:110
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:118
bool empty() const
Definition MapVector.h:79
Representation for a specific memory location.
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:235
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
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,...
RegionT * getParent() const
Get the parent of the Region.
Definition RegionInfo.h:362
This class uses information about analyze scalars to rewrite expressions in canonical form.
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, ValueToSCEVMapTy &Map)
This class represents an analyzed expression in the program.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
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,...
static LLVM_ABI AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
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:151
size_type size() const
Definition SmallPtrSet.h:99
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)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
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.
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
@ SK_Broadcast
Broadcast element 0 to all other elements.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This class implements a switch-like dispatch statement for a value of 'T' using dyn_cast functionalit...
Definition TypeSwitch.h:89
TypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
Definition TypeSwitch.h:98
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:313
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:284
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:311
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:278
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:201
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:236
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:310
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
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
A recipe for generating the active lane mask for the vector loop that is used to predicate the vector...
Definition VPlan.h:3896
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4248
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4323
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4275
iterator end()
Definition VPlan.h:4285
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4283
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4336
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:266
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
Definition VPlan.cpp:582
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:661
const VPRecipeBase & back() const
Definition VPlan.h:4297
A recipe for vectorizing a phi-node as a sequence of mask-based select instructions.
Definition VPlan.h:2873
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
Definition VPlan.h:2909
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2899
void setMask(unsigned Idx, VPValue *V)
Set mask number Idx to V.
Definition VPlan.h:2915
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:2895
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:93
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:314
VPRegionBlock * getParent()
Definition VPlan.h:185
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:236
size_t getNumSuccessors() const
Definition VPlan.h:236
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition VPlan.h:305
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:221
VPlan * getPlan()
Definition VPlan.cpp:211
const std::string & getName() const
Definition VPlan.h:176
void clearSuccessors()
Remove all the successors of this block.
Definition VPlan.h:324
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:232
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
VPBlockBase * getSingleHierarchicalPredecessor()
Definition VPlan.h:278
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:226
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:210
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:314
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
Definition VPlanUtils.h:333
static bool isLatch(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop latch, using isHeader().
static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBases IfTrue and IfFalse after BlockPtr.
Definition VPlanUtils.h:223
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:241
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:259
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:295
static void transferSuccessors(VPBlockBase *Old, VPBlockBase *New)
Transfer successors from Old to New. New must have no successors.
Definition VPlanUtils.h:279
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:3371
RAII object that stores the current insertion point and restores it when the object is destroyed.
VPlan-based builder utility analogous to IRBuilder.
VPInstruction * createFirstActiveLane(ArrayRef< VPValue * > Masks, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPValue * createScalarZExtOrTrunc(VPValue *Op, Type *ResultTy, Type *SrcTy, DebugLoc DL)
VPInstruction * createNot(VPValue *Operand, 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 ...
Definition VPlan.cpp:1683
VPInstruction * createLogicalAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPDerivedIVRecipe * createDerivedIV(InductionDescriptor::InductionKind Kind, FPMathOperator *FPBinOp, VPIRValue *Start, VPValue *Current, VPValue *Step)
Convert the input value Current to the corresponding value of an induction with Start and Step values...
VPInstruction * createScalarCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, DebugLoc DL, const VPIRMetadata &Metadata={})
VPWidenPHIRecipe * createWidenPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
static VPBuilder getToInsertAfter(VPRecipeBase *R)
Create a VPBuilder to insert after R.
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", const VPIRFlags &Flags={})
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.
VPInstruction * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", const VPIRFlags &Flags={})
void setInsertPoint(VPBasicBlock *TheBB)
This specifies that created VPInstructions should be appended to the end of the specified block.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
A recipe for generating the phi node tracking the current scalar iteration index.
Definition VPlan.h:3928
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:556
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:529
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:541
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:551
A recipe for converting the input value IV value to the corresponding value of an IV with different s...
Definition VPlan.h:4022
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B)
A recipe to combine multiple recipes into a single 'expression' recipe, which should be considered a ...
Definition VPlan.h:3416
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2391
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2433
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2422
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition VPlan.h:2129
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4401
Class to record and manage LLVM IR flags.
Definition VPlan.h:696
static VPIRFlags getDefaultFlags(unsigned Opcode)
Returns default flags for Opcode for opcodes that support it, asserts otherwise.
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
static LLVM_ABI_FOR_TEST VPIRInstruction * create(Instruction &I)
Create a new VPIRPhi for \I , if it is a PHINode, otherwise create a VPIRInstruction.
Helper to manage IR metadata for recipes.
Definition VPlan.h:1172
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetadata object with MD, keeping only metadata nodes that are common to both.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1227
unsigned getNumOperandsWithoutMask() const
Returns the number of operands, excluding the mask if the VPInstruction is masked.
Definition VPlan.h:1459
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1316
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1267
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1312
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1262
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1259
@ CanonicalIVIncrementForPart
Definition VPlan.h:1243
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1270
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3010
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3002
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3031
A recipe for interleaved memory operations with vector-predication intrinsics.
Definition VPlan.h:3083
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:3041
VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when control converges back from ...
Definition VPlan.h:3558
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:401
VPBasicBlock * getParent()
Definition VPlan.h:476
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:554
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
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.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
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...
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.
VPReplicateRecipe * handleReplication(VPInstruction *VPI, VFRange &Range)
Build a VPReplicationRecipe for VPI.
A recipe to represent inloop reduction operations with vector-predication intrinsics,...
Definition VPlan.h:3243
A recipe for handling reduction phis.
Definition VPlan.h:2779
void setVFScaleFactor(unsigned ScaleFactor)
Set the VFScaleFactor for this reduction phi.
Definition VPlan.h:2826
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:2819
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2837
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3134
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4458
const VPBlockBase * getEntry() const
Definition VPlan.h:4502
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4534
VPInstruction * getOrCreateCanonicalIVIncrement()
Get the canonical IV increment instruction if it exists.
Definition VPlan.cpp:879
void setExiting(VPBlockBase *ExitingBlock)
Set ExitingBlock as the exiting VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4519
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4578
void clearCanonicalIVNUW(VPInstruction *Increment)
Unsets NUW for the canonical IV increment Increment, for loop regions.
Definition VPlan.h:4586
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4570
const VPBlockBase * getExiting() const
Definition VPlan.h:4514
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4527
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3288
bool isSingleScalar() const
Definition VPlan.h:3336
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.
bool isPredicated() const
Definition VPlan.h:3338
VPValue * getMask()
Return the mask of a predicated VPReplicateRecipe.
Definition VPlan.h:3355
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition VPlan.h:4093
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:610
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:681
VPSingleDefRecipe * clone() override=0
Clone the current recipe.
An analysis for type-inference for VPValues.
LLVMContext & getContext()
Return the LLVMContext used by the analysis.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:384
operand_range operands()
Definition VPlanValue.h:452
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:428
unsigned getNumOperands() const
Definition VPlanValue.h:422
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:423
void addOperand(VPValue *Operand)
Definition VPlanValue.h:417
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:143
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1508
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:130
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:208
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1511
unsigned getNumUsers() const
Definition VPlanValue.h:115
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser &U, unsigned Idx)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1517
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:2236
A recipe for widening Call instructions using library calls.
Definition VPlan.h:2063
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:1844
Instruction::CastOps getOpcode() const
Definition VPlan.h:1880
A recipe for handling GEP instructions.
Definition VPlan.h:2171
Base class for widened induction (VPWidenIntOrFpInductionRecipe and VPWidenPointerInductionRecipe),...
Definition VPlan.h:2457
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2485
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2488
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2508
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2539
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2586
VPValue * getSplatVFValue() const
If the recipe has been unrolled, return the VPValue for the induction increment, otherwise return nul...
Definition VPlan.h:2590
VPValue * getLastUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the last unrolled part,...
Definition VPlan.h:2617
A recipe for widening vector intrinsics.
Definition VPlan.h:1891
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:3594
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
A recipe for widened phis.
Definition VPlan.h:2675
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1788
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenRecipe.
VPWidenRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1808
unsigned getOpcode() const
Definition VPlan.h:1825
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4606
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:4931
bool hasVF(ElementCount VF) const
Definition VPlan.h:4829
const DataLayout & getDataLayout() const
Definition VPlan.h:4811
LLVMContext & getContext() const
Definition VPlan.h:4807
VPBasicBlock * getEntry()
Definition VPlan.h:4702
bool hasScalableVF() const
Definition VPlan.h:4830
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4765
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition VPlan.h:4786
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition VPlan.h:4836
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:4902
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:4805
VPIRValue * getAllOnesValue(Type *Ty)
Return a VPIRValue wrapping the AllOnes value of type Ty.
Definition VPlan.h:4908
VPRegionBlock * createReplicateRegion(VPBlockBase *Entry, VPBlockBase *Exiting, const std::string &Name="")
Create a new replicate region with Entry, Exiting and Name.
Definition VPlan.h:4980
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:4934
bool hasUF(unsigned UF) const
Definition VPlan.h:4854
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:4755
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4795
VPValue * getBackedgeTakenCount() const
Definition VPlan.h:4792
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:4879
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:4905
void setVF(ElementCount VF)
Definition VPlan.h:4817
bool isUnrolled() const
Returns true if the VPlan already has been unrolled, i.e.
Definition VPlan.h:4870
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1098
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:4857
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:4779
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4731
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:4957
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:4899
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4707
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:4802
bool hasScalarVFOnly() const
Definition VPlan.h:4847
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4745
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4798
void setUF(unsigned UF)
Definition VPlan.h:4862
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5012
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:1254
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:4913
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
iterator_range< user_iterator > users()
Definition Value.h:426
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
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.multiplyCoefficientBy(X) will result in a value whos...
Definition TypeSize.h:269
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr ScalarTy getKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns a value X where RHS.multiplyCoefficientBy(X) will result in a value whose quantity matches ou...
Definition TypeSize.h:277
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:216
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr LeafTy multiplyCoefficientBy(ScalarTy RHS) const
Definition TypeSize.h:256
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:171
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#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:2815
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
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_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
m_Intrinsic_Ty< Opnd0, Opnd1, Opnd2 >::Ty m_MaskedStore(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
Matches MaskedStore Intrinsic.
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
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 ?
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
m_Intrinsic_Ty< Opnd0, Opnd1, Opnd2 >::Ty m_MaskedLoad(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
Matches MaskedLoad Intrinsic.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
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)
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)
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.
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.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
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.
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()
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.
VPInstruction_match< VPInstruction::StepVector > m_StepVector()
auto m_VPPhi(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::BranchOnTwoConds > m_BranchOnTwoConds()
AllRecipe_match< Opcode, Op0_t, Op1_t > m_Binary(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::LastActiveLane, Op0_t > m_LastActiveLane(const Op0_t &Op0)
auto m_WidenIntrinsic(const T &...Ops)
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)
specific_intval< 1 > m_False()
VPInstruction_match< VPInstruction::ExtractLastLane, Op0_t > m_ExtractLastLane(const Op0_t &Op0)
VPInstruction_match< VPInstruction::ActiveLaneMask, Op0_t, Op1_t, Op2_t > m_ActiveLaneMask(const Op0_t &Op0, const Op1_t &Op1, const Op2_t &Op2)
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)
specific_intval< 1 > m_True()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VectorEndPointerRecipe_match< Op0_t, Op1_t > m_VecEndPtr(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > m_ExtractLastPart(const Op0_t &Op0)
VPInstruction_match< VPInstruction::Broadcast, Op0_t > m_Broadcast(const Op0_t &Op0)
VPInstruction_match< VPInstruction::ExplicitVectorLength, Op0_t > m_EVL(const Op0_t &Op0)
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)
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)
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...
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
bool cannotHoistOrSinkRecipe(const VPRecipeBase &R, bool Sinking=false)
Return true if we do not know how to (mechanically) hoist or sink R.
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.
VPRecipeBase * findRecipe(VPValue *Start, PredT Pred)
Search Start's users for a recipe satisfying Pred, looking through recipes with definitions.
Definition VPlanUtils.h:116
VPSingleDefRecipe * findHeaderMask(VPlan &Plan)
Collect the header mask with the pattern: (ICMP_ULE, WideCanonicalIV, backedge-taken-count) TODO: Int...
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
static VPRecipeBase * findUserOf(VPValue *V, const MatchT &P)
If V is used by a recipe matching pattern P, return it.
Definition VPlanUtils.h:137
bool isUniformAcrossVFsAndUFs(const VPValue *V)
Checks if V is uniform across all VF lanes and UF parts.
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
bool isHeaderMask(const VPValue *V, const VPlan &Plan)
Return true if V is a header mask in Plan.
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:315
@ Offset
Definition DWP.cpp:558
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:2179
void stable_sort(R &&Range)
Definition STLExtras.h:2115
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:2077
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:1738
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:1668
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:840
DenseMap< const Value *, const SCEV * > ValueToSCEVMapTy
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:2553
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.
constexpr from_range_t from_range
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:2207
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:633
auto cast_or_null(const Y &Val)
Definition Casting.h:714
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:253
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:288
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:2172
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
SmallVector< VPRegisterUsage, 8 > calculateRegisterUsageForPlan(VPlan &Plan, ArrayRef< ElementCount > VFs, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value * > &ValuesToIgnore)
Estimate the register usage for Plan and vectorization factors in VFs by calculating the highest numb...
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1151
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:385
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:1745
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
LLVM_ABI_FOR_TEST cl::opt< bool > EnableWideActiveLaneMask
UncountableExitStyle
Different methods of handling early exits.
Definition VPlan.h:78
@ ReadOnly
No side effects to worry about, so we can process any uncountable exits in the loop and branch either...
Definition VPlan.h:83
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:1752
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:551
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:1882
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:322
@ 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.
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
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:2011
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:2087
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1408
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:1771
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
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:2165
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:325
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:2145
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:305
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:876
#define N
RemoveMask_match(const Op0_t &In, Op1_t &Out)
bool match(OpTy *V) const
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:786
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...
This reduction is unordered with the partial result scaled down by some factor.
Definition VPlan.h:2761
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.
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:1978
CallWideningKind
Choice for how to widen a call at a given VF.
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
VPTypeAnalysis Types
const TargetLibraryInfo & TLI
std::optional< CallWideningKind > getLegacyCallKind(CallInst *CI, ElementCount VF) const
Returns the legacy call widening decision for CI at VF, or std::nullopt if none was recorded.
const TargetTransformInfo & TTI
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:246
Type * getType() const
Returns the type of the underlying IR value.
Definition VPlan.cpp:147
A struct that represents some properties of the register usage of a loop.
SmallMapVector< unsigned, unsigned, 4 > MaxLocalUsers
Holds the maximum number of concurrent live intervals in the loop.
InstructionCost spillCost(const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, unsigned OverrideMaxNumRegs=0) const
Calculate the estimated cost of any spills due to using more registers than the number available for ...
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:286
bool isMaterialized() const
Returns true if this symbolic value has been materialized.
Definition VPlanValue.h:297
A recipe for widening load operations with vector-predication intrinsics, using the address to load f...
Definition VPlan.h:3705
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3656
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:3807
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:3754
static void handleUncountableEarlyExits(VPlan &Plan, VPBasicBlock *HeaderVPBB, VPBasicBlock *LatchVPBB, VPBasicBlock *MiddleVPBB, 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)
Replaces the VPInstructions in Plan with corresponding widen recipes.
static void makeMemOpWideningDecisions(VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder)
Convert load/store VPInstructions in Plan into widened or replicate recipes.
static void materializeBroadcasts(VPlan &Plan)
Add explicit broadcasts for live-ins and VPValues defined in Plan's entry block if they are used as v...
static void materializePacksAndUnpacks(VPlan &Plan)
Add explicit Build[Struct]Vector recipes to Pack multiple scalar values into vectors and Unpack recip...
static void createInterleaveGroups(VPlan &Plan, const SmallPtrSetImpl< const InterleaveGroup< Instruction > * > &InterleaveGroups, const bool &EpilogueAllowed)
static bool simplifyKnownEVL(VPlan &Plan, ElementCount VF, PredicatedScalarEvolution &PSE)
Try to simplify VPInstruction::ExplicitVectorLength recipes when the AVL is known to be <= VF,...
static void removeBranchOnConst(VPlan &Plan, bool OnlyLatches=false)
Remove BranchOnCond recipes with true or false conditions together with removing dead edges to their ...
static void materializeFactors(VPlan &Plan, VPBasicBlock *VectorPH, ElementCount VF)
Materialize UF, VF and VFxUF to be computed explicitly using VPInstructions.
static void materializeBackedgeTakenCount(VPlan &Plan, VPBasicBlock *VectorPH)
Materialize the backedge-taken count to be computed explicitly using VPInstructions.
static void addActiveLaneMask(VPlan &Plan, bool UseActiveLaneMaskForControlFlow)
Replace (ICMP_ULE, wide canonical IV, backedge-taken-count) checks with an (active-lane-mask recipe,...
static void replaceWideCanonicalIVWithWideIV(VPlan &Plan, ScalarEvolution &SE, const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, ElementCount VF, unsigned UF, const SmallPtrSetImpl< const Value * > &ValuesToIgnore)
Replace a VPWidenCanonicalIVRecipe if it is present in Plan, with a VPWidenIntOrFpInductionRecipe,...
static void createAndOptimizeReplicateRegions(VPlan &Plan)
Wrap predicated VPReplicateRecipes with a mask operand in an if-then region block and remove the mask...
static void convertToVariableLengthStep(VPlan &Plan)
Transform loops with variable-length stepping after region dissolution.
static void addBranchWeightToMiddleTerminator(VPlan &Plan, ElementCount VF, std::optional< unsigned > VScaleForTuning)
Add branch weight metadata, if the Plan's middle block is terminated by a BranchOnCond recipe.
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 DenseMap< const SCEV *, Value * > expandSCEVs(VPlan &Plan, ScalarEvolution &SE)
Expand VPExpandSCEVRecipes in Plan's entry block.
static void convertToConcreteRecipes(VPlan &Plan)
Lower abstract recipes to concrete ones, that can be codegen'd.
static void expandBranchOnTwoConds(VPlan &Plan)
Expand BranchOnTwoConds instructions into explicit CFG with BranchOnCond instructions.
static void materializeVectorTripCount(VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking, bool RequiresScalarEpilogue, VPValue *Step, std::optional< uint64_t > MaxRuntimeStep=std::nullopt)
Materialize vector trip count computations to a set of VPInstructions.
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 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 materializeConstantVectorTripCount(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
static void makeScalarizationDecisions(VPlan &Plan, VFRange &Range)
Make VPlan-based scalarization decision prior to delegating to the ones made by the legacy CM.
static void addExplicitVectorLength(VPlan &Plan, const std::optional< unsigned > &MaxEVLSafeElements)
Add a VPCurrentIterationPHIRecipe and related recipes to Plan and replaces all uses of the canonical ...
static void 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 void adjustFirstOrderRecurrenceMiddleUsers(VPlan &Plan, VFRange &Range)
Adjust first-order recurrence users in the middle block: create penultimate element extracts for LCSS...
static void optimizeEVLMasks(VPlan &Plan)
Optimize recipes which use an EVL-based header mask to VP intrinsics, for example:
static void replaceSymbolicStrides(VPlan &Plan, PredicatedScalarEvolution &PSE, const DenseMap< Value *, const SCEV * > &StridesMap)
Replace symbolic strides from StridesMap in Plan with constants when possible.
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void simplifyRecipes(VPlan &Plan)
Perform instcombine-like simplifications on recipes in 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 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 void optimizeInductionLiveOutUsers(VPlan &Plan, PredicatedScalarEvolution &PSE, bool FoldTail)
If there's a single exit block, optimize its phi recipes that use exiting IV values by feeding them p...
static void createPartialReductions(VPlan &Plan, VPCostContext &CostCtx, VFRange &Range)
Detect and create partial reduction recipes for scaled reductions in Plan.
static void cse(VPlan &Plan)
Perform common-subexpression-elimination on Plan.
static LLVM_ABI_FOR_TEST void optimize(VPlan &Plan)
Apply VPlan-to-VPlan optimizations to Plan, including induction recipe optimizations,...
static void dissolveLoopRegions(VPlan &Plan)
Replace loop regions with explicit CFG.
static void truncateToMinimalBitwidths(VPlan &Plan, const MapVector< Instruction *, uint64_t > &MinBWs)
Insert truncates and extends for any truncated recipe.
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 convertEVLExitCond(VPlan &Plan)
Replaces the exit condition from (branch-on-cond eq CanonicalIVInc, VectorTripCount) to (branch-on-co...