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