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 
364e4ecae0SHideki Saito extern cl::opt<bool> EnableVPlanPredication;
374e4ecae0SHideki Saito 
38f2ec16ccSHideki Saito static cl::opt<bool>
39f2ec16ccSHideki Saito     EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
40f2ec16ccSHideki Saito                        cl::desc("Enable if-conversion during vectorization."));
41f2ec16ccSHideki Saito 
429f76a852SKerry McLaughlin namespace llvm {
439f76a852SKerry McLaughlin cl::opt<bool>
449f76a852SKerry McLaughlin     HintsAllowReordering("hints-allow-reordering", cl::init(true), cl::Hidden,
459f76a852SKerry McLaughlin                          cl::desc("Allow enabling loop hints to reorder "
469f76a852SKerry McLaughlin                                   "FP operations during vectorization."));
479f76a852SKerry McLaughlin }
489f76a852SKerry McLaughlin 
49c773d0f9SFlorian Hahn // TODO: Move size-based thresholds out of legality checking, make cost based
50c773d0f9SFlorian Hahn // decisions instead of hard thresholds.
51f2ec16ccSHideki Saito static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
52f2ec16ccSHideki Saito     "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
53f2ec16ccSHideki Saito     cl::desc("The maximum number of SCEV checks allowed."));
54f2ec16ccSHideki Saito 
55f2ec16ccSHideki Saito static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
56f2ec16ccSHideki Saito     "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
57f2ec16ccSHideki Saito     cl::desc("The maximum number of SCEV checks allowed with a "
58f2ec16ccSHideki Saito              "vectorize(enable) pragma"));
59f2ec16ccSHideki Saito 
60b1ff20fdSSander de Smalen static cl::opt<LoopVectorizeHints::ScalableForceKind>
61b1ff20fdSSander de Smalen     ForceScalableVectorization(
62b1ff20fdSSander de Smalen         "scalable-vectorization", cl::init(LoopVectorizeHints::SK_Unspecified),
634f86aa65SSander de Smalen         cl::Hidden,
644f86aa65SSander de Smalen         cl::desc("Control whether the compiler can use scalable vectors to "
654f86aa65SSander de Smalen                  "vectorize a loop"),
664f86aa65SSander de Smalen         cl::values(
674f86aa65SSander de Smalen             clEnumValN(LoopVectorizeHints::SK_FixedWidthOnly, "off",
684f86aa65SSander de Smalen                        "Scalable vectorization is disabled."),
69b1ff20fdSSander de Smalen             clEnumValN(
707c68ed88SPaul Walker                 LoopVectorizeHints::SK_PreferScalable, "preferred",
717c68ed88SPaul Walker                 "Scalable vectorization is available and favored when the "
727c68ed88SPaul Walker                 "cost is inconclusive."),
737c68ed88SPaul Walker             clEnumValN(
74b1ff20fdSSander de Smalen                 LoopVectorizeHints::SK_PreferScalable, "on",
754f86aa65SSander de Smalen                 "Scalable vectorization is available and favored when the "
764f86aa65SSander de Smalen                 "cost is inconclusive.")));
774f86aa65SSander de Smalen 
78f2ec16ccSHideki Saito /// Maximum vectorization interleave count.
79f2ec16ccSHideki Saito static const unsigned MaxInterleaveFactor = 16;
80f2ec16ccSHideki Saito 
81f2ec16ccSHideki Saito namespace llvm {
82f2ec16ccSHideki Saito 
83f2ec16ccSHideki Saito bool LoopVectorizeHints::Hint::validate(unsigned Val) {
84f2ec16ccSHideki Saito   switch (Kind) {
85f2ec16ccSHideki Saito   case HK_WIDTH:
86f2ec16ccSHideki Saito     return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
87ddb3b26aSBardia Mahjour   case HK_INTERLEAVE:
88f2ec16ccSHideki Saito     return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
89f2ec16ccSHideki Saito   case HK_FORCE:
90f2ec16ccSHideki Saito     return (Val <= 1);
91f2ec16ccSHideki Saito   case HK_ISVECTORIZED:
9220b198ecSSjoerd Meijer   case HK_PREDICATE:
9371bd59f0SDavid Sherwood   case HK_SCALABLE:
94f2ec16ccSHideki Saito     return (Val == 0 || Val == 1);
95f2ec16ccSHideki Saito   }
96f2ec16ccSHideki Saito   return false;
97f2ec16ccSHideki Saito }
98f2ec16ccSHideki Saito 
99d4eb13c8SMichael Kruse LoopVectorizeHints::LoopVectorizeHints(const Loop *L,
100d4eb13c8SMichael Kruse                                        bool InterleaveOnlyWhenForced,
101b1ff20fdSSander de Smalen                                        OptimizationRemarkEmitter &ORE,
102b1ff20fdSSander de Smalen                                        const TargetTransformInfo *TTI)
103f2ec16ccSHideki Saito     : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
104ddb3b26aSBardia Mahjour       Interleave("interleave.count", InterleaveOnlyWhenForced, HK_INTERLEAVE),
105f2ec16ccSHideki Saito       Force("vectorize.enable", FK_Undefined, HK_FORCE),
10620b198ecSSjoerd Meijer       IsVectorized("isvectorized", 0, HK_ISVECTORIZED),
10771bd59f0SDavid Sherwood       Predicate("vectorize.predicate.enable", FK_Undefined, HK_PREDICATE),
1084f86aa65SSander de Smalen       Scalable("vectorize.scalable.enable", SK_Unspecified, HK_SCALABLE),
1094f86aa65SSander de Smalen       TheLoop(L), ORE(ORE) {
110f2ec16ccSHideki Saito   // Populate values with existing loop metadata.
111f2ec16ccSHideki Saito   getHintsFromMetadata();
112f2ec16ccSHideki Saito 
113f2ec16ccSHideki Saito   // force-vector-interleave overrides DisableInterleaving.
114f2ec16ccSHideki Saito   if (VectorizerParams::isInterleaveForced())
115f2ec16ccSHideki Saito     Interleave.Value = VectorizerParams::VectorizationInterleave;
116f2ec16ccSHideki Saito 
117b1ff20fdSSander de Smalen   // If the metadata doesn't explicitly specify whether to enable scalable
118b1ff20fdSSander de Smalen   // vectorization, then decide based on the following criteria (increasing
119b1ff20fdSSander de Smalen   // level of priority):
120b1ff20fdSSander de Smalen   //  - Target default
121b1ff20fdSSander de Smalen   //  - Metadata width
122b1ff20fdSSander de Smalen   //  - Force option (always overrides)
123b1ff20fdSSander de Smalen   if ((LoopVectorizeHints::ScalableForceKind)Scalable.Value == SK_Unspecified) {
124b1ff20fdSSander de Smalen     if (TTI)
125b1ff20fdSSander de Smalen       Scalable.Value = TTI->enableScalableVectorization() ? SK_PreferScalable
126b1ff20fdSSander de Smalen                                                           : SK_FixedWidthOnly;
127b1ff20fdSSander de Smalen 
128b1ff20fdSSander de Smalen     if (Width.Value)
1294f86aa65SSander de Smalen       // If the width is set, but the metadata says nothing about the scalable
1304f86aa65SSander de Smalen       // property, then assume it concerns only a fixed-width UserVF.
1314f86aa65SSander de Smalen       // If width is not set, the flag takes precedence.
132b1ff20fdSSander de Smalen       Scalable.Value = SK_FixedWidthOnly;
133b1ff20fdSSander de Smalen   }
134b1ff20fdSSander de Smalen 
135b1ff20fdSSander de Smalen   // If the flag is set to force any use of scalable vectors, override the loop
136b1ff20fdSSander de Smalen   // hints.
137b1ff20fdSSander de Smalen   if (ForceScalableVectorization.getValue() !=
138b1ff20fdSSander de Smalen       LoopVectorizeHints::SK_Unspecified)
139b1ff20fdSSander de Smalen     Scalable.Value = ForceScalableVectorization.getValue();
140b1ff20fdSSander de Smalen 
141b1ff20fdSSander de Smalen   // Scalable vectorization is disabled if no preference is specified.
142b1ff20fdSSander de Smalen   if ((LoopVectorizeHints::ScalableForceKind)Scalable.Value == SK_Unspecified)
1434f86aa65SSander de Smalen     Scalable.Value = SK_FixedWidthOnly;
1444f86aa65SSander de Smalen 
145f2ec16ccSHideki Saito   if (IsVectorized.Value != 1)
146f2ec16ccSHideki Saito     // If the vectorization width and interleaving count are both 1 then
147f2ec16ccSHideki Saito     // consider the loop to have been already vectorized because there's
148f2ec16ccSHideki Saito     // nothing more that we can do.
14971bd59f0SDavid Sherwood     IsVectorized.Value =
150ddb3b26aSBardia Mahjour         getWidth() == ElementCount::getFixed(1) && getInterleave() == 1;
151ddb3b26aSBardia Mahjour   LLVM_DEBUG(if (InterleaveOnlyWhenForced && getInterleave() == 1) dbgs()
152f2ec16ccSHideki Saito              << "LV: Interleaving disabled by the pass manager\n");
153f2ec16ccSHideki Saito }
154f2ec16ccSHideki Saito 
15577a614a6SMichael Kruse void LoopVectorizeHints::setAlreadyVectorized() {
15677a614a6SMichael Kruse   LLVMContext &Context = TheLoop->getHeader()->getContext();
15777a614a6SMichael Kruse 
15877a614a6SMichael Kruse   MDNode *IsVectorizedMD = MDNode::get(
15977a614a6SMichael Kruse       Context,
16077a614a6SMichael Kruse       {MDString::get(Context, "llvm.loop.isvectorized"),
16177a614a6SMichael Kruse        ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))});
16277a614a6SMichael Kruse   MDNode *LoopID = TheLoop->getLoopID();
16377a614a6SMichael Kruse   MDNode *NewLoopID =
16477a614a6SMichael Kruse       makePostTransformationMetadata(Context, LoopID,
16577a614a6SMichael Kruse                                      {Twine(Prefix(), "vectorize.").str(),
16677a614a6SMichael Kruse                                       Twine(Prefix(), "interleave.").str()},
16777a614a6SMichael Kruse                                      {IsVectorizedMD});
16877a614a6SMichael Kruse   TheLoop->setLoopID(NewLoopID);
16977a614a6SMichael Kruse 
17077a614a6SMichael Kruse   // Update internal cache.
17177a614a6SMichael Kruse   IsVectorized.Value = 1;
17277a614a6SMichael Kruse }
17377a614a6SMichael Kruse 
174d4eb13c8SMichael Kruse bool LoopVectorizeHints::allowVectorization(
175d4eb13c8SMichael Kruse     Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
176f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Disabled) {
177d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
178f2ec16ccSHideki Saito     emitRemarkWithHints();
179f2ec16ccSHideki Saito     return false;
180f2ec16ccSHideki Saito   }
181f2ec16ccSHideki Saito 
182d4eb13c8SMichael Kruse   if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
183d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
184f2ec16ccSHideki Saito     emitRemarkWithHints();
185f2ec16ccSHideki Saito     return false;
186f2ec16ccSHideki Saito   }
187f2ec16ccSHideki Saito 
188f2ec16ccSHideki Saito   if (getIsVectorized() == 1) {
189d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
190f2ec16ccSHideki Saito     // FIXME: Add interleave.disable metadata. This will allow
191f2ec16ccSHideki Saito     // vectorize.disable to be used without disabling the pass and errors
192f2ec16ccSHideki Saito     // to differentiate between disabled vectorization and a width of 1.
193f2ec16ccSHideki Saito     ORE.emit([&]() {
194f2ec16ccSHideki Saito       return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
195f2ec16ccSHideki Saito                                         "AllDisabled", L->getStartLoc(),
196f2ec16ccSHideki Saito                                         L->getHeader())
197f2ec16ccSHideki Saito              << "loop not vectorized: vectorization and interleaving are "
198f2ec16ccSHideki Saito                 "explicitly disabled, or the loop has already been "
199f2ec16ccSHideki Saito                 "vectorized";
200f2ec16ccSHideki Saito     });
201f2ec16ccSHideki Saito     return false;
202f2ec16ccSHideki Saito   }
203f2ec16ccSHideki Saito 
204f2ec16ccSHideki Saito   return true;
205f2ec16ccSHideki Saito }
206f2ec16ccSHideki Saito 
207f2ec16ccSHideki Saito void LoopVectorizeHints::emitRemarkWithHints() const {
208f2ec16ccSHideki Saito   using namespace ore;
209f2ec16ccSHideki Saito 
210f2ec16ccSHideki Saito   ORE.emit([&]() {
211f2ec16ccSHideki Saito     if (Force.Value == LoopVectorizeHints::FK_Disabled)
212f2ec16ccSHideki Saito       return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
213f2ec16ccSHideki Saito                                       TheLoop->getStartLoc(),
214f2ec16ccSHideki Saito                                       TheLoop->getHeader())
215f2ec16ccSHideki Saito              << "loop not vectorized: vectorization is explicitly disabled";
216f2ec16ccSHideki Saito     else {
217f2ec16ccSHideki Saito       OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
218f2ec16ccSHideki Saito                                  TheLoop->getStartLoc(), TheLoop->getHeader());
219f2ec16ccSHideki Saito       R << "loop not vectorized";
220f2ec16ccSHideki Saito       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
221f2ec16ccSHideki Saito         R << " (Force=" << NV("Force", true);
222f2ec16ccSHideki Saito         if (Width.Value != 0)
22371bd59f0SDavid Sherwood           R << ", Vector Width=" << NV("VectorWidth", getWidth());
224ddb3b26aSBardia Mahjour         if (getInterleave() != 0)
225ddb3b26aSBardia Mahjour           R << ", Interleave Count=" << NV("InterleaveCount", getInterleave());
226f2ec16ccSHideki Saito         R << ")";
227f2ec16ccSHideki Saito       }
228f2ec16ccSHideki Saito       return R;
229f2ec16ccSHideki Saito     }
230f2ec16ccSHideki Saito   });
231f2ec16ccSHideki Saito }
232f2ec16ccSHideki Saito 
233f2ec16ccSHideki Saito const char *LoopVectorizeHints::vectorizeAnalysisPassName() const {
23471bd59f0SDavid Sherwood   if (getWidth() == ElementCount::getFixed(1))
235f2ec16ccSHideki Saito     return LV_NAME;
236f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Disabled)
237f2ec16ccSHideki Saito     return LV_NAME;
23871bd59f0SDavid Sherwood   if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth().isZero())
239f2ec16ccSHideki Saito     return LV_NAME;
240f2ec16ccSHideki Saito   return OptimizationRemarkAnalysis::AlwaysPrint;
241f2ec16ccSHideki Saito }
242f2ec16ccSHideki Saito 
2439f76a852SKerry McLaughlin bool LoopVectorizeHints::allowReordering() const {
2449f76a852SKerry McLaughlin   // Allow the vectorizer to change the order of operations if enabling
2459f76a852SKerry McLaughlin   // loop hints are provided
2469f76a852SKerry McLaughlin   ElementCount EC = getWidth();
2479f76a852SKerry McLaughlin   return HintsAllowReordering &&
2489f76a852SKerry McLaughlin          (getForce() == LoopVectorizeHints::FK_Enabled ||
2499f76a852SKerry McLaughlin           EC.getKnownMinValue() > 1);
2509f76a852SKerry McLaughlin }
2519f76a852SKerry McLaughlin 
252f2ec16ccSHideki Saito void LoopVectorizeHints::getHintsFromMetadata() {
253f2ec16ccSHideki Saito   MDNode *LoopID = TheLoop->getLoopID();
254f2ec16ccSHideki Saito   if (!LoopID)
255f2ec16ccSHideki Saito     return;
256f2ec16ccSHideki Saito 
257f2ec16ccSHideki Saito   // First operand should refer to the loop id itself.
258f2ec16ccSHideki Saito   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
259f2ec16ccSHideki Saito   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
260f2ec16ccSHideki Saito 
261f2ec16ccSHideki Saito   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
262f2ec16ccSHideki Saito     const MDString *S = nullptr;
263f2ec16ccSHideki Saito     SmallVector<Metadata *, 4> Args;
264f2ec16ccSHideki Saito 
265f2ec16ccSHideki Saito     // The expected hint is either a MDString or a MDNode with the first
266f2ec16ccSHideki Saito     // operand a MDString.
267f2ec16ccSHideki Saito     if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
268f2ec16ccSHideki Saito       if (!MD || MD->getNumOperands() == 0)
269f2ec16ccSHideki Saito         continue;
270f2ec16ccSHideki Saito       S = dyn_cast<MDString>(MD->getOperand(0));
271f2ec16ccSHideki Saito       for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
272f2ec16ccSHideki Saito         Args.push_back(MD->getOperand(i));
273f2ec16ccSHideki Saito     } else {
274f2ec16ccSHideki Saito       S = dyn_cast<MDString>(LoopID->getOperand(i));
275f2ec16ccSHideki Saito       assert(Args.size() == 0 && "too many arguments for MDString");
276f2ec16ccSHideki Saito     }
277f2ec16ccSHideki Saito 
278f2ec16ccSHideki Saito     if (!S)
279f2ec16ccSHideki Saito       continue;
280f2ec16ccSHideki Saito 
281f2ec16ccSHideki Saito     // Check if the hint starts with the loop metadata prefix.
282f2ec16ccSHideki Saito     StringRef Name = S->getString();
283f2ec16ccSHideki Saito     if (Args.size() == 1)
284f2ec16ccSHideki Saito       setHint(Name, Args[0]);
285f2ec16ccSHideki Saito   }
286f2ec16ccSHideki Saito }
287f2ec16ccSHideki Saito 
288f2ec16ccSHideki Saito void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
289f2ec16ccSHideki Saito   if (!Name.startswith(Prefix()))
290f2ec16ccSHideki Saito     return;
291f2ec16ccSHideki Saito   Name = Name.substr(Prefix().size(), StringRef::npos);
292f2ec16ccSHideki Saito 
293f2ec16ccSHideki Saito   const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
294f2ec16ccSHideki Saito   if (!C)
295f2ec16ccSHideki Saito     return;
296f2ec16ccSHideki Saito   unsigned Val = C->getZExtValue();
297f2ec16ccSHideki Saito 
29871bd59f0SDavid Sherwood   Hint *Hints[] = {&Width,        &Interleave, &Force,
29971bd59f0SDavid Sherwood                    &IsVectorized, &Predicate,  &Scalable};
300f2ec16ccSHideki Saito   for (auto H : Hints) {
301f2ec16ccSHideki Saito     if (Name == H->Name) {
302f2ec16ccSHideki Saito       if (H->validate(Val))
303f2ec16ccSHideki Saito         H->Value = Val;
304f2ec16ccSHideki Saito       else
305d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
306f2ec16ccSHideki Saito       break;
307f2ec16ccSHideki Saito     }
308f2ec16ccSHideki Saito   }
309f2ec16ccSHideki Saito }
310f2ec16ccSHideki Saito 
311f2ec16ccSHideki Saito // Return true if the inner loop \p Lp is uniform with regard to the outer loop
312f2ec16ccSHideki Saito // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
313f2ec16ccSHideki Saito // executing the inner loop will execute the same iterations). This check is
314f2ec16ccSHideki Saito // very constrained for now but it will be relaxed in the future. \p Lp is
315f2ec16ccSHideki Saito // considered uniform if it meets all the following conditions:
316f2ec16ccSHideki Saito //   1) it has a canonical IV (starting from 0 and with stride 1),
317f2ec16ccSHideki Saito //   2) its latch terminator is a conditional branch and,
318f2ec16ccSHideki Saito //   3) its latch condition is a compare instruction whose operands are the
319f2ec16ccSHideki Saito //      canonical IV and an OuterLp invariant.
320f2ec16ccSHideki Saito // This check doesn't take into account the uniformity of other conditions not
321f2ec16ccSHideki Saito // related to the loop latch because they don't affect the loop uniformity.
322f2ec16ccSHideki Saito //
323f2ec16ccSHideki Saito // NOTE: We decided to keep all these checks and its associated documentation
324f2ec16ccSHideki Saito // together so that we can easily have a picture of the current supported loop
325f2ec16ccSHideki Saito // nests. However, some of the current checks don't depend on \p OuterLp and
326f2ec16ccSHideki Saito // would be redundantly executed for each \p Lp if we invoked this function for
327f2ec16ccSHideki Saito // different candidate outer loops. This is not the case for now because we
328f2ec16ccSHideki Saito // don't currently have the infrastructure to evaluate multiple candidate outer
329f2ec16ccSHideki Saito // loops and \p OuterLp will be a fixed parameter while we only support explicit
330f2ec16ccSHideki Saito // outer loop vectorization. It's also very likely that these checks go away
331f2ec16ccSHideki Saito // before introducing the aforementioned infrastructure. However, if this is not
332f2ec16ccSHideki Saito // the case, we should move the \p OuterLp independent checks to a separate
333f2ec16ccSHideki Saito // function that is only executed once for each \p Lp.
334f2ec16ccSHideki Saito static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
335f2ec16ccSHideki Saito   assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
336f2ec16ccSHideki Saito 
337f2ec16ccSHideki Saito   // If Lp is the outer loop, it's uniform by definition.
338f2ec16ccSHideki Saito   if (Lp == OuterLp)
339f2ec16ccSHideki Saito     return true;
340f2ec16ccSHideki Saito   assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
341f2ec16ccSHideki Saito 
342f2ec16ccSHideki Saito   // 1.
343f2ec16ccSHideki Saito   PHINode *IV = Lp->getCanonicalInductionVariable();
344f2ec16ccSHideki Saito   if (!IV) {
345d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
346f2ec16ccSHideki Saito     return false;
347f2ec16ccSHideki Saito   }
348f2ec16ccSHideki Saito 
349f2ec16ccSHideki Saito   // 2.
350f2ec16ccSHideki Saito   BasicBlock *Latch = Lp->getLoopLatch();
351f2ec16ccSHideki Saito   auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
352f2ec16ccSHideki Saito   if (!LatchBr || LatchBr->isUnconditional()) {
353d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
354f2ec16ccSHideki Saito     return false;
355f2ec16ccSHideki Saito   }
356f2ec16ccSHideki Saito 
357f2ec16ccSHideki Saito   // 3.
358f2ec16ccSHideki Saito   auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
359f2ec16ccSHideki Saito   if (!LatchCmp) {
360d34e60caSNicola Zaghen     LLVM_DEBUG(
361d34e60caSNicola Zaghen         dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
362f2ec16ccSHideki Saito     return false;
363f2ec16ccSHideki Saito   }
364f2ec16ccSHideki Saito 
365f2ec16ccSHideki Saito   Value *CondOp0 = LatchCmp->getOperand(0);
366f2ec16ccSHideki Saito   Value *CondOp1 = LatchCmp->getOperand(1);
367f2ec16ccSHideki Saito   Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
368f2ec16ccSHideki Saito   if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
369f2ec16ccSHideki Saito       !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
370d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
371f2ec16ccSHideki Saito     return false;
372f2ec16ccSHideki Saito   }
373f2ec16ccSHideki Saito 
374f2ec16ccSHideki Saito   return true;
375f2ec16ccSHideki Saito }
376f2ec16ccSHideki Saito 
377f2ec16ccSHideki Saito // Return true if \p Lp and all its nested loops are uniform with regard to \p
378f2ec16ccSHideki Saito // OuterLp.
379f2ec16ccSHideki Saito static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
380f2ec16ccSHideki Saito   if (!isUniformLoop(Lp, OuterLp))
381f2ec16ccSHideki Saito     return false;
382f2ec16ccSHideki Saito 
383f2ec16ccSHideki Saito   // Check if nested loops are uniform.
384f2ec16ccSHideki Saito   for (Loop *SubLp : *Lp)
385f2ec16ccSHideki Saito     if (!isUniformLoopNest(SubLp, OuterLp))
386f2ec16ccSHideki Saito       return false;
387f2ec16ccSHideki Saito 
388f2ec16ccSHideki Saito   return true;
389f2ec16ccSHideki Saito }
390f2ec16ccSHideki Saito 
3915f8f34e4SAdrian Prantl /// Check whether it is safe to if-convert this phi node.
392f2ec16ccSHideki Saito ///
393f2ec16ccSHideki Saito /// Phi nodes with constant expressions that can trap are not safe to if
394f2ec16ccSHideki Saito /// convert.
395f2ec16ccSHideki Saito static bool canIfConvertPHINodes(BasicBlock *BB) {
396f2ec16ccSHideki Saito   for (PHINode &Phi : BB->phis()) {
397f2ec16ccSHideki Saito     for (Value *V : Phi.incoming_values())
398f2ec16ccSHideki Saito       if (auto *C = dyn_cast<Constant>(V))
399f2ec16ccSHideki Saito         if (C->canTrap())
400f2ec16ccSHideki Saito           return false;
401f2ec16ccSHideki Saito   }
402f2ec16ccSHideki Saito   return true;
403f2ec16ccSHideki Saito }
404f2ec16ccSHideki Saito 
405f2ec16ccSHideki Saito static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
406f2ec16ccSHideki Saito   if (Ty->isPointerTy())
407f2ec16ccSHideki Saito     return DL.getIntPtrType(Ty);
408f2ec16ccSHideki Saito 
409f2ec16ccSHideki Saito   // It is possible that char's or short's overflow when we ask for the loop's
410f2ec16ccSHideki Saito   // trip count, work around this by changing the type size.
411f2ec16ccSHideki Saito   if (Ty->getScalarSizeInBits() < 32)
412f2ec16ccSHideki Saito     return Type::getInt32Ty(Ty->getContext());
413f2ec16ccSHideki Saito 
414f2ec16ccSHideki Saito   return Ty;
415f2ec16ccSHideki Saito }
416f2ec16ccSHideki Saito 
417f2ec16ccSHideki Saito static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
418f2ec16ccSHideki Saito   Ty0 = convertPointerToIntegerType(DL, Ty0);
419f2ec16ccSHideki Saito   Ty1 = convertPointerToIntegerType(DL, Ty1);
420f2ec16ccSHideki Saito   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
421f2ec16ccSHideki Saito     return Ty0;
422f2ec16ccSHideki Saito   return Ty1;
423f2ec16ccSHideki Saito }
424f2ec16ccSHideki Saito 
4255f8f34e4SAdrian Prantl /// Check that the instruction has outside loop users and is not an
426f2ec16ccSHideki Saito /// identified reduction variable.
427f2ec16ccSHideki Saito static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
428f2ec16ccSHideki Saito                                SmallPtrSetImpl<Value *> &AllowedExit) {
42960a1e4ddSAnna Thomas   // Reductions, Inductions and non-header phis are allowed to have exit users. All
430f2ec16ccSHideki Saito   // other instructions must not have external users.
431f2ec16ccSHideki Saito   if (!AllowedExit.count(Inst))
432f2ec16ccSHideki Saito     // Check that all of the users of the loop are inside the BB.
433f2ec16ccSHideki Saito     for (User *U : Inst->users()) {
434f2ec16ccSHideki Saito       Instruction *UI = cast<Instruction>(U);
435f2ec16ccSHideki Saito       // This user may be a reduction exit value.
436f2ec16ccSHideki Saito       if (!TheLoop->contains(UI)) {
437d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
438f2ec16ccSHideki Saito         return true;
439f2ec16ccSHideki Saito       }
440f2ec16ccSHideki Saito     }
441f2ec16ccSHideki Saito   return false;
442f2ec16ccSHideki Saito }
443f2ec16ccSHideki Saito 
44445c46734SNikita Popov int LoopVectorizationLegality::isConsecutivePtr(Type *AccessTy,
44545c46734SNikita Popov                                                 Value *Ptr) const {
446f2ec16ccSHideki Saito   const ValueToValueMap &Strides =
447f2ec16ccSHideki Saito       getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
448f2ec16ccSHideki Saito 
4497bedae7dSHiroshi Yamauchi   Function *F = TheLoop->getHeader()->getParent();
4507bedae7dSHiroshi Yamauchi   bool OptForSize = F->hasOptSize() ||
4517bedae7dSHiroshi Yamauchi                     llvm::shouldOptimizeForSize(TheLoop->getHeader(), PSI, BFI,
4527bedae7dSHiroshi Yamauchi                                                 PGSOQueryType::IRPass);
4537bedae7dSHiroshi Yamauchi   bool CanAddPredicate = !OptForSize;
45445c46734SNikita Popov   int Stride = getPtrStride(PSE, AccessTy, Ptr, TheLoop, Strides,
45545c46734SNikita Popov                             CanAddPredicate, false);
456f2ec16ccSHideki Saito   if (Stride == 1 || Stride == -1)
457f2ec16ccSHideki Saito     return Stride;
458f2ec16ccSHideki Saito   return 0;
459f2ec16ccSHideki Saito }
460f2ec16ccSHideki Saito 
461f2ec16ccSHideki Saito bool LoopVectorizationLegality::isUniform(Value *V) {
462f2ec16ccSHideki Saito   return LAI->isUniform(V);
463f2ec16ccSHideki Saito }
464f2ec16ccSHideki Saito 
465f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeOuterLoop() {
46689c1e35fSStefanos Baziotis   assert(!TheLoop->isInnermost() && "We are not vectorizing an outer loop.");
467f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
468f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
469f2ec16ccSHideki Saito   bool Result = true;
470f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
471f2ec16ccSHideki Saito 
472f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
473f2ec16ccSHideki Saito     // Check whether the BB terminator is a BranchInst. Any other terminator is
474f2ec16ccSHideki Saito     // not supported yet.
475f2ec16ccSHideki Saito     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
476f2ec16ccSHideki Saito     if (!Br) {
4779e97caf5SRenato Golin       reportVectorizationFailure("Unsupported basic block terminator",
4789e97caf5SRenato Golin           "loop control flow is not understood by vectorizer",
479ec818d7fSHideki Saito           "CFGNotUnderstood", ORE, TheLoop);
480f2ec16ccSHideki Saito       if (DoExtraAnalysis)
481f2ec16ccSHideki Saito         Result = false;
482f2ec16ccSHideki Saito       else
483f2ec16ccSHideki Saito         return false;
484f2ec16ccSHideki Saito     }
485f2ec16ccSHideki Saito 
486f2ec16ccSHideki Saito     // Check whether the BranchInst is a supported one. Only unconditional
487f2ec16ccSHideki Saito     // branches, conditional branches with an outer loop invariant condition or
488f2ec16ccSHideki Saito     // backedges are supported.
4894e4ecae0SHideki Saito     // FIXME: We skip these checks when VPlan predication is enabled as we
4904e4ecae0SHideki Saito     // want to allow divergent branches. This whole check will be removed
4914e4ecae0SHideki Saito     // once VPlan predication is on by default.
4924e4ecae0SHideki Saito     if (!EnableVPlanPredication && Br && Br->isConditional() &&
493f2ec16ccSHideki Saito         !TheLoop->isLoopInvariant(Br->getCondition()) &&
494f2ec16ccSHideki Saito         !LI->isLoopHeader(Br->getSuccessor(0)) &&
495f2ec16ccSHideki Saito         !LI->isLoopHeader(Br->getSuccessor(1))) {
4969e97caf5SRenato Golin       reportVectorizationFailure("Unsupported conditional branch",
4979e97caf5SRenato Golin           "loop control flow is not understood by vectorizer",
498ec818d7fSHideki Saito           "CFGNotUnderstood", ORE, TheLoop);
499f2ec16ccSHideki Saito       if (DoExtraAnalysis)
500f2ec16ccSHideki Saito         Result = false;
501f2ec16ccSHideki Saito       else
502f2ec16ccSHideki Saito         return false;
503f2ec16ccSHideki Saito     }
504f2ec16ccSHideki Saito   }
505f2ec16ccSHideki Saito 
506f2ec16ccSHideki Saito   // Check whether inner loops are uniform. At this point, we only support
507f2ec16ccSHideki Saito   // simple outer loops scenarios with uniform nested loops.
508f2ec16ccSHideki Saito   if (!isUniformLoopNest(TheLoop /*loop nest*/,
509f2ec16ccSHideki Saito                          TheLoop /*context outer loop*/)) {
5109e97caf5SRenato Golin     reportVectorizationFailure("Outer loop contains divergent loops",
5119e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
512ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
513f2ec16ccSHideki Saito     if (DoExtraAnalysis)
514f2ec16ccSHideki Saito       Result = false;
515f2ec16ccSHideki Saito     else
516f2ec16ccSHideki Saito       return false;
517f2ec16ccSHideki Saito   }
518f2ec16ccSHideki Saito 
519ea7f3035SHideki Saito   // Check whether we are able to set up outer loop induction.
520ea7f3035SHideki Saito   if (!setupOuterLoopInductions()) {
5219e97caf5SRenato Golin     reportVectorizationFailure("Unsupported outer loop Phi(s)",
5229e97caf5SRenato Golin                                "Unsupported outer loop Phi(s)",
523ec818d7fSHideki Saito                                "UnsupportedPhi", ORE, TheLoop);
524ea7f3035SHideki Saito     if (DoExtraAnalysis)
525ea7f3035SHideki Saito       Result = false;
526ea7f3035SHideki Saito     else
527ea7f3035SHideki Saito       return false;
528ea7f3035SHideki Saito   }
529ea7f3035SHideki Saito 
530f2ec16ccSHideki Saito   return Result;
531f2ec16ccSHideki Saito }
532f2ec16ccSHideki Saito 
533f2ec16ccSHideki Saito void LoopVectorizationLegality::addInductionPhi(
534f2ec16ccSHideki Saito     PHINode *Phi, const InductionDescriptor &ID,
535f2ec16ccSHideki Saito     SmallPtrSetImpl<Value *> &AllowedExit) {
536f2ec16ccSHideki Saito   Inductions[Phi] = ID;
537f2ec16ccSHideki Saito 
538f2ec16ccSHideki Saito   // In case this induction also comes with casts that we know we can ignore
539f2ec16ccSHideki Saito   // in the vectorized loop body, record them here. All casts could be recorded
540f2ec16ccSHideki Saito   // here for ignoring, but suffices to record only the first (as it is the
541f2ec16ccSHideki Saito   // only one that may bw used outside the cast sequence).
542f2ec16ccSHideki Saito   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
543f2ec16ccSHideki Saito   if (!Casts.empty())
544f2ec16ccSHideki Saito     InductionCastsToIgnore.insert(*Casts.begin());
545f2ec16ccSHideki Saito 
546f2ec16ccSHideki Saito   Type *PhiTy = Phi->getType();
547f2ec16ccSHideki Saito   const DataLayout &DL = Phi->getModule()->getDataLayout();
548f2ec16ccSHideki Saito 
549f2ec16ccSHideki Saito   // Get the widest type.
550f2ec16ccSHideki Saito   if (!PhiTy->isFloatingPointTy()) {
551f2ec16ccSHideki Saito     if (!WidestIndTy)
552f2ec16ccSHideki Saito       WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
553f2ec16ccSHideki Saito     else
554f2ec16ccSHideki Saito       WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
555f2ec16ccSHideki Saito   }
556f2ec16ccSHideki Saito 
557f2ec16ccSHideki Saito   // Int inductions are special because we only allow one IV.
558f2ec16ccSHideki Saito   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
559f2ec16ccSHideki Saito       ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
560f2ec16ccSHideki Saito       isa<Constant>(ID.getStartValue()) &&
561f2ec16ccSHideki Saito       cast<Constant>(ID.getStartValue())->isNullValue()) {
562f2ec16ccSHideki Saito 
563f2ec16ccSHideki Saito     // Use the phi node with the widest type as induction. Use the last
564f2ec16ccSHideki Saito     // one if there are multiple (no good reason for doing this other
565f2ec16ccSHideki Saito     // than it is expedient). We've checked that it begins at zero and
566f2ec16ccSHideki Saito     // steps by one, so this is a canonical induction variable.
567f2ec16ccSHideki Saito     if (!PrimaryInduction || PhiTy == WidestIndTy)
568f2ec16ccSHideki Saito       PrimaryInduction = Phi;
569f2ec16ccSHideki Saito   }
570f2ec16ccSHideki Saito 
571f2ec16ccSHideki Saito   // Both the PHI node itself, and the "post-increment" value feeding
572f2ec16ccSHideki Saito   // back into the PHI node may have external users.
573f2ec16ccSHideki Saito   // We can allow those uses, except if the SCEVs we have for them rely
574f2ec16ccSHideki Saito   // on predicates that only hold within the loop, since allowing the exit
5756a1dd77fSAnna Thomas   // currently means re-using this SCEV outside the loop (see PR33706 for more
5766a1dd77fSAnna Thomas   // details).
5775ba11503SPhilip Reames   if (PSE.getPredicate().isAlwaysTrue()) {
578f2ec16ccSHideki Saito     AllowedExit.insert(Phi);
579f2ec16ccSHideki Saito     AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
580f2ec16ccSHideki Saito   }
581f2ec16ccSHideki Saito 
582d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
583f2ec16ccSHideki Saito }
584f2ec16ccSHideki Saito 
585ea7f3035SHideki Saito bool LoopVectorizationLegality::setupOuterLoopInductions() {
586ea7f3035SHideki Saito   BasicBlock *Header = TheLoop->getHeader();
587ea7f3035SHideki Saito 
588ea7f3035SHideki Saito   // Returns true if a given Phi is a supported induction.
589ea7f3035SHideki Saito   auto isSupportedPhi = [&](PHINode &Phi) -> bool {
590ea7f3035SHideki Saito     InductionDescriptor ID;
591ea7f3035SHideki Saito     if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
592ea7f3035SHideki Saito         ID.getKind() == InductionDescriptor::IK_IntInduction) {
593ea7f3035SHideki Saito       addInductionPhi(&Phi, ID, AllowedExit);
594ea7f3035SHideki Saito       return true;
595ea7f3035SHideki Saito     } else {
596ea7f3035SHideki Saito       // Bail out for any Phi in the outer loop header that is not a supported
597ea7f3035SHideki Saito       // induction.
598ea7f3035SHideki Saito       LLVM_DEBUG(
599ea7f3035SHideki Saito           dbgs()
600ea7f3035SHideki Saito           << "LV: Found unsupported PHI for outer loop vectorization.\n");
601ea7f3035SHideki Saito       return false;
602ea7f3035SHideki Saito     }
603ea7f3035SHideki Saito   };
604ea7f3035SHideki Saito 
605ea7f3035SHideki Saito   if (llvm::all_of(Header->phis(), isSupportedPhi))
606ea7f3035SHideki Saito     return true;
607ea7f3035SHideki Saito   else
608ea7f3035SHideki Saito     return false;
609ea7f3035SHideki Saito }
610ea7f3035SHideki Saito 
61166c120f0SFrancesco Petrogalli /// Checks if a function is scalarizable according to the TLI, in
61266c120f0SFrancesco Petrogalli /// the sense that it should be vectorized and then expanded in
61366c120f0SFrancesco Petrogalli /// multiple scalar calls. This is represented in the
61466c120f0SFrancesco Petrogalli /// TLI via mappings that do not specify a vector name, as in the
61566c120f0SFrancesco Petrogalli /// following example:
61666c120f0SFrancesco Petrogalli ///
61766c120f0SFrancesco Petrogalli ///    const VecDesc VecIntrinsics[] = {
61866c120f0SFrancesco Petrogalli ///      {"llvm.phx.abs.i32", "", 4}
61966c120f0SFrancesco Petrogalli ///    };
62066c120f0SFrancesco Petrogalli static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI) {
62166c120f0SFrancesco Petrogalli   const StringRef ScalarName = CI.getCalledFunction()->getName();
62266c120f0SFrancesco Petrogalli   bool Scalarize = TLI.isFunctionVectorizable(ScalarName);
62366c120f0SFrancesco Petrogalli   // Check that all known VFs are not associated to a vector
62466c120f0SFrancesco Petrogalli   // function, i.e. the vector name is emty.
62501b87444SDavid Sherwood   if (Scalarize) {
62601b87444SDavid Sherwood     ElementCount WidestFixedVF, WidestScalableVF;
62701b87444SDavid Sherwood     TLI.getWidestVF(ScalarName, WidestFixedVF, WidestScalableVF);
62801b87444SDavid Sherwood     for (ElementCount VF = ElementCount::getFixed(2);
62901b87444SDavid Sherwood          ElementCount::isKnownLE(VF, WidestFixedVF); VF *= 2)
63066c120f0SFrancesco Petrogalli       Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
63101b87444SDavid Sherwood     for (ElementCount VF = ElementCount::getScalable(1);
63201b87444SDavid Sherwood          ElementCount::isKnownLE(VF, WidestScalableVF); VF *= 2)
63301b87444SDavid Sherwood       Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
63401b87444SDavid Sherwood     assert((WidestScalableVF.isZero() || !Scalarize) &&
63501b87444SDavid Sherwood            "Caller may decide to scalarize a variant using a scalable VF");
63666c120f0SFrancesco Petrogalli   }
63766c120f0SFrancesco Petrogalli   return Scalarize;
63866c120f0SFrancesco Petrogalli }
63966c120f0SFrancesco Petrogalli 
640f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeInstrs() {
641f2ec16ccSHideki Saito   BasicBlock *Header = TheLoop->getHeader();
642f2ec16ccSHideki Saito 
643f2ec16ccSHideki Saito   // For each block in the loop.
644f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
645f2ec16ccSHideki Saito     // Scan the instructions in the block and look for hazards.
646f2ec16ccSHideki Saito     for (Instruction &I : *BB) {
647f2ec16ccSHideki Saito       if (auto *Phi = dyn_cast<PHINode>(&I)) {
648f2ec16ccSHideki Saito         Type *PhiTy = Phi->getType();
649f2ec16ccSHideki Saito         // Check that this PHI type is allowed.
650f2ec16ccSHideki Saito         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
651f2ec16ccSHideki Saito             !PhiTy->isPointerTy()) {
6529e97caf5SRenato Golin           reportVectorizationFailure("Found a non-int non-pointer PHI",
6539e97caf5SRenato Golin                                      "loop control flow is not understood by vectorizer",
654ec818d7fSHideki Saito                                      "CFGNotUnderstood", ORE, TheLoop);
655f2ec16ccSHideki Saito           return false;
656f2ec16ccSHideki Saito         }
657f2ec16ccSHideki Saito 
658f2ec16ccSHideki Saito         // If this PHINode is not in the header block, then we know that we
659f2ec16ccSHideki Saito         // can convert it to select during if-conversion. No need to check if
660f2ec16ccSHideki Saito         // the PHIs in this block are induction or reduction variables.
661f2ec16ccSHideki Saito         if (BB != Header) {
66260a1e4ddSAnna Thomas           // Non-header phi nodes that have outside uses can be vectorized. Add
66360a1e4ddSAnna Thomas           // them to the list of allowed exits.
66460a1e4ddSAnna Thomas           // Unsafe cyclic dependencies with header phis are identified during
66560a1e4ddSAnna Thomas           // legalization for reduction, induction and first order
66660a1e4ddSAnna Thomas           // recurrences.
667dd18ce45SBjorn Pettersson           AllowedExit.insert(&I);
668f2ec16ccSHideki Saito           continue;
669f2ec16ccSHideki Saito         }
670f2ec16ccSHideki Saito 
671f2ec16ccSHideki Saito         // We only allow if-converted PHIs with exactly two incoming values.
672f2ec16ccSHideki Saito         if (Phi->getNumIncomingValues() != 2) {
6739e97caf5SRenato Golin           reportVectorizationFailure("Found an invalid PHI",
6749e97caf5SRenato Golin               "loop control flow is not understood by vectorizer",
675ec818d7fSHideki Saito               "CFGNotUnderstood", ORE, TheLoop, Phi);
676f2ec16ccSHideki Saito           return false;
677f2ec16ccSHideki Saito         }
678f2ec16ccSHideki Saito 
679f2ec16ccSHideki Saito         RecurrenceDescriptor RedDes;
680f2ec16ccSHideki Saito         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
681f2ec16ccSHideki Saito                                                  DT)) {
682b3a33553SSanjay Patel           Requirements->addExactFPMathInst(RedDes.getExactFPMathInst());
683f2ec16ccSHideki Saito           AllowedExit.insert(RedDes.getLoopExitInstr());
684f2ec16ccSHideki Saito           Reductions[Phi] = RedDes;
685f2ec16ccSHideki Saito           continue;
686f2ec16ccSHideki Saito         }
687f2ec16ccSHideki Saito 
688b02b0ad8SAnna Thomas         // TODO: Instead of recording the AllowedExit, it would be good to record the
689b02b0ad8SAnna Thomas         // complementary set: NotAllowedExit. These include (but may not be
690b02b0ad8SAnna Thomas         // limited to):
691b02b0ad8SAnna Thomas         // 1. Reduction phis as they represent the one-before-last value, which
692b02b0ad8SAnna Thomas         // is not available when vectorized
693b02b0ad8SAnna Thomas         // 2. Induction phis and increment when SCEV predicates cannot be used
694b02b0ad8SAnna Thomas         // outside the loop - see addInductionPhi
695b02b0ad8SAnna Thomas         // 3. Non-Phis with outside uses when SCEV predicates cannot be used
696b02b0ad8SAnna Thomas         // outside the loop - see call to hasOutsideLoopUser in the non-phi
697b02b0ad8SAnna Thomas         // handling below
698b02b0ad8SAnna Thomas         // 4. FirstOrderRecurrence phis that can possibly be handled by
699b02b0ad8SAnna Thomas         // extraction.
700b02b0ad8SAnna Thomas         // By recording these, we can then reason about ways to vectorize each
701b02b0ad8SAnna Thomas         // of these NotAllowedExit.
702f2ec16ccSHideki Saito         InductionDescriptor ID;
703f2ec16ccSHideki Saito         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
704f2ec16ccSHideki Saito           addInductionPhi(Phi, ID, AllowedExit);
70536a489d1SSanjay Patel           Requirements->addExactFPMathInst(ID.getExactFPMathInst());
706f2ec16ccSHideki Saito           continue;
707f2ec16ccSHideki Saito         }
708f2ec16ccSHideki Saito 
709f2ec16ccSHideki Saito         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
710f2ec16ccSHideki Saito                                                          SinkAfter, DT)) {
7118e0c5f72SAyal Zaks           AllowedExit.insert(Phi);
712f2ec16ccSHideki Saito           FirstOrderRecurrences.insert(Phi);
713f2ec16ccSHideki Saito           continue;
714f2ec16ccSHideki Saito         }
715f2ec16ccSHideki Saito 
716f2ec16ccSHideki Saito         // As a last resort, coerce the PHI to a AddRec expression
717f2ec16ccSHideki Saito         // and re-try classifying it a an induction PHI.
718f2ec16ccSHideki Saito         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
719f2ec16ccSHideki Saito           addInductionPhi(Phi, ID, AllowedExit);
720f2ec16ccSHideki Saito           continue;
721f2ec16ccSHideki Saito         }
722f2ec16ccSHideki Saito 
7239e97caf5SRenato Golin         reportVectorizationFailure("Found an unidentified PHI",
7249e97caf5SRenato Golin             "value that could not be identified as "
7259e97caf5SRenato Golin             "reduction is used outside the loop",
726ec818d7fSHideki Saito             "NonReductionValueUsedOutsideLoop", ORE, TheLoop, Phi);
727f2ec16ccSHideki Saito         return false;
728f2ec16ccSHideki Saito       } // end of PHI handling
729f2ec16ccSHideki Saito 
730f2ec16ccSHideki Saito       // We handle calls that:
731f2ec16ccSHideki Saito       //   * Are debug info intrinsics.
732f2ec16ccSHideki Saito       //   * Have a mapping to an IR intrinsic.
733f2ec16ccSHideki Saito       //   * Have a vector version available.
734f2ec16ccSHideki Saito       auto *CI = dyn_cast<CallInst>(&I);
73566c120f0SFrancesco Petrogalli 
736f2ec16ccSHideki Saito       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
737f2ec16ccSHideki Saito           !isa<DbgInfoIntrinsic>(CI) &&
738f2ec16ccSHideki Saito           !(CI->getCalledFunction() && TLI &&
73966c120f0SFrancesco Petrogalli             (!VFDatabase::getMappings(*CI).empty() ||
74066c120f0SFrancesco Petrogalli              isTLIScalarize(*TLI, *CI)))) {
7417d65fe5cSSanjay Patel         // If the call is a recognized math libary call, it is likely that
7427d65fe5cSSanjay Patel         // we can vectorize it given loosened floating-point constraints.
7437d65fe5cSSanjay Patel         LibFunc Func;
7447d65fe5cSSanjay Patel         bool IsMathLibCall =
7457d65fe5cSSanjay Patel             TLI && CI->getCalledFunction() &&
7467d65fe5cSSanjay Patel             CI->getType()->isFloatingPointTy() &&
7477d65fe5cSSanjay Patel             TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
7487d65fe5cSSanjay Patel             TLI->hasOptimizedCodeGen(Func);
7497d65fe5cSSanjay Patel 
7507d65fe5cSSanjay Patel         if (IsMathLibCall) {
7517d65fe5cSSanjay Patel           // TODO: Ideally, we should not use clang-specific language here,
7527d65fe5cSSanjay Patel           // but it's hard to provide meaningful yet generic advice.
7537d65fe5cSSanjay Patel           // Also, should this be guarded by allowExtraAnalysis() and/or be part
7547d65fe5cSSanjay Patel           // of the returned info from isFunctionVectorizable()?
75566c120f0SFrancesco Petrogalli           reportVectorizationFailure(
75666c120f0SFrancesco Petrogalli               "Found a non-intrinsic callsite",
7579e97caf5SRenato Golin               "library call cannot be vectorized. "
7587d65fe5cSSanjay Patel               "Try compiling with -fno-math-errno, -ffast-math, "
7599e97caf5SRenato Golin               "or similar flags",
760ec818d7fSHideki Saito               "CantVectorizeLibcall", ORE, TheLoop, CI);
7617d65fe5cSSanjay Patel         } else {
7629e97caf5SRenato Golin           reportVectorizationFailure("Found a non-intrinsic callsite",
7639e97caf5SRenato Golin                                      "call instruction cannot be vectorized",
764ec818d7fSHideki Saito                                      "CantVectorizeLibcall", ORE, TheLoop, CI);
7657d65fe5cSSanjay Patel         }
766f2ec16ccSHideki Saito         return false;
767f2ec16ccSHideki Saito       }
768f2ec16ccSHideki Saito 
769a066f1f9SSimon Pilgrim       // Some intrinsics have scalar arguments and should be same in order for
770a066f1f9SSimon Pilgrim       // them to be vectorized (i.e. loop invariant).
771a066f1f9SSimon Pilgrim       if (CI) {
772f2ec16ccSHideki Saito         auto *SE = PSE.getSE();
773a066f1f9SSimon Pilgrim         Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
7744f0225f6SKazu Hirata         for (unsigned i = 0, e = CI->arg_size(); i != e; ++i)
775a066f1f9SSimon Pilgrim           if (hasVectorInstrinsicScalarOpd(IntrinID, i)) {
776a066f1f9SSimon Pilgrim             if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(i)), TheLoop)) {
7779e97caf5SRenato Golin               reportVectorizationFailure("Found unvectorizable intrinsic",
7789e97caf5SRenato Golin                   "intrinsic instruction cannot be vectorized",
779ec818d7fSHideki Saito                   "CantVectorizeIntrinsic", ORE, TheLoop, CI);
780f2ec16ccSHideki Saito               return false;
781f2ec16ccSHideki Saito             }
782f2ec16ccSHideki Saito           }
783a066f1f9SSimon Pilgrim       }
784f2ec16ccSHideki Saito 
785f2ec16ccSHideki Saito       // Check that the instruction return type is vectorizable.
786f2ec16ccSHideki Saito       // Also, we can't vectorize extractelement instructions.
787f2ec16ccSHideki Saito       if ((!VectorType::isValidElementType(I.getType()) &&
788f2ec16ccSHideki Saito            !I.getType()->isVoidTy()) ||
789f2ec16ccSHideki Saito           isa<ExtractElementInst>(I)) {
7909e97caf5SRenato Golin         reportVectorizationFailure("Found unvectorizable type",
7919e97caf5SRenato Golin             "instruction return type cannot be vectorized",
792ec818d7fSHideki Saito             "CantVectorizeInstructionReturnType", ORE, TheLoop, &I);
793f2ec16ccSHideki Saito         return false;
794f2ec16ccSHideki Saito       }
795f2ec16ccSHideki Saito 
796f2ec16ccSHideki Saito       // Check that the stored type is vectorizable.
797f2ec16ccSHideki Saito       if (auto *ST = dyn_cast<StoreInst>(&I)) {
798f2ec16ccSHideki Saito         Type *T = ST->getValueOperand()->getType();
799f2ec16ccSHideki Saito         if (!VectorType::isValidElementType(T)) {
8009e97caf5SRenato Golin           reportVectorizationFailure("Store instruction cannot be vectorized",
8019e97caf5SRenato Golin                                      "store instruction cannot be vectorized",
802ec818d7fSHideki Saito                                      "CantVectorizeStore", ORE, TheLoop, ST);
803f2ec16ccSHideki Saito           return false;
804f2ec16ccSHideki Saito         }
805f2ec16ccSHideki Saito 
8066452bdd2SWarren Ristow         // For nontemporal stores, check that a nontemporal vector version is
8076452bdd2SWarren Ristow         // supported on the target.
8086452bdd2SWarren Ristow         if (ST->getMetadata(LLVMContext::MD_nontemporal)) {
8096452bdd2SWarren Ristow           // Arbitrarily try a vector of 2 elements.
8106913812aSFangrui Song           auto *VecTy = FixedVectorType::get(T, /*NumElts=*/2);
8116452bdd2SWarren Ristow           assert(VecTy && "did not find vectorized version of stored type");
81252e98f62SNikita Popov           if (!TTI->isLegalNTStore(VecTy, ST->getAlign())) {
8136452bdd2SWarren Ristow             reportVectorizationFailure(
8146452bdd2SWarren Ristow                 "nontemporal store instruction cannot be vectorized",
8156452bdd2SWarren Ristow                 "nontemporal store instruction cannot be vectorized",
816ec818d7fSHideki Saito                 "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
8176452bdd2SWarren Ristow             return false;
8186452bdd2SWarren Ristow           }
8196452bdd2SWarren Ristow         }
8206452bdd2SWarren Ristow 
8216452bdd2SWarren Ristow       } else if (auto *LD = dyn_cast<LoadInst>(&I)) {
8226452bdd2SWarren Ristow         if (LD->getMetadata(LLVMContext::MD_nontemporal)) {
8236452bdd2SWarren Ristow           // For nontemporal loads, check that a nontemporal vector version is
8246452bdd2SWarren Ristow           // supported on the target (arbitrarily try a vector of 2 elements).
8256913812aSFangrui Song           auto *VecTy = FixedVectorType::get(I.getType(), /*NumElts=*/2);
8266452bdd2SWarren Ristow           assert(VecTy && "did not find vectorized version of load type");
82752e98f62SNikita Popov           if (!TTI->isLegalNTLoad(VecTy, LD->getAlign())) {
8286452bdd2SWarren Ristow             reportVectorizationFailure(
8296452bdd2SWarren Ristow                 "nontemporal load instruction cannot be vectorized",
8306452bdd2SWarren Ristow                 "nontemporal load instruction cannot be vectorized",
831ec818d7fSHideki Saito                 "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
8326452bdd2SWarren Ristow             return false;
8336452bdd2SWarren Ristow           }
8346452bdd2SWarren Ristow         }
8356452bdd2SWarren Ristow 
836f2ec16ccSHideki Saito         // FP instructions can allow unsafe algebra, thus vectorizable by
837f2ec16ccSHideki Saito         // non-IEEE-754 compliant SIMD units.
838f2ec16ccSHideki Saito         // This applies to floating-point math operations and calls, not memory
839f2ec16ccSHideki Saito         // operations, shuffles, or casts, as they don't change precision or
840f2ec16ccSHideki Saito         // semantics.
841f2ec16ccSHideki Saito       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
842f2ec16ccSHideki Saito                  !I.isFast()) {
843d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
844f2ec16ccSHideki Saito         Hints->setPotentiallyUnsafe();
845f2ec16ccSHideki Saito       }
846f2ec16ccSHideki Saito 
847f2ec16ccSHideki Saito       // Reduction instructions are allowed to have exit users.
848f2ec16ccSHideki Saito       // All other instructions must not have external users.
849f2ec16ccSHideki Saito       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
850b02b0ad8SAnna Thomas         // We can safely vectorize loops where instructions within the loop are
851b02b0ad8SAnna Thomas         // used outside the loop only if the SCEV predicates within the loop is
852b02b0ad8SAnna Thomas         // same as outside the loop. Allowing the exit means reusing the SCEV
853b02b0ad8SAnna Thomas         // outside the loop.
8545ba11503SPhilip Reames         if (PSE.getPredicate().isAlwaysTrue()) {
855b02b0ad8SAnna Thomas           AllowedExit.insert(&I);
856b02b0ad8SAnna Thomas           continue;
857b02b0ad8SAnna Thomas         }
8589e97caf5SRenato Golin         reportVectorizationFailure("Value cannot be used outside the loop",
8599e97caf5SRenato Golin                                    "value cannot be used outside the loop",
860ec818d7fSHideki Saito                                    "ValueUsedOutsideLoop", ORE, TheLoop, &I);
861f2ec16ccSHideki Saito         return false;
862f2ec16ccSHideki Saito       }
863f2ec16ccSHideki Saito     } // next instr.
864f2ec16ccSHideki Saito   }
865f2ec16ccSHideki Saito 
866f2ec16ccSHideki Saito   if (!PrimaryInduction) {
867f2ec16ccSHideki Saito     if (Inductions.empty()) {
8689e97caf5SRenato Golin       reportVectorizationFailure("Did not find one integer induction var",
8699e97caf5SRenato Golin           "loop induction variable could not be identified",
870ec818d7fSHideki Saito           "NoInductionVariable", ORE, TheLoop);
871f2ec16ccSHideki Saito       return false;
8724f27730eSWarren Ristow     } else if (!WidestIndTy) {
8739e97caf5SRenato Golin       reportVectorizationFailure("Did not find one integer induction var",
8749e97caf5SRenato Golin           "integer loop induction variable could not be identified",
875ec818d7fSHideki Saito           "NoIntegerInductionVariable", ORE, TheLoop);
8764f27730eSWarren Ristow       return false;
8779e97caf5SRenato Golin     } else {
8789e97caf5SRenato Golin       LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
879f2ec16ccSHideki Saito     }
880f2ec16ccSHideki Saito   }
881f2ec16ccSHideki Saito 
8829d24933fSFlorian Hahn   // For first order recurrences, we use the previous value (incoming value from
8839d24933fSFlorian Hahn   // the latch) to check if it dominates all users of the recurrence. Bail out
8849d24933fSFlorian Hahn   // if we have to sink such an instruction for another recurrence, as the
8859d24933fSFlorian Hahn   // dominance requirement may not hold after sinking.
8869d24933fSFlorian Hahn   BasicBlock *LoopLatch = TheLoop->getLoopLatch();
8879d24933fSFlorian Hahn   if (any_of(FirstOrderRecurrences, [LoopLatch, this](const PHINode *Phi) {
8889d24933fSFlorian Hahn         Instruction *V =
8899d24933fSFlorian Hahn             cast<Instruction>(Phi->getIncomingValueForBlock(LoopLatch));
8909d24933fSFlorian Hahn         return SinkAfter.find(V) != SinkAfter.end();
8919d24933fSFlorian Hahn       }))
8929d24933fSFlorian Hahn     return false;
8939d24933fSFlorian Hahn 
894f2ec16ccSHideki Saito   // Now we know the widest induction type, check if our found induction
895f2ec16ccSHideki Saito   // is the same size. If it's not, unset it here and InnerLoopVectorizer
896f2ec16ccSHideki Saito   // will create another.
897f2ec16ccSHideki Saito   if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
898f2ec16ccSHideki Saito     PrimaryInduction = nullptr;
899f2ec16ccSHideki Saito 
900f2ec16ccSHideki Saito   return true;
901f2ec16ccSHideki Saito }
902f2ec16ccSHideki Saito 
903f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeMemory() {
904f2ec16ccSHideki Saito   LAI = &(*GetLAA)(*TheLoop);
905f2ec16ccSHideki Saito   const OptimizationRemarkAnalysis *LAR = LAI->getReport();
906f2ec16ccSHideki Saito   if (LAR) {
907f2ec16ccSHideki Saito     ORE->emit([&]() {
908f2ec16ccSHideki Saito       return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
909f2ec16ccSHideki Saito                                         "loop not vectorized: ", *LAR);
910f2ec16ccSHideki Saito     });
911f2ec16ccSHideki Saito   }
912287d39ddSPaul Walker 
913f2ec16ccSHideki Saito   if (!LAI->canVectorizeMemory())
914f2ec16ccSHideki Saito     return false;
915f2ec16ccSHideki Saito 
9165e9215f0SAnna Thomas   if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
9179e97caf5SRenato Golin     reportVectorizationFailure("Stores to a uniform address",
9189e97caf5SRenato Golin         "write to a loop invariant address could not be vectorized",
919ec818d7fSHideki Saito         "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
920f2ec16ccSHideki Saito     return false;
921f2ec16ccSHideki Saito   }
922287d39ddSPaul Walker 
923f2ec16ccSHideki Saito   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
9245ba11503SPhilip Reames   PSE.addPredicate(LAI->getPSE().getPredicate());
925f2ec16ccSHideki Saito   return true;
926f2ec16ccSHideki Saito }
927f2ec16ccSHideki Saito 
9289f76a852SKerry McLaughlin bool LoopVectorizationLegality::canVectorizeFPMath(
9299f76a852SKerry McLaughlin     bool EnableStrictReductions) {
9309f76a852SKerry McLaughlin 
9319f76a852SKerry McLaughlin   // First check if there is any ExactFP math or if we allow reassociations
9329f76a852SKerry McLaughlin   if (!Requirements->getExactFPInst() || Hints->allowReordering())
9339f76a852SKerry McLaughlin     return true;
9349f76a852SKerry McLaughlin 
9359f76a852SKerry McLaughlin   // If the above is false, we have ExactFPMath & do not allow reordering.
9369f76a852SKerry McLaughlin   // If the EnableStrictReductions flag is set, first check if we have any
9379f76a852SKerry McLaughlin   // Exact FP induction vars, which we cannot vectorize.
9389f76a852SKerry McLaughlin   if (!EnableStrictReductions ||
9399f76a852SKerry McLaughlin       any_of(getInductionVars(), [&](auto &Induction) -> bool {
9409f76a852SKerry McLaughlin         InductionDescriptor IndDesc = Induction.second;
9419f76a852SKerry McLaughlin         return IndDesc.getExactFPMathInst();
9429f76a852SKerry McLaughlin       }))
9439f76a852SKerry McLaughlin     return false;
9449f76a852SKerry McLaughlin 
9459f76a852SKerry McLaughlin   // We can now only vectorize if all reductions with Exact FP math also
9469f76a852SKerry McLaughlin   // have the isOrdered flag set, which indicates that we can move the
9479f76a852SKerry McLaughlin   // reduction operations in-loop.
9489f76a852SKerry McLaughlin   return (all_of(getReductionVars(), [&](auto &Reduction) -> bool {
9495e6bfb66SSimon Pilgrim     const RecurrenceDescriptor &RdxDesc = Reduction.second;
9509f76a852SKerry McLaughlin     return !RdxDesc.hasExactFPMath() || RdxDesc.isOrdered();
9519f76a852SKerry McLaughlin   }));
9529f76a852SKerry McLaughlin }
9539f76a852SKerry McLaughlin 
954d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isInductionPhi(const Value *V) const {
955f2ec16ccSHideki Saito   Value *In0 = const_cast<Value *>(V);
956f2ec16ccSHideki Saito   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
957f2ec16ccSHideki Saito   if (!PN)
958f2ec16ccSHideki Saito     return false;
959f2ec16ccSHideki Saito 
960f2ec16ccSHideki Saito   return Inductions.count(PN);
961f2ec16ccSHideki Saito }
962f2ec16ccSHideki Saito 
963978883d2SFlorian Hahn const InductionDescriptor *
964978883d2SFlorian Hahn LoopVectorizationLegality::getIntOrFpInductionDescriptor(PHINode *Phi) const {
965978883d2SFlorian Hahn   if (!isInductionPhi(Phi))
966978883d2SFlorian Hahn     return nullptr;
967978883d2SFlorian Hahn   auto &ID = getInductionVars().find(Phi)->second;
968978883d2SFlorian Hahn   if (ID.getKind() == InductionDescriptor::IK_IntInduction ||
969978883d2SFlorian Hahn       ID.getKind() == InductionDescriptor::IK_FpInduction)
970978883d2SFlorian Hahn     return &ID;
971978883d2SFlorian Hahn   return nullptr;
972978883d2SFlorian Hahn }
973978883d2SFlorian Hahn 
974*46432a00SFlorian Hahn const InductionDescriptor *
975*46432a00SFlorian Hahn LoopVectorizationLegality::getPointerInductionDescriptor(PHINode *Phi) const {
976*46432a00SFlorian Hahn   if (!isInductionPhi(Phi))
977*46432a00SFlorian Hahn     return nullptr;
978*46432a00SFlorian Hahn   auto &ID = getInductionVars().find(Phi)->second;
979*46432a00SFlorian Hahn   if (ID.getKind() == InductionDescriptor::IK_PtrInduction)
980*46432a00SFlorian Hahn     return &ID;
981*46432a00SFlorian Hahn   return nullptr;
982*46432a00SFlorian Hahn }
983*46432a00SFlorian Hahn 
984d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isCastedInductionVariable(
985d74a8a78SFlorian Hahn     const Value *V) const {
986f2ec16ccSHideki Saito   auto *Inst = dyn_cast<Instruction>(V);
987f2ec16ccSHideki Saito   return (Inst && InductionCastsToIgnore.count(Inst));
988f2ec16ccSHideki Saito }
989f2ec16ccSHideki Saito 
990d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isInductionVariable(const Value *V) const {
991f2ec16ccSHideki Saito   return isInductionPhi(V) || isCastedInductionVariable(V);
992f2ec16ccSHideki Saito }
993f2ec16ccSHideki Saito 
994d74a8a78SFlorian Hahn bool LoopVectorizationLegality::isFirstOrderRecurrence(
995d74a8a78SFlorian Hahn     const PHINode *Phi) const {
996f2ec16ccSHideki Saito   return FirstOrderRecurrences.count(Phi);
997f2ec16ccSHideki Saito }
998f2ec16ccSHideki Saito 
999f82966d1SSander de Smalen bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) const {
1000f2ec16ccSHideki Saito   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1001f2ec16ccSHideki Saito }
1002f2ec16ccSHideki Saito 
1003f2ec16ccSHideki Saito bool LoopVectorizationLegality::blockCanBePredicated(
1004bda8fbe2SSjoerd Meijer     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs,
1005bda8fbe2SSjoerd Meijer     SmallPtrSetImpl<const Instruction *> &MaskedOp,
10064f01122cSJoachim Meyer     SmallPtrSetImpl<Instruction *> &ConditionalAssumes) const {
1007f2ec16ccSHideki Saito   for (Instruction &I : *BB) {
1008f2ec16ccSHideki Saito     // Check that we don't have a constant expression that can trap as operand.
1009f2ec16ccSHideki Saito     for (Value *Operand : I.operands()) {
1010f2ec16ccSHideki Saito       if (auto *C = dyn_cast<Constant>(Operand))
1011f2ec16ccSHideki Saito         if (C->canTrap())
1012f2ec16ccSHideki Saito           return false;
1013f2ec16ccSHideki Saito     }
101423c11380SFlorian Hahn 
101523c11380SFlorian Hahn     // We can predicate blocks with calls to assume, as long as we drop them in
101623c11380SFlorian Hahn     // case we flatten the CFG via predication.
101723c11380SFlorian Hahn     if (match(&I, m_Intrinsic<Intrinsic::assume>())) {
101823c11380SFlorian Hahn       ConditionalAssumes.insert(&I);
101923c11380SFlorian Hahn       continue;
102023c11380SFlorian Hahn     }
102123c11380SFlorian Hahn 
1022121cac01SJeroen Dobbelaere     // Do not let llvm.experimental.noalias.scope.decl block the vectorization.
1023121cac01SJeroen Dobbelaere     // TODO: there might be cases that it should block the vectorization. Let's
1024121cac01SJeroen Dobbelaere     // ignore those for now.
1025c83cff45SNikita Popov     if (isa<NoAliasScopeDeclInst>(&I))
1026121cac01SJeroen Dobbelaere       continue;
1027121cac01SJeroen Dobbelaere 
1028f2ec16ccSHideki Saito     // We might be able to hoist the load.
1029f2ec16ccSHideki Saito     if (I.mayReadFromMemory()) {
1030f2ec16ccSHideki Saito       auto *LI = dyn_cast<LoadInst>(&I);
1031f2ec16ccSHideki Saito       if (!LI)
1032f2ec16ccSHideki Saito         return false;
1033f2ec16ccSHideki Saito       if (!SafePtrs.count(LI->getPointerOperand())) {
1034f2ec16ccSHideki Saito         MaskedOp.insert(LI);
1035f2ec16ccSHideki Saito         continue;
1036f2ec16ccSHideki Saito       }
1037f2ec16ccSHideki Saito     }
1038f2ec16ccSHideki Saito 
1039f2ec16ccSHideki Saito     if (I.mayWriteToMemory()) {
1040f2ec16ccSHideki Saito       auto *SI = dyn_cast<StoreInst>(&I);
1041f2ec16ccSHideki Saito       if (!SI)
1042f2ec16ccSHideki Saito         return false;
1043f2ec16ccSHideki Saito       // Predicated store requires some form of masking:
1044f2ec16ccSHideki Saito       // 1) masked store HW instruction,
1045f2ec16ccSHideki Saito       // 2) emulation via load-blend-store (only if safe and legal to do so,
1046f2ec16ccSHideki Saito       //    be aware on the race conditions), or
1047f2ec16ccSHideki Saito       // 3) element-by-element predicate check and scalar store.
1048f2ec16ccSHideki Saito       MaskedOp.insert(SI);
1049f2ec16ccSHideki Saito       continue;
1050f2ec16ccSHideki Saito     }
1051f2ec16ccSHideki Saito     if (I.mayThrow())
1052f2ec16ccSHideki Saito       return false;
1053f2ec16ccSHideki Saito   }
1054f2ec16ccSHideki Saito 
1055f2ec16ccSHideki Saito   return true;
1056f2ec16ccSHideki Saito }
1057f2ec16ccSHideki Saito 
1058f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1059f2ec16ccSHideki Saito   if (!EnableIfConversion) {
10609e97caf5SRenato Golin     reportVectorizationFailure("If-conversion is disabled",
10619e97caf5SRenato Golin                                "if-conversion is disabled",
1062ec818d7fSHideki Saito                                "IfConversionDisabled",
1063ec818d7fSHideki Saito                                ORE, TheLoop);
1064f2ec16ccSHideki Saito     return false;
1065f2ec16ccSHideki Saito   }
1066f2ec16ccSHideki Saito 
1067f2ec16ccSHideki Saito   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1068f2ec16ccSHideki Saito 
1069cf3b5559SPhilip Reames   // A list of pointers which are known to be dereferenceable within scope of
1070cf3b5559SPhilip Reames   // the loop body for each iteration of the loop which executes.  That is,
1071cf3b5559SPhilip Reames   // the memory pointed to can be dereferenced (with the access size implied by
1072cf3b5559SPhilip Reames   // the value's type) unconditionally within the loop header without
1073cf3b5559SPhilip Reames   // introducing a new fault.
10743bbc71d6SSjoerd Meijer   SmallPtrSet<Value *, 8> SafePointers;
1075f2ec16ccSHideki Saito 
1076f2ec16ccSHideki Saito   // Collect safe addresses.
1077f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
10787403569bSPhilip Reames     if (!blockNeedsPredication(BB)) {
1079f2ec16ccSHideki Saito       for (Instruction &I : *BB)
1080f2ec16ccSHideki Saito         if (auto *Ptr = getLoadStorePointerOperand(&I))
10813bbc71d6SSjoerd Meijer           SafePointers.insert(Ptr);
10827403569bSPhilip Reames       continue;
10837403569bSPhilip Reames     }
10847403569bSPhilip Reames 
10857403569bSPhilip Reames     // For a block which requires predication, a address may be safe to access
10867403569bSPhilip Reames     // in the loop w/o predication if we can prove dereferenceability facts
10877403569bSPhilip Reames     // sufficient to ensure it'll never fault within the loop. For the moment,
10887403569bSPhilip Reames     // we restrict this to loads; stores are more complicated due to
10897403569bSPhilip Reames     // concurrency restrictions.
10907403569bSPhilip Reames     ScalarEvolution &SE = *PSE.getSE();
10917403569bSPhilip Reames     for (Instruction &I : *BB) {
10927403569bSPhilip Reames       LoadInst *LI = dyn_cast<LoadInst>(&I);
1093467e5cf4SJoe Ellis       if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) &&
10947403569bSPhilip Reames           isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT))
10953bbc71d6SSjoerd Meijer         SafePointers.insert(LI->getPointerOperand());
10967403569bSPhilip Reames     }
1097f2ec16ccSHideki Saito   }
1098f2ec16ccSHideki Saito 
1099f2ec16ccSHideki Saito   // Collect the blocks that need predication.
1100f2ec16ccSHideki Saito   BasicBlock *Header = TheLoop->getHeader();
1101f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
1102f2ec16ccSHideki Saito     // We don't support switch statements inside loops.
1103f2ec16ccSHideki Saito     if (!isa<BranchInst>(BB->getTerminator())) {
11049e97caf5SRenato Golin       reportVectorizationFailure("Loop contains a switch statement",
11059e97caf5SRenato Golin                                  "loop contains a switch statement",
1106ec818d7fSHideki Saito                                  "LoopContainsSwitch", ORE, TheLoop,
1107ec818d7fSHideki Saito                                  BB->getTerminator());
1108f2ec16ccSHideki Saito       return false;
1109f2ec16ccSHideki Saito     }
1110f2ec16ccSHideki Saito 
1111f2ec16ccSHideki Saito     // We must be able to predicate all blocks that need to be predicated.
1112f2ec16ccSHideki Saito     if (blockNeedsPredication(BB)) {
1113bda8fbe2SSjoerd Meijer       if (!blockCanBePredicated(BB, SafePointers, MaskedOp,
1114bda8fbe2SSjoerd Meijer                                 ConditionalAssumes)) {
11159e97caf5SRenato Golin         reportVectorizationFailure(
11169e97caf5SRenato Golin             "Control flow cannot be substituted for a select",
11179e97caf5SRenato Golin             "control flow cannot be substituted for a select",
1118ec818d7fSHideki Saito             "NoCFGForSelect", ORE, TheLoop,
1119ec818d7fSHideki Saito             BB->getTerminator());
1120f2ec16ccSHideki Saito         return false;
1121f2ec16ccSHideki Saito       }
1122f2ec16ccSHideki Saito     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
11239e97caf5SRenato Golin       reportVectorizationFailure(
11249e97caf5SRenato Golin           "Control flow cannot be substituted for a select",
11259e97caf5SRenato Golin           "control flow cannot be substituted for a select",
1126ec818d7fSHideki Saito           "NoCFGForSelect", ORE, TheLoop,
1127ec818d7fSHideki Saito           BB->getTerminator());
1128f2ec16ccSHideki Saito       return false;
1129f2ec16ccSHideki Saito     }
1130f2ec16ccSHideki Saito   }
1131f2ec16ccSHideki Saito 
1132f2ec16ccSHideki Saito   // We can if-convert this loop.
1133f2ec16ccSHideki Saito   return true;
1134f2ec16ccSHideki Saito }
1135f2ec16ccSHideki Saito 
1136f2ec16ccSHideki Saito // Helper function to canVectorizeLoopNestCFG.
1137f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
1138f2ec16ccSHideki Saito                                                     bool UseVPlanNativePath) {
113989c1e35fSStefanos Baziotis   assert((UseVPlanNativePath || Lp->isInnermost()) &&
1140f2ec16ccSHideki Saito          "VPlan-native path is not enabled.");
1141f2ec16ccSHideki Saito 
1142f2ec16ccSHideki Saito   // TODO: ORE should be improved to show more accurate information when an
1143f2ec16ccSHideki Saito   // outer loop can't be vectorized because a nested loop is not understood or
1144f2ec16ccSHideki Saito   // legal. Something like: "outer_loop_location: loop not vectorized:
1145f2ec16ccSHideki Saito   // (inner_loop_location) loop control flow is not understood by vectorizer".
1146f2ec16ccSHideki Saito 
1147f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1148f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1149f2ec16ccSHideki Saito   bool Result = true;
1150f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1151f2ec16ccSHideki Saito 
1152f2ec16ccSHideki Saito   // We must have a loop in canonical form. Loops with indirectbr in them cannot
1153f2ec16ccSHideki Saito   // be canonicalized.
1154f2ec16ccSHideki Saito   if (!Lp->getLoopPreheader()) {
11559e97caf5SRenato Golin     reportVectorizationFailure("Loop doesn't have a legal pre-header",
11569e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1157ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
1158f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1159f2ec16ccSHideki Saito       Result = false;
1160f2ec16ccSHideki Saito     else
1161f2ec16ccSHideki Saito       return false;
1162f2ec16ccSHideki Saito   }
1163f2ec16ccSHideki Saito 
1164f2ec16ccSHideki Saito   // We must have a single backedge.
1165f2ec16ccSHideki Saito   if (Lp->getNumBackEdges() != 1) {
11669e97caf5SRenato Golin     reportVectorizationFailure("The loop must have a single backedge",
11679e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1168ec818d7fSHideki Saito         "CFGNotUnderstood", ORE, TheLoop);
1169f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1170f2ec16ccSHideki Saito       Result = false;
1171f2ec16ccSHideki Saito     else
1172f2ec16ccSHideki Saito       return false;
1173f2ec16ccSHideki Saito   }
1174f2ec16ccSHideki Saito 
1175f2ec16ccSHideki Saito   return Result;
1176f2ec16ccSHideki Saito }
1177f2ec16ccSHideki Saito 
1178f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1179f2ec16ccSHideki Saito     Loop *Lp, bool UseVPlanNativePath) {
1180f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1181f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1182f2ec16ccSHideki Saito   bool Result = true;
1183f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1184f2ec16ccSHideki Saito   if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1185f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1186f2ec16ccSHideki Saito       Result = false;
1187f2ec16ccSHideki Saito     else
1188f2ec16ccSHideki Saito       return false;
1189f2ec16ccSHideki Saito   }
1190f2ec16ccSHideki Saito 
1191f2ec16ccSHideki Saito   // Recursively check whether the loop control flow of nested loops is
1192f2ec16ccSHideki Saito   // understood.
1193f2ec16ccSHideki Saito   for (Loop *SubLp : *Lp)
1194f2ec16ccSHideki Saito     if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1195f2ec16ccSHideki Saito       if (DoExtraAnalysis)
1196f2ec16ccSHideki Saito         Result = false;
1197f2ec16ccSHideki Saito       else
1198f2ec16ccSHideki Saito         return false;
1199f2ec16ccSHideki Saito     }
1200f2ec16ccSHideki Saito 
1201f2ec16ccSHideki Saito   return Result;
1202f2ec16ccSHideki Saito }
1203f2ec16ccSHideki Saito 
1204f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1205f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1206f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1207f2ec16ccSHideki Saito   bool Result = true;
1208f2ec16ccSHideki Saito 
1209f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1210f2ec16ccSHideki Saito   // Check whether the loop-related control flow in the loop nest is expected by
1211f2ec16ccSHideki Saito   // vectorizer.
1212f2ec16ccSHideki Saito   if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1213f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1214f2ec16ccSHideki Saito       Result = false;
1215f2ec16ccSHideki Saito     else
1216f2ec16ccSHideki Saito       return false;
1217f2ec16ccSHideki Saito   }
1218f2ec16ccSHideki Saito 
1219f2ec16ccSHideki Saito   // We need to have a loop header.
1220d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1221f2ec16ccSHideki Saito                     << '\n');
1222f2ec16ccSHideki Saito 
1223f2ec16ccSHideki Saito   // Specific checks for outer loops. We skip the remaining legal checks at this
1224f2ec16ccSHideki Saito   // point because they don't support outer loops.
122589c1e35fSStefanos Baziotis   if (!TheLoop->isInnermost()) {
1226f2ec16ccSHideki Saito     assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1227f2ec16ccSHideki Saito 
1228f2ec16ccSHideki Saito     if (!canVectorizeOuterLoop()) {
12299e97caf5SRenato Golin       reportVectorizationFailure("Unsupported outer loop",
12309e97caf5SRenato Golin                                  "unsupported outer loop",
1231ec818d7fSHideki Saito                                  "UnsupportedOuterLoop",
1232ec818d7fSHideki Saito                                  ORE, TheLoop);
1233f2ec16ccSHideki Saito       // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1234f2ec16ccSHideki Saito       // outer loops.
1235f2ec16ccSHideki Saito       return false;
1236f2ec16ccSHideki Saito     }
1237f2ec16ccSHideki Saito 
1238d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1239f2ec16ccSHideki Saito     return Result;
1240f2ec16ccSHideki Saito   }
1241f2ec16ccSHideki Saito 
124289c1e35fSStefanos Baziotis   assert(TheLoop->isInnermost() && "Inner loop expected.");
1243f2ec16ccSHideki Saito   // Check if we can if-convert non-single-bb loops.
1244f2ec16ccSHideki Saito   unsigned NumBlocks = TheLoop->getNumBlocks();
1245f2ec16ccSHideki Saito   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1246d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1247f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1248f2ec16ccSHideki Saito       Result = false;
1249f2ec16ccSHideki Saito     else
1250f2ec16ccSHideki Saito       return false;
1251f2ec16ccSHideki Saito   }
1252f2ec16ccSHideki Saito 
1253f2ec16ccSHideki Saito   // Check if we can vectorize the instructions and CFG in this loop.
1254f2ec16ccSHideki Saito   if (!canVectorizeInstrs()) {
1255d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1256f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1257f2ec16ccSHideki Saito       Result = false;
1258f2ec16ccSHideki Saito     else
1259f2ec16ccSHideki Saito       return false;
1260f2ec16ccSHideki Saito   }
1261f2ec16ccSHideki Saito 
1262f2ec16ccSHideki Saito   // Go over each instruction and look at memory deps.
1263f2ec16ccSHideki Saito   if (!canVectorizeMemory()) {
1264d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1265f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1266f2ec16ccSHideki Saito       Result = false;
1267f2ec16ccSHideki Saito     else
1268f2ec16ccSHideki Saito       return false;
1269f2ec16ccSHideki Saito   }
1270f2ec16ccSHideki Saito 
1271d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
1272f2ec16ccSHideki Saito                     << (LAI->getRuntimePointerChecking()->Need
1273f2ec16ccSHideki Saito                             ? " (with a runtime bound check)"
1274f2ec16ccSHideki Saito                             : "")
1275f2ec16ccSHideki Saito                     << "!\n");
1276f2ec16ccSHideki Saito 
1277f2ec16ccSHideki Saito   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
1278f2ec16ccSHideki Saito   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
1279f2ec16ccSHideki Saito     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
1280f2ec16ccSHideki Saito 
12815ba11503SPhilip Reames   if (PSE.getPredicate().getComplexity() > SCEVThreshold) {
12829e97caf5SRenato Golin     reportVectorizationFailure("Too many SCEV checks needed",
12839e97caf5SRenato Golin         "Too many SCEV assumptions need to be made and checked at runtime",
1284ec818d7fSHideki Saito         "TooManySCEVRunTimeChecks", ORE, TheLoop);
1285f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1286f2ec16ccSHideki Saito       Result = false;
1287f2ec16ccSHideki Saito     else
1288f2ec16ccSHideki Saito       return false;
1289f2ec16ccSHideki Saito   }
1290f2ec16ccSHideki Saito 
1291f2ec16ccSHideki Saito   // Okay! We've done all the tests. If any have failed, return false. Otherwise
1292f2ec16ccSHideki Saito   // we can vectorize, and at this point we don't have any other mem analysis
1293f2ec16ccSHideki Saito   // which may limit our maximum vectorization factor, so just return true with
1294f2ec16ccSHideki Saito   // no restrictions.
1295f2ec16ccSHideki Saito   return Result;
1296f2ec16ccSHideki Saito }
1297f2ec16ccSHideki Saito 
1298d57d73daSDorit Nuzman bool LoopVectorizationLegality::prepareToFoldTailByMasking() {
1299b0b5312eSAyal Zaks 
1300b0b5312eSAyal Zaks   LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
1301b0b5312eSAyal Zaks 
1302d15df0edSAyal Zaks   SmallPtrSet<const Value *, 8> ReductionLiveOuts;
1303b0b5312eSAyal Zaks 
1304d0d38df0SDavid Green   for (auto &Reduction : getReductionVars())
1305d15df0edSAyal Zaks     ReductionLiveOuts.insert(Reduction.second.getLoopExitInstr());
1306d15df0edSAyal Zaks 
1307d15df0edSAyal Zaks   // TODO: handle non-reduction outside users when tail is folded by masking.
1308b0b5312eSAyal Zaks   for (auto *AE : AllowedExit) {
1309d15df0edSAyal Zaks     // Check that all users of allowed exit values are inside the loop or
1310d15df0edSAyal Zaks     // are the live-out of a reduction.
1311d15df0edSAyal Zaks     if (ReductionLiveOuts.count(AE))
1312d15df0edSAyal Zaks       continue;
1313b0b5312eSAyal Zaks     for (User *U : AE->users()) {
1314b0b5312eSAyal Zaks       Instruction *UI = cast<Instruction>(U);
1315b0b5312eSAyal Zaks       if (TheLoop->contains(UI))
1316b0b5312eSAyal Zaks         continue;
1317bda8fbe2SSjoerd Meijer       LLVM_DEBUG(
1318bda8fbe2SSjoerd Meijer           dbgs()
1319bda8fbe2SSjoerd Meijer           << "LV: Cannot fold tail by masking, loop has an outside user for "
1320bda8fbe2SSjoerd Meijer           << *UI << "\n");
1321b0b5312eSAyal Zaks       return false;
1322b0b5312eSAyal Zaks     }
1323b0b5312eSAyal Zaks   }
1324b0b5312eSAyal Zaks 
1325b0b5312eSAyal Zaks   // The list of pointers that we can safely read and write to remains empty.
1326b0b5312eSAyal Zaks   SmallPtrSet<Value *, 8> SafePointers;
1327b0b5312eSAyal Zaks 
1328bda8fbe2SSjoerd Meijer   SmallPtrSet<const Instruction *, 8> TmpMaskedOp;
1329bda8fbe2SSjoerd Meijer   SmallPtrSet<Instruction *, 8> TmpConditionalAssumes;
1330bda8fbe2SSjoerd Meijer 
1331b0b5312eSAyal Zaks   // Check and mark all blocks for predication, including those that ordinarily
1332b0b5312eSAyal Zaks   // do not need predication such as the header block.
1333b0b5312eSAyal Zaks   for (BasicBlock *BB : TheLoop->blocks()) {
1334bda8fbe2SSjoerd Meijer     if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp,
13354f01122cSJoachim Meyer                               TmpConditionalAssumes)) {
1336bda8fbe2SSjoerd Meijer       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as requested.\n");
1337b0b5312eSAyal Zaks       return false;
1338b0b5312eSAyal Zaks     }
1339b0b5312eSAyal Zaks   }
1340b0b5312eSAyal Zaks 
1341b0b5312eSAyal Zaks   LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
1342bda8fbe2SSjoerd Meijer 
1343bda8fbe2SSjoerd Meijer   MaskedOp.insert(TmpMaskedOp.begin(), TmpMaskedOp.end());
1344bda8fbe2SSjoerd Meijer   ConditionalAssumes.insert(TmpConditionalAssumes.begin(),
1345bda8fbe2SSjoerd Meijer                             TmpConditionalAssumes.end());
1346bda8fbe2SSjoerd Meijer 
1347b0b5312eSAyal Zaks   return true;
1348b0b5312eSAyal Zaks }
1349b0b5312eSAyal Zaks 
1350f2ec16ccSHideki Saito } // namespace llvm
1351