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 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.
851 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
852 PrimaryInduction = nullptr;
853
854 return Result;
855}
856
857bool LoopVectorizationLegality::canVectorizeInstr(Instruction &I) {
858 BasicBlock *BB = I.getParent();
859 BasicBlock *Header = TheLoop->getHeader();
860
861 if (auto *Phi = dyn_cast<PHINode>(&I)) {
862 Type *PhiTy = Phi->getType();
863 // Check that this PHI type is allowed.
864 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
865 !PhiTy->isPointerTy()) {
867 "Found a non-int non-pointer PHI",
868 "loop control flow is not understood by vectorizer",
869 "CFGNotUnderstood", ORE, TheLoop);
870 return false;
871 }
872
873 // If this PHINode is not in the header block, then we know that we
874 // can convert it to select during if-conversion. No need to check if
875 // the PHIs in this block are induction or reduction variables.
876 if (BB != Header) {
877 // Non-header phi nodes that have outside uses can be vectorized. Unsafe
878 // cyclic dependencies with header phis are identified during legalization
879 // for reduction, induction and fixed order recurrences.
880 return true;
881 }
882
883 // We only allow if-converted PHIs with exactly two incoming values.
884 if (Phi->getNumIncomingValues() != 2) {
886 "Found an invalid PHI",
887 "loop control flow is not understood by vectorizer",
888 "CFGNotUnderstood", ORE, TheLoop, Phi);
889 return false;
890 }
891
892 RecurrenceDescriptor RedDes;
893 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC, DT,
894 PSE.getSE())) {
895 Requirements->addExactFPMathInst(RedDes.getExactFPMathInst());
896 Reductions[Phi] = std::move(RedDes);
899 RedDes.getRecurrenceKind())) &&
900 "Only min/max recurrences are allowed to have multiple uses "
901 "currently");
902 return true;
903 }
904
905 InductionDescriptor ID;
906 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID) &&
908 addInductionPhi(Phi, ID);
909 Requirements->addExactFPMathInst(ID.getExactFPMathInst());
910 return true;
911 }
912
913 ConditionalInductionDescriptor CondID;
914 if (Opts.lv_compressing_patterns &&
916 Phi, TheLoop, CondID, *PSE.getSE())) {
917 return addConditionalInduction(Phi, CondID);
918 }
919
920 if (RecurrenceDescriptor::isFixedOrderRecurrence(Phi, TheLoop, DT)) {
921 FixedOrderRecurrences.insert(Phi);
922 return true;
923 }
924
925 // As a last resort, coerce the PHI to a AddRec expression
926 // and re-try classifying it a an induction PHI.
927 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true) &&
929 addInductionPhi(Phi, ID);
930 return true;
931 }
932
934 reportVectorizationFailure("Found a disallowed pointer induction",
935 "pointer induction with a non-constant step "
936 "could not be vectorized",
937 "StridedPointerInduction", ORE, TheLoop, Phi);
938 return false;
939 }
940
941 reportVectorizationFailure("Found an unidentified PHI",
942 "value that could not be identified as "
943 "reduction is used outside the loop",
944 "NonReductionValueUsedOutsideLoop", ORE, TheLoop,
945 Phi);
946 return false;
947 } // end of PHI handling
948
949 if (!canVectorizeSwiftErrorUses(I, ORE, TheLoop) ||
950 !canVectorizeOperandBundles(I, ORE, TheLoop))
951 return false;
952
953 // We handle calls that:
954 // * Have a mapping to an IR intrinsic.
955 // * Have a vector version available.
956 auto *CI = dyn_cast<CallInst>(&I);
957
958 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
959 !(CI->getCalledFunction() && TLI &&
960 (!VFDatabase::getMappings(*CI).empty() || isTLIScalarize(*TLI, *CI)))) {
961 // If the call is a recognized math libary call, it is likely that
962 // we can vectorize it given loosened floating-point constraints.
963 bool IsMathLibCall =
964 TLI && CI->getCalledFunction() && CI->getType()->isFloatingPointTy() &&
965 TLI->hasOptimizedCodeGen(
966 TLI->getLibFunc(CI->getCalledFunction()->getName()));
967
968 if (IsMathLibCall) {
969 // TODO: Ideally, we should not use clang-specific language here,
970 // but it's hard to provide meaningful yet generic advice.
971 // Also, should this be guarded by allowExtraAnalysis() and/or be part
972 // of the returned info from isFunctionVectorizable()?
974 "Found a non-intrinsic callsite",
975 "library call cannot be vectorized. "
976 "Try compiling with -fno-math-errno, -ffast-math, "
977 "or similar flags",
978 "CantVectorizeLibcall", ORE, TheLoop, CI);
979 } else {
980 reportVectorizationFailure("Found a non-intrinsic callsite",
981 "call instruction cannot be vectorized",
982 "CantVectorizeLibcall", ORE, TheLoop, CI);
983 }
984 return false;
985 }
986
987 // Some intrinsics have scalar arguments and should be same in order for
988 // them to be vectorized (i.e. loop invariant).
989 if (CI) {
990 auto *SE = PSE.getSE();
991 Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
992 for (unsigned Idx = 0; Idx < CI->arg_size(); ++Idx)
993 if (isVectorIntrinsicWithScalarOpAtArg(IntrinID, Idx, TTI)) {
994 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(Idx)), TheLoop)) {
996 "Found unvectorizable intrinsic",
997 "intrinsic instruction cannot be vectorized",
998 "CantVectorizeIntrinsic", ORE, TheLoop, CI);
999 return false;
1000 }
1001 }
1002 }
1003
1004 // If we found a vectorized variant of a function, note that so LV can
1005 // make better decisions about maximum VF.
1006 if (CI && !VFDatabase::getMappings(*CI).empty())
1007 VecCallVariantsFound = true;
1008
1009 // Check that the instruction return and stored types are vectorizable.
1010 if (!canWidenTypes(I, /*AllowStructCalls=*/true, ORE, TheLoop))
1011 return false;
1012
1013 if (auto *ST = dyn_cast<StoreInst>(&I)) {
1014 // For nontemporal stores, check that a nontemporal vector version is
1015 // supported on the target.
1016 if (ST->getMetadata(LLVMContext::MD_nontemporal)) {
1017 // Arbitrarily try a vector of 2 elements.
1018 auto *VecTy =
1019 FixedVectorType::get(ST->getValueOperand()->getType(), /*NumElts=*/2);
1020 assert(VecTy && "did not find vectorized version of stored type");
1021 if (!TTI->isLegalNTStore(VecTy, ST->getAlign())) {
1023 "nontemporal store instruction cannot be vectorized",
1024 "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
1025 return false;
1026 }
1027 }
1028
1029 } else if (auto *LD = dyn_cast<LoadInst>(&I)) {
1030 if (LD->getMetadata(LLVMContext::MD_nontemporal)) {
1031 // For nontemporal loads, check that a nontemporal vector version is
1032 // supported on the target (arbitrarily try a vector of 2 elements).
1033 auto *VecTy = FixedVectorType::get(I.getType(), /*NumElts=*/2);
1034 assert(VecTy && "did not find vectorized version of load type");
1035 if (!TTI->isLegalNTLoad(VecTy, LD->getAlign())) {
1037 "nontemporal load instruction cannot be vectorized",
1038 "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
1039 return false;
1040 }
1041 }
1042
1043 // FP instructions can allow unsafe algebra, thus vectorizable by
1044 // non-IEEE-754 compliant SIMD units.
1045 // This applies to floating-point math operations and calls, not memory
1046 // operations, shuffles, or casts, as they don't change precision or
1047 // semantics.
1048 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
1049 !I.isFast()) {
1050 LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
1051 Hints->setPotentiallyUnsafe();
1052 }
1053
1054 return true;
1055}
1056
1057/// Find histogram operations that match high-level code in loops:
1058/// \code
1059/// buckets[indices[i]] = UpdateOp(buckets[indices[i]], Val);
1060/// \endcode
1061/// Where UpdateOp can be add, sub, uadd.sat, umax, or umin.
1062///
1063/// It matches a pattern starting from \p HSt, which Stores to the 'buckets'
1064/// array the computed histogram. It uses an update instruction to update all
1065/// counts, storing them using a loop-variant index Load from the 'indices'
1066/// input array.
1067///
1068/// On successful matches it updates the STATISTIC 'HistogramsDetected',
1069/// regardless of hardware support. When there is support, it additionally
1070/// stores the UpdateOp/Load pairs in \p HistogramCounts, as well the pointers
1071/// used to update histogram in \p HistogramPtrs.
1072static bool findHistogram(LoadInst *LI, StoreInst *HSt, Loop *TheLoop,
1073 const PredicatedScalarEvolution &PSE,
1074 SmallVectorImpl<HistogramInfo> &Histograms) {
1075
1076 // Store value must come from an update operation (binary op or intrinsic).
1077 Instruction *HPtrInstr = nullptr;
1078 Instruction *HUpdateOp = nullptr;
1079 if (!match(HSt, m_Store(m_Instruction(HUpdateOp), m_Instruction(HPtrInstr))))
1080 return false;
1081
1082 // The update operation must modify the bucket value by a loop invariant
1083 // amount. Supported operations: add, sub, uadd.sat, umax, umin.
1084 // FIXME: We assume the loop invariant term is on the RHS.
1085 // Fine for an immediate/constant, but maybe not a generic value?
1086 Value *HIncVal = nullptr;
1087 HistogramUpdateKind UpdateKind;
1088 auto Bucket = m_Load(m_Specific(HPtrInstr));
1089 if (match(HUpdateOp, m_Add(Bucket, m_Value(HIncVal))))
1090 UpdateKind = HistogramUpdateKind::Add;
1091 else if (match(HUpdateOp, m_Sub(Bucket, m_Value(HIncVal))))
1092 UpdateKind = HistogramUpdateKind::Sub;
1093 else if (match(HUpdateOp,
1094 m_Intrinsic<Intrinsic::uadd_sat>(Bucket, m_Value(HIncVal))))
1095 UpdateKind = HistogramUpdateKind::UAddSat;
1096 else if (match(HUpdateOp, m_UMax(Bucket, m_Value(HIncVal))))
1097 UpdateKind = HistogramUpdateKind::UMax;
1098 else if (match(HUpdateOp, m_UMin(Bucket, m_Value(HIncVal))))
1099 UpdateKind = HistogramUpdateKind::UMin;
1100 else
1101 return false;
1102
1103 // Make sure the increment value is loop invariant.
1104 if (!TheLoop->isLoopInvariant(HIncVal))
1105 return false;
1106
1107 // The address to store is calculated through a GEP Instruction.
1109 if (!GEP)
1110 return false;
1111
1112 // Restrict address calculation to constant indices except for the last term.
1113 Value *HIdx = nullptr;
1114 for (Value *Index : GEP->indices()) {
1115 if (HIdx)
1116 return false;
1117 if (!isa<ConstantInt>(Index))
1118 HIdx = Index;
1119 }
1120
1121 if (!HIdx)
1122 return false;
1123
1124 // Check that the index is calculated by loading from another array. Ignore
1125 // any extensions.
1126 // FIXME: Support indices from other sources than a linear load from memory?
1127 // We're currently trying to match an operation looping over an array
1128 // of indices, but there could be additional levels of indirection
1129 // in place, or possibly some additional calculation to form the index
1130 // from the loaded data.
1131 Value *VPtrVal;
1132 if (!match(HIdx, m_ZExtOrSExtOrSelf(m_Load(m_Value(VPtrVal)))))
1133 return false;
1134
1135 // Make sure the index address varies in this loop, not an outer loop.
1136 const auto *AR = dyn_cast<SCEVAddRecExpr>(PSE.getSE()->getSCEV(VPtrVal));
1137 if (!AR || AR->getLoop() != TheLoop)
1138 return false;
1139
1140 // Ensure we'll have the same mask by checking that all parts of the histogram
1141 // (gather load, update, scatter store) are in the same block.
1142 LoadInst *IndexedLoad = cast<LoadInst>(HUpdateOp->getOperand(0));
1143 BasicBlock *LdBB = IndexedLoad->getParent();
1144 if (LdBB != HUpdateOp->getParent() || LdBB != HSt->getParent())
1145 return false;
1146
1147 // The bucket value and its update must not be used outside the histogram.
1148 if (!IndexedLoad->hasOneUse() || !HUpdateOp->hasOneUse())
1149 return false;
1150
1151 LLVM_DEBUG(dbgs() << "LV: Found histogram for: " << *HSt << "\n");
1152
1153 // Store the operations that make up the histogram.
1154 Histograms.emplace_back(IndexedLoad, HUpdateOp, HSt, UpdateKind);
1155 return true;
1156}
1157
1158bool LoopVectorizationLegality::canVectorizeIndirectUnsafeDependences() {
1159 // For now, we only support an IndirectUnsafe dependency that calculates
1160 // a histogram
1161 if (!Opts.enable_histogram_loop_vectorization)
1162 return false;
1163
1164 // Find a single IndirectUnsafe dependency.
1165 const MemoryDepChecker::Dependence *IUDep = nullptr;
1166 const MemoryDepChecker &DepChecker = LAI->getDepChecker();
1167 const auto *Deps = DepChecker.getDependences();
1168 // If there were too many dependences, LAA abandons recording them. We can't
1169 // proceed safely if we don't know what the dependences are.
1170 if (!Deps)
1171 return false;
1172
1173 for (const MemoryDepChecker::Dependence &Dep : *Deps) {
1174 // Ignore dependencies that are either known to be safe or can be
1175 // checked at runtime.
1178 continue;
1179
1180 // We're only interested in IndirectUnsafe dependencies here, where the
1181 // address might come from a load from memory. We also only want to handle
1182 // one such dependency, at least for now.
1183 if (Dep.Type != MemoryDepChecker::Dependence::IndirectUnsafe || IUDep)
1184 return false;
1185
1186 IUDep = &Dep;
1187 }
1188 if (!IUDep)
1189 return false;
1190
1191 // For now only normal loads and stores are supported.
1192 LoadInst *LI = dyn_cast<LoadInst>(IUDep->getSource(DepChecker));
1193 StoreInst *SI = dyn_cast<StoreInst>(IUDep->getDestination(DepChecker));
1194
1195 if (!LI || !SI)
1196 return false;
1197
1198 LLVM_DEBUG(dbgs() << "LV: Checking for a histogram on: " << *SI << "\n");
1199 return findHistogram(LI, SI, TheLoop, LAI->getPSE(), Histograms);
1200}
1201
1202bool LoopVectorizationLegality::canVectorizeMemory() {
1203 LAI = &LAIs.getInfo(*TheLoop);
1204 const OptimizationRemarkAnalysis *LAR = LAI->getReport();
1205 if (LAR) {
1206 ORE->emit([&]() {
1207 return OptimizationRemarkAnalysis(LV_NAME, "loop not vectorized: ", *LAR);
1208 });
1209 }
1210
1211 // We can vectorize stores to invariant address when final reduction value is
1212 // guaranteed to be stored at the end of the loop. Also, if decision to
1213 // vectorize loop is made, runtime checks are added so as to make sure that
1214 // invariant address won't alias with any other objects.
1215 if (!LAI->getStoresToInvariantAddresses().empty()) {
1216 // For each invariant address, check if last stored value is unconditional
1217 // and the address is not calculated inside the loop.
1218 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1220 continue;
1221
1222 if (blockNeedsPredication(SI->getParent())) {
1224 "We don't allow storing to uniform addresses",
1225 "write of conditional recurring variant value to a loop "
1226 "invariant address could not be vectorized",
1227 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1228 return false;
1229 }
1230
1231 // Invariant address should be defined outside of loop. LICM pass usually
1232 // makes sure it happens, but in rare cases it does not, we do not want
1233 // to overcomplicate vectorization to support this case.
1234 if (Instruction *Ptr = dyn_cast<Instruction>(SI->getPointerOperand())) {
1235 if (TheLoop->contains(Ptr)) {
1237 "Invariant address is calculated inside the loop",
1238 "write to a loop invariant address could not "
1239 "be vectorized",
1240 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1241 return false;
1242 }
1243 }
1244 }
1245
1246 if (LAI->hasStoreStoreDependenceInvolvingLoopInvariantAddress()) {
1247 // For each invariant address, check its last stored value is the result
1248 // of one of our reductions.
1249 //
1250 // We do not check if dependence with loads exists because that is already
1251 // checked via hasLoadStoreDependenceInvolvingLoopInvariantAddress.
1252 ScalarEvolution *SE = PSE.getSE();
1253 SmallVector<StoreInst *, 4> UnhandledStores;
1254 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1256 // Earlier stores to this address are effectively deadcode.
1257 // With opaque pointers it is possible for one pointer to be used with
1258 // different sizes of stored values:
1259 // store i32 0, ptr %x
1260 // store i8 0, ptr %x
1261 // The latest store doesn't complitely overwrite the first one in the
1262 // example. That is why we have to make sure that types of stored
1263 // values are same.
1264 // TODO: Check that bitwidth of unhandled store is smaller then the
1265 // one that overwrites it and add a test.
1266 erase_if(UnhandledStores, [SE, SI](StoreInst *I) {
1267 return storeToSameAddress(SE, SI, I) &&
1268 I->getValueOperand()->getType() ==
1269 SI->getValueOperand()->getType();
1270 });
1271 continue;
1272 }
1273 UnhandledStores.push_back(SI);
1274 }
1275
1276 bool IsOK = UnhandledStores.empty();
1277 // TODO: we should also validate against InvariantMemSets.
1278 if (!IsOK) {
1280 "We don't allow storing to uniform addresses",
1281 "write to a loop invariant address could not "
1282 "be vectorized",
1283 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1284 return false;
1285 }
1286 }
1287 }
1288
1289 if (!LAI->canVectorizeMemory()) {
1292 "Cannot vectorize unsafe dependencies in uncountable exit loop with "
1293 "side effects",
1294 "CantVectorizeUnsafeDependencyForEELoopWithSideEffects", ORE,
1295 TheLoop);
1296 return false;
1297 }
1298
1299 return canVectorizeIndirectUnsafeDependences();
1300 }
1301
1302 if (LAI->hasLoadStoreDependenceInvolvingLoopInvariantAddress()) {
1303 reportVectorizationFailure("We don't allow storing to uniform addresses",
1304 "write to a loop invariant address could not "
1305 "be vectorized",
1306 "CantVectorizeStoreToLoopInvariantAddress", ORE,
1307 TheLoop);
1308 return false;
1309 }
1310
1311 PSE.addPredicate(LAI->getPSE().getPredicate());
1312 return true;
1313}
1314
1316 bool EnableStrictReductions) {
1317
1318 // First check if there is any ExactFP math or if we allow reassociations
1319 if (!Requirements->getExactFPInst() || Hints->allowReordering())
1320 return true;
1321
1322 // If the above is false, we have ExactFPMath & do not allow reordering.
1323 // If the EnableStrictReductions flag is set, first check if we have any
1324 // Exact FP induction vars, which we cannot vectorize.
1325 if (!EnableStrictReductions ||
1326 any_of(getInductionVars().values(),
1327 [](const InductionDescriptor &IndDesc) -> bool {
1328 return IndDesc.getExactFPMathInst();
1329 }))
1330 return false;
1331
1332 // We can now only vectorize if all reductions with Exact FP math also
1333 // have the isOrdered flag set, which indicates that we can move the
1334 // reduction operations in-loop.
1335 return (all_of(getReductionVars().values(),
1336 [](const RecurrenceDescriptor &RdxDesc) -> bool {
1337 return !RdxDesc.hasExactFPMath() || RdxDesc.isOrdered();
1338 }));
1339}
1340
1342 return any_of(getReductionVars().values(),
1343 [&](const RecurrenceDescriptor &RdxDesc) -> bool {
1344 return RdxDesc.IntermediateStore == SI;
1345 });
1346}
1347
1349 return any_of(getReductionVars().values(),
1350 [&](const RecurrenceDescriptor &RdxDesc) -> bool {
1351 if (!RdxDesc.IntermediateStore)
1352 return false;
1353
1354 ScalarEvolution *SE = PSE.getSE();
1355 Value *InvariantAddress =
1357 return V == InvariantAddress ||
1358 SE->getSCEV(V) == SE->getSCEV(InvariantAddress);
1359 });
1360}
1361
1363 Value *In0 = const_cast<Value *>(V);
1365 if (!PN)
1366 return false;
1367
1368 return Inductions.count(PN);
1369}
1370
1372 const PHINode *Phi) const {
1373 return FixedOrderRecurrences.count(Phi);
1374}
1375
1377 const BasicBlock *BB) const {
1378 BasicBlock *Latch = TheLoop->getLoopLatch();
1379
1380 // Without a latch, we cannot properly answer blockNeedsPredication,
1381 // return early.
1382 if (!Latch) {
1383 assert(ORE->allowExtraAnalysis(DEBUG_TYPE) &&
1384 !canVectorizeLoopCFG(TheLoop, /*UseVPlanNativePath=*/false) &&
1385 "Loop shape should have been rejected by earlier checks");
1386 return false;
1387 }
1388
1389 // When vectorizing early exits, create predicates for the latch block only.
1390 // For a single early exit, it must be a direct predecessor of the latch.
1391 // For multiple early exits, they form a chain where each exiting block
1392 // dominates all subsequent blocks up to the latch.
1394 return BB == Latch;
1395 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1396}
1397
1398bool LoopVectorizationLegality::blockCanBePredicated(
1399 BasicBlock *BB, SafeAccessesTy &SafeAccesses,
1400 SmallPtrSetImpl<const Instruction *> &MaskedOp) const {
1401 for (Instruction &I : *BB) {
1402 // We can predicate blocks with calls to assume, as long as we drop them in
1403 // case we flatten the CFG via predication.
1405 MaskedOp.insert(&I);
1406 continue;
1407 }
1408
1409 // Do not let llvm.experimental.noalias.scope.decl block the vectorization.
1410 // TODO: there might be cases that it should block the vectorization. Let's
1411 // ignore those for now.
1413 continue;
1414
1415 // We can allow masked calls if there's at least one vector variant, even
1416 // if we end up scalarizing due to the cost model calculations.
1417 // TODO: Allow other calls if they have appropriate attributes... readonly
1418 // and argmemonly?
1419 if (CallInst *CI = dyn_cast<CallInst>(&I))
1421 MaskedOp.insert(CI);
1422 continue;
1423 }
1424
1425 // Loads are handled via masking (or speculated if safe to do so.)
1426 if (auto *LI = dyn_cast<LoadInst>(&I)) {
1427 auto It = SafeAccesses.find(LI->getPointerOperand());
1428 TypeSize Size = LI->getDataLayout().getTypeStoreSize(LI->getType());
1429 if (Size.isScalable() || It == SafeAccesses.end() ||
1430 It->second.MaxAlign < LI->getAlign() ||
1431 It->second.MaxSizeInBytes < Size.getFixedValue())
1432 MaskedOp.insert(LI);
1433 continue;
1434 }
1435
1436 // Predicated store requires some form of masking:
1437 // 1) masked store HW instruction,
1438 // 2) emulation via load-blend-store (only if safe and legal to do so,
1439 // be aware on the race conditions), or
1440 // 3) element-by-element predicate check and scalar store.
1441 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1442 MaskedOp.insert(SI);
1443 continue;
1444 }
1445
1446 if (I.mayReadFromMemory() || I.mayWriteToMemory() || I.mayThrow())
1447 return false;
1448 }
1449
1450 return true;
1451}
1452
1453bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1454 if (!Opts.enable_if_conversion) {
1455 reportVectorizationFailure("If-conversion is disabled",
1456 "IfConversionDisabled", ORE, TheLoop);
1457 return false;
1458 }
1459
1460 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1461
1462 // Record the maximum fixed access size and alignment known to be safe for
1463 // each pointer in every executed iteration. A conditional load can execute
1464 // unconditionally if its size and alignment do not exceed these bounds.
1465 // Scalable accesses do not establish either size or alignment.
1466 SafeAccessesTy SafeAccesses;
1467 auto RecordSafeAccess = [&SafeAccesses](Instruction &I) {
1469 if (!Ptr)
1470 return;
1471 TypeSize Size = I.getDataLayout().getTypeStoreSize(getLoadStoreType(&I));
1472 if (Size.isScalable())
1473 return;
1475 auto &Info = SafeAccesses[Ptr];
1476 Info.MaxAlign = std::max(Info.MaxAlign, Alignment);
1477 Info.MaxSizeInBytes = std::max(Info.MaxSizeInBytes, Size.getFixedValue());
1478 };
1479
1480 // Collect safe accesses.
1481 for (BasicBlock *BB : TheLoop->blocks()) {
1482 if (!blockNeedsPredication(BB)) {
1483 for (Instruction &I : *BB)
1484 RecordSafeAccess(I);
1485 continue;
1486 }
1487
1488 // For a block which requires predication, a address may be safe to access
1489 // in the loop w/o predication if we can prove dereferenceability facts
1490 // sufficient to ensure it'll never fault within the loop. For the moment,
1491 // we restrict this to loads; stores are more complicated due to
1492 // concurrency restrictions.
1493 ScalarEvolution &SE = *PSE.getSE();
1495 for (Instruction &I : *BB) {
1496 LoadInst *LI = dyn_cast<LoadInst>(&I);
1497
1498 // Make sure we can execute all computations feeding into Ptr in the loop
1499 // w/o triggering UB and that none of the out-of-loop operands are poison.
1500 // We do not need to check if operations inside the loop can produce
1501 // poison due to flags (e.g. due to an inbounds GEP going out of bounds),
1502 // because flags will be dropped when executing them unconditionally.
1503 // TODO: Results could be improved by considering poison-propagation
1504 // properties of visited ops.
1505 auto CanSpeculatePointerOp = [this](Value *Ptr) {
1506 SmallVector<Value *> Worklist = {Ptr};
1507 SmallPtrSet<Value *, 4> Visited;
1508 while (!Worklist.empty()) {
1509 Value *CurrV = Worklist.pop_back_val();
1510 if (!Visited.insert(CurrV).second)
1511 continue;
1512
1513 auto *CurrI = dyn_cast<Instruction>(CurrV);
1514 if (!CurrI || !TheLoop->contains(CurrI)) {
1515 BasicBlock *LoopPred = TheLoop->getLoopPredecessor();
1516 Instruction *CtxI = LoopPred ? LoopPred->getTerminator() : nullptr;
1517 assert((CtxI || ORE->allowExtraAnalysis(DEBUG_TYPE)) &&
1518 "Loop with multiple predecessors should have been rejected "
1519 "early.");
1520 // If operands from outside the loop may be poison then Ptr may also
1521 // be poison.
1522 if (!isGuaranteedNotToBePoison(CurrV, AC, CtxI, DT))
1523 return false;
1524 continue;
1525 }
1526
1527 // A loaded value may be poison, independent of any flags.
1528 if (isa<LoadInst>(CurrI) && !isGuaranteedNotToBePoison(CurrV, AC))
1529 return false;
1530
1531 // For other ops, assume poison can only be introduced via flags,
1532 // which can be dropped.
1533 if (!isa<PHINode>(CurrI) && !isSafeToSpeculativelyExecute(CurrI))
1534 return false;
1535 append_range(Worklist, CurrI->operands());
1536 }
1537 return true;
1538 };
1539 // Pass the Predicates pointer to isDereferenceableAndAlignedInLoop so
1540 // that it will consider loops that need guarding by SCEV checks. The
1541 // vectoriser will generate these checks if we decide to vectorise.
1542 if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) &&
1543 CanSpeculatePointerOp(LI->getPointerOperand()) &&
1544 isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT, AC,
1545 &Predicates))
1546 RecordSafeAccess(*LI);
1547 Predicates.clear();
1548 }
1549 }
1550
1551 // Collect the blocks that need predication.
1552 for (BasicBlock *BB : TheLoop->blocks()) {
1553 // We support only branches and switch statements as terminators inside the
1554 // loop.
1555 if (isa<SwitchInst>(BB->getTerminator())) {
1556 if (TheLoop->isLoopExiting(BB)) {
1557 reportVectorizationFailure("Loop contains an unsupported switch",
1558 "LoopContainsUnsupportedSwitch", ORE,
1559 TheLoop, BB->getTerminator());
1560 return false;
1561 }
1562 } else if (!isa<UncondBrInst, CondBrInst>(BB->getTerminator())) {
1563 reportVectorizationFailure("Loop contains an unsupported terminator",
1564 "LoopContainsUnsupportedTerminator", ORE,
1565 TheLoop, BB->getTerminator());
1566 return false;
1567 }
1568
1569 // We must be able to predicate all blocks that need to be predicated.
1570 if (blockNeedsPredication(BB) &&
1571 !blockCanBePredicated(BB, SafeAccesses, ConditionallyExecutedOps)) {
1573 "Control flow cannot be substituted for a select", "NoCFGForSelect",
1574 ORE, TheLoop, BB->getTerminator());
1575 return false;
1576 }
1577 }
1578
1579 // We can if-convert this loop.
1580 return true;
1581}
1582
1583// Helper function to canVectorizeLoopNestCFG.
1584bool LoopVectorizationLegality::canVectorizeLoopCFG(
1585 Loop *Lp, bool UseVPlanNativePath) const {
1586 assert((UseVPlanNativePath || Lp->isInnermost()) &&
1587 "VPlan-native path is not enabled.");
1588
1589 // TODO: ORE should be improved to show more accurate information when an
1590 // outer loop can't be vectorized because a nested loop is not understood or
1591 // legal. Something like: "outer_loop_location: loop not vectorized:
1592 // (inner_loop_location) loop control flow is not understood by vectorizer".
1593
1594 // Store the result and return it at the end instead of exiting early, in case
1595 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1596 bool Result = true;
1597 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1598
1599 // We must have a loop in canonical form. Loops with indirectbr in them cannot
1600 // be canonicalized. The preheader must also be terminated by an unconditional
1601 // branch, which gets replaced when creating the vector loop.
1602 BasicBlock *Preheader = Lp->getLoopPreheader();
1603 if (!Preheader || !isa<UncondBrInst>(Preheader->getTerminator())) {
1605 "Loop doesn't have a legal pre-header",
1606 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1607 ORE, TheLoop);
1608 if (DoExtraAnalysis)
1609 Result = false;
1610 else
1611 return false;
1612 }
1613
1614 // We must have a single backedge.
1615 if (Lp->getNumBackEdges() != 1) {
1617 "The loop must have a single backedge",
1618 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1619 ORE, TheLoop);
1620 if (DoExtraAnalysis)
1621 Result = false;
1622 else
1623 return false;
1624 }
1625
1626 // The latch must be terminated by a branch.
1627 BasicBlock *Latch = Lp->getLoopLatch();
1628 if (Latch && !isa<UncondBrInst, CondBrInst>(Latch->getTerminator())) {
1630 "The loop latch terminator is not a UncondBrInst/CondBrInst",
1631 "loop control flow is not understood by vectorizer", "CFGNotUnderstood",
1632 ORE, TheLoop);
1633 if (DoExtraAnalysis)
1634 Result = false;
1635 else
1636 return false;
1637 }
1638
1639 return Result;
1640}
1641
1642bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1643 Loop *Lp, bool UseVPlanNativePath) {
1644 // Store the result and return it at the end instead of exiting early, in case
1645 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1646 bool Result = true;
1647 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1648 if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1649 if (DoExtraAnalysis)
1650 Result = false;
1651 else
1652 return false;
1653 }
1654
1655 // Recursively check whether the loop control flow of nested loops is
1656 // understood.
1657 for (Loop *SubLp : *Lp)
1658 if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1659 if (DoExtraAnalysis)
1660 Result = false;
1661 else
1662 return false;
1663 }
1664
1665 return Result;
1666}
1667
1668/// Matches an exit condition formed by comparing a value loaded from memory
1669/// with another term. Binds the pointer, load, and the other comparison term.
1671 Instruction *&Load, Value *&Other) {
1672 return match(
1674}
1675
1676/// Matches an exit condition formed by comparing the current value of an
1677/// affine add recurrence in the given loop with a stride of 1 against a
1678/// loop-invariant term.
1680 Loop *TheLoop) {
1681 using namespace llvm::SCEVPatternMatch;
1682 Value *IVUpdate, *Limit;
1683 return match(Cond, m_c_ICmp(m_Value(IVUpdate, m_Add(m_Value(), m_Value())),
1684 m_Value(Limit))) &&
1685 TheLoop->isLoopInvariant(Limit) &&
1686 SCEVPatternMatch::match(SE.getSCEV(IVUpdate),
1688 m_SpecificLoop(TheLoop)));
1689}
1690
1691/// Matches a combined exit condition consisting of an uncountable condition and
1692/// a countable condition, combined by an or. Binds the pointer, load, the
1693/// second comparison term for the uncountable condition, and the comparison for
1694/// the countable condition.
1695static bool matchCombinedExitCondition(Value *Cond, Instruction *&CountableCond,
1696 Value *&Ptr, Instruction *&Load,
1698 Loop *TheLoop) {
1699 Value *L, *R;
1700 if (!match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1701 return false;
1702
1703 if (matchCountableExitCondition(L, SE, TheLoop) &&
1705 CountableCond = cast<Instruction>(L);
1706 return true;
1707 }
1708
1709 if (matchCountableExitCondition(R, SE, TheLoop) &&
1711 CountableCond = cast<Instruction>(R);
1712 return true;
1713 }
1714
1715 return false;
1716}
1717
1720 Value *Cond) const {
1721 Value *Ptr, *Other;
1722 Instruction *Load, *CountableCmp;
1723 if (matchCombinedExitCondition(Cond, CountableCmp, Ptr, Load, Other,
1724 *PSE.getSE(), TheLoop))
1725 return CountableCmp;
1726
1727 return nullptr;
1728}
1729
1730bool LoopVectorizationLegality::isVectorizableEarlyExitLoop() {
1731 BasicBlock *LatchBB = TheLoop->getLoopLatch();
1732 if (!LatchBB) {
1733 reportVectorizationFailure("Loop does not have a latch",
1734 "Cannot vectorize early exit loop",
1735 "NoLatchEarlyExit", ORE, TheLoop);
1736 return false;
1737 }
1738
1739 if (!FixedOrderRecurrences.empty()) {
1741 "Found fixed-order recurrences in early-exit loop",
1742 "Cannot vectorize early exit loop with fixed-order recurrences",
1743 "RecurrencesInEarlyExitLoop", ORE, TheLoop);
1744 return false;
1745 }
1746
1747 SmallVector<BasicBlock *, 8> ExitingBlocks;
1748 TheLoop->getExitingBlocks(ExitingBlocks);
1749
1750 // Keep a record of all the exiting blocks.
1752 SmallVector<BasicBlock *> UncountableExitingBlocks;
1753 for (BasicBlock *BB : ExitingBlocks) {
1754 const SCEV *EC =
1755 PSE.getSE()->getPredicatedExitCount(TheLoop, BB, &Predicates);
1756 if (isa<SCEVCouldNotCompute>(EC)) {
1757 if (size(successors(BB)) != 2) {
1759 "Early exiting block does not have exactly two successors",
1760 "Incorrect number of successors from early exiting block",
1761 "EarlyExitTooManySuccessors", ORE, TheLoop);
1762 return false;
1763 }
1764
1765 UncountableExitingBlocks.push_back(BB);
1766 } else
1767 CountableExitingBlocks.push_back(BB);
1768 }
1769 // We can safely ignore the predicates here because when vectorizing the loop
1770 // the PredicatatedScalarEvolution class will keep track of all predicates
1771 // for each exiting block anyway. This happens when calling
1772 // PSE.getSymbolicMaxBackedgeTakenCount() below.
1773 Predicates.clear();
1774
1775 if (UncountableExitingBlocks.empty()) {
1776 LLVM_DEBUG(dbgs() << "LV: Could not find any uncountable exits\n");
1777 return false;
1778 }
1779
1780 // The latch block must have a countable exit.
1781 if (isa<SCEVCouldNotCompute>(PSE.getSE()->getPredicatedExitCount(
1782 TheLoop, LatchBB, &Predicates, ScalarEvolution::SymbolicMaximum))) {
1784 "Cannot determine symbolic max exit count for latch block",
1785 "Cannot vectorize early exit loop",
1786 "UnknownLatchExitCountEarlyExitLoop", ORE, TheLoop);
1787 return false;
1788 }
1789
1790 if (!is_contained(CountableExitingBlocks, LatchBB)) {
1791 // If not a separate counted exit in the latch, then check for a combined
1792 // countable and uncountable exit.
1793 auto *Br = dyn_cast<CondBrInst>(LatchBB->getTerminator());
1794 if (!Br ||
1795 !findCountableComparisonInCombinedCondition(Br->getCondition())) {
1797 "Latch block does not have a countable exit condition",
1798 "NoCountableConditionInLatchBlock", ORE, TheLoop);
1799 return false;
1800 }
1801 }
1802
1803 // Check to see if there are instructions that could potentially generate
1804 // exceptions or have side-effects.
1805 auto IsSafeOperation = [](Instruction *I) -> bool {
1806 switch (I->getOpcode()) {
1807 case Instruction::Load:
1808 case Instruction::Store:
1809 case Instruction::PHI:
1810 case Instruction::UncondBr:
1811 case Instruction::CondBr:
1812 // These are checked separately.
1813 return true;
1814 default:
1816 }
1817 };
1818
1819 bool HasSideEffects = false;
1820 for (auto *BB : TheLoop->blocks())
1821 for (auto &I : *BB) {
1823 continue;
1824 if (I.mayWriteToMemory()) {
1825 if (isa<StoreInst>(&I) && cast<StoreInst>(&I)->isSimple()) {
1826 HasSideEffects = true;
1827 continue;
1828 }
1829
1830 // We don't support complex writes to memory.
1832 "Complex writes to memory unsupported in early exit loops",
1833 "Cannot vectorize early exit loop with complex writes to memory",
1834 "WritesInEarlyExitLoop", ORE, TheLoop);
1835 return false;
1836 }
1837
1838 if (!IsSafeOperation(&I)) {
1839 reportVectorizationFailure("Early exit loop contains operations that "
1840 "cannot be speculatively executed",
1841 "UnsafeOperationsEarlyExitLoop", ORE,
1842 TheLoop);
1843 return false;
1844 }
1845 }
1846
1847 SmallVector<LoadInst *, 4> NonDerefLoads;
1848 // TODO: Handle loops that may fault.
1849 if (!HasSideEffects) {
1850 // Read-only loop.
1851 Predicates.clear();
1852 if (!isReadOnlyLoop(TheLoop, PSE.getSE(), DT, AC, NonDerefLoads,
1853 &Predicates)) {
1855 "Loop may fault", "Cannot vectorize non-read-only early exit loop",
1856 "NonReadOnlyEarlyExitLoop", ORE, TheLoop);
1857 return false;
1858 }
1859 } else {
1860 // Check all uncountable exiting blocks for movable loads.
1861 for (BasicBlock *ExitingBB : UncountableExitingBlocks) {
1862 if (!canUncountableExitConditionLoadBeMoved(ExitingBB))
1863 return false;
1864 }
1865 }
1866
1867 // Check non-dereferenceable loads if any.
1868 for (LoadInst *LI : NonDerefLoads) {
1869 // Only support unit-stride access for now.
1870 int Stride = isConsecutivePtr(LI->getType(), LI->getPointerOperand());
1871 if (Stride != 1) {
1873 "Loop contains potentially faulting strided load",
1874 "Cannot vectorize early exit loop with "
1875 "strided fault-only-first load",
1876 "EarlyExitLoopWithStridedFaultOnlyFirstLoad", ORE, TheLoop);
1877 return false;
1878 }
1879 }
1880
1881 // We're only handling combined exit conditions via masking at present, which
1882 // is used for loops with side effects.
1883 // TODO: Support readonly loops with combined exit conditions.
1884 // TODO: Decouple style from the presence of side effects.
1885 if (!llvm::is_contained(CountableExitingBlocks, LatchBB) && !HasSideEffects)
1886 return false;
1887
1888 [[maybe_unused]] const SCEV *SymbolicMaxBTC =
1889 PSE.getSymbolicMaxBackedgeTakenCount();
1890 // Since we have an exact exit count for the latch and the early exit
1891 // dominates the latch, then this should guarantee a computed SCEV value.
1892 assert(!isa<SCEVCouldNotCompute>(SymbolicMaxBTC) &&
1893 "Failed to get symbolic expression for backedge taken count");
1894 LLVM_DEBUG(dbgs() << "LV: Found an early exit loop with symbolic max "
1895 "backedge taken count: "
1896 << *SymbolicMaxBTC << '\n');
1897 UncountableExitType = HasSideEffects ? UncountableExitTrait::ReadWrite
1899 return true;
1900}
1901
1902bool LoopVectorizationLegality::canUncountableExitConditionLoadBeMoved(
1903 BasicBlock *ExitingBlock) {
1904 // Try to find a load in the critical path for the uncountable exit condition.
1905 // This is currently matching about the simplest form we can, expecting
1906 // only one in-loop load, the result of which is directly compared against
1907 // a loop-invariant value.
1908 auto *Br = cast<CondBrInst>(ExitingBlock->getTerminator());
1909
1910 using namespace llvm::PatternMatch;
1911 Value *Ptr, *Other;
1912 Instruction *L, *CountableCond;
1913 // We want to match either an uncounted condition (loaded value compared
1914 // against a loop invariant value) or the combination (via logical or) of
1915 // an uncounted condition with a counted condition (integer comparison of
1916 // an induction variable for which we can identify an add recurrence within
1917 // this loop).
1918 if (!matchUncountableExitCondition(Br->getCondition(), Ptr, L, Other) &&
1919 !matchCombinedExitCondition(Br->getCondition(), CountableCond, Ptr, L,
1920 Other, *PSE.getSE(), TheLoop)) {
1922 "Early exit loop with store but no supported condition load",
1923 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1924 return false;
1925 }
1926
1927 // Bail if the uncountable exit load is compared against a non-invariant
1928 // value.
1929 // TODO: Remove this restriction.
1930 if (!TheLoop->isLoopInvariant(Other)) {
1932 "Early exit loop with store but no supported condition load",
1933 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1934 return false;
1935 }
1936
1937 // Make sure that the load address is not loop invariant; we want an
1938 // address calculation that we can rotate to the next vector iteration.
1939 const auto *AR = dyn_cast<SCEVAddRecExpr>(PSE.getSE()->getSCEV(Ptr));
1940 if (!AR || AR->getLoop() != TheLoop || !AR->isAffine()) {
1942 "Uncountable exit condition depends on load with an address that is "
1943 "not an add recurrence in the loop",
1944 "EarlyExitLoadInvariantAddress", ORE, TheLoop);
1945 return false;
1946 }
1947
1948 ICFLoopSafetyInfo SafetyInfo(TheLoop);
1949 LoadInst *Load = cast<LoadInst>(L);
1950 // We need to know that load will be executed before we can hoist a
1951 // copy out to run just before the first iteration.
1952 if (!SafetyInfo.isGuaranteedToExecute(*Load, DT)) {
1954 "Load for uncountable exit not guaranteed to execute",
1955 "ConditionalUncountableExitLoad", ORE, TheLoop);
1956 return false;
1957 }
1958
1959 // Prohibit any potential aliasing with any instruction in the loop which
1960 // might store to memory.
1961 // FIXME: Relax this constraint where possible.
1962 for (auto *BB : TheLoop->blocks()) {
1963 for (auto &I : *BB) {
1964 if (&I == Load)
1965 continue;
1966
1967 // Pseudo-probes are placeholders with no real memory
1968 // access, so they cannot alias the exit condition load and do not need
1969 // to be masked.
1971 continue;
1972
1973 if (I.mayReadOrWriteMemory()) {
1974 // We need to mask all other memory ops.
1975 ConditionallyExecutedOps.insert(&I);
1976 if (isa<LoadInst>(&I))
1977 continue;
1978 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1979 AliasResult AR = AA->alias(Ptr, SI->getPointerOperand());
1980 if (AR == AliasResult::NoAlias)
1981 continue;
1982 }
1983
1985 "Cannot determine whether critical uncountable exit load address "
1986 "does not alias with a memory write",
1987 "CantVectorizeAliasWithCriticalUncountableExitLoad", ORE, TheLoop);
1988 return false;
1989 }
1990 }
1991 }
1992
1993 return true;
1994}
1995
1996bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1997 // Store the result and return it at the end instead of exiting early, in case
1998 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1999 bool Result = true;
2000
2001 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
2002 // Check whether the loop-related control flow in the loop nest is expected by
2003 // vectorizer.
2004 if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
2005 if (DoExtraAnalysis) {
2006 LLVM_DEBUG(dbgs() << "LV: legality check failed: loop nest");
2007 Result = false;
2008 } else {
2009 return false;
2010 }
2011 }
2012
2013 // We need to have a loop header.
2014 LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
2015 << '\n');
2016
2017 // Specific checks for outer loops. We skip the remaining legal checks at this
2018 // point because they don't support outer loops.
2019 if (!TheLoop->isInnermost()) {
2020 assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
2021
2022 if (!canVectorizeOuterLoop()) {
2023 reportVectorizationFailure("Unsupported outer loop",
2024 "UnsupportedOuterLoop", ORE, TheLoop);
2025 // TODO: Implement DoExtraAnalysis when subsequent legal checks support
2026 // outer loops.
2027 return false;
2028 }
2029
2030 LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
2031 return Result;
2032 }
2033
2034 assert(TheLoop->isInnermost() && "Inner loop expected.");
2035 // Check if we can if-convert non-single-bb loops.
2036 unsigned NumBlocks = TheLoop->getNumBlocks();
2037 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2038 LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2039 if (DoExtraAnalysis)
2040 Result = false;
2041 else
2042 return false;
2043 }
2044
2045 // Check if we can vectorize the instructions and CFG in this loop.
2046 if (!canVectorizeInstrs()) {
2047 LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2048 if (DoExtraAnalysis)
2049 Result = false;
2050 else
2051 return false;
2052 }
2053
2054 if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount()) &&
2055 !isVectorizableEarlyExitLoop()) {
2056 assert(UncountableExitType == UncountableExitTrait::None &&
2057 "Must be false without vectorizable early-exit loop");
2058 if (TheLoop->getExitingBlock())
2059 reportVectorizationFailure("Cannot vectorize uncountable loop",
2060 "UnsupportedUncountableLoop", ORE, TheLoop);
2061 if (DoExtraAnalysis)
2062 Result = false;
2063 else
2064 return false;
2065 }
2066
2067 // Go over each instruction and look at memory deps.
2068 if (!canVectorizeMemory()) {
2069 LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2070 if (DoExtraAnalysis)
2071 Result = false;
2072 else
2073 return false;
2074 }
2075
2076 // TODO: Remove this restriction, should be straightforward to support.
2077 if (UncountableExitType != UncountableExitTrait::None &&
2078 !LAI->getStoresToInvariantAddresses().empty()) {
2079 LLVM_DEBUG(dbgs() << "LV: Cannot vectorize early exit loops with stores to "
2080 "loop-invariant addresses\n");
2081 reportVectorizationFailure("Cannot vectorize early exit loops with stores "
2082 "to loop-invariant addresses",
2083 "LoopInvariantStoresInEELoop", ORE, TheLoop);
2084 return false;
2085 }
2086
2087 if (Result) {
2088 LLVM_DEBUG(dbgs() << "LV: Loop passed LoopVectorizationLegality checks"
2089 << (LAI->getRuntimePointerChecking()->Need
2090 ? " (with a runtime bound check)"
2091 : "")
2092 << "!\n");
2093 }
2094
2095 // Okay! We've done all the tests. If any have failed, return false. Otherwise
2096 // we can vectorize, and at this point we don't have any other mem analysis
2097 // which may limit our maximum vectorization factor, so just return true with
2098 // no restrictions.
2099 return Result;
2100}
2101
2103 // The only loops we can vectorize without a scalar epilogue, are loops with
2104 // a bottom-test and a single exiting block. We'd have to handle the fact
2105 // that not every instruction executes on the last iteration. This will
2106 // require a lane mask which varies through the vector loop body. (TODO)
2107 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
2108 LLVM_DEBUG(
2109 dbgs()
2110 << "LV: Cannot fold tail by masking. Requires a singe latch exit\n");
2111 return false;
2112 }
2113
2114 // TODO: Support tail folding with uncountable exits.
2116 LLVM_DEBUG(dbgs() << "LV: Cannot tail fold by masking. Loop contains an "
2117 "uncountable early exit.\n");
2118 return false;
2119 }
2120
2121 LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
2122
2123 // No accesses are known to be safe in inactive lanes of the folded tail.
2124 SafeAccessesTy SafeAccesses;
2125
2126 // Check all blocks for predication, including those that ordinarily do not
2127 // need predication such as the header block.
2129 for (BasicBlock *BB : TheLoop->blocks()) {
2130 if (!blockCanBePredicated(BB, SafeAccesses, TmpMaskedOp)) {
2131 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking.\n");
2132 return false;
2133 }
2134 }
2135
2136 LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
2137
2138 return true;
2139}
2140
2142 // No accesses are known to be safe in inactive lanes of the folded tail.
2143 SafeAccessesTy SafeAccesses;
2144
2145 // Mark all blocks for predication, including those that ordinarily do not
2146 // need predication such as the header block, and collect instructions needing
2147 // predication in TailFoldedMaskedOp.
2148 for (BasicBlock *BB : TheLoop->blocks()) {
2149 [[maybe_unused]] bool R =
2150 blockCanBePredicated(BB, SafeAccesses, TailFoldedMaskedOp);
2151 assert(R && "Must be able to predicate block when tail-folding.");
2152 }
2153}
2154
2155} // namespace llvm
const TargetLowering & TLI
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 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 allowReordering() const
When enabling loop hints are provided we allow the vectorizer to change the order of operations that ...
LLVM_ABI LoopVectorizeHints(const VectorizeOptions &Opts, const Loop *L, bool InterleaveOnlyWhenForced, OptimizationRemarkEmitter &ORE, const TargetTransformInfo *TTI=nullptr)
LLVM_ABI void emitRemarkWithHints() const
Dumps all the hint information.
LLVM_ABI bool allowVectorization(Loop *L, bool VectorizeOnlyWhenForced) const
LLVM_ABI void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:68
LLVM_ABI 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:613
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...
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.
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:314
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 Align[]
Key for Kernel::Arg::Metadata::mAlign.
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:841
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:452
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
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:956
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
static bool matchUncountableExitCondition(Value *Cond, Value *&Ptr, Instruction *&Load, Value *&Other)
Matches an exit condition formed by comparing a value loaded from memory with another term.
static bool findHistogram(LoadInst *LI, StoreInst *HSt, Loop *TheLoop, const PredicatedScalarEvolution &PSE, SmallVectorImpl< HistogramInfo > &Histograms)
Find histogram operations that match high-level code in loops:
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI)
Checks if a function is scalarizable according to the TLI, in the sense that it should be vectorized ...
static bool matchCountableExitCondition(Value *Cond, ScalarEvolution &SE, Loop *TheLoop)
Matches an exit condition formed by comparing the current value of an affine add recurrence in the gi...
LLVM_ABI bool isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC=nullptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return true if we can prove that the given load (which is assumed to be within the specified loop) wo...
Definition Loads.cpp: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.