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