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