LLVM  9.0.0svn
LoopVectorizationLegality.cpp
Go to the documentation of this file.
1 //===- LoopVectorizationLegality.cpp --------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides loop vectorization legality analysis. Original code
10 // resided in LoopVectorize.cpp for a long time.
11 //
12 // At this point, it is implemented as a utility class, not as an analysis
13 // pass. It should be easy to create an analysis pass around it if there
14 // is a need (but D45420 needs to happen first).
15 //
18 #include "llvm/IR/IntrinsicInst.h"
19 
20 using namespace llvm;
21 
22 #define LV_NAME "loop-vectorize"
23 #define DEBUG_TYPE LV_NAME
24 
26 
27 static cl::opt<bool>
28  EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
29  cl::desc("Enable if-conversion during vectorization."));
30 
32  "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
33  cl::desc("The maximum allowed number of runtime memory checks with a "
34  "vectorize(enable) pragma."));
35 
37  "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
38  cl::desc("The maximum number of SCEV checks allowed."));
39 
41  "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
42  cl::desc("The maximum number of SCEV checks allowed with a "
43  "vectorize(enable) pragma"));
44 
45 /// Maximum vectorization interleave count.
46 static const unsigned MaxInterleaveFactor = 16;
47 
48 namespace llvm {
49 
51  StringRef RemarkName,
52  Loop *TheLoop,
53  Instruction *I) {
54  Value *CodeRegion = TheLoop->getHeader();
55  DebugLoc DL = TheLoop->getStartLoc();
56 
57  if (I) {
58  CodeRegion = I->getParent();
59  // If there is no debug location attached to the instruction, revert back to
60  // using the loop's.
61  if (I->getDebugLoc())
62  DL = I->getDebugLoc();
63  }
64 
65  OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
66  R << "loop not vectorized: ";
67  return R;
68 }
69 
70 bool LoopVectorizeHints::Hint::validate(unsigned Val) {
71  switch (Kind) {
72  case HK_WIDTH:
73  return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
74  case HK_UNROLL:
75  return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
76  case HK_FORCE:
77  return (Val <= 1);
78  case HK_ISVECTORIZED:
79  return (Val == 0 || Val == 1);
80  }
81  return false;
82 }
83 
85  bool InterleaveOnlyWhenForced,
87  : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
88  Interleave("interleave.count", InterleaveOnlyWhenForced, HK_UNROLL),
89  Force("vectorize.enable", FK_Undefined, HK_FORCE),
90  IsVectorized("isvectorized", 0, HK_ISVECTORIZED), TheLoop(L), ORE(ORE) {
91  // Populate values with existing loop metadata.
92  getHintsFromMetadata();
93 
94  // force-vector-interleave overrides DisableInterleaving.
97 
98  if (IsVectorized.Value != 1)
99  // If the vectorization width and interleaving count are both 1 then
100  // consider the loop to have been already vectorized because there's
101  // nothing more that we can do.
102  IsVectorized.Value = Width.Value == 1 && Interleave.Value == 1;
103  LLVM_DEBUG(if (InterleaveOnlyWhenForced && Interleave.Value == 1) dbgs()
104  << "LV: Interleaving disabled by the pass manager\n");
105 }
106 
108  LLVMContext &Context = TheLoop->getHeader()->getContext();
109 
110  MDNode *IsVectorizedMD = MDNode::get(
111  Context,
112  {MDString::get(Context, "llvm.loop.isvectorized"),
113  ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))});
114  MDNode *LoopID = TheLoop->getLoopID();
115  MDNode *NewLoopID =
116  makePostTransformationMetadata(Context, LoopID,
117  {Twine(Prefix(), "vectorize.").str(),
118  Twine(Prefix(), "interleave.").str()},
119  {IsVectorizedMD});
120  TheLoop->setLoopID(NewLoopID);
121 
122  // Update internal cache.
123  IsVectorized.Value = 1;
124 }
125 
127  Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
129  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
131  return false;
132  }
133 
134  if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
135  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
137  return false;
138  }
139 
140  if (getIsVectorized() == 1) {
141  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
142  // FIXME: Add interleave.disable metadata. This will allow
143  // vectorize.disable to be used without disabling the pass and errors
144  // to differentiate between disabled vectorization and a width of 1.
145  ORE.emit([&]() {
147  "AllDisabled", L->getStartLoc(),
148  L->getHeader())
149  << "loop not vectorized: vectorization and interleaving are "
150  "explicitly disabled, or the loop has already been "
151  "vectorized";
152  });
153  return false;
154  }
155 
156  return true;
157 }
158 
160  using namespace ore;
161 
162  ORE.emit([&]() {
163  if (Force.Value == LoopVectorizeHints::FK_Disabled)
164  return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
165  TheLoop->getStartLoc(),
166  TheLoop->getHeader())
167  << "loop not vectorized: vectorization is explicitly disabled";
168  else {
169  OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
170  TheLoop->getStartLoc(), TheLoop->getHeader());
171  R << "loop not vectorized";
172  if (Force.Value == LoopVectorizeHints::FK_Enabled) {
173  R << " (Force=" << NV("Force", true);
174  if (Width.Value != 0)
175  R << ", Vector Width=" << NV("VectorWidth", Width.Value);
176  if (Interleave.Value != 0)
177  R << ", Interleave Count=" << NV("InterleaveCount", Interleave.Value);
178  R << ")";
179  }
180  return R;
181  }
182  });
183 }
184 
186  if (getWidth() == 1)
187  return LV_NAME;
189  return LV_NAME;
191  return LV_NAME;
193 }
194 
195 void LoopVectorizeHints::getHintsFromMetadata() {
196  MDNode *LoopID = TheLoop->getLoopID();
197  if (!LoopID)
198  return;
199 
200  // First operand should refer to the loop id itself.
201  assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
202  assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
203 
204  for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
205  const MDString *S = nullptr;
207 
208  // The expected hint is either a MDString or a MDNode with the first
209  // operand a MDString.
210  if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
211  if (!MD || MD->getNumOperands() == 0)
212  continue;
213  S = dyn_cast<MDString>(MD->getOperand(0));
214  for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
215  Args.push_back(MD->getOperand(i));
216  } else {
217  S = dyn_cast<MDString>(LoopID->getOperand(i));
218  assert(Args.size() == 0 && "too many arguments for MDString");
219  }
220 
221  if (!S)
222  continue;
223 
224  // Check if the hint starts with the loop metadata prefix.
225  StringRef Name = S->getString();
226  if (Args.size() == 1)
227  setHint(Name, Args[0]);
228  }
229 }
230 
231 void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
232  if (!Name.startswith(Prefix()))
233  return;
234  Name = Name.substr(Prefix().size(), StringRef::npos);
235 
236  const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
237  if (!C)
238  return;
239  unsigned Val = C->getZExtValue();
240 
241  Hint *Hints[] = {&Width, &Interleave, &Force, &IsVectorized};
242  for (auto H : Hints) {
243  if (Name == H->Name) {
244  if (H->validate(Val))
245  H->Value = Val;
246  else
247  LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
248  break;
249  }
250  }
251 }
252 
254  Function *F, Loop *L, const LoopVectorizeHints &Hints) {
255  const char *PassName = Hints.vectorizeAnalysisPassName();
256  bool Failed = false;
257  if (UnsafeAlgebraInst && !Hints.allowReordering()) {
258  ORE.emit([&]() {
260  PassName, "CantReorderFPOps", UnsafeAlgebraInst->getDebugLoc(),
261  UnsafeAlgebraInst->getParent())
262  << "loop not vectorized: cannot prove it is safe to reorder "
263  "floating-point operations";
264  });
265  Failed = true;
266  }
267 
268  // Test if runtime memcheck thresholds are exceeded.
269  bool PragmaThresholdReached =
270  NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
271  bool ThresholdReached =
272  NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
273  if ((ThresholdReached && !Hints.allowReordering()) ||
274  PragmaThresholdReached) {
275  ORE.emit([&]() {
276  return OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
277  L->getStartLoc(),
278  L->getHeader())
279  << "loop not vectorized: cannot prove it is safe to reorder "
280  "memory operations";
281  });
282  LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
283  Failed = true;
284  }
285 
286  return Failed;
287 }
288 
289 // Return true if the inner loop \p Lp is uniform with regard to the outer loop
290 // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
291 // executing the inner loop will execute the same iterations). This check is
292 // very constrained for now but it will be relaxed in the future. \p Lp is
293 // considered uniform if it meets all the following conditions:
294 // 1) it has a canonical IV (starting from 0 and with stride 1),
295 // 2) its latch terminator is a conditional branch and,
296 // 3) its latch condition is a compare instruction whose operands are the
297 // canonical IV and an OuterLp invariant.
298 // This check doesn't take into account the uniformity of other conditions not
299 // related to the loop latch because they don't affect the loop uniformity.
300 //
301 // NOTE: We decided to keep all these checks and its associated documentation
302 // together so that we can easily have a picture of the current supported loop
303 // nests. However, some of the current checks don't depend on \p OuterLp and
304 // would be redundantly executed for each \p Lp if we invoked this function for
305 // different candidate outer loops. This is not the case for now because we
306 // don't currently have the infrastructure to evaluate multiple candidate outer
307 // loops and \p OuterLp will be a fixed parameter while we only support explicit
308 // outer loop vectorization. It's also very likely that these checks go away
309 // before introducing the aforementioned infrastructure. However, if this is not
310 // the case, we should move the \p OuterLp independent checks to a separate
311 // function that is only executed once for each \p Lp.
312 static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
313  assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
314 
315  // If Lp is the outer loop, it's uniform by definition.
316  if (Lp == OuterLp)
317  return true;
318  assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
319 
320  // 1.
322  if (!IV) {
323  LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
324  return false;
325  }
326 
327  // 2.
328  BasicBlock *Latch = Lp->getLoopLatch();
329  auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
330  if (!LatchBr || LatchBr->isUnconditional()) {
331  LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
332  return false;
333  }
334 
335  // 3.
336  auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
337  if (!LatchCmp) {
338  LLVM_DEBUG(
339  dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
340  return false;
341  }
342 
343  Value *CondOp0 = LatchCmp->getOperand(0);
344  Value *CondOp1 = LatchCmp->getOperand(1);
345  Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
346  if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
347  !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
348  LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
349  return false;
350  }
351 
352  return true;
353 }
354 
355 // Return true if \p Lp and all its nested loops are uniform with regard to \p
356 // OuterLp.
357 static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
358  if (!isUniformLoop(Lp, OuterLp))
359  return false;
360 
361  // Check if nested loops are uniform.
362  for (Loop *SubLp : *Lp)
363  if (!isUniformLoopNest(SubLp, OuterLp))
364  return false;
365 
366  return true;
367 }
368 
369 /// Check whether it is safe to if-convert this phi node.
370 ///
371 /// Phi nodes with constant expressions that can trap are not safe to if
372 /// convert.
374  for (PHINode &Phi : BB->phis()) {
375  for (Value *V : Phi.incoming_values())
376  if (auto *C = dyn_cast<Constant>(V))
377  if (C->canTrap())
378  return false;
379  }
380  return true;
381 }
382 
384  if (Ty->isPointerTy())
385  return DL.getIntPtrType(Ty);
386 
387  // It is possible that char's or short's overflow when we ask for the loop's
388  // trip count, work around this by changing the type size.
389  if (Ty->getScalarSizeInBits() < 32)
390  return Type::getInt32Ty(Ty->getContext());
391 
392  return Ty;
393 }
394 
395 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
396  Ty0 = convertPointerToIntegerType(DL, Ty0);
397  Ty1 = convertPointerToIntegerType(DL, Ty1);
398  if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
399  return Ty0;
400  return Ty1;
401 }
402 
403 /// Check that the instruction has outside loop users and is not an
404 /// identified reduction variable.
405 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
406  SmallPtrSetImpl<Value *> &AllowedExit) {
407  // Reductions, Inductions and non-header phis are allowed to have exit users. All
408  // other instructions must not have external users.
409  if (!AllowedExit.count(Inst))
410  // Check that all of the users of the loop are inside the BB.
411  for (User *U : Inst->users()) {
412  Instruction *UI = cast<Instruction>(U);
413  // This user may be a reduction exit value.
414  if (!TheLoop->contains(UI)) {
415  LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
416  return true;
417  }
418  }
419  return false;
420 }
421 
423  const ValueToValueMap &Strides =
424  getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
425 
426  int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
427  if (Stride == 1 || Stride == -1)
428  return Stride;
429  return 0;
430 }
431 
433  return LAI->isUniform(V);
434 }
435 
436 bool LoopVectorizationLegality::canVectorizeOuterLoop() {
437  assert(!TheLoop->empty() && "We are not vectorizing an outer loop.");
438  // Store the result and return it at the end instead of exiting early, in case
439  // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
440  bool Result = true;
441  bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
442 
443  for (BasicBlock *BB : TheLoop->blocks()) {
444  // Check whether the BB terminator is a BranchInst. Any other terminator is
445  // not supported yet.
446  auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
447  if (!Br) {
448  LLVM_DEBUG(dbgs() << "LV: Unsupported basic block terminator.\n");
449  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
450  << "loop control flow is not understood by vectorizer");
451  if (DoExtraAnalysis)
452  Result = false;
453  else
454  return false;
455  }
456 
457  // Check whether the BranchInst is a supported one. Only unconditional
458  // branches, conditional branches with an outer loop invariant condition or
459  // backedges are supported.
460  // FIXME: We skip these checks when VPlan predication is enabled as we
461  // want to allow divergent branches. This whole check will be removed
462  // once VPlan predication is on by default.
463  if (!EnableVPlanPredication && Br && Br->isConditional() &&
464  !TheLoop->isLoopInvariant(Br->getCondition()) &&
465  !LI->isLoopHeader(Br->getSuccessor(0)) &&
466  !LI->isLoopHeader(Br->getSuccessor(1))) {
467  LLVM_DEBUG(dbgs() << "LV: Unsupported conditional branch.\n");
468  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
469  << "loop control flow is not understood by vectorizer");
470  if (DoExtraAnalysis)
471  Result = false;
472  else
473  return false;
474  }
475  }
476 
477  // Check whether inner loops are uniform. At this point, we only support
478  // simple outer loops scenarios with uniform nested loops.
479  if (!isUniformLoopNest(TheLoop /*loop nest*/,
480  TheLoop /*context outer loop*/)) {
481  LLVM_DEBUG(
482  dbgs()
483  << "LV: Not vectorizing: Outer loop contains divergent loops.\n");
484  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
485  << "loop control flow is not understood by vectorizer");
486  if (DoExtraAnalysis)
487  Result = false;
488  else
489  return false;
490  }
491 
492  // Check whether we are able to set up outer loop induction.
493  if (!setupOuterLoopInductions()) {
494  LLVM_DEBUG(
495  dbgs() << "LV: Not vectorizing: Unsupported outer loop Phi(s).\n");
496  ORE->emit(createMissedAnalysis("UnsupportedPhi")
497  << "Unsupported outer loop Phi(s)");
498  if (DoExtraAnalysis)
499  Result = false;
500  else
501  return false;
502  }
503 
504  return Result;
505 }
506 
507 void LoopVectorizationLegality::addInductionPhi(
508  PHINode *Phi, const InductionDescriptor &ID,
509  SmallPtrSetImpl<Value *> &AllowedExit) {
510  Inductions[Phi] = ID;
511 
512  // In case this induction also comes with casts that we know we can ignore
513  // in the vectorized loop body, record them here. All casts could be recorded
514  // here for ignoring, but suffices to record only the first (as it is the
515  // only one that may bw used outside the cast sequence).
516  const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
517  if (!Casts.empty())
518  InductionCastsToIgnore.insert(*Casts.begin());
519 
520  Type *PhiTy = Phi->getType();
521  const DataLayout &DL = Phi->getModule()->getDataLayout();
522 
523  // Get the widest type.
524  if (!PhiTy->isFloatingPointTy()) {
525  if (!WidestIndTy)
526  WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
527  else
528  WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
529  }
530 
531  // Int inductions are special because we only allow one IV.
534  isa<Constant>(ID.getStartValue()) &&
535  cast<Constant>(ID.getStartValue())->isNullValue()) {
536 
537  // Use the phi node with the widest type as induction. Use the last
538  // one if there are multiple (no good reason for doing this other
539  // than it is expedient). We've checked that it begins at zero and
540  // steps by one, so this is a canonical induction variable.
541  if (!PrimaryInduction || PhiTy == WidestIndTy)
542  PrimaryInduction = Phi;
543  }
544 
545  // Both the PHI node itself, and the "post-increment" value feeding
546  // back into the PHI node may have external users.
547  // We can allow those uses, except if the SCEVs we have for them rely
548  // on predicates that only hold within the loop, since allowing the exit
549  // currently means re-using this SCEV outside the loop (see PR33706 for more
550  // details).
551  if (PSE.getUnionPredicate().isAlwaysTrue()) {
552  AllowedExit.insert(Phi);
553  AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
554  }
555 
556  LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
557 }
558 
559 bool LoopVectorizationLegality::setupOuterLoopInductions() {
560  BasicBlock *Header = TheLoop->getHeader();
561 
562  // Returns true if a given Phi is a supported induction.
563  auto isSupportedPhi = [&](PHINode &Phi) -> bool {
565  if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
567  addInductionPhi(&Phi, ID, AllowedExit);
568  return true;
569  } else {
570  // Bail out for any Phi in the outer loop header that is not a supported
571  // induction.
572  LLVM_DEBUG(
573  dbgs()
574  << "LV: Found unsupported PHI for outer loop vectorization.\n");
575  return false;
576  }
577  };
578 
579  if (llvm::all_of(Header->phis(), isSupportedPhi))
580  return true;
581  else
582  return false;
583 }
584 
585 bool LoopVectorizationLegality::canVectorizeInstrs() {
586  BasicBlock *Header = TheLoop->getHeader();
587 
588  // Look for the attribute signaling the absence of NaNs.
589  Function &F = *Header->getParent();
590  HasFunNoNaNAttr =
591  F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
592 
593  // For each block in the loop.
594  for (BasicBlock *BB : TheLoop->blocks()) {
595  // Scan the instructions in the block and look for hazards.
596  for (Instruction &I : *BB) {
597  if (auto *Phi = dyn_cast<PHINode>(&I)) {
598  Type *PhiTy = Phi->getType();
599  // Check that this PHI type is allowed.
600  if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
601  !PhiTy->isPointerTy()) {
602  ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
603  << "loop control flow is not understood by vectorizer");
604  LLVM_DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
605  return false;
606  }
607 
608  // If this PHINode is not in the header block, then we know that we
609  // can convert it to select during if-conversion. No need to check if
610  // the PHIs in this block are induction or reduction variables.
611  if (BB != Header) {
612  // Non-header phi nodes that have outside uses can be vectorized. Add
613  // them to the list of allowed exits.
614  // Unsafe cyclic dependencies with header phis are identified during
615  // legalization for reduction, induction and first order
616  // recurrences.
617  continue;
618  }
619 
620  // We only allow if-converted PHIs with exactly two incoming values.
621  if (Phi->getNumIncomingValues() != 2) {
622  ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
623  << "control flow not understood by vectorizer");
624  LLVM_DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
625  return false;
626  }
627 
628  RecurrenceDescriptor RedDes;
629  if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
630  DT)) {
631  if (RedDes.hasUnsafeAlgebra())
632  Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
633  AllowedExit.insert(RedDes.getLoopExitInstr());
634  Reductions[Phi] = RedDes;
635  continue;
636  }
637 
638  // TODO: Instead of recording the AllowedExit, it would be good to record the
639  // complementary set: NotAllowedExit. These include (but may not be
640  // limited to):
641  // 1. Reduction phis as they represent the one-before-last value, which
642  // is not available when vectorized
643  // 2. Induction phis and increment when SCEV predicates cannot be used
644  // outside the loop - see addInductionPhi
645  // 3. Non-Phis with outside uses when SCEV predicates cannot be used
646  // outside the loop - see call to hasOutsideLoopUser in the non-phi
647  // handling below
648  // 4. FirstOrderRecurrence phis that can possibly be handled by
649  // extraction.
650  // By recording these, we can then reason about ways to vectorize each
651  // of these NotAllowedExit.
653  if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
654  addInductionPhi(Phi, ID, AllowedExit);
655  if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
656  Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
657  continue;
658  }
659 
661  SinkAfter, DT)) {
662  FirstOrderRecurrences.insert(Phi);
663  continue;
664  }
665 
666  // As a last resort, coerce the PHI to a AddRec expression
667  // and re-try classifying it a an induction PHI.
668  if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
669  addInductionPhi(Phi, ID, AllowedExit);
670  continue;
671  }
672 
673  ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
674  << "value that could not be identified as "
675  "reduction is used outside the loop");
676  LLVM_DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
677  return false;
678  } // end of PHI handling
679 
680  // We handle calls that:
681  // * Are debug info intrinsics.
682  // * Have a mapping to an IR intrinsic.
683  // * Have a vector version available.
684  auto *CI = dyn_cast<CallInst>(&I);
685  if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
686  !isa<DbgInfoIntrinsic>(CI) &&
687  !(CI->getCalledFunction() && TLI &&
688  TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
689  // If the call is a recognized math libary call, it is likely that
690  // we can vectorize it given loosened floating-point constraints.
691  LibFunc Func;
692  bool IsMathLibCall =
693  TLI && CI->getCalledFunction() &&
694  CI->getType()->isFloatingPointTy() &&
695  TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
696  TLI->hasOptimizedCodeGen(Func);
697 
698  if (IsMathLibCall) {
699  // TODO: Ideally, we should not use clang-specific language here,
700  // but it's hard to provide meaningful yet generic advice.
701  // Also, should this be guarded by allowExtraAnalysis() and/or be part
702  // of the returned info from isFunctionVectorizable()?
703  ORE->emit(createMissedAnalysis("CantVectorizeLibcall", CI)
704  << "library call cannot be vectorized. "
705  "Try compiling with -fno-math-errno, -ffast-math, "
706  "or similar flags");
707  } else {
708  ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
709  << "call instruction cannot be vectorized");
710  }
711  LLVM_DEBUG(
712  dbgs() << "LV: Found a non-intrinsic callsite.\n");
713  return false;
714  }
715 
716  // Some intrinsics have scalar arguments and should be same in order for
717  // them to be vectorized (i.e. loop invariant).
718  if (CI) {
719  auto *SE = PSE.getSE();
720  Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
721  for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
722  if (hasVectorInstrinsicScalarOpd(IntrinID, i)) {
723  if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(i)), TheLoop)) {
724  ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
725  << "intrinsic instruction cannot be vectorized");
726  LLVM_DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI
727  << "\n");
728  return false;
729  }
730  }
731  }
732 
733  // Check that the instruction return type is vectorizable.
734  // Also, we can't vectorize extractelement instructions.
735  if ((!VectorType::isValidElementType(I.getType()) &&
736  !I.getType()->isVoidTy()) ||
737  isa<ExtractElementInst>(I)) {
738  ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
739  << "instruction return type cannot be vectorized");
740  LLVM_DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
741  return false;
742  }
743 
744  // Check that the stored type is vectorizable.
745  if (auto *ST = dyn_cast<StoreInst>(&I)) {
746  Type *T = ST->getValueOperand()->getType();
748  ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
749  << "store instruction cannot be vectorized");
750  return false;
751  }
752 
753  // FP instructions can allow unsafe algebra, thus vectorizable by
754  // non-IEEE-754 compliant SIMD units.
755  // This applies to floating-point math operations and calls, not memory
756  // operations, shuffles, or casts, as they don't change precision or
757  // semantics.
758  } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
759  !I.isFast()) {
760  LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
761  Hints->setPotentiallyUnsafe();
762  }
763 
764  // Reduction instructions are allowed to have exit users.
765  // All other instructions must not have external users.
766  if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
767  // We can safely vectorize loops where instructions within the loop are
768  // used outside the loop only if the SCEV predicates within the loop is
769  // same as outside the loop. Allowing the exit means reusing the SCEV
770  // outside the loop.
771  if (PSE.getUnionPredicate().isAlwaysTrue()) {
772  AllowedExit.insert(&I);
773  continue;
774  }
775  ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
776  << "value cannot be used outside the loop");
777  return false;
778  }
779  } // next instr.
780  }
781 
782  if (!PrimaryInduction) {
783  LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
784  if (Inductions.empty()) {
785  ORE->emit(createMissedAnalysis("NoInductionVariable")
786  << "loop induction variable could not be identified");
787  return false;
788  } else if (!WidestIndTy) {
789  ORE->emit(createMissedAnalysis("NoIntegerInductionVariable")
790  << "integer loop induction variable could not be identified");
791  return false;
792  }
793  }
794 
795  // Now we know the widest induction type, check if our found induction
796  // is the same size. If it's not, unset it here and InnerLoopVectorizer
797  // will create another.
798  if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
799  PrimaryInduction = nullptr;
800 
801  return true;
802 }
803 
804 bool LoopVectorizationLegality::canVectorizeMemory() {
805  LAI = &(*GetLAA)(*TheLoop);
806  const OptimizationRemarkAnalysis *LAR = LAI->getReport();
807  if (LAR) {
808  ORE->emit([&]() {
809  return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
810  "loop not vectorized: ", *LAR);
811  });
812  }
813  if (!LAI->canVectorizeMemory())
814  return false;
815 
816  if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
817  ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
818  << "write to a loop invariant address could not "
819  "be vectorized");
820  LLVM_DEBUG(
821  dbgs() << "LV: Non vectorizable stores to a uniform address\n");
822  return false;
823  }
824  Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
825  PSE.addPredicate(LAI->getPSE().getUnionPredicate());
826 
827  return true;
828 }
829 
831  Value *In0 = const_cast<Value *>(V);
832  PHINode *PN = dyn_cast_or_null<PHINode>(In0);
833  if (!PN)
834  return false;
835 
836  return Inductions.count(PN);
837 }
838 
840  auto *Inst = dyn_cast<Instruction>(V);
841  return (Inst && InductionCastsToIgnore.count(Inst));
842 }
843 
845  return isInductionPhi(V) || isCastedInductionVariable(V);
846 }
847 
849  return FirstOrderRecurrences.count(Phi);
850 }
851 
853  return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
854 }
855 
856 bool LoopVectorizationLegality::blockCanBePredicated(
857  BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
858  const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
859 
860  for (Instruction &I : *BB) {
861  // Check that we don't have a constant expression that can trap as operand.
862  for (Value *Operand : I.operands()) {
863  if (auto *C = dyn_cast<Constant>(Operand))
864  if (C->canTrap())
865  return false;
866  }
867  // We might be able to hoist the load.
868  if (I.mayReadFromMemory()) {
869  auto *LI = dyn_cast<LoadInst>(&I);
870  if (!LI)
871  return false;
872  if (!SafePtrs.count(LI->getPointerOperand())) {
873  // !llvm.mem.parallel_loop_access implies if-conversion safety.
874  // Otherwise, record that the load needs (real or emulated) masking
875  // and let the cost model decide.
876  if (!IsAnnotatedParallel)
877  MaskedOp.insert(LI);
878  continue;
879  }
880  }
881 
882  if (I.mayWriteToMemory()) {
883  auto *SI = dyn_cast<StoreInst>(&I);
884  if (!SI)
885  return false;
886  // Predicated store requires some form of masking:
887  // 1) masked store HW instruction,
888  // 2) emulation via load-blend-store (only if safe and legal to do so,
889  // be aware on the race conditions), or
890  // 3) element-by-element predicate check and scalar store.
891  MaskedOp.insert(SI);
892  continue;
893  }
894  if (I.mayThrow())
895  return false;
896  }
897 
898  return true;
899 }
900 
901 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
902  if (!EnableIfConversion) {
903  ORE->emit(createMissedAnalysis("IfConversionDisabled")
904  << "if-conversion is disabled");
905  return false;
906  }
907 
908  assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
909 
910  // A list of pointers that we can safely read and write to.
911  SmallPtrSet<Value *, 8> SafePointes;
912 
913  // Collect safe addresses.
914  for (BasicBlock *BB : TheLoop->blocks()) {
915  if (blockNeedsPredication(BB))
916  continue;
917 
918  for (Instruction &I : *BB)
919  if (auto *Ptr = getLoadStorePointerOperand(&I))
920  SafePointes.insert(Ptr);
921  }
922 
923  // Collect the blocks that need predication.
924  BasicBlock *Header = TheLoop->getHeader();
925  for (BasicBlock *BB : TheLoop->blocks()) {
926  // We don't support switch statements inside loops.
927  if (!isa<BranchInst>(BB->getTerminator())) {
928  ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
929  << "loop contains a switch statement");
930  return false;
931  }
932 
933  // We must be able to predicate all blocks that need to be predicated.
934  if (blockNeedsPredication(BB)) {
935  if (!blockCanBePredicated(BB, SafePointes)) {
936  ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
937  << "control flow cannot be substituted for a select");
938  return false;
939  }
940  } else if (BB != Header && !canIfConvertPHINodes(BB)) {
941  ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
942  << "control flow cannot be substituted for a select");
943  return false;
944  }
945  }
946 
947  // We can if-convert this loop.
948  return true;
949 }
950 
951 // Helper function to canVectorizeLoopNestCFG.
952 bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
953  bool UseVPlanNativePath) {
954  assert((UseVPlanNativePath || Lp->empty()) &&
955  "VPlan-native path is not enabled.");
956 
957  // TODO: ORE should be improved to show more accurate information when an
958  // outer loop can't be vectorized because a nested loop is not understood or
959  // legal. Something like: "outer_loop_location: loop not vectorized:
960  // (inner_loop_location) loop control flow is not understood by vectorizer".
961 
962  // Store the result and return it at the end instead of exiting early, in case
963  // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
964  bool Result = true;
965  bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
966 
967  // We must have a loop in canonical form. Loops with indirectbr in them cannot
968  // be canonicalized.
969  if (!Lp->getLoopPreheader()) {
970  LLVM_DEBUG(dbgs() << "LV: Loop doesn't have a legal pre-header.\n");
971  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
972  << "loop control flow is not understood by vectorizer");
973  if (DoExtraAnalysis)
974  Result = false;
975  else
976  return false;
977  }
978 
979  // We must have a single backedge.
980  if (Lp->getNumBackEdges() != 1) {
981  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
982  << "loop control flow is not understood by vectorizer");
983  if (DoExtraAnalysis)
984  Result = false;
985  else
986  return false;
987  }
988 
989  // We must have a single exiting block.
990  if (!Lp->getExitingBlock()) {
991  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
992  << "loop control flow is not understood by vectorizer");
993  if (DoExtraAnalysis)
994  Result = false;
995  else
996  return false;
997  }
998 
999  // We only handle bottom-tested loops, i.e. loop in which the condition is
1000  // checked at the end of each iteration. With that we can assume that all
1001  // instructions in the loop are executed the same number of times.
1002  if (Lp->getExitingBlock() != Lp->getLoopLatch()) {
1003  ORE->emit(createMissedAnalysis("CFGNotUnderstood")
1004  << "loop control flow is not understood by vectorizer");
1005  if (DoExtraAnalysis)
1006  Result = false;
1007  else
1008  return false;
1009  }
1010 
1011  return Result;
1012 }
1013 
1014 bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1015  Loop *Lp, bool UseVPlanNativePath) {
1016  // Store the result and return it at the end instead of exiting early, in case
1017  // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1018  bool Result = true;
1019  bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1020  if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1021  if (DoExtraAnalysis)
1022  Result = false;
1023  else
1024  return false;
1025  }
1026 
1027  // Recursively check whether the loop control flow of nested loops is
1028  // understood.
1029  for (Loop *SubLp : *Lp)
1030  if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1031  if (DoExtraAnalysis)
1032  Result = false;
1033  else
1034  return false;
1035  }
1036 
1037  return Result;
1038 }
1039 
1040 bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1041  // Store the result and return it at the end instead of exiting early, in case
1042  // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1043  bool Result = true;
1044 
1045  bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1046  // Check whether the loop-related control flow in the loop nest is expected by
1047  // vectorizer.
1048  if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1049  if (DoExtraAnalysis)
1050  Result = false;
1051  else
1052  return false;
1053  }
1054 
1055  // We need to have a loop header.
1056  LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1057  << '\n');
1058 
1059  // Specific checks for outer loops. We skip the remaining legal checks at this
1060  // point because they don't support outer loops.
1061  if (!TheLoop->empty()) {
1062  assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1063 
1064  if (!canVectorizeOuterLoop()) {
1065  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Unsupported outer loop.\n");
1066  // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1067  // outer loops.
1068  return false;
1069  }
1070 
1071  LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1072  return Result;
1073  }
1074 
1075  assert(TheLoop->empty() && "Inner loop expected.");
1076  // Check if we can if-convert non-single-bb loops.
1077  unsigned NumBlocks = TheLoop->getNumBlocks();
1078  if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1079  LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1080  if (DoExtraAnalysis)
1081  Result = false;
1082  else
1083  return false;
1084  }
1085 
1086  // Check if we can vectorize the instructions and CFG in this loop.
1087  if (!canVectorizeInstrs()) {
1088  LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1089  if (DoExtraAnalysis)
1090  Result = false;
1091  else
1092  return false;
1093  }
1094 
1095  // Go over each instruction and look at memory deps.
1096  if (!canVectorizeMemory()) {
1097  LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1098  if (DoExtraAnalysis)
1099  Result = false;
1100  else
1101  return false;
1102  }
1103 
1104  LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
1105  << (LAI->getRuntimePointerChecking()->Need
1106  ? " (with a runtime bound check)"
1107  : "")
1108  << "!\n");
1109 
1110  unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
1111  if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
1112  SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
1113 
1114  if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
1115  ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
1116  << "Too many SCEV assumptions need to be made and checked "
1117  << "at runtime");
1118  LLVM_DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
1119  if (DoExtraAnalysis)
1120  Result = false;
1121  else
1122  return false;
1123  }
1124 
1125  // Okay! We've done all the tests. If any have failed, return false. Otherwise
1126  // we can vectorize, and at this point we don't have any other mem analysis
1127  // which may limit our maximum vectorization factor, so just return true with
1128  // no restrictions.
1129  return Result;
1130 }
1131 
1133 
1134  LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
1135 
1136  if (!PrimaryInduction) {
1137  ORE->emit(createMissedAnalysis("NoPrimaryInduction")
1138  << "Missing a primary induction variable in the loop, which is "
1139  << "needed in order to fold tail by masking as required.");
1140  LLVM_DEBUG(dbgs() << "LV: No primary induction, cannot fold tail by "
1141  << "masking.\n");
1142  return false;
1143  }
1144 
1145  // TODO: handle reductions when tail is folded by masking.
1146  if (!Reductions.empty()) {
1147  ORE->emit(createMissedAnalysis("ReductionFoldingTailByMasking")
1148  << "Cannot fold tail by masking in the presence of reductions.");
1149  LLVM_DEBUG(dbgs() << "LV: Loop has reductions, cannot fold tail by "
1150  << "masking.\n");
1151  return false;
1152  }
1153 
1154  // TODO: handle outside users when tail is folded by masking.
1155  for (auto *AE : AllowedExit) {
1156  // Check that all users of allowed exit values are inside the loop.
1157  for (User *U : AE->users()) {
1158  Instruction *UI = cast<Instruction>(U);
1159  if (TheLoop->contains(UI))
1160  continue;
1161  ORE->emit(createMissedAnalysis("LiveOutFoldingTailByMasking")
1162  << "Cannot fold tail by masking in the presence of live outs.");
1163  LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking, loop has an "
1164  << "outside user for : " << *UI << '\n');
1165  return false;
1166  }
1167  }
1168 
1169  // The list of pointers that we can safely read and write to remains empty.
1170  SmallPtrSet<Value *, 8> SafePointers;
1171 
1172  // Check and mark all blocks for predication, including those that ordinarily
1173  // do not need predication such as the header block.
1174  for (BasicBlock *BB : TheLoop->blocks()) {
1175  if (!blockCanBePredicated(BB, SafePointers)) {
1176  ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
1177  << "control flow cannot be substituted for a select");
1178  LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as required.\n");
1179  return false;
1180  }
1181  }
1182 
1183  LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
1184  return true;
1185 }
1186 
1187 } // namespace llvm
static bool isUniformLoop(Loop *Lp, Loop *OuterLp)
static unsigned RuntimeMemoryCheckThreshold
performing memory disambiguation checks at runtime do not make more than this number of comparisons...
uint64_t CallInst * C
#define LV_NAME
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:636
Diagnostic information for missed-optimization remarks.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:224
LLVMContext & Context
static Type * getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1)
DiagnosticInfoOptimizationBase::Argument NV
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Instruction * getUnsafeAlgebraInst()
Returns first unsafe algebra instruction in the PHI node&#39;s use-chain.
bool isCastedInductionVariable(const Value *V)
Returns True if V is a cast that is part of an induction def-use chain, and had been proven to be red...
static bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction *> *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:453
ConstantInt * getConstIntStepValue() const
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:256
llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode *> AddAttrs)
Create a new LoopID after the loop has been transformed.
Definition: LoopInfo.cpp:741
bool isUniform(Value *V)
Returns true if the value V is uniform within the loop.
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class...
This class represents a function call, abstracting a target machine&#39;s calling convention.
int64_t getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr, const Loop *Lp, const ValueToValueMap &StridesMap=ValueToValueMap(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of its element size.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:173
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1185
InductionKind getKind() const
A debug info location.
Definition: DebugLoc.h:33
Metadata node.
Definition: Metadata.h:863
F(f)
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1068
An instruction for reading from memory.
Definition: Instructions.h:167
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:137
cl::opt< bool > EnableVPlanPredication
Value * getStartValue() const
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:32
#define DEBUG_TYPE
const char * vectorizeAnalysisPassName() const
If hints are provided that force vectorization, use the AlwaysPrint pass name to force the frontend t...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
bool hasUnsafeAlgebra()
Returns true if the recurrence has unsafe algebra which requires a relaxed floating-point model...
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
Definition: LoopInfo.h:226
This file defines the LoopVectorizationLegality class.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
static const unsigned MaxVectorWidth
Maximum SIMD width.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Definition: Type.h:161
static cl::opt< bool > EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, cl::desc("Enable if-conversion during vectorization."))
Diagnostic information for optimization analysis remarks.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:578
BlockT * getHeader() const
Definition: LoopInfo.h:99
int isConsecutivePtr(Value *Ptr)
Check if this pointer is consecutive when vectorizing.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition: Constants.h:200
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
bool isInductionVariable(const Value *V)
Returns True if V can be considered as an induction variable in this loop.
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition: LoopInfo.cpp:238
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:620
Value * getLoadStorePointerOperand(Value *V)
A helper function that returns the pointer operand of a load or store instruction.
An instruction for storing to memory.
Definition: Instructions.h:320
static cl::opt< unsigned > PragmaVectorizeMemoryCheckThreshold("pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum allowed number of runtime memory checks with a " "vectorize(enable) pragma."))
bool blockNeedsPredication(BasicBlock *BB)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
Diagnostic information for optimization analysis remarks related to pointer aliasing.
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:409
StringRef getString() const
Definition: Metadata.cpp:463
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:769
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1165
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
Integer induction variable. Step = C.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:148
static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, SmallPtrSetImpl< Value *> &AllowedExit)
Check that the instruction has outside loop users and is not an identified reduction variable...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:428
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
Conditional or Unconditional Branch instruction.
Instruction * getUnsafeAlgebraInst()
Returns induction operator that does not have "fast-math" property and requires FP unsafe mode...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:223
#define H(x, y, z)
Definition: MD5.cpp:57
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
OptimizationRemarkAnalysis createLVMissedAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop, Instruction *I=nullptr)
Create an analysis remark that explains why vectorization failed.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
static bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Returns true if Phi is a reduction in TheLoop.
static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp)
bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints)
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition: LoopInfo.cpp:342
size_t size() const
Definition: SmallVector.h:52
static bool isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop, DenseMap< Instruction *, Instruction *> &SinkAfter, DominatorTree *DT)
Returns true if Phi is a first-order recurrence.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition: LoopInfo.cpp:57
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Definition: IVDescriptors.h:62
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:109
Diagnostic information for optimization analysis remarks related to floating-point non-commutativity...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1166
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file. ...
A struct for saving information about induction variables.
bool canFoldTailByMasking()
Return true if we can vectorize this loop while folding its tail by masking.
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition: Error.h:147
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:129
DenseMap< const Value *, Value * > ValueToValueMap
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
bool isFirstOrderRecurrence(const PHINode *Phi)
Returns True if Phi is a first-order recurrence in this loop.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:631
static const unsigned MaxInterleaveFactor
Maximum vectorization interleave count.
bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the intrinsic has a scalar operand.
Definition: VectorUtils.cpp:90
unsigned getNumIncomingValues() const
Return the number of incoming edges.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
Definition: LoopInfo.cpp:112
static bool canIfConvertPHINodes(BasicBlock *BB)
Check whether it is safe to if-convert this phi node.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
bool isInductionPhi(const Value *V)
Returns True if V is a Phi node of an induction variable in this loop.
Class for arbitrary precision integers.
Definition: APInt.h:69
iterator_range< user_iterator > users()
Definition: Value.h:399
bool hasUnsafeAlgebra()
Returns true if the induction type is FP and the binary operator does not have the "fast-math" proper...
const SmallVectorImpl< Instruction * > & getCastInsts() const
Returns a reference to the type cast instructions in the induction update chain, that are redundant w...
LoopVectorizeHints(const Loop *L, bool InterleaveOnlyWhenForced, OptimizationRemarkEmitter &ORE)
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition: LoopInfo.cpp:214
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:324
static const size_t npos
Definition: StringRef.h:50
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:175
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
Instruction * getLoopExitInstr()
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:194
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:464
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:322
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:324
Collection of parameters shared beetween the Loop Vectorizer and the Loop Access Analysis.
bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
bool empty() const
Definition: LoopInfo.h:145
void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:72
static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, DominatorTree *DT)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:330
static unsigned VectorizationInterleave
Interleave factor as overridden by the user.
static Type * convertPointerToIntegerType(const DataLayout &DL, Type *Ty)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
static cl::opt< unsigned > VectorizeSCEVCheckThreshold("vectorize-scev-check-threshold", cl::init(16), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed."))
A single uniqued string.
Definition: Metadata.h:603
static cl::opt< unsigned > PragmaVectorizeSCEVCheckThreshold("pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum number of SCEV checks allowed with a " "vectorize(enable) pragma"))
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
static bool isInterleaveForced()
True if force-vector-interleave was specified by the user.
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1074
#define LLVM_DEBUG(X)
Definition: Debug.h:122
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:49
Root of the metadata hierarchy.
Definition: Metadata.h:57
The optimization diagnostic interface.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
void emitRemarkWithHints() const
Dumps all the hint information.
void validate(const Triple &TT, const FeatureBitset &FeatureBits)
const BasicBlock * getParent() const
Definition: Instruction.h:66