1 //===-- RISCVTargetTransformInfo.cpp - RISC-V specific TTI ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "RISCVTargetTransformInfo.h"
10 #include "MCTargetDesc/RISCVMatInt.h"
11 #include "llvm/Analysis/TargetTransformInfo.h"
12 #include "llvm/CodeGen/BasicTTIImpl.h"
13 #include "llvm/CodeGen/TargetLowering.h"
14 using namespace llvm;
15 
16 #define DEBUG_TYPE "riscvtti"
17 
18 static cl::opt<unsigned> RVVRegisterWidthLMUL(
19     "riscv-v-register-bit-width-lmul",
20     cl::desc(
21         "The LMUL to use for getRegisterBitWidth queries. Affects LMUL used "
22         "by autovectorized code. Fractional LMULs are not supported."),
23     cl::init(1), cl::Hidden);
24 
25 InstructionCost RISCVTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
26                                             TTI::TargetCostKind CostKind) {
27   assert(Ty->isIntegerTy() &&
28          "getIntImmCost can only estimate cost of materialising integers");
29 
30   // We have a Zero register, so 0 is always free.
31   if (Imm == 0)
32     return TTI::TCC_Free;
33 
34   // Otherwise, we check how many instructions it will take to materialise.
35   const DataLayout &DL = getDataLayout();
36   return RISCVMatInt::getIntMatCost(Imm, DL.getTypeSizeInBits(Ty),
37                                     getST()->getFeatureBits());
38 }
39 
40 InstructionCost RISCVTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
41                                                 const APInt &Imm, Type *Ty,
42                                                 TTI::TargetCostKind CostKind,
43                                                 Instruction *Inst) {
44   assert(Ty->isIntegerTy() &&
45          "getIntImmCost can only estimate cost of materialising integers");
46 
47   // We have a Zero register, so 0 is always free.
48   if (Imm == 0)
49     return TTI::TCC_Free;
50 
51   // Some instructions in RISC-V can take a 12-bit immediate. Some of these are
52   // commutative, in others the immediate comes from a specific argument index.
53   bool Takes12BitImm = false;
54   unsigned ImmArgIdx = ~0U;
55 
56   switch (Opcode) {
57   case Instruction::GetElementPtr:
58     // Never hoist any arguments to a GetElementPtr. CodeGenPrepare will
59     // split up large offsets in GEP into better parts than ConstantHoisting
60     // can.
61     return TTI::TCC_Free;
62   case Instruction::And:
63     // zext.h
64     if (Imm == UINT64_C(0xffff) && ST->hasStdExtZbb())
65       return TTI::TCC_Free;
66     // zext.w
67     if (Imm == UINT64_C(0xffffffff) && ST->hasStdExtZbb())
68       return TTI::TCC_Free;
69     LLVM_FALLTHROUGH;
70   case Instruction::Add:
71   case Instruction::Or:
72   case Instruction::Xor:
73   case Instruction::Mul:
74     Takes12BitImm = true;
75     break;
76   case Instruction::Sub:
77   case Instruction::Shl:
78   case Instruction::LShr:
79   case Instruction::AShr:
80     Takes12BitImm = true;
81     ImmArgIdx = 1;
82     break;
83   default:
84     break;
85   }
86 
87   if (Takes12BitImm) {
88     // Check immediate is the correct argument...
89     if (Instruction::isCommutative(Opcode) || Idx == ImmArgIdx) {
90       // ... and fits into the 12-bit immediate.
91       if (Imm.getMinSignedBits() <= 64 &&
92           getTLI()->isLegalAddImmediate(Imm.getSExtValue())) {
93         return TTI::TCC_Free;
94       }
95     }
96 
97     // Otherwise, use the full materialisation cost.
98     return getIntImmCost(Imm, Ty, CostKind);
99   }
100 
101   // By default, prevent hoisting.
102   return TTI::TCC_Free;
103 }
104 
105 InstructionCost
106 RISCVTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
107                                   const APInt &Imm, Type *Ty,
108                                   TTI::TargetCostKind CostKind) {
109   // Prevent hoisting in unknown cases.
110   return TTI::TCC_Free;
111 }
112 
113 TargetTransformInfo::PopcntSupportKind
114 RISCVTTIImpl::getPopcntSupport(unsigned TyWidth) {
115   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
116   return ST->hasStdExtZbb() ? TTI::PSK_FastHardware : TTI::PSK_Software;
117 }
118 
119 bool RISCVTTIImpl::shouldExpandReduction(const IntrinsicInst *II) const {
120   // Currently, the ExpandReductions pass can't expand scalable-vector
121   // reductions, but we still request expansion as RVV doesn't support certain
122   // reductions and the SelectionDAG can't legalize them either.
123   switch (II->getIntrinsicID()) {
124   default:
125     return false;
126   // These reductions have no equivalent in RVV
127   case Intrinsic::vector_reduce_mul:
128   case Intrinsic::vector_reduce_fmul:
129     return true;
130   }
131 }
132 
133 Optional<unsigned> RISCVTTIImpl::getMaxVScale() const {
134   // There is no assumption of the maximum vector length in V specification.
135   // We use the value specified by users as the maximum vector length.
136   // This function will use the assumed maximum vector length to get the
137   // maximum vscale for LoopVectorizer.
138   // If users do not specify the maximum vector length, we have no way to
139   // know whether the LoopVectorizer is safe to do or not.
140   // We only consider to use single vector register (LMUL = 1) to vectorize.
141   unsigned MaxVectorSizeInBits = ST->getMaxRVVVectorSizeInBits();
142   if (ST->hasVInstructions() && MaxVectorSizeInBits != 0)
143     return MaxVectorSizeInBits / RISCV::RVVBitsPerBlock;
144   return BaseT::getMaxVScale();
145 }
146 
147 TypeSize
148 RISCVTTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
149   unsigned LMUL = PowerOf2Floor(
150       std::max<unsigned>(std::min<unsigned>(RVVRegisterWidthLMUL, 8), 1));
151   switch (K) {
152   case TargetTransformInfo::RGK_Scalar:
153     return TypeSize::getFixed(ST->getXLen());
154   case TargetTransformInfo::RGK_FixedWidthVector:
155     return TypeSize::getFixed(
156         ST->hasVInstructions() ? LMUL * ST->getMinRVVVectorSizeInBits() : 0);
157   case TargetTransformInfo::RGK_ScalableVector:
158     return TypeSize::getScalable(
159         ST->hasVInstructions() ? LMUL * RISCV::RVVBitsPerBlock : 0);
160   }
161 
162   llvm_unreachable("Unsupported register kind");
163 }
164 
165 InstructionCost RISCVTTIImpl::getSpliceCost(VectorType *Tp, int Index) {
166   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
167 
168   unsigned Cost = 2; // vslidedown+vslideup.
169   // TODO: LMUL should increase cost.
170   // TODO: Multiplying by LT.first implies this legalizes into multiple copies
171   // of similar code, but I think we expand through memory.
172   return Cost * LT.first;
173 }
174 
175 InstructionCost RISCVTTIImpl::getShuffleCost(TTI::ShuffleKind Kind,
176                                              VectorType *Tp, ArrayRef<int> Mask,
177                                              int Index, VectorType *SubTp) {
178   if (Kind == TTI::SK_Splice && isa<ScalableVectorType>(Tp))
179     return getSpliceCost(Tp, Index);
180   return BaseT::getShuffleCost(Kind, Tp, Mask, Index, SubTp);
181 }
182 
183 InstructionCost RISCVTTIImpl::getGatherScatterOpCost(
184     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
185     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) {
186   if (CostKind != TTI::TCK_RecipThroughput)
187     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
188                                          Alignment, CostKind, I);
189 
190   if ((Opcode == Instruction::Load &&
191        !isLegalMaskedGather(DataTy, Align(Alignment))) ||
192       (Opcode == Instruction::Store &&
193        !isLegalMaskedScatter(DataTy, Align(Alignment))))
194     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
195                                          Alignment, CostKind, I);
196 
197   // FIXME: Only supporting fixed vectors for now.
198   if (!isa<FixedVectorType>(DataTy))
199     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
200                                          Alignment, CostKind, I);
201 
202   auto *VTy = cast<FixedVectorType>(DataTy);
203   unsigned NumLoads = VTy->getNumElements();
204   InstructionCost MemOpCost =
205       getMemoryOpCost(Opcode, VTy->getElementType(), Alignment, 0, CostKind, I);
206   return NumLoads * MemOpCost;
207 }
208 
209 void RISCVTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
210                                            TTI::UnrollingPreferences &UP,
211                                            OptimizationRemarkEmitter *ORE) {
212   // TODO: More tuning on benchmarks and metrics with changes as needed
213   //       would apply to all settings below to enable performance.
214 
215   // Support explicit targets enabled for SiFive with the unrolling preferences
216   // below
217   bool UseDefaultPreferences = true;
218   if (ST->getProcFamily() == RISCVSubtarget::SiFive7)
219     UseDefaultPreferences = false;
220 
221   if (UseDefaultPreferences)
222     return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP, ORE);
223 
224   // Enable Upper bound unrolling universally, not dependant upon the conditions
225   // below.
226   UP.UpperBound = true;
227 
228   // Disable loop unrolling for Oz and Os.
229   UP.OptSizeThreshold = 0;
230   UP.PartialOptSizeThreshold = 0;
231   if (L->getHeader()->getParent()->hasOptSize())
232     return;
233 
234   SmallVector<BasicBlock *, 4> ExitingBlocks;
235   L->getExitingBlocks(ExitingBlocks);
236   LLVM_DEBUG(dbgs() << "Loop has:\n"
237                     << "Blocks: " << L->getNumBlocks() << "\n"
238                     << "Exit blocks: " << ExitingBlocks.size() << "\n");
239 
240   // Only allow another exit other than the latch. This acts as an early exit
241   // as it mirrors the profitability calculation of the runtime unroller.
242   if (ExitingBlocks.size() > 2)
243     return;
244 
245   // Limit the CFG of the loop body for targets with a branch predictor.
246   // Allowing 4 blocks permits if-then-else diamonds in the body.
247   if (L->getNumBlocks() > 4)
248     return;
249 
250   // Don't unroll vectorized loops, including the remainder loop
251   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
252     return;
253 
254   // Scan the loop: don't unroll loops with calls as this could prevent
255   // inlining.
256   InstructionCost Cost = 0;
257   for (auto *BB : L->getBlocks()) {
258     for (auto &I : *BB) {
259       // Initial setting - Don't unroll loops containing vectorized
260       // instructions.
261       if (I.getType()->isVectorTy())
262         return;
263 
264       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
265         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
266           if (!isLoweredToCall(F))
267             continue;
268         }
269         return;
270       }
271 
272       SmallVector<const Value *> Operands(I.operand_values());
273       Cost +=
274           getUserCost(&I, Operands, TargetTransformInfo::TCK_SizeAndLatency);
275     }
276   }
277 
278   LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
279 
280   UP.Partial = true;
281   UP.Runtime = true;
282   UP.UnrollRemainder = true;
283   UP.UnrollAndJam = true;
284   UP.UnrollAndJamInnerLoopThreshold = 60;
285 
286   // Force unrolling small loops can be very useful because of the branch
287   // taken cost of the backedge.
288   if (Cost < 12)
289     UP.Force = true;
290 }
291 
292 void RISCVTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
293                                          TTI::PeelingPreferences &PP) {
294   BaseT::getPeelingPreferences(L, SE, PP);
295 }
296 
297 InstructionCost RISCVTTIImpl::getRegUsageForType(Type *Ty) {
298   TypeSize Size = Ty->getPrimitiveSizeInBits();
299   if (Ty->isVectorTy()) {
300     if (Size.isScalable() && ST->hasVInstructions())
301       return divideCeil(Size.getKnownMinValue(), RISCV::RVVBitsPerBlock);
302 
303     if (ST->useRVVForFixedLengthVectors())
304       return divideCeil(Size, ST->getMinRVVVectorSizeInBits());
305   }
306 
307   return BaseT::getRegUsageForType(Ty);
308 }
309