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