1f2ec16ccSHideki Saito //===- LoopVectorizationLegality.cpp --------------------------------------===//
2f2ec16ccSHideki Saito //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f2ec16ccSHideki Saito //
7f2ec16ccSHideki Saito //===----------------------------------------------------------------------===//
8f2ec16ccSHideki Saito //
9f2ec16ccSHideki Saito // This file provides loop vectorization legality analysis. Original code
10f2ec16ccSHideki Saito // resided in LoopVectorize.cpp for a long time.
11f2ec16ccSHideki Saito //
12f2ec16ccSHideki Saito // At this point, it is implemented as a utility class, not as an analysis
13f2ec16ccSHideki Saito // pass. It should be easy to create an analysis pass around it if there
14f2ec16ccSHideki Saito // is a need (but D45420 needs to happen first).
15f2ec16ccSHideki Saito //
16cc529285SSimon Pilgrim 
17f2ec16ccSHideki Saito #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
187403569bSPhilip Reames #include "llvm/Analysis/Loads.h"
19a5f1f9c9SSimon Pilgrim #include "llvm/Analysis/LoopInfo.h"
20cc529285SSimon Pilgrim #include "llvm/Analysis/TargetLibraryInfo.h"
217403569bSPhilip Reames #include "llvm/Analysis/ValueTracking.h"
22f2ec16ccSHideki Saito #include "llvm/Analysis/VectorUtils.h"
23f2ec16ccSHideki Saito #include "llvm/IR/IntrinsicInst.h"
2423c11380SFlorian Hahn #include "llvm/IR/PatternMatch.h"
257bedae7dSHiroshi Yamauchi #include "llvm/Transforms/Utils/SizeOpts.h"
2623c11380SFlorian Hahn #include "llvm/Transforms/Vectorize/LoopVectorize.h"
27f2ec16ccSHideki Saito 
28f2ec16ccSHideki Saito using namespace llvm;
2923c11380SFlorian Hahn using namespace PatternMatch;
30f2ec16ccSHideki Saito 
31f2ec16ccSHideki Saito #define LV_NAME "loop-vectorize"
32f2ec16ccSHideki Saito #define DEBUG_TYPE LV_NAME
33f2ec16ccSHideki Saito 
344e4ecae0SHideki Saito extern cl::opt<bool> EnableVPlanPredication;
354e4ecae0SHideki Saito 
36f2ec16ccSHideki Saito static cl::opt<bool>
37f2ec16ccSHideki Saito     EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
38f2ec16ccSHideki Saito                        cl::desc("Enable if-conversion during vectorization."));
39f2ec16ccSHideki Saito 
40c773d0f9SFlorian Hahn // TODO: Move size-based thresholds out of legality checking, make cost based
41c773d0f9SFlorian Hahn // decisions instead of hard thresholds.
42f2ec16ccSHideki Saito static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
43f2ec16ccSHideki Saito     "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
44f2ec16ccSHideki Saito     cl::desc("The maximum number of SCEV checks allowed."));
45f2ec16ccSHideki Saito 
46f2ec16ccSHideki Saito static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
47f2ec16ccSHideki Saito     "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
48f2ec16ccSHideki Saito     cl::desc("The maximum number of SCEV checks allowed with a "
49f2ec16ccSHideki Saito              "vectorize(enable) pragma"));
50f2ec16ccSHideki Saito 
51*4f86aa65SSander de Smalen // FIXME: When scalable vectorization is stable enough, change the default
52*4f86aa65SSander de Smalen // to SK_PreferFixedWidth.
53*4f86aa65SSander de Smalen static cl::opt<LoopVectorizeHints::ScalableForceKind> ScalableVectorization(
54*4f86aa65SSander de Smalen     "scalable-vectorization", cl::init(LoopVectorizeHints::SK_FixedWidthOnly),
55*4f86aa65SSander de Smalen     cl::Hidden,
56*4f86aa65SSander de Smalen     cl::desc("Control whether the compiler can use scalable vectors to "
57*4f86aa65SSander de Smalen              "vectorize a loop"),
58*4f86aa65SSander de Smalen     cl::values(
59*4f86aa65SSander de Smalen         clEnumValN(LoopVectorizeHints::SK_FixedWidthOnly, "off",
60*4f86aa65SSander de Smalen                    "Scalable vectorization is disabled."),
61*4f86aa65SSander de Smalen         clEnumValN(LoopVectorizeHints::SK_PreferFixedWidth, "on",
62*4f86aa65SSander de Smalen                    "Scalable vectorization is available, but favor fixed-width "
63*4f86aa65SSander de Smalen                    "vectorization when the cost is inconclusive."),
64*4f86aa65SSander de Smalen         clEnumValN(LoopVectorizeHints::SK_PreferScalable, "preferred",
65*4f86aa65SSander de Smalen                    "Scalable vectorization is available and favored when the "
66*4f86aa65SSander de Smalen                    "cost is inconclusive.")));
67*4f86aa65SSander de Smalen 
68f2ec16ccSHideki Saito /// Maximum vectorization interleave count.
69f2ec16ccSHideki Saito static const unsigned MaxInterleaveFactor = 16;
70f2ec16ccSHideki Saito 
71f2ec16ccSHideki Saito namespace llvm {
72f2ec16ccSHideki Saito 
73f2ec16ccSHideki Saito bool LoopVectorizeHints::Hint::validate(unsigned Val) {
74f2ec16ccSHideki Saito   switch (Kind) {
75f2ec16ccSHideki Saito   case HK_WIDTH:
76f2ec16ccSHideki Saito     return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
77ddb3b26aSBardia Mahjour   case HK_INTERLEAVE:
78f2ec16ccSHideki Saito     return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
79f2ec16ccSHideki Saito   case HK_FORCE:
80f2ec16ccSHideki Saito     return (Val <= 1);
81f2ec16ccSHideki Saito   case HK_ISVECTORIZED:
8220b198ecSSjoerd Meijer   case HK_PREDICATE:
8371bd59f0SDavid Sherwood   case HK_SCALABLE:
84f2ec16ccSHideki Saito     return (Val == 0 || Val == 1);
85f2ec16ccSHideki Saito   }
86f2ec16ccSHideki Saito   return false;
87f2ec16ccSHideki Saito }
88f2ec16ccSHideki Saito 
89d4eb13c8SMichael Kruse LoopVectorizeHints::LoopVectorizeHints(const Loop *L,
90d4eb13c8SMichael Kruse                                        bool InterleaveOnlyWhenForced,
91f2ec16ccSHideki Saito                                        OptimizationRemarkEmitter &ORE)
92f2ec16ccSHideki Saito     : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
93ddb3b26aSBardia Mahjour       Interleave("interleave.count", InterleaveOnlyWhenForced, HK_INTERLEAVE),
94f2ec16ccSHideki Saito       Force("vectorize.enable", FK_Undefined, HK_FORCE),
9520b198ecSSjoerd Meijer       IsVectorized("isvectorized", 0, HK_ISVECTORIZED),
9671bd59f0SDavid Sherwood       Predicate("vectorize.predicate.enable", FK_Undefined, HK_PREDICATE),
97*4f86aa65SSander de Smalen       Scalable("vectorize.scalable.enable", SK_Unspecified, HK_SCALABLE),
98*4f86aa65SSander de Smalen       TheLoop(L), ORE(ORE) {
99f2ec16ccSHideki Saito   // Populate values with existing loop metadata.
100f2ec16ccSHideki Saito   getHintsFromMetadata();
101f2ec16ccSHideki Saito 
102f2ec16ccSHideki Saito   // force-vector-interleave overrides DisableInterleaving.
103f2ec16ccSHideki Saito   if (VectorizerParams::isInterleaveForced())
104f2ec16ccSHideki Saito     Interleave.Value = VectorizerParams::VectorizationInterleave;
105f2ec16ccSHideki Saito 
106*4f86aa65SSander de Smalen   if ((LoopVectorizeHints::ScalableForceKind)Scalable.Value == SK_Unspecified)
107*4f86aa65SSander de Smalen     // If the width is set, but the metadata says nothing about the scalable
108*4f86aa65SSander de Smalen     // property, then assume it concerns only a fixed-width UserVF.
109*4f86aa65SSander de Smalen     // If width is not set, the flag takes precedence.
110*4f86aa65SSander de Smalen     Scalable.Value = Width.Value ? SK_FixedWidthOnly : ScalableVectorization;
111*4f86aa65SSander de Smalen   else if (ScalableVectorization == SK_FixedWidthOnly)
112*4f86aa65SSander de Smalen     // If the flag is set to disable any use of scalable vectors, override the
113*4f86aa65SSander de Smalen     // loop hint.
114*4f86aa65SSander de Smalen     Scalable.Value = SK_FixedWidthOnly;
115*4f86aa65SSander de Smalen 
116f2ec16ccSHideki Saito   if (IsVectorized.Value != 1)
117f2ec16ccSHideki Saito     // If the vectorization width and interleaving count are both 1 then
118f2ec16ccSHideki Saito     // consider the loop to have been already vectorized because there's
119f2ec16ccSHideki Saito     // nothing more that we can do.
12071bd59f0SDavid Sherwood     IsVectorized.Value =
121ddb3b26aSBardia Mahjour         getWidth() == ElementCount::getFixed(1) && getInterleave() == 1;
122ddb3b26aSBardia Mahjour   LLVM_DEBUG(if (InterleaveOnlyWhenForced && getInterleave() == 1) dbgs()
123f2ec16ccSHideki Saito              << "LV: Interleaving disabled by the pass manager\n");
124f2ec16ccSHideki Saito }
125f2ec16ccSHideki Saito 
12677a614a6SMichael Kruse void LoopVectorizeHints::setAlreadyVectorized() {
12777a614a6SMichael Kruse   LLVMContext &Context = TheLoop->getHeader()->getContext();
12877a614a6SMichael Kruse 
12977a614a6SMichael Kruse   MDNode *IsVectorizedMD = MDNode::get(
13077a614a6SMichael Kruse       Context,
13177a614a6SMichael Kruse       {MDString::get(Context, "llvm.loop.isvectorized"),
13277a614a6SMichael Kruse        ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))});
13377a614a6SMichael Kruse   MDNode *LoopID = TheLoop->getLoopID();
13477a614a6SMichael Kruse   MDNode *NewLoopID =
13577a614a6SMichael Kruse       makePostTransformationMetadata(Context, LoopID,
13677a614a6SMichael Kruse                                      {Twine(Prefix(), "vectorize.").str(),
13777a614a6SMichael Kruse                                       Twine(Prefix(), "interleave.").str()},
13877a614a6SMichael Kruse                                      {IsVectorizedMD});
13977a614a6SMichael Kruse   TheLoop->setLoopID(NewLoopID);
14077a614a6SMichael Kruse 
14177a614a6SMichael Kruse   // Update internal cache.
14277a614a6SMichael Kruse   IsVectorized.Value = 1;
14377a614a6SMichael Kruse }
14477a614a6SMichael Kruse 
145d4eb13c8SMichael Kruse bool LoopVectorizeHints::allowVectorization(
146d4eb13c8SMichael Kruse     Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
147f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Disabled) {
148d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
149f2ec16ccSHideki Saito     emitRemarkWithHints();
150f2ec16ccSHideki Saito     return false;
151f2ec16ccSHideki Saito   }
152f2ec16ccSHideki Saito 
153d4eb13c8SMichael Kruse   if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
154d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
155f2ec16ccSHideki Saito     emitRemarkWithHints();
156f2ec16ccSHideki Saito     return false;
157f2ec16ccSHideki Saito   }
158f2ec16ccSHideki Saito 
159f2ec16ccSHideki Saito   if (getIsVectorized() == 1) {
160d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
161f2ec16ccSHideki Saito     // FIXME: Add interleave.disable metadata. This will allow
162f2ec16ccSHideki Saito     // vectorize.disable to be used without disabling the pass and errors
163f2ec16ccSHideki Saito     // to differentiate between disabled vectorization and a width of 1.
164f2ec16ccSHideki Saito     ORE.emit([&]() {
165f2ec16ccSHideki Saito       return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
166f2ec16ccSHideki Saito                                         "AllDisabled", L->getStartLoc(),
167f2ec16ccSHideki Saito                                         L->getHeader())
168f2ec16ccSHideki Saito              << "loop not vectorized: vectorization and interleaving are "
169f2ec16ccSHideki Saito                 "explicitly disabled, or the loop has already been "
170f2ec16ccSHideki Saito                 "vectorized";
171f2ec16ccSHideki Saito     });
172f2ec16ccSHideki Saito     return false;
173f2ec16ccSHideki Saito   }
174f2ec16ccSHideki Saito 
175f2ec16ccSHideki Saito   return true;
176f2ec16ccSHideki Saito }
177f2ec16ccSHideki Saito 
178f2ec16ccSHideki Saito void LoopVectorizeHints::emitRemarkWithHints() const {
179f2ec16ccSHideki Saito   using namespace ore;
180f2ec16ccSHideki Saito 
181f2ec16ccSHideki Saito   ORE.emit([&]() {
182f2ec16ccSHideki Saito     if (Force.Value == LoopVectorizeHints::FK_Disabled)
183f2ec16ccSHideki Saito       return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
184f2ec16ccSHideki Saito                                       TheLoop->getStartLoc(),
185f2ec16ccSHideki Saito                                       TheLoop->getHeader())
186f2ec16ccSHideki Saito              << "loop not vectorized: vectorization is explicitly disabled";
187f2ec16ccSHideki Saito     else {
188f2ec16ccSHideki Saito       OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
189f2ec16ccSHideki Saito                                  TheLoop->getStartLoc(), TheLoop->getHeader());
190f2ec16ccSHideki Saito       R << "loop not vectorized";
191f2ec16ccSHideki Saito       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
192f2ec16ccSHideki Saito         R << " (Force=" << NV("Force", true);
193f2ec16ccSHideki Saito         if (Width.Value != 0)
19471bd59f0SDavid Sherwood           R << ", Vector Width=" << NV("VectorWidth", getWidth());
195ddb3b26aSBardia Mahjour         if (getInterleave() != 0)
196ddb3b26aSBardia Mahjour           R << ", Interleave Count=" << NV("InterleaveCount", getInterleave());
197f2ec16ccSHideki Saito         R << ")";
198f2ec16ccSHideki Saito       }
199f2ec16ccSHideki Saito       return R;
200f2ec16ccSHideki Saito     }
201f2ec16ccSHideki Saito   });
202f2ec16ccSHideki Saito }
203f2ec16ccSHideki Saito 
204f2ec16ccSHideki Saito const char *LoopVectorizeHints::vectorizeAnalysisPassName() const {
20571bd59f0SDavid Sherwood   if (getWidth() == ElementCount::getFixed(1))
206f2ec16ccSHideki Saito     return LV_NAME;
207f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Disabled)
208f2ec16ccSHideki Saito     return LV_NAME;
20971bd59f0SDavid Sherwood   if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth().isZero())
210f2ec16ccSHideki Saito     return LV_NAME;
211f2ec16ccSHideki Saito   return OptimizationRemarkAnalysis::AlwaysPrint;
212f2ec16ccSHideki Saito }
213f2ec16ccSHideki Saito 
214f2ec16ccSHideki Saito void LoopVectorizeHints::getHintsFromMetadata() {
215f2ec16ccSHideki Saito   MDNode *LoopID = TheLoop->getLoopID();
216f2ec16ccSHideki Saito   if (!LoopID)
217f2ec16ccSHideki Saito     return;
218f2ec16ccSHideki Saito 
219f2ec16ccSHideki Saito   // First operand should refer to the loop id itself.
220f2ec16ccSHideki Saito   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
221f2ec16ccSHideki Saito   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
222f2ec16ccSHideki Saito 
223f2ec16ccSHideki Saito   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
224f2ec16ccSHideki Saito     const MDString *S = nullptr;
225f2ec16ccSHideki Saito     SmallVector<Metadata *, 4> Args;
226f2ec16ccSHideki Saito 
227f2ec16ccSHideki Saito     // The expected hint is either a MDString or a MDNode with the first
228f2ec16ccSHideki Saito     // operand a MDString.
229f2ec16ccSHideki Saito     if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
230f2ec16ccSHideki Saito       if (!MD || MD->getNumOperands() == 0)
231f2ec16ccSHideki Saito         continue;
232f2ec16ccSHideki Saito       S = dyn_cast<MDString>(MD->getOperand(0));
233f2ec16ccSHideki Saito       for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
234f2ec16ccSHideki Saito         Args.push_back(MD->getOperand(i));
235f2ec16ccSHideki Saito     } else {
236f2ec16ccSHideki Saito       S = dyn_cast<MDString>(LoopID->getOperand(i));
237f2ec16ccSHideki Saito       assert(Args.size() == 0 && "too many arguments for MDString");
238f2ec16ccSHideki Saito     }
239f2ec16ccSHideki Saito 
240f2ec16ccSHideki Saito     if (!S)
241f2ec16ccSHideki Saito       continue;
242f2ec16ccSHideki Saito 
243f2ec16ccSHideki Saito     // Check if the hint starts with the loop metadata prefix.
244f2ec16ccSHideki Saito     StringRef Name = S->getString();
245f2ec16ccSHideki Saito     if (Args.size() == 1)
246f2ec16ccSHideki Saito       setHint(Name, Args[0]);
247f2ec16ccSHideki Saito   }
248f2ec16ccSHideki Saito }
249f2ec16ccSHideki Saito 
250f2ec16ccSHideki Saito void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
251f2ec16ccSHideki Saito   if (!Name.startswith(Prefix()))
252f2ec16ccSHideki Saito     return;
253f2ec16ccSHideki Saito   Name = Name.substr(Prefix().size(), StringRef::npos);
254f2ec16ccSHideki Saito 
255f2ec16ccSHideki Saito   const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
256f2ec16ccSHideki Saito   if (!C)
257f2ec16ccSHideki Saito     return;
258f2ec16ccSHideki Saito   unsigned Val = C->getZExtValue();
259f2ec16ccSHideki Saito 
26071bd59f0SDavid Sherwood   Hint *Hints[] = {&Width,        &Interleave, &Force,
26171bd59f0SDavid Sherwood                    &IsVectorized, &Predicate,  &Scalable};
262f2ec16ccSHideki Saito   for (auto H : Hints) {
263f2ec16ccSHideki Saito     if (Name == H->Name) {
264f2ec16ccSHideki Saito       if (H->validate(Val))
265f2ec16ccSHideki Saito         H->Value = Val;
266f2ec16ccSHideki Saito       else
267d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
268f2ec16ccSHideki Saito       break;
269f2ec16ccSHideki Saito     }
270f2ec16ccSHideki Saito   }
271f2ec16ccSHideki Saito }
272f2ec16ccSHideki Saito 
273f2ec16ccSHideki Saito // Return true if the inner loop \p Lp is uniform with regard to the outer loop
274f2ec16ccSHideki Saito // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
275f2ec16ccSHideki Saito // executing the inner loop will execute the same iterations). This check is
276f2ec16ccSHideki Saito // very constrained for now but it will be relaxed in the future. \p Lp is
277f2ec16ccSHideki Saito // considered uniform if it meets all the following conditions:
278f2ec16ccSHideki Saito //   1) it has a canonical IV (starting from 0 and with stride 1),
279f2ec16ccSHideki Saito //   2) its latch terminator is a conditional branch and,
280f2ec16ccSHideki Saito //   3) its latch condition is a compare instruction whose operands are the
281f2ec16ccSHideki Saito //      canonical IV and an OuterLp invariant.
282f2ec16ccSHideki Saito // This check doesn't take into account the uniformity of other conditions not
283f2ec16ccSHideki Saito // related to the loop latch because they don't affect the loop uniformity.
284f2ec16ccSHideki Saito //
285f2ec16ccSHideki Saito // NOTE: We decided to keep all these checks and its associated documentation
286f2ec16ccSHideki Saito // together so that we can easily have a picture of the current supported loop
287f2ec16ccSHideki Saito // nests. However, some of the current checks don't depend on \p OuterLp and
288f2ec16ccSHideki Saito // would be redundantly executed for each \p Lp if we invoked this function for
289f2ec16ccSHideki Saito // different candidate outer loops. This is not the case for now because we
290f2ec16ccSHideki Saito // don't currently have the infrastructure to evaluate multiple candidate outer
291f2ec16ccSHideki Saito // loops and \p OuterLp will be a fixed parameter while we only support explicit
292f2ec16ccSHideki Saito // outer loop vectorization. It's also very likely that these checks go away
293f2ec16ccSHideki Saito // before introducing the aforementioned infrastructure. However, if this is not
294f2ec16ccSHideki Saito // the case, we should move the \p OuterLp independent checks to a separate
295f2ec16ccSHideki Saito // function that is only executed once for each \p Lp.
296f2ec16ccSHideki Saito static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
297f2ec16ccSHideki Saito   assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
298f2ec16ccSHideki Saito 
299f2ec16ccSHideki Saito   // If Lp is the outer loop, it's uniform by definition.
300f2ec16ccSHideki Saito   if (Lp == OuterLp)
301f2ec16ccSHideki Saito     return true;
302f2ec16ccSHideki Saito   assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
303f2ec16ccSHideki Saito 
304f2ec16ccSHideki Saito   // 1.
305f2ec16ccSHideki Saito   PHINode *IV = Lp->getCanonicalInductionVariable();
306f2ec16ccSHideki Saito   if (!IV) {
307d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
308f2ec16ccSHideki Saito     return false;
309f2ec16ccSHideki Saito   }
310f2ec16ccSHideki Saito 
311f2ec16ccSHideki Saito   // 2.
312f2ec16ccSHideki Saito   BasicBlock *Latch = Lp->getLoopLatch();
313f2ec16ccSHideki Saito   auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
314f2ec16ccSHideki Saito   if (!LatchBr || LatchBr->isUnconditional()) {
315d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
316f2ec16ccSHideki Saito     return false;
317f2ec16ccSHideki Saito   }
318f2ec16ccSHideki Saito 
319f2ec16ccSHideki Saito   // 3.
320f2ec16ccSHideki Saito   auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
321f2ec16ccSHideki Saito   if (!LatchCmp) {
322d34e60caSNicola Zaghen     LLVM_DEBUG(
323d34e60caSNicola Zaghen         dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
324f2ec16ccSHideki Saito     return false;
325f2ec16ccSHideki Saito   }
326f2ec16ccSHideki Saito 
327f2ec16ccSHideki Saito   Value *CondOp0 = LatchCmp->getOperand(0);
328f2ec16ccSHideki Saito   Value *CondOp1 = LatchCmp->getOperand(1);
329f2ec16ccSHideki Saito   Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
330f2ec16ccSHideki Saito   if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
331f2ec16ccSHideki Saito       !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
332d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
333f2ec16ccSHideki Saito     return false;
334f2ec16ccSHideki Saito   }
335f2ec16ccSHideki Saito 
336f2ec16ccSHideki Saito   return true;
337f2ec16ccSHideki Saito }
338f2ec16ccSHideki Saito 
339f2ec16ccSHideki Saito // Return true if \p Lp and all its nested loops are uniform with regard to \p
340f2ec16ccSHideki Saito // OuterLp.
341f2ec16ccSHideki Saito static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
342f2ec16ccSHideki Saito   if (!isUniformLoop(Lp, OuterLp))
343f2ec16ccSHideki Saito     return false;
344f2ec16ccSHideki Saito 
345f2ec16ccSHideki Saito   // Check if nested loops are uniform.
346f2ec16ccSHideki Saito   for (Loop *SubLp : *Lp)
347f2ec16ccSHideki Saito     if (!isUniformLoopNest(SubLp, OuterLp))
348f2ec16ccSHideki Saito       return false;
349f2ec16ccSHideki Saito 
350f2ec16ccSHideki Saito   return true;
351f2ec16ccSHideki Saito }
352f2ec16ccSHideki Saito 
3535f8f34e4SAdrian Prantl /// Check whether it is safe to if-convert this phi node.
354f2ec16ccSHideki Saito ///
355f2ec16ccSHideki Saito /// Phi nodes with constant expressions that can trap are not safe to if
356f2ec16ccSHideki Saito /// convert.
357f2ec16ccSHideki Saito static bool canIfConvertPHINodes(BasicBlock *BB) {
358f2ec16ccSHideki Saito   for (PHINode &Phi : BB->phis()) {
359f2ec16ccSHideki Saito     for (Value *V : Phi.incoming_values())
360f2ec16ccSHideki Saito       if (auto *C = dyn_cast<Constant>(V))
361f2ec16ccSHideki Saito         if (C->canTrap())
362f2ec16ccSHideki Saito           return false;
363f2ec16ccSHideki Saito   }
364f2ec16ccSHideki Saito   return true;
365f2ec16ccSHideki Saito }
366f2ec16ccSHideki Saito 
367f2ec16ccSHideki Saito static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
368f2ec16ccSHideki Saito   if (Ty->isPointerTy())
369f2ec16ccSHideki Saito     return DL.getIntPtrType(Ty);
370f2ec16ccSHideki Saito 
371f2ec16ccSHideki Saito   // It is possible that char's or short's overflow when we ask for the loop's
372f2ec16ccSHideki Saito   // trip count, work around this by changing the type size.
373f2ec16ccSHideki Saito   if (Ty->getScalarSizeInBits() < 32)
374f2ec16ccSHideki Saito     return Type::getInt32Ty(Ty->getContext());
375f2ec16ccSHideki Saito 
376f2ec16ccSHideki Saito   return Ty;
377f2ec16ccSHideki Saito }
378f2ec16ccSHideki Saito 
379f2ec16ccSHideki Saito static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
380f2ec16ccSHideki Saito   Ty0 = convertPointerToIntegerType(DL, Ty0);
381f2ec16ccSHideki Saito   Ty1 = convertPointerToIntegerType(DL, Ty1);
382f2ec16ccSHideki Saito   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
383f2ec16ccSHideki Saito     return Ty0;
384f2ec16ccSHideki Saito   return Ty1;
385f2ec16ccSHideki Saito }
386f2ec16ccSHideki Saito 
3875f8f34e4SAdrian Prantl /// Check that the instruction has outside loop users and is not an
388f2ec16ccSHideki Saito /// identified reduction variable.
389f2ec16ccSHideki Saito static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
390f2ec16ccSHideki Saito                                SmallPtrSetImpl<Value *> &AllowedExit) {
39160a1e4ddSAnna Thomas   // Reductions, Inductions and non-header phis are allowed to have exit users. All
392f2ec16ccSHideki Saito   // other instructions must not have external users.
393f2ec16ccSHideki Saito   if (!AllowedExit.count(Inst))
394f2ec16ccSHideki Saito     // Check that all of the users of the loop are inside the BB.
395f2ec16ccSHideki Saito     for (User *U : Inst->users()) {
396f2ec16ccSHideki Saito       Instruction *UI = cast<Instruction>(U);
397f2ec16ccSHideki Saito       // This user may be a reduction exit value.
398f2ec16ccSHideki Saito       if (!TheLoop->contains(UI)) {
399d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
400f2ec16ccSHideki Saito         return true;
401f2ec16ccSHideki Saito       }
402f2ec16ccSHideki Saito     }
403f2ec16ccSHideki Saito   return false;
404f2ec16ccSHideki Saito }
405f2ec16ccSHideki Saito 
406f82966d1SSander de Smalen int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) const {
407f2ec16ccSHideki Saito   const ValueToValueMap &Strides =
408f2ec16ccSHideki Saito       getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
409f2ec16ccSHideki Saito 
4107bedae7dSHiroshi Yamauchi   Function *F = TheLoop->getHeader()->getParent();
4117bedae7dSHiroshi Yamauchi   bool OptForSize = F->hasOptSize() ||
4127bedae7dSHiroshi Yamauchi                     llvm::shouldOptimizeForSize(TheLoop->getHeader(), PSI, BFI,
4137bedae7dSHiroshi Yamauchi                                                 PGSOQueryType::IRPass);
4147bedae7dSHiroshi Yamauchi   bool CanAddPredicate = !OptForSize;
415d1170dbeSSjoerd Meijer   int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, CanAddPredicate, false);
416f2ec16ccSHideki Saito   if (Stride == 1 || Stride == -1)
417f2ec16ccSHideki Saito     return Stride;
418f2ec16ccSHideki Saito   return 0;
419f2ec16ccSHideki Saito }
420f2ec16ccSHideki Saito 
421f2ec16ccSHideki Saito bool LoopVectorizationLegality::isUniform(Value *V) {
422f2ec16ccSHideki Saito   return LAI->isUniform(V);
423f2ec16ccSHideki Saito }
424f2ec16ccSHideki Saito 
425f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeOuterLoop() {
42689c1e35fSStefanos Baziotis   assert(!TheLoop->isInnermost() && "We are not vectorizing an outer loop.");
427f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
428f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
429f2ec16ccSHideki Saito   bool Result = true;
430f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
431f2ec16ccSHideki Saito 
432f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
433f2ec16ccSHideki Saito     // Check whether the BB terminator is a BranchInst. Any other terminator is
434f2ec16ccSHideki Saito     // not supported yet.
435f2ec16ccSHideki Saito     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
436f2ec16ccSHideki Saito     if (!Br) {
4379e97caf5SRenato Golin       reportVectorizationFailure("Unsupported basic block terminator",
4389e97caf5SRenato Golin           "loop control flow is not understood by vectorizer",
439ec818d7fSHideki Saito           "CFGNotUnderstood", ORE, TheLoop);
440f2ec16ccSHideki Saito       if (DoExtraAnalysis)
441f2ec16ccSHideki Saito         Result = false;
442f2ec16ccSHideki Saito       else
443f2ec16ccSHideki Saito         return false;
444f2ec16ccSHideki Saito     }
445f2ec16ccSHideki Saito 
446f2ec16ccSHideki Saito     // Check whether the BranchInst is a supported one. Only unconditional
447f2ec16ccSHideki Saito     // branches, conditional branches with an outer loop invariant condition or
448f2ec16ccSHideki Saito     // backedges are supported.
4494e4ecae0SHideki Saito     // FIXME: We skip these checks when VPlan predication is enabled as we
4504e4ecae0SHideki Saito     // want to allow divergent branches. This whole check will be removed
4514e4ecae0SHideki Saito     // once VPlan predication is on by default.
4524e4ecae0SHideki Saito     if (!EnableVPlanPredication && Br && Br->isConditional() &&
453f2ec16ccSHideki Saito         !TheLoop->isLoopInvariant(Br->getCondition()) &&
454f2ec16ccSHideki Saito         !LI->isLoopHeader(Br->getSuccessor(0)) &&
455f2ec16ccSHideki Saito         !LI->isLoopHeader(Br->getSuccessor(1))) {
4569e97caf5SRenato Golin       reportVectorizationFailure("Unsupported conditional branch",
4579e97caf5SRenato Golin           "loop control flow is not understood by vectorizer",
458ec818d7fSHideki Saito           "CFGNotUnderstood", ORE, TheLoop);
459f2ec16ccSHideki Saito       if (DoExtraAnalysis)
460f2ec16ccSHideki Saito         Result = false;
461f2ec16ccSHideki Saito       else
462f2ec16ccSHideki Saito         return false;
463f2ec16ccSHideki Saito     }
464f2ec16ccSHideki Saito   }
465f2ec16ccSHideki Saito 
466f2ec16ccSHideki Saito   // Check whether inner loops are uniform. At this point, we only support
467f2ec16ccSHideki Saito   // simple outer loops scenarios with uniform nested loops.
468f2ec16ccSHideki Saito   if (!isUniformLoopNest(TheLoop /*loop nest*/,
469f2ec16ccSHideki Saito                          TheLoop /*context outer loop*/)) {
4709e97caf5SRenato Golin     reportVectorizationFailure("Outer loop contains divergent loops",
4719e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
472ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
473f2ec16ccSHideki Saito     if (DoExtraAnalysis)
474f2ec16ccSHideki Saito       Result = false;
475f2ec16ccSHideki Saito     else
476f2ec16ccSHideki Saito       return false;
477f2ec16ccSHideki Saito   }
478f2ec16ccSHideki Saito 
479ea7f3035SHideki Saito   // Check whether we are able to set up outer loop induction.
480ea7f3035SHideki Saito   if (!setupOuterLoopInductions()) {
4819e97caf5SRenato Golin     reportVectorizationFailure("Unsupported outer loop Phi(s)",
4829e97caf5SRenato Golin                                "Unsupported outer loop Phi(s)",
483ec818d7fSHideki Saito                                "UnsupportedPhi", ORE, TheLoop);
484ea7f3035SHideki Saito     if (DoExtraAnalysis)
485ea7f3035SHideki Saito       Result = false;
486ea7f3035SHideki Saito     else
487ea7f3035SHideki Saito       return false;
488ea7f3035SHideki Saito   }
489ea7f3035SHideki Saito 
490f2ec16ccSHideki Saito   return Result;
491f2ec16ccSHideki Saito }
492f2ec16ccSHideki Saito 
493f2ec16ccSHideki Saito void LoopVectorizationLegality::addInductionPhi(
494f2ec16ccSHideki Saito     PHINode *Phi, const InductionDescriptor &ID,
495f2ec16ccSHideki Saito     SmallPtrSetImpl<Value *> &AllowedExit) {
496f2ec16ccSHideki Saito   Inductions[Phi] = ID;
497f2ec16ccSHideki Saito 
498f2ec16ccSHideki Saito   // In case this induction also comes with casts that we know we can ignore
499f2ec16ccSHideki Saito   // in the vectorized loop body, record them here. All casts could be recorded
500f2ec16ccSHideki Saito   // here for ignoring, but suffices to record only the first (as it is the
501f2ec16ccSHideki Saito   // only one that may bw used outside the cast sequence).
502f2ec16ccSHideki Saito   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
503f2ec16ccSHideki Saito   if (!Casts.empty())
504f2ec16ccSHideki Saito     InductionCastsToIgnore.insert(*Casts.begin());
505f2ec16ccSHideki Saito 
506f2ec16ccSHideki Saito   Type *PhiTy = Phi->getType();
507f2ec16ccSHideki Saito   const DataLayout &DL = Phi->getModule()->getDataLayout();
508f2ec16ccSHideki Saito 
509f2ec16ccSHideki Saito   // Get the widest type.
510f2ec16ccSHideki Saito   if (!PhiTy->isFloatingPointTy()) {
511f2ec16ccSHideki Saito     if (!WidestIndTy)
512f2ec16ccSHideki Saito       WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
513f2ec16ccSHideki Saito     else
514f2ec16ccSHideki Saito       WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
515f2ec16ccSHideki Saito   }
516f2ec16ccSHideki Saito 
517f2ec16ccSHideki Saito   // Int inductions are special because we only allow one IV.
518f2ec16ccSHideki Saito   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
519f2ec16ccSHideki Saito       ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
520f2ec16ccSHideki Saito       isa<Constant>(ID.getStartValue()) &&
521f2ec16ccSHideki Saito       cast<Constant>(ID.getStartValue())->isNullValue()) {
522f2ec16ccSHideki Saito 
523f2ec16ccSHideki Saito     // Use the phi node with the widest type as induction. Use the last
524f2ec16ccSHideki Saito     // one if there are multiple (no good reason for doing this other
525f2ec16ccSHideki Saito     // than it is expedient). We've checked that it begins at zero and
526f2ec16ccSHideki Saito     // steps by one, so this is a canonical induction variable.
527f2ec16ccSHideki Saito     if (!PrimaryInduction || PhiTy == WidestIndTy)
528f2ec16ccSHideki Saito       PrimaryInduction = Phi;
529f2ec16ccSHideki Saito   }
530f2ec16ccSHideki Saito 
531f2ec16ccSHideki Saito   // Both the PHI node itself, and the "post-increment" value feeding
532f2ec16ccSHideki Saito   // back into the PHI node may have external users.
533f2ec16ccSHideki Saito   // We can allow those uses, except if the SCEVs we have for them rely
534f2ec16ccSHideki Saito   // on predicates that only hold within the loop, since allowing the exit
5356a1dd77fSAnna Thomas   // currently means re-using this SCEV outside the loop (see PR33706 for more
5366a1dd77fSAnna Thomas   // details).
537f2ec16ccSHideki Saito   if (PSE.getUnionPredicate().isAlwaysTrue()) {
538f2ec16ccSHideki Saito     AllowedExit.insert(Phi);
539f2ec16ccSHideki Saito     AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
540f2ec16ccSHideki Saito   }
541f2ec16ccSHideki Saito 
542d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
543f2ec16ccSHideki Saito }
544f2ec16ccSHideki Saito 
545ea7f3035SHideki Saito bool LoopVectorizationLegality::setupOuterLoopInductions() {
546ea7f3035SHideki Saito   BasicBlock *Header = TheLoop->getHeader();
547ea7f3035SHideki Saito 
548ea7f3035SHideki Saito   // Returns true if a given Phi is a supported induction.
549ea7f3035SHideki Saito   auto isSupportedPhi = [&](PHINode &Phi) -> bool {
550ea7f3035SHideki Saito     InductionDescriptor ID;
551ea7f3035SHideki Saito     if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
552ea7f3035SHideki Saito         ID.getKind() == InductionDescriptor::IK_IntInduction) {
553ea7f3035SHideki Saito       addInductionPhi(&Phi, ID, AllowedExit);
554ea7f3035SHideki Saito       return true;
555ea7f3035SHideki Saito     } else {
556ea7f3035SHideki Saito       // Bail out for any Phi in the outer loop header that is not a supported
557ea7f3035SHideki Saito       // induction.
558ea7f3035SHideki Saito       LLVM_DEBUG(
559ea7f3035SHideki Saito           dbgs()
560ea7f3035SHideki Saito           << "LV: Found unsupported PHI for outer loop vectorization.\n");
561ea7f3035SHideki Saito       return false;
562ea7f3035SHideki Saito     }
563ea7f3035SHideki Saito   };
564ea7f3035SHideki Saito 
565ea7f3035SHideki Saito   if (llvm::all_of(Header->phis(), isSupportedPhi))
566ea7f3035SHideki Saito     return true;
567ea7f3035SHideki Saito   else
568ea7f3035SHideki Saito     return false;
569ea7f3035SHideki Saito }
570ea7f3035SHideki Saito 
57166c120f0SFrancesco Petrogalli /// Checks if a function is scalarizable according to the TLI, in
57266c120f0SFrancesco Petrogalli /// the sense that it should be vectorized and then expanded in
57366c120f0SFrancesco Petrogalli /// multiple scalarcalls. This is represented in the
57466c120f0SFrancesco Petrogalli /// TLI via mappings that do not specify a vector name, as in the
57566c120f0SFrancesco Petrogalli /// following example:
57666c120f0SFrancesco Petrogalli ///
57766c120f0SFrancesco Petrogalli ///    const VecDesc VecIntrinsics[] = {
57866c120f0SFrancesco Petrogalli ///      {"llvm.phx.abs.i32", "", 4}
57966c120f0SFrancesco Petrogalli ///    };
58066c120f0SFrancesco Petrogalli static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI) {
58166c120f0SFrancesco Petrogalli   const StringRef ScalarName = CI.getCalledFunction()->getName();
58266c120f0SFrancesco Petrogalli   bool Scalarize = TLI.isFunctionVectorizable(ScalarName);
58366c120f0SFrancesco Petrogalli   // Check that all known VFs are not associated to a vector
58466c120f0SFrancesco Petrogalli   // function, i.e. the vector name is emty.
58501b87444SDavid Sherwood   if (Scalarize) {
58601b87444SDavid Sherwood     ElementCount WidestFixedVF, WidestScalableVF;
58701b87444SDavid Sherwood     TLI.getWidestVF(ScalarName, WidestFixedVF, WidestScalableVF);
58801b87444SDavid Sherwood     for (ElementCount VF = ElementCount::getFixed(2);
58901b87444SDavid Sherwood          ElementCount::isKnownLE(VF, WidestFixedVF); VF *= 2)
59066c120f0SFrancesco Petrogalli       Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
59101b87444SDavid Sherwood     for (ElementCount VF = ElementCount::getScalable(1);
59201b87444SDavid Sherwood          ElementCount::isKnownLE(VF, WidestScalableVF); VF *= 2)
59301b87444SDavid Sherwood       Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
59401b87444SDavid Sherwood     assert((WidestScalableVF.isZero() || !Scalarize) &&
59501b87444SDavid Sherwood            "Caller may decide to scalarize a variant using a scalable VF");
59666c120f0SFrancesco Petrogalli   }
59766c120f0SFrancesco Petrogalli   return Scalarize;
59866c120f0SFrancesco Petrogalli }
59966c120f0SFrancesco Petrogalli 
600f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeInstrs() {
601f2ec16ccSHideki Saito   BasicBlock *Header = TheLoop->getHeader();
602f2ec16ccSHideki Saito 
603f2ec16ccSHideki Saito   // For each block in the loop.
604f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
605f2ec16ccSHideki Saito     // Scan the instructions in the block and look for hazards.
606f2ec16ccSHideki Saito     for (Instruction &I : *BB) {
607f2ec16ccSHideki Saito       if (auto *Phi = dyn_cast<PHINode>(&I)) {
608f2ec16ccSHideki Saito         Type *PhiTy = Phi->getType();
609f2ec16ccSHideki Saito         // Check that this PHI type is allowed.
610f2ec16ccSHideki Saito         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
611f2ec16ccSHideki Saito             !PhiTy->isPointerTy()) {
6129e97caf5SRenato Golin           reportVectorizationFailure("Found a non-int non-pointer PHI",
6139e97caf5SRenato Golin                                      "loop control flow is not understood by vectorizer",
614ec818d7fSHideki Saito                                      "CFGNotUnderstood", ORE, TheLoop);
615f2ec16ccSHideki Saito           return false;
616f2ec16ccSHideki Saito         }
617f2ec16ccSHideki Saito 
618f2ec16ccSHideki Saito         // If this PHINode is not in the header block, then we know that we
619f2ec16ccSHideki Saito         // can convert it to select during if-conversion. No need to check if
620f2ec16ccSHideki Saito         // the PHIs in this block are induction or reduction variables.
621f2ec16ccSHideki Saito         if (BB != Header) {
62260a1e4ddSAnna Thomas           // Non-header phi nodes that have outside uses can be vectorized. Add
62360a1e4ddSAnna Thomas           // them to the list of allowed exits.
62460a1e4ddSAnna Thomas           // Unsafe cyclic dependencies with header phis are identified during
62560a1e4ddSAnna Thomas           // legalization for reduction, induction and first order
62660a1e4ddSAnna Thomas           // recurrences.
627dd18ce45SBjorn Pettersson           AllowedExit.insert(&I);
628f2ec16ccSHideki Saito           continue;
629f2ec16ccSHideki Saito         }
630f2ec16ccSHideki Saito 
631f2ec16ccSHideki Saito         // We only allow if-converted PHIs with exactly two incoming values.
632f2ec16ccSHideki Saito         if (Phi->getNumIncomingValues() != 2) {
6339e97caf5SRenato Golin           reportVectorizationFailure("Found an invalid PHI",
6349e97caf5SRenato Golin               "loop control flow is not understood by vectorizer",
635ec818d7fSHideki Saito               "CFGNotUnderstood", ORE, TheLoop, Phi);
636f2ec16ccSHideki Saito           return false;
637f2ec16ccSHideki Saito         }
638f2ec16ccSHideki Saito 
639f2ec16ccSHideki Saito         RecurrenceDescriptor RedDes;
640f2ec16ccSHideki Saito         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
641f2ec16ccSHideki Saito                                                  DT)) {
642b3a33553SSanjay Patel           Requirements->addExactFPMathInst(RedDes.getExactFPMathInst());
643f2ec16ccSHideki Saito           AllowedExit.insert(RedDes.getLoopExitInstr());
644f2ec16ccSHideki Saito           Reductions[Phi] = RedDes;
645f2ec16ccSHideki Saito           continue;
646f2ec16ccSHideki Saito         }
647f2ec16ccSHideki Saito 
648b02b0ad8SAnna Thomas         // TODO: Instead of recording the AllowedExit, it would be good to record the
649b02b0ad8SAnna Thomas         // complementary set: NotAllowedExit. These include (but may not be
650b02b0ad8SAnna Thomas         // limited to):
651b02b0ad8SAnna Thomas         // 1. Reduction phis as they represent the one-before-last value, which
652b02b0ad8SAnna Thomas         // is not available when vectorized
653b02b0ad8SAnna Thomas         // 2. Induction phis and increment when SCEV predicates cannot be used
654b02b0ad8SAnna Thomas         // outside the loop - see addInductionPhi
655b02b0ad8SAnna Thomas         // 3. Non-Phis with outside uses when SCEV predicates cannot be used
656b02b0ad8SAnna Thomas         // outside the loop - see call to hasOutsideLoopUser in the non-phi
657b02b0ad8SAnna Thomas         // handling below
658b02b0ad8SAnna Thomas         // 4. FirstOrderRecurrence phis that can possibly be handled by
659b02b0ad8SAnna Thomas         // extraction.
660b02b0ad8SAnna Thomas         // By recording these, we can then reason about ways to vectorize each
661b02b0ad8SAnna Thomas         // of these NotAllowedExit.
662f2ec16ccSHideki Saito         InductionDescriptor ID;
663f2ec16ccSHideki Saito         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
664f2ec16ccSHideki Saito           addInductionPhi(Phi, ID, AllowedExit);
66536a489d1SSanjay Patel           Requirements->addExactFPMathInst(ID.getExactFPMathInst());
666f2ec16ccSHideki Saito           continue;
667f2ec16ccSHideki Saito         }
668f2ec16ccSHideki Saito 
669f2ec16ccSHideki Saito         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
670f2ec16ccSHideki Saito                                                          SinkAfter, DT)) {
6718e0c5f72SAyal Zaks           AllowedExit.insert(Phi);
672f2ec16ccSHideki Saito           FirstOrderRecurrences.insert(Phi);
673f2ec16ccSHideki Saito           continue;
674f2ec16ccSHideki Saito         }
675f2ec16ccSHideki Saito 
676f2ec16ccSHideki Saito         // As a last resort, coerce the PHI to a AddRec expression
677f2ec16ccSHideki Saito         // and re-try classifying it a an induction PHI.
678f2ec16ccSHideki Saito         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
679f2ec16ccSHideki Saito           addInductionPhi(Phi, ID, AllowedExit);
680f2ec16ccSHideki Saito           continue;
681f2ec16ccSHideki Saito         }
682f2ec16ccSHideki Saito 
6839e97caf5SRenato Golin         reportVectorizationFailure("Found an unidentified PHI",
6849e97caf5SRenato Golin             "value that could not be identified as "
6859e97caf5SRenato Golin             "reduction is used outside the loop",
686ec818d7fSHideki Saito             "NonReductionValueUsedOutsideLoop", ORE, TheLoop, Phi);
687f2ec16ccSHideki Saito         return false;
688f2ec16ccSHideki Saito       } // end of PHI handling
689f2ec16ccSHideki Saito 
690f2ec16ccSHideki Saito       // We handle calls that:
691f2ec16ccSHideki Saito       //   * Are debug info intrinsics.
692f2ec16ccSHideki Saito       //   * Have a mapping to an IR intrinsic.
693f2ec16ccSHideki Saito       //   * Have a vector version available.
694f2ec16ccSHideki Saito       auto *CI = dyn_cast<CallInst>(&I);
69566c120f0SFrancesco Petrogalli 
696f2ec16ccSHideki Saito       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
697f2ec16ccSHideki Saito           !isa<DbgInfoIntrinsic>(CI) &&
698f2ec16ccSHideki Saito           !(CI->getCalledFunction() && TLI &&
69966c120f0SFrancesco Petrogalli             (!VFDatabase::getMappings(*CI).empty() ||
70066c120f0SFrancesco Petrogalli              isTLIScalarize(*TLI, *CI)))) {
7017d65fe5cSSanjay Patel         // If the call is a recognized math libary call, it is likely that
7027d65fe5cSSanjay Patel         // we can vectorize it given loosened floating-point constraints.
7037d65fe5cSSanjay Patel         LibFunc Func;
7047d65fe5cSSanjay Patel         bool IsMathLibCall =
7057d65fe5cSSanjay Patel             TLI && CI->getCalledFunction() &&
7067d65fe5cSSanjay Patel             CI->getType()->isFloatingPointTy() &&
7077d65fe5cSSanjay Patel             TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
7087d65fe5cSSanjay Patel             TLI->hasOptimizedCodeGen(Func);
7097d65fe5cSSanjay Patel 
7107d65fe5cSSanjay Patel         if (IsMathLibCall) {
7117d65fe5cSSanjay Patel           // TODO: Ideally, we should not use clang-specific language here,
7127d65fe5cSSanjay Patel           // but it's hard to provide meaningful yet generic advice.
7137d65fe5cSSanjay Patel           // Also, should this be guarded by allowExtraAnalysis() and/or be part
7147d65fe5cSSanjay Patel           // of the returned info from isFunctionVectorizable()?
71566c120f0SFrancesco Petrogalli           reportVectorizationFailure(
71666c120f0SFrancesco Petrogalli               "Found a non-intrinsic callsite",
7179e97caf5SRenato Golin               "library call cannot be vectorized. "
7187d65fe5cSSanjay Patel               "Try compiling with -fno-math-errno, -ffast-math, "
7199e97caf5SRenato Golin               "or similar flags",
720ec818d7fSHideki Saito               "CantVectorizeLibcall", ORE, TheLoop, CI);
7217d65fe5cSSanjay Patel         } else {
7229e97caf5SRenato Golin           reportVectorizationFailure("Found a non-intrinsic callsite",
7239e97caf5SRenato Golin                                      "call instruction cannot be vectorized",
724ec818d7fSHideki Saito                                      "CantVectorizeLibcall", ORE, TheLoop, CI);
7257d65fe5cSSanjay Patel         }
726f2ec16ccSHideki Saito         return false;
727f2ec16ccSHideki Saito       }
728f2ec16ccSHideki Saito 
729a066f1f9SSimon Pilgrim       // Some intrinsics have scalar arguments and should be same in order for
730a066f1f9SSimon Pilgrim       // them to be vectorized (i.e. loop invariant).
731a066f1f9SSimon Pilgrim       if (CI) {
732f2ec16ccSHideki Saito         auto *SE = PSE.getSE();
733a066f1f9SSimon Pilgrim         Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
734a066f1f9SSimon Pilgrim         for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
735a066f1f9SSimon Pilgrim           if (hasVectorInstrinsicScalarOpd(IntrinID, i)) {
736a066f1f9SSimon Pilgrim             if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(i)), TheLoop)) {
7379e97caf5SRenato Golin               reportVectorizationFailure("Found unvectorizable intrinsic",
7389e97caf5SRenato Golin                   "intrinsic instruction cannot be vectorized",
739ec818d7fSHideki Saito                   "CantVectorizeIntrinsic", ORE, TheLoop, CI);
740f2ec16ccSHideki Saito               return false;
741f2ec16ccSHideki Saito             }
742f2ec16ccSHideki Saito           }
743a066f1f9SSimon Pilgrim       }
744f2ec16ccSHideki Saito 
745f2ec16ccSHideki Saito       // Check that the instruction return type is vectorizable.
746f2ec16ccSHideki Saito       // Also, we can't vectorize extractelement instructions.
747f2ec16ccSHideki Saito       if ((!VectorType::isValidElementType(I.getType()) &&
748f2ec16ccSHideki Saito            !I.getType()->isVoidTy()) ||
749f2ec16ccSHideki Saito           isa<ExtractElementInst>(I)) {
7509e97caf5SRenato Golin         reportVectorizationFailure("Found unvectorizable type",
7519e97caf5SRenato Golin             "instruction return type cannot be vectorized",
752ec818d7fSHideki Saito             "CantVectorizeInstructionReturnType", ORE, TheLoop, &I);
753f2ec16ccSHideki Saito         return false;
754f2ec16ccSHideki Saito       }
755f2ec16ccSHideki Saito 
756f2ec16ccSHideki Saito       // Check that the stored type is vectorizable.
757f2ec16ccSHideki Saito       if (auto *ST = dyn_cast<StoreInst>(&I)) {
758f2ec16ccSHideki Saito         Type *T = ST->getValueOperand()->getType();
759f2ec16ccSHideki Saito         if (!VectorType::isValidElementType(T)) {
7609e97caf5SRenato Golin           reportVectorizationFailure("Store instruction cannot be vectorized",
7619e97caf5SRenato Golin                                      "store instruction cannot be vectorized",
762ec818d7fSHideki Saito                                      "CantVectorizeStore", ORE, TheLoop, ST);
763f2ec16ccSHideki Saito           return false;
764f2ec16ccSHideki Saito         }
765f2ec16ccSHideki Saito 
7666452bdd2SWarren Ristow         // For nontemporal stores, check that a nontemporal vector version is
7676452bdd2SWarren Ristow         // supported on the target.
7686452bdd2SWarren Ristow         if (ST->getMetadata(LLVMContext::MD_nontemporal)) {
7696452bdd2SWarren Ristow           // Arbitrarily try a vector of 2 elements.
7706913812aSFangrui Song           auto *VecTy = FixedVectorType::get(T, /*NumElts=*/2);
7716452bdd2SWarren Ristow           assert(VecTy && "did not find vectorized version of stored type");
77252e98f62SNikita Popov           if (!TTI->isLegalNTStore(VecTy, ST->getAlign())) {
7736452bdd2SWarren Ristow             reportVectorizationFailure(
7746452bdd2SWarren Ristow                 "nontemporal store instruction cannot be vectorized",
7756452bdd2SWarren Ristow                 "nontemporal store instruction cannot be vectorized",
776ec818d7fSHideki Saito                 "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
7776452bdd2SWarren Ristow             return false;
7786452bdd2SWarren Ristow           }
7796452bdd2SWarren Ristow         }
7806452bdd2SWarren Ristow 
7816452bdd2SWarren Ristow       } else if (auto *LD = dyn_cast<LoadInst>(&I)) {
7826452bdd2SWarren Ristow         if (LD->getMetadata(LLVMContext::MD_nontemporal)) {
7836452bdd2SWarren Ristow           // For nontemporal loads, check that a nontemporal vector version is
7846452bdd2SWarren Ristow           // supported on the target (arbitrarily try a vector of 2 elements).
7856913812aSFangrui Song           auto *VecTy = FixedVectorType::get(I.getType(), /*NumElts=*/2);
7866452bdd2SWarren Ristow           assert(VecTy && "did not find vectorized version of load type");
78752e98f62SNikita Popov           if (!TTI->isLegalNTLoad(VecTy, LD->getAlign())) {
7886452bdd2SWarren Ristow             reportVectorizationFailure(
7896452bdd2SWarren Ristow                 "nontemporal load instruction cannot be vectorized",
7906452bdd2SWarren Ristow                 "nontemporal load instruction cannot be vectorized",
791ec818d7fSHideki Saito                 "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
7926452bdd2SWarren Ristow             return false;
7936452bdd2SWarren Ristow           }
7946452bdd2SWarren Ristow         }
7956452bdd2SWarren Ristow 
796f2ec16ccSHideki Saito         // FP instructions can allow unsafe algebra, thus vectorizable by
797f2ec16ccSHideki Saito         // non-IEEE-754 compliant SIMD units.
798f2ec16ccSHideki Saito         // This applies to floating-point math operations and calls, not memory
799f2ec16ccSHideki Saito         // operations, shuffles, or casts, as they don't change precision or
800f2ec16ccSHideki Saito         // semantics.
801f2ec16ccSHideki Saito       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
802f2ec16ccSHideki Saito                  !I.isFast()) {
803d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
804f2ec16ccSHideki Saito         Hints->setPotentiallyUnsafe();
805f2ec16ccSHideki Saito       }
806f2ec16ccSHideki Saito 
807f2ec16ccSHideki Saito       // Reduction instructions are allowed to have exit users.
808f2ec16ccSHideki Saito       // All other instructions must not have external users.
809f2ec16ccSHideki Saito       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
810b02b0ad8SAnna Thomas         // We can safely vectorize loops where instructions within the loop are
811b02b0ad8SAnna Thomas         // used outside the loop only if the SCEV predicates within the loop is
812b02b0ad8SAnna Thomas         // same as outside the loop. Allowing the exit means reusing the SCEV
813b02b0ad8SAnna Thomas         // outside the loop.
814b02b0ad8SAnna Thomas         if (PSE.getUnionPredicate().isAlwaysTrue()) {
815b02b0ad8SAnna Thomas           AllowedExit.insert(&I);
816b02b0ad8SAnna Thomas           continue;
817b02b0ad8SAnna Thomas         }
8189e97caf5SRenato Golin         reportVectorizationFailure("Value cannot be used outside the loop",
8199e97caf5SRenato Golin                                    "value cannot be used outside the loop",
820ec818d7fSHideki Saito                                    "ValueUsedOutsideLoop", ORE, TheLoop, &I);
821f2ec16ccSHideki Saito         return false;
822f2ec16ccSHideki Saito       }
823f2ec16ccSHideki Saito     } // next instr.
824f2ec16ccSHideki Saito   }
825f2ec16ccSHideki Saito 
826f2ec16ccSHideki Saito   if (!PrimaryInduction) {
827f2ec16ccSHideki Saito     if (Inductions.empty()) {
8289e97caf5SRenato Golin       reportVectorizationFailure("Did not find one integer induction var",
8299e97caf5SRenato Golin           "loop induction variable could not be identified",
830ec818d7fSHideki Saito           "NoInductionVariable", ORE, TheLoop);
831f2ec16ccSHideki Saito       return false;
8324f27730eSWarren Ristow     } else if (!WidestIndTy) {
8339e97caf5SRenato Golin       reportVectorizationFailure("Did not find one integer induction var",
8349e97caf5SRenato Golin           "integer loop induction variable could not be identified",
835ec818d7fSHideki Saito           "NoIntegerInductionVariable", ORE, TheLoop);
8364f27730eSWarren Ristow       return false;
8379e97caf5SRenato Golin     } else {
8389e97caf5SRenato Golin       LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
839f2ec16ccSHideki Saito     }
840f2ec16ccSHideki Saito   }
841f2ec16ccSHideki Saito 
8429d24933fSFlorian Hahn   // For first order recurrences, we use the previous value (incoming value from
8439d24933fSFlorian Hahn   // the latch) to check if it dominates all users of the recurrence. Bail out
8449d24933fSFlorian Hahn   // if we have to sink such an instruction for another recurrence, as the
8459d24933fSFlorian Hahn   // dominance requirement may not hold after sinking.
8469d24933fSFlorian Hahn   BasicBlock *LoopLatch = TheLoop->getLoopLatch();
8479d24933fSFlorian Hahn   if (any_of(FirstOrderRecurrences, [LoopLatch, this](const PHINode *Phi) {
8489d24933fSFlorian Hahn         Instruction *V =
8499d24933fSFlorian Hahn             cast<Instruction>(Phi->getIncomingValueForBlock(LoopLatch));
8509d24933fSFlorian Hahn         return SinkAfter.find(V) != SinkAfter.end();
8519d24933fSFlorian Hahn       }))
8529d24933fSFlorian Hahn     return false;
8539d24933fSFlorian Hahn 
854f2ec16ccSHideki Saito   // Now we know the widest induction type, check if our found induction
855f2ec16ccSHideki Saito   // is the same size. If it's not, unset it here and InnerLoopVectorizer
856f2ec16ccSHideki Saito   // will create another.
857f2ec16ccSHideki Saito   if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
858f2ec16ccSHideki Saito     PrimaryInduction = nullptr;
859f2ec16ccSHideki Saito 
860f2ec16ccSHideki Saito   return true;
861f2ec16ccSHideki Saito }
862f2ec16ccSHideki Saito 
863f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeMemory() {
864f2ec16ccSHideki Saito   LAI = &(*GetLAA)(*TheLoop);
865f2ec16ccSHideki Saito   const OptimizationRemarkAnalysis *LAR = LAI->getReport();
866f2ec16ccSHideki Saito   if (LAR) {
867f2ec16ccSHideki Saito     ORE->emit([&]() {
868f2ec16ccSHideki Saito       return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
869f2ec16ccSHideki Saito                                         "loop not vectorized: ", *LAR);
870f2ec16ccSHideki Saito     });
871f2ec16ccSHideki Saito   }
872f2ec16ccSHideki Saito   if (!LAI->canVectorizeMemory())
873f2ec16ccSHideki Saito     return false;
874f2ec16ccSHideki Saito 
8755e9215f0SAnna Thomas   if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
8769e97caf5SRenato Golin     reportVectorizationFailure("Stores to a uniform address",
8779e97caf5SRenato Golin         "write to a loop invariant address could not be vectorized",
878ec818d7fSHideki Saito         "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
879f2ec16ccSHideki Saito     return false;
880f2ec16ccSHideki Saito   }
881f2ec16ccSHideki Saito   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
882f2ec16ccSHideki Saito   PSE.addPredicate(LAI->getPSE().getUnionPredicate());
883f2ec16ccSHideki Saito 
884f2ec16ccSHideki Saito   return true;
885f2ec16ccSHideki Saito }
886f2ec16ccSHideki Saito 
887f2ec16ccSHideki Saito bool LoopVectorizationLegality::isInductionPhi(const Value *V) {
888f2ec16ccSHideki Saito   Value *In0 = const_cast<Value *>(V);
889f2ec16ccSHideki Saito   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
890f2ec16ccSHideki Saito   if (!PN)
891f2ec16ccSHideki Saito     return false;
892f2ec16ccSHideki Saito 
893f2ec16ccSHideki Saito   return Inductions.count(PN);
894f2ec16ccSHideki Saito }
895f2ec16ccSHideki Saito 
896f2ec16ccSHideki Saito bool LoopVectorizationLegality::isCastedInductionVariable(const Value *V) {
897f2ec16ccSHideki Saito   auto *Inst = dyn_cast<Instruction>(V);
898f2ec16ccSHideki Saito   return (Inst && InductionCastsToIgnore.count(Inst));
899f2ec16ccSHideki Saito }
900f2ec16ccSHideki Saito 
901f2ec16ccSHideki Saito bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
902f2ec16ccSHideki Saito   return isInductionPhi(V) || isCastedInductionVariable(V);
903f2ec16ccSHideki Saito }
904f2ec16ccSHideki Saito 
905f2ec16ccSHideki Saito bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
906f2ec16ccSHideki Saito   return FirstOrderRecurrences.count(Phi);
907f2ec16ccSHideki Saito }
908f2ec16ccSHideki Saito 
909f82966d1SSander de Smalen bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) const {
910f2ec16ccSHideki Saito   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
911f2ec16ccSHideki Saito }
912f2ec16ccSHideki Saito 
913f2ec16ccSHideki Saito bool LoopVectorizationLegality::blockCanBePredicated(
914bda8fbe2SSjoerd Meijer     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs,
915bda8fbe2SSjoerd Meijer     SmallPtrSetImpl<const Instruction *> &MaskedOp,
916bda8fbe2SSjoerd Meijer     SmallPtrSetImpl<Instruction *> &ConditionalAssumes,
917bda8fbe2SSjoerd Meijer     bool PreserveGuards) const {
918f2ec16ccSHideki Saito   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
919f2ec16ccSHideki Saito 
920f2ec16ccSHideki Saito   for (Instruction &I : *BB) {
921f2ec16ccSHideki Saito     // Check that we don't have a constant expression that can trap as operand.
922f2ec16ccSHideki Saito     for (Value *Operand : I.operands()) {
923f2ec16ccSHideki Saito       if (auto *C = dyn_cast<Constant>(Operand))
924f2ec16ccSHideki Saito         if (C->canTrap())
925f2ec16ccSHideki Saito           return false;
926f2ec16ccSHideki Saito     }
92723c11380SFlorian Hahn 
92823c11380SFlorian Hahn     // We can predicate blocks with calls to assume, as long as we drop them in
92923c11380SFlorian Hahn     // case we flatten the CFG via predication.
93023c11380SFlorian Hahn     if (match(&I, m_Intrinsic<Intrinsic::assume>())) {
93123c11380SFlorian Hahn       ConditionalAssumes.insert(&I);
93223c11380SFlorian Hahn       continue;
93323c11380SFlorian Hahn     }
93423c11380SFlorian Hahn 
935121cac01SJeroen Dobbelaere     // Do not let llvm.experimental.noalias.scope.decl block the vectorization.
936121cac01SJeroen Dobbelaere     // TODO: there might be cases that it should block the vectorization. Let's
937121cac01SJeroen Dobbelaere     // ignore those for now.
938c83cff45SNikita Popov     if (isa<NoAliasScopeDeclInst>(&I))
939121cac01SJeroen Dobbelaere       continue;
940121cac01SJeroen Dobbelaere 
941f2ec16ccSHideki Saito     // We might be able to hoist the load.
942f2ec16ccSHideki Saito     if (I.mayReadFromMemory()) {
943f2ec16ccSHideki Saito       auto *LI = dyn_cast<LoadInst>(&I);
944f2ec16ccSHideki Saito       if (!LI)
945f2ec16ccSHideki Saito         return false;
946f2ec16ccSHideki Saito       if (!SafePtrs.count(LI->getPointerOperand())) {
947f2ec16ccSHideki Saito         // !llvm.mem.parallel_loop_access implies if-conversion safety.
948f2ec16ccSHideki Saito         // Otherwise, record that the load needs (real or emulated) masking
949f2ec16ccSHideki Saito         // and let the cost model decide.
950d57d73daSDorit Nuzman         if (!IsAnnotatedParallel || PreserveGuards)
951f2ec16ccSHideki Saito           MaskedOp.insert(LI);
952f2ec16ccSHideki Saito         continue;
953f2ec16ccSHideki Saito       }
954f2ec16ccSHideki Saito     }
955f2ec16ccSHideki Saito 
956f2ec16ccSHideki Saito     if (I.mayWriteToMemory()) {
957f2ec16ccSHideki Saito       auto *SI = dyn_cast<StoreInst>(&I);
958f2ec16ccSHideki Saito       if (!SI)
959f2ec16ccSHideki Saito         return false;
960f2ec16ccSHideki Saito       // Predicated store requires some form of masking:
961f2ec16ccSHideki Saito       // 1) masked store HW instruction,
962f2ec16ccSHideki Saito       // 2) emulation via load-blend-store (only if safe and legal to do so,
963f2ec16ccSHideki Saito       //    be aware on the race conditions), or
964f2ec16ccSHideki Saito       // 3) element-by-element predicate check and scalar store.
965f2ec16ccSHideki Saito       MaskedOp.insert(SI);
966f2ec16ccSHideki Saito       continue;
967f2ec16ccSHideki Saito     }
968f2ec16ccSHideki Saito     if (I.mayThrow())
969f2ec16ccSHideki Saito       return false;
970f2ec16ccSHideki Saito   }
971f2ec16ccSHideki Saito 
972f2ec16ccSHideki Saito   return true;
973f2ec16ccSHideki Saito }
974f2ec16ccSHideki Saito 
975f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
976f2ec16ccSHideki Saito   if (!EnableIfConversion) {
9779e97caf5SRenato Golin     reportVectorizationFailure("If-conversion is disabled",
9789e97caf5SRenato Golin                                "if-conversion is disabled",
979ec818d7fSHideki Saito                                "IfConversionDisabled",
980ec818d7fSHideki Saito                                ORE, TheLoop);
981f2ec16ccSHideki Saito     return false;
982f2ec16ccSHideki Saito   }
983f2ec16ccSHideki Saito 
984f2ec16ccSHideki Saito   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
985f2ec16ccSHideki Saito 
986cf3b5559SPhilip Reames   // A list of pointers which are known to be dereferenceable within scope of
987cf3b5559SPhilip Reames   // the loop body for each iteration of the loop which executes.  That is,
988cf3b5559SPhilip Reames   // the memory pointed to can be dereferenced (with the access size implied by
989cf3b5559SPhilip Reames   // the value's type) unconditionally within the loop header without
990cf3b5559SPhilip Reames   // introducing a new fault.
9913bbc71d6SSjoerd Meijer   SmallPtrSet<Value *, 8> SafePointers;
992f2ec16ccSHideki Saito 
993f2ec16ccSHideki Saito   // Collect safe addresses.
994f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
9957403569bSPhilip Reames     if (!blockNeedsPredication(BB)) {
996f2ec16ccSHideki Saito       for (Instruction &I : *BB)
997f2ec16ccSHideki Saito         if (auto *Ptr = getLoadStorePointerOperand(&I))
9983bbc71d6SSjoerd Meijer           SafePointers.insert(Ptr);
9997403569bSPhilip Reames       continue;
10007403569bSPhilip Reames     }
10017403569bSPhilip Reames 
10027403569bSPhilip Reames     // For a block which requires predication, a address may be safe to access
10037403569bSPhilip Reames     // in the loop w/o predication if we can prove dereferenceability facts
10047403569bSPhilip Reames     // sufficient to ensure it'll never fault within the loop. For the moment,
10057403569bSPhilip Reames     // we restrict this to loads; stores are more complicated due to
10067403569bSPhilip Reames     // concurrency restrictions.
10077403569bSPhilip Reames     ScalarEvolution &SE = *PSE.getSE();
10087403569bSPhilip Reames     for (Instruction &I : *BB) {
10097403569bSPhilip Reames       LoadInst *LI = dyn_cast<LoadInst>(&I);
1010467e5cf4SJoe Ellis       if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) &&
10117403569bSPhilip Reames           isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT))
10123bbc71d6SSjoerd Meijer         SafePointers.insert(LI->getPointerOperand());
10137403569bSPhilip Reames     }
1014f2ec16ccSHideki Saito   }
1015f2ec16ccSHideki Saito 
1016f2ec16ccSHideki Saito   // Collect the blocks that need predication.
1017f2ec16ccSHideki Saito   BasicBlock *Header = TheLoop->getHeader();
1018f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
1019f2ec16ccSHideki Saito     // We don't support switch statements inside loops.
1020f2ec16ccSHideki Saito     if (!isa<BranchInst>(BB->getTerminator())) {
10219e97caf5SRenato Golin       reportVectorizationFailure("Loop contains a switch statement",
10229e97caf5SRenato Golin                                  "loop contains a switch statement",
1023ec818d7fSHideki Saito                                  "LoopContainsSwitch", ORE, TheLoop,
1024ec818d7fSHideki Saito                                  BB->getTerminator());
1025f2ec16ccSHideki Saito       return false;
1026f2ec16ccSHideki Saito     }
1027f2ec16ccSHideki Saito 
1028f2ec16ccSHideki Saito     // We must be able to predicate all blocks that need to be predicated.
1029f2ec16ccSHideki Saito     if (blockNeedsPredication(BB)) {
1030bda8fbe2SSjoerd Meijer       if (!blockCanBePredicated(BB, SafePointers, MaskedOp,
1031bda8fbe2SSjoerd Meijer                                 ConditionalAssumes)) {
10329e97caf5SRenato Golin         reportVectorizationFailure(
10339e97caf5SRenato Golin             "Control flow cannot be substituted for a select",
10349e97caf5SRenato Golin             "control flow cannot be substituted for a select",
1035ec818d7fSHideki Saito             "NoCFGForSelect", ORE, TheLoop,
1036ec818d7fSHideki Saito             BB->getTerminator());
1037f2ec16ccSHideki Saito         return false;
1038f2ec16ccSHideki Saito       }
1039f2ec16ccSHideki Saito     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
10409e97caf5SRenato Golin       reportVectorizationFailure(
10419e97caf5SRenato Golin           "Control flow cannot be substituted for a select",
10429e97caf5SRenato Golin           "control flow cannot be substituted for a select",
1043ec818d7fSHideki Saito           "NoCFGForSelect", ORE, TheLoop,
1044ec818d7fSHideki Saito           BB->getTerminator());
1045f2ec16ccSHideki Saito       return false;
1046f2ec16ccSHideki Saito     }
1047f2ec16ccSHideki Saito   }
1048f2ec16ccSHideki Saito 
1049f2ec16ccSHideki Saito   // We can if-convert this loop.
1050f2ec16ccSHideki Saito   return true;
1051f2ec16ccSHideki Saito }
1052f2ec16ccSHideki Saito 
1053f2ec16ccSHideki Saito // Helper function to canVectorizeLoopNestCFG.
1054f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
1055f2ec16ccSHideki Saito                                                     bool UseVPlanNativePath) {
105689c1e35fSStefanos Baziotis   assert((UseVPlanNativePath || Lp->isInnermost()) &&
1057f2ec16ccSHideki Saito          "VPlan-native path is not enabled.");
1058f2ec16ccSHideki Saito 
1059f2ec16ccSHideki Saito   // TODO: ORE should be improved to show more accurate information when an
1060f2ec16ccSHideki Saito   // outer loop can't be vectorized because a nested loop is not understood or
1061f2ec16ccSHideki Saito   // legal. Something like: "outer_loop_location: loop not vectorized:
1062f2ec16ccSHideki Saito   // (inner_loop_location) loop control flow is not understood by vectorizer".
1063f2ec16ccSHideki Saito 
1064f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1065f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1066f2ec16ccSHideki Saito   bool Result = true;
1067f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1068f2ec16ccSHideki Saito 
1069f2ec16ccSHideki Saito   // We must have a loop in canonical form. Loops with indirectbr in them cannot
1070f2ec16ccSHideki Saito   // be canonicalized.
1071f2ec16ccSHideki Saito   if (!Lp->getLoopPreheader()) {
10729e97caf5SRenato Golin     reportVectorizationFailure("Loop doesn't have a legal pre-header",
10739e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1074ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
1075f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1076f2ec16ccSHideki Saito       Result = false;
1077f2ec16ccSHideki Saito     else
1078f2ec16ccSHideki Saito       return false;
1079f2ec16ccSHideki Saito   }
1080f2ec16ccSHideki Saito 
1081f2ec16ccSHideki Saito   // We must have a single backedge.
1082f2ec16ccSHideki Saito   if (Lp->getNumBackEdges() != 1) {
10839e97caf5SRenato Golin     reportVectorizationFailure("The loop must have a single backedge",
10849e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1085ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
1086f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1087f2ec16ccSHideki Saito       Result = false;
1088f2ec16ccSHideki Saito     else
1089f2ec16ccSHideki Saito       return false;
1090f2ec16ccSHideki Saito   }
1091f2ec16ccSHideki Saito 
10924b33b238SPhilip Reames   // We currently must have a single "exit block" after the loop. Note that
10934b33b238SPhilip Reames   // multiple "exiting blocks" inside the loop are allowed, provided they all
10944b33b238SPhilip Reames   // reach the single exit block.
10954b33b238SPhilip Reames   // TODO: This restriction can be relaxed in the near future, it's here solely
10964b33b238SPhilip Reames   // to allow separation of changes for review. We need to generalize the phi
10974b33b238SPhilip Reames   // update logic in a number of places.
10989f61fbd7SPhilip Reames   if (!Lp->getUniqueExitBlock()) {
10994b33b238SPhilip Reames     reportVectorizationFailure("The loop must have a unique exit block",
11009e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1101ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
1102f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1103f2ec16ccSHideki Saito       Result = false;
1104f2ec16ccSHideki Saito     else
1105f2ec16ccSHideki Saito       return false;
1106f2ec16ccSHideki Saito   }
1107f2ec16ccSHideki Saito   return Result;
1108f2ec16ccSHideki Saito }
1109f2ec16ccSHideki Saito 
1110f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1111f2ec16ccSHideki Saito     Loop *Lp, bool UseVPlanNativePath) {
1112f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1113f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1114f2ec16ccSHideki Saito   bool Result = true;
1115f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1116f2ec16ccSHideki Saito   if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1117f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1118f2ec16ccSHideki Saito       Result = false;
1119f2ec16ccSHideki Saito     else
1120f2ec16ccSHideki Saito       return false;
1121f2ec16ccSHideki Saito   }
1122f2ec16ccSHideki Saito 
1123f2ec16ccSHideki Saito   // Recursively check whether the loop control flow of nested loops is
1124f2ec16ccSHideki Saito   // understood.
1125f2ec16ccSHideki Saito   for (Loop *SubLp : *Lp)
1126f2ec16ccSHideki Saito     if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1127f2ec16ccSHideki Saito       if (DoExtraAnalysis)
1128f2ec16ccSHideki Saito         Result = false;
1129f2ec16ccSHideki Saito       else
1130f2ec16ccSHideki Saito         return false;
1131f2ec16ccSHideki Saito     }
1132f2ec16ccSHideki Saito 
1133f2ec16ccSHideki Saito   return Result;
1134f2ec16ccSHideki Saito }
1135f2ec16ccSHideki Saito 
1136f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1137f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1138f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1139f2ec16ccSHideki Saito   bool Result = true;
1140f2ec16ccSHideki Saito 
1141f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1142f2ec16ccSHideki Saito   // Check whether the loop-related control flow in the loop nest is expected by
1143f2ec16ccSHideki Saito   // vectorizer.
1144f2ec16ccSHideki Saito   if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1145f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1146f2ec16ccSHideki Saito       Result = false;
1147f2ec16ccSHideki Saito     else
1148f2ec16ccSHideki Saito       return false;
1149f2ec16ccSHideki Saito   }
1150f2ec16ccSHideki Saito 
1151f2ec16ccSHideki Saito   // We need to have a loop header.
1152d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1153f2ec16ccSHideki Saito                     << '\n');
1154f2ec16ccSHideki Saito 
1155f2ec16ccSHideki Saito   // Specific checks for outer loops. We skip the remaining legal checks at this
1156f2ec16ccSHideki Saito   // point because they don't support outer loops.
115789c1e35fSStefanos Baziotis   if (!TheLoop->isInnermost()) {
1158f2ec16ccSHideki Saito     assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1159f2ec16ccSHideki Saito 
1160f2ec16ccSHideki Saito     if (!canVectorizeOuterLoop()) {
11619e97caf5SRenato Golin       reportVectorizationFailure("Unsupported outer loop",
11629e97caf5SRenato Golin                                  "unsupported outer loop",
1163ec818d7fSHideki Saito                                  "UnsupportedOuterLoop",
1164ec818d7fSHideki Saito                                  ORE, TheLoop);
1165f2ec16ccSHideki Saito       // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1166f2ec16ccSHideki Saito       // outer loops.
1167f2ec16ccSHideki Saito       return false;
1168f2ec16ccSHideki Saito     }
1169f2ec16ccSHideki Saito 
1170d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1171f2ec16ccSHideki Saito     return Result;
1172f2ec16ccSHideki Saito   }
1173f2ec16ccSHideki Saito 
117489c1e35fSStefanos Baziotis   assert(TheLoop->isInnermost() && "Inner loop expected.");
1175f2ec16ccSHideki Saito   // Check if we can if-convert non-single-bb loops.
1176f2ec16ccSHideki Saito   unsigned NumBlocks = TheLoop->getNumBlocks();
1177f2ec16ccSHideki Saito   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1178d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1179f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1180f2ec16ccSHideki Saito       Result = false;
1181f2ec16ccSHideki Saito     else
1182f2ec16ccSHideki Saito       return false;
1183f2ec16ccSHideki Saito   }
1184f2ec16ccSHideki Saito 
1185f2ec16ccSHideki Saito   // Check if we can vectorize the instructions and CFG in this loop.
1186f2ec16ccSHideki Saito   if (!canVectorizeInstrs()) {
1187d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1188f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1189f2ec16ccSHideki Saito       Result = false;
1190f2ec16ccSHideki Saito     else
1191f2ec16ccSHideki Saito       return false;
1192f2ec16ccSHideki Saito   }
1193f2ec16ccSHideki Saito 
1194f2ec16ccSHideki Saito   // Go over each instruction and look at memory deps.
1195f2ec16ccSHideki Saito   if (!canVectorizeMemory()) {
1196d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1197f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1198f2ec16ccSHideki Saito       Result = false;
1199f2ec16ccSHideki Saito     else
1200f2ec16ccSHideki Saito       return false;
1201f2ec16ccSHideki Saito   }
1202f2ec16ccSHideki Saito 
1203d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
1204f2ec16ccSHideki Saito                     << (LAI->getRuntimePointerChecking()->Need
1205f2ec16ccSHideki Saito                             ? " (with a runtime bound check)"
1206f2ec16ccSHideki Saito                             : "")
1207f2ec16ccSHideki Saito                     << "!\n");
1208f2ec16ccSHideki Saito 
1209f2ec16ccSHideki Saito   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
1210f2ec16ccSHideki Saito   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
1211f2ec16ccSHideki Saito     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
1212f2ec16ccSHideki Saito 
1213f2ec16ccSHideki Saito   if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
12149e97caf5SRenato Golin     reportVectorizationFailure("Too many SCEV checks needed",
12159e97caf5SRenato Golin         "Too many SCEV assumptions need to be made and checked at runtime",
1216ec818d7fSHideki Saito         "TooManySCEVRunTimeChecks", ORE, TheLoop);
1217f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1218f2ec16ccSHideki Saito       Result = false;
1219f2ec16ccSHideki Saito     else
1220f2ec16ccSHideki Saito       return false;
1221f2ec16ccSHideki Saito   }
1222f2ec16ccSHideki Saito 
1223f2ec16ccSHideki Saito   // Okay! We've done all the tests. If any have failed, return false. Otherwise
1224f2ec16ccSHideki Saito   // we can vectorize, and at this point we don't have any other mem analysis
1225f2ec16ccSHideki Saito   // which may limit our maximum vectorization factor, so just return true with
1226f2ec16ccSHideki Saito   // no restrictions.
1227f2ec16ccSHideki Saito   return Result;
1228f2ec16ccSHideki Saito }
1229f2ec16ccSHideki Saito 
1230d57d73daSDorit Nuzman bool LoopVectorizationLegality::prepareToFoldTailByMasking() {
1231b0b5312eSAyal Zaks 
1232b0b5312eSAyal Zaks   LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
1233b0b5312eSAyal Zaks 
1234d15df0edSAyal Zaks   SmallPtrSet<const Value *, 8> ReductionLiveOuts;
1235b0b5312eSAyal Zaks 
1236d0d38df0SDavid Green   for (auto &Reduction : getReductionVars())
1237d15df0edSAyal Zaks     ReductionLiveOuts.insert(Reduction.second.getLoopExitInstr());
1238d15df0edSAyal Zaks 
1239d15df0edSAyal Zaks   // TODO: handle non-reduction outside users when tail is folded by masking.
1240b0b5312eSAyal Zaks   for (auto *AE : AllowedExit) {
1241d15df0edSAyal Zaks     // Check that all users of allowed exit values are inside the loop or
1242d15df0edSAyal Zaks     // are the live-out of a reduction.
1243d15df0edSAyal Zaks     if (ReductionLiveOuts.count(AE))
1244d15df0edSAyal Zaks       continue;
1245b0b5312eSAyal Zaks     for (User *U : AE->users()) {
1246b0b5312eSAyal Zaks       Instruction *UI = cast<Instruction>(U);
1247b0b5312eSAyal Zaks       if (TheLoop->contains(UI))
1248b0b5312eSAyal Zaks         continue;
1249bda8fbe2SSjoerd Meijer       LLVM_DEBUG(
1250bda8fbe2SSjoerd Meijer           dbgs()
1251bda8fbe2SSjoerd Meijer           << "LV: Cannot fold tail by masking, loop has an outside user for "
1252bda8fbe2SSjoerd Meijer           << *UI << "\n");
1253b0b5312eSAyal Zaks       return false;
1254b0b5312eSAyal Zaks     }
1255b0b5312eSAyal Zaks   }
1256b0b5312eSAyal Zaks 
1257b0b5312eSAyal Zaks   // The list of pointers that we can safely read and write to remains empty.
1258b0b5312eSAyal Zaks   SmallPtrSet<Value *, 8> SafePointers;
1259b0b5312eSAyal Zaks 
1260bda8fbe2SSjoerd Meijer   SmallPtrSet<const Instruction *, 8> TmpMaskedOp;
1261bda8fbe2SSjoerd Meijer   SmallPtrSet<Instruction *, 8> TmpConditionalAssumes;
1262bda8fbe2SSjoerd Meijer 
1263b0b5312eSAyal Zaks   // Check and mark all blocks for predication, including those that ordinarily
1264b0b5312eSAyal Zaks   // do not need predication such as the header block.
1265b0b5312eSAyal Zaks   for (BasicBlock *BB : TheLoop->blocks()) {
1266bda8fbe2SSjoerd Meijer     if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp,
1267bda8fbe2SSjoerd Meijer                               TmpConditionalAssumes,
1268bda8fbe2SSjoerd Meijer                               /* MaskAllLoads= */ true)) {
1269bda8fbe2SSjoerd Meijer       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as requested.\n");
1270b0b5312eSAyal Zaks       return false;
1271b0b5312eSAyal Zaks     }
1272b0b5312eSAyal Zaks   }
1273b0b5312eSAyal Zaks 
1274b0b5312eSAyal Zaks   LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
1275bda8fbe2SSjoerd Meijer 
1276bda8fbe2SSjoerd Meijer   MaskedOp.insert(TmpMaskedOp.begin(), TmpMaskedOp.end());
1277bda8fbe2SSjoerd Meijer   ConditionalAssumes.insert(TmpConditionalAssumes.begin(),
1278bda8fbe2SSjoerd Meijer                             TmpConditionalAssumes.end());
1279bda8fbe2SSjoerd Meijer 
1280b0b5312eSAyal Zaks   return true;
1281b0b5312eSAyal Zaks }
1282b0b5312eSAyal Zaks 
1283f2ec16ccSHideki Saito } // namespace llvm
1284