Index: llvm/include/llvm/Transforms/Vectorize/LoopVectorizationLegality.h =================================================================== --- llvm/include/llvm/Transforms/Vectorize/LoopVectorizationLegality.h +++ llvm/include/llvm/Transforms/Vectorize/LoopVectorizationLegality.h @@ -229,6 +229,7 @@ /// Return true if we can vectorize this loop while folding its tail by /// masking, and mark all respective loads/stores for masking. + /// This object's state is only modified iff this function returns true. bool prepareToFoldTailByMasking(); /// Returns the primary induction variable. @@ -369,8 +370,14 @@ /// its original trip-count, under a proper guard, which should be preserved. /// \p SafePtrs is a list of addresses that are known to be legal and we know /// that we can read from them without segfault. + /// \p MaskedOp is a list of instructions that have to be transformed into + /// calls to the appropriate masked intrinsic when the loop is vectorized. + /// \p ConditionalAssumes is a list of assume instructions in predicated + /// blocks that must be dropped if the CFG gets flattened. bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl &SafePtrs, - bool PreserveGuards = false); + SmallPtrSetImpl &MaskedOp, + SmallPtrSetImpl &ConditionalAssumes, + bool PreserveGuards = false) const; /// Updates the vectorization state by adding \p Phi to the inductions list. /// This can set \p Phi as the main induction of the loop if \p Phi is a Index: llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp =================================================================== --- llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp +++ llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp @@ -912,7 +912,10 @@ } bool LoopVectorizationLegality::blockCanBePredicated( - BasicBlock *BB, SmallPtrSetImpl &SafePtrs, bool PreserveGuards) { + BasicBlock *BB, SmallPtrSetImpl &SafePtrs, + SmallPtrSetImpl &MaskedOp, + SmallPtrSetImpl &ConditionalAssumes, + bool PreserveGuards) const { const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); for (Instruction &I : *BB) { @@ -1019,7 +1022,8 @@ // We must be able to predicate all blocks that need to be predicated. if (blockNeedsPredication(BB)) { - if (!blockCanBePredicated(BB, SafePointers)) { + if (!blockCanBePredicated(BB, SafePointers, MaskedOp, + ConditionalAssumes)) { reportVectorizationFailure( "Control flow cannot be substituted for a select", "control flow cannot be substituted for a select", @@ -1246,10 +1250,10 @@ Instruction *UI = cast(U); if (TheLoop->contains(UI)) continue; - reportVectorizationFailure( - "Cannot fold tail by masking, loop has an outside user for", - "Cannot fold tail by masking in the presence of live outs.", - "LiveOutFoldingTailByMasking", ORE, TheLoop, UI); + LLVM_DEBUG( + dbgs() + << "LV: Cannot fold tail by masking, loop has an outside user for " + << *UI << "\n"); return false; } } @@ -1257,20 +1261,26 @@ // The list of pointers that we can safely read and write to remains empty. SmallPtrSet SafePointers; + SmallPtrSet TmpMaskedOp; + SmallPtrSet TmpConditionalAssumes; + // Check and mark all blocks for predication, including those that ordinarily // do not need predication such as the header block. for (BasicBlock *BB : TheLoop->blocks()) { - if (!blockCanBePredicated(BB, SafePointers, /* MaskAllLoads= */ true)) { - reportVectorizationFailure( - "Cannot fold tail by masking as required", - "control flow cannot be substituted for a select", - "NoCFGForSelect", ORE, TheLoop, - BB->getTerminator()); + if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp, + TmpConditionalAssumes, + /* MaskAllLoads= */ true)) { + LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as requested.\n"); return false; } } LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n"); + + MaskedOp.insert(TmpMaskedOp.begin(), TmpMaskedOp.end()); + ConditionalAssumes.insert(TmpConditionalAssumes.begin(), + TmpConditionalAssumes.end()); + return true; } Index: llvm/lib/Transforms/Vectorize/LoopVectorize.cpp =================================================================== --- llvm/lib/Transforms/Vectorize/LoopVectorize.cpp +++ llvm/lib/Transforms/Vectorize/LoopVectorize.cpp @@ -180,11 +180,33 @@ // Indicates that an epilogue is undesired, predication is preferred. // This means that the vectorizer will try to fold the loop-tail (epilogue) -// into the loop and predicate the loop body accordingly. -static cl::opt PreferPredicateOverEpilog( - "prefer-predicate-over-epilog", cl::init(false), cl::Hidden, - cl::desc("Indicate that an epilogue is undesired, predication should be " - "used instead.")); +// into the loop and predicate the loop body accordingly. If that fails, +// there different fallback strategies depending on the option. +namespace PreferPredicateTy { + enum Option { + ScalarEpilogue, + PredicateAndVectorize, + PredicateOrDontVectorize + }; +} + +static cl::opt PreferPredicateOverEpilog( + "prefer-predicate-over-epilog", + cl::init(PreferPredicateTy::ScalarEpilogue), + cl::Hidden, + cl::desc("Set tail-folding and predication over creating a scalar " + "epilogue loop preferences."), + cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue, + "scalar-epilogue", + "Don't tail-predicate loops, create scalar epilogue"), + clEnumValN(PreferPredicateTy::PredicateAndVectorize, + "predicate-vectorize", + "prefer tail-folding, attempt vectorization if " + "tail-folding fails."), + clEnumValN(PreferPredicateTy::PredicateOrDontVectorize, + "predicate-dont-vectorize", + "prefers tail-folding, don't attempt vectorization if " + "tail-folding fails."))); static cl::opt MaximizeBandwidth( "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden, @@ -196,7 +218,7 @@ cl::desc("Enable vectorization on interleaved memory accesses in a loop")); /// An interleave-group may need masking if it resides in a block that needs -/// predication, or in order to mask away gaps. +/// predication, or in order to mask away gaps. static cl::opt EnableMaskedInterleavedMemAccesses( "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on masked interleaved memory accesses in a loop")); @@ -5038,6 +5060,19 @@ return MaxVF; } + // If there was a tail-folding hint/switch, but we can't fold the tail by + // masking, fallback to a vectorization with a scalar epilogue. + if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) { + if (PreferPredicateOverEpilog == PreferPredicateTy::PredicateOrDontVectorize) { + LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n"); + return None; + } + LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a " + "scalar epilogue instead.\n"); + ScalarEpilogueStatus = CM_ScalarEpilogueAllowed; + return MaxVF; + } + if (TC == 0) { reportVectorizationFailure( "Unable to calculate the loop count due to complex control flow", @@ -7635,7 +7670,7 @@ // 3) and 4) look if enabling predication is requested on the command line, // with a loop hint, or if the TTI hook indicates this is profitable, request - // predication . + // predication. if (PreferPredicateOverEpilog || Hints.getPredicate() == LoopVectorizeHints::FK_Enabled || (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT, Index: llvm/test/Transforms/LoopVectorize/ARM/prefer-tail-loop-folding.ll =================================================================== --- llvm/test/Transforms/LoopVectorize/ARM/prefer-tail-loop-folding.ll +++ llvm/test/Transforms/LoopVectorize/ARM/prefer-tail-loop-folding.ll @@ -31,13 +31,13 @@ ; RUN: FileCheck %s -check-prefixes=CHECK,PREFER-FOLDING ; RUN: opt -mtriple=thumbv8.1m.main-arm-eabihf -mattr=+mve.fp \ -; RUN: -prefer-predicate-over-epilog=false \ +; RUN: -prefer-predicate-over-epilog=scalar-epilogue \ ; RUN: -tail-predication=enabled -loop-vectorize \ ; RUN: -enable-arm-maskedldst=true -S < %s | \ ; RUN: FileCheck %s -check-prefixes=CHECK,NO-FOLDING ; RUN: opt -mtriple=thumbv8.1m.main-arm-eabihf -mattr=+mve.fp \ -; RUN: -prefer-predicate-over-epilog=true \ +; RUN: -prefer-predicate-over-epilog=predicate-dont-vectorize \ ; RUN: -tail-predication=enabled -loop-vectorize \ ; RUN: -enable-arm-maskedldst=true -S < %s | \ ; RUN: FileCheck %s -check-prefixes=CHECK,FOLDING-OPT Index: llvm/test/Transforms/LoopVectorize/ARM/tail-folding-counting-down.ll =================================================================== --- llvm/test/Transforms/LoopVectorize/ARM/tail-folding-counting-down.ll +++ llvm/test/Transforms/LoopVectorize/ARM/tail-folding-counting-down.ll @@ -1,5 +1,5 @@ ; RUN: opt < %s -loop-vectorize -S | FileCheck %s --check-prefixes=COMMON,DEFAULT -; RUN: opt < %s -loop-vectorize -tail-predication=enabled -prefer-predicate-over-epilog -S | FileCheck %s --check-prefixes=COMMON,CHECK-TF,CHECK-PREFER +; RUN: opt < %s -loop-vectorize -tail-predication=enabled -prefer-predicate-over-epilog=predicate-dont-vectorize -S | FileCheck %s --check-prefixes=COMMON,CHECK-TF,CHECK-PREFER ; RUN: opt < %s -loop-vectorize -tail-predication=enabled -S | FileCheck %s --check-prefixes=COMMON,CHECK-TF,CHECK-ENABLE-TP target datalayout = "e-m:e-p:32:32-Fi8-i64:64-v128:64:128-a:0:32-n32-S64" Index: llvm/test/Transforms/LoopVectorize/ARM/tail-loop-folding.ll =================================================================== --- llvm/test/Transforms/LoopVectorize/ARM/tail-loop-folding.ll +++ llvm/test/Transforms/LoopVectorize/ARM/tail-loop-folding.ll @@ -1,7 +1,7 @@ ; RUN: opt < %s -loop-vectorize -tail-predication=enabled -S | \ ; RUN: FileCheck %s -check-prefixes=COMMON,CHECK -; RUN: opt < %s -loop-vectorize -tail-predication=enabled -prefer-predicate-over-epilog -S | \ +; RUN: opt < %s -loop-vectorize -tail-predication=enabled -prefer-predicate-over-epilog=predicate-dont-vectorize -S | \ ; RUN: FileCheck -check-prefixes=COMMON,PREDFLAG %s ; RUN: opt < %s -loop-vectorize -tail-predication=enabled-no-reductions -S | \ Index: llvm/test/Transforms/LoopVectorize/X86/tail_loop_folding.ll =================================================================== --- llvm/test/Transforms/LoopVectorize/X86/tail_loop_folding.ll +++ llvm/test/Transforms/LoopVectorize/X86/tail_loop_folding.ll @@ -1,6 +1,6 @@ ; NOTE: Assertions have been autogenerated by utils/update_test_checks.py ; RUN: opt < %s -loop-vectorize -S | FileCheck %s -; RUN: opt < %s -loop-vectorize -prefer-predicate-over-epilog -S | FileCheck %s +; RUN: opt < %s -loop-vectorize -prefer-predicate-over-epilog=predicate-dont-vectorize -S | FileCheck %s target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-unknown-linux-gnu" Index: llvm/test/Transforms/LoopVectorize/memdep-fold-tail.ll =================================================================== --- llvm/test/Transforms/LoopVectorize/memdep-fold-tail.ll +++ llvm/test/Transforms/LoopVectorize/memdep-fold-tail.ll @@ -1,5 +1,5 @@ ; NOTE: Assertions have been autogenerated by utils/update_test_checks.py -; RUN: opt < %s -loop-vectorize -vectorize-num-stores-pred=2 -prefer-predicate-over-epilog -S | FileCheck %s +; RUN: opt < %s -loop-vectorize -vectorize-num-stores-pred=2 -prefer-predicate-over-epilog=predicate-dont-vectorize -S | FileCheck %s target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128" Index: llvm/test/Transforms/LoopVectorize/pr46525-expander-insertpoint.ll =================================================================== --- llvm/test/Transforms/LoopVectorize/pr46525-expander-insertpoint.ll +++ llvm/test/Transforms/LoopVectorize/pr46525-expander-insertpoint.ll @@ -1,5 +1,5 @@ ; NOTE: Assertions have been autogenerated by utils/update_test_checks.py -; RUN: opt -loop-vectorize -force-vector-width=2 -S -prefer-predicate-over-epilog %s | FileCheck %s +; RUN: opt -loop-vectorize -force-vector-width=2 -S -prefer-predicate-over-epilog=predicate-dont-vectorize %s | FileCheck %s ; Test case for PR46525. There are two candidates to pick for Index: llvm/test/Transforms/LoopVectorize/tail-folding-counting-down.ll =================================================================== --- llvm/test/Transforms/LoopVectorize/tail-folding-counting-down.ll +++ llvm/test/Transforms/LoopVectorize/tail-folding-counting-down.ll @@ -1,4 +1,4 @@ -; RUN: opt < %s -loop-vectorize -prefer-predicate-over-epilog -force-vector-width=4 -S | FileCheck %s +; RUN: opt < %s -loop-vectorize -prefer-predicate-over-epilog=predicate-dont-vectorize -force-vector-width=4 -S | FileCheck %s ; Check that a counting-down loop which has no primary induction variable ; is vectorized with preferred predication.