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