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