xref: /llvm-project/llvm/lib/Target/PowerPC/PPCTargetTransformInfo.cpp (revision f8438e8e591880d7857161a7cc83655c3fd076ef)
1 //===-- PPCTargetTransformInfo.cpp - PPC specific TTI ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "PPCTargetTransformInfo.h"
11 #include "llvm/Analysis/TargetTransformInfo.h"
12 #include "llvm/CodeGen/BasicTTIImpl.h"
13 #include "llvm/CodeGen/CostTable.h"
14 #include "llvm/CodeGen/TargetLowering.h"
15 #include "llvm/Support/CommandLine.h"
16 #include "llvm/Support/Debug.h"
17 using namespace llvm;
18 
19 #define DEBUG_TYPE "ppctti"
20 
21 static cl::opt<bool> DisablePPCConstHoist("disable-ppc-constant-hoisting",
22 cl::desc("disable constant hoisting on PPC"), cl::init(false), cl::Hidden);
23 
24 // This is currently only used for the data prefetch pass which is only enabled
25 // for BG/Q by default.
26 static cl::opt<unsigned>
27 CacheLineSize("ppc-loop-prefetch-cache-line", cl::Hidden, cl::init(64),
28               cl::desc("The loop prefetch cache line size"));
29 
30 static cl::opt<bool>
31 EnablePPCColdCC("ppc-enable-coldcc", cl::Hidden, cl::init(false),
32                 cl::desc("Enable using coldcc calling conv for cold "
33                          "internal functions"));
34 
35 //===----------------------------------------------------------------------===//
36 //
37 // PPC cost model.
38 //
39 //===----------------------------------------------------------------------===//
40 
41 TargetTransformInfo::PopcntSupportKind
42 PPCTTIImpl::getPopcntSupport(unsigned TyWidth) {
43   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
44   if (ST->hasPOPCNTD() != PPCSubtarget::POPCNTD_Unavailable && TyWidth <= 64)
45     return ST->hasPOPCNTD() == PPCSubtarget::POPCNTD_Slow ?
46              TTI::PSK_SlowHardware : TTI::PSK_FastHardware;
47   return TTI::PSK_Software;
48 }
49 
50 int PPCTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
51   if (DisablePPCConstHoist)
52     return BaseT::getIntImmCost(Imm, Ty);
53 
54   assert(Ty->isIntegerTy());
55 
56   unsigned BitSize = Ty->getPrimitiveSizeInBits();
57   if (BitSize == 0)
58     return ~0U;
59 
60   if (Imm == 0)
61     return TTI::TCC_Free;
62 
63   if (Imm.getBitWidth() <= 64) {
64     if (isInt<16>(Imm.getSExtValue()))
65       return TTI::TCC_Basic;
66 
67     if (isInt<32>(Imm.getSExtValue())) {
68       // A constant that can be materialized using lis.
69       if ((Imm.getZExtValue() & 0xFFFF) == 0)
70         return TTI::TCC_Basic;
71 
72       return 2 * TTI::TCC_Basic;
73     }
74   }
75 
76   return 4 * TTI::TCC_Basic;
77 }
78 
79 int PPCTTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
80                               Type *Ty) {
81   if (DisablePPCConstHoist)
82     return BaseT::getIntImmCost(IID, Idx, Imm, Ty);
83 
84   assert(Ty->isIntegerTy());
85 
86   unsigned BitSize = Ty->getPrimitiveSizeInBits();
87   if (BitSize == 0)
88     return ~0U;
89 
90   switch (IID) {
91   default:
92     return TTI::TCC_Free;
93   case Intrinsic::sadd_with_overflow:
94   case Intrinsic::uadd_with_overflow:
95   case Intrinsic::ssub_with_overflow:
96   case Intrinsic::usub_with_overflow:
97     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<16>(Imm.getSExtValue()))
98       return TTI::TCC_Free;
99     break;
100   case Intrinsic::experimental_stackmap:
101     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
102       return TTI::TCC_Free;
103     break;
104   case Intrinsic::experimental_patchpoint_void:
105   case Intrinsic::experimental_patchpoint_i64:
106     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
107       return TTI::TCC_Free;
108     break;
109   }
110   return PPCTTIImpl::getIntImmCost(Imm, Ty);
111 }
112 
113 int PPCTTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
114                               Type *Ty) {
115   if (DisablePPCConstHoist)
116     return BaseT::getIntImmCost(Opcode, Idx, Imm, Ty);
117 
118   assert(Ty->isIntegerTy());
119 
120   unsigned BitSize = Ty->getPrimitiveSizeInBits();
121   if (BitSize == 0)
122     return ~0U;
123 
124   unsigned ImmIdx = ~0U;
125   bool ShiftedFree = false, RunFree = false, UnsignedFree = false,
126        ZeroFree = false;
127   switch (Opcode) {
128   default:
129     return TTI::TCC_Free;
130   case Instruction::GetElementPtr:
131     // Always hoist the base address of a GetElementPtr. This prevents the
132     // creation of new constants for every base constant that gets constant
133     // folded with the offset.
134     if (Idx == 0)
135       return 2 * TTI::TCC_Basic;
136     return TTI::TCC_Free;
137   case Instruction::And:
138     RunFree = true; // (for the rotate-and-mask instructions)
139     LLVM_FALLTHROUGH;
140   case Instruction::Add:
141   case Instruction::Or:
142   case Instruction::Xor:
143     ShiftedFree = true;
144     LLVM_FALLTHROUGH;
145   case Instruction::Sub:
146   case Instruction::Mul:
147   case Instruction::Shl:
148   case Instruction::LShr:
149   case Instruction::AShr:
150     ImmIdx = 1;
151     break;
152   case Instruction::ICmp:
153     UnsignedFree = true;
154     ImmIdx = 1;
155     // Zero comparisons can use record-form instructions.
156     LLVM_FALLTHROUGH;
157   case Instruction::Select:
158     ZeroFree = true;
159     break;
160   case Instruction::PHI:
161   case Instruction::Call:
162   case Instruction::Ret:
163   case Instruction::Load:
164   case Instruction::Store:
165     break;
166   }
167 
168   if (ZeroFree && Imm == 0)
169     return TTI::TCC_Free;
170 
171   if (Idx == ImmIdx && Imm.getBitWidth() <= 64) {
172     if (isInt<16>(Imm.getSExtValue()))
173       return TTI::TCC_Free;
174 
175     if (RunFree) {
176       if (Imm.getBitWidth() <= 32 &&
177           (isShiftedMask_32(Imm.getZExtValue()) ||
178            isShiftedMask_32(~Imm.getZExtValue())))
179         return TTI::TCC_Free;
180 
181       if (ST->isPPC64() &&
182           (isShiftedMask_64(Imm.getZExtValue()) ||
183            isShiftedMask_64(~Imm.getZExtValue())))
184         return TTI::TCC_Free;
185     }
186 
187     if (UnsignedFree && isUInt<16>(Imm.getZExtValue()))
188       return TTI::TCC_Free;
189 
190     if (ShiftedFree && (Imm.getZExtValue() & 0xFFFF) == 0)
191       return TTI::TCC_Free;
192   }
193 
194   return PPCTTIImpl::getIntImmCost(Imm, Ty);
195 }
196 
197 unsigned PPCTTIImpl::getUserCost(const User *U,
198                                  ArrayRef<const Value *> Operands) {
199   if (U->getType()->isVectorTy()) {
200     // Instructions that need to be split should cost more.
201     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, U->getType());
202     return LT.first * BaseT::getUserCost(U, Operands);
203   }
204 
205   return BaseT::getUserCost(U, Operands);
206 }
207 
208 void PPCTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
209                                          TTI::UnrollingPreferences &UP) {
210   if (ST->getDarwinDirective() == PPC::DIR_A2) {
211     // The A2 is in-order with a deep pipeline, and concatenation unrolling
212     // helps expose latency-hiding opportunities to the instruction scheduler.
213     UP.Partial = UP.Runtime = true;
214 
215     // We unroll a lot on the A2 (hundreds of instructions), and the benefits
216     // often outweigh the cost of a division to compute the trip count.
217     UP.AllowExpensiveTripCount = true;
218   }
219 
220   BaseT::getUnrollingPreferences(L, SE, UP);
221 }
222 
223 // This function returns true to allow using coldcc calling convention.
224 // Returning true results in coldcc being used for functions which are cold at
225 // all call sites when the callers of the functions are not calling any other
226 // non coldcc functions.
227 bool PPCTTIImpl::useColdCCForColdCall(Function &F) {
228   return EnablePPCColdCC;
229 }
230 
231 bool PPCTTIImpl::enableAggressiveInterleaving(bool LoopHasReductions) {
232   // On the A2, always unroll aggressively. For QPX unaligned loads, we depend
233   // on combining the loads generated for consecutive accesses, and failure to
234   // do so is particularly expensive. This makes it much more likely (compared
235   // to only using concatenation unrolling).
236   if (ST->getDarwinDirective() == PPC::DIR_A2)
237     return true;
238 
239   return LoopHasReductions;
240 }
241 
242 const PPCTTIImpl::TTI::MemCmpExpansionOptions *
243 PPCTTIImpl::enableMemCmpExpansion(bool IsZeroCmp) const {
244   static const auto Options = []() {
245     TTI::MemCmpExpansionOptions Options;
246     Options.LoadSizes.push_back(8);
247     Options.LoadSizes.push_back(4);
248     Options.LoadSizes.push_back(2);
249     Options.LoadSizes.push_back(1);
250     return Options;
251   }();
252   return &Options;
253 }
254 
255 bool PPCTTIImpl::enableInterleavedAccessVectorization() {
256   return true;
257 }
258 
259 bool PPCTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
260                                TargetTransformInfo::LSRCost &C2) {
261   // This is mainly the default cost calculation. The only difference
262   //  is that now the number of instructions is the most important
263   //  metric.
264   return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
265                   C1.NumIVMuls, C1.NumBaseAdds,
266                   C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
267          std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
268                   C2.NumIVMuls, C2.NumBaseAdds,
269                   C2.ScaleCost, C2.ImmCost, C2.SetupCost);
270 }
271 
272 unsigned PPCTTIImpl::getNumberOfRegisters(bool Vector) {
273   if (Vector && !ST->hasAltivec() && !ST->hasQPX())
274     return 0;
275   return ST->hasVSX() ? 64 : 32;
276 }
277 
278 unsigned PPCTTIImpl::getRegisterBitWidth(bool Vector) const {
279   if (Vector) {
280     if (ST->hasQPX()) return 256;
281     if (ST->hasAltivec()) return 128;
282     return 0;
283   }
284 
285   if (ST->isPPC64())
286     return 64;
287   return 32;
288 
289 }
290 
291 unsigned PPCTTIImpl::getCacheLineSize() {
292   // Check first if the user specified a custom line size.
293   if (CacheLineSize.getNumOccurrences() > 0)
294     return CacheLineSize;
295 
296   // On P7, P8 or P9 we have a cache line size of 128.
297   unsigned Directive = ST->getDarwinDirective();
298   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
299       Directive == PPC::DIR_PWR9)
300     return 128;
301 
302   // On other processors return a default of 64 bytes.
303   return 64;
304 }
305 
306 unsigned PPCTTIImpl::getPrefetchDistance() {
307   // This seems like a reasonable default for the BG/Q (this pass is enabled, by
308   // default, only on the BG/Q).
309   return 300;
310 }
311 
312 unsigned PPCTTIImpl::getMaxInterleaveFactor(unsigned VF) {
313   unsigned Directive = ST->getDarwinDirective();
314   // The 440 has no SIMD support, but floating-point instructions
315   // have a 5-cycle latency, so unroll by 5x for latency hiding.
316   if (Directive == PPC::DIR_440)
317     return 5;
318 
319   // The A2 has no SIMD support, but floating-point instructions
320   // have a 6-cycle latency, so unroll by 6x for latency hiding.
321   if (Directive == PPC::DIR_A2)
322     return 6;
323 
324   // FIXME: For lack of any better information, do no harm...
325   if (Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500)
326     return 1;
327 
328   // For P7 and P8, floating-point instructions have a 6-cycle latency and
329   // there are two execution units, so unroll by 12x for latency hiding.
330   // FIXME: the same for P9 as previous gen until POWER9 scheduling is ready
331   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
332       Directive == PPC::DIR_PWR9)
333     return 12;
334 
335   // For most things, modern systems have two execution units (and
336   // out-of-order execution).
337   return 2;
338 }
339 
340 int PPCTTIImpl::getArithmeticInstrCost(
341     unsigned Opcode, Type *Ty, TTI::OperandValueKind Op1Info,
342     TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
343     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args) {
344   assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
345 
346   // Fallback to the default implementation.
347   return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
348                                        Opd1PropInfo, Opd2PropInfo);
349 }
350 
351 int PPCTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
352                                Type *SubTp) {
353   // Legalize the type.
354   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
355 
356   // PPC, for both Altivec/VSX and QPX, support cheap arbitrary permutations
357   // (at least in the sense that there need only be one non-loop-invariant
358   // instruction). We need one such shuffle instruction for each actual
359   // register (this is not true for arbitrary shuffles, but is true for the
360   // structured types of shuffles covered by TTI::ShuffleKind).
361   return LT.first;
362 }
363 
364 int PPCTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
365                                  const Instruction *I) {
366   assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
367 
368   return BaseT::getCastInstrCost(Opcode, Dst, Src);
369 }
370 
371 int PPCTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
372                                    const Instruction *I) {
373   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
374 }
375 
376 int PPCTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
377   assert(Val->isVectorTy() && "This must be a vector type");
378 
379   int ISD = TLI->InstructionOpcodeToISD(Opcode);
380   assert(ISD && "Invalid opcode");
381 
382   if (ST->hasVSX() && Val->getScalarType()->isDoubleTy()) {
383     // Double-precision scalars are already located in index #0.
384     if (Index == 0)
385       return 0;
386 
387     return BaseT::getVectorInstrCost(Opcode, Val, Index);
388   } else if (ST->hasQPX() && Val->getScalarType()->isFloatingPointTy()) {
389     // Floating point scalars are already located in index #0.
390     if (Index == 0)
391       return 0;
392 
393     return BaseT::getVectorInstrCost(Opcode, Val, Index);
394   }
395 
396   // Estimated cost of a load-hit-store delay.  This was obtained
397   // experimentally as a minimum needed to prevent unprofitable
398   // vectorization for the paq8p benchmark.  It may need to be
399   // raised further if other unprofitable cases remain.
400   unsigned LHSPenalty = 2;
401   if (ISD == ISD::INSERT_VECTOR_ELT)
402     LHSPenalty += 7;
403 
404   // Vector element insert/extract with Altivec is very expensive,
405   // because they require store and reload with the attendant
406   // processor stall for load-hit-store.  Until VSX is available,
407   // these need to be estimated as very costly.
408   if (ISD == ISD::EXTRACT_VECTOR_ELT ||
409       ISD == ISD::INSERT_VECTOR_ELT)
410     return LHSPenalty + BaseT::getVectorInstrCost(Opcode, Val, Index);
411 
412   return BaseT::getVectorInstrCost(Opcode, Val, Index);
413 }
414 
415 int PPCTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
416                                 unsigned AddressSpace, const Instruction *I) {
417   // Legalize the type.
418   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
419   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
420          "Invalid Opcode");
421 
422   int Cost = BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
423 
424   bool IsAltivecType = ST->hasAltivec() &&
425                        (LT.second == MVT::v16i8 || LT.second == MVT::v8i16 ||
426                         LT.second == MVT::v4i32 || LT.second == MVT::v4f32);
427   bool IsVSXType = ST->hasVSX() &&
428                    (LT.second == MVT::v2f64 || LT.second == MVT::v2i64);
429   bool IsQPXType = ST->hasQPX() &&
430                    (LT.second == MVT::v4f64 || LT.second == MVT::v4f32);
431 
432   // VSX has 32b/64b load instructions. Legalization can handle loading of
433   // 32b/64b to VSR correctly and cheaply. But BaseT::getMemoryOpCost and
434   // PPCTargetLowering can't compute the cost appropriately. So here we
435   // explicitly check this case.
436   unsigned MemBytes = Src->getPrimitiveSizeInBits();
437   if (Opcode == Instruction::Load && ST->hasVSX() && IsAltivecType &&
438       (MemBytes == 64 || (ST->hasP8Vector() && MemBytes == 32)))
439     return 1;
440 
441   // Aligned loads and stores are easy.
442   unsigned SrcBytes = LT.second.getStoreSize();
443   if (!SrcBytes || !Alignment || Alignment >= SrcBytes)
444     return Cost;
445 
446   // If we can use the permutation-based load sequence, then this is also
447   // relatively cheap (not counting loop-invariant instructions): one load plus
448   // one permute (the last load in a series has extra cost, but we're
449   // neglecting that here). Note that on the P7, we could do unaligned loads
450   // for Altivec types using the VSX instructions, but that's more expensive
451   // than using the permutation-based load sequence. On the P8, that's no
452   // longer true.
453   if (Opcode == Instruction::Load &&
454       ((!ST->hasP8Vector() && IsAltivecType) || IsQPXType) &&
455       Alignment >= LT.second.getScalarType().getStoreSize())
456     return Cost + LT.first; // Add the cost of the permutations.
457 
458   // For VSX, we can do unaligned loads and stores on Altivec/VSX types. On the
459   // P7, unaligned vector loads are more expensive than the permutation-based
460   // load sequence, so that might be used instead, but regardless, the net cost
461   // is about the same (not counting loop-invariant instructions).
462   if (IsVSXType || (ST->hasVSX() && IsAltivecType))
463     return Cost;
464 
465   // Newer PPC supports unaligned memory access.
466   if (TLI->allowsMisalignedMemoryAccesses(LT.second, 0))
467     return Cost;
468 
469   // PPC in general does not support unaligned loads and stores. They'll need
470   // to be decomposed based on the alignment factor.
471 
472   // Add the cost of each scalar load or store.
473   Cost += LT.first*(SrcBytes/Alignment-1);
474 
475   // For a vector type, there is also scalarization overhead (only for
476   // stores, loads are expanded using the vector-load + permutation sequence,
477   // which is much less expensive).
478   if (Src->isVectorTy() && Opcode == Instruction::Store)
479     for (int i = 0, e = Src->getVectorNumElements(); i < e; ++i)
480       Cost += getVectorInstrCost(Instruction::ExtractElement, Src, i);
481 
482   return Cost;
483 }
484 
485 int PPCTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
486                                            unsigned Factor,
487                                            ArrayRef<unsigned> Indices,
488                                            unsigned Alignment,
489                                            unsigned AddressSpace) {
490   assert(isa<VectorType>(VecTy) &&
491          "Expect a vector type for interleaved memory op");
492 
493   // Legalize the type.
494   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, VecTy);
495 
496   // Firstly, the cost of load/store operation.
497   int Cost = getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace);
498 
499   // PPC, for both Altivec/VSX and QPX, support cheap arbitrary permutations
500   // (at least in the sense that there need only be one non-loop-invariant
501   // instruction). For each result vector, we need one shuffle per incoming
502   // vector (except that the first shuffle can take two incoming vectors
503   // because it does not need to take itself).
504   Cost += Factor*(LT.first-1);
505 
506   return Cost;
507 }
508 
509