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]] = UpdateOp(buckets[indices[i]], Val);
1041/// \endcode
1042/// Where UpdateOp can be add, sub, uadd.sat, umax, or umin.
1043///
1044/// It matches a pattern starting from \p HSt, which Stores to the 'buckets'
1045/// array the computed histogram. It uses an update instruction to update all
1046/// counts, storing them using a loop-variant index Load from the 'indices'
1047/// input array.
1048///
1049/// On successful matches it updates the STATISTIC 'HistogramsDetected',
1050/// regardless of hardware support. When there is support, it additionally
1051/// stores the UpdateOp/Load pairs in \p HistogramCounts, as well the pointers
1052/// used to update histogram in \p HistogramPtrs.
1053static bool findHistogram(LoadInst *LI, StoreInst *HSt, Loop *TheLoop,
1054 const PredicatedScalarEvolution &PSE,
1055 SmallVectorImpl<HistogramInfo> &Histograms) {
1056
1057 // Store value must come from an update operation (binary op or intrinsic).
1058 Instruction *HPtrInstr = nullptr;
1059 Instruction *HUpdateOp = nullptr;
1060 if (!match(HSt, m_Store(m_Instruction(HUpdateOp), m_Instruction(HPtrInstr))))
1061 return false;
1062
1063 // The update operation must modify the bucket value by a loop invariant
1064 // amount. Supported operations: add, sub, uadd.sat, umax, umin.
1065 // FIXME: We assume the loop invariant term is on the RHS.
1066 // Fine for an immediate/constant, but maybe not a generic value?
1067 Value *HIncVal = nullptr;
1068 HistogramUpdateKind UpdateKind;
1069 auto Bucket = m_Load(m_Specific(HPtrInstr));
1070 if (match(HUpdateOp, m_Add(Bucket, m_Value(HIncVal))))
1071 UpdateKind = HistogramUpdateKind::Add;
1072 else if (match(HUpdateOp, m_Sub(Bucket, m_Value(HIncVal))))
1073 UpdateKind = HistogramUpdateKind::Sub;
1074 else if (match(HUpdateOp,
1075 m_Intrinsic<Intrinsic::uadd_sat>(Bucket, m_Value(HIncVal))))
1076 UpdateKind = HistogramUpdateKind::UAddSat;
1077 else if (match(HUpdateOp, m_UMax(Bucket, m_Value(HIncVal))))
1078 UpdateKind = HistogramUpdateKind::UMax;
1079 else if (match(HUpdateOp, m_UMin(Bucket, m_Value(HIncVal))))
1080 UpdateKind = HistogramUpdateKind::UMin;
1081 else
1082 return false;
1083
1084 // Make sure the increment value is loop invariant.
1085 if (!TheLoop->isLoopInvariant(HIncVal))
1086 return false;
1087
1088 // The address to store is calculated through a GEP Instruction.
1090 if (!GEP)
1091 return false;
1092
1093 // Restrict address calculation to constant indices except for the last term.
1094 Value *HIdx = nullptr;
1095 for (Value *Index : GEP->indices()) {
1096 if (HIdx)
1097 return false;
1098 if (!isa<ConstantInt>(Index))
1099 HIdx = Index;
1100 }
1101
1102 if (!HIdx)
1103 return false;
1104
1105 // Check that the index is calculated by loading from another array. Ignore
1106 // any extensions.
1107 // FIXME: Support indices from other sources than a linear load from memory?
1108 // We're currently trying to match an operation looping over an array
1109 // of indices, but there could be additional levels of indirection
1110 // in place, or possibly some additional calculation to form the index
1111 // from the loaded data.
1112 Value *VPtrVal;
1113 if (!match(HIdx, m_ZExtOrSExtOrSelf(m_Load(m_Value(VPtrVal)))))
1114 return false;
1115
1116 // Make sure the index address varies in this loop, not an outer loop.
1117 const auto *AR = dyn_cast<SCEVAddRecExpr>(PSE.getSE()->getSCEV(VPtrVal));
1118 if (!AR || AR->getLoop() != TheLoop)
1119 return false;
1120
1121 // Ensure we'll have the same mask by checking that all parts of the histogram
1122 // (gather load, update, scatter store) are in the same block.
1123 LoadInst *IndexedLoad = cast<LoadInst>(HUpdateOp->getOperand(0));
1124 BasicBlock *LdBB = IndexedLoad->getParent();
1125 if (LdBB != HUpdateOp->getParent() || LdBB != HSt->getParent())
1126 return false;
1127
1128 // The bucket value and its update must not be used outside the histogram.
1129 if (!IndexedLoad->hasOneUse() || !HUpdateOp->hasOneUse())
1130 return false;
1131
1132 LLVM_DEBUG(dbgs() << "LV: Found histogram for: " << *HSt << "\n");
1133
1134 // Store the operations that make up the histogram.
1135 Histograms.emplace_back(IndexedLoad, HUpdateOp, HSt, UpdateKind);
1136 return true;
1137}
1138
1139bool LoopVectorizationLegality::canVectorizeIndirectUnsafeDependences() {
1140 // For now, we only support an IndirectUnsafe dependency that calculates
1141 // a histogram
1143 return false;
1144
1145 // Find a single IndirectUnsafe dependency.
1146 const MemoryDepChecker::Dependence *IUDep = nullptr;
1147 const MemoryDepChecker &DepChecker = LAI->getDepChecker();
1148 const auto *Deps = DepChecker.getDependences();
1149 // If there were too many dependences, LAA abandons recording them. We can't
1150 // proceed safely if we don't know what the dependences are.
1151 if (!Deps)
1152 return false;
1153
1154 for (const MemoryDepChecker::Dependence &Dep : *Deps) {
1155 // Ignore dependencies that are either known to be safe or can be
1156 // checked at runtime.
1159 continue;
1160
1161 // We're only interested in IndirectUnsafe dependencies here, where the
1162 // address might come from a load from memory. We also only want to handle
1163 // one such dependency, at least for now.
1164 if (Dep.Type != MemoryDepChecker::Dependence::IndirectUnsafe || IUDep)
1165 return false;
1166
1167 IUDep = &Dep;
1168 }
1169 if (!IUDep)
1170 return false;
1171
1172 // For now only normal loads and stores are supported.
1173 LoadInst *LI = dyn_cast<LoadInst>(IUDep->getSource(DepChecker));
1174 StoreInst *SI = dyn_cast<StoreInst>(IUDep->getDestination(DepChecker));
1175
1176 if (!LI || !SI)
1177 return false;
1178
1179 LLVM_DEBUG(dbgs() << "LV: Checking for a histogram on: " << *SI << "\n");
1180 return findHistogram(LI, SI, TheLoop, LAI->getPSE(), Histograms);
1181}
1182
1183bool LoopVectorizationLegality::canVectorizeMemory() {
1184 LAI = &LAIs.getInfo(*TheLoop);
1185 const OptimizationRemarkAnalysis *LAR = LAI->getReport();
1186 if (LAR) {
1187 ORE->emit([&]() {
1188 return OptimizationRemarkAnalysis(LV_NAME, "loop not vectorized: ", *LAR);
1189 });
1190 }
1191
1192 if (!LAI->canVectorizeMemory()) {
1195 "Cannot vectorize unsafe dependencies in uncountable exit loop with "
1196 "side effects",
1197 "CantVectorizeUnsafeDependencyForEELoopWithSideEffects", ORE,
1198 TheLoop);
1199 return false;
1200 }
1201
1202 return canVectorizeIndirectUnsafeDependences();
1203 }
1204
1205 if (LAI->hasLoadStoreDependenceInvolvingLoopInvariantAddress()) {
1206 reportVectorizationFailure("We don't allow storing to uniform addresses",
1207 "write to a loop invariant address could not "
1208 "be vectorized",
1209 "CantVectorizeStoreToLoopInvariantAddress", ORE,
1210 TheLoop);
1211 return false;
1212 }
1213
1214 // We can vectorize stores to invariant address when final reduction value is
1215 // guaranteed to be stored at the end of the loop. Also, if decision to
1216 // vectorize loop is made, runtime checks are added so as to make sure that
1217 // invariant address won't alias with any other objects.
1218 if (!LAI->getStoresToInvariantAddresses().empty()) {
1219 // For each invariant address, check if last stored value is unconditional
1220 // and the address is not calculated inside the loop.
1221 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1223 continue;
1224
1225 if (blockNeedsPredication(SI->getParent())) {
1227 "We don't allow storing to uniform addresses",
1228 "write of conditional recurring variant value to a loop "
1229 "invariant address could not be vectorized",
1230 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1231 return false;
1232 }
1233
1234 // Invariant address should be defined outside of loop. LICM pass usually
1235 // makes sure it happens, but in rare cases it does not, we do not want
1236 // to overcomplicate vectorization to support this case.
1237 if (Instruction *Ptr = dyn_cast<Instruction>(SI->getPointerOperand())) {
1238 if (TheLoop->contains(Ptr)) {
1240 "Invariant address is calculated inside the loop",
1241 "write to a loop invariant address could not "
1242 "be vectorized",
1243 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1244 return false;
1245 }
1246 }
1247 }
1248
1249 if (LAI->hasStoreStoreDependenceInvolvingLoopInvariantAddress()) {
1250 // For each invariant address, check its last stored value is the result
1251 // of one of our reductions.
1252 //
1253 // We do not check if dependence with loads exists because that is already
1254 // checked via hasLoadStoreDependenceInvolvingLoopInvariantAddress.
1255 ScalarEvolution *SE = PSE.getSE();
1256 SmallVector<StoreInst *, 4> UnhandledStores;
1257 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1259 // Earlier stores to this address are effectively deadcode.
1260 // With opaque pointers it is possible for one pointer to be used with
1261 // different sizes of stored values:
1262 // store i32 0, ptr %x
1263 // store i8 0, ptr %x
1264 // The latest store doesn't complitely overwrite the first one in the
1265 // example. That is why we have to make sure that types of stored
1266 // values are same.
1267 // TODO: Check that bitwidth of unhandled store is smaller then the
1268 // one that overwrites it and add a test.
1269 erase_if(UnhandledStores, [SE, SI](StoreInst *I) {
1270 return storeToSameAddress(SE, SI, I) &&
1271 I->getValueOperand()->getType() ==
1272 SI->getValueOperand()->getType();
1273 });
1274 continue;
1275 }
1276 UnhandledStores.push_back(SI);
1277 }
1278
1279 bool IsOK = UnhandledStores.empty();
1280 // TODO: we should also validate against InvariantMemSets.
1281 if (!IsOK) {
1283 "We don't allow storing to uniform addresses",
1284 "write to a loop invariant address could not "
1285 "be vectorized",
1286 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1287 return false;
1288 }
1289 }
1290 }
1291
1292 PSE.addPredicate(LAI->getPSE().getPredicate());
1293 return true;
1294}
1295
1297 bool EnableStrictReductions) {
1298
1299 // First check if there is any ExactFP math or if we allow reassociations
1300 if (!Requirements->getExactFPInst() || Hints->allowReordering())
1301 return true;
1302
1303 // If the above is false, we have ExactFPMath & do not allow reordering.
1304 // If the EnableStrictReductions flag is set, first check if we have any
1305 // Exact FP induction vars, which we cannot vectorize.
1306 if (!EnableStrictReductions ||
1307 any_of(getInductionVars().values(),
1308 [](const InductionDescriptor &IndDesc) -> bool {
1309 return IndDesc.getExactFPMathInst();
1310 }))
1311 return false;
1312
1313 // We can now only vectorize if all reductions with Exact FP math also
1314 // have the isOrdered flag set, which indicates that we can move the
1315 // reduction operations in-loop.
1316 return (all_of(getReductionVars().values(),
1317 [](const RecurrenceDescriptor &RdxDesc) -> bool {
1318 return !RdxDesc.hasExactFPMath() || RdxDesc.isOrdered();
1319 }));
1320}
1321
1323 return any_of(getReductionVars().values(),
1324 [&](const RecurrenceDescriptor &RdxDesc) -> bool {
1325 return RdxDesc.IntermediateStore == SI;
1326 });
1327}
1328
1330 return any_of(getReductionVars().values(),
1331 [&](const RecurrenceDescriptor &RdxDesc) -> bool {
1332 if (!RdxDesc.IntermediateStore)
1333 return false;
1334
1335 ScalarEvolution *SE = PSE.getSE();
1336 Value *InvariantAddress =
1338 return V == InvariantAddress ||
1339 SE->getSCEV(V) == SE->getSCEV(InvariantAddress);
1340 });
1341}
1342
1344 Value *In0 = const_cast<Value *>(V);
1346 if (!PN)
1347 return false;
1348
1349 return Inductions.count(PN);
1350}
1351
1353 const PHINode *Phi) const {
1354 return FixedOrderRecurrences.count(Phi);
1355}
1356
1358 const BasicBlock *BB) const {
1359 BasicBlock *Latch = TheLoop->getLoopLatch();
1360
1361 // Without a latch, we cannot properly answer blockNeedsPredication,
1362 // return early.
1363 if (!Latch) {
1364 assert(ORE->allowExtraAnalysis(DEBUG_TYPE) &&
1365 !canVectorizeLoopCFG(TheLoop, /*UseVPlanNativePath=*/false) &&
1366 "Loop shape should have been rejected by earlier checks");
1367 return false;
1368 }
1369
1370 // When vectorizing early exits, create predicates for the latch block only.
1371 // For a single early exit, it must be a direct predecessor of the latch.
1372 // For multiple early exits, they form a chain where each exiting block
1373 // dominates all subsequent blocks up to the latch.
1375 return BB == Latch;
1376 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1377}
1378
1379bool LoopVectorizationLegality::blockCanBePredicated(
1380 BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs,
1381 SmallPtrSetImpl<const Instruction *> &MaskedOp) const {
1382 for (Instruction &I : *BB) {
1383 // We can predicate blocks with calls to assume, as long as we drop them in
1384 // case we flatten the CFG via predication.
1386 MaskedOp.insert(&I);
1387 continue;
1388 }
1389
1390 // Do not let llvm.experimental.noalias.scope.decl block the vectorization.
1391 // TODO: there might be cases that it should block the vectorization. Let's
1392 // ignore those for now.
1394 continue;
1395
1396 // We can allow masked calls if there's at least one vector variant, even
1397 // if we end up scalarizing due to the cost model calculations.
1398 // TODO: Allow other calls if they have appropriate attributes... readonly
1399 // and argmemonly?
1400 if (CallInst *CI = dyn_cast<CallInst>(&I))
1402 MaskedOp.insert(CI);
1403 continue;
1404 }
1405
1406 // Loads are handled via masking (or speculated if safe to do so.)
1407 if (auto *LI = dyn_cast<LoadInst>(&I)) {
1408 if (!SafePtrs.count(LI->getPointerOperand()))
1409 MaskedOp.insert(LI);
1410 continue;
1411 }
1412
1413 // Predicated store requires some form of masking:
1414 // 1) masked store HW instruction,
1415 // 2) emulation via load-blend-store (only if safe and legal to do so,
1416 // be aware on the race conditions), or
1417 // 3) element-by-element predicate check and scalar store.
1418 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1419 MaskedOp.insert(SI);
1420 continue;
1421 }
1422
1423 if (I.mayReadFromMemory() || I.mayWriteToMemory() || I.mayThrow())
1424 return false;
1425 }
1426
1427 return true;
1428}
1429
1430bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1431 if (!EnableIfConversion) {
1432 reportVectorizationFailure("If-conversion is disabled",
1433 "IfConversionDisabled", ORE, TheLoop);
1434 return false;
1435 }
1436
1437 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1438
1439 // A list of pointers which are known to be dereferenceable within scope of
1440 // the loop body for each iteration of the loop which executes. That is,
1441 // the memory pointed to can be dereferenced (with the access size implied by
1442 // the value's type) unconditionally within the loop header without
1443 // introducing a new fault.
1444 SmallPtrSet<Value *, 8> SafePointers;
1445
1446 // Collect safe addresses.
1447 for (BasicBlock *BB : TheLoop->blocks()) {
1448 if (!blockNeedsPredication(BB)) {
1449 for (Instruction &I : *BB)
1450 if (auto *Ptr = getLoadStorePointerOperand(&I))
1451 SafePointers.insert(Ptr);
1452 continue;
1453 }
1454
1455 // For a block which requires predication, a address may be safe to access
1456 // in the loop w/o predication if we can prove dereferenceability facts
1457 // sufficient to ensure it'll never fault within the loop. For the moment,
1458 // we restrict this to loads; stores are more complicated due to
1459 // concurrency restrictions.
1460 ScalarEvolution &SE = *PSE.getSE();
1462 for (Instruction &I : *BB) {
1463 LoadInst *LI = dyn_cast<LoadInst>(&I);
1464
1465 // Make sure we can execute all computations feeding into Ptr in the loop
1466 // w/o triggering UB and that none of the out-of-loop operands are poison.
1467 // We do not need to check if operations inside the loop can produce
1468 // poison due to flags (e.g. due to an inbounds GEP going out of bounds),
1469 // because flags will be dropped when executing them unconditionally.
1470 // TODO: Results could be improved by considering poison-propagation
1471 // properties of visited ops.
1472 auto CanSpeculatePointerOp = [this](Value *Ptr) {
1473 SmallVector<Value *> Worklist = {Ptr};
1474 SmallPtrSet<Value *, 4> Visited;
1475 while (!Worklist.empty()) {
1476 Value *CurrV = Worklist.pop_back_val();
1477 if (!Visited.insert(CurrV).second)
1478 continue;
1479
1480 auto *CurrI = dyn_cast<Instruction>(CurrV);
1481 if (!CurrI || !TheLoop->contains(CurrI)) {
1482 BasicBlock *LoopPred = TheLoop->getLoopPredecessor();
1483 Instruction *CtxI = LoopPred ? LoopPred->getTerminator() : nullptr;
1484 assert((CtxI || ORE->allowExtraAnalysis(DEBUG_TYPE)) &&
1485 "Loop with multiple predecessors should have been rejected "
1486 "early.");
1487 // If operands from outside the loop may be poison then Ptr may also
1488 // be poison.
1489 if (!isGuaranteedNotToBePoison(CurrV, AC, CtxI, DT))
1490 return false;
1491 continue;
1492 }
1493
1494 // A loaded value may be poison, independent of any flags.
1495 if (isa<LoadInst>(CurrI) && !isGuaranteedNotToBePoison(CurrV, AC))
1496 return false;
1497
1498 // For other ops, assume poison can only be introduced via flags,
1499 // which can be dropped.
1500 if (!isa<PHINode>(CurrI) && !isSafeToSpeculativelyExecute(CurrI))
1501 return false;
1502 append_range(Worklist, CurrI->operands());
1503 }
1504 return true;
1505 };
1506 // Pass the Predicates pointer to isDereferenceableAndAlignedInLoop so
1507 // that it will consider loops that need guarding by SCEV checks. The
1508 // vectoriser will generate these checks if we decide to vectorise.
1509 if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) &&
1510 CanSpeculatePointerOp(LI->getPointerOperand()) &&
1511 isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT, AC,
1512 &Predicates))
1513 SafePointers.insert(LI->getPointerOperand());
1514 Predicates.clear();
1515 }
1516 }
1517
1518 // Collect the blocks that need predication.
1519 for (BasicBlock *BB : TheLoop->blocks()) {
1520 // We support only branches and switch statements as terminators inside the
1521 // loop.
1522 if (isa<SwitchInst>(BB->getTerminator())) {
1523 if (TheLoop->isLoopExiting(BB)) {
1524 reportVectorizationFailure("Loop contains an unsupported switch",
1525 "LoopContainsUnsupportedSwitch", ORE,
1526 TheLoop, BB->getTerminator());
1527 return false;
1528 }
1529 } else if (!isa<UncondBrInst, CondBrInst>(BB->getTerminator())) {
1530 reportVectorizationFailure("Loop contains an unsupported terminator",
1531 "LoopContainsUnsupportedTerminator", ORE,
1532 TheLoop, BB->getTerminator());
1533 return false;
1534 }
1535
1536 // We must be able to predicate all blocks that need to be predicated.
1537 if (blockNeedsPredication(BB) &&
1538 !blockCanBePredicated(BB, SafePointers, ConditionallyExecutedOps)) {
1540 "Control flow cannot be substituted for a select", "NoCFGForSelect",
1541 ORE, TheLoop, BB->getTerminator());
1542 return false;
1543 }
1544 }
1545
1546 // We can if-convert this loop.
1547 return true;
1548}
1549
1550// Helper function to canVectorizeLoopNestCFG.
1551bool LoopVectorizationLegality::canVectorizeLoopCFG(
1552 Loop *Lp, bool UseVPlanNativePath) const {
1553 assert((UseVPlanNativePath || Lp->isInnermost()) &&
1554 "VPlan-native path is not enabled.");
1555
1556 // TODO: ORE should be improved to show more accurate information when an
1557 // outer loop can't be vectorized because a nested loop is not understood or
1558 // legal. Something like: "outer_loop_location: loop not vectorized:
1559 // (inner_loop_location) loop control flow is not understood by vectorizer".
1560
1561 // Store the result and return it at the end instead of exiting early, in case
1562 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1563 bool Result = true;
1564 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1565
1566 // We must have a loop in canonical form. Loops with indirectbr in them cannot
1567 // be canonicalized.
1568 if (!Lp->getLoopPreheader()) {
1570 "Loop doesn't have a legal pre-header",
1571 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1572 ORE, TheLoop);
1573 if (DoExtraAnalysis)
1574 Result = false;
1575 else
1576 return false;
1577 }
1578
1579 // We must have a single backedge.
1580 if (Lp->getNumBackEdges() != 1) {
1582 "The loop must have a single backedge",
1583 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1584 ORE, TheLoop);
1585 if (DoExtraAnalysis)
1586 Result = false;
1587 else
1588 return false;
1589 }
1590
1591 // The latch must be terminated by a branch.
1592 BasicBlock *Latch = Lp->getLoopLatch();
1593 if (Latch && !isa<UncondBrInst, CondBrInst>(Latch->getTerminator())) {
1595 "The loop latch terminator is not a UncondBrInst/CondBrInst",
1596 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1597 ORE, TheLoop);
1598 if (DoExtraAnalysis)
1599 Result = false;
1600 else
1601 return false;
1602 }
1603
1604 return Result;
1605}
1606
1607bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1608 Loop *Lp, bool UseVPlanNativePath) {
1609 // Store the result and return it at the end instead of exiting early, in case
1610 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1611 bool Result = true;
1612 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1613 if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1614 if (DoExtraAnalysis)
1615 Result = false;
1616 else
1617 return false;
1618 }
1619
1620 // Recursively check whether the loop control flow of nested loops is
1621 // understood.
1622 for (Loop *SubLp : *Lp)
1623 if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1624 if (DoExtraAnalysis)
1625 Result = false;
1626 else
1627 return false;
1628 }
1629
1630 return Result;
1631}
1632
1633/// Matches an exit condition formed by comparing a value loaded from memory
1634/// with another term. Binds the pointer, load, and the other comparison term.
1636 Instruction *&Load, Value *&Other) {
1637 return match(Cond, m_OneUse(m_c_Cmp(
1639 m_Value(Other))));
1640}
1641
1642/// Matches an exit condition formed by comparing the current value of an
1643/// affine add recurrence in the given loop with a stride of 1 against a
1644/// loop-invariant term.
1646 Loop *TheLoop) {
1647 using namespace llvm::SCEVPatternMatch;
1648 Value *IVUpdate, *Limit;
1649 return match(Cond, m_c_ICmp(m_Value(IVUpdate, m_Add(m_Value(), m_Value())),
1650 m_Value(Limit))) &&
1651 TheLoop->isLoopInvariant(Limit) &&
1652 SCEVPatternMatch::match(SE.getSCEV(IVUpdate),
1654 m_SpecificLoop(TheLoop)));
1655}
1656
1657/// Matches a combined exit condition consisting of an uncountable condition and
1658/// a countable condition, combined by an or. Binds the pointer, load, the
1659/// second comparison term for the uncountable condition, and the comparison for
1660/// the countable condition.
1661static bool matchCombinedExitCondition(Value *Cond, Instruction *&CountableCond,
1662 Value *&Ptr, Instruction *&Load,
1664 Loop *TheLoop) {
1665 Value *L, *R;
1666 if (!match(Cond, m_OneUse(m_LogicalOr(m_Value(L), m_Value(R)))))
1667 return false;
1668
1669 if (matchCountableExitCondition(L, SE, TheLoop) &&
1671 CountableCond = cast<Instruction>(L);
1672 return true;
1673 }
1674
1675 if (matchCountableExitCondition(R, SE, TheLoop) &&
1677 CountableCond = cast<Instruction>(R);
1678 return true;
1679 }
1680
1681 return false;
1682}
1683
1686 Value *Cond) const {
1687 Value *Ptr, *Other;
1688 Instruction *Load, *CountableCmp;
1689 if (matchCombinedExitCondition(Cond, CountableCmp, Ptr, Load, Other,
1690 *PSE.getSE(), TheLoop))
1691 return CountableCmp;
1692
1693 return nullptr;
1694}
1695
1696bool LoopVectorizationLegality::isVectorizableEarlyExitLoop() {
1697 BasicBlock *LatchBB = TheLoop->getLoopLatch();
1698 if (!LatchBB) {
1699 reportVectorizationFailure("Loop does not have a latch",
1700 "Cannot vectorize early exit loop",
1701 "NoLatchEarlyExit", ORE, TheLoop);
1702 return false;
1703 }
1704
1705 if (Reductions.size() || FixedOrderRecurrences.size()) {
1707 "Found reductions or recurrences in early-exit loop",
1708 "Cannot vectorize early exit loop with reductions or recurrences",
1709 "RecurrencesInEarlyExitLoop", ORE, TheLoop);
1710 return false;
1711 }
1712
1713 SmallVector<BasicBlock *, 8> ExitingBlocks;
1714 TheLoop->getExitingBlocks(ExitingBlocks);
1715
1716 // Keep a record of all the exiting blocks.
1718 SmallVector<BasicBlock *> UncountableExitingBlocks;
1719 for (BasicBlock *BB : ExitingBlocks) {
1720 const SCEV *EC =
1721 PSE.getSE()->getPredicatedExitCount(TheLoop, BB, &Predicates);
1722 if (isa<SCEVCouldNotCompute>(EC)) {
1723 if (size(successors(BB)) != 2) {
1725 "Early exiting block does not have exactly two successors",
1726 "Incorrect number of successors from early exiting block",
1727 "EarlyExitTooManySuccessors", ORE, TheLoop);
1728 return false;
1729 }
1730
1731 UncountableExitingBlocks.push_back(BB);
1732 } else
1733 CountableExitingBlocks.push_back(BB);
1734 }
1735 // We can safely ignore the predicates here because when vectorizing the loop
1736 // the PredicatatedScalarEvolution class will keep track of all predicates
1737 // for each exiting block anyway. This happens when calling
1738 // PSE.getSymbolicMaxBackedgeTakenCount() below.
1739 Predicates.clear();
1740
1741 if (UncountableExitingBlocks.empty()) {
1742 LLVM_DEBUG(dbgs() << "LV: Could not find any uncountable exits");
1743 return false;
1744 }
1745
1746 // The latch block must have a countable exit.
1747 if (isa<SCEVCouldNotCompute>(PSE.getSE()->getPredicatedExitCount(
1748 TheLoop, LatchBB, &Predicates, ScalarEvolution::SymbolicMaximum))) {
1750 "Cannot determine symbolic max exit count for latch block",
1751 "Cannot vectorize early exit loop",
1752 "UnknownLatchExitCountEarlyExitLoop", ORE, TheLoop);
1753 return false;
1754 }
1755
1756 if (!is_contained(CountableExitingBlocks, LatchBB)) {
1757 // If not a separate counted exit in the latch, then check for a combined
1758 // countable and uncountable exit.
1759 auto *Br = dyn_cast<CondBrInst>(LatchBB->getTerminator());
1760 if (!Br ||
1761 !findCountableComparisonInCombinedCondition(Br->getCondition())) {
1763 "Latch block does not have a countable exit condition",
1764 "NoCountableConditionInLatchBlock", ORE, TheLoop);
1765 return false;
1766 }
1767 }
1768
1769 // Check to see if there are instructions that could potentially generate
1770 // exceptions or have side-effects.
1771 auto IsSafeOperation = [](Instruction *I) -> bool {
1772 switch (I->getOpcode()) {
1773 case Instruction::Load:
1774 case Instruction::Store:
1775 case Instruction::PHI:
1776 case Instruction::UncondBr:
1777 case Instruction::CondBr:
1778 // These are checked separately.
1779 return true;
1780 default:
1782 }
1783 };
1784
1785 bool HasSideEffects = false;
1786 for (auto *BB : TheLoop->blocks())
1787 for (auto &I : *BB) {
1788 if (I.mayWriteToMemory()) {
1789 if (isa<StoreInst>(&I) && cast<StoreInst>(&I)->isSimple()) {
1790 HasSideEffects = true;
1791 continue;
1792 }
1793
1794 // We don't support complex writes to memory.
1796 "Complex writes to memory unsupported in early exit loops",
1797 "Cannot vectorize early exit loop with complex writes to memory",
1798 "WritesInEarlyExitLoop", ORE, TheLoop);
1799 return false;
1800 }
1801
1802 if (!IsSafeOperation(&I)) {
1803 reportVectorizationFailure("Early exit loop contains operations that "
1804 "cannot be speculatively executed",
1805 "UnsafeOperationsEarlyExitLoop", ORE,
1806 TheLoop);
1807 return false;
1808 }
1809 }
1810
1811 SmallVector<LoadInst *, 4> NonDerefLoads;
1812 // TODO: Handle loops that may fault.
1813 if (!HasSideEffects) {
1814 // Read-only loop.
1815 Predicates.clear();
1816 if (!isReadOnlyLoop(TheLoop, PSE.getSE(), DT, AC, NonDerefLoads,
1817 &Predicates)) {
1819 "Loop may fault", "Cannot vectorize non-read-only early exit loop",
1820 "NonReadOnlyEarlyExitLoop", ORE, TheLoop);
1821 return false;
1822 }
1823 } else {
1824 // Check all uncountable exiting blocks for movable loads.
1825 for (BasicBlock *ExitingBB : UncountableExitingBlocks) {
1826 if (!canUncountableExitConditionLoadBeMoved(ExitingBB))
1827 return false;
1828 }
1829 }
1830
1831 // Check non-dereferenceable loads if any.
1832 for (LoadInst *LI : NonDerefLoads) {
1833 // Only support unit-stride access for now.
1834 int Stride = isConsecutivePtr(LI->getType(), LI->getPointerOperand());
1835 if (Stride != 1) {
1837 "Loop contains potentially faulting strided load",
1838 "Cannot vectorize early exit loop with "
1839 "strided fault-only-first load",
1840 "EarlyExitLoopWithStridedFaultOnlyFirstLoad", ORE, TheLoop);
1841 return false;
1842 }
1843 }
1844
1845 // We're only handling combined exit conditions via masking at present, which
1846 // is used for loops with side effects.
1847 // TODO: Support readonly loops with combined exit conditions.
1848 // TODO: Decouple style from the presence of side effects.
1849 if (!llvm::is_contained(CountableExitingBlocks, LatchBB) && !HasSideEffects)
1850 return false;
1851
1852 [[maybe_unused]] const SCEV *SymbolicMaxBTC =
1853 PSE.getSymbolicMaxBackedgeTakenCount();
1854 // Since we have an exact exit count for the latch and the early exit
1855 // dominates the latch, then this should guarantee a computed SCEV value.
1856 assert(!isa<SCEVCouldNotCompute>(SymbolicMaxBTC) &&
1857 "Failed to get symbolic expression for backedge taken count");
1858 LLVM_DEBUG(dbgs() << "LV: Found an early exit loop with symbolic max "
1859 "backedge taken count: "
1860 << *SymbolicMaxBTC << '\n');
1861 UncountableExitType = HasSideEffects ? UncountableExitTrait::ReadWrite
1863 return true;
1864}
1865
1866bool LoopVectorizationLegality::canUncountableExitConditionLoadBeMoved(
1867 BasicBlock *ExitingBlock) {
1868 // Try to find a load in the critical path for the uncountable exit condition.
1869 // This is currently matching about the simplest form we can, expecting
1870 // only one in-loop load, the result of which is directly compared against
1871 // a loop-invariant value.
1872 // FIXME: We're insisting on a single use for now, because otherwise we will
1873 // need to make PHI nodes for other users. That can be done once the initial
1874 // transform code lands.
1875 auto *Br = cast<CondBrInst>(ExitingBlock->getTerminator());
1876
1877 using namespace llvm::PatternMatch;
1878 Value *Ptr, *Other;
1879 Instruction *L, *CountableCond;
1880 // We want to match either an uncounted condition (loaded value compared
1881 // against a loop invariant value) or the combination (via logical or) of
1882 // an uncounted condition with a counted condition (integer comparison of
1883 // an induction variable for which we can identify an add recurrence within
1884 // this loop).
1885 if (!matchUncountableExitCondition(Br->getCondition(), Ptr, L, Other) &&
1886 !matchCombinedExitCondition(Br->getCondition(), CountableCond, Ptr, L,
1887 Other, *PSE.getSE(), TheLoop)) {
1889 "Early exit loop with store but no supported condition load",
1890 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1891 return false;
1892 }
1893
1894 // Bail if the uncountable exit load is compared against a non-invariant
1895 // value.
1896 // TODO: Remove this restriction.
1897 if (!TheLoop->isLoopInvariant(Other)) {
1899 "Early exit loop with store but no supported condition load",
1900 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1901 return false;
1902 }
1903
1904 // Make sure that the load address is not loop invariant; we want an
1905 // address calculation that we can rotate to the next vector iteration.
1906 const auto *AR = dyn_cast<SCEVAddRecExpr>(PSE.getSE()->getSCEV(Ptr));
1907 if (!AR || AR->getLoop() != TheLoop || !AR->isAffine()) {
1909 "Uncountable exit condition depends on load with an address that is "
1910 "not an add recurrence in the loop",
1911 "EarlyExitLoadInvariantAddress", ORE, TheLoop);
1912 return false;
1913 }
1914
1915 ICFLoopSafetyInfo SafetyInfo(TheLoop);
1916 LoadInst *Load = cast<LoadInst>(L);
1917 // We need to know that load will be executed before we can hoist a
1918 // copy out to run just before the first iteration.
1919 if (!SafetyInfo.isGuaranteedToExecute(*Load, DT)) {
1921 "Load for uncountable exit not guaranteed to execute",
1922 "ConditionalUncountableExitLoad", ORE, TheLoop);
1923 return false;
1924 }
1925
1926 // Prohibit any potential aliasing with any instruction in the loop which
1927 // might store to memory.
1928 // FIXME: Relax this constraint where possible.
1929 for (auto *BB : TheLoop->blocks()) {
1930 for (auto &I : *BB) {
1931 if (&I == Load)
1932 continue;
1933
1934 if (I.mayReadOrWriteMemory()) {
1935 // We need to mask all other memory ops.
1936 ConditionallyExecutedOps.insert(&I);
1937 if (isa<LoadInst>(&I))
1938 continue;
1939 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1940 AliasResult AR = AA->alias(Ptr, SI->getPointerOperand());
1941 if (AR == AliasResult::NoAlias)
1942 continue;
1943 }
1944
1946 "Cannot determine whether critical uncountable exit load address "
1947 "does not alias with a memory write",
1948 "CantVectorizeAliasWithCriticalUncountableExitLoad", ORE, TheLoop);
1949 return false;
1950 }
1951 }
1952 }
1953
1954 return true;
1955}
1956
1957bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1958 // Store the result and return it at the end instead of exiting early, in case
1959 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1960 bool Result = true;
1961
1962 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1963 // Check whether the loop-related control flow in the loop nest is expected by
1964 // vectorizer.
1965 if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1966 if (DoExtraAnalysis) {
1967 LLVM_DEBUG(dbgs() << "LV: legality check failed: loop nest");
1968 Result = false;
1969 } else {
1970 return false;
1971 }
1972 }
1973
1974 // We need to have a loop header.
1975 LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1976 << '\n');
1977
1978 // Specific checks for outer loops. We skip the remaining legal checks at this
1979 // point because they don't support outer loops.
1980 if (!TheLoop->isInnermost()) {
1981 assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1982
1983 if (!canVectorizeOuterLoop()) {
1984 reportVectorizationFailure("Unsupported outer loop",
1985 "UnsupportedOuterLoop", ORE, TheLoop);
1986 // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1987 // outer loops.
1988 return false;
1989 }
1990
1991 LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1992 return Result;
1993 }
1994
1995 assert(TheLoop->isInnermost() && "Inner loop expected.");
1996 // Check if we can if-convert non-single-bb loops.
1997 unsigned NumBlocks = TheLoop->getNumBlocks();
1998 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1999 LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2000 if (DoExtraAnalysis)
2001 Result = false;
2002 else
2003 return false;
2004 }
2005
2006 // Check if we can vectorize the instructions and CFG in this loop.
2007 if (!canVectorizeInstrs()) {
2008 LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2009 if (DoExtraAnalysis)
2010 Result = false;
2011 else
2012 return false;
2013 }
2014
2015 if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount()) &&
2016 !isVectorizableEarlyExitLoop()) {
2017 assert(UncountableExitType == UncountableExitTrait::None &&
2018 "Must be false without vectorizable early-exit loop");
2019 if (TheLoop->getExitingBlock())
2020 reportVectorizationFailure("Cannot vectorize uncountable loop",
2021 "UnsupportedUncountableLoop", ORE, TheLoop);
2022 if (DoExtraAnalysis)
2023 Result = false;
2024 else
2025 return false;
2026 }
2027
2028 // Go over each instruction and look at memory deps.
2029 if (!canVectorizeMemory()) {
2030 LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2031 if (DoExtraAnalysis)
2032 Result = false;
2033 else
2034 return false;
2035 }
2036
2037 // TODO: Remove this restriction, should be straightforward to support.
2038 if (UncountableExitType != UncountableExitTrait::None &&
2039 !LAI->getStoresToInvariantAddresses().empty()) {
2040 LLVM_DEBUG(dbgs() << "LV: Cannot vectorize early exit loops with stores to "
2041 "loop-invariant addresses\n");
2042 reportVectorizationFailure("Cannot vectorize early exit loops with stores "
2043 "to loop-invariant addresses",
2044 "LoopInvariantStoresInEELoop", ORE, TheLoop);
2045 return false;
2046 }
2047
2048 if (Result) {
2049 LLVM_DEBUG(dbgs() << "LV: Loop passed LoopVectorizationLegality checks"
2050 << (LAI->getRuntimePointerChecking()->Need
2051 ? " (with a runtime bound check)"
2052 : "")
2053 << "!\n");
2054 }
2055
2056 // Okay! We've done all the tests. If any have failed, return false. Otherwise
2057 // we can vectorize, and at this point we don't have any other mem analysis
2058 // which may limit our maximum vectorization factor, so just return true with
2059 // no restrictions.
2060 return Result;
2061}
2062
2064 // The only loops we can vectorize without a scalar epilogue, are loops with
2065 // a bottom-test and a single exiting block. We'd have to handle the fact
2066 // that not every instruction executes on the last iteration. This will
2067 // require a lane mask which varies through the vector loop body. (TODO)
2068 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
2069 LLVM_DEBUG(
2070 dbgs()
2071 << "LV: Cannot fold tail by masking. Requires a singe latch exit\n");
2072 return false;
2073 }
2074
2075 // TODO: Support tail folding with uncountable exits.
2077 LLVM_DEBUG(dbgs() << "LV: Cannot tail fold by masking. Loop contains an "
2078 "uncountable early exit.\n");
2079 return false;
2080 }
2081
2082 LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
2083
2084 // The list of pointers that we can safely read and write to remains empty.
2085 SmallPtrSet<Value *, 8> SafePointers;
2086
2087 // Check all blocks for predication, including those that ordinarily do not
2088 // need predication such as the header block.
2090 for (BasicBlock *BB : TheLoop->blocks()) {
2091 if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp)) {
2092 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking.\n");
2093 return false;
2094 }
2095 }
2096
2097 LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
2098
2099 return true;
2100}
2101
2103 // The list of pointers that we can safely read and write to remains empty.
2104 SmallPtrSet<Value *, 8> SafePointers;
2105
2106 // Mark all blocks for predication, including those that ordinarily do not
2107 // need predication such as the header block, and collect instructions needing
2108 // predication in TailFoldedMaskedOp.
2109 for (BasicBlock *BB : TheLoop->blocks()) {
2110 [[maybe_unused]] bool R =
2111 blockCanBePredicated(BB, SafePointers, TailFoldedMaskedOp);
2112 assert(R && "Must be able to predicate block when tail-folding.");
2113 }
2114}
2115
2116} // 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.
Instruction * getExactFPMathInst() const
Returns floating-point induction operator that does not allow reassociation (transforming the inducti...
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.
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.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
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_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
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:831
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,...
HistogramUpdateKind
The kind of update operation performed on the buckets of a histogram, i.e.
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:956
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.