29using namespace PatternMatch;
31#define DEBUG_TYPE "riscv-gather-scatter-lowering"
62 return "RISC-V gather/scatter lowering";
69 std::pair<Value *, Value *> determineBaseAndStride(
Instruction *
Ptr,
79char RISCVGatherScatterLowering::ID = 0;
82 "RISC-V gather/scatter lowering pass",
false,
false)
85 return new RISCVGatherScatterLowering();
90 if (!isa<FixedVectorType>(StartC->
getType()))
91 return std::make_pair(
nullptr,
nullptr);
93 unsigned NumElts = cast<FixedVectorType>(StartC->
getType())->getNumElements();
99 return std::make_pair(
nullptr,
nullptr);
100 APInt StrideVal(StartVal->getValue().getBitWidth(), 0);
102 for (
unsigned i = 1; i != NumElts; ++i) {
105 return std::make_pair(
nullptr,
nullptr);
109 StrideVal = LocalStride;
110 else if (StrideVal != LocalStride)
111 return std::make_pair(
nullptr,
nullptr);
116 Value *Stride = ConstantInt::get(StartVal->getType(), StrideVal);
118 return std::make_pair(StartVal, Stride);
124 auto *StartC = dyn_cast<Constant>(Start);
129 if (
match(Start, m_Intrinsic<Intrinsic::stepvector>())) {
130 auto *Ty = Start->getType()->getScalarType();
131 return std::make_pair(ConstantInt::get(Ty, 0), ConstantInt::get(Ty, 1));
136 auto *BO = dyn_cast<BinaryOperator>(Start);
137 if (!BO || (BO->getOpcode() != Instruction::Add &&
138 BO->getOpcode() != Instruction::Or &&
139 BO->getOpcode() != Instruction::Shl &&
140 BO->getOpcode() != Instruction::Mul))
141 return std::make_pair(
nullptr,
nullptr);
143 if (BO->getOpcode() == Instruction::Or &&
144 !cast<PossiblyDisjointInst>(BO)->isDisjoint())
145 return std::make_pair(
nullptr,
nullptr);
148 unsigned OtherIndex = 0;
155 return std::make_pair(
nullptr,
nullptr);
161 return std::make_pair(
nullptr,
nullptr);
167 switch (BO->getOpcode()) {
170 case Instruction::Or:
174 case Instruction::Add:
177 case Instruction::Mul:
181 case Instruction::Shl:
187 return std::make_pair(Start, Stride);
194bool RISCVGatherScatterLowering::matchStridedRecurrence(
Value *Index,
Loop *L,
200 if (
auto *Phi = dyn_cast<PHINode>(Index)) {
203 if (
Phi->getParent() !=
L->getHeader())
210 assert(
Phi->getNumIncomingValues() == 2 &&
"Expected 2 operand phi.");
211 unsigned IncrementingBlock =
Phi->getIncomingValue(0) == Inc ? 0 : 1;
212 assert(
Phi->getIncomingValue(IncrementingBlock) == Inc &&
213 "Expected one operand of phi to be Inc");
216 if (!
L->isLoopInvariant(Step))
227 assert(Stride !=
nullptr);
232 Inc = BinaryOperator::CreateAdd(BasePtr, Step, Inc->
getName() +
".scalar",
234 BasePtr->addIncoming(Start,
Phi->getIncomingBlock(1 - IncrementingBlock));
235 BasePtr->addIncoming(Inc,
Phi->getIncomingBlock(IncrementingBlock));
238 MaybeDeadPHIs.push_back(Phi);
243 auto *BO = dyn_cast<BinaryOperator>(Index);
247 switch (BO->getOpcode()) {
250 case Instruction::Or:
252 if (!cast<PossiblyDisjointInst>(BO)->isDisjoint())
255 case Instruction::Add:
257 case Instruction::Shl:
259 case Instruction::Mul:
265 if (isa<Instruction>(BO->getOperand(0)) &&
266 L->contains(cast<Instruction>(BO->getOperand(0)))) {
267 Index = cast<Instruction>(BO->getOperand(0));
268 OtherOp = BO->getOperand(1);
269 }
else if (isa<Instruction>(BO->getOperand(1)) &&
270 L->contains(cast<Instruction>(BO->getOperand(1))) &&
272 Index = cast<Instruction>(BO->getOperand(1));
273 OtherOp = BO->getOperand(0);
279 if (!
L->isLoopInvariant(OtherOp))
288 if (!matchStridedRecurrence(Index, L, Stride, BasePtr, Inc, Builder))
293 unsigned StartBlock =
BasePtr->getOperand(0) == Inc ? 1 : 0;
299 BasePtr->getIncomingBlock(StartBlock)->getTerminator());
302 switch (BO->getOpcode()) {
305 case Instruction::Add:
306 case Instruction::Or: {
309 Start = Builder.
CreateAdd(Start, SplatOp,
"start");
312 case Instruction::Mul: {
313 Start = Builder.
CreateMul(Start, SplatOp,
"start");
314 Step = Builder.
CreateMul(Step, SplatOp,
"step");
315 Stride = Builder.
CreateMul(Stride, SplatOp,
"stride");
318 case Instruction::Shl: {
319 Start = Builder.
CreateShl(Start, SplatOp,
"start");
320 Step = Builder.
CreateShl(Step, SplatOp,
"step");
321 Stride = Builder.
CreateShl(Stride, SplatOp,
"stride");
327 BasePtr->setIncomingValue(StartBlock, Start);
331std::pair<Value *, Value *>
332RISCVGatherScatterLowering::determineBaseAndStride(
Instruction *
Ptr,
338 return std::make_pair(BasePtr, ConstantInt::get(IntPtrTy, 0));
341 auto *
GEP = dyn_cast<GetElementPtrInst>(
Ptr);
343 return std::make_pair(
nullptr,
nullptr);
345 auto I = StridedAddrs.find(
GEP);
346 if (
I != StridedAddrs.end())
353 if (
auto *BaseInst = dyn_cast<Instruction>(
Base);
354 BaseInst && BaseInst->getType()->isVectorTy()) {
356 auto IsScalar = [](
Value *
Idx) {
return !
Idx->getType()->isVectorTy(); };
358 auto [BaseBase, Stride] = determineBaseAndStride(BaseInst, Builder);
363 Builder.
CreateGEP(
GEP->getSourceElementType(), BaseBase, Indices,
364 GEP->getName() +
"offset",
GEP->isInBounds());
365 return {OffsetBase, Stride};
375 return std::make_pair(
nullptr,
nullptr);
378 std::optional<unsigned> VecOperand;
379 unsigned TypeScale = 0;
383 for (
unsigned i = 1, e =
GEP->getNumOperands(); i != e; ++i, ++GTI) {
384 if (!Ops[i]->
getType()->isVectorTy())
388 return std::make_pair(
nullptr,
nullptr);
394 return std::make_pair(
nullptr,
nullptr);
401 return std::make_pair(
nullptr,
nullptr);
408 Value *VecIndex = Ops[*VecOperand];
409 Type *VecIntPtrTy =
DL->getIntPtrType(
GEP->getType());
410 if (VecIndex->
getType() != VecIntPtrTy) {
411 auto *VecIndexC = dyn_cast<Constant>(VecIndex);
413 return std::make_pair(
nullptr,
nullptr);
428 Ops[*VecOperand] = Start;
429 Type *SourceTy =
GEP->getSourceElementType();
439 Stride = Builder.
CreateMul(Stride, ConstantInt::get(IntPtrTy, TypeScale));
441 auto P = std::make_pair(BasePtr, Stride);
442 StridedAddrs[
GEP] =
P;
447 Loop *
L = LI->getLoopFor(
GEP->getParent());
448 if (!L || !
L->getLoopPreheader() || !
L->getLoopLatch())
449 return std::make_pair(
nullptr,
nullptr);
453 if (!matchStridedRecurrence(VecIndex, L, Stride, BasePhi, Inc, Builder))
454 return std::make_pair(
nullptr,
nullptr);
457 unsigned IncrementingBlock = BasePhi->
getOperand(0) == Inc ? 0 : 1;
459 "Expected one operand of phi to be Inc");
464 Ops[*VecOperand] = BasePhi;
465 Type *SourceTy =
GEP->getSourceElementType();
479 Stride = Builder.
CreateMul(Stride, ConstantInt::get(IntPtrTy, TypeScale));
481 auto P = std::make_pair(BasePtr, Stride);
482 StridedAddrs[
GEP] =
P;
486bool RISCVGatherScatterLowering::tryCreateStridedLoadStore(
IntrinsicInst *
II,
491 MaybeAlign MA = cast<ConstantInt>(AlignOp)->getMaybeAlignValue();
492 EVT DataTypeVT = TLI->getValueType(*
DL, DataType);
493 if (!MA || !TLI->isLegalStridedLoadStore(DataTypeVT, *MA))
497 if (!TLI->isTypeLegal(DataTypeVT))
501 auto *PtrI = dyn_cast<Instruction>(
Ptr);
510 std::tie(BasePtr, Stride) = determineBaseAndStride(PtrI, Builder);
513 assert(Stride !=
nullptr);
521 if (
II->getIntrinsicID() == Intrinsic::masked_gather) {
523 Intrinsic::experimental_vp_strided_load,
525 {
BasePtr, Stride,
II->getArgOperand(2), EVL});
527 Intrinsic::vp_select, {DataType},
528 {
II->getOperand(2), Call,
II->getArgOperand(3), EVL});
531 Intrinsic::experimental_vp_strided_store,
532 {DataType,
BasePtr->getType(), Stride->getType()},
533 {
II->getArgOperand(0), BasePtr, Stride,
II->getArgOperand(3), EVL});
536 II->replaceAllUsesWith(Call);
537 II->eraseFromParent();
539 if (PtrI->use_empty())
545bool RISCVGatherScatterLowering::runOnFunction(
Function &
F) {
549 auto &TPC = getAnalysis<TargetPassConfig>();
552 if (!
ST->hasVInstructions() || !
ST->useRVVForFixedLengthVectors())
555 TLI =
ST->getTargetLowering();
556 DL = &
F.getDataLayout();
557 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
559 StridedAddrs.clear();
564 bool Changed =
false;
569 if (
II &&
II->getIntrinsicID() == Intrinsic::masked_gather) {
571 }
else if (
II &&
II->getIntrinsicID() == Intrinsic::masked_scatter) {
578 for (
auto *
II : Gathers)
579 Changed |= tryCreateStridedLoadStore(
580 II,
II->getType(),
II->getArgOperand(0),
II->getArgOperand(1));
581 for (
auto *
II : Scatters)
583 tryCreateStridedLoadStore(
II,
II->getArgOperand(0)->getType(),
584 II->getArgOperand(1),
II->getArgOperand(2));
587 while (!MaybeDeadPHIs.empty()) {
588 if (
auto *Phi = dyn_cast_or_null<PHINode>(MaybeDeadPHIs.pop_back_val()))
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static std::pair< Value *, Value * > matchStridedStart(Value *Start, IRBuilderBase &Builder)
static std::pair< Value *, Value * > matchStridedConstant(Constant *StartC)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static SymbolRef::Type getType(const Symbol *Sym)
Target-Independent Code Generator Pass Configuration Options pass.
Class for arbitrary precision integers.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesCFG()
This function should be called by the pass, iff they do not:
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
LLVM Basic Block Representation.
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...
BinaryOps getOpcode() const
This class represents a function call, abstracting a target machine's calling convention.
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.
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.
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
Common base class shared among various IRBuilders.
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
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)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateElementCount(Type *DstType, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
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)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
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...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Target-Independent Code Generator Pass Configuration Options.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
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.
StringRef getName() const
Return a constant reference to the value's name.
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.
@ C
The default llvm calling convention, compatible with C.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
bool match(Val *V, const Pattern &P)
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.
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.
Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
FunctionPass * createRISCVGatherScatterLoweringPass()
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,...
gep_type_iterator gep_type_begin(const User *GEP)
bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.