37#define LV_NAME "loop-vectorize"
38#define DEBUG_TYPE LV_NAME
42 cl::desc(
"Enable if-conversion during vectorization."));
46 cl::desc(
"Enable recognition of non-constant strided "
47 "pointer induction variables."));
51 cl::desc(
"Allow enabling loop hints to reorder "
52 "FP operations during vectorization."));
58 cl::desc(
"The maximum number of SCEV checks allowed."));
62 cl::desc(
"The maximum number of SCEV checks allowed with a "
63 "vectorize(enable) pragma"));
69 cl::desc(
"Control whether the compiler can use scalable vectors to "
73 "Scalable vectorization is disabled."),
76 "Scalable vectorization is available and favored when the "
77 "cost is inconclusive."),
80 "Scalable vectorization is available and favored when the "
81 "cost is inconclusive.")));
85 cl::desc(
"Enables autovectorization of some loops containing histograms"));
92bool LoopVectorizeHints::Hint::validate(
unsigned Val) {
100 case HK_ISVECTORIZED:
103 return (Val == 0 || Val == 1);
109 bool InterleaveOnlyWhenForced,
113 Interleave(
"interleave.count", InterleaveOnlyWhenForced, HK_INTERLEAVE),
115 IsVectorized(
"isvectorized", 0, HK_ISVECTORIZED),
116 Predicate(
"vectorize.predicate.enable",
FK_Undefined, HK_PREDICATE),
117 Scalable(
"vectorize.scalable.enable",
SK_Unspecified, HK_SCALABLE),
118 TheLoop(L), ORE(ORE) {
120 getHintsFromMetadata();
154 if (IsVectorized.Value != 1)
161 <<
"LV: Interleaving disabled by the pass manager\n");
165 LLVMContext &Context = TheLoop->getHeader()->getContext();
171 MDNode *LoopID = TheLoop->getLoopID();
174 {
Twine(Prefix(),
"vectorize.").
str(),
175 Twine(Prefix(),
"interleave.").
str()},
177 TheLoop->setLoopID(NewLoopID);
180 IsVectorized.Value = 1;
183void LoopVectorizeHints::reportDisallowedVectorization(
186 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: " << DebugMsg <<
".\n");
189 <<
"loop not vectorized: " << RemarkMsg);
196 reportDisallowedVectorization(
"#pragma vectorize disable",
197 "MissedExplicitlyDisabled",
198 "vectorization is explicitly disabled", L);
200 reportDisallowedVectorization(
"loop hasDisableAllTransformsHint",
201 "MissedTransformsDisabled",
202 "loop transformations are disabled", L);
210 reportDisallowedVectorization(
211 "VectorizeOnlyWhenForced is set, and no #pragma vectorize enable",
212 "MissedForceOnly",
"only vectorizing loops that explicitly request it",
218 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Disabled/already vectorized.\n");
224 "AllDisabled", L->getStartLoc(),
226 <<
"loop not vectorized: vectorization and interleaving are "
227 "explicitly disabled, or the loop has already been "
242 TheLoop->getStartLoc(),
243 TheLoop->getHeader())
244 <<
"loop not vectorized: vectorization is explicitly disabled";
247 TheLoop->getHeader());
248 R <<
"loop not vectorized";
250 R <<
" (Force=" << NV(
"Force",
true);
251 if (Width.Value != 0)
252 R <<
", Vector Width=" << NV(
"VectorWidth",
getWidth());
254 R <<
", Interleave Count=" << NV(
"InterleaveCount",
getInterleave());
277 EC.getKnownMinValue() > 1);
280void LoopVectorizeHints::getHintsFromMetadata() {
296 if (!MD || MD->getNumOperands() == 0)
299 for (
unsigned Idx = 1; Idx < MD->getNumOperands(); ++Idx)
300 Args.push_back(MD->getOperand(Idx));
303 assert(Args.size() == 0 &&
"too many arguments for MDString");
311 if (
Args.size() == 1)
312 setHint(Name, Args[0]);
317 if (!
Name.consume_front(Prefix()))
323 unsigned Val =
C->getZExtValue();
325 Hint *Hints[] = {&Width, &Interleave, &Force,
326 &IsVectorized, &Predicate, &Scalable};
327 for (
auto *
H : Hints) {
328 if (Name ==
H->Name) {
329 if (
H->validate(Val))
332 LLVM_DEBUG(
dbgs() <<
"LV: ignoring invalid hint '" << Name <<
"'\n");
379 if (!LatchBr || LatchBr->isUnconditional()) {
388 dbgs() <<
"LV: Loop latch condition is not a compare instruction.\n");
392 Value *CondOp0 = LatchCmp->getOperand(0);
393 Value *CondOp1 = LatchCmp->getOperand(1);
394 Value *IVUpdate =
IV->getIncomingValueForBlock(Latch);
397 LLVM_DEBUG(
dbgs() <<
"LV: Loop latch condition is not uniform.\n");
411 for (
Loop *SubLp : *Lp)
419 assert(Ty->isIntOrPtrTy() &&
"Expected integer or pointer type");
421 if (Ty->isPointerTy())
422 return DL.getIntPtrType(Ty->getContext(), Ty->getPointerAddressSpace());
426 if (Ty->getScalarSizeInBits() < 32)
445 if (!AllowedExit.
count(Inst))
451 LLVM_DEBUG(
dbgs() <<
"LV: Found an outside user for : " << *UI <<
'\n');
466 Value *APtr =
A->getPointerOperand();
467 Value *BPtr =
B->getPointerOperand();
481 const auto &Strides =
484 int Stride =
getPtrStride(PSE, AccessTy, Ptr, TheLoop, *DT, Strides,
485 AllowRuntimeSCEVChecks,
false)
487 if (Stride == 1 || Stride == -1)
493 return LAI->isInvariant(V);
503class SCEVAddRecForUniformityRewriter
506 unsigned StepMultiplier;
515 bool CannotAnalyze =
false;
517 bool canAnalyze()
const {
return !CannotAnalyze; }
520 SCEVAddRecForUniformityRewriter(
ScalarEvolution &SE,
unsigned StepMultiplier,
525 const SCEV *visitAddRecExpr(
const SCEVAddRecExpr *Expr) {
527 "addrec outside of TheLoop must be invariant and should have been "
533 if (!SE.isLoopInvariant(Step, TheLoop)) {
534 CannotAnalyze =
true;
537 const SCEV *NewStep =
538 SE.getMulExpr(Step, SE.getConstant(Ty, StepMultiplier));
539 const SCEV *ScaledOffset = SE.getMulExpr(Step, SE.getConstant(Ty, Offset));
540 const SCEV *NewStart =
541 SE.getAddExpr(Expr->
getStart(), SCEVUse(ScaledOffset));
545 const SCEV *
visit(
const SCEV *S) {
546 if (CannotAnalyze || SE.isLoopInvariant(S, TheLoop))
551 const SCEV *visitUnknown(
const SCEVUnknown *S) {
552 if (SE.isLoopInvariant(S, TheLoop))
555 CannotAnalyze =
true;
559 const SCEV *visitCouldNotCompute(
const SCEVCouldNotCompute *S) {
561 CannotAnalyze =
true;
565 static const SCEV *rewrite(
const SCEV *S, ScalarEvolution &SE,
566 unsigned StepMultiplier,
unsigned Offset,
576 SCEVAddRecForUniformityRewriter
Rewriter(SE, StepMultiplier, Offset,
598 auto *SE = PSE.getSE();
606 const SCEV *FirstLaneExpr =
607 SCEVAddRecForUniformityRewriter::rewrite(S, *SE, FixedVF, 0, TheLoop);
615 const SCEV *IthLaneExpr =
616 SCEVAddRecForUniformityRewriter::rewrite(S, *SE, FixedVF,
I, TheLoop);
617 return FirstLaneExpr == IthLaneExpr;
633bool LoopVectorizationLegality::canVectorizeOuterLoop() {
646 "loop control flow is not understood by vectorizer",
647 "CFGNotUnderstood", ORE, TheLoop);
660 if (Br && Br->isConditional() &&
665 "loop control flow is not understood by vectorizer",
666 "CFGNotUnderstood", ORE, TheLoop);
679 "loop control flow is not understood by vectorizer",
680 "CFGNotUnderstood", ORE, TheLoop);
688 if (!setupOuterLoopInductions()) {
690 "UnsupportedPhi", ORE, TheLoop);
700void LoopVectorizationLegality::addInductionPhi(
703 Inductions[
Phi] =
ID;
711 InductionCastsToIgnore.insert(*Casts.
begin());
714 const DataLayout &
DL =
Phi->getDataLayout();
717 "Expected int, ptr, or FP induction phi type");
729 ID.getConstIntStepValue() &&
ID.getConstIntStepValue()->isOne() &&
737 if (!PrimaryInduction || PhiTy == WidestIndTy)
738 PrimaryInduction =
Phi;
747 if (PSE.getPredicate().isAlwaysTrue()) {
748 AllowedExit.insert(Phi);
749 AllowedExit.insert(
Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
755bool LoopVectorizationLegality::setupOuterLoopInductions() {
759 auto IsSupportedPhi = [&](PHINode &
Phi) ->
bool {
760 InductionDescriptor
ID;
763 addInductionPhi(&Phi,
ID, AllowedExit);
769 dbgs() <<
"LV: Found unsupported PHI for outer loop vectorization.\n");
792 TLI.
getWidestVF(ScalarName, WidestFixedVF, WidestScalableVF);
800 "Caller may decide to scalarize a variant using a scalable VF");
805bool LoopVectorizationLegality::canVectorizeInstrs() {
813 Result &= canVectorizeInstr(
I);
814 if (!DoExtraAnalysis && !Result)
819 if (!PrimaryInduction) {
820 if (Inductions.empty()) {
822 "Did not find one integer induction var",
823 "loop induction variable could not be identified",
824 "NoInductionVariable", ORE, TheLoop);
829 "Did not find one integer induction var",
830 "integer loop induction variable could not be identified",
831 "NoIntegerInductionVariable", ORE, TheLoop);
834 LLVM_DEBUG(
dbgs() <<
"LV: Did not find one integer induction var.\n");
840 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
841 PrimaryInduction =
nullptr;
846bool LoopVectorizationLegality::canVectorizeInstr(
Instruction &
I) {
856 "Found a non-int non-pointer PHI",
857 "loop control flow is not understood by vectorizer",
858 "CFGNotUnderstood", ORE, TheLoop);
871 AllowedExit.insert(&
I);
876 if (
Phi->getNumIncomingValues() != 2) {
878 "Found an invalid PHI",
879 "loop control flow is not understood by vectorizer",
880 "CFGNotUnderstood", ORE, TheLoop, Phi);
884 RecurrenceDescriptor RedDes;
889 Reductions[
Phi] = std::move(RedDes);
893 "Only min/max recurrences are allowed to have multiple uses "
902 auto IsDisallowedStridedPointerInduction =
903 [](
const InductionDescriptor &
ID) {
907 ID.getConstIntStepValue() ==
nullptr;
924 InductionDescriptor
ID;
926 !IsDisallowedStridedPointerInduction(
ID)) {
927 addInductionPhi(Phi,
ID, AllowedExit);
928 Requirements->addExactFPMathInst(
ID.getExactFPMathInst());
933 AllowedExit.insert(Phi);
934 FixedOrderRecurrences.insert(Phi);
941 !IsDisallowedStridedPointerInduction(
ID)) {
942 addInductionPhi(Phi,
ID, AllowedExit);
947 "value that could not be identified as "
948 "reduction is used outside the loop",
949 "NonReductionValueUsedOutsideLoop", ORE, TheLoop,
960 !(CI->getCalledFunction() && TLI &&
966 TLI && CI->getCalledFunction() && CI->getType()->isFloatingPointTy() &&
967 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
968 TLI->hasOptimizedCodeGen(Func);
976 "Found a non-intrinsic callsite",
977 "library call cannot be vectorized. "
978 "Try compiling with -fno-math-errno, -ffast-math, "
980 "CantVectorizeLibcall", ORE, TheLoop, CI);
983 "call instruction cannot be vectorized",
984 "CantVectorizeLibcall", ORE, TheLoop, CI);
992 auto *SE = PSE.getSE();
994 for (
unsigned Idx = 0; Idx < CI->arg_size(); ++Idx)
998 "Found unvectorizable intrinsic",
999 "intrinsic instruction cannot be vectorized",
1000 "CantVectorizeIntrinsic", ORE, TheLoop, CI);
1009 VecCallVariantsFound =
true;
1011 auto CanWidenInstructionTy = [](
Instruction const &Inst) {
1012 Type *InstTy = Inst.getType();
1026 if (!CanWidenInstructionTy(
I) ||
1031 "instruction return type cannot be vectorized",
1032 "CantVectorizeInstructionReturnType", ORE,
1039 Type *
T =
ST->getValueOperand()->getType();
1042 "CantVectorizeStore", ORE, TheLoop, ST);
1048 if (
ST->getMetadata(LLVMContext::MD_nontemporal)) {
1051 assert(VecTy &&
"did not find vectorized version of stored type");
1052 if (!TTI->isLegalNTStore(VecTy,
ST->getAlign())) {
1054 "nontemporal store instruction cannot be vectorized",
1055 "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
1061 if (
LD->getMetadata(LLVMContext::MD_nontemporal)) {
1065 assert(VecTy &&
"did not find vectorized version of load type");
1066 if (!TTI->isLegalNTLoad(VecTy,
LD->getAlign())) {
1068 "nontemporal load instruction cannot be vectorized",
1069 "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
1079 }
else if (
I.getType()->isFloatingPointTy() && (CI ||
I.isBinaryOp()) &&
1082 Hints->setPotentiallyUnsafe();
1092 if (PSE.getPredicate().isAlwaysTrue()) {
1093 AllowedExit.insert(&
I);
1097 "ValueUsedOutsideLoop", ORE, TheLoop, &
I);
1131 Value *HIncVal =
nullptr;
1146 Value *HIdx =
nullptr;
1147 for (
Value *Index :
GEP->indices()) {
1170 if (!AR || AR->getLoop() != TheLoop)
1180 LLVM_DEBUG(
dbgs() <<
"LV: Found histogram for: " << *HSt <<
"\n");
1187bool LoopVectorizationLegality::canVectorizeIndirectUnsafeDependences() {
1227 LLVM_DEBUG(
dbgs() <<
"LV: Checking for a histogram on: " << *SI <<
"\n");
1228 return findHistogram(LI, SI, TheLoop, LAI->getPSE(), Histograms);
1231bool LoopVectorizationLegality::canVectorizeMemory() {
1232 LAI = &LAIs.getInfo(*TheLoop);
1233 const OptimizationRemarkAnalysis *LAR = LAI->getReport();
1236 return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
1237 "loop not vectorized: ", *LAR);
1241 if (!LAI->canVectorizeMemory()) {
1244 "Cannot vectorize unsafe dependencies in uncountable exit loop with "
1246 "CantVectorizeUnsafeDependencyForEELoopWithSideEffects", ORE,
1251 return canVectorizeIndirectUnsafeDependences();
1254 if (LAI->hasLoadStoreDependenceInvolvingLoopInvariantAddress()) {
1256 "write to a loop invariant address could not "
1258 "CantVectorizeStoreToLoopInvariantAddress", ORE,
1267 if (!LAI->getStoresToInvariantAddresses().empty()) {
1270 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1276 "We don't allow storing to uniform addresses",
1277 "write of conditional recurring variant value to a loop "
1278 "invariant address could not be vectorized",
1279 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1287 if (TheLoop->contains(Ptr)) {
1289 "Invariant address is calculated inside the loop",
1290 "write to a loop invariant address could not "
1292 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1298 if (LAI->hasStoreStoreDependenceInvolvingLoopInvariantAddress()) {
1304 ScalarEvolution *SE = PSE.getSE();
1306 for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
1318 erase_if(UnhandledStores, [SE, SI](StoreInst *
I) {
1320 I->getValueOperand()->getType() ==
1321 SI->getValueOperand()->getType();
1328 bool IsOK = UnhandledStores.
empty();
1332 "We don't allow storing to uniform addresses",
1333 "write to a loop invariant address could not "
1335 "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
1341 PSE.addPredicate(LAI->getPSE().getPredicate());
1346 bool EnableStrictReductions) {
1349 if (!Requirements->getExactFPInst() || Hints->allowReordering())
1355 if (!EnableStrictReductions ||
1386 return V == InvariantAddress ||
1397 return Inductions.count(PN);
1422 const Value *V)
const {
1424 return (Inst && InductionCastsToIgnore.count(Inst));
1433 return FixedOrderRecurrences.count(Phi);
1448bool LoopVectorizationLegality::blockCanBePredicated(
1477 if (!SafePtrs.
count(LI->getPointerOperand()))
1478 MaskedOp.insert(LI);
1488 MaskedOp.insert(SI);
1492 if (
I.mayReadFromMemory() ||
I.mayWriteToMemory() ||
I.mayThrow())
1499bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1502 "IfConversionDisabled", ORE, TheLoop);
1506 assert(TheLoop->getNumBlocks() > 1 &&
"Single block loops are vectorizable");
1513 SmallPtrSet<Value *, 8> SafePointers;
1516 for (BasicBlock *BB : TheLoop->blocks()) {
1518 for (Instruction &
I : *BB)
1520 SafePointers.
insert(Ptr);
1529 ScalarEvolution &SE = *PSE.getSE();
1531 for (Instruction &
I : *BB) {
1541 auto CanSpeculatePointerOp = [
this](
Value *Ptr) {
1543 SmallPtrSet<Value *, 4> Visited;
1544 while (!Worklist.
empty()) {
1546 if (!Visited.
insert(CurrV).second)
1550 if (!CurrI || !TheLoop->contains(CurrI)) {
1554 TheLoop->getLoopPredecessor()
1578 CanSpeculatePointerOp(LI->getPointerOperand()) &&
1581 SafePointers.
insert(LI->getPointerOperand());
1587 for (BasicBlock *BB : TheLoop->blocks()) {
1591 if (TheLoop->isLoopExiting(BB)) {
1593 "LoopContainsUnsupportedSwitch", ORE,
1594 TheLoop, BB->getTerminator());
1599 "LoopContainsUnsupportedTerminator", ORE,
1600 TheLoop, BB->getTerminator());
1606 !blockCanBePredicated(BB, SafePointers, MaskedOp)) {
1608 "Control flow cannot be substituted for a select",
"NoCFGForSelect",
1609 ORE, TheLoop, BB->getTerminator());
1619bool LoopVectorizationLegality::canVectorizeLoopCFG(
Loop *Lp,
1620 bool UseVPlanNativePath) {
1622 "VPlan-native path is not enabled.");
1632 bool DoExtraAnalysis = ORE->allowExtraAnalysis(
DEBUG_TYPE);
1638 "loop control flow is not understood by vectorizer",
1639 "CFGNotUnderstood", ORE, TheLoop);
1640 if (DoExtraAnalysis)
1649 "loop control flow is not understood by vectorizer",
1650 "CFGNotUnderstood", ORE, TheLoop);
1651 if (DoExtraAnalysis)
1661 "The loop latch terminator is not a BranchInst",
1662 "loop control flow is not understood by vectorizer",
"CFGNotUnderstood",
1664 if (DoExtraAnalysis)
1673bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1674 Loop *Lp,
bool UseVPlanNativePath) {
1678 bool DoExtraAnalysis = ORE->allowExtraAnalysis(
DEBUG_TYPE);
1679 if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1680 if (DoExtraAnalysis)
1688 for (Loop *SubLp : *Lp)
1689 if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1690 if (DoExtraAnalysis)
1699bool LoopVectorizationLegality::isVectorizableEarlyExitLoop() {
1700 BasicBlock *LatchBB = TheLoop->getLoopLatch();
1703 "Cannot vectorize early exit loop",
1704 "NoLatchEarlyExit", ORE, TheLoop);
1708 if (Reductions.size() || FixedOrderRecurrences.size()) {
1710 "Found reductions or recurrences in early-exit loop",
1711 "Cannot vectorize early exit loop with reductions or recurrences",
1712 "RecurrencesInEarlyExitLoop", ORE, TheLoop);
1716 SmallVector<BasicBlock *, 8> ExitingBlocks;
1717 TheLoop->getExitingBlocks(ExitingBlocks);
1722 for (BasicBlock *BB : ExitingBlocks) {
1724 PSE.getSE()->getPredicatedExitCount(TheLoop, BB, &Predicates);
1728 "Early exiting block does not have exactly two successors",
1729 "Incorrect number of successors from early exiting block",
1730 "EarlyExitTooManySuccessors", ORE, TheLoop);
1736 CountableExitingBlocks.push_back(BB);
1744 if (UncountableExitingBlocks.
empty()) {
1745 LLVM_DEBUG(
dbgs() <<
"LV: Could not find any uncountable exits");
1751 PSE.getSE()->getPredicatedExitCount(TheLoop, LatchBB, &Predicates))) {
1753 "Cannot determine exact exit count for latch block",
1754 "Cannot vectorize early exit loop",
1755 "UnknownLatchExitCountEarlyExitLoop", ORE, TheLoop);
1759 "Latch block not found in list of countable exits!");
1764 switch (
I->getOpcode()) {
1765 case Instruction::Load:
1766 case Instruction::Store:
1767 case Instruction::PHI:
1768 case Instruction::UncondBr:
1769 case Instruction::CondBr:
1777 bool HasSideEffects =
false;
1778 for (
auto *BB : TheLoop->blocks())
1779 for (
auto &
I : *BB) {
1780 if (
I.mayWriteToMemory()) {
1782 HasSideEffects =
true;
1788 "Complex writes to memory unsupported in early exit loops",
1789 "Cannot vectorize early exit loop with complex writes to memory",
1790 "WritesInEarlyExitLoop", ORE, TheLoop);
1794 if (!IsSafeOperation(&
I)) {
1796 "cannot be speculatively executed",
1797 "UnsafeOperationsEarlyExitLoop", ORE,
1805 if (!HasSideEffects) {
1811 "Loop may fault",
"Cannot vectorize non-read-only early exit loop",
1812 "NonReadOnlyEarlyExitLoop", ORE, TheLoop);
1817 for (BasicBlock *ExitingBB : UncountableExitingBlocks) {
1818 if (!canUncountableExitConditionLoadBeMoved(ExitingBB))
1824 for (LoadInst *LI : NonDerefLoads) {
1829 "Loop contains potentially faulting strided load",
1830 "Cannot vectorize early exit loop with "
1831 "strided fault-only-first load",
1832 "EarlyExitLoopWithStridedFaultOnlyFirstLoad", ORE, TheLoop);
1835 PotentiallyFaultingLoads.insert(LI);
1836 LLVM_DEBUG(
dbgs() <<
"LV: Found potentially faulting load: " << *LI
1840 [[maybe_unused]]
const SCEV *SymbolicMaxBTC =
1841 PSE.getSymbolicMaxBackedgeTakenCount();
1845 "Failed to get symbolic expression for backedge taken count");
1846 LLVM_DEBUG(
dbgs() <<
"LV: Found an early exit loop with symbolic max "
1847 "backedge taken count: "
1848 << *SymbolicMaxBTC <<
'\n');
1849 HasUncountableEarlyExit =
true;
1850 UncountableExitWithSideEffects = HasSideEffects;
1854bool LoopVectorizationLegality::canUncountableExitConditionLoadBeMoved(
1865 using namespace llvm::PatternMatch;
1867 Value *Ptr =
nullptr;
1869 if (!
match(Br->getCondition(),
1873 "Early exit loop with store but no supported condition load",
1874 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1879 if (!TheLoop->isLoopInvariant(R)) {
1881 "Early exit loop with store but no supported condition load",
1882 "NoConditionLoadForEarlyExitLoop", ORE, TheLoop);
1889 if (!AR || AR->getLoop() != TheLoop || !AR->isAffine()) {
1891 "Uncountable exit condition depends on load with an address that is "
1892 "not an add recurrence in the loop",
1893 "EarlyExitLoadInvariantAddress", ORE, TheLoop);
1904 "Cannot vectorize potentially faulting early exit loop",
1905 "PotentiallyFaultingEarlyExitLoop", ORE, TheLoop);
1909 ICFLoopSafetyInfo SafetyInfo;
1915 "Load for uncountable exit not guaranteed to execute",
1916 "ConditionalUncountableExitLoad", ORE, TheLoop);
1923 for (
auto *BB : TheLoop->blocks()) {
1924 for (
auto &
I : *BB) {
1928 if (
I.mayWriteToMemory()) {
1930 AliasResult AR = AA->alias(Ptr,
SI->getPointerOperand());
1936 "Cannot determine whether critical uncountable exit load address "
1937 "does not alias with a memory write",
1938 "CantVectorizeAliasWithCriticalUncountableExitLoad", ORE, TheLoop);
1952 bool DoExtraAnalysis = ORE->allowExtraAnalysis(
DEBUG_TYPE);
1955 if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1956 if (DoExtraAnalysis) {
1965 LLVM_DEBUG(
dbgs() <<
"LV: Found a loop: " << TheLoop->getHeader()->getName()
1970 if (!TheLoop->isInnermost()) {
1971 assert(UseVPlanNativePath &&
"VPlan-native path is not enabled.");
1973 if (!canVectorizeOuterLoop()) {
1975 "UnsupportedOuterLoop", ORE, TheLoop);
1985 assert(TheLoop->isInnermost() &&
"Inner loop expected.");
1987 unsigned NumBlocks = TheLoop->getNumBlocks();
1988 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1990 if (DoExtraAnalysis)
1997 if (!canVectorizeInstrs()) {
1998 LLVM_DEBUG(
dbgs() <<
"LV: Can't vectorize the instructions or CFG\n");
1999 if (DoExtraAnalysis)
2006 if (TheLoop->getExitingBlock()) {
2008 "UnsupportedUncountableLoop", ORE, TheLoop);
2009 if (DoExtraAnalysis)
2014 if (!isVectorizableEarlyExitLoop()) {
2017 "Must be false without vectorizable early-exit loop");
2018 if (DoExtraAnalysis)
2027 if (!canVectorizeMemory()) {
2028 LLVM_DEBUG(
dbgs() <<
"LV: Can't vectorize due to memory conflicts\n");
2029 if (DoExtraAnalysis)
2036 if (UncountableExitWithSideEffects) {
2038 "Writes to memory unsupported in early exit loops",
2039 "Cannot vectorize early exit loop with writes to memory",
2040 "WritesInEarlyExitLoop", ORE, TheLoop);
2046 << (LAI->getRuntimePointerChecking()->Need
2047 ?
" (with a runtime bound check)"
2056 if (PSE.getPredicate().getComplexity() > SCEVThreshold) {
2058 "due to SCEVThreshold");
2060 "Too many SCEV assumptions need to be made and checked at runtime",
2061 "TooManySCEVRunTimeChecks", ORE, TheLoop);
2062 if (DoExtraAnalysis)
2080 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
2083 <<
"LV: Cannot fold tail by masking. Requires a singe latch exit\n");
2087 LLVM_DEBUG(
dbgs() <<
"LV: checking if tail can be folded by masking.\n");
2092 ReductionLiveOuts.
insert(Reduction.second.getLoopExitInstr());
2101 if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp)) {
2119 [[maybe_unused]]
bool R = blockCanBePredicated(BB, SafePointers, MaskedOp);
2120 assert(R &&
"Must be able to predicate block when tail-folding.");
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)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
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.")))
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.
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
static bool isSimple(Instruction *I)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
Virtual Register Rewriter
static const uint32_t IV[8]
Class for arbitrary precision integers.
@ NoAlias
The two locations do not alias at all.
bool empty() const
empty - Check if the array is empty.
LLVM Basic Block Representation.
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...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
This class represents a function call, abstracting a target machine's calling convention.
A parsed version of the target data layout string in and methods for querying it.
static constexpr ElementCount getScalable(ScalarTy MinVal)
static constexpr ElementCount getFixed(ScalarTy MinVal)
constexpr bool isScalar() const
Exactly one element.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
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.
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 uncountable early exits, 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,...
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_Unspecified
Not selected.
@ SK_FixedWidthOnly
Disables vectorization with scalable vectors.
enum ForceKind getForce() const
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.
ElementCount getWidth() const
@ FK_Enabled
Forcing enabled.
@ FK_Undefined
Not selected.
@ FK_Disabled
Forcing disabled.
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...
unsigned getInterleave() const
unsigned getIsVectorized() const
Represents a single loop in the control flow graph.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
unsigned getNumOperands() const
Return number of MDNode operands.
Tracking metadata reference owned by Metadata.
LLVM_ABI StringRef getString() const
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
iterator find(const KeyT &Key)
Checks memory dependences among accesses to the same underlying object to determine whether there vec...
const SmallVectorImpl< Dependence > * getDependences() const
Returns the memory dependences.
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 Loop * getLoop() const
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visit(const SCEV *S)
This class represents an analyzed expression in the program.
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.
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
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Value * getOperand(unsigned i) const
static bool hasMaskedVariant(const CallInst &CI, std::optional< ElementCount > VF=std::nullopt)
static SmallVector< VFInfo, 8 > getMappings(const CallInst &CI)
Retrieve all the VFInfo instances associated to the CallInst CI.
LLVM Value Representation.
iterator_range< user_iterator > users()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
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)
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
constexpr bool isZero() const
const ParentTy * getParent() const
#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.
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
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.
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
NodeAddr< PhiNode * > Phi
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
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.
FunctionAddr VTableAddr Value
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
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.
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.
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.
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...
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)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
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.
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...
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...
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.
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.
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...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
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...
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
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.