33#define DEBUG_TYPE "riscv-gather-scatter-lowering"
37class RISCVGatherScatterLoweringImpl {
53 : ST(ST), TLI(ST->getTargetLowering()), LI(LI),
DL(
DL) {}
60 std::pair<Value *, Value *> determineBaseAndStride(
Instruction *Ptr,
71class RISCVGatherScatterLoweringLegacy :
public FunctionPass {
75 RISCVGatherScatterLoweringLegacy() : FunctionPass(ID) {}
79 void getAnalysisUsage(AnalysisUsage &AU)
const override {
85 StringRef getPassName()
const override {
86 return "RISC-V gather/scatter lowering";
91char RISCVGatherScatterLoweringLegacy::ID = 0;
94 "RISC-V gather/scatter lowering pass",
false,
false)
101 return new RISCVGatherScatterLoweringLegacy();
107 return std::make_pair(
nullptr,
nullptr);
115 return std::make_pair(
nullptr,
nullptr);
116 APInt StrideVal(StartVal->getValue().getBitWidth(), 0);
118 for (
unsigned i = 1; i != NumElts; ++i) {
121 return std::make_pair(
nullptr,
nullptr);
125 StrideVal = LocalStride;
126 else if (StrideVal != LocalStride)
127 return std::make_pair(
nullptr,
nullptr);
132 Value *Stride = ConstantInt::get(StartVal->getType(), StrideVal);
134 return std::make_pair(StartVal, Stride);
146 auto *Ty = Start->getType()->getScalarType();
147 return std::make_pair(ConstantInt::get(Ty, 0), ConstantInt::get(Ty, 1));
153 if (!BO || (BO->getOpcode() != Instruction::Add &&
154 BO->getOpcode() != Instruction::Or &&
155 BO->getOpcode() != Instruction::Shl &&
156 BO->getOpcode() != Instruction::Mul))
157 return std::make_pair(
nullptr,
nullptr);
159 if (BO->getOpcode() == Instruction::Or &&
161 return std::make_pair(
nullptr,
nullptr);
164 unsigned OtherIndex = 0;
171 return std::make_pair(
nullptr,
nullptr);
177 return std::make_pair(
nullptr,
nullptr);
179 Builder.SetInsertPoint(BO);
180 Builder.SetCurrentDebugLocation(
DebugLoc());
183 switch (BO->getOpcode()) {
186 case Instruction::Or:
187 Start = Builder.CreateDisjointOr(Start,
Splat);
189 case Instruction::Add:
190 Start = Builder.CreateAdd(Start,
Splat);
192 case Instruction::Mul:
193 Start = Builder.CreateMul(Start,
Splat);
194 Stride = Builder.CreateMul(Stride,
Splat);
196 case Instruction::Shl:
197 Start = Builder.CreateShl(Start,
Splat);
198 Stride = Builder.CreateShl(Stride,
Splat);
202 return std::make_pair(Start, Stride);
209bool RISCVGatherScatterLoweringImpl::matchStridedRecurrence(
216 if (
Phi->getParent() !=
L->getHeader())
223 assert(
Phi->getNumIncomingValues() == 2 &&
"Expected 2 operand phi.");
224 unsigned IncrementingBlock =
Phi->getIncomingValue(0) == Inc ? 0 : 1;
225 assert(
Phi->getIncomingValue(IncrementingBlock) == Inc &&
226 "Expected one operand of phi to be Inc");
236 assert(Stride !=
nullptr);
241 Inc = BinaryOperator::CreateAdd(BasePtr, Step, Inc->
getName() +
".scalar",
243 BasePtr->addIncoming(Start,
Phi->getIncomingBlock(1 - IncrementingBlock));
244 BasePtr->addIncoming(Inc,
Phi->getIncomingBlock(IncrementingBlock));
247 MaybeDeadPHIs.push_back(Phi);
256 switch (BO->getOpcode()) {
259 case Instruction::Or:
264 case Instruction::Add:
266 case Instruction::Shl:
268 case Instruction::Mul:
277 OtherOp = BO->getOperand(1);
282 OtherOp = BO->getOperand(0);
288 if (!
L->isLoopInvariant(OtherOp))
297 if (!matchStridedRecurrence(Index, L, Stride, BasePtr, Inc, Builder))
302 unsigned StartBlock =
BasePtr->getOperand(0) == Inc ? 1 : 0;
308 BasePtr->getIncomingBlock(StartBlock)->getTerminator());
312 switch (BO->getOpcode()) {
315 case Instruction::Add:
316 case Instruction::Or: {
322 case Instruction::Mul: {
324 Stride = Builder.
CreateMul(Stride, SplatOp,
"stride");
327 case Instruction::Shl: {
329 Stride = Builder.
CreateShl(Stride, SplatOp,
"stride");
339 switch (BO->getOpcode()) {
342 case Instruction::Mul:
343 Step = Builder.
CreateMul(Step, SplatOp,
"step");
345 case Instruction::Shl:
346 Step = Builder.
CreateShl(Step, SplatOp,
"step");
351 BasePtr->setIncomingValue(StartBlock, Start);
355std::pair<Value *, Value *>
356RISCVGatherScatterLoweringImpl::determineBaseAndStride(Instruction *Ptr,
357 IRBuilderBase &Builder) {
362 return std::make_pair(BasePtr, ConstantInt::get(
IntPtrTy, 0));
367 return std::make_pair(
nullptr,
nullptr);
369 auto I = StridedAddrs.find(
GEP);
370 if (
I != StridedAddrs.end())
373 SmallVector<Value *, 2>
Ops(
GEP->operands());
378 BaseInst && BaseInst->getType()->isVectorTy()) {
380 auto IsScalar = [](
Value *Idx) {
return !Idx->getType()->isVectorTy(); };
382 auto [BaseBase, Stride] = determineBaseAndStride(BaseInst, Builder);
387 Builder.
CreateGEP(
GEP->getSourceElementType(), BaseBase, Indices,
388 GEP->getName() +
"offset",
GEP->isInBounds());
389 return {OffsetBase, Stride};
399 return std::make_pair(
nullptr,
nullptr);
402 std::optional<unsigned> VecOperand;
403 unsigned TypeScale = 0;
407 for (
unsigned i = 1, e =
GEP->getNumOperands(); i != e; ++i, ++GTI) {
412 return std::make_pair(
nullptr,
nullptr);
418 return std::make_pair(
nullptr,
nullptr);
425 return std::make_pair(
nullptr,
nullptr);
433 Type *VecIntPtrTy =
DL->getIntPtrType(
GEP->getType());
434 if (VecIndex->
getType() != VecIntPtrTy) {
437 return std::make_pair(
nullptr,
nullptr);
453 Type *SourceTy =
GEP->getSourceElementType();
465 auto P = std::make_pair(BasePtr, Stride);
466 StridedAddrs[
GEP] =
P;
472 if (!L || !
L->getLoopPreheader() || !
L->getLoopLatch())
473 return std::make_pair(
nullptr,
nullptr);
477 if (!matchStridedRecurrence(VecIndex, L, Stride, BasePhi, Inc, Builder))
478 return std::make_pair(
nullptr,
nullptr);
481 unsigned IncrementingBlock = BasePhi->
getOperand(0) == Inc ? 0 : 1;
483 "Expected one operand of phi to be Inc");
488 Ops[*VecOperand] = BasePhi;
489 Type *SourceTy =
GEP->getSourceElementType();
505 auto P = std::make_pair(BasePtr, Stride);
506 StridedAddrs[
GEP] =
P;
510bool RISCVGatherScatterLoweringImpl::tryCreateStridedLoadStore(
513 Value *StoreVal =
nullptr, *Ptr, *
Mask, *EVL =
nullptr;
515 switch (
II->getIntrinsicID()) {
516 case Intrinsic::masked_gather:
518 Ptr =
II->getArgOperand(0);
519 Alignment =
II->getParamAlign(0).valueOrOne();
520 Mask =
II->getArgOperand(1);
522 case Intrinsic::vp_gather:
524 Ptr =
II->getArgOperand(0);
526 Alignment =
II->getParamAlign(0).value_or(
527 DL->getABITypeAlign(DataType->getElementType()));
528 Mask =
II->getArgOperand(1);
529 EVL =
II->getArgOperand(2);
531 case Intrinsic::masked_scatter:
533 StoreVal =
II->getArgOperand(0);
534 Ptr =
II->getArgOperand(1);
535 Alignment =
II->getParamAlign(1).valueOrOne();
536 Mask =
II->getArgOperand(2);
538 case Intrinsic::vp_scatter:
540 StoreVal =
II->getArgOperand(0);
541 Ptr =
II->getArgOperand(1);
543 Alignment =
II->getParamAlign(1).value_or(
544 DL->getABITypeAlign(DataType->getElementType()));
545 Mask =
II->getArgOperand(2);
546 EVL =
II->getArgOperand(3);
566 LLVMContext &Ctx = PtrI->getContext();
571 std::tie(BasePtr, Stride) = determineBaseAndStride(PtrI, Builder);
574 assert(Stride !=
nullptr);
586 Intrinsic::experimental_vp_strided_load,
591 if (
II->getIntrinsicID() == Intrinsic::masked_gather)
595 Intrinsic::experimental_vp_strided_store,
600 II->replaceAllUsesWith(
Call);
601 II->eraseFromParent();
603 if (PtrI->use_empty())
609bool RISCVGatherScatterLoweringImpl::run(
Function &
F) {
617 for (BasicBlock &BB :
F) {
618 for (Instruction &
I : BB) {
622 switch (
II->getIntrinsicID()) {
623 case Intrinsic::masked_gather:
624 case Intrinsic::masked_scatter:
625 case Intrinsic::vp_gather:
626 case Intrinsic::vp_scatter:
636 for (
auto *
II : Worklist)
637 Changed |= tryCreateStridedLoadStore(
II);
640 while (!MaybeDeadPHIs.empty()) {
648bool RISCVGatherScatterLoweringLegacy::runOnFunction(
Function &
F) {
652 auto &TPC = getAnalysis<TargetPassConfig>();
653 auto &TM = TPC.getTM<RISCVTargetMachine>();
654 auto *
ST = &TM.getSubtarget<RISCVSubtarget>(
F);
655 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
656 return RISCVGatherScatterLoweringImpl(ST, LI, &
F.getDataLayout()).run(
F);
664 RISCVGatherScatterLoweringImpl(ST, LI, &
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)
This file declares the RISC-V gather/scatter lowering passes.
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).
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.
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)
FunctionPass * createRISCVGatherScatterLoweringPass()
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...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
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.