xref: /llvm-project/llvm/lib/Target/PowerPC/PPCTargetTransformInfo.cpp (revision e9c9329aa44e803416c3749e5a2e22d5a768f62a)
1 //===-- PPCTargetTransformInfo.cpp - PPC 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 "PPCTargetTransformInfo.h"
10 #include "llvm/Analysis/CodeMetrics.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/CodeGen/TargetSchedule.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Debug.h"
18 using namespace llvm;
19 
20 #define DEBUG_TYPE "ppctti"
21 
22 static cl::opt<bool> DisablePPCConstHoist("disable-ppc-constant-hoisting",
23 cl::desc("disable constant hoisting on PPC"), cl::init(false), cl::Hidden);
24 
25 // This is currently only used for the data prefetch pass which is only enabled
26 // for BG/Q by default.
27 static cl::opt<unsigned>
28 CacheLineSize("ppc-loop-prefetch-cache-line", cl::Hidden, cl::init(64),
29               cl::desc("The loop prefetch cache line size"));
30 
31 static cl::opt<bool>
32 EnablePPCColdCC("ppc-enable-coldcc", cl::Hidden, cl::init(false),
33                 cl::desc("Enable using coldcc calling conv for cold "
34                          "internal functions"));
35 
36 static cl::opt<bool>
37 LsrNoInsnsCost("ppc-lsr-no-insns-cost", cl::Hidden, cl::init(false),
38                cl::desc("Do not add instruction count to lsr cost model"));
39 
40 // The latency of mtctr is only justified if there are more than 4
41 // comparisons that will be removed as a result.
42 static cl::opt<unsigned>
43 SmallCTRLoopThreshold("min-ctr-loop-threshold", cl::init(4), cl::Hidden,
44                       cl::desc("Loops with a constant trip count smaller than "
45                                "this value will not use the count register."));
46 
47 //===----------------------------------------------------------------------===//
48 //
49 // PPC cost model.
50 //
51 //===----------------------------------------------------------------------===//
52 
53 TargetTransformInfo::PopcntSupportKind
54 PPCTTIImpl::getPopcntSupport(unsigned TyWidth) {
55   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
56   if (ST->hasPOPCNTD() != PPCSubtarget::POPCNTD_Unavailable && TyWidth <= 64)
57     return ST->hasPOPCNTD() == PPCSubtarget::POPCNTD_Slow ?
58              TTI::PSK_SlowHardware : TTI::PSK_FastHardware;
59   return TTI::PSK_Software;
60 }
61 
62 int PPCTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
63   if (DisablePPCConstHoist)
64     return BaseT::getIntImmCost(Imm, Ty);
65 
66   assert(Ty->isIntegerTy());
67 
68   unsigned BitSize = Ty->getPrimitiveSizeInBits();
69   if (BitSize == 0)
70     return ~0U;
71 
72   if (Imm == 0)
73     return TTI::TCC_Free;
74 
75   if (Imm.getBitWidth() <= 64) {
76     if (isInt<16>(Imm.getSExtValue()))
77       return TTI::TCC_Basic;
78 
79     if (isInt<32>(Imm.getSExtValue())) {
80       // A constant that can be materialized using lis.
81       if ((Imm.getZExtValue() & 0xFFFF) == 0)
82         return TTI::TCC_Basic;
83 
84       return 2 * TTI::TCC_Basic;
85     }
86   }
87 
88   return 4 * TTI::TCC_Basic;
89 }
90 
91 int PPCTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
92                                     const APInt &Imm, Type *Ty) {
93   if (DisablePPCConstHoist)
94     return BaseT::getIntImmCostIntrin(IID, Idx, Imm, Ty);
95 
96   assert(Ty->isIntegerTy());
97 
98   unsigned BitSize = Ty->getPrimitiveSizeInBits();
99   if (BitSize == 0)
100     return ~0U;
101 
102   switch (IID) {
103   default:
104     return TTI::TCC_Free;
105   case Intrinsic::sadd_with_overflow:
106   case Intrinsic::uadd_with_overflow:
107   case Intrinsic::ssub_with_overflow:
108   case Intrinsic::usub_with_overflow:
109     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<16>(Imm.getSExtValue()))
110       return TTI::TCC_Free;
111     break;
112   case Intrinsic::experimental_stackmap:
113     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
114       return TTI::TCC_Free;
115     break;
116   case Intrinsic::experimental_patchpoint_void:
117   case Intrinsic::experimental_patchpoint_i64:
118     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
119       return TTI::TCC_Free;
120     break;
121   }
122   return PPCTTIImpl::getIntImmCost(Imm, Ty);
123 }
124 
125 int PPCTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
126                                   const APInt &Imm, Type *Ty) {
127   if (DisablePPCConstHoist)
128     return BaseT::getIntImmCostInst(Opcode, Idx, Imm, Ty);
129 
130   assert(Ty->isIntegerTy());
131 
132   unsigned BitSize = Ty->getPrimitiveSizeInBits();
133   if (BitSize == 0)
134     return ~0U;
135 
136   unsigned ImmIdx = ~0U;
137   bool ShiftedFree = false, RunFree = false, UnsignedFree = false,
138        ZeroFree = false;
139   switch (Opcode) {
140   default:
141     return TTI::TCC_Free;
142   case Instruction::GetElementPtr:
143     // Always hoist the base address of a GetElementPtr. This prevents the
144     // creation of new constants for every base constant that gets constant
145     // folded with the offset.
146     if (Idx == 0)
147       return 2 * TTI::TCC_Basic;
148     return TTI::TCC_Free;
149   case Instruction::And:
150     RunFree = true; // (for the rotate-and-mask instructions)
151     LLVM_FALLTHROUGH;
152   case Instruction::Add:
153   case Instruction::Or:
154   case Instruction::Xor:
155     ShiftedFree = true;
156     LLVM_FALLTHROUGH;
157   case Instruction::Sub:
158   case Instruction::Mul:
159   case Instruction::Shl:
160   case Instruction::LShr:
161   case Instruction::AShr:
162     ImmIdx = 1;
163     break;
164   case Instruction::ICmp:
165     UnsignedFree = true;
166     ImmIdx = 1;
167     // Zero comparisons can use record-form instructions.
168     LLVM_FALLTHROUGH;
169   case Instruction::Select:
170     ZeroFree = true;
171     break;
172   case Instruction::PHI:
173   case Instruction::Call:
174   case Instruction::Ret:
175   case Instruction::Load:
176   case Instruction::Store:
177     break;
178   }
179 
180   if (ZeroFree && Imm == 0)
181     return TTI::TCC_Free;
182 
183   if (Idx == ImmIdx && Imm.getBitWidth() <= 64) {
184     if (isInt<16>(Imm.getSExtValue()))
185       return TTI::TCC_Free;
186 
187     if (RunFree) {
188       if (Imm.getBitWidth() <= 32 &&
189           (isShiftedMask_32(Imm.getZExtValue()) ||
190            isShiftedMask_32(~Imm.getZExtValue())))
191         return TTI::TCC_Free;
192 
193       if (ST->isPPC64() &&
194           (isShiftedMask_64(Imm.getZExtValue()) ||
195            isShiftedMask_64(~Imm.getZExtValue())))
196         return TTI::TCC_Free;
197     }
198 
199     if (UnsignedFree && isUInt<16>(Imm.getZExtValue()))
200       return TTI::TCC_Free;
201 
202     if (ShiftedFree && (Imm.getZExtValue() & 0xFFFF) == 0)
203       return TTI::TCC_Free;
204   }
205 
206   return PPCTTIImpl::getIntImmCost(Imm, Ty);
207 }
208 
209 unsigned
210 PPCTTIImpl::getUserCost(const User *U, ArrayRef<const Value *> Operands,
211                         TTI::TargetCostKind CostKind) {
212   if (U->getType()->isVectorTy()) {
213     // Instructions that need to be split should cost more.
214     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, U->getType());
215     return LT.first * BaseT::getUserCost(U, Operands, CostKind);
216   }
217 
218   return BaseT::getUserCost(U, Operands, CostKind);
219 }
220 
221 bool PPCTTIImpl::mightUseCTR(BasicBlock *BB, TargetLibraryInfo *LibInfo,
222                              SmallPtrSetImpl<const Value *> &Visited) {
223   const PPCTargetMachine &TM = ST->getTargetMachine();
224 
225   // Loop through the inline asm constraints and look for something that
226   // clobbers ctr.
227   auto asmClobbersCTR = [](InlineAsm *IA) {
228     InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
229     for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
230       InlineAsm::ConstraintInfo &C = CIV[i];
231       if (C.Type != InlineAsm::isInput)
232         for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
233           if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
234             return true;
235     }
236     return false;
237   };
238 
239   // Determining the address of a TLS variable results in a function call in
240   // certain TLS models.
241   std::function<bool(const Value *)> memAddrUsesCTR =
242       [&memAddrUsesCTR, &TM, &Visited](const Value *MemAddr) -> bool {
243     // No need to traverse again if we already checked this operand.
244     if (!Visited.insert(MemAddr).second)
245       return false;
246     const auto *GV = dyn_cast<GlobalValue>(MemAddr);
247     if (!GV) {
248       // Recurse to check for constants that refer to TLS global variables.
249       if (const auto *CV = dyn_cast<Constant>(MemAddr))
250         for (const auto &CO : CV->operands())
251           if (memAddrUsesCTR(CO))
252             return true;
253 
254       return false;
255     }
256 
257     if (!GV->isThreadLocal())
258       return false;
259     TLSModel::Model Model = TM.getTLSModel(GV);
260     return Model == TLSModel::GeneralDynamic ||
261       Model == TLSModel::LocalDynamic;
262   };
263 
264   auto isLargeIntegerTy = [](bool Is32Bit, Type *Ty) {
265     if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
266       return ITy->getBitWidth() > (Is32Bit ? 32U : 64U);
267 
268     return false;
269   };
270 
271   for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
272        J != JE; ++J) {
273     if (CallInst *CI = dyn_cast<CallInst>(J)) {
274       // Inline ASM is okay, unless it clobbers the ctr register.
275       if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand())) {
276         if (asmClobbersCTR(IA))
277           return true;
278         continue;
279       }
280 
281       if (Function *F = CI->getCalledFunction()) {
282         // Most intrinsics don't become function calls, but some might.
283         // sin, cos, exp and log are always calls.
284         unsigned Opcode = 0;
285         if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
286           switch (F->getIntrinsicID()) {
287           default: continue;
288           // If we have a call to ppc_is_decremented_ctr_nonzero, or ppc_mtctr
289           // we're definitely using CTR.
290           case Intrinsic::set_loop_iterations:
291           case Intrinsic::loop_decrement:
292             return true;
293 
294           // Exclude eh_sjlj_setjmp; we don't need to exclude eh_sjlj_longjmp
295           // because, although it does clobber the counter register, the
296           // control can't then return to inside the loop unless there is also
297           // an eh_sjlj_setjmp.
298           case Intrinsic::eh_sjlj_setjmp:
299 
300           case Intrinsic::memcpy:
301           case Intrinsic::memmove:
302           case Intrinsic::memset:
303           case Intrinsic::powi:
304           case Intrinsic::log:
305           case Intrinsic::log2:
306           case Intrinsic::log10:
307           case Intrinsic::exp:
308           case Intrinsic::exp2:
309           case Intrinsic::pow:
310           case Intrinsic::sin:
311           case Intrinsic::cos:
312             return true;
313           case Intrinsic::copysign:
314             if (CI->getArgOperand(0)->getType()->getScalarType()->
315                 isPPC_FP128Ty())
316               return true;
317             else
318               continue; // ISD::FCOPYSIGN is never a library call.
319           case Intrinsic::sqrt:               Opcode = ISD::FSQRT;      break;
320           case Intrinsic::floor:              Opcode = ISD::FFLOOR;     break;
321           case Intrinsic::ceil:               Opcode = ISD::FCEIL;      break;
322           case Intrinsic::trunc:              Opcode = ISD::FTRUNC;     break;
323           case Intrinsic::rint:               Opcode = ISD::FRINT;      break;
324           case Intrinsic::lrint:              Opcode = ISD::LRINT;      break;
325           case Intrinsic::llrint:             Opcode = ISD::LLRINT;     break;
326           case Intrinsic::nearbyint:          Opcode = ISD::FNEARBYINT; break;
327           case Intrinsic::round:              Opcode = ISD::FROUND;     break;
328           case Intrinsic::lround:             Opcode = ISD::LROUND;     break;
329           case Intrinsic::llround:            Opcode = ISD::LLROUND;    break;
330           case Intrinsic::minnum:             Opcode = ISD::FMINNUM;    break;
331           case Intrinsic::maxnum:             Opcode = ISD::FMAXNUM;    break;
332           case Intrinsic::umul_with_overflow: Opcode = ISD::UMULO;      break;
333           case Intrinsic::smul_with_overflow: Opcode = ISD::SMULO;      break;
334           }
335         }
336 
337         // PowerPC does not use [US]DIVREM or other library calls for
338         // operations on regular types which are not otherwise library calls
339         // (i.e. soft float or atomics). If adapting for targets that do,
340         // additional care is required here.
341 
342         LibFunc Func;
343         if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
344             LibInfo->getLibFunc(F->getName(), Func) &&
345             LibInfo->hasOptimizedCodeGen(Func)) {
346           // Non-read-only functions are never treated as intrinsics.
347           if (!CI->onlyReadsMemory())
348             return true;
349 
350           // Conversion happens only for FP calls.
351           if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
352             return true;
353 
354           switch (Func) {
355           default: return true;
356           case LibFunc_copysign:
357           case LibFunc_copysignf:
358             continue; // ISD::FCOPYSIGN is never a library call.
359           case LibFunc_copysignl:
360             return true;
361           case LibFunc_fabs:
362           case LibFunc_fabsf:
363           case LibFunc_fabsl:
364             continue; // ISD::FABS is never a library call.
365           case LibFunc_sqrt:
366           case LibFunc_sqrtf:
367           case LibFunc_sqrtl:
368             Opcode = ISD::FSQRT; break;
369           case LibFunc_floor:
370           case LibFunc_floorf:
371           case LibFunc_floorl:
372             Opcode = ISD::FFLOOR; break;
373           case LibFunc_nearbyint:
374           case LibFunc_nearbyintf:
375           case LibFunc_nearbyintl:
376             Opcode = ISD::FNEARBYINT; break;
377           case LibFunc_ceil:
378           case LibFunc_ceilf:
379           case LibFunc_ceill:
380             Opcode = ISD::FCEIL; break;
381           case LibFunc_rint:
382           case LibFunc_rintf:
383           case LibFunc_rintl:
384             Opcode = ISD::FRINT; break;
385           case LibFunc_round:
386           case LibFunc_roundf:
387           case LibFunc_roundl:
388             Opcode = ISD::FROUND; break;
389           case LibFunc_trunc:
390           case LibFunc_truncf:
391           case LibFunc_truncl:
392             Opcode = ISD::FTRUNC; break;
393           case LibFunc_fmin:
394           case LibFunc_fminf:
395           case LibFunc_fminl:
396             Opcode = ISD::FMINNUM; break;
397           case LibFunc_fmax:
398           case LibFunc_fmaxf:
399           case LibFunc_fmaxl:
400             Opcode = ISD::FMAXNUM; break;
401           }
402         }
403 
404         if (Opcode) {
405           EVT EVTy =
406               TLI->getValueType(DL, CI->getArgOperand(0)->getType(), true);
407 
408           if (EVTy == MVT::Other)
409             return true;
410 
411           if (TLI->isOperationLegalOrCustom(Opcode, EVTy))
412             continue;
413           else if (EVTy.isVector() &&
414                    TLI->isOperationLegalOrCustom(Opcode, EVTy.getScalarType()))
415             continue;
416 
417           return true;
418         }
419       }
420 
421       return true;
422     } else if (isa<BinaryOperator>(J) &&
423                J->getType()->getScalarType()->isPPC_FP128Ty()) {
424       // Most operations on ppc_f128 values become calls.
425       return true;
426     } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
427                isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
428       CastInst *CI = cast<CastInst>(J);
429       if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
430           CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
431           isLargeIntegerTy(!TM.isPPC64(), CI->getSrcTy()->getScalarType()) ||
432           isLargeIntegerTy(!TM.isPPC64(), CI->getDestTy()->getScalarType()))
433         return true;
434     } else if (isLargeIntegerTy(!TM.isPPC64(),
435                                 J->getType()->getScalarType()) &&
436                (J->getOpcode() == Instruction::UDiv ||
437                 J->getOpcode() == Instruction::SDiv ||
438                 J->getOpcode() == Instruction::URem ||
439                 J->getOpcode() == Instruction::SRem)) {
440       return true;
441     } else if (!TM.isPPC64() &&
442                isLargeIntegerTy(false, J->getType()->getScalarType()) &&
443                (J->getOpcode() == Instruction::Shl ||
444                 J->getOpcode() == Instruction::AShr ||
445                 J->getOpcode() == Instruction::LShr)) {
446       // Only on PPC32, for 128-bit integers (specifically not 64-bit
447       // integers), these might be runtime calls.
448       return true;
449     } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
450       // On PowerPC, indirect jumps use the counter register.
451       return true;
452     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
453       if (SI->getNumCases() + 1 >= (unsigned)TLI->getMinimumJumpTableEntries())
454         return true;
455     }
456 
457     // FREM is always a call.
458     if (J->getOpcode() == Instruction::FRem)
459       return true;
460 
461     if (ST->useSoftFloat()) {
462       switch(J->getOpcode()) {
463       case Instruction::FAdd:
464       case Instruction::FSub:
465       case Instruction::FMul:
466       case Instruction::FDiv:
467       case Instruction::FPTrunc:
468       case Instruction::FPExt:
469       case Instruction::FPToUI:
470       case Instruction::FPToSI:
471       case Instruction::UIToFP:
472       case Instruction::SIToFP:
473       case Instruction::FCmp:
474         return true;
475       }
476     }
477 
478     for (Value *Operand : J->operands())
479       if (memAddrUsesCTR(Operand))
480         return true;
481   }
482 
483   return false;
484 }
485 
486 bool PPCTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
487                                           AssumptionCache &AC,
488                                           TargetLibraryInfo *LibInfo,
489                                           HardwareLoopInfo &HWLoopInfo) {
490   const PPCTargetMachine &TM = ST->getTargetMachine();
491   TargetSchedModel SchedModel;
492   SchedModel.init(ST);
493 
494   // Do not convert small short loops to CTR loop.
495   unsigned ConstTripCount = SE.getSmallConstantTripCount(L);
496   if (ConstTripCount && ConstTripCount < SmallCTRLoopThreshold) {
497     SmallPtrSet<const Value *, 32> EphValues;
498     CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
499     CodeMetrics Metrics;
500     for (BasicBlock *BB : L->blocks())
501       Metrics.analyzeBasicBlock(BB, *this, EphValues);
502     // 6 is an approximate latency for the mtctr instruction.
503     if (Metrics.NumInsts <= (6 * SchedModel.getIssueWidth()))
504       return false;
505   }
506 
507   // We don't want to spill/restore the counter register, and so we don't
508   // want to use the counter register if the loop contains calls.
509   SmallPtrSet<const Value *, 4> Visited;
510   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
511        I != IE; ++I)
512     if (mightUseCTR(*I, LibInfo, Visited))
513       return false;
514 
515   SmallVector<BasicBlock*, 4> ExitingBlocks;
516   L->getExitingBlocks(ExitingBlocks);
517 
518   // If there is an exit edge known to be frequently taken,
519   // we should not transform this loop.
520   for (auto &BB : ExitingBlocks) {
521     Instruction *TI = BB->getTerminator();
522     if (!TI) continue;
523 
524     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
525       uint64_t TrueWeight = 0, FalseWeight = 0;
526       if (!BI->isConditional() ||
527           !BI->extractProfMetadata(TrueWeight, FalseWeight))
528         continue;
529 
530       // If the exit path is more frequent than the loop path,
531       // we return here without further analysis for this loop.
532       bool TrueIsExit = !L->contains(BI->getSuccessor(0));
533       if (( TrueIsExit && FalseWeight < TrueWeight) ||
534           (!TrueIsExit && FalseWeight > TrueWeight))
535         return false;
536     }
537   }
538 
539   LLVMContext &C = L->getHeader()->getContext();
540   HWLoopInfo.CountType = TM.isPPC64() ?
541     Type::getInt64Ty(C) : Type::getInt32Ty(C);
542   HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
543   return true;
544 }
545 
546 void PPCTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
547                                          TTI::UnrollingPreferences &UP) {
548   if (ST->getCPUDirective() == PPC::DIR_A2) {
549     // The A2 is in-order with a deep pipeline, and concatenation unrolling
550     // helps expose latency-hiding opportunities to the instruction scheduler.
551     UP.Partial = UP.Runtime = true;
552 
553     // We unroll a lot on the A2 (hundreds of instructions), and the benefits
554     // often outweigh the cost of a division to compute the trip count.
555     UP.AllowExpensiveTripCount = true;
556   }
557 
558   BaseT::getUnrollingPreferences(L, SE, UP);
559 }
560 
561 // This function returns true to allow using coldcc calling convention.
562 // Returning true results in coldcc being used for functions which are cold at
563 // all call sites when the callers of the functions are not calling any other
564 // non coldcc functions.
565 bool PPCTTIImpl::useColdCCForColdCall(Function &F) {
566   return EnablePPCColdCC;
567 }
568 
569 bool PPCTTIImpl::enableAggressiveInterleaving(bool LoopHasReductions) {
570   // On the A2, always unroll aggressively. For QPX unaligned loads, we depend
571   // on combining the loads generated for consecutive accesses, and failure to
572   // do so is particularly expensive. This makes it much more likely (compared
573   // to only using concatenation unrolling).
574   if (ST->getCPUDirective() == PPC::DIR_A2)
575     return true;
576 
577   return LoopHasReductions;
578 }
579 
580 PPCTTIImpl::TTI::MemCmpExpansionOptions
581 PPCTTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
582   TTI::MemCmpExpansionOptions Options;
583   Options.LoadSizes = {8, 4, 2, 1};
584   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
585   return Options;
586 }
587 
588 bool PPCTTIImpl::enableInterleavedAccessVectorization() {
589   return true;
590 }
591 
592 unsigned PPCTTIImpl::getNumberOfRegisters(unsigned ClassID) const {
593   assert(ClassID == GPRRC || ClassID == FPRRC ||
594          ClassID == VRRC || ClassID == VSXRC);
595   if (ST->hasVSX()) {
596     assert(ClassID == GPRRC || ClassID == VSXRC || ClassID == VRRC);
597     return ClassID == VSXRC ? 64 : 32;
598   }
599   assert(ClassID == GPRRC || ClassID == FPRRC || ClassID == VRRC);
600   return 32;
601 }
602 
603 unsigned PPCTTIImpl::getRegisterClassForType(bool Vector, Type *Ty) const {
604   if (Vector)
605     return ST->hasVSX() ? VSXRC : VRRC;
606   else if (Ty && (Ty->getScalarType()->isFloatTy() ||
607                   Ty->getScalarType()->isDoubleTy()))
608     return ST->hasVSX() ? VSXRC : FPRRC;
609   else if (Ty && (Ty->getScalarType()->isFP128Ty() ||
610                   Ty->getScalarType()->isPPC_FP128Ty()))
611     return VRRC;
612   else if (Ty && Ty->getScalarType()->isHalfTy())
613     return VSXRC;
614   else
615     return GPRRC;
616 }
617 
618 const char* PPCTTIImpl::getRegisterClassName(unsigned ClassID) const {
619 
620   switch (ClassID) {
621     default:
622       llvm_unreachable("unknown register class");
623       return "PPC::unknown register class";
624     case GPRRC:       return "PPC::GPRRC";
625     case FPRRC:       return "PPC::FPRRC";
626     case VRRC:        return "PPC::VRRC";
627     case VSXRC:       return "PPC::VSXRC";
628   }
629 }
630 
631 unsigned PPCTTIImpl::getRegisterBitWidth(bool Vector) const {
632   if (Vector) {
633     if (ST->hasQPX()) return 256;
634     if (ST->hasAltivec()) return 128;
635     return 0;
636   }
637 
638   if (ST->isPPC64())
639     return 64;
640   return 32;
641 
642 }
643 
644 unsigned PPCTTIImpl::getCacheLineSize() const {
645   // Check first if the user specified a custom line size.
646   if (CacheLineSize.getNumOccurrences() > 0)
647     return CacheLineSize;
648 
649   // On P7, P8 or P9 we have a cache line size of 128.
650   unsigned Directive = ST->getCPUDirective();
651   // Assume that Future CPU has the same cache line size as the others.
652   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
653       Directive == PPC::DIR_PWR9 || Directive == PPC::DIR_PWR_FUTURE)
654     return 128;
655 
656   // On other processors return a default of 64 bytes.
657   return 64;
658 }
659 
660 unsigned PPCTTIImpl::getPrefetchDistance() const {
661   // This seems like a reasonable default for the BG/Q (this pass is enabled, by
662   // default, only on the BG/Q).
663   return 300;
664 }
665 
666 unsigned PPCTTIImpl::getMaxInterleaveFactor(unsigned VF) {
667   unsigned Directive = ST->getCPUDirective();
668   // The 440 has no SIMD support, but floating-point instructions
669   // have a 5-cycle latency, so unroll by 5x for latency hiding.
670   if (Directive == PPC::DIR_440)
671     return 5;
672 
673   // The A2 has no SIMD support, but floating-point instructions
674   // have a 6-cycle latency, so unroll by 6x for latency hiding.
675   if (Directive == PPC::DIR_A2)
676     return 6;
677 
678   // FIXME: For lack of any better information, do no harm...
679   if (Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500)
680     return 1;
681 
682   // For P7 and P8, floating-point instructions have a 6-cycle latency and
683   // there are two execution units, so unroll by 12x for latency hiding.
684   // FIXME: the same for P9 as previous gen until POWER9 scheduling is ready
685   // Assume that future is the same as the others.
686   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
687       Directive == PPC::DIR_PWR9 || Directive == PPC::DIR_PWR_FUTURE)
688     return 12;
689 
690   // For most things, modern systems have two execution units (and
691   // out-of-order execution).
692   return 2;
693 }
694 
695 // Adjust the cost of vector instructions on targets which there is overlap
696 // between the vector and scalar units, thereby reducing the overall throughput
697 // of vector code wrt. scalar code.
698 int PPCTTIImpl::vectorCostAdjustment(int Cost, unsigned Opcode, Type *Ty1,
699                                      Type *Ty2) {
700   if (!ST->vectorsUseTwoUnits() || !Ty1->isVectorTy())
701     return Cost;
702 
703   std::pair<int, MVT> LT1 = TLI->getTypeLegalizationCost(DL, Ty1);
704   // If type legalization involves splitting the vector, we don't want to
705   // double the cost at every step - only the last step.
706   if (LT1.first != 1 || !LT1.second.isVector())
707     return Cost;
708 
709   int ISD = TLI->InstructionOpcodeToISD(Opcode);
710   if (TLI->isOperationExpand(ISD, LT1.second))
711     return Cost;
712 
713   if (Ty2) {
714     std::pair<int, MVT> LT2 = TLI->getTypeLegalizationCost(DL, Ty2);
715     if (LT2.first != 1 || !LT2.second.isVector())
716       return Cost;
717   }
718 
719   return Cost * 2;
720 }
721 
722 int PPCTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
723                                        TTI::OperandValueKind Op1Info,
724                                        TTI::OperandValueKind Op2Info,
725                                        TTI::OperandValueProperties Opd1PropInfo,
726                                        TTI::OperandValueProperties Opd2PropInfo,
727                                        ArrayRef<const Value *> Args,
728                                        const Instruction *CxtI) {
729   assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
730 
731   // Fallback to the default implementation.
732   int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
733                                            Opd1PropInfo, Opd2PropInfo);
734   return vectorCostAdjustment(Cost, Opcode, Ty, nullptr);
735 }
736 
737 int PPCTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
738                                Type *SubTp) {
739   // Legalize the type.
740   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
741 
742   // PPC, for both Altivec/VSX and QPX, support cheap arbitrary permutations
743   // (at least in the sense that there need only be one non-loop-invariant
744   // instruction). We need one such shuffle instruction for each actual
745   // register (this is not true for arbitrary shuffles, but is true for the
746   // structured types of shuffles covered by TTI::ShuffleKind).
747   return vectorCostAdjustment(LT.first, Instruction::ShuffleVector, Tp,
748                               nullptr);
749 }
750 
751 int PPCTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
752                                  const Instruction *I) {
753   assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
754 
755   int Cost = BaseT::getCastInstrCost(Opcode, Dst, Src);
756   return vectorCostAdjustment(Cost, Opcode, Dst, Src);
757 }
758 
759 int PPCTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
760                                    const Instruction *I) {
761   int Cost = BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
762   return vectorCostAdjustment(Cost, Opcode, ValTy, nullptr);
763 }
764 
765 int PPCTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
766   assert(Val->isVectorTy() && "This must be a vector type");
767 
768   int ISD = TLI->InstructionOpcodeToISD(Opcode);
769   assert(ISD && "Invalid opcode");
770 
771   int Cost = BaseT::getVectorInstrCost(Opcode, Val, Index);
772   Cost = vectorCostAdjustment(Cost, Opcode, Val, nullptr);
773 
774   if (ST->hasVSX() && Val->getScalarType()->isDoubleTy()) {
775     // Double-precision scalars are already located in index #0 (or #1 if LE).
776     if (ISD == ISD::EXTRACT_VECTOR_ELT &&
777         Index == (ST->isLittleEndian() ? 1 : 0))
778       return 0;
779 
780     return Cost;
781 
782   } else if (ST->hasQPX() && Val->getScalarType()->isFloatingPointTy()) {
783     // Floating point scalars are already located in index #0.
784     if (Index == 0)
785       return 0;
786 
787     return Cost;
788 
789   } else if (Val->getScalarType()->isIntegerTy() && Index != -1U) {
790     if (ST->hasP9Altivec()) {
791       if (ISD == ISD::INSERT_VECTOR_ELT)
792         // A move-to VSR and a permute/insert.  Assume vector operation cost
793         // for both (cost will be 2x on P9).
794         return vectorCostAdjustment(2, Opcode, Val, nullptr);
795 
796       // It's an extract.  Maybe we can do a cheap move-from VSR.
797       unsigned EltSize = Val->getScalarSizeInBits();
798       if (EltSize == 64) {
799         unsigned MfvsrdIndex = ST->isLittleEndian() ? 1 : 0;
800         if (Index == MfvsrdIndex)
801           return 1;
802       } else if (EltSize == 32) {
803         unsigned MfvsrwzIndex = ST->isLittleEndian() ? 2 : 1;
804         if (Index == MfvsrwzIndex)
805           return 1;
806       }
807 
808       // We need a vector extract (or mfvsrld).  Assume vector operation cost.
809       // The cost of the load constant for a vector extract is disregarded
810       // (invariant, easily schedulable).
811       return vectorCostAdjustment(1, Opcode, Val, nullptr);
812 
813     } else if (ST->hasDirectMove())
814       // Assume permute has standard cost.
815       // Assume move-to/move-from VSR have 2x standard cost.
816       return 3;
817   }
818 
819   // Estimated cost of a load-hit-store delay.  This was obtained
820   // experimentally as a minimum needed to prevent unprofitable
821   // vectorization for the paq8p benchmark.  It may need to be
822   // raised further if other unprofitable cases remain.
823   unsigned LHSPenalty = 2;
824   if (ISD == ISD::INSERT_VECTOR_ELT)
825     LHSPenalty += 7;
826 
827   // Vector element insert/extract with Altivec is very expensive,
828   // because they require store and reload with the attendant
829   // processor stall for load-hit-store.  Until VSX is available,
830   // these need to be estimated as very costly.
831   if (ISD == ISD::EXTRACT_VECTOR_ELT ||
832       ISD == ISD::INSERT_VECTOR_ELT)
833     return LHSPenalty + Cost;
834 
835   return Cost;
836 }
837 
838 int PPCTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
839                                 MaybeAlign Alignment, unsigned AddressSpace,
840                                 const Instruction *I) {
841   // Legalize the type.
842   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
843   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
844          "Invalid Opcode");
845 
846   int Cost = BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
847   Cost = vectorCostAdjustment(Cost, Opcode, Src, nullptr);
848 
849   bool IsAltivecType = ST->hasAltivec() &&
850                        (LT.second == MVT::v16i8 || LT.second == MVT::v8i16 ||
851                         LT.second == MVT::v4i32 || LT.second == MVT::v4f32);
852   bool IsVSXType = ST->hasVSX() &&
853                    (LT.second == MVT::v2f64 || LT.second == MVT::v2i64);
854   bool IsQPXType = ST->hasQPX() &&
855                    (LT.second == MVT::v4f64 || LT.second == MVT::v4f32);
856 
857   // VSX has 32b/64b load instructions. Legalization can handle loading of
858   // 32b/64b to VSR correctly and cheaply. But BaseT::getMemoryOpCost and
859   // PPCTargetLowering can't compute the cost appropriately. So here we
860   // explicitly check this case.
861   unsigned MemBytes = Src->getPrimitiveSizeInBits();
862   if (Opcode == Instruction::Load && ST->hasVSX() && IsAltivecType &&
863       (MemBytes == 64 || (ST->hasP8Vector() && MemBytes == 32)))
864     return 1;
865 
866   // Aligned loads and stores are easy.
867   unsigned SrcBytes = LT.second.getStoreSize();
868   if (!SrcBytes || !Alignment || Alignment >= SrcBytes)
869     return Cost;
870 
871   // If we can use the permutation-based load sequence, then this is also
872   // relatively cheap (not counting loop-invariant instructions): one load plus
873   // one permute (the last load in a series has extra cost, but we're
874   // neglecting that here). Note that on the P7, we could do unaligned loads
875   // for Altivec types using the VSX instructions, but that's more expensive
876   // than using the permutation-based load sequence. On the P8, that's no
877   // longer true.
878   if (Opcode == Instruction::Load &&
879       ((!ST->hasP8Vector() && IsAltivecType) || IsQPXType) &&
880       Alignment >= LT.second.getScalarType().getStoreSize())
881     return Cost + LT.first; // Add the cost of the permutations.
882 
883   // For VSX, we can do unaligned loads and stores on Altivec/VSX types. On the
884   // P7, unaligned vector loads are more expensive than the permutation-based
885   // load sequence, so that might be used instead, but regardless, the net cost
886   // is about the same (not counting loop-invariant instructions).
887   if (IsVSXType || (ST->hasVSX() && IsAltivecType))
888     return Cost;
889 
890   // Newer PPC supports unaligned memory access.
891   if (TLI->allowsMisalignedMemoryAccesses(LT.second, 0))
892     return Cost;
893 
894   // PPC in general does not support unaligned loads and stores. They'll need
895   // to be decomposed based on the alignment factor.
896 
897   // Add the cost of each scalar load or store.
898   assert(Alignment);
899   Cost += LT.first * ((SrcBytes / Alignment->value()) - 1);
900 
901   // For a vector type, there is also scalarization overhead (only for
902   // stores, loads are expanded using the vector-load + permutation sequence,
903   // which is much less expensive).
904   if (Src->isVectorTy() && Opcode == Instruction::Store)
905     for (int i = 0, e = cast<VectorType>(Src)->getNumElements(); i < e; ++i)
906       Cost += getVectorInstrCost(Instruction::ExtractElement, Src, i);
907 
908   return Cost;
909 }
910 
911 int PPCTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
912                                            unsigned Factor,
913                                            ArrayRef<unsigned> Indices,
914                                            unsigned Alignment,
915                                            unsigned AddressSpace,
916                                            bool UseMaskForCond,
917                                            bool UseMaskForGaps) {
918   if (UseMaskForCond || UseMaskForGaps)
919     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
920                                              Alignment, AddressSpace,
921                                              UseMaskForCond, UseMaskForGaps);
922 
923   assert(isa<VectorType>(VecTy) &&
924          "Expect a vector type for interleaved memory op");
925 
926   // Legalize the type.
927   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, VecTy);
928 
929   // Firstly, the cost of load/store operation.
930   int Cost =
931       getMemoryOpCost(Opcode, VecTy, MaybeAlign(Alignment), AddressSpace);
932 
933   // PPC, for both Altivec/VSX and QPX, support cheap arbitrary permutations
934   // (at least in the sense that there need only be one non-loop-invariant
935   // instruction). For each result vector, we need one shuffle per incoming
936   // vector (except that the first shuffle can take two incoming vectors
937   // because it does not need to take itself).
938   Cost += Factor*(LT.first-1);
939 
940   return Cost;
941 }
942 
943 unsigned PPCTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
944                                            ArrayRef<Value *> Args,
945                                            FastMathFlags FMF, unsigned VF,
946                                            const Instruction *I) {
947   return BaseT::getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF, I);
948 }
949 
950 unsigned PPCTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
951                                            ArrayRef<Type *> Tys,
952                                            FastMathFlags FMF,
953                                            unsigned ScalarizationCostPassed,
954                                            const Instruction *I) {
955   if (ID == Intrinsic::bswap && ST->hasP9Vector())
956     return TLI->getTypeLegalizationCost(DL, RetTy).first;
957   return BaseT::getIntrinsicInstrCost(ID, RetTy, Tys, FMF,
958                                       ScalarizationCostPassed, I);
959 }
960 
961 bool PPCTTIImpl::canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE,
962                             LoopInfo *LI, DominatorTree *DT,
963                             AssumptionCache *AC, TargetLibraryInfo *LibInfo) {
964   // Process nested loops first.
965   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
966     if (canSaveCmp(*I, BI, SE, LI, DT, AC, LibInfo))
967       return false; // Stop search.
968 
969   HardwareLoopInfo HWLoopInfo(L);
970 
971   if (!HWLoopInfo.canAnalyze(*LI))
972     return false;
973 
974   if (!isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo))
975     return false;
976 
977   if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT))
978     return false;
979 
980   *BI = HWLoopInfo.ExitBranch;
981   return true;
982 }
983 
984 bool PPCTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
985                                TargetTransformInfo::LSRCost &C2) {
986   // PowerPC default behaviour here is "instruction number 1st priority".
987   // If LsrNoInsnsCost is set, call default implementation.
988   if (!LsrNoInsnsCost)
989     return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost, C1.NumIVMuls,
990                     C1.NumBaseAdds, C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
991            std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost, C2.NumIVMuls,
992                     C2.NumBaseAdds, C2.ScaleCost, C2.ImmCost, C2.SetupCost);
993   else
994     return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
995 }
996