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 //
16f2ec16ccSHideki Saito #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
17f2ec16ccSHideki Saito #include "llvm/Analysis/VectorUtils.h"
18f2ec16ccSHideki Saito #include "llvm/IR/IntrinsicInst.h"
19f2ec16ccSHideki Saito 
20f2ec16ccSHideki Saito using namespace llvm;
21f2ec16ccSHideki Saito 
22f2ec16ccSHideki Saito #define LV_NAME "loop-vectorize"
23f2ec16ccSHideki Saito #define DEBUG_TYPE LV_NAME
24f2ec16ccSHideki Saito 
254e4ecae0SHideki Saito extern cl::opt<bool> EnableVPlanPredication;
264e4ecae0SHideki Saito 
27f2ec16ccSHideki Saito static cl::opt<bool>
28f2ec16ccSHideki Saito     EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
29f2ec16ccSHideki Saito                        cl::desc("Enable if-conversion during vectorization."));
30f2ec16ccSHideki Saito 
31f2ec16ccSHideki Saito static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
32f2ec16ccSHideki Saito     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
33f2ec16ccSHideki Saito     cl::desc("The maximum allowed number of runtime memory checks with a "
34f2ec16ccSHideki Saito              "vectorize(enable) pragma."));
35f2ec16ccSHideki Saito 
36f2ec16ccSHideki Saito static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
37f2ec16ccSHideki Saito     "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
38f2ec16ccSHideki Saito     cl::desc("The maximum number of SCEV checks allowed."));
39f2ec16ccSHideki Saito 
40f2ec16ccSHideki Saito static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
41f2ec16ccSHideki Saito     "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
42f2ec16ccSHideki Saito     cl::desc("The maximum number of SCEV checks allowed with a "
43f2ec16ccSHideki Saito              "vectorize(enable) pragma"));
44f2ec16ccSHideki Saito 
45f2ec16ccSHideki Saito /// Maximum vectorization interleave count.
46f2ec16ccSHideki Saito static const unsigned MaxInterleaveFactor = 16;
47f2ec16ccSHideki Saito 
48f2ec16ccSHideki Saito namespace llvm {
49f2ec16ccSHideki Saito 
50*9e97caf5SRenato Golin static void debugVectorizationFailure(const StringRef DebugMsg,
51*9e97caf5SRenato Golin     Instruction *I) {
52*9e97caf5SRenato Golin   dbgs() << "LV: Not vectorizing: " << DebugMsg;
53*9e97caf5SRenato Golin   if (I != nullptr)
54*9e97caf5SRenato Golin     dbgs() << " " << *I;
55*9e97caf5SRenato Golin   else
56*9e97caf5SRenato Golin     dbgs() << '.';
57*9e97caf5SRenato Golin   dbgs() << '\n';
58*9e97caf5SRenato Golin }
59*9e97caf5SRenato Golin 
60f2ec16ccSHideki Saito OptimizationRemarkAnalysis createLVMissedAnalysis(const char *PassName,
61f2ec16ccSHideki Saito                                                   StringRef RemarkName,
62f2ec16ccSHideki Saito                                                   Loop *TheLoop,
63f2ec16ccSHideki Saito                                                   Instruction *I) {
64f2ec16ccSHideki Saito   Value *CodeRegion = TheLoop->getHeader();
65f2ec16ccSHideki Saito   DebugLoc DL = TheLoop->getStartLoc();
66f2ec16ccSHideki Saito 
67f2ec16ccSHideki Saito   if (I) {
68f2ec16ccSHideki Saito     CodeRegion = I->getParent();
69f2ec16ccSHideki Saito     // If there is no debug location attached to the instruction, revert back to
70f2ec16ccSHideki Saito     // using the loop's.
71f2ec16ccSHideki Saito     if (I->getDebugLoc())
72f2ec16ccSHideki Saito       DL = I->getDebugLoc();
73f2ec16ccSHideki Saito   }
74f2ec16ccSHideki Saito 
75f2ec16ccSHideki Saito   OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
76f2ec16ccSHideki Saito   R << "loop not vectorized: ";
77f2ec16ccSHideki Saito   return R;
78f2ec16ccSHideki Saito }
79f2ec16ccSHideki Saito 
80f2ec16ccSHideki Saito bool LoopVectorizeHints::Hint::validate(unsigned Val) {
81f2ec16ccSHideki Saito   switch (Kind) {
82f2ec16ccSHideki Saito   case HK_WIDTH:
83f2ec16ccSHideki Saito     return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
84f2ec16ccSHideki Saito   case HK_UNROLL:
85f2ec16ccSHideki Saito     return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
86f2ec16ccSHideki Saito   case HK_FORCE:
87f2ec16ccSHideki Saito     return (Val <= 1);
88f2ec16ccSHideki Saito   case HK_ISVECTORIZED:
89f2ec16ccSHideki Saito     return (Val == 0 || Val == 1);
90f2ec16ccSHideki Saito   }
91f2ec16ccSHideki Saito   return false;
92f2ec16ccSHideki Saito }
93f2ec16ccSHideki Saito 
94d4eb13c8SMichael Kruse LoopVectorizeHints::LoopVectorizeHints(const Loop *L,
95d4eb13c8SMichael Kruse                                        bool InterleaveOnlyWhenForced,
96f2ec16ccSHideki Saito                                        OptimizationRemarkEmitter &ORE)
97f2ec16ccSHideki Saito     : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
98d4eb13c8SMichael Kruse       Interleave("interleave.count", InterleaveOnlyWhenForced, HK_UNROLL),
99f2ec16ccSHideki Saito       Force("vectorize.enable", FK_Undefined, HK_FORCE),
100f2ec16ccSHideki Saito       IsVectorized("isvectorized", 0, HK_ISVECTORIZED), TheLoop(L), ORE(ORE) {
101f2ec16ccSHideki Saito   // Populate values with existing loop metadata.
102f2ec16ccSHideki Saito   getHintsFromMetadata();
103f2ec16ccSHideki Saito 
104f2ec16ccSHideki Saito   // force-vector-interleave overrides DisableInterleaving.
105f2ec16ccSHideki Saito   if (VectorizerParams::isInterleaveForced())
106f2ec16ccSHideki Saito     Interleave.Value = VectorizerParams::VectorizationInterleave;
107f2ec16ccSHideki Saito 
108f2ec16ccSHideki Saito   if (IsVectorized.Value != 1)
109f2ec16ccSHideki Saito     // If the vectorization width and interleaving count are both 1 then
110f2ec16ccSHideki Saito     // consider the loop to have been already vectorized because there's
111f2ec16ccSHideki Saito     // nothing more that we can do.
112f2ec16ccSHideki Saito     IsVectorized.Value = Width.Value == 1 && Interleave.Value == 1;
113d4eb13c8SMichael Kruse   LLVM_DEBUG(if (InterleaveOnlyWhenForced && Interleave.Value == 1) dbgs()
114f2ec16ccSHideki Saito              << "LV: Interleaving disabled by the pass manager\n");
115f2ec16ccSHideki Saito }
116f2ec16ccSHideki Saito 
11777a614a6SMichael Kruse void LoopVectorizeHints::setAlreadyVectorized() {
11877a614a6SMichael Kruse   LLVMContext &Context = TheLoop->getHeader()->getContext();
11977a614a6SMichael Kruse 
12077a614a6SMichael Kruse   MDNode *IsVectorizedMD = MDNode::get(
12177a614a6SMichael Kruse       Context,
12277a614a6SMichael Kruse       {MDString::get(Context, "llvm.loop.isvectorized"),
12377a614a6SMichael Kruse        ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))});
12477a614a6SMichael Kruse   MDNode *LoopID = TheLoop->getLoopID();
12577a614a6SMichael Kruse   MDNode *NewLoopID =
12677a614a6SMichael Kruse       makePostTransformationMetadata(Context, LoopID,
12777a614a6SMichael Kruse                                      {Twine(Prefix(), "vectorize.").str(),
12877a614a6SMichael Kruse                                       Twine(Prefix(), "interleave.").str()},
12977a614a6SMichael Kruse                                      {IsVectorizedMD});
13077a614a6SMichael Kruse   TheLoop->setLoopID(NewLoopID);
13177a614a6SMichael Kruse 
13277a614a6SMichael Kruse   // Update internal cache.
13377a614a6SMichael Kruse   IsVectorized.Value = 1;
13477a614a6SMichael Kruse }
13577a614a6SMichael Kruse 
136d4eb13c8SMichael Kruse bool LoopVectorizeHints::allowVectorization(
137d4eb13c8SMichael Kruse     Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
138f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Disabled) {
139d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
140f2ec16ccSHideki Saito     emitRemarkWithHints();
141f2ec16ccSHideki Saito     return false;
142f2ec16ccSHideki Saito   }
143f2ec16ccSHideki Saito 
144d4eb13c8SMichael Kruse   if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
145d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
146f2ec16ccSHideki Saito     emitRemarkWithHints();
147f2ec16ccSHideki Saito     return false;
148f2ec16ccSHideki Saito   }
149f2ec16ccSHideki Saito 
150f2ec16ccSHideki Saito   if (getIsVectorized() == 1) {
151d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
152f2ec16ccSHideki Saito     // FIXME: Add interleave.disable metadata. This will allow
153f2ec16ccSHideki Saito     // vectorize.disable to be used without disabling the pass and errors
154f2ec16ccSHideki Saito     // to differentiate between disabled vectorization and a width of 1.
155f2ec16ccSHideki Saito     ORE.emit([&]() {
156f2ec16ccSHideki Saito       return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
157f2ec16ccSHideki Saito                                         "AllDisabled", L->getStartLoc(),
158f2ec16ccSHideki Saito                                         L->getHeader())
159f2ec16ccSHideki Saito              << "loop not vectorized: vectorization and interleaving are "
160f2ec16ccSHideki Saito                 "explicitly disabled, or the loop has already been "
161f2ec16ccSHideki Saito                 "vectorized";
162f2ec16ccSHideki Saito     });
163f2ec16ccSHideki Saito     return false;
164f2ec16ccSHideki Saito   }
165f2ec16ccSHideki Saito 
166f2ec16ccSHideki Saito   return true;
167f2ec16ccSHideki Saito }
168f2ec16ccSHideki Saito 
169f2ec16ccSHideki Saito void LoopVectorizeHints::emitRemarkWithHints() const {
170f2ec16ccSHideki Saito   using namespace ore;
171f2ec16ccSHideki Saito 
172f2ec16ccSHideki Saito   ORE.emit([&]() {
173f2ec16ccSHideki Saito     if (Force.Value == LoopVectorizeHints::FK_Disabled)
174f2ec16ccSHideki Saito       return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
175f2ec16ccSHideki Saito                                       TheLoop->getStartLoc(),
176f2ec16ccSHideki Saito                                       TheLoop->getHeader())
177f2ec16ccSHideki Saito              << "loop not vectorized: vectorization is explicitly disabled";
178f2ec16ccSHideki Saito     else {
179f2ec16ccSHideki Saito       OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
180f2ec16ccSHideki Saito                                  TheLoop->getStartLoc(), TheLoop->getHeader());
181f2ec16ccSHideki Saito       R << "loop not vectorized";
182f2ec16ccSHideki Saito       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
183f2ec16ccSHideki Saito         R << " (Force=" << NV("Force", true);
184f2ec16ccSHideki Saito         if (Width.Value != 0)
185f2ec16ccSHideki Saito           R << ", Vector Width=" << NV("VectorWidth", Width.Value);
186f2ec16ccSHideki Saito         if (Interleave.Value != 0)
187f2ec16ccSHideki Saito           R << ", Interleave Count=" << NV("InterleaveCount", Interleave.Value);
188f2ec16ccSHideki Saito         R << ")";
189f2ec16ccSHideki Saito       }
190f2ec16ccSHideki Saito       return R;
191f2ec16ccSHideki Saito     }
192f2ec16ccSHideki Saito   });
193f2ec16ccSHideki Saito }
194f2ec16ccSHideki Saito 
195f2ec16ccSHideki Saito const char *LoopVectorizeHints::vectorizeAnalysisPassName() const {
196f2ec16ccSHideki Saito   if (getWidth() == 1)
197f2ec16ccSHideki Saito     return LV_NAME;
198f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Disabled)
199f2ec16ccSHideki Saito     return LV_NAME;
200f2ec16ccSHideki Saito   if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
201f2ec16ccSHideki Saito     return LV_NAME;
202f2ec16ccSHideki Saito   return OptimizationRemarkAnalysis::AlwaysPrint;
203f2ec16ccSHideki Saito }
204f2ec16ccSHideki Saito 
205f2ec16ccSHideki Saito void LoopVectorizeHints::getHintsFromMetadata() {
206f2ec16ccSHideki Saito   MDNode *LoopID = TheLoop->getLoopID();
207f2ec16ccSHideki Saito   if (!LoopID)
208f2ec16ccSHideki Saito     return;
209f2ec16ccSHideki Saito 
210f2ec16ccSHideki Saito   // First operand should refer to the loop id itself.
211f2ec16ccSHideki Saito   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
212f2ec16ccSHideki Saito   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
213f2ec16ccSHideki Saito 
214f2ec16ccSHideki Saito   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
215f2ec16ccSHideki Saito     const MDString *S = nullptr;
216f2ec16ccSHideki Saito     SmallVector<Metadata *, 4> Args;
217f2ec16ccSHideki Saito 
218f2ec16ccSHideki Saito     // The expected hint is either a MDString or a MDNode with the first
219f2ec16ccSHideki Saito     // operand a MDString.
220f2ec16ccSHideki Saito     if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
221f2ec16ccSHideki Saito       if (!MD || MD->getNumOperands() == 0)
222f2ec16ccSHideki Saito         continue;
223f2ec16ccSHideki Saito       S = dyn_cast<MDString>(MD->getOperand(0));
224f2ec16ccSHideki Saito       for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
225f2ec16ccSHideki Saito         Args.push_back(MD->getOperand(i));
226f2ec16ccSHideki Saito     } else {
227f2ec16ccSHideki Saito       S = dyn_cast<MDString>(LoopID->getOperand(i));
228f2ec16ccSHideki Saito       assert(Args.size() == 0 && "too many arguments for MDString");
229f2ec16ccSHideki Saito     }
230f2ec16ccSHideki Saito 
231f2ec16ccSHideki Saito     if (!S)
232f2ec16ccSHideki Saito       continue;
233f2ec16ccSHideki Saito 
234f2ec16ccSHideki Saito     // Check if the hint starts with the loop metadata prefix.
235f2ec16ccSHideki Saito     StringRef Name = S->getString();
236f2ec16ccSHideki Saito     if (Args.size() == 1)
237f2ec16ccSHideki Saito       setHint(Name, Args[0]);
238f2ec16ccSHideki Saito   }
239f2ec16ccSHideki Saito }
240f2ec16ccSHideki Saito 
241f2ec16ccSHideki Saito void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
242f2ec16ccSHideki Saito   if (!Name.startswith(Prefix()))
243f2ec16ccSHideki Saito     return;
244f2ec16ccSHideki Saito   Name = Name.substr(Prefix().size(), StringRef::npos);
245f2ec16ccSHideki Saito 
246f2ec16ccSHideki Saito   const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
247f2ec16ccSHideki Saito   if (!C)
248f2ec16ccSHideki Saito     return;
249f2ec16ccSHideki Saito   unsigned Val = C->getZExtValue();
250f2ec16ccSHideki Saito 
251f2ec16ccSHideki Saito   Hint *Hints[] = {&Width, &Interleave, &Force, &IsVectorized};
252f2ec16ccSHideki Saito   for (auto H : Hints) {
253f2ec16ccSHideki Saito     if (Name == H->Name) {
254f2ec16ccSHideki Saito       if (H->validate(Val))
255f2ec16ccSHideki Saito         H->Value = Val;
256f2ec16ccSHideki Saito       else
257d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
258f2ec16ccSHideki Saito       break;
259f2ec16ccSHideki Saito     }
260f2ec16ccSHideki Saito   }
261f2ec16ccSHideki Saito }
262f2ec16ccSHideki Saito 
263f2ec16ccSHideki Saito bool LoopVectorizationRequirements::doesNotMeet(
264f2ec16ccSHideki Saito     Function *F, Loop *L, const LoopVectorizeHints &Hints) {
265f2ec16ccSHideki Saito   const char *PassName = Hints.vectorizeAnalysisPassName();
266f2ec16ccSHideki Saito   bool Failed = false;
267f2ec16ccSHideki Saito   if (UnsafeAlgebraInst && !Hints.allowReordering()) {
268f2ec16ccSHideki Saito     ORE.emit([&]() {
269f2ec16ccSHideki Saito       return OptimizationRemarkAnalysisFPCommute(
270f2ec16ccSHideki Saito                  PassName, "CantReorderFPOps", UnsafeAlgebraInst->getDebugLoc(),
271f2ec16ccSHideki Saito                  UnsafeAlgebraInst->getParent())
272f2ec16ccSHideki Saito              << "loop not vectorized: cannot prove it is safe to reorder "
273f2ec16ccSHideki Saito                 "floating-point operations";
274f2ec16ccSHideki Saito     });
275f2ec16ccSHideki Saito     Failed = true;
276f2ec16ccSHideki Saito   }
277f2ec16ccSHideki Saito 
278f2ec16ccSHideki Saito   // Test if runtime memcheck thresholds are exceeded.
279f2ec16ccSHideki Saito   bool PragmaThresholdReached =
280f2ec16ccSHideki Saito       NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
281f2ec16ccSHideki Saito   bool ThresholdReached =
282f2ec16ccSHideki Saito       NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
283f2ec16ccSHideki Saito   if ((ThresholdReached && !Hints.allowReordering()) ||
284f2ec16ccSHideki Saito       PragmaThresholdReached) {
285f2ec16ccSHideki Saito     ORE.emit([&]() {
286f2ec16ccSHideki Saito       return OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
287f2ec16ccSHideki Saito                                                 L->getStartLoc(),
288f2ec16ccSHideki Saito                                                 L->getHeader())
289f2ec16ccSHideki Saito              << "loop not vectorized: cannot prove it is safe to reorder "
290f2ec16ccSHideki Saito                 "memory operations";
291f2ec16ccSHideki Saito     });
292d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
293f2ec16ccSHideki Saito     Failed = true;
294f2ec16ccSHideki Saito   }
295f2ec16ccSHideki Saito 
296f2ec16ccSHideki Saito   return Failed;
297f2ec16ccSHideki Saito }
298f2ec16ccSHideki Saito 
299f2ec16ccSHideki Saito // Return true if the inner loop \p Lp is uniform with regard to the outer loop
300f2ec16ccSHideki Saito // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
301f2ec16ccSHideki Saito // executing the inner loop will execute the same iterations). This check is
302f2ec16ccSHideki Saito // very constrained for now but it will be relaxed in the future. \p Lp is
303f2ec16ccSHideki Saito // considered uniform if it meets all the following conditions:
304f2ec16ccSHideki Saito //   1) it has a canonical IV (starting from 0 and with stride 1),
305f2ec16ccSHideki Saito //   2) its latch terminator is a conditional branch and,
306f2ec16ccSHideki Saito //   3) its latch condition is a compare instruction whose operands are the
307f2ec16ccSHideki Saito //      canonical IV and an OuterLp invariant.
308f2ec16ccSHideki Saito // This check doesn't take into account the uniformity of other conditions not
309f2ec16ccSHideki Saito // related to the loop latch because they don't affect the loop uniformity.
310f2ec16ccSHideki Saito //
311f2ec16ccSHideki Saito // NOTE: We decided to keep all these checks and its associated documentation
312f2ec16ccSHideki Saito // together so that we can easily have a picture of the current supported loop
313f2ec16ccSHideki Saito // nests. However, some of the current checks don't depend on \p OuterLp and
314f2ec16ccSHideki Saito // would be redundantly executed for each \p Lp if we invoked this function for
315f2ec16ccSHideki Saito // different candidate outer loops. This is not the case for now because we
316f2ec16ccSHideki Saito // don't currently have the infrastructure to evaluate multiple candidate outer
317f2ec16ccSHideki Saito // loops and \p OuterLp will be a fixed parameter while we only support explicit
318f2ec16ccSHideki Saito // outer loop vectorization. It's also very likely that these checks go away
319f2ec16ccSHideki Saito // before introducing the aforementioned infrastructure. However, if this is not
320f2ec16ccSHideki Saito // the case, we should move the \p OuterLp independent checks to a separate
321f2ec16ccSHideki Saito // function that is only executed once for each \p Lp.
322f2ec16ccSHideki Saito static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
323f2ec16ccSHideki Saito   assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
324f2ec16ccSHideki Saito 
325f2ec16ccSHideki Saito   // If Lp is the outer loop, it's uniform by definition.
326f2ec16ccSHideki Saito   if (Lp == OuterLp)
327f2ec16ccSHideki Saito     return true;
328f2ec16ccSHideki Saito   assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
329f2ec16ccSHideki Saito 
330f2ec16ccSHideki Saito   // 1.
331f2ec16ccSHideki Saito   PHINode *IV = Lp->getCanonicalInductionVariable();
332f2ec16ccSHideki Saito   if (!IV) {
333d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
334f2ec16ccSHideki Saito     return false;
335f2ec16ccSHideki Saito   }
336f2ec16ccSHideki Saito 
337f2ec16ccSHideki Saito   // 2.
338f2ec16ccSHideki Saito   BasicBlock *Latch = Lp->getLoopLatch();
339f2ec16ccSHideki Saito   auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
340f2ec16ccSHideki Saito   if (!LatchBr || LatchBr->isUnconditional()) {
341d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
342f2ec16ccSHideki Saito     return false;
343f2ec16ccSHideki Saito   }
344f2ec16ccSHideki Saito 
345f2ec16ccSHideki Saito   // 3.
346f2ec16ccSHideki Saito   auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
347f2ec16ccSHideki Saito   if (!LatchCmp) {
348d34e60caSNicola Zaghen     LLVM_DEBUG(
349d34e60caSNicola Zaghen         dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
350f2ec16ccSHideki Saito     return false;
351f2ec16ccSHideki Saito   }
352f2ec16ccSHideki Saito 
353f2ec16ccSHideki Saito   Value *CondOp0 = LatchCmp->getOperand(0);
354f2ec16ccSHideki Saito   Value *CondOp1 = LatchCmp->getOperand(1);
355f2ec16ccSHideki Saito   Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
356f2ec16ccSHideki Saito   if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
357f2ec16ccSHideki Saito       !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
358d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
359f2ec16ccSHideki Saito     return false;
360f2ec16ccSHideki Saito   }
361f2ec16ccSHideki Saito 
362f2ec16ccSHideki Saito   return true;
363f2ec16ccSHideki Saito }
364f2ec16ccSHideki Saito 
365f2ec16ccSHideki Saito // Return true if \p Lp and all its nested loops are uniform with regard to \p
366f2ec16ccSHideki Saito // OuterLp.
367f2ec16ccSHideki Saito static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
368f2ec16ccSHideki Saito   if (!isUniformLoop(Lp, OuterLp))
369f2ec16ccSHideki Saito     return false;
370f2ec16ccSHideki Saito 
371f2ec16ccSHideki Saito   // Check if nested loops are uniform.
372f2ec16ccSHideki Saito   for (Loop *SubLp : *Lp)
373f2ec16ccSHideki Saito     if (!isUniformLoopNest(SubLp, OuterLp))
374f2ec16ccSHideki Saito       return false;
375f2ec16ccSHideki Saito 
376f2ec16ccSHideki Saito   return true;
377f2ec16ccSHideki Saito }
378f2ec16ccSHideki Saito 
3795f8f34e4SAdrian Prantl /// Check whether it is safe to if-convert this phi node.
380f2ec16ccSHideki Saito ///
381f2ec16ccSHideki Saito /// Phi nodes with constant expressions that can trap are not safe to if
382f2ec16ccSHideki Saito /// convert.
383f2ec16ccSHideki Saito static bool canIfConvertPHINodes(BasicBlock *BB) {
384f2ec16ccSHideki Saito   for (PHINode &Phi : BB->phis()) {
385f2ec16ccSHideki Saito     for (Value *V : Phi.incoming_values())
386f2ec16ccSHideki Saito       if (auto *C = dyn_cast<Constant>(V))
387f2ec16ccSHideki Saito         if (C->canTrap())
388f2ec16ccSHideki Saito           return false;
389f2ec16ccSHideki Saito   }
390f2ec16ccSHideki Saito   return true;
391f2ec16ccSHideki Saito }
392f2ec16ccSHideki Saito 
393f2ec16ccSHideki Saito static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
394f2ec16ccSHideki Saito   if (Ty->isPointerTy())
395f2ec16ccSHideki Saito     return DL.getIntPtrType(Ty);
396f2ec16ccSHideki Saito 
397f2ec16ccSHideki Saito   // It is possible that char's or short's overflow when we ask for the loop's
398f2ec16ccSHideki Saito   // trip count, work around this by changing the type size.
399f2ec16ccSHideki Saito   if (Ty->getScalarSizeInBits() < 32)
400f2ec16ccSHideki Saito     return Type::getInt32Ty(Ty->getContext());
401f2ec16ccSHideki Saito 
402f2ec16ccSHideki Saito   return Ty;
403f2ec16ccSHideki Saito }
404f2ec16ccSHideki Saito 
405f2ec16ccSHideki Saito static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
406f2ec16ccSHideki Saito   Ty0 = convertPointerToIntegerType(DL, Ty0);
407f2ec16ccSHideki Saito   Ty1 = convertPointerToIntegerType(DL, Ty1);
408f2ec16ccSHideki Saito   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
409f2ec16ccSHideki Saito     return Ty0;
410f2ec16ccSHideki Saito   return Ty1;
411f2ec16ccSHideki Saito }
412f2ec16ccSHideki Saito 
4135f8f34e4SAdrian Prantl /// Check that the instruction has outside loop users and is not an
414f2ec16ccSHideki Saito /// identified reduction variable.
415f2ec16ccSHideki Saito static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
416f2ec16ccSHideki Saito                                SmallPtrSetImpl<Value *> &AllowedExit) {
41760a1e4ddSAnna Thomas   // Reductions, Inductions and non-header phis are allowed to have exit users. All
418f2ec16ccSHideki Saito   // other instructions must not have external users.
419f2ec16ccSHideki Saito   if (!AllowedExit.count(Inst))
420f2ec16ccSHideki Saito     // Check that all of the users of the loop are inside the BB.
421f2ec16ccSHideki Saito     for (User *U : Inst->users()) {
422f2ec16ccSHideki Saito       Instruction *UI = cast<Instruction>(U);
423f2ec16ccSHideki Saito       // This user may be a reduction exit value.
424f2ec16ccSHideki Saito       if (!TheLoop->contains(UI)) {
425d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
426f2ec16ccSHideki Saito         return true;
427f2ec16ccSHideki Saito       }
428f2ec16ccSHideki Saito     }
429f2ec16ccSHideki Saito   return false;
430f2ec16ccSHideki Saito }
431f2ec16ccSHideki Saito 
432f2ec16ccSHideki Saito int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
433f2ec16ccSHideki Saito   const ValueToValueMap &Strides =
434f2ec16ccSHideki Saito       getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
435f2ec16ccSHideki Saito 
436f2ec16ccSHideki Saito   int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
437f2ec16ccSHideki Saito   if (Stride == 1 || Stride == -1)
438f2ec16ccSHideki Saito     return Stride;
439f2ec16ccSHideki Saito   return 0;
440f2ec16ccSHideki Saito }
441f2ec16ccSHideki Saito 
442f2ec16ccSHideki Saito bool LoopVectorizationLegality::isUniform(Value *V) {
443f2ec16ccSHideki Saito   return LAI->isUniform(V);
444f2ec16ccSHideki Saito }
445f2ec16ccSHideki Saito 
446*9e97caf5SRenato Golin void LoopVectorizationLegality::reportVectorizationFailure(
447*9e97caf5SRenato Golin     const StringRef DebugMsg, const StringRef OREMsg,
448*9e97caf5SRenato Golin     const StringRef ORETag, Instruction *I) const {
449*9e97caf5SRenato Golin   LLVM_DEBUG(debugVectorizationFailure(DebugMsg, I));
450*9e97caf5SRenato Golin   ORE->emit(createLVMissedAnalysis(Hints->vectorizeAnalysisPassName(),
451*9e97caf5SRenato Golin       ORETag, TheLoop, I) << OREMsg);
452*9e97caf5SRenato Golin }
453*9e97caf5SRenato Golin 
454f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeOuterLoop() {
455f2ec16ccSHideki Saito   assert(!TheLoop->empty() && "We are not vectorizing an outer loop.");
456f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
457f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
458f2ec16ccSHideki Saito   bool Result = true;
459f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
460f2ec16ccSHideki Saito 
461f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
462f2ec16ccSHideki Saito     // Check whether the BB terminator is a BranchInst. Any other terminator is
463f2ec16ccSHideki Saito     // not supported yet.
464f2ec16ccSHideki Saito     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
465f2ec16ccSHideki Saito     if (!Br) {
466*9e97caf5SRenato Golin       reportVectorizationFailure("Unsupported basic block terminator",
467*9e97caf5SRenato Golin           "loop control flow is not understood by vectorizer",
468*9e97caf5SRenato Golin           "CFGNotUnderstood");
469f2ec16ccSHideki Saito       if (DoExtraAnalysis)
470f2ec16ccSHideki Saito         Result = false;
471f2ec16ccSHideki Saito       else
472f2ec16ccSHideki Saito         return false;
473f2ec16ccSHideki Saito     }
474f2ec16ccSHideki Saito 
475f2ec16ccSHideki Saito     // Check whether the BranchInst is a supported one. Only unconditional
476f2ec16ccSHideki Saito     // branches, conditional branches with an outer loop invariant condition or
477f2ec16ccSHideki Saito     // backedges are supported.
4784e4ecae0SHideki Saito     // FIXME: We skip these checks when VPlan predication is enabled as we
4794e4ecae0SHideki Saito     // want to allow divergent branches. This whole check will be removed
4804e4ecae0SHideki Saito     // once VPlan predication is on by default.
4814e4ecae0SHideki Saito     if (!EnableVPlanPredication && Br && Br->isConditional() &&
482f2ec16ccSHideki Saito         !TheLoop->isLoopInvariant(Br->getCondition()) &&
483f2ec16ccSHideki Saito         !LI->isLoopHeader(Br->getSuccessor(0)) &&
484f2ec16ccSHideki Saito         !LI->isLoopHeader(Br->getSuccessor(1))) {
485*9e97caf5SRenato Golin       reportVectorizationFailure("Unsupported conditional branch",
486*9e97caf5SRenato Golin           "loop control flow is not understood by vectorizer",
487*9e97caf5SRenato Golin           "CFGNotUnderstood");
488f2ec16ccSHideki Saito       if (DoExtraAnalysis)
489f2ec16ccSHideki Saito         Result = false;
490f2ec16ccSHideki Saito       else
491f2ec16ccSHideki Saito         return false;
492f2ec16ccSHideki Saito     }
493f2ec16ccSHideki Saito   }
494f2ec16ccSHideki Saito 
495f2ec16ccSHideki Saito   // Check whether inner loops are uniform. At this point, we only support
496f2ec16ccSHideki Saito   // simple outer loops scenarios with uniform nested loops.
497f2ec16ccSHideki Saito   if (!isUniformLoopNest(TheLoop /*loop nest*/,
498f2ec16ccSHideki Saito                          TheLoop /*context outer loop*/)) {
499*9e97caf5SRenato Golin     reportVectorizationFailure("Outer loop contains divergent loops",
500*9e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
501*9e97caf5SRenato Golin         "CFGNotUnderstood");
502f2ec16ccSHideki Saito     if (DoExtraAnalysis)
503f2ec16ccSHideki Saito       Result = false;
504f2ec16ccSHideki Saito     else
505f2ec16ccSHideki Saito       return false;
506f2ec16ccSHideki Saito   }
507f2ec16ccSHideki Saito 
508ea7f3035SHideki Saito   // Check whether we are able to set up outer loop induction.
509ea7f3035SHideki Saito   if (!setupOuterLoopInductions()) {
510*9e97caf5SRenato Golin     reportVectorizationFailure("Unsupported outer loop Phi(s)",
511*9e97caf5SRenato Golin                                "Unsupported outer loop Phi(s)",
512*9e97caf5SRenato Golin                                "UnsupportedPhi");
513ea7f3035SHideki Saito     if (DoExtraAnalysis)
514ea7f3035SHideki Saito       Result = false;
515ea7f3035SHideki Saito     else
516ea7f3035SHideki Saito       return false;
517ea7f3035SHideki Saito   }
518ea7f3035SHideki Saito 
519f2ec16ccSHideki Saito   return Result;
520f2ec16ccSHideki Saito }
521f2ec16ccSHideki Saito 
522f2ec16ccSHideki Saito void LoopVectorizationLegality::addInductionPhi(
523f2ec16ccSHideki Saito     PHINode *Phi, const InductionDescriptor &ID,
524f2ec16ccSHideki Saito     SmallPtrSetImpl<Value *> &AllowedExit) {
525f2ec16ccSHideki Saito   Inductions[Phi] = ID;
526f2ec16ccSHideki Saito 
527f2ec16ccSHideki Saito   // In case this induction also comes with casts that we know we can ignore
528f2ec16ccSHideki Saito   // in the vectorized loop body, record them here. All casts could be recorded
529f2ec16ccSHideki Saito   // here for ignoring, but suffices to record only the first (as it is the
530f2ec16ccSHideki Saito   // only one that may bw used outside the cast sequence).
531f2ec16ccSHideki Saito   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
532f2ec16ccSHideki Saito   if (!Casts.empty())
533f2ec16ccSHideki Saito     InductionCastsToIgnore.insert(*Casts.begin());
534f2ec16ccSHideki Saito 
535f2ec16ccSHideki Saito   Type *PhiTy = Phi->getType();
536f2ec16ccSHideki Saito   const DataLayout &DL = Phi->getModule()->getDataLayout();
537f2ec16ccSHideki Saito 
538f2ec16ccSHideki Saito   // Get the widest type.
539f2ec16ccSHideki Saito   if (!PhiTy->isFloatingPointTy()) {
540f2ec16ccSHideki Saito     if (!WidestIndTy)
541f2ec16ccSHideki Saito       WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
542f2ec16ccSHideki Saito     else
543f2ec16ccSHideki Saito       WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
544f2ec16ccSHideki Saito   }
545f2ec16ccSHideki Saito 
546f2ec16ccSHideki Saito   // Int inductions are special because we only allow one IV.
547f2ec16ccSHideki Saito   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
548f2ec16ccSHideki Saito       ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
549f2ec16ccSHideki Saito       isa<Constant>(ID.getStartValue()) &&
550f2ec16ccSHideki Saito       cast<Constant>(ID.getStartValue())->isNullValue()) {
551f2ec16ccSHideki Saito 
552f2ec16ccSHideki Saito     // Use the phi node with the widest type as induction. Use the last
553f2ec16ccSHideki Saito     // one if there are multiple (no good reason for doing this other
554f2ec16ccSHideki Saito     // than it is expedient). We've checked that it begins at zero and
555f2ec16ccSHideki Saito     // steps by one, so this is a canonical induction variable.
556f2ec16ccSHideki Saito     if (!PrimaryInduction || PhiTy == WidestIndTy)
557f2ec16ccSHideki Saito       PrimaryInduction = Phi;
558f2ec16ccSHideki Saito   }
559f2ec16ccSHideki Saito 
560f2ec16ccSHideki Saito   // Both the PHI node itself, and the "post-increment" value feeding
561f2ec16ccSHideki Saito   // back into the PHI node may have external users.
562f2ec16ccSHideki Saito   // We can allow those uses, except if the SCEVs we have for them rely
563f2ec16ccSHideki Saito   // on predicates that only hold within the loop, since allowing the exit
5646a1dd77fSAnna Thomas   // currently means re-using this SCEV outside the loop (see PR33706 for more
5656a1dd77fSAnna Thomas   // details).
566f2ec16ccSHideki Saito   if (PSE.getUnionPredicate().isAlwaysTrue()) {
567f2ec16ccSHideki Saito     AllowedExit.insert(Phi);
568f2ec16ccSHideki Saito     AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
569f2ec16ccSHideki Saito   }
570f2ec16ccSHideki Saito 
571d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
572f2ec16ccSHideki Saito }
573f2ec16ccSHideki Saito 
574ea7f3035SHideki Saito bool LoopVectorizationLegality::setupOuterLoopInductions() {
575ea7f3035SHideki Saito   BasicBlock *Header = TheLoop->getHeader();
576ea7f3035SHideki Saito 
577ea7f3035SHideki Saito   // Returns true if a given Phi is a supported induction.
578ea7f3035SHideki Saito   auto isSupportedPhi = [&](PHINode &Phi) -> bool {
579ea7f3035SHideki Saito     InductionDescriptor ID;
580ea7f3035SHideki Saito     if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
581ea7f3035SHideki Saito         ID.getKind() == InductionDescriptor::IK_IntInduction) {
582ea7f3035SHideki Saito       addInductionPhi(&Phi, ID, AllowedExit);
583ea7f3035SHideki Saito       return true;
584ea7f3035SHideki Saito     } else {
585ea7f3035SHideki Saito       // Bail out for any Phi in the outer loop header that is not a supported
586ea7f3035SHideki Saito       // induction.
587ea7f3035SHideki Saito       LLVM_DEBUG(
588ea7f3035SHideki Saito           dbgs()
589ea7f3035SHideki Saito           << "LV: Found unsupported PHI for outer loop vectorization.\n");
590ea7f3035SHideki Saito       return false;
591ea7f3035SHideki Saito     }
592ea7f3035SHideki Saito   };
593ea7f3035SHideki Saito 
594ea7f3035SHideki Saito   if (llvm::all_of(Header->phis(), isSupportedPhi))
595ea7f3035SHideki Saito     return true;
596ea7f3035SHideki Saito   else
597ea7f3035SHideki Saito     return false;
598ea7f3035SHideki Saito }
599ea7f3035SHideki Saito 
600f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeInstrs() {
601f2ec16ccSHideki Saito   BasicBlock *Header = TheLoop->getHeader();
602f2ec16ccSHideki Saito 
603f2ec16ccSHideki Saito   // Look for the attribute signaling the absence of NaNs.
604f2ec16ccSHideki Saito   Function &F = *Header->getParent();
605f2ec16ccSHideki Saito   HasFunNoNaNAttr =
606f2ec16ccSHideki Saito       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
607f2ec16ccSHideki Saito 
608f2ec16ccSHideki Saito   // For each block in the loop.
609f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
610f2ec16ccSHideki Saito     // Scan the instructions in the block and look for hazards.
611f2ec16ccSHideki Saito     for (Instruction &I : *BB) {
612f2ec16ccSHideki Saito       if (auto *Phi = dyn_cast<PHINode>(&I)) {
613f2ec16ccSHideki Saito         Type *PhiTy = Phi->getType();
614f2ec16ccSHideki Saito         // Check that this PHI type is allowed.
615f2ec16ccSHideki Saito         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
616f2ec16ccSHideki Saito             !PhiTy->isPointerTy()) {
617*9e97caf5SRenato Golin           reportVectorizationFailure("Found a non-int non-pointer PHI",
618*9e97caf5SRenato Golin                                      "loop control flow is not understood by vectorizer",
619*9e97caf5SRenato Golin                                      "CFGNotUnderstood");
620f2ec16ccSHideki Saito           return false;
621f2ec16ccSHideki Saito         }
622f2ec16ccSHideki Saito 
623f2ec16ccSHideki Saito         // If this PHINode is not in the header block, then we know that we
624f2ec16ccSHideki Saito         // can convert it to select during if-conversion. No need to check if
625f2ec16ccSHideki Saito         // the PHIs in this block are induction or reduction variables.
626f2ec16ccSHideki Saito         if (BB != Header) {
62760a1e4ddSAnna Thomas           // Non-header phi nodes that have outside uses can be vectorized. Add
62860a1e4ddSAnna Thomas           // them to the list of allowed exits.
62960a1e4ddSAnna Thomas           // Unsafe cyclic dependencies with header phis are identified during
63060a1e4ddSAnna Thomas           // legalization for reduction, induction and first order
63160a1e4ddSAnna Thomas           // recurrences.
632f2ec16ccSHideki Saito           continue;
633f2ec16ccSHideki Saito         }
634f2ec16ccSHideki Saito 
635f2ec16ccSHideki Saito         // We only allow if-converted PHIs with exactly two incoming values.
636f2ec16ccSHideki Saito         if (Phi->getNumIncomingValues() != 2) {
637*9e97caf5SRenato Golin           reportVectorizationFailure("Found an invalid PHI",
638*9e97caf5SRenato Golin               "loop control flow is not understood by vectorizer",
639*9e97caf5SRenato Golin               "CFGNotUnderstood", Phi);
640f2ec16ccSHideki Saito           return false;
641f2ec16ccSHideki Saito         }
642f2ec16ccSHideki Saito 
643f2ec16ccSHideki Saito         RecurrenceDescriptor RedDes;
644f2ec16ccSHideki Saito         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
645f2ec16ccSHideki Saito                                                  DT)) {
646f2ec16ccSHideki Saito           if (RedDes.hasUnsafeAlgebra())
647f2ec16ccSHideki Saito             Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
648f2ec16ccSHideki Saito           AllowedExit.insert(RedDes.getLoopExitInstr());
649f2ec16ccSHideki Saito           Reductions[Phi] = RedDes;
650f2ec16ccSHideki Saito           continue;
651f2ec16ccSHideki Saito         }
652f2ec16ccSHideki Saito 
653b02b0ad8SAnna Thomas         // TODO: Instead of recording the AllowedExit, it would be good to record the
654b02b0ad8SAnna Thomas         // complementary set: NotAllowedExit. These include (but may not be
655b02b0ad8SAnna Thomas         // limited to):
656b02b0ad8SAnna Thomas         // 1. Reduction phis as they represent the one-before-last value, which
657b02b0ad8SAnna Thomas         // is not available when vectorized
658b02b0ad8SAnna Thomas         // 2. Induction phis and increment when SCEV predicates cannot be used
659b02b0ad8SAnna Thomas         // outside the loop - see addInductionPhi
660b02b0ad8SAnna Thomas         // 3. Non-Phis with outside uses when SCEV predicates cannot be used
661b02b0ad8SAnna Thomas         // outside the loop - see call to hasOutsideLoopUser in the non-phi
662b02b0ad8SAnna Thomas         // handling below
663b02b0ad8SAnna Thomas         // 4. FirstOrderRecurrence phis that can possibly be handled by
664b02b0ad8SAnna Thomas         // extraction.
665b02b0ad8SAnna Thomas         // By recording these, we can then reason about ways to vectorize each
666b02b0ad8SAnna Thomas         // of these NotAllowedExit.
667f2ec16ccSHideki Saito         InductionDescriptor ID;
668f2ec16ccSHideki Saito         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
669f2ec16ccSHideki Saito           addInductionPhi(Phi, ID, AllowedExit);
670f2ec16ccSHideki Saito           if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
671f2ec16ccSHideki Saito             Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
672f2ec16ccSHideki Saito           continue;
673f2ec16ccSHideki Saito         }
674f2ec16ccSHideki Saito 
675f2ec16ccSHideki Saito         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
676f2ec16ccSHideki Saito                                                          SinkAfter, DT)) {
677f2ec16ccSHideki Saito           FirstOrderRecurrences.insert(Phi);
678f2ec16ccSHideki Saito           continue;
679f2ec16ccSHideki Saito         }
680f2ec16ccSHideki Saito 
681f2ec16ccSHideki Saito         // As a last resort, coerce the PHI to a AddRec expression
682f2ec16ccSHideki Saito         // and re-try classifying it a an induction PHI.
683f2ec16ccSHideki Saito         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
684f2ec16ccSHideki Saito           addInductionPhi(Phi, ID, AllowedExit);
685f2ec16ccSHideki Saito           continue;
686f2ec16ccSHideki Saito         }
687f2ec16ccSHideki Saito 
688*9e97caf5SRenato Golin         reportVectorizationFailure("Found an unidentified PHI",
689*9e97caf5SRenato Golin             "value that could not be identified as "
690*9e97caf5SRenato Golin             "reduction is used outside the loop",
691*9e97caf5SRenato Golin             "NonReductionValueUsedOutsideLoop", Phi);
692f2ec16ccSHideki Saito         return false;
693f2ec16ccSHideki Saito       } // end of PHI handling
694f2ec16ccSHideki Saito 
695f2ec16ccSHideki Saito       // We handle calls that:
696f2ec16ccSHideki Saito       //   * Are debug info intrinsics.
697f2ec16ccSHideki Saito       //   * Have a mapping to an IR intrinsic.
698f2ec16ccSHideki Saito       //   * Have a vector version available.
699f2ec16ccSHideki Saito       auto *CI = dyn_cast<CallInst>(&I);
700f2ec16ccSHideki Saito       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
701f2ec16ccSHideki Saito           !isa<DbgInfoIntrinsic>(CI) &&
702f2ec16ccSHideki Saito           !(CI->getCalledFunction() && TLI &&
703f2ec16ccSHideki Saito             TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
7047d65fe5cSSanjay Patel         // If the call is a recognized math libary call, it is likely that
7057d65fe5cSSanjay Patel         // we can vectorize it given loosened floating-point constraints.
7067d65fe5cSSanjay Patel         LibFunc Func;
7077d65fe5cSSanjay Patel         bool IsMathLibCall =
7087d65fe5cSSanjay Patel             TLI && CI->getCalledFunction() &&
7097d65fe5cSSanjay Patel             CI->getType()->isFloatingPointTy() &&
7107d65fe5cSSanjay Patel             TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
7117d65fe5cSSanjay Patel             TLI->hasOptimizedCodeGen(Func);
7127d65fe5cSSanjay Patel 
7137d65fe5cSSanjay Patel         if (IsMathLibCall) {
7147d65fe5cSSanjay Patel           // TODO: Ideally, we should not use clang-specific language here,
7157d65fe5cSSanjay Patel           // but it's hard to provide meaningful yet generic advice.
7167d65fe5cSSanjay Patel           // Also, should this be guarded by allowExtraAnalysis() and/or be part
7177d65fe5cSSanjay Patel           // of the returned info from isFunctionVectorizable()?
718*9e97caf5SRenato Golin           reportVectorizationFailure("Found a non-intrinsic callsite",
719*9e97caf5SRenato Golin               "library call cannot be vectorized. "
7207d65fe5cSSanjay Patel               "Try compiling with -fno-math-errno, -ffast-math, "
721*9e97caf5SRenato Golin               "or similar flags",
722*9e97caf5SRenato Golin               "CantVectorizeLibcall", CI);
7237d65fe5cSSanjay Patel         } else {
724*9e97caf5SRenato Golin           reportVectorizationFailure("Found a non-intrinsic callsite",
725*9e97caf5SRenato Golin                                      "call instruction cannot be vectorized",
726*9e97caf5SRenato Golin                                      "CantVectorizeLibcall", CI);
7277d65fe5cSSanjay Patel         }
728f2ec16ccSHideki Saito         return false;
729f2ec16ccSHideki Saito       }
730f2ec16ccSHideki Saito 
731a066f1f9SSimon Pilgrim       // Some intrinsics have scalar arguments and should be same in order for
732a066f1f9SSimon Pilgrim       // them to be vectorized (i.e. loop invariant).
733a066f1f9SSimon Pilgrim       if (CI) {
734f2ec16ccSHideki Saito         auto *SE = PSE.getSE();
735a066f1f9SSimon Pilgrim         Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
736a066f1f9SSimon Pilgrim         for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
737a066f1f9SSimon Pilgrim           if (hasVectorInstrinsicScalarOpd(IntrinID, i)) {
738a066f1f9SSimon Pilgrim             if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(i)), TheLoop)) {
739*9e97caf5SRenato Golin               reportVectorizationFailure("Found unvectorizable intrinsic",
740*9e97caf5SRenato Golin                   "intrinsic instruction cannot be vectorized",
741*9e97caf5SRenato Golin                   "CantVectorizeIntrinsic", CI);
742f2ec16ccSHideki Saito               return false;
743f2ec16ccSHideki Saito             }
744f2ec16ccSHideki Saito           }
745a066f1f9SSimon Pilgrim       }
746f2ec16ccSHideki Saito 
747f2ec16ccSHideki Saito       // Check that the instruction return type is vectorizable.
748f2ec16ccSHideki Saito       // Also, we can't vectorize extractelement instructions.
749f2ec16ccSHideki Saito       if ((!VectorType::isValidElementType(I.getType()) &&
750f2ec16ccSHideki Saito            !I.getType()->isVoidTy()) ||
751f2ec16ccSHideki Saito           isa<ExtractElementInst>(I)) {
752*9e97caf5SRenato Golin         reportVectorizationFailure("Found unvectorizable type",
753*9e97caf5SRenato Golin             "instruction return type cannot be vectorized",
754*9e97caf5SRenato Golin             "CantVectorizeInstructionReturnType", &I);
755f2ec16ccSHideki Saito         return false;
756f2ec16ccSHideki Saito       }
757f2ec16ccSHideki Saito 
758f2ec16ccSHideki Saito       // Check that the stored type is vectorizable.
759f2ec16ccSHideki Saito       if (auto *ST = dyn_cast<StoreInst>(&I)) {
760f2ec16ccSHideki Saito         Type *T = ST->getValueOperand()->getType();
761f2ec16ccSHideki Saito         if (!VectorType::isValidElementType(T)) {
762*9e97caf5SRenato Golin           reportVectorizationFailure("Store instruction cannot be vectorized",
763*9e97caf5SRenato Golin                                      "store instruction cannot be vectorized",
764*9e97caf5SRenato Golin                                      "CantVectorizeStore", ST);
765f2ec16ccSHideki Saito           return false;
766f2ec16ccSHideki Saito         }
767f2ec16ccSHideki Saito 
768f2ec16ccSHideki Saito         // FP instructions can allow unsafe algebra, thus vectorizable by
769f2ec16ccSHideki Saito         // non-IEEE-754 compliant SIMD units.
770f2ec16ccSHideki Saito         // This applies to floating-point math operations and calls, not memory
771f2ec16ccSHideki Saito         // operations, shuffles, or casts, as they don't change precision or
772f2ec16ccSHideki Saito         // semantics.
773f2ec16ccSHideki Saito       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
774f2ec16ccSHideki Saito                  !I.isFast()) {
775d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
776f2ec16ccSHideki Saito         Hints->setPotentiallyUnsafe();
777f2ec16ccSHideki Saito       }
778f2ec16ccSHideki Saito 
779f2ec16ccSHideki Saito       // Reduction instructions are allowed to have exit users.
780f2ec16ccSHideki Saito       // All other instructions must not have external users.
781f2ec16ccSHideki Saito       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
782b02b0ad8SAnna Thomas         // We can safely vectorize loops where instructions within the loop are
783b02b0ad8SAnna Thomas         // used outside the loop only if the SCEV predicates within the loop is
784b02b0ad8SAnna Thomas         // same as outside the loop. Allowing the exit means reusing the SCEV
785b02b0ad8SAnna Thomas         // outside the loop.
786b02b0ad8SAnna Thomas         if (PSE.getUnionPredicate().isAlwaysTrue()) {
787b02b0ad8SAnna Thomas           AllowedExit.insert(&I);
788b02b0ad8SAnna Thomas           continue;
789b02b0ad8SAnna Thomas         }
790*9e97caf5SRenato Golin         reportVectorizationFailure("Value cannot be used outside the loop",
791*9e97caf5SRenato Golin                                    "value cannot be used outside the loop",
792*9e97caf5SRenato Golin                                    "ValueUsedOutsideLoop", &I);
793f2ec16ccSHideki Saito         return false;
794f2ec16ccSHideki Saito       }
795f2ec16ccSHideki Saito     } // next instr.
796f2ec16ccSHideki Saito   }
797f2ec16ccSHideki Saito 
798f2ec16ccSHideki Saito   if (!PrimaryInduction) {
799f2ec16ccSHideki Saito     if (Inductions.empty()) {
800*9e97caf5SRenato Golin       reportVectorizationFailure("Did not find one integer induction var",
801*9e97caf5SRenato Golin           "loop induction variable could not be identified",
802*9e97caf5SRenato Golin           "NoInductionVariable");
803f2ec16ccSHideki Saito       return false;
8044f27730eSWarren Ristow     } else if (!WidestIndTy) {
805*9e97caf5SRenato Golin       reportVectorizationFailure("Did not find one integer induction var",
806*9e97caf5SRenato Golin           "integer loop induction variable could not be identified",
807*9e97caf5SRenato Golin           "NoIntegerInductionVariable");
8084f27730eSWarren Ristow       return false;
809*9e97caf5SRenato Golin     } else {
810*9e97caf5SRenato Golin       LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
811f2ec16ccSHideki Saito     }
812f2ec16ccSHideki Saito   }
813f2ec16ccSHideki Saito 
814f2ec16ccSHideki Saito   // Now we know the widest induction type, check if our found induction
815f2ec16ccSHideki Saito   // is the same size. If it's not, unset it here and InnerLoopVectorizer
816f2ec16ccSHideki Saito   // will create another.
817f2ec16ccSHideki Saito   if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
818f2ec16ccSHideki Saito     PrimaryInduction = nullptr;
819f2ec16ccSHideki Saito 
820f2ec16ccSHideki Saito   return true;
821f2ec16ccSHideki Saito }
822f2ec16ccSHideki Saito 
823f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeMemory() {
824f2ec16ccSHideki Saito   LAI = &(*GetLAA)(*TheLoop);
825f2ec16ccSHideki Saito   const OptimizationRemarkAnalysis *LAR = LAI->getReport();
826f2ec16ccSHideki Saito   if (LAR) {
827f2ec16ccSHideki Saito     ORE->emit([&]() {
828f2ec16ccSHideki Saito       return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
829f2ec16ccSHideki Saito                                         "loop not vectorized: ", *LAR);
830f2ec16ccSHideki Saito     });
831f2ec16ccSHideki Saito   }
832f2ec16ccSHideki Saito   if (!LAI->canVectorizeMemory())
833f2ec16ccSHideki Saito     return false;
834f2ec16ccSHideki Saito 
8355e9215f0SAnna Thomas   if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
836*9e97caf5SRenato Golin     reportVectorizationFailure("Stores to a uniform address",
837*9e97caf5SRenato Golin         "write to a loop invariant address could not be vectorized",
838*9e97caf5SRenato Golin         "CantVectorizeStoreToLoopInvariantAddress");
839f2ec16ccSHideki Saito     return false;
840f2ec16ccSHideki Saito   }
841f2ec16ccSHideki Saito   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
842f2ec16ccSHideki Saito   PSE.addPredicate(LAI->getPSE().getUnionPredicate());
843f2ec16ccSHideki Saito 
844f2ec16ccSHideki Saito   return true;
845f2ec16ccSHideki Saito }
846f2ec16ccSHideki Saito 
847f2ec16ccSHideki Saito bool LoopVectorizationLegality::isInductionPhi(const Value *V) {
848f2ec16ccSHideki Saito   Value *In0 = const_cast<Value *>(V);
849f2ec16ccSHideki Saito   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
850f2ec16ccSHideki Saito   if (!PN)
851f2ec16ccSHideki Saito     return false;
852f2ec16ccSHideki Saito 
853f2ec16ccSHideki Saito   return Inductions.count(PN);
854f2ec16ccSHideki Saito }
855f2ec16ccSHideki Saito 
856f2ec16ccSHideki Saito bool LoopVectorizationLegality::isCastedInductionVariable(const Value *V) {
857f2ec16ccSHideki Saito   auto *Inst = dyn_cast<Instruction>(V);
858f2ec16ccSHideki Saito   return (Inst && InductionCastsToIgnore.count(Inst));
859f2ec16ccSHideki Saito }
860f2ec16ccSHideki Saito 
861f2ec16ccSHideki Saito bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
862f2ec16ccSHideki Saito   return isInductionPhi(V) || isCastedInductionVariable(V);
863f2ec16ccSHideki Saito }
864f2ec16ccSHideki Saito 
865f2ec16ccSHideki Saito bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
866f2ec16ccSHideki Saito   return FirstOrderRecurrences.count(Phi);
867f2ec16ccSHideki Saito }
868f2ec16ccSHideki Saito 
869f2ec16ccSHideki Saito bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
870f2ec16ccSHideki Saito   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
871f2ec16ccSHideki Saito }
872f2ec16ccSHideki Saito 
873f2ec16ccSHideki Saito bool LoopVectorizationLegality::blockCanBePredicated(
874f2ec16ccSHideki Saito     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
875f2ec16ccSHideki Saito   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
876f2ec16ccSHideki Saito 
877f2ec16ccSHideki Saito   for (Instruction &I : *BB) {
878f2ec16ccSHideki Saito     // Check that we don't have a constant expression that can trap as operand.
879f2ec16ccSHideki Saito     for (Value *Operand : I.operands()) {
880f2ec16ccSHideki Saito       if (auto *C = dyn_cast<Constant>(Operand))
881f2ec16ccSHideki Saito         if (C->canTrap())
882f2ec16ccSHideki Saito           return false;
883f2ec16ccSHideki Saito     }
884f2ec16ccSHideki Saito     // We might be able to hoist the load.
885f2ec16ccSHideki Saito     if (I.mayReadFromMemory()) {
886f2ec16ccSHideki Saito       auto *LI = dyn_cast<LoadInst>(&I);
887f2ec16ccSHideki Saito       if (!LI)
888f2ec16ccSHideki Saito         return false;
889f2ec16ccSHideki Saito       if (!SafePtrs.count(LI->getPointerOperand())) {
890f2ec16ccSHideki Saito         // !llvm.mem.parallel_loop_access implies if-conversion safety.
891f2ec16ccSHideki Saito         // Otherwise, record that the load needs (real or emulated) masking
892f2ec16ccSHideki Saito         // and let the cost model decide.
893f2ec16ccSHideki Saito         if (!IsAnnotatedParallel)
894f2ec16ccSHideki Saito           MaskedOp.insert(LI);
895f2ec16ccSHideki Saito         continue;
896f2ec16ccSHideki Saito       }
897f2ec16ccSHideki Saito     }
898f2ec16ccSHideki Saito 
899f2ec16ccSHideki Saito     if (I.mayWriteToMemory()) {
900f2ec16ccSHideki Saito       auto *SI = dyn_cast<StoreInst>(&I);
901f2ec16ccSHideki Saito       if (!SI)
902f2ec16ccSHideki Saito         return false;
903f2ec16ccSHideki Saito       // Predicated store requires some form of masking:
904f2ec16ccSHideki Saito       // 1) masked store HW instruction,
905f2ec16ccSHideki Saito       // 2) emulation via load-blend-store (only if safe and legal to do so,
906f2ec16ccSHideki Saito       //    be aware on the race conditions), or
907f2ec16ccSHideki Saito       // 3) element-by-element predicate check and scalar store.
908f2ec16ccSHideki Saito       MaskedOp.insert(SI);
909f2ec16ccSHideki Saito       continue;
910f2ec16ccSHideki Saito     }
911f2ec16ccSHideki Saito     if (I.mayThrow())
912f2ec16ccSHideki Saito       return false;
913f2ec16ccSHideki Saito   }
914f2ec16ccSHideki Saito 
915f2ec16ccSHideki Saito   return true;
916f2ec16ccSHideki Saito }
917f2ec16ccSHideki Saito 
918f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
919f2ec16ccSHideki Saito   if (!EnableIfConversion) {
920*9e97caf5SRenato Golin     reportVectorizationFailure("If-conversion is disabled",
921*9e97caf5SRenato Golin                                "if-conversion is disabled",
922*9e97caf5SRenato Golin                                "IfConversionDisabled");
923f2ec16ccSHideki Saito     return false;
924f2ec16ccSHideki Saito   }
925f2ec16ccSHideki Saito 
926f2ec16ccSHideki Saito   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
927f2ec16ccSHideki Saito 
928f2ec16ccSHideki Saito   // A list of pointers that we can safely read and write to.
929f2ec16ccSHideki Saito   SmallPtrSet<Value *, 8> SafePointes;
930f2ec16ccSHideki Saito 
931f2ec16ccSHideki Saito   // Collect safe addresses.
932f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
933f2ec16ccSHideki Saito     if (blockNeedsPredication(BB))
934f2ec16ccSHideki Saito       continue;
935f2ec16ccSHideki Saito 
936f2ec16ccSHideki Saito     for (Instruction &I : *BB)
937f2ec16ccSHideki Saito       if (auto *Ptr = getLoadStorePointerOperand(&I))
938f2ec16ccSHideki Saito         SafePointes.insert(Ptr);
939f2ec16ccSHideki Saito   }
940f2ec16ccSHideki Saito 
941f2ec16ccSHideki Saito   // Collect the blocks that need predication.
942f2ec16ccSHideki Saito   BasicBlock *Header = TheLoop->getHeader();
943f2ec16ccSHideki Saito   for (BasicBlock *BB : TheLoop->blocks()) {
944f2ec16ccSHideki Saito     // We don't support switch statements inside loops.
945f2ec16ccSHideki Saito     if (!isa<BranchInst>(BB->getTerminator())) {
946*9e97caf5SRenato Golin       reportVectorizationFailure("Loop contains a switch statement",
947*9e97caf5SRenato Golin                                  "loop contains a switch statement",
948*9e97caf5SRenato Golin                                  "LoopContainsSwitch", BB->getTerminator());
949f2ec16ccSHideki Saito       return false;
950f2ec16ccSHideki Saito     }
951f2ec16ccSHideki Saito 
952f2ec16ccSHideki Saito     // We must be able to predicate all blocks that need to be predicated.
953f2ec16ccSHideki Saito     if (blockNeedsPredication(BB)) {
954f2ec16ccSHideki Saito       if (!blockCanBePredicated(BB, SafePointes)) {
955*9e97caf5SRenato Golin         reportVectorizationFailure(
956*9e97caf5SRenato Golin             "Control flow cannot be substituted for a select",
957*9e97caf5SRenato Golin             "control flow cannot be substituted for a select",
958*9e97caf5SRenato Golin             "NoCFGForSelect", BB->getTerminator());
959f2ec16ccSHideki Saito         return false;
960f2ec16ccSHideki Saito       }
961f2ec16ccSHideki Saito     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
962*9e97caf5SRenato Golin       reportVectorizationFailure(
963*9e97caf5SRenato Golin           "Control flow cannot be substituted for a select",
964*9e97caf5SRenato Golin           "control flow cannot be substituted for a select",
965*9e97caf5SRenato Golin           "NoCFGForSelect", BB->getTerminator());
966f2ec16ccSHideki Saito       return false;
967f2ec16ccSHideki Saito     }
968f2ec16ccSHideki Saito   }
969f2ec16ccSHideki Saito 
970f2ec16ccSHideki Saito   // We can if-convert this loop.
971f2ec16ccSHideki Saito   return true;
972f2ec16ccSHideki Saito }
973f2ec16ccSHideki Saito 
974f2ec16ccSHideki Saito // Helper function to canVectorizeLoopNestCFG.
975f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
976f2ec16ccSHideki Saito                                                     bool UseVPlanNativePath) {
977f2ec16ccSHideki Saito   assert((UseVPlanNativePath || Lp->empty()) &&
978f2ec16ccSHideki Saito          "VPlan-native path is not enabled.");
979f2ec16ccSHideki Saito 
980f2ec16ccSHideki Saito   // TODO: ORE should be improved to show more accurate information when an
981f2ec16ccSHideki Saito   // outer loop can't be vectorized because a nested loop is not understood or
982f2ec16ccSHideki Saito   // legal. Something like: "outer_loop_location: loop not vectorized:
983f2ec16ccSHideki Saito   // (inner_loop_location) loop control flow is not understood by vectorizer".
984f2ec16ccSHideki Saito 
985f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
986f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
987f2ec16ccSHideki Saito   bool Result = true;
988f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
989f2ec16ccSHideki Saito 
990f2ec16ccSHideki Saito   // We must have a loop in canonical form. Loops with indirectbr in them cannot
991f2ec16ccSHideki Saito   // be canonicalized.
992f2ec16ccSHideki Saito   if (!Lp->getLoopPreheader()) {
993*9e97caf5SRenato Golin     reportVectorizationFailure("Loop doesn't have a legal pre-header",
994*9e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
995*9e97caf5SRenato Golin         "CFGNotUnderstood");
996f2ec16ccSHideki Saito     if (DoExtraAnalysis)
997f2ec16ccSHideki Saito       Result = false;
998f2ec16ccSHideki Saito     else
999f2ec16ccSHideki Saito       return false;
1000f2ec16ccSHideki Saito   }
1001f2ec16ccSHideki Saito 
1002f2ec16ccSHideki Saito   // We must have a single backedge.
1003f2ec16ccSHideki Saito   if (Lp->getNumBackEdges() != 1) {
1004*9e97caf5SRenato Golin     reportVectorizationFailure("The loop must have a single backedge",
1005*9e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1006*9e97caf5SRenato Golin         "CFGNotUnderstood");
1007f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1008f2ec16ccSHideki Saito       Result = false;
1009f2ec16ccSHideki Saito     else
1010f2ec16ccSHideki Saito       return false;
1011f2ec16ccSHideki Saito   }
1012f2ec16ccSHideki Saito 
1013f2ec16ccSHideki Saito   // We must have a single exiting block.
1014f2ec16ccSHideki Saito   if (!Lp->getExitingBlock()) {
1015*9e97caf5SRenato Golin     reportVectorizationFailure("The loop must have an exiting block",
1016*9e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1017*9e97caf5SRenato Golin         "CFGNotUnderstood");
1018f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1019f2ec16ccSHideki Saito       Result = false;
1020f2ec16ccSHideki Saito     else
1021f2ec16ccSHideki Saito       return false;
1022f2ec16ccSHideki Saito   }
1023f2ec16ccSHideki Saito 
1024f2ec16ccSHideki Saito   // We only handle bottom-tested loops, i.e. loop in which the condition is
1025f2ec16ccSHideki Saito   // checked at the end of each iteration. With that we can assume that all
1026f2ec16ccSHideki Saito   // instructions in the loop are executed the same number of times.
1027f2ec16ccSHideki Saito   if (Lp->getExitingBlock() != Lp->getLoopLatch()) {
1028*9e97caf5SRenato Golin     reportVectorizationFailure("The exiting block is not the loop latch",
1029*9e97caf5SRenato Golin         "loop control flow is not understood by vectorizer",
1030*9e97caf5SRenato Golin         "CFGNotUnderstood");
1031f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1032f2ec16ccSHideki Saito       Result = false;
1033f2ec16ccSHideki Saito     else
1034f2ec16ccSHideki Saito       return false;
1035f2ec16ccSHideki Saito   }
1036f2ec16ccSHideki Saito 
1037f2ec16ccSHideki Saito   return Result;
1038f2ec16ccSHideki Saito }
1039f2ec16ccSHideki Saito 
1040f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1041f2ec16ccSHideki Saito     Loop *Lp, bool UseVPlanNativePath) {
1042f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1043f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1044f2ec16ccSHideki Saito   bool Result = true;
1045f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1046f2ec16ccSHideki Saito   if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1047f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1048f2ec16ccSHideki Saito       Result = false;
1049f2ec16ccSHideki Saito     else
1050f2ec16ccSHideki Saito       return false;
1051f2ec16ccSHideki Saito   }
1052f2ec16ccSHideki Saito 
1053f2ec16ccSHideki Saito   // Recursively check whether the loop control flow of nested loops is
1054f2ec16ccSHideki Saito   // understood.
1055f2ec16ccSHideki Saito   for (Loop *SubLp : *Lp)
1056f2ec16ccSHideki Saito     if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1057f2ec16ccSHideki Saito       if (DoExtraAnalysis)
1058f2ec16ccSHideki Saito         Result = false;
1059f2ec16ccSHideki Saito       else
1060f2ec16ccSHideki Saito         return false;
1061f2ec16ccSHideki Saito     }
1062f2ec16ccSHideki Saito 
1063f2ec16ccSHideki Saito   return Result;
1064f2ec16ccSHideki Saito }
1065f2ec16ccSHideki Saito 
1066f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1067f2ec16ccSHideki Saito   // Store the result and return it at the end instead of exiting early, in case
1068f2ec16ccSHideki Saito   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1069f2ec16ccSHideki Saito   bool Result = true;
1070f2ec16ccSHideki Saito 
1071f2ec16ccSHideki Saito   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1072f2ec16ccSHideki Saito   // Check whether the loop-related control flow in the loop nest is expected by
1073f2ec16ccSHideki Saito   // vectorizer.
1074f2ec16ccSHideki Saito   if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1075f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1076f2ec16ccSHideki Saito       Result = false;
1077f2ec16ccSHideki Saito     else
1078f2ec16ccSHideki Saito       return false;
1079f2ec16ccSHideki Saito   }
1080f2ec16ccSHideki Saito 
1081f2ec16ccSHideki Saito   // We need to have a loop header.
1082d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1083f2ec16ccSHideki Saito                     << '\n');
1084f2ec16ccSHideki Saito 
1085f2ec16ccSHideki Saito   // Specific checks for outer loops. We skip the remaining legal checks at this
1086f2ec16ccSHideki Saito   // point because they don't support outer loops.
1087f2ec16ccSHideki Saito   if (!TheLoop->empty()) {
1088f2ec16ccSHideki Saito     assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1089f2ec16ccSHideki Saito 
1090f2ec16ccSHideki Saito     if (!canVectorizeOuterLoop()) {
1091*9e97caf5SRenato Golin       reportVectorizationFailure("Unsupported outer loop",
1092*9e97caf5SRenato Golin                                  "unsupported outer loop",
1093*9e97caf5SRenato Golin                                  "UnsupportedOuterLoop");
1094f2ec16ccSHideki Saito       // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1095f2ec16ccSHideki Saito       // outer loops.
1096f2ec16ccSHideki Saito       return false;
1097f2ec16ccSHideki Saito     }
1098f2ec16ccSHideki Saito 
1099d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1100f2ec16ccSHideki Saito     return Result;
1101f2ec16ccSHideki Saito   }
1102f2ec16ccSHideki Saito 
1103f2ec16ccSHideki Saito   assert(TheLoop->empty() && "Inner loop expected.");
1104f2ec16ccSHideki Saito   // Check if we can if-convert non-single-bb loops.
1105f2ec16ccSHideki Saito   unsigned NumBlocks = TheLoop->getNumBlocks();
1106f2ec16ccSHideki Saito   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1107d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1108f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1109f2ec16ccSHideki Saito       Result = false;
1110f2ec16ccSHideki Saito     else
1111f2ec16ccSHideki Saito       return false;
1112f2ec16ccSHideki Saito   }
1113f2ec16ccSHideki Saito 
1114f2ec16ccSHideki Saito   // Check if we can vectorize the instructions and CFG in this loop.
1115f2ec16ccSHideki Saito   if (!canVectorizeInstrs()) {
1116d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1117f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1118f2ec16ccSHideki Saito       Result = false;
1119f2ec16ccSHideki Saito     else
1120f2ec16ccSHideki Saito       return false;
1121f2ec16ccSHideki Saito   }
1122f2ec16ccSHideki Saito 
1123f2ec16ccSHideki Saito   // Go over each instruction and look at memory deps.
1124f2ec16ccSHideki Saito   if (!canVectorizeMemory()) {
1125d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1126f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1127f2ec16ccSHideki Saito       Result = false;
1128f2ec16ccSHideki Saito     else
1129f2ec16ccSHideki Saito       return false;
1130f2ec16ccSHideki Saito   }
1131f2ec16ccSHideki Saito 
1132d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
1133f2ec16ccSHideki Saito                     << (LAI->getRuntimePointerChecking()->Need
1134f2ec16ccSHideki Saito                             ? " (with a runtime bound check)"
1135f2ec16ccSHideki Saito                             : "")
1136f2ec16ccSHideki Saito                     << "!\n");
1137f2ec16ccSHideki Saito 
1138f2ec16ccSHideki Saito   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
1139f2ec16ccSHideki Saito   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
1140f2ec16ccSHideki Saito     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
1141f2ec16ccSHideki Saito 
1142f2ec16ccSHideki Saito   if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
1143*9e97caf5SRenato Golin     reportVectorizationFailure("Too many SCEV checks needed",
1144*9e97caf5SRenato Golin         "Too many SCEV assumptions need to be made and checked at runtime",
1145*9e97caf5SRenato Golin         "TooManySCEVRunTimeChecks");
1146f2ec16ccSHideki Saito     if (DoExtraAnalysis)
1147f2ec16ccSHideki Saito       Result = false;
1148f2ec16ccSHideki Saito     else
1149f2ec16ccSHideki Saito       return false;
1150f2ec16ccSHideki Saito   }
1151f2ec16ccSHideki Saito 
1152f2ec16ccSHideki Saito   // Okay! We've done all the tests. If any have failed, return false. Otherwise
1153f2ec16ccSHideki Saito   // we can vectorize, and at this point we don't have any other mem analysis
1154f2ec16ccSHideki Saito   // which may limit our maximum vectorization factor, so just return true with
1155f2ec16ccSHideki Saito   // no restrictions.
1156f2ec16ccSHideki Saito   return Result;
1157f2ec16ccSHideki Saito }
1158f2ec16ccSHideki Saito 
1159b0b5312eSAyal Zaks bool LoopVectorizationLegality::canFoldTailByMasking() {
1160b0b5312eSAyal Zaks 
1161b0b5312eSAyal Zaks   LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
1162b0b5312eSAyal Zaks 
1163b0b5312eSAyal Zaks   if (!PrimaryInduction) {
1164*9e97caf5SRenato Golin     reportVectorizationFailure(
1165*9e97caf5SRenato Golin         "No primary induction, cannot fold tail by masking",
1166*9e97caf5SRenato Golin         "Missing a primary induction variable in the loop, which is "
1167*9e97caf5SRenato Golin         "needed in order to fold tail by masking as required.",
1168*9e97caf5SRenato Golin         "NoPrimaryInduction");
1169b0b5312eSAyal Zaks     return false;
1170b0b5312eSAyal Zaks   }
1171b0b5312eSAyal Zaks 
1172b0b5312eSAyal Zaks   // TODO: handle reductions when tail is folded by masking.
1173b0b5312eSAyal Zaks   if (!Reductions.empty()) {
1174*9e97caf5SRenato Golin     reportVectorizationFailure(
1175*9e97caf5SRenato Golin         "Loop has reductions, cannot fold tail by masking",
1176*9e97caf5SRenato Golin         "Cannot fold tail by masking in the presence of reductions.",
1177*9e97caf5SRenato Golin         "ReductionFoldingTailByMasking");
1178b0b5312eSAyal Zaks     return false;
1179b0b5312eSAyal Zaks   }
1180b0b5312eSAyal Zaks 
1181b0b5312eSAyal Zaks   // TODO: handle outside users when tail is folded by masking.
1182b0b5312eSAyal Zaks   for (auto *AE : AllowedExit) {
1183b0b5312eSAyal Zaks     // Check that all users of allowed exit values are inside the loop.
1184b0b5312eSAyal Zaks     for (User *U : AE->users()) {
1185b0b5312eSAyal Zaks       Instruction *UI = cast<Instruction>(U);
1186b0b5312eSAyal Zaks       if (TheLoop->contains(UI))
1187b0b5312eSAyal Zaks         continue;
1188*9e97caf5SRenato Golin       reportVectorizationFailure(
1189*9e97caf5SRenato Golin           "Cannot fold tail by masking, loop has an outside user for",
1190*9e97caf5SRenato Golin           "Cannot fold tail by masking in the presence of live outs.",
1191*9e97caf5SRenato Golin           "LiveOutFoldingTailByMasking", UI);
1192b0b5312eSAyal Zaks       return false;
1193b0b5312eSAyal Zaks     }
1194b0b5312eSAyal Zaks   }
1195b0b5312eSAyal Zaks 
1196b0b5312eSAyal Zaks   // The list of pointers that we can safely read and write to remains empty.
1197b0b5312eSAyal Zaks   SmallPtrSet<Value *, 8> SafePointers;
1198b0b5312eSAyal Zaks 
1199b0b5312eSAyal Zaks   // Check and mark all blocks for predication, including those that ordinarily
1200b0b5312eSAyal Zaks   // do not need predication such as the header block.
1201b0b5312eSAyal Zaks   for (BasicBlock *BB : TheLoop->blocks()) {
1202b0b5312eSAyal Zaks     if (!blockCanBePredicated(BB, SafePointers)) {
1203*9e97caf5SRenato Golin       reportVectorizationFailure(
1204*9e97caf5SRenato Golin           "Cannot fold tail by masking as required",
1205*9e97caf5SRenato Golin           "control flow cannot be substituted for a select",
1206*9e97caf5SRenato Golin           "NoCFGForSelect", BB->getTerminator());
1207b0b5312eSAyal Zaks       return false;
1208b0b5312eSAyal Zaks     }
1209b0b5312eSAyal Zaks   }
1210b0b5312eSAyal Zaks 
1211b0b5312eSAyal Zaks   LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
1212b0b5312eSAyal Zaks   return true;
1213b0b5312eSAyal Zaks }
1214b0b5312eSAyal Zaks 
1215f2ec16ccSHideki Saito } // namespace llvm
1216