146 #include <functional> 154 using namespace llvm;
156 #define LV_NAME "loop-vectorize" 157 #define DEBUG_TYPE LV_NAME 162 "llvm.loop.vectorize.followup_all";
164 "llvm.loop.vectorize.followup_vectorized";
166 "llvm.loop.vectorize.followup_epilogue";
169 STATISTIC(LoopsVectorized,
"Number of loops vectorized");
170 STATISTIC(LoopsAnalyzed,
"Number of loops analyzed for vectorization");
176 cl::desc(
"Loops with a constant trip count that is smaller than this " 177 "value are vectorized only if no scalar iteration overheads " 185 cl::desc(
"Indicate that an epilogue is undesired, predication should be " 190 cl::desc(
"Maximize bandwidth when selecting vectorization factor which " 191 "will be determined by the smallest type in loop."));
195 cl::desc(
"Enable vectorization on interleaved memory accesses in a loop"));
201 cl::desc(
"Enable vectorization on masked interleaved memory accesses in a loop"));
205 cl::desc(
"We don't interleave loops with a estimated constant trip count " 206 "below this number"));
210 cl::desc(
"A flag that overrides the target's number of scalar registers."));
214 cl::desc(
"A flag that overrides the target's number of vector registers."));
218 cl::desc(
"A flag that overrides the target's max interleave factor for " 223 cl::desc(
"A flag that overrides the target's max interleave factor for " 224 "vectorized loops."));
228 cl::desc(
"A flag that overrides the target's expected cost for " 229 "an instruction to a single constant value. Mostly " 230 "useful for getting consistent testing."));
235 "The cost of a loop that is considered 'small' by the interleaver."));
239 cl::desc(
"Enable the use of the block frequency analysis to access PGO " 240 "heuristics minimizing code growth in cold regions and being more " 241 "aggressive in hot regions."));
247 "Enable runtime interleaving until load/store ports are saturated"));
252 cl::desc(
"Max number of stores to be predicated behind an if."));
256 cl::desc(
"Count the induction variable only once when interleaving"));
260 cl::desc(
"Enable if predication of stores during vectorization."));
264 cl::desc(
"The maximum interleave count to use when interleaving a scalar " 265 "reduction in a nested loop."));
269 cl::desc(
"Enable VPlan-native vectorization path with " 270 "support for outer loop vectorization."));
276 cl::desc(
"Enable VPlan-native vectorization path predicator with " 277 "support for outer loop vectorization."));
286 "Build VPlan for every supported loop nest in the function and bail " 287 "out right after the build (stress test the VPlan H-CFG construction " 288 "in the VPlan-native vectorization path)."));
292 cl::desc(
"Enable loop interleaving in Loop vectorization passes"));
295 cl::desc(
"Run the Loop vectorization passes"));
308 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
309 "Expected Load or Store instruction");
310 if (
auto *LI = dyn_cast<LoadInst>(I))
311 return LI->getType();
312 return cast<StoreInst>(
I)->getValueOperand()->getType();
341 if (isa<FPMathOperator>(V))
347 if (isa<FPMathOperator>(V))
348 cast<Instruction>(V)->setFastMathFlags(FMF);
407 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
408 AC(AC), ORE(ORE),
VF(VecWidth),
UF(UnrollFactor),
409 Builder(PSE.getSE()->getContext()),
446 bool IfPredicateInstr);
498 VPValue *BlockInMask =
nullptr);
568 Instruction::BinaryOpsEnd);
613 Value *VectorLoopValue,
615 unsigned Lane = UINT_MAX);
704 std::unique_ptr<LoopVersioning>
LVer;
789 UnrollFactor, LVL, CM) {}
795 Instruction::BinaryOpsEnd)
override;
812 if (
Instruction *OpInst = dyn_cast<Instruction>(*OI))
813 if (OpInst->getDebugLoc() !=
Empty)
821 if (
const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
823 if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
824 !isa<DbgInfoIntrinsic>(Inst)) {
830 <<
"Failed to create new discriminator: " 831 << DIL->getFilename() <<
" Line: " << DIL->getLine());
845 dbgs() <<
"LV: Not vectorizing: " << DebugMsg;
875 R <<
"loop not vectorized: ";
887 ORETag, TheLoop,
I) << OREMsg);
899 LoopDbgLoc.print(OS);
913 if (
LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
914 LVer->annotateInstWithNoAlias(To, Orig);
925 for (
Value *V : To) {
971 : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
972 TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
973 Hints(Hints), InterleaveInfo(IAI) {}
981 bool runtimeChecksRequired();
991 collectUniformsAndScalars(UserVF);
992 collectInstsToScalarize(UserVF);
998 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1004 unsigned selectInterleaveCount(
unsigned VF,
unsigned LoopCost);
1013 void setCostBasedWideningDecision(
unsigned VF);
1031 void collectValuesToIgnore();
1043 assert(VF > 1 &&
"Profitable to scalarize relevant only for VF > 1.");
1050 auto Scalars = InstsToScalarize.find(VF);
1051 assert(Scalars != InstsToScalarize.end() &&
1052 "VF not yet analyzed for scalarization profitability");
1053 return Scalars->second.find(I) != Scalars->second.end();
1066 auto UniformsPerVF = Uniforms.find(VF);
1067 assert(UniformsPerVF != Uniforms.end() &&
1068 "VF not yet analyzed for uniformity");
1069 return UniformsPerVF->second.find(I) != UniformsPerVF->second.end();
1082 auto ScalarsPerVF = Scalars.find(VF);
1083 assert(ScalarsPerVF != Scalars.end() &&
1084 "Scalar values are not calculated for VF");
1085 return ScalarsPerVF->second.find(I) != ScalarsPerVF->second.end();
1091 return VF > 1 && MinBWs.find(I) != MinBWs.end() &&
1092 !isProfitableToScalarize(I, VF) &&
1093 !isScalarAfterVectorization(I, VF);
1110 assert(VF >= 2 &&
"Expected VF >=2");
1111 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1118 assert(VF >= 2 &&
"Expected VF >=2");
1121 for (
unsigned i = 0; i < Grp->
getFactor(); ++i) {
1124 WideningDecisions[std::make_pair(
I, VF)] = std::make_pair(W, Cost);
1126 WideningDecisions[std::make_pair(
I, VF)] = std::make_pair(W, 0);
1135 assert(VF >= 2 &&
"Expected VF >=2");
1140 return CM_GatherScatter;
1142 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1143 auto Itr = WideningDecisions.find(InstOnVF);
1144 if (Itr == WideningDecisions.end())
1146 return Itr->second.first;
1152 assert(VF >= 2 &&
"Expected VF >=2");
1153 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1154 assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1155 "The cost is not calculated");
1156 return WideningDecisions[InstOnVF].second;
1177 Value *
Op = Trunc->getOperand(0);
1187 void collectInstsToScalarize(
unsigned VF);
1194 if (VF == 1 || Uniforms.find(VF) != Uniforms.end())
1196 setCostBasedWideningDecision(VF);
1197 collectLoopUniforms(VF);
1198 collectLoopScalars(VF);
1230 bool LI = isa<LoadInst>(V);
1231 bool SI = isa<StoreInst>(V);
1236 return (LI && isLegalMaskedGather(Ty, Align)) ||
1237 (SI && isLegalMaskedScatter(Ty, Align));
1245 bool isScalarWithPredication(
Instruction *
I,
unsigned VF = 1);
1251 if (!blockNeedsPredication(I->
getParent()))
1255 if (isa<LoadInst>(I) || isa<StoreInst>(
I))
1257 return isScalarWithPredication(I);
1262 bool memoryInstructionCanBeWidened(
Instruction *I,
unsigned VF = 1);
1267 bool interleavedAccessCanBeWidened(
Instruction *I,
unsigned VF = 1);
1271 return InterleaveInfo.isInterleaved(Instr);
1277 return InterleaveInfo.getInterleaveGroup(Instr);
1284 return isScalarEpilogueAllowed() && InterleaveInfo.requiresScalarEpilogue();
1303 unsigned getVectorIntrinsicCost(
CallInst *CI,
unsigned VF);
1310 unsigned getVectorCallCost(
CallInst *CI,
unsigned VF,
bool &NeedToScalarize);
1313 unsigned NumPredStores = 0;
1317 unsigned computeFeasibleMaxVF(
unsigned ConstTripCount);
1326 using VectorizationCostTy = std::pair<unsigned, bool>;
1332 VectorizationCostTy expectedCost(
unsigned VF);
1336 VectorizationCostTy getInstructionCost(
Instruction *I,
unsigned VF);
1340 unsigned getInstructionCost(
Instruction *I,
unsigned VF,
Type *&VectorTy);
1343 unsigned getMemoryInstructionCost(
Instruction *I,
unsigned VF);
1346 unsigned getMemInstScalarizationCost(
Instruction *I,
unsigned VF);
1349 unsigned getInterleaveGroupCost(
Instruction *I,
unsigned VF);
1352 unsigned getGatherScatterCost(
Instruction *I,
unsigned VF);
1356 unsigned getConsecutiveMemOpCost(
Instruction *I,
unsigned VF);
1362 unsigned getUniformMemOpCost(
Instruction *I,
unsigned VF);
1366 unsigned getScalarizationOverhead(
Instruction *I,
unsigned VF);
1400 bool FoldTailByMasking =
false;
1437 void collectLoopUniforms(
unsigned VF);
1444 void collectLoopScalars(
unsigned VF);
1449 std::pair<InstWidening, unsigned>>;
1455 bool needsExtract(
Value *V,
unsigned VF)
const {
1457 if (VF == 1 || !I || !TheLoop->contains(I) || TheLoop->isLoopInvariant(I))
1466 return Scalars.
find(VF) == Scalars.
end() ||
1467 !isScalarAfterVectorization(I, VF);
1474 Ops, [
this, VF](
Value *V) {
return this->needsExtract(V, VF); }));
1539 assert(!OuterLp->
empty() &&
"This is not an outer loop");
1548 if (!Hints.allowVectorization(Fn, OuterLp,
1550 LLVM_DEBUG(
dbgs() <<
"LV: Loop hints prevent outer loop vectorization.\n");
1554 if (Hints.getInterleave() > 1) {
1556 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Interleave is not supported for " 1558 Hints.emitRemarkWithHints();
1576 if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
1586 for (
Loop *InnerL : L)
1599 explicit LoopVectorize(
bool InterleaveOnlyWhenForced =
false,
1600 bool VectorizeOnlyWhenForced =
false)
1608 if (skipFunction(F))
1611 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1612 auto *
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1613 auto *
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1614 auto *
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1615 auto *
BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1616 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1617 auto *
TLI = TLIP ? &TLIP->getTLI(F) :
nullptr;
1618 auto *
AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1619 auto *
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1620 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
1621 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
1622 auto *
ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1623 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1625 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
1628 return Impl.
runImpl(F, *SE, *
LI, *
TTI, *
DT, *
BFI, TLI, *DB, *
AA, *
AC,
1687 assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
1688 "Expected either an induction phi-node or a truncate of it!");
1694 if (isa<TruncInst>(EntryVal)) {
1696 "Truncation requires an integer type");
1697 auto *TruncType = cast<IntegerType>(EntryVal->
getType());
1702 Value *SteppedStart =
1711 MulOp = Instruction::Mul;
1714 MulOp = Instruction::FMul;
1727 Value *SplatVF = isa<Constant>(Mul)
1738 for (
unsigned Part = 0; Part <
UF; ++Part) {
1741 if (isa<TruncInst>(EntryVal))
1753 auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
1754 auto *ICmp = cast<Instruction>(Br->getCondition());
1756 LastInduction->
setName(
"vec.ind.next");
1759 VecInd->
addIncoming(LastInduction, LoopVectorLatch);
1770 auto isScalarInst = [&](
User *U) ->
bool {
1771 auto *
I = cast<Instruction>(U);
1779 Value *VectorLoopVal,
unsigned Part,
unsigned Lane) {
1780 assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
1781 "Expected either an induction phi-node or a truncate of it!");
1789 if (isa<TruncInst>(EntryVal))
1799 if (Lane < UINT_MAX)
1807 "Primary induction variable must have an integer type");
1812 auto ID = II->second;
1813 assert(IV->
getType() == ID.getStartValue()->getType() &&
"Types must match");
1817 Value *ScalarIV =
nullptr;
1821 Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
1824 auto VectorizedIV =
false;
1834 "Induction step should be loop invariant");
1836 Value *Step =
nullptr;
1839 Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
1842 Step = cast<SCEVUnknown>(ID.getStep())->getValue();
1850 VectorizedIV =
true;
1858 if (!VectorizedIV || NeedsScalarIV) {
1866 ScalarIV->
setName(
"offset.idx");
1869 auto *TruncType = cast<IntegerType>(Trunc->
getType());
1871 "Truncation requires an integer step");
1880 if (!VectorizedIV) {
1882 for (
unsigned Part = 0; Part <
UF; ++Part) {
1910 "Induction Step must be an integer or FP");
1917 for (
int i = 0; i < VLen; ++i)
1924 assert(Step->getType() == Val->
getType() &&
"Invalid step vec");
1932 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
1933 "Binary Opcode should be specified for FP induction");
1935 for (
int i = 0; i < VLen; ++i)
1948 if (isa<Instruction>(MulOp))
1950 cast<Instruction>(MulOp)->setFastMathFlags(Flags);
1953 if (isa<Instruction>(BOp))
1954 cast<Instruction>(BOp)->setFastMathFlags(Flags);
1962 assert(
VF > 1 &&
"VF should be greater than one");
1967 "Val and Step should have the same type");
1975 MulOp = Instruction::Mul;
1978 MulOp = Instruction::FMul;
1988 for (
unsigned Part = 0; Part <
UF; ++Part) {
1989 for (
unsigned Lane = 0; Lane < Lanes; ++Lane) {
2000 assert(V !=
Induction &&
"The new induction variable should not be used.");
2020 auto *
I = cast<Instruction>(V);
2034 auto *LastInst = cast<Instruction>(
2049 Value *VectorValue =
nullptr;
2057 for (
unsigned Lane = 0; Lane <
VF; ++Lane)
2082 :
true &&
"Uniform values only have lane zero");
2095 if (!U->getType()->isVectorTy()) {
2096 assert(
VF == 1 &&
"Value not scalarized has non-vector type");
2108 assert(V !=
Induction &&
"The new induction variable should not be used.");
2122 for (
unsigned i = 0; i <
VF; ++i)
2175 assert(Group &&
"Fail to get an interleaved access group.");
2185 unsigned InterleaveFactor = Group->
getFactor();
2194 "Reversed masked interleave-group not supported.");
2205 for (
unsigned Part = 0; Part <
UF; Part++) {
2206 Value *AddrPart = State.
get(Addr, {Part, 0});
2221 bool InBounds =
false;
2223 InBounds =
gep->isInBounds();
2225 cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2236 Value *MaskForGaps =
nullptr;
2239 assert(MaskForGaps &&
"Mask for Gaps is required but it is null");
2243 if (isa<LoadInst>(Instr)) {
2246 for (
unsigned Part = 0; Part <
UF; Part++) {
2248 if (BlockInMask || MaskForGaps) {
2250 "masked interleaved groups are not allowed.");
2251 Value *GroupMask = MaskForGaps;
2253 Value *BlockInMaskPart = State.
get(BlockInMask, Part);
2257 BlockInMaskPart, Undefs, RepMask,
"interleaved.mask");
2258 GroupMask = MaskForGaps
2265 GroupMask, UndefVec,
"wide.masked.vec");
2276 for (
unsigned I = 0;
I < InterleaveFactor; ++
I) {
2284 for (
unsigned Part = 0; Part <
UF; Part++) {
2286 NewLoads[Part], UndefVec, StrideMask,
"strided.vec");
2289 if (Member->
getType() != ScalarTy) {
2307 for (
unsigned Part = 0; Part <
UF; Part++) {
2310 for (
unsigned i = 0; i < InterleaveFactor; i++) {
2313 assert(Member &&
"Fail to get a member from an interleaved store group");
2316 cast<StoreInst>(Member)->getValueOperand(), Part);
2322 if (StoredVec->
getType() != SubVT)
2338 Value *BlockInMaskPart = State.
get(BlockInMask, Part);
2342 BlockInMaskPart, Undefs, RepMask,
"interleaved.mask");
2344 IVec, AddrParts[Part], Group->
getAlignment(), ShuffledMask);
2362 assert((LI || SI) &&
"Invalid Load/Store instruction");
2367 "CM decision should be taken at this point");
2376 const Align Alignment =
2382 bool ConsecutiveStride =
2384 bool CreateGatherScatter =
2389 assert((ConsecutiveStride || CreateGatherScatter) &&
2390 "The instruction should be scalarized");
2391 (void)ConsecutiveStride;
2394 bool isMaskRequired = BlockInMask;
2396 for (
unsigned Part = 0; Part <
UF; ++Part)
2397 BlockInMaskParts[Part] = State.
get(BlockInMask, Part);
2399 const auto CreateVecPtr = [&](
unsigned Part,
Value *Ptr) ->
Value * {
2403 bool InBounds =
false;
2404 if (
auto *
gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2405 InBounds =
gep->isInBounds();
2410 PartPtr = cast<GetElementPtrInst>(
2413 PartPtr = cast<GetElementPtrInst>(
2417 BlockInMaskParts[Part] =
reverseVector(BlockInMaskParts[Part]);
2419 PartPtr = cast<GetElementPtrInst>(
2424 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2432 for (
unsigned Part = 0; Part <
UF; ++Part) {
2435 if (CreateGatherScatter) {
2436 Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] :
nullptr;
2437 Value *VectorGep = State.
get(Addr, Part);
2439 Alignment.
value(), MaskPart);
2448 auto *VecPtr = CreateVecPtr(Part, State.
get(Addr, {0, 0}));
2451 StoredVal, VecPtr, Alignment.
value(), BlockInMaskParts[Part]);
2462 assert(LI &&
"Must have a load instruction");
2464 for (
unsigned Part = 0; Part <
UF; ++Part) {
2466 if (CreateGatherScatter) {
2467 Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] :
nullptr;
2468 Value *VectorGep = State.
get(Addr, Part);
2470 nullptr,
"wide.masked.gather");
2473 auto *VecPtr = CreateVecPtr(Part, State.
get(Addr, {0, 0}));
2476 VecPtr, Alignment.
value(), BlockInMaskParts[Part],
2493 bool IfPredicateInstr) {
2520 if (
auto *II = dyn_cast<IntrinsicInst>(Cloned))
2521 if (II->getIntrinsicID() == Intrinsic::assume)
2525 if (IfPredicateInstr)
2565 assert(L &&
"Create Trip Count for null loop.");
2570 assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
2571 "Invalid loop count");
2574 assert(IdxTy &&
"No type for induction");
2582 IdxTy->getPrimitiveSizeInBits())
2583 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2584 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2587 const SCEV *ExitCount = SE->getAddExpr(
2588 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->
getType()));
2626 "VF*UF must be a power of 2 when folding tail by masking");
2663 "Vector elements must have same size");
2674 "Only one type should be a pointer type");
2676 "Only one type should be a floating point type");
2714 "TC check is expected to dominate Bypass");
2736 Value *SCEVCheck = Exp.expandCodeForPredicate(
2739 if (
auto *
C = dyn_cast<ConstantInt>(SCEVCheck))
2744 "Cannot SCEV check stride or overflow when optimizing for size");
2746 SCEVCheckBlock->
setName(
"vector.scevcheck");
2750 nullptr,
"vector.ph");
2779 std::tie(FirstCheckInst, MemRuntimeCheck) =
2781 if (!MemRuntimeCheck)
2786 "Cannot emit memory checks when optimizing for size, unless forced " 2791 <<
"Code-size may be reduced by not forcing " 2792 "vectorization, or by source-code modifications " 2793 "eliminating the need for runtime checks " 2794 "(e.g., adding 'restrict').";
2798 MemCheckBlock->
setName(
"vector.memcheck");
2820 LVer->prepareNoAliasMetadata();
2831 "Index type does not match StepValue type");
2841 if (
auto *CX = dyn_cast<ConstantInt>(X))
2844 if (
auto *CY = dyn_cast<ConstantInt>(
Y))
2852 if (
auto *CX = dyn_cast<ConstantInt>(X))
2855 if (
auto *CY = dyn_cast<ConstantInt>(
Y))
2864 "Index type does not match StartValue type");
2872 assert(isa<SCEVConstant>(Step) &&
2873 "Expected constant step for pointer induction");
2875 StartValue->getType()->getPointerElementType(), StartValue,
2880 assert(Step->getType()->isFloatingPointTy() &&
"Expected FP Step value");
2883 (InductionBinOp->getOpcode() == Instruction::FAdd ||
2884 InductionBinOp->getOpcode() == Instruction::FSub) &&
2885 "Original bin op should be defined for FP induction");
2887 Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
2894 if (isa<Instruction>(MulExp))
2896 cast<Instruction>(MulExp)->setFastMathFlags(Flags);
2898 Value *BOp = B.
CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2900 if (isa<Instruction>(BOp))
2901 cast<Instruction>(BOp)->setFastMathFlags(Flags);
2969 LI,
nullptr,
"middle.block");
2972 nullptr,
"scalar.ph");
2978 nullptr,
nullptr,
"vector.body");
2984 Loop *Lp = LI->AllocateLoop();
2992 LI->addTopLevelLoop(Lp);
3038 for (
auto &InductionEntry : *List) {
3039 PHINode *OrigPhi = InductionEntry.first;
3045 LoopScalarPreHeader->getTerminator());
3051 EndValue = CountRoundDown;
3057 Value *CRD =
B.CreateCast(CastOp, CountRoundDown, StepType,
"cast.crd");
3080 "Scalar loop latch terminator isn't a branch");
3091 CountRoundDown,
"cmp.n",
3098 cast<Instruction>(CmpN)->setDebugLoc(ScalarLatchBr->
getDebugLoc());
3103 BrInst->setDebugLoc(ScalarLatchBr->
getDebugLoc());
3108 "Inconsistent vector loop preheader");
3113 LLVMLoopVectorizeFollowupVectorized});
3130 #ifdef EXPENSIVE_CHECKS 3161 assert(isa<PHINode>(UI) &&
"Expected LCSSA form");
3162 MissingVals[UI] = EndValue;
3170 auto *UI = cast<Instruction>(U);
3174 assert(isa<PHINode>(UI) &&
"Expected LCSSA form");
3177 Value *CountMinusOne =
B.CreateSub(
3181 ?
B.CreateCast(Instruction::SIToFP, CountMinusOne,
3186 Escape->
setName(
"ind.escape");
3187 MissingVals[UI] = Escape;
3191 for (
auto &
I : MissingVals) {
3192 PHINode *PHI = cast<PHINode>(
I.first);
3205 struct CSEDenseMapInfo {
3207 return isa<InsertElementInst>(
I) || isa<ExtractElementInst>(I) ||
3208 isa<ShuffleVectorInst>(
I) || isa<GetElementPtrInst>(I);
3219 static unsigned getHashValue(
const Instruction *I) {
3220 assert(canHandle(I) &&
"Unknown instruction!");
3226 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3227 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3242 if (!CSEDenseMapInfo::canHandle(In))
3259 bool &NeedToScalarize) {
3273 return ScalarCallCost;
3277 for (
Type *ScalarTy : ScalarTys)
3282 unsigned ScalarizationCost = getScalarizationOverhead(CI, VF);
3284 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3288 NeedToScalarize =
true;
3294 if (VectorCallCost < Cost) {
3295 NeedToScalarize =
false;
3296 return VectorCallCost;
3304 assert(ID &&
"Expected intrinsic call!");
3307 if (
auto *FPMO = dyn_cast<FPMathOperator>(CI))
3308 FMF = FPMO->getFastMathFlags();
3317 return I1->getBitWidth() < I2->getBitWidth() ?
T1 : T2;
3322 return I1->getBitWidth() > I2->getBitWidth() ?
T1 : T2;
3336 for (
unsigned Part = 0; Part <
UF; ++Part) {
3339 !isa<Instruction>(
I))
3342 Type *ScalarTruncatedTy =
3346 if (TruncatedTy == OriginalTy)
3350 auto ShrinkOperand = [&](
Value *V) ->
Value * {
3351 if (
auto *ZI = dyn_cast<ZExtInst>(V))
3352 if (ZI->getSrcTy() == TruncatedTy)
3353 return ZI->getOperand(0);
3359 Value *NewI =
nullptr;
3360 if (
auto *BO = dyn_cast<BinaryOperator>(I)) {
3361 NewI = B.
CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3362 ShrinkOperand(BO->getOperand(1)));
3367 cast<BinaryOperator>(NewI)->copyIRFlags(I,
false);
3368 }
else if (
auto *CI = dyn_cast<ICmpInst>(I)) {
3370 B.
CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3371 ShrinkOperand(CI->getOperand(1)));
3372 }
else if (
auto *
SI = dyn_cast<SelectInst>(I)) {
3374 ShrinkOperand(
SI->getTrueValue()),
3375 ShrinkOperand(
SI->getFalseValue()));
3376 }
else if (
auto *CI = dyn_cast<CastInst>(I)) {
3377 switch (CI->getOpcode()) {
3380 case Instruction::Trunc:
3381 NewI = ShrinkOperand(CI->getOperand(0));
3383 case Instruction::SExt:
3388 case Instruction::ZExt:
3394 }
else if (
auto *
SI = dyn_cast<ShuffleVectorInst>(I)) {
3395 auto Elements0 =
SI->getOperand(0)->getType()->getVectorNumElements();
3398 auto Elements1 =
SI->getOperand(1)->getType()->getVectorNumElements();
3403 }
else if (isa<LoadInst>(I) || isa<PHINode>(
I)) {
3406 }
else if (
auto *
IE = dyn_cast<InsertElementInst>(I)) {
3407 auto Elements =
IE->getOperand(0)->getType()->getVectorNumElements();
3412 }
else if (
auto *EE = dyn_cast<ExtractElementInst>(I)) {
3423 NewI->
takeName(cast<Instruction>(I));
3426 cast<Instruction>(
I)->eraseFromParent();
3439 for (
unsigned Part = 0; Part <
UF; ++Part) {
3460 "Unexpected non-induction PHIs for fixup in non VPlan-native path");
3562 auto *VectorInit = ScalarInit;
3577 auto *VecPhi =
Builder.
CreatePHI(VectorInit->getType(), 2,
"vector.recur");
3594 Instruction *PreviousInst = cast<Instruction>(PreviousLastPart);
3595 if (isa<PHINode>(PreviousLastPart))
3610 for (
unsigned I = 1;
I <
VF; ++
I)
3615 Value *Incoming = VecPhi;
3618 for (
unsigned Part = 0; Part <
UF; ++Part) {
3626 cast<Instruction>(PhiPart)->eraseFromParent();
3628 Incoming = PreviousPart;
3636 auto *ExtractForScalar = Incoming;
3647 Value *ExtractForPhiUsedOutsideLoop =
nullptr;
3662 auto *Incoming = BB ==
LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3663 Start->addIncoming(Incoming, BB);
3675 if (LCSSAPhi.getIncomingValue(0) == Phi) {
3686 "Unable to find the reduction variable");
3691 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3693 RdxDesc.getMinMaxRecurrenceKind();
3713 VectorStart = Identity = ReductionStartValue;
3715 VectorStart = Identity =
3726 VectorStart = ReductionStartValue;
3747 for (
unsigned Part = 0; Part <
UF; ++Part) {
3752 Value *StartVal = (Part == 0) ? VectorStart : Identity;
3754 cast<PHINode>(VecRdxPhi)
3770 for (
unsigned Part = 0; Part <
UF; ++Part) {
3771 Value *VecLoopExitInst =
3773 Value *Sel =
nullptr;
3774 for (
User *U : VecLoopExitInst->
users()) {
3775 if (isa<SelectInst>(U)) {
3776 assert(!Sel &&
"Reduction exit feeding two selects");
3779 assert(isa<PHINode>(U) &&
"Reduction exit must feed Phi's or select");
3781 assert(Sel &&
"Reduction exit feeds no select");
3789 if (
VF > 1 && Phi->
getType() != RdxDesc.getRecurrenceType()) {
3794 for (
unsigned Part = 0; Part <
UF; ++Part) {
3800 UI != RdxParts[Part]->user_end();)
3802 (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
3803 RdxParts[Part] = Extnd;
3809 for (
unsigned Part = 0; Part <
UF; ++Part) {
3827 for (
unsigned Part = 1; Part <
UF; ++Part) {
3829 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3833 ReducedPartRdx,
"bin.rdx"),
3834 RdxDesc.getFastMathFlags());
3846 if (Phi->
getType() != RdxDesc.getRecurrenceType())
3868 assert(LCSSAPhi.getNumIncomingValues() < 3 &&
"Invalid LCSSA PHI");
3872 if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
3878 int IncomingEdgeBlockIdx =
3880 assert(IncomingEdgeBlockIdx >= 0 &&
"Invalid block index");
3882 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3895 assert(LoopExitInstr &&
"null loop exit instruction");
3899 Visited.
insert(LoopExitInstr);
3901 while (!Worklist.
empty()) {
3903 if (isa<OverflowingBinaryOperator>(Cur))
3904 for (
unsigned Part = 0; Part <
UF; ++Part) {
3906 cast<Instruction>(V)->dropPoisonGeneratingFlags();
3912 Visited.
insert(UI).second)
3920 if (LCSSAPhi.getNumIncomingValues() == 1) {
3921 auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
3923 unsigned LastLane = 0;
3924 if (isa<Instruction>(IncomingValue))
3926 cast<Instruction>(IncomingValue),
VF)
3932 Value *lastIncomingValue =
3953 auto isBlockOfUsePredicated = [&](
Use &U) ->
bool {
3954 auto *
I = cast<Instruction>(U.getUser());
3956 if (
auto *Phi = dyn_cast<PHINode>(
I))
3957 BB = Phi->getIncomingBlock(
3959 return BB == PredBB;
3970 Worklist.insert(InstsToReanalyze.
begin(), InstsToReanalyze.
end());
3971 InstsToReanalyze.
clear();
3974 while (!Worklist.empty()) {
3979 if (!
I || isa<PHINode>(
I) ||
I->getParent() == PredBB ||
3980 !VectorLoop->contains(
I) ||
I->mayHaveSideEffects())
3987 InstsToReanalyze.push_back(
I);
3993 I->moveBefore(&*PredBB->getFirstInsertionPt());
3994 Worklist.insert(
I->op_begin(),
I->op_end());
4013 assert(ScalarBBPredecessors.
size() == VectorBBPredecessors.
size() &&
4014 "Scalar and Vector BB should have the same number of predecessors");
4024 for (
unsigned i = 0; i < NumIncomingValues; ++i) {
4025 BasicBlock *NewPredBB = VectorBBPredecessors[i];
4030 OrigPhi->getIncomingValueForBlock(ScalarBBPredecessors[i]);
4040 unsigned VF,
bool IsPtrLoopInvariant,
4048 if (VF > 1 && IsPtrLoopInvariant && IsIndexLoopInvariant.
all()) {
4062 for (
unsigned Part = 0; Part <
UF; ++Part) {
4075 for (
unsigned Part = 0; Part <
UF; ++Part) {
4078 auto *Ptr = IsPtrLoopInvariant
4087 if (IsIndexLoopInvariant[
Index.index()])
4088 Indices.push_back(User);
4100 assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
4101 "NewGEP is not a pointer vector");
4126 "Non-header phis should have been handled elsewhere");
4133 for (
unsigned Part = 0; Part <
UF; ++Part) {
4155 switch (II.getKind()) {
4173 for (
unsigned Part = 0; Part <
UF; ++Part) {
4174 for (
unsigned Lane = 0; Lane < Lanes; ++Lane) {
4200 "Unexpected instruction");
4203 return !CInt || CInt->
isZero();
4208 case Instruction::Br:
4209 case Instruction::PHI:
4210 case Instruction::GetElementPtr:
4212 case Instruction::UDiv:
4213 case Instruction::SDiv:
4214 case Instruction::SRem:
4215 case Instruction::URem:
4217 case Instruction::FAdd:
4218 case Instruction::Sub:
4219 case Instruction::FSub:
4220 case Instruction::FNeg:
4221 case Instruction::Mul:
4222 case Instruction::FMul:
4223 case Instruction::FDiv:
4224 case Instruction::FRem:
4225 case Instruction::Shl:
4226 case Instruction::LShr:
4227 case Instruction::AShr:
4228 case Instruction::And:
4229 case Instruction::Or:
4230 case Instruction::Xor: {
4234 for (
unsigned Part = 0; Part <
UF; ++Part) {
4241 if (
auto *VecOp = dyn_cast<Instruction>(V))
4242 VecOp->copyIRFlags(&I);
4256 bool InvariantCond =
4267 for (
unsigned Part = 0; Part <
UF; ++Part) {
4280 case Instruction::ICmp:
4281 case Instruction::FCmp: {
4283 bool FCmp = (I.
getOpcode() == Instruction::FCmp);
4284 auto *Cmp = cast<CmpInst>(&
I);
4286 for (
unsigned Part = 0; Part <
UF; ++Part) {
4305 case Instruction::ZExt:
4306 case Instruction::SExt:
4307 case Instruction::FPToUI:
4308 case Instruction::FPToSI:
4309 case Instruction::FPExt:
4310 case Instruction::PtrToInt:
4311 case Instruction::IntToPtr:
4312 case Instruction::SIToFP:
4313 case Instruction::UIToFP:
4314 case Instruction::Trunc:
4315 case Instruction::FPTrunc:
4316 case Instruction::BitCast: {
4317 auto *CI = cast<CastInst>(&
I);
4324 for (
unsigned Part = 0; Part <
UF; ++Part) {
4335 if (isa<DbgInfoIntrinsic>(I))
4340 auto *CI = cast<CallInst>(&
I);
4342 StringRef FnName = CI->getCalledFunction()->getName();
4346 for (
Value *ArgOperand : CI->arg_operands())
4354 bool NeedToScalarize;
4356 bool UseVectorIntrinsic =
4358 assert((UseVectorIntrinsic || !NeedToScalarize) &&
4359 "Instruction should be scalarized elsewhere.");
4361 for (
unsigned Part = 0; Part <
UF; ++Part) {
4363 for (
unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4373 if (UseVectorIntrinsic) {
4375 Type *TysForDecl[] = {CI->getType()};
4382 assert(!VFnName.
empty() &&
"Vector function name is empty.");
4389 VectorF->copyAttributesFrom(F);
4392 assert(VectorF &&
"Can't create vector function.");
4395 CI->getOperandBundlesAsDefs(OpBundles);
4398 if (isa<FPMathOperator>(V))
4410 LLVM_DEBUG(
dbgs() <<
"LV: Found an unhandled instruction: " << I);
4415 void LoopVectorizationCostModel::collectLoopScalars(
unsigned VF) {
4419 assert(VF >= 2 && Scalars.find(VF) == Scalars.end() &&
4420 "This function should not be visited twice for the same VF");
4434 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4435 assert(WideningDecision != CM_Unknown &&
4436 "Widening decision should be ready at this moment");
4437 if (
auto *
Store = dyn_cast<StoreInst>(MemAccess))
4438 if (Ptr ==
Store->getValueOperand())
4439 return WideningDecision == CM_Scalarize;
4441 "Ptr is neither a value or pointer operand");
4442 return WideningDecision != CM_GatherScatter;
4447 auto isLoopVaryingBitCastOrGEP = [&](
Value *V) {
4448 return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4449 isa<GetElementPtrInst>(V)) &&
4450 !TheLoop->isLoopInvariant(V);
4460 if (!isLoopVaryingBitCastOrGEP(Ptr))
4465 auto *
I = cast<Instruction>(Ptr);
4466 if (Worklist.count(
I))
4473 return isa<LoadInst>(U) || isa<StoreInst>(U);
4477 PossibleNonScalarPtrs.
insert(
I);
4488 Worklist.insert(Uniforms[VF].
begin(), Uniforms[VF].
end());
4495 for (
auto *BB : TheLoop->blocks())
4496 for (
auto &
I : *BB) {
4497 if (
auto *
Load = dyn_cast<LoadInst>(&
I)) {
4498 evaluatePtrUse(
Load,
Load->getPointerOperand());
4499 }
else if (
auto *
Store = dyn_cast<StoreInst>(&
I)) {
4500 evaluatePtrUse(
Store,
Store->getPointerOperand());
4501 evaluatePtrUse(
Store,
Store->getValueOperand());
4504 for (
auto *
I : ScalarPtrs)
4505 if (PossibleNonScalarPtrs.
find(
I) == PossibleNonScalarPtrs.
end()) {
4515 auto *Latch = TheLoop->getLoopLatch();
4518 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4521 Worklist.insert(Ind);
4522 Worklist.insert(IndUpdate);
4523 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Ind <<
"\n");
4524 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *IndUpdate
4531 auto ForcedScalar = ForcedScalars.find(VF);
4532 if (ForcedScalar != ForcedScalars.end())
4533 for (
auto *
I : ForcedScalar->second)
4541 while (Idx != Worklist.size()) {
4543 if (!isLoopVaryingBitCastOrGEP(Dst->
getOperand(0)))
4545 auto *Src = cast<Instruction>(Dst->
getOperand(0));
4547 auto *J = cast<Instruction>(U);
4548 return !TheLoop->contains(J) || Worklist.count(J) ||
4549 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4550 isScalarUse(J, Src));
4552 Worklist.insert(Src);
4553 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Src <<
"\n");
4561 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4574 auto *
I = cast<Instruction>(U);
4575 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
4582 auto ScalarIndUpdate =
4584 auto *
I = cast<Instruction>(U);
4585 return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
4587 if (!ScalarIndUpdate)
4591 Worklist.insert(Ind);
4592 Worklist.insert(IndUpdate);
4593 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Ind <<
"\n");
4594 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *IndUpdate
4598 Scalars[
VF].insert(Worklist.begin(), Worklist.end());
4602 if (!blockNeedsPredication(I->
getParent()))
4616 InstWidening WideningDecision = getWideningDecision(I, VF);
4617 assert(WideningDecision != CM_Unknown &&
4618 "Widening decision should be ready at this moment");
4619 return WideningDecision == CM_Scalarize;
4622 return isa<LoadInst>(
I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4623 isLegalMaskedGather(Ty, Alignment))
4624 : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4625 isLegalMaskedScatter(Ty, Alignment));
4627 case Instruction::UDiv:
4628 case Instruction::SDiv:
4629 case Instruction::SRem:
4630 case Instruction::URem:
4638 assert(isAccessInterleaved(I) &&
"Expecting interleaved access.");
4639 assert(getWideningDecision(I, VF) == CM_Unknown &&
4640 "Decision should not be set yet.");
4641 auto *Group = getInterleavedAccessGroup(I);
4642 assert(Group &&
"Must have a group.");
4654 bool PredicatedAccessRequiresMasking =
4656 bool AccessWithGapsRequiresMasking =
4657 Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
4658 if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
4665 "Masked interleave-groups for predicated accesses are not enabled.");
4678 assert((LI || SI) &&
"Invalid memory instruction");
4688 if (isScalarWithPredication(I))
4694 auto *ScalarTy = LI ? LI->
getType() : SI->getValueOperand()->getType();
4701 void LoopVectorizationCostModel::collectLoopUniforms(
unsigned VF) {
4707 assert(VF >= 2 && Uniforms.find(VF) == Uniforms.end() &&
4708 "This function should not be visited twice for the same VF");
4712 Uniforms[
VF].clear();
4720 auto isOutOfScope = [&](
Value *V) ->
bool {
4722 return (!I || !TheLoop->contains(I));
4732 auto addToWorklistIfAllowed = [&](
Instruction *
I) ->
void {
4733 if (isScalarWithPredication(
I, VF)) {
4734 LLVM_DEBUG(
dbgs() <<
"LV: Found not uniform being ScalarWithPredication: " 4738 LLVM_DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *
I <<
"\n");
4746 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
4747 addToWorklistIfAllowed(Cmp);
4759 InstWidening WideningDecision = getWideningDecision(I, VF);
4760 assert(WideningDecision != CM_Unknown &&
4761 "Widening decision should be ready at this moment");
4763 return (WideningDecision == CM_Widen ||
4764 WideningDecision == CM_Widen_Reverse ||
4765 WideningDecision == CM_Interleave);
4775 for (
auto *BB : TheLoop->blocks())
4776 for (
auto &I : *BB) {
4784 auto UsersAreMemAccesses =
4793 if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
4794 PossibleNonUniformPtrs.
insert(Ptr);
4800 ConsecutiveLikePtrs.
insert(Ptr);
4805 for (
auto *V : ConsecutiveLikePtrs)
4806 if (PossibleNonUniformPtrs.
find(V) == PossibleNonUniformPtrs.
end())
4807 addToWorklistIfAllowed(V);
4813 while (idx != Worklist.
size()) {
4818 if (isOutOfScope(OV))
4827 auto *OI = cast<Instruction>(OV);
4829 auto *J = cast<Instruction>(U);
4830 return Worklist.
count(J) ||
4832 isUniformDecision(J, VF));
4834 addToWorklistIfAllowed(OI);
4852 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4857 auto *I = cast<Instruction>(U);
4858 return I == IndUpdate || !TheLoop->contains(I) || Worklist.
count(I) ||
4859 isVectorizedMemAccessUse(I, Ind);
4866 auto UniformIndUpdate =
4868 auto *I = cast<Instruction>(U);
4869 return I == Ind || !TheLoop->contains(I) || Worklist.
count(I) ||
4870 isVectorizedMemAccessUse(I, IndUpdate);
4872 if (!UniformIndUpdate)
4876 addToWorklistIfAllowed(Ind);
4877 addToWorklistIfAllowed(IndUpdate);
4880 Uniforms[
VF].insert(Worklist.
begin(), Worklist.
end());
4888 "runtime pointer checks needed. Enable vectorization of this " 4889 "loop with '#pragma clang loop vectorize(enable)' when " 4890 "compiling with -Os/-Oz",
4891 "CantVersionLoopWithOptForSize",
ORE, TheLoop);
4897 "runtime SCEV checks needed. Enable vectorization of this " 4898 "loop with '#pragma clang loop vectorize(enable)' when " 4899 "compiling with -Os/-Oz",
4900 "CantVersionLoopWithOptForSize",
ORE, TheLoop);
4907 "runtime stride == 1 checks needed. Enable vectorization of " 4908 "this loop with '#pragma clang loop vectorize(enable)' when " 4909 "compiling with -Os/-Oz",
4910 "CantVersionLoopWithOptForSize",
ORE, TheLoop);
4922 "Not inserting runtime ptr check for divergent target",
4923 "runtime pointer checks needed. Not enabled for divergent target",
4924 "CantVersionLoopWithDivergentTarget",
ORE, TheLoop);
4932 "loop trip count is one, irrelevant for vectorization",
4933 "SingleIterationLoop",
ORE, TheLoop);
4937 switch (ScalarEpilogueStatus) {
4939 return computeFeasibleMaxVF(TC);
4942 dbgs() <<
"LV: vector predicate hint/switch found.\n" 4943 <<
"LV: Not allowing scalar epilogue, creating predicated " 4944 <<
"vector loop.\n");
4951 dbgs() <<
"LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
4953 LLVM_DEBUG(
dbgs() <<
"LV: Not allowing scalar epilogue due to low trip " 4958 if (runtimeChecksRequired())
4968 InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
4970 unsigned MaxVF = computeFeasibleMaxVF(TC);
4971 if (TC > 0 && TC % MaxVF == 0) {
4973 LLVM_DEBUG(
dbgs() <<
"LV: No tail will remain for any chosen VF.\n");
4982 FoldTailByMasking =
true;
4988 "Unable to calculate the loop count due to complex control flow",
4989 "unable to calculate the loop count due to complex control flow",
4990 "UnknownLoopCountComplexCFG",
ORE, TheLoop);
4995 "Cannot optimize for size and vectorize at the same time.",
4996 "cannot optimize for size and vectorize at the same time. " 4997 "Enable vectorization of this loop with '#pragma clang loop " 4998 "vectorize(enable)' when compiling with -Os/-Oz",
4999 "NoTailLoopWithOptForSize",
ORE, TheLoop);
5004 LoopVectorizationCostModel::computeFeasibleMaxVF(
unsigned ConstTripCount) {
5006 unsigned SmallestType, WidestType;
5007 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5016 WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
5018 unsigned MaxVectorSize = WidestRegister / WidestType;
5020 LLVM_DEBUG(
dbgs() <<
"LV: The Smallest and Widest types: " << SmallestType
5021 <<
" / " << WidestType <<
" bits.\n");
5023 << WidestRegister <<
" bits.\n");
5025 assert(MaxVectorSize <= 256 &&
"Did not expect to pack so many elements" 5026 " into one vector!");
5027 if (MaxVectorSize == 0) {
5028 LLVM_DEBUG(
dbgs() <<
"LV: The target has no vector registers.\n");
5030 return MaxVectorSize;
5031 }
else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
5035 LLVM_DEBUG(
dbgs() <<
"LV: Clamping the MaxVF to the constant trip count: " 5036 << ConstTripCount <<
"\n");
5037 MaxVectorSize = ConstTripCount;
5038 return MaxVectorSize;
5041 unsigned MaxVF = MaxVectorSize;
5047 unsigned NewMaxVectorSize = WidestRegister / SmallestType;
5048 for (
unsigned VS = MaxVectorSize * 2;
VS <= NewMaxVectorSize;
VS *= 2)
5052 auto RUs = calculateRegisterUsage(VFs);
5056 for (
int i = RUs.size() - 1; i >= 0; --i) {
5057 bool Selected =
true;
5058 for (
auto& pair : RUs[i].MaxLocalUsers) {
5060 if (pair.second > TargetNumRegisters)
5069 if (MaxVF < MinVF) {
5071 <<
") with target's minimum: " << MinVF <<
'\n');
5081 float Cost = expectedCost(1).first;
5082 const float ScalarCost =
Cost;
5084 LLVM_DEBUG(
dbgs() <<
"LV: Scalar loop costs: " << (
int)ScalarCost <<
".\n");
5087 if (ForceVectorization && MaxVF > 1) {
5094 for (
unsigned i = 2; i <= MaxVF; i *= 2) {
5098 VectorizationCostTy
C = expectedCost(i);
5099 float VectorCost = C.first / (float)i;
5101 <<
" costs: " << (
int)VectorCost <<
".\n");
5102 if (!C.second && !ForceVectorization) {
5104 dbgs() <<
"LV: Not considering vector loop of width " << i
5105 <<
" because it will not generate any vector instructions.\n");
5108 if (VectorCost < Cost) {
5116 "store that is conditionally executed prevents vectorization",
5117 "ConditionalStore",
ORE, TheLoop);
5122 LLVM_DEBUG(
if (ForceVectorization && Width > 1 && Cost >= ScalarCost)
dbgs()
5123 <<
"LV: Vectorization seems to be not beneficial, " 5124 <<
"but was forced by a user.\n");
5130 std::pair<unsigned, unsigned>
5132 unsigned MinWidth = -1U;
5133 unsigned MaxWidth = 8;
5134 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5139 for (
Instruction &
I : BB->instructionsWithoutDebug()) {
5143 if (ValuesToIgnore.find(&
I) != ValuesToIgnore.end())
5147 if (!isa<LoadInst>(
I) && !isa<StoreInst>(
I) && !isa<PHINode>(
I))
5152 if (
auto *PN = dyn_cast<PHINode>(&
I)) {
5160 if (
auto *
ST = dyn_cast<StoreInst>(&
I))
5161 T =
ST->getValueOperand()->getType();
5172 if (T->
isPointerTy() && !isConsecutiveLoadOrStore(&
I) &&
5173 !isAccessInterleaved(&
I) && !isLegalGatherOrScatter(&
I))
5176 MinWidth = std::min(MinWidth,
5183 return {MinWidth, MaxWidth};
5187 unsigned LoopCost) {
5202 if (!isScalarEpilogueAllowed())
5219 pair.second =
std::max(pair.second, 1U);
5233 unsigned IC = UINT_MAX;
5247 unsigned MaxLocalUsers = pair.second;
5248 unsigned LoopInvariantRegs = 0;
5252 unsigned TmpIC =
PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
5256 PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
5257 std::max(1U, (MaxLocalUsers - 1)));
5260 IC = std::min(IC, TmpIC);
5278 MaxInterleaveCount = std::min(*BestKnownTC / VF, MaxInterleaveCount);
5284 LoopCost = expectedCost(VF).first;
5286 assert(LoopCost &&
"Non-zero loop cost expected");
5290 if (IC > MaxInterleaveCount)
5291 IC = MaxInterleaveCount;
5298 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving because of reductions.\n");
5304 bool InterleavingRequiresRuntimePointerCheck =
5310 if (!InterleavingRequiresRuntimePointerCheck && LoopCost <
SmallLoopCost) {
5321 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5322 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5330 SmallIC = std::min(SmallIC, F);
5331 StoresIC = std::min(StoresIC, F);
5332 LoadsIC = std::min(LoadsIC, F);
5336 std::max(StoresIC, LoadsIC) > SmallIC) {
5338 dbgs() <<
"LV: Interleaving to saturate store or load ports.\n");
5339 return std::max(StoresIC, LoadsIC);
5342 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving to reduce branch cost.\n");
5398 for (
Instruction &
I : BB->instructionsWithoutDebug()) {
5402 for (
Value *U :
I.operands()) {
5410 if (!TheLoop->contains(Instr)) {
5411 LoopInvariants.
insert(Instr);
5416 EndPoint[Instr] = IdxToInstr.
size();
5433 unsigned MaxSafeDepDist = -1U;
5436 unsigned WidestRegister =
5438 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5443 LLVM_DEBUG(
dbgs() <<
"LV(REG): Calculating max register usage:\n");
5446 auto GetRegUsage = [&DL, WidestRegister](
Type *Ty,
unsigned VF) {
5447 if (Ty->isTokenTy())
5449 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
5450 return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
5453 for (
unsigned int i = 0, s = IdxToInstr.
size(); i < s; ++i) {
5457 InstrList &
List = TransposeEnds[i];
5459 OpenIntervals.
erase(ToRemove);
5462 if (Ends.
find(I) == Ends.
end())
5466 if (ValuesToIgnore.find(I) != ValuesToIgnore.end())
5470 for (
unsigned j = 0,
e = VFs.
size(); j <
e; ++j) {
5475 for (
auto Inst : OpenIntervals) {
5477 if (RegUsage.
find(ClassID) == RegUsage.
end())
5478 RegUsage[ClassID] = 1;
5480 RegUsage[ClassID] += 1;
5483 collectUniformsAndScalars(VFs[j]);
5484 for (
auto Inst : OpenIntervals) {
5486 if (VecValuesToIgnore.find(Inst) != VecValuesToIgnore.end())
5488 if (isScalarAfterVectorization(Inst, VFs[j])) {
5490 if (RegUsage.
find(ClassID) == RegUsage.
end())
5491 RegUsage[ClassID] = 1;
5493 RegUsage[ClassID] += 1;
5496 if (RegUsage.
find(ClassID) == RegUsage.
end())
5497 RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
5499 RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
5504 for (
auto& pair : RegUsage) {
5505 if (MaxUsages[j].
find(pair.first) != MaxUsages[j].end())
5506 MaxUsages[j][pair.first] =
std::max(MaxUsages[j][pair.first], pair.second);
5508 MaxUsages[j][pair.first] = pair.second;
5513 << OpenIntervals.
size() <<
'\n');
5519 for (
unsigned i = 0,
e = VFs.
size(); i <
e; ++i) {
5522 for (
auto Inst : LoopInvariants) {
5523 unsigned Usage = VFs[i] == 1 ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
5525 if (Invariant.
find(ClassID) == Invariant.
end())
5526 Invariant[ClassID] = Usage;
5528 Invariant[ClassID] += Usage;
5532 dbgs() <<
"LV(REG): VF = " << VFs[i] <<
'\n';
5533 dbgs() <<
"LV(REG): Found max usage: " << MaxUsages[i].size()
5535 for (
const auto &pair : MaxUsages[i]) {
5536 dbgs() <<
"LV(REG): RegisterClass: " 5540 dbgs() <<
"LV(REG): Found invariant usage: " << Invariant.
size()
5542 for (
const auto &pair : Invariant) {
5543 dbgs() <<
"LV(REG): RegisterClass: " 5557 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(
Instruction *
I){
5566 assert(isPredicatedInst(I) &&
"Expecting a scalar emulated instruction");
5567 return isa<LoadInst>(
I) ||
5568 (isa<StoreInst>(I) &&
5577 if (VF < 2 || InstsToScalarize.find(VF) != InstsToScalarize.end())
5589 if (!blockNeedsPredication(BB))
5592 if (isScalarWithPredication(&I)) {
5596 if (!useEmulatedMaskMemRefHack(&I) &&
5597 computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
5600 PredicatedBBsAfterVectorization.insert(BB);
5605 int LoopVectorizationCostModel::computePredInstDiscount(
5608 assert(!isUniformAfterVectorization(PredInst, VF) &&
5609 "Instruction marked uniform-after-vectorization will be predicated");
5628 isScalarAfterVectorization(I, VF))
5633 if (isScalarWithPredication(I))
5647 if (
auto *J = dyn_cast<Instruction>(U.get()))
5648 if (isUniformAfterVectorization(J, VF))
5659 while (!Worklist.
empty()) {
5663 if (ScalarCosts.
find(I) != ScalarCosts.
end())
5668 unsigned VectorCost = getInstructionCost(I, VF).first;
5674 unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
5689 if (
auto *J = dyn_cast<Instruction>(U.get())) {
5691 "Instruction has non-scalar type");
5692 if (canBeScalarized(J))
5694 else if (needsExtract(J, VF))
5704 Discount += VectorCost - ScalarCost;
5705 ScalarCosts[
I] = ScalarCost;
5711 LoopVectorizationCostModel::VectorizationCostTy
5712 LoopVectorizationCostModel::expectedCost(
unsigned VF) {
5713 VectorizationCostTy
Cost;
5717 VectorizationCostTy BlockCost;
5720 for (
Instruction &I : BB->instructionsWithoutDebug()) {
5722 if (ValuesToIgnore.find(&I) != ValuesToIgnore.end() ||
5723 (VF > 1 && VecValuesToIgnore.find(&I) != VecValuesToIgnore.end()))
5726 VectorizationCostTy
C = getInstructionCost(&I, VF);
5732 BlockCost.first += C.first;
5733 BlockCost.second |= C.second;
5734 LLVM_DEBUG(
dbgs() <<
"LV: Found an estimated cost of " << C.first
5735 <<
" for VF " << VF <<
" For instruction: " << I
5745 if (VF == 1 && blockNeedsPredication(BB))
5748 Cost.first += BlockCost.first;
5749 Cost.second |= BlockCost.second;
5764 const Loop *TheLoop) {
5772 auto SE = PSE.
getSE();
5773 unsigned NumOperands = Gep->getNumOperands();
5774 for (
unsigned i = 1; i < NumOperands; ++i) {
5775 Value *Opd = Gep->getOperand(i);
5776 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5790 unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(
Instruction *I,
5792 assert(VF > 1 &&
"Scalarization cost of instruction implies vectorization.");
5815 Cost += getScalarizationOverhead(I, VF);
5820 if (isPredicatedInst(I)) {
5823 if (useEmulatedMaskMemRefHack(I))
5832 unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(
Instruction *I,
5840 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5841 "Stride should be 1 or -1 for consecutive memory access");
5846 Alignment ? Alignment->value() : 0, AS);
5850 bool Reverse = ConsecutiveStride < 0;
5856 unsigned LoopVectorizationCostModel::getUniformMemOpCost(
Instruction *I,
5862 if (isa<LoadInst>(I)) {
5872 (isLoopInvariantStoreValue
5878 unsigned LoopVectorizationCostModel::getGatherScatterCost(
Instruction *I,
5888 Alignment ? Alignment->value() : 0);
5891 unsigned LoopVectorizationCostModel::getInterleaveGroupCost(
Instruction *I,
5897 auto Group = getInterleavedAccessGroup(I);
5898 assert(Group &&
"Fail to get an interleaved access group.");
5900 unsigned InterleaveFactor = Group->getFactor();
5906 if (isa<LoadInst>(I)) {
5907 for (
unsigned i = 0; i < InterleaveFactor; i++)
5908 if (Group->getMember(i))
5913 bool UseMaskForGaps =
5914 Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
5916 I->
getOpcode(), WideVecTy, Group->getFactor(), Indices,
5919 if (Group->isReverse()) {
5922 "Reverse masked interleaved access not supported.");
5923 Cost += Group->getNumMembers() *
5929 unsigned LoopVectorizationCostModel::getMemoryInstructionCost(
Instruction *I,
5941 return getWideningCost(I, VF);
5944 LoopVectorizationCostModel::VectorizationCostTy
5945 LoopVectorizationCostModel::getInstructionCost(
Instruction *I,
unsigned VF) {
5948 if (isUniformAfterVectorization(I, VF))
5951 if (VF > 1 && isProfitableToScalarize(I, VF))
5952 return VectorizationCostTy(InstsToScalarize[VF][I],
false);
5955 auto ForcedScalar = ForcedScalars.find(VF);
5956 if (VF > 1 && ForcedScalar != ForcedScalars.end()) {
5957 auto InstSet = ForcedScalar->second;
5958 if (InstSet.find(I) != InstSet.end())
5959 return VectorizationCostTy((getInstructionCost(I, 1).
first * VF),
false);
5963 unsigned C = getInstructionCost(I, VF, VectorTy);
5965 bool TypeNotScalarized =
5967 return VectorizationCostTy(C, TypeNotScalarized);
5970 unsigned LoopVectorizationCostModel::getScalarizationOverhead(
Instruction *I,
5997 filterExtractingOperands(Ops, VF), VF);
6015 if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
6027 unsigned Cost = getUniformMemOpCost(&I, VF);
6028 setWideningDecision(&I, VF, CM_Scalarize, Cost);
6033 if (memoryInstructionCanBeWidened(&I, VF)) {
6034 unsigned Cost = getConsecutiveMemOpCost(&I, VF);
6035 int ConsecutiveStride =
6037 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6038 "Expected consecutive stride.");
6040 ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
6041 setWideningDecision(&I, VF, Decision, Cost);
6047 unsigned NumAccesses = 1;
6048 if (isAccessInterleaved(&I)) {
6049 auto Group = getInterleavedAccessGroup(&I);
6050 assert(Group &&
"Fail to get an interleaved access group.");
6053 if (getWideningDecision(&I, VF) != CM_Unknown)
6056 NumAccesses = Group->getNumMembers();
6057 if (interleavedAccessCanBeWidened(&I, VF))
6058 InterleaveCost = getInterleaveGroupCost(&I, VF);
6061 unsigned GatherScatterCost =
6062 isLegalGatherOrScatter(&I)
6063 ? getGatherScatterCost(&I, VF) * NumAccesses
6066 unsigned ScalarizationCost =
6067 getMemInstScalarizationCost(&I, VF) * NumAccesses;
6073 if (InterleaveCost <= GatherScatterCost &&
6074 InterleaveCost < ScalarizationCost) {
6075 Decision = CM_Interleave;
6076 Cost = InterleaveCost;
6077 }
else if (GatherScatterCost < ScalarizationCost) {
6078 Decision = CM_GatherScatter;
6079 Cost = GatherScatterCost;
6081 Decision = CM_Scalarize;
6082 Cost = ScalarizationCost;
6087 if (
auto Group = getInterleavedAccessGroup(&I))
6088 setWideningDecision(Group, VF, Decision, Cost);
6090 setWideningDecision(&I, VF, Decision, Cost);
6108 if (PtrDef && TheLoop->contains(PtrDef) &&
6109 getWideningDecision(&I, VF) != CM_GatherScatter)
6115 for (
auto *I : AddrDefs)
6117 while (!Worklist.
empty()) {
6120 if (
auto *InstOp = dyn_cast<Instruction>(
Op))
6121 if ((InstOp->getParent() == I->
getParent()) && !isa<PHINode>(InstOp) &&
6122 AddrDefs.insert(InstOp).second)
6126 for (
auto *I : AddrDefs) {
6127 if (isa<LoadInst>(I)) {
6133 if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
6135 setWideningDecision(I, VF, CM_Scalarize,
6136 (VF * getMemoryInstructionCost(I, 1)));
6137 else if (
auto Group = getInterleavedAccessGroup(I)) {
6139 for (
unsigned I = 0; I < Group->getFactor(); ++
I) {
6141 setWideningDecision(Member, VF, CM_Scalarize,
6142 (VF * getMemoryInstructionCost(Member, 1)));
6148 ForcedScalars[
VF].insert(I);
6152 unsigned LoopVectorizationCostModel::getInstructionCost(
Instruction *I,
6156 if (canTruncateToMinimalBitwidth(I, VF))
6158 VectorTy = isScalarAfterVectorization(I, VF) ? RetTy :
ToVectorTy(RetTy, VF);
6163 case Instruction::GetElementPtr:
6169 case Instruction::Br: {
6173 bool ScalarPredicatedBB =
false;
6176 (PredicatedBBsAfterVectorization.find(BI->
getSuccessor(0)) !=
6177 PredicatedBBsAfterVectorization.end() ||
6178 PredicatedBBsAfterVectorization.find(BI->
getSuccessor(1)) !=
6179 PredicatedBBsAfterVectorization.end()))
6180 ScalarPredicatedBB =
true;
6182 if (ScalarPredicatedBB) {
6188 }
else if (I->
getParent() == TheLoop->getLoopLatch() || VF == 1)
6198 case Instruction::PHI: {
6199 auto *Phi = cast<PHINode>(
I);
6210 if (VF > 1 && Phi->getParent() != TheLoop->getHeader())
6211 return (Phi->getNumIncomingValues() - 1) *
6218 case Instruction::UDiv:
6219 case Instruction::SDiv:
6220 case Instruction::URem:
6221 case Instruction::SRem:
6226 if (VF > 1 && isScalarWithPredication(I)) {
6240 Cost += getScalarizationOverhead(I, VF);
6249 case Instruction::FAdd:
6250 case Instruction::Sub:
6251 case Instruction::FSub:
6252 case Instruction::Mul:
6253 case Instruction::FMul:
6254 case Instruction::FDiv:
6255 case Instruction::FRem:
6256 case Instruction::Shl:
6257 case Instruction::LShr:
6258 case Instruction::AShr:
6259 case Instruction::And:
6260 case Instruction::Or:
6261 case Instruction::Xor: {
6275 unsigned N = isScalarAfterVectorization(I, VF) ?
VF : 1;
6280 case Instruction::FNeg: {
6281 unsigned N = isScalarAfterVectorization(I, VF) ?
VF : 1;
6291 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
6298 case Instruction::ICmp:
6299 case Instruction::FCmp: {
6302 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
6312 assert(Decision != CM_Unknown &&
6313 "CM decision should be taken at this point");
6314 if (Decision == CM_Scalarize)
6318 return getMemoryInstructionCost(I, VF);
6320 case Instruction::ZExt:
6321 case Instruction::SExt:
6322 case Instruction::FPToUI:
6323 case Instruction::FPToSI:
6324 case Instruction::FPExt:
6325 case Instruction::PtrToInt:
6326 case Instruction::IntToPtr:
6327 case Instruction::SIToFP:
6328 case Instruction::UIToFP:
6329 case Instruction::Trunc:
6330 case Instruction::FPTrunc:
6331 case Instruction::BitCast: {
6335 if (isOptimizableIVTruncate(I, VF)) {
6336 auto *Trunc = cast<TruncInst>(
I);
6338 Trunc->getSrcTy(), Trunc);
6344 if (canTruncateToMinimalBitwidth(I, VF)) {
6350 Type *MinVecTy = VectorTy;
6351 if (I->
getOpcode() == Instruction::Trunc) {
6355 }
else if (I->
getOpcode() == Instruction::ZExt ||
6363 unsigned N = isScalarAfterVectorization(I, VF) ?
VF : 1;
6367 bool NeedToScalarize;
6369 unsigned CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
6371 return std::min(CallCost, getVectorIntrinsicCost(CI, VF));
6378 getScalarizationOverhead(I, VF);
6384 static const char lv_name[] =
"Loop Vectorization";
6407 bool VectorizeOnlyWhenForced) {
6408 return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
6413 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(
Instruction *Inst) {
6430 VecValuesToIgnore.insert(Casts.
begin(), Casts.
end());
6437 VecValuesToIgnore.insert(Casts.
begin(), Casts.
end());
6448 unsigned WidestType;
6450 return WidestVectorRegBits / WidestType;
6455 unsigned VF = UserVF;
6470 <<
"overriding computed VF.\n");
6476 LLVM_DEBUG(
dbgs() <<
"LV: Using " << (UserVF ?
"user " :
"") <<
"VF " << VF
6477 <<
" to build VPlans.\n");
6478 buildVPlans(VF, VF);
6488 dbgs() <<
"LV: Not vectorizing. Inner loops aren't supported in the " 6489 "VPlan-native path.\n");
6504 <<
"LV: Invalidate all interleaved groups due to fold-tail by masking " 6505 "which requires masked-interleaved support.\n");
6506 CM.InterleaveInfo.reset();
6514 CM.selectUserVectorizationFactor(UserVF);
6515 buildVPlansWithVPRecipes(UserVF, UserVF);
6517 return {{UserVF, 0}};
6520 unsigned MaxVF = MaybeMaxVF.getValue();
6521 assert(MaxVF != 0 &&
"MaxVF is zero.");
6523 for (
unsigned VF = 1; VF <= MaxVF; VF *= 2) {
6525 CM.collectUniformsAndScalars(VF);
6530 CM.collectInstsToScalarize(VF);
6533 buildVPlansWithVPRecipes(1, MaxVF);
6539 return CM.selectVectorizationFactor(MaxVF);
6543 LLVM_DEBUG(
dbgs() <<
"Setting best plan to VF=" << VF <<
", UF=" << UF
6549 return !Plan->hasVF(VF);
6551 assert(VPlans.size() == 1 &&
"Best VF has not a single VPlan.");
6559 VPCallbackILV CallbackILV(ILV);
6576 assert(VPlans.size() == 1 &&
"Not a single VPlan to execute.");
6577 VPlans.front()->execute(&State);
6592 if (Cmp && Cmp->hasOneUse())
6593 DeadInstructions.
insert(Cmp);
6602 return U == Ind || DeadInstructions.
find(cast<Instruction>(U)) !=
6603 DeadInstructions.
end();
6605 DeadInstructions.
insert(IndUpdate);
6621 Value *InnerLoopUnroller::reverseVector(
Value *Vec) {
return Vec; }
6623 Value *InnerLoopUnroller::getBroadcastInstrs(
Value *V) {
return V; }
6625 Value *InnerLoopUnroller::getStepVector(
Value *Val,
int StartIdx,
Value *Step,
6646 bool IsUnrollMetadata =
false;
6650 for (
unsigned i = 1, ie = LoopID->
getNumOperands(); i < ie; ++i) {
6655 S && S->getString().startswith(
"llvm.loop.unroll.disable");
6661 if (!IsUnrollMetadata) {
6666 MDString::get(Context,
"llvm.loop.unroll.runtime.disable"));
6678 assert(Range.
End > Range.
Start &&
"Trying to test an empty VF range.");
6681 for (
unsigned TmpVF = Range.
Start * 2; TmpVF < Range.
End; TmpVF *= 2)
6682 if (
Predicate(TmpVF) != PredicateAtRangeStart) {
6687 return PredicateAtRangeStart;
6696 for (
unsigned VF = MinVF; VF < MaxVF + 1;) {
6698 VPlans.push_back(buildVPlan(SubRange));
6708 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
6710 if (ECEntryIt != EdgeMaskCache.end())
6711 return ECEntryIt->second;
6713 VPValue *SrcMask = createBlockInMask(Src, Plan);
6717 assert(BI &&
"Unexpected terminator found");
6720 return EdgeMaskCache[Edge] = SrcMask;
6723 assert(EdgeMask &&
"No Edge Mask found for condition");
6726 EdgeMask =
Builder.createNot(EdgeMask);
6729 EdgeMask =
Builder.createAnd(EdgeMask, SrcMask);
6731 return EdgeMaskCache[Edge] = EdgeMask;
6739 if (BCEntryIt != BlockMaskCache.end())
6740 return BCEntryIt->second;
6747 if (!CM.blockNeedsPredication(BB))
6748 return BlockMaskCache[BB] = BlockMask;
6753 VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
6755 return BlockMaskCache[BB] = BlockMask;
6760 VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
6762 return BlockMaskCache[BB] = EdgeMask;
6765 BlockMask = EdgeMask;
6769 BlockMask =
Builder.createOr(BlockMask, EdgeMask);
6772 return BlockMaskCache[BB] = BlockMask;
6778 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
6781 auto willWiden = [&](
unsigned VF) ->
bool {
6785 CM.getWideningDecision(I, VF);
6787 "CM decision should be taken at this point.");
6790 if (CM.isScalarAfterVectorization(I, VF) ||
6791 CM.isProfitableToScalarize(I, VF))
6801 Mask = createBlockInMask(I->
getParent(), Plan);
6809 if (
PHINode *Phi = dyn_cast<PHINode>(I)) {
6827 auto isOptimizableIVTruncate =
6830 [=](
unsigned VF) ->
bool {
return CM.isOptimizableIVTruncate(K, VF); };
6834 isOptimizableIVTruncate(I), Range))
6836 cast<TruncInst>(I));
6853 for (
unsigned In = 0;
In < NumIncoming;
In++) {
6856 assert((EdgeMask || NumIncoming == 1) &&
6857 "Multiple predecessors with one having a full mask");
6868 [&](
unsigned VF) {
return CM.isScalarWithPredication(I, VF); }, Range);
6873 auto IsVectorizableOpcode = [](
unsigned Opcode) {
6876 case Instruction::And:
6877 case Instruction::AShr:
6878 case Instruction::BitCast:
6879 case Instruction::Br:
6881 case Instruction::FAdd:
6882 case Instruction::FCmp:
6883 case Instruction::FDiv:
6884 case Instruction::FMul:
6885 case Instruction::FNeg:
6886 case Instruction::FPExt:
6887 case Instruction::FPToSI:
6888 case Instruction::FPToUI:
6889 case Instruction::FPTrunc:
6890 case Instruction::FRem:
6891 case Instruction::FSub:
6892 case Instruction::ICmp:
6893 case Instruction::IntToPtr:
6895 case Instruction::LShr:
6896 case Instruction::Mul:
6897 case Instruction::Or:
6898 case Instruction::PHI:
6899 case Instruction::PtrToInt:
6900 case Instruction::SDiv:
6902 case Instruction::SExt:
6903 case Instruction::Shl:
6904 case Instruction::SIToFP:
6905 case Instruction::SRem:
6907 case Instruction::Sub:
6908 case Instruction::Trunc:
6909 case Instruction::UDiv:
6910 case Instruction::UIToFP:
6911 case Instruction::URem:
6912 case Instruction::Xor:
6913 case Instruction::ZExt:
6919 if (!IsVectorizableOpcode(I->
getOpcode()))
6922 if (
CallInst *CI = dyn_cast<CallInst>(I)) {
6924 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
6925 ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect))
6929 auto willWiden = [&](
unsigned VF) ->
bool {
6930 if (!isa<PHINode>(I) && (CM.isScalarAfterVectorization(I, VF) ||
6931 CM.isProfitableToScalarize(I, VF)))
6933 if (
CallInst *CI = dyn_cast<CallInst>(I)) {
6939 bool NeedToScalarize;
6940 unsigned CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
6941 bool UseVectorIntrinsic =
6942 ID && CM.getVectorIntrinsicCost(CI, VF) <= CallCost;
6943 return UseVectorIntrinsic || !NeedToScalarize;
6945 if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
6946 assert(CM.getWideningDecision(I, VF) ==
6948 "Memory widening decisions should have been taken care by now");
6958 bool IsSingleton = Ingredient2Recipe.count(I);
6964 if (!IsSingleton && !VPBB->
empty() && LastExtensibleRecipe == &VPBB->
back() &&
6965 LastExtensibleRecipe->appendInstruction(I))
6970 LastExtensibleRecipe = WidenRecipe;
6971 setRecipe(I, WidenRecipe);
6981 [&](
unsigned VF) {
return CM.isUniformAfterVectorization(I, VF); },
6985 [&](
unsigned VF) {
return CM.isScalarWithPredication(I, VF); }, Range);
6988 setRecipe(I, Recipe);
6994 if (
auto *PredInst = dyn_cast<Instruction>(
Op))
6995 if (PredInst2Recipe.
find(PredInst) != PredInst2Recipe.
end())
6996 PredInst2Recipe[PredInst]->setAlsoPack(
false);
6999 if (!IsPredicated) {
7004 LLVM_DEBUG(
dbgs() <<
"LV: Scalarizing and predicating:" << *I <<
"\n");
7006 "VPBB has successors when handling predicated replication.");
7008 PredInst2Recipe[
I] = Recipe;
7027 assert(Instr->
getParent() &&
"Predicated instruction not in any basic block");
7050 if ((Recipe = tryToWidenMemory(Instr, Range, Plan)) ||
7051 (Recipe = tryToOptimizeInduction(Instr, Range)) ||
7052 (Recipe = tryToBlend(Instr, Plan)) ||
7053 (isa<PHINode>(Instr) &&
7055 setRecipe(Instr, Recipe);
7062 auto Scalarize = [&](
unsigned VF) {
7063 return CM.isScalarWithPredication(Instr, VF) ||
7064 CM.isScalarAfterVectorization(Instr, VF) ||
7065 CM.isProfitableToScalarize(Instr, VF);
7070 setRecipe(Instr, Recipe);
7077 if (tryToWiden(Instr, VPBB, Range))
7083 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(
unsigned MinVF,
7104 if (CM.foldTailByMasking()) {
7108 NeedDef.insert(
Reduction.second.getLoopExitInstr());
7119 collectTriviallyDeadInstructions(DeadInstructions);
7126 for (
unsigned VF = MinVF; VF < MaxVF + 1;) {
7128 VPlans.push_back(buildVPlanWithVPRecipes(SubRange, NeedDef,
7129 DeadInstructions, SinkAfter));
7134 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
7155 for (
auto &
Entry : SinkAfter) {
7165 auto applyIG = [IG,
this](
unsigned VF) ->
bool {
7167 CM.getWideningDecision(IG->getInsertPos(),
VF) ==
7170 if (!getDecisionAndClampRange(applyIG, Range))
7172 InterleaveGroups.
insert(IG);
7173 for (
unsigned i = 0; i < IG->getFactor(); i++)
7185 auto Plan = std::make_unique<VPlan>(VPBB);
7188 for (
Value *V : NeedDef)
7189 Plan->addVPValue(V);
7199 unsigned VPBBsForBB = 0;
7200 auto *FirstVPBBForBB =
new VPBasicBlock(BB->getName());
7202 VPBB = FirstVPBBForBB;
7206 for (
Instruction &I : BB->instructionsWithoutDebug()) {
7211 if (isa<BranchInst>(Instr) ||
7212 DeadInstructions.
find(Instr) != DeadInstructions.
end())
7221 Instr, Range, VPBB, PredInst2Recipe, Plan);
7222 if (NextVPBB != VPBB) {
7224 VPBB->
setName(BB->hasName() ? BB->getName() +
"." +
Twine(VPBBsForBB++)
7233 VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
7234 assert(PreEntry->
empty() &&
"Expecting empty pre-entry block.");
7245 for (
auto &Entry : SinkAfter) {
7254 for (
auto IG : InterleaveGroups) {
7255 auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
7256 RecipeBuilder.
getRecipe(IG->getInsertPos()));
7258 ->insertBefore(Recipe);
7260 for (
unsigned i = 0; i < IG->getFactor(); ++i)
7268 if (CM.foldTailByMasking()) {
7278 std::string PlanName;
7280 unsigned VF = Range.
Start;
7282 RSO <<
"Initial VPlan for VF={" <<
VF;
7283 for (VF *= 2; VF < Range.
End; VF *= 2) {
7289 Plan->setName(PlanName);
7303 auto Plan = std::make_unique<VPlan>();
7307 HCFGBuilder.buildHierarchicalCFG();
7309 for (
unsigned VF = Range.
Start; VF < Range.
End; VF *= 2)
7327 Value* LoopVectorizationPlanner::VPCallbackILV::
7328 getOrCreateVectorValues(
Value *V,
unsigned Part) {
7329 return ILV.getOrCreateVectorValue(V, Part);
7332 Value *LoopVectorizationPlanner::VPCallbackILV::getOrCreateScalarValue(
7334 return ILV.getOrCreateScalarValue(V, Instance);
7339 << Indent <<
"\"INTERLEAVE-GROUP with factor " << IG->getFactor() <<
" at ";
7340 IG->getInsertPos()->printAsOperand(O,
false);
7342 getAddr()->printAsOperand(O);
7349 for (
unsigned i = 0; i < IG->getFactor(); ++i)
7362 IsIndexLoopInvariant);
7366 assert(!State.
Instance &&
"Int or FP induction being replicated.");
7383 unsigned NumIncoming = Phi->getNumIncomingValues();
7386 "Multiple predecessors with predecessors having a full mask");
7392 for (
unsigned In = 0;
In < NumIncoming; ++
In) {
7393 for (
unsigned Part = 0; Part < State.
UF; ++Part) {
7409 for (
unsigned Part = 0; Part < State.
UF; ++Part)
7423 if (AlsoPack && State.
VF > 1) {
7438 unsigned EndLane = IsUniform ? 1 : State.
VF;
7439 for (
unsigned Part = 0; Part < State.
UF; ++Part)
7440 for (
unsigned Lane = 0; Lane < EndLane; ++Lane)
7445 assert(State.
Instance &&
"Branch on Mask works only on single instance.");
7447 unsigned Part = State.
Instance->Part;
7448 unsigned Lane = State.
Instance->Lane;
7450 Value *ConditionBit =
nullptr;
7455 ConditionBit = State.
get(BlockInMask, Part);
7464 assert(isa<UnreachableInst>(CurrentTerminator) &&
7465 "Expected to replace unreachable terminator with conditional branch.");
7467 CondBr->setSuccessor(0,
nullptr);
7472 assert(State.
Instance &&
"Predicated instruction PHI works per instance.");
7477 assert(PredicatingBB &&
"Predicated block has no single predecessor.");
7485 unsigned Part = State.
Instance->Part;
7491 VPhi->addIncoming(IEI, PredicatedBB);
7561 F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.
getSE(),
DT, *LVL);
7563 LoopVectorizationCostModel CM(
SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
7571 const unsigned UserVF = Hints.
getWidth();
7585 InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.
Width, 1, LVL,
7600 "VPlan-native path is not enabled. Only process inner loops.");
7608 << DebugLocStr <<
"\n");
7613 dbgs() <<
"LV: Loop hints:" 7620 <<
" width=" << Hints.getWidth()
7621 <<
" unroll=" << Hints.getInterleave() <<
"\n");
7634 if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
7643 LoopVectorizationLegality LVL(L, PSE,
DT,
TTI,
TLI,
AA, F, GetLAA,
LI,
ORE,
7644 &Requirements, &Hints, DB,
AC);
7646 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Cannot prove legality.\n");
7647 Hints.emitRemarkWithHints();
7654 F, L, Hints, PSI,
BFI,
TTI,
TLI,
AC,
LI, PSE.
getSE(),
DT, LVL);
7671 LLVM_DEBUG(
dbgs() <<
"LV: Found a loop with a very small trip count. " 7672 <<
"This loop is worth vectorizing only if no scalar " 7673 <<
"iteration overheads are incurred.");
7675 LLVM_DEBUG(
dbgs() <<
" But vectorizing was explicitly forced.\n");
7686 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7688 "Can't vectorize when the NoImplicitFloat attribute is used",
7689 "loop not vectorized due to NoImplicitFloat attribute",
7690 "NoImplicitFloat",
ORE, L);
7691 Hints.emitRemarkWithHints();
7699 if (Hints.isPotentiallyUnsafe() &&
7702 "Potentially unsafe FP op prevents vectorization",
7703 "loop not vectorized due to unsafe FP support.",
7704 "UnsafeFP",
ORE, L);
7705 Hints.emitRemarkWithHints();
7717 if (UseInterleaved) {
7722 LoopVectorizationCostModel CM(
SEL, L, PSE,
LI, &LVL, *
TTI,
TLI, DB,
AC,
ORE,
7730 unsigned UserVF = Hints.getWidth();
7737 unsigned UserIC = Hints.getInterleave();
7746 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
7747 bool VectorizeLoop =
true, InterleaveLoop =
true;
7749 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: loop did not meet vectorization " 7751 Hints.emitRemarkWithHints();
7755 if (VF.
Width == 1) {
7756 LLVM_DEBUG(
dbgs() <<
"LV: Vectorization is possible but not beneficial.\n");
7757 VecDiagMsg = std::make_pair(
7758 "VectorizationNotBeneficial",
7759 "the cost-model indicates that vectorization is not beneficial");
7760 VectorizeLoop =
false;
7763 if (!MaybeVF && UserIC > 1) {
7766 LLVM_DEBUG(
dbgs() <<
"LV: Ignoring UserIC, because vectorization and " 7767 "interleaving should be avoided up front\n");
7768 IntDiagMsg = std::make_pair(
7769 "InterleavingAvoided",
7770 "Ignoring UserIC, because interleaving was avoided up front");
7771 InterleaveLoop =
false;
7772 }
else if (IC == 1 && UserIC <= 1) {
7775 IntDiagMsg = std::make_pair(
7776 "InterleavingNotBeneficial",
7777 "the cost-model indicates that interleaving is not beneficial");
7778 InterleaveLoop =
false;
7780 IntDiagMsg.first =
"InterleavingNotBeneficialAndDisabled";
7781 IntDiagMsg.second +=
7782 " and is explicitly disabled or interleave count is set to 1";
7784 }
else if (IC > 1 && UserIC == 1) {
7787 dbgs() <<
"LV: Interleaving is beneficial but is explicitly disabled.");
7788 IntDiagMsg = std::make_pair(
7789 "InterleavingBeneficialButDisabled",
7790 "the cost-model indicates that interleaving is beneficial " 7791 "but is explicitly disabled or interleave count is set to 1");
7792 InterleaveLoop =
false;
7796 IC = UserIC > 0 ? UserIC : IC;
7799 const char *VAPassName = Hints.vectorizeAnalysisPassName();
7800 if (!VectorizeLoop && !InterleaveLoop) {
7805 << VecDiagMsg.second;
7810 << IntDiagMsg.second;
7813 }
else if (!VectorizeLoop && InterleaveLoop) {
7818 << VecDiagMsg.second;
7820 }
else if (VectorizeLoop && !InterleaveLoop) {
7822 <<
") in " << DebugLocStr <<
'\n');
7826 << IntDiagMsg.second;
7828 }
else if (VectorizeLoop && InterleaveLoop) {
7830 <<
") in " << DebugLocStr <<
'\n');
7836 using namespace ore;
7837 bool DisableRuntimeUnroll =
false;
7840 if (!VectorizeLoop) {
7841 assert(IC > 1 &&
"interleave count should not be 1 or 0");
7844 InnerLoopUnroller Unroller(L, PSE,
LI,
DT,
TLI,
TTI,
AC,
ORE, IC, &LVL,
7851 <<
"interleaved loop (interleaved count: " 7852 <<
NV(
"InterleaveCount", IC) <<
")";
7856 InnerLoopVectorizer LB(L, PSE,
LI,
DT,
TLI,
TTI,
AC,
ORE, VF.
Width, IC,
7865 DisableRuntimeUnroll =
true;
7871 <<
"vectorized loop (vectorization width: " 7872 <<
NV(
"VectorizationFactor", VF.
Width)
7873 <<
", interleaved count: " <<
NV(
"InterleaveCount", IC) <<
")";
7879 LLVMLoopVectorizeFollowupEpilogue});
7883 if (DisableRuntimeUnroll)
7887 Hints.setAlreadyVectorized();
7924 bool Changed =
false;
7943 LoopsAnalyzed += Worklist.
size();
7946 while (!Worklist.
empty()) {
7953 Changed |= processLoop(L);
7977 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
7987 runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
Legacy wrapper pass to provide the GlobalsAAResult object.
Pass interface - Implemented by all 'passes'.
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Type * getVectorElementType() const
Value * getValueOperand()
unsigned getSmallConstantTripCount(const Loop *L)
Returns the maximum trip count of the loop if it is a single-exit loop and we can compute a small max...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Value * getOrCreateScalarValue(Value *V, const VPIteration &Instance)
Return a value in the new loop corresponding to V from the original loop at unroll and vector indices...
Main class to build the VPlan H-CFG for an incoming IR.
void vectorizeInterleaveGroup(Instruction *Instr, VPTransformState &State, VPValue *Addr, VPValue *BlockInMask=nullptr)
Try to vectorize the interleaved access group that Instr belongs to with the base address given in Ad...
A parsed version of the target data layout string in and methods for querying it. ...
const_iterator end(StringRef path)
Get end iterator over path.
void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction, which must be an operator which supports these flags.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
Type * getWidestInductionType()
Returns the widest induction type.
Value * getPointerOperand()
bool processLoop(Loop *L)
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
unsigned getWidth() const
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
DemandedBits * DB
Demanded bits analysis.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
BinaryOperator * getInductionBinOp() const
static IntegerType * getInt1Ty(LLVMContext &C)
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
static cl::opt< bool > MaximizeBandwidth("vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden, cl::desc("Maximize bandwidth when selecting vectorization factor which " "will be determined by the smallest type in loop."))
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static cl::opt< bool > LoopVectorizeWithBlockFrequency("loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden, cl::desc("Enable the use of the block frequency analysis to access PGO " "heuristics minimizing code growth in cold regions and being more " "aggressive in hot regions."))
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
InstWidening
Decision that was taken during cost calculation for memory instruction.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
MapVector< Instruction *, uint64_t > computeMinimumValueSizes(ArrayRef< BasicBlock *> Blocks, DemandedBits &DB, const TargetTransformInfo *TTI=nullptr)
Compute a map of integer instructions to their minimum legal type size.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF=1)
Returns true if I is a memory instruction with consecutive memory access that can be widened...
DiagnosticInfoOptimizationBase::Argument NV
void setFast(bool B=true)
bool isMaskRequired(const Instruction *I)
Returns true if vector representation of the instruction I requires mask.
void execute(VPTransformState &State) override
Generate the wide load/store.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
void addNewMetadata(Instruction *To, const Instruction *Orig)
Add additional metadata to To that was not present on Orig.
unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF)
Estimate cost of an intrinsic call instruction CI if it were vectorized with factor VF...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void collectValuesToIgnore()
Collect values we want to ignore in the cost model.
This class represents lattice values for constants.
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
static cl::opt< unsigned > ForceTargetNumScalarRegs("force-target-num-scalar-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of scalar registers."))
const LoopVectorizeHints * Hints
Loop Vectorize Hint.
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...
const InterleaveGroup< Instruction > * getInterleavedAccessGroup(Instruction *Instr)
Get the interleaved access group that Instr belongs to.
size_type size() const
Determine the number of elements in the SetVector.
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module. ...
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, unsigned Align, const char *Name)
Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly, instead of converting the strin...
Optional< const DILocation * > cloneByMultiplyingDuplicationFactor(unsigned DF) const
Returns a new DILocation with duplication factor DF * current duplication factor encoded in the discr...
void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance, bool IfPredicateInstr)
A helper function to scalarize a single Instruction in the innermost loop.
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
std::unique_ptr< LoopVersioning > LVer
LoopVersioning.
void emitSCEVChecks(Loop *L, BasicBlock *Bypass)
Emit a bypass check to see if all of the SCEV assumptions we've had to make are correct.
static MDString * get(LLVMContext &Context, StringRef Str)
Interval Class - An Interval is a set of nodes defined such that every node in the interval has all o...
ConstantInt * getConstIntStepValue() const
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
Min/max implemented in terms of select(cmp()).
This class represents zero extension of integer types.
Value * getScalarValue(Value *Key, const VPIteration &Instance)
Retrieve the existing scalar value that corresponds to Key and Instance.
Instruction::BinaryOps getInductionOpcode() const
Returns binary opcode of the induction operator.
void push_back(const T &Elt)
Value * createBitOrPointerCast(Value *V, VectorType *DstVTy, const DataLayout &DL)
Returns a bitcasted value to the requested vector type.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Analysis providing profile information.
value_op_iterator value_op_begin()
Instruction * propagateMetadata(Instruction *I, ArrayRef< Value *> VL)
Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath, MD_nontemporal, MD_access_group].
static void AddRuntimeUnrollDisableMetaData(Loop *L)
The main scalar evolution driver.
bool isUniform(Value *V)
Returns true if the value V is uniform within the loop.
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class...
static std::string getDebugLocString(const Loop *L)
static cl::opt< unsigned > TinyTripCountInterleaveThreshold("tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden, cl::desc("We don't interleave loops with a estimated constant trip count " "below this number"))
This is a helper struct for maintaining vectorization state.
LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, LoopVectorizationLegality *Legal, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, const Function *F, const LoopVectorizeHints *Hints, InterleavedAccessInfo &IAI)
Pass * createLoopVectorizePass()
This class represents a function call, abstracting a target machine's calling convention.
const ValueToValueMap & getSymbolicStrides() const
If an access has a symbolic strides, this maps the pointer value to the stride symbol.
void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF)
Vectorize a single PHINode in a block.
DominatorTree * DT
Dominator Tree.
void collectTriviallyDeadInstructions(SmallPtrSetImpl< Instruction *> &DeadInstructions)
Collect the instructions from the original loop that would be trivially dead in the vectorized loop i...
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
An immutable pass that tracks lazily created AssumptionCache objects.
VPWidenMemoryInstructionRecipe * tryToWidenMemory(Instruction *I, VFRange &Range, VPlanPtr &Plan)
Check if is a memory instruction to be widened for Range.Start and potentially masked.
static Type * largestIntegerVectorType(Type *T1, Type *T2)
void fixLCSSAPHIs()
The Loop exit block may have single value PHI nodes with some incoming value.
iterator_range< op_iterator > op_range
Helper class to create VPRecipies from IR instructions.
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
void createVectorIntOrFpInductionPHI(const InductionDescriptor &II, Value *Step, Instruction *EntryVal)
Create a vector induction phi node based on an existing scalar one.
VPRecipeBase * getRecipe(Instruction *I)
Return the recipe created for given ingredient.
Externally visible function.
Loop * TheLoop
The loop that we evaluate.
BasicBlock * LoopScalarPreHeader
The scalar-loop preheader.
bool tryToCreateRecipe(Instruction *Instr, VFRange &Range, VPlanPtr &Plan, VPBasicBlock *VPBB)
Check if a recipe can be create for I withing the given VF Range.
LLVMContext & getContext() const
All values hold a context through their type.
void initializeLoopVectorizePass(PassRegistry &)
static void collectSupportedLoops(Loop &L, LoopInfo *LI, OptimizationRemarkEmitter *ORE, SmallVectorImpl< Loop *> &V)
A Recipe for widening load/store operations.
SmallMapVector< unsigned, unsigned, 4 > LoopInvariantRegs
Holds the number of loop invariant values that are used in the loop.
Value * TripCount
Trip count of the original loop.
void recordVectorLoopValueForInductionCast(const InductionDescriptor &ID, const Instruction *EntryVal, Value *VectorLoopValue, unsigned Part, unsigned Lane=UINT_MAX)
If there is a cast involved in the induction variable ID, which should be ignored in the vectorized l...
This class implements a map that also provides access to all stored values in a deterministic order...
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
value_op_iterator value_op_end()
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
BasicBlock * getSuccessor(unsigned i) const
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
InductionKind getKind() const
STATISTIC(NumFunctions, "Total number of functions")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Analysis pass which computes a DominatorTree.
const MDOperand & getOperand(unsigned I) const
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
Value * getCondition() const
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
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...
bool isVectorTy() const
True if this is an instance of VectorType.
unsigned selectInterleaveCount(unsigned VF, unsigned LoopCost)
bool hasAnyScalarValue(Value *Key) const
virtual Value * getStepVector(Value *Val, int StartIdx, Value *Step, Instruction::BinaryOps Opcode=Instruction::BinaryOpsEnd)
This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...) to each vector element of Val...
This defines the Use class.
VPBlockBase * getSingleSuccessor() const
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
Value * getStartValue() const
static cl::opt< unsigned > NumberOfStoresToPredicate("vectorize-num-stores-pred", cl::init(1), cl::Hidden, cl::desc("Max number of stores to be predicated behind an if."))
The number of stores in a loop that are allowed to need predication.
const TargetLibraryInfo * TLI
Target Library Info.
static const char *const LLVMLoopVectorizeFollowupAll
iterator end()
Get an iterator to the end of the SetVector.
LLVMContext & getContext() const
Get the context in which this basic block lives.
A recipe for handling GEP instructions.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
VPValue * createBlockInMask(BasicBlock *BB, VPlanPtr &Plan)
A helper function that computes the predicate of the block BB, assuming that the header block of the ...
const char * vectorizeAnalysisPassName() const
If hints are provided that force vectorization, use the AlwaysPrint pass name to force the frontend t...
unsigned getSmallConstantMaxTripCount(const Loop *L)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
SmallVector< Instruction *, 4 > PredicatedInstructions
Store instructions that were predicated.
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo *TTI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, unsigned VecWidth, unsigned UnrollFactor, LoopVectorizationLegality *LVL, LoopVectorizationCostModel *CM)
static bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op...
iterator begin()
Instruction iterator methods.
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align, bool isVolatile=false)
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
const MapVector< Instruction *, uint64_t > & getMinimalBitwidths() const
SmallMapVector< unsigned, unsigned, 4 > MaxLocalUsers
Holds the maximum number of concurrent live intervals in the loop.
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
bool hasAnyVectorValue(Value *Key) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
virtual ~InnerLoopVectorizer()=default
cl::opt< bool > EnableLoopInterleaving
VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when control converges back from ...
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
bool isScalarWithPredication(Instruction *I, unsigned VF=1)
Returns true if I is an instruction that will be scalarized with predication.
AnalysisUsage & addRequired()
PredicatedScalarEvolution & PSE
A wrapper around ScalarEvolution used to add runtime SCEV checks.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
void print(raw_ostream &O, const Twine &Indent) const override
Print the recipe.
static FastMathFlags getFast()
bool tryToWiden(Instruction *I, VPBasicBlock *VPBB, VFRange &Range)
Check if I can be widened within the given VF Range.
static cl::opt< bool > EnableMaskedInterleavedMemAccesses("enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"))
An interleave-group may need masking if it resides in a block that needs predication, or in order to mask away gaps.
This file defines the LoopVectorizationLegality class.
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal)
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
This is the base class for all instructions that perform data casts.
static VectorizationFactor Disabled()
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
SmallVector< PHINode *, 8 > OrigPHIsToFix
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
A Use represents the edge between a Value definition and its users.
iterator find(ConstPtrType Ptr) const
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
bool hasVectorValue(Value *Key, unsigned Part) const
void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
Encapsulates MemorySSA, including all data associated with memory accesses.
const TargetLibraryInfo * TLI
Target Library Info.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Value * emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL, const InductionDescriptor &ID) const
Compute the transformed value of Index at offset StartValue using step StepValue. ...
const Function * TheFunction
An analysis that produces DemandedBits for a function.
This file contains the simple types necessary to represent the attributes associated with functions a...
A recipe for handling all phi nodes except for integer and FP inductions.
Legacy analysis pass which computes BlockFrequencyInfo.
void setName(const Twine &newName)
void setWideningDecision(Instruction *I, unsigned VF, InstWidening W, unsigned Cost)
Save vectorization decision W and Cost taken by the cost model for instruction I and vector width VF...
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void setName(const Twine &Name)
Change the name of the value.
Analysis pass that exposes the LoopInfo for a function.
RPOIterator endRPO() const
bool isOptimizableIVTruncate(Instruction *I, unsigned VF)
Return True if instruction I is an optimizable truncate whose operand is an induction variable...
mir Rename Register Operands
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
BasicBlock * LoopExitBlock
The ExitBlock of the scalar loop.
static void cse(BasicBlock *BB)
Perform cse of induction variable instructions.
bool isScalarEpilogueAllowed() const
Returns true if a scalar epilogue is not allowed due to optsize or a loop hint annotation.
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Type * getSourceElementType() const
Value * getOrCreateVectorTripCount(Loop *NewLoop)
Returns (and creates if needed) the trip count of the widened loop.
CallInst * CreateMaskedGather(Value *Ptrs, unsigned Align, Value *Mask=nullptr, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Gather intrinsic.
virtual Value * reverseVector(Value *Vec)
Generate a shuffle sequence that will reverse the vector Vec.
This file implements a class to represent arbitrary precision integral constant values and operations...
BlockT * getHeader() const
VPBlendRecipe * tryToBlend(Instruction *I, VPlanPtr &Plan)
Handle non-loop phi nodes.
int isConsecutivePtr(Value *Ptr)
Check if this pointer is consecutive when vectorizing.
void sinkScalarOperands(Instruction *PredInst)
Iteratively sink the scalarized operands of a predicated instruction into the block that was created ...
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
Class to represent function types.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Type * getType() const
All values are typed, get the type of this value.
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
VPRegionBlock * createReplicateRegion(Instruction *I, VPRecipeBase *PredRecipe, VPlanPtr &Plan)
Create a replicating region for instruction I that requires predication.
Drive the analysis of interleaved memory accesses in the loop.
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool isInductionVariable(const Value *V)
Returns True if V can be considered as an induction variable in this loop.
static cl::opt< unsigned > MaxNestedScalarReductionIC("max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden, cl::desc("The maximum interleave count to use when interleaving a scalar " "reduction in a nested loop."))
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
This file provides a LoopVectorizationPlanner class.
void fixNonInductionPHIs(void)
Fix the non-induction PHIs in the OrigPHIsToFix vector.
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
const T & getValue() const LLVM_LVALUE_FUNCTION
void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc=nullptr)
Widen an integer or floating-point induction variable IV.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
SmallVector< RegisterUsage, 8 > calculateRegisterUsage(ArrayRef< unsigned > VFs)
iterator begin()
Get an iterator to the beginning of the SetVector.
static Type * smallestIntegerVectorType(Type *T1, Type *T2)
The group of interleaved loads/stores sharing the same stride and close to each other.
This header provides classes for managing per-loop analyses.
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name="", Instruction *InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
ReductionList * getReductionVars()
Returns the reduction variables found in the loop.
PHINode * getPrimaryInduction()
Returns the primary induction variable.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
iterator_range< User::op_iterator > arg_operands()
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
A struct that represents some properties of the register usage of a loop.
Not an induction variable.
Value * getOrCreateTripCount(Loop *NewLoop)
Returns (and creates if needed) the original loop trip count.
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
bool isLegalMaskedScatter(Type *DataType, MaybeAlign Alignment)
Returns true if the target machine supports masked scatter operation for the given DataType...
unsigned getLoadStoreAddressSpace(Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
SmallPtrSet< const Value *, 16 > VecValuesToIgnore
Values to ignore in the cost model when VF > 1.
bool blockNeedsPredication(BasicBlock *BB)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
bool isLegalGatherOrScatter(Value *V)
Returns true if the target machine can represent V as a masked gather or scatter operation.
uint64_t value() const
This is a hole in the type system and should not be abused.
Align getValueOrABITypeAlignment(MaybeAlign Alignment, Type *Ty) const
Helper function to return Alignment if it's set or the result of getABITypeAlignment(Ty), in any case the result is a valid alignment.
static cl::opt< bool > PreferPredicateOverEpilog("prefer-predicate-over-epilog", cl::init(false), cl::Hidden, cl::desc("Indicate that an epilogue is undesired, predication should be " "used instead."))
void takeName(Value *V)
Transfer the name from V to this value.
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Value * getOrCreateVectorValue(Value *V, unsigned Part)
getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a vector or scalar value on-...
iterator find(const KeyT &Key)
static unsigned determineVPlanVF(const unsigned WidestVectorRegBits, LoopVectorizationCostModel &CM)
Optional< unsigned > computeMaxVF()
void truncateToMinimalBitwidths()
Shrinks vector element sizes to the smallest bitwidth they can be legally represented as...
VectorType * getType() const
Overload to return most specific vector type.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
BasicBlock * createVectorizedLoopSkeleton()
Create a new empty loop.
void execute(VPTransformState &State) override
Produce widened copies of all Ingredients.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass)
Emit a bypass check to see if the vector trip count is zero, including if it overflows.
This class represents a truncation of integer types.
void resetScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar)
Reset the scalar value associated with Key for Part and Lane.
void execute(VPTransformState &State) override
Generate the gep nodes.
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
bool isPredicatedInst(Instruction *I)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
Pointer induction var. Step = C / sizeof(elem).
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
void execute(VPTransformState &State) override
Generates phi nodes for live-outs as needed to retain SSA form.
Value * CreateNAryOp(unsigned Opc, ArrayRef< Value *> Ops, const Twine &Name="", MDNode *FPMathTag=nullptr)
Create either a UnaryOperator or BinaryOperator depending on Opc.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
iterator find(const_arg_type_t< KeyT > Val)
void widenInstruction(Instruction &I)
Widen a single instruction within the innermost loop.
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
BasicBlock * LoopMiddleBlock
Middle Block between the vector and the scalar.
std::pair< Instruction *, Instruction * > addRuntimeChecks(Instruction *Loc) const
Add code that checks at runtime if the accessed arrays overlap.
bool isVoidTy() const
Return true if this is 'void'.
bool InterleaveOnlyWhenForced
If false, consider all loops for interleaving.
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
void setBestPlan(unsigned VF, unsigned UF)
Finalize the best decision and dispose of all other VPlans.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static bool runOnFunction(Function &F, bool PostInlining)
enum ForceKind getForce() const
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II, Value *CountRoundDown, Value *EndValue, BasicBlock *MiddleBlock)
Set up the values of the IVs correctly when exiting the vector loop.
This instruction inserts a single (scalar) element into a VectorType value.
void restoreIP(InsertPoint IP)
Sets the current insert point to a previously-saved location.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
static cl::opt< bool > EnableCondStoresVectorization("enable-cond-stores-vec", cl::init(true), cl::Hidden, cl::desc("Enable if predication of stores during vectorization."))
Integer induction variable. Step = C.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF)
A helper function that returns true if the given type is irregular.
Value * concatenateVectors(IRBuilder<> &Builder, ArrayRef< Value *> Vecs)
Concatenate a list of vectors.
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
This file contains the declarations of the Vectorization Plan base classes:
The instances of the Type class are immutable: once they are created, they are never changed...
bool isProfitableToScalarize(Instruction *I, unsigned VF) const
This is an important class for using LLVM in a threaded context.
void fixVectorizedLoop()
Fix the vectorized code, taking care of header phi's, live-outs, and more.
ConstantInt * getTrue()
Get the constant value for i1 true.
Conditional or Unconditional Branch instruction.
Min/max implemented in terms of select(cmp()).
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Value handle that tracks a Value across RAUW.
BasicBlock * LoopScalarBody
The scalar loop body.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
size_t size() const
size - Get the array size.
const char * getOpcodeName() const
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static Instruction * getDebugLocFromInstOrOperands(Instruction *I)
Look for a meaningful debug location on the instruction or it's operands.
This is an important base class in LLVM.
bool hasScalarValue(Value *Key, const VPIteration &Instance) const
This analysis provides dependence information for the memory accesses of a loop.
bool prepareToFoldTailByMasking()
Return true if we can vectorize this loop while folding its tail by masking, and mark all respective ...
PredicatedScalarEvolution & PSE
Predicated scalar evolution analysis.
InsertPoint saveIP() const
Returns the current insert point.
void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr)
Set the debug location in the builder using the debug location in the instruction.
void clearReductionWrapFlags(RecurrenceDescriptor &RdxDesc)
Clear NSW/NUW flags from reduction instructions if necessary.
const SCEV * getStep() const
void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State, VPValue *Addr, VPValue *BlockInMask=nullptr)
Vectorize Load and Store instructions with the base address given in Addr, optionally masking the vec...
Constant * createReplicatedMask(IRBuilder<> &Builder, unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool getDecisionAndClampRange(const std::function< bool(unsigned)> &Predicate, VFRange &Range)
Test a Predicate on a Range of VF's.
Value * createMinMaxOp(IRBuilder<> &Builder, RecurrenceDescriptor::MinMaxRecurrenceKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
bool isPointerTy() const
True if this is an instance of PointerType.
static Value * addFastMathFlag(Value *V)
A helper function that adds a 'fast' flag to floating-point operations.
bool foldTailByMasking() const
Returns true if all loop blocks should be masked to fold tail loop.
A manager for alias analyses.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static const char *const LLVMLoopVectorizeFollowupEpilogue
InterleavedAccessInfo & InterleaveInfo
The interleave access information contains groups of interleaved accesses with the same stride and cl...
std::unique_ptr< VPlan > VPlanPtr
static cl::opt< unsigned > SmallLoopCost("small-loop-cost", cl::init(20), cl::Hidden, cl::desc("The cost of a loop that is considered 'small' by the interleaver."))
Represent the analysis usage information of a pass.
PHINode * Induction
The new Induction variable which was added to the new block.
void predicate(void)
Predicate Plan's HCFG.
unsigned getNumLoads() const
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
bool hasFunNoNaNAttr() const
bool isReductionVariable(PHINode *PN)
Returns True if PN is a reduction variable in this loop.
uint32_t getIndex(const InstTy *Instr) const
Get the index for the given member.
Analysis pass providing a never-invalidated alias analysis result.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
void fixCrossIterationPHIs()
Handle all cross-iteration phis in the header.
void fixFirstOrderRecurrence(PHINode *Phi)
Fix a first-order recurrence.
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
VectorizationFactor selectVectorizationFactor(unsigned MaxVF)
Constant * createBitMaskForGaps(IRBuilder<> &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
self_iterator getIterator()
unsigned UF
The vectorization unroll factor to use.
Optional< unsigned > getLoopEstimatedTripCount(Loop *L)
Get a loop's estimated trip count based on branch weight metadata.
static cl::opt< unsigned > ForceTargetNumVectorRegs("force-target-num-vector-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of vector registers."))
const RuntimePointerChecking * getRuntimePointerChecking() const
Returns the information that we collected about runtime memory check.
static CastInst * CreatePointerCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
void printAsOperand(raw_ostream &OS) const
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
bool isLegalMaskedStore(Type *DataType, Value *Ptr, MaybeAlign Alignment)
Returns true if the target machine supports masked store operation for the given DataType and kind of...
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch...
const Value * getCondition() const
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
AssumptionCache * AC
Assumption cache.
bool runImpl(Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_, DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_, DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_, std::function< const LoopAccessInfo &(Loop &)> &GetLAA_, OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_)
bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
AssumptionCache * AC
Assumption Cache.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
static void connectBlocks(VPBlockBase *From, VPBlockBase *To)
Connect VPBlockBases From and To bi-directionally.
static unsigned getIncomingValueNumForOperand(unsigned i)
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
RecurrenceKind getRecurrenceKind()
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar)
Set a scalar value associated with Key and Instance.
bool requiresScalarEpilogue() const
Returns true if an interleaved group requires a scalar iteration to handle accesses with gaps...
static unsigned getRecurrenceBinOp(RecurrenceKind Kind)
Returns the opcode of binary operation corresponding to the RecurrenceKind.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void recordRecipeOf(Instruction *I)
Mark given ingredient for recording its recipe once one is created for it.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
This struct is a compact representation of a valid (non-zero power of two) alignment.
void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass)
Emit bypass checks to check any memory assumptions we may have made.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
static const char *const LLVMLoopVectorizeFollowupVectorized
BasicBlock * LoopVectorBody
The vector loop body.
void fixReduction(PHINode *Phi)
Fix a reduction cross-iteration phi.
void executePlan(InnerLoopVectorizer &LB, DominatorTree *DT)
Generate the IR code for the body of the vectorized loop according to the best selected VPlan...
Planner drives the vectorization process after having passed Legality checks.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
unsigned getPredicate() const
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
const VPRecipeBase & back() const
static bool processLoopInVPlanNativePath(Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, LoopVectorizationLegality *LVL, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints)
A SetVector that performs no allocations if smaller than a certain size.
This file defines the VPlanPredicator class which contains the public interfaces to predicate and lin...
Analysis pass which computes BlockFrequencyInfo.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
This file defines the VPlanHCFGBuilder class which contains the public interface (buildHierarchicalCF...
static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop, Instruction *I)
Create an analysis remark that explains why vectorization failed.
static bool mayDivideByZero(Instruction &I)
A helper function for checking whether an integer division-related instruction may divide by zero (in...
LoopVectorizationLegality * Legal
Vectorization legality.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, VPValue *Condition, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBases IfTrue and IfFalse after BlockPtr.
bool VectorizeOnlyWhenForced
If false, consider all loops for vectorization.
This is the shared class of boolean and integer constants.
const SCEVUnionPredicate & getUnionPredicate() const
Type * getType() const
Return the LLVM type of this SCEV expression.
A struct for saving information about induction variables.
BlockVerifier::State From
A range of powers-of-2 vectorization factors with fixed start and adjustable end. ...
Align max(MaybeAlign Lhs, Align Rhs)
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
BasicBlock * LoopVectorPreHeader
The vector-loop preheader.
bool isFunctionVectorizable(StringRef F, unsigned VF) const
This holds vectorization requirements that must be verified late in the process.
cl::opt< bool > EnableVPlanNativePath("enable-vplan-native-path", cl::init(false), cl::Hidden, cl::desc("Enable VPlan-native vectorization path with " "support for outer loop vectorization."))
bool runtimeChecksRequired()
static cl::opt< bool > EnableLoadStoreRuntimeInterleave("enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden, cl::desc("Enable runtime interleaving until load/store ports are saturated"))
bool isAccessInterleaved(Instruction *Instr)
Check if Instr belongs to any interleaved access group.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
SmallPtrSet< const Value *, 16 > ValuesToIgnore
Values to ignore in the cost model.
Module.h This file contains the declarations for the Module class.
Value * CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, const Twine &Name="")
Provides information about what library functions are available for the current target.
void buildVPlans(unsigned MinVF, unsigned MaxVF)
Build VPlans for power-of-2 VF's between MinVF and MaxVF inclusive, according to the information gath...
VPValue * createEdgeMask(BasicBlock *Src, BasicBlock *Dst, VPlanPtr &Plan)
A helper function that computes the predicate of the edge between SRC and DST.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
static void debugVectorizationFailure(const StringRef DebugMsg, Instruction *I)
Write a record DebugMsg about vectorization failure to the debug output stream.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
size_type count(const KeyT &Key) const
bool isAggregateType() const
Return true if the type is an aggregate type.
bool isFirstOrderRecurrence(const PHINode *Phi)
Returns True if Phi is a first-order recurrence in this loop.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
An analysis that produces MemorySSA for a function.
void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal, const InductionDescriptor &ID)
Compute scalar induction steps.
static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI)
CallInst * CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align, Value *Mask)
Create a call to Masked Store intrinsic.
LLVM_NODISCARD T pop_back_val()
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
unsigned getMaxSafeDepDistBytes()
static const SCEV * getAddressAccessSCEV(Value *Ptr, LoopVectorizationLegality *Legal, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets Address Access SCEV after verifying that the access pattern is loop invariant except the inducti...
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Drive the analysis of memory accesses in the loop.
static Constant * getSignedIntOrFpConstant(Type *Ty, int64_t C)
A helper function that returns an integer or floating-point constant with value C.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
static cl::opt< bool > EnableIndVarRegisterHeur("enable-ind-var-reg-heur", cl::init(true), cl::Hidden, cl::desc("Count the induction variable only once when interleaving"))
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
pred_range predecessors(BasicBlock *BB)
const VPBlocksTy & getSuccessors() const
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
CallInst * CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the vector form of the intrinsic has a scalar operand.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
StringRef getVectorizedFunction(StringRef F, unsigned VF) const
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
void setOperand(unsigned i, Value *Val)
Value * createTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, RecurrenceDescriptor &Desc, Value *Src, bool NoNaN=false)
Create a generic target reduction using a recurrence descriptor Desc The target is queried to determi...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Optional< MDNode * > makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef< StringRef > FollowupAttrs, const char *InheritOptionsAttrsPrefix="", bool AlwaysNew=false)
Create a new loop identifier for a loop created from a loop transformation.
uint32_t getAlignment() const
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
unsigned getVectorNumElements() const
static Constant * getRecurrenceIdentity(RecurrenceKind K, Type *Tp)
Returns identity corresponding to the RecurrenceKind.
Store the result of a depth first search within basic blocks contained by a single loop...
void clear()
Completely clear the SetVector.
A range adaptor for a pair of iterators.
DenseMap< PHINode *, Value * > IVEndValues
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Class to represent vector types.
VectorizationFactor planInVPlanNativePath(unsigned UserVF)
Use the VPlan-native path to plan how to best vectorize, return the best VF and its cost...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static Optional< unsigned > getSmallBestKnownTC(ScalarEvolution &SE, Loop *L)
Returns "best known" trip count for the specified loop L as defined by the following procedure: 1) Re...
Target - Wrapper for Target specific information.
bool isInductionPhi(const Value *V)
Returns True if V is a Phi node of an induction variable in this loop.
cl::opt< bool > EnableVPlanPredication("enable-vplan-predication", cl::init(false), cl::Hidden, cl::desc("Enable VPlan-native vectorization path predicator with " "support for outer loop vectorization."))
void collectUniformsAndScalars(unsigned VF)
Collect Uniform and Scalar values for the given VF.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
void addMetadata(Instruction *To, Instruction *From)
Add metadata from one instruction to another.
const LoopAccessInfo * getLAI() const
void resetVectorValue(Value *Key, unsigned Part, Value *Vector)
Reset the vector value associated with Key for the given Part.
LoopInfo * LI
Loop Info analysis.
bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile...
iterator_range< user_iterator > users()
unsigned getVectorCallCost(CallInst *CI, unsigned VF, bool &NeedToScalarize)
Estimate cost of a call instruction CI if it were vectorized with factor VF.
static const char lv_name[]
This class uses information about analyze scalars to rewrite expressions in canonical form...
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
static cl::opt< unsigned > ForceTargetMaxVectorInterleaveFactor("force-target-max-vector-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "vectorized loops."))
bool isLegalMaskedLoad(Type *DataType, Value *Ptr, MaybeAlign Alignment)
Returns true if the target machine supports masked load operation for the given DataType and kind of ...
Value * VectorTripCount
Trip count of the widened loop (TripCount - TripCount % (VF*UF))
loop Loop Strength Reduction
static cl::opt< bool > VPlanBuildStressTest("vplan-build-stress-test", cl::init(false), cl::Hidden, cl::desc("Build VPlan for every supported loop nest in the function and bail " "out right after the build (stress test the VPlan H-CFG construction " "in the VPlan-native vectorization path)."))
ValueT lookup(const KeyT &Key) const
const TargetTransformInfo & TTI
Vector target information.
ConstantInt * getFalse()
Get the constant value for i1 false.
const SmallVectorImpl< Instruction * > & getCastInsts() const
Returns a reference to the type cast instructions in the induction update chain, that are redundant w...
LoopVectorizationCostModel * Cost
The profitablity analysis.
Analysis pass that exposes the ScalarEvolution for a function.
void setWideningDecision(const InterleaveGroup< Instruction > *Grp, unsigned VF, InstWidening W, unsigned Cost)
Save vectorization decision W and Cost taken by the cost model for interleaving group Grp and vector ...
Constant * createStrideMask(IRBuilder<> &Builder, unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
PHINode * OldInduction
The induction variable of the old basic block.
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
bool blockNeedsPredication(BasicBlock *BB)
bool interleavedAccessCanBeWidened(Instruction *I, unsigned VF=1)
Returns true if I is a memory instruction in an interleaved-group of memory accesses that can be vect...
LoopT * getParentLoop() const
static unsigned getReciprocalPredBlockProb()
A helper function that returns the reciprocal of the block probability of predicated blocks...
Analysis pass providing a never-invalidated alias analysis result.
iterator_range< op_iterator > indices()
const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
static cl::opt< unsigned > TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16), cl::Hidden, cl::desc("Loops with a constant trip count that is smaller than this " "value are vectorized only if no scalar iteration overheads " "are incurred."))
Loops with a known constant trip count below this number are vectorized only if no scalar iteration o...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
This analysis provides dependence information for the memory accesses of a loop.
uint64_t getMaxSafeRegisterWidth() const
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
static Type * getMemInstValueType(Value *I)
A helper function that returns the type of loaded or stored value.
static ScalarEpilogueLowering getScalarEpilogueLowering(Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, LoopVectorizationLegality &LVL)
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void packScalarIntoVectorValue(Value *V, const VPIteration &Instance)
Construct the vector value of a scalarized value V one lane at a time.
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
bool areSafetyChecksAdded()
This class represents an analyzed expression in the program.
Value * getVectorValue(Value *Key, unsigned Part)
Retrieve the existing vector value that corresponds to Key and Part.
static cl::opt< bool > EnableInterleavedMemAccesses("enable-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on interleaved memory accesses in a loop"))
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
LLVM_NODISCARD bool empty() const
bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const
Floating point induction variable.
Instruction * getLoopExitInstr()
void execute(VPTransformState &State) override
Generate the phi/select nodes.
Represents a single loop in the control flow graph.
VPBasicBlock * handleReplication(Instruction *I, VFRange &Range, VPBasicBlock *VPBB, DenseMap< Instruction *, VPReplicateRecipe *> &PredInst2Recipe, VPlanPtr &Plan)
Build a VPReplicationRecipe for I and enclose it within a Region if it is predicated.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
InductionList * getInductionVars()
Returns the induction variables found in the loop.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isUniformAfterVectorization(Instruction *I, unsigned VF) const
Returns true if I is known to be uniform after vectorization.
void collectInstsToScalarize(unsigned VF)
Collects the instructions to scalarize for each predicated instruction in the loop.
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
user_iterator_impl< User > user_iterator
void execute(VPTransformState &State) override
Generate the vectorized and scalarized versions of the phi node as needed by their users...
PHINode * createInductionVariable(Loop *L, Value *Start, Value *End, Value *Step, Instruction *DL)
Create a new induction variable inside L.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
uint32_t getFactor() const
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
iterator_range< value_op_iterator > operand_values()
bool all() const
Returns true if all bits are set.
Loop * OrigLoop
The original loop.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
unsigned getWideningCost(Instruction *I, unsigned VF)
Return the vectorization cost for the given instruction I and vector width VF.
void preserve()
Mark an analysis as preserved.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector and ...
TypeSize getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
InstWidening getWideningDecision(Instruction *I, unsigned VF)
Return the cost model decision for the given instruction I and vector width VF.
LLVM_NODISCARD bool empty() const
void setVectorValue(Value *Key, unsigned Part, Value *Vector)
Set a vector value associated with Key and Part.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Analysis pass providing the TargetLibraryInfo.
AliasAnalysis * AA
Alias Analysis.
LoopVectorizationLegality * Legal
The legality analysis.
const SmallVectorImpl< const SCEVPredicate * > & getPredicates() const
cl::opt< bool > EnableLoopVectorization
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
separate const offset from gep
void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
void widenGEP(GetElementPtrInst *GEP, unsigned UF, unsigned VF, bool IsPtrLoopInvariant, SmallBitVector &IsIndexLoopInvariant)
Vectorize a single GetElementPtrInst based on information gathered and decisions taken during plannin...
Constant * createInterleaveMask(IRBuilder<> &Builder, unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isExplicitVecOuterLoop(Loop *OuterLp, OptimizationRemarkEmitter *ORE)
SmallPtrSet< Instruction *, 8 > & getCastInsts()
Returns a reference to the instructions used for type-promoting the recurrence.
unsigned VF
The vectorization SIMD factor to use.
CallInst * CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned Align, Value *Mask=nullptr)
Create a call to Masked Scatter intrinsic.
A raw_ostream that writes to an std::string.
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
VPWidenRecipe is a recipe for producing a copy of vector type for each Instruction in its ingredients...
IRBuilder Builder
The builder that we use.
uint64_t PowerOf2Floor(uint64_t A)
Returns the power of two which is less than or equal to the given value.
InstTy * getInsertPos() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
virtual Value * getBroadcastInstrs(Value *V)
Create a broadcast instruction.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
A recipe for generating conditional branches on the bits of a mask.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
BasicBlock::iterator GetInsertPoint() const
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
This class implements an extremely fast bulk output stream that can only output to a stream...
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
Type * getElementType() const
The legacy pass manager's analysis pass to compute loop information.
print Print MemDeps of function
SmallVector< BasicBlock *, 4 > LoopBypassBlocks
A list of all bypass blocks. The first block is the entry of the loop.
static Type * ToVectorTy(Type *Scalar, unsigned VF)
A helper function for converting Scalar types to vector types.
const TargetTransformInfo * TTI
Target Transform Info.
bool hasOneUse() const
Return true if there is exactly one user of this value.
Convenience struct for specifying and reasoning about fast-math flags.
StringRef - Represent a constant reference to a string, i.e.
This is the interface for LLVM's primary stateless and local alias analysis.
A recipe for vectorizing a phi-node as a sequence of mask-based select instructions.
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
A container for analyses that lazily runs them and caches their results.
VectorizerValueMap VectorLoopValueMap
Maps values from the original loop to their corresponding values in the vectorized loop...
Legacy analysis pass which computes a DominatorTree.
void selectUserVectorizationFactor(unsigned UserVF)
Setup cost-based decisions for user vectorization factor.
bool shouldScalarizeInstruction(Instruction *I) const
Returns true if an instruction I should be scalarized instead of vectorized for the chosen vectorizat...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
void setIncomingValue(unsigned i, Value *V)
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
unsigned getNumOperands() const
Return number of MDNode operands.
static BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
static cl::opt< unsigned > ForceTargetInstructionCost("force-target-instruction-cost", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's expected cost for " "an instruction to a single constant value. Mostly " "useful for getting consistent testing."))
unsigned getNumStores() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
iterator_range< block_iterator > blocks() const
MaybeAlign getLoadStoreAlignment(Value *I)
A helper function that returns the alignment of load or store instruction.
VPWidenIntOrFpInductionRecipe * tryToOptimizeInduction(Instruction *I, VFRange &Range)
Check if an induction recipe should be constructed for within the given VF Range.
void setCostBasedWideningDecision(unsigned VF)
Memory access instruction may be vectorized in more than one way.
bool isScalarAfterVectorization(Instruction *I, unsigned VF) const
Returns true if I is known to be scalar after vectorization.
Optional< VectorizationFactor > plan(unsigned UserVF)
Plan how to best vectorize, return the best VF and its cost, or None if vectorization and interleavin...
static Constant * get(ArrayRef< Constant *> V)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
DenseMap< Instruction *, Instruction * > & getSinkAfter()
Return the set of instructions to sink to handle first-order recurrences.
static cl::opt< unsigned > ForceTargetMaxScalarInterleaveFactor("force-target-max-scalar-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "scalar loops."))
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
bool isLegalMaskedGather(Type *DataType, MaybeAlign Alignment)
Returns true if the target machine supports masked gather operation for the given DataType...
detail::enumerator< R > enumerate(R &&TheRange)
Given an input range, returns a new range whose values are are pair (A,B) such that A is the 0-based ...
RecurrenceKind
This enum represents the kinds of recurrences that we support.
const BasicBlock * getParent() const
bool needsScalarInduction(Instruction *IV) const
Returns true if we should generate a scalar version of IV.
bool requiresScalarEpilogue() const
Returns true if this Group requires a scalar iteration to handle gaps.
InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo *TTI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, unsigned UnrollFactor, LoopVectorizationLegality *LVL, LoopVectorizationCostModel *CM)
Legacy wrapper pass to provide the BasicAAResult object.
bool Need
This flag indicates if we need to add the runtime check.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Type * getRecurrenceType()
Returns the type of the recurrence.
std::pair< unsigned, unsigned > getSmallestAndWidestTypes()
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.