40 #include "llvm/IR/IntrinsicsARM.h" 47 #define DEBUG_TYPE "mve-tail-predication" 48 #define DESC "Transform predicated vector loops to use MVE tail predication" 53 cl::desc(
"Disable MVE Tail Predication"));
56 class MVETailPredication :
public LoopPass {
65 MVETailPredication() :
LoopPass(ID) { }
81 bool TryConvert(
Value *TripCount);
85 bool IsPredicatedVectorLoop();
110 return ID == Intrinsic::loop_decrement_reg;
120 return ID == Intrinsic::masked_store || ID == Intrinsic::masked_load;
128 auto &TPC = getAnalysis<TargetPassConfig>();
131 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
132 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
137 if (!ST->hasMVEIntegerOps() || !ST->hasV8_1MMainlineOps()) {
147 for (
auto &
I : *BB) {
153 if (ID == Intrinsic::set_loop_iterations ||
154 ID == Intrinsic::test_set_loop_iterations)
155 return cast<IntrinsicInst>(&
I);
175 for (
auto &
I : *BB) {
177 Decrement = cast<IntrinsicInst>(&
I);
186 LLVM_DEBUG(
dbgs() <<
"ARM TP: Running on Loop: " << *L << *Setup <<
"\n" 187 << *Decrement <<
"\n");
239 Value *TripCount =
nullptr;
255 if (
auto *CDS = dyn_cast<ConstantDataSequential>(Const)) {
256 for (
unsigned i = 0; i < CDS->getNumElements(); ++i) {
257 if (CDS->getElementAsInteger(i) != i)
284 unsigned Lanes = cast<VectorType>(Insert->
getType())->getNumElements();
294 unsigned TypeOp = I->
getIntrinsicID() == Intrinsic::masked_load ? 0 : 1;
296 return cast<VectorType>(PtrTy->getElementType());
299 bool MVETailPredication::IsPredicatedVectorLoop() {
304 for (
auto &I : *BB) {
311 unsigned MaxWidth = TTI->getRegisterBitWidth(
true);
312 if (Lanes * ElementWidth > MaxWidth || Lanes == MaxWidth)
314 MaskedInsts.push_back(cast<IntrinsicInst>(&I));
315 }
else if (
auto *Int = dyn_cast<IntrinsicInst>(&I)) {
316 for (
auto &U : Int->args()) {
317 if (isa<VectorType>(U->getType()))
324 return !MaskedInsts.empty();
327 Value* MVETailPredication::ComputeElements(
Value *TripCount,
329 const SCEV *TripCountSE = SE->getSCEV(TripCount);
338 if (
auto *Const = dyn_cast<SCEVConstant>(S->getOperand(0))) {
339 if (Const->getAPInt() != -VF->
getValue())
346 auto VisitMul = [&](
const SCEVMulExpr *S) ->
const SCEVUDivExpr* {
347 if (
auto *Const = dyn_cast<SCEVConstant>(S->getOperand(0))) {
348 if (Const->getValue() != VF)
355 auto VisitDiv = [&](
const SCEVUDivExpr *S) ->
const SCEV* {
356 if (
auto *Const = dyn_cast<SCEVConstant>(S->getRHS())) {
357 if (Const->getValue() != VF)
362 if (
auto *RoundUp = dyn_cast<SCEVAddExpr>(S->getLHS())) {
363 if (
auto *Const = dyn_cast<SCEVConstant>(RoundUp->getOperand(0))) {
364 if (Const->getAPInt() != (VF->
getValue() - 1))
369 return RoundUp->getOperand(1);
382 const SCEV *Elems =
nullptr;
383 if (
auto *TC = dyn_cast<SCEVAddExpr>(TripCountSE))
384 if (
auto *Div = dyn_cast<SCEVUDivExpr>(TC->getOperand(1)))
385 if (
auto *
Add = dyn_cast<SCEVAddExpr>(Div->getLHS()))
386 if (
auto *Mul = VisitAdd(
Add))
387 if (
auto *Div = VisitMul(Mul))
388 if (
auto *Res = VisitDiv(Div))
418 for (
auto &Pair : NewPredicates) {
422 for (
auto &I : *Exit) {
429 dbgs() <<
"ARM TP: with: "; PredClone->
dump());
437 while (!MaybeDead.
empty()) {
438 auto *I = MaybeDead.
front();
444 if (
auto *OpI = dyn_cast<Instruction>(U))
451 for (
auto *I : Dead) {
456 for (
auto I : L->
blocks())
468 PHINode *Processed = Builder.CreatePHI(Ty, 2);
472 Builder.SetInsertPoint(cast<Instruction>(Predicate));
480 case 4: VCTPID = Intrinsic::arm_mve_vctp32;
break;
481 case 8: VCTPID = Intrinsic::arm_mve_vctp16;
break;
482 case 16: VCTPID = Intrinsic::arm_mve_vctp8;
break;
491 Value *TailPredicate = Builder.CreateCall(VCTP, Processed);
493 NewPredicates[
Predicate] = cast<Instruction>(TailPredicate);
497 Value *Remaining = Builder.CreateSub(Processed, Factor);
500 << *Processed <<
"\n" 501 <<
"ARM TP: Inserted VCTP: " << *TailPredicate <<
"\n");
504 bool MVETailPredication::TryConvert(
Value *TripCount) {
505 if (!IsPredicatedVectorLoop()) {
517 for (
auto *I : MaskedInsts) {
519 unsigned PredOp = ID == Intrinsic::masked_load ? 2 : 3;
521 if (!Predicate || Predicates.
count(Predicate))
525 Value *NumElements = ComputeElements(TripCount, VecTy);
529 if (!isTailPredicate(Predicate, NumElements)) {
530 LLVM_DEBUG(
dbgs() <<
"ARM TP: Not tail predicate: " << *Predicate <<
"\n");
534 LLVM_DEBUG(
dbgs() <<
"ARM TP: Found tail predicate: " << *Predicate <<
"\n");
535 Predicates.
insert(Predicate);
537 InsertVCTPIntrinsic(Predicate, NewPredicates, VecTy, NumElements);
541 Cleanup(NewPredicates, Predicates, L);
546 return new MVETailPredication();
Pass interface - Implemented by all 'passes'.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
class_match< UndefValue > m_Undef()
Match an arbitrary undef constant.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
LLVMContext & getContext() const
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
void dropAllReferences()
Drop all references to operands.
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
const T & front() const
Return the first element of the SetVector.
This class represents lattice values for constants.
static bool IsMasked(Instruction *I)
A Module instance is used to store all the information related to an LLVM module. ...
bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are d...
static void Cleanup(DenseMap< Instruction *, Instruction *> &NewPredicates, SetVector< Instruction *> &MaybeDead, Loop *L)
The main scalar evolution driver.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElement(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Pass * createMVETailPredicationPass()
static bool IsDecrement(Instruction &I)
bool equalsInt(uint64_t V) const
A helper method that can be used to determine if the constant contained within is equal to a constant...
ThreeOps_match< V1_t, V2_t, Mask_t, Instruction::ShuffleVector > m_ShuffleVector(const V1_t &v1, const V2_t &v2, const Mask_t &m)
Matches ShuffleVectorInst.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Value * getArgOperand(unsigned i) const
void dump() const
Support for debugging, callable in GDB: V->dump()
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
bool remove(const value_type &X)
Remove an item from the set vector.
This node represents multiplication of some number of SCEVs.
Target-Independent Code Generator Pass Configuration Options.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BlockT * getHeader() const
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Examine each PHI in the given block and delete it if it is dead.
const APInt & getValue() const
Return the constant as an APInt value reference.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
initializer< Ty > init(const Ty &Val)
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
This class represents a binary unsigned division operation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important base class in LLVM.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
specific_intval m_SpecificInt(APInt V)
Match a specific integer value or vector with all elements equal to the value.
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
Represent the analysis usage information of a pass.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
cl::opt< bool > DisableTailPredication("disable-mve-tail-predication", cl::Hidden, cl::init(true), cl::desc("Disable MVE Tail Predication"))
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
This is the shared class of boolean and integer constants.
Type * getType() const
Return the LLVM type of this SCEV expression.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Class to represent vector types.
This node represents an addition of some number of SCEVs.
This class uses information about analyze scalars to rewrite expressions in canonical form...
This class represents an analyzed expression in the program.
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
const Function * getParent() const
Return the enclosing method, or null if none.
bool empty() const
Determine if the SetVector is empty or not.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
LLVM Value Representation.
A vector that has set insertion semantics.
static VectorType * getVectorType(IntrinsicInst *I)
Primary interface to the complete machine description for the target machine.
The legacy pass manager's analysis pass to compute loop information.
iterator_range< block_iterator > blocks() const
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
A wrapper class for inspecting calls to intrinsic functions.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)