104 using namespace llvm;
105 using namespace llvm::PatternMatch;
107 #define LV_NAME "loop-vectorize"
108 #define DEBUG_TYPE LV_NAME
110 STATISTIC(LoopsVectorized,
"Number of loops vectorized");
111 STATISTIC(LoopsAnalyzed,
"Number of loops analyzed for vectorization");
115 cl::desc(
"Enable if-conversion during vectorization."));
121 cl::desc(
"Loops with a constant trip count that is smaller than this "
122 "value are vectorized only if no scalar iteration overheads "
127 cl::desc(
"Maximize bandwidth when selecting vectorization factor which "
128 "will be determined by the smallest type in loop."));
132 cl::desc(
"Enable vectorization on interleaved memory accesses in a loop"));
137 cl::desc(
"Maximum factor for an interleaved access group (default = 8)"),
146 cl::desc(
"A flag that overrides the target's number of scalar registers."));
150 cl::desc(
"A flag that overrides the target's number of vector registers."));
157 cl::desc(
"A flag that overrides the target's max interleave factor for "
162 cl::desc(
"A flag that overrides the target's max interleave factor for "
163 "vectorized loops."));
167 cl::desc(
"A flag that overrides the target's expected cost for "
168 "an instruction to a single constant value. Mostly "
169 "useful for getting consistent testing."));
174 "The cost of a loop that is considered 'small' by the interleaver."));
178 cl::desc(
"Enable the use of the block frequency analysis to access PGO "
179 "heuristics minimizing code growth in cold regions and being more "
180 "aggressive in hot regions."));
186 "Enable runtime interleaving until load/store ports are saturated"));
191 cl::desc(
"Max number of stores to be predicated behind an if."));
195 cl::desc(
"Count the induction variable only once when interleaving"));
199 cl::desc(
"Enable if predication of stores during vectorization."));
203 cl::desc(
"The maximum interleave count to use when interleaving a scalar "
204 "reduction in a nested loop."));
208 cl::desc(
"The maximum allowed number of runtime memory checks with a "
209 "vectorize(enable) pragma."));
213 cl::desc(
"The maximum number of SCEV checks allowed."));
217 cl::desc(
"The maximum number of SCEV checks allowed with a "
218 "vectorize(enable) pragma"));
234 CodeRegion =
I->getParent();
237 if (
I->getDebugLoc())
238 DL =
I->getDebugLoc();
242 R <<
"loop not vectorized: ";
249 class LoopVectorizeHints;
250 class LoopVectorizationLegality;
251 class LoopVectorizationCostModel;
252 class LoopVectorizationRequirements;
256 static bool hasCyclesInLoopBody(
const Loop &
L) {
260 for (
const auto &SCC :
263 if (SCC.size() > 1) {
264 DEBUG(
dbgs() <<
"LVL: Detected a cycle in the loop body:\n");
288 if (
auto *LI = dyn_cast<LoadInst>(I))
289 return LI->getPointerOperand();
290 if (
auto *
SI = dyn_cast<StoreInst>(I))
291 return SI->getPointerOperand();
296 static Type *getMemInstValueType(
Value *I) {
297 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
298 "Expected Load or Store instruction");
299 if (
auto *LI = dyn_cast<LoadInst>(I))
300 return LI->getType();
301 return cast<StoreInst>(
I)->getValueOperand()->getType();
305 static unsigned getMemInstAlignment(
Value *I) {
306 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
307 "Expected Load or Store instruction");
308 if (
auto *LI = dyn_cast<LoadInst>(I))
309 return LI->getAlignment();
315 static unsigned getMemInstAddressSpace(
Value *I) {
316 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
317 "Expected Load or Store instruction");
318 if (
auto *LI = dyn_cast<LoadInst>(I))
319 return LI->getPointerAddressSpace();
320 return cast<StoreInst>(
I)->getPointerAddressSpace();
346 static unsigned getReciprocalPredBlockProb() {
return 2; }
350 if (isa<FPMathOperator>(V)) {
353 cast<Instruction>(V)->setFastMathFlags(Flags);
360 static Constant *getSignedIntOrFpConstant(
Type *Ty, int64_t
C) {
379 class InnerLoopVectorizer {
386 unsigned UnrollFactor, LoopVectorizationLegality *LVL,
387 LoopVectorizationCostModel *CM)
388 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
389 AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
390 Builder(PSE.getSE()->getContext()), Induction(nullptr),
391 OldInduction(nullptr), VectorLoopValueMap(UnrollFactor, VecWidth),
392 TripCount(nullptr), VectorTripCount(nullptr), Legal(LVL), Cost(CM),
393 AddedSafetyChecks(
false) {}
396 void createVectorizedLoopSkeleton();
402 void fixVectorizedLoop();
405 bool areSafetyChecksAdded() {
return AddedSafetyChecks; }
407 virtual ~InnerLoopVectorizer() {}
440 void fixCrossIterationPHIs();
444 void fixFirstOrderRecurrence(
PHINode *Phi);
448 void fixReduction(
PHINode *Phi);
462 void predicateInstructions();
466 void truncateToMinimalBitwidths();
471 VectorParts createBlockInMask(
BasicBlock *BB);
479 void widenPHIInstruction(
Instruction *PN,
unsigned UF,
unsigned VF);
483 void updateAnalysis();
489 void scalarizeInstruction(
Instruction *Instr,
bool IfPredicateInstr =
false);
492 virtual void vectorizeMemoryInstruction(
Instruction *Instr);
506 Instruction::BinaryOpsEnd);
531 bool shouldScalarizeInstruction(
Instruction *I)
const;
557 Value *getOrCreateVectorValue(
Value *V,
unsigned Part);
563 Value *getOrCreateScalarValue(
Value *V,
unsigned Part,
unsigned Lane);
572 Value *getOrCreateTripCount(
Loop *NewLoop);
575 Value *getOrCreateVectorTripCount(
Loop *NewLoop);
629 ValueMap(
unsigned UF,
unsigned VF) : UF(UF), VF(VF) {}
632 bool hasAnyVectorValue(
Value *Key)
const {
633 return VectorMapStorage.count(Key);
637 bool hasVectorValue(
Value *Key,
unsigned Part)
const {
638 assert(Part < UF &&
"Queried Vector Part is too large.");
639 if (!hasAnyVectorValue(Key))
641 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
642 assert(Entry.size() == UF &&
"VectorParts has wrong dimensions.");
643 return Entry[Part] !=
nullptr;
647 bool hasAnyScalarValue(
Value *Key)
const {
648 return ScalarMapStorage.count(Key);
653 bool hasScalarValue(
Value *Key,
unsigned Part,
unsigned Lane)
const {
654 assert(Part < UF &&
"Queried Scalar Part is too large.");
655 assert(Lane < VF &&
"Queried Scalar Lane is too large.");
656 if (!hasAnyScalarValue(Key))
658 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
659 assert(Entry.size() == UF &&
"ScalarParts has wrong dimensions.");
660 assert(Entry[Part].size() == VF &&
"ScalarParts has wrong dimensions.");
661 return Entry[Part][Lane] !=
nullptr;
666 Value *getVectorValue(
Value *Key,
unsigned Part) {
667 assert(hasVectorValue(Key, Part) &&
"Getting non-existent value.");
668 return VectorMapStorage[Key][Part];
673 Value *getScalarValue(
Value *Key,
unsigned Part,
unsigned Lane) {
674 assert(hasScalarValue(Key, Part, Lane) &&
"Getting non-existent value.");
675 return ScalarMapStorage[Key][Part][Lane];
680 void setVectorValue(
Value *Key,
unsigned Part,
Value *Vector) {
681 assert(!hasVectorValue(Key, Part) &&
"Vector value already set for part");
682 if (!VectorMapStorage.count(Key)) {
683 VectorParts Entry(UF);
684 VectorMapStorage[Key] = Entry;
686 VectorMapStorage[Key][Part] = Vector;
691 void setScalarValue(
Value *Key,
unsigned Part,
unsigned Lane,
693 assert(!hasScalarValue(Key, Part, Lane) &&
"Scalar value already set");
694 if (!ScalarMapStorage.count(Key)) {
695 ScalarParts Entry(UF);
696 for (
unsigned Part = 0; Part < UF; ++Part)
697 Entry[Part].resize(VF,
nullptr);
700 ScalarMapStorage[Key] = Entry;
702 ScalarMapStorage[Key][Part][Lane] =
Scalar;
709 void resetVectorValue(
Value *Key,
unsigned Part,
Value *Vector) {
710 assert(hasVectorValue(Key, Part) &&
"Vector value not set for part");
711 VectorMapStorage[Key][Part] = Vector;
725 std::map<Value *, VectorParts> VectorMapStorage;
726 std::map<Value *, ScalarParts> ScalarMapStorage;
755 std::unique_ptr<LoopVersioning> LVer;
800 EdgeMaskCacheTy EdgeMaskCache;
801 BlockMaskCacheTy BlockMaskCache;
805 Value *VectorTripCount;
808 LoopVectorizationLegality *Legal;
811 LoopVectorizationCostModel *Cost;
814 bool AddedSafetyChecks;
821 class InnerLoopUnroller :
public InnerLoopVectorizer {
828 LoopVectorizationLegality *LVL,
829 LoopVectorizationCostModel *CM)
830 : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
831 UnrollFactor, LVL, CM) {}
834 void vectorizeMemoryInstruction(
Instruction *Instr)
override;
838 Instruction::BinaryOpsEnd)
override;
853 if (
Instruction *OpInst = dyn_cast<Instruction>(*OI))
854 if (OpInst->getDebugLoc() != Empty)
862 if (
const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
864 if (DIL && Inst->getFunction()->isDebugInfoForProfiling())
874 static std::string getDebugLocString(
const Loop *L) {
879 LoopDbgLoc.print(OS);
882 OS << L->
getHeader()->getParent()->getParent()->getModuleIdentifier();
889 void InnerLoopVectorizer::addNewMetadata(
Instruction *To,
893 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
894 LVer->annotateInstWithNoAlias(To, Orig);
897 void InnerLoopVectorizer::addMetadata(
Instruction *To,
900 addNewMetadata(To, From);
905 for (
Value *V : To) {
907 addMetadata(I, From);
937 class InterleaveGroup {
940 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
941 assert(Align &&
"The alignment should be non-zero");
944 assert(Factor > 1 &&
"Invalid interleave factor");
946 Reverse = Stride < 0;
950 bool isReverse()
const {
return Reverse; }
951 unsigned getFactor()
const {
return Factor; }
953 unsigned getNumMembers()
const {
return Members.size(); }
960 bool insertMember(
Instruction *Instr,
int Index,
unsigned NewAlign) {
961 assert(NewAlign &&
"The new member's alignment should be non-zero");
963 int Key = Index + SmallestKey;
966 if (Members.count(Key))
969 if (Key > LargestKey) {
971 if (Index >= static_cast<int>(Factor))
975 }
else if (Key < SmallestKey) {
977 if (LargestKey - Key >= static_cast<int>(Factor))
985 Members[Key] = Instr;
993 int Key = SmallestKey + Index;
994 if (!Members.count(Key))
997 return Members.find(Key)->second;
1003 for (
auto I : Members)
1004 if (I.second == Instr)
1005 return I.first - SmallestKey;
1010 Instruction *getInsertPos()
const {
return InsertPos; }
1011 void setInsertPos(
Instruction *Inst) { InsertPos = Inst; }
1043 class InterleavedAccessInfo {
1047 : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(nullptr),
1048 RequiresScalarEpilogue(
false) {}
1050 ~InterleavedAccessInfo() {
1053 for (
auto &I : InterleaveGroupMap)
1055 for (
auto *Ptr : DelSet)
1065 return InterleaveGroupMap.count(Instr);
1069 unsigned getMaxInterleaveFactor()
const {
1070 unsigned MaxFactor = 1;
1071 for (
auto &Entry : InterleaveGroupMap)
1072 MaxFactor =
std::max(MaxFactor, Entry.second->getFactor());
1079 InterleaveGroup *getInterleaveGroup(
Instruction *Instr)
const {
1080 if (InterleaveGroupMap.count(Instr))
1081 return InterleaveGroupMap.find(Instr)->second;
1087 bool requiresScalarEpilogue()
const {
return RequiresScalarEpilogue; }
1106 bool RequiresScalarEpilogue;
1116 struct StrideDescriptor {
1117 StrideDescriptor(int64_t Stride,
const SCEV *Scev, uint64_t
Size,
1119 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
1121 StrideDescriptor() =
default;
1125 const SCEV *Scev =
nullptr;
1131 typedef std::pair<Instruction *, StrideDescriptor> StrideEntry;
1137 InterleaveGroup *createInterleaveGroup(
Instruction *Instr,
int Stride,
1139 assert(!InterleaveGroupMap.count(Instr) &&
1140 "Already in an interleaved access group");
1141 InterleaveGroupMap[Instr] =
new InterleaveGroup(Instr, Stride, Align);
1142 return InterleaveGroupMap[Instr];
1146 void releaseGroup(InterleaveGroup *Group) {
1147 for (
unsigned i = 0; i < Group->getFactor(); i++)
1149 InterleaveGroupMap.erase(Member);
1155 void collectConstStrideAccesses(
1160 static bool isStrided(
int Stride) {
1161 unsigned Factor =
std::abs(Stride);
1171 bool areDependencesValid()
const {
1172 return LAI && LAI->getDepChecker().getDependences();
1180 bool canReorderMemAccessesForInterleavedGroups(StrideEntry *
A,
1181 StrideEntry *B)
const {
1198 auto *Src = A->first;
1199 auto SrcDes = A->second;
1202 auto *
Sink = B->first;
1203 auto SinkDes = B->second;
1207 if (!Src->mayWriteToMemory())
1211 if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
1216 if (!areDependencesValid())
1221 return !Dependences.count(Src) || !Dependences.lookup(Src).count(
Sink);
1228 void collectDependences() {
1229 if (!areDependencesValid())
1231 auto *Deps = LAI->getDepChecker().getDependences();
1232 for (
auto Dep : *Deps)
1233 Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
1246 class LoopVectorizeHints {
1247 enum HintKind { HK_WIDTH, HK_UNROLL, HK_FORCE };
1256 : Name(Name), Value(Value), Kind(Kind) {}
1258 bool validate(
unsigned Val) {
1282 bool PotentiallyUnsafe;
1291 LoopVectorizeHints(
const Loop *L,
bool DisableInterleaving,
1295 Interleave(
"interleave.count", DisableInterleaving, HK_UNROLL),
1296 Force(
"vectorize.enable", FK_Undefined, HK_FORCE),
1297 PotentiallyUnsafe(
false), TheLoop(L), ORE(ORE) {
1299 getHintsFromMetadata();
1305 DEBUG(
if (DisableInterleaving && Interleave.Value == 1)
dbgs()
1306 <<
"LV: Interleaving disabled by the pass manager\n");
1310 void setAlreadyVectorized() {
1311 Width.Value = Interleave.Value = 1;
1312 Hint Hints[] = {Width, Interleave};
1313 writeHintsToMetadata(Hints);
1316 bool allowVectorization(
Function *
F,
Loop *L,
bool AlwaysVectorize)
const {
1317 if (getForce() == LoopVectorizeHints::FK_Disabled) {
1318 DEBUG(
dbgs() <<
"LV: Not vectorizing: #pragma vectorize disable.\n");
1319 emitRemarkWithHints();
1323 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
1324 DEBUG(
dbgs() <<
"LV: Not vectorizing: No #pragma vectorize enable.\n");
1325 emitRemarkWithHints();
1329 if (
getWidth() == 1 && getInterleave() == 1) {
1332 DEBUG(
dbgs() <<
"LV: Not vectorizing: Disabled/already vectorized.\n");
1339 <<
"loop not vectorized: vectorization and interleaving are "
1340 "explicitly disabled, or vectorize width and interleave "
1341 "count are both set to 1");
1349 void emitRemarkWithHints()
const {
1350 using namespace ore;
1351 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1353 TheLoop->getStartLoc(),
1354 TheLoop->getHeader())
1355 <<
"loop not vectorized: vectorization is explicitly disabled");
1358 TheLoop->getStartLoc(), TheLoop->getHeader());
1359 R <<
"loop not vectorized";
1360 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1361 R <<
" (Force=" <<
NV(
"Force",
true);
1362 if (Width.Value != 0)
1363 R <<
", Vector Width=" <<
NV(
"VectorWidth", Width.Value);
1364 if (Interleave.Value != 0)
1365 R <<
", Interleave Count=" <<
NV(
"InterleaveCount", Interleave.Value);
1372 unsigned getWidth()
const {
return Width.Value; }
1373 unsigned getInterleave()
const {
return Interleave.Value; }
1374 enum ForceKind getForce()
const {
return (ForceKind)Force.Value; }
1378 const char *vectorizeAnalysisPassName()
const {
1381 if (getForce() == LoopVectorizeHints::FK_Disabled)
1383 if (getForce() == LoopVectorizeHints::FK_Undefined &&
getWidth() == 0)
1388 bool allowReordering()
const {
1394 return getForce() == LoopVectorizeHints::FK_Enabled ||
getWidth() > 1;
1397 bool isPotentiallyUnsafe()
const {
1403 return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
1406 void setPotentiallyUnsafe() { PotentiallyUnsafe =
true; }
1410 void getHintsFromMetadata() {
1411 MDNode *LoopID = TheLoop->getLoopID();
1419 for (
unsigned i = 1, ie = LoopID->
getNumOperands(); i < ie; ++i) {
1426 if (!MD || MD->getNumOperands() == 0)
1429 for (
unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1433 assert(Args.
size() == 0 &&
"too many arguments for MDString");
1441 if (Args.
size() == 1)
1442 setHint(Name, Args[0]);
1452 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1457 Hint *Hints[] = {&Width, &Interleave, &Force};
1458 for (
auto H : Hints) {
1459 if (Name ==
H->Name) {
1460 if (
H->validate(Val))
1463 DEBUG(
dbgs() <<
"LV: ignoring invalid hint '" << Name <<
"'\n");
1484 for (
auto H : HintTypes)
1492 if (HintTypes.
size() == 0)
1498 MDNode *LoopID = TheLoop->getLoopID();
1500 for (
unsigned i = 1, ie = LoopID->
getNumOperands(); i < ie; ++i) {
1503 if (!matchesHintMetadataName(Node, HintTypes))
1504 MDs.push_back(Node);
1509 for (
auto H : HintTypes)
1513 LLVMContext &Context = TheLoop->getHeader()->getContext();
1518 TheLoop->setLoopID(NewLoopID);
1522 const Loop *TheLoop;
1529 const LoopVectorizeHints &LH,
1531 LH.emitRemarkWithHints();
1533 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1534 if (LH.getWidth() != 1)
1538 <<
"loop not vectorized: "
1539 <<
"failed explicitly specified loop vectorization");
1540 else if (LH.getInterleave() != 1)
1544 <<
"loop not interleaved: "
1545 <<
"failed explicitly specified loop interleaving");
1562 class LoopVectorizationLegality {
1564 LoopVectorizationLegality(
1570 LoopVectorizeHints *
H)
1571 : NumPredStores(0), TheLoop(L), PSE(PSE), TLI(TLI), TTI(TTI), DT(DT),
1572 GetLAA(GetLAA), LAI(nullptr), ORE(ORE), InterleaveInfo(PSE, L, DT, LI),
1573 PrimaryInduction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(
false),
1574 Requirements(R), Hints(H) {}
1591 bool canVectorize();
1594 PHINode *getPrimaryInduction() {
return PrimaryInduction; }
1597 ReductionList *getReductionVars() {
return &Reductions; }
1600 InductionList *getInductionVars() {
return &Inductions; }
1603 RecurrenceSet *getFirstOrderRecurrences() {
return &FirstOrderRecurrences; }
1609 Type *getWidestInductionType() {
return WidestIndTy; }
1612 bool isInductionVariable(
const Value *V);
1615 bool isReductionVariable(
PHINode *PN) {
return Reductions.count(PN); }
1618 bool isFirstOrderRecurrence(
const PHINode *Phi);
1632 int isConsecutivePtr(
Value *Ptr);
1635 bool isUniform(
Value *V);
1639 return LAI->getRuntimePointerChecking();
1646 return InterleaveInfo.isInterleaved(Instr);
1650 unsigned getMaxInterleaveFactor()
const {
1651 return InterleaveInfo.getMaxInterleaveFactor();
1655 const InterleaveGroup *getInterleavedAccessGroup(
Instruction *Instr) {
1656 return InterleaveInfo.getInterleaveGroup(Instr);
1661 bool requiresScalarEpilogue()
const {
1662 return InterleaveInfo.requiresScalarEpilogue();
1667 bool hasStride(
Value *V) {
return LAI->hasStride(V); }
1676 bool isLegalMaskedLoad(
Type *DataType,
Value *Ptr) {
1681 bool isLegalMaskedScatter(
Type *DataType) {
1686 bool isLegalMaskedGather(
Type *DataType) {
1691 bool isLegalGatherOrScatter(
Value *V) {
1697 auto *Ty = cast<PointerType>(Ptr->
getType())->getElementType();
1698 return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
1703 bool isMaskRequired(
const Instruction *I) {
return (MaskedOp.count(I) != 0); }
1704 unsigned getNumStores()
const {
return LAI->getNumStores(); }
1705 unsigned getNumLoads()
const {
return LAI->getNumLoads(); }
1706 unsigned getNumPredStores()
const {
return NumPredStores; }
1715 bool memoryInstructionCanBeWidened(
Instruction *I,
unsigned VF = 1);
1718 bool hasFunNoNaNAttr()
const {
return HasFunNoNaNAttr; }
1724 bool canVectorizeInstrs();
1730 bool canVectorizeMemory();
1734 bool canVectorizeWithIfConvert();
1756 RemarkName, TheLoop,
I);
1766 return LAI ? &LAI->getSymbolicStrides() :
nullptr;
1769 unsigned NumPredStores;
1786 std::function<const LoopAccessInfo &(Loop &)> *GetLAA;
1795 InterleavedAccessInfo InterleaveInfo;
1803 ReductionList Reductions;
1807 InductionList Inductions;
1809 RecurrenceSet FirstOrderRecurrences;
1821 bool HasFunNoNaNAttr;
1824 LoopVectorizationRequirements *Requirements;
1827 LoopVectorizeHints *Hints;
1841 class LoopVectorizationCostModel {
1844 LoopInfo *LI, LoopVectorizationLegality *Legal,
1849 const LoopVectorizeHints *Hints)
1850 : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1851 AC(AC), ORE(ORE), TheFunction(F), Hints(Hints) {}
1869 void selectUserVectorizationFactor(
unsigned UserVF) {
1870 collectUniformsAndScalars(UserVF);
1871 collectInstsToScalarize(UserVF);
1877 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1883 unsigned selectInterleaveCount(
bool OptForSize,
unsigned VF,
1893 void setCostBasedWideningDecision(
unsigned VF);
1897 struct RegisterUsage {
1899 unsigned LoopInvariantRegs;
1901 unsigned MaxLocalUsers;
1903 unsigned NumInstructions;
1911 void collectValuesToIgnore();
1922 bool isProfitableToScalarize(
Instruction *I,
unsigned VF)
const {
1923 auto Scalars = InstsToScalarize.
find(VF);
1924 assert(Scalars != InstsToScalarize.end() &&
1925 "VF not yet analyzed for scalarization profitability");
1926 return Scalars->second.count(I);
1930 bool isUniformAfterVectorization(
Instruction *I,
unsigned VF)
const {
1933 assert(Uniforms.count(VF) &&
"VF not yet analyzed for uniformity");
1934 auto UniformsPerVF = Uniforms.find(VF);
1935 return UniformsPerVF->second.count(I);
1939 bool isScalarAfterVectorization(
Instruction *I,
unsigned VF)
const {
1942 assert(Scalars.count(VF) &&
"Scalar values are not calculated for VF");
1943 auto ScalarsPerVF = Scalars.find(VF);
1944 return ScalarsPerVF->second.count(I);
1949 bool canTruncateToMinimalBitwidth(
Instruction *I,
unsigned VF)
const {
1950 return VF > 1 && MinBWs.count(I) && !isProfitableToScalarize(I, VF) &&
1951 !isScalarAfterVectorization(I, VF);
1965 void setWideningDecision(
Instruction *I,
unsigned VF, InstWidening W,
1967 assert(VF >= 2 &&
"Expected VF >=2");
1968 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1973 void setWideningDecision(
const InterleaveGroup *Grp,
unsigned VF,
1974 InstWidening W,
unsigned Cost) {
1975 assert(VF >= 2 &&
"Expected VF >=2");
1978 for (
unsigned i = 0; i < Grp->getFactor(); ++i) {
1979 if (
auto *I = Grp->getMember(i)) {
1980 if (Grp->getInsertPos() ==
I)
1981 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1983 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1991 InstWidening getWideningDecision(
Instruction *I,
unsigned VF) {
1992 assert(VF >= 2 &&
"Expected VF >=2");
1993 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1994 auto Itr = WideningDecisions.find(InstOnVF);
1995 if (Itr == WideningDecisions.end())
1997 return Itr->second.first;
2002 unsigned getWideningCost(
Instruction *I,
unsigned VF) {
2003 assert(VF >= 2 &&
"Expected VF >=2");
2004 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
2005 assert(WideningDecisions.count(InstOnVF) &&
"The cost is not calculated");
2006 return WideningDecisions[InstOnVF].second;
2012 bool isOptimizableIVTruncate(
Instruction *I,
unsigned VF) {
2020 Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
2021 Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
2028 Value *
Op = Trunc->getOperand(0);
2029 if (Op != Legal->getPrimaryInduction() && TTI.
isTruncateFree(SrcTy, DestTy))
2033 return Legal->isInductionVariable(Op);
2039 unsigned computeFeasibleMaxVF(
bool OptForSize);
2048 typedef std::pair<unsigned, bool> VectorizationCostTy;
2054 VectorizationCostTy expectedCost(
unsigned VF);
2058 VectorizationCostTy getInstructionCost(
Instruction *I,
unsigned VF);
2062 unsigned getInstructionCost(
Instruction *I,
unsigned VF,
Type *&VectorTy);
2065 unsigned getMemoryInstructionCost(
Instruction *I,
unsigned VF);
2068 unsigned getMemInstScalarizationCost(
Instruction *I,
unsigned VF);
2071 unsigned getInterleaveGroupCost(
Instruction *I,
unsigned VF);
2074 unsigned getGatherScatterCost(
Instruction *I,
unsigned VF);
2078 unsigned getConsecutiveMemOpCost(
Instruction *I,
unsigned VF);
2082 unsigned getUniformMemOpCost(
Instruction *I,
unsigned VF);
2094 RemarkName, TheLoop);
2134 int computePredInstDiscount(
Instruction *PredInst, ScalarCostsTy &ScalarCosts,
2139 void collectInstsToScalarize(
unsigned VF);
2150 void collectLoopUniforms(
unsigned VF);
2157 void collectLoopScalars(
unsigned VF);
2162 void collectUniformsAndScalars(
unsigned VF) {
2164 if (VF == 1 || Uniforms.count(VF))
2166 setCostBasedWideningDecision(VF);
2167 collectLoopUniforms(VF);
2168 collectLoopScalars(VF);
2174 std::pair<InstWidening, unsigned>>
2177 DecisionList WideningDecisions;
2187 LoopVectorizationLegality *Legal;
2201 const LoopVectorizeHints *Hints;
2210 class LoopVectorizationPlanner {
2213 LoopVectorizationLegality *Legal,
2214 LoopVectorizationCostModel &CM)
2215 : OrigLoop(OrigLoop), LI(LI), Legal(Legal), CM(CM) {}
2217 ~LoopVectorizationPlanner() {}
2224 void executePlan(InnerLoopVectorizer &ILV);
2229 void collectTriviallyDeadInstructions(
2240 LoopVectorizationLegality *Legal;
2243 LoopVectorizationCostModel &CM;
2258 class LoopVectorizationRequirements {
2261 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr), ORE(ORE) {}
2265 if (!UnsafeAlgebraInst)
2266 UnsafeAlgebraInst =
I;
2269 void addRuntimePointerChecks(
unsigned Num) { NumRuntimePointerChecks = Num; }
2271 bool doesNotMeet(
Function *F,
Loop *L,
const LoopVectorizeHints &Hints) {
2272 const char *PassName = Hints.vectorizeAnalysisPassName();
2273 bool Failed =
false;
2274 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
2277 UnsafeAlgebraInst->getDebugLoc(),
2278 UnsafeAlgebraInst->getParent())
2279 <<
"loop not vectorized: cannot prove it is safe to reorder "
2280 "floating-point operations");
2285 bool PragmaThresholdReached =
2287 bool ThresholdReached =
2289 if ((ThresholdReached && !Hints.allowReordering()) ||
2290 PragmaThresholdReached) {
2294 <<
"loop not vectorized: cannot prove it is safe to reorder "
2295 "memory operations");
2296 DEBUG(
dbgs() <<
"LV: Too many memory checks needed.\n");
2304 unsigned NumRuntimePointerChecks;
2313 if (!hasCyclesInLoopBody(L))
2317 for (
Loop *InnerL : L)
2318 addAcyclicInnerLoop(*InnerL, V);
2326 explicit LoopVectorize(
bool NoUnrolling =
false,
bool AlwaysVectorize =
true)
2328 Impl.DisableUnrolling = NoUnrolling;
2329 Impl.AlwaysVectorize = AlwaysVectorize;
2335 bool runOnFunction(
Function &F)
override {
2336 if (skipFunction(F))
2339 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2340 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2341 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2342 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2343 auto *
BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2344 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2345 auto *TLI = TLIP ? &TLIP->getTLI() :
nullptr;
2346 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2347 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2348 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2349 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2350 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2352 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2355 return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *
BFI, TLI, *DB, *AA, *AC,
2384 Value *InnerLoopVectorizer::getBroadcastInstrs(
Value *V) {
2387 bool NewInstr = (Instr && Instr->
getParent() == LoopVectorBody);
2388 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
2393 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2396 Value *Shuf = Builder.CreateVectorSplat(VF, V,
"broadcast");
2401 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2406 auto CurrIP = Builder.saveIP();
2407 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2408 if (isa<TruncInst>(EntryVal)) {
2410 "Truncation requires an integer type");
2411 auto *TruncType = cast<IntegerType>(EntryVal->
getType());
2412 Step = Builder.CreateTrunc(Step, TruncType);
2413 Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2415 Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2416 Value *SteppedStart =
2423 if (Step->getType()->isIntegerTy()) {
2425 MulOp = Instruction::Mul;
2428 MulOp = Instruction::FMul;
2433 Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
2441 Value *SplatVF = isa<Constant>(Mul)
2443 : Builder.CreateVectorSplat(VF, Mul);
2444 Builder.restoreIP(CurrIP);
2449 &*LoopVectorBody->getFirstInsertionPt());
2451 for (
unsigned Part = 0; Part < UF; ++Part) {
2452 VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
2453 if (isa<TruncInst>(EntryVal))
2454 addMetadata(LastInduction, EntryVal);
2456 Builder.CreateBinOp(AddOp, LastInduction, SplatVF,
"step.add")));
2461 auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2462 auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2463 auto *ICmp = cast<Instruction>(Br->getCondition());
2464 LastInduction->moveBefore(ICmp);
2465 LastInduction->setName(
"vec.ind.next");
2467 VecInd->
addIncoming(SteppedStart, LoopVectorPreHeader);
2468 VecInd->
addIncoming(LastInduction, LoopVectorLatch);
2471 bool InnerLoopVectorizer::shouldScalarizeInstruction(
Instruction *I)
const {
2472 return Cost->isScalarAfterVectorization(I, VF) ||
2473 Cost->isProfitableToScalarize(I, VF);
2476 bool InnerLoopVectorizer::needsScalarInduction(
Instruction *IV)
const {
2477 if (shouldScalarizeInstruction(IV))
2479 auto isScalarInst = [&](
User *U) ->
bool {
2480 auto *I = cast<Instruction>(U);
2481 return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2486 void InnerLoopVectorizer::widenIntOrFpInduction(
PHINode *IV,
TruncInst *Trunc) {
2489 "Primary induction variable must have an integer type");
2491 auto II = Legal->getInductionVars()->find(IV);
2492 assert(II != Legal->getInductionVars()->end() &&
"IV is not an induction");
2494 auto ID = II->second;
2495 assert(IV->
getType() == ID.getStartValue()->getType() &&
"Types must match");
2499 Value *ScalarIV =
nullptr;
2503 Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2506 auto VectorizedIV =
false;
2511 auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
2516 "Induction step should be loop invariant");
2517 auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2518 Value *Step =
nullptr;
2521 Step =
Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
2522 LoopVectorPreHeader->getTerminator());
2524 Step = cast<SCEVUnknown>(ID.getStep())->getValue();
2530 if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
2531 createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
2532 VectorizedIV =
true;
2540 if (!VectorizedIV || NeedsScalarIV) {
2541 ScalarIV = Induction;
2542 if (IV != OldInduction) {
2544 ? Builder.CreateSExtOrTrunc(Induction, IV->
getType())
2545 : Builder.CreateCast(Instruction::SIToFP, Induction,
2547 ScalarIV = ID.transform(Builder, ScalarIV, PSE.
getSE(), DL);
2548 ScalarIV->setName(
"offset.idx");
2551 auto *TruncType = cast<IntegerType>(Trunc->
getType());
2552 assert(Step->getType()->isIntegerTy() &&
2553 "Truncation requires an integer step");
2554 ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2555 Step = Builder.CreateTrunc(Step, TruncType);
2561 if (!VectorizedIV) {
2562 Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2563 for (
unsigned Part = 0; Part < UF; ++Part) {
2565 getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
2566 VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
2568 addMetadata(EntryPart, Trunc);
2579 buildScalarSteps(ScalarIV, Step, EntryVal, ID);
2582 Value *InnerLoopVectorizer::getStepVector(
Value *Val,
int StartIdx,
Value *Step,
2590 "Induction Step must be an integer or FP");
2597 for (
int i = 0; i < VLen; ++i)
2603 Step = Builder.CreateVectorSplat(VLen, Step);
2604 assert(Step->getType() == Val->
getType() &&
"Invalid step vec");
2607 Step = Builder.CreateMul(Cv, Step);
2608 return Builder.CreateAdd(Val, Step,
"induction");
2612 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2613 "Binary Opcode should be specified for FP induction");
2615 for (
int i = 0; i < VLen; ++i)
2621 Step = Builder.CreateVectorSplat(VLen, Step);
2627 Value *MulOp = Builder.CreateFMul(Cv, Step);
2628 if (isa<Instruction>(MulOp))
2630 cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2632 Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp,
"induction");
2633 if (isa<Instruction>(BOp))
2634 cast<Instruction>(BOp)->setFastMathFlags(Flags);
2638 void InnerLoopVectorizer::buildScalarSteps(
Value *ScalarIV,
Value *Step,
2643 assert(VF > 1 &&
"VF should be greater than one");
2648 "Val and Step should have the same type");
2656 MulOp = Instruction::Mul;
2659 MulOp = Instruction::FMul;
2666 Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1 : VF;
2669 for (
unsigned Part = 0; Part < UF; ++Part) {
2670 for (
unsigned Lane = 0; Lane < Lanes; ++Lane) {
2671 auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
2672 auto *Mul =
addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2674 VectorLoopValueMap.setScalarValue(EntryVal, Part, Lane, Add);
2679 int LoopVectorizationLegality::isConsecutivePtr(
Value *Ptr) {
2681 const ValueToValueMap &Strides = getSymbolicStrides() ? *getSymbolicStrides() :
2684 int Stride =
getPtrStride(PSE, Ptr, TheLoop, Strides,
true,
false);
2685 if (Stride == 1 || Stride == -1)
2690 bool LoopVectorizationLegality::isUniform(
Value *V) {
2691 return LAI->isUniform(V);
2694 Value *InnerLoopVectorizer::getOrCreateVectorValue(
Value *V,
unsigned Part) {
2695 assert(V != Induction &&
"The new induction variable should not be used.");
2700 if (Legal->hasStride(V))
2704 if (VectorLoopValueMap.hasVectorValue(V, Part))
2705 return VectorLoopValueMap.getVectorValue(V, Part);
2710 if (VectorLoopValueMap.hasAnyScalarValue(V)) {
2712 Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, Part, 0);
2715 auto *I = cast<Instruction>(V);
2720 VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
2728 unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
2730 cast<Instruction>(VectorLoopValueMap.getScalarValue(V, Part, LastLane));
2734 auto OldIP = Builder.saveIP();
2736 Builder.SetInsertPoint(&*NewIP);
2744 Value *VectorValue =
nullptr;
2745 if (Cost->isUniformAfterVectorization(I, VF)) {
2746 VectorValue = getBroadcastInstrs(ScalarValue);
2749 for (
unsigned Lane = 0; Lane < VF; ++Lane)
2750 VectorValue = Builder.CreateInsertElement(
2751 VectorValue, getOrCreateScalarValue(V, Part, Lane),
2752 Builder.getInt32(Lane));
2754 VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
2755 Builder.restoreIP(OldIP);
2761 Value *B = getBroadcastInstrs(V);
2762 VectorLoopValueMap.setVectorValue(V, Part, B);
2766 Value *InnerLoopVectorizer::getOrCreateScalarValue(
Value *V,
unsigned Part,
2771 if (OrigLoop->isLoopInvariant(V))
2774 assert(Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
2775 :
true &&
"Uniform values only have lane zero");
2780 if (VectorLoopValueMap.hasScalarValue(V, Part, Lane))
2781 return VectorLoopValueMap.getScalarValue(V, Part, Lane);
2787 auto *U = getOrCreateVectorValue(V, Part);
2788 if (!U->getType()->isVectorTy()) {
2789 assert(VF == 1 &&
"Value not scalarized has non-vector type");
2796 return Builder.CreateExtractElement(U, Builder.getInt32(Lane));
2799 Value *InnerLoopVectorizer::reverseVector(
Value *Vec) {
2802 for (
unsigned i = 0; i < VF; ++i)
2803 ShuffleMask.
push_back(Builder.getInt32(VF - i - 1));
2838 void InnerLoopVectorizer::vectorizeInterleaveGroup(
Instruction *Instr) {
2839 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2840 assert(Group &&
"Fail to get an interleaved access group.");
2843 if (Instr != Group->getInsertPos())
2849 Type *ScalarTy = getMemInstValueType(Instr);
2850 unsigned InterleaveFactor = Group->getFactor();
2855 setDebugLocFromInst(Builder, Ptr);
2857 unsigned Index = Group->getIndex(Instr);
2865 if (Group->isReverse())
2866 Index += (VF - 1) * Group->getFactor();
2868 for (
unsigned Part = 0; Part < UF; Part++) {
2869 Value *NewPtr = getOrCreateScalarValue(Ptr, Part, 0);
2882 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2885 NewPtrs.
push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2888 setDebugLocFromInst(Builder, Instr);
2892 if (isa<LoadInst>(Instr)) {
2896 for (
unsigned Part = 0; Part < UF; Part++) {
2897 auto *NewLoad = Builder.CreateAlignedLoad(
2898 NewPtrs[Part], Group->getAlignment(),
"wide.vec");
2899 addMetadata(NewLoad, Instr);
2905 for (
unsigned I = 0; I < InterleaveFactor; ++
I) {
2913 for (
unsigned Part = 0; Part < UF; Part++) {
2914 Value *StridedVec = Builder.CreateShuffleVector(
2915 NewLoads[Part], UndefVec, StrideMask,
"strided.vec");
2918 if (Member->
getType() != ScalarTy) {
2920 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2923 if (Group->isReverse())
2924 StridedVec = reverseVector(StridedVec);
2926 VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
2936 for (
unsigned Part = 0; Part < UF; Part++) {
2939 for (
unsigned i = 0; i < InterleaveFactor; i++) {
2942 assert(Member &&
"Fail to get a member from an interleaved store group");
2944 Value *StoredVec = getOrCreateVectorValue(
2945 cast<StoreInst>(Member)->getValueOperand(), Part);
2946 if (Group->isReverse())
2947 StoredVec = reverseVector(StoredVec);
2950 if (StoredVec->
getType() != SubVT)
2951 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2961 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2965 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2966 addMetadata(NewStoreInstr, Instr);
2970 void InnerLoopVectorizer::vectorizeMemoryInstruction(
Instruction *Instr) {
2975 assert((LI || SI) &&
"Invalid Load/Store instruction");
2977 LoopVectorizationCostModel::InstWidening Decision =
2978 Cost->getWideningDecision(Instr, VF);
2979 assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
2980 "CM decision should be taken at this point");
2981 if (Decision == LoopVectorizationCostModel::CM_Interleave)
2982 return vectorizeInterleaveGroup(Instr);
2984 Type *ScalarDataTy = getMemInstValueType(Instr);
2987 unsigned Alignment = getMemInstAlignment(Instr);
2996 if (Decision == LoopVectorizationCostModel::CM_Scalarize)
2997 return scalarizeInstruction(Instr, Legal->isScalarWithPredication(Instr));
3001 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
3002 bool Reverse = ConsecutiveStride < 0;
3003 bool CreateGatherScatter =
3004 (Decision == LoopVectorizationCostModel::CM_GatherScatter);
3008 assert((ConsecutiveStride || CreateGatherScatter) &&
3009 "The instruction should be scalarized");
3012 if (ConsecutiveStride)
3013 Ptr = getOrCreateScalarValue(Ptr, 0, 0);
3018 assert(!Legal->isUniform(SI->getPointerOperand()) &&
3019 "We do not allow storing to uniform addresses");
3020 setDebugLocFromInst(Builder, SI);
3022 for (
unsigned Part = 0; Part < UF; ++Part) {
3024 Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
3025 if (CreateGatherScatter) {
3026 Value *MaskPart = Legal->isMaskRequired(SI) ? Mask[Part] :
nullptr;
3027 Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
3028 NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
3033 Builder.CreateGEP(
nullptr, Ptr, Builder.getInt32(Part * VF));
3038 StoredVal = reverseVector(StoredVal);
3045 Builder.CreateGEP(
nullptr, Ptr, Builder.getInt32(-Part * VF));
3047 Builder.CreateGEP(
nullptr, PartPtr, Builder.getInt32(1 - VF));
3048 Mask[Part] = reverseVector(Mask[Part]);
3052 Builder.CreateBitCast(PartPtr, DataTy->
getPointerTo(AddressSpace));
3054 if (Legal->isMaskRequired(SI))
3055 NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
3058 NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
3060 addMetadata(NewSI, SI);
3066 assert(LI &&
"Must have a load instruction");
3067 setDebugLocFromInst(Builder, LI);
3068 for (
unsigned Part = 0; Part < UF; ++Part) {
3070 if (CreateGatherScatter) {
3071 Value *MaskPart = Legal->isMaskRequired(LI) ? Mask[Part] :
nullptr;
3072 Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
3073 NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
3074 nullptr,
"wide.masked.gather");
3075 addMetadata(NewLI, LI);
3079 Builder.CreateGEP(
nullptr, Ptr, Builder.getInt32(Part * VF));
3084 PartPtr = Builder.CreateGEP(
nullptr, Ptr, Builder.getInt32(-Part * VF));
3085 PartPtr = Builder.CreateGEP(
nullptr, PartPtr, Builder.getInt32(1 - VF));
3086 Mask[Part] = reverseVector(Mask[Part]);
3090 Builder.CreateBitCast(PartPtr, DataTy->
getPointerTo(AddressSpace));
3091 if (Legal->isMaskRequired(LI))
3092 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
3094 "wide.masked.load");
3096 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment,
"wide.load");
3099 addMetadata(NewLI, LI);
3101 NewLI = reverseVector(NewLI);
3103 VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
3107 void InnerLoopVectorizer::scalarizeInstruction(
Instruction *Instr,
3108 bool IfPredicateInstr) {
3111 << (IfPredicateInstr ?
" and predicating:" :
":") << *Instr
3116 setDebugLocFromInst(Builder, Instr);
3122 if (IfPredicateInstr)
3123 Cond = createBlockInMask(Instr->
getParent());
3128 unsigned Lanes = Cost->isUniformAfterVectorization(Instr, VF) ? 1 : VF;
3131 for (
unsigned Part = 0; Part < UF; ++Part) {
3133 for (
unsigned Lane = 0; Lane < Lanes; ++Lane) {
3136 Value *Cmp =
nullptr;
3137 if (IfPredicateInstr) {
3140 Cmp = Builder.CreateExtractElement(Cmp, Builder.getInt32(Lane));
3152 auto *NewOp = getOrCreateScalarValue(Instr->
getOperand(
op), Part, Lane);
3155 addNewMetadata(Cloned, Instr);
3158 Builder.Insert(Cloned);
3161 VectorLoopValueMap.setScalarValue(Instr, Part, Lane, Cloned);
3164 if (
auto *II = dyn_cast<IntrinsicInst>(Cloned))
3165 if (II->getIntrinsicID() == Intrinsic::assume)
3166 AC->registerAssumption(II);
3169 if (IfPredicateInstr)
3170 PredicatedInstructions.push_back(std::make_pair(Cloned, Cmp));
3175 PHINode *InnerLoopVectorizer::createInductionVariable(
Loop *L,
Value *Start,
3186 Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3187 setDebugLocFromInst(Builder, OldInst);
3188 auto *Induction = Builder.CreatePHI(Start->
getType(), 2,
"index");
3191 setDebugLocFromInst(Builder, OldInst);
3194 Value *Next = Builder.CreateAdd(Induction, Step,
"index.next");
3196 Induction->addIncoming(Next, Latch);
3198 Value *ICmp = Builder.CreateICmpEQ(Next, End);
3207 Value *InnerLoopVectorizer::getOrCreateTripCount(
Loop *L) {
3215 assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
3216 "Invalid loop count");
3218 Type *IdxTy = Legal->getWidestInductionType();
3226 IdxTy->getPrimitiveSizeInBits())
3227 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3228 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3231 const SCEV *ExitCount = SE->getAddExpr(
3232 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->
getType()));
3241 TripCount =
Exp.expandCodeFor(ExitCount, ExitCount->
getType(),
3244 if (TripCount->getType()->isPointerTy())
3252 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(
Loop *L) {
3253 if (VectorTripCount)
3254 return VectorTripCount;
3256 Value *TC = getOrCreateTripCount(L);
3265 Value *R = Builder.CreateURem(TC, Step,
"n.mod.vf");
3274 if (VF > 1 && Legal->requiresScalarEpilogue()) {
3276 R = Builder.CreateSelect(IsZero, Step, R);
3279 VectorTripCount = Builder.CreateSub(TC, R,
"n.vec");
3281 return VectorTripCount;
3284 void InnerLoopVectorizer::emitMinimumIterationCountCheck(
Loop *L,
3286 Value *Count = getOrCreateTripCount(L);
3297 Value *CheckMinIters = Builder.CreateICmp(
3309 LoopBypassBlocks.push_back(BB);
3312 void InnerLoopVectorizer::emitSCEVChecks(
Loop *L,
BasicBlock *Bypass) {
3323 if (
auto *C = dyn_cast<ConstantInt>(SCEVCheck))
3328 BB->
setName(
"vector.scevcheck");
3338 LoopBypassBlocks.push_back(BB);
3339 AddedSafetyChecks =
true;
3342 void InnerLoopVectorizer::emitMemRuntimeChecks(
Loop *L,
BasicBlock *Bypass) {
3350 std::tie(FirstCheckInst, MemRuntimeCheck) =
3352 if (!MemRuntimeCheck)
3356 BB->
setName(
"vector.memcheck");
3366 LoopBypassBlocks.push_back(BB);
3367 AddedSafetyChecks =
true;
3371 LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
3373 LVer->prepareNoAliasMetadata();
3376 void InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3409 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
3410 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
3411 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
3412 assert(VectorPH &&
"Invalid loop structure");
3413 assert(ExitBlock &&
"Must have an exit block");
3426 OldInduction = Legal->getPrimaryInduction();
3427 Type *IdxTy = Legal->getWidestInductionType();
3448 LI->addTopLevelLoop(Lp);
3453 Value *Count = getOrCreateTripCount(Lp);
3462 emitMinimumIterationCountCheck(Lp, ScalarPH);
3466 emitSCEVChecks(Lp, ScalarPH);
3471 emitMemRuntimeChecks(Lp, ScalarPH);
3476 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3479 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3480 getDebugLocFromInstOrOperands(OldInduction));
3494 for (
auto &InductionEntry : *List) {
3495 PHINode *OrigPhi = InductionEntry.first;
3501 Value *&EndValue = IVEndValues[OrigPhi];
3502 if (OrigPhi == OldInduction) {
3504 EndValue = CountRoundDown;
3510 Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType,
"cast.crd");
3511 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3544 LoopScalarPreHeader = ScalarPH;
3545 LoopMiddleBlock = MiddleBlock;
3546 LoopExitBlock = ExitBlock;
3547 LoopVectorBody = VecBody;
3548 LoopScalarBody = OldBasicBlock;
3552 if (
MDNode *LID = OrigLoop->getLoopID())
3555 LoopVectorizeHints Hints(Lp,
true, *ORE);
3556 Hints.setAlreadyVectorized();
3563 void InnerLoopVectorizer::fixupIVUsers(
PHINode *OrigPhi,
3572 assert(OrigLoop->getExitBlock() &&
"Expected a single exit block");
3581 if (!OrigLoop->contains(UI)) {
3582 assert(isa<PHINode>(UI) &&
"Expected LCSSA form");
3583 MissingVals[UI] = EndValue;
3591 auto *UI = cast<Instruction>(U);
3592 if (!OrigLoop->contains(UI)) {
3594 OrigLoop->getHeader()->getModule()->getDataLayout();
3595 assert(isa<PHINode>(UI) &&
"Expected LCSSA form");
3598 Value *CountMinusOne = B.CreateSub(
3602 ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3607 Escape->
setName(
"ind.escape");
3608 MissingVals[UI] = Escape;
3612 for (
auto &I : MissingVals) {
3613 PHINode *PHI = cast<PHINode>(I.first);
3625 struct CSEDenseMapInfo {
3627 return isa<InsertElementInst>(
I) || isa<ExtractElementInst>(I) ||
3628 isa<ShuffleVectorInst>(
I) || isa<GetElementPtrInst>(I);
3636 static unsigned getHashValue(
const Instruction *I) {
3637 assert(canHandle(I) &&
"Unknown instruction!");
3642 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3643 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3657 if (!CSEDenseMapInfo::canHandle(In))
3682 (!isa<LoadInst>(
I) ||
3686 if (
CallInst *CI = dyn_cast<CallInst>(I)) {
3690 else if (!isa<StoreInst>(I) ||
3706 bool &NeedToScalarize) {
3720 return ScalarCallCost;
3723 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3724 for (
Type *ScalarTy : ScalarTys)
3725 Tys.
push_back(ToVectorTy(ScalarTy, VF));
3731 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3735 NeedToScalarize =
true;
3741 if (VectorCallCost < Cost) {
3742 NeedToScalarize =
false;
3743 return VectorCallCost;
3755 assert(ID &&
"Expected intrinsic call!");
3758 if (
auto *FPMO = dyn_cast<FPMathOperator>(CI))
3759 FMF = FPMO->getFastMathFlags();
3768 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3773 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3776 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3782 for (
const auto &KV : Cost->getMinimalBitwidths()) {
3786 if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3788 for (
unsigned Part = 0; Part < UF; ++Part) {
3789 Value *I = getOrCreateVectorValue(KV.first, Part);
3793 Type *ScalarTruncatedTy =
3797 if (TruncatedTy == OriginalTy)
3801 auto ShrinkOperand = [&](
Value *V) ->
Value * {
3802 if (
auto *ZI = dyn_cast<ZExtInst>(V))
3803 if (ZI->getSrcTy() == TruncatedTy)
3804 return ZI->getOperand(0);
3805 return B.CreateZExtOrTrunc(V, TruncatedTy);
3810 Value *NewI =
nullptr;
3811 if (
auto *BO = dyn_cast<BinaryOperator>(I)) {
3812 NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3813 ShrinkOperand(BO->getOperand(1)));
3818 cast<BinaryOperator>(NewI)->copyIRFlags(I,
false);
3819 }
else if (
auto *CI = dyn_cast<ICmpInst>(I)) {
3821 B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3822 ShrinkOperand(CI->getOperand(1)));
3823 }
else if (
auto *SI = dyn_cast<SelectInst>(I)) {
3824 NewI = B.CreateSelect(SI->getCondition(),
3825 ShrinkOperand(SI->getTrueValue()),
3826 ShrinkOperand(SI->getFalseValue()));
3827 }
else if (
auto *CI = dyn_cast<CastInst>(I)) {
3828 switch (CI->getOpcode()) {
3831 case Instruction::Trunc:
3832 NewI = ShrinkOperand(CI->getOperand(0));
3834 case Instruction::SExt:
3835 NewI = B.CreateSExtOrTrunc(
3839 case Instruction::ZExt:
3840 NewI = B.CreateZExtOrTrunc(
3845 }
else if (
auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3847 auto *O0 = B.CreateZExtOrTrunc(
3850 auto *O1 = B.CreateZExtOrTrunc(
3853 NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3854 }
else if (isa<LoadInst>(I)) {
3857 }
else if (
auto *
IE = dyn_cast<InsertElementInst>(I)) {
3858 auto Elements =
IE->getOperand(0)->getType()->getVectorNumElements();
3859 auto *O0 = B.CreateZExtOrTrunc(
3861 auto *O1 = B.CreateZExtOrTrunc(
IE->getOperand(1), ScalarTruncatedTy);
3862 NewI = B.CreateInsertElement(O0, O1,
IE->getOperand(2));
3863 }
else if (
auto *EE = dyn_cast<ExtractElementInst>(I)) {
3865 auto *O0 = B.CreateZExtOrTrunc(
3867 NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3873 NewI->
takeName(cast<Instruction>(I));
3874 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3876 cast<Instruction>(
I)->eraseFromParent();
3878 VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
3883 for (
const auto &KV : Cost->getMinimalBitwidths()) {
3887 if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3889 for (
unsigned Part = 0; Part < UF; ++Part) {
3890 Value *I = getOrCreateVectorValue(KV.first, Part);
3895 VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
3901 void InnerLoopVectorizer::fixVectorizedLoop() {
3905 truncateToMinimalBitwidths();
3911 fixCrossIterationPHIs();
3924 for (
auto &Entry : *Legal->getInductionVars())
3925 fixupIVUsers(Entry.first, Entry.second,
3926 getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3927 IVEndValues[Entry.first], LoopMiddleBlock);
3930 predicateInstructions();
3933 cse(LoopVectorBody);
3936 void InnerLoopVectorizer::fixCrossIterationPHIs() {
3948 if (Legal->isFirstOrderRecurrence(Phi))
3949 fixFirstOrderRecurrence(Phi);
3950 else if (Legal->isReductionVariable(Phi))
3955 void InnerLoopVectorizer::fixFirstOrderRecurrence(
PHINode *Phi) {
4007 auto *Preheader = OrigLoop->getLoopPreheader();
4008 auto *Latch = OrigLoop->getLoopLatch();
4015 auto *VectorInit = ScalarInit;
4017 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4018 VectorInit = Builder.CreateInsertElement(
4020 Builder.getInt32(VF - 1),
"vector.recur.init");
4025 Builder.SetInsertPoint(
4026 cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
4030 auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2,
"vector.recur");
4031 VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4035 Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
4042 if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
4043 isa<PHINode>(PreviousLastPart))
4044 Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
4046 Builder.SetInsertPoint(
4052 ShuffleMask[0] = Builder.getInt32(VF - 1);
4053 for (
unsigned I = 1; I < VF; ++
I)
4054 ShuffleMask[I] = Builder.getInt32(I + VF - 1);
4058 Value *Incoming = VecPhi;
4061 for (
unsigned Part = 0; Part < UF; ++Part) {
4062 Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
4063 Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
4065 VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
4069 cast<Instruction>(PhiPart)->eraseFromParent();
4070 VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
4071 Incoming = PreviousPart;
4075 VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4079 auto *ExtractForScalar = Incoming;
4081 Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4082 ExtractForScalar = Builder.CreateExtractElement(
4083 ExtractForScalar, Builder.getInt32(VF - 1),
"vector.recur.extract");
4090 Value *ExtractForPhiUsedOutsideLoop =
nullptr;
4092 ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4093 Incoming, Builder.getInt32(VF - 2),
"vector.recur.extract.for.phi");
4099 ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
4102 Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4103 auto *Start = Builder.CreatePHI(Phi->
getType(), 2,
"scalar.recur.init");
4105 auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4106 Start->addIncoming(Incoming, BB);
4117 for (
auto &I : *LoopExitBlock) {
4121 if (LCSSAPhi->getIncomingValue(0) == Phi) {
4122 LCSSAPhi->
addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4128 void InnerLoopVectorizer::fixReduction(
PHINode *Phi) {
4132 assert(Legal->isReductionVariable(Phi) &&
4133 "Unable to find the reduction variable");
4138 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4140 RdxDesc.getMinMaxRecurrenceKind();
4141 setDebugLocFromInst(Builder, ReductionStartValue);
4147 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4150 Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
4160 VectorStart = Identity = ReductionStartValue;
4162 VectorStart = Identity =
4163 Builder.CreateVectorSplat(VF, ReductionStartValue,
"minmax.ident");
4173 VectorStart = ReductionStartValue;
4180 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
4188 BasicBlock *Latch = OrigLoop->getLoopLatch();
4190 for (
unsigned Part = 0; Part < UF; ++Part) {
4191 Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
4192 Value *Val = getOrCreateVectorValue(LoopVal, Part);
4195 Value *StartVal = (Part == 0) ? VectorStart : Identity;
4196 cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
4197 cast<PHINode>(VecRdxPhi)
4198 ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4205 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4207 setDebugLocFromInst(Builder, LoopExitInst);
4212 if (VF > 1 && Phi->
getType() != RdxDesc.getRecurrenceType()) {
4214 Builder.SetInsertPoint(LoopVectorBody->getTerminator());
4215 VectorParts RdxParts(UF);
4216 for (
unsigned Part = 0; Part < UF; ++Part) {
4217 RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4218 Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4219 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4220 : Builder.CreateZExt(Trunc, VecTy);
4224 (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4225 RdxParts[Part] = Extnd;
4230 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4231 for (
unsigned Part = 0; Part < UF; ++Part) {
4232 RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4233 VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
4238 Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
4240 setDebugLocFromInst(Builder, ReducedPartRdx);
4241 for (
unsigned Part = 1; Part < UF; ++Part) {
4242 Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4243 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
4247 ReducedPartRdx,
"bin.rdx"));
4250 Builder, MinMaxKind, ReducedPartRdx, RdxPart);
4254 bool NoNaN = Legal->hasFunNoNaNAttr();
4259 if (Phi->
getType() != RdxDesc.getRecurrenceType())
4262 ? Builder.CreateSExt(ReducedPartRdx, Phi->
getType())
4263 : Builder.CreateZExt(ReducedPartRdx, Phi->
getType());
4269 LoopScalarPreHeader->getTerminator());
4270 for (
unsigned I = 0,
E = LoopBypassBlocks.size(); I !=
E; ++
I)
4271 BCBlockPhi->
addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4272 BCBlockPhi->
addIncoming(ReducedPartRdx, LoopMiddleBlock);
4279 LEE = LoopExitBlock->end();
4280 LEI != LEE; ++LEI) {
4292 LCSSAPhi->
addIncoming(ReducedPartRdx, LoopMiddleBlock);
4297 int IncomingEdgeBlockIdx =
4299 assert(IncomingEdgeBlockIdx >= 0 &&
"Invalid block index");
4301 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4306 void InnerLoopVectorizer::fixLCSSAPHIs() {
4313 "Incoming value isn't loop invariant");
4319 void InnerLoopVectorizer::sinkScalarOperands(
Instruction *PredInst) {
4323 auto *VectorLoop = LI->getLoopFor(PredBB);
4334 auto isBlockOfUsePredicated = [&](
Use &U) ->
bool {
4335 auto *I = cast<Instruction>(U.getUser());
4337 if (
auto *Phi = dyn_cast<PHINode>(I))
4340 return BB == PredBB;
4352 Worklist.insert(InstsToReanalyze.
begin(), InstsToReanalyze.
end());
4353 InstsToReanalyze.
clear();
4356 while (!Worklist.empty()) {
4361 if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4362 !VectorLoop->contains(I) || I->mayHaveSideEffects())
4368 if (!
all_of(I->uses(), isBlockOfUsePredicated)) {
4369 InstsToReanalyze.push_back(I);
4375 I->moveBefore(&*PredBB->getFirstInsertionPt());
4376 Worklist.
insert(I->op_begin(), I->op_end());
4385 void InnerLoopVectorizer::predicateInstructions() {
4461 for (
auto KV : PredicatedInstructions) {
4467 sinkScalarOperands(&*I);
4470 Twine BBNamePrefix =
Twine(
"pred.") + I->getOpcodeName();
4471 PredicatedBlock->
setName(BBNamePrefix +
".if");
4475 if (!I->getType()->isVoidTy()) {
4476 Value *IncomingTrue =
nullptr;
4477 Value *IncomingFalse =
nullptr;
4479 if (I->hasOneUse() && isa<InsertElementInst>(*I->user_begin())) {
4493 assert(PostDom &&
"Then block has multiple successors");
4502 DEBUG(DT->verifyDomTree());
4510 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
4511 EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
4512 if (ECEntryIt != EdgeMaskCache.end())
4513 return ECEntryIt->second;
4515 VectorParts SrcMask = createBlockInMask(Src);
4519 assert(BI &&
"Unexpected terminator found");
4523 VectorParts EdgeMask(UF);
4524 for (
unsigned Part = 0; Part < UF; ++Part) {
4525 auto *EdgeMaskPart = getOrCreateVectorValue(BI->
getCondition(), Part);
4527 EdgeMaskPart = Builder.CreateNot(EdgeMaskPart);
4529 EdgeMaskPart = Builder.CreateAnd(EdgeMaskPart, SrcMask[Part]);
4530 EdgeMask[Part] = EdgeMaskPart;
4533 EdgeMaskCache[Edge] = EdgeMask;
4537 EdgeMaskCache[Edge] = SrcMask;
4542 InnerLoopVectorizer::createBlockInMask(
BasicBlock *BB) {
4543 assert(OrigLoop->contains(BB) &&
"Block is not a part of a loop");
4546 BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
4547 if (BCEntryIt != BlockMaskCache.end())
4548 return BCEntryIt->second;
4550 VectorParts BlockMask(UF);
4553 if (OrigLoop->getHeader() == BB) {
4555 for (
unsigned Part = 0; Part < UF; ++Part)
4556 BlockMask[Part] = getOrCreateVectorValue(C, Part);
4557 BlockMaskCache[BB] = BlockMask;
4563 for (
unsigned Part = 0; Part < UF; ++Part)
4564 BlockMask[Part] = getOrCreateVectorValue(Zero, Part);
4568 VectorParts EM = createEdgeMask(*It, BB);
4569 for (
unsigned Part = 0; Part < UF; ++Part)
4570 BlockMask[Part] = Builder.CreateOr(BlockMask[Part], EM[Part]);
4573 BlockMaskCache[BB] = BlockMask;
4577 void InnerLoopVectorizer::widenPHIInstruction(
Instruction *PN,
unsigned UF,
4579 PHINode *P = cast<PHINode>(PN);
4584 if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4585 for (
unsigned Part = 0; Part < UF; ++Part) {
4590 VecTy, 2,
"vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4591 VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
4596 setDebugLocFromInst(Builder, P);
4598 if (P->
getParent() != OrigLoop->getHeader()) {
4612 VectorParts Entry(UF);
4613 for (
unsigned In = 0;
In < NumIncoming;
In++) {
4617 for (
unsigned Part = 0; Part < UF; ++Part) {
4622 Entry[Part] = Builder.CreateSelect(Cond[Part], In0, In0);
4626 Entry[Part] = Builder.CreateSelect(Cond[Part], In0, Entry[Part],
4630 for (
unsigned Part = 0; Part < UF; ++Part)
4631 VectorLoopValueMap.setVectorValue(P, Part, Entry[Part]);
4637 assert(Legal->getInductionVars()->count(P) &&
"Not an induction variable");
4640 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4644 switch (II.getKind()) {
4649 return widenIntOrFpInduction(P);
4654 Value *PtrInd = Induction;
4655 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
4659 unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
4662 for (
unsigned Part = 0; Part < UF; ++Part) {
4663 for (
unsigned Lane = 0; Lane < Lanes; ++Lane) {
4665 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4666 Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.
getSE(), DL);
4668 VectorLoopValueMap.setScalarValue(P, Part, Lane, SclrGep);
4688 "Unexpected instruction");
4691 return !CInt || CInt->
isZero();
4694 void InnerLoopVectorizer::vectorizeInstruction(
Instruction &I) {
4697 !(isa<BranchInst>(&I) || isa<PHINode>(&I) || isa<DbgInfoIntrinsic>(&I)) &&
4698 shouldScalarizeInstruction(&I)) {
4699 scalarizeInstruction(&I, Legal->isScalarWithPredication(&I));
4704 case Instruction::Br:
4708 case Instruction::PHI: {
4710 widenPHIInstruction(&I, UF, VF);
4713 case Instruction::GetElementPtr: {
4719 auto *
GEP = cast<GetElementPtrInst>(&
I);
4721 if (VF > 1 && OrigLoop->hasLoopInvariantOperands(
GEP)) {
4734 auto *Clone = Builder.Insert(
GEP->clone());
4735 for (
unsigned Part = 0; Part < UF; ++Part) {
4736 Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4737 VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
4738 addMetadata(EntryPart,
GEP);
4748 for (
unsigned Part = 0; Part < UF; ++Part) {
4753 OrigLoop->isLoopInvariant(
GEP->getPointerOperand())
4754 ?
GEP->getPointerOperand()
4755 : getOrCreateVectorValue(
GEP->getPointerOperand(), Part);
4761 if (OrigLoop->isLoopInvariant(U.get()))
4764 Indices.push_back(getOrCreateVectorValue(U.get(), Part));
4769 auto *NewGEP =
GEP->isInBounds()
4770 ? Builder.CreateInBoundsGEP(Ptr, Indices)
4771 : Builder.CreateGEP(Ptr, Indices);
4772 assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
4773 "NewGEP is not a pointer vector");
4774 VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
4775 addMetadata(NewGEP,
GEP);
4781 case Instruction::UDiv:
4782 case Instruction::SDiv:
4783 case Instruction::SRem:
4784 case Instruction::URem:
4787 if (Legal->isScalarWithPredication(&I)) {
4788 scalarizeInstruction(&I,
true);
4793 case Instruction::FAdd:
4794 case Instruction::Sub:
4795 case Instruction::FSub:
4796 case Instruction::Mul:
4797 case Instruction::FMul:
4798 case Instruction::FDiv:
4799 case Instruction::FRem:
4800 case Instruction::Shl:
4801 case Instruction::LShr:
4802 case Instruction::AShr:
4803 case Instruction::And:
4804 case Instruction::Or:
4805 case Instruction::Xor: {
4807 auto *BinOp = cast<BinaryOperator>(&
I);
4808 setDebugLocFromInst(Builder, BinOp);
4810 for (
unsigned Part = 0; Part < UF; ++Part) {
4811 Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
4812 Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
4813 Value *V = Builder.CreateBinOp(BinOp->getOpcode(),
A,
B);
4816 VecOp->copyIRFlags(BinOp);
4819 VectorLoopValueMap.setVectorValue(&I, Part, V);
4820 addMetadata(V, BinOp);
4829 auto *SE = PSE.
getSE();
4830 bool InvariantCond =
4832 setDebugLocFromInst(Builder, &I);
4839 auto *ScalarCond = getOrCreateScalarValue(I.
getOperand(0), 0, 0);
4841 for (
unsigned Part = 0; Part < UF; ++Part) {
4846 Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
4847 VectorLoopValueMap.setVectorValue(&I, Part, Sel);
4848 addMetadata(Sel, &I);
4854 case Instruction::ICmp:
4855 case Instruction::FCmp: {
4857 bool FCmp = (I.
getOpcode() == Instruction::FCmp);
4859 setDebugLocFromInst(Builder, Cmp);
4860 for (
unsigned Part = 0; Part < UF; ++Part) {
4861 Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
4862 Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
4865 C = Builder.CreateFCmp(Cmp->getPredicate(),
A,
B);
4866 cast<FCmpInst>(
C)->copyFastMathFlags(Cmp);
4868 C = Builder.CreateICmp(Cmp->getPredicate(),
A,
B);
4870 VectorLoopValueMap.setVectorValue(&I, Part, C);
4879 vectorizeMemoryInstruction(&I);
4881 case Instruction::ZExt:
4882 case Instruction::SExt:
4883 case Instruction::FPToUI:
4884 case Instruction::FPToSI:
4885 case Instruction::FPExt:
4886 case Instruction::PtrToInt:
4887 case Instruction::IntToPtr:
4888 case Instruction::SIToFP:
4889 case Instruction::UIToFP:
4890 case Instruction::Trunc:
4891 case Instruction::FPTrunc:
4892 case Instruction::BitCast: {
4894 setDebugLocFromInst(Builder, CI);
4900 if (Cost->isOptimizableIVTruncate(CI, VF)) {
4901 widenIntOrFpInduction(cast<PHINode>(CI->getOperand(0)),
4902 cast<TruncInst>(CI));
4910 for (
unsigned Part = 0; Part < UF; ++Part) {
4911 Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
4912 Value *Cast = Builder.CreateCast(CI->getOpcode(),
A, DestTy);
4913 VectorLoopValueMap.setVectorValue(&I, Part, Cast);
4914 addMetadata(Cast, &I);
4921 if (isa<DbgInfoIntrinsic>(I))
4923 setDebugLocFromInst(Builder, &I);
4926 auto *CI = cast<CallInst>(&
I);
4928 StringRef FnName = CI->getCalledFunction()->getName();
4929 Function *F = CI->getCalledFunction();
4930 Type *RetTy = ToVectorTy(CI->getType(), VF);
4932 for (
Value *ArgOperand : CI->arg_operands())
4933 Tys.
push_back(ToVectorTy(ArgOperand->getType(), VF));
4936 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
4937 ID == Intrinsic::lifetime_start)) {
4938 scalarizeInstruction(&I);
4944 bool NeedToScalarize;
4946 bool UseVectorIntrinsic =
4948 if (!UseVectorIntrinsic && NeedToScalarize) {
4949 scalarizeInstruction(&I);
4953 for (
unsigned Part = 0; Part < UF; ++Part) {
4955 for (
unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4956 Value *Arg = CI->getArgOperand(i);
4960 Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
4965 if (UseVectorIntrinsic) {
4967 Type *TysForDecl[] = {CI->getType()};
4973 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4974 assert(!VFnName.
empty() &&
"Vector function name is empty.");
4981 VectorF->copyAttributesFrom(F);
4984 assert(VectorF &&
"Can't create vector function.");
4987 CI->getOperandBundlesAsDefs(OpBundles);
4988 CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4990 if (isa<FPMathOperator>(V))
4993 VectorLoopValueMap.setVectorValue(&I, Part, V);
5002 scalarizeInstruction(&I);
5007 void InnerLoopVectorizer::updateAnalysis() {
5012 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
5013 "Entry does not dominate exit.");
5015 DT->addNewBlock(LI->getLoopFor(LoopVectorBody)->getHeader(),
5016 LoopVectorPreHeader);
5017 DT->addNewBlock(LoopMiddleBlock,
5018 LI->getLoopFor(LoopVectorBody)->getLoopLatch());
5019 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
5020 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
5021 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
5023 DEBUG(DT->verifyDomTree());
5036 if (
auto *C = dyn_cast<Constant>(V))
5043 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
5046 <<
"if-conversion is disabled");
5050 assert(TheLoop->getNumBlocks() > 1 &&
"Single block loops are vectorizable");
5057 if (blockNeedsPredication(BB))
5069 if (!isa<BranchInst>(BB->getTerminator())) {
5071 <<
"loop contains a switch statement");
5076 if (blockNeedsPredication(BB)) {
5077 if (!blockCanBePredicated(BB, SafePointes)) {
5079 <<
"control flow cannot be substituted for a select");
5084 <<
"control flow cannot be substituted for a select");
5093 bool LoopVectorizationLegality::canVectorize() {
5099 if (!TheLoop->getLoopPreheader()) {
5101 <<
"loop control flow is not understood by vectorizer");
5112 if (!TheLoop->empty()) {
5114 <<
"loop is not the innermost loop");
5122 if (TheLoop->getNumBackEdges() != 1) {
5124 <<
"loop control flow is not understood by vectorizer");
5132 if (!TheLoop->getExitingBlock()) {
5134 <<
"loop control flow is not understood by vectorizer");
5144 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5146 <<
"loop control flow is not understood by vectorizer");
5154 DEBUG(
dbgs() <<
"LV: Found a loop: " << TheLoop->getHeader()->getName()
5158 unsigned NumBlocks = TheLoop->getNumBlocks();
5159 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
5160 DEBUG(
dbgs() <<
"LV: Can't if-convert the loop.\n");
5168 if (!canVectorizeInstrs()) {
5169 DEBUG(
dbgs() <<
"LV: Can't vectorize the instructions or CFG\n");
5177 if (!canVectorizeMemory()) {
5178 DEBUG(
dbgs() <<
"LV: Can't vectorize due to memory conflicts\n");
5185 DEBUG(
dbgs() <<
"LV: We can vectorize this loop"
5186 << (LAI->getRuntimePointerChecking()->Need
5187 ?
" (with a runtime bound check)"
5199 InterleaveInfo.analyzeInterleaving(*getSymbolicStrides());
5202 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
5207 <<
"Too many SCEV assumptions need to be made and checked "
5209 DEBUG(
dbgs() <<
"LV: Too many SCEV checks needed.\n");
5249 if (!AllowedExit.
count(Inst))
5255 DEBUG(
dbgs() <<
"LV: Found an outside user for : " << *UI <<
'\n');
5262 void LoopVectorizationLegality::addInductionPhi(
5265 Inductions[Phi] =
ID;
5288 if (!PrimaryInduction || PhiTy == WidestIndTy)
5289 PrimaryInduction = Phi;
5302 DEBUG(
dbgs() <<
"LV: Found an induction variable.\n");
5306 bool LoopVectorizationLegality::canVectorizeInstrs() {
5318 if (
auto *Phi = dyn_cast<PHINode>(&I)) {
5324 <<
"loop control flow is not understood by vectorizer");
5325 DEBUG(
dbgs() <<
"LV: Found an non-int non-pointer PHI.\n");
5338 <<
"value could not be identified as "
5339 "an induction or reduction variable");
5346 <<
"control flow not understood by vectorizer");
5347 DEBUG(
dbgs() <<
"LV: Found an invalid PHI.\n");
5356 Reductions[Phi] = RedDes;
5362 addInductionPhi(Phi, ID, AllowedExit);
5370 FirstOrderRecurrences.insert(Phi);
5377 addInductionPhi(Phi, ID, AllowedExit);
5382 <<
"value that could not be identified as "
5383 "reduction is used outside the loop");
5384 DEBUG(
dbgs() <<
"LV: Found an unidentified PHI." << *Phi <<
"\n");
5394 !isa<DbgInfoIntrinsic>(CI) &&
5395 !(CI->getCalledFunction() && TLI &&
5396 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
5398 <<
"call instruction cannot be vectorized");
5399 DEBUG(
dbgs() <<
"LV: Found a non-intrinsic, non-libfunc callsite.\n");
5407 auto *SE = PSE.
getSE();
5408 if (!SE->isLoopInvariant(PSE.
getSCEV(CI->getOperand(1)), TheLoop)) {
5410 <<
"intrinsic instruction cannot be vectorized");
5411 DEBUG(
dbgs() <<
"LV: Found unvectorizable intrinsic " << *CI <<
"\n");
5420 isa<ExtractElementInst>(I)) {
5422 <<
"instruction return type cannot be vectorized");
5423 DEBUG(
dbgs() <<
"LV: Found unvectorizable type.\n");
5428 if (
auto *
ST = dyn_cast<StoreInst>(&I)) {
5429 Type *
T =
ST->getValueOperand()->getType();
5432 <<
"store instruction cannot be vectorized");
5443 DEBUG(
dbgs() <<
"LV: Found FP op with unsafe algebra.\n");
5444 Hints->setPotentiallyUnsafe();
5451 <<
"value cannot be used outside the loop");
5458 if (!PrimaryInduction) {
5459 DEBUG(
dbgs() <<
"LV: Did not find one integer induction var.\n");
5460 if (Inductions.empty()) {
5462 <<
"loop induction variable could not be identified");
5470 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
5471 PrimaryInduction =
nullptr;
5476 void LoopVectorizationCostModel::collectLoopScalars(
unsigned VF) {
5481 assert(VF >= 2 && !Scalars.count(VF) &&
5482 "This function should not be visited twice for the same VF");
5496 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5497 assert(WideningDecision != CM_Unknown &&
5498 "Widening decision should be ready at this moment");
5499 if (
auto *
Store = dyn_cast<StoreInst>(MemAccess))
5500 if (Ptr ==
Store->getValueOperand())
5501 return WideningDecision == CM_Scalarize;
5503 "Ptr is neither a value or pointer operand");
5504 return WideningDecision != CM_GatherScatter;
5509 auto isLoopVaryingBitCastOrGEP = [&](
Value *V) {
5511 isa<GetElementPtrInst>(V)) &&
5512 !TheLoop->isLoopInvariant(V);
5523 if (!isLoopVaryingBitCastOrGEP(Ptr))
5528 auto *I = cast<Instruction>(
Ptr);
5529 if (Worklist.count(I))
5536 return isa<LoadInst>(U) || isa<StoreInst>(U);
5540 PossibleNonScalarPtrs.
insert(I);
5551 Worklist.insert(Uniforms[VF].
begin(), Uniforms[VF].
end());
5558 for (
auto *BB : TheLoop->blocks())
5559 for (
auto &I : *BB) {
5560 if (
auto *
Load = dyn_cast<LoadInst>(&I)) {
5561 evaluatePtrUse(
Load,
Load->getPointerOperand());
5562 }
else if (
auto *
Store = dyn_cast<StoreInst>(&I)) {
5563 evaluatePtrUse(
Store,
Store->getPointerOperand());
5564 evaluatePtrUse(
Store,
Store->getValueOperand());
5567 for (
auto *I : ScalarPtrs)
5568 if (!PossibleNonScalarPtrs.
count(I)) {
5569 DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *I <<
"\n");
5578 auto *Latch = TheLoop->getLoopLatch();
5579 for (
auto &Induction : *Legal->getInductionVars()) {
5580 auto *Ind = Induction.first;
5581 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5584 Worklist.insert(Ind);
5585 Worklist.insert(IndUpdate);
5586 DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Ind <<
"\n");
5587 DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *IndUpdate <<
"\n");
5593 if (ForcedScalars.count(VF))
5594 for (
auto *I : ForcedScalars.find(VF)->second)
5602 while (Idx != Worklist.size()) {
5604 if (!isLoopVaryingBitCastOrGEP(Dst->
getOperand(0)))
5606 auto *Src = cast<Instruction>(Dst->
getOperand(0));
5608 auto *J = cast<Instruction>(U);
5609 return !TheLoop->contains(J) || Worklist.count(J) ||
5610 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5611 isScalarUse(J, Src));
5613 Worklist.insert(Src);
5614 DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Src <<
"\n");
5620 for (
auto &Induction : *Legal->getInductionVars()) {
5621 auto *Ind = Induction.first;
5622 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5634 auto ScalarInd =
all_of(Ind->users(), [&](
User *U) ->
bool {
5635 auto *I = cast<Instruction>(U);
5636 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5643 auto ScalarIndUpdate =
all_of(IndUpdate->users(), [&](
User *U) ->
bool {
5644 auto *I = cast<Instruction>(U);
5645 return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5647 if (!ScalarIndUpdate)
5651 Worklist.insert(Ind);
5652 Worklist.insert(IndUpdate);
5653 DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Ind <<
"\n");
5654 DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *IndUpdate <<
"\n");
5657 Scalars[VF].insert(Worklist.begin(), Worklist.end());
5660 bool LoopVectorizationLegality::isScalarWithPredication(
Instruction *I) {
5661 if (!blockNeedsPredication(I->
getParent()))
5667 return !isMaskRequired(I);
5668 case Instruction::UDiv:
5669 case Instruction::SDiv:
5670 case Instruction::SRem:
5671 case Instruction::URem:
5677 bool LoopVectorizationLegality::memoryInstructionCanBeWidened(
Instruction *I,
5682 assert((LI || SI) &&
"Invalid memory instruction");
5687 if (!isConsecutivePtr(Ptr))
5692 if (isScalarWithPredication(I))
5698 auto *ScalarTy = LI ? LI->
getType() : SI->getValueOperand()->getType();
5699 if (hasIrregularType(ScalarTy, DL, VF))
5705 void LoopVectorizationCostModel::collectLoopUniforms(
unsigned VF) {
5712 assert(VF >= 2 && !Uniforms.count(VF) &&
5713 "This function should not be visited twice for the same VF");
5717 Uniforms[VF].clear();
5725 auto isOutOfScope = [&](
Value *V) ->
bool {
5727 return (!I || !TheLoop->contains(I));
5737 if (Cmp && TheLoop->contains(Cmp) && Cmp->
hasOneUse()) {
5739 DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *Cmp <<
"\n");
5751 auto isUniformDecision = [&](
Instruction *
I,
unsigned VF) {
5752 InstWidening WideningDecision = getWideningDecision(I, VF);
5753 assert(WideningDecision != CM_Unknown &&
5754 "Widening decision should be ready at this moment");
5756 return (WideningDecision == CM_Widen ||
5757 WideningDecision == CM_Interleave);
5767 for (
auto *BB : TheLoop->blocks())
5768 for (
auto &I : *BB) {
5777 auto UsersAreMemAccesses =
all_of(Ptr->
users(), [&](
User *U) ->
bool {
5785 if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
5786 PossibleNonUniformPtrs.
insert(Ptr);
5792 ConsecutiveLikePtrs.
insert(Ptr);
5797 for (
auto *V : ConsecutiveLikePtrs)
5798 if (!PossibleNonUniformPtrs.
count(V)) {
5799 DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *V <<
"\n");
5808 while (idx != Worklist.
size()) {
5812 if (isOutOfScope(OV))
5814 auto *OI = cast<Instruction>(OV);
5815 if (
all_of(OI->users(), [&](
User *U) ->
bool {
5816 auto *J = cast<Instruction>(U);
5817 return !TheLoop->contains(J) || Worklist.
count(J) ||
5821 DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *OI <<
"\n");
5838 for (
auto &Induction : *Legal->getInductionVars()) {
5839 auto *Ind = Induction.first;
5840 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5844 auto UniformInd =
all_of(Ind->users(), [&](
User *U) ->
bool {
5845 auto *I = cast<Instruction>(U);
5846 return I == IndUpdate || !TheLoop->contains(I) || Worklist.
count(I) ||
5847 isVectorizedMemAccessUse(I, Ind);
5854 auto UniformIndUpdate =
all_of(IndUpdate->users(), [&](
User *U) ->
bool {
5855 auto *I = cast<Instruction>(U);
5856 return I == Ind || !TheLoop->contains(I) || Worklist.
count(I) ||
5857 isVectorizedMemAccessUse(I, IndUpdate);
5859 if (!UniformIndUpdate)
5864 Worklist.
insert(IndUpdate);
5865 DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *Ind <<
"\n");
5866 DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *IndUpdate <<
"\n");
5869 Uniforms[VF].insert(Worklist.
begin(), Worklist.
end());
5872 bool LoopVectorizationLegality::canVectorizeMemory() {
5873 LAI = &(*GetLAA)(*TheLoop);
5874 InterleaveInfo.setLAI(LAI);
5878 "loop not vectorized: ", *LAR);
5881 if (!LAI->canVectorizeMemory())
5884 if (LAI->hasStoreToLoopInvariantAddress()) {
5886 <<
"write to a loop invariant address could not be vectorized");
5887 DEBUG(
dbgs() <<
"LV: We don't allow storing to uniform addresses\n");
5891 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
5897 bool LoopVectorizationLegality::isInductionVariable(
const Value *V) {
5899 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5903 return Inductions.count(PN);
5906 bool LoopVectorizationLegality::isFirstOrderRecurrence(
const PHINode *Phi) {
5907 return FirstOrderRecurrences.count(Phi);
5910 bool LoopVectorizationLegality::blockNeedsPredication(
BasicBlock *BB) {
5914 bool LoopVectorizationLegality::blockCanBePredicated(
5916 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
5920 for (
Value *Operand : I.operands()) {
5921 if (
auto *C = dyn_cast<Constant>(Operand))
5926 if (I.mayReadFromMemory()) {
5932 isLegalMaskedGather(LI->
getType())) {
5933 MaskedOp.insert(LI);
5937 if (IsAnnotatedParallel)
5943 if (I.mayWriteToMemory()) {
5951 if (isLegalMaskedStore(SI->getValueOperand()->getType(),
5952 SI->getPointerOperand()) ||
5953 isLegalMaskedScatter(SI->getValueOperand()->getType())) {
5954 MaskedOp.insert(SI);
5958 bool isSafePtr = (SafePtrs.
count(SI->getPointerOperand()) != 0);
5962 !isSinglePredecessor)
5972 void InterleavedAccessInfo::collectConstStrideAccesses(
5976 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
5987 for (
auto &I : *BB) {
6001 int64_t Stride =
getPtrStride(PSE, Ptr, TheLoop, Strides,
6009 unsigned Align = getMemInstAlignment(&I);
6013 AccessStrideInfo[&
I] = StrideDescriptor(Stride, Scev, Size, Align);
6053 void InterleavedAccessInfo::analyzeInterleaving(
6055 DEBUG(
dbgs() <<
"LV: Analyzing interleaved accesses...\n");
6059 collectConstStrideAccesses(AccessStrideInfo, Strides);
6061 if (AccessStrideInfo.
empty())
6065 collectDependences();
6084 for (
auto BI = AccessStrideInfo.
rbegin(),
E = AccessStrideInfo.
rend();
6087 StrideDescriptor DesB = BI->second;
6092 InterleaveGroup *Group =
nullptr;
6093 if (isStrided(DesB.Stride)) {
6094 Group = getInterleaveGroup(B);
6096 DEBUG(
dbgs() <<
"LV: Creating an interleave group with:" << *B <<
'\n');
6097 Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
6100 StoreGroups.
insert(Group);
6102 LoadGroups.
insert(Group);
6105 for (
auto AI = std::next(BI); AI !=
E; ++AI) {
6107 StrideDescriptor DesA = AI->second;
6128 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
6135 if (isInterleaved(A)) {
6136 InterleaveGroup *StoreGroup = getInterleaveGroup(A);
6137 StoreGroups.
remove(StoreGroup);
6138 releaseGroup(StoreGroup);
6151 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
6161 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
6166 if (getMemInstAddressSpace(A) != getMemInstAddressSpace(B))
6178 if (DistanceToB % static_cast<int64_t>(DesB.Size))
6191 Group->getIndex(B) + DistanceToB /
static_cast<int64_t
>(DesB.Size);
6194 if (Group->insertMember(A, IndexA, DesA.Align)) {
6195 DEBUG(
dbgs() <<
"LV: Inserted:" << *A <<
'\n'
6196 <<
" into the interleave group with" << *B <<
'\n');
6197 InterleaveGroupMap[
A] = Group;
6201 Group->setInsertPos(A);
6207 for (InterleaveGroup *Group : StoreGroups)
6208 if (Group->getNumMembers() != Group->getFactor())
6209 releaseGroup(Group);
6226 for (InterleaveGroup *Group : LoadGroups) {
6231 if (Group->getNumMembers() == Group->getFactor())
6240 if (!
getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides,
false,
6242 DEBUG(
dbgs() <<
"LV: Invalidate candidate interleaved group due to "
6243 "first group member potentially pointer-wrapping.\n");
6244 releaseGroup(Group);
6247 Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
6250 if (!
getPtrStride(PSE, LastMemberPtr, TheLoop, Strides,
false,
6252 DEBUG(
dbgs() <<
"LV: Invalidate candidate interleaved group due to "
6253 "last group member potentially pointer-wrapping.\n");
6254 releaseGroup(Group);
6262 if (Group->isReverse()) {
6263 releaseGroup(Group);
6266 DEBUG(
dbgs() <<
"LV: Interleaved group requires epilogue iteration.\n");
6267 RequiresScalarEpilogue =
true;
6275 <<
"store that is conditionally executed prevents vectorization");
6276 DEBUG(
dbgs() <<
"LV: No vectorization. There are conditional stores.\n");
6281 return computeFeasibleMaxVF(OptForSize);
6283 if (Legal->getRuntimePointerChecking()->Need) {
6285 <<
"runtime pointer checks needed. Enable vectorization of this "
6286 "loop with '#pragma clang loop vectorize(enable)' when "
6287 "compiling with -Os/-Oz");
6289 <<
"LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
6295 DEBUG(
dbgs() <<
"LV: Found trip count: " << TC <<
'\n');
6301 <<
"unable to calculate the loop count due to complex control flow");
6302 DEBUG(
dbgs() <<
"LV: Aborting. A tail loop is required with -Os/-Oz.\n");
6306 unsigned MaxVF = computeFeasibleMaxVF(OptForSize);
6308 if (TC % MaxVF != 0) {
6316 <<
"cannot optimize for size and vectorize at the "
6317 "same time. Enable vectorization of this loop "
6318 "with '#pragma clang loop vectorize(enable)' "
6319 "when compiling with -Os/-Oz");
6320 DEBUG(
dbgs() <<
"LV: Aborting. A tail loop is required with -Os/-Oz.\n");
6327 unsigned LoopVectorizationCostModel::computeFeasibleMaxVF(
bool OptForSize) {
6329 unsigned SmallestType, WidestType;
6330 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
6332 unsigned MaxSafeDepDist = -1U;
6340 if (Legal->getMaxSafeDepDistBytes() != -1U)
6342 Legal->getMaxSafeDepDistBytes() * 8 / Legal->getMaxInterleaveFactor();
6345 ((WidestRegister < MaxSafeDepDist) ? WidestRegister : MaxSafeDepDist);
6346 unsigned MaxVectorSize = WidestRegister / WidestType;
6348 DEBUG(
dbgs() <<
"LV: The Smallest and Widest types: " << SmallestType <<
" / "
6349 << WidestType <<
" bits.\n");
6350 DEBUG(
dbgs() <<
"LV: The Widest register is: " << WidestRegister
6353 if (MaxVectorSize == 0) {
6354 DEBUG(
dbgs() <<
"LV: The target has no vector registers.\n");
6358 assert(MaxVectorSize <= 64 &&
"Did not expect to pack so many elements"
6359 " into one vector!");
6361 unsigned MaxVF = MaxVectorSize;
6365 unsigned NewMaxVectorSize = WidestRegister / SmallestType;
6366 for (
unsigned VS = MaxVectorSize;
VS <= NewMaxVectorSize;
VS *= 2)
6370 auto RUs = calculateRegisterUsage(VFs);
6375 for (
int i = RUs.size() - 1; i >= 0; --i) {
6376 if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
6386 LoopVectorizationCostModel::selectVectorizationFactor(
unsigned MaxVF) {
6387 float Cost = expectedCost(1).first;
6389 const float ScalarCost = Cost;
6392 DEBUG(
dbgs() <<
"LV: Scalar loop costs: " << (
int)ScalarCost <<
".\n");
6394 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6396 if (ForceVectorization && MaxVF > 1) {
6398 Cost = expectedCost(Width).first / (float)Width;
6401 for (
unsigned i = 2; i <= MaxVF; i *= 2) {
6405 VectorizationCostTy C = expectedCost(i);
6406 float VectorCost = C.first / (float)i;
6407 DEBUG(
dbgs() <<
"LV: Vector loop of width " << i
6408 <<
" costs: " << (
int)VectorCost <<
".\n");
6409 if (!C.second && !ForceVectorization) {
6411 dbgs() <<
"LV: Not considering vector loop of width " << i
6412 <<
" because it will not generate any vector instructions.\n");
6415 if (VectorCost < Cost) {
6421 DEBUG(
if (ForceVectorization && Width > 1 && Cost >= ScalarCost)
dbgs()
6422 <<
"LV: Vectorization seems to be not beneficial, "
6423 <<
"but was forced by a user.\n");
6424 DEBUG(
dbgs() <<
"LV: Selecting VF: " << Width <<
".\n");
6429 std::pair<unsigned, unsigned>
6430 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6431 unsigned MinWidth = -1U;
6432 unsigned MaxWidth = 8;
6433 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6439 Type *T = I.getType();
6442 if (ValuesToIgnore.count(&I))
6446 if (!isa<LoadInst>(I) && !isa<StoreInst>(
I) && !isa<PHINode>(I))
6451 if (
auto *PN = dyn_cast<PHINode>(&I)) {
6452 if (!Legal->isReductionVariable(PN))
6459 if (
auto *
ST = dyn_cast<StoreInst>(&I))
6460 T =
ST->getValueOperand()->getType();
6471 if (T->
isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6472 !Legal->isAccessInterleaved(&I) && !Legal->isLegalGatherOrScatter(&I))
6482 return {MinWidth, MaxWidth};
6485 unsigned LoopVectorizationCostModel::selectInterleaveCount(
bool OptForSize,
6487 unsigned LoopCost) {
6508 if (Legal->getMaxSafeDepDistBytes() != -1U)
6517 DEBUG(
dbgs() <<
"LV: The target has " << TargetNumRegisters
6528 RegisterUsage R = calculateRegisterUsage({VF})[0];
6531 R.MaxLocalUsers =
std::max(R.MaxLocalUsers, 1U);
6532 R.NumInstructions =
std::max(R.NumInstructions, 1U);
6542 unsigned IC =
PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
6547 IC =
PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
6548 std::max(1U, (R.MaxLocalUsers - 1)));
6565 LoopCost = expectedCost(VF).first;
6569 if (IC > MaxInterleaveCount)
6570 IC = MaxInterleaveCount;
6576 if (VF > 1 && Legal->getReductionVars()->size()) {
6577 DEBUG(
dbgs() <<
"LV: Interleaving because of reductions.\n");
6583 bool InterleavingRequiresRuntimePointerCheck =
6584 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
6588 DEBUG(
dbgs() <<
"LV: Loop cost is " << LoopCost <<
'\n');
6589 if (!InterleavingRequiresRuntimePointerCheck && LoopCost <
SmallLoopCost) {
6598 unsigned NumStores = Legal->getNumStores();
6599 unsigned NumLoads = Legal->getNumLoads();
6600 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6601 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6607 if (Legal->getReductionVars()->size() && TheLoop->getLoopDepth() > 1) {
6615 std::max(StoresIC, LoadsIC) > SmallIC) {
6616 DEBUG(
dbgs() <<
"LV: Interleaving to saturate store or load ports.\n");
6617 return std::max(StoresIC, LoadsIC);
6620 DEBUG(
dbgs() <<
"LV: Interleaving to reduce branch cost.\n");
6626 bool HasReductions = (Legal->getReductionVars()->size() > 0);
6628 DEBUG(
dbgs() <<
"LV: Interleaving to expose ILP.\n");
6632 DEBUG(
dbgs() <<
"LV: Not Interleaving.\n");
6659 RU.NumInstructions = 0;
6668 IntervalMap EndPoint;
6677 RU.NumInstructions += BB->size();
6679 IdxToInstr[Index++] = &
I;
6682 for (
Value *U : I.operands()) {
6690 if (!TheLoop->contains(Instr)) {
6691 LoopInvariants.
insert(Instr);
6696 EndPoint[Instr] = Index;
6713 unsigned MaxSafeDepDist = -1U;
6714 if (Legal->getMaxSafeDepDistBytes() != -1U)
6715 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
6716 unsigned WidestRegister =
6718 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6723 DEBUG(
dbgs() <<
"LV(REG): Calculating max register usage:\n");
6726 auto GetRegUsage = [&DL, WidestRegister](
Type *Ty,
unsigned VF) {
6727 if (Ty->isTokenTy())
6729 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
6730 return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
6733 for (
unsigned int i = 0; i < Index; ++i) {
6737 InstrList &List = TransposeEnds[i];
6739 OpenIntervals.
erase(ToRemove);
6746 if (ValuesToIgnore.count(I))
6750 for (
unsigned j = 0, e = VFs.
size(); j < e; ++j) {
6752 MaxUsages[j] =
std::max(MaxUsages[j], OpenIntervals.
size());
6755 collectUniformsAndScalars(VFs[j]);
6758 for (
auto Inst : OpenIntervals) {
6760 if (VecValuesToIgnore.count(Inst) ||
6761 isScalarAfterVectorization(Inst, VFs[j]))
6763 RegUsage += GetRegUsage(Inst->
getType(), VFs[j]);
6765 MaxUsages[j] =
std::max(MaxUsages[j], RegUsage);
6768 DEBUG(
dbgs() <<
"LV(REG): At #" << i <<
" Interval # "
6769 << OpenIntervals.size() <<
'\n');
6772 OpenIntervals.insert(I);
6775 for (
unsigned i = 0, e = VFs.
size(); i < e; ++i) {
6776 unsigned Invariant = 0;
6778 Invariant = LoopInvariants.
size();
6780 for (
auto Inst : LoopInvariants)
6781 Invariant += GetRegUsage(Inst->
getType(), VFs[i]);
6784 DEBUG(
dbgs() <<
"LV(REG): VF = " << VFs[i] <<
'\n');
6785 DEBUG(
dbgs() <<
"LV(REG): Found max usage: " << MaxUsages[i] <<
'\n');
6786 DEBUG(
dbgs() <<
"LV(REG): Found invariant usage: " << Invariant <<
'\n');
6787 DEBUG(
dbgs() <<
"LV(REG): LoopSize: " << RU.NumInstructions <<
'\n');
6789 RU.LoopInvariantRegs = Invariant;
6790 RU.MaxLocalUsers = MaxUsages[i];
6797 void LoopVectorizationCostModel::collectInstsToScalarize(
unsigned VF) {
6803 if (VF < 2 || InstsToScalarize.count(VF))
6809 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6815 if (!Legal->blockNeedsPredication(BB))
6818 if (Legal->isScalarWithPredication(&I)) {
6819 ScalarCostsTy ScalarCosts;
6820 if (computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6821 ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6824 PredicatedBBsAfterVectorization.insert(BB);
6829 int LoopVectorizationCostModel::computePredInstDiscount(
6833 assert(!isUniformAfterVectorization(PredInst, VF) &&
6834 "Instruction marked uniform-after-vectorization will be predicated");
6854 isScalarAfterVectorization(I, VF))
6859 if (Legal->isScalarWithPredication(I))
6873 if (
auto *J = dyn_cast<Instruction>(U.get()))
6874 if (isUniformAfterVectorization(J, VF))
6887 return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
6894 while (!Worklist.
empty()) {
6898 if (ScalarCosts.
count(I))
6903 unsigned VectorCost = getInstructionCost(I, VF).first;
6909 unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
6924 if (
auto *J = dyn_cast<Instruction>(U.get())) {
6926 "Instruction has non-scalar type");
6927 if (canBeScalarized(J))
6929 else if (needsExtract(J))
6931 ToVectorTy(J->getType(),VF),
false,
true);
6935 ScalarCost /= getReciprocalPredBlockProb();
6939 Discount += VectorCost - ScalarCost;
6940 ScalarCosts[
I] = ScalarCost;
6946 LoopVectorizationCostModel::VectorizationCostTy
6947 LoopVectorizationCostModel::expectedCost(
unsigned VF) {
6948 VectorizationCostTy Cost;
6951 collectUniformsAndScalars(VF);
6955 collectInstsToScalarize(VF);
6959 VectorizationCostTy BlockCost;
6964 if (isa<DbgInfoIntrinsic>(I))
6968 if (ValuesToIgnore.count(&I))
6971 VectorizationCostTy C = getInstructionCost(&I, VF);
6977 BlockCost.first += C.first;
6978 BlockCost.second |= C.second;
6979 DEBUG(
dbgs() <<
"LV: Found an estimated cost of " << C.first <<
" for VF "
6980 << VF <<
" For instruction: " << I <<
'\n');
6989 if (VF == 1 && Legal->blockNeedsPredication(BB))
6990 BlockCost.first /= getReciprocalPredBlockProb();
6992 Cost.first += BlockCost.first;
6993 Cost.second |= BlockCost.second;
7006 LoopVectorizationLegality *Legal,
7008 const Loop *TheLoop) {
7016 for (
unsigned i = 1; i < NumOperands; ++i) {
7017 Value *Opd = Gep->getOperand(i);
7019 !Legal->isInductionVariable(Opd))
7032 unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(
Instruction *I,
7034 Type *ValTy = getMemInstValueType(I);
7035 auto SE = PSE.
getSE();
7037 unsigned Alignment = getMemInstAlignment(I);
7038 unsigned AS = getMemInstAddressSpace(I);
7060 if (Legal->isScalarWithPredication(I))
7061 Cost /= getReciprocalPredBlockProb();
7066 unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(
Instruction *I,
7068 Type *ValTy = getMemInstValueType(I);
7069 Type *VectorTy = ToVectorTy(ValTy, VF);
7070 unsigned Alignment = getMemInstAlignment(I);
7072 unsigned AS = getMemInstAddressSpace(I);
7073 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
7075 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7076 "Stride should be 1 or -1 for consecutive memory access");
7078 if (Legal->isMaskRequired(I))
7083 bool Reverse = ConsecutiveStride < 0;
7089 unsigned LoopVectorizationCostModel::getUniformMemOpCost(
Instruction *I,
7093 Type *VectorTy = ToVectorTy(ValTy, VF);
7102 unsigned LoopVectorizationCostModel::getGatherScatterCost(
Instruction *I,
7104 Type *ValTy = getMemInstValueType(I);
7105 Type *VectorTy = ToVectorTy(ValTy, VF);
7106 unsigned Alignment = getMemInstAlignment(I);
7111 Legal->isMaskRequired(I), Alignment);
7114 unsigned LoopVectorizationCostModel::getInterleaveGroupCost(
Instruction *I,
7116 Type *ValTy = getMemInstValueType(I);
7117 Type *VectorTy = ToVectorTy(ValTy, VF);
7118 unsigned AS = getMemInstAddressSpace(I);
7120 auto Group = Legal->getInterleavedAccessGroup(I);
7121 assert(Group &&
"Fail to get an interleaved access group.");
7123 unsigned InterleaveFactor = Group->getFactor();
7129 if (isa<LoadInst>(I)) {
7130 for (
unsigned i = 0; i < InterleaveFactor; i++)
7131 if (Group->getMember(i))
7137 Group->getFactor(), Indices,
7138 Group->getAlignment(), AS);
7140 if (Group->isReverse())
7141 Cost += Group->getNumMembers() *
7146 unsigned LoopVectorizationCostModel::getMemoryInstructionCost(
Instruction *I,
7152 Type *ValTy = getMemInstValueType(I);
7153 unsigned Alignment = getMemInstAlignment(I);
7154 unsigned AS = getMemInstAddressSpace(I);
7159 return getWideningCost(I, VF);
7162 LoopVectorizationCostModel::VectorizationCostTy
7163 LoopVectorizationCostModel::getInstructionCost(
Instruction *I,
unsigned VF) {
7166 if (isUniformAfterVectorization(I, VF))
7169 if (VF > 1 && isProfitableToScalarize(I, VF))
7170 return VectorizationCostTy(InstsToScalarize[VF][I],
false);
7173 if (VF > 1 && ForcedScalars.count(VF) &&
7174 ForcedScalars.find(VF)->second.count(I))
7175 return VectorizationCostTy((getInstructionCost(I, 1).
first * VF),
false);
7178 unsigned C = getInstructionCost(I, VF, VectorTy);
7180 bool TypeNotScalarized =
7182 return VectorizationCostTy(C, TypeNotScalarized);
7185 void LoopVectorizationCostModel::setCostBasedWideningDecision(
unsigned VF) {
7195 if (isa<LoadInst>(&I) && Legal->isUniform(Ptr)) {
7197 unsigned Cost = getUniformMemOpCost(&I, VF);
7198 setWideningDecision(&I, VF, CM_Scalarize, Cost);
7203 if (Legal->memoryInstructionCanBeWidened(&I, VF)) {
7204 unsigned Cost = getConsecutiveMemOpCost(&I, VF);
7205 setWideningDecision(&I, VF, CM_Widen, Cost);
7210 unsigned InterleaveCost = UINT_MAX;
7211 unsigned NumAccesses = 1;
7212 if (Legal->isAccessInterleaved(&I)) {
7213 auto Group = Legal->getInterleavedAccessGroup(&I);
7214 assert(Group &&
"Fail to get an interleaved access group.");
7217 if (getWideningDecision(&I, VF) != CM_Unknown)
7220 NumAccesses = Group->getNumMembers();
7221 InterleaveCost = getInterleaveGroupCost(&I, VF);
7224 unsigned GatherScatterCost =
7225 Legal->isLegalGatherOrScatter(&I)
7226 ? getGatherScatterCost(&I, VF) * NumAccesses
7229 unsigned ScalarizationCost =
7230 getMemInstScalarizationCost(&I, VF) * NumAccesses;
7235 InstWidening Decision;
7236 if (InterleaveCost <= GatherScatterCost &&
7237 InterleaveCost < ScalarizationCost) {
7238 Decision = CM_Interleave;
7239 Cost = InterleaveCost;
7240 }
else if (GatherScatterCost < ScalarizationCost) {
7241 Decision = CM_GatherScatter;
7242 Cost = GatherScatterCost;
7244 Decision = CM_Scalarize;
7245 Cost = ScalarizationCost;
7250 if (
auto Group = Legal->getInterleavedAccessGroup(&I))
7251 setWideningDecision(Group, VF, Decision, Cost);
7253 setWideningDecision(&I, VF, Decision, Cost);
7271 if (PtrDef && TheLoop->contains(PtrDef) &&
7272 getWideningDecision(&I, VF) != CM_GatherScatter)
7278 for (
auto *I : AddrDefs)
7280 while (!Worklist.
empty()) {
7283 if (
auto *InstOp = dyn_cast<Instruction>(Op))
7284 if ((InstOp->getParent() == I->
getParent()) && !isa<PHINode>(InstOp) &&
7285 AddrDefs.insert(InstOp).second ==
true)
7289 for (
auto *I : AddrDefs) {
7290 if (isa<LoadInst>(I)) {
7295 if (getWideningDecision(I, VF) == CM_Widen)
7297 setWideningDecision(I, VF, CM_Scalarize,
7298 (VF * getMemoryInstructionCost(I, 1)));
7299 else if (
auto Group = Legal->getInterleavedAccessGroup(I)) {
7301 for (
unsigned I = 0; I < Group->getFactor(); ++
I) {
7303 setWideningDecision(Member, VF, CM_Scalarize,
7304 (VF * getMemoryInstructionCost(Member, 1)));
7310 ForcedScalars[VF].insert(I);
7314 unsigned LoopVectorizationCostModel::getInstructionCost(
Instruction *I,
7318 if (canTruncateToMinimalBitwidth(I, VF))
7320 VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
7321 auto SE = PSE.
getSE();
7325 case Instruction::GetElementPtr:
7331 case Instruction::Br: {
7335 bool ScalarPredicatedBB =
false;
7338 (PredicatedBBsAfterVectorization.count(BI->
getSuccessor(0)) ||
7339 PredicatedBBsAfterVectorization.count(BI->
getSuccessor(1))))
7340 ScalarPredicatedBB =
true;
7342 if (ScalarPredicatedBB) {
7348 }
else if (I->
getParent() == TheLoop->getLoopLatch() || VF == 1)
7358 case Instruction::PHI: {
7359 auto *Phi = cast<PHINode>(
I);
7362 if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
7364 VectorTy, VF - 1, VectorTy);
7369 if (VF > 1 && Phi->
getParent() != TheLoop->getHeader())
7377 case Instruction::UDiv:
7378 case Instruction::SDiv:
7379 case Instruction::URem:
7380 case Instruction::SRem:
7385 if (VF > 1 && Legal->isScalarWithPredication(I)) {
7404 return Cost / getReciprocalPredBlockProb();
7408 case Instruction::FAdd:
7409 case Instruction::Sub:
7410 case Instruction::FSub:
7411 case Instruction::Mul:
7412 case Instruction::FMul:
7413 case Instruction::FDiv:
7414 case Instruction::FRem:
7415 case Instruction::Shl:
7416 case Instruction::LShr:
7417 case Instruction::AShr:
7418 case Instruction::And:
7419 case Instruction::Or:
7420 case Instruction::Xor: {
7437 if (isa<ConstantInt>(Op2)) {
7442 }
else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
7451 }
else if (Legal->isUniform(Op2)) {
7455 unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
7457 Op2VK, Op1VP, Op2VP, Operands);
7462 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7469 case Instruction::ICmp:
7470 case Instruction::FCmp: {
7473 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7475 VectorTy = ToVectorTy(ValTy, VF);
7480 unsigned Width = VF;
7482 InstWidening Decision = getWideningDecision(I, Width);
7483 assert(Decision != CM_Unknown &&
7484 "CM decision should be taken at this point");
7485 if (Decision == CM_Scalarize)
7488 VectorTy = ToVectorTy(getMemInstValueType(I), Width);
7489 return getMemoryInstructionCost(I, VF);
7491 case Instruction::ZExt:
7492 case Instruction::SExt:
7493 case Instruction::FPToUI:
7494 case Instruction::FPToSI:
7495 case Instruction::FPExt:
7496 case Instruction::PtrToInt:
7497 case Instruction::IntToPtr:
7498 case Instruction::SIToFP:
7499 case Instruction::UIToFP:
7500 case Instruction::Trunc:
7501 case Instruction::FPTrunc:
7502 case Instruction::BitCast: {
7506 if (isOptimizableIVTruncate(I, VF)) {
7507 auto *Trunc = cast<TruncInst>(
I);
7509 Trunc->getSrcTy(), Trunc);
7514 VectorTy->
isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7515 if (canTruncateToMinimalBitwidth(I, VF)) {
7521 Type *MinVecTy = VectorTy;
7522 if (I->
getOpcode() == Instruction::Trunc) {
7526 }
else if (I->
getOpcode() == Instruction::ZExt ||
7534 unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
7538 bool NeedToScalarize;
7554 static const char lv_name[] =
"Loop Vectorization";
7572 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
7576 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(
Instruction *Inst) {
7581 return Legal->isConsecutivePtr(Ptr);
7585 void LoopVectorizationCostModel::collectValuesToIgnore() {
7591 for (
auto &
Reduction : *Legal->getReductionVars()) {
7594 VecValuesToIgnore.insert(Casts.
begin(), Casts.
end());
7599 LoopVectorizationPlanner::plan(
bool OptForSize,
unsigned UserVF) {
7606 return NoVectorization;
7609 DEBUG(
dbgs() <<
"LV: Using user VF " << UserVF <<
".\n");
7613 CM.selectUserVectorizationFactor(UserVF);
7617 unsigned MaxVF = MaybeMaxVF.
getValue();
7618 assert(MaxVF != 0 &&
"MaxVF is zero.");
7620 return NoVectorization;
7623 return CM.selectVectorizationFactor(MaxVF);
7626 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV) {
7630 ILV.createVectorizedLoopSkeleton();
7644 for (
auto &Entry : SinkAfter) {
7645 Entry.first->removeFromParent();
7646 Entry.first->insertAfter(Entry.second);
7647 DEBUG(
dbgs() <<
"Sinking" << *Entry.first <<
" after" << *Entry.second
7648 <<
" to vectorize a 1st order recurrence.\n");
7658 collectTriviallyDeadInstructions(DeadInstructions);
7669 if (!DeadInstructions.
count(&I))
7670 ILV.vectorizeInstruction(I);
7674 ILV.fixVectorizedLoop();
7677 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7679 BasicBlock *Latch = OrigLoop->getLoopLatch();
7686 DeadInstructions.
insert(Cmp);
7691 for (
auto &Induction : *Legal->getInductionVars()) {
7692 PHINode *Ind = Induction.first;
7694 if (
all_of(IndUpdate->users(), [&](
User *U) ->
bool {
7695 return U == Ind || DeadInstructions.
count(cast<Instruction>(U));
7697 DeadInstructions.
insert(IndUpdate);
7701 void InnerLoopUnroller::vectorizeMemoryInstruction(
Instruction *Instr) {
7703 bool IfPredicateInstr = (SI && Legal->blockNeedsPredication(SI->
getParent()));
7705 return scalarizeInstruction(Instr, IfPredicateInstr);
7708 Value *InnerLoopUnroller::reverseVector(
Value *Vec) {
return Vec; }
7710 Value *InnerLoopUnroller::getBroadcastInstrs(
Value *V) {
return V; }
7712 Value *InnerLoopUnroller::getStepVector(
Value *Val,
int StartIdx,
Value *Step,
7726 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step),
"induction");
7733 bool IsUnrollMetadata =
false;
7737 for (
unsigned i = 1, ie = LoopID->
getNumOperands(); i < ie; ++i) {
7748 if (!IsUnrollMetadata) {
7753 MDString::get(Context,
"llvm.loop.unroll.runtime.disable"));
7764 assert(L->
empty() &&
"Only process inner loops.");
7767 const std::string DebugLocStr = getDebugLocString(L);
7770 DEBUG(
dbgs() <<
"\nLV: Checking a loop in \""
7771 << L->
getHeader()->getParent()->getName() <<
"\" from "
7772 << DebugLocStr <<
"\n");
7774 LoopVectorizeHints Hints(L, DisableUnrolling, *ORE);
7778 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
7780 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
7783 <<
" width=" << Hints.getWidth()
7784 <<
" unroll=" << Hints.getInterleave() <<
"\n");
7797 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
7798 DEBUG(
dbgs() <<
"LV: Loop hints prevent vectorization.\n");
7805 LoopVectorizationRequirements Requirements(*ORE);
7806 LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI, ORE,
7807 &Requirements, &Hints);
7808 if (!LVL.canVectorize()) {
7809 DEBUG(
dbgs() <<
"LV: Not vectorizing: Cannot prove legality.\n");
7810 emitMissedWarning(F, L, Hints, ORE);
7817 Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
7821 unsigned ExpectedTC = SE->getSmallConstantMaxTripCount(L);
7822 bool HasExpectedTC = (ExpectedTC > 0);
7827 ExpectedTC = *EstimatedTC;
7828 HasExpectedTC =
true;
7833 DEBUG(
dbgs() <<
"LV: Found a loop with a very small trip count. "
7834 <<
"This loop is worth vectorizing only if no scalar "
7835 <<
"iteration overheads are incurred.");
7836 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
7837 DEBUG(
dbgs() <<
" But vectorizing was explicitly forced.\n");
7851 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7852 DEBUG(
dbgs() <<
"LV: Can't vectorize when the NoImplicitFloat"
7853 "attribute is used.\n");
7855 "NoImplicitFloat",
L)
7856 <<
"loop not vectorized due to NoImplicitFloat attribute");
7857 emitMissedWarning(F, L, Hints, ORE);
7865 if (Hints.isPotentiallyUnsafe() &&
7867 DEBUG(
dbgs() <<
"LV: Potentially unsafe FP op prevents vectorization.\n");
7870 <<
"loop not vectorized due to unsafe FP support.");
7871 emitMissedWarning(F, L, Hints, ORE);
7876 LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F,
7878 CM.collectValuesToIgnore();
7881 LoopVectorizationPlanner LVP(L, LI, &LVL, CM);
7884 unsigned UserVF = Hints.getWidth();
7888 LVP.plan(OptForSize, UserVF);
7891 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
7894 unsigned UserIC = Hints.getInterleave();
7897 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
7898 bool VectorizeLoop =
true, InterleaveLoop =
true;
7899 if (Requirements.doesNotMeet(F, L, Hints)) {
7900 DEBUG(
dbgs() <<
"LV: Not vectorizing: loop did not meet vectorization "
7902 emitMissedWarning(F, L, Hints, ORE);
7906 if (VF.Width == 1) {
7907 DEBUG(
dbgs() <<
"LV: Vectorization is possible but not beneficial.\n");
7908 VecDiagMsg = std::make_pair(
7909 "VectorizationNotBeneficial",
7910 "the cost-model indicates that vectorization is not beneficial");
7911 VectorizeLoop =
false;
7914 if (IC == 1 && UserIC <= 1) {
7916 DEBUG(
dbgs() <<
"LV: Interleaving is not beneficial.\n");
7917 IntDiagMsg = std::make_pair(
7918 "InterleavingNotBeneficial",
7919 "the cost-model indicates that interleaving is not beneficial");
7920 InterleaveLoop =
false;
7922 IntDiagMsg.first =
"InterleavingNotBeneficialAndDisabled";
7923 IntDiagMsg.second +=
7924 " and is explicitly disabled or interleave count is set to 1";
7926 }
else if (IC > 1 && UserIC == 1) {
7929 <<
"LV: Interleaving is beneficial but is explicitly disabled.");
7930 IntDiagMsg = std::make_pair(
7931 "InterleavingBeneficialButDisabled",
7932 "the cost-model indicates that interleaving is beneficial "
7933 "but is explicitly disabled or interleave count is set to 1");
7934 InterleaveLoop =
false;
7938 IC = UserIC > 0 ? UserIC : IC;
7941 const char *VAPassName = Hints.vectorizeAnalysisPassName();
7942 if (!VectorizeLoop && !InterleaveLoop) {
7946 << VecDiagMsg.second);
7949 << IntDiagMsg.second);
7951 }
else if (!VectorizeLoop && InterleaveLoop) {
7952 DEBUG(
dbgs() <<
"LV: Interleave Count is " << IC <<
'\n');
7955 << VecDiagMsg.second);
7956 }
else if (VectorizeLoop && !InterleaveLoop) {
7957 DEBUG(
dbgs() <<
"LV: Found a vectorizable loop (" << VF.Width <<
") in "
7958 << DebugLocStr <<
'\n');
7961 << IntDiagMsg.second);
7962 }
else if (VectorizeLoop && InterleaveLoop) {
7963 DEBUG(
dbgs() <<
"LV: Found a vectorizable loop (" << VF.Width <<
") in "
7964 << DebugLocStr <<
'\n');
7965 DEBUG(
dbgs() <<
"LV: Interleave Count is " << IC <<
'\n');
7968 using namespace ore;
7969 if (!VectorizeLoop) {
7970 assert(IC > 1 &&
"interleave count should not be 1 or 0");
7973 InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
7975 LVP.executePlan(Unroller);
7979 <<
"interleaved loop (interleaved count: "
7980 <<
NV(
"InterleaveCount", IC) <<
")");
7983 InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
7985 LVP.executePlan(LB);
7991 if (!LB.areSafetyChecksAdded())
7997 <<
"vectorized loop (vectorization width: "
7998 <<
NV(
"VectorizationFactor", VF.Width)
7999 <<
", interleaved count: " <<
NV(
"InterleaveCount", IC) <<
")");
8003 Hints.setAlreadyVectorized();
8038 bool Changed =
false;
8054 addAcyclicInnerLoop(*L, Worklist);
8056 LoopsAnalyzed += Worklist.
size();
8059 while (!Worklist.
empty()) {
8066 Changed |= processLoop(L);
8089 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
8095 runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE);
Legacy wrapper pass to provide the GlobalsAAResult object.
Pass interface - Implemented by all 'passes'.
static unsigned RuntimeMemoryCheckThreshold
\brief When performing memory disambiguation checks at runtime do not make more than this number of c...
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.
void push_back(const T &Elt)
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
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.
bool processLoop(Loop *L)
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
This class is the base class for the comparison instructions.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool endswith(StringRef Suffix) const
Check if this string ends with the given Suffix.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
uint64_t getMaxSafeDepDistBytes() const
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
DiagnosticInfoOptimizationBase::Argument NV
STATISTIC(NumFunctions,"Total number of functions")
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."))
Instruction * getUnsafeAlgebraInst()
Returns first unsafe algebra instruction in the PHI node's use-chain.
int getWidth()
Get the width of a number.
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. ...
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDString * get(LLVMContext &Context, StringRef Str)
const Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
Interval Class - An Interval is a set of nodes defined such that every node in the interval has all o...
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Min/max implemented in terms of select(cmp()).
This class represents zero extension of integer types.
unsigned getNumOperands() const
unsigned getNumOperands() const
Return number of MDNode operands.
static unsigned getScalarizationOverhead(Instruction *I, unsigned VF, const TargetTransformInfo &TTI)
Estimate the overhead of scalarizing an instruction.
value_op_iterator value_op_begin()
static void AddRuntimeUnrollDisableMetaData(Loop *L)
The main scalar evolution driver.
This class represents a function call, abstracting a target machine's calling convention.
int64_t getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr, const Loop *Lp, const ValueToValueMap &StridesMap=ValueToValueMap(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of its element size.
An immutable pass that tracks lazily created AssumptionCache objects.
static Type * largestIntegerVectorType(Type *T1, Type *T2)
static bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes)
Returns true if Phi is a reduction in TheLoop.
A cache of .assume calls within a function.
Analysis pass providing the TargetTransformInfo.
Externally visible function.
void initializeLoopVectorizePass(PassRegistry &)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
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...
LoopT * getParentLoop() const
const Function * getParent() const
Return the enclosing method, or null if none.
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."))
const Instruction & front() const
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
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.
An instruction for reading from memory.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
Type * getElementType() 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.
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
iterator end()
Get an iterator to the end of the SetVector.
size_type size() const
Determine the number of elements in the SetVector.
BlockT * getHeader() const
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
uint64_t getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
static bool isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop, DenseMap< Instruction *, Instruction * > &SinkAfter, DominatorTree *DT)
Returns true if Phi is a first-order recurrence.
StringRef getName() const
Return a constant reference to the value's name.
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
iterator begin()
Instruction iterator methods.
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
static uint32_t getAlignment(const MCSectionCOFF &Sec)
std::string str() const
Return the twine contents as a std::string.
bool hasUnsafeAlgebra()
Returns true if the recurrence has unsafe algebra which requires a relaxed floating-point model...
static Value * getPointerOperand(Instruction &Inst)
This class represents the LLVM 'select' instruction.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
static const unsigned MaxVectorWidth
Maximum SIMD width.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal)
This is the base class for all instructions that perform data casts.
const APInt & getValue() const
Return the constant as an APInt value reference.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
A Use represents the edge between a Value definition and its users.
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"))
Diagnostic information for optimization failures.
static cl::opt< unsigned > MaxInterleaveGroupFactor("max-interleave-group-factor", cl::Hidden, cl::desc("Maximum factor for an interleaved access group (default = 8)"), cl::init(8))
Maximum factor for an interleaved memory access.
static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
static Constant * get(ArrayRef< Constant * > V)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
An analysis that produces DemandedBits for a function.
Legacy analysis pass which computes BlockFrequencyInfo.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void setName(const Twine &Name)
Change the name of the value.
Analysis pass that exposes the LoopInfo for a function.
ConstantInt * getConstIntStepValue() const
Type * getVectorElementType() const
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
static void cse(BasicBlock *BB)
Perform cse of induction variable instructions.
bool remove(const value_type &X)
Remove an item from the set vector.
static const unsigned TinyTripCountInterleaveThreshold
We don't interleave loops with a known constant trip count below this number.
void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_NODISCARD bool empty() const
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Class to represent function types.
static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI)
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static bool isEqual(const Function &Caller, const Function &Callee)
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
Value * transform(IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL) const
Compute the transformed value of Index at offset StartValue using step StepValue. ...
Value * concatenateVectors(IRBuilder<> &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
const T & getValue() const LLVM_LVALUE_FUNCTION
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
Pass * createLoopVectorizePass(bool NoUnrolling=false, bool AlwaysVectorize=true)
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
BasicBlock * getSuccessor(unsigned i) const
iterator begin()
Get an iterator to the beginning of the SetVector.
bool hasUnsafeAlgebra() const
Determine whether the unsafe-algebra flag is set.
static Type * smallestIntegerVectorType(Type *T1, Type *T2)
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Not an induction variable.
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
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."))
void takeName(Value *V)
Transfer the name from V to this value.
iterator find(const KeyT &Key)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
This class represents a truncation of integer types.
size_t size() const
size - Get the array size.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
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)
Class to represent pointers.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Pointer induction var. Step = C / sizeof(elem).
static bool canIfConvertPHINodes(BasicBlock *BB)
Check whether it is safe to if-convert this phi node.
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Function Alias Analysis false
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
This instruction inserts a single (scalar) element into a VectorType value.
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.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
A set of analyses that are preserved following a run of a transformation pass.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
LLVM Basic Block Representation.
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."))
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
Type * getType() const
Return the LLVM type of this SCEV expression.
Conditional or Unconditional Branch instruction.
Min/max implemented in terms of select(cmp()).
bool isVectorTy() const
True if this is an instance of VectorType.
Value handle that tracks a Value across RAUW.
static cl::opt< unsigned > PragmaVectorizeSCEVCheckThreshold("pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed with a ""vectorize(enable) pragma"))
This is an important base class in LLVM.
This analysis provides dependence information for the memory accesses of a loop.
const Value * getCondition() const
Instruction * getUnsafeAlgebraInst()
Returns induction operator that does not have "fast-math" property and requires FP unsafe mode...
int64_t getSExtValue() const
Get sign extended value.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Type * getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
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.
A manager for alias analyses.
ConstantFP - Floating Point Values [float, double].
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
const DILocation * cloneWithDuplicationFactor(unsigned DF) const
Returns a new DILocation with duplication factor DF encoded in the discriminator. ...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
static cl::opt< unsigned > PragmaVectorizeMemoryCheckThreshold("pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum allowed number of runtime memory checks with a ""vectorize(enable) pragma."))
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass providing a never-invalidated alias analysis result.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
Instruction::BinaryOps getInductionOpcode() const
Returns binary opcode of the induction operator.
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
const SCEV * replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, const ValueToValueMap &PtrToStride, Value *Ptr, Value *OrigPtr=nullptr)
Return the SCEV corresponding to a pointer with the symbolic stride replaced with constant one...
Interval::pred_iterator pred_end(Interval *I)
Value * getPointerOperand()
Optional< unsigned > getLoopEstimatedTripCount(Loop *L)
Get a loop's estimated trip count based on branch weight metadata.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
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."))
static CastInst * CreatePointerCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
const APInt & getAPInt() const
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVMContext & getContext() const
All values hold a context through their type.
static unsigned getIncomingValueNumForOperand(unsigned i)
RecurrenceKind getRecurrenceKind()
static unsigned getRecurrenceBinOp(RecurrenceKind Kind)
Returns the opcode of binary operation corresponding to the RecurrenceKind.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
Value * getStartValue() const
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
bool isConditional() const
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
static const SCEV * getAddressAccessSCEV(Value *Ptr, LoopVectorizationLegality *Legal, ScalarEvolution *SE, const Loop *TheLoop)
Gets Address Access SCEV after verifying that the access pattern is loop invariant except the inducti...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
StringRef getString() const
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
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.
const MDOperand & getOperand(unsigned I) const
A SetVector that performs no allocations if smaller than a certain size.
Analysis pass which computes BlockFrequencyInfo.
Iterator for intrusive lists based on ilist_node.
static bool mayDivideByZero(Instruction &I)
A helper function for checking whether an integer division-related instruction may divide by zero (in...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
A struct for saving information about induction variables.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
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...
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
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."))
Provides information about what library functions are available for the current target.
InductionKind getKind() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static Type * convertPointerToIntegerType(const DataLayout &DL, Type *Ty)
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
TerminatorInst * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
LLVM_NODISCARD T pop_back_val()
Drive the analysis of memory accesses in the loop.
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.
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
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)
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"))
reverse_iterator rbegin()
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
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)
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...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the intrinsic has a scalar operand.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
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.
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.
Class to represent vector types.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool isIntegerTy() const
True if this is an instance of IntegerType.
iterator_range< user_iterator > users()
static Value * createMinMaxOp(IRBuilder<> &Builder, MinMaxRecurrenceKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
unsigned getVectorNumElements() const
static const char lv_name[]
This class uses information about analyze scalars to rewrite expressions in canonical form...
bool isPredicated(MCInstrInfo const &MCII, MCInst const &MCI)
static const unsigned MaxInterleaveFactor
Maximum vectorization interleave count.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
loop Loop Strength Reduction
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
bool hasUnsafeAlgebra()
Returns true if the induction type is FP and the binary operator does not have the "fast-math" proper...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
Analysis pass that exposes the ScalarEvolution for a function.
Constant * createStrideMask(IRBuilder<> &Builder, unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
unsigned getComplexity() const override
We estimate the complexity of a union predicate as the size number of predicates in the union...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Analysis pass providing a never-invalidated alias analysis result.
static std::vector< std::string > Flags
static cl::opt< bool > EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, cl::desc("Enable if-conversion during vectorization."))
const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
const SCEVUnionPredicate & getUnionPredicate() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
This analysis provides dependence information for the memory accesses of a loop.
Value * getCondition() const
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...
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
bool isAggregateType() const
Return true if the type is an aggregate type.
static unsigned getVectorCallCost(CallInst *CI, unsigned VF, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, bool &NeedToScalarize)
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
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"))
Floating point induction variable.
Instruction * getLoopExitInstr()
bool isFunctionVectorizable(StringRef F, unsigned VF) const
Represents a single loop in the control flow graph.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
user_iterator_impl< User > user_iterator
APFloat abs(APFloat X)
Returns the absolute value of the argument.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
static cl::opt< unsigned, true > VectorizationFactor("force-vector-width", cl::Hidden, cl::desc("Sets the SIMD width. Zero is autoselect."), cl::location(VectorizerParams::VectorizationFactor))
iterator_range< value_op_iterator > operand_values()
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
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."))
void preserve()
Mark an analysis as preserved.
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."))
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Collection of parameters shared beetween the Loop Vectorizer and the Loop Access Analysis.
const SCEV * getStep() const
static OptimizationRemarkAnalysis createMissedAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop, Instruction *I=nullptr)
Create an analysis remark that explains why vectorization failed.
Analysis pass providing the TargetLibraryInfo.
iterator_range< op_iterator > arg_operands()
Iteration adapter for range-for loops.
StringRef getValueAsString() const
Return the attribute's value as a string.
Constant * createInterleaveMask(IRBuilder<> &Builder, unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static cl::opt< bool > LoopVectorizeWithBlockFrequency("loop-vectorize-with-block-frequency", cl::init(false), 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."))
SmallPtrSet< Instruction *, 8 > & getCastInsts()
Returns a reference to the instructions used for type-promoting the recurrence.
LLVMContext & getContext() const
Get the context in which this basic block lives.
A raw_ostream that writes to an std::string.
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
uint64_t PowerOf2Floor(uint64_t A)
Returns the power of two which is less than or equal to the given value.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
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.
static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, DominatorTree *DT)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, SmallPtrSetImpl< Value * > &AllowedExit)
Check that the instruction has outside loop users and is not an identified reduction variable...
The legacy pass manager's analysis pass to compute loop information.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
print Print MemDeps of function
static unsigned VectorizationInterleave
Interleave factor as overridden by the user.
Convenience struct for specifying and reasoning about fast-math flags.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Legacy analysis pass which computes a DominatorTree.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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)...
void setIncomingValue(unsigned i, Value *V)
static bool isInterleaveForced()
True if force-vector-interleave was specified by the user.
op_range incoming_values()
static Value * addFastMathFlag(Value *V)
Adds a 'fast' flag to floating point operations.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
const BasicBlock * getParent() const
static bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr)
Returns true if Phi is an induction in the loop L.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
static cl::opt< unsigned > VectorizeSCEVCheckThreshold("vectorize-scev-check-threshold", cl::init(16), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed."))
RecurrenceKind
This enum represents the kinds of recurrences that we support.
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.
Instruction * propagateMetadata(Instruction *I, ArrayRef< Value * > VL)
Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath, MD_nontemporal].
bool isVoidTy() const
Return true if this is 'void'.
This class represents a constant integer value.
Legacy wrapper pass to provide the BasicAAResult object.
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.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.