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 #include <cmath>
15 using namespace llvm;
16 
17 #define DEBUG_TYPE "riscvtti"
18 
19 static cl::opt<unsigned> RVVRegisterWidthLMUL(
20     "riscv-v-register-bit-width-lmul",
21     cl::desc(
22         "The LMUL to use for getRegisterBitWidth queries. Affects LMUL used "
23         "by autovectorized code. Fractional LMULs are not supported."),
24     cl::init(1), cl::Hidden);
25 
26 InstructionCost RISCVTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
27                                             TTI::TargetCostKind CostKind) {
28   assert(Ty->isIntegerTy() &&
29          "getIntImmCost can only estimate cost of materialising integers");
30 
31   // We have a Zero register, so 0 is always free.
32   if (Imm == 0)
33     return TTI::TCC_Free;
34 
35   // Otherwise, we check how many instructions it will take to materialise.
36   const DataLayout &DL = getDataLayout();
37   return RISCVMatInt::getIntMatCost(Imm, DL.getTypeSizeInBits(Ty),
38                                     getST()->getFeatureBits());
39 }
40 
41 InstructionCost RISCVTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
42                                                 const APInt &Imm, Type *Ty,
43                                                 TTI::TargetCostKind CostKind,
44                                                 Instruction *Inst) {
45   assert(Ty->isIntegerTy() &&
46          "getIntImmCost can only estimate cost of materialising integers");
47 
48   // We have a Zero register, so 0 is always free.
49   if (Imm == 0)
50     return TTI::TCC_Free;
51 
52   // Some instructions in RISC-V can take a 12-bit immediate. Some of these are
53   // commutative, in others the immediate comes from a specific argument index.
54   bool Takes12BitImm = false;
55   unsigned ImmArgIdx = ~0U;
56 
57   switch (Opcode) {
58   case Instruction::GetElementPtr:
59     // Never hoist any arguments to a GetElementPtr. CodeGenPrepare will
60     // split up large offsets in GEP into better parts than ConstantHoisting
61     // can.
62     return TTI::TCC_Free;
63   case Instruction::And:
64     // zext.h
65     if (Imm == UINT64_C(0xffff) && ST->hasStdExtZbb())
66       return TTI::TCC_Free;
67     // zext.w
68     if (Imm == UINT64_C(0xffffffff) && ST->hasStdExtZbb())
69       return TTI::TCC_Free;
70     LLVM_FALLTHROUGH;
71   case Instruction::Add:
72   case Instruction::Or:
73   case Instruction::Xor:
74   case Instruction::Mul:
75     Takes12BitImm = true;
76     break;
77   case Instruction::Sub:
78   case Instruction::Shl:
79   case Instruction::LShr:
80   case Instruction::AShr:
81     Takes12BitImm = true;
82     ImmArgIdx = 1;
83     break;
84   default:
85     break;
86   }
87 
88   if (Takes12BitImm) {
89     // Check immediate is the correct argument...
90     if (Instruction::isCommutative(Opcode) || Idx == ImmArgIdx) {
91       // ... and fits into the 12-bit immediate.
92       if (Imm.getMinSignedBits() <= 64 &&
93           getTLI()->isLegalAddImmediate(Imm.getSExtValue())) {
94         return TTI::TCC_Free;
95       }
96     }
97 
98     // Otherwise, use the full materialisation cost.
99     return getIntImmCost(Imm, Ty, CostKind);
100   }
101 
102   // By default, prevent hoisting.
103   return TTI::TCC_Free;
104 }
105 
106 InstructionCost
107 RISCVTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
108                                   const APInt &Imm, Type *Ty,
109                                   TTI::TargetCostKind CostKind) {
110   // Prevent hoisting in unknown cases.
111   return TTI::TCC_Free;
112 }
113 
114 TargetTransformInfo::PopcntSupportKind
115 RISCVTTIImpl::getPopcntSupport(unsigned TyWidth) {
116   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
117   return ST->hasStdExtZbb() ? TTI::PSK_FastHardware : TTI::PSK_Software;
118 }
119 
120 bool RISCVTTIImpl::shouldExpandReduction(const IntrinsicInst *II) const {
121   // Currently, the ExpandReductions pass can't expand scalable-vector
122   // reductions, but we still request expansion as RVV doesn't support certain
123   // reductions and the SelectionDAG can't legalize them either.
124   switch (II->getIntrinsicID()) {
125   default:
126     return false;
127   // These reductions have no equivalent in RVV
128   case Intrinsic::vector_reduce_mul:
129   case Intrinsic::vector_reduce_fmul:
130     return true;
131   }
132 }
133 
134 Optional<unsigned> RISCVTTIImpl::getMaxVScale() const {
135   if (ST->hasVInstructions())
136     return ST->getRealMaxVLen() / RISCV::RVVBitsPerBlock;
137   return BaseT::getMaxVScale();
138 }
139 
140 TypeSize
141 RISCVTTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
142   unsigned LMUL = PowerOf2Floor(
143       std::max<unsigned>(std::min<unsigned>(RVVRegisterWidthLMUL, 8), 1));
144   switch (K) {
145   case TargetTransformInfo::RGK_Scalar:
146     return TypeSize::getFixed(ST->getXLen());
147   case TargetTransformInfo::RGK_FixedWidthVector:
148     return TypeSize::getFixed(
149         ST->useRVVForFixedLengthVectors() ? LMUL * ST->getRealMinVLen() : 0);
150   case TargetTransformInfo::RGK_ScalableVector:
151     return TypeSize::getScalable(
152         ST->hasVInstructions() ? LMUL * RISCV::RVVBitsPerBlock : 0);
153   }
154 
155   llvm_unreachable("Unsupported register kind");
156 }
157 
158 InstructionCost RISCVTTIImpl::getSpliceCost(VectorType *Tp, int Index) {
159   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
160 
161   unsigned Cost = 2; // vslidedown+vslideup.
162   // TODO: LMUL should increase cost.
163   // TODO: Multiplying by LT.first implies this legalizes into multiple copies
164   // of similar code, but I think we expand through memory.
165   return Cost * LT.first;
166 }
167 
168 InstructionCost RISCVTTIImpl::getShuffleCost(TTI::ShuffleKind Kind,
169                                              VectorType *Tp, ArrayRef<int> Mask,
170                                              int Index, VectorType *SubTp,
171                                              ArrayRef<const Value *> Args) {
172   if (isa<ScalableVectorType>(Tp)) {
173     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
174     switch (Kind) {
175     default:
176       // Fallthrough to generic handling.
177       // TODO: Most of these cases will return getInvalid in generic code, and
178       // must be implemented here.
179       break;
180     case TTI::SK_Broadcast: {
181       return LT.first * 1;
182     }
183     case TTI::SK_Splice:
184       return getSpliceCost(Tp, Index);
185     case TTI::SK_Reverse:
186       // Most of the cost here is producing the vrgather index register
187       // Example sequence:
188       //   csrr a0, vlenb
189       //   srli a0, a0, 3
190       //   addi a0, a0, -1
191       //   vsetvli a1, zero, e8, mf8, ta, mu (ignored)
192       //   vid.v v9
193       //   vrsub.vx v10, v9, a0
194       //   vrgather.vv v9, v8, v10
195       return LT.first * 6;
196     }
197   }
198 
199   return BaseT::getShuffleCost(Kind, Tp, Mask, Index, SubTp);
200 }
201 
202 InstructionCost
203 RISCVTTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
204                                     unsigned AddressSpace,
205                                     TTI::TargetCostKind CostKind) {
206   if (!isa<ScalableVectorType>(Src))
207     return BaseT::getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
208                                         CostKind);
209 
210   return getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, CostKind);
211 }
212 
213 InstructionCost RISCVTTIImpl::getGatherScatterOpCost(
214     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
215     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) {
216   if (CostKind != TTI::TCK_RecipThroughput)
217     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
218                                          Alignment, CostKind, I);
219 
220   if ((Opcode == Instruction::Load &&
221        !isLegalMaskedGather(DataTy, Align(Alignment))) ||
222       (Opcode == Instruction::Store &&
223        !isLegalMaskedScatter(DataTy, Align(Alignment))))
224     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
225                                          Alignment, CostKind, I);
226 
227   // Cost is proportional to the number of memory operations implied.  For
228   // scalable vectors, we use an upper bound on that number since we don't
229   // know exactly what VL will be.
230   auto &VTy = *cast<VectorType>(DataTy);
231   InstructionCost MemOpCost = getMemoryOpCost(Opcode, VTy.getElementType(),
232                                               Alignment, 0, CostKind, I);
233   if (isa<ScalableVectorType>(VTy)) {
234     const unsigned EltSize = DL.getTypeSizeInBits(VTy.getElementType());
235     const unsigned MinSize = DL.getTypeSizeInBits(&VTy).getKnownMinValue();
236     const unsigned VectorBitsMax = ST->getRealMaxVLen();
237     const unsigned MaxVLMAX =
238       RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
239     return MaxVLMAX * MemOpCost;
240   }
241   unsigned NumLoads = cast<FixedVectorType>(VTy).getNumElements();
242   return NumLoads * MemOpCost;
243 }
244 
245 InstructionCost
246 RISCVTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
247                                     TTI::TargetCostKind CostKind) {
248   auto *RetTy = ICA.getReturnType();
249   switch (ICA.getID()) {
250   // TODO: add more intrinsic
251   case Intrinsic::experimental_stepvector: {
252     unsigned Cost = 1; // vid
253     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
254     return Cost + (LT.first - 1);
255   }
256   default:
257     break;
258   }
259   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
260 }
261 
262 InstructionCost RISCVTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst,
263                                                Type *Src,
264                                                TTI::CastContextHint CCH,
265                                                TTI::TargetCostKind CostKind,
266                                                const Instruction *I) {
267   if (isa<VectorType>(Dst) && isa<VectorType>(Src)) {
268     // FIXME: Need to compute legalizing cost for illegal types.
269     if (!isTypeLegal(Src) || !isTypeLegal(Dst))
270       return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
271 
272     // Skip if element size of Dst or Src is bigger than ELEN.
273     if (Src->getScalarSizeInBits() > ST->getELEN() ||
274         Dst->getScalarSizeInBits() > ST->getELEN())
275       return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
276 
277     int ISD = TLI->InstructionOpcodeToISD(Opcode);
278     assert(ISD && "Invalid opcode");
279 
280     // FIXME: Need to consider vsetvli and lmul.
281     int PowDiff = (int)Log2_32(Dst->getScalarSizeInBits()) -
282                   (int)Log2_32(Src->getScalarSizeInBits());
283     switch (ISD) {
284     case ISD::SIGN_EXTEND:
285     case ISD::ZERO_EXTEND:
286       return 1;
287     case ISD::TRUNCATE:
288     case ISD::FP_EXTEND:
289     case ISD::FP_ROUND:
290       // Counts of narrow/widen instructions.
291       return std::abs(PowDiff);
292     case ISD::FP_TO_SINT:
293     case ISD::FP_TO_UINT:
294     case ISD::SINT_TO_FP:
295     case ISD::UINT_TO_FP:
296       if (std::abs(PowDiff) <= 1)
297         return 1;
298       // Backend could lower (v[sz]ext i8 to double) to vfcvt(v[sz]ext.f8 i8),
299       // so it only need two conversion.
300       if (Src->isIntOrIntVectorTy())
301         return 2;
302       // Counts of narrow/widen instructions.
303       return std::abs(PowDiff);
304     }
305   }
306   return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
307 }
308 
309 InstructionCost
310 RISCVTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
311                                      bool IsUnsigned,
312                                      TTI::TargetCostKind CostKind) {
313   // FIXME: Only supporting fixed vectors for now.
314   if (!isa<FixedVectorType>(Ty))
315     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
316 
317   if (!ST->useRVVForFixedLengthVectors())
318     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
319 
320   // Skip if scalar size of Ty is bigger than ELEN.
321   if (Ty->getScalarSizeInBits() > ST->getELEN())
322     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
323 
324   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
325   if (Ty->getElementType()->isIntegerTy(1))
326     // vcpop sequences, see vreduction-mask.ll.  umax, smin actually only
327     // cost 2, but we don't have enough info here so we slightly over cost.
328     return (LT.first - 1) + 3;
329 
330   // IR Reduction is composed by two vmv and one rvv reduction instruction.
331   InstructionCost BaseCost = 2;
332   unsigned VL = cast<FixedVectorType>(Ty)->getNumElements();
333   return (LT.first - 1) + BaseCost + Log2_32_Ceil(VL);
334 }
335 
336 InstructionCost
337 RISCVTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
338                                          Optional<FastMathFlags> FMF,
339                                          TTI::TargetCostKind CostKind) {
340   // FIXME: Only supporting fixed vectors for now.
341   if (!isa<FixedVectorType>(Ty))
342     return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
343 
344   if (!ST->useRVVForFixedLengthVectors())
345     return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
346 
347   // Skip if scalar size of Ty is bigger than ELEN.
348   if (Ty->getScalarSizeInBits() > ST->getELEN())
349     return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
350 
351   int ISD = TLI->InstructionOpcodeToISD(Opcode);
352   assert(ISD && "Invalid opcode");
353 
354   if (ISD != ISD::ADD && ISD != ISD::OR && ISD != ISD::XOR && ISD != ISD::AND &&
355       ISD != ISD::FADD)
356     return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
357 
358   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
359   if (Ty->getElementType()->isIntegerTy(1))
360     // vcpop sequences, see vreduction-mask.ll
361     return (LT.first - 1) + (ISD == ISD::AND ? 3 : 2);
362 
363   // IR Reduction is composed by two vmv and one rvv reduction instruction.
364   InstructionCost BaseCost = 2;
365   unsigned VL = cast<FixedVectorType>(Ty)->getNumElements();
366   if (TTI::requiresOrderedReduction(FMF))
367     return (LT.first - 1) + BaseCost + VL;
368   return (LT.first - 1) + BaseCost + Log2_32_Ceil(VL);
369 }
370 
371 void RISCVTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
372                                            TTI::UnrollingPreferences &UP,
373                                            OptimizationRemarkEmitter *ORE) {
374   // TODO: More tuning on benchmarks and metrics with changes as needed
375   //       would apply to all settings below to enable performance.
376 
377 
378   if (ST->enableDefaultUnroll())
379     return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP, ORE);
380 
381   // Enable Upper bound unrolling universally, not dependant upon the conditions
382   // below.
383   UP.UpperBound = true;
384 
385   // Disable loop unrolling for Oz and Os.
386   UP.OptSizeThreshold = 0;
387   UP.PartialOptSizeThreshold = 0;
388   if (L->getHeader()->getParent()->hasOptSize())
389     return;
390 
391   SmallVector<BasicBlock *, 4> ExitingBlocks;
392   L->getExitingBlocks(ExitingBlocks);
393   LLVM_DEBUG(dbgs() << "Loop has:\n"
394                     << "Blocks: " << L->getNumBlocks() << "\n"
395                     << "Exit blocks: " << ExitingBlocks.size() << "\n");
396 
397   // Only allow another exit other than the latch. This acts as an early exit
398   // as it mirrors the profitability calculation of the runtime unroller.
399   if (ExitingBlocks.size() > 2)
400     return;
401 
402   // Limit the CFG of the loop body for targets with a branch predictor.
403   // Allowing 4 blocks permits if-then-else diamonds in the body.
404   if (L->getNumBlocks() > 4)
405     return;
406 
407   // Don't unroll vectorized loops, including the remainder loop
408   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
409     return;
410 
411   // Scan the loop: don't unroll loops with calls as this could prevent
412   // inlining.
413   InstructionCost Cost = 0;
414   for (auto *BB : L->getBlocks()) {
415     for (auto &I : *BB) {
416       // Initial setting - Don't unroll loops containing vectorized
417       // instructions.
418       if (I.getType()->isVectorTy())
419         return;
420 
421       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
422         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
423           if (!isLoweredToCall(F))
424             continue;
425         }
426         return;
427       }
428 
429       SmallVector<const Value *> Operands(I.operand_values());
430       Cost +=
431           getUserCost(&I, Operands, TargetTransformInfo::TCK_SizeAndLatency);
432     }
433   }
434 
435   LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
436 
437   UP.Partial = true;
438   UP.Runtime = true;
439   UP.UnrollRemainder = true;
440   UP.UnrollAndJam = true;
441   UP.UnrollAndJamInnerLoopThreshold = 60;
442 
443   // Force unrolling small loops can be very useful because of the branch
444   // taken cost of the backedge.
445   if (Cost < 12)
446     UP.Force = true;
447 }
448 
449 void RISCVTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
450                                          TTI::PeelingPreferences &PP) {
451   BaseT::getPeelingPreferences(L, SE, PP);
452 }
453 
454 unsigned RISCVTTIImpl::getRegUsageForType(Type *Ty) {
455   TypeSize Size = Ty->getPrimitiveSizeInBits();
456   if (Ty->isVectorTy()) {
457     if (Size.isScalable() && ST->hasVInstructions())
458       return divideCeil(Size.getKnownMinValue(), RISCV::RVVBitsPerBlock);
459 
460     if (ST->useRVVForFixedLengthVectors())
461       return divideCeil(Size, ST->getRealMinVLen());
462   }
463 
464   return BaseT::getRegUsageForType(Ty);
465 }
466