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