46#include "llvm/IR/IntrinsicsARM.h"
55#define DEBUG_TYPE "mve-tail-predication"
56#define DESC "Transform predicated vector loops to use MVE tail predication"
59 "tail-predication",
cl::desc(
"MVE tail-predication pass options"),
62 "Don't tail-predicate loops"),
64 "enabled-no-reductions",
65 "Enable tail-predication, but not for reduction loops"),
68 "Enable tail-predication, including reduction loops"),
70 "force-enabled-no-reductions",
71 "Enable tail-predication, but not for reduction loops, "
72 "and force this which might be unsafe"),
75 "Enable tail-predication, including reduction loops, "
76 "and force this which might be unsafe")));
81class MVETailPredication :
public LoopPass {
91 MVETailPredication() :
LoopPass(ID) { }
93 void getAnalysisUsage(AnalysisUsage &AU)
const override {
100 bool runOnLoop(Loop *L, LPPassManager&)
override;
105 bool TryConvertActiveLaneMask(
Value *TripCount);
111 const SCEV *IsSafeActiveMask(IntrinsicInst *ActiveLaneMask,
Value *TripCount);
114 void InsertVCTPIntrinsic(IntrinsicInst *ActiveLaneMask,
Value *Start);
125 auto &TPC = getAnalysis<TargetPassConfig>();
126 auto &TM = TPC.getTM<TargetMachine>();
127 ST = &TM.getSubtarget<ARMSubtarget>(
F);
128 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
F);
129 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
134 if (!
ST->hasMVEIntegerOps() || !
ST->hasV8_1MMainlineOps()) {
143 auto FindLoopIterations = [](
BasicBlock *BB) -> IntrinsicInst* {
144 for (
auto &
I : *BB) {
150 if (ID == Intrinsic::start_loop_iterations ||
151 ID == Intrinsic::test_start_loop_iterations)
158 IntrinsicInst *
Setup = FindLoopIterations(Preheader);
169 LLVM_DEBUG(
dbgs() <<
"ARM TP: Running on Loop: " << *L << *Setup <<
"\n");
171 bool Changed = TryConvertActiveLaneMask(
Setup->getArgOperand(0));
193const SCEV *MVETailPredication::IsSafeActiveMask(IntrinsicInst *ActiveLaneMask,
195 bool ForceTailPredication =
201 if (!
L->makeLoopInvariant(ElemCount,
Changed))
205 const SCEV *TC = SE->
getSCEV(TripCount);
208 if (VectorWidth != 2 && VectorWidth != 4 && VectorWidth != 8 &&
211 ConstantInt *ConstElemCount =
nullptr;
217 LLVM_DEBUG(
dbgs() <<
"ARM TP: element count must be loop invariant.\n");
235 if (AddExpr->getLoop() != L) {
241 LLVM_DEBUG(
dbgs() <<
"ARM TP: induction step is not a constant: ";
242 AddExpr->getOperand(1)->
dump());
245 auto StepValue = Step->getValue()->getSExtValue();
246 if (VectorWidth != StepValue) {
248 <<
" doesn't match vector width " << VectorWidth <<
"\n");
256 "set.loop.iterations\n");
266 (ConstElemCount->
getZExtValue() + VectorWidth - 1) / VectorWidth;
272 LLVM_DEBUG(
dbgs() <<
"ARM TP: inconsistent constant tripcount values: "
273 << TC1 <<
" from set.loop.iterations, and "
274 << TC2 <<
" from get.active.lane.mask\n");
277 }
else if (!ForceTailPredication) {
293 const SCEV *
Start = AddExpr->getStart();
296 SE->
getSCEV(ConstantInt::get(TripCount->
getType(), VectorWidth - 1)));
299 const SCEV *Ceil = SE->
getUDivExpr(ECPlusVWMinus1, VW);
304 dbgs() <<
"ARM TP: Analysing overflow behaviour for:\n";
305 dbgs() <<
"ARM TP: - TripCount = " << *TC <<
"\n";
306 dbgs() <<
"ARM TP: - ElemCount = " << *
EC <<
"\n";
307 dbgs() <<
"ARM TP: - Start = " << *
Start <<
"\n";
309 dbgs() <<
"ARM TP: - VecWidth = " << VectorWidth <<
"\n";
310 dbgs() <<
"ARM TP: - (ElemCount+VW-1) / VW = " << *Ceil <<
"\n";
338 if (!
Sub->isZero()) {
339 LLVM_DEBUG(
dbgs() <<
"ARM TP: possible overflow in sub expression.\n");
349 if (BaseC->getAPInt().urem(VectorWidth) == 0)
352 Type *Ty = BaseV->getType();
356 L->getHeader()->getDataLayout()))
360 if (BaseC->getAPInt().urem(VectorWidth) == 0)
363 if (BaseC->getAPInt().urem(VectorWidth) == 0)
368 dbgs() <<
"ARM TP: induction base is not know to be a multiple of VF: "
369 << *AddExpr->getOperand(0) <<
"\n");
373void MVETailPredication::InsertVCTPIntrinsic(IntrinsicInst *ActiveLaneMask,
375 IRBuilder<> Builder(
L->getLoopPreheader()->getTerminator());
376 Module *
M =
L->getHeader()->getModule();
378 unsigned VectorWidth =
382 Builder.SetInsertPoint(
L->getHeader(),
L->getHeader()->getFirstNonPHIIt());
383 PHINode *Processed = Builder.CreatePHI(Ty, 2);
388 Builder.SetInsertPoint(ActiveLaneMask);
392 switch (VectorWidth) {
395 case 2: VCTPID = Intrinsic::arm_mve_vctp64;
break;
396 case 4: VCTPID = Intrinsic::arm_mve_vctp32;
break;
397 case 8: VCTPID = Intrinsic::arm_mve_vctp16;
break;
398 case 16: VCTPID = Intrinsic::arm_mve_vctp8;
break;
400 Value *VCTPCall = Builder.CreateIntrinsic(VCTPID, Processed);
405 Value *Remaining = Builder.CreateSub(Processed, Factor);
408 << *Processed <<
"\n"
409 <<
"ARM TP: Inserted VCTP: " << *VCTPCall <<
"\n");
412bool MVETailPredication::TryConvertActiveLaneMask(
Value *TripCount) {
414 for (
auto *BB :
L->getBlocks())
417 if (
Int->getIntrinsicID() == Intrinsic::get_active_lane_mask)
420 if (ActiveLaneMasks.
empty())
425 for (
auto *ActiveLaneMask : ActiveLaneMasks) {
427 << *ActiveLaneMask <<
"\n");
429 const SCEV *StartSCEV = IsSafeActiveMask(ActiveLaneMask, TripCount);
434 LLVM_DEBUG(
dbgs() <<
"ARM TP: Safe to insert VCTP. Start is " << *StartSCEV
436 SCEVExpander Expander(*SE,
"start");
437 Instruction *Ins =
L->getLoopPreheader()->getTerminator();
439 LLVM_DEBUG(
dbgs() <<
"ARM TP: Created start value " << *Start <<
"\n");
440 InsertVCTPIntrinsic(ActiveLaneMask, Start);
444 for (
auto *
II : ActiveLaneMasks)
446 for (
auto *
I :
L->blocks())
452 return new MVETailPredication();
455char MVETailPredication::ID = 0;
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
cl::opt< TailPredication::Mode > EnableTailPredication("tail-predication", cl::desc("MVE tail-predication pass options"), cl::init(TailPredication::Enabled), cl::values(clEnumValN(TailPredication::Disabled, "disabled", "Don't tail-predicate loops"), clEnumValN(TailPredication::EnabledNoReductions, "enabled-no-reductions", "Enable tail-predication, but not for reduction loops"), clEnumValN(TailPredication::Enabled, "enabled", "Enable tail-predication, including reduction loops"), clEnumValN(TailPredication::ForceEnabledNoReductions, "force-enabled-no-reductions", "Enable tail-predication, but not for reduction loops, " "and force this which might be unsafe"), clEnumValN(TailPredication::ForceEnabled, "force-enabled", "Enable tail-predication, including reduction loops, " "and force this which might be unsafe")))
Machine Check Debug Module
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Target-Independent Code Generator Pass Configuration Options pass.
static const uint32_t IV[8]
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Represents a single loop in the control flow graph.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Pass interface - Implemented by all 'passes'.
LLVM_ABI void dump() const
This method is used for debugging.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Value * getOperand(unsigned i) const
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
@ ForceEnabledNoReductions
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
Pass * createMVETailPredicationPass()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
@ Sub
Subtraction of integers.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.