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"
20ed98c1b3Sserge-sans-paille #include "llvm/Analysis/OptimizationRemarkEmitter.h"
21cc529285SSimon Pilgrim #include "llvm/Analysis/TargetLibraryInfo.h"
22ed98c1b3Sserge-sans-paille #include "llvm/Analysis/TargetTransformInfo.h"
237403569bSPhilip Reames #include "llvm/Analysis/ValueTracking.h"
24f2ec16ccSHideki Saito #include "llvm/Analysis/VectorUtils.h"
25f2ec16ccSHideki Saito #include "llvm/IR/IntrinsicInst.h"
2623c11380SFlorian Hahn #include "llvm/IR/PatternMatch.h"
277bedae7dSHiroshi Yamauchi #include "llvm/Transforms/Utils/SizeOpts.h"
2823c11380SFlorian Hahn #include "llvm/Transforms/Vectorize/LoopVectorize.h"
29f2ec16ccSHideki Saito 
30f2ec16ccSHideki Saito using namespace llvm;
3123c11380SFlorian Hahn using namespace PatternMatch;
32f2ec16ccSHideki Saito 
33f2ec16ccSHideki Saito #define LV_NAME "loop-vectorize"
34f2ec16ccSHideki Saito #define DEBUG_TYPE LV_NAME
35f2ec16ccSHideki 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 
409f76a852SKerry McLaughlin namespace llvm {
419f76a852SKerry McLaughlin cl::opt<bool>
429f76a852SKerry McLaughlin     HintsAllowReordering("hints-allow-reordering", cl::init(true), cl::Hidden,
439f76a852SKerry McLaughlin                          cl::desc("Allow enabling loop hints to reorder "
449f76a852SKerry McLaughlin                                   "FP operations during vectorization."));
459f76a852SKerry McLaughlin }
469f76a852SKerry McLaughlin 
47c773d0f9SFlorian Hahn // TODO: Move size-based thresholds out of legality checking, make cost based
48c773d0f9SFlorian Hahn // decisions instead of hard thresholds.
49f2ec16ccSHideki Saito static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
50f2ec16ccSHideki Saito     "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
51f2ec16ccSHideki Saito     cl::desc("The maximum number of SCEV checks allowed."));
52f2ec16ccSHideki Saito 
53f2ec16ccSHideki Saito static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
54f2ec16ccSHideki Saito     "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
55f2ec16ccSHideki Saito     cl::desc("The maximum number of SCEV checks allowed with a "
56f2ec16ccSHideki Saito              "vectorize(enable) pragma"));
57f2ec16ccSHideki Saito 
58b1ff20fdSSander de Smalen static cl::opt<LoopVectorizeHints::ScalableForceKind>
59b1ff20fdSSander de Smalen     ForceScalableVectorization(
60b1ff20fdSSander de Smalen         "scalable-vectorization", cl::init(LoopVectorizeHints::SK_Unspecified),
614f86aa65SSander de Smalen         cl::Hidden,
624f86aa65SSander de Smalen         cl::desc("Control whether the compiler can use scalable vectors to "
634f86aa65SSander de Smalen                  "vectorize a loop"),
644f86aa65SSander de Smalen         cl::values(
654f86aa65SSander de Smalen             clEnumValN(LoopVectorizeHints::SK_FixedWidthOnly, "off",
664f86aa65SSander de Smalen                        "Scalable vectorization is disabled."),
67b1ff20fdSSander de Smalen             clEnumValN(
687c68ed88SPaul Walker                 LoopVectorizeHints::SK_PreferScalable, "preferred",
697c68ed88SPaul Walker                 "Scalable vectorization is available and favored when the "
707c68ed88SPaul Walker                 "cost is inconclusive."),
717c68ed88SPaul Walker             clEnumValN(
72b1ff20fdSSander de Smalen                 LoopVectorizeHints::SK_PreferScalable, "on",
734f86aa65SSander de Smalen                 "Scalable vectorization is available and favored when the "
744f86aa65SSander de Smalen                 "cost is inconclusive.")));
754f86aa65SSander de Smalen 
76f2ec16ccSHideki Saito /// Maximum vectorization interleave count.
77f2ec16ccSHideki Saito static const unsigned MaxInterleaveFactor = 16;
78f2ec16ccSHideki Saito 
79f2ec16ccSHideki Saito namespace llvm {
80f2ec16ccSHideki Saito 
81f2ec16ccSHideki Saito bool LoopVectorizeHints::Hint::validate(unsigned Val) {
82f2ec16ccSHideki Saito   switch (Kind) {
83f2ec16ccSHideki Saito   case HK_WIDTH:
84f2ec16ccSHideki Saito     return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
85ddb3b26aSBardia Mahjour   case HK_INTERLEAVE:
86f2ec16ccSHideki Saito     return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
87f2ec16ccSHideki Saito   case HK_FORCE:
88f2ec16ccSHideki Saito     return (Val <= 1);
89f2ec16ccSHideki Saito   case HK_ISVECTORIZED:
9020b198ecSSjoerd Meijer   case HK_PREDICATE:
9171bd59f0SDavid Sherwood   case HK_SCALABLE:
92f2ec16ccSHideki Saito     return (Val == 0 || Val == 1);
93f2ec16ccSHideki Saito   }
94f2ec16ccSHideki Saito   return false;
95f2ec16ccSHideki Saito }
96f2ec16ccSHideki Saito 
97d4eb13c8SMichael Kruse LoopVectorizeHints::LoopVectorizeHints(const Loop *L,
98d4eb13c8SMichael Kruse                                        bool InterleaveOnlyWhenForced,
99b1ff20fdSSander de Smalen                                        OptimizationRemarkEmitter &ORE,
100b1ff20fdSSander de Smalen                                        const TargetTransformInfo *TTI)
101f2ec16ccSHideki Saito     : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
102ddb3b26aSBardia Mahjour       Interleave("interleave.count", InterleaveOnlyWhenForced, HK_INTERLEAVE),
103f2ec16ccSHideki Saito       Force("vectorize.enable", FK_Undefined, HK_FORCE),
10420b198ecSSjoerd Meijer       IsVectorized("isvectorized", 0, HK_ISVECTORIZED),
10571bd59f0SDavid Sherwood       Predicate("vectorize.predicate.enable", FK_Undefined, HK_PREDICATE),
1064f86aa65SSander de Smalen       Scalable("vectorize.scalable.enable", SK_Unspecified, HK_SCALABLE),
1074f86aa65SSander de Smalen       TheLoop(L), ORE(ORE) {
108f2ec16ccSHideki Saito   // Populate values with existing loop metadata.
109f2ec16ccSHideki Saito   getHintsFromMetadata();
110f2ec16ccSHideki Saito 
111f2ec16ccSHideki Saito   // force-vector-interleave overrides DisableInterleaving.
112f2ec16ccSHideki Saito   if (VectorizerParams::isInterleaveForced())
113f2ec16ccSHideki Saito     Interleave.Value = VectorizerParams::VectorizationInterleave;
114f2ec16ccSHideki Saito 
115b1ff20fdSSander de Smalen   // If the metadata doesn't explicitly specify whether to enable scalable
116b1ff20fdSSander de Smalen   // vectorization, then decide based on the following criteria (increasing
117b1ff20fdSSander de Smalen   // level of priority):
118b1ff20fdSSander de Smalen   //  - Target default
119b1ff20fdSSander de Smalen   //  - Metadata width
120b1ff20fdSSander de Smalen   //  - Force option (always overrides)
121b1ff20fdSSander de Smalen   if ((LoopVectorizeHints::ScalableForceKind)Scalable.Value == SK_Unspecified) {
122b1ff20fdSSander de Smalen     if (TTI)
123b1ff20fdSSander de Smalen       Scalable.Value = TTI->enableScalableVectorization() ? SK_PreferScalable
124b1ff20fdSSander de Smalen                                                           : SK_FixedWidthOnly;
125b1ff20fdSSander de Smalen 
126b1ff20fdSSander de Smalen     if (Width.Value)
1274f86aa65SSander de Smalen       // If the width is set, but the metadata says nothing about the scalable
1284f86aa65SSander de Smalen       // property, then assume it concerns only a fixed-width UserVF.
1294f86aa65SSander de Smalen       // If width is not set, the flag takes precedence.
130b1ff20fdSSander de Smalen       Scalable.Value = SK_FixedWidthOnly;
131b1ff20fdSSander de Smalen   }
132b1ff20fdSSander de Smalen 
133b1ff20fdSSander de Smalen   // If the flag is set to force any use of scalable vectors, override the loop
134b1ff20fdSSander de Smalen   // hints.
135b1ff20fdSSander de Smalen   if (ForceScalableVectorization.getValue() !=
136b1ff20fdSSander de Smalen       LoopVectorizeHints::SK_Unspecified)
137b1ff20fdSSander de Smalen     Scalable.Value = ForceScalableVectorization.getValue();
138b1ff20fdSSander de Smalen 
139b1ff20fdSSander de Smalen   // Scalable vectorization is disabled if no preference is specified.
140b1ff20fdSSander de Smalen   if ((LoopVectorizeHints::ScalableForceKind)Scalable.Value == SK_Unspecified)
1414f86aa65SSander de Smalen     Scalable.Value = SK_FixedWidthOnly;
1424f86aa65SSander de Smalen 
143f2ec16ccSHideki Saito   if (IsVectorized.Value != 1)
144f2ec16ccSHideki Saito     // If the vectorization width and interleaving count are both 1 then
145f2ec16ccSHideki Saito     // consider the loop to have been already vectorized because there's
146f2ec16ccSHideki Saito     // nothing more that we can do.
14771bd59f0SDavid Sherwood     IsVectorized.Value =
148ddb3b26aSBardia Mahjour         getWidth() == ElementCount::getFixed(1) && getInterleave() == 1;
149ddb3b26aSBardia Mahjour   LLVM_DEBUG(if (InterleaveOnlyWhenForced && getInterleave() == 1) dbgs()
150f2ec16ccSHideki Saito              << "LV: Interleaving disabled by the pass manager\n");
151f2ec16ccSHideki Saito }
152f2ec16ccSHideki Saito 
15377a614a6SMichael Kruse void LoopVectorizeHints::setAlreadyVectorized() {
15477a614a6SMichael Kruse   LLVMContext &Context = TheLoop->getHeader()->getContext();
15577a614a6SMichael Kruse 
15677a614a6SMichael Kruse   MDNode *IsVectorizedMD = MDNode::get(
15777a614a6SMichael Kruse       Context,
15877a614a6SMichael Kruse       {MDString::get(Context, "llvm.loop.isvectorized"),
15977a614a6SMichael Kruse        ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))});
16077a614a6SMichael Kruse   MDNode *LoopID = TheLoop->getLoopID();
16177a614a6SMichael Kruse   MDNode *NewLoopID =
16277a614a6SMichael Kruse       makePostTransformationMetadata(Context, LoopID,
16377a614a6SMichael Kruse                                      {Twine(Prefix(), "vectorize.").str(),
16477a614a6SMichael Kruse                                       Twine(Prefix(), "interleave.").str()},
16577a614a6SMichael Kruse                                      {IsVectorizedMD});
16677a614a6SMichael Kruse   TheLoop->setLoopID(NewLoopID);
16777a614a6SMichael Kruse 
16877a614a6SMichael Kruse   // Update internal cache.
16977a614a6SMichael Kruse   IsVectorized.Value = 1;
17077a614a6SMichael Kruse }
17177a614a6SMichael Kruse 
172d4eb13c8SMichael Kruse bool LoopVectorizeHints::allowVectorization(
173d4eb13c8SMichael Kruse     Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
174f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Disabled) {
175d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
176f2ec16ccSHideki Saito     emitRemarkWithHints();
177f2ec16ccSHideki Saito     return false;
178f2ec16ccSHideki Saito   }
179f2ec16ccSHideki Saito 
180d4eb13c8SMichael Kruse   if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
181d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
182f2ec16ccSHideki Saito     emitRemarkWithHints();
183f2ec16ccSHideki Saito     return false;
184f2ec16ccSHideki Saito   }
185f2ec16ccSHideki Saito 
186f2ec16ccSHideki Saito   if (getIsVectorized() == 1) {
187d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
188f2ec16ccSHideki Saito     // FIXME: Add interleave.disable metadata. This will allow
189f2ec16ccSHideki Saito     // vectorize.disable to be used without disabling the pass and errors
190f2ec16ccSHideki Saito     // to differentiate between disabled vectorization and a width of 1.
191f2ec16ccSHideki Saito     ORE.emit([&]() {
192f2ec16ccSHideki Saito       return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
193f2ec16ccSHideki Saito                                         "AllDisabled", L->getStartLoc(),
194f2ec16ccSHideki Saito                                         L->getHeader())
195f2ec16ccSHideki Saito              << "loop not vectorized: vectorization and interleaving are "
196f2ec16ccSHideki Saito                 "explicitly disabled, or the loop has already been "
197f2ec16ccSHideki Saito                 "vectorized";
198f2ec16ccSHideki Saito     });
199f2ec16ccSHideki Saito     return false;
200f2ec16ccSHideki Saito   }
201f2ec16ccSHideki Saito 
202f2ec16ccSHideki Saito   return true;
203f2ec16ccSHideki Saito }
204f2ec16ccSHideki Saito 
205f2ec16ccSHideki Saito void LoopVectorizeHints::emitRemarkWithHints() const {
206f2ec16ccSHideki Saito   using namespace ore;
207f2ec16ccSHideki Saito 
208f2ec16ccSHideki Saito   ORE.emit([&]() {
209f2ec16ccSHideki Saito     if (Force.Value == LoopVectorizeHints::FK_Disabled)
210f2ec16ccSHideki Saito       return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
211f2ec16ccSHideki Saito                                       TheLoop->getStartLoc(),
212f2ec16ccSHideki Saito                                       TheLoop->getHeader())
213f2ec16ccSHideki Saito              << "loop not vectorized: vectorization is explicitly disabled";
214f2ec16ccSHideki Saito     else {
215f2ec16ccSHideki Saito       OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
216f2ec16ccSHideki Saito                                  TheLoop->getStartLoc(), TheLoop->getHeader());
217f2ec16ccSHideki Saito       R << "loop not vectorized";
218f2ec16ccSHideki Saito       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
219f2ec16ccSHideki Saito         R << " (Force=" << NV("Force", true);
220f2ec16ccSHideki Saito         if (Width.Value != 0)
22171bd59f0SDavid Sherwood           R << ", Vector Width=" << NV("VectorWidth", getWidth());
222ddb3b26aSBardia Mahjour         if (getInterleave() != 0)
223ddb3b26aSBardia Mahjour           R << ", Interleave Count=" << NV("InterleaveCount", getInterleave());
224f2ec16ccSHideki Saito         R << ")";
225f2ec16ccSHideki Saito       }
226f2ec16ccSHideki Saito       return R;
227f2ec16ccSHideki Saito     }
228f2ec16ccSHideki Saito   });
229f2ec16ccSHideki Saito }
230f2ec16ccSHideki Saito 
231f2ec16ccSHideki Saito const char *LoopVectorizeHints::vectorizeAnalysisPassName() const {
23271bd59f0SDavid Sherwood   if (getWidth() == ElementCount::getFixed(1))
233f2ec16ccSHideki Saito     return LV_NAME;
234f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Disabled)
235f2ec16ccSHideki Saito     return LV_NAME;
23671bd59f0SDavid Sherwood   if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth().isZero())
237f2ec16ccSHideki Saito     return LV_NAME;
238f2ec16ccSHideki Saito   return OptimizationRemarkAnalysis::AlwaysPrint;
239f2ec16ccSHideki Saito }
240f2ec16ccSHideki Saito 
2419f76a852SKerry McLaughlin bool LoopVectorizeHints::allowReordering() const {
2429f76a852SKerry McLaughlin   // Allow the vectorizer to change the order of operations if enabling
2439f76a852SKerry McLaughlin   // loop hints are provided
2449f76a852SKerry McLaughlin   ElementCount EC = getWidth();
2459f76a852SKerry McLaughlin   return HintsAllowReordering &&
2469f76a852SKerry McLaughlin          (getForce() == LoopVectorizeHints::FK_Enabled ||
2479f76a852SKerry McLaughlin           EC.getKnownMinValue() > 1);
2489f76a852SKerry McLaughlin }
2499f76a852SKerry McLaughlin 
250f2ec16ccSHideki Saito void LoopVectorizeHints::getHintsFromMetadata() {
251f2ec16ccSHideki Saito   MDNode *LoopID = TheLoop->getLoopID();
252f2ec16ccSHideki Saito   if (!LoopID)
253f2ec16ccSHideki Saito     return;
254f2ec16ccSHideki Saito 
255f2ec16ccSHideki Saito   // First operand should refer to the loop id itself.
256f2ec16ccSHideki Saito   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
257f2ec16ccSHideki Saito   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
258f2ec16ccSHideki Saito 
259f2ec16ccSHideki Saito   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
260f2ec16ccSHideki Saito     const MDString *S = nullptr;
261f2ec16ccSHideki Saito     SmallVector<Metadata *, 4> Args;
262f2ec16ccSHideki Saito 
263f2ec16ccSHideki Saito     // The expected hint is either a MDString or a MDNode with the first
264f2ec16ccSHideki Saito     // operand a MDString.
265f2ec16ccSHideki Saito     if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
266f2ec16ccSHideki Saito       if (!MD || MD->getNumOperands() == 0)
267f2ec16ccSHideki Saito         continue;
268f2ec16ccSHideki Saito       S = dyn_cast<MDString>(MD->getOperand(0));
269f2ec16ccSHideki Saito       for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
270f2ec16ccSHideki Saito         Args.push_back(MD->getOperand(i));
271f2ec16ccSHideki Saito     } else {
272f2ec16ccSHideki Saito       S = dyn_cast<MDString>(LoopID->getOperand(i));
273f2ec16ccSHideki Saito       assert(Args.size() == 0 && "too many arguments for MDString");
274f2ec16ccSHideki Saito     }
275f2ec16ccSHideki Saito 
276f2ec16ccSHideki Saito     if (!S)
277f2ec16ccSHideki Saito       continue;
278f2ec16ccSHideki Saito 
279f2ec16ccSHideki Saito     // Check if the hint starts with the loop metadata prefix.
280f2ec16ccSHideki Saito     StringRef Name = S->getString();
281f2ec16ccSHideki Saito     if (Args.size() == 1)
282f2ec16ccSHideki Saito       setHint(Name, Args[0]);
283f2ec16ccSHideki Saito   }
284f2ec16ccSHideki Saito }
285f2ec16ccSHideki Saito 
286f2ec16ccSHideki Saito void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
287f2ec16ccSHideki Saito   if (!Name.startswith(Prefix()))
288f2ec16ccSHideki Saito     return;
289f2ec16ccSHideki Saito   Name = Name.substr(Prefix().size(), StringRef::npos);
290f2ec16ccSHideki Saito 
291f2ec16ccSHideki Saito   const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
292f2ec16ccSHideki Saito   if (!C)
293f2ec16ccSHideki Saito     return;
294f2ec16ccSHideki Saito   unsigned Val = C->getZExtValue();
295f2ec16ccSHideki Saito 
29671bd59f0SDavid Sherwood   Hint *Hints[] = {&Width,        &Interleave, &Force,
29771bd59f0SDavid Sherwood                    &IsVectorized, &Predicate,  &Scalable};
298f2ec16ccSHideki Saito   for (auto H : Hints) {
299f2ec16ccSHideki Saito     if (Name == H->Name) {
300f2ec16ccSHideki Saito       if (H->validate(Val))
301f2ec16ccSHideki Saito         H->Value = Val;
302f2ec16ccSHideki Saito       else
303d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
304f2ec16ccSHideki Saito       break;
305f2ec16ccSHideki Saito     }
306f2ec16ccSHideki Saito   }
307f2ec16ccSHideki Saito }
308f2ec16ccSHideki Saito 
309f2ec16ccSHideki Saito // Return true if the inner loop \p Lp is uniform with regard to the outer loop
310f2ec16ccSHideki Saito // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
311f2ec16ccSHideki Saito // executing the inner loop will execute the same iterations). This check is
312f2ec16ccSHideki Saito // very constrained for now but it will be relaxed in the future. \p Lp is
313f2ec16ccSHideki Saito // considered uniform if it meets all the following conditions:
314f2ec16ccSHideki Saito //   1) it has a canonical IV (starting from 0 and with stride 1),
315f2ec16ccSHideki Saito //   2) its latch terminator is a conditional branch and,
316f2ec16ccSHideki Saito //   3) its latch condition is a compare instruction whose operands are the
317f2ec16ccSHideki Saito //      canonical IV and an OuterLp invariant.
318f2ec16ccSHideki Saito // This check doesn't take into account the uniformity of other conditions not
319f2ec16ccSHideki Saito // related to the loop latch because they don't affect the loop uniformity.
320f2ec16ccSHideki Saito //
321f2ec16ccSHideki Saito // NOTE: We decided to keep all these checks and its associated documentation
322f2ec16ccSHideki Saito // together so that we can easily have a picture of the current supported loop
323f2ec16ccSHideki Saito // nests. However, some of the current checks don't depend on \p OuterLp and
324f2ec16ccSHideki Saito // would be redundantly executed for each \p Lp if we invoked this function for
325f2ec16ccSHideki Saito // different candidate outer loops. This is not the case for now because we
326f2ec16ccSHideki Saito // don't currently have the infrastructure to evaluate multiple candidate outer
327f2ec16ccSHideki Saito // loops and \p OuterLp will be a fixed parameter while we only support explicit
328f2ec16ccSHideki Saito // outer loop vectorization. It's also very likely that these checks go away
329f2ec16ccSHideki Saito // before introducing the aforementioned infrastructure. However, if this is not
330f2ec16ccSHideki Saito // the case, we should move the \p OuterLp independent checks to a separate
331f2ec16ccSHideki Saito // function that is only executed once for each \p Lp.
332f2ec16ccSHideki Saito static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
333f2ec16ccSHideki Saito   assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
334f2ec16ccSHideki Saito 
335f2ec16ccSHideki Saito   // If Lp is the outer loop, it's uniform by definition.
336f2ec16ccSHideki Saito   if (Lp == OuterLp)
337f2ec16ccSHideki Saito     return true;
338f2ec16ccSHideki Saito   assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
339f2ec16ccSHideki Saito 
340f2ec16ccSHideki Saito   // 1.
341f2ec16ccSHideki Saito   PHINode *IV = Lp->getCanonicalInductionVariable();
342f2ec16ccSHideki Saito   if (!IV) {
343d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
344f2ec16ccSHideki Saito     return false;
345f2ec16ccSHideki Saito   }
346f2ec16ccSHideki Saito 
347f2ec16ccSHideki Saito   // 2.
348f2ec16ccSHideki Saito   BasicBlock *Latch = Lp->getLoopLatch();
349f2ec16ccSHideki Saito   auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
350f2ec16ccSHideki Saito   if (!LatchBr || LatchBr->isUnconditional()) {
351d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
352f2ec16ccSHideki Saito     return false;
353f2ec16ccSHideki Saito   }
354f2ec16ccSHideki Saito 
355f2ec16ccSHideki Saito   // 3.
356f2ec16ccSHideki Saito   auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
357f2ec16ccSHideki Saito   if (!LatchCmp) {
358d34e60caSNicola Zaghen     LLVM_DEBUG(
359d34e60caSNicola Zaghen         dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
360f2ec16ccSHideki Saito     return false;
361f2ec16ccSHideki Saito   }
362f2ec16ccSHideki Saito 
363f2ec16ccSHideki Saito   Value *CondOp0 = LatchCmp->getOperand(0);
364f2ec16ccSHideki Saito   Value *CondOp1 = LatchCmp->getOperand(1);
365f2ec16ccSHideki Saito   Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
366f2ec16ccSHideki Saito   if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
367f2ec16ccSHideki Saito       !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
368d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
369f2ec16ccSHideki Saito     return false;
370f2ec16ccSHideki Saito   }
371f2ec16ccSHideki Saito 
372f2ec16ccSHideki Saito   return true;
373f2ec16ccSHideki Saito }
374f2ec16ccSHideki Saito 
375f2ec16ccSHideki Saito // Return true if \p Lp and all its nested loops are uniform with regard to \p
376f2ec16ccSHideki Saito // OuterLp.
377f2ec16ccSHideki Saito static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
378f2ec16ccSHideki Saito   if (!isUniformLoop(Lp, OuterLp))
379f2ec16ccSHideki Saito     return false;
380f2ec16ccSHideki Saito 
381f2ec16ccSHideki Saito   // Check if nested loops are uniform.
382f2ec16ccSHideki Saito   for (Loop *SubLp : *Lp)
383f2ec16ccSHideki Saito     if (!isUniformLoopNest(SubLp, OuterLp))
384f2ec16ccSHideki Saito       return false;
385f2ec16ccSHideki Saito 
386f2ec16ccSHideki Saito   return true;
387f2ec16ccSHideki Saito }
388f2ec16ccSHideki Saito 
3895f8f34e4SAdrian Prantl /// Check whether it is safe to if-convert this phi node.
390f2ec16ccSHideki Saito ///
391f2ec16ccSHideki Saito /// Phi nodes with constant expressions that can trap are not safe to if
392f2ec16ccSHideki Saito /// convert.
393f2ec16ccSHideki Saito static bool canIfConvertPHINodes(BasicBlock *BB) {
394f2ec16ccSHideki Saito   for (PHINode &Phi : BB->phis()) {
395f2ec16ccSHideki Saito     for (Value *V : Phi.incoming_values())
396f2ec16ccSHideki Saito       if (auto *C = dyn_cast<Constant>(V))
397f2ec16ccSHideki Saito         if (C->canTrap())
398f2ec16ccSHideki Saito           return false;
399f2ec16ccSHideki Saito   }
400f2ec16ccSHideki Saito   return true;
401f2ec16ccSHideki Saito }
402f2ec16ccSHideki Saito 
403f2ec16ccSHideki Saito static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
404f2ec16ccSHideki Saito   if (Ty->isPointerTy())
405f2ec16ccSHideki Saito     return DL.getIntPtrType(Ty);
406f2ec16ccSHideki Saito 
407f2ec16ccSHideki Saito   // It is possible that char's or short's overflow when we ask for the loop's
408f2ec16ccSHideki Saito   // trip count, work around this by changing the type size.
409f2ec16ccSHideki Saito   if (Ty->getScalarSizeInBits() < 32)
410f2ec16ccSHideki Saito     return Type::getInt32Ty(Ty->getContext());
411f2ec16ccSHideki Saito 
412f2ec16ccSHideki Saito   return Ty;
413f2ec16ccSHideki Saito }
414f2ec16ccSHideki Saito 
415f2ec16ccSHideki Saito static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
416f2ec16ccSHideki Saito   Ty0 = convertPointerToIntegerType(DL, Ty0);
417f2ec16ccSHideki Saito   Ty1 = convertPointerToIntegerType(DL, Ty1);
418f2ec16ccSHideki Saito   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
419f2ec16ccSHideki Saito     return Ty0;
420f2ec16ccSHideki Saito   return Ty1;
421f2ec16ccSHideki Saito }
422f2ec16ccSHideki Saito 
4235f8f34e4SAdrian Prantl /// Check that the instruction has outside loop users and is not an
424f2ec16ccSHideki Saito /// identified reduction variable.
425f2ec16ccSHideki Saito static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
426f2ec16ccSHideki Saito                                SmallPtrSetImpl<Value *> &AllowedExit) {
42760a1e4ddSAnna Thomas   // Reductions, Inductions and non-header phis are allowed to have exit users. All
428f2ec16ccSHideki Saito   // other instructions must not have external users.
429f2ec16ccSHideki Saito   if (!AllowedExit.count(Inst))
430f2ec16ccSHideki Saito     // Check that all of the users of the loop are inside the BB.
431f2ec16ccSHideki Saito     for (User *U : Inst->users()) {
432f2ec16ccSHideki Saito       Instruction *UI = cast<Instruction>(U);
433f2ec16ccSHideki Saito       // This user may be a reduction exit value.
434f2ec16ccSHideki Saito       if (!TheLoop->contains(UI)) {
435d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
436f2ec16ccSHideki Saito         return true;
437f2ec16ccSHideki Saito       }
438f2ec16ccSHideki Saito     }
439f2ec16ccSHideki Saito   return false;
440f2ec16ccSHideki Saito }
441f2ec16ccSHideki Saito 
4424e5e042dSIgor Kirillov /// Returns true if A and B have same pointer operands or same SCEVs addresses
4434e5e042dSIgor Kirillov static bool storeToSameAddress(ScalarEvolution *SE, StoreInst *A,
4444e5e042dSIgor Kirillov                                StoreInst *B) {
4454e5e042dSIgor Kirillov   // Compare store
4464e5e042dSIgor Kirillov   if (A == B)
4474e5e042dSIgor Kirillov     return true;
4484e5e042dSIgor Kirillov 
4494e5e042dSIgor Kirillov   // Otherwise Compare pointers
4504e5e042dSIgor Kirillov   Value *APtr = A->getPointerOperand();
4514e5e042dSIgor Kirillov   Value *BPtr = B->getPointerOperand();
4524e5e042dSIgor Kirillov   if (APtr == BPtr)
4534e5e042dSIgor Kirillov     return true;
4544e5e042dSIgor Kirillov 
4554e5e042dSIgor Kirillov   // Otherwise compare address SCEVs
4564e5e042dSIgor Kirillov   if (SE->getSCEV(APtr) == SE->getSCEV(BPtr))
4574e5e042dSIgor Kirillov     return true;
4584e5e042dSIgor Kirillov 
4594e5e042dSIgor Kirillov   return false;
4604e5e042dSIgor Kirillov }
4614e5e042dSIgor Kirillov 
46245c46734SNikita Popov int LoopVectorizationLegality::isConsecutivePtr(Type *AccessTy,
46345c46734SNikita Popov                                                 Value *Ptr) const {
464f2ec16ccSHideki Saito   const ValueToValueMap &Strides =
465f2ec16ccSHideki Saito       getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
466f2ec16ccSHideki Saito 
4677bedae7dSHiroshi Yamauchi   Function *F = TheLoop->getHeader()->getParent();
4687bedae7dSHiroshi Yamauchi   bool OptForSize = F->hasOptSize() ||
4697bedae7dSHiroshi Yamauchi                     llvm::shouldOptimizeForSize(TheLoop->getHeader(), PSI, BFI,
4707bedae7dSHiroshi Yamauchi                                                 PGSOQueryType::IRPass);
4717bedae7dSHiroshi Yamauchi   bool CanAddPredicate = !OptForSize;
47245c46734SNikita Popov   int Stride = getPtrStride(PSE, AccessTy, Ptr, TheLoop, Strides,
47345c46734SNikita Popov                             CanAddPredicate, false);
474f2ec16ccSHideki Saito   if (Stride == 1 || Stride == -1)
475f2ec16ccSHideki Saito     return Stride;
476f2ec16ccSHideki Saito   return 0;
477f2ec16ccSHideki Saito }
478f2ec16ccSHideki Saito 
479f2ec16ccSHideki Saito bool LoopVectorizationLegality::isUniform(Value *V) {
480f2ec16ccSHideki Saito   return LAI->isUniform(V);
481f2ec16ccSHideki Saito }
482f2ec16ccSHideki Saito 
483f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeOuterLoop() {
48489c1e35fSStefanos Baziotis   assert(!TheLoop->isInnermost() && "We are not vectorizing an outer loop.");
485f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
486f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
487f2ec16ccSHideki Saito   bool Result = true;
488f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
489f2ec16ccSHideki Saito 
490f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
491f2ec16ccSHideki Saito     // Check whether the BB terminator is a BranchInst. Any other terminator is
492f2ec16ccSHideki Saito     // not supported yet.
493f2ec16ccSHideki Saito     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
494f2ec16ccSHideki Saito     if (!Br) {
4959e97caf5SRenato Golin       reportVectorizationFailure("Unsupported basic block terminator",
4969e97caf5SRenato Golin           "loop control flow is not understood by vectorizer",
497ec818d7fSHideki Saito           "CFGNotUnderstood", ORE, TheLoop);
498f2ec16ccSHideki Saito       if (DoExtraAnalysis)
499f2ec16ccSHideki Saito         Result = false;
500f2ec16ccSHideki Saito       else
501f2ec16ccSHideki Saito         return false;
502f2ec16ccSHideki Saito     }
503f2ec16ccSHideki Saito 
504f2ec16ccSHideki Saito     // Check whether the BranchInst is a supported one. Only unconditional
505f2ec16ccSHideki Saito     // branches, conditional branches with an outer loop invariant condition or
506f2ec16ccSHideki Saito     // backedges are supported.
5074e4ecae0SHideki Saito     // FIXME: We skip these checks when VPlan predication is enabled as we
5084e4ecae0SHideki Saito     // want to allow divergent branches. This whole check will be removed
5094e4ecae0SHideki Saito     // once VPlan predication is on by default.
510d1570194SFlorian Hahn     if (Br && Br->isConditional() &&
511f2ec16ccSHideki Saito         !TheLoop->isLoopInvariant(Br->getCondition()) &&
512f2ec16ccSHideki Saito         !LI->isLoopHeader(Br->getSuccessor(0)) &&
513f2ec16ccSHideki Saito         !LI->isLoopHeader(Br->getSuccessor(1))) {
5149e97caf5SRenato Golin       reportVectorizationFailure("Unsupported conditional branch",
5159e97caf5SRenato Golin           "loop control flow is not understood by vectorizer",
516ec818d7fSHideki Saito           "CFGNotUnderstood", ORE, TheLoop);
517f2ec16ccSHideki Saito       if (DoExtraAnalysis)
518f2ec16ccSHideki Saito         Result = false;
519f2ec16ccSHideki Saito       else
520f2ec16ccSHideki Saito         return false;
521f2ec16ccSHideki Saito     }
522f2ec16ccSHideki Saito   }
523f2ec16ccSHideki Saito 
524f2ec16ccSHideki Saito   // Check whether inner loops are uniform. At this point, we only support
525f2ec16ccSHideki Saito   // simple outer loops scenarios with uniform nested loops.
526f2ec16ccSHideki Saito   if (!isUniformLoopNest(TheLoop /*loop nest*/,
527f2ec16ccSHideki Saito                          TheLoop /*context outer loop*/)) {
5289e97caf5SRenato Golin     reportVectorizationFailure("Outer loop contains divergent loops",
5299e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
530ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
531f2ec16ccSHideki Saito     if (DoExtraAnalysis)
532f2ec16ccSHideki Saito       Result = false;
533f2ec16ccSHideki Saito     else
534f2ec16ccSHideki Saito       return false;
535f2ec16ccSHideki Saito   }
536f2ec16ccSHideki Saito 
537ea7f3035SHideki Saito   // Check whether we are able to set up outer loop induction.
538ea7f3035SHideki Saito   if (!setupOuterLoopInductions()) {
5399e97caf5SRenato Golin     reportVectorizationFailure("Unsupported outer loop Phi(s)",
5409e97caf5SRenato Golin                                "Unsupported outer loop Phi(s)",
541ec818d7fSHideki Saito                                "UnsupportedPhi", ORE, TheLoop);
542ea7f3035SHideki Saito     if (DoExtraAnalysis)
543ea7f3035SHideki Saito       Result = false;
544ea7f3035SHideki Saito     else
545ea7f3035SHideki Saito       return false;
546ea7f3035SHideki Saito   }
547ea7f3035SHideki Saito 
548f2ec16ccSHideki Saito   return Result;
549f2ec16ccSHideki Saito }
550f2ec16ccSHideki Saito 
551f2ec16ccSHideki Saito void LoopVectorizationLegality::addInductionPhi(
552f2ec16ccSHideki Saito     PHINode *Phi, const InductionDescriptor &ID,
553f2ec16ccSHideki Saito     SmallPtrSetImpl<Value *> &AllowedExit) {
554f2ec16ccSHideki Saito   Inductions[Phi] = ID;
555f2ec16ccSHideki Saito 
556f2ec16ccSHideki Saito   // In case this induction also comes with casts that we know we can ignore
557f2ec16ccSHideki Saito   // in the vectorized loop body, record them here. All casts could be recorded
558f2ec16ccSHideki Saito   // here for ignoring, but suffices to record only the first (as it is the
559f2ec16ccSHideki Saito   // only one that may bw used outside the cast sequence).
560f2ec16ccSHideki Saito   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
561f2ec16ccSHideki Saito   if (!Casts.empty())
562f2ec16ccSHideki Saito     InductionCastsToIgnore.insert(*Casts.begin());
563f2ec16ccSHideki Saito 
564f2ec16ccSHideki Saito   Type *PhiTy = Phi->getType();
565f2ec16ccSHideki Saito   const DataLayout &DL = Phi->getModule()->getDataLayout();
566f2ec16ccSHideki Saito 
567f2ec16ccSHideki Saito   // Get the widest type.
568f2ec16ccSHideki Saito   if (!PhiTy->isFloatingPointTy()) {
569f2ec16ccSHideki Saito     if (!WidestIndTy)
570f2ec16ccSHideki Saito       WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
571f2ec16ccSHideki Saito     else
572f2ec16ccSHideki Saito       WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
573f2ec16ccSHideki Saito   }
574f2ec16ccSHideki Saito 
575f2ec16ccSHideki Saito   // Int inductions are special because we only allow one IV.
576f2ec16ccSHideki Saito   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
577f2ec16ccSHideki Saito       ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
578f2ec16ccSHideki Saito       isa<Constant>(ID.getStartValue()) &&
579f2ec16ccSHideki Saito       cast<Constant>(ID.getStartValue())->isNullValue()) {
580f2ec16ccSHideki Saito 
581f2ec16ccSHideki Saito     // Use the phi node with the widest type as induction. Use the last
582f2ec16ccSHideki Saito     // one if there are multiple (no good reason for doing this other
583f2ec16ccSHideki Saito     // than it is expedient). We've checked that it begins at zero and
584f2ec16ccSHideki Saito     // steps by one, so this is a canonical induction variable.
585f2ec16ccSHideki Saito     if (!PrimaryInduction || PhiTy == WidestIndTy)
586f2ec16ccSHideki Saito       PrimaryInduction = Phi;
587f2ec16ccSHideki Saito   }
588f2ec16ccSHideki Saito 
589f2ec16ccSHideki Saito   // Both the PHI node itself, and the "post-increment" value feeding
590f2ec16ccSHideki Saito   // back into the PHI node may have external users.
591f2ec16ccSHideki Saito   // We can allow those uses, except if the SCEVs we have for them rely
592f2ec16ccSHideki Saito   // on predicates that only hold within the loop, since allowing the exit
5936a1dd77fSAnna Thomas   // currently means re-using this SCEV outside the loop (see PR33706 for more
5946a1dd77fSAnna Thomas   // details).
5955ba11503SPhilip Reames   if (PSE.getPredicate().isAlwaysTrue()) {
596f2ec16ccSHideki Saito     AllowedExit.insert(Phi);
597f2ec16ccSHideki Saito     AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
598f2ec16ccSHideki Saito   }
599f2ec16ccSHideki Saito 
600d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
601f2ec16ccSHideki Saito }
602f2ec16ccSHideki Saito 
603ea7f3035SHideki Saito bool LoopVectorizationLegality::setupOuterLoopInductions() {
604ea7f3035SHideki Saito   BasicBlock *Header = TheLoop->getHeader();
605ea7f3035SHideki Saito 
606ea7f3035SHideki Saito   // Returns true if a given Phi is a supported induction.
607ea7f3035SHideki Saito   auto isSupportedPhi = [&](PHINode &Phi) -> bool {
608ea7f3035SHideki Saito     InductionDescriptor ID;
609ea7f3035SHideki Saito     if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
610ea7f3035SHideki Saito         ID.getKind() == InductionDescriptor::IK_IntInduction) {
611ea7f3035SHideki Saito       addInductionPhi(&Phi, ID, AllowedExit);
612ea7f3035SHideki Saito       return true;
613ea7f3035SHideki Saito     } else {
614ea7f3035SHideki Saito       // Bail out for any Phi in the outer loop header that is not a supported
615ea7f3035SHideki Saito       // induction.
616ea7f3035SHideki Saito       LLVM_DEBUG(
617ea7f3035SHideki Saito           dbgs()
618ea7f3035SHideki Saito           << "LV: Found unsupported PHI for outer loop vectorization.\n");
619ea7f3035SHideki Saito       return false;
620ea7f3035SHideki Saito     }
621ea7f3035SHideki Saito   };
622ea7f3035SHideki Saito 
623ea7f3035SHideki Saito   if (llvm::all_of(Header->phis(), isSupportedPhi))
624ea7f3035SHideki Saito     return true;
625ea7f3035SHideki Saito   else
626ea7f3035SHideki Saito     return false;
627ea7f3035SHideki Saito }
628ea7f3035SHideki Saito 
62966c120f0SFrancesco Petrogalli /// Checks if a function is scalarizable according to the TLI, in
63066c120f0SFrancesco Petrogalli /// the sense that it should be vectorized and then expanded in
63166c120f0SFrancesco Petrogalli /// multiple scalar calls. This is represented in the
63266c120f0SFrancesco Petrogalli /// TLI via mappings that do not specify a vector name, as in the
63366c120f0SFrancesco Petrogalli /// following example:
63466c120f0SFrancesco Petrogalli ///
63566c120f0SFrancesco Petrogalli ///    const VecDesc VecIntrinsics[] = {
63666c120f0SFrancesco Petrogalli ///      {"llvm.phx.abs.i32", "", 4}
63766c120f0SFrancesco Petrogalli ///    };
63866c120f0SFrancesco Petrogalli static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI) {
63966c120f0SFrancesco Petrogalli   const StringRef ScalarName = CI.getCalledFunction()->getName();
64066c120f0SFrancesco Petrogalli   bool Scalarize = TLI.isFunctionVectorizable(ScalarName);
64166c120f0SFrancesco Petrogalli   // Check that all known VFs are not associated to a vector
64266c120f0SFrancesco Petrogalli   // function, i.e. the vector name is emty.
64301b87444SDavid Sherwood   if (Scalarize) {
64401b87444SDavid Sherwood     ElementCount WidestFixedVF, WidestScalableVF;
64501b87444SDavid Sherwood     TLI.getWidestVF(ScalarName, WidestFixedVF, WidestScalableVF);
64601b87444SDavid Sherwood     for (ElementCount VF = ElementCount::getFixed(2);
64701b87444SDavid Sherwood          ElementCount::isKnownLE(VF, WidestFixedVF); VF *= 2)
64866c120f0SFrancesco Petrogalli       Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
64901b87444SDavid Sherwood     for (ElementCount VF = ElementCount::getScalable(1);
65001b87444SDavid Sherwood          ElementCount::isKnownLE(VF, WidestScalableVF); VF *= 2)
65101b87444SDavid Sherwood       Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
65201b87444SDavid Sherwood     assert((WidestScalableVF.isZero() || !Scalarize) &&
65301b87444SDavid Sherwood            "Caller may decide to scalarize a variant using a scalable VF");
65466c120f0SFrancesco Petrogalli   }
65566c120f0SFrancesco Petrogalli   return Scalarize;
65666c120f0SFrancesco Petrogalli }
65766c120f0SFrancesco Petrogalli 
658f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeInstrs() {
659f2ec16ccSHideki Saito   BasicBlock *Header = TheLoop->getHeader();
660f2ec16ccSHideki Saito 
661f2ec16ccSHideki Saito   // For each block in the loop.
662f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
663f2ec16ccSHideki Saito     // Scan the instructions in the block and look for hazards.
664f2ec16ccSHideki Saito     for (Instruction &I : *BB) {
665f2ec16ccSHideki Saito       if (auto *Phi = dyn_cast<PHINode>(&I)) {
666f2ec16ccSHideki Saito         Type *PhiTy = Phi->getType();
667f2ec16ccSHideki Saito         // Check that this PHI type is allowed.
668f2ec16ccSHideki Saito         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
669f2ec16ccSHideki Saito             !PhiTy->isPointerTy()) {
6709e97caf5SRenato Golin           reportVectorizationFailure("Found a non-int non-pointer PHI",
6719e97caf5SRenato Golin                                      "loop control flow is not understood by vectorizer",
672ec818d7fSHideki Saito                                      "CFGNotUnderstood", ORE, TheLoop);
673f2ec16ccSHideki Saito           return false;
674f2ec16ccSHideki Saito         }
675f2ec16ccSHideki Saito 
676f2ec16ccSHideki Saito         // If this PHINode is not in the header block, then we know that we
677f2ec16ccSHideki Saito         // can convert it to select during if-conversion. No need to check if
678f2ec16ccSHideki Saito         // the PHIs in this block are induction or reduction variables.
679f2ec16ccSHideki Saito         if (BB != Header) {
68060a1e4ddSAnna Thomas           // Non-header phi nodes that have outside uses can be vectorized. Add
68160a1e4ddSAnna Thomas           // them to the list of allowed exits.
68260a1e4ddSAnna Thomas           // Unsafe cyclic dependencies with header phis are identified during
68360a1e4ddSAnna Thomas           // legalization for reduction, induction and first order
68460a1e4ddSAnna Thomas           // recurrences.
685dd18ce45SBjorn Pettersson           AllowedExit.insert(&I);
686f2ec16ccSHideki Saito           continue;
687f2ec16ccSHideki Saito         }
688f2ec16ccSHideki Saito 
689f2ec16ccSHideki Saito         // We only allow if-converted PHIs with exactly two incoming values.
690f2ec16ccSHideki Saito         if (Phi->getNumIncomingValues() != 2) {
6919e97caf5SRenato Golin           reportVectorizationFailure("Found an invalid PHI",
6929e97caf5SRenato Golin               "loop control flow is not understood by vectorizer",
693ec818d7fSHideki Saito               "CFGNotUnderstood", ORE, TheLoop, Phi);
694f2ec16ccSHideki Saito           return false;
695f2ec16ccSHideki Saito         }
696f2ec16ccSHideki Saito 
697f2ec16ccSHideki Saito         RecurrenceDescriptor RedDes;
698f2ec16ccSHideki Saito         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
6994e5e042dSIgor Kirillov                                                  DT, PSE.getSE())) {
700b3a33553SSanjay Patel           Requirements->addExactFPMathInst(RedDes.getExactFPMathInst());
701f2ec16ccSHideki Saito           AllowedExit.insert(RedDes.getLoopExitInstr());
702f2ec16ccSHideki Saito           Reductions[Phi] = RedDes;
703f2ec16ccSHideki Saito           continue;
704f2ec16ccSHideki Saito         }
705f2ec16ccSHideki Saito 
706b02b0ad8SAnna Thomas         // TODO: Instead of recording the AllowedExit, it would be good to record the
707b02b0ad8SAnna Thomas         // complementary set: NotAllowedExit. These include (but may not be
708b02b0ad8SAnna Thomas         // limited to):
709b02b0ad8SAnna Thomas         // 1. Reduction phis as they represent the one-before-last value, which
710b02b0ad8SAnna Thomas         // is not available when vectorized
711b02b0ad8SAnna Thomas         // 2. Induction phis and increment when SCEV predicates cannot be used
712b02b0ad8SAnna Thomas         // outside the loop - see addInductionPhi
713b02b0ad8SAnna Thomas         // 3. Non-Phis with outside uses when SCEV predicates cannot be used
714b02b0ad8SAnna Thomas         // outside the loop - see call to hasOutsideLoopUser in the non-phi
715b02b0ad8SAnna Thomas         // handling below
716b02b0ad8SAnna Thomas         // 4. FirstOrderRecurrence phis that can possibly be handled by
717b02b0ad8SAnna Thomas         // extraction.
718b02b0ad8SAnna Thomas         // By recording these, we can then reason about ways to vectorize each
719b02b0ad8SAnna Thomas         // of these NotAllowedExit.
720f2ec16ccSHideki Saito         InductionDescriptor ID;
721f2ec16ccSHideki Saito         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
722f2ec16ccSHideki Saito           addInductionPhi(Phi, ID, AllowedExit);
72336a489d1SSanjay Patel           Requirements->addExactFPMathInst(ID.getExactFPMathInst());
724f2ec16ccSHideki Saito           continue;
725f2ec16ccSHideki Saito         }
726f2ec16ccSHideki Saito 
727f2ec16ccSHideki Saito         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
728f2ec16ccSHideki Saito                                                          SinkAfter, DT)) {
7298e0c5f72SAyal Zaks           AllowedExit.insert(Phi);
730f2ec16ccSHideki Saito           FirstOrderRecurrences.insert(Phi);
731f2ec16ccSHideki Saito           continue;
732f2ec16ccSHideki Saito         }
733f2ec16ccSHideki Saito 
734f2ec16ccSHideki Saito         // As a last resort, coerce the PHI to a AddRec expression
735f2ec16ccSHideki Saito         // and re-try classifying it a an induction PHI.
736f2ec16ccSHideki Saito         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
737f2ec16ccSHideki Saito           addInductionPhi(Phi, ID, AllowedExit);
738f2ec16ccSHideki Saito           continue;
739f2ec16ccSHideki Saito         }
740f2ec16ccSHideki Saito 
7419e97caf5SRenato Golin         reportVectorizationFailure("Found an unidentified PHI",
7429e97caf5SRenato Golin             "value that could not be identified as "
7439e97caf5SRenato Golin             "reduction is used outside the loop",
744ec818d7fSHideki Saito             "NonReductionValueUsedOutsideLoop", ORE, TheLoop, Phi);
745f2ec16ccSHideki Saito         return false;
746f2ec16ccSHideki Saito       } // end of PHI handling
747f2ec16ccSHideki Saito 
748f2ec16ccSHideki Saito       // We handle calls that:
749f2ec16ccSHideki Saito       //   * Are debug info intrinsics.
750f2ec16ccSHideki Saito       //   * Have a mapping to an IR intrinsic.
751f2ec16ccSHideki Saito       //   * Have a vector version available.
752f2ec16ccSHideki Saito       auto *CI = dyn_cast<CallInst>(&I);
75366c120f0SFrancesco Petrogalli 
754f2ec16ccSHideki Saito       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
755f2ec16ccSHideki Saito           !isa<DbgInfoIntrinsic>(CI) &&
756f2ec16ccSHideki Saito           !(CI->getCalledFunction() && TLI &&
75766c120f0SFrancesco Petrogalli             (!VFDatabase::getMappings(*CI).empty() ||
75866c120f0SFrancesco Petrogalli              isTLIScalarize(*TLI, *CI)))) {
7597d65fe5cSSanjay Patel         // If the call is a recognized math libary call, it is likely that
7607d65fe5cSSanjay Patel         // we can vectorize it given loosened floating-point constraints.
7617d65fe5cSSanjay Patel         LibFunc Func;
7627d65fe5cSSanjay Patel         bool IsMathLibCall =
7637d65fe5cSSanjay Patel             TLI && CI->getCalledFunction() &&
7647d65fe5cSSanjay Patel             CI->getType()->isFloatingPointTy() &&
7657d65fe5cSSanjay Patel             TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
7667d65fe5cSSanjay Patel             TLI->hasOptimizedCodeGen(Func);
7677d65fe5cSSanjay Patel 
7687d65fe5cSSanjay Patel         if (IsMathLibCall) {
7697d65fe5cSSanjay Patel           // TODO: Ideally, we should not use clang-specific language here,
7707d65fe5cSSanjay Patel           // but it's hard to provide meaningful yet generic advice.
7717d65fe5cSSanjay Patel           // Also, should this be guarded by allowExtraAnalysis() and/or be part
7727d65fe5cSSanjay Patel           // of the returned info from isFunctionVectorizable()?
77366c120f0SFrancesco Petrogalli           reportVectorizationFailure(
77466c120f0SFrancesco Petrogalli               "Found a non-intrinsic callsite",
7759e97caf5SRenato Golin               "library call cannot be vectorized. "
7767d65fe5cSSanjay Patel               "Try compiling with -fno-math-errno, -ffast-math, "
7779e97caf5SRenato Golin               "or similar flags",
778ec818d7fSHideki Saito               "CantVectorizeLibcall", ORE, TheLoop, CI);
7797d65fe5cSSanjay Patel         } else {
7809e97caf5SRenato Golin           reportVectorizationFailure("Found a non-intrinsic callsite",
7819e97caf5SRenato Golin                                      "call instruction cannot be vectorized",
782ec818d7fSHideki Saito                                      "CantVectorizeLibcall", ORE, TheLoop, CI);
7837d65fe5cSSanjay Patel         }
784f2ec16ccSHideki Saito         return false;
785f2ec16ccSHideki Saito       }
786f2ec16ccSHideki Saito 
787a066f1f9SSimon Pilgrim       // Some intrinsics have scalar arguments and should be same in order for
788a066f1f9SSimon Pilgrim       // them to be vectorized (i.e. loop invariant).
789a066f1f9SSimon Pilgrim       if (CI) {
790f2ec16ccSHideki Saito         auto *SE = PSE.getSE();
791a066f1f9SSimon Pilgrim         Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
7924f0225f6SKazu Hirata         for (unsigned i = 0, e = CI->arg_size(); i != e; ++i)
7936f81903eSDavid Green           if (isVectorIntrinsicWithScalarOpAtArg(IntrinID, i)) {
794a066f1f9SSimon Pilgrim             if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(i)), TheLoop)) {
7959e97caf5SRenato Golin               reportVectorizationFailure("Found unvectorizable intrinsic",
7969e97caf5SRenato Golin                   "intrinsic instruction cannot be vectorized",
797ec818d7fSHideki Saito                   "CantVectorizeIntrinsic", ORE, TheLoop, CI);
798f2ec16ccSHideki Saito               return false;
799f2ec16ccSHideki Saito             }
800f2ec16ccSHideki Saito           }
801a066f1f9SSimon Pilgrim       }
802f2ec16ccSHideki Saito 
803f2ec16ccSHideki Saito       // Check that the instruction return type is vectorizable.
804f2ec16ccSHideki Saito       // Also, we can't vectorize extractelement instructions.
805f2ec16ccSHideki Saito       if ((!VectorType::isValidElementType(I.getType()) &&
806f2ec16ccSHideki Saito            !I.getType()->isVoidTy()) ||
807f2ec16ccSHideki Saito           isa<ExtractElementInst>(I)) {
8089e97caf5SRenato Golin         reportVectorizationFailure("Found unvectorizable type",
8099e97caf5SRenato Golin             "instruction return type cannot be vectorized",
810ec818d7fSHideki Saito             "CantVectorizeInstructionReturnType", ORE, TheLoop, &I);
811f2ec16ccSHideki Saito         return false;
812f2ec16ccSHideki Saito       }
813f2ec16ccSHideki Saito 
814f2ec16ccSHideki Saito       // Check that the stored type is vectorizable.
815f2ec16ccSHideki Saito       if (auto *ST = dyn_cast<StoreInst>(&I)) {
816f2ec16ccSHideki Saito         Type *T = ST->getValueOperand()->getType();
817f2ec16ccSHideki Saito         if (!VectorType::isValidElementType(T)) {
8189e97caf5SRenato Golin           reportVectorizationFailure("Store instruction cannot be vectorized",
8199e97caf5SRenato Golin                                      "store instruction cannot be vectorized",
820ec818d7fSHideki Saito                                      "CantVectorizeStore", ORE, TheLoop, ST);
821f2ec16ccSHideki Saito           return false;
822f2ec16ccSHideki Saito         }
823f2ec16ccSHideki Saito 
8246452bdd2SWarren Ristow         // For nontemporal stores, check that a nontemporal vector version is
8256452bdd2SWarren Ristow         // supported on the target.
8266452bdd2SWarren Ristow         if (ST->getMetadata(LLVMContext::MD_nontemporal)) {
8276452bdd2SWarren Ristow           // Arbitrarily try a vector of 2 elements.
8286913812aSFangrui Song           auto *VecTy = FixedVectorType::get(T, /*NumElts=*/2);
8296452bdd2SWarren Ristow           assert(VecTy && "did not find vectorized version of stored type");
83052e98f62SNikita Popov           if (!TTI->isLegalNTStore(VecTy, ST->getAlign())) {
8316452bdd2SWarren Ristow             reportVectorizationFailure(
8326452bdd2SWarren Ristow                 "nontemporal store instruction cannot be vectorized",
8336452bdd2SWarren Ristow                 "nontemporal store instruction cannot be vectorized",
834ec818d7fSHideki Saito                 "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
8356452bdd2SWarren Ristow             return false;
8366452bdd2SWarren Ristow           }
8376452bdd2SWarren Ristow         }
8386452bdd2SWarren Ristow 
8396452bdd2SWarren Ristow       } else if (auto *LD = dyn_cast<LoadInst>(&I)) {
8406452bdd2SWarren Ristow         if (LD->getMetadata(LLVMContext::MD_nontemporal)) {
8416452bdd2SWarren Ristow           // For nontemporal loads, check that a nontemporal vector version is
8426452bdd2SWarren Ristow           // supported on the target (arbitrarily try a vector of 2 elements).
8436913812aSFangrui Song           auto *VecTy = FixedVectorType::get(I.getType(), /*NumElts=*/2);
8446452bdd2SWarren Ristow           assert(VecTy && "did not find vectorized version of load type");
84552e98f62SNikita Popov           if (!TTI->isLegalNTLoad(VecTy, LD->getAlign())) {
8466452bdd2SWarren Ristow             reportVectorizationFailure(
8476452bdd2SWarren Ristow                 "nontemporal load instruction cannot be vectorized",
8486452bdd2SWarren Ristow                 "nontemporal load instruction cannot be vectorized",
849ec818d7fSHideki Saito                 "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
8506452bdd2SWarren Ristow             return false;
8516452bdd2SWarren Ristow           }
8526452bdd2SWarren Ristow         }
8536452bdd2SWarren Ristow 
854f2ec16ccSHideki Saito         // FP instructions can allow unsafe algebra, thus vectorizable by
855f2ec16ccSHideki Saito         // non-IEEE-754 compliant SIMD units.
856f2ec16ccSHideki Saito         // This applies to floating-point math operations and calls, not memory
857f2ec16ccSHideki Saito         // operations, shuffles, or casts, as they don't change precision or
858f2ec16ccSHideki Saito         // semantics.
859f2ec16ccSHideki Saito       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
860f2ec16ccSHideki Saito                  !I.isFast()) {
861d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
862f2ec16ccSHideki Saito         Hints->setPotentiallyUnsafe();
863f2ec16ccSHideki Saito       }
864f2ec16ccSHideki Saito 
865f2ec16ccSHideki Saito       // Reduction instructions are allowed to have exit users.
866f2ec16ccSHideki Saito       // All other instructions must not have external users.
867f2ec16ccSHideki Saito       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
868b02b0ad8SAnna Thomas         // We can safely vectorize loops where instructions within the loop are
869b02b0ad8SAnna Thomas         // used outside the loop only if the SCEV predicates within the loop is
870b02b0ad8SAnna Thomas         // same as outside the loop. Allowing the exit means reusing the SCEV
871b02b0ad8SAnna Thomas         // outside the loop.
8725ba11503SPhilip Reames         if (PSE.getPredicate().isAlwaysTrue()) {
873b02b0ad8SAnna Thomas           AllowedExit.insert(&I);
874b02b0ad8SAnna Thomas           continue;
875b02b0ad8SAnna Thomas         }
8769e97caf5SRenato Golin         reportVectorizationFailure("Value cannot be used outside the loop",
8779e97caf5SRenato Golin                                    "value cannot be used outside the loop",
878ec818d7fSHideki Saito                                    "ValueUsedOutsideLoop", ORE, TheLoop, &I);
879f2ec16ccSHideki Saito         return false;
880f2ec16ccSHideki Saito       }
881f2ec16ccSHideki Saito     } // next instr.
882f2ec16ccSHideki Saito   }
883f2ec16ccSHideki Saito 
884f2ec16ccSHideki Saito   if (!PrimaryInduction) {
885f2ec16ccSHideki Saito     if (Inductions.empty()) {
8869e97caf5SRenato Golin       reportVectorizationFailure("Did not find one integer induction var",
8879e97caf5SRenato Golin           "loop induction variable could not be identified",
888ec818d7fSHideki Saito           "NoInductionVariable", ORE, TheLoop);
889f2ec16ccSHideki Saito       return false;
8904f27730eSWarren Ristow     } else if (!WidestIndTy) {
8919e97caf5SRenato Golin       reportVectorizationFailure("Did not find one integer induction var",
8929e97caf5SRenato Golin           "integer loop induction variable could not be identified",
893ec818d7fSHideki Saito           "NoIntegerInductionVariable", ORE, TheLoop);
8944f27730eSWarren Ristow       return false;
8959e97caf5SRenato Golin     } else {
8969e97caf5SRenato Golin       LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
897f2ec16ccSHideki Saito     }
898f2ec16ccSHideki Saito   }
899f2ec16ccSHideki Saito 
9009d24933fSFlorian Hahn   // For first order recurrences, we use the previous value (incoming value from
9019d24933fSFlorian Hahn   // the latch) to check if it dominates all users of the recurrence. Bail out
9029d24933fSFlorian Hahn   // if we have to sink such an instruction for another recurrence, as the
9039d24933fSFlorian Hahn   // dominance requirement may not hold after sinking.
9049d24933fSFlorian Hahn   BasicBlock *LoopLatch = TheLoop->getLoopLatch();
9059d24933fSFlorian Hahn   if (any_of(FirstOrderRecurrences, [LoopLatch, this](const PHINode *Phi) {
9069d24933fSFlorian Hahn         Instruction *V =
9079d24933fSFlorian Hahn             cast<Instruction>(Phi->getIncomingValueForBlock(LoopLatch));
9089d24933fSFlorian Hahn         return SinkAfter.find(V) != SinkAfter.end();
9099d24933fSFlorian Hahn       }))
9109d24933fSFlorian Hahn     return false;
9119d24933fSFlorian Hahn 
912f2ec16ccSHideki Saito   // Now we know the widest induction type, check if our found induction
913f2ec16ccSHideki Saito   // is the same size. If it's not, unset it here and InnerLoopVectorizer
914f2ec16ccSHideki Saito   // will create another.
915f2ec16ccSHideki Saito   if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
916f2ec16ccSHideki Saito     PrimaryInduction = nullptr;
917f2ec16ccSHideki Saito 
918f2ec16ccSHideki Saito   return true;
919f2ec16ccSHideki Saito }
920f2ec16ccSHideki Saito 
921f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeMemory() {
922f2ec16ccSHideki Saito   LAI = &(*GetLAA)(*TheLoop);
923f2ec16ccSHideki Saito   const OptimizationRemarkAnalysis *LAR = LAI->getReport();
924f2ec16ccSHideki Saito   if (LAR) {
925f2ec16ccSHideki Saito     ORE->emit([&]() {
926f2ec16ccSHideki Saito       return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
927f2ec16ccSHideki Saito                                         "loop not vectorized: ", *LAR);
928f2ec16ccSHideki Saito     });
929f2ec16ccSHideki Saito   }
930287d39ddSPaul Walker 
931f2ec16ccSHideki Saito   if (!LAI->canVectorizeMemory())
932f2ec16ccSHideki Saito     return false;
933f2ec16ccSHideki Saito 
9344e5e042dSIgor Kirillov   // We can vectorize stores to invariant address when final reduction value is
9354e5e042dSIgor Kirillov   // guaranteed to be stored at the end of the loop. Also, if decision to
9364e5e042dSIgor Kirillov   // vectorize loop is made, runtime checks are added so as to make sure that
9374e5e042dSIgor Kirillov   // invariant address won't alias with any other objects.
9384e5e042dSIgor Kirillov   if (!LAI->getStoresToInvariantAddresses().empty()) {
9394e5e042dSIgor Kirillov     // For each invariant address, check its last stored value is unconditional.
9404e5e042dSIgor Kirillov     for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
9414e5e042dSIgor Kirillov       if (isInvariantStoreOfReduction(SI) &&
9424e5e042dSIgor Kirillov           blockNeedsPredication(SI->getParent())) {
9434e5e042dSIgor Kirillov         reportVectorizationFailure(
9444e5e042dSIgor Kirillov             "We don't allow storing to uniform addresses",
9454e5e042dSIgor Kirillov             "write of conditional recurring variant value to a loop "
9464e5e042dSIgor Kirillov             "invariant address could not be vectorized",
947ec818d7fSHideki Saito             "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
948f2ec16ccSHideki Saito         return false;
949f2ec16ccSHideki Saito       }
9504e5e042dSIgor Kirillov     }
9514e5e042dSIgor Kirillov 
9524e5e042dSIgor Kirillov     if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
9534e5e042dSIgor Kirillov       // For each invariant address, check its last stored value is the result
9544e5e042dSIgor Kirillov       // of one of our reductions.
9554e5e042dSIgor Kirillov       //
9564e5e042dSIgor Kirillov       // We do not check if dependence with loads exists because they are
9574e5e042dSIgor Kirillov       // currently rejected earlier in LoopAccessInfo::analyzeLoop. In case this
9584e5e042dSIgor Kirillov       // behaviour changes we have to modify this code.
9594e5e042dSIgor Kirillov       ScalarEvolution *SE = PSE.getSE();
9604e5e042dSIgor Kirillov       SmallVector<StoreInst *, 4> UnhandledStores;
9614e5e042dSIgor Kirillov       for (StoreInst *SI : LAI->getStoresToInvariantAddresses()) {
9624e5e042dSIgor Kirillov         if (isInvariantStoreOfReduction(SI)) {
9634e5e042dSIgor Kirillov           // Earlier stores to this address are effectively deadcode.
9644e5e042dSIgor Kirillov           // With opaque pointers it is possible for one pointer to be used with
9654e5e042dSIgor Kirillov           // different sizes of stored values:
9664e5e042dSIgor Kirillov           //    store i32 0, ptr %x
9674e5e042dSIgor Kirillov           //    store i8 0, ptr %x
9684e5e042dSIgor Kirillov           // The latest store doesn't complitely overwrite the first one in the
9694e5e042dSIgor Kirillov           // example. That is why we have to make sure that types of stored
9704e5e042dSIgor Kirillov           // values are same.
9714e5e042dSIgor Kirillov           // TODO: Check that bitwidth of unhandled store is smaller then the
9724e5e042dSIgor Kirillov           // one that overwrites it and add a test.
9734e5e042dSIgor Kirillov           erase_if(UnhandledStores, [SE, SI](StoreInst *I) {
9744e5e042dSIgor Kirillov             return storeToSameAddress(SE, SI, I) &&
9754e5e042dSIgor Kirillov                    I->getValueOperand()->getType() ==
9764e5e042dSIgor Kirillov                        SI->getValueOperand()->getType();
9774e5e042dSIgor Kirillov           });
9784e5e042dSIgor Kirillov           continue;
9794e5e042dSIgor Kirillov         }
9804e5e042dSIgor Kirillov         UnhandledStores.push_back(SI);
9814e5e042dSIgor Kirillov       }
9824e5e042dSIgor Kirillov 
9834e5e042dSIgor Kirillov       bool IsOK = UnhandledStores.empty();
9844e5e042dSIgor Kirillov       // TODO: we should also validate against InvariantMemSets.
9854e5e042dSIgor Kirillov       if (!IsOK) {
9864e5e042dSIgor Kirillov         reportVectorizationFailure(
9874e5e042dSIgor Kirillov             "We don't allow storing to uniform addresses",
9884e5e042dSIgor Kirillov             "write to a loop invariant address could not "
9894e5e042dSIgor Kirillov             "be vectorized",
9904e5e042dSIgor Kirillov             "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
9914e5e042dSIgor Kirillov         return false;
9924e5e042dSIgor Kirillov       }
9934e5e042dSIgor Kirillov     }
9944e5e042dSIgor Kirillov   }
995287d39ddSPaul Walker 
996f2ec16ccSHideki Saito   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
9975ba11503SPhilip Reames   PSE.addPredicate(LAI->getPSE().getPredicate());
998f2ec16ccSHideki Saito   return true;
999f2ec16ccSHideki Saito }
1000f2ec16ccSHideki Saito 
10019f76a852SKerry McLaughlin bool LoopVectorizationLegality::canVectorizeFPMath(
10029f76a852SKerry McLaughlin     bool EnableStrictReductions) {
10039f76a852SKerry McLaughlin 
10049f76a852SKerry McLaughlin   // First check if there is any ExactFP math or if we allow reassociations
10059f76a852SKerry McLaughlin   if (!Requirements->getExactFPInst() || Hints->allowReordering())
10069f76a852SKerry McLaughlin     return true;
10079f76a852SKerry McLaughlin 
10089f76a852SKerry McLaughlin   // If the above is false, we have ExactFPMath & do not allow reordering.
10099f76a852SKerry McLaughlin   // If the EnableStrictReductions flag is set, first check if we have any
10109f76a852SKerry McLaughlin   // Exact FP induction vars, which we cannot vectorize.
10119f76a852SKerry McLaughlin   if (!EnableStrictReductions ||
10129f76a852SKerry McLaughlin       any_of(getInductionVars(), [&](auto &Induction) -> bool {
10139f76a852SKerry McLaughlin         InductionDescriptor IndDesc = Induction.second;
10149f76a852SKerry McLaughlin         return IndDesc.getExactFPMathInst();
10159f76a852SKerry McLaughlin       }))
10169f76a852SKerry McLaughlin     return false;
10179f76a852SKerry McLaughlin 
10189f76a852SKerry McLaughlin   // We can now only vectorize if all reductions with Exact FP math also
10199f76a852SKerry McLaughlin   // have the isOrdered flag set, which indicates that we can move the
1020*6bb40552SMalhar Jajoo   // reduction operations in-loop.
10219f76a852SKerry McLaughlin   return (all_of(getReductionVars(), [&](auto &Reduction) -> bool {
10225e6bfb66SSimon Pilgrim     const RecurrenceDescriptor &RdxDesc = Reduction.second;
1023*6bb40552SMalhar Jajoo     return !RdxDesc.hasExactFPMath() || RdxDesc.isOrdered();
10249f76a852SKerry McLaughlin   }));
10259f76a852SKerry McLaughlin }
10269f76a852SKerry McLaughlin 
10274e5e042dSIgor Kirillov bool LoopVectorizationLegality::isInvariantStoreOfReduction(StoreInst *SI) {
10284e5e042dSIgor Kirillov   return any_of(getReductionVars(), [&](auto &Reduction) -> bool {
10294e5e042dSIgor Kirillov     const RecurrenceDescriptor &RdxDesc = Reduction.second;
10304e5e042dSIgor Kirillov     return RdxDesc.IntermediateStore == SI;
10314e5e042dSIgor Kirillov   });
10324e5e042dSIgor Kirillov }
10334e5e042dSIgor Kirillov 
10344e5e042dSIgor Kirillov bool LoopVectorizationLegality::isInvariantAddressOfReduction(Value *V) {
10354e5e042dSIgor Kirillov   return any_of(getReductionVars(), [&](auto &Reduction) -> bool {
10364e5e042dSIgor Kirillov     const RecurrenceDescriptor &RdxDesc = Reduction.second;
10374e5e042dSIgor Kirillov     if (!RdxDesc.IntermediateStore)
10384e5e042dSIgor Kirillov       return false;
10394e5e042dSIgor Kirillov 
10404e5e042dSIgor Kirillov     ScalarEvolution *SE = PSE.getSE();
10414e5e042dSIgor Kirillov     Value *InvariantAddress = RdxDesc.IntermediateStore->getPointerOperand();
10424e5e042dSIgor Kirillov     return V == InvariantAddress ||
10434e5e042dSIgor Kirillov            SE->getSCEV(V) == SE->getSCEV(InvariantAddress);
10444e5e042dSIgor Kirillov   });
10454e5e042dSIgor Kirillov }
10464e5e042dSIgor Kirillov 
1047d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isInductionPhi(const Value *V) const {
1048f2ec16ccSHideki Saito   Value *In0 = const_cast<Value *>(V);
1049f2ec16ccSHideki Saito   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
1050f2ec16ccSHideki Saito   if (!PN)
1051f2ec16ccSHideki Saito     return false;
1052f2ec16ccSHideki Saito 
1053f2ec16ccSHideki Saito   return Inductions.count(PN);
1054f2ec16ccSHideki Saito }
1055f2ec16ccSHideki Saito 
1056978883d2SFlorian Hahn const InductionDescriptor *
1057978883d2SFlorian Hahn LoopVectorizationLegality::getIntOrFpInductionDescriptor(PHINode *Phi) const {
1058978883d2SFlorian Hahn   if (!isInductionPhi(Phi))
1059978883d2SFlorian Hahn     return nullptr;
1060978883d2SFlorian Hahn   auto &ID = getInductionVars().find(Phi)->second;
1061978883d2SFlorian Hahn   if (ID.getKind() == InductionDescriptor::IK_IntInduction ||
1062978883d2SFlorian Hahn       ID.getKind() == InductionDescriptor::IK_FpInduction)
1063978883d2SFlorian Hahn     return &ID;
1064978883d2SFlorian Hahn   return nullptr;
1065978883d2SFlorian Hahn }
1066978883d2SFlorian Hahn 
106746432a00SFlorian Hahn const InductionDescriptor *
106846432a00SFlorian Hahn LoopVectorizationLegality::getPointerInductionDescriptor(PHINode *Phi) const {
106946432a00SFlorian Hahn   if (!isInductionPhi(Phi))
107046432a00SFlorian Hahn     return nullptr;
107146432a00SFlorian Hahn   auto &ID = getInductionVars().find(Phi)->second;
107246432a00SFlorian Hahn   if (ID.getKind() == InductionDescriptor::IK_PtrInduction)
107346432a00SFlorian Hahn     return &ID;
107446432a00SFlorian Hahn   return nullptr;
107546432a00SFlorian Hahn }
107646432a00SFlorian Hahn 
1077d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isCastedInductionVariable(
1078d74a8a78SFlorian Hahn     const Value *V) const {
1079f2ec16ccSHideki Saito   auto *Inst = dyn_cast<Instruction>(V);
1080f2ec16ccSHideki Saito   return (Inst && InductionCastsToIgnore.count(Inst));
1081f2ec16ccSHideki Saito }
1082f2ec16ccSHideki Saito 
1083d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isInductionVariable(const Value *V) const {
1084f2ec16ccSHideki Saito   return isInductionPhi(V) || isCastedInductionVariable(V);
1085f2ec16ccSHideki Saito }
1086f2ec16ccSHideki Saito 
1087d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isFirstOrderRecurrence(
1088d74a8a78SFlorian Hahn     const PHINode *Phi) const {
1089f2ec16ccSHideki Saito   return FirstOrderRecurrences.count(Phi);
1090f2ec16ccSHideki Saito }
1091f2ec16ccSHideki Saito 
1092f82966d1SSander de Smalen bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) const {
1093f2ec16ccSHideki Saito   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1094f2ec16ccSHideki Saito }
1095f2ec16ccSHideki Saito 
1096f2ec16ccSHideki Saito bool LoopVectorizationLegality::blockCanBePredicated(
1097bda8fbe2SSjoerd Meijer     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs,
1098bda8fbe2SSjoerd Meijer     SmallPtrSetImpl<const Instruction *> &MaskedOp,
10994f01122cSJoachim Meyer     SmallPtrSetImpl<Instruction *> &ConditionalAssumes) const {
1100f2ec16ccSHideki Saito   for (Instruction &I : *BB) {
1101f2ec16ccSHideki Saito     // Check that we don't have a constant expression that can trap as operand.
1102f2ec16ccSHideki Saito     for (Value *Operand : I.operands()) {
1103f2ec16ccSHideki Saito       if (auto *C = dyn_cast<Constant>(Operand))
1104f2ec16ccSHideki Saito         if (C->canTrap())
1105f2ec16ccSHideki Saito           return false;
1106f2ec16ccSHideki Saito     }
110723c11380SFlorian Hahn 
110823c11380SFlorian Hahn     // We can predicate blocks with calls to assume, as long as we drop them in
110923c11380SFlorian Hahn     // case we flatten the CFG via predication.
111023c11380SFlorian Hahn     if (match(&I, m_Intrinsic<Intrinsic::assume>())) {
111123c11380SFlorian Hahn       ConditionalAssumes.insert(&I);
111223c11380SFlorian Hahn       continue;
111323c11380SFlorian Hahn     }
111423c11380SFlorian Hahn 
1115121cac01SJeroen Dobbelaere     // Do not let llvm.experimental.noalias.scope.decl block the vectorization.
1116121cac01SJeroen Dobbelaere     // TODO: there might be cases that it should block the vectorization. Let's
1117121cac01SJeroen Dobbelaere     // ignore those for now.
1118c83cff45SNikita Popov     if (isa<NoAliasScopeDeclInst>(&I))
1119121cac01SJeroen Dobbelaere       continue;
1120121cac01SJeroen Dobbelaere 
1121f2ec16ccSHideki Saito     // We might be able to hoist the load.
1122f2ec16ccSHideki Saito     if (I.mayReadFromMemory()) {
1123f2ec16ccSHideki Saito       auto *LI = dyn_cast<LoadInst>(&I);
1124f2ec16ccSHideki Saito       if (!LI)
1125f2ec16ccSHideki Saito         return false;
1126f2ec16ccSHideki Saito       if (!SafePtrs.count(LI->getPointerOperand())) {
1127f2ec16ccSHideki Saito         MaskedOp.insert(LI);
1128f2ec16ccSHideki Saito         continue;
1129f2ec16ccSHideki Saito       }
1130f2ec16ccSHideki Saito     }
1131f2ec16ccSHideki Saito 
1132f2ec16ccSHideki Saito     if (I.mayWriteToMemory()) {
1133f2ec16ccSHideki Saito       auto *SI = dyn_cast<StoreInst>(&I);
1134f2ec16ccSHideki Saito       if (!SI)
1135f2ec16ccSHideki Saito         return false;
1136f2ec16ccSHideki Saito       // Predicated store requires some form of masking:
1137f2ec16ccSHideki Saito       // 1) masked store HW instruction,
1138f2ec16ccSHideki Saito       // 2) emulation via load-blend-store (only if safe and legal to do so,
1139f2ec16ccSHideki Saito       //    be aware on the race conditions), or
1140f2ec16ccSHideki Saito       // 3) element-by-element predicate check and scalar store.
1141f2ec16ccSHideki Saito       MaskedOp.insert(SI);
1142f2ec16ccSHideki Saito       continue;
1143f2ec16ccSHideki Saito     }
1144f2ec16ccSHideki Saito     if (I.mayThrow())
1145f2ec16ccSHideki Saito       return false;
1146f2ec16ccSHideki Saito   }
1147f2ec16ccSHideki Saito 
1148f2ec16ccSHideki Saito   return true;
1149f2ec16ccSHideki Saito }
1150f2ec16ccSHideki Saito 
1151f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1152f2ec16ccSHideki Saito   if (!EnableIfConversion) {
11539e97caf5SRenato Golin     reportVectorizationFailure("If-conversion is disabled",
11549e97caf5SRenato Golin                                "if-conversion is disabled",
1155ec818d7fSHideki Saito                                "IfConversionDisabled",
1156ec818d7fSHideki Saito                                ORE, TheLoop);
1157f2ec16ccSHideki Saito     return false;
1158f2ec16ccSHideki Saito   }
1159f2ec16ccSHideki Saito 
1160f2ec16ccSHideki Saito   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1161f2ec16ccSHideki Saito 
1162cf3b5559SPhilip Reames   // A list of pointers which are known to be dereferenceable within scope of
1163cf3b5559SPhilip Reames   // the loop body for each iteration of the loop which executes.  That is,
1164cf3b5559SPhilip Reames   // the memory pointed to can be dereferenced (with the access size implied by
1165cf3b5559SPhilip Reames   // the value's type) unconditionally within the loop header without
1166cf3b5559SPhilip Reames   // introducing a new fault.
11673bbc71d6SSjoerd Meijer   SmallPtrSet<Value *, 8> SafePointers;
1168f2ec16ccSHideki Saito 
1169f2ec16ccSHideki Saito   // Collect safe addresses.
1170f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
11717403569bSPhilip Reames     if (!blockNeedsPredication(BB)) {
1172f2ec16ccSHideki Saito       for (Instruction &I : *BB)
1173f2ec16ccSHideki Saito         if (auto *Ptr = getLoadStorePointerOperand(&I))
11743bbc71d6SSjoerd Meijer           SafePointers.insert(Ptr);
11757403569bSPhilip Reames       continue;
11767403569bSPhilip Reames     }
11777403569bSPhilip Reames 
11787403569bSPhilip Reames     // For a block which requires predication, a address may be safe to access
11797403569bSPhilip Reames     // in the loop w/o predication if we can prove dereferenceability facts
11807403569bSPhilip Reames     // sufficient to ensure it'll never fault within the loop. For the moment,
11817403569bSPhilip Reames     // we restrict this to loads; stores are more complicated due to
11827403569bSPhilip Reames     // concurrency restrictions.
11837403569bSPhilip Reames     ScalarEvolution &SE = *PSE.getSE();
11847403569bSPhilip Reames     for (Instruction &I : *BB) {
11857403569bSPhilip Reames       LoadInst *LI = dyn_cast<LoadInst>(&I);
1186467e5cf4SJoe Ellis       if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) &&
11877403569bSPhilip Reames           isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT))
11883bbc71d6SSjoerd Meijer         SafePointers.insert(LI->getPointerOperand());
11897403569bSPhilip Reames     }
1190f2ec16ccSHideki Saito   }
1191f2ec16ccSHideki Saito 
1192f2ec16ccSHideki Saito   // Collect the blocks that need predication.
1193f2ec16ccSHideki Saito   BasicBlock *Header = TheLoop->getHeader();
1194f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
1195f2ec16ccSHideki Saito     // We don't support switch statements inside loops.
1196f2ec16ccSHideki Saito     if (!isa<BranchInst>(BB->getTerminator())) {
11979e97caf5SRenato Golin       reportVectorizationFailure("Loop contains a switch statement",
11989e97caf5SRenato Golin                                  "loop contains a switch statement",
1199ec818d7fSHideki Saito                                  "LoopContainsSwitch", ORE, TheLoop,
1200ec818d7fSHideki Saito                                  BB->getTerminator());
1201f2ec16ccSHideki Saito       return false;
1202f2ec16ccSHideki Saito     }
1203f2ec16ccSHideki Saito 
1204f2ec16ccSHideki Saito     // We must be able to predicate all blocks that need to be predicated.
1205f2ec16ccSHideki Saito     if (blockNeedsPredication(BB)) {
1206bda8fbe2SSjoerd Meijer       if (!blockCanBePredicated(BB, SafePointers, MaskedOp,
1207bda8fbe2SSjoerd Meijer                                 ConditionalAssumes)) {
12089e97caf5SRenato Golin         reportVectorizationFailure(
12099e97caf5SRenato Golin             "Control flow cannot be substituted for a select",
12109e97caf5SRenato Golin             "control flow cannot be substituted for a select",
1211ec818d7fSHideki Saito             "NoCFGForSelect", ORE, TheLoop,
1212ec818d7fSHideki Saito             BB->getTerminator());
1213f2ec16ccSHideki Saito         return false;
1214f2ec16ccSHideki Saito       }
1215f2ec16ccSHideki Saito     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
12169e97caf5SRenato Golin       reportVectorizationFailure(
12179e97caf5SRenato Golin           "Control flow cannot be substituted for a select",
12189e97caf5SRenato Golin           "control flow cannot be substituted for a select",
1219ec818d7fSHideki Saito           "NoCFGForSelect", ORE, TheLoop,
1220ec818d7fSHideki Saito           BB->getTerminator());
1221f2ec16ccSHideki Saito       return false;
1222f2ec16ccSHideki Saito     }
1223f2ec16ccSHideki Saito   }
1224f2ec16ccSHideki Saito 
1225f2ec16ccSHideki Saito   // We can if-convert this loop.
1226f2ec16ccSHideki Saito   return true;
1227f2ec16ccSHideki Saito }
1228f2ec16ccSHideki Saito 
1229f2ec16ccSHideki Saito // Helper function to canVectorizeLoopNestCFG.
1230f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
1231f2ec16ccSHideki Saito                                                     bool UseVPlanNativePath) {
123289c1e35fSStefanos Baziotis   assert((UseVPlanNativePath || Lp->isInnermost()) &&
1233f2ec16ccSHideki Saito          "VPlan-native path is not enabled.");
1234f2ec16ccSHideki Saito 
1235f2ec16ccSHideki Saito   // TODO: ORE should be improved to show more accurate information when an
1236f2ec16ccSHideki Saito   // outer loop can't be vectorized because a nested loop is not understood or
1237f2ec16ccSHideki Saito   // legal. Something like: "outer_loop_location: loop not vectorized:
1238f2ec16ccSHideki Saito   // (inner_loop_location) loop control flow is not understood by vectorizer".
1239f2ec16ccSHideki Saito 
1240f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1241f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1242f2ec16ccSHideki Saito   bool Result = true;
1243f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1244f2ec16ccSHideki Saito 
1245f2ec16ccSHideki Saito   // We must have a loop in canonical form. Loops with indirectbr in them cannot
1246f2ec16ccSHideki Saito   // be canonicalized.
1247f2ec16ccSHideki Saito   if (!Lp->getLoopPreheader()) {
12489e97caf5SRenato Golin     reportVectorizationFailure("Loop doesn't have a legal pre-header",
12499e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1250ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
1251f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1252f2ec16ccSHideki Saito       Result = false;
1253f2ec16ccSHideki Saito     else
1254f2ec16ccSHideki Saito       return false;
1255f2ec16ccSHideki Saito   }
1256f2ec16ccSHideki Saito 
1257f2ec16ccSHideki Saito   // We must have a single backedge.
1258f2ec16ccSHideki Saito   if (Lp->getNumBackEdges() != 1) {
12599e97caf5SRenato Golin     reportVectorizationFailure("The loop must have a single backedge",
12609e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1261ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
1262f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1263f2ec16ccSHideki Saito       Result = false;
1264f2ec16ccSHideki Saito     else
1265f2ec16ccSHideki Saito       return false;
1266f2ec16ccSHideki Saito   }
1267f2ec16ccSHideki Saito 
1268f2ec16ccSHideki Saito   return Result;
1269f2ec16ccSHideki Saito }
1270f2ec16ccSHideki Saito 
1271f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1272f2ec16ccSHideki Saito     Loop *Lp, bool UseVPlanNativePath) {
1273f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1274f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1275f2ec16ccSHideki Saito   bool Result = true;
1276f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1277f2ec16ccSHideki Saito   if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1278f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1279f2ec16ccSHideki Saito       Result = false;
1280f2ec16ccSHideki Saito     else
1281f2ec16ccSHideki Saito       return false;
1282f2ec16ccSHideki Saito   }
1283f2ec16ccSHideki Saito 
1284f2ec16ccSHideki Saito   // Recursively check whether the loop control flow of nested loops is
1285f2ec16ccSHideki Saito   // understood.
1286f2ec16ccSHideki Saito   for (Loop *SubLp : *Lp)
1287f2ec16ccSHideki Saito     if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1288f2ec16ccSHideki Saito       if (DoExtraAnalysis)
1289f2ec16ccSHideki Saito         Result = false;
1290f2ec16ccSHideki Saito       else
1291f2ec16ccSHideki Saito         return false;
1292f2ec16ccSHideki Saito     }
1293f2ec16ccSHideki Saito 
1294f2ec16ccSHideki Saito   return Result;
1295f2ec16ccSHideki Saito }
1296f2ec16ccSHideki Saito 
1297f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1298f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1299f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1300f2ec16ccSHideki Saito   bool Result = true;
1301f2ec16ccSHideki Saito 
1302f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1303f2ec16ccSHideki Saito   // Check whether the loop-related control flow in the loop nest is expected by
1304f2ec16ccSHideki Saito   // vectorizer.
1305f2ec16ccSHideki Saito   if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1306f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1307f2ec16ccSHideki Saito       Result = false;
1308f2ec16ccSHideki Saito     else
1309f2ec16ccSHideki Saito       return false;
1310f2ec16ccSHideki Saito   }
1311f2ec16ccSHideki Saito 
1312f2ec16ccSHideki Saito   // We need to have a loop header.
1313d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1314f2ec16ccSHideki Saito                     << '\n');
1315f2ec16ccSHideki Saito 
1316f2ec16ccSHideki Saito   // Specific checks for outer loops. We skip the remaining legal checks at this
1317f2ec16ccSHideki Saito   // point because they don't support outer loops.
131889c1e35fSStefanos Baziotis   if (!TheLoop->isInnermost()) {
1319f2ec16ccSHideki Saito     assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1320f2ec16ccSHideki Saito 
1321f2ec16ccSHideki Saito     if (!canVectorizeOuterLoop()) {
13229e97caf5SRenato Golin       reportVectorizationFailure("Unsupported outer loop",
13239e97caf5SRenato Golin                                  "unsupported outer loop",
1324ec818d7fSHideki Saito                                  "UnsupportedOuterLoop",
1325ec818d7fSHideki Saito                                  ORE, TheLoop);
1326f2ec16ccSHideki Saito       // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1327f2ec16ccSHideki Saito       // outer loops.
1328f2ec16ccSHideki Saito       return false;
1329f2ec16ccSHideki Saito     }
1330f2ec16ccSHideki Saito 
1331d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1332f2ec16ccSHideki Saito     return Result;
1333f2ec16ccSHideki Saito   }
1334f2ec16ccSHideki Saito 
133589c1e35fSStefanos Baziotis   assert(TheLoop->isInnermost() && "Inner loop expected.");
1336f2ec16ccSHideki Saito   // Check if we can if-convert non-single-bb loops.
1337f2ec16ccSHideki Saito   unsigned NumBlocks = TheLoop->getNumBlocks();
1338f2ec16ccSHideki Saito   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1339d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1340f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1341f2ec16ccSHideki Saito       Result = false;
1342f2ec16ccSHideki Saito     else
1343f2ec16ccSHideki Saito       return false;
1344f2ec16ccSHideki Saito   }
1345f2ec16ccSHideki Saito 
1346f2ec16ccSHideki Saito   // Check if we can vectorize the instructions and CFG in this loop.
1347f2ec16ccSHideki Saito   if (!canVectorizeInstrs()) {
1348d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1349f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1350f2ec16ccSHideki Saito       Result = false;
1351f2ec16ccSHideki Saito     else
1352f2ec16ccSHideki Saito       return false;
1353f2ec16ccSHideki Saito   }
1354f2ec16ccSHideki Saito 
1355f2ec16ccSHideki Saito   // Go over each instruction and look at memory deps.
1356f2ec16ccSHideki Saito   if (!canVectorizeMemory()) {
1357d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1358f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1359f2ec16ccSHideki Saito       Result = false;
1360f2ec16ccSHideki Saito     else
1361f2ec16ccSHideki Saito       return false;
1362f2ec16ccSHideki Saito   }
1363f2ec16ccSHideki Saito 
1364d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
1365f2ec16ccSHideki Saito                     << (LAI->getRuntimePointerChecking()->Need
1366f2ec16ccSHideki Saito                             ? " (with a runtime bound check)"
1367f2ec16ccSHideki Saito                             : "")
1368f2ec16ccSHideki Saito                     << "!\n");
1369f2ec16ccSHideki Saito 
1370f2ec16ccSHideki Saito   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
1371f2ec16ccSHideki Saito   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
1372f2ec16ccSHideki Saito     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
1373f2ec16ccSHideki Saito 
13745ba11503SPhilip Reames   if (PSE.getPredicate().getComplexity() > SCEVThreshold) {
13759e97caf5SRenato Golin     reportVectorizationFailure("Too many SCEV checks needed",
13769e97caf5SRenato Golin         "Too many SCEV assumptions need to be made and checked at runtime",
1377ec818d7fSHideki Saito         "TooManySCEVRunTimeChecks", ORE, TheLoop);
1378f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1379f2ec16ccSHideki Saito       Result = false;
1380f2ec16ccSHideki Saito     else
1381f2ec16ccSHideki Saito       return false;
1382f2ec16ccSHideki Saito   }
1383f2ec16ccSHideki Saito 
1384f2ec16ccSHideki Saito   // Okay! We've done all the tests. If any have failed, return false. Otherwise
1385f2ec16ccSHideki Saito   // we can vectorize, and at this point we don't have any other mem analysis
1386f2ec16ccSHideki Saito   // which may limit our maximum vectorization factor, so just return true with
1387f2ec16ccSHideki Saito   // no restrictions.
1388f2ec16ccSHideki Saito   return Result;
1389f2ec16ccSHideki Saito }
1390f2ec16ccSHideki Saito 
1391d57d73daSDorit Nuzman bool LoopVectorizationLegality::prepareToFoldTailByMasking() {
1392b0b5312eSAyal Zaks 
1393b0b5312eSAyal Zaks   LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
1394b0b5312eSAyal Zaks 
1395d15df0edSAyal Zaks   SmallPtrSet<const Value *, 8> ReductionLiveOuts;
1396b0b5312eSAyal Zaks 
1397d0d38df0SDavid Green   for (auto &Reduction : getReductionVars())
1398d15df0edSAyal Zaks     ReductionLiveOuts.insert(Reduction.second.getLoopExitInstr());
1399d15df0edSAyal Zaks 
1400d15df0edSAyal Zaks   // TODO: handle non-reduction outside users when tail is folded by masking.
1401b0b5312eSAyal Zaks   for (auto *AE : AllowedExit) {
1402d15df0edSAyal Zaks     // Check that all users of allowed exit values are inside the loop or
1403d15df0edSAyal Zaks     // are the live-out of a reduction.
1404d15df0edSAyal Zaks     if (ReductionLiveOuts.count(AE))
1405d15df0edSAyal Zaks       continue;
1406b0b5312eSAyal Zaks     for (User *U : AE->users()) {
1407b0b5312eSAyal Zaks       Instruction *UI = cast<Instruction>(U);
1408b0b5312eSAyal Zaks       if (TheLoop->contains(UI))
1409b0b5312eSAyal Zaks         continue;
1410bda8fbe2SSjoerd Meijer       LLVM_DEBUG(
1411bda8fbe2SSjoerd Meijer           dbgs()
1412bda8fbe2SSjoerd Meijer           << "LV: Cannot fold tail by masking, loop has an outside user for "
1413bda8fbe2SSjoerd Meijer           << *UI << "\n");
1414b0b5312eSAyal Zaks       return false;
1415b0b5312eSAyal Zaks     }
1416b0b5312eSAyal Zaks   }
1417b0b5312eSAyal Zaks 
1418b0b5312eSAyal Zaks   // The list of pointers that we can safely read and write to remains empty.
1419b0b5312eSAyal Zaks   SmallPtrSet<Value *, 8> SafePointers;
1420b0b5312eSAyal Zaks 
1421bda8fbe2SSjoerd Meijer   SmallPtrSet<const Instruction *, 8> TmpMaskedOp;
1422bda8fbe2SSjoerd Meijer   SmallPtrSet<Instruction *, 8> TmpConditionalAssumes;
1423bda8fbe2SSjoerd Meijer 
1424b0b5312eSAyal Zaks   // Check and mark all blocks for predication, including those that ordinarily
1425b0b5312eSAyal Zaks   // do not need predication such as the header block.
1426b0b5312eSAyal Zaks   for (BasicBlock *BB : TheLoop->blocks()) {
1427bda8fbe2SSjoerd Meijer     if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp,
14284f01122cSJoachim Meyer                               TmpConditionalAssumes)) {
1429bda8fbe2SSjoerd Meijer       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as requested.\n");
1430b0b5312eSAyal Zaks       return false;
1431b0b5312eSAyal Zaks     }
1432b0b5312eSAyal Zaks   }
1433b0b5312eSAyal Zaks 
1434b0b5312eSAyal Zaks   LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
1435bda8fbe2SSjoerd Meijer 
1436bda8fbe2SSjoerd Meijer   MaskedOp.insert(TmpMaskedOp.begin(), TmpMaskedOp.end());
1437bda8fbe2SSjoerd Meijer   ConditionalAssumes.insert(TmpConditionalAssumes.begin(),
1438bda8fbe2SSjoerd Meijer                             TmpConditionalAssumes.end());
1439bda8fbe2SSjoerd Meijer 
1440b0b5312eSAyal Zaks   return true;
1441b0b5312eSAyal Zaks }
1442b0b5312eSAyal Zaks 
1443f2ec16ccSHideki Saito } // namespace llvm
1444