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