1 //===- HexagonTargetTransformInfo.cpp - Hexagon specific TTI pass ---------===//
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 /// \file
8 /// This file implements a TargetTransformInfo analysis pass specific to the
9 /// Hexagon target machine. It uses the target's detailed information to provide
10 /// more precise answers to certain TTI queries, while letting the target
11 /// independent and default TTI implementations handle the rest.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "HexagonTargetTransformInfo.h"
16 #include "HexagonSubtarget.h"
17 #include "llvm/Analysis/TargetTransformInfo.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/IR/InstrTypes.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/User.h"
22 #include "llvm/Support/Casting.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Transforms/Utils/LoopPeel.h"
25 #include "llvm/Transforms/Utils/UnrollLoop.h"
26 
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "hexagontti"
30 
31 static cl::opt<bool> HexagonAutoHVX("hexagon-autohvx", cl::init(false),
32   cl::Hidden, cl::desc("Enable loop vectorizer for HVX"));
33 
34 static cl::opt<bool> EmitLookupTables("hexagon-emit-lookup-tables",
35   cl::init(true), cl::Hidden,
36   cl::desc("Control lookup table emission on Hexagon target"));
37 
38 static cl::opt<bool> HexagonMaskedVMem("hexagon-masked-vmem", cl::init(true),
39   cl::Hidden, cl::desc("Enable masked loads/stores for HVX"));
40 
41 // Constant "cost factor" to make floating point operations more expensive
42 // in terms of vectorization cost. This isn't the best way, but it should
43 // do. Ultimately, the cost should use cycles.
44 static const unsigned FloatFactor = 4;
45 
46 bool HexagonTTIImpl::useHVX() const {
47   return ST.useHVXOps() && HexagonAutoHVX;
48 }
49 
50 unsigned HexagonTTIImpl::getTypeNumElements(Type *Ty) const {
51   if (auto *VTy = dyn_cast<FixedVectorType>(Ty))
52     return VTy->getNumElements();
53   assert((Ty->isIntegerTy() || Ty->isFloatingPointTy()) &&
54          "Expecting scalar type");
55   return 1;
56 }
57 
58 TargetTransformInfo::PopcntSupportKind
59 HexagonTTIImpl::getPopcntSupport(unsigned IntTyWidthInBit) const {
60   // Return fast hardware support as every input < 64 bits will be promoted
61   // to 64 bits.
62   return TargetTransformInfo::PSK_FastHardware;
63 }
64 
65 // The Hexagon target can unroll loops with run-time trip counts.
66 void HexagonTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
67                                              TTI::UnrollingPreferences &UP) {
68   UP.Runtime = UP.Partial = true;
69 }
70 
71 void HexagonTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
72                                            TTI::PeelingPreferences &PP) {
73   BaseT::getPeelingPreferences(L, SE, PP);
74   // Only try to peel innermost loops with small runtime trip counts.
75   if (L && L->isInnermost() && canPeel(L) &&
76       SE.getSmallConstantTripCount(L) == 0 &&
77       SE.getSmallConstantMaxTripCount(L) > 0 &&
78       SE.getSmallConstantMaxTripCount(L) <= 5) {
79     PP.PeelCount = 2;
80   }
81 }
82 
83 TTI::AddressingModeKind
84 HexagonTTIImpl::getPreferredAddressingMode(const Loop *L,
85                                            ScalarEvolution *SE) const {
86   return TTI::AMK_PostIndexed;
87 }
88 
89 /// --- Vector TTI begin ---
90 
91 unsigned HexagonTTIImpl::getNumberOfRegisters(bool Vector) const {
92   if (Vector)
93     return useHVX() ? 32 : 0;
94   return 32;
95 }
96 
97 unsigned HexagonTTIImpl::getMaxInterleaveFactor(unsigned VF) {
98   return useHVX() ? 2 : 1;
99 }
100 
101 TypeSize
102 HexagonTTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
103   switch (K) {
104   case TargetTransformInfo::RGK_Scalar:
105     return TypeSize::getFixed(32);
106   case TargetTransformInfo::RGK_FixedWidthVector:
107     return TypeSize::getFixed(getMinVectorRegisterBitWidth());
108   case TargetTransformInfo::RGK_ScalableVector:
109     return TypeSize::getScalable(0);
110   }
111 
112   llvm_unreachable("Unsupported register kind");
113 }
114 
115 unsigned HexagonTTIImpl::getMinVectorRegisterBitWidth() const {
116   return useHVX() ? ST.getVectorLength()*8 : 32;
117 }
118 
119 ElementCount HexagonTTIImpl::getMinimumVF(unsigned ElemWidth,
120                                           bool IsScalable) const {
121   assert(!IsScalable && "Scalable VFs are not supported for Hexagon");
122   return ElementCount::getFixed((8 * ST.getVectorLength()) / ElemWidth);
123 }
124 
125 unsigned HexagonTTIImpl::getScalarizationOverhead(VectorType *Ty,
126                                                   const APInt &DemandedElts,
127                                                   bool Insert, bool Extract) {
128   return BaseT::getScalarizationOverhead(Ty, DemandedElts, Insert, Extract);
129 }
130 
131 unsigned
132 HexagonTTIImpl::getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
133                                                  ArrayRef<Type *> Tys) {
134   return BaseT::getOperandsScalarizationOverhead(Args, Tys);
135 }
136 
137 InstructionCost HexagonTTIImpl::getCallInstrCost(Function *F, Type *RetTy,
138                                                  ArrayRef<Type *> Tys,
139                                                  TTI::TargetCostKind CostKind) {
140   return BaseT::getCallInstrCost(F, RetTy, Tys, CostKind);
141 }
142 
143 InstructionCost
144 HexagonTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
145                                       TTI::TargetCostKind CostKind) {
146   if (ICA.getID() == Intrinsic::bswap) {
147     std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, ICA.getReturnType());
148     return LT.first + 2;
149   }
150   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
151 }
152 
153 unsigned HexagonTTIImpl::getAddressComputationCost(Type *Tp,
154       ScalarEvolution *SE, const SCEV *S) {
155   return 0;
156 }
157 
158 InstructionCost HexagonTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
159                                                 MaybeAlign Alignment,
160                                                 unsigned AddressSpace,
161                                                 TTI::TargetCostKind CostKind,
162                                                 const Instruction *I) {
163   assert(Opcode == Instruction::Load || Opcode == Instruction::Store);
164   // TODO: Handle other cost kinds.
165   if (CostKind != TTI::TCK_RecipThroughput)
166     return 1;
167 
168   if (Opcode == Instruction::Store)
169     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
170                                   CostKind, I);
171 
172   if (Src->isVectorTy()) {
173     VectorType *VecTy = cast<VectorType>(Src);
174     unsigned VecWidth = VecTy->getPrimitiveSizeInBits().getFixedSize();
175     if (useHVX() && ST.isTypeForHVX(VecTy)) {
176       unsigned RegWidth =
177           getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
178               .getFixedSize();
179       assert(RegWidth && "Non-zero vector register width expected");
180       // Cost of HVX loads.
181       if (VecWidth % RegWidth == 0)
182         return VecWidth / RegWidth;
183       // Cost of constructing HVX vector from scalar loads
184       const Align RegAlign(RegWidth / 8);
185       if (!Alignment || *Alignment > RegAlign)
186         Alignment = RegAlign;
187       assert(Alignment);
188       unsigned AlignWidth = 8 * Alignment->value();
189       unsigned NumLoads = alignTo(VecWidth, AlignWidth) / AlignWidth;
190       return 3 * NumLoads;
191     }
192 
193     // Non-HVX vectors.
194     // Add extra cost for floating point types.
195     unsigned Cost =
196         VecTy->getElementType()->isFloatingPointTy() ? FloatFactor : 1;
197 
198     // At this point unspecified alignment is considered as Align(1).
199     const Align BoundAlignment = std::min(Alignment.valueOrOne(), Align(8));
200     unsigned AlignWidth = 8 * BoundAlignment.value();
201     unsigned NumLoads = alignTo(VecWidth, AlignWidth) / AlignWidth;
202     if (Alignment == Align(4) || Alignment == Align(8))
203       return Cost * NumLoads;
204     // Loads of less than 32 bits will need extra inserts to compose a vector.
205     assert(BoundAlignment <= Align(8));
206     unsigned LogA = Log2(BoundAlignment);
207     return (3 - LogA) * Cost * NumLoads;
208   }
209 
210   return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
211                                 CostKind, I);
212 }
213 
214 InstructionCost
215 HexagonTTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
216                                       Align Alignment, unsigned AddressSpace,
217                                       TTI::TargetCostKind CostKind) {
218   return BaseT::getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
219                                       CostKind);
220 }
221 
222 InstructionCost HexagonTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp,
223                                                ArrayRef<int> Mask, int Index,
224                                                Type *SubTp) {
225   return 1;
226 }
227 
228 InstructionCost HexagonTTIImpl::getGatherScatterOpCost(
229     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
230     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) {
231   return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
232                                        Alignment, CostKind, I);
233 }
234 
235 InstructionCost HexagonTTIImpl::getInterleavedMemoryOpCost(
236     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
237     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
238     bool UseMaskForCond, bool UseMaskForGaps) {
239   if (Indices.size() != Factor || UseMaskForCond || UseMaskForGaps)
240     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
241                                              Alignment, AddressSpace,
242                                              CostKind,
243                                              UseMaskForCond, UseMaskForGaps);
244   return getMemoryOpCost(Opcode, VecTy, MaybeAlign(Alignment), AddressSpace,
245                          CostKind);
246 }
247 
248 InstructionCost HexagonTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
249                                                    Type *CondTy,
250                                                    CmpInst::Predicate VecPred,
251                                                    TTI::TargetCostKind CostKind,
252                                                    const Instruction *I) {
253   if (ValTy->isVectorTy() && CostKind == TTI::TCK_RecipThroughput) {
254     std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, ValTy);
255     if (Opcode == Instruction::FCmp)
256       return LT.first + FloatFactor * getTypeNumElements(ValTy);
257   }
258   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
259 }
260 
261 InstructionCost HexagonTTIImpl::getArithmeticInstrCost(
262     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
263     TTI::OperandValueKind Opd1Info, TTI::OperandValueKind Opd2Info,
264     TTI::OperandValueProperties Opd1PropInfo,
265     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
266     const Instruction *CxtI) {
267   // TODO: Handle more cost kinds.
268   if (CostKind != TTI::TCK_RecipThroughput)
269     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
270                                          Opd2Info, Opd1PropInfo,
271                                          Opd2PropInfo, Args, CxtI);
272 
273   if (Ty->isVectorTy()) {
274     std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, Ty);
275     if (LT.second.isFloatingPoint())
276       return LT.first + FloatFactor * getTypeNumElements(Ty);
277   }
278   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, Opd2Info,
279                                        Opd1PropInfo, Opd2PropInfo, Args, CxtI);
280 }
281 
282 InstructionCost HexagonTTIImpl::getCastInstrCost(unsigned Opcode, Type *DstTy,
283                                                  Type *SrcTy,
284                                                  TTI::CastContextHint CCH,
285                                                  TTI::TargetCostKind CostKind,
286                                                  const Instruction *I) {
287   if (SrcTy->isFPOrFPVectorTy() || DstTy->isFPOrFPVectorTy()) {
288     unsigned SrcN = SrcTy->isFPOrFPVectorTy() ? getTypeNumElements(SrcTy) : 0;
289     unsigned DstN = DstTy->isFPOrFPVectorTy() ? getTypeNumElements(DstTy) : 0;
290 
291     std::pair<int, MVT> SrcLT = TLI.getTypeLegalizationCost(DL, SrcTy);
292     std::pair<int, MVT> DstLT = TLI.getTypeLegalizationCost(DL, DstTy);
293     unsigned Cost = std::max(SrcLT.first, DstLT.first) + FloatFactor * (SrcN + DstN);
294     // TODO: Allow non-throughput costs that aren't binary.
295     if (CostKind != TTI::TCK_RecipThroughput)
296       return Cost == 0 ? 0 : 1;
297     return Cost;
298   }
299   return 1;
300 }
301 
302 InstructionCost HexagonTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
303                                                    unsigned Index) {
304   Type *ElemTy = Val->isVectorTy() ? cast<VectorType>(Val)->getElementType()
305                                    : Val;
306   if (Opcode == Instruction::InsertElement) {
307     // Need two rotations for non-zero index.
308     unsigned Cost = (Index != 0) ? 2 : 0;
309     if (ElemTy->isIntegerTy(32))
310       return Cost;
311     // If it's not a 32-bit value, there will need to be an extract.
312     return Cost + getVectorInstrCost(Instruction::ExtractElement, Val, Index);
313   }
314 
315   if (Opcode == Instruction::ExtractElement)
316     return 2;
317 
318   return 1;
319 }
320 
321 bool HexagonTTIImpl::isLegalMaskedStore(Type *DataType, Align /*Alignment*/) {
322   return HexagonMaskedVMem && ST.isTypeForHVX(DataType);
323 }
324 
325 bool HexagonTTIImpl::isLegalMaskedLoad(Type *DataType, Align /*Alignment*/) {
326   return HexagonMaskedVMem && ST.isTypeForHVX(DataType);
327 }
328 
329 /// --- Vector TTI end ---
330 
331 unsigned HexagonTTIImpl::getPrefetchDistance() const {
332   return ST.getL1PrefetchDistance();
333 }
334 
335 unsigned HexagonTTIImpl::getCacheLineSize() const {
336   return ST.getL1CacheLineSize();
337 }
338 
339 InstructionCost HexagonTTIImpl::getUserCost(const User *U,
340                                             ArrayRef<const Value *> Operands,
341                                             TTI::TargetCostKind CostKind) {
342   auto isCastFoldedIntoLoad = [this](const CastInst *CI) -> bool {
343     if (!CI->isIntegerCast())
344       return false;
345     // Only extensions from an integer type shorter than 32-bit to i32
346     // can be folded into the load.
347     const DataLayout &DL = getDataLayout();
348     unsigned SBW = DL.getTypeSizeInBits(CI->getSrcTy());
349     unsigned DBW = DL.getTypeSizeInBits(CI->getDestTy());
350     if (DBW != 32 || SBW >= DBW)
351       return false;
352 
353     const LoadInst *LI = dyn_cast<const LoadInst>(CI->getOperand(0));
354     // Technically, this code could allow multiple uses of the load, and
355     // check if all the uses are the same extension operation, but this
356     // should be sufficient for most cases.
357     return LI && LI->hasOneUse();
358   };
359 
360   if (const CastInst *CI = dyn_cast<const CastInst>(U))
361     if (isCastFoldedIntoLoad(CI))
362       return TargetTransformInfo::TCC_Free;
363   return BaseT::getUserCost(U, Operands, CostKind);
364 }
365 
366 bool HexagonTTIImpl::shouldBuildLookupTables() const {
367   return EmitLookupTables;
368 }
369