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