xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVGatherScatterLowering.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
1349cc55cSDimitry Andric //===- RISCVGatherScatterLowering.cpp - Gather/Scatter lowering -----------===//
2349cc55cSDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6349cc55cSDimitry Andric //
7349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
8349cc55cSDimitry Andric //
9349cc55cSDimitry Andric // This pass custom lowers llvm.gather and llvm.scatter instructions to
10349cc55cSDimitry Andric // RISCV intrinsics.
11349cc55cSDimitry Andric //
12349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
13349cc55cSDimitry Andric 
14349cc55cSDimitry Andric #include "RISCV.h"
15349cc55cSDimitry Andric #include "RISCVTargetMachine.h"
16349cc55cSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
17349cc55cSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
18349cc55cSDimitry Andric #include "llvm/Analysis/VectorUtils.h"
19349cc55cSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
20349cc55cSDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
21349cc55cSDimitry Andric #include "llvm/IR/IRBuilder.h"
22349cc55cSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
23349cc55cSDimitry Andric #include "llvm/IR/IntrinsicsRISCV.h"
24349cc55cSDimitry Andric #include "llvm/Transforms/Utils/Local.h"
25349cc55cSDimitry Andric 
26349cc55cSDimitry Andric using namespace llvm;
27349cc55cSDimitry Andric 
28349cc55cSDimitry Andric #define DEBUG_TYPE "riscv-gather-scatter-lowering"
29349cc55cSDimitry Andric 
30349cc55cSDimitry Andric namespace {
31349cc55cSDimitry Andric 
32349cc55cSDimitry Andric class RISCVGatherScatterLowering : public FunctionPass {
33349cc55cSDimitry Andric   const RISCVSubtarget *ST = nullptr;
34349cc55cSDimitry Andric   const RISCVTargetLowering *TLI = nullptr;
35349cc55cSDimitry Andric   LoopInfo *LI = nullptr;
36349cc55cSDimitry Andric   const DataLayout *DL = nullptr;
37349cc55cSDimitry Andric 
38349cc55cSDimitry Andric   SmallVector<WeakTrackingVH> MaybeDeadPHIs;
39349cc55cSDimitry Andric 
40*81ad6265SDimitry Andric   // Cache of the BasePtr and Stride determined from this GEP. When a GEP is
41*81ad6265SDimitry Andric   // used by multiple gathers/scatters, this allow us to reuse the scalar
42*81ad6265SDimitry Andric   // instructions we created for the first gather/scatter for the others.
43*81ad6265SDimitry Andric   DenseMap<GetElementPtrInst *, std::pair<Value *, Value *>> StridedAddrs;
44*81ad6265SDimitry Andric 
45349cc55cSDimitry Andric public:
46349cc55cSDimitry Andric   static char ID; // Pass identification, replacement for typeid
47349cc55cSDimitry Andric 
48349cc55cSDimitry Andric   RISCVGatherScatterLowering() : FunctionPass(ID) {}
49349cc55cSDimitry Andric 
50349cc55cSDimitry Andric   bool runOnFunction(Function &F) override;
51349cc55cSDimitry Andric 
52349cc55cSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
53349cc55cSDimitry Andric     AU.setPreservesCFG();
54349cc55cSDimitry Andric     AU.addRequired<TargetPassConfig>();
55349cc55cSDimitry Andric     AU.addRequired<LoopInfoWrapperPass>();
56349cc55cSDimitry Andric   }
57349cc55cSDimitry Andric 
58349cc55cSDimitry Andric   StringRef getPassName() const override {
59349cc55cSDimitry Andric     return "RISCV gather/scatter lowering";
60349cc55cSDimitry Andric   }
61349cc55cSDimitry Andric 
62349cc55cSDimitry Andric private:
63349cc55cSDimitry Andric   bool isLegalTypeAndAlignment(Type *DataType, Value *AlignOp);
64349cc55cSDimitry Andric 
65349cc55cSDimitry Andric   bool tryCreateStridedLoadStore(IntrinsicInst *II, Type *DataType, Value *Ptr,
66349cc55cSDimitry Andric                                  Value *AlignOp);
67349cc55cSDimitry Andric 
68349cc55cSDimitry Andric   std::pair<Value *, Value *> determineBaseAndStride(GetElementPtrInst *GEP,
69349cc55cSDimitry Andric                                                      IRBuilder<> &Builder);
70349cc55cSDimitry Andric 
71349cc55cSDimitry Andric   bool matchStridedRecurrence(Value *Index, Loop *L, Value *&Stride,
72349cc55cSDimitry Andric                               PHINode *&BasePtr, BinaryOperator *&Inc,
73349cc55cSDimitry Andric                               IRBuilder<> &Builder);
74349cc55cSDimitry Andric };
75349cc55cSDimitry Andric 
76349cc55cSDimitry Andric } // end anonymous namespace
77349cc55cSDimitry Andric 
78349cc55cSDimitry Andric char RISCVGatherScatterLowering::ID = 0;
79349cc55cSDimitry Andric 
80349cc55cSDimitry Andric INITIALIZE_PASS(RISCVGatherScatterLowering, DEBUG_TYPE,
81349cc55cSDimitry Andric                 "RISCV gather/scatter lowering pass", false, false)
82349cc55cSDimitry Andric 
83349cc55cSDimitry Andric FunctionPass *llvm::createRISCVGatherScatterLoweringPass() {
84349cc55cSDimitry Andric   return new RISCVGatherScatterLowering();
85349cc55cSDimitry Andric }
86349cc55cSDimitry Andric 
87349cc55cSDimitry Andric bool RISCVGatherScatterLowering::isLegalTypeAndAlignment(Type *DataType,
88349cc55cSDimitry Andric                                                          Value *AlignOp) {
89349cc55cSDimitry Andric   Type *ScalarType = DataType->getScalarType();
90349cc55cSDimitry Andric   if (!TLI->isLegalElementTypeForRVV(ScalarType))
91349cc55cSDimitry Andric     return false;
92349cc55cSDimitry Andric 
93349cc55cSDimitry Andric   MaybeAlign MA = cast<ConstantInt>(AlignOp)->getMaybeAlignValue();
94349cc55cSDimitry Andric   if (MA && MA->value() < DL->getTypeStoreSize(ScalarType).getFixedSize())
95349cc55cSDimitry Andric     return false;
96349cc55cSDimitry Andric 
97349cc55cSDimitry Andric   // FIXME: Let the backend type legalize by splitting/widening?
98349cc55cSDimitry Andric   EVT DataVT = TLI->getValueType(*DL, DataType);
99349cc55cSDimitry Andric   if (!TLI->isTypeLegal(DataVT))
100349cc55cSDimitry Andric     return false;
101349cc55cSDimitry Andric 
102349cc55cSDimitry Andric   return true;
103349cc55cSDimitry Andric }
104349cc55cSDimitry Andric 
105349cc55cSDimitry Andric // TODO: Should we consider the mask when looking for a stride?
106349cc55cSDimitry Andric static std::pair<Value *, Value *> matchStridedConstant(Constant *StartC) {
107349cc55cSDimitry Andric   unsigned NumElts = cast<FixedVectorType>(StartC->getType())->getNumElements();
108349cc55cSDimitry Andric 
109349cc55cSDimitry Andric   // Check that the start value is a strided constant.
110349cc55cSDimitry Andric   auto *StartVal =
111349cc55cSDimitry Andric       dyn_cast_or_null<ConstantInt>(StartC->getAggregateElement((unsigned)0));
112349cc55cSDimitry Andric   if (!StartVal)
113349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
114349cc55cSDimitry Andric   APInt StrideVal(StartVal->getValue().getBitWidth(), 0);
115349cc55cSDimitry Andric   ConstantInt *Prev = StartVal;
116349cc55cSDimitry Andric   for (unsigned i = 1; i != NumElts; ++i) {
117349cc55cSDimitry Andric     auto *C = dyn_cast_or_null<ConstantInt>(StartC->getAggregateElement(i));
118349cc55cSDimitry Andric     if (!C)
119349cc55cSDimitry Andric       return std::make_pair(nullptr, nullptr);
120349cc55cSDimitry Andric 
121349cc55cSDimitry Andric     APInt LocalStride = C->getValue() - Prev->getValue();
122349cc55cSDimitry Andric     if (i == 1)
123349cc55cSDimitry Andric       StrideVal = LocalStride;
124349cc55cSDimitry Andric     else if (StrideVal != LocalStride)
125349cc55cSDimitry Andric       return std::make_pair(nullptr, nullptr);
126349cc55cSDimitry Andric 
127349cc55cSDimitry Andric     Prev = C;
128349cc55cSDimitry Andric   }
129349cc55cSDimitry Andric 
130349cc55cSDimitry Andric   Value *Stride = ConstantInt::get(StartVal->getType(), StrideVal);
131349cc55cSDimitry Andric 
132349cc55cSDimitry Andric   return std::make_pair(StartVal, Stride);
133349cc55cSDimitry Andric }
134349cc55cSDimitry Andric 
13504eeddc0SDimitry Andric static std::pair<Value *, Value *> matchStridedStart(Value *Start,
13604eeddc0SDimitry Andric                                                      IRBuilder<> &Builder) {
13704eeddc0SDimitry Andric   // Base case, start is a strided constant.
13804eeddc0SDimitry Andric   auto *StartC = dyn_cast<Constant>(Start);
13904eeddc0SDimitry Andric   if (StartC)
14004eeddc0SDimitry Andric     return matchStridedConstant(StartC);
14104eeddc0SDimitry Andric 
14204eeddc0SDimitry Andric   // Not a constant, maybe it's a strided constant with a splat added to it.
14304eeddc0SDimitry Andric   auto *BO = dyn_cast<BinaryOperator>(Start);
14404eeddc0SDimitry Andric   if (!BO || BO->getOpcode() != Instruction::Add)
14504eeddc0SDimitry Andric     return std::make_pair(nullptr, nullptr);
14604eeddc0SDimitry Andric 
14704eeddc0SDimitry Andric   // Look for an operand that is splatted.
14804eeddc0SDimitry Andric   unsigned OtherIndex = 1;
14904eeddc0SDimitry Andric   Value *Splat = getSplatValue(BO->getOperand(0));
15004eeddc0SDimitry Andric   if (!Splat) {
15104eeddc0SDimitry Andric     Splat = getSplatValue(BO->getOperand(1));
15204eeddc0SDimitry Andric     OtherIndex = 0;
15304eeddc0SDimitry Andric   }
15404eeddc0SDimitry Andric   if (!Splat)
15504eeddc0SDimitry Andric     return std::make_pair(nullptr, nullptr);
15604eeddc0SDimitry Andric 
15704eeddc0SDimitry Andric   Value *Stride;
15804eeddc0SDimitry Andric   std::tie(Start, Stride) = matchStridedStart(BO->getOperand(OtherIndex),
15904eeddc0SDimitry Andric                                               Builder);
16004eeddc0SDimitry Andric   if (!Start)
16104eeddc0SDimitry Andric     return std::make_pair(nullptr, nullptr);
16204eeddc0SDimitry Andric 
16304eeddc0SDimitry Andric   // Add the splat value to the start.
16404eeddc0SDimitry Andric   Builder.SetInsertPoint(BO);
16504eeddc0SDimitry Andric   Builder.SetCurrentDebugLocation(DebugLoc());
16604eeddc0SDimitry Andric   Start = Builder.CreateAdd(Start, Splat);
16704eeddc0SDimitry Andric   return std::make_pair(Start, Stride);
16804eeddc0SDimitry Andric }
16904eeddc0SDimitry Andric 
170349cc55cSDimitry Andric // Recursively, walk about the use-def chain until we find a Phi with a strided
171349cc55cSDimitry Andric // start value. Build and update a scalar recurrence as we unwind the recursion.
172349cc55cSDimitry Andric // We also update the Stride as we unwind. Our goal is to move all of the
173349cc55cSDimitry Andric // arithmetic out of the loop.
174349cc55cSDimitry Andric bool RISCVGatherScatterLowering::matchStridedRecurrence(Value *Index, Loop *L,
175349cc55cSDimitry Andric                                                         Value *&Stride,
176349cc55cSDimitry Andric                                                         PHINode *&BasePtr,
177349cc55cSDimitry Andric                                                         BinaryOperator *&Inc,
178349cc55cSDimitry Andric                                                         IRBuilder<> &Builder) {
179349cc55cSDimitry Andric   // Our base case is a Phi.
180349cc55cSDimitry Andric   if (auto *Phi = dyn_cast<PHINode>(Index)) {
181349cc55cSDimitry Andric     // A phi node we want to perform this function on should be from the
182349cc55cSDimitry Andric     // loop header.
183349cc55cSDimitry Andric     if (Phi->getParent() != L->getHeader())
184349cc55cSDimitry Andric       return false;
185349cc55cSDimitry Andric 
186349cc55cSDimitry Andric     Value *Step, *Start;
187349cc55cSDimitry Andric     if (!matchSimpleRecurrence(Phi, Inc, Start, Step) ||
188349cc55cSDimitry Andric         Inc->getOpcode() != Instruction::Add)
189349cc55cSDimitry Andric       return false;
190349cc55cSDimitry Andric     assert(Phi->getNumIncomingValues() == 2 && "Expected 2 operand phi.");
191349cc55cSDimitry Andric     unsigned IncrementingBlock = Phi->getIncomingValue(0) == Inc ? 0 : 1;
192349cc55cSDimitry Andric     assert(Phi->getIncomingValue(IncrementingBlock) == Inc &&
193349cc55cSDimitry Andric            "Expected one operand of phi to be Inc");
194349cc55cSDimitry Andric 
195349cc55cSDimitry Andric     // Only proceed if the step is loop invariant.
196349cc55cSDimitry Andric     if (!L->isLoopInvariant(Step))
197349cc55cSDimitry Andric       return false;
198349cc55cSDimitry Andric 
199349cc55cSDimitry Andric     // Step should be a splat.
200349cc55cSDimitry Andric     Step = getSplatValue(Step);
201349cc55cSDimitry Andric     if (!Step)
202349cc55cSDimitry Andric       return false;
203349cc55cSDimitry Andric 
20404eeddc0SDimitry Andric     std::tie(Start, Stride) = matchStridedStart(Start, Builder);
205349cc55cSDimitry Andric     if (!Start)
206349cc55cSDimitry Andric       return false;
207349cc55cSDimitry Andric     assert(Stride != nullptr);
208349cc55cSDimitry Andric 
209349cc55cSDimitry Andric     // Build scalar phi and increment.
210349cc55cSDimitry Andric     BasePtr =
211349cc55cSDimitry Andric         PHINode::Create(Start->getType(), 2, Phi->getName() + ".scalar", Phi);
212349cc55cSDimitry Andric     Inc = BinaryOperator::CreateAdd(BasePtr, Step, Inc->getName() + ".scalar",
213349cc55cSDimitry Andric                                     Inc);
214349cc55cSDimitry Andric     BasePtr->addIncoming(Start, Phi->getIncomingBlock(1 - IncrementingBlock));
215349cc55cSDimitry Andric     BasePtr->addIncoming(Inc, Phi->getIncomingBlock(IncrementingBlock));
216349cc55cSDimitry Andric 
217349cc55cSDimitry Andric     // Note that this Phi might be eligible for removal.
218349cc55cSDimitry Andric     MaybeDeadPHIs.push_back(Phi);
219349cc55cSDimitry Andric     return true;
220349cc55cSDimitry Andric   }
221349cc55cSDimitry Andric 
222349cc55cSDimitry Andric   // Otherwise look for binary operator.
223349cc55cSDimitry Andric   auto *BO = dyn_cast<BinaryOperator>(Index);
224349cc55cSDimitry Andric   if (!BO)
225349cc55cSDimitry Andric     return false;
226349cc55cSDimitry Andric 
227349cc55cSDimitry Andric   if (BO->getOpcode() != Instruction::Add &&
228349cc55cSDimitry Andric       BO->getOpcode() != Instruction::Or &&
229349cc55cSDimitry Andric       BO->getOpcode() != Instruction::Mul &&
230349cc55cSDimitry Andric       BO->getOpcode() != Instruction::Shl)
231349cc55cSDimitry Andric     return false;
232349cc55cSDimitry Andric 
233349cc55cSDimitry Andric   // Only support shift by constant.
234349cc55cSDimitry Andric   if (BO->getOpcode() == Instruction::Shl && !isa<Constant>(BO->getOperand(1)))
235349cc55cSDimitry Andric     return false;
236349cc55cSDimitry Andric 
237349cc55cSDimitry Andric   // We need to be able to treat Or as Add.
238349cc55cSDimitry Andric   if (BO->getOpcode() == Instruction::Or &&
239349cc55cSDimitry Andric       !haveNoCommonBitsSet(BO->getOperand(0), BO->getOperand(1), *DL))
240349cc55cSDimitry Andric     return false;
241349cc55cSDimitry Andric 
242349cc55cSDimitry Andric   // We should have one operand in the loop and one splat.
243349cc55cSDimitry Andric   Value *OtherOp;
244349cc55cSDimitry Andric   if (isa<Instruction>(BO->getOperand(0)) &&
245349cc55cSDimitry Andric       L->contains(cast<Instruction>(BO->getOperand(0)))) {
246349cc55cSDimitry Andric     Index = cast<Instruction>(BO->getOperand(0));
247349cc55cSDimitry Andric     OtherOp = BO->getOperand(1);
248349cc55cSDimitry Andric   } else if (isa<Instruction>(BO->getOperand(1)) &&
249349cc55cSDimitry Andric              L->contains(cast<Instruction>(BO->getOperand(1)))) {
250349cc55cSDimitry Andric     Index = cast<Instruction>(BO->getOperand(1));
251349cc55cSDimitry Andric     OtherOp = BO->getOperand(0);
252349cc55cSDimitry Andric   } else {
253349cc55cSDimitry Andric     return false;
254349cc55cSDimitry Andric   }
255349cc55cSDimitry Andric 
256349cc55cSDimitry Andric   // Make sure other op is loop invariant.
257349cc55cSDimitry Andric   if (!L->isLoopInvariant(OtherOp))
258349cc55cSDimitry Andric     return false;
259349cc55cSDimitry Andric 
260349cc55cSDimitry Andric   // Make sure we have a splat.
261349cc55cSDimitry Andric   Value *SplatOp = getSplatValue(OtherOp);
262349cc55cSDimitry Andric   if (!SplatOp)
263349cc55cSDimitry Andric     return false;
264349cc55cSDimitry Andric 
265349cc55cSDimitry Andric   // Recurse up the use-def chain.
266349cc55cSDimitry Andric   if (!matchStridedRecurrence(Index, L, Stride, BasePtr, Inc, Builder))
267349cc55cSDimitry Andric     return false;
268349cc55cSDimitry Andric 
269349cc55cSDimitry Andric   // Locate the Step and Start values from the recurrence.
270349cc55cSDimitry Andric   unsigned StepIndex = Inc->getOperand(0) == BasePtr ? 1 : 0;
271349cc55cSDimitry Andric   unsigned StartBlock = BasePtr->getOperand(0) == Inc ? 1 : 0;
272349cc55cSDimitry Andric   Value *Step = Inc->getOperand(StepIndex);
273349cc55cSDimitry Andric   Value *Start = BasePtr->getOperand(StartBlock);
274349cc55cSDimitry Andric 
275349cc55cSDimitry Andric   // We need to adjust the start value in the preheader.
276349cc55cSDimitry Andric   Builder.SetInsertPoint(
277349cc55cSDimitry Andric       BasePtr->getIncomingBlock(StartBlock)->getTerminator());
278349cc55cSDimitry Andric   Builder.SetCurrentDebugLocation(DebugLoc());
279349cc55cSDimitry Andric 
280349cc55cSDimitry Andric   switch (BO->getOpcode()) {
281349cc55cSDimitry Andric   default:
282349cc55cSDimitry Andric     llvm_unreachable("Unexpected opcode!");
283349cc55cSDimitry Andric   case Instruction::Add:
284349cc55cSDimitry Andric   case Instruction::Or: {
285349cc55cSDimitry Andric     // An add only affects the start value. It's ok to do this for Or because
286349cc55cSDimitry Andric     // we already checked that there are no common set bits.
287349cc55cSDimitry Andric 
288349cc55cSDimitry Andric     // If the start value is Zero, just take the SplatOp.
289349cc55cSDimitry Andric     if (isa<ConstantInt>(Start) && cast<ConstantInt>(Start)->isZero())
290349cc55cSDimitry Andric       Start = SplatOp;
291349cc55cSDimitry Andric     else
292349cc55cSDimitry Andric       Start = Builder.CreateAdd(Start, SplatOp, "start");
293349cc55cSDimitry Andric     BasePtr->setIncomingValue(StartBlock, Start);
294349cc55cSDimitry Andric     break;
295349cc55cSDimitry Andric   }
296349cc55cSDimitry Andric   case Instruction::Mul: {
297349cc55cSDimitry Andric     // If the start is zero we don't need to multiply.
298349cc55cSDimitry Andric     if (!isa<ConstantInt>(Start) || !cast<ConstantInt>(Start)->isZero())
299349cc55cSDimitry Andric       Start = Builder.CreateMul(Start, SplatOp, "start");
300349cc55cSDimitry Andric 
301349cc55cSDimitry Andric     Step = Builder.CreateMul(Step, SplatOp, "step");
302349cc55cSDimitry Andric 
303349cc55cSDimitry Andric     // If the Stride is 1 just take the SplatOpt.
304349cc55cSDimitry Andric     if (isa<ConstantInt>(Stride) && cast<ConstantInt>(Stride)->isOne())
305349cc55cSDimitry Andric       Stride = SplatOp;
306349cc55cSDimitry Andric     else
307349cc55cSDimitry Andric       Stride = Builder.CreateMul(Stride, SplatOp, "stride");
308349cc55cSDimitry Andric     Inc->setOperand(StepIndex, Step);
309349cc55cSDimitry Andric     BasePtr->setIncomingValue(StartBlock, Start);
310349cc55cSDimitry Andric     break;
311349cc55cSDimitry Andric   }
312349cc55cSDimitry Andric   case Instruction::Shl: {
313349cc55cSDimitry Andric     // If the start is zero we don't need to shift.
314349cc55cSDimitry Andric     if (!isa<ConstantInt>(Start) || !cast<ConstantInt>(Start)->isZero())
315349cc55cSDimitry Andric       Start = Builder.CreateShl(Start, SplatOp, "start");
316349cc55cSDimitry Andric     Step = Builder.CreateShl(Step, SplatOp, "step");
317349cc55cSDimitry Andric     Stride = Builder.CreateShl(Stride, SplatOp, "stride");
318349cc55cSDimitry Andric     Inc->setOperand(StepIndex, Step);
319349cc55cSDimitry Andric     BasePtr->setIncomingValue(StartBlock, Start);
320349cc55cSDimitry Andric     break;
321349cc55cSDimitry Andric   }
322349cc55cSDimitry Andric   }
323349cc55cSDimitry Andric 
324349cc55cSDimitry Andric   return true;
325349cc55cSDimitry Andric }
326349cc55cSDimitry Andric 
327349cc55cSDimitry Andric std::pair<Value *, Value *>
328349cc55cSDimitry Andric RISCVGatherScatterLowering::determineBaseAndStride(GetElementPtrInst *GEP,
329349cc55cSDimitry Andric                                                    IRBuilder<> &Builder) {
330349cc55cSDimitry Andric 
331*81ad6265SDimitry Andric   auto I = StridedAddrs.find(GEP);
332*81ad6265SDimitry Andric   if (I != StridedAddrs.end())
333*81ad6265SDimitry Andric     return I->second;
334*81ad6265SDimitry Andric 
335349cc55cSDimitry Andric   SmallVector<Value *, 2> Ops(GEP->operands());
336349cc55cSDimitry Andric 
337349cc55cSDimitry Andric   // Base pointer needs to be a scalar.
338349cc55cSDimitry Andric   if (Ops[0]->getType()->isVectorTy())
339349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
340349cc55cSDimitry Andric 
341*81ad6265SDimitry Andric   // Make sure we're in a loop and that has a pre-header and a single latch.
342349cc55cSDimitry Andric   Loop *L = LI->getLoopFor(GEP->getParent());
343*81ad6265SDimitry Andric   if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
344349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
345349cc55cSDimitry Andric 
346349cc55cSDimitry Andric   Optional<unsigned> VecOperand;
347349cc55cSDimitry Andric   unsigned TypeScale = 0;
348349cc55cSDimitry Andric 
349349cc55cSDimitry Andric   // Look for a vector operand and scale.
350349cc55cSDimitry Andric   gep_type_iterator GTI = gep_type_begin(GEP);
351349cc55cSDimitry Andric   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
352349cc55cSDimitry Andric     if (!Ops[i]->getType()->isVectorTy())
353349cc55cSDimitry Andric       continue;
354349cc55cSDimitry Andric 
355349cc55cSDimitry Andric     if (VecOperand)
356349cc55cSDimitry Andric       return std::make_pair(nullptr, nullptr);
357349cc55cSDimitry Andric 
358349cc55cSDimitry Andric     VecOperand = i;
359349cc55cSDimitry Andric 
360349cc55cSDimitry Andric     TypeSize TS = DL->getTypeAllocSize(GTI.getIndexedType());
361349cc55cSDimitry Andric     if (TS.isScalable())
362349cc55cSDimitry Andric       return std::make_pair(nullptr, nullptr);
363349cc55cSDimitry Andric 
364349cc55cSDimitry Andric     TypeScale = TS.getFixedSize();
365349cc55cSDimitry Andric   }
366349cc55cSDimitry Andric 
367349cc55cSDimitry Andric   // We need to find a vector index to simplify.
368349cc55cSDimitry Andric   if (!VecOperand)
369349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
370349cc55cSDimitry Andric 
371349cc55cSDimitry Andric   // We can't extract the stride if the arithmetic is done at a different size
372349cc55cSDimitry Andric   // than the pointer type. Adding the stride later may not wrap correctly.
373349cc55cSDimitry Andric   // Technically we could handle wider indices, but I don't expect that in
374349cc55cSDimitry Andric   // practice.
375349cc55cSDimitry Andric   Value *VecIndex = Ops[*VecOperand];
376349cc55cSDimitry Andric   Type *VecIntPtrTy = DL->getIntPtrType(GEP->getType());
377349cc55cSDimitry Andric   if (VecIndex->getType() != VecIntPtrTy)
378349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
379349cc55cSDimitry Andric 
380349cc55cSDimitry Andric   Value *Stride;
381349cc55cSDimitry Andric   BinaryOperator *Inc;
382349cc55cSDimitry Andric   PHINode *BasePhi;
383349cc55cSDimitry Andric   if (!matchStridedRecurrence(VecIndex, L, Stride, BasePhi, Inc, Builder))
384349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
385349cc55cSDimitry Andric 
386349cc55cSDimitry Andric   assert(BasePhi->getNumIncomingValues() == 2 && "Expected 2 operand phi.");
387349cc55cSDimitry Andric   unsigned IncrementingBlock = BasePhi->getOperand(0) == Inc ? 0 : 1;
388349cc55cSDimitry Andric   assert(BasePhi->getIncomingValue(IncrementingBlock) == Inc &&
389349cc55cSDimitry Andric          "Expected one operand of phi to be Inc");
390349cc55cSDimitry Andric 
391349cc55cSDimitry Andric   Builder.SetInsertPoint(GEP);
392349cc55cSDimitry Andric 
393349cc55cSDimitry Andric   // Replace the vector index with the scalar phi and build a scalar GEP.
394349cc55cSDimitry Andric   Ops[*VecOperand] = BasePhi;
395349cc55cSDimitry Andric   Type *SourceTy = GEP->getSourceElementType();
396349cc55cSDimitry Andric   Value *BasePtr =
397349cc55cSDimitry Andric       Builder.CreateGEP(SourceTy, Ops[0], makeArrayRef(Ops).drop_front());
398349cc55cSDimitry Andric 
399349cc55cSDimitry Andric   // Final adjustments to stride should go in the start block.
400349cc55cSDimitry Andric   Builder.SetInsertPoint(
401349cc55cSDimitry Andric       BasePhi->getIncomingBlock(1 - IncrementingBlock)->getTerminator());
402349cc55cSDimitry Andric 
403349cc55cSDimitry Andric   // Convert stride to pointer size if needed.
404349cc55cSDimitry Andric   Type *IntPtrTy = DL->getIntPtrType(BasePtr->getType());
405349cc55cSDimitry Andric   assert(Stride->getType() == IntPtrTy && "Unexpected type");
406349cc55cSDimitry Andric 
407349cc55cSDimitry Andric   // Scale the stride by the size of the indexed type.
408349cc55cSDimitry Andric   if (TypeScale != 1)
409349cc55cSDimitry Andric     Stride = Builder.CreateMul(Stride, ConstantInt::get(IntPtrTy, TypeScale));
410349cc55cSDimitry Andric 
411*81ad6265SDimitry Andric   auto P = std::make_pair(BasePtr, Stride);
412*81ad6265SDimitry Andric   StridedAddrs[GEP] = P;
413*81ad6265SDimitry Andric   return P;
414349cc55cSDimitry Andric }
415349cc55cSDimitry Andric 
416349cc55cSDimitry Andric bool RISCVGatherScatterLowering::tryCreateStridedLoadStore(IntrinsicInst *II,
417349cc55cSDimitry Andric                                                            Type *DataType,
418349cc55cSDimitry Andric                                                            Value *Ptr,
419349cc55cSDimitry Andric                                                            Value *AlignOp) {
420349cc55cSDimitry Andric   // Make sure the operation will be supported by the backend.
421349cc55cSDimitry Andric   if (!isLegalTypeAndAlignment(DataType, AlignOp))
422349cc55cSDimitry Andric     return false;
423349cc55cSDimitry Andric 
424349cc55cSDimitry Andric   // Pointer should be a GEP.
425349cc55cSDimitry Andric   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
426349cc55cSDimitry Andric   if (!GEP)
427349cc55cSDimitry Andric     return false;
428349cc55cSDimitry Andric 
429349cc55cSDimitry Andric   IRBuilder<> Builder(GEP);
430349cc55cSDimitry Andric 
431349cc55cSDimitry Andric   Value *BasePtr, *Stride;
432349cc55cSDimitry Andric   std::tie(BasePtr, Stride) = determineBaseAndStride(GEP, Builder);
433349cc55cSDimitry Andric   if (!BasePtr)
434349cc55cSDimitry Andric     return false;
435349cc55cSDimitry Andric   assert(Stride != nullptr);
436349cc55cSDimitry Andric 
437349cc55cSDimitry Andric   Builder.SetInsertPoint(II);
438349cc55cSDimitry Andric 
439349cc55cSDimitry Andric   CallInst *Call;
440349cc55cSDimitry Andric   if (II->getIntrinsicID() == Intrinsic::masked_gather)
441349cc55cSDimitry Andric     Call = Builder.CreateIntrinsic(
442349cc55cSDimitry Andric         Intrinsic::riscv_masked_strided_load,
443349cc55cSDimitry Andric         {DataType, BasePtr->getType(), Stride->getType()},
444349cc55cSDimitry Andric         {II->getArgOperand(3), BasePtr, Stride, II->getArgOperand(2)});
445349cc55cSDimitry Andric   else
446349cc55cSDimitry Andric     Call = Builder.CreateIntrinsic(
447349cc55cSDimitry Andric         Intrinsic::riscv_masked_strided_store,
448349cc55cSDimitry Andric         {DataType, BasePtr->getType(), Stride->getType()},
449349cc55cSDimitry Andric         {II->getArgOperand(0), BasePtr, Stride, II->getArgOperand(3)});
450349cc55cSDimitry Andric 
451349cc55cSDimitry Andric   Call->takeName(II);
452349cc55cSDimitry Andric   II->replaceAllUsesWith(Call);
453349cc55cSDimitry Andric   II->eraseFromParent();
454349cc55cSDimitry Andric 
455349cc55cSDimitry Andric   if (GEP->use_empty())
456349cc55cSDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(GEP);
457349cc55cSDimitry Andric 
458349cc55cSDimitry Andric   return true;
459349cc55cSDimitry Andric }
460349cc55cSDimitry Andric 
461349cc55cSDimitry Andric bool RISCVGatherScatterLowering::runOnFunction(Function &F) {
462349cc55cSDimitry Andric   if (skipFunction(F))
463349cc55cSDimitry Andric     return false;
464349cc55cSDimitry Andric 
465349cc55cSDimitry Andric   auto &TPC = getAnalysis<TargetPassConfig>();
466349cc55cSDimitry Andric   auto &TM = TPC.getTM<RISCVTargetMachine>();
467349cc55cSDimitry Andric   ST = &TM.getSubtarget<RISCVSubtarget>(F);
468349cc55cSDimitry Andric   if (!ST->hasVInstructions() || !ST->useRVVForFixedLengthVectors())
469349cc55cSDimitry Andric     return false;
470349cc55cSDimitry Andric 
471349cc55cSDimitry Andric   TLI = ST->getTargetLowering();
472349cc55cSDimitry Andric   DL = &F.getParent()->getDataLayout();
473349cc55cSDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
474349cc55cSDimitry Andric 
475*81ad6265SDimitry Andric   StridedAddrs.clear();
476*81ad6265SDimitry Andric 
477349cc55cSDimitry Andric   SmallVector<IntrinsicInst *, 4> Gathers;
478349cc55cSDimitry Andric   SmallVector<IntrinsicInst *, 4> Scatters;
479349cc55cSDimitry Andric 
480349cc55cSDimitry Andric   bool Changed = false;
481349cc55cSDimitry Andric 
482349cc55cSDimitry Andric   for (BasicBlock &BB : F) {
483349cc55cSDimitry Andric     for (Instruction &I : BB) {
484349cc55cSDimitry Andric       IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
485349cc55cSDimitry Andric       if (II && II->getIntrinsicID() == Intrinsic::masked_gather &&
486349cc55cSDimitry Andric           isa<FixedVectorType>(II->getType())) {
487349cc55cSDimitry Andric         Gathers.push_back(II);
488349cc55cSDimitry Andric       } else if (II && II->getIntrinsicID() == Intrinsic::masked_scatter &&
489349cc55cSDimitry Andric                  isa<FixedVectorType>(II->getArgOperand(0)->getType())) {
490349cc55cSDimitry Andric         Scatters.push_back(II);
491349cc55cSDimitry Andric       }
492349cc55cSDimitry Andric     }
493349cc55cSDimitry Andric   }
494349cc55cSDimitry Andric 
495349cc55cSDimitry Andric   // Rewrite gather/scatter to form strided load/store if possible.
496349cc55cSDimitry Andric   for (auto *II : Gathers)
497349cc55cSDimitry Andric     Changed |= tryCreateStridedLoadStore(
498349cc55cSDimitry Andric         II, II->getType(), II->getArgOperand(0), II->getArgOperand(1));
499349cc55cSDimitry Andric   for (auto *II : Scatters)
500349cc55cSDimitry Andric     Changed |=
501349cc55cSDimitry Andric         tryCreateStridedLoadStore(II, II->getArgOperand(0)->getType(),
502349cc55cSDimitry Andric                                   II->getArgOperand(1), II->getArgOperand(2));
503349cc55cSDimitry Andric 
504349cc55cSDimitry Andric   // Remove any dead phis.
505349cc55cSDimitry Andric   while (!MaybeDeadPHIs.empty()) {
506349cc55cSDimitry Andric     if (auto *Phi = dyn_cast_or_null<PHINode>(MaybeDeadPHIs.pop_back_val()))
507349cc55cSDimitry Andric       RecursivelyDeleteDeadPHINode(Phi);
508349cc55cSDimitry Andric   }
509349cc55cSDimitry Andric 
510349cc55cSDimitry Andric   return Changed;
511349cc55cSDimitry Andric }
512