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