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