LLVM 24.0.0git
LoopVectorizationLegality.h
Go to the documentation of this file.
1//===- llvm/Transforms/Vectorize/LoopVectorizationLegality.h ----*- C++ -*-===//
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 defines the LoopVectorizationLegality class. Original code
11/// in Loop Vectorizer has been moved out to its own file for modularity
12/// and reusability.
13///
14/// Currently, it works for innermost loop vectorization. Extending this to
15/// outer loop vectorization is a TODO item.
16///
17/// Also provides:
18/// 1) LoopVectorizeHints class which keeps a number of loop annotations
19/// locally for easy look up. It has the ability to write them back as
20/// loop metadata, upon request.
21/// 2) LoopVectorizationRequirements class for lazy bail out for the purpose
22/// of reporting useful failure to vectorize message.
23//
24//===----------------------------------------------------------------------===//
25
26#ifndef LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONLEGALITY_H
27#define LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONLEGALITY_H
28
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/MapVector.h"
36
37namespace llvm {
38class AssumptionCache;
39class BasicBlock;
40class DemandedBits;
41class DominatorTree;
42class Function;
43class Loop;
44class LoopInfo;
45class Metadata;
50class Type;
51struct VectorizeOptions;
52
53/// Utility class for getting and setting loop vectorizer hints in the form
54/// of loop metadata.
55/// This class keeps a number of loop annotations locally (as member variables)
56/// and can, upon request, write them back as metadata on the loop. It will
57/// initially scan the loop for existing metadata, and will update the local
58/// values based on information in the loop.
59/// We cannot write all values to metadata, as the mere presence of some info,
60/// for example 'force', means a decision has been made. So, we need to be
61/// careful NOT to add them if the user hasn't specifically asked so.
63 enum HintKind { HK_WIDTH, HK_INTERLEAVE, HK_ISVECTORIZED };
64
65 /// Hint - associates name and validation with the hint value.
66 struct Hint {
67 const char *Name;
68 unsigned Value; // This may have to change for non-numeric values.
69 HintKind Kind;
70
71 Hint(const char *Name, unsigned Value, HintKind Kind)
72 : Name(Name), Value(Value), Kind(Kind) {}
73
74 LLVM_ABI bool validate(unsigned Val);
75 };
76
77 const VectorizeOptions &Opts;
78
79 /// Vectorization width.
80 Hint Width;
81
82 /// Vectorization interleave factor.
83 Hint Interleave;
84
85 /// Vectorization forced; one of ForceKind. Carried as a plain value because
86 /// the enable/disable pair is a standalone tag with no operand to validate.
87 unsigned Force;
88
89 /// Already Vectorized
90 Hint IsVectorized;
91
92 /// Vector Predicate; one of ForceKind, carried as a plain value like Force.
93 unsigned Predicate;
94
95 /// Scalable vs fixed-width preference; one of ScalableForceKind. Carried as
96 /// a plain value because the enable/disable pair has no operand to validate.
97 unsigned Scalable;
98
99 /// Return the loop metadata prefix.
100 static StringRef Prefix() { return "llvm.loop."; }
101
102 /// True if there is any unsafe math in the loop.
103 bool PotentiallyUnsafe = false;
104
105public:
107 FK_Undefined = -1, ///< Not selected.
108 FK_Disabled = 0, ///< Forcing disabled.
109 FK_Enabled = 1, ///< Forcing enabled.
110 };
111
113 /// Not selected.
115 /// Disables vectorization with scalable vectors.
117 /// Vectorize loops using scalable vectors or fixed-width vectors, but favor
118 /// scalable vectors when the cost-model is inconclusive. This is the
119 /// default when the scalable.enable hint is enabled through a pragma.
121 /// Always vectorize loops using scalable vectors if feasible (i.e. the plan
122 /// has a valid cost and is not restricted by fixed-length dependence
123 /// distances).
125 };
126
127 LLVM_ABI LoopVectorizeHints(const VectorizeOptions &Opts, const Loop *L,
128 bool InterleaveOnlyWhenForced,
130 const TargetTransformInfo *TTI = nullptr);
131
132 /// Mark the loop L as already vectorized by setting the width to 1.
134
135 LLVM_ABI bool allowVectorization(Loop *L, bool VectorizeOnlyWhenForced) const;
136
137 /// Dumps all the hint information.
138 LLVM_ABI void emitRemarkWithHints() const;
139
141 return ElementCount::get(
142 Width.Value, (ScalableForceKind)Scalable == SK_PreferScalable ||
144 }
145
146 unsigned getInterleave() const {
147 if (Interleave.Value)
148 return Interleave.Value;
149 // If interleaving is not explicitly set, assume that if we do not want
150 // unrolling, we also don't want any interleaving.
152 return 1;
153 return 0;
154 }
155 unsigned getIsVectorized() const { return IsVectorized.Value; }
156 unsigned getPredicate() const { return Predicate; }
157 enum ForceKind getForce() const {
158 if ((ForceKind)Force == FK_Undefined &&
160 return FK_Disabled;
161 return (ForceKind)Force;
162 }
163
164 /// \return true if scalable vectorization has been explicitly disabled.
166 return (ScalableForceKind)Scalable == SK_FixedWidthOnly;
167 }
168
169 /// \return true if scalable vectorization is always preferred over
170 /// fixed-length when feasible, regardless of cost.
174
175 /// When enabling loop hints are provided we allow the vectorizer to change
176 /// the order of operations that is given by the scalar loop. This is not
177 /// enabled by default because can be unsafe or inefficient. For example,
178 /// reordering floating-point operations will change the way round-off
179 /// error accumulates in the loop.
180 LLVM_ABI bool allowReordering() const;
181
182 bool isPotentiallyUnsafe() const {
183 // Avoid FP vectorization if the target is unsure about proper support.
184 // This may be related to the SIMD unit in the target not handling
185 // IEEE 754 FP ops properly, or bad single-to-double promotions.
186 // Otherwise, a sequence of vectorized loops, even without reduction,
187 // could lead to different end results on the destination vectors.
188 return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
189 }
190
191 void setPotentiallyUnsafe() { PotentiallyUnsafe = true; }
192
193private:
194 /// Find hints specified in the loop metadata and update local values.
195 void getHintsFromMetadata();
196
197 /// Checks string hint with one operand and set value if valid.
198 void setHint(StringRef Name, Metadata *Arg);
199
200 /// The loop these hints belong to.
201 const Loop *TheLoop;
202
203 /// Interface to emit optimization remarks.
205
206 /// Reports a condition where loop vectorization is disallowed: prints
207 /// \p DebugMsg for debugging purposes along with the corresponding
208 /// optimization remark \p RemarkName, with \p RemarkMsg as the user-facing
209 /// message. The loop \p L is used for the location of the remark.
210 void reportDisallowedVectorization(const StringRef DebugMsg,
211 const StringRef RemarkName,
212 const StringRef RemarkMsg,
213 const Loop *L) const;
214};
215
216/// This holds vectorization requirements that must be verified late in
217/// the process. The requirements are set by legalize and costmodel. Once
218/// vectorization has been determined to be possible and profitable the
219/// requirements can be verified by looking for metadata or compiler options.
220/// For example, some loops require FP commutativity which is only allowed if
221/// vectorization is explicitly specified or if the fast-math compiler option
222/// has been provided.
223/// Late evaluation of these requirements allows helpful diagnostics to be
224/// composed that tells the user what need to be done to vectorize the loop. For
225/// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
226/// evaluation should be used only when diagnostics can generated that can be
227/// followed by a non-expert user.
229public:
230 /// Track the 1st floating-point instruction that can not be reassociated.
232 if (I && !ExactFPMathInst)
233 ExactFPMathInst = I;
234 }
235
236 Instruction *getExactFPInst() { return ExactFPMathInst; }
237
238private:
239 Instruction *ExactFPMathInst = nullptr;
240};
241
242/// This holds details about a histogram operation -- a load -> update -> store
243/// sequence where each lane in a vector might be updating the same element as
244/// another lane.
256
257/// Holds details about a "compressed" pointer: the conditional induction PHI
258/// used to derive the pointer and the SCEV expression for the pointer.
263
264/// Indicates the characteristics of a loop with an uncountable exit.
265/// * None -- No uncountable exit present.
266/// * ReadOnly -- At least one uncountable exit in a readonly loop.
267/// * ReadWrite -- At least one uncountable exit in a loop with side effects
268/// that may require masking.
270
271/// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
272/// to what vectorization factor.
273/// This class does not look at the profitability of vectorization, only the
274/// legality. This class has two main kinds of checks:
275/// * Memory checks - The code in canVectorizeMemory checks if vectorization
276/// will change the order of memory accesses in a way that will change the
277/// correctness of the program.
278/// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
279/// checks for a number of different conditions, such as the availability of a
280/// single induction variable, that all types are supported and vectorize-able,
281/// etc. It also identifies the induction and reduction variables of the loop.
283public:
284 LoopVectorizationLegality(const VectorizeOptions &Opts, Loop *L,
291 AssumptionCache *AC, bool AllowRuntimeSCEVChecks,
292 AAResults *AA)
293 : Opts(Opts), TheLoop(L), LI(LI), PSE(PSE), TTI(TTI), TLI(TLI), DT(DT),
294 LAIs(LAIs), ORE(ORE), Requirements(R), Hints(H), DB(DB), AC(AC),
295 AllowRuntimeSCEVChecks(AllowRuntimeSCEVChecks), AA(AA) {}
296
297 /// ReductionList contains the reduction descriptors for all
298 /// of the reductions that were found in the loop.
300
301 /// InductionList saves induction variables and maps them to the
302 /// induction descriptor.
304
305 /// ConditionalInductionList saves conditional inductions and maps them to
306 /// their descriptors.
309
310 /// RecurrenceSet contains the phi nodes that are recurrences other than
311 /// inductions and reductions.
313
314 /// Returns true if it is legal to vectorize this loop.
315 /// This does not mean that it is profitable to vectorize this
316 /// loop, only that it is legal to do so.
317 /// Temporarily taking UseVPlanNativePath parameter. If true, take
318 /// the new code path being implemented for outer loop vectorization
319 /// (should be functional for inner loop vectorization) based on VPlan.
320 /// If false, good old LV code.
321 LLVM_ABI bool canVectorize(bool UseVPlanNativePath);
322
323 /// Returns true if it is legal to vectorize the FP math operations in this
324 /// loop. Vectorizing is legal if we allow reordering of FP operations, or if
325 /// we can use in-order reductions.
326 LLVM_ABI bool canVectorizeFPMath(bool EnableStrictReductions);
327
328 /// Return true if we can vectorize this loop while folding its tail by
329 /// masking.
330 LLVM_ABI bool canFoldTailByMasking() const;
331
332 /// Mark all respective loads/stores for masking. Must only be called when
333 /// tail-folding is possible.
335
336 /// Returns the primary induction variable.
337 PHINode *getPrimaryInduction() { return PrimaryInduction; }
338
339 /// Returns the reduction variables found in the loop.
340 const ReductionList &getReductionVars() const { return Reductions; }
341
342 /// Returns the recurrence descriptor associated with a given phi node \p PN,
343 /// expecting one to exist.
346 "only reductions have recurrence descriptors");
347 return Reductions.find(PN)->second;
348 }
349
350 /// Returns the induction variables found in the loop.
351 const InductionList &getInductionVars() const { return Inductions; }
352
353 /// Returns the conditional inductions found in the loop.
355 return ConditionalInductions;
356 }
357
359 return !ConditionalInductions.empty();
360 }
361
362 /// Return the fixed-order recurrences found in the loop.
363 RecurrenceSet &getFixedOrderRecurrences() { return FixedOrderRecurrences; }
364
365 /// Returns the widest induction type.
366 IntegerType *getWidestInductionType() { return WidestIndTy; }
367
368 /// Returns True if given store is a final invariant store of one of the
369 /// reductions found in the loop.
371
372 /// Returns True if given address is invariant and is used to store recurrent
373 /// expression
375
376 /// Returns True if V is a Phi node of an induction variable in this loop.
377 LLVM_ABI bool isInductionPhi(const Value *V) const;
378
379 /// Returns True if PN is a reduction variable in this loop.
380 bool isReductionVariable(PHINode *PN) const { return Reductions.count(PN); }
381
382 /// Returns True if Phi is a fixed-order recurrence in this loop.
383 LLVM_ABI bool isFixedOrderRecurrence(const PHINode *Phi) const;
384
385 /// Return true if the block BB needs to be predicated in order for the loop
386 /// to be vectorized.
387 LLVM_ABI bool blockNeedsPredication(const BasicBlock *BB) const;
388
389 /// Add unit stride predicates for memory accesses to PSE, if runtime checks
390 /// are allowed and an inner loop is vectorized.
392
393 /// Check if this pointer is consecutive when vectorizing. This happens
394 /// when the last index of the GEP is the induction variable, or that the
395 /// pointer itself is an induction variable.
396 /// This check allows us to vectorize A[idx] into a wide load/store.
397 /// Returns:
398 /// 0 - Stride is unknown or non-consecutive.
399 /// 1 - Address is consecutive.
400 /// -1 - Address is consecutive, and decreasing.
401 /// NOTE: This method must only be used before modifying the original scalar
402 /// loop. Do not use after executing a VPlan (PR34965).
403 LLVM_ABI int isConsecutivePtr(Type *AccessTy, Value *Ptr) const;
404
405 /// Returns true if \p V is invariant across all loop iterations according to
406 /// SCEV.
407 LLVM_ABI bool isInvariant(Value *V) const;
408
409 /// Returns true if value V is uniform across \p VF lanes, when \p VF is
410 /// provided, and otherwise if \p V is invariant across all loop iterations.
411 LLVM_ABI bool isUniform(Value *V, std::optional<ElementCount> VF) const;
412
413 /// A uniform memory op is a load or store which accesses the same memory
414 /// location on all \p VF lanes, if \p VF is provided and otherwise if the
415 /// memory location is invariant.
417 std::optional<ElementCount> VF) const;
418
419 /// Returns the information that we collected about runtime memory check.
421 return LAI->getRuntimePointerChecking();
422 }
423
424 const LoopAccessInfo *getLAI() const { return LAI; }
425
427 return LAI->getDepChecker().isSafeForAnyVectorWidth() &&
428 LAI->getDepChecker().isSafeForAnyStoreLoadForwardDistances();
429 }
430
432 return LAI->getDepChecker().getMaxSafeVectorWidthInBits();
433 }
434
435 /// Returns information about whether this loop contains at least one
436 /// uncountable early exit, and if so, if it also contains instructions (such
437 /// as stores) that cause side-effects.
439 return UncountableExitType;
440 }
441
442 /// Returns true if the loop has uncountable early exits, i.e. uncountable
443 /// exits that aren't the latch block.
447
448 /// Returns true if this is an early exit loop with state-changing or
449 /// potentially-faulting operations and the condition for the uncountable
450 /// exit must be determined before any of the state changes or potentially
451 /// faulting operations take place.
455
456 /// If Cond is a combined exit condition featuring uncountable and countable
457 /// comparisons, returns the countable comparison. Otherwise returns nullptr.
460
461 /// Return true if there is store-load forwarding dependencies.
463 return LAI->getDepChecker().isSafeForAnyStoreLoadForwardDistances();
464 }
465
466 /// Return safe power-of-2 number of elements, which do not prevent store-load
467 /// forwarding and safe to operate simultaneously.
469 return LAI->getDepChecker().getStoreLoadForwardSafeDistanceInBits();
470 }
471
472 /// Returns true if instruction \p I requires a mask for vectorization.
473 /// This accounts for both control flow masking (conditionally executed
474 /// blocks) and tail-folding masking (predicated loop vectorization).
475 bool isMaskRequired(const Instruction *I, bool TailFolded) const {
476 if (TailFolded)
477 return TailFoldedMaskedOp.contains(I);
478 return ConditionallyExecutedOps.contains(I);
479 }
480
481 /// Returns true if there is at least one function call in the loop which
482 /// has a vectorized variant available.
483 bool hasVectorCallVariants() const { return VecCallVariantsFound; }
484
485 /// Returns a HistogramInfo* for the given instruction if it was determined
486 /// to be part of a load -> update -> store sequence where multiple lanes
487 /// may be working on the same memory address.
489 for (const HistogramInfo &HGram : Histograms)
490 if (HGram.Load == I || HGram.Update == I || HGram.Store == I)
491 return &HGram;
492
493 return nullptr;
494 }
495
496 /// Returns a list of all known histogram operations in the loop.
497 bool hasHistograms() const { return !Histograms.empty(); }
498
499 /// Returns the CompressedPtrInfo for \p Ptr if the pointer is defined via
500 /// a conditional induction PHI, otherwise std::nullopt.
501 std::optional<CompressedPtrInfo> getCompressedPtrInfo(Value *Ptr) const {
502 auto It = CompressedPtrs.find(Ptr);
503 if (It != CompressedPtrs.end())
504 return It->second;
505 return std::nullopt;
506 }
507
508 /// Returns true for \p I if it corresponds to a compressed load or store
509 /// (which can map to an llvm.masked.expandload or llvm.masked.compressstore).
514
518
519 Loop *getLoop() const { return TheLoop; }
520
521 LoopInfo *getLoopInfo() const { return LI; }
522
523 AssumptionCache *getAssumptionCache() const { return AC; }
524
525 ScalarEvolution *getScalarEvolution() const { return PSE.getSE(); }
526
527 DominatorTree *getDominatorTree() const { return DT; }
528
529 AAResults *getAA() const { return AA; }
530
531 /// Returns all exiting blocks with a countable exit, i.e. the
532 /// exit-not-taken count is known exactly at compile time.
534 return CountableExitingBlocks;
535 }
536
537private:
538 /// Return true if the pre-header, exiting and latch blocks of \p Lp and all
539 /// its nested loops are considered legal for vectorization. These legal
540 /// checks are common for inner and outer loop vectorization.
541 /// Temporarily taking UseVPlanNativePath parameter. If true, take
542 /// the new code path being implemented for outer loop vectorization
543 /// (should be functional for inner loop vectorization) based on VPlan.
544 /// If false, good old LV code.
545 bool canVectorizeLoopNestCFG(Loop *Lp, bool UseVPlanNativePath);
546
547 /// Set up outer loop inductions by checking Phis in outer loop header for
548 /// supported inductions (int and pointer inductions). Return false if any of
549 /// these Phis is not a supported induction or if we fail to find any
550 /// induction.
551 bool setupOuterLoopInductions();
552
553 /// Return true if the widest induction type, used for the canonical IV and
554 /// trip count, can be determined, i.e. there is at least one integer or
555 /// pointer induction. Otherwise report the reason and return false.
556 bool canDetermineWidestInductionType();
557
558 /// Return true if the pre-header, exiting and latch blocks of \p Lp
559 /// (non-recursive) are considered legal for vectorization.
560 /// Temporarily taking UseVPlanNativePath parameter. If true, take
561 /// the new code path being implemented for outer loop vectorization
562 /// (should be functional for inner loop vectorization) based on VPlan.
563 /// If false, good old LV code.
564 bool canVectorizeLoopCFG(Loop *Lp, bool UseVPlanNativePath) const;
565
566 /// Check if a single basic block loop is vectorizable.
567 /// At this point we know that this is a loop with a constant trip count
568 /// and we only need to check individual instructions.
569 bool canVectorizeInstrs();
570
571 /// Check if an individual instruction is vectorizable.
572 bool canVectorizeInstr(Instruction &I);
573
574 /// When we vectorize loops we may change the order in which
575 /// we read and write from memory. This method checks if it is
576 /// legal to vectorize the code, considering only memory constrains.
577 /// Returns true if the loop is vectorizable
578 bool canVectorizeMemory();
579
580 /// If LAA cannot determine whether all dependences are safe, we may be able
581 /// to further analyse some IndirectUnsafe dependences and if they match a
582 /// certain pattern (like a histogram) then we may still be able to vectorize.
583 bool canVectorizeIndirectUnsafeDependences();
584
585 /// Return true if we can vectorize this loop using the IF-conversion
586 /// transformation.
587 bool canVectorizeWithIfConvert();
588
589 /// Return true if we can vectorize this outer loop. The method performs
590 /// specific checks for outer loop vectorization.
591 bool canVectorizeOuterLoop();
592
593 /// Returns true if this is an early exit loop that can be vectorized.
594 /// Currently, a loop with an uncountable early exit is considered
595 /// vectorizable if:
596 /// 1. Writes to memory will access different underlying objects than
597 /// any load used as part of the uncountable exit condition.
598 /// 2. The loop has only one early uncountable exit
599 /// 3. The early exit block dominates the latch block.
600 /// 4. The latch block has an exact exit count.
601 /// 5. The loop does not contain fixed-order recurrences or reductions where
602 /// the live-out value is used from a non-latch exit..
603 /// 6. We can prove at compile-time that loops will not contain faulting
604 /// loads, or that any faulting loads would also occur in a purely
605 /// scalar loop.
606 /// 7. It is safe to speculatively execute instructions such as divide or
607 /// call instructions.
608 /// The list above is not based on theoretical limitations of vectorization,
609 /// but simply a statement that more work is needed to support these
610 /// additional cases safely.
611 bool isVectorizableEarlyExitLoop();
612
613 /// When vectorizing an early exit loop containing side effects, we need to
614 /// determine whether an uncounted exit will be taken before any operation
615 /// that has side effects.
616 ///
617 /// Consider a loop like the following:
618 /// for (int i = 0; i < N; ++i) {
619 /// a[i] = b[i];
620 /// if (c[i] == 0)
621 /// break;
622 /// }
623 ///
624 /// We have both a load and a store operation occurring before the condition
625 /// is checked for early termination. We could potentially restrict
626 /// vectorization to cases where we know all addresses are guaranteed to be
627 /// dereferenceable, which would allow the load before the condition check to
628 /// be vectorized.
629 ///
630 /// The store, however, should not execute across all lanes if early
631 /// termination occurs before the end of the vector. We must only store to the
632 /// locations that would have been stored to by a scalar loop. So we need to
633 /// know what the result of 'c[i] == 0' is before performing the vector store,
634 /// with or without masking.
635 ///
636 /// We can either do this by moving the condition load to the top of the
637 /// vector body and using the comparison to create masks for other operations
638 /// in the loop, or by looking ahead one vector iteration and bailing out to
639 /// the scalar loop if an exit would occur.
640 ///
641 /// Using the latter approach (applicable to more targets), we need to hoist
642 /// the first load (of c[0]) out of the loop then rotate the load within the
643 /// loop to the next iteration, remembering to adjust the vector trip count.
644 /// Something like the following:
645 ///
646 /// vec.ph:
647 /// %ci.0 = load <4 x i32>, ptr %c
648 /// %cmp.0 = icmp eq <4 x i32> %ci.0, zeroinitializer
649 /// %any.of.0 = call i1 @llvm.vector.reduce.or.v4i1(<4 x i1> %cmp.0)
650 /// br i1 %any.of.0, label %scalar.ph, label %vec.body
651 /// vec.body:
652 /// %iv = phi...
653 /// phi for c[i] if used elsewhere in the loop...
654 /// other operations in the loop...
655 /// %iv.next = add i64 %iv, 4
656 /// %addr.next = getelementptr i32, ptr %c, i64 %iv.next
657 /// %ci.next = load <4 x i32>, ptr %addr.next
658 /// %cmp.next = icmp eq <4 x i32> %ci.next, zeroinitializer
659 /// %any.of.next = call i1 @llvm.vector.reduce.or.v4i1(<4 x i1> %cmp.next)
660 /// iv.next compared with shortened vector tripcount...
661 /// uncountable condition combined with counted condition...
662 /// br...
663 ///
664 /// Doing this means the last few iterations will always be performed by a
665 /// scalar loop regardless of which exit is taken, and so vector iterations
666 /// will never execute a memory operation to a location that the scalar loop
667 /// would not have.
668 ///
669 /// This means we must ensure that it is safe to move the load for 'c[i]'
670 /// before other memory operations (or any other observable side effects) in
671 /// the loop.
672 ///
673 /// Currently, c[i] must have only one user (the comparison used for the
674 /// uncountable exit) since we would otherwise need to introduce a PHI node
675 /// for it.
676 bool canUncountableExitConditionLoadBeMoved(BasicBlock *ExitingBlock);
677
678 struct SafeAccessInfo {
679 uint64_t MaxSizeInBytes = 0;
680 Align MaxAlign = Align(1);
681 };
682
683 /// Maps a pointer to its maximum fixed access size and safe alignment.
684 using SafeAccessesTy = SmallDenseMap<Value *, SafeAccessInfo, 8>;
685
686 /// Return true if all of the instructions in the block can be speculatively
687 /// executed, and record the loads/stores that require masking.
688 /// \p SafeAccesses records pointers that can be accessed unconditionally,
689 /// together with the fixed access sizes and alignments justified for each
690 /// pointer.
691 /// \p MaskedOp is a list of instructions that have to be transformed into
692 /// calls to the appropriate masked intrinsic when the loop is vectorized
693 /// or dropped if the instruction is a conditional assume intrinsic.
694 bool
695 blockCanBePredicated(BasicBlock *BB, SafeAccessesTy &SafeAccesses,
696 SmallPtrSetImpl<const Instruction *> &MaskedOp) const;
697
698 /// Updates the vectorization state by adding \p Phi to the inductions list.
699 /// This can set \p Phi as the main induction of the loop if \p Phi is a
700 /// better choice for the main induction than the existing one.
701 void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID);
702
703 /// Adds \p Phi to the conditional induction list and collects load/store
704 /// users of the PHI. Returns true if all users of \p Phi are legal for
705 /// vectorization.
706 bool addConditionalInduction(PHINode *Phi,
707 const ConditionalInductionDescriptor &CondID);
708
709 const VectorizeOptions &Opts;
710
711 /// The loop that we evaluate.
712 Loop *TheLoop;
713
714 /// Loop Info analysis.
715 LoopInfo *LI;
716
717 /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
718 /// Applies dynamic knowledge to simplify SCEV expressions in the context
719 /// of existing SCEV assumptions. The analysis will also add a minimal set
720 /// of new predicates if this is required to enable vectorization and
721 /// unrolling.
722 PredicatedScalarEvolution &PSE;
723
724 /// Target Transform Info.
725 TargetTransformInfo *TTI;
726
727 /// Target Library Info.
728 TargetLibraryInfo *TLI;
729
730 /// Dominator Tree.
731 DominatorTree *DT;
732
733 // LoopAccess analysis.
734 LoopAccessInfoManager &LAIs;
735
736 const LoopAccessInfo *LAI = nullptr;
737
738 /// Interface to emit optimization remarks.
739 OptimizationRemarkEmitter *ORE;
740
741 // --- vectorization state --- //
742
743 /// Holds the primary induction variable. This is the counter of the
744 /// loop.
745 PHINode *PrimaryInduction = nullptr;
746
747 /// Holds the reduction variables.
749
750 /// Holds all of the induction variables that we found in the loop.
751 /// Notice that inductions don't need to start at zero and that induction
752 /// variables can be pointers.
753 InductionList Inductions;
754
755 /// Holds all of the conditional inductions found in the loop.
756 ConditionalInductionList ConditionalInductions;
757
758 /// Holds the phi nodes that are fixed-order recurrences.
759 RecurrenceSet FixedOrderRecurrences;
760
761 /// Holds the widest induction type encountered.
762 IntegerType *WidestIndTy = nullptr;
763
764 /// Vectorization requirements that will go through late-evaluation.
765 LoopVectorizationRequirements *Requirements;
766
767 /// Used to emit an analysis of any legality issues.
768 LoopVectorizeHints *Hints;
769
770 /// The demanded bits analysis is used to compute the minimum type size in
771 /// which a reduction can be computed.
772 DemandedBits *DB;
773
774 /// The assumption cache analysis is used to compute the minimum type size in
775 /// which a reduction can be computed.
776 AssumptionCache *AC;
777
778 /// Instructions that require masking because they are in source-level
779 /// conditionally executed blocks.
780 SmallPtrSet<const Instruction *, 8> ConditionallyExecutedOps;
781 /// Instructions that require masking only due to tail-folding predication.
782 SmallPtrSet<const Instruction *, 8> TailFoldedMaskedOp;
783
784 /// Contains all identified histogram operations, which are sequences of
785 /// load -> update -> store instructions where multiple lanes in a vector
786 /// may work on the same memory location.
788
789 /// Contains all pointers used in the loop that are defined using an index
790 /// derived from a conditional induction PHI. Loads/stores to these pointers
791 /// map to expandloads or compressstores.
792 SmallDenseMap<const Value *, CompressedPtrInfo> CompressedPtrs;
793
794 /// Whether or not creating SCEV predicates is allowed.
795 bool AllowRuntimeSCEVChecks;
796
797 // Alias Analysis results used to check for possible aliasing with loads
798 // used in uncountable exit conditions.
799 AAResults *AA;
800
801 /// If we discover function calls within the loop which have a valid
802 /// vectorized variant, record that fact so that LoopVectorize can
803 /// (potentially) make a better decision on the maximum VF and enable
804 /// the use of those function variants.
805 bool VecCallVariantsFound = false;
806
807 /// Keep track of all the countable and uncountable exiting blocks if
808 /// the exact backedge taken count is not computable.
809 SmallVector<BasicBlock *, 4> CountableExitingBlocks;
810
811 /// Records whether we have an uncountable early exit in a loop that's
812 /// either read-only or read-write.
813 UncountableExitTrait UncountableExitType = UncountableExitTrait::None;
814};
815
816} // namespace llvm
817
818#endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONLEGALITY_H
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
#define LLVM_ABI
Definition Compiler.h:211
This file defines the DenseMap class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
This file implements a map that provides insertion order iteration.
SmallVector< MachineOperand, 4 > Cond
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
Class to represent integer types.
An instruction for reading from memory.
Drive the analysis of memory accesses in the loop.
bool isCompressedLoadOrStore(Instruction *I)
Returns true for I if it corresponds to a compressed load or store (which can map to an llvm....
MapVector< PHINode *, InductionDescriptor > InductionList
InductionList saves induction variables and maps them to the induction descriptor.
LLVM_ABI bool isInvariantStoreOfReduction(StoreInst *SI)
Returns True if given store is a final invariant store of one of the reductions found in the loop.
bool hasVectorCallVariants() const
Returns true if there is at least one function call in the loop which has a vectorized variant availa...
LLVM_ABI void collectUnitStridePredicates() const
Add unit stride predicates for memory accesses to PSE, if runtime checks are allowed and an inner loo...
const ConditionalInductionList & getConditionalInductions() const
Returns the conditional inductions found in the loop.
const RecurrenceDescriptor & getRecurrenceDescriptor(PHINode *PN) const
Returns the recurrence descriptor associated with a given phi node PN, expecting one to exist.
RecurrenceSet & getFixedOrderRecurrences()
Return the fixed-order recurrences found in the loop.
uint64_t getMaxStoreLoadForwardSafeDistanceInBits() const
Return safe power-of-2 number of elements, which do not prevent store-load forwarding and safe to ope...
LLVM_ABI bool isInvariantAddressOfReduction(Value *V)
Returns True if given address is invariant and is used to store recurrent expression.
LLVM_ABI bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
PredicatedScalarEvolution * getPredicatedScalarEvolution() const
LLVM_ABI bool blockNeedsPredication(const BasicBlock *BB) const
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
LLVM_ABI int isConsecutivePtr(Type *AccessTy, Value *Ptr) const
Check if this pointer is consecutive when vectorizing.
AssumptionCache * getAssumptionCache() const
SmallPtrSet< const PHINode *, 8 > RecurrenceSet
RecurrenceSet contains the phi nodes that are recurrences other than inductions and reductions.
std::optional< CompressedPtrInfo > getCompressedPtrInfo(Value *Ptr) const
Returns the CompressedPtrInfo for Ptr if the pointer is defined via a conditional induction PHI,...
bool hasUncountableExitWithSideEffects() const
Returns true if this is an early exit loop with state-changing or potentially-faulting operations and...
LLVM_ABI bool canVectorizeFPMath(bool EnableStrictReductions)
Returns true if it is legal to vectorize the FP math operations in this loop.
bool isReductionVariable(PHINode *PN) const
Returns True if PN is a reduction variable in this loop.
LLVM_ABI bool isFixedOrderRecurrence(const PHINode *Phi) const
Returns True if Phi is a fixed-order recurrence in this loop.
IntegerType * getWidestInductionType()
Returns the widest induction type.
LLVM_ABI bool isInductionPhi(const Value *V) const
Returns True if V is a Phi node of an induction variable in this loop.
PHINode * getPrimaryInduction()
Returns the primary induction variable.
UncountableExitTrait getUncountableExitTrait() const
Returns information about whether this loop contains at least one uncountable early exit,...
const SmallVector< BasicBlock *, 4 > & getCountableExitingBlocks() const
Returns all exiting blocks with a countable exit, i.e.
LLVM_ABI Instruction * findCountableComparisonInCombinedCondition(Value *Cond) const
If Cond is a combined exit condition featuring uncountable and countable comparisons,...
const HistogramInfo * getHistogramInfo(Instruction *I) const
Returns a HistogramInfo* for the given instruction if it was determined to be part of a load -> updat...
const InductionList & getInductionVars() const
Returns the induction variables found in the loop.
LLVM_ABI bool isInvariant(Value *V) const
Returns true if V is invariant across all loop iterations according to SCEV.
const ReductionList & getReductionVars() const
Returns the reduction variables found in the loop.
bool isSafeForAnyStoreLoadForwardDistances() const
Return true if there is store-load forwarding dependencies.
LLVM_ABI bool canFoldTailByMasking() const
Return true if we can vectorize this loop while folding its tail by masking.
LLVM_ABI void prepareToFoldTailByMasking()
Mark all respective loads/stores for masking.
bool hasUncountableEarlyExit() const
Returns true if the loop has uncountable early exits, i.e.
LLVM_ABI bool isUniformMemOp(Instruction &I, std::optional< ElementCount > VF) const
A uniform memory op is a load or store which accesses the same memory location on all VF lanes,...
bool hasHistograms() const
Returns a list of all known histogram operations in the loop.
const LoopAccessInfo * getLAI() const
MapVector< PHINode *, RecurrenceDescriptor > ReductionList
ReductionList contains the reduction descriptors for all of the reductions that were found in the loo...
ScalarEvolution * getScalarEvolution() const
MapVector< PHINode *, ConditionalInductionDescriptor > ConditionalInductionList
ConditionalInductionList saves conditional inductions and maps them to their descriptors.
bool isMaskRequired(const Instruction *I, bool TailFolded) const
Returns true if instruction I requires a mask for vectorization.
LoopVectorizationLegality(const VectorizeOptions &Opts, Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, Function *F, LoopAccessInfoManager &LAIs, LoopInfo *LI, OptimizationRemarkEmitter *ORE, LoopVectorizationRequirements *R, LoopVectorizeHints *H, DemandedBits *DB, AssumptionCache *AC, bool AllowRuntimeSCEVChecks, AAResults *AA)
LLVM_ABI bool isUniform(Value *V, std::optional< ElementCount > VF) const
Returns true if value V is uniform across VF lanes, when VF is provided, and otherwise if V is invari...
const RuntimePointerChecking * getRuntimePointerChecking() const
Returns the information that we collected about runtime memory check.
This holds vectorization requirements that must be verified late in the process.
void addExactFPMathInst(Instruction *I)
Track the 1st floating-point instruction that can not be reassociated.
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
@ SK_PreferScalable
Vectorize loops using scalable vectors or fixed-width vectors, but favor scalable vectors when the co...
@ SK_AlwaysScalable
Always vectorize loops using scalable vectors if feasible (i.e.
@ SK_FixedWidthOnly
Disables vectorization with scalable vectors.
LLVM_ABI bool allowReordering() const
When enabling loop hints are provided we allow the vectorizer to change the order of operations that ...
LLVM_ABI LoopVectorizeHints(const VectorizeOptions &Opts, const Loop *L, bool InterleaveOnlyWhenForced, OptimizationRemarkEmitter &ORE, const TargetTransformInfo *TTI=nullptr)
LLVM_ABI void emitRemarkWithHints() const
Dumps all the hint information.
LLVM_ABI bool allowVectorization(Loop *L, bool VectorizeOnlyWhenForced) const
LLVM_ABI void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
Root of the metadata hierarchy.
Definition Metadata.h:64
The optimization diagnostic interface.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
This node represents a polynomial recurrence on the trip count of the specified loop.
The main scalar evolution driver.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
This is an optimization pass for GlobalISel generic memory operations.
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
HistogramUpdateKind
The kind of update operation performed on the buckets of a histogram, i.e.
UncountableExitTrait
Indicates the characteristics of a loop with an uncountable exit.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool hasDisableAllTransformsHint(const Loop *L)
Look for the loop attribute that disables all transformation heuristic.
LLVM_ABI TransformationMode hasUnrollTransformation(const Loop *L)
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
TargetTransformInfo TTI
@ TM_Disable
The transformation should not be applied.
Definition LoopUtils.h:301
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Holds details about a "compressed" pointer: the conditional induction PHI used to derive the pointer ...
This holds details about a histogram operation – a load -> update -> store sequence where each lane i...
HistogramInfo(LoadInst *Load, Instruction *Update, StoreInst *Store, HistogramUpdateKind UpdateKind)
HistogramUpdateKind UpdateKind
The update operation applied to the histogram buckets.