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