33#define DEBUG_TYPE "riscv-gather-scatter-lowering"
37class RISCVGatherScatterLoweringImpl {
55 : ST(ST), TLI(ST->getTargetLowering()), GetLI(GetLI),
DL(
DL) {}
62 std::pair<Value *, Value *> determineBaseAndStride(
Instruction *Ptr,
73class RISCVGatherScatterLoweringLegacy :
public FunctionPass {
77 RISCVGatherScatterLoweringLegacy() : FunctionPass(ID) {}
81 void getAnalysisUsage(AnalysisUsage &AU)
const override {
87 StringRef getPassName()
const override {
88 return "RISC-V gather/scatter lowering";
93char RISCVGatherScatterLoweringLegacy::ID = 0;
96 "RISC-V gather/scatter lowering pass",
false,
false)
103 return new RISCVGatherScatterLoweringLegacy();
109 return std::make_pair(
nullptr,
nullptr);
117 return std::make_pair(
nullptr,
nullptr);
118 APInt StrideVal(StartVal->getValue().getBitWidth(), 0);
120 for (
unsigned i = 1; i != NumElts; ++i) {
123 return std::make_pair(
nullptr,
nullptr);
127 StrideVal = LocalStride;
128 else if (StrideVal != LocalStride)
129 return std::make_pair(
nullptr,
nullptr);
134 Value *Stride = ConstantInt::get(StartVal->getType(), StrideVal);
136 return std::make_pair(StartVal, Stride);
148 auto *Ty = Start->getType()->getScalarType();
149 return std::make_pair(ConstantInt::get(Ty, 0), ConstantInt::get(Ty, 1));
155 if (!BO || (BO->getOpcode() != Instruction::Add &&
156 BO->getOpcode() != Instruction::Or &&
157 BO->getOpcode() != Instruction::Shl &&
158 BO->getOpcode() != Instruction::Mul))
159 return std::make_pair(
nullptr,
nullptr);
161 if (BO->getOpcode() == Instruction::Or &&
163 return std::make_pair(
nullptr,
nullptr);
166 unsigned OtherIndex = 0;
173 return std::make_pair(
nullptr,
nullptr);
179 return std::make_pair(
nullptr,
nullptr);
181 Builder.SetInsertPoint(BO);
182 Builder.SetCurrentDebugLocation(
DebugLoc());
185 switch (BO->getOpcode()) {
188 case Instruction::Or:
189 Start = Builder.CreateDisjointOr(Start,
Splat);
191 case Instruction::Add:
192 Start = Builder.CreateAdd(Start,
Splat);
194 case Instruction::Mul:
195 Start = Builder.CreateMul(Start,
Splat);
196 Stride = Builder.CreateMul(Stride,
Splat);
198 case Instruction::Shl:
199 Start = Builder.CreateShl(Start,
Splat);
200 Stride = Builder.CreateShl(Stride,
Splat);
204 return std::make_pair(Start, Stride);
211bool RISCVGatherScatterLoweringImpl::matchStridedRecurrence(
218 if (
Phi->getParent() !=
L->getHeader())
225 assert(
Phi->getNumIncomingValues() == 2 &&
"Expected 2 operand phi.");
226 unsigned IncrementingBlock =
Phi->getIncomingValue(0) == Inc ? 0 : 1;
227 assert(
Phi->getIncomingValue(IncrementingBlock) == Inc &&
228 "Expected one operand of phi to be Inc");
238 assert(Stride !=
nullptr);
243 Inc = BinaryOperator::CreateAdd(BasePtr, Step, Inc->
getName() +
".scalar",
245 BasePtr->addIncoming(Start,
Phi->getIncomingBlock(1 - IncrementingBlock));
246 BasePtr->addIncoming(Inc,
Phi->getIncomingBlock(IncrementingBlock));
249 MaybeDeadPHIs.push_back(Phi);
258 switch (BO->getOpcode()) {
261 case Instruction::Or:
266 case Instruction::Add:
268 case Instruction::Shl:
270 case Instruction::Mul:
279 OtherOp = BO->getOperand(1);
284 OtherOp = BO->getOperand(0);
290 if (!
L->isLoopInvariant(OtherOp))
299 if (!matchStridedRecurrence(Index, L, Stride, BasePtr, Inc, Builder))
304 unsigned StartBlock =
BasePtr->getOperand(0) == Inc ? 1 : 0;
310 BasePtr->getIncomingBlock(StartBlock)->getTerminator());
314 switch (BO->getOpcode()) {
317 case Instruction::Add:
318 case Instruction::Or: {
324 case Instruction::Mul: {
326 Stride = Builder.
CreateMul(Stride, SplatOp,
"stride");
329 case Instruction::Shl: {
331 Stride = Builder.
CreateShl(Stride, SplatOp,
"stride");
341 switch (BO->getOpcode()) {
344 case Instruction::Mul:
345 Step = Builder.
CreateMul(Step, SplatOp,
"step");
347 case Instruction::Shl:
348 Step = Builder.
CreateShl(Step, SplatOp,
"step");
353 BasePtr->setIncomingValue(StartBlock, Start);
357std::pair<Value *, Value *>
358RISCVGatherScatterLoweringImpl::determineBaseAndStride(Instruction *Ptr,
359 IRBuilderBase &Builder) {
364 return std::make_pair(BasePtr, ConstantInt::get(
IntPtrTy, 0));
369 return std::make_pair(
nullptr,
nullptr);
371 auto I = StridedAddrs.find(
GEP);
372 if (
I != StridedAddrs.end())
375 SmallVector<Value *, 2>
Ops(
GEP->operands());
380 BaseInst && BaseInst->getType()->isVectorTy()) {
382 auto IsScalar = [](
Value *
Idx) {
return !
Idx->getType()->isVectorTy(); };
384 auto [BaseBase, Stride] = determineBaseAndStride(BaseInst, Builder);
389 Builder.
CreateGEP(
GEP->getSourceElementType(), BaseBase, Indices,
390 GEP->getName() +
"offset",
GEP->isInBounds());
391 return {OffsetBase, Stride};
401 return std::make_pair(
nullptr,
nullptr);
404 std::optional<unsigned> VecOperand;
405 unsigned TypeScale = 0;
409 for (
unsigned i = 1, e =
GEP->getNumOperands(); i != e; ++i, ++GTI) {
414 return std::make_pair(
nullptr,
nullptr);
420 return std::make_pair(
nullptr,
nullptr);
427 return std::make_pair(
nullptr,
nullptr);
435 Type *VecIntPtrTy =
DL->getIntPtrType(
GEP->getType());
436 if (VecIndex->
getType() != VecIntPtrTy) {
439 return std::make_pair(
nullptr,
nullptr);
455 Type *SourceTy =
GEP->getSourceElementType();
467 auto P = std::make_pair(BasePtr, Stride);
468 StridedAddrs[
GEP] =
P;
477 if (!L || !
L->getLoopPreheader() || !
L->getLoopLatch())
478 return std::make_pair(
nullptr,
nullptr);
482 if (!matchStridedRecurrence(VecIndex, L, Stride, BasePhi, Inc, Builder))
483 return std::make_pair(
nullptr,
nullptr);
486 unsigned IncrementingBlock = BasePhi->
getOperand(0) == Inc ? 0 : 1;
488 "Expected one operand of phi to be Inc");
493 Ops[*VecOperand] = BasePhi;
494 Type *SourceTy =
GEP->getSourceElementType();
510 auto P = std::make_pair(BasePtr, Stride);
511 StridedAddrs[
GEP] =
P;
515bool RISCVGatherScatterLoweringImpl::tryCreateStridedLoadStore(
518 Value *StoreVal =
nullptr, *Ptr, *
Mask, *EVL =
nullptr;
520 switch (
II->getIntrinsicID()) {
521 case Intrinsic::masked_gather:
523 Ptr =
II->getArgOperand(0);
525 Mask =
II->getArgOperand(1);
527 case Intrinsic::vp_gather:
529 Ptr =
II->getArgOperand(0);
532 DL->getABITypeAlign(DataType->getElementType()));
533 Mask =
II->getArgOperand(1);
534 EVL =
II->getArgOperand(2);
536 case Intrinsic::masked_scatter:
538 StoreVal =
II->getArgOperand(0);
539 Ptr =
II->getArgOperand(1);
541 Mask =
II->getArgOperand(2);
543 case Intrinsic::vp_scatter:
545 StoreVal =
II->getArgOperand(0);
546 Ptr =
II->getArgOperand(1);
549 DL->getABITypeAlign(DataType->getElementType()));
550 Mask =
II->getArgOperand(2);
551 EVL =
II->getArgOperand(3);
571 IRBuilder Builder(PtrI->getIterator(), InstSimplifyFolder(*
DL));
574 std::tie(BasePtr, Stride) = determineBaseAndStride(PtrI, Builder);
577 assert(Stride !=
nullptr);
589 Intrinsic::experimental_vp_strided_load,
594 if (
II->getIntrinsicID() == Intrinsic::masked_gather)
598 Intrinsic::experimental_vp_strided_store,
603 II->replaceAllUsesWith(
Call);
604 II->eraseFromParent();
606 if (PtrI->use_empty())
612bool RISCVGatherScatterLoweringImpl::run(
Function &
F) {
620 for (BasicBlock &BB :
F) {
621 for (Instruction &
I : BB) {
625 switch (
II->getIntrinsicID()) {
626 case Intrinsic::masked_gather:
627 case Intrinsic::masked_scatter:
628 case Intrinsic::vp_gather:
629 case Intrinsic::vp_scatter:
639 for (
auto *
II : Worklist)
640 Changed |= tryCreateStridedLoadStore(
II);
643 while (!MaybeDeadPHIs.empty()) {
651bool RISCVGatherScatterLoweringLegacy::runOnFunction(
Function &
F) {
655 auto &TPC = getAnalysis<TargetPassConfig>();
656 auto &TM = TPC.getTM<RISCVTargetMachine>();
657 auto *
ST = &TM.getSubtarget<RISCVSubtarget>(
F);
658 auto GetLI = [&]() -> LoopInfo & {
659 return getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
661 return RISCVGatherScatterLoweringImpl(ST, GetLI, &
F.getDataLayout()).run(
F);
669 RISCVGatherScatterLoweringImpl(ST, GetLI, &
F.getDataLayout()).run(
F);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static bool runOnFunction(Function &F, bool PostInlining)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static std::pair< Value *, Value * > matchStridedStart(Value *Start, IRBuilderBase &Builder)
static std::pair< Value *, Value * > matchStridedConstant(Constant *StartC)
static SymbolRef::Type getType(const Symbol *Sym)
Target-Independent Code Generator Pass Configuration Options pass.
Class for arbitrary precision integers.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
BinaryOps getOpcode() const
This is the shared class of boolean and integer constants.
const APInt & getValue() const
Return the constant as an APInt value reference.
This is an important base class in LLVM.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
FunctionPass class - This class is used to implement most global optimizations.
Common base class shared among various IRBuilders.
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
LLVM_ABI Value * CreateElementCount(Type *Ty, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
A wrapper class for inspecting calls to intrinsic functions.
Analysis pass that exposes the LoopInfo for a function.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Represents a single loop in the control flow graph.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static PreservedAnalyses allInSet()
Construct a preserved analyses object with a single preserved set.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
bool useRVVForFixedLengthVectors() const
bool hasVInstructions() const
bool isLegalStridedLoadStore(EVT DataType, Align Alignment) const
Return true if a stride load store of the given result type and alignment is legal.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
Target-Independent Code Generator Pass Configuration Options.
bool isVectorTy() const
True if this is an instance of VectorType.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
constexpr ScalarTy getFixedValue() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
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.
bool match(Val *V, const Pattern &P)
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
NodeAddr< PhiNode * > Phi
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
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.
FunctionPass * createRISCVGatherScatterLoweringLegacyPass()
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.