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