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