LLVM 24.0.0git
VPlanTransforms.h
Go to the documentation of this file.
1//===- VPlanTransforms.h - 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 provides utility VPlan to VPlan transformations.
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLANTRANSFORMS_H
14#define LLVM_TRANSFORMS_VECTORIZE_VPLANTRANSFORMS_H
15
16#include "VPlan.h"
17#include "VPlanVerifier.h"
19#include "llvm/ADT/ScopeExit.h"
23#include "llvm/Support/Regex.h"
24
25namespace llvm {
26
28class Instruction;
29class Loop;
30class LoopVersioning;
32class PHINode;
33class ScalarEvolution;
37class VPBuilder;
38class VPRecipeBuilder;
39struct VFRange;
40
43
44#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
50#endif
51
53 /// Helper to run a VPlan pass \p Pass on \p VPlan, forwarding extra arguments
54 /// to the pass. Performs verification/printing after each VPlan pass if
55 /// requested via command line options.
56 template <bool EnableVerify = true, typename PassTy, typename... ArgsTy>
57 static decltype(auto) runPass(StringRef PassName, PassTy &&Pass, VPlan &Plan,
58 ArgsTy &&...Args) {
59#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
60 auto PrintPlan = [&](StringRef BeforeOrAfterStr) {
61 dbgs()
62 << "VPlan for loop in '"
64 << "' " << BeforeOrAfterStr << " " << PassName << '\n';
67 else
68 dbgs() << Plan << '\n';
69 };
70
71 auto MatchesPassListOption = [&](const cl::list<std::string> &ListOpt) {
72 return (ListOpt.getNumOccurrences() > 0 &&
73 any_of(ListOpt, [PassName](StringRef Entry) {
74 return Regex(Entry).match(PassName);
75 }));
76 };
77
78 if (VPlanPrintBeforeAll || MatchesPassListOption(VPlanPrintBeforePasses))
79 PrintPlan("before");
80#endif
81
82 scope_exit PostTransformActions{[&]() {
83#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
84 // Make sure to print before verification, so that output is more useful
85 // in case of failures:
86 if (VPlanPrintAfterAll || MatchesPassListOption(VPlanPrintAfterPasses))
87 PrintPlan("after");
88#endif
89 if (VerifyEachVPlan && EnableVerify) {
90 if (!verifyVPlanIsValid(Plan))
91 report_fatal_error("Broken VPlan found, compilation aborted!");
92 }
93 }};
94
95 return std::forward<PassTy>(Pass)(Plan, std::forward<ArgsTy>(Args)...);
96 }
97#define RUN_VPLAN_PASS(PASS, ...) \
98 llvm::VPlanTransforms::runPass(#PASS, PASS, __VA_ARGS__)
99#define RUN_VPLAN_PASS_NO_VERIFY(PASS, ...) \
100 llvm::VPlanTransforms::runPass<false>(#PASS, PASS, __VA_ARGS__)
101
102 /// Create a base VPlan0, serving as the common starting point for all later
103 /// candidates. It consists of an initial plain CFG loop with loop blocks from
104 /// \p TheLoop being directly translated to VPBasicBlocks with VPInstruction
105 /// corresponding to the input IR.
106 ///
107 /// The created loop is wrapped in an initial skeleton to facilitate
108 /// vectorization, consisting of a vector pre-header, an exit block for the
109 /// main vector loop (middle.block) and a new block as preheader of the scalar
110 /// loop (scalar.ph). See below for an illustration. It also creates a
111 /// VPValue expression for the original trip count.
112 ///
113 /// [ ] <-- Plan's entry VPIRBasicBlock, wrapping the original loop's
114 /// / \ old preheader. Will contain iteration number check and SCEV
115 /// | | expansions.
116 /// | |
117 /// / v
118 /// | [ ] <-- vector loop bypass (may consist of multiple blocks) will be
119 /// | / | added later.
120 /// | / v
121 /// || [ ] <-- vector pre header.
122 /// |/ |
123 /// | v
124 /// | [ ] \ <-- plain CFG loop wrapping original loop to be vectorized.
125 /// | [ ]_|
126 /// | |
127 /// | v
128 /// | [ ] <--- middle-block with the branch to successors
129 /// | / |
130 /// | / |
131 /// | | v
132 /// \--->[ ] <--- scalar preheader (initial a VPBasicBlock, which will be
133 /// | | replaced later by a VPIRBasicBlock wrapping the scalar
134 /// | | preheader basic block.
135 /// | |
136 /// v <-- edge from middle to exit iff epilogue is not required.
137 /// | [ ] \
138 /// | [ ]_| <-- old scalar loop to handle remainder (scalar epilogue,
139 /// | | header wrapped in VPIRBasicBlock).
140 /// \ |
141 /// \ v
142 /// >[ ] <-- original loop exit block(s), wrapped in VPIRBasicBlocks.
143 LLVM_ABI_FOR_TEST static std::unique_ptr<VPlan>
144 buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy,
145 PredicatedScalarEvolution &PSE, LoopVersioning *LVer = nullptr);
146
147 /// Replace VPPhi recipes in \p Plan's header with corresponding
148 /// VPHeaderPHIRecipe subclasses for inductions, reductions, and
149 /// fixed-order recurrences. This processes all header phis and creates
150 /// the appropriate widened recipe for each one. For fixed-order
151 /// recurrences, also creates FirstOrderRecurrenceSplice instructions and
152 /// sinks/hoists users as needed. Returns false if any fixed-order
153 /// recurrence cannot be handled.
154 static bool createHeaderPhiRecipes(
155 VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop,
156 const VPDominatorTree &VPDT,
157 const MapVector<PHINode *, InductionDescriptor> &Inductions,
158 const MapVector<PHINode *, RecurrenceDescriptor> &Reductions,
159 const SmallPtrSetImpl<const PHINode *> &FixedOrderRecurrences,
160 const SmallPtrSetImpl<PHINode *> &InLoopReductions, bool AllowReordering);
161
162 /// Finalize SCEV predicates by adding induction predicates from \p Plan to
163 /// \p PSE and checking constraints. Returns false if predicated IVs have
164 /// outside-loop uses via ExitingIVValue, if SCEV predicate complexity exceeds
165 /// \p SCEVCheckThreshold, or if predicates are needed but \p OptForSize is
166 /// true.
167 static bool
168 finalizeSCEVPredicates(VPlan &Plan, PredicatedScalarEvolution &PSE,
169 bool OptForSize, unsigned SCEVCheckThreshold,
170 OptimizationRemarkEmitter *ORE, Loop *TheLoop);
171
172 /// Create VPReductionRecipes for in-loop reductions. This processes chains
173 /// of operations contributing to in-loop reductions and creates appropriate
174 /// VPReductionRecipe instances.
175 static void createInLoopReductionRecipes(VPlan &Plan, ElementCount MinVF);
176
177 /// Update \p Plan to account for all early exits. If \p Style is not
178 /// NoUncountableExit, handles uncountable early exits and checks that all
179 /// loads are dereferenceable. Returns false if a non-dereferenceable load is
180 /// found.
181 LLVM_ABI_FOR_TEST static bool
182 handleEarlyExits(VPlan &Plan, UncountableExitStyle Style, Loop *TheLoop,
183 PredicatedScalarEvolution &PSE, DominatorTree &DT,
184 AssumptionCache *AC);
185
186 /// If a check is needed to guard executing the scalar epilogue loop, it will
187 /// be added to the middle block.
188 LLVM_ABI_FOR_TEST static void addMiddleCheck(VPlan &Plan);
189
190 // Create a check in \p CheckBlock to see if the vector loop should be
191 // executed. May create VPExpandSCEV recipes in the plan's entry block.
192 static void addMinimumIterationCheck(
193 VPlan &Plan, ElementCount VF, unsigned UF,
194 ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue,
195 bool TailFolded, Loop *OrigLoop, const uint32_t *MinItersBypassWeights,
196 DebugLoc DL, PredicatedScalarEvolution &PSE, VPBasicBlock *CheckBlock);
197
198 /// Add a new check block before the vector preheader to \p Plan to check if
199 /// the main vector loop should be executed (TC >= VF * UF).
200 static void
201 addIterationCountCheckBlock(VPlan &Plan, ElementCount VF, unsigned UF,
202 bool RequiresScalarEpilogue, Loop *OrigLoop,
204 DebugLoc DL, PredicatedScalarEvolution &PSE);
205
206 /// Add a check to \p Plan to see if the epilogue vector loop should be
207 /// executed.
209 VPlan &Plan, Value *VectorTripCount, bool RequiresScalarEpilogue,
210 ElementCount EpilogueVF, unsigned EpilogueUF, unsigned MainLoopStep,
211 unsigned EpilogueLoopStep, ScalarEvolution &SE);
212
213 /// Replace loops in \p Plan's flat CFG with VPRegionBlocks, turning \p Plan's
214 /// flat CFG into a hierarchical CFG. For the outermost loop, also create the
215 /// canonical IV's increment and adjust the latch terminator: replace
216 /// BranchOnCond with BranchOnCount, using \p DL for the canonical IV.
217 LLVM_ABI_FOR_TEST static void createLoopRegions(VPlan &Plan, DebugLoc DL);
218
219 /// Wrap runtime check block \p CheckBlock in a VPIRBB and \p Cond in a
220 /// VPValue and connect the block to \p Plan, using the VPValue as branch
221 /// condition.
222 static void attachVPCheckBlock(VPlan &Plan, VPValue *Cond,
223 VPBasicBlock *CheckBlock,
224 bool AddBranchWeights);
225 static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock,
226 bool AddBranchWeights);
227
228 /// Replaces the VPInstructions in \p Plan with corresponding
229 /// widen recipes. Returns false if any VPInstructions could not be converted
230 /// to a wide recipe if needed. Uses \p PSE to detect contiguous memory
231 /// accesses w.r.t. the \p OuterLoop induction variable.
233 VPlan &Plan, const TargetLibraryInfo &TLI, PredicatedScalarEvolution &PSE,
234 Loop *OuterLoop);
235
236 /// Try to legalize reductions with multiple in-loop uses. Currently only
237 /// strict and non-strict min/max reductions used by FindLastIV reductions are
238 /// supported, corresponding to computing the first and last argmin/argmax,
239 /// respectively. Otherwise return false.
240 static bool handleMultiUseReductions(VPlan &Plan,
241 OptimizationRemarkEmitter *ORE,
242 Loop *TheLoop);
243
244 /// Check if \p Plan contains any FMaxNum or FMinNum reductions. If they do,
245 /// try to update the vector loop to exit early if any input is NaN and resume
246 /// executing in the scalar loop to handle the NaNs there. Return false if
247 /// this attempt was unsuccessful.
248 static bool handleMaxMinNumReductions(VPlan &Plan);
249
250 /// Check if \p Plan contains any FindLast reductions. If it does, try to
251 /// update the vector loop to save the appropriate state using selects
252 /// for entire vectors for both the latest mask containing at least one active
253 /// element and the corresponding data vector. Return false if this attempt
254 /// was unsuccessful.
255 static bool handleFindLastReductions(VPlan &Plan);
256
257 /// Clear NSW/NUW flags from reduction instructions if necessary.
258 static void clearReductionWrapFlags(VPlan &Plan);
259
260 /// Explicitly unroll \p Plan by \p UF.
261 static void unrollByUF(VPlan &Plan, unsigned UF);
262
263 /// Replace replicating VPReplicateRecipe, VPScalarIVStepsRecipe and
264 /// VPInstruction in \p Plan with \p VF single-scalar recipes. Replicate
265 /// regions are dissolved by replicating their blocks and their recipes \p VF
266 /// times.
267 /// TODO: Also dissolve replicate regions with live outs.
268 static void replicateByVF(VPlan &Plan, ElementCount VF);
269
270 /// Optimize \p Plan based on \p BestVF and \p BestUF. This may restrict the
271 /// resulting plan to \p BestVF and \p BestUF.
272 static void optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF,
273 unsigned BestUF,
274 PredicatedScalarEvolution &PSE);
275
276 /// Try to simplify VPInstruction::ExplicitVectorLength recipes when the AVL
277 /// is known to be <= VF, replacing them with the AVL directly.
278 static bool simplifyKnownEVL(VPlan &Plan, ElementCount VF,
279 PredicatedScalarEvolution &PSE);
280
281 /// Apply VPlan-to-VPlan optimizations to \p Plan, including induction recipe
282 /// optimizations, dead recipe removal, replicate region optimizations and
283 /// block merging.
284 LLVM_ABI_FOR_TEST static void optimize(VPlan &Plan);
285
286 /// Remove redundant VPBasicBlocks by merging them into their single
287 /// predecessor if the latter has a single successor.
288 static bool mergeBlocksIntoPredecessors(VPlan &Plan);
289
290 /// Wrap predicated VPReplicateRecipes with a mask operand in an if-then
291 /// region block and remove the mask operand. Optimize the created regions by
292 /// iteratively sinking scalar operands into the region, followed by merging
293 /// regions until no improvements are remaining.
294 static void createAndOptimizeReplicateRegions(VPlan &Plan);
295
296 /// Materialize the abstract header mask of the loop region into concrete
297 /// recipes: an active-lane-mask if \p UseActiveLaneMask (with a PHI if \p
298 /// UseActiveLaneMaskForControlFlow), else (WideCanonicalIV icmp ule BTC).
299 static void materializeHeaderMask(VPlan &Plan, bool UseActiveLaneMask,
300 bool UseActiveLaneMaskForControlFlow);
301
302 /// Insert truncates and extends for any truncated recipe. Redundant casts
303 /// will be folded later.
304 static void
305 truncateToMinimalBitwidths(VPlan &Plan,
306 const MapVector<Instruction *, uint64_t> &MinBWs);
307
308 /// Replace symbolic strides from \p StridesMap in \p Plan with constants when
309 /// possible.
310 static void
311 replaceSymbolicStrides(VPlan &Plan, PredicatedScalarEvolution &PSE,
312 const DenseMap<Value *, const SCEV *> &StridesMap,
313 const VPDominatorTree &VPDT);
314
315 /// Drop poison flags from recipes that may generate a poison value that is
316 /// used after vectorization, even when their operands are not poison. Those
317 /// recipes meet the following conditions:
318 /// * Contribute to the address computation of a recipe generating a widen
319 /// memory load/store (VPWidenMemoryInstructionRecipe or
320 /// VPInterleaveRecipe).
321 /// * Such a widen memory load/store is masked, but not with the header mask.
322 static void dropPoisonGeneratingRecipes(VPlan &Plan);
323
324 /// Add a VPCurrentIterationPHIRecipe and related recipes to \p Plan and
325 /// replaces all uses of the canonical IV except for the canonical IV
326 /// increment with a VPCurrentIterationPHIRecipe. The canonical IV is only
327 /// used to control the loop after this transformation.
328 static void
329 addExplicitVectorLength(VPlan &Plan,
330 const std::optional<unsigned> &MaxEVLSafeElements);
331
332 /// Optimize recipes which use an EVL-based header mask to VP intrinsics, for
333 /// example:
334 ///
335 /// %mask = icmp ult step-vector, EVL
336 /// %load = load %ptr, %mask
337 /// -->
338 /// %load = vp.load %ptr, EVL
339 static void optimizeEVLMasks(VPlan &Plan);
340
341 // For each Interleave Group in \p InterleaveGroups replace the Recipes
342 // widening its memory instructions with a single VPInterleaveRecipe at its
343 // insertion point.
344 static void createInterleaveGroups(
345 VPlan &Plan,
346 const SmallPtrSetImpl<const InterleaveGroup<Instruction> *>
347 &InterleaveGroups,
348 const bool &EpilogueAllowed);
349
350 /// Transform widen memory recipes into strided access recipes when legal
351 /// and profitable. Clamps \p Range to maintain consistency with widen
352 /// decisions of \p Plan, and uses \p Ctx to evaluate the cost.
353 static void convertToStridedAccesses(VPlan &Plan,
354 PredicatedScalarEvolution &PSE, Loop &L,
355 VPCostContext &Ctx, VFRange &Range);
356
357 /// Remove dead recipes from \p Plan.
358 static void removeDeadRecipes(VPlan &Plan);
359
360 /// Update \p Plan to account for uncountable early exits by introducing
361 /// appropriate branching logic in the latch that handles early exits and the
362 /// latch exit condition. Multiple exits are handled with a dispatch block
363 /// that determines which exit to take based on lane-by-lane semantics.
364 static bool handleUncountableEarlyExits(
365 VPlan &Plan, VPBasicBlock *HeaderVPBB, VPBasicBlock *LatchVPBB,
366 VPBasicBlock *MiddleVPBB, Loop *TheLoop, PredicatedScalarEvolution &PSE,
367 DominatorTree &DT, AssumptionCache *AC, UncountableExitStyle Style);
368
369 /// Replaces the exit condition from
370 /// (branch-on-cond eq CanonicalIVInc, VectorTripCount)
371 /// to
372 /// (branch-on-cond eq AVLNext, 0)
373 static void convertEVLExitCond(VPlan &Plan);
374
375 /// Replace loop regions with explicit CFG.
376 static void dissolveLoopRegions(VPlan &Plan);
377
378 /// Expand BranchOnTwoConds instructions into explicit CFG with
379 /// BranchOnCond instructions. Should be called after dissolveLoopRegions.
380 static void expandBranchOnTwoConds(VPlan &Plan);
381
382 /// Transform loops with variable-length stepping after region
383 /// dissolution.
384 ///
385 /// Once loop regions are replaced with explicit CFG, loops can step with
386 /// variable vector lengths instead of fixed lengths. This transformation:
387 /// * Makes CurrentIteration-Phi concrete.
388 // * Removes CanonicalIV and increment.
389 static void convertToVariableLengthStep(VPlan &Plan);
390
391 /// Lower abstract recipes to concrete ones, that can be codegen'd.
392 static void convertToConcreteRecipes(VPlan &Plan);
393
394 /// This function converts initial recipes to the abstract recipes and clamps
395 /// \p Range based on cost model for following optimizations and cost
396 /// estimations. The converted abstract recipes will lower to concrete
397 /// recipes before codegen.
398 static void convertToAbstractRecipes(VPlan &Plan, VPCostContext &Ctx,
399 VFRange &Range);
400
401 /// Perform instcombine-like simplifications on recipes in \p Plan.
402 static void simplifyRecipes(VPlan &Plan);
403
404 /// Cancel out redundant reverses in \p Plan, e.g. reverse(reverse(x)) -> x.
405 static void simplifyReverses(VPlan &Plan);
406
407 /// Remove BranchOnCond recipes with true or false conditions together with
408 /// removing dead edges to their successors. If \p OnlyLatches is true, only
409 /// process loop latches. Returns true if incoming values from any phi-like
410 /// recipe have been removed.
411 static bool removeBranchOnConst(VPlan &Plan, bool OnlyLatches = false);
412
413 /// Perform common-subexpression-elimination on \p Plan.
414 static void cse(VPlan &Plan);
415
416 /// If there's a single exit block, optimize its phi recipes that use exiting
417 /// IV values by feeding them precomputed end values instead, possibly taken
418 /// one step backwards.
419 static void optimizeInductionLiveOutUsers(VPlan &Plan,
420 PredicatedScalarEvolution &PSE);
421
422 /// Add explicit broadcasts for live-ins and VPValues defined in \p Plan's entry block if they are used as vectors.
423 static void materializeBroadcasts(VPlan &Plan);
424
425 /// Hoist predicated loads from the same address to the loop entry block, if
426 /// they are guaranteed to execute on both paths (i.e., in replicate regions
427 /// with complementary masks P and NOT P).
428 static void hoistPredicatedLoads(VPlan &Plan, PredicatedScalarEvolution &PSE,
429 const Loop *L);
430
431 /// Sink predicated stores to the same address with complementary predicates
432 /// (P and NOT P) to an unconditional store with select recipes for the
433 /// stored values. This eliminates branching overhead when all paths
434 /// unconditionally store to the same location.
435 static void sinkPredicatedStores(VPlan &Plan, PredicatedScalarEvolution &PSE,
436 const Loop *L);
437
438 // Materialize vector trip counts for constants early if it can simply be
439 // computed as (Original TC / VF * UF) * VF * UF.
440 static void
441 materializeConstantVectorTripCount(VPlan &Plan, ElementCount BestVF,
442 unsigned BestUF,
443 PredicatedScalarEvolution &PSE);
444
445 /// Materialize vector trip count computations to a set of VPInstructions.
446 /// \p Step is used as the step value for the trip count computation.
447 /// \p MaxRuntimeStep is the maximum possible runtime value of Step, used to
448 /// prove the trip count is divisible by the step for scalable VFs.
449 static void materializeVectorTripCount(
450 VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking,
451 bool RequiresScalarEpilogue, VPValue *Step,
452 std::optional<uint64_t> MaxRuntimeStep = std::nullopt);
453
454 /// Materialize the backedge-taken count to be computed explicitly using
455 /// VPInstructions.
456 static void materializeBackedgeTakenCount(VPlan &Plan,
457 VPBasicBlock *VectorPH);
458
459 /// Add explicit Build[Struct]Vector recipes to Pack multiple scalar values
460 /// into vectors and Unpack recipes to extract scalars from vectors as
461 /// needed.
462 static void materializePacksAndUnpacks(VPlan &Plan);
463
464 /// Materialize UF, VF and VFxUF to be computed explicitly using
465 /// VPInstructions.
466 static void materializeFactors(VPlan &Plan, VPBasicBlock *VectorPH,
467 ElementCount VF);
468
469 /// Attaches the alias-mask to the existing header-mask.
470 static void attachAliasMaskToHeaderMask(VPlan &Plan);
471
472 /// Materializes within the \p AliasCheckVPBB block. Updates the header mask
473 /// of the loop to use the alias mask. Returns the clamped VF.
474 static VPValue *materializeAliasMask(VPlan &Plan,
475 VPBasicBlock *AliasCheckVPBB,
476 ArrayRef<PointerDiffInfo> DiffChecks);
477
478 /// Materializes the alias mask within a check block before the loop. The
479 /// vector loop will only be entered if the clamped VF from the alias mask
480 /// is not scalar.
482 VPlan &Plan, ArrayRef<PointerDiffInfo> DiffChecks, bool HasBranchWeights);
483
484 /// Try to expand VPExpandSCEVRecipes in \p Plan's entry block to
485 /// VPInstructions. Recipes that cannot be expanded (like casts, min/max) are
486 /// kept for later IR-level expansion.
487 static void expandSCEVsToVPInstructions(VPlan &Plan, ScalarEvolution &SE);
488
489 /// Expand remaining VPExpandSCEVRecipes in \p Plan's entry block using
490 /// SCEVExpander. Each VPExpandSCEVRecipe is replaced with a live-in wrapping
491 /// the expanded IR value. A mapping from SCEV expressions to their expanded
492 /// IR value is returned.
493 static DenseMap<const SCEV *, Value *> expandSCEVs(VPlan &Plan,
494 ScalarEvolution &SE);
495
496 /// Try to find a single VF among \p Plan's VFs for which all interleave
497 /// groups (with known minimum VF elements) can be replaced by wide loads and
498 /// stores processing VF elements, if all transformed interleave groups access
499 /// the full vector width (checked via the maximum vector register width). If
500 /// the transformation can be applied, the original \p Plan will be split in
501 /// 2:
502 /// 1. The original Plan with the single VF containing the optimized recipes
503 /// using wide loads instead of interleave groups.
504 /// 2. A new clone which contains all VFs of Plan except the optimized VF.
505 ///
506 /// This effectively is a very simple form of loop-aware SLP, where we use
507 /// interleave groups to identify candidates.
508 static std::unique_ptr<VPlan>
509 narrowInterleaveGroups(VPlan &Plan, const TargetTransformInfo &TTI);
510
511 /// Adapts the vector loop region for tail folding by introducing a header
512 /// mask and conditionally executing the content of the region:
513 ///
514 /// Vector loop region before:
515 /// +-------------------------------------------+
516 /// |%iv = ... |
517 /// |... |
518 /// |%iv.next = add %iv, vfxuf |
519 /// |branch-on-count %iv.next, vector-trip-count|
520 /// +-------------------------------------------+
521 ///
522 /// Vector loop region after:
523 /// +-------------------------------------------+
524 /// |%iv = ... |
525 /// |%wide.iv = widen-canonical-iv ... |
526 /// |%header-mask = icmp ule %wide.iv, BTC |
527 /// |branch-on-cond %header-mask |---+
528 /// +-------------------------------------------+ |
529 /// | |
530 /// v |
531 /// +-------------------------------------------+ |
532 /// | ... | |
533 /// +-------------------------------------------+ |
534 /// | |
535 /// v |
536 /// +-------------------------------------------+ |
537 /// |<phis> = phi [..., ...], [poison, header] |
538 /// |%iv.next = add %iv, vfxuf |<--+
539 /// |branch-on-count %iv.next, vector-trip-count|
540 /// +-------------------------------------------+
541 ///
542 /// Any VPInstruction::ExtractLastLanes are also updated to extract from the
543 /// last active lane of the header mask.
544 static void foldTailByMasking(VPlan &Plan);
545
546 /// Predicate and linearize the control-flow in the only loop region of
547 /// \p Plan.
548 static void introduceMasksAndLinearize(VPlan &Plan);
549
550 /// Replace a VPWidenCanonicalIVRecipe if it is present in \p Plan, with a
551 /// VPWidenIntOrFpInductionRecipe, provided it would not cause additional
552 /// spills for \p VF at unroll factor \p UF.
554 VPlan &Plan, ScalarEvolution &SE, const TargetTransformInfo &TTI,
556 unsigned UF, const SmallPtrSetImpl<const Value *> &ValuesToIgnore);
557
558 /// Add branch weight metadata, if the \p Plan's middle block is terminated by
559 /// a BranchOnCond recipe.
560 static void
561 addBranchWeightToMiddleTerminator(VPlan &Plan, ElementCount VF,
562 std::optional<unsigned> VScaleForTuning);
563
564 /// Adjust first-order recurrence users in the middle block: create
565 /// penultimate element extracts for LCSSA phi users, and handle penultimate
566 /// extracts of the last active lane edge.
567 static void adjustFirstOrderRecurrenceMiddleUsers(VPlan &Plan,
568 VFRange &Range);
569
570 /// Optimize FindLast reductions selecting IVs (or expressions of IVs) by
571 /// converting them to FindIV reductions, if their IV range excludes a
572 /// suitable sentinel value. For expressions of IVs, the expression is sunk
573 /// to the middle block.
574 static void optimizeFindIVReductions(VPlan &Plan,
575 PredicatedScalarEvolution &PSE, Loop &L);
576
577 /// Detect and create partial reduction recipes for scaled reductions in
578 /// \p Plan. Must be called after recipe construction. If partial reductions
579 /// are only valid for a subset of VFs in Range, Range.End is updated.
580 static void createPartialReductions(VPlan &Plan, VPCostContext &CostCtx,
581 VFRange &Range);
582
583 /// Convert load/store VPInstructions in \p Plan into widened or replicate
584 /// recipes. Non load/store input instructions are left unchanged.
585 static void makeMemOpWideningDecisions(VPlan &Plan, VFRange &Range,
586 VPRecipeBuilder &RecipeBuilder,
587 VPCostContext &CostCtx);
588
589 /// Make VPlan-based scalarization decision prior to delegating to the ones
590 /// made by the legacy CM. Only transforms "usesFirstLaneOnly` def-use chains
591 /// enabled by prior widening of consecutive memory operations for now.
592 static void makeScalarizationDecisions(VPlan &Plan, VFRange &Range);
593
594 /// Convert call VPInstructions in \p Plan into widened call, vector
595 /// intrinsic or replicate recipes based on a cost comparison via \p CostCtx.
596 static void makeCallWideningDecisions(VPlan &Plan, VFRange &Range,
597 VPRecipeBuilder &RecipeBuilder,
598 VPCostContext &CostCtx);
599};
600
601} // namespace llvm
602
603#endif // LLVM_TRANSFORMS_VECTORIZE_VPLANTRANSFORMS_H
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_ABI_FOR_TEST
Definition Compiler.h:220
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 constexpr uint32_t MinItersBypassWeights[]
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
const SmallVectorImpl< MachineOperand > & Cond
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This pass exposes codegen information to IR-level passes.
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 char PassName[]
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
A struct for saving information about induction variables.
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
The optimization diagnostic interface.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
LLVM_ABI bool match(StringRef String, SmallVectorImpl< StringRef > *Matches=nullptr, std::string *Error=nullptr) const
matches - Match the regex against a given String.
Definition Regex.cpp:83
The main scalar evolution driver.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
VPlan-based builder utility analogous to IRBuilder.
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4542
Helper class to create VPRecipies from IR instructions.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print this VPRegionBlock to O (recursively), prefixing all lines with Indent.
Definition VPlan.cpp:819
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4769
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1065
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4920
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI_FOR_TEST cl::opt< bool > VerifyEachVPlan
LLVM_ABI_FOR_TEST cl::opt< bool > VPlanPrintAfterAll
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI_FOR_TEST cl::opt< bool > EnableWideActiveLaneMask
UncountableExitStyle
Different methods of handling early exits.
Definition VPlan.h:79
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI_FOR_TEST cl::list< std::string > VPlanPrintAfterPasses
TargetTransformInfo TTI
LLVM_ABI_FOR_TEST cl::list< std::string > VPlanPrintBeforePasses
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI_FOR_TEST cl::opt< bool > VPlanPrintBeforeAll
LLVM_ABI_FOR_TEST bool verifyVPlanIsValid(const VPlan &Plan)
Verify invariants for general VPlans.
LLVM_ABI_FOR_TEST cl::opt< bool > VPlanPrintVectorRegionScope
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
static VPValue * materializeAliasMask(VPlan &Plan, VPBasicBlock *AliasCheckVPBB, ArrayRef< PointerDiffInfo > DiffChecks)
Materializes within the AliasCheckVPBB block.
static decltype(auto) runPass(StringRef PassName, PassTy &&Pass, VPlan &Plan, ArgsTy &&...Args)
Helper to run a VPlan pass Pass on VPlan, forwarding extra arguments to the pass.
static void expandSCEVsToVPInstructions(VPlan &Plan, ScalarEvolution &SE)
Try to expand VPExpandSCEVRecipes in Plan's entry block to VPInstructions.
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 introduceMasksAndLinearize(VPlan &Plan)
Predicate and linearize the control-flow in the only loop region of Plan.
static void materializeFactors(VPlan &Plan, VPBasicBlock *VectorPH, ElementCount VF)
Materialize UF, VF and VFxUF to be computed explicitly using VPInstructions.
static void foldTailByMasking(VPlan &Plan)
Adapts the vector loop region for tail folding by introducing a header mask and conditionally executi...
static void materializeBackedgeTakenCount(VPlan &Plan, VPBasicBlock *VectorPH)
Materialize the backedge-taken count to be computed explicitly using VPInstructions.
static void addMinimumVectorEpilogueIterationCheck(VPlan &Plan, Value *VectorTripCount, bool RequiresScalarEpilogue, ElementCount EpilogueVF, unsigned EpilogueUF, unsigned MainLoopStep, unsigned EpilogueLoopStep, ScalarEvolution &SE)
Add a check to Plan to see if the epilogue vector loop should be executed.
static LLVM_ABI_FOR_TEST bool tryToConvertVPInstructionsToVPRecipes(VPlan &Plan, const TargetLibraryInfo &TLI, PredicatedScalarEvolution &PSE, Loop *OuterLoop)
Replaces the VPInstructions in Plan with corresponding widen recipes.
static bool handleMultiUseReductions(VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Try to legalize reductions with multiple in-loop uses.
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 materializeHeaderMask(VPlan &Plan, bool UseActiveLaneMask, bool UseActiveLaneMaskForControlFlow)
Materialize the abstract header mask of the loop region into concrete recipes: an active-lane-mask if...
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 bool handleFindLastReductions(VPlan &Plan)
Check if Plan contains any FindLast reductions.
static void createInLoopReductionRecipes(VPlan &Plan, ElementCount MinVF)
Create VPReductionRecipes for in-loop reductions.
static void optimizeInductionLiveOutUsers(VPlan &Plan, PredicatedScalarEvolution &PSE)
If there's a single exit block, optimize its phi recipes that use exiting IV values by feeding them p...
static void materializeAliasMaskCheckBlock(VPlan &Plan, ArrayRef< PointerDiffInfo > DiffChecks, bool HasBranchWeights)
Materializes the alias mask within a check block before the loop.
static void unrollByUF(VPlan &Plan, unsigned UF)
Explicitly unroll Plan by UF.
static DenseMap< const SCEV *, Value * > expandSCEVs(VPlan &Plan, ScalarEvolution &SE)
Expand remaining VPExpandSCEVRecipes in Plan's entry block using SCEVExpander.
static void convertToConcreteRecipes(VPlan &Plan)
Lower abstract recipes to concrete ones, that can be codegen'd.
static LLVM_ABI_FOR_TEST void createLoopRegions(VPlan &Plan, DebugLoc DL)
Replace loops in Plan's flat CFG with VPRegionBlocks, turning Plan's flat CFG into a hierarchical CFG...
static void makeMemOpWideningDecisions(VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder, VPCostContext &CostCtx)
Convert load/store VPInstructions in Plan into widened or replicate recipes.
static LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, PredicatedScalarEvolution &PSE, LoopVersioning *LVer=nullptr)
Create a base VPlan0, serving as the common starting point for all later candidates.
static LLVM_ABI_FOR_TEST void addMiddleCheck(VPlan &Plan)
If a check is needed to guard executing the scalar epilogue loop, it will be added to the middle bloc...
static bool createHeaderPhiRecipes(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, const VPDominatorTree &VPDT, const MapVector< PHINode *, InductionDescriptor > &Inductions, const MapVector< PHINode *, RecurrenceDescriptor > &Reductions, const SmallPtrSetImpl< const PHINode * > &FixedOrderRecurrences, const SmallPtrSetImpl< PHINode * > &InLoopReductions, bool AllowReordering)
Replace VPPhi recipes in Plan's header with corresponding VPHeaderPHIRecipe subclasses for inductions...
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 attachAliasMaskToHeaderMask(VPlan &Plan)
Attaches the alias-mask to the existing header-mask.
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 simplifyReverses(VPlan &Plan)
Cancel out redundant reverses in Plan, e.g. reverse(reverse(x)) -> x.
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 LLVM_ABI_FOR_TEST bool handleEarlyExits(VPlan &Plan, UncountableExitStyle Style, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC)
Update Plan to account for all early exits.
static bool handleMaxMinNumReductions(VPlan &Plan)
Check if Plan contains any FMaxNum or FMinNum reductions.
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock, bool AddBranchWeights)
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 bool finalizeSCEVPredicates(VPlan &Plan, PredicatedScalarEvolution &PSE, bool OptForSize, unsigned SCEVCheckThreshold, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Finalize SCEV predicates by adding induction predicates from Plan to PSE and checking constraints.
static void replaceSymbolicStrides(VPlan &Plan, PredicatedScalarEvolution &PSE, const DenseMap< Value *, const SCEV * > &StridesMap, const VPDominatorTree &VPDT)
Replace symbolic strides from StridesMap in Plan with constants when possible.
static void replicateByVF(VPlan &Plan, ElementCount VF)
Replace replicating VPReplicateRecipe, VPScalarIVStepsRecipe and VPInstruction in Plan with VF single...
static bool removeBranchOnConst(VPlan &Plan, bool OnlyLatches=false)
Remove BranchOnCond recipes with true or false conditions together with removing dead edges to their ...
static void convertToStridedAccesses(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &L, VPCostContext &Ctx, VFRange &Range)
Transform widen memory recipes into strided access recipes when legal and profitable.
static void addIterationCountCheckBlock(VPlan &Plan, ElementCount VF, unsigned UF, bool RequiresScalarEpilogue, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE)
Add a new check block before the vector preheader to Plan to check if the main vector loop should be ...
static bool handleUncountableEarlyExits(VPlan &Plan, VPBasicBlock *HeaderVPBB, VPBasicBlock *LatchVPBB, VPBasicBlock *MiddleVPBB, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC, UncountableExitStyle Style)
Update Plan to account for uncountable early exits by introducing appropriate branching logic in the ...
static void clearReductionWrapFlags(VPlan &Plan)
Clear NSW/NUW flags from reduction instructions if necessary.
static void createPartialReductions(VPlan &Plan, VPCostContext &CostCtx, VFRange &Range)
Detect and create partial reduction recipes for scaled reductions in Plan.
static void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue, bool TailFolded, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE, VPBasicBlock *CheckBlock)
static void cse(VPlan &Plan)
Perform common-subexpression-elimination on Plan.
static void attachVPCheckBlock(VPlan &Plan, VPValue *Cond, VPBasicBlock *CheckBlock, bool AddBranchWeights)
Wrap runtime check block CheckBlock in a VPIRBB and Cond in a VPValue and connect the block to 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...