LLVM 24.0.0git
LoopVectorizationLegality.cpp
Go to the documentation of this file.
1//===- LoopVectorizationLegality.cpp --------------------------------------===//
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// This file provides loop vectorization legality analysis. Original code
10// resided in LoopVectorize.cpp for a long time.
11//
12// At this point, it is implemented as a utility class, not as an analysis
13// pass. It should be easy to create an analysis pass around it if there
14// is a need (but D45420 needs to happen first).
15//
16
20#include "llvm/Analysis/Loads.h"
30#include "llvm/IR/Dominators.h"
35
36using namespace llvm;
37using namespace PatternMatch;
38using namespace LoopVectorizationUtils;
39
40#define LV_NAME "loop-vectorize"
41#define DEBUG_TYPE LV_NAME
42
43static cl::opt<bool>
44 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
45 cl::desc("Enable if-conversion during vectorization."));
46
47static cl::opt<bool>
48AllowStridedPointerIVs("lv-strided-pointer-ivs", cl::init(false), cl::Hidden,
49 cl::desc("Enable recognition of non-constant strided "
50 "pointer induction variables."));
51
52static cl::opt<bool>
53 HintsAllowReordering("hints-allow-reordering", cl::init(true), cl::Hidden,
54 cl::desc("Allow enabling loop hints to reorder "
55 "FP operations during vectorization."));
56
59 "scalable-vectorization", cl::init(LoopVectorizeHints::SK_Unspecified),
61 cl::desc("Control whether the compiler can use scalable vectors to "
62 "vectorize a loop"),
65 "Scalable vectorization is disabled."),
68 "Scalable vectorization is available and favored when the "
69 "cost is inconclusive."),
72 "Scalable vectorization is available and favored when the "
73 "cost is inconclusive."),
76 "Scalable vectorization is available and always favored when "
77 "feasible")));
78
80 "enable-histogram-loop-vectorization", cl::init(false), cl::Hidden,
81 cl::desc("Enables autovectorization of some loops containing histograms"));
82
83/// Maximum vectorization interleave count.
84static const unsigned MaxInterleaveFactor = 16;
85
86namespace llvm {
87
88bool LoopVectorizeHints::Hint::validate(unsigned Val) {
89 switch (Kind) {
90 case HK_WIDTH:
92 case HK_INTERLEAVE:
93 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
94 case HK_ISVECTORIZED:
95 return (Val == 0 || Val == 1);
96 }
97 return false;
98}
99
101 bool InterleaveOnlyWhenForced,
104 : Width("vectorize.width",
105 VectorizerParams::VectorizationFactor.getKnownMinValue(), HK_WIDTH),
106 Interleave("interleave.count", InterleaveOnlyWhenForced, HK_INTERLEAVE),
107 Force(FK_Undefined), IsVectorized("isvectorized", 0, HK_ISVECTORIZED),
108 Predicate(FK_Undefined), Scalable(SK_Unspecified), TheLoop(L), ORE(ORE) {
109 // Populate values with existing loop metadata.
110 getHintsFromMetadata();
111
112 // force-vector-interleave overrides DisableInterleaving.
115
116 // If the metadata doesn't explicitly specify whether to enable scalable
117 // vectorization, then decide based on the following criteria (increasing
118 // level of priority):
119 // - Target default
120 // - Metadata width
121 // - Force option (always overrides)
123 if (TTI)
124 Scalable = TTI->enableScalableVectorization() ? SK_PreferScalable
126
127 if (Width.Value)
128 // If the width is set, but the metadata says nothing about the scalable
129 // property, then assume it concerns only a fixed-width UserVF.
130 // If width is not set, the flag takes precedence.
131 Scalable = SK_FixedWidthOnly;
132 }
133
134 // If the flag is set to force any use of scalable vectors, override the loop
135 // hints.
136 if (ForceScalableVectorization.getValue() !=
138 Scalable = ForceScalableVectorization.getValue();
139
140 // If force-vector-width is scalable, force scalable vectorization.
142 Scalable = SK_AlwaysScalable;
143
144 // Scalable vectorization is disabled if no preference is specified.
146 Scalable = SK_FixedWidthOnly;
147
148 if (IsVectorized.Value != 1)
149 // If the vectorization width and interleaving count are both 1 then
150 // consider the loop to have been already vectorized because there's
151 // nothing more that we can do.
152 IsVectorized.Value =
154 LLVM_DEBUG(if (InterleaveOnlyWhenForced && getInterleave() == 1) dbgs()
155 << "LV: Interleaving disabled by the pass manager\n");
156}
157
159 TheLoop->addIntLoopAttribute("llvm.loop.isvectorized", 1,
160 {Twine(Prefix(), "vectorize.").str(),
161 Twine(Prefix(), "interleave.").str()});
162
163 // Update internal cache.
164 IsVectorized.Value = 1;
165}
166
167void LoopVectorizeHints::reportDisallowedVectorization(
168 const StringRef DebugMsg, const StringRef RemarkName,
169 const StringRef RemarkMsg, const Loop *L) const {
170 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: " << DebugMsg << ".\n");
171 ORE.emit(OptimizationRemarkMissed(LV_NAME, RemarkName, L->getStartLoc(),
172 L->getHeader())
173 << "loop not vectorized: " << RemarkMsg);
174}
175
177 Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
179 if (Force == LoopVectorizeHints::FK_Disabled) {
180 reportDisallowedVectorization("#pragma vectorize disable",
181 "MissedExplicitlyDisabled",
182 "vectorization is explicitly disabled", L);
183 } else if (hasDisableAllTransformsHint(L)) {
184 reportDisallowedVectorization("loop hasDisableAllTransformsHint",
185 "MissedTransformsDisabled",
186 "loop transformations are disabled", L);
187 } else {
188 llvm_unreachable("loop vect disabled for an unknown reason");
189 }
190 return false;
191 }
192
193 if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
194 reportDisallowedVectorization(
195 "VectorizeOnlyWhenForced is set, and no #pragma vectorize enable",
196 "MissedForceOnly", "only vectorizing loops that explicitly request it",
197 L);
198 return false;
199 }
200
201 if (getIsVectorized() == 1) {
202 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
203 // FIXME: Add interleave.disable metadata. This will allow
204 // vectorize.disable to be used without disabling the pass and errors
205 // to differentiate between disabled vectorization and a width of 1.
206 ORE.emit([&]() {
207 return OptimizationRemarkAnalysis(LV_NAME, "AllDisabled",
208 L->getStartLoc(), L->getHeader())
209 << "loop not vectorized: vectorization and interleaving are "
210 "explicitly disabled, or the loop has already been "
211 "vectorized";
212 });
213 return false;
214 }
215
216 return true;
217}
218
220 using namespace ore;
221
222 ORE.emit([&]() {
224 return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
225 TheLoop->getStartLoc(),
226 TheLoop->getHeader())
227 << "loop not vectorized: vectorization is explicitly disabled";
228
229 OptimizationRemarkMissed R(LV_NAME, "MissedDetails", TheLoop->getStartLoc(),
230 TheLoop->getHeader());
231 R << "loop not vectorized";
232 if (Force == LoopVectorizeHints::FK_Enabled) {
233 R << " (Force=" << NV("Force", true);
234 if (Width.Value != 0)
235 R << ", Vector Width=" << NV("VectorWidth", getWidth());
236 if (getInterleave() != 0)
237 R << ", Interleave Count=" << NV("InterleaveCount", getInterleave());
238 R << ")";
239 }
240 return R;
241 });
242}
243
245 // Allow the vectorizer to change the order of operations if enabling
246 // loop hints are provided
247 ElementCount EC = getWidth();
248 return HintsAllowReordering &&
250 EC.getKnownMinValue() > 1);
251}
252
253void LoopVectorizeHints::getHintsFromMetadata() {
254 MDNode *LoopID = TheLoop->getLoopID();
255 if (!LoopID)
256 return;
257
258 // First operand should refer to the loop id itself.
259 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
260 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
261
262 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
263 const MDString *S = nullptr;
265
266 // The expected hint is either a MDString or a MDNode with the first
267 // operand a MDString.
268 if (const MDNode *MD = dyn_cast<MDNode>(MDO)) {
269 if (!MD || MD->getNumOperands() == 0)
270 continue;
271 S = dyn_cast<MDString>(MD->getOperand(0));
272 for (unsigned Idx = 1; Idx < MD->getNumOperands(); ++Idx)
273 Args.push_back(MD->getOperand(Idx));
274 } else {
275 S = dyn_cast<MDString>(MDO);
276 assert(Args.size() == 0 && "too many arguments for MDString");
277 }
278
279 if (!S)
280 continue;
281
282 // Check if the hint starts with the loop metadata prefix.
283 StringRef Name = S->getString();
284 // The single-operand enable/disable pair carries no argument.
285 if (Args.empty()) {
286 if (Name == "llvm.loop.vectorize.enable")
287 Force = FK_Enabled;
288 else if (Name == "llvm.loop.vectorize.disable")
289 Force = FK_Disabled;
290 else if (Name == "llvm.loop.vectorize.predicate.enable")
291 Predicate = FK_Enabled;
292 else if (Name == "llvm.loop.vectorize.predicate.disable")
293 Predicate = FK_Disabled;
294 else if (Name == "llvm.loop.vectorize.scalable.enable")
295 Scalable = SK_PreferScalable;
296 else if (Name == "llvm.loop.vectorize.scalable.disable")
297 Scalable = SK_FixedWidthOnly;
298 continue;
299 }
300 if (Args.size() == 1)
301 setHint(Name, Args[0]);
302 }
303}
304
305void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
306 if (!Name.consume_front(Prefix()))
307 return;
308
309 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
310 if (!C)
311 return;
312 unsigned Val = C->getZExtValue();
313
314 // Force, Predicate, and Scalable are omitted: they are only spelled as
315 // single-operand enable/disable nodes, which never reach setHint().
316 Hint *Hints[] = {&Width, &Interleave, &IsVectorized};
317 for (auto *H : Hints) {
318 if (Name == H->Name) {
319 if (H->validate(Val))
320 H->Value = Val;
321 else
322 LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
323 break;
324 }
325 }
326}
327
329 assert(Ty->isIntOrPtrTy() && "Expected integer or pointer type");
330
331 if (Ty->isPointerTy())
332 return DL.getIntPtrType(Ty->getContext(), Ty->getPointerAddressSpace());
333
334 // It is possible that char's or short's overflow when we ask for the loop's
335 // trip count, work around this by changing the type size.
336 if (Ty->getScalarSizeInBits() < 32)
337 return Type::getInt32Ty(Ty->getContext());
338
339 return cast<IntegerType>(Ty);
340}
341
343 Type *Ty1) {
346 return TyA->getScalarSizeInBits() > TyB->getScalarSizeInBits() ? TyA : TyB;
347}
348
349/// Returns true if A and B have same pointer operands or same SCEVs addresses
351 StoreInst *B) {
352 // Compare store
353 if (A == B)
354 return true;
355
356 // Otherwise Compare pointers
357 Value *APtr = A->getPointerOperand();
358 Value *BPtr = B->getPointerOperand();
359 if (APtr == BPtr)
360 return true;
361
362 // Otherwise compare address SCEVs
363 return SE->getSCEV(APtr) == SE->getSCEV(BPtr);
364}
365
367 if (!AllowRuntimeSCEVChecks || !TheLoop->isInnermost())
368 return;
369
370 for (BasicBlock *BB : TheLoop->blocks())
371 for (Instruction &I : *BB)
374}
375
377 Value *Ptr) const {
378 // FIXME: Currently, the set of symbolic strides is sometimes queried before
379 // it's collected. This happens from canVectorizeWithIfConvert, when the
380 // pointer is checked to reference consecutive elements suitable for a
381 // masked access.
382 // Stride versioning requires adding a SCEV equality predicate; only consult
383 // the symbolic strides when runtime SCEV checks are permitted.
384 const auto &Strides = LAI && AllowRuntimeSCEVChecks
385 ? LAI->getSymbolicStrides()
388 int Stride = getPtrStride(PSE, AccessTy, Ptr, TheLoop, *DT, Strides, false,
389 AllowRuntimeSCEVChecks ? &Predicates : nullptr)
390 .value_or(0);
391 if (Stride != 1 && Stride != -1)
392 return 0;
393 PSE.addPredicates(Predicates);
394 return Stride;
395}
396
398 return LAI->isInvariant(V);
399}
400
401namespace {
402/// A rewriter to build the SCEVs for each of the VF lanes in the expected
403/// vectorized loop, which can then be compared to detect their uniformity. This
404/// is done by replacing the AddRec SCEVs of the original scalar loop (TheLoop)
405/// with new AddRecs where the step is multiplied by StepMultiplier and Offset *
406/// Step is added. Also checks if all sub-expressions are analyzable w.r.t.
407/// uniformity.
408class SCEVAddRecForUniformityRewriter
409 : public SCEVRewriteVisitor<SCEVAddRecForUniformityRewriter> {
410 /// Multiplier to be applied to the step of AddRecs in TheLoop.
411 unsigned StepMultiplier;
412
413 /// Offset to be added to the AddRecs in TheLoop.
414 unsigned Offset;
415
416 /// Loop for which to rewrite AddRecsFor.
417 Loop *TheLoop;
418
419 /// Is any sub-expressions not analyzable w.r.t. uniformity?
420 bool CannotAnalyze = false;
421
422 bool canAnalyze() const { return !CannotAnalyze; }
423
424public:
425 SCEVAddRecForUniformityRewriter(ScalarEvolution &SE, unsigned StepMultiplier,
426 unsigned Offset, Loop *TheLoop)
427 : SCEVRewriteVisitor(SE), StepMultiplier(StepMultiplier), Offset(Offset),
428 TheLoop(TheLoop) {}
429
430 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
431 assert(Expr->getLoop() == TheLoop &&
432 "addrec outside of TheLoop must be invariant and should have been "
433 "handled earlier");
434 // Build a new AddRec by multiplying the step by StepMultiplier and
435 // incrementing the start by Offset * step.
436 Type *Ty = Expr->getType();
437 const SCEV *Step = Expr->getStepRecurrence(SE);
438 if (!SE.isLoopInvariant(Step, TheLoop)) {
439 CannotAnalyze = true;
440 return Expr;
441 }
442 const SCEV *NewStep =
443 SE.getMulExpr(Step, SE.getConstant(Ty, StepMultiplier));
444 const SCEV *ScaledOffset = SE.getMulExpr(Step, SE.getConstant(Ty, Offset));
445 const SCEV *NewStart =
446 SE.getAddExpr(Expr->getStart(), SCEVUse(ScaledOffset));
447 return SE.getAddRecExpr(NewStart, NewStep, TheLoop, SCEV::FlagNone);
448 }
449
450 const SCEV *visit(const SCEV *S) {
451 if (CannotAnalyze || SE.isLoopInvariant(S, TheLoop))
452 return S;
454 }
455
456 const SCEV *visitUnknown(const SCEVUnknown *S) {
457 if (SE.isLoopInvariant(S, TheLoop))
458 return S;
459 // The value could vary across iterations.
460 CannotAnalyze = true;
461 return S;
462 }
463
464 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *S) {
465 // Could not analyze the expression.
466 CannotAnalyze = true;
467 return S;
468 }
469
470 static const SCEV *rewrite(const SCEV *S, ScalarEvolution &SE,
471 unsigned StepMultiplier, unsigned Offset,
472 Loop *TheLoop) {
473 /// Bail out if the expression does not contain an UDiv expression.
474 /// Uniform values which are not loop invariant require operations to strip
475 /// out the lowest bits. For now just look for UDivs and use it to avoid
476 /// re-writing UDIV-free expressions for other lanes to limit compile time.
477 if (!SCEVExprContains(S,
478 [](const SCEV *S) { return isa<SCEVUDivExpr>(S); }))
479 return SE.getCouldNotCompute();
480
481 SCEVAddRecForUniformityRewriter Rewriter(SE, StepMultiplier, Offset,
482 TheLoop);
483 const SCEV *Result = Rewriter.visit(S);
484
485 if (Rewriter.canAnalyze())
486 return Result;
487 return SE.getCouldNotCompute();
488 }
489};
490
491} // namespace
492
494 Value *V, std::optional<ElementCount> VF) const {
495 if (isInvariant(V))
496 return true;
497 if (!VF || VF->isScalable())
498 return false;
499 if (VF->isScalar())
500 return true;
501
502 // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is
503 // never considered uniform.
504 auto *SE = PSE.getSE();
505 if (!SE->isSCEVable(V->getType()))
506 return false;
507 const SCEV *S = SE->getSCEV(V);
508
509 // Rewrite AddRecs in TheLoop to step by VF and check if the expression for
510 // lane 0 matches the expressions for all other lanes.
511 unsigned FixedVF = VF->getKnownMinValue();
512 const SCEV *FirstLaneExpr =
513 SCEVAddRecForUniformityRewriter::rewrite(S, *SE, FixedVF, 0, TheLoop);
514 if (isa<SCEVCouldNotCompute>(FirstLaneExpr))
515 return false;
516
517 // Make sure the expressions for lanes FixedVF-1..1 match the expression for
518 // lane 0. We check lanes in reverse order for compile-time, as frequently
519 // checking the last lane is sufficient to rule out uniformity.
520 return all_of(reverse(seq<unsigned>(1, FixedVF)), [&](unsigned I) {
521 const SCEV *IthLaneExpr =
522 SCEVAddRecForUniformityRewriter::rewrite(S, *SE, FixedVF, I, TheLoop);
523 return FirstLaneExpr == IthLaneExpr;
524 });
525}
526
528 Instruction &I, std::optional<ElementCount> VF) const {
530 if (!Ptr)
531 return false;
532 // Note: There's nothing inherent which prevents predicated loads and
533 // stores from being uniform. The current lowering simply doesn't handle
534 // it; in particular, the cost model distinguishes scatter/gather from
535 // scalar w/predication, and we currently rely on the scalar path.
536 return isUniform(Ptr, VF) && !blockNeedsPredication(I.getParent());
537}
538
539/// Returns true if the type produced by \p I can be widened. Casts from vector
540/// types and extractelement instructions cannot be widened. Struct results are
541/// only supported if \p AllowStructCalls is set, for calls whose users are all
542/// extractvalue instructions and whose struct element types can be widened.
543static bool canWidenResultType(const Instruction &I, bool AllowStructCalls) {
545 (isa<CastInst>(I) &&
546 !VectorType::isValidElementType(I.getOperand(0)->getType())))
547 return false;
548 Type *Ty = I.getType();
549 if (!isa<StructType>(Ty))
550 return canVectorizeTy(Ty);
551 return AllowStructCalls && isa<CallInst>(I) && canVectorizeTy(Ty) &&
553}
554
555/// Returns true if the types produced and stored by \p I can be widened,
556/// otherwise reports a vectorization failure for \p TheLoop and returns false.
557static bool canWidenTypes(Instruction &I, bool AllowStructCalls,
558 OptimizationRemarkEmitter *ORE, Loop *TheLoop) {
559 if (!canWidenResultType(I, AllowStructCalls)) {
560 reportVectorizationFailure("Found unvectorizable type",
561 "instruction return type cannot be vectorized",
562 "CantVectorizeInstructionReturnType", ORE,
563 TheLoop, &I);
564 return false;
565 }
566 auto *SI = dyn_cast<StoreInst>(&I);
567 if (SI && !VectorType::isValidElementType(SI->getValueOperand()->getType())) {
568 reportVectorizationFailure("Store instruction cannot be vectorized",
569 "CantVectorizeStore", ORE, TheLoop, SI);
570 return false;
571 }
572 return true;
573}
574
575/// Returns true if \p I does not use a swifterror value, otherwise reports a
576/// vectorization failure for \p TheLoop and returns false.
577/// TODO: Allow unmasked uniform accesses through loop-invariant swifterror
578/// pointers once memory operations on them are guaranteed to stay scalar.
581 Loop *TheLoop) {
582 if (none_of(I.operands(), [](Value *Op) { return Op->isSwiftError(); }))
583 return true;
584 reportVectorizationFailure("Found a use of a swifterror value",
585 "swifterror value cannot be vectorized",
586 "CantVectorizeSwiftError", ORE, TheLoop, &I);
587 return false;
588}
589
590bool LoopVectorizationLegality::canVectorizeOuterLoop() {
591 assert(!TheLoop->isInnermost() && "We are not vectorizing an outer loop.");
592 // Store the result and return it at the end instead of exiting early, in case
593 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
594 bool Result = true;
595 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
596
597 for (BasicBlock *BB : TheLoop->blocks()) {
598 // Instructions in the loop nest are widened, so the types they produce and
599 // store must be widenable. Struct-returning calls are not supported yet.
600 // Uses of swifterror values must remain scalar.
601 for (Instruction &I : *BB) {
602 if (canWidenTypes(I, /*AllowStructCalls=*/false, ORE, TheLoop) &&
603 canVectorizeSwiftErrorUses(I, ORE, TheLoop))
604 continue;
605 if (!DoExtraAnalysis)
606 return false;
607 Result = false;
608 }
609
610 // Don't try to vectorize outer loops with atomic or volatile accesses.
611 for (Instruction &I : *BB) {
612 if (!I.isAtomic() && !I.isVolatile())
613 continue;
615 "Unsupported volatile or atomic memory operation",
616 "instruction cannot be vectorized", "CantVectorizeInstruction", ORE,
617 TheLoop, &I);
618 if (DoExtraAnalysis)
619 Result = false;
620 else
621 return false;
622 }
623
624 // Check whether the BB terminator is a branch. Any other terminator is
625 // not supported yet.
626 Instruction *Term = BB->getTerminator();
629 "Unsupported basic block terminator",
630 "loop control flow is not understood by vectorizer",
631 "CFGNotUnderstood", ORE, TheLoop);
632 if (DoExtraAnalysis)
633 Result = false;
634 else
635 return false;
636 }
637
638 // Check whether the branch is a supported one. Only unconditional
639 // branches, conditional branches with an outer loop uniform condition or
640 // backedges are supported.
641 // FIXME: We skip these checks when VPlan predication is enabled as we
642 // want to allow divergent branches. This whole check will be removed
643 // once VPlan predication is on by default.
644 auto *Br = dyn_cast<CondBrInst>(Term);
645 if (Br && !TheLoop->isLoopLatch(BB)) {
646 bool IsUniformCondBr = TheLoop->isLoopInvariant(Br->getCondition());
647
648 Value *Lhs = nullptr;
649 Value *Rhs = nullptr;
650 auto *SE = PSE.getSE();
651 if (match(Br->getCondition(), m_c_ICmp(m_Value(Lhs), m_Value(Rhs))) &&
652 !IsUniformCondBr && SE->isSCEVable(Lhs->getType())) {
653 const SCEV *LhsExpr = PSE.getSCEV(Lhs);
654 const SCEV *RhsExpr = PSE.getSCEV(Rhs);
655 IsUniformCondBr |= (SE->isLoopUniform(LhsExpr, TheLoop) &&
656 SE->isLoopUniform(RhsExpr, TheLoop));
657 }
658
659 // If the condition is not uniform, report a failure. We currently require
660 // uniform conditions to avoid the complexity of vectorizing divergent
661 // control flow in the outer loop.
662 if (!IsUniformCondBr) {
664 "Outer loop contains divergent conditional branch",
665 "loop control flow is not understood by vectorizer",
666 "CFGNotUnderstood", ORE, TheLoop);
667 if (DoExtraAnalysis)
668 Result = false;
669 else
670 return false;
671 }
672 }
673 }
674
675 // Each nested loop must exit via its latch only, as a region with the latch
676 // as its only exiting block is created for it. Note that the branch check
677 // rejects divergent exits, but exits with an outer-loop uniform condition
678 // are allowed through.
679 SmallVector<Loop *, 4> LoopNest = TheLoop->getLoopsInPreorder();
680 for (Loop *Lp : drop_begin(LoopNest)) {
681 if (Lp->getExitingBlock() != Lp->getLoopLatch()) {
683 "Nested loop does not exit via its latch",
684 "loop control flow is not understood by vectorizer",
685 "CFGNotUnderstood", ORE, TheLoop);
686 if (DoExtraAnalysis)
687 Result = false;
688 else
689 return false;
690 }
691 }
692
693 // Check whether we are able to set up outer loop induction.
694 if (!setupOuterLoopInductions()) {
695 reportVectorizationFailure("Unsupported outer loop Phi(s)",
696 "UnsupportedPhi", ORE, TheLoop);
697 if (DoExtraAnalysis)
698 Result = false;
699 else
700 return false;
701 }
702
703 // Like for inner loops, the widest integer induction type is used for the
704 // canonical IV and trip count, so at least one integer induction is required.
705 if (!WidestIndTy) {
707 "Did not find one integer induction var",
708 "loop induction variable could not be identified",
709 "NoInductionVariable", ORE, TheLoop);
710 return false;
711 }
712
713 return Result;
714}
715
716void LoopVectorizationLegality::addInductionPhi(PHINode *Phi,
717 const InductionDescriptor &ID) {
718 Inductions[Phi] = ID;
719
720 Type *PhiTy = Phi->getType();
721 const DataLayout &DL = Phi->getDataLayout();
722
723 assert((PhiTy->isIntOrPtrTy() || PhiTy->isFloatingPointTy()) &&
724 "Expected int, ptr, or FP induction phi type");
725
726 // Get the widest type.
727 if (PhiTy->isIntOrPtrTy()) {
728 if (!WidestIndTy)
729 WidestIndTy = getInductionIntegerTy(DL, PhiTy);
730 else
731 WidestIndTy = getWiderInductionTy(DL, PhiTy, WidestIndTy);
732 }
733
734 // Int inductions are special because we only allow one IV.
735 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
736 ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
737 isa<Constant>(ID.getStartValue()) &&
738 cast<Constant>(ID.getStartValue())->isNullValue()) {
739
740 // Use the phi node with the widest type as induction. Use the last
741 // one if there are multiple (no good reason for doing this other
742 // than it is expedient). We've checked that it begins at zero and
743 // steps by one, so this is a canonical induction variable.
744 if (!PrimaryInduction || PhiTy == WidestIndTy)
745 PrimaryInduction = Phi;
746 }
747
748 LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
749}
750
751bool LoopVectorizationLegality::setupOuterLoopInductions() {
752 BasicBlock *Header = TheLoop->getHeader();
753
754 // Returns true if a given Phi is a supported induction.
755 auto IsSupportedPhi = [&](PHINode &Phi) -> bool {
756 InductionDescriptor ID;
757 if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
759 addInductionPhi(&Phi, ID);
760 return true;
761 }
762 // Bail out for any Phi in the outer loop header that is not a supported
763 // induction.
765 dbgs() << "LV: Found unsupported PHI for outer loop vectorization.\n");
766 return false;
767 };
768
769 return llvm::all_of(Header->phis(), IsSupportedPhi);
770}
771
772/// Checks if a function is scalarizable according to the TLI, in
773/// the sense that it should be vectorized and then expanded in
774/// multiple scalar calls. This is represented in the
775/// TLI via mappings that do not specify a vector name, as in the
776/// following example:
777///
778/// const VecDesc VecIntrinsics[] = {
779/// {"llvm.phx.abs.i32", "", 4}
780/// };
781static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI) {
782 const StringRef ScalarName = CI.getCalledFunction()->getName();
783 bool Scalarize = TLI.isFunctionVectorizable(ScalarName);
784 // Check that all known VFs are not associated to a vector
785 // function, i.e. the vector name is emty.
786 if (Scalarize) {
787 ElementCount WidestFixedVF, WidestScalableVF;
788 TLI.getWidestVF(ScalarName, WidestFixedVF, WidestScalableVF);
790 ElementCount::isKnownLE(VF, WidestFixedVF); VF *= 2)
791 Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
793 ElementCount::isKnownLE(VF, WidestScalableVF); VF *= 2)
794 Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
795 assert((WidestScalableVF.isZero() || !Scalarize) &&
796 "Caller may decide to scalarize a variant using a scalable VF");
797 }
798 return Scalarize;
799}
800
801bool LoopVectorizationLegality::canVectorizeInstrs() {
802 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
803 bool Result = true;
804
805 // For each block in the loop.
806 for (BasicBlock *BB : TheLoop->blocks()) {
807 // Scan the instructions in the block and look for hazards.
808 for (Instruction &I : *BB) {
809 Result &= canVectorizeInstr(I);
810 if (!DoExtraAnalysis && !Result)
811 return false;
812 }
813 }
814
815 if (!PrimaryInduction) {
816 if (Inductions.empty()) {
818 "Did not find one integer induction var",
819 "loop induction variable could not be identified",
820 "NoInductionVariable", ORE, TheLoop);
821 return false;
822 }
823 if (!WidestIndTy) {
825 "Did not find one integer induction var",
826 "integer loop induction variable could not be identified",
827 "NoIntegerInductionVariable", ORE, TheLoop);
828 return false;
829 }
830 LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
831 }
832
833 // Now we know the widest induction type, check if our found induction
834 // is the same size. If it's not, unset it here and InnerLoopVectorizer
835 // will create another.
836 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
837 PrimaryInduction = nullptr;
838
839 return Result;
840}
841
842bool LoopVectorizationLegality::canVectorizeInstr(Instruction &I) {
843 BasicBlock *BB = I.getParent();
844 BasicBlock *Header = TheLoop->getHeader();
845
846 if (auto *Phi = dyn_cast<PHINode>(&I)) {
847 Type *PhiTy = Phi->getType();
848 // Check that this PHI type is allowed.
849 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
850 !PhiTy->isPointerTy()) {
852 "Found a non-int non-pointer PHI",
853 "loop control flow is not understood by vectorizer",
854 "CFGNotUnderstood", ORE, TheLoop);
855 return false;
856 }
857
858 // If this PHINode is not in the header block, then we know that we
859 // can convert it to select during if-conversion. No need to check if
860 // the PHIs in this block are induction or reduction variables.
861 if (BB != Header) {
862 // Non-header phi nodes that have outside uses can be vectorized. Unsafe
863 // cyclic dependencies with header phis are identified during legalization
864 // for reduction, induction and fixed order recurrences.
865 return true;
866 }
867
868 // We only allow if-converted PHIs with exactly two incoming values.
869 if (Phi->getNumIncomingValues() != 2) {
871 "Found an invalid PHI",
872 "loop control flow is not understood by vectorizer",
873 "CFGNotUnderstood", ORE, TheLoop, Phi);
874 return false;
875 }
876
877 RecurrenceDescriptor RedDes;
878 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC, DT,
879 PSE.getSE())) {
880 Requirements->addExactFPMathInst(RedDes.getExactFPMathInst());
881 Reductions[Phi] = std::move(RedDes);
884 RedDes.getRecurrenceKind())) &&
885 "Only min/max recurrences are allowed to have multiple uses "
886 "currently");
887 return true;
888 }
889
890 // We prevent matching non-constant strided pointer IVS to preserve
891 // historical vectorizer behavior after a generalization of the
892 // IVDescriptor code. The intent is to remove this check, but we
893 // have to fix issues around code quality for such loops first.
894 auto IsDisallowedStridedPointerInduction =
895 [](const InductionDescriptor &ID) {
897 return false;
898 return ID.getKind() == InductionDescriptor::IK_PtrInduction &&
899 ID.getConstIntStepValue() == nullptr;
900 };
901
902 InductionDescriptor ID;
903 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID) &&
904 !IsDisallowedStridedPointerInduction(ID)) {
905 addInductionPhi(Phi, ID);
906 Requirements->addExactFPMathInst(ID.getExactFPMathInst());
907 return true;
908 }
909
910 if (RecurrenceDescriptor::isFixedOrderRecurrence(Phi, TheLoop, DT)) {
911 FixedOrderRecurrences.insert(Phi);
912 return true;
913 }
914
915 // As a last resort, coerce the PHI to a AddRec expression
916 // and re-try classifying it a an induction PHI.
917 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true) &&
918 !IsDisallowedStridedPointerInduction(ID)) {
919 addInductionPhi(Phi, ID);
920 return true;
921 }
922
923 reportVectorizationFailure("Found an unidentified PHI",
924 "value that could not be identified as "
925 "reduction is used outside the loop",
926 "NonReductionValueUsedOutsideLoop", ORE, TheLoop,
927 Phi);
928 return false;
929 } // end of PHI handling
930
931 if (!canVectorizeSwiftErrorUses(I, ORE, TheLoop))
932 return false;
933
934 // We handle calls that:
935 // * Have a mapping to an IR intrinsic.
936 // * Have a vector version available.
937 auto *CI = dyn_cast<CallInst>(&I);
938
939 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
940 !(CI->getCalledFunction() && TLI &&
941 (!VFDatabase::getMappings(*CI).empty() || isTLIScalarize(*TLI, *CI)))) {
942 // If the call is a recognized math libary call, it is likely that
943 // we can vectorize it given loosened floating-point constraints.
944 bool IsMathLibCall =
945 TLI && CI->getCalledFunction() && CI->getType()->isFloatingPointTy() &&
946 TLI->hasOptimizedCodeGen(
947 TLI->getLibFunc(CI->getCalledFunction()->getName()));
948
949 if (IsMathLibCall) {
950 // TODO: Ideally, we should not use clang-specific language here,
951 // but it's hard to provide meaningful yet generic advice.
952 // Also, should this be guarded by allowExtraAnalysis() and/or be part
953 // of the returned info from isFunctionVectorizable()?
955 "Found a non-intrinsic callsite",
956 "library call cannot be vectorized. "
957 "Try compiling with -fno-math-errno, -ffast-math, "
958 "or similar flags",
959 "CantVectorizeLibcall", ORE, TheLoop, CI);
960 } else {
961 reportVectorizationFailure("Found a non-intrinsic callsite",
962 "call instruction cannot be vectorized",
963 "CantVectorizeLibcall", ORE, TheLoop, CI);
964 }
965 return false;
966 }
967
968 // Some intrinsics have scalar arguments and should be same in order for
969 // them to be vectorized (i.e. loop invariant).
970 if (CI) {
971 auto *SE = PSE.getSE();
972 Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
973 for (unsigned Idx = 0; Idx < CI->arg_size(); ++Idx)
974 if (isVectorIntrinsicWithScalarOpAtArg(IntrinID, Idx, TTI)) {
975 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(Idx)), TheLoop)) {
977 "Found unvectorizable intrinsic",
978 "intrinsic instruction cannot be vectorized",
979 "CantVectorizeIntrinsic", ORE, TheLoop, CI);
980 return false;
981 }
982 }
983 }
984
985 // If we found a vectorized variant of a function, note that so LV can
986 // make better decisions about maximum VF.
987 if (CI && !VFDatabase::getMappings(*CI).empty())
988 VecCallVariantsFound = true;
989
990 // Check that the instruction return and stored types are vectorizable.
991 if (!canWidenTypes(I, /*AllowStructCalls=*/true, ORE, TheLoop))
992 return false;
993
994 if (auto *ST = dyn_cast<StoreInst>(&I)) {
995 // For nontemporal stores, check that a nontemporal vector version is
996 // supported on the target.
997 if (ST->getMetadata(LLVMContext::MD_nontemporal)) {
998 // Arbitrarily try a vector of 2 elements.
999 auto *VecTy =
1000 FixedVectorType::get(ST->getValueOperand()->getType(), /*NumElts=*/2);
1001 assert(VecTy && "did not find vectorized version of stored type");
1002 if (!TTI->isLegalNTStore(VecTy, ST->getAlign())) {
1004 "nontemporal store instruction cannot be vectorized",
1005 "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
1006 return false;
1007 }
1008 }
1009
1010 } else if (auto *LD = dyn_cast<LoadInst>(&I)) {
1011 if (LD->getMetadata(LLVMContext::MD_nontemporal)) {
1012 // For nontemporal loads, check that a nontemporal vector version is
1013 // supported on the target (arbitrarily try a vector of 2 elements).
1014 auto *VecTy = FixedVectorType::get(I.getType(), /*NumElts=*/2);
1015 assert(VecTy && "did not find vectorized version of load type");
1016 if (!TTI->isLegalNTLoad(VecTy, LD->getAlign())) {
1018 "nontemporal load instruction cannot be vectorized",
1019 "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
1020 return false;
1021 }
1022 }
1023
1024 // FP instructions can allow unsafe algebra, thus vectorizable by
1025 // non-IEEE-754 compliant SIMD units.
1026 // This applies to floating-point math operations and calls, not memory
1027 // operations, shuffles, or casts, as they don't change precision or
1028 // semantics.
1029 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
1030 !I.isFast()) {
1031 LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
1032 Hints->setPotentiallyUnsafe();
1033 }
1034
1035 return true;
1036}
1037
1038/// Find histogram operations that match high-level code in loops:
1039/// \code
1040/// buckets[indices[i]]+=step;
1041/// \endcode
1042///
1043/// It matches a pattern starting from \p HSt, which Stores to the 'buckets'
1044/// array the computed histogram. It uses a BinOp to sum all counts, storing
1045/// them using a loop-variant index Load from the 'indices' input array.
1046///
1047/// On successful matches it updates the STATISTIC 'HistogramsDetected',
1048/// regardless of hardware support. When there is support, it additionally
1049/// stores the BinOp/Load pairs in \p HistogramCounts, as well the pointers
1050/// used to update histogram in \p HistogramPtrs.
1051static bool findHistogram(LoadInst *LI, StoreInst *HSt, Loop *TheLoop,
1052 const PredicatedScalarEvolution &PSE,
1053 SmallVectorImpl<HistogramInfo> &Histograms) {
1054
1055 // Store value must come from a Binary Operation.
1056 Instruction *HPtrInstr = nullptr;
1057 BinaryOperator *HBinOp = nullptr;
1058 if (!match(HSt, m_Store(m_BinOp(HBinOp), m_Instruction(HPtrInstr))))
1059 return false;
1060
1061 // BinOp must be an Add or a Sub modifying the bucket value by a
1062 // loop invariant amount.
1063 // FIXME: We assume the loop invariant term is on the RHS.
1064 // Fine for an immediate/constant, but maybe not a generic value?
1065 Value *HIncVal = nullptr;
1066 if (!match(HBinOp, m_Add(m_Load(m_Specific(HPtrInstr)), m_Value(HIncVal))) &&
1067 !match(HBinOp, m_Sub(m_Load(m_Specific(HPtrInstr)), m_Value(HIncVal))))
1068 return false;
1069
1070 // Make sure the increment value is loop invariant.
1071 if (!TheLoop->isLoopInvariant(HIncVal))
1072 return false;
1073
1074 // The address to store is calculated through a GEP Instruction.
1076 if (!GEP)
1077 return false;
1078
1079 // Restrict address calculation to constant indices except for the last term.
1080 Value *HIdx = nullptr;
1081 for (Value *Index : GEP->indices()) {
1082 if (HIdx)
1083 return false;
1084 if (!isa<ConstantInt>(Index))
1085 HIdx = Index;
1086 }
1087
1088 if (!HIdx)
1089 return false;
1090
1091 // Check that the index is calculated by loading from another array. Ignore
1092 // any extensions.
1093 // FIXME: Support indices from other sources than a linear load from memory?
1094 // We're currently trying to match an operation looping over an array
1095 // of indices, but there could be additional levels of indirection
1096 // in place, or possibly some additional calculation to form the index
1097 // from the loaded data.
1098 Value *VPtrVal;
1099 if (!match(HIdx, m_ZExtOrSExtOrSelf(m_Load(m_Value(VPtrVal)))))
1100 return false;
1101
1102 // Make sure the index address varies in this loop, not an outer loop.
1103 const auto *AR = dyn_cast<SCEVAddRecExpr>(PSE.getSE()->getSCEV(VPtrVal));
1104 if (!AR || AR->getLoop() != TheLoop)
1105 return false;
1106
1107 // Ensure we'll have the same mask by checking that all parts of the histogram
1108 // (gather load, update, scatter store) are in the same block.
1109 LoadInst *IndexedLoad = cast<LoadInst>(HBinOp->getOperand(0));
1110 BasicBlock *LdBB = IndexedLoad->getParent();
1111 if (LdBB != HBinOp->getParent() || LdBB != HSt->getParent())
1112 return false;
1113
1114 // The bucket value and its update must not be used outside the histogram.
1115 if (!IndexedLoad->hasOneUse() || !HBinOp->hasOneUse())
1116 return false;
1117
1118 LLVM_DEBUG(dbgs() << "LV: Found histogram for: " << *HSt << "\n");
1119
1120 // Store the operations that make up the histogram.
1121 Histograms.emplace_back(IndexedLoad, HBinOp, HSt);
1122 return true;
1123}
1124
1125bool LoopVectorizationLegality::canVectorizeIndirectUnsafeDependences() {
1126 // For now, we only support an IndirectUnsafe dependency that calculates
1127 // a histogram
1129 return false;
1130
1131 // Find a single IndirectUnsafe dependency.
1132 const MemoryDepChecker::Dependence *IUDep = nullptr;
1133 const MemoryDepChecker &DepChecker = LAI->getDepChecker();
1134 const auto *Deps = DepChecker.getDependences();
1135 // If there were too many dependences, LAA abandons recording them. We can't
1136 // proceed safely if we don't know what the dependences are.
1137 if (!Deps)
1138 return false;
1139
1140 for (const MemoryDepChecker::Dependence &Dep : *Deps) {
1141 // Ignore dependencies that are either known to be safe or can be
1142 // checked at runtime.
1145 continue;
1146
1147 // We're only interested in IndirectUnsafe dependencies here, where the
1148 // address might come from a load from memory. We also only want to handle
1149 // one such dependency, at least for now.
1150 if (Dep.Type != MemoryDepChecker::Dependence::IndirectUnsafe || IUDep)
1151 return false;
1152
1153 IUDep = &Dep;
1154 }
1155 if (!IUDep)
1156 return false;
1157
1158 // For now only normal loads and stores are supported.
1159 LoadInst *LI = dyn_cast<LoadInst>(IUDep->getSource(DepChecker));
1160 StoreInst *SI = dyn_cast<StoreInst>(IUDep->getDestination(DepChecker));
1161
1162 if (!LI || !SI)
1163 return false;
1164
1165 LLVM_DEBUG(dbgs() << "LV: Checking for a histogram on: " << *SI << "\n");
1166 return findHistogram(LI, SI, TheLoop, LAI->getPSE(), Histograms);
1167}
1168
1169bool LoopVectorizationLegality::canVectorizeMemory() {
1170 LAI = &LAIs.getInfo(*TheLoop);
1171 const OptimizationRemarkAnalysis *LAR = LAI->getReport();
1172 if (LAR) {
1173 ORE->emit([&]() {
1174 return OptimizationRemarkAnalysis(LV_NAME, "loop not vectorized: ", *LAR);
1175 });
1176 }
1177
1178 if (!LAI->canVectorizeMemory()) {
1181 "Cannot vectorize unsafe dependencies in uncountable exit loop with "
1182 "side effects",
1183 "CantVectorizeUnsafeDependencyForEELoopWithSideEffects", ORE,
1184 TheLoop);
1185 return false;
1186 }
1187
1188 return canVectorizeIndirectUnsafeDependences();
1189 }
1190
1191 if (LAI->hasLoadStoreDependenceInvolvingLoopInvariantAddress()) {
1192 reportVectorizationFailure("We don't allow storing to uniform addresses",
1193 "write to a loop invariant address could not "
1194 "be vectorized",
1195 "CantVectorizeStoreToLoopInvariantAddress", ORE,
1196 TheLoop);
1197 return false;
1198 }
1199
1200 // We can vectorize stores to invariant address when final reduction value is
1201 // guaranteed to be stored at the end of the loop. Also, if decision to
1202 // vectorize loop is made, runtime checks are added so as to make sure that
1203 // invariant address won't alias with any other objects.
1204 if (!LAI->getStoresToInvariantAddresses().empty()) {
1205 // For each invariant address, check if last stored value is unconditional
1206 // and the address is not calculated inside the loop.
1207 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1209 continue;
1210
1211 if (blockNeedsPredication(SI->getParent())) {
1213 "We don't allow storing to uniform addresses",
1214 "write of conditional recurring variant value to a loop "
1215 "invariant address could not be vectorized",
1216 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1217 return false;
1218 }
1219
1220 // Invariant address should be defined outside of loop. LICM pass usually
1221 // makes sure it happens, but in rare cases it does not, we do not want
1222 // to overcomplicate vectorization to support this case.
1223 if (Instruction *Ptr = dyn_cast<Instruction>(SI->getPointerOperand())) {
1224 if (TheLoop->contains(Ptr)) {
1226 "Invariant address is calculated inside the loop",
1227 "write to a loop invariant address could not "
1228 "be vectorized",
1229 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1230 return false;
1231 }
1232 }
1233 }
1234
1235 if (LAI->hasStoreStoreDependenceInvolvingLoopInvariantAddress()) {
1236 // For each invariant address, check its last stored value is the result
1237 // of one of our reductions.
1238 //
1239 // We do not check if dependence with loads exists because that is already
1240 // checked via hasLoadStoreDependenceInvolvingLoopInvariantAddress.
1241 ScalarEvolution *SE = PSE.getSE();
1242 SmallVector<StoreInst *, 4> UnhandledStores;
1243 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1245 // Earlier stores to this address are effectively deadcode.
1246 // With opaque pointers it is possible for one pointer to be used with
1247 // different sizes of stored values:
1248 // store i32 0, ptr %x
1249 // store i8 0, ptr %x
1250 // The latest store doesn't complitely overwrite the first one in the
1251 // example. That is why we have to make sure that types of stored
1252 // values are same.
1253 // TODO: Check that bitwidth of unhandled store is smaller then the
1254 // one that overwrites it and add a test.
1255 erase_if(UnhandledStores, [SE, SI](StoreInst *I) {
1256 return storeToSameAddress(SE, SI, I) &&
1257 I->getValueOperand()->getType() ==
1258 SI->getValueOperand()->getType();
1259 });
1260 continue;
1261 }
1262 UnhandledStores.push_back(SI);
1263 }
1264
1265 bool IsOK = UnhandledStores.empty();
1266 // TODO: we should also validate against InvariantMemSets.
1267 if (!IsOK) {
1269 "We don't allow storing to uniform addresses",
1270 "write to a loop invariant address could not "
1271 "be vectorized",
1272 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1273 return false;
1274 }
1275 }
1276 }
1277
1278 PSE.addPredicate(LAI->getPSE().getPredicate());
1279 return true;
1280}
1281
1283 bool EnableStrictReductions) {
1284
1285 // First check if there is any ExactFP math or if we allow reassociations
1286 if (!Requirements->getExactFPInst() || Hints->allowReordering())
1287 return true;
1288
1289 // If the above is false, we have ExactFPMath & do not allow reordering.
1290 // If the EnableStrictReductions flag is set, first check if we have any
1291 // Exact FP induction vars, which we cannot vectorize.
1292 if (!EnableStrictReductions ||
1293 any_of(getInductionVars(), [&](auto &Induction) -> bool {
1294 InductionDescriptor IndDesc = Induction.second;
1295 return IndDesc.getExactFPMathInst();
1296 }))
1297 return false;
1298
1299 // We can now only vectorize if all reductions with Exact FP math also
1300 // have the isOrdered flag set, which indicates that we can move the
1301 // reduction operations in-loop.
1302 return (all_of(getReductionVars(), [&](auto &Reduction) -> bool {
1303 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1304 return !RdxDesc.hasExactFPMath() || RdxDesc.isOrdered();
1305 }));
1306}
1307
1309 return any_of(getReductionVars(), [&](auto &Reduction) -> bool {
1310 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1311 return RdxDesc.IntermediateStore == SI;
1312 });
1313}
1314
1316 return any_of(getReductionVars(), [&](auto &Reduction) -> bool {
1317 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1318 if (!RdxDesc.IntermediateStore)
1319 return false;
1320
1321 ScalarEvolution *SE = PSE.getSE();
1322 Value *InvariantAddress = RdxDesc.IntermediateStore->getPointerOperand();
1323 return V == InvariantAddress ||
1324 SE->getSCEV(V) == SE->getSCEV(InvariantAddress);
1325 });
1326}
1327
1329 Value *In0 = const_cast<Value *>(V);
1331 if (!PN)
1332 return false;
1333
1334 return Inductions.count(PN);
1335}
1336
1338 const PHINode *Phi) const {
1339 return FixedOrderRecurrences.count(Phi);
1340}
1341
1343 const BasicBlock *BB) const {
1344 BasicBlock *Latch = TheLoop->getLoopLatch();
1345
1346 // Without a latch, we cannot properly answer blockNeedsPredication,
1347 // return early.
1348 if (!Latch) {
1349 assert(ORE->allowExtraAnalysis(DEBUG_TYPE) &&
1350 !canVectorizeLoopCFG(TheLoop, /*UseVPlanNativePath=*/false) &&
1351 "Loop shape should have been rejected by earlier checks");
1352 return false;
1353 }
1354
1355 // When vectorizing early exits, create predicates for the latch block only.
1356 // For a single early exit, it must be a direct predecessor of the latch.
1357 // For multiple early exits, they form a chain where each exiting block
1358 // dominates all subsequent blocks up to the latch.
1360 return BB == Latch;
1361 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1362}
1363
1364bool LoopVectorizationLegality::blockCanBePredicated(
1365 BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs,
1366 SmallPtrSetImpl<const Instruction *> &MaskedOp) const {
1367 for (Instruction &I : *BB) {
1368 // We can predicate blocks with calls to assume, as long as we drop them in
1369 // case we flatten the CFG via predication.
1371 MaskedOp.insert(&I);
1372 continue;
1373 }
1374
1375 // Do not let llvm.experimental.noalias.scope.decl block the vectorization.
1376 // TODO: there might be cases that it should block the vectorization. Let's
1377 // ignore those for now.
1379 continue;
1380
1381 // We can allow masked calls if there's at least one vector variant, even
1382 // if we end up scalarizing due to the cost model calculations.
1383 // TODO: Allow other calls if they have appropriate attributes... readonly
1384 // and argmemonly?
1385 if (CallInst *CI = dyn_cast<CallInst>(&I))
1387 MaskedOp.insert(CI);
1388 continue;
1389 }
1390
1391 // Loads are handled via masking (or speculated if safe to do so.)
1392 if (auto *LI = dyn_cast<LoadInst>(&I)) {
1393 if (!SafePtrs.count(LI->getPointerOperand()))
1394 MaskedOp.insert(LI);
1395 continue;
1396 }
1397
1398 // Predicated store requires some form of masking:
1399 // 1) masked store HW instruction,
1400 // 2) emulation via load-blend-store (only if safe and legal to do so,
1401 // be aware on the race conditions), or
1402 // 3) element-by-element predicate check and scalar store.
1403 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1404 MaskedOp.insert(SI);
1405 continue;
1406 }
1407
1408 if (I.mayReadFromMemory() || I.mayWriteToMemory() || I.mayThrow())
1409 return false;
1410 }
1411
1412 return true;
1413}
1414
1415bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1416 if (!EnableIfConversion) {
1417 reportVectorizationFailure("If-conversion is disabled",
1418 "IfConversionDisabled", ORE, TheLoop);
1419 return false;
1420 }
1421
1422 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1423
1424 // A list of pointers which are known to be dereferenceable within scope of
1425 // the loop body for each iteration of the loop which executes. That is,
1426 // the memory pointed to can be dereferenced (with the access size implied by
1427 // the value's type) unconditionally within the loop header without
1428 // introducing a new fault.
1429 SmallPtrSet<Value *, 8> SafePointers;
1430
1431 // Collect safe addresses.
1432 for (BasicBlock *BB : TheLoop->blocks()) {
1433 if (!blockNeedsPredication(BB)) {
1434 for (Instruction &I : *BB)
1435 if (auto *Ptr = getLoadStorePointerOperand(&I))
1436 SafePointers.insert(Ptr);
1437 continue;
1438 }
1439
1440 // For a block which requires predication, a address may be safe to access
1441 // in the loop w/o predication if we can prove dereferenceability facts
1442 // sufficient to ensure it'll never fault within the loop. For the moment,
1443 // we restrict this to loads; stores are more complicated due to
1444 // concurrency restrictions.
1445 ScalarEvolution &SE = *PSE.getSE();
1447 for (Instruction &I : *BB) {
1448 LoadInst *LI = dyn_cast<LoadInst>(&I);
1449
1450 // Make sure we can execute all computations feeding into Ptr in the loop
1451 // w/o triggering UB and that none of the out-of-loop operands are poison.
1452 // We do not need to check if operations inside the loop can produce
1453 // poison due to flags (e.g. due to an inbounds GEP going out of bounds),
1454 // because flags will be dropped when executing them unconditionally.
1455 // TODO: Results could be improved by considering poison-propagation
1456 // properties of visited ops.
1457 auto CanSpeculatePointerOp = [this](Value *Ptr) {
1458 SmallVector<Value *> Worklist = {Ptr};
1459 SmallPtrSet<Value *, 4> Visited;
1460 while (!Worklist.empty()) {
1461 Value *CurrV = Worklist.pop_back_val();
1462 if (!Visited.insert(CurrV).second)
1463 continue;
1464
1465 auto *CurrI = dyn_cast<Instruction>(CurrV);
1466 if (!CurrI || !TheLoop->contains(CurrI)) {
1467 BasicBlock *LoopPred = TheLoop->getLoopPredecessor();
1468 Instruction *CtxI = LoopPred ? LoopPred->getTerminator() : nullptr;
1469 assert((CtxI || ORE->allowExtraAnalysis(DEBUG_TYPE)) &&
1470 "Loop with multiple predecessors should have been rejected "
1471 "early.");
1472 // If operands from outside the loop may be poison then Ptr may also
1473 // be poison.
1474 if (!isGuaranteedNotToBePoison(CurrV, AC, CtxI, DT))
1475 return false;
1476 continue;
1477 }
1478
1479 // A loaded value may be poison, independent of any flags.
1480 if (isa<LoadInst>(CurrI) && !isGuaranteedNotToBePoison(CurrV, AC))
1481 return false;
1482
1483 // For other ops, assume poison can only be introduced via flags,
1484 // which can be dropped.
1485 if (!isa<PHINode>(CurrI) && !isSafeToSpeculativelyExecute(CurrI))
1486 return false;
1487 append_range(Worklist, CurrI->operands());
1488 }
1489 return true;
1490 };
1491 // Pass the Predicates pointer to isDereferenceableAndAlignedInLoop so
1492 // that it will consider loops that need guarding by SCEV checks. The
1493 // vectoriser will generate these checks if we decide to vectorise.
1494 if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) &&
1495 CanSpeculatePointerOp(LI->getPointerOperand()) &&
1496 isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT, AC,
1497 &Predicates))
1498 SafePointers.insert(LI->getPointerOperand());
1499 Predicates.clear();
1500 }
1501 }
1502
1503 // Collect the blocks that need predication.
1504 for (BasicBlock *BB : TheLoop->blocks()) {
1505 // We support only branches and switch statements as terminators inside the
1506 // loop.
1507 if (isa<SwitchInst>(BB->getTerminator())) {
1508 if (TheLoop->isLoopExiting(BB)) {
1509 reportVectorizationFailure("Loop contains an unsupported switch",
1510 "LoopContainsUnsupportedSwitch", ORE,
1511 TheLoop, BB->getTerminator());
1512 return false;
1513 }
1514 } else if (!isa<UncondBrInst, CondBrInst>(BB->getTerminator())) {
1515 reportVectorizationFailure("Loop contains an unsupported terminator",
1516 "LoopContainsUnsupportedTerminator", ORE,
1517 TheLoop, BB->getTerminator());
1518 return false;
1519 }
1520
1521 // We must be able to predicate all blocks that need to be predicated.
1522 if (blockNeedsPredication(BB) &&
1523 !blockCanBePredicated(BB, SafePointers, ConditionallyExecutedOps)) {
1525 "Control flow cannot be substituted for a select", "NoCFGForSelect",
1526 ORE, TheLoop, BB->getTerminator());
1527 return false;
1528 }
1529 }
1530
1531 // We can if-convert this loop.
1532 return true;
1533}
1534
1535// Helper function to canVectorizeLoopNestCFG.
1536bool LoopVectorizationLegality::canVectorizeLoopCFG(
1537 Loop *Lp, bool UseVPlanNativePath) const {
1538 assert((UseVPlanNativePath || Lp->isInnermost()) &&
1539 "VPlan-native path is not enabled.");
1540
1541 // TODO: ORE should be improved to show more accurate information when an
1542 // outer loop can't be vectorized because a nested loop is not understood or
1543 // legal. Something like: "outer_loop_location: loop not vectorized:
1544 // (inner_loop_location) loop control flow is not understood by vectorizer".
1545
1546 // Store the result and return it at the end instead of exiting early, in case
1547 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1548 bool Result = true;
1549 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1550
1551 // We must have a loop in canonical form. Loops with indirectbr in them cannot
1552 // be canonicalized.
1553 if (!Lp->getLoopPreheader()) {
1555 "Loop doesn't have a legal pre-header",
1556 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1557 ORE, TheLoop);
1558 if (DoExtraAnalysis)
1559 Result = false;
1560 else
1561 return false;
1562 }
1563
1564 // We must have a single backedge.
1565 if (Lp->getNumBackEdges() != 1) {
1567 "The loop must have a single backedge",
1568 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1569 ORE, TheLoop);
1570 if (DoExtraAnalysis)
1571 Result = false;
1572 else
1573 return false;
1574 }
1575
1576 // The latch must be terminated by a branch.
1577 BasicBlock *Latch = Lp->getLoopLatch();
1578 if (Latch && !isa<UncondBrInst, CondBrInst>(Latch->getTerminator())) {
1580 "The loop latch terminator is not a UncondBrInst/CondBrInst",
1581 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1582 ORE, TheLoop);
1583 if (DoExtraAnalysis)
1584 Result = false;
1585 else
1586 return false;
1587 }
1588
1589 return Result;
1590}
1591
1592bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1593 Loop *Lp, bool UseVPlanNativePath) {
1594 // Store the result and return it at the end instead of exiting early, in case
1595 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1596 bool Result = true;
1597 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1598 if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1599 if (DoExtraAnalysis)
1600 Result = false;
1601 else
1602 return false;
1603 }
1604
1605 // Recursively check whether the loop control flow of nested loops is
1606 // understood.
1607 for (Loop *SubLp : *Lp)
1608 if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1609 if (DoExtraAnalysis)
1610 Result = false;
1611 else
1612 return false;
1613 }
1614
1615 return Result;
1616}
1617
1618/// Matches an exit condition formed by comparing a value loaded from memory
1619/// with another term. Binds the pointer, load, and the other comparison term.
1621 Instruction *&Load, Value *&Other) {
1622 return match(Cond, m_OneUse(m_c_Cmp(
1624 m_Value(Other))));
1625}
1626
1627/// Matches an exit condition formed by comparing the current value of an
1628/// affine add recurrence in the given loop with a stride of 1 against a
1629/// loop-invariant term.
1631 Loop *TheLoop) {
1632 using namespace llvm::SCEVPatternMatch;
1633 Value *IVUpdate, *Limit;
1634 return match(Cond, m_c_ICmp(m_Value(IVUpdate, m_Add(m_Value(), m_Value())),
1635 m_Value(Limit))) &&
1636 TheLoop->isLoopInvariant(Limit) &&
1637 SCEVPatternMatch::match(SE.getSCEV(IVUpdate),
1639 m_SpecificLoop(TheLoop)));
1640}
1641
1642/// Matches a combined exit condition consisting of an uncountable condition and
1643/// a countable condition, combined by an or. Binds the pointer, load, the
1644/// second comparison term for the uncountable condition, and the comparison for
1645/// the countable condition.
1646static bool matchCombinedExitCondition(Value *Cond, Instruction *&CountableCond,
1647 Value *&Ptr, Instruction *&Load,
1649 Loop *TheLoop) {
1650 Value *L, *R;
1651 if (!match(Cond, m_OneUse(m_LogicalOr(m_Value(L), m_Value(R)))))
1652 return false;
1653
1654 if (matchCountableExitCondition(L, SE, TheLoop) &&
1656 CountableCond = cast<Instruction>(L);
1657 return true;
1658 }
1659
1660 if (matchCountableExitCondition(R, SE, TheLoop) &&
1662 CountableCond = cast<Instruction>(R);
1663 return true;
1664 }
1665
1666 return false;
1667}
1668
1671 Value *Cond) const {
1672 Value *Ptr, *Other;
1673 Instruction *Load, *CountableCmp;
1674 if (matchCombinedExitCondition(Cond, CountableCmp, Ptr, Load, Other,
1675 *PSE.getSE(), TheLoop))
1676 return CountableCmp;
1677
1678 return nullptr;
1679}
1680
1681bool LoopVectorizationLegality::isVectorizableEarlyExitLoop() {
1682 BasicBlock *LatchBB = TheLoop->getLoopLatch();
1683 if (!LatchBB) {
1684 reportVectorizationFailure("Loop does not have a latch",
1685 "Cannot vectorize early exit loop",
1686 "NoLatchEarlyExit", ORE, TheLoop);
1687 return false;
1688 }
1689
1690 if (Reductions.size() || FixedOrderRecurrences.size()) {
1692 "Found reductions or recurrences in early-exit loop",
1693 "Cannot vectorize early exit loop with reductions or recurrences",
1694 "RecurrencesInEarlyExitLoop", ORE, TheLoop);
1695 return false;
1696 }
1697
1698 SmallVector<BasicBlock *, 8> ExitingBlocks;
1699 TheLoop->getExitingBlocks(ExitingBlocks);
1700
1701 // Keep a record of all the exiting blocks.
1703 SmallVector<BasicBlock *> UncountableExitingBlocks;
1704 for (BasicBlock *BB : ExitingBlocks) {
1705 const SCEV *EC =
1706 PSE.getSE()->getPredicatedExitCount(TheLoop, BB, &Predicates);
1707 if (isa<SCEVCouldNotCompute>(EC)) {
1708 if (size(successors(BB)) != 2) {
1710 "Early exiting block does not have exactly two successors",
1711 "Incorrect number of successors from early exiting block",
1712 "EarlyExitTooManySuccessors", ORE, TheLoop);
1713 return false;
1714 }
1715
1716 UncountableExitingBlocks.push_back(BB);
1717 } else
1718 CountableExitingBlocks.push_back(BB);
1719 }
1720 // We can safely ignore the predicates here because when vectorizing the loop
1721 // the PredicatatedScalarEvolution class will keep track of all predicates
1722 // for each exiting block anyway. This happens when calling
1723 // PSE.getSymbolicMaxBackedgeTakenCount() below.
1724 Predicates.clear();
1725
1726 if (UncountableExitingBlocks.empty()) {
1727 LLVM_DEBUG(dbgs() << "LV: Could not find any uncountable exits");
1728 return false;
1729 }
1730
1731 // The latch block must have a countable exit.
1732 if (isa<SCEVCouldNotCompute>(PSE.getSE()->getPredicatedExitCount(
1733 TheLoop, LatchBB, &Predicates, ScalarEvolution::SymbolicMaximum))) {
1735 "Cannot determine symbolic max exit count for latch block",
1736 "Cannot vectorize early exit loop",
1737 "UnknownLatchExitCountEarlyExitLoop", ORE, TheLoop);
1738 return false;
1739 }
1740
1741 if (!is_contained(CountableExitingBlocks, LatchBB)) {
1742 // If not a separate counted exit in the latch, then check for a combined
1743 // countable and uncountable exit.
1744 auto *Br = dyn_cast<CondBrInst>(LatchBB->getTerminator());
1745 if (!Br ||
1746 !findCountableComparisonInCombinedCondition(Br->getCondition())) {
1748 "Latch block does not have a countable exit condition",
1749 "NoCountableConditionInLatchBlock", ORE, TheLoop);
1750 return false;
1751 }
1752 }
1753
1754 // Check to see if there are instructions that could potentially generate
1755 // exceptions or have side-effects.
1756 auto IsSafeOperation = [](Instruction *I) -> bool {
1757 switch (I->getOpcode()) {
1758 case Instruction::Load:
1759 case Instruction::Store:
1760 case Instruction::PHI:
1761 case Instruction::UncondBr:
1762 case Instruction::CondBr:
1763 // These are checked separately.
1764 return true;
1765 default:
1767 }
1768 };
1769
1770 bool HasSideEffects = false;
1771 for (auto *BB : TheLoop->blocks())
1772 for (auto &I : *BB) {
1773 if (I.mayWriteToMemory()) {
1774 if (isa<StoreInst>(&I) && cast<StoreInst>(&I)->isSimple()) {
1775 HasSideEffects = true;
1776 continue;
1777 }
1778
1779 // We don't support complex writes to memory.
1781 "Complex writes to memory unsupported in early exit loops",
1782 "Cannot vectorize early exit loop with complex writes to memory",
1783 "WritesInEarlyExitLoop", ORE, TheLoop);
1784 return false;
1785 }
1786
1787 if (!IsSafeOperation(&I)) {
1788 reportVectorizationFailure("Early exit loop contains operations that "
1789 "cannot be speculatively executed",
1790 "UnsafeOperationsEarlyExitLoop", ORE,
1791 TheLoop);
1792 return false;
1793 }
1794 }
1795
1796 SmallVector<LoadInst *, 4> NonDerefLoads;
1797 // TODO: Handle loops that may fault.
1798 if (!HasSideEffects) {
1799 // Read-only loop.
1800 Predicates.clear();
1801 if (!isReadOnlyLoop(TheLoop, PSE.getSE(), DT, AC, NonDerefLoads,
1802 &Predicates)) {
1804 "Loop may fault", "Cannot vectorize non-read-only early exit loop",
1805 "NonReadOnlyEarlyExitLoop", ORE, TheLoop);
1806 return false;
1807 }
1808 } else {
1809 // Check all uncountable exiting blocks for movable loads.
1810 for (BasicBlock *ExitingBB : UncountableExitingBlocks) {
1811 if (!canUncountableExitConditionLoadBeMoved(ExitingBB))
1812 return false;
1813 }
1814 }
1815
1816 // Check non-dereferenceable loads if any.
1817 for (LoadInst *LI : NonDerefLoads) {
1818 // Only support unit-stride access for now.
1819 int Stride = isConsecutivePtr(LI->getType(), LI->getPointerOperand());
1820 if (Stride != 1) {
1822 "Loop contains potentially faulting strided load",
1823 "Cannot vectorize early exit loop with "
1824 "strided fault-only-first load",
1825 "EarlyExitLoopWithStridedFaultOnlyFirstLoad", ORE, TheLoop);
1826 return false;
1827 }
1828 }
1829
1830 // We're only handling combined exit conditions via masking at present, which
1831 // is used for loops with side effects.
1832 // TODO: Support readonly loops with combined exit conditions.
1833 // TODO: Decouple style from the presence of side effects.
1834 if (!llvm::is_contained(CountableExitingBlocks, LatchBB) && !HasSideEffects)
1835 return false;
1836
1837 [[maybe_unused]] const SCEV *SymbolicMaxBTC =
1838 PSE.getSymbolicMaxBackedgeTakenCount();
1839 // Since we have an exact exit count for the latch and the early exit
1840 // dominates the latch, then this should guarantee a computed SCEV value.
1841 assert(!isa<SCEVCouldNotCompute>(SymbolicMaxBTC) &&
1842 "Failed to get symbolic expression for backedge taken count");
1843 LLVM_DEBUG(dbgs() << "LV: Found an early exit loop with symbolic max "
1844 "backedge taken count: "
1845 << *SymbolicMaxBTC << '\n');
1846 UncountableExitType = HasSideEffects ? UncountableExitTrait::ReadWrite
1848 return true;
1849}
1850
1851bool LoopVectorizationLegality::canUncountableExitConditionLoadBeMoved(
1852 BasicBlock *ExitingBlock) {
1853 // Try to find a load in the critical path for the uncountable exit condition.
1854 // This is currently matching about the simplest form we can, expecting
1855 // only one in-loop load, the result of which is directly compared against
1856 // a loop-invariant value.
1857 // FIXME: We're insisting on a single use for now, because otherwise we will
1858 // need to make PHI nodes for other users. That can be done once the initial
1859 // transform code lands.
1860 auto *Br = cast<CondBrInst>(ExitingBlock->getTerminator());
1861
1862 using namespace llvm::PatternMatch;
1863 Value *Ptr, *Other;
1864 Instruction *L, *CountableCond;
1865 // We want to match either an uncounted condition (loaded value compared
1866 // against a loop invariant value) or the combination (via logical or) of
1867 // an uncounted condition with a counted condition (integer comparison of
1868 // an induction variable for which we can identify an add recurrence within
1869 // this loop).
1870 if (!matchUncountableExitCondition(Br->getCondition(), Ptr, L, Other) &&
1871 !matchCombinedExitCondition(Br->getCondition(), CountableCond, Ptr, L,
1872 Other, *PSE.getSE(), TheLoop)) {
1874 "Early exit loop with store but no supported condition load",
1875 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1876 return false;
1877 }
1878
1879 // Bail if the uncountable exit load is compared against a non-invariant
1880 // value.
1881 // TODO: Remove this restriction.
1882 if (!TheLoop->isLoopInvariant(Other)) {
1884 "Early exit loop with store but no supported condition load",
1885 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1886 return false;
1887 }
1888
1889 // Make sure that the load address is not loop invariant; we want an
1890 // address calculation that we can rotate to the next vector iteration.
1891 const auto *AR = dyn_cast<SCEVAddRecExpr>(PSE.getSE()->getSCEV(Ptr));
1892 if (!AR || AR->getLoop() != TheLoop || !AR->isAffine()) {
1894 "Uncountable exit condition depends on load with an address that is "
1895 "not an add recurrence in the loop",
1896 "EarlyExitLoadInvariantAddress", ORE, TheLoop);
1897 return false;
1898 }
1899
1900 ICFLoopSafetyInfo SafetyInfo(TheLoop);
1901 LoadInst *Load = cast<LoadInst>(L);
1902 // We need to know that load will be executed before we can hoist a
1903 // copy out to run just before the first iteration.
1904 if (!SafetyInfo.isGuaranteedToExecute(*Load, DT)) {
1906 "Load for uncountable exit not guaranteed to execute",
1907 "ConditionalUncountableExitLoad", ORE, TheLoop);
1908 return false;
1909 }
1910
1911 // Prohibit any potential aliasing with any instruction in the loop which
1912 // might store to memory.
1913 // FIXME: Relax this constraint where possible.
1914 for (auto *BB : TheLoop->blocks()) {
1915 for (auto &I : *BB) {
1916 if (&I == Load)
1917 continue;
1918
1919 if (I.mayReadOrWriteMemory()) {
1920 // We need to mask all other memory ops.
1921 ConditionallyExecutedOps.insert(&I);
1922 if (isa<LoadInst>(&I))
1923 continue;
1924 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1925 AliasResult AR = AA->alias(Ptr, SI->getPointerOperand());
1926 if (AR == AliasResult::NoAlias)
1927 continue;
1928 }
1929
1931 "Cannot determine whether critical uncountable exit load address "
1932 "does not alias with a memory write",
1933 "CantVectorizeAliasWithCriticalUncountableExitLoad", ORE, TheLoop);
1934 return false;
1935 }
1936 }
1937 }
1938
1939 return true;
1940}
1941
1942bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1943 // Store the result and return it at the end instead of exiting early, in case
1944 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1945 bool Result = true;
1946
1947 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1948 // Check whether the loop-related control flow in the loop nest is expected by
1949 // vectorizer.
1950 if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1951 if (DoExtraAnalysis) {
1952 LLVM_DEBUG(dbgs() << "LV: legality check failed: loop nest");
1953 Result = false;
1954 } else {
1955 return false;
1956 }
1957 }
1958
1959 // We need to have a loop header.
1960 LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1961 << '\n');
1962
1963 // Specific checks for outer loops. We skip the remaining legal checks at this
1964 // point because they don't support outer loops.
1965 if (!TheLoop->isInnermost()) {
1966 assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1967
1968 if (!canVectorizeOuterLoop()) {
1969 reportVectorizationFailure("Unsupported outer loop",
1970 "UnsupportedOuterLoop", ORE, TheLoop);
1971 // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1972 // outer loops.
1973 return false;
1974 }
1975
1976 LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1977 return Result;
1978 }
1979
1980 assert(TheLoop->isInnermost() && "Inner loop expected.");
1981 // Check if we can if-convert non-single-bb loops.
1982 unsigned NumBlocks = TheLoop->getNumBlocks();
1983 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1984 LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1985 if (DoExtraAnalysis)
1986 Result = false;
1987 else
1988 return false;
1989 }
1990
1991 // Check if we can vectorize the instructions and CFG in this loop.
1992 if (!canVectorizeInstrs()) {
1993 LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1994 if (DoExtraAnalysis)
1995 Result = false;
1996 else
1997 return false;
1998 }
1999
2000 if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount()) &&
2001 !isVectorizableEarlyExitLoop()) {
2002 assert(UncountableExitType == UncountableExitTrait::None &&
2003 "Must be false without vectorizable early-exit loop");
2004 if (TheLoop->getExitingBlock())
2005 reportVectorizationFailure("Cannot vectorize uncountable loop",
2006 "UnsupportedUncountableLoop", ORE, TheLoop);
2007 if (DoExtraAnalysis)
2008 Result = false;
2009 else
2010 return false;
2011 }
2012
2013 // Go over each instruction and look at memory deps.
2014 if (!canVectorizeMemory()) {
2015 LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2016 if (DoExtraAnalysis)
2017 Result = false;
2018 else
2019 return false;
2020 }
2021
2022 // TODO: Remove this restriction, should be straightforward to support.
2023 if (UncountableExitType != UncountableExitTrait::None &&
2024 !LAI->getStoresToInvariantAddresses().empty()) {
2025 LLVM_DEBUG(dbgs() << "LV: Cannot vectorize early exit loops with stores to "
2026 "loop-invariant addresses\n");
2027 reportVectorizationFailure("Cannot vectorize early exit loops with stores "
2028 "to loop-invariant addresses",
2029 "LoopInvariantStoresInEELoop", ORE, TheLoop);
2030 return false;
2031 }
2032
2033 if (Result) {
2034 LLVM_DEBUG(dbgs() << "LV: Loop passed LoopVectorizationLegality checks"
2035 << (LAI->getRuntimePointerChecking()->Need
2036 ? " (with a runtime bound check)"
2037 : "")
2038 << "!\n");
2039 }
2040
2041 // Okay! We've done all the tests. If any have failed, return false. Otherwise
2042 // we can vectorize, and at this point we don't have any other mem analysis
2043 // which may limit our maximum vectorization factor, so just return true with
2044 // no restrictions.
2045 return Result;
2046}
2047
2049 // The only loops we can vectorize without a scalar epilogue, are loops with
2050 // a bottom-test and a single exiting block. We'd have to handle the fact
2051 // that not every instruction executes on the last iteration. This will
2052 // require a lane mask which varies through the vector loop body. (TODO)
2053 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
2054 LLVM_DEBUG(
2055 dbgs()
2056 << "LV: Cannot fold tail by masking. Requires a singe latch exit\n");
2057 return false;
2058 }
2059
2060 // TODO: Support tail folding with uncountable exits.
2062 LLVM_DEBUG(dbgs() << "LV: Cannot tail fold by masking. Loop contains an "
2063 "uncountable early exit.\n");
2064 return false;
2065 }
2066
2067 LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
2068
2069 // The list of pointers that we can safely read and write to remains empty.
2070 SmallPtrSet<Value *, 8> SafePointers;
2071
2072 // Check all blocks for predication, including those that ordinarily do not
2073 // need predication such as the header block.
2075 for (BasicBlock *BB : TheLoop->blocks()) {
2076 if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp)) {
2077 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking.\n");
2078 return false;
2079 }
2080 }
2081
2082 LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
2083
2084 return true;
2085}
2086
2088 // The list of pointers that we can safely read and write to remains empty.
2089 SmallPtrSet<Value *, 8> SafePointers;
2090
2091 // Mark all blocks for predication, including those that ordinarily do not
2092 // need predication such as the header block, and collect instructions needing
2093 // predication in TailFoldedMaskedOp.
2094 for (BasicBlock *BB : TheLoop->blocks()) {
2095 [[maybe_unused]] bool R =
2096 blockCanBePredicated(BB, SafePointers, TailFoldedMaskedOp);
2097 assert(R && "Must be able to predicate block when tail-folding.");
2098 }
2099}
2100
2101} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define DEBUG_TYPE
Hexagon Common GEP
#define LV_NAME
static cl::opt< bool > HintsAllowReordering("hints-allow-reordering", cl::init(true), cl::Hidden, cl::desc("Allow enabling loop hints to reorder " "FP operations during vectorization."))
static const unsigned MaxInterleaveFactor
Maximum vectorization interleave count.
static cl::opt< bool > AllowStridedPointerIVs("lv-strided-pointer-ivs", cl::init(false), cl::Hidden, cl::desc("Enable recognition of non-constant strided " "pointer induction variables."))
static cl::opt< LoopVectorizeHints::ScalableForceKind > ForceScalableVectorization("scalable-vectorization", cl::init(LoopVectorizeHints::SK_Unspecified), cl::Hidden, cl::desc("Control whether the compiler can use scalable vectors to " "vectorize a loop"), cl::values(clEnumValN(LoopVectorizeHints::SK_FixedWidthOnly, "off", "Scalable vectorization is disabled."), clEnumValN(LoopVectorizeHints::SK_PreferScalable, "preferred", "Scalable vectorization is available and favored when the " "cost is inconclusive."), clEnumValN(LoopVectorizeHints::SK_PreferScalable, "on", "Scalable vectorization is available and favored when the " "cost is inconclusive."), clEnumValN(LoopVectorizeHints::SK_AlwaysScalable, "always", "Scalable vectorization is available and always favored when " "feasible")))
static cl::opt< bool > EnableHistogramVectorization("enable-histogram-loop-vectorization", cl::init(false), cl::Hidden, cl::desc("Enables autovectorization of some loops containing histograms"))
static cl::opt< bool > EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, cl::desc("Enable if-conversion during vectorization."))
This file defines the LoopVectorizationLegality class.
This file provides a LoopVectorizationPlanner 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
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
const SmallVectorImpl< MachineOperand > & Cond
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
virt reg Virtual Register Rewriter
@ NoAlias
The two locations do not alias at all.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
This class represents a function call, abstracting a target machine's calling convention.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:308
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
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 bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, ArrayRef< const SCEVPredicate * > NoWrapPreds={}, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
Instruction * getExactFPMathInst()
Returns floating-point induction operator that does not allow reassociation (transforming the inducti...
Class to represent integer types.
An instruction for reading from memory.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
static LLVM_ABI bool blockNeedsPredication(const BasicBlock *BB, const Loop *TheLoop, const DominatorTree *DT)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
iterator_range< block_iterator > blocks() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
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.
LLVM_ABI void collectUnitStridePredicates() const
Add unit stride predicates for memory accesses to PSE, if runtime checks are allowed and an inner loo...
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.
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.
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.
LLVM_ABI bool isFixedOrderRecurrence(const PHINode *Phi) const
Returns True if Phi is a fixed-order recurrence in this loop.
LLVM_ABI bool isInductionPhi(const Value *V) const
Returns True if V is a Phi node of an induction variable in this loop.
LLVM_ABI Instruction * findCountableComparisonInCombinedCondition(Value *Cond) const
If Cond is a combined exit condition featuring uncountable and countable comparisons,...
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.
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,...
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...
@ 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 allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
LLVM_ABI bool allowReordering() const
When enabling loop hints are provided we allow the vectorizer to change the order of operations that ...
LLVM_ABI void emitRemarkWithHints() const
Dumps all the hint information.
LLVM_ABI void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
LLVM_ABI LoopVectorizeHints(const Loop *L, bool InterleaveOnlyWhenForced, OptimizationRemarkEmitter &ORE, const TargetTransformInfo *TTI=nullptr)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition LoopInfo.cpp:559
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
A single uniqued string.
Definition Metadata.h:733
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:615
Checks memory dependences among accesses to the same underlying object to determine whether there vec...
const SmallVectorImpl< Dependence > * getDependences() const
Returns the memory dependences.
Root of the metadata hierarchy.
Definition Metadata.h:64
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
bool allowExtraAnalysis(StringRef PassName) const
Whether we allow for extra compile-time budget to perform more analysis to produce fewer false positi...
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
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.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Instruction * getExactFPMathInst() const
Returns 1st non-reassociative FP instruction in the PHI node's use-chain.
static LLVM_ABI bool isFixedOrderRecurrence(PHINode *Phi, Loop *TheLoop, DominatorTree *DT)
Returns true if Phi is a fixed-order recurrence.
bool hasExactFPMath() const
Returns true if the recurrence has floating-point math that requires precise (ordered) operations.
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
RecurKind getRecurrenceKind() const
bool isOrdered() const
Expose an ordered FP reduction to the instance users.
StoreInst * IntermediateStore
Reductions may store temporary or final result to an invariant address.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visit(const SCEV *S)
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
The main scalar evolution driver.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI bool isLoopUniform(const SCEV *S, const Loop *L)
Returns true if the given SCEV is loop-uniform with respect to the specified loop L.
LLVM_ABI const SCEV * getCouldNotCompute()
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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...
reference emplace_back(ArgTypes &&... Args)
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.
Value * getPointerOperand()
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.
void getWidestVF(StringRef ScalarF, ElementCount &FixedVF, ElementCount &ScalableVF) const
Returns the largest vectorization factor used in the list of vector functions.
bool isFunctionVectorizable(StringRef F, const ElementCount &VF) const
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
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:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Value * getOperand(unsigned i) const
Definition User.h:207
static bool hasMaskedVariant(const CallInst &CI, std::optional< ElementCount > VF=std::nullopt)
Definition VectorUtils.h:87
static SmallVector< VFInfo, 8 > getMappings(const CallInst &CI)
Retrieve all the VFInfo instances associated to the CallInst CI.
Definition VectorUtils.h:76
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isZero() const
Definition TypeSize.h:153
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
TwoOps_match< ValueOpTy, PointerOpTy, Instruction::Store > m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp)
Matches StoreInst.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
CmpClass_match< LHS, RHS, CmpInst, true > m_c_Cmp(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
match_combine_or< match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > >, OpTy > m_ZExtOrSExtOrSelf(const OpTy &Op)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
bool match(const SCEV *S, const Pattern &P)
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:707
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
bool isSimple(Instruction *I)
Definition SLPUtils.cpp:812
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
static bool canWidenTypes(Instruction &I, bool AllowStructCalls, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Returns true if the types produced and stored by I can be widened, otherwise reports a vectorization ...
static bool matchCombinedExitCondition(Value *Cond, Instruction *&CountableCond, Value *&Ptr, Instruction *&Load, Value *&Other, ScalarEvolution &SE, Loop *TheLoop)
Matches a combined exit condition consisting of an uncountable condition and a countable condition,...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:452
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DominatorTree &DT, const SymbolicStrideMap &StridesMap=SymbolicStrideMap(), bool ShouldCheckWrap=true, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
If the pointer has a constant stride return it in units of the access type size.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
DenseMap< Value *, const SCEVUnknown * > SymbolicStrideMap
Maps a pointer to its symbolic (non-constant) stride.
static IntegerType * getWiderInductionTy(const DataLayout &DL, Type *Ty0, Type *Ty1)
static IntegerType * getInductionIntegerTy(const DataLayout &DL, Type *Ty)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool hasDisableAllTransformsHint(const Loop *L)
Look for the loop attribute that disables all transformation heuristic.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
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
static bool storeToSameAddress(ScalarEvolution *SE, StoreInst *A, StoreInst *B)
Returns true if A and B have same pointer operands or same SCEVs addresses.
@ Other
Any other memory.
Definition ModRef.h:68
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
TargetTransformInfo TTI
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static bool canVectorizeSwiftErrorUses(Instruction &I, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Returns true if I does not use a swifterror value, otherwise reports a vectorization failure for TheL...
LLVM_ABI bool isReadOnlyLoop(Loop *L, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, SmallVectorImpl< LoadInst * > &NonDereferenceableAndAlignedLoads, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns true if the loop contains read-only memory accesses and doesn't throw.
Definition Loads.cpp:954
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
static bool matchUncountableExitCondition(Value *Cond, Value *&Ptr, Instruction *&Load, Value *&Other)
Matches an exit condition formed by comparing a value loaded from memory with another term.
static bool findHistogram(LoadInst *LI, StoreInst *HSt, Loop *TheLoop, const PredicatedScalarEvolution &PSE, SmallVectorImpl< HistogramInfo > &Histograms)
Find histogram operations that match high-level code in loops:
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI)
Checks if a function is scalarizable according to the TLI, in the sense that it should be vectorized ...
static bool matchCountableExitCondition(Value *Cond, ScalarEvolution &SE, Loop *TheLoop)
Matches an exit condition formed by comparing the current value of an affine add recurrence in the gi...
LLVM_ABI bool isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC=nullptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return true if we can prove that the given load (which is assumed to be within the specified loop) wo...
Definition Loads.cpp:304
static bool canWidenResultType(const Instruction &I, bool AllowStructCalls)
Returns true if the type produced by I can be widened.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Dependece between memory access instructions.
Instruction * getDestination(const MemoryDepChecker &DepChecker) const
Return the destination instruction of the dependence.
Instruction * getSource(const MemoryDepChecker &DepChecker) const
Return the source instruction of the dependence.
static LLVM_ABI VectorizationSafetyStatus isSafeForVectorization(DepType Type)
Dependence types that don't prevent vectorization.
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class.
Collection of parameters shared beetween the Loop Vectorizer and the Loop Access Analysis.
static LLVM_ABI const unsigned MaxVectorWidth
Maximum SIMD width.
static LLVM_ABI bool isInterleaveForced()
True if force-vector-interleave was specified by the user.
static LLVM_ABI unsigned VectorizationInterleave
Interleave factor as overridden by the user.
static LLVM_ABI ElementCount VectorizationFactor
VF as overridden by the user.