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