1f2ec16ccSHideki Saito //===- LoopVectorizationLegality.cpp --------------------------------------===//
2f2ec16ccSHideki Saito //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f2ec16ccSHideki Saito //
7f2ec16ccSHideki Saito //===----------------------------------------------------------------------===//
8f2ec16ccSHideki Saito //
9f2ec16ccSHideki Saito // This file provides loop vectorization legality analysis. Original code
10f2ec16ccSHideki Saito // resided in LoopVectorize.cpp for a long time.
11f2ec16ccSHideki Saito //
12f2ec16ccSHideki Saito // At this point, it is implemented as a utility class, not as an analysis
13f2ec16ccSHideki Saito // pass. It should be easy to create an analysis pass around it if there
14f2ec16ccSHideki Saito // is a need (but D45420 needs to happen first).
15f2ec16ccSHideki Saito //
16cc529285SSimon Pilgrim 
17f2ec16ccSHideki Saito #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
187403569bSPhilip Reames #include "llvm/Analysis/Loads.h"
19a5f1f9c9SSimon Pilgrim #include "llvm/Analysis/LoopInfo.h"
20cc529285SSimon Pilgrim #include "llvm/Analysis/TargetLibraryInfo.h"
217403569bSPhilip Reames #include "llvm/Analysis/ValueTracking.h"
22f2ec16ccSHideki Saito #include "llvm/Analysis/VectorUtils.h"
23f2ec16ccSHideki Saito #include "llvm/IR/IntrinsicInst.h"
2423c11380SFlorian Hahn #include "llvm/IR/PatternMatch.h"
257bedae7dSHiroshi Yamauchi #include "llvm/Transforms/Utils/SizeOpts.h"
2623c11380SFlorian Hahn #include "llvm/Transforms/Vectorize/LoopVectorize.h"
27f2ec16ccSHideki Saito 
28f2ec16ccSHideki Saito using namespace llvm;
2923c11380SFlorian Hahn using namespace PatternMatch;
30f2ec16ccSHideki Saito 
31f2ec16ccSHideki Saito #define LV_NAME "loop-vectorize"
32f2ec16ccSHideki Saito #define DEBUG_TYPE LV_NAME
33f2ec16ccSHideki Saito 
344e4ecae0SHideki Saito extern cl::opt<bool> EnableVPlanPredication;
354e4ecae0SHideki Saito 
36f2ec16ccSHideki Saito static cl::opt<bool>
37f2ec16ccSHideki Saito     EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
38f2ec16ccSHideki Saito                        cl::desc("Enable if-conversion during vectorization."));
39f2ec16ccSHideki Saito 
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 
58*b1ff20fdSSander de Smalen static cl::opt<LoopVectorizeHints::ScalableForceKind>
59*b1ff20fdSSander de Smalen     ForceScalableVectorization(
60*b1ff20fdSSander 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."),
67*b1ff20fdSSander de Smalen             clEnumValN(
68*b1ff20fdSSander de Smalen                 LoopVectorizeHints::SK_PreferScalable, "on",
694f86aa65SSander de Smalen                 "Scalable vectorization is available and favored when the "
704f86aa65SSander de Smalen                 "cost is inconclusive.")));
714f86aa65SSander de Smalen 
72f2ec16ccSHideki Saito /// Maximum vectorization interleave count.
73f2ec16ccSHideki Saito static const unsigned MaxInterleaveFactor = 16;
74f2ec16ccSHideki Saito 
75f2ec16ccSHideki Saito namespace llvm {
76f2ec16ccSHideki Saito 
77f2ec16ccSHideki Saito bool LoopVectorizeHints::Hint::validate(unsigned Val) {
78f2ec16ccSHideki Saito   switch (Kind) {
79f2ec16ccSHideki Saito   case HK_WIDTH:
80f2ec16ccSHideki Saito     return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
81ddb3b26aSBardia Mahjour   case HK_INTERLEAVE:
82f2ec16ccSHideki Saito     return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
83f2ec16ccSHideki Saito   case HK_FORCE:
84f2ec16ccSHideki Saito     return (Val <= 1);
85f2ec16ccSHideki Saito   case HK_ISVECTORIZED:
8620b198ecSSjoerd Meijer   case HK_PREDICATE:
8771bd59f0SDavid Sherwood   case HK_SCALABLE:
88f2ec16ccSHideki Saito     return (Val == 0 || Val == 1);
89f2ec16ccSHideki Saito   }
90f2ec16ccSHideki Saito   return false;
91f2ec16ccSHideki Saito }
92f2ec16ccSHideki Saito 
93d4eb13c8SMichael Kruse LoopVectorizeHints::LoopVectorizeHints(const Loop *L,
94d4eb13c8SMichael Kruse                                        bool InterleaveOnlyWhenForced,
95*b1ff20fdSSander de Smalen                                        OptimizationRemarkEmitter &ORE,
96*b1ff20fdSSander de Smalen                                        const TargetTransformInfo *TTI)
97f2ec16ccSHideki Saito     : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
98ddb3b26aSBardia Mahjour       Interleave("interleave.count", InterleaveOnlyWhenForced, HK_INTERLEAVE),
99f2ec16ccSHideki Saito       Force("vectorize.enable", FK_Undefined, HK_FORCE),
10020b198ecSSjoerd Meijer       IsVectorized("isvectorized", 0, HK_ISVECTORIZED),
10171bd59f0SDavid Sherwood       Predicate("vectorize.predicate.enable", FK_Undefined, HK_PREDICATE),
1024f86aa65SSander de Smalen       Scalable("vectorize.scalable.enable", SK_Unspecified, HK_SCALABLE),
1034f86aa65SSander de Smalen       TheLoop(L), ORE(ORE) {
104f2ec16ccSHideki Saito   // Populate values with existing loop metadata.
105f2ec16ccSHideki Saito   getHintsFromMetadata();
106f2ec16ccSHideki Saito 
107f2ec16ccSHideki Saito   // force-vector-interleave overrides DisableInterleaving.
108f2ec16ccSHideki Saito   if (VectorizerParams::isInterleaveForced())
109f2ec16ccSHideki Saito     Interleave.Value = VectorizerParams::VectorizationInterleave;
110f2ec16ccSHideki Saito 
111*b1ff20fdSSander de Smalen   // If the metadata doesn't explicitly specify whether to enable scalable
112*b1ff20fdSSander de Smalen   // vectorization, then decide based on the following criteria (increasing
113*b1ff20fdSSander de Smalen   // level of priority):
114*b1ff20fdSSander de Smalen   //  - Target default
115*b1ff20fdSSander de Smalen   //  - Metadata width
116*b1ff20fdSSander de Smalen   //  - Force option (always overrides)
117*b1ff20fdSSander de Smalen   if ((LoopVectorizeHints::ScalableForceKind)Scalable.Value == SK_Unspecified) {
118*b1ff20fdSSander de Smalen     if (TTI)
119*b1ff20fdSSander de Smalen       Scalable.Value = TTI->enableScalableVectorization() ? SK_PreferScalable
120*b1ff20fdSSander de Smalen                                                           : SK_FixedWidthOnly;
121*b1ff20fdSSander de Smalen 
122*b1ff20fdSSander de Smalen     if (Width.Value)
1234f86aa65SSander de Smalen       // If the width is set, but the metadata says nothing about the scalable
1244f86aa65SSander de Smalen       // property, then assume it concerns only a fixed-width UserVF.
1254f86aa65SSander de Smalen       // If width is not set, the flag takes precedence.
126*b1ff20fdSSander de Smalen       Scalable.Value = SK_FixedWidthOnly;
127*b1ff20fdSSander de Smalen   }
128*b1ff20fdSSander de Smalen 
129*b1ff20fdSSander de Smalen   // If the flag is set to force any use of scalable vectors, override the loop
130*b1ff20fdSSander de Smalen   // hints.
131*b1ff20fdSSander de Smalen   if (ForceScalableVectorization.getValue() !=
132*b1ff20fdSSander de Smalen       LoopVectorizeHints::SK_Unspecified)
133*b1ff20fdSSander de Smalen     Scalable.Value = ForceScalableVectorization.getValue();
134*b1ff20fdSSander de Smalen 
135*b1ff20fdSSander de Smalen   // Scalable vectorization is disabled if no preference is specified.
136*b1ff20fdSSander de Smalen   if ((LoopVectorizeHints::ScalableForceKind)Scalable.Value == SK_Unspecified)
1374f86aa65SSander de Smalen     Scalable.Value = SK_FixedWidthOnly;
1384f86aa65SSander de Smalen 
139f2ec16ccSHideki Saito   if (IsVectorized.Value != 1)
140f2ec16ccSHideki Saito     // If the vectorization width and interleaving count are both 1 then
141f2ec16ccSHideki Saito     // consider the loop to have been already vectorized because there's
142f2ec16ccSHideki Saito     // nothing more that we can do.
14371bd59f0SDavid Sherwood     IsVectorized.Value =
144ddb3b26aSBardia Mahjour         getWidth() == ElementCount::getFixed(1) && getInterleave() == 1;
145ddb3b26aSBardia Mahjour   LLVM_DEBUG(if (InterleaveOnlyWhenForced && getInterleave() == 1) dbgs()
146f2ec16ccSHideki Saito              << "LV: Interleaving disabled by the pass manager\n");
147f2ec16ccSHideki Saito }
148f2ec16ccSHideki Saito 
14977a614a6SMichael Kruse void LoopVectorizeHints::setAlreadyVectorized() {
15077a614a6SMichael Kruse   LLVMContext &Context = TheLoop->getHeader()->getContext();
15177a614a6SMichael Kruse 
15277a614a6SMichael Kruse   MDNode *IsVectorizedMD = MDNode::get(
15377a614a6SMichael Kruse       Context,
15477a614a6SMichael Kruse       {MDString::get(Context, "llvm.loop.isvectorized"),
15577a614a6SMichael Kruse        ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))});
15677a614a6SMichael Kruse   MDNode *LoopID = TheLoop->getLoopID();
15777a614a6SMichael Kruse   MDNode *NewLoopID =
15877a614a6SMichael Kruse       makePostTransformationMetadata(Context, LoopID,
15977a614a6SMichael Kruse                                      {Twine(Prefix(), "vectorize.").str(),
16077a614a6SMichael Kruse                                       Twine(Prefix(), "interleave.").str()},
16177a614a6SMichael Kruse                                      {IsVectorizedMD});
16277a614a6SMichael Kruse   TheLoop->setLoopID(NewLoopID);
16377a614a6SMichael Kruse 
16477a614a6SMichael Kruse   // Update internal cache.
16577a614a6SMichael Kruse   IsVectorized.Value = 1;
16677a614a6SMichael Kruse }
16777a614a6SMichael Kruse 
168d4eb13c8SMichael Kruse bool LoopVectorizeHints::allowVectorization(
169d4eb13c8SMichael Kruse     Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
170f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Disabled) {
171d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
172f2ec16ccSHideki Saito     emitRemarkWithHints();
173f2ec16ccSHideki Saito     return false;
174f2ec16ccSHideki Saito   }
175f2ec16ccSHideki Saito 
176d4eb13c8SMichael Kruse   if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
177d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
178f2ec16ccSHideki Saito     emitRemarkWithHints();
179f2ec16ccSHideki Saito     return false;
180f2ec16ccSHideki Saito   }
181f2ec16ccSHideki Saito 
182f2ec16ccSHideki Saito   if (getIsVectorized() == 1) {
183d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
184f2ec16ccSHideki Saito     // FIXME: Add interleave.disable metadata. This will allow
185f2ec16ccSHideki Saito     // vectorize.disable to be used without disabling the pass and errors
186f2ec16ccSHideki Saito     // to differentiate between disabled vectorization and a width of 1.
187f2ec16ccSHideki Saito     ORE.emit([&]() {
188f2ec16ccSHideki Saito       return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
189f2ec16ccSHideki Saito                                         "AllDisabled", L->getStartLoc(),
190f2ec16ccSHideki Saito                                         L->getHeader())
191f2ec16ccSHideki Saito              << "loop not vectorized: vectorization and interleaving are "
192f2ec16ccSHideki Saito                 "explicitly disabled, or the loop has already been "
193f2ec16ccSHideki Saito                 "vectorized";
194f2ec16ccSHideki Saito     });
195f2ec16ccSHideki Saito     return false;
196f2ec16ccSHideki Saito   }
197f2ec16ccSHideki Saito 
198f2ec16ccSHideki Saito   return true;
199f2ec16ccSHideki Saito }
200f2ec16ccSHideki Saito 
201f2ec16ccSHideki Saito void LoopVectorizeHints::emitRemarkWithHints() const {
202f2ec16ccSHideki Saito   using namespace ore;
203f2ec16ccSHideki Saito 
204f2ec16ccSHideki Saito   ORE.emit([&]() {
205f2ec16ccSHideki Saito     if (Force.Value == LoopVectorizeHints::FK_Disabled)
206f2ec16ccSHideki Saito       return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
207f2ec16ccSHideki Saito                                       TheLoop->getStartLoc(),
208f2ec16ccSHideki Saito                                       TheLoop->getHeader())
209f2ec16ccSHideki Saito              << "loop not vectorized: vectorization is explicitly disabled";
210f2ec16ccSHideki Saito     else {
211f2ec16ccSHideki Saito       OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
212f2ec16ccSHideki Saito                                  TheLoop->getStartLoc(), TheLoop->getHeader());
213f2ec16ccSHideki Saito       R << "loop not vectorized";
214f2ec16ccSHideki Saito       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
215f2ec16ccSHideki Saito         R << " (Force=" << NV("Force", true);
216f2ec16ccSHideki Saito         if (Width.Value != 0)
21771bd59f0SDavid Sherwood           R << ", Vector Width=" << NV("VectorWidth", getWidth());
218ddb3b26aSBardia Mahjour         if (getInterleave() != 0)
219ddb3b26aSBardia Mahjour           R << ", Interleave Count=" << NV("InterleaveCount", getInterleave());
220f2ec16ccSHideki Saito         R << ")";
221f2ec16ccSHideki Saito       }
222f2ec16ccSHideki Saito       return R;
223f2ec16ccSHideki Saito     }
224f2ec16ccSHideki Saito   });
225f2ec16ccSHideki Saito }
226f2ec16ccSHideki Saito 
227f2ec16ccSHideki Saito const char *LoopVectorizeHints::vectorizeAnalysisPassName() const {
22871bd59f0SDavid Sherwood   if (getWidth() == ElementCount::getFixed(1))
229f2ec16ccSHideki Saito     return LV_NAME;
230f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Disabled)
231f2ec16ccSHideki Saito     return LV_NAME;
23271bd59f0SDavid Sherwood   if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth().isZero())
233f2ec16ccSHideki Saito     return LV_NAME;
234f2ec16ccSHideki Saito   return OptimizationRemarkAnalysis::AlwaysPrint;
235f2ec16ccSHideki Saito }
236f2ec16ccSHideki Saito 
2379f76a852SKerry McLaughlin bool LoopVectorizeHints::allowReordering() const {
2389f76a852SKerry McLaughlin   // Allow the vectorizer to change the order of operations if enabling
2399f76a852SKerry McLaughlin   // loop hints are provided
2409f76a852SKerry McLaughlin   ElementCount EC = getWidth();
2419f76a852SKerry McLaughlin   return HintsAllowReordering &&
2429f76a852SKerry McLaughlin          (getForce() == LoopVectorizeHints::FK_Enabled ||
2439f76a852SKerry McLaughlin           EC.getKnownMinValue() > 1);
2449f76a852SKerry McLaughlin }
2459f76a852SKerry McLaughlin 
246f2ec16ccSHideki Saito void LoopVectorizeHints::getHintsFromMetadata() {
247f2ec16ccSHideki Saito   MDNode *LoopID = TheLoop->getLoopID();
248f2ec16ccSHideki Saito   if (!LoopID)
249f2ec16ccSHideki Saito     return;
250f2ec16ccSHideki Saito 
251f2ec16ccSHideki Saito   // First operand should refer to the loop id itself.
252f2ec16ccSHideki Saito   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
253f2ec16ccSHideki Saito   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
254f2ec16ccSHideki Saito 
255f2ec16ccSHideki Saito   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
256f2ec16ccSHideki Saito     const MDString *S = nullptr;
257f2ec16ccSHideki Saito     SmallVector<Metadata *, 4> Args;
258f2ec16ccSHideki Saito 
259f2ec16ccSHideki Saito     // The expected hint is either a MDString or a MDNode with the first
260f2ec16ccSHideki Saito     // operand a MDString.
261f2ec16ccSHideki Saito     if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
262f2ec16ccSHideki Saito       if (!MD || MD->getNumOperands() == 0)
263f2ec16ccSHideki Saito         continue;
264f2ec16ccSHideki Saito       S = dyn_cast<MDString>(MD->getOperand(0));
265f2ec16ccSHideki Saito       for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
266f2ec16ccSHideki Saito         Args.push_back(MD->getOperand(i));
267f2ec16ccSHideki Saito     } else {
268f2ec16ccSHideki Saito       S = dyn_cast<MDString>(LoopID->getOperand(i));
269f2ec16ccSHideki Saito       assert(Args.size() == 0 && "too many arguments for MDString");
270f2ec16ccSHideki Saito     }
271f2ec16ccSHideki Saito 
272f2ec16ccSHideki Saito     if (!S)
273f2ec16ccSHideki Saito       continue;
274f2ec16ccSHideki Saito 
275f2ec16ccSHideki Saito     // Check if the hint starts with the loop metadata prefix.
276f2ec16ccSHideki Saito     StringRef Name = S->getString();
277f2ec16ccSHideki Saito     if (Args.size() == 1)
278f2ec16ccSHideki Saito       setHint(Name, Args[0]);
279f2ec16ccSHideki Saito   }
280f2ec16ccSHideki Saito }
281f2ec16ccSHideki Saito 
282f2ec16ccSHideki Saito void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
283f2ec16ccSHideki Saito   if (!Name.startswith(Prefix()))
284f2ec16ccSHideki Saito     return;
285f2ec16ccSHideki Saito   Name = Name.substr(Prefix().size(), StringRef::npos);
286f2ec16ccSHideki Saito 
287f2ec16ccSHideki Saito   const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
288f2ec16ccSHideki Saito   if (!C)
289f2ec16ccSHideki Saito     return;
290f2ec16ccSHideki Saito   unsigned Val = C->getZExtValue();
291f2ec16ccSHideki Saito 
29271bd59f0SDavid Sherwood   Hint *Hints[] = {&Width,        &Interleave, &Force,
29371bd59f0SDavid Sherwood                    &IsVectorized, &Predicate,  &Scalable};
294f2ec16ccSHideki Saito   for (auto H : Hints) {
295f2ec16ccSHideki Saito     if (Name == H->Name) {
296f2ec16ccSHideki Saito       if (H->validate(Val))
297f2ec16ccSHideki Saito         H->Value = Val;
298f2ec16ccSHideki Saito       else
299d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
300f2ec16ccSHideki Saito       break;
301f2ec16ccSHideki Saito     }
302f2ec16ccSHideki Saito   }
303f2ec16ccSHideki Saito }
304f2ec16ccSHideki Saito 
305f2ec16ccSHideki Saito // Return true if the inner loop \p Lp is uniform with regard to the outer loop
306f2ec16ccSHideki Saito // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
307f2ec16ccSHideki Saito // executing the inner loop will execute the same iterations). This check is
308f2ec16ccSHideki Saito // very constrained for now but it will be relaxed in the future. \p Lp is
309f2ec16ccSHideki Saito // considered uniform if it meets all the following conditions:
310f2ec16ccSHideki Saito //   1) it has a canonical IV (starting from 0 and with stride 1),
311f2ec16ccSHideki Saito //   2) its latch terminator is a conditional branch and,
312f2ec16ccSHideki Saito //   3) its latch condition is a compare instruction whose operands are the
313f2ec16ccSHideki Saito //      canonical IV and an OuterLp invariant.
314f2ec16ccSHideki Saito // This check doesn't take into account the uniformity of other conditions not
315f2ec16ccSHideki Saito // related to the loop latch because they don't affect the loop uniformity.
316f2ec16ccSHideki Saito //
317f2ec16ccSHideki Saito // NOTE: We decided to keep all these checks and its associated documentation
318f2ec16ccSHideki Saito // together so that we can easily have a picture of the current supported loop
319f2ec16ccSHideki Saito // nests. However, some of the current checks don't depend on \p OuterLp and
320f2ec16ccSHideki Saito // would be redundantly executed for each \p Lp if we invoked this function for
321f2ec16ccSHideki Saito // different candidate outer loops. This is not the case for now because we
322f2ec16ccSHideki Saito // don't currently have the infrastructure to evaluate multiple candidate outer
323f2ec16ccSHideki Saito // loops and \p OuterLp will be a fixed parameter while we only support explicit
324f2ec16ccSHideki Saito // outer loop vectorization. It's also very likely that these checks go away
325f2ec16ccSHideki Saito // before introducing the aforementioned infrastructure. However, if this is not
326f2ec16ccSHideki Saito // the case, we should move the \p OuterLp independent checks to a separate
327f2ec16ccSHideki Saito // function that is only executed once for each \p Lp.
328f2ec16ccSHideki Saito static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
329f2ec16ccSHideki Saito   assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
330f2ec16ccSHideki Saito 
331f2ec16ccSHideki Saito   // If Lp is the outer loop, it's uniform by definition.
332f2ec16ccSHideki Saito   if (Lp == OuterLp)
333f2ec16ccSHideki Saito     return true;
334f2ec16ccSHideki Saito   assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
335f2ec16ccSHideki Saito 
336f2ec16ccSHideki Saito   // 1.
337f2ec16ccSHideki Saito   PHINode *IV = Lp->getCanonicalInductionVariable();
338f2ec16ccSHideki Saito   if (!IV) {
339d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
340f2ec16ccSHideki Saito     return false;
341f2ec16ccSHideki Saito   }
342f2ec16ccSHideki Saito 
343f2ec16ccSHideki Saito   // 2.
344f2ec16ccSHideki Saito   BasicBlock *Latch = Lp->getLoopLatch();
345f2ec16ccSHideki Saito   auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
346f2ec16ccSHideki Saito   if (!LatchBr || LatchBr->isUnconditional()) {
347d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
348f2ec16ccSHideki Saito     return false;
349f2ec16ccSHideki Saito   }
350f2ec16ccSHideki Saito 
351f2ec16ccSHideki Saito   // 3.
352f2ec16ccSHideki Saito   auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
353f2ec16ccSHideki Saito   if (!LatchCmp) {
354d34e60caSNicola Zaghen     LLVM_DEBUG(
355d34e60caSNicola Zaghen         dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
356f2ec16ccSHideki Saito     return false;
357f2ec16ccSHideki Saito   }
358f2ec16ccSHideki Saito 
359f2ec16ccSHideki Saito   Value *CondOp0 = LatchCmp->getOperand(0);
360f2ec16ccSHideki Saito   Value *CondOp1 = LatchCmp->getOperand(1);
361f2ec16ccSHideki Saito   Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
362f2ec16ccSHideki Saito   if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
363f2ec16ccSHideki Saito       !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
364d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
365f2ec16ccSHideki Saito     return false;
366f2ec16ccSHideki Saito   }
367f2ec16ccSHideki Saito 
368f2ec16ccSHideki Saito   return true;
369f2ec16ccSHideki Saito }
370f2ec16ccSHideki Saito 
371f2ec16ccSHideki Saito // Return true if \p Lp and all its nested loops are uniform with regard to \p
372f2ec16ccSHideki Saito // OuterLp.
373f2ec16ccSHideki Saito static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
374f2ec16ccSHideki Saito   if (!isUniformLoop(Lp, OuterLp))
375f2ec16ccSHideki Saito     return false;
376f2ec16ccSHideki Saito 
377f2ec16ccSHideki Saito   // Check if nested loops are uniform.
378f2ec16ccSHideki Saito   for (Loop *SubLp : *Lp)
379f2ec16ccSHideki Saito     if (!isUniformLoopNest(SubLp, OuterLp))
380f2ec16ccSHideki Saito       return false;
381f2ec16ccSHideki Saito 
382f2ec16ccSHideki Saito   return true;
383f2ec16ccSHideki Saito }
384f2ec16ccSHideki Saito 
3855f8f34e4SAdrian Prantl /// Check whether it is safe to if-convert this phi node.
386f2ec16ccSHideki Saito ///
387f2ec16ccSHideki Saito /// Phi nodes with constant expressions that can trap are not safe to if
388f2ec16ccSHideki Saito /// convert.
389f2ec16ccSHideki Saito static bool canIfConvertPHINodes(BasicBlock *BB) {
390f2ec16ccSHideki Saito   for (PHINode &Phi : BB->phis()) {
391f2ec16ccSHideki Saito     for (Value *V : Phi.incoming_values())
392f2ec16ccSHideki Saito       if (auto *C = dyn_cast<Constant>(V))
393f2ec16ccSHideki Saito         if (C->canTrap())
394f2ec16ccSHideki Saito           return false;
395f2ec16ccSHideki Saito   }
396f2ec16ccSHideki Saito   return true;
397f2ec16ccSHideki Saito }
398f2ec16ccSHideki Saito 
399f2ec16ccSHideki Saito static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
400f2ec16ccSHideki Saito   if (Ty->isPointerTy())
401f2ec16ccSHideki Saito     return DL.getIntPtrType(Ty);
402f2ec16ccSHideki Saito 
403f2ec16ccSHideki Saito   // It is possible that char's or short's overflow when we ask for the loop's
404f2ec16ccSHideki Saito   // trip count, work around this by changing the type size.
405f2ec16ccSHideki Saito   if (Ty->getScalarSizeInBits() < 32)
406f2ec16ccSHideki Saito     return Type::getInt32Ty(Ty->getContext());
407f2ec16ccSHideki Saito 
408f2ec16ccSHideki Saito   return Ty;
409f2ec16ccSHideki Saito }
410f2ec16ccSHideki Saito 
411f2ec16ccSHideki Saito static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
412f2ec16ccSHideki Saito   Ty0 = convertPointerToIntegerType(DL, Ty0);
413f2ec16ccSHideki Saito   Ty1 = convertPointerToIntegerType(DL, Ty1);
414f2ec16ccSHideki Saito   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
415f2ec16ccSHideki Saito     return Ty0;
416f2ec16ccSHideki Saito   return Ty1;
417f2ec16ccSHideki Saito }
418f2ec16ccSHideki Saito 
4195f8f34e4SAdrian Prantl /// Check that the instruction has outside loop users and is not an
420f2ec16ccSHideki Saito /// identified reduction variable.
421f2ec16ccSHideki Saito static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
422f2ec16ccSHideki Saito                                SmallPtrSetImpl<Value *> &AllowedExit) {
42360a1e4ddSAnna Thomas   // Reductions, Inductions and non-header phis are allowed to have exit users. All
424f2ec16ccSHideki Saito   // other instructions must not have external users.
425f2ec16ccSHideki Saito   if (!AllowedExit.count(Inst))
426f2ec16ccSHideki Saito     // Check that all of the users of the loop are inside the BB.
427f2ec16ccSHideki Saito     for (User *U : Inst->users()) {
428f2ec16ccSHideki Saito       Instruction *UI = cast<Instruction>(U);
429f2ec16ccSHideki Saito       // This user may be a reduction exit value.
430f2ec16ccSHideki Saito       if (!TheLoop->contains(UI)) {
431d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
432f2ec16ccSHideki Saito         return true;
433f2ec16ccSHideki Saito       }
434f2ec16ccSHideki Saito     }
435f2ec16ccSHideki Saito   return false;
436f2ec16ccSHideki Saito }
437f2ec16ccSHideki Saito 
43845c46734SNikita Popov int LoopVectorizationLegality::isConsecutivePtr(Type *AccessTy,
43945c46734SNikita Popov                                                 Value *Ptr) const {
440f2ec16ccSHideki Saito   const ValueToValueMap &Strides =
441f2ec16ccSHideki Saito       getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
442f2ec16ccSHideki Saito 
4437bedae7dSHiroshi Yamauchi   Function *F = TheLoop->getHeader()->getParent();
4447bedae7dSHiroshi Yamauchi   bool OptForSize = F->hasOptSize() ||
4457bedae7dSHiroshi Yamauchi                     llvm::shouldOptimizeForSize(TheLoop->getHeader(), PSI, BFI,
4467bedae7dSHiroshi Yamauchi                                                 PGSOQueryType::IRPass);
4477bedae7dSHiroshi Yamauchi   bool CanAddPredicate = !OptForSize;
44845c46734SNikita Popov   int Stride = getPtrStride(PSE, AccessTy, Ptr, TheLoop, Strides,
44945c46734SNikita Popov                             CanAddPredicate, false);
450f2ec16ccSHideki Saito   if (Stride == 1 || Stride == -1)
451f2ec16ccSHideki Saito     return Stride;
452f2ec16ccSHideki Saito   return 0;
453f2ec16ccSHideki Saito }
454f2ec16ccSHideki Saito 
455f2ec16ccSHideki Saito bool LoopVectorizationLegality::isUniform(Value *V) {
456f2ec16ccSHideki Saito   return LAI->isUniform(V);
457f2ec16ccSHideki Saito }
458f2ec16ccSHideki Saito 
459f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeOuterLoop() {
46089c1e35fSStefanos Baziotis   assert(!TheLoop->isInnermost() && "We are not vectorizing an outer loop.");
461f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
462f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
463f2ec16ccSHideki Saito   bool Result = true;
464f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
465f2ec16ccSHideki Saito 
466f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
467f2ec16ccSHideki Saito     // Check whether the BB terminator is a BranchInst. Any other terminator is
468f2ec16ccSHideki Saito     // not supported yet.
469f2ec16ccSHideki Saito     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
470f2ec16ccSHideki Saito     if (!Br) {
4719e97caf5SRenato Golin       reportVectorizationFailure("Unsupported basic block terminator",
4729e97caf5SRenato Golin           "loop control flow is not understood by vectorizer",
473ec818d7fSHideki Saito           "CFGNotUnderstood", ORE, TheLoop);
474f2ec16ccSHideki Saito       if (DoExtraAnalysis)
475f2ec16ccSHideki Saito         Result = false;
476f2ec16ccSHideki Saito       else
477f2ec16ccSHideki Saito         return false;
478f2ec16ccSHideki Saito     }
479f2ec16ccSHideki Saito 
480f2ec16ccSHideki Saito     // Check whether the BranchInst is a supported one. Only unconditional
481f2ec16ccSHideki Saito     // branches, conditional branches with an outer loop invariant condition or
482f2ec16ccSHideki Saito     // backedges are supported.
4834e4ecae0SHideki Saito     // FIXME: We skip these checks when VPlan predication is enabled as we
4844e4ecae0SHideki Saito     // want to allow divergent branches. This whole check will be removed
4854e4ecae0SHideki Saito     // once VPlan predication is on by default.
4864e4ecae0SHideki Saito     if (!EnableVPlanPredication && Br && Br->isConditional() &&
487f2ec16ccSHideki Saito         !TheLoop->isLoopInvariant(Br->getCondition()) &&
488f2ec16ccSHideki Saito         !LI->isLoopHeader(Br->getSuccessor(0)) &&
489f2ec16ccSHideki Saito         !LI->isLoopHeader(Br->getSuccessor(1))) {
4909e97caf5SRenato Golin       reportVectorizationFailure("Unsupported conditional branch",
4919e97caf5SRenato Golin           "loop control flow is not understood by vectorizer",
492ec818d7fSHideki Saito           "CFGNotUnderstood", ORE, TheLoop);
493f2ec16ccSHideki Saito       if (DoExtraAnalysis)
494f2ec16ccSHideki Saito         Result = false;
495f2ec16ccSHideki Saito       else
496f2ec16ccSHideki Saito         return false;
497f2ec16ccSHideki Saito     }
498f2ec16ccSHideki Saito   }
499f2ec16ccSHideki Saito 
500f2ec16ccSHideki Saito   // Check whether inner loops are uniform. At this point, we only support
501f2ec16ccSHideki Saito   // simple outer loops scenarios with uniform nested loops.
502f2ec16ccSHideki Saito   if (!isUniformLoopNest(TheLoop /*loop nest*/,
503f2ec16ccSHideki Saito                          TheLoop /*context outer loop*/)) {
5049e97caf5SRenato Golin     reportVectorizationFailure("Outer loop contains divergent loops",
5059e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
506ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
507f2ec16ccSHideki Saito     if (DoExtraAnalysis)
508f2ec16ccSHideki Saito       Result = false;
509f2ec16ccSHideki Saito     else
510f2ec16ccSHideki Saito       return false;
511f2ec16ccSHideki Saito   }
512f2ec16ccSHideki Saito 
513ea7f3035SHideki Saito   // Check whether we are able to set up outer loop induction.
514ea7f3035SHideki Saito   if (!setupOuterLoopInductions()) {
5159e97caf5SRenato Golin     reportVectorizationFailure("Unsupported outer loop Phi(s)",
5169e97caf5SRenato Golin                                "Unsupported outer loop Phi(s)",
517ec818d7fSHideki Saito                                "UnsupportedPhi", ORE, TheLoop);
518ea7f3035SHideki Saito     if (DoExtraAnalysis)
519ea7f3035SHideki Saito       Result = false;
520ea7f3035SHideki Saito     else
521ea7f3035SHideki Saito       return false;
522ea7f3035SHideki Saito   }
523ea7f3035SHideki Saito 
524f2ec16ccSHideki Saito   return Result;
525f2ec16ccSHideki Saito }
526f2ec16ccSHideki Saito 
527f2ec16ccSHideki Saito void LoopVectorizationLegality::addInductionPhi(
528f2ec16ccSHideki Saito     PHINode *Phi, const InductionDescriptor &ID,
529f2ec16ccSHideki Saito     SmallPtrSetImpl<Value *> &AllowedExit) {
530f2ec16ccSHideki Saito   Inductions[Phi] = ID;
531f2ec16ccSHideki Saito 
532f2ec16ccSHideki Saito   // In case this induction also comes with casts that we know we can ignore
533f2ec16ccSHideki Saito   // in the vectorized loop body, record them here. All casts could be recorded
534f2ec16ccSHideki Saito   // here for ignoring, but suffices to record only the first (as it is the
535f2ec16ccSHideki Saito   // only one that may bw used outside the cast sequence).
536f2ec16ccSHideki Saito   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
537f2ec16ccSHideki Saito   if (!Casts.empty())
538f2ec16ccSHideki Saito     InductionCastsToIgnore.insert(*Casts.begin());
539f2ec16ccSHideki Saito 
540f2ec16ccSHideki Saito   Type *PhiTy = Phi->getType();
541f2ec16ccSHideki Saito   const DataLayout &DL = Phi->getModule()->getDataLayout();
542f2ec16ccSHideki Saito 
543f2ec16ccSHideki Saito   // Get the widest type.
544f2ec16ccSHideki Saito   if (!PhiTy->isFloatingPointTy()) {
545f2ec16ccSHideki Saito     if (!WidestIndTy)
546f2ec16ccSHideki Saito       WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
547f2ec16ccSHideki Saito     else
548f2ec16ccSHideki Saito       WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
549f2ec16ccSHideki Saito   }
550f2ec16ccSHideki Saito 
551f2ec16ccSHideki Saito   // Int inductions are special because we only allow one IV.
552f2ec16ccSHideki Saito   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
553f2ec16ccSHideki Saito       ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
554f2ec16ccSHideki Saito       isa<Constant>(ID.getStartValue()) &&
555f2ec16ccSHideki Saito       cast<Constant>(ID.getStartValue())->isNullValue()) {
556f2ec16ccSHideki Saito 
557f2ec16ccSHideki Saito     // Use the phi node with the widest type as induction. Use the last
558f2ec16ccSHideki Saito     // one if there are multiple (no good reason for doing this other
559f2ec16ccSHideki Saito     // than it is expedient). We've checked that it begins at zero and
560f2ec16ccSHideki Saito     // steps by one, so this is a canonical induction variable.
561f2ec16ccSHideki Saito     if (!PrimaryInduction || PhiTy == WidestIndTy)
562f2ec16ccSHideki Saito       PrimaryInduction = Phi;
563f2ec16ccSHideki Saito   }
564f2ec16ccSHideki Saito 
565f2ec16ccSHideki Saito   // Both the PHI node itself, and the "post-increment" value feeding
566f2ec16ccSHideki Saito   // back into the PHI node may have external users.
567f2ec16ccSHideki Saito   // We can allow those uses, except if the SCEVs we have for them rely
568f2ec16ccSHideki Saito   // on predicates that only hold within the loop, since allowing the exit
5696a1dd77fSAnna Thomas   // currently means re-using this SCEV outside the loop (see PR33706 for more
5706a1dd77fSAnna Thomas   // details).
571f2ec16ccSHideki Saito   if (PSE.getUnionPredicate().isAlwaysTrue()) {
572f2ec16ccSHideki Saito     AllowedExit.insert(Phi);
573f2ec16ccSHideki Saito     AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
574f2ec16ccSHideki Saito   }
575f2ec16ccSHideki Saito 
576d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
577f2ec16ccSHideki Saito }
578f2ec16ccSHideki Saito 
579ea7f3035SHideki Saito bool LoopVectorizationLegality::setupOuterLoopInductions() {
580ea7f3035SHideki Saito   BasicBlock *Header = TheLoop->getHeader();
581ea7f3035SHideki Saito 
582ea7f3035SHideki Saito   // Returns true if a given Phi is a supported induction.
583ea7f3035SHideki Saito   auto isSupportedPhi = [&](PHINode &Phi) -> bool {
584ea7f3035SHideki Saito     InductionDescriptor ID;
585ea7f3035SHideki Saito     if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
586ea7f3035SHideki Saito         ID.getKind() == InductionDescriptor::IK_IntInduction) {
587ea7f3035SHideki Saito       addInductionPhi(&Phi, ID, AllowedExit);
588ea7f3035SHideki Saito       return true;
589ea7f3035SHideki Saito     } else {
590ea7f3035SHideki Saito       // Bail out for any Phi in the outer loop header that is not a supported
591ea7f3035SHideki Saito       // induction.
592ea7f3035SHideki Saito       LLVM_DEBUG(
593ea7f3035SHideki Saito           dbgs()
594ea7f3035SHideki Saito           << "LV: Found unsupported PHI for outer loop vectorization.\n");
595ea7f3035SHideki Saito       return false;
596ea7f3035SHideki Saito     }
597ea7f3035SHideki Saito   };
598ea7f3035SHideki Saito 
599ea7f3035SHideki Saito   if (llvm::all_of(Header->phis(), isSupportedPhi))
600ea7f3035SHideki Saito     return true;
601ea7f3035SHideki Saito   else
602ea7f3035SHideki Saito     return false;
603ea7f3035SHideki Saito }
604ea7f3035SHideki Saito 
60566c120f0SFrancesco Petrogalli /// Checks if a function is scalarizable according to the TLI, in
60666c120f0SFrancesco Petrogalli /// the sense that it should be vectorized and then expanded in
60766c120f0SFrancesco Petrogalli /// multiple scalar calls. This is represented in the
60866c120f0SFrancesco Petrogalli /// TLI via mappings that do not specify a vector name, as in the
60966c120f0SFrancesco Petrogalli /// following example:
61066c120f0SFrancesco Petrogalli ///
61166c120f0SFrancesco Petrogalli ///    const VecDesc VecIntrinsics[] = {
61266c120f0SFrancesco Petrogalli ///      {"llvm.phx.abs.i32", "", 4}
61366c120f0SFrancesco Petrogalli ///    };
61466c120f0SFrancesco Petrogalli static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI) {
61566c120f0SFrancesco Petrogalli   const StringRef ScalarName = CI.getCalledFunction()->getName();
61666c120f0SFrancesco Petrogalli   bool Scalarize = TLI.isFunctionVectorizable(ScalarName);
61766c120f0SFrancesco Petrogalli   // Check that all known VFs are not associated to a vector
61866c120f0SFrancesco Petrogalli   // function, i.e. the vector name is emty.
61901b87444SDavid Sherwood   if (Scalarize) {
62001b87444SDavid Sherwood     ElementCount WidestFixedVF, WidestScalableVF;
62101b87444SDavid Sherwood     TLI.getWidestVF(ScalarName, WidestFixedVF, WidestScalableVF);
62201b87444SDavid Sherwood     for (ElementCount VF = ElementCount::getFixed(2);
62301b87444SDavid Sherwood          ElementCount::isKnownLE(VF, WidestFixedVF); VF *= 2)
62466c120f0SFrancesco Petrogalli       Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
62501b87444SDavid Sherwood     for (ElementCount VF = ElementCount::getScalable(1);
62601b87444SDavid Sherwood          ElementCount::isKnownLE(VF, WidestScalableVF); VF *= 2)
62701b87444SDavid Sherwood       Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
62801b87444SDavid Sherwood     assert((WidestScalableVF.isZero() || !Scalarize) &&
62901b87444SDavid Sherwood            "Caller may decide to scalarize a variant using a scalable VF");
63066c120f0SFrancesco Petrogalli   }
63166c120f0SFrancesco Petrogalli   return Scalarize;
63266c120f0SFrancesco Petrogalli }
63366c120f0SFrancesco Petrogalli 
634f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeInstrs() {
635f2ec16ccSHideki Saito   BasicBlock *Header = TheLoop->getHeader();
636f2ec16ccSHideki Saito 
637f2ec16ccSHideki Saito   // For each block in the loop.
638f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
639f2ec16ccSHideki Saito     // Scan the instructions in the block and look for hazards.
640f2ec16ccSHideki Saito     for (Instruction &I : *BB) {
641f2ec16ccSHideki Saito       if (auto *Phi = dyn_cast<PHINode>(&I)) {
642f2ec16ccSHideki Saito         Type *PhiTy = Phi->getType();
643f2ec16ccSHideki Saito         // Check that this PHI type is allowed.
644f2ec16ccSHideki Saito         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
645f2ec16ccSHideki Saito             !PhiTy->isPointerTy()) {
6469e97caf5SRenato Golin           reportVectorizationFailure("Found a non-int non-pointer PHI",
6479e97caf5SRenato Golin                                      "loop control flow is not understood by vectorizer",
648ec818d7fSHideki Saito                                      "CFGNotUnderstood", ORE, TheLoop);
649f2ec16ccSHideki Saito           return false;
650f2ec16ccSHideki Saito         }
651f2ec16ccSHideki Saito 
652f2ec16ccSHideki Saito         // If this PHINode is not in the header block, then we know that we
653f2ec16ccSHideki Saito         // can convert it to select during if-conversion. No need to check if
654f2ec16ccSHideki Saito         // the PHIs in this block are induction or reduction variables.
655f2ec16ccSHideki Saito         if (BB != Header) {
65660a1e4ddSAnna Thomas           // Non-header phi nodes that have outside uses can be vectorized. Add
65760a1e4ddSAnna Thomas           // them to the list of allowed exits.
65860a1e4ddSAnna Thomas           // Unsafe cyclic dependencies with header phis are identified during
65960a1e4ddSAnna Thomas           // legalization for reduction, induction and first order
66060a1e4ddSAnna Thomas           // recurrences.
661dd18ce45SBjorn Pettersson           AllowedExit.insert(&I);
662f2ec16ccSHideki Saito           continue;
663f2ec16ccSHideki Saito         }
664f2ec16ccSHideki Saito 
665f2ec16ccSHideki Saito         // We only allow if-converted PHIs with exactly two incoming values.
666f2ec16ccSHideki Saito         if (Phi->getNumIncomingValues() != 2) {
6679e97caf5SRenato Golin           reportVectorizationFailure("Found an invalid PHI",
6689e97caf5SRenato Golin               "loop control flow is not understood by vectorizer",
669ec818d7fSHideki Saito               "CFGNotUnderstood", ORE, TheLoop, Phi);
670f2ec16ccSHideki Saito           return false;
671f2ec16ccSHideki Saito         }
672f2ec16ccSHideki Saito 
673f2ec16ccSHideki Saito         RecurrenceDescriptor RedDes;
674f2ec16ccSHideki Saito         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
675f2ec16ccSHideki Saito                                                  DT)) {
676b3a33553SSanjay Patel           Requirements->addExactFPMathInst(RedDes.getExactFPMathInst());
677f2ec16ccSHideki Saito           AllowedExit.insert(RedDes.getLoopExitInstr());
678f2ec16ccSHideki Saito           Reductions[Phi] = RedDes;
679f2ec16ccSHideki Saito           continue;
680f2ec16ccSHideki Saito         }
681f2ec16ccSHideki Saito 
682b02b0ad8SAnna Thomas         // TODO: Instead of recording the AllowedExit, it would be good to record the
683b02b0ad8SAnna Thomas         // complementary set: NotAllowedExit. These include (but may not be
684b02b0ad8SAnna Thomas         // limited to):
685b02b0ad8SAnna Thomas         // 1. Reduction phis as they represent the one-before-last value, which
686b02b0ad8SAnna Thomas         // is not available when vectorized
687b02b0ad8SAnna Thomas         // 2. Induction phis and increment when SCEV predicates cannot be used
688b02b0ad8SAnna Thomas         // outside the loop - see addInductionPhi
689b02b0ad8SAnna Thomas         // 3. Non-Phis with outside uses when SCEV predicates cannot be used
690b02b0ad8SAnna Thomas         // outside the loop - see call to hasOutsideLoopUser in the non-phi
691b02b0ad8SAnna Thomas         // handling below
692b02b0ad8SAnna Thomas         // 4. FirstOrderRecurrence phis that can possibly be handled by
693b02b0ad8SAnna Thomas         // extraction.
694b02b0ad8SAnna Thomas         // By recording these, we can then reason about ways to vectorize each
695b02b0ad8SAnna Thomas         // of these NotAllowedExit.
696f2ec16ccSHideki Saito         InductionDescriptor ID;
697f2ec16ccSHideki Saito         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
698f2ec16ccSHideki Saito           addInductionPhi(Phi, ID, AllowedExit);
69936a489d1SSanjay Patel           Requirements->addExactFPMathInst(ID.getExactFPMathInst());
700f2ec16ccSHideki Saito           continue;
701f2ec16ccSHideki Saito         }
702f2ec16ccSHideki Saito 
703f2ec16ccSHideki Saito         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
704f2ec16ccSHideki Saito                                                          SinkAfter, DT)) {
7058e0c5f72SAyal Zaks           AllowedExit.insert(Phi);
706f2ec16ccSHideki Saito           FirstOrderRecurrences.insert(Phi);
707f2ec16ccSHideki Saito           continue;
708f2ec16ccSHideki Saito         }
709f2ec16ccSHideki Saito 
710f2ec16ccSHideki Saito         // As a last resort, coerce the PHI to a AddRec expression
711f2ec16ccSHideki Saito         // and re-try classifying it a an induction PHI.
712f2ec16ccSHideki Saito         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
713f2ec16ccSHideki Saito           addInductionPhi(Phi, ID, AllowedExit);
714f2ec16ccSHideki Saito           continue;
715f2ec16ccSHideki Saito         }
716f2ec16ccSHideki Saito 
7179e97caf5SRenato Golin         reportVectorizationFailure("Found an unidentified PHI",
7189e97caf5SRenato Golin             "value that could not be identified as "
7199e97caf5SRenato Golin             "reduction is used outside the loop",
720ec818d7fSHideki Saito             "NonReductionValueUsedOutsideLoop", ORE, TheLoop, Phi);
721f2ec16ccSHideki Saito         return false;
722f2ec16ccSHideki Saito       } // end of PHI handling
723f2ec16ccSHideki Saito 
724f2ec16ccSHideki Saito       // We handle calls that:
725f2ec16ccSHideki Saito       //   * Are debug info intrinsics.
726f2ec16ccSHideki Saito       //   * Have a mapping to an IR intrinsic.
727f2ec16ccSHideki Saito       //   * Have a vector version available.
728f2ec16ccSHideki Saito       auto *CI = dyn_cast<CallInst>(&I);
72966c120f0SFrancesco Petrogalli 
730f2ec16ccSHideki Saito       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
731f2ec16ccSHideki Saito           !isa<DbgInfoIntrinsic>(CI) &&
732f2ec16ccSHideki Saito           !(CI->getCalledFunction() && TLI &&
73366c120f0SFrancesco Petrogalli             (!VFDatabase::getMappings(*CI).empty() ||
73466c120f0SFrancesco Petrogalli              isTLIScalarize(*TLI, *CI)))) {
7357d65fe5cSSanjay Patel         // If the call is a recognized math libary call, it is likely that
7367d65fe5cSSanjay Patel         // we can vectorize it given loosened floating-point constraints.
7377d65fe5cSSanjay Patel         LibFunc Func;
7387d65fe5cSSanjay Patel         bool IsMathLibCall =
7397d65fe5cSSanjay Patel             TLI && CI->getCalledFunction() &&
7407d65fe5cSSanjay Patel             CI->getType()->isFloatingPointTy() &&
7417d65fe5cSSanjay Patel             TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
7427d65fe5cSSanjay Patel             TLI->hasOptimizedCodeGen(Func);
7437d65fe5cSSanjay Patel 
7447d65fe5cSSanjay Patel         if (IsMathLibCall) {
7457d65fe5cSSanjay Patel           // TODO: Ideally, we should not use clang-specific language here,
7467d65fe5cSSanjay Patel           // but it's hard to provide meaningful yet generic advice.
7477d65fe5cSSanjay Patel           // Also, should this be guarded by allowExtraAnalysis() and/or be part
7487d65fe5cSSanjay Patel           // of the returned info from isFunctionVectorizable()?
74966c120f0SFrancesco Petrogalli           reportVectorizationFailure(
75066c120f0SFrancesco Petrogalli               "Found a non-intrinsic callsite",
7519e97caf5SRenato Golin               "library call cannot be vectorized. "
7527d65fe5cSSanjay Patel               "Try compiling with -fno-math-errno, -ffast-math, "
7539e97caf5SRenato Golin               "or similar flags",
754ec818d7fSHideki Saito               "CantVectorizeLibcall", ORE, TheLoop, CI);
7557d65fe5cSSanjay Patel         } else {
7569e97caf5SRenato Golin           reportVectorizationFailure("Found a non-intrinsic callsite",
7579e97caf5SRenato Golin                                      "call instruction cannot be vectorized",
758ec818d7fSHideki Saito                                      "CantVectorizeLibcall", ORE, TheLoop, CI);
7597d65fe5cSSanjay Patel         }
760f2ec16ccSHideki Saito         return false;
761f2ec16ccSHideki Saito       }
762f2ec16ccSHideki Saito 
763a066f1f9SSimon Pilgrim       // Some intrinsics have scalar arguments and should be same in order for
764a066f1f9SSimon Pilgrim       // them to be vectorized (i.e. loop invariant).
765a066f1f9SSimon Pilgrim       if (CI) {
766f2ec16ccSHideki Saito         auto *SE = PSE.getSE();
767a066f1f9SSimon Pilgrim         Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
7684f0225f6SKazu Hirata         for (unsigned i = 0, e = CI->arg_size(); i != e; ++i)
769a066f1f9SSimon Pilgrim           if (hasVectorInstrinsicScalarOpd(IntrinID, i)) {
770a066f1f9SSimon Pilgrim             if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(i)), TheLoop)) {
7719e97caf5SRenato Golin               reportVectorizationFailure("Found unvectorizable intrinsic",
7729e97caf5SRenato Golin                   "intrinsic instruction cannot be vectorized",
773ec818d7fSHideki Saito                   "CantVectorizeIntrinsic", ORE, TheLoop, CI);
774f2ec16ccSHideki Saito               return false;
775f2ec16ccSHideki Saito             }
776f2ec16ccSHideki Saito           }
777a066f1f9SSimon Pilgrim       }
778f2ec16ccSHideki Saito 
779f2ec16ccSHideki Saito       // Check that the instruction return type is vectorizable.
780f2ec16ccSHideki Saito       // Also, we can't vectorize extractelement instructions.
781f2ec16ccSHideki Saito       if ((!VectorType::isValidElementType(I.getType()) &&
782f2ec16ccSHideki Saito            !I.getType()->isVoidTy()) ||
783f2ec16ccSHideki Saito           isa<ExtractElementInst>(I)) {
7849e97caf5SRenato Golin         reportVectorizationFailure("Found unvectorizable type",
7859e97caf5SRenato Golin             "instruction return type cannot be vectorized",
786ec818d7fSHideki Saito             "CantVectorizeInstructionReturnType", ORE, TheLoop, &I);
787f2ec16ccSHideki Saito         return false;
788f2ec16ccSHideki Saito       }
789f2ec16ccSHideki Saito 
790f2ec16ccSHideki Saito       // Check that the stored type is vectorizable.
791f2ec16ccSHideki Saito       if (auto *ST = dyn_cast<StoreInst>(&I)) {
792f2ec16ccSHideki Saito         Type *T = ST->getValueOperand()->getType();
793f2ec16ccSHideki Saito         if (!VectorType::isValidElementType(T)) {
7949e97caf5SRenato Golin           reportVectorizationFailure("Store instruction cannot be vectorized",
7959e97caf5SRenato Golin                                      "store instruction cannot be vectorized",
796ec818d7fSHideki Saito                                      "CantVectorizeStore", ORE, TheLoop, ST);
797f2ec16ccSHideki Saito           return false;
798f2ec16ccSHideki Saito         }
799f2ec16ccSHideki Saito 
8006452bdd2SWarren Ristow         // For nontemporal stores, check that a nontemporal vector version is
8016452bdd2SWarren Ristow         // supported on the target.
8026452bdd2SWarren Ristow         if (ST->getMetadata(LLVMContext::MD_nontemporal)) {
8036452bdd2SWarren Ristow           // Arbitrarily try a vector of 2 elements.
8046913812aSFangrui Song           auto *VecTy = FixedVectorType::get(T, /*NumElts=*/2);
8056452bdd2SWarren Ristow           assert(VecTy && "did not find vectorized version of stored type");
80652e98f62SNikita Popov           if (!TTI->isLegalNTStore(VecTy, ST->getAlign())) {
8076452bdd2SWarren Ristow             reportVectorizationFailure(
8086452bdd2SWarren Ristow                 "nontemporal store instruction cannot be vectorized",
8096452bdd2SWarren Ristow                 "nontemporal store instruction cannot be vectorized",
810ec818d7fSHideki Saito                 "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
8116452bdd2SWarren Ristow             return false;
8126452bdd2SWarren Ristow           }
8136452bdd2SWarren Ristow         }
8146452bdd2SWarren Ristow 
8156452bdd2SWarren Ristow       } else if (auto *LD = dyn_cast<LoadInst>(&I)) {
8166452bdd2SWarren Ristow         if (LD->getMetadata(LLVMContext::MD_nontemporal)) {
8176452bdd2SWarren Ristow           // For nontemporal loads, check that a nontemporal vector version is
8186452bdd2SWarren Ristow           // supported on the target (arbitrarily try a vector of 2 elements).
8196913812aSFangrui Song           auto *VecTy = FixedVectorType::get(I.getType(), /*NumElts=*/2);
8206452bdd2SWarren Ristow           assert(VecTy && "did not find vectorized version of load type");
82152e98f62SNikita Popov           if (!TTI->isLegalNTLoad(VecTy, LD->getAlign())) {
8226452bdd2SWarren Ristow             reportVectorizationFailure(
8236452bdd2SWarren Ristow                 "nontemporal load instruction cannot be vectorized",
8246452bdd2SWarren Ristow                 "nontemporal load instruction cannot be vectorized",
825ec818d7fSHideki Saito                 "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
8266452bdd2SWarren Ristow             return false;
8276452bdd2SWarren Ristow           }
8286452bdd2SWarren Ristow         }
8296452bdd2SWarren Ristow 
830f2ec16ccSHideki Saito         // FP instructions can allow unsafe algebra, thus vectorizable by
831f2ec16ccSHideki Saito         // non-IEEE-754 compliant SIMD units.
832f2ec16ccSHideki Saito         // This applies to floating-point math operations and calls, not memory
833f2ec16ccSHideki Saito         // operations, shuffles, or casts, as they don't change precision or
834f2ec16ccSHideki Saito         // semantics.
835f2ec16ccSHideki Saito       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
836f2ec16ccSHideki Saito                  !I.isFast()) {
837d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
838f2ec16ccSHideki Saito         Hints->setPotentiallyUnsafe();
839f2ec16ccSHideki Saito       }
840f2ec16ccSHideki Saito 
841f2ec16ccSHideki Saito       // Reduction instructions are allowed to have exit users.
842f2ec16ccSHideki Saito       // All other instructions must not have external users.
843f2ec16ccSHideki Saito       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
844b02b0ad8SAnna Thomas         // We can safely vectorize loops where instructions within the loop are
845b02b0ad8SAnna Thomas         // used outside the loop only if the SCEV predicates within the loop is
846b02b0ad8SAnna Thomas         // same as outside the loop. Allowing the exit means reusing the SCEV
847b02b0ad8SAnna Thomas         // outside the loop.
848b02b0ad8SAnna Thomas         if (PSE.getUnionPredicate().isAlwaysTrue()) {
849b02b0ad8SAnna Thomas           AllowedExit.insert(&I);
850b02b0ad8SAnna Thomas           continue;
851b02b0ad8SAnna Thomas         }
8529e97caf5SRenato Golin         reportVectorizationFailure("Value cannot be used outside the loop",
8539e97caf5SRenato Golin                                    "value cannot be used outside the loop",
854ec818d7fSHideki Saito                                    "ValueUsedOutsideLoop", ORE, TheLoop, &I);
855f2ec16ccSHideki Saito         return false;
856f2ec16ccSHideki Saito       }
857f2ec16ccSHideki Saito     } // next instr.
858f2ec16ccSHideki Saito   }
859f2ec16ccSHideki Saito 
860f2ec16ccSHideki Saito   if (!PrimaryInduction) {
861f2ec16ccSHideki Saito     if (Inductions.empty()) {
8629e97caf5SRenato Golin       reportVectorizationFailure("Did not find one integer induction var",
8639e97caf5SRenato Golin           "loop induction variable could not be identified",
864ec818d7fSHideki Saito           "NoInductionVariable", ORE, TheLoop);
865f2ec16ccSHideki Saito       return false;
8664f27730eSWarren Ristow     } else if (!WidestIndTy) {
8679e97caf5SRenato Golin       reportVectorizationFailure("Did not find one integer induction var",
8689e97caf5SRenato Golin           "integer loop induction variable could not be identified",
869ec818d7fSHideki Saito           "NoIntegerInductionVariable", ORE, TheLoop);
8704f27730eSWarren Ristow       return false;
8719e97caf5SRenato Golin     } else {
8729e97caf5SRenato Golin       LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
873f2ec16ccSHideki Saito     }
874f2ec16ccSHideki Saito   }
875f2ec16ccSHideki Saito 
8769d24933fSFlorian Hahn   // For first order recurrences, we use the previous value (incoming value from
8779d24933fSFlorian Hahn   // the latch) to check if it dominates all users of the recurrence. Bail out
8789d24933fSFlorian Hahn   // if we have to sink such an instruction for another recurrence, as the
8799d24933fSFlorian Hahn   // dominance requirement may not hold after sinking.
8809d24933fSFlorian Hahn   BasicBlock *LoopLatch = TheLoop->getLoopLatch();
8819d24933fSFlorian Hahn   if (any_of(FirstOrderRecurrences, [LoopLatch, this](const PHINode *Phi) {
8829d24933fSFlorian Hahn         Instruction *V =
8839d24933fSFlorian Hahn             cast<Instruction>(Phi->getIncomingValueForBlock(LoopLatch));
8849d24933fSFlorian Hahn         return SinkAfter.find(V) != SinkAfter.end();
8859d24933fSFlorian Hahn       }))
8869d24933fSFlorian Hahn     return false;
8879d24933fSFlorian Hahn 
888f2ec16ccSHideki Saito   // Now we know the widest induction type, check if our found induction
889f2ec16ccSHideki Saito   // is the same size. If it's not, unset it here and InnerLoopVectorizer
890f2ec16ccSHideki Saito   // will create another.
891f2ec16ccSHideki Saito   if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
892f2ec16ccSHideki Saito     PrimaryInduction = nullptr;
893f2ec16ccSHideki Saito 
894f2ec16ccSHideki Saito   return true;
895f2ec16ccSHideki Saito }
896f2ec16ccSHideki Saito 
897f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeMemory() {
898f2ec16ccSHideki Saito   LAI = &(*GetLAA)(*TheLoop);
899f2ec16ccSHideki Saito   const OptimizationRemarkAnalysis *LAR = LAI->getReport();
900f2ec16ccSHideki Saito   if (LAR) {
901f2ec16ccSHideki Saito     ORE->emit([&]() {
902f2ec16ccSHideki Saito       return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
903f2ec16ccSHideki Saito                                         "loop not vectorized: ", *LAR);
904f2ec16ccSHideki Saito     });
905f2ec16ccSHideki Saito   }
906287d39ddSPaul Walker 
907f2ec16ccSHideki Saito   if (!LAI->canVectorizeMemory())
908f2ec16ccSHideki Saito     return false;
909f2ec16ccSHideki Saito 
9105e9215f0SAnna Thomas   if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
9119e97caf5SRenato Golin     reportVectorizationFailure("Stores to a uniform address",
9129e97caf5SRenato Golin         "write to a loop invariant address could not be vectorized",
913ec818d7fSHideki Saito         "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
914f2ec16ccSHideki Saito     return false;
915f2ec16ccSHideki Saito   }
916287d39ddSPaul Walker 
917f2ec16ccSHideki Saito   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
918f2ec16ccSHideki Saito   PSE.addPredicate(LAI->getPSE().getUnionPredicate());
919f2ec16ccSHideki Saito   return true;
920f2ec16ccSHideki Saito }
921f2ec16ccSHideki Saito 
9229f76a852SKerry McLaughlin bool LoopVectorizationLegality::canVectorizeFPMath(
9239f76a852SKerry McLaughlin     bool EnableStrictReductions) {
9249f76a852SKerry McLaughlin 
9259f76a852SKerry McLaughlin   // First check if there is any ExactFP math or if we allow reassociations
9269f76a852SKerry McLaughlin   if (!Requirements->getExactFPInst() || Hints->allowReordering())
9279f76a852SKerry McLaughlin     return true;
9289f76a852SKerry McLaughlin 
9299f76a852SKerry McLaughlin   // If the above is false, we have ExactFPMath & do not allow reordering.
9309f76a852SKerry McLaughlin   // If the EnableStrictReductions flag is set, first check if we have any
9319f76a852SKerry McLaughlin   // Exact FP induction vars, which we cannot vectorize.
9329f76a852SKerry McLaughlin   if (!EnableStrictReductions ||
9339f76a852SKerry McLaughlin       any_of(getInductionVars(), [&](auto &Induction) -> bool {
9349f76a852SKerry McLaughlin         InductionDescriptor IndDesc = Induction.second;
9359f76a852SKerry McLaughlin         return IndDesc.getExactFPMathInst();
9369f76a852SKerry McLaughlin       }))
9379f76a852SKerry McLaughlin     return false;
9389f76a852SKerry McLaughlin 
9399f76a852SKerry McLaughlin   // We can now only vectorize if all reductions with Exact FP math also
9409f76a852SKerry McLaughlin   // have the isOrdered flag set, which indicates that we can move the
9419f76a852SKerry McLaughlin   // reduction operations in-loop.
9429f76a852SKerry McLaughlin   return (all_of(getReductionVars(), [&](auto &Reduction) -> bool {
9435e6bfb66SSimon Pilgrim     const RecurrenceDescriptor &RdxDesc = Reduction.second;
9449f76a852SKerry McLaughlin     return !RdxDesc.hasExactFPMath() || RdxDesc.isOrdered();
9459f76a852SKerry McLaughlin   }));
9469f76a852SKerry McLaughlin }
9479f76a852SKerry McLaughlin 
948d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isInductionPhi(const Value *V) const {
949f2ec16ccSHideki Saito   Value *In0 = const_cast<Value *>(V);
950f2ec16ccSHideki Saito   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
951f2ec16ccSHideki Saito   if (!PN)
952f2ec16ccSHideki Saito     return false;
953f2ec16ccSHideki Saito 
954f2ec16ccSHideki Saito   return Inductions.count(PN);
955f2ec16ccSHideki Saito }
956f2ec16ccSHideki Saito 
957978883d2SFlorian Hahn const InductionDescriptor *
958978883d2SFlorian Hahn LoopVectorizationLegality::getIntOrFpInductionDescriptor(PHINode *Phi) const {
959978883d2SFlorian Hahn   if (!isInductionPhi(Phi))
960978883d2SFlorian Hahn     return nullptr;
961978883d2SFlorian Hahn   auto &ID = getInductionVars().find(Phi)->second;
962978883d2SFlorian Hahn   if (ID.getKind() == InductionDescriptor::IK_IntInduction ||
963978883d2SFlorian Hahn       ID.getKind() == InductionDescriptor::IK_FpInduction)
964978883d2SFlorian Hahn     return &ID;
965978883d2SFlorian Hahn   return nullptr;
966978883d2SFlorian Hahn }
967978883d2SFlorian Hahn 
968d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isCastedInductionVariable(
969d74a8a78SFlorian Hahn     const Value *V) const {
970f2ec16ccSHideki Saito   auto *Inst = dyn_cast<Instruction>(V);
971f2ec16ccSHideki Saito   return (Inst && InductionCastsToIgnore.count(Inst));
972f2ec16ccSHideki Saito }
973f2ec16ccSHideki Saito 
974d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isInductionVariable(const Value *V) const {
975f2ec16ccSHideki Saito   return isInductionPhi(V) || isCastedInductionVariable(V);
976f2ec16ccSHideki Saito }
977f2ec16ccSHideki Saito 
978d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isFirstOrderRecurrence(
979d74a8a78SFlorian Hahn     const PHINode *Phi) const {
980f2ec16ccSHideki Saito   return FirstOrderRecurrences.count(Phi);
981f2ec16ccSHideki Saito }
982f2ec16ccSHideki Saito 
983f82966d1SSander de Smalen bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) const {
984f2ec16ccSHideki Saito   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
985f2ec16ccSHideki Saito }
986f2ec16ccSHideki Saito 
987f2ec16ccSHideki Saito bool LoopVectorizationLegality::blockCanBePredicated(
988bda8fbe2SSjoerd Meijer     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs,
989bda8fbe2SSjoerd Meijer     SmallPtrSetImpl<const Instruction *> &MaskedOp,
9904f01122cSJoachim Meyer     SmallPtrSetImpl<Instruction *> &ConditionalAssumes) const {
991f2ec16ccSHideki Saito   for (Instruction &I : *BB) {
992f2ec16ccSHideki Saito     // Check that we don't have a constant expression that can trap as operand.
993f2ec16ccSHideki Saito     for (Value *Operand : I.operands()) {
994f2ec16ccSHideki Saito       if (auto *C = dyn_cast<Constant>(Operand))
995f2ec16ccSHideki Saito         if (C->canTrap())
996f2ec16ccSHideki Saito           return false;
997f2ec16ccSHideki Saito     }
99823c11380SFlorian Hahn 
99923c11380SFlorian Hahn     // We can predicate blocks with calls to assume, as long as we drop them in
100023c11380SFlorian Hahn     // case we flatten the CFG via predication.
100123c11380SFlorian Hahn     if (match(&I, m_Intrinsic<Intrinsic::assume>())) {
100223c11380SFlorian Hahn       ConditionalAssumes.insert(&I);
100323c11380SFlorian Hahn       continue;
100423c11380SFlorian Hahn     }
100523c11380SFlorian Hahn 
1006121cac01SJeroen Dobbelaere     // Do not let llvm.experimental.noalias.scope.decl block the vectorization.
1007121cac01SJeroen Dobbelaere     // TODO: there might be cases that it should block the vectorization. Let's
1008121cac01SJeroen Dobbelaere     // ignore those for now.
1009c83cff45SNikita Popov     if (isa<NoAliasScopeDeclInst>(&I))
1010121cac01SJeroen Dobbelaere       continue;
1011121cac01SJeroen Dobbelaere 
1012f2ec16ccSHideki Saito     // We might be able to hoist the load.
1013f2ec16ccSHideki Saito     if (I.mayReadFromMemory()) {
1014f2ec16ccSHideki Saito       auto *LI = dyn_cast<LoadInst>(&I);
1015f2ec16ccSHideki Saito       if (!LI)
1016f2ec16ccSHideki Saito         return false;
1017f2ec16ccSHideki Saito       if (!SafePtrs.count(LI->getPointerOperand())) {
1018f2ec16ccSHideki Saito         MaskedOp.insert(LI);
1019f2ec16ccSHideki Saito         continue;
1020f2ec16ccSHideki Saito       }
1021f2ec16ccSHideki Saito     }
1022f2ec16ccSHideki Saito 
1023f2ec16ccSHideki Saito     if (I.mayWriteToMemory()) {
1024f2ec16ccSHideki Saito       auto *SI = dyn_cast<StoreInst>(&I);
1025f2ec16ccSHideki Saito       if (!SI)
1026f2ec16ccSHideki Saito         return false;
1027f2ec16ccSHideki Saito       // Predicated store requires some form of masking:
1028f2ec16ccSHideki Saito       // 1) masked store HW instruction,
1029f2ec16ccSHideki Saito       // 2) emulation via load-blend-store (only if safe and legal to do so,
1030f2ec16ccSHideki Saito       //    be aware on the race conditions), or
1031f2ec16ccSHideki Saito       // 3) element-by-element predicate check and scalar store.
1032f2ec16ccSHideki Saito       MaskedOp.insert(SI);
1033f2ec16ccSHideki Saito       continue;
1034f2ec16ccSHideki Saito     }
1035f2ec16ccSHideki Saito     if (I.mayThrow())
1036f2ec16ccSHideki Saito       return false;
1037f2ec16ccSHideki Saito   }
1038f2ec16ccSHideki Saito 
1039f2ec16ccSHideki Saito   return true;
1040f2ec16ccSHideki Saito }
1041f2ec16ccSHideki Saito 
1042f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1043f2ec16ccSHideki Saito   if (!EnableIfConversion) {
10449e97caf5SRenato Golin     reportVectorizationFailure("If-conversion is disabled",
10459e97caf5SRenato Golin                                "if-conversion is disabled",
1046ec818d7fSHideki Saito                                "IfConversionDisabled",
1047ec818d7fSHideki Saito                                ORE, TheLoop);
1048f2ec16ccSHideki Saito     return false;
1049f2ec16ccSHideki Saito   }
1050f2ec16ccSHideki Saito 
1051f2ec16ccSHideki Saito   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1052f2ec16ccSHideki Saito 
1053cf3b5559SPhilip Reames   // A list of pointers which are known to be dereferenceable within scope of
1054cf3b5559SPhilip Reames   // the loop body for each iteration of the loop which executes.  That is,
1055cf3b5559SPhilip Reames   // the memory pointed to can be dereferenced (with the access size implied by
1056cf3b5559SPhilip Reames   // the value's type) unconditionally within the loop header without
1057cf3b5559SPhilip Reames   // introducing a new fault.
10583bbc71d6SSjoerd Meijer   SmallPtrSet<Value *, 8> SafePointers;
1059f2ec16ccSHideki Saito 
1060f2ec16ccSHideki Saito   // Collect safe addresses.
1061f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
10627403569bSPhilip Reames     if (!blockNeedsPredication(BB)) {
1063f2ec16ccSHideki Saito       for (Instruction &I : *BB)
1064f2ec16ccSHideki Saito         if (auto *Ptr = getLoadStorePointerOperand(&I))
10653bbc71d6SSjoerd Meijer           SafePointers.insert(Ptr);
10667403569bSPhilip Reames       continue;
10677403569bSPhilip Reames     }
10687403569bSPhilip Reames 
10697403569bSPhilip Reames     // For a block which requires predication, a address may be safe to access
10707403569bSPhilip Reames     // in the loop w/o predication if we can prove dereferenceability facts
10717403569bSPhilip Reames     // sufficient to ensure it'll never fault within the loop. For the moment,
10727403569bSPhilip Reames     // we restrict this to loads; stores are more complicated due to
10737403569bSPhilip Reames     // concurrency restrictions.
10747403569bSPhilip Reames     ScalarEvolution &SE = *PSE.getSE();
10757403569bSPhilip Reames     for (Instruction &I : *BB) {
10767403569bSPhilip Reames       LoadInst *LI = dyn_cast<LoadInst>(&I);
1077467e5cf4SJoe Ellis       if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) &&
10787403569bSPhilip Reames           isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT))
10793bbc71d6SSjoerd Meijer         SafePointers.insert(LI->getPointerOperand());
10807403569bSPhilip Reames     }
1081f2ec16ccSHideki Saito   }
1082f2ec16ccSHideki Saito 
1083f2ec16ccSHideki Saito   // Collect the blocks that need predication.
1084f2ec16ccSHideki Saito   BasicBlock *Header = TheLoop->getHeader();
1085f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
1086f2ec16ccSHideki Saito     // We don't support switch statements inside loops.
1087f2ec16ccSHideki Saito     if (!isa<BranchInst>(BB->getTerminator())) {
10889e97caf5SRenato Golin       reportVectorizationFailure("Loop contains a switch statement",
10899e97caf5SRenato Golin                                  "loop contains a switch statement",
1090ec818d7fSHideki Saito                                  "LoopContainsSwitch", ORE, TheLoop,
1091ec818d7fSHideki Saito                                  BB->getTerminator());
1092f2ec16ccSHideki Saito       return false;
1093f2ec16ccSHideki Saito     }
1094f2ec16ccSHideki Saito 
1095f2ec16ccSHideki Saito     // We must be able to predicate all blocks that need to be predicated.
1096f2ec16ccSHideki Saito     if (blockNeedsPredication(BB)) {
1097bda8fbe2SSjoerd Meijer       if (!blockCanBePredicated(BB, SafePointers, MaskedOp,
1098bda8fbe2SSjoerd Meijer                                 ConditionalAssumes)) {
10999e97caf5SRenato Golin         reportVectorizationFailure(
11009e97caf5SRenato Golin             "Control flow cannot be substituted for a select",
11019e97caf5SRenato Golin             "control flow cannot be substituted for a select",
1102ec818d7fSHideki Saito             "NoCFGForSelect", ORE, TheLoop,
1103ec818d7fSHideki Saito             BB->getTerminator());
1104f2ec16ccSHideki Saito         return false;
1105f2ec16ccSHideki Saito       }
1106f2ec16ccSHideki Saito     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
11079e97caf5SRenato Golin       reportVectorizationFailure(
11089e97caf5SRenato Golin           "Control flow cannot be substituted for a select",
11099e97caf5SRenato Golin           "control flow cannot be substituted for a select",
1110ec818d7fSHideki Saito           "NoCFGForSelect", ORE, TheLoop,
1111ec818d7fSHideki Saito           BB->getTerminator());
1112f2ec16ccSHideki Saito       return false;
1113f2ec16ccSHideki Saito     }
1114f2ec16ccSHideki Saito   }
1115f2ec16ccSHideki Saito 
1116f2ec16ccSHideki Saito   // We can if-convert this loop.
1117f2ec16ccSHideki Saito   return true;
1118f2ec16ccSHideki Saito }
1119f2ec16ccSHideki Saito 
1120f2ec16ccSHideki Saito // Helper function to canVectorizeLoopNestCFG.
1121f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
1122f2ec16ccSHideki Saito                                                     bool UseVPlanNativePath) {
112389c1e35fSStefanos Baziotis   assert((UseVPlanNativePath || Lp->isInnermost()) &&
1124f2ec16ccSHideki Saito          "VPlan-native path is not enabled.");
1125f2ec16ccSHideki Saito 
1126f2ec16ccSHideki Saito   // TODO: ORE should be improved to show more accurate information when an
1127f2ec16ccSHideki Saito   // outer loop can't be vectorized because a nested loop is not understood or
1128f2ec16ccSHideki Saito   // legal. Something like: "outer_loop_location: loop not vectorized:
1129f2ec16ccSHideki Saito   // (inner_loop_location) loop control flow is not understood by vectorizer".
1130f2ec16ccSHideki Saito 
1131f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1132f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1133f2ec16ccSHideki Saito   bool Result = true;
1134f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1135f2ec16ccSHideki Saito 
1136f2ec16ccSHideki Saito   // We must have a loop in canonical form. Loops with indirectbr in them cannot
1137f2ec16ccSHideki Saito   // be canonicalized.
1138f2ec16ccSHideki Saito   if (!Lp->getLoopPreheader()) {
11399e97caf5SRenato Golin     reportVectorizationFailure("Loop doesn't have a legal pre-header",
11409e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1141ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
1142f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1143f2ec16ccSHideki Saito       Result = false;
1144f2ec16ccSHideki Saito     else
1145f2ec16ccSHideki Saito       return false;
1146f2ec16ccSHideki Saito   }
1147f2ec16ccSHideki Saito 
1148f2ec16ccSHideki Saito   // We must have a single backedge.
1149f2ec16ccSHideki Saito   if (Lp->getNumBackEdges() != 1) {
11509e97caf5SRenato Golin     reportVectorizationFailure("The loop must have a single backedge",
11519e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1152ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
1153f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1154f2ec16ccSHideki Saito       Result = false;
1155f2ec16ccSHideki Saito     else
1156f2ec16ccSHideki Saito       return false;
1157f2ec16ccSHideki Saito   }
1158f2ec16ccSHideki Saito 
1159f2ec16ccSHideki Saito   return Result;
1160f2ec16ccSHideki Saito }
1161f2ec16ccSHideki Saito 
1162f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1163f2ec16ccSHideki Saito     Loop *Lp, bool UseVPlanNativePath) {
1164f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1165f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1166f2ec16ccSHideki Saito   bool Result = true;
1167f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1168f2ec16ccSHideki Saito   if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1169f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1170f2ec16ccSHideki Saito       Result = false;
1171f2ec16ccSHideki Saito     else
1172f2ec16ccSHideki Saito       return false;
1173f2ec16ccSHideki Saito   }
1174f2ec16ccSHideki Saito 
1175f2ec16ccSHideki Saito   // Recursively check whether the loop control flow of nested loops is
1176f2ec16ccSHideki Saito   // understood.
1177f2ec16ccSHideki Saito   for (Loop *SubLp : *Lp)
1178f2ec16ccSHideki Saito     if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1179f2ec16ccSHideki Saito       if (DoExtraAnalysis)
1180f2ec16ccSHideki Saito         Result = false;
1181f2ec16ccSHideki Saito       else
1182f2ec16ccSHideki Saito         return false;
1183f2ec16ccSHideki Saito     }
1184f2ec16ccSHideki Saito 
1185f2ec16ccSHideki Saito   return Result;
1186f2ec16ccSHideki Saito }
1187f2ec16ccSHideki Saito 
1188f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1189f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1190f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1191f2ec16ccSHideki Saito   bool Result = true;
1192f2ec16ccSHideki Saito 
1193f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1194f2ec16ccSHideki Saito   // Check whether the loop-related control flow in the loop nest is expected by
1195f2ec16ccSHideki Saito   // vectorizer.
1196f2ec16ccSHideki Saito   if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1197f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1198f2ec16ccSHideki Saito       Result = false;
1199f2ec16ccSHideki Saito     else
1200f2ec16ccSHideki Saito       return false;
1201f2ec16ccSHideki Saito   }
1202f2ec16ccSHideki Saito 
1203f2ec16ccSHideki Saito   // We need to have a loop header.
1204d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1205f2ec16ccSHideki Saito                     << '\n');
1206f2ec16ccSHideki Saito 
1207f2ec16ccSHideki Saito   // Specific checks for outer loops. We skip the remaining legal checks at this
1208f2ec16ccSHideki Saito   // point because they don't support outer loops.
120989c1e35fSStefanos Baziotis   if (!TheLoop->isInnermost()) {
1210f2ec16ccSHideki Saito     assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1211f2ec16ccSHideki Saito 
1212f2ec16ccSHideki Saito     if (!canVectorizeOuterLoop()) {
12139e97caf5SRenato Golin       reportVectorizationFailure("Unsupported outer loop",
12149e97caf5SRenato Golin                                  "unsupported outer loop",
1215ec818d7fSHideki Saito                                  "UnsupportedOuterLoop",
1216ec818d7fSHideki Saito                                  ORE, TheLoop);
1217f2ec16ccSHideki Saito       // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1218f2ec16ccSHideki Saito       // outer loops.
1219f2ec16ccSHideki Saito       return false;
1220f2ec16ccSHideki Saito     }
1221f2ec16ccSHideki Saito 
1222d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1223f2ec16ccSHideki Saito     return Result;
1224f2ec16ccSHideki Saito   }
1225f2ec16ccSHideki Saito 
122689c1e35fSStefanos Baziotis   assert(TheLoop->isInnermost() && "Inner loop expected.");
1227f2ec16ccSHideki Saito   // Check if we can if-convert non-single-bb loops.
1228f2ec16ccSHideki Saito   unsigned NumBlocks = TheLoop->getNumBlocks();
1229f2ec16ccSHideki Saito   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1230d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1231f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1232f2ec16ccSHideki Saito       Result = false;
1233f2ec16ccSHideki Saito     else
1234f2ec16ccSHideki Saito       return false;
1235f2ec16ccSHideki Saito   }
1236f2ec16ccSHideki Saito 
1237f2ec16ccSHideki Saito   // Check if we can vectorize the instructions and CFG in this loop.
1238f2ec16ccSHideki Saito   if (!canVectorizeInstrs()) {
1239d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1240f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1241f2ec16ccSHideki Saito       Result = false;
1242f2ec16ccSHideki Saito     else
1243f2ec16ccSHideki Saito       return false;
1244f2ec16ccSHideki Saito   }
1245f2ec16ccSHideki Saito 
1246f2ec16ccSHideki Saito   // Go over each instruction and look at memory deps.
1247f2ec16ccSHideki Saito   if (!canVectorizeMemory()) {
1248d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1249f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1250f2ec16ccSHideki Saito       Result = false;
1251f2ec16ccSHideki Saito     else
1252f2ec16ccSHideki Saito       return false;
1253f2ec16ccSHideki Saito   }
1254f2ec16ccSHideki Saito 
1255d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
1256f2ec16ccSHideki Saito                     << (LAI->getRuntimePointerChecking()->Need
1257f2ec16ccSHideki Saito                             ? " (with a runtime bound check)"
1258f2ec16ccSHideki Saito                             : "")
1259f2ec16ccSHideki Saito                     << "!\n");
1260f2ec16ccSHideki Saito 
1261f2ec16ccSHideki Saito   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
1262f2ec16ccSHideki Saito   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
1263f2ec16ccSHideki Saito     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
1264f2ec16ccSHideki Saito 
1265f2ec16ccSHideki Saito   if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
12669e97caf5SRenato Golin     reportVectorizationFailure("Too many SCEV checks needed",
12679e97caf5SRenato Golin         "Too many SCEV assumptions need to be made and checked at runtime",
1268ec818d7fSHideki Saito         "TooManySCEVRunTimeChecks", ORE, TheLoop);
1269f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1270f2ec16ccSHideki Saito       Result = false;
1271f2ec16ccSHideki Saito     else
1272f2ec16ccSHideki Saito       return false;
1273f2ec16ccSHideki Saito   }
1274f2ec16ccSHideki Saito 
1275f2ec16ccSHideki Saito   // Okay! We've done all the tests. If any have failed, return false. Otherwise
1276f2ec16ccSHideki Saito   // we can vectorize, and at this point we don't have any other mem analysis
1277f2ec16ccSHideki Saito   // which may limit our maximum vectorization factor, so just return true with
1278f2ec16ccSHideki Saito   // no restrictions.
1279f2ec16ccSHideki Saito   return Result;
1280f2ec16ccSHideki Saito }
1281f2ec16ccSHideki Saito 
1282d57d73daSDorit Nuzman bool LoopVectorizationLegality::prepareToFoldTailByMasking() {
1283b0b5312eSAyal Zaks 
1284b0b5312eSAyal Zaks   LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
1285b0b5312eSAyal Zaks 
1286d15df0edSAyal Zaks   SmallPtrSet<const Value *, 8> ReductionLiveOuts;
1287b0b5312eSAyal Zaks 
1288d0d38df0SDavid Green   for (auto &Reduction : getReductionVars())
1289d15df0edSAyal Zaks     ReductionLiveOuts.insert(Reduction.second.getLoopExitInstr());
1290d15df0edSAyal Zaks 
1291d15df0edSAyal Zaks   // TODO: handle non-reduction outside users when tail is folded by masking.
1292b0b5312eSAyal Zaks   for (auto *AE : AllowedExit) {
1293d15df0edSAyal Zaks     // Check that all users of allowed exit values are inside the loop or
1294d15df0edSAyal Zaks     // are the live-out of a reduction.
1295d15df0edSAyal Zaks     if (ReductionLiveOuts.count(AE))
1296d15df0edSAyal Zaks       continue;
1297b0b5312eSAyal Zaks     for (User *U : AE->users()) {
1298b0b5312eSAyal Zaks       Instruction *UI = cast<Instruction>(U);
1299b0b5312eSAyal Zaks       if (TheLoop->contains(UI))
1300b0b5312eSAyal Zaks         continue;
1301bda8fbe2SSjoerd Meijer       LLVM_DEBUG(
1302bda8fbe2SSjoerd Meijer           dbgs()
1303bda8fbe2SSjoerd Meijer           << "LV: Cannot fold tail by masking, loop has an outside user for "
1304bda8fbe2SSjoerd Meijer           << *UI << "\n");
1305b0b5312eSAyal Zaks       return false;
1306b0b5312eSAyal Zaks     }
1307b0b5312eSAyal Zaks   }
1308b0b5312eSAyal Zaks 
1309b0b5312eSAyal Zaks   // The list of pointers that we can safely read and write to remains empty.
1310b0b5312eSAyal Zaks   SmallPtrSet<Value *, 8> SafePointers;
1311b0b5312eSAyal Zaks 
1312bda8fbe2SSjoerd Meijer   SmallPtrSet<const Instruction *, 8> TmpMaskedOp;
1313bda8fbe2SSjoerd Meijer   SmallPtrSet<Instruction *, 8> TmpConditionalAssumes;
1314bda8fbe2SSjoerd Meijer 
1315b0b5312eSAyal Zaks   // Check and mark all blocks for predication, including those that ordinarily
1316b0b5312eSAyal Zaks   // do not need predication such as the header block.
1317b0b5312eSAyal Zaks   for (BasicBlock *BB : TheLoop->blocks()) {
1318bda8fbe2SSjoerd Meijer     if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp,
13194f01122cSJoachim Meyer                               TmpConditionalAssumes)) {
1320bda8fbe2SSjoerd Meijer       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as requested.\n");
1321b0b5312eSAyal Zaks       return false;
1322b0b5312eSAyal Zaks     }
1323b0b5312eSAyal Zaks   }
1324b0b5312eSAyal Zaks 
1325b0b5312eSAyal Zaks   LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
1326bda8fbe2SSjoerd Meijer 
1327bda8fbe2SSjoerd Meijer   MaskedOp.insert(TmpMaskedOp.begin(), TmpMaskedOp.end());
1328bda8fbe2SSjoerd Meijer   ConditionalAssumes.insert(TmpConditionalAssumes.begin(),
1329bda8fbe2SSjoerd Meijer                             TmpConditionalAssumes.end());
1330bda8fbe2SSjoerd Meijer 
1331b0b5312eSAyal Zaks   return true;
1332b0b5312eSAyal Zaks }
1333b0b5312eSAyal Zaks 
1334f2ec16ccSHideki Saito } // namespace llvm
1335