xref: /llvm-project/llvm/lib/Target/PowerPC/PPCTargetTransformInfo.cpp (revision b5e1fc19da9527b96665bc4937f96a60092e77c6)
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/TargetLibraryInfo.h"
12 #include "llvm/Analysis/TargetTransformInfo.h"
13 #include "llvm/CodeGen/BasicTTIImpl.h"
14 #include "llvm/CodeGen/CostTable.h"
15 #include "llvm/CodeGen/TargetLowering.h"
16 #include "llvm/CodeGen/TargetSchedule.h"
17 #include "llvm/IR/IntrinsicsPowerPC.h"
18 #include "llvm/IR/ProfDataUtils.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/KnownBits.h"
22 #include "llvm/Transforms/InstCombine/InstCombiner.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include <optional>
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "ppctti"
29 
30 static cl::opt<bool> DisablePPCConstHoist("disable-ppc-constant-hoisting",
31 cl::desc("disable constant hoisting on PPC"), cl::init(false), cl::Hidden);
32 
33 static cl::opt<bool>
34 EnablePPCColdCC("ppc-enable-coldcc", cl::Hidden, cl::init(false),
35                 cl::desc("Enable using coldcc calling conv for cold "
36                          "internal functions"));
37 
38 static cl::opt<bool>
39 LsrNoInsnsCost("ppc-lsr-no-insns-cost", cl::Hidden, cl::init(false),
40                cl::desc("Do not add instruction count to lsr cost model"));
41 
42 // The latency of mtctr is only justified if there are more than 4
43 // comparisons that will be removed as a result.
44 static cl::opt<unsigned>
45 SmallCTRLoopThreshold("min-ctr-loop-threshold", cl::init(4), cl::Hidden,
46                       cl::desc("Loops with a constant trip count smaller than "
47                                "this value will not use the count register."));
48 
49 //===----------------------------------------------------------------------===//
50 //
51 // PPC cost model.
52 //
53 //===----------------------------------------------------------------------===//
54 
55 TargetTransformInfo::PopcntSupportKind
56 PPCTTIImpl::getPopcntSupport(unsigned TyWidth) {
57   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
58   if (ST->hasPOPCNTD() != PPCSubtarget::POPCNTD_Unavailable && TyWidth <= 64)
59     return ST->hasPOPCNTD() == PPCSubtarget::POPCNTD_Slow ?
60              TTI::PSK_SlowHardware : TTI::PSK_FastHardware;
61   return TTI::PSK_Software;
62 }
63 
64 std::optional<Instruction *>
65 PPCTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
66   Intrinsic::ID IID = II.getIntrinsicID();
67   switch (IID) {
68   default:
69     break;
70   case Intrinsic::ppc_altivec_lvx:
71   case Intrinsic::ppc_altivec_lvxl:
72     // Turn PPC lvx -> load if the pointer is known aligned.
73     if (getOrEnforceKnownAlignment(
74             II.getArgOperand(0), Align(16), IC.getDataLayout(), &II,
75             &IC.getAssumptionCache(), &IC.getDominatorTree()) >= 16) {
76       Value *Ptr = IC.Builder.CreateBitCast(
77           II.getArgOperand(0), PointerType::getUnqual(II.getType()));
78       return new LoadInst(II.getType(), Ptr, "", false, Align(16));
79     }
80     break;
81   case Intrinsic::ppc_vsx_lxvw4x:
82   case Intrinsic::ppc_vsx_lxvd2x: {
83     // Turn PPC VSX loads into normal loads.
84     Value *Ptr = IC.Builder.CreateBitCast(II.getArgOperand(0),
85                                           PointerType::getUnqual(II.getType()));
86     return new LoadInst(II.getType(), Ptr, Twine(""), false, Align(1));
87   }
88   case Intrinsic::ppc_altivec_stvx:
89   case Intrinsic::ppc_altivec_stvxl:
90     // Turn stvx -> store if the pointer is known aligned.
91     if (getOrEnforceKnownAlignment(
92             II.getArgOperand(1), Align(16), IC.getDataLayout(), &II,
93             &IC.getAssumptionCache(), &IC.getDominatorTree()) >= 16) {
94       Type *OpPtrTy = PointerType::getUnqual(II.getArgOperand(0)->getType());
95       Value *Ptr = IC.Builder.CreateBitCast(II.getArgOperand(1), OpPtrTy);
96       return new StoreInst(II.getArgOperand(0), Ptr, false, Align(16));
97     }
98     break;
99   case Intrinsic::ppc_vsx_stxvw4x:
100   case Intrinsic::ppc_vsx_stxvd2x: {
101     // Turn PPC VSX stores into normal stores.
102     Type *OpPtrTy = PointerType::getUnqual(II.getArgOperand(0)->getType());
103     Value *Ptr = IC.Builder.CreateBitCast(II.getArgOperand(1), OpPtrTy);
104     return new StoreInst(II.getArgOperand(0), Ptr, false, Align(1));
105   }
106   case Intrinsic::ppc_altivec_vperm:
107     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
108     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
109     // a vectorshuffle for little endian, we must undo the transformation
110     // performed on vec_perm in altivec.h.  That is, we must complement
111     // the permutation mask with respect to 31 and reverse the order of
112     // V1 and V2.
113     if (Constant *Mask = dyn_cast<Constant>(II.getArgOperand(2))) {
114       assert(cast<FixedVectorType>(Mask->getType())->getNumElements() == 16 &&
115              "Bad type for intrinsic!");
116 
117       // Check that all of the elements are integer constants or undefs.
118       bool AllEltsOk = true;
119       for (unsigned i = 0; i != 16; ++i) {
120         Constant *Elt = Mask->getAggregateElement(i);
121         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
122           AllEltsOk = false;
123           break;
124         }
125       }
126 
127       if (AllEltsOk) {
128         // Cast the input vectors to byte vectors.
129         Value *Op0 =
130             IC.Builder.CreateBitCast(II.getArgOperand(0), Mask->getType());
131         Value *Op1 =
132             IC.Builder.CreateBitCast(II.getArgOperand(1), Mask->getType());
133         Value *Result = UndefValue::get(Op0->getType());
134 
135         // Only extract each element once.
136         Value *ExtractedElts[32];
137         memset(ExtractedElts, 0, sizeof(ExtractedElts));
138 
139         for (unsigned i = 0; i != 16; ++i) {
140           if (isa<UndefValue>(Mask->getAggregateElement(i)))
141             continue;
142           unsigned Idx =
143               cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
144           Idx &= 31; // Match the hardware behavior.
145           if (DL.isLittleEndian())
146             Idx = 31 - Idx;
147 
148           if (!ExtractedElts[Idx]) {
149             Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
150             Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
151             ExtractedElts[Idx] = IC.Builder.CreateExtractElement(
152                 Idx < 16 ? Op0ToUse : Op1ToUse, IC.Builder.getInt32(Idx & 15));
153           }
154 
155           // Insert this value into the result vector.
156           Result = IC.Builder.CreateInsertElement(Result, ExtractedElts[Idx],
157                                                   IC.Builder.getInt32(i));
158         }
159         return CastInst::Create(Instruction::BitCast, Result, II.getType());
160       }
161     }
162     break;
163   }
164   return std::nullopt;
165 }
166 
167 InstructionCost PPCTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
168                                           TTI::TargetCostKind CostKind) {
169   if (DisablePPCConstHoist)
170     return BaseT::getIntImmCost(Imm, Ty, CostKind);
171 
172   assert(Ty->isIntegerTy());
173 
174   unsigned BitSize = Ty->getPrimitiveSizeInBits();
175   if (BitSize == 0)
176     return ~0U;
177 
178   if (Imm == 0)
179     return TTI::TCC_Free;
180 
181   if (Imm.getBitWidth() <= 64) {
182     if (isInt<16>(Imm.getSExtValue()))
183       return TTI::TCC_Basic;
184 
185     if (isInt<32>(Imm.getSExtValue())) {
186       // A constant that can be materialized using lis.
187       if ((Imm.getZExtValue() & 0xFFFF) == 0)
188         return TTI::TCC_Basic;
189 
190       return 2 * TTI::TCC_Basic;
191     }
192   }
193 
194   return 4 * TTI::TCC_Basic;
195 }
196 
197 InstructionCost PPCTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
198                                                 const APInt &Imm, Type *Ty,
199                                                 TTI::TargetCostKind CostKind) {
200   if (DisablePPCConstHoist)
201     return BaseT::getIntImmCostIntrin(IID, Idx, Imm, Ty, CostKind);
202 
203   assert(Ty->isIntegerTy());
204 
205   unsigned BitSize = Ty->getPrimitiveSizeInBits();
206   if (BitSize == 0)
207     return ~0U;
208 
209   switch (IID) {
210   default:
211     return TTI::TCC_Free;
212   case Intrinsic::sadd_with_overflow:
213   case Intrinsic::uadd_with_overflow:
214   case Intrinsic::ssub_with_overflow:
215   case Intrinsic::usub_with_overflow:
216     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<16>(Imm.getSExtValue()))
217       return TTI::TCC_Free;
218     break;
219   case Intrinsic::experimental_stackmap:
220     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
221       return TTI::TCC_Free;
222     break;
223   case Intrinsic::experimental_patchpoint_void:
224   case Intrinsic::experimental_patchpoint_i64:
225     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
226       return TTI::TCC_Free;
227     break;
228   }
229   return PPCTTIImpl::getIntImmCost(Imm, Ty, CostKind);
230 }
231 
232 InstructionCost PPCTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
233                                               const APInt &Imm, Type *Ty,
234                                               TTI::TargetCostKind CostKind,
235                                               Instruction *Inst) {
236   if (DisablePPCConstHoist)
237     return BaseT::getIntImmCostInst(Opcode, Idx, Imm, Ty, CostKind, Inst);
238 
239   assert(Ty->isIntegerTy());
240 
241   unsigned BitSize = Ty->getPrimitiveSizeInBits();
242   if (BitSize == 0)
243     return ~0U;
244 
245   unsigned ImmIdx = ~0U;
246   bool ShiftedFree = false, RunFree = false, UnsignedFree = false,
247        ZeroFree = false;
248   switch (Opcode) {
249   default:
250     return TTI::TCC_Free;
251   case Instruction::GetElementPtr:
252     // Always hoist the base address of a GetElementPtr. This prevents the
253     // creation of new constants for every base constant that gets constant
254     // folded with the offset.
255     if (Idx == 0)
256       return 2 * TTI::TCC_Basic;
257     return TTI::TCC_Free;
258   case Instruction::And:
259     RunFree = true; // (for the rotate-and-mask instructions)
260     [[fallthrough]];
261   case Instruction::Add:
262   case Instruction::Or:
263   case Instruction::Xor:
264     ShiftedFree = true;
265     [[fallthrough]];
266   case Instruction::Sub:
267   case Instruction::Mul:
268   case Instruction::Shl:
269   case Instruction::LShr:
270   case Instruction::AShr:
271     ImmIdx = 1;
272     break;
273   case Instruction::ICmp:
274     UnsignedFree = true;
275     ImmIdx = 1;
276     // Zero comparisons can use record-form instructions.
277     [[fallthrough]];
278   case Instruction::Select:
279     ZeroFree = true;
280     break;
281   case Instruction::PHI:
282   case Instruction::Call:
283   case Instruction::Ret:
284   case Instruction::Load:
285   case Instruction::Store:
286     break;
287   }
288 
289   if (ZeroFree && Imm == 0)
290     return TTI::TCC_Free;
291 
292   if (Idx == ImmIdx && Imm.getBitWidth() <= 64) {
293     if (isInt<16>(Imm.getSExtValue()))
294       return TTI::TCC_Free;
295 
296     if (RunFree) {
297       if (Imm.getBitWidth() <= 32 &&
298           (isShiftedMask_32(Imm.getZExtValue()) ||
299            isShiftedMask_32(~Imm.getZExtValue())))
300         return TTI::TCC_Free;
301 
302       if (ST->isPPC64() &&
303           (isShiftedMask_64(Imm.getZExtValue()) ||
304            isShiftedMask_64(~Imm.getZExtValue())))
305         return TTI::TCC_Free;
306     }
307 
308     if (UnsignedFree && isUInt<16>(Imm.getZExtValue()))
309       return TTI::TCC_Free;
310 
311     if (ShiftedFree && (Imm.getZExtValue() & 0xFFFF) == 0)
312       return TTI::TCC_Free;
313   }
314 
315   return PPCTTIImpl::getIntImmCost(Imm, Ty, CostKind);
316 }
317 
318 // Check if the current Type is an MMA vector type. Valid MMA types are
319 // v256i1 and v512i1 respectively.
320 static bool isMMAType(Type *Ty) {
321   return Ty->isVectorTy() && (Ty->getScalarSizeInBits() == 1) &&
322          (Ty->getPrimitiveSizeInBits() > 128);
323 }
324 
325 InstructionCost PPCTTIImpl::getInstructionCost(const User *U,
326                                                ArrayRef<const Value *> Operands,
327                                                TTI::TargetCostKind CostKind) {
328   // We already implement getCastInstrCost and getMemoryOpCost where we perform
329   // the vector adjustment there.
330   if (isa<CastInst>(U) || isa<LoadInst>(U) || isa<StoreInst>(U))
331     return BaseT::getInstructionCost(U, Operands, CostKind);
332 
333   if (U->getType()->isVectorTy()) {
334     // Instructions that need to be split should cost more.
335     std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(U->getType());
336     return LT.first * BaseT::getInstructionCost(U, Operands, CostKind);
337   }
338 
339   return BaseT::getInstructionCost(U, Operands, CostKind);
340 }
341 
342 // Determining the address of a TLS variable results in a function call in
343 // certain TLS models.
344 static bool memAddrUsesCTR(const Value *MemAddr, const PPCTargetMachine &TM,
345                            SmallPtrSetImpl<const Value *> &Visited) {
346   // No need to traverse again if we already checked this operand.
347   if (!Visited.insert(MemAddr).second)
348     return false;
349   const auto *GV = dyn_cast<GlobalValue>(MemAddr);
350   if (!GV) {
351     // Recurse to check for constants that refer to TLS global variables.
352     if (const auto *CV = dyn_cast<Constant>(MemAddr))
353       for (const auto &CO : CV->operands())
354         if (memAddrUsesCTR(CO, TM, Visited))
355           return true;
356     return false;
357   }
358 
359   if (!GV->isThreadLocal())
360     return false;
361   TLSModel::Model Model = TM.getTLSModel(GV);
362   return Model == TLSModel::GeneralDynamic || Model == TLSModel::LocalDynamic;
363 }
364 
365 bool PPCTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
366                                           AssumptionCache &AC,
367                                           TargetLibraryInfo *LibInfo,
368                                           HardwareLoopInfo &HWLoopInfo) {
369   const PPCTargetMachine &TM = ST->getTargetMachine();
370   TargetSchedModel SchedModel;
371   SchedModel.init(ST);
372 
373   // Do not convert small short loops to CTR loop.
374   unsigned ConstTripCount = SE.getSmallConstantTripCount(L);
375   if (ConstTripCount && ConstTripCount < SmallCTRLoopThreshold) {
376     SmallPtrSet<const Value *, 32> EphValues;
377     CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
378     CodeMetrics Metrics;
379     for (BasicBlock *BB : L->blocks())
380       Metrics.analyzeBasicBlock(BB, *this, EphValues);
381     // 6 is an approximate latency for the mtctr instruction.
382     if (Metrics.NumInsts <= (6 * SchedModel.getIssueWidth()))
383       return false;
384   }
385 
386   SmallVector<BasicBlock*, 4> ExitingBlocks;
387   L->getExitingBlocks(ExitingBlocks);
388 
389   // If there is an exit edge known to be frequently taken,
390   // we should not transform this loop.
391   for (auto &BB : ExitingBlocks) {
392     Instruction *TI = BB->getTerminator();
393     if (!TI) continue;
394 
395     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
396       uint64_t TrueWeight = 0, FalseWeight = 0;
397       if (!BI->isConditional() ||
398           !extractBranchWeights(*BI, TrueWeight, FalseWeight))
399         continue;
400 
401       // If the exit path is more frequent than the loop path,
402       // we return here without further analysis for this loop.
403       bool TrueIsExit = !L->contains(BI->getSuccessor(0));
404       if (( TrueIsExit && FalseWeight < TrueWeight) ||
405           (!TrueIsExit && FalseWeight > TrueWeight))
406         return false;
407     }
408   }
409 
410   // If an exit block has a PHI that accesses a TLS variable as one of the
411   // incoming values from the loop, we cannot produce a CTR loop because the
412   // address for that value will be computed in the loop.
413   SmallVector<BasicBlock *, 4> ExitBlocks;
414   L->getExitBlocks(ExitBlocks);
415   SmallPtrSet<const Value *, 4> Visited;
416   for (auto &BB : ExitBlocks) {
417     for (auto &PHI : BB->phis()) {
418       for (int Idx = 0, EndIdx = PHI.getNumIncomingValues(); Idx < EndIdx;
419            Idx++) {
420         const BasicBlock *IncomingBB = PHI.getIncomingBlock(Idx);
421         const Value *IncomingValue = PHI.getIncomingValue(Idx);
422         if (L->contains(IncomingBB) &&
423             memAddrUsesCTR(IncomingValue, TM, Visited))
424           return false;
425       }
426     }
427   }
428 
429   LLVMContext &C = L->getHeader()->getContext();
430   HWLoopInfo.CountType = TM.isPPC64() ?
431     Type::getInt64Ty(C) : Type::getInt32Ty(C);
432   HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
433   return true;
434 }
435 
436 void PPCTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
437                                          TTI::UnrollingPreferences &UP,
438                                          OptimizationRemarkEmitter *ORE) {
439   if (ST->getCPUDirective() == PPC::DIR_A2) {
440     // The A2 is in-order with a deep pipeline, and concatenation unrolling
441     // helps expose latency-hiding opportunities to the instruction scheduler.
442     UP.Partial = UP.Runtime = true;
443 
444     // We unroll a lot on the A2 (hundreds of instructions), and the benefits
445     // often outweigh the cost of a division to compute the trip count.
446     UP.AllowExpensiveTripCount = true;
447   }
448 
449   BaseT::getUnrollingPreferences(L, SE, UP, ORE);
450 }
451 
452 void PPCTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
453                                        TTI::PeelingPreferences &PP) {
454   BaseT::getPeelingPreferences(L, SE, PP);
455 }
456 // This function returns true to allow using coldcc calling convention.
457 // Returning true results in coldcc being used for functions which are cold at
458 // all call sites when the callers of the functions are not calling any other
459 // non coldcc functions.
460 bool PPCTTIImpl::useColdCCForColdCall(Function &F) {
461   return EnablePPCColdCC;
462 }
463 
464 bool PPCTTIImpl::enableAggressiveInterleaving(bool LoopHasReductions) {
465   // On the A2, always unroll aggressively.
466   if (ST->getCPUDirective() == PPC::DIR_A2)
467     return true;
468 
469   return LoopHasReductions;
470 }
471 
472 PPCTTIImpl::TTI::MemCmpExpansionOptions
473 PPCTTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
474   TTI::MemCmpExpansionOptions Options;
475   Options.LoadSizes = {8, 4, 2, 1};
476   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
477   return Options;
478 }
479 
480 bool PPCTTIImpl::enableInterleavedAccessVectorization() {
481   return true;
482 }
483 
484 unsigned PPCTTIImpl::getNumberOfRegisters(unsigned ClassID) const {
485   assert(ClassID == GPRRC || ClassID == FPRRC ||
486          ClassID == VRRC || ClassID == VSXRC);
487   if (ST->hasVSX()) {
488     assert(ClassID == GPRRC || ClassID == VSXRC || ClassID == VRRC);
489     return ClassID == VSXRC ? 64 : 32;
490   }
491   assert(ClassID == GPRRC || ClassID == FPRRC || ClassID == VRRC);
492   return 32;
493 }
494 
495 unsigned PPCTTIImpl::getRegisterClassForType(bool Vector, Type *Ty) const {
496   if (Vector)
497     return ST->hasVSX() ? VSXRC : VRRC;
498   else if (Ty && (Ty->getScalarType()->isFloatTy() ||
499                   Ty->getScalarType()->isDoubleTy()))
500     return ST->hasVSX() ? VSXRC : FPRRC;
501   else if (Ty && (Ty->getScalarType()->isFP128Ty() ||
502                   Ty->getScalarType()->isPPC_FP128Ty()))
503     return VRRC;
504   else if (Ty && Ty->getScalarType()->isHalfTy())
505     return VSXRC;
506   else
507     return GPRRC;
508 }
509 
510 const char* PPCTTIImpl::getRegisterClassName(unsigned ClassID) const {
511 
512   switch (ClassID) {
513     default:
514       llvm_unreachable("unknown register class");
515       return "PPC::unknown register class";
516     case GPRRC:       return "PPC::GPRRC";
517     case FPRRC:       return "PPC::FPRRC";
518     case VRRC:        return "PPC::VRRC";
519     case VSXRC:       return "PPC::VSXRC";
520   }
521 }
522 
523 TypeSize
524 PPCTTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
525   switch (K) {
526   case TargetTransformInfo::RGK_Scalar:
527     return TypeSize::getFixed(ST->isPPC64() ? 64 : 32);
528   case TargetTransformInfo::RGK_FixedWidthVector:
529     return TypeSize::getFixed(ST->hasAltivec() ? 128 : 0);
530   case TargetTransformInfo::RGK_ScalableVector:
531     return TypeSize::getScalable(0);
532   }
533 
534   llvm_unreachable("Unsupported register kind");
535 }
536 
537 unsigned PPCTTIImpl::getCacheLineSize() const {
538   // Starting with P7 we have a cache line size of 128.
539   unsigned Directive = ST->getCPUDirective();
540   // Assume that Future CPU has the same cache line size as the others.
541   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
542       Directive == PPC::DIR_PWR9 || Directive == PPC::DIR_PWR10 ||
543       Directive == PPC::DIR_PWR_FUTURE)
544     return 128;
545 
546   // On other processors return a default of 64 bytes.
547   return 64;
548 }
549 
550 unsigned PPCTTIImpl::getPrefetchDistance() const {
551   return 300;
552 }
553 
554 unsigned PPCTTIImpl::getMaxInterleaveFactor(unsigned VF) {
555   unsigned Directive = ST->getCPUDirective();
556   // The 440 has no SIMD support, but floating-point instructions
557   // have a 5-cycle latency, so unroll by 5x for latency hiding.
558   if (Directive == PPC::DIR_440)
559     return 5;
560 
561   // The A2 has no SIMD support, but floating-point instructions
562   // have a 6-cycle latency, so unroll by 6x for latency hiding.
563   if (Directive == PPC::DIR_A2)
564     return 6;
565 
566   // FIXME: For lack of any better information, do no harm...
567   if (Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500)
568     return 1;
569 
570   // For P7 and P8, floating-point instructions have a 6-cycle latency and
571   // there are two execution units, so unroll by 12x for latency hiding.
572   // FIXME: the same for P9 as previous gen until POWER9 scheduling is ready
573   // FIXME: the same for P10 as previous gen until POWER10 scheduling is ready
574   // Assume that future is the same as the others.
575   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
576       Directive == PPC::DIR_PWR9 || Directive == PPC::DIR_PWR10 ||
577       Directive == PPC::DIR_PWR_FUTURE)
578     return 12;
579 
580   // For most things, modern systems have two execution units (and
581   // out-of-order execution).
582   return 2;
583 }
584 
585 // Returns a cost adjustment factor to adjust the cost of vector instructions
586 // on targets which there is overlap between the vector and scalar units,
587 // thereby reducing the overall throughput of vector code wrt. scalar code.
588 // An invalid instruction cost is returned if the type is an MMA vector type.
589 InstructionCost PPCTTIImpl::vectorCostAdjustmentFactor(unsigned Opcode,
590                                                        Type *Ty1, Type *Ty2) {
591   // If the vector type is of an MMA type (v256i1, v512i1), an invalid
592   // instruction cost is returned. This is to signify to other cost computing
593   // functions to return the maximum instruction cost in order to prevent any
594   // opportunities for the optimizer to produce MMA types within the IR.
595   if (isMMAType(Ty1))
596     return InstructionCost::getInvalid();
597 
598   if (!ST->vectorsUseTwoUnits() || !Ty1->isVectorTy())
599     return InstructionCost(1);
600 
601   std::pair<InstructionCost, MVT> LT1 = getTypeLegalizationCost(Ty1);
602   // If type legalization involves splitting the vector, we don't want to
603   // double the cost at every step - only the last step.
604   if (LT1.first != 1 || !LT1.second.isVector())
605     return InstructionCost(1);
606 
607   int ISD = TLI->InstructionOpcodeToISD(Opcode);
608   if (TLI->isOperationExpand(ISD, LT1.second))
609     return InstructionCost(1);
610 
611   if (Ty2) {
612     std::pair<InstructionCost, MVT> LT2 = getTypeLegalizationCost(Ty2);
613     if (LT2.first != 1 || !LT2.second.isVector())
614       return InstructionCost(1);
615   }
616 
617   return InstructionCost(2);
618 }
619 
620 InstructionCost PPCTTIImpl::getArithmeticInstrCost(
621     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
622     TTI::OperandValueInfo Op1Info, TTI::OperandValueInfo Op2Info,
623     ArrayRef<const Value *> Args,
624     const Instruction *CxtI) {
625   assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
626 
627   InstructionCost CostFactor = vectorCostAdjustmentFactor(Opcode, Ty, nullptr);
628   if (!CostFactor.isValid())
629     return InstructionCost::getMax();
630 
631   // TODO: Handle more cost kinds.
632   if (CostKind != TTI::TCK_RecipThroughput)
633     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
634                                          Op2Info, Args, CxtI);
635 
636   // Fallback to the default implementation.
637   InstructionCost Cost = BaseT::getArithmeticInstrCost(
638       Opcode, Ty, CostKind, Op1Info, Op2Info);
639   return Cost * CostFactor;
640 }
641 
642 InstructionCost PPCTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp,
643                                            ArrayRef<int> Mask,
644                                            TTI::TargetCostKind CostKind,
645                                            int Index, Type *SubTp,
646                                            ArrayRef<const Value *> Args) {
647 
648   InstructionCost CostFactor =
649       vectorCostAdjustmentFactor(Instruction::ShuffleVector, Tp, nullptr);
650   if (!CostFactor.isValid())
651     return InstructionCost::getMax();
652 
653   // Legalize the type.
654   std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Tp);
655 
656   // PPC, for both Altivec/VSX, support cheap arbitrary permutations
657   // (at least in the sense that there need only be one non-loop-invariant
658   // instruction). We need one such shuffle instruction for each actual
659   // register (this is not true for arbitrary shuffles, but is true for the
660   // structured types of shuffles covered by TTI::ShuffleKind).
661   return LT.first * CostFactor;
662 }
663 
664 InstructionCost PPCTTIImpl::getCFInstrCost(unsigned Opcode,
665                                            TTI::TargetCostKind CostKind,
666                                            const Instruction *I) {
667   if (CostKind != TTI::TCK_RecipThroughput)
668     return Opcode == Instruction::PHI ? 0 : 1;
669   // Branches are assumed to be predicted.
670   return 0;
671 }
672 
673 InstructionCost PPCTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst,
674                                              Type *Src,
675                                              TTI::CastContextHint CCH,
676                                              TTI::TargetCostKind CostKind,
677                                              const Instruction *I) {
678   assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
679 
680   InstructionCost CostFactor = vectorCostAdjustmentFactor(Opcode, Dst, Src);
681   if (!CostFactor.isValid())
682     return InstructionCost::getMax();
683 
684   InstructionCost Cost =
685       BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
686   Cost *= CostFactor;
687   // TODO: Allow non-throughput costs that aren't binary.
688   if (CostKind != TTI::TCK_RecipThroughput)
689     return Cost == 0 ? 0 : 1;
690   return Cost;
691 }
692 
693 InstructionCost PPCTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
694                                                Type *CondTy,
695                                                CmpInst::Predicate VecPred,
696                                                TTI::TargetCostKind CostKind,
697                                                const Instruction *I) {
698   InstructionCost CostFactor =
699       vectorCostAdjustmentFactor(Opcode, ValTy, nullptr);
700   if (!CostFactor.isValid())
701     return InstructionCost::getMax();
702 
703   InstructionCost Cost =
704       BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
705   // TODO: Handle other cost kinds.
706   if (CostKind != TTI::TCK_RecipThroughput)
707     return Cost;
708   return Cost * CostFactor;
709 }
710 
711 InstructionCost PPCTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
712                                                unsigned Index) {
713   assert(Val->isVectorTy() && "This must be a vector type");
714 
715   int ISD = TLI->InstructionOpcodeToISD(Opcode);
716   assert(ISD && "Invalid opcode");
717 
718   InstructionCost CostFactor = vectorCostAdjustmentFactor(Opcode, Val, nullptr);
719   if (!CostFactor.isValid())
720     return InstructionCost::getMax();
721 
722   InstructionCost Cost = BaseT::getVectorInstrCost(Opcode, Val, Index);
723   Cost *= CostFactor;
724 
725   if (ST->hasVSX() && Val->getScalarType()->isDoubleTy()) {
726     // Double-precision scalars are already located in index #0 (or #1 if LE).
727     if (ISD == ISD::EXTRACT_VECTOR_ELT &&
728         Index == (ST->isLittleEndian() ? 1 : 0))
729       return 0;
730 
731     return Cost;
732 
733   } else if (Val->getScalarType()->isIntegerTy() && Index != -1U) {
734     if (ST->hasP9Altivec()) {
735       if (ISD == ISD::INSERT_VECTOR_ELT)
736         // A move-to VSR and a permute/insert.  Assume vector operation cost
737         // for both (cost will be 2x on P9).
738         return 2 * CostFactor;
739 
740       // It's an extract.  Maybe we can do a cheap move-from VSR.
741       unsigned EltSize = Val->getScalarSizeInBits();
742       if (EltSize == 64) {
743         unsigned MfvsrdIndex = ST->isLittleEndian() ? 1 : 0;
744         if (Index == MfvsrdIndex)
745           return 1;
746       } else if (EltSize == 32) {
747         unsigned MfvsrwzIndex = ST->isLittleEndian() ? 2 : 1;
748         if (Index == MfvsrwzIndex)
749           return 1;
750       }
751 
752       // We need a vector extract (or mfvsrld).  Assume vector operation cost.
753       // The cost of the load constant for a vector extract is disregarded
754       // (invariant, easily schedulable).
755       return CostFactor;
756 
757     } else if (ST->hasDirectMove())
758       // Assume permute has standard cost.
759       // Assume move-to/move-from VSR have 2x standard cost.
760       return 3;
761   }
762 
763   // Estimated cost of a load-hit-store delay.  This was obtained
764   // experimentally as a minimum needed to prevent unprofitable
765   // vectorization for the paq8p benchmark.  It may need to be
766   // raised further if other unprofitable cases remain.
767   unsigned LHSPenalty = 2;
768   if (ISD == ISD::INSERT_VECTOR_ELT)
769     LHSPenalty += 7;
770 
771   // Vector element insert/extract with Altivec is very expensive,
772   // because they require store and reload with the attendant
773   // processor stall for load-hit-store.  Until VSX is available,
774   // these need to be estimated as very costly.
775   if (ISD == ISD::EXTRACT_VECTOR_ELT ||
776       ISD == ISD::INSERT_VECTOR_ELT)
777     return LHSPenalty + Cost;
778 
779   return Cost;
780 }
781 
782 InstructionCost PPCTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
783                                             MaybeAlign Alignment,
784                                             unsigned AddressSpace,
785                                             TTI::TargetCostKind CostKind,
786                                             TTI::OperandValueInfo OpInfo,
787                                             const Instruction *I) {
788 
789   InstructionCost CostFactor = vectorCostAdjustmentFactor(Opcode, Src, nullptr);
790   if (!CostFactor.isValid())
791     return InstructionCost::getMax();
792 
793   if (TLI->getValueType(DL, Src,  true) == MVT::Other)
794     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
795                                   CostKind);
796   // Legalize the type.
797   std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Src);
798   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
799          "Invalid Opcode");
800 
801   InstructionCost Cost =
802       BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, CostKind);
803   // TODO: Handle other cost kinds.
804   if (CostKind != TTI::TCK_RecipThroughput)
805     return Cost;
806 
807   Cost *= CostFactor;
808 
809   bool IsAltivecType = ST->hasAltivec() &&
810                        (LT.second == MVT::v16i8 || LT.second == MVT::v8i16 ||
811                         LT.second == MVT::v4i32 || LT.second == MVT::v4f32);
812   bool IsVSXType = ST->hasVSX() &&
813                    (LT.second == MVT::v2f64 || LT.second == MVT::v2i64);
814 
815   // VSX has 32b/64b load instructions. Legalization can handle loading of
816   // 32b/64b to VSR correctly and cheaply. But BaseT::getMemoryOpCost and
817   // PPCTargetLowering can't compute the cost appropriately. So here we
818   // explicitly check this case.
819   unsigned MemBytes = Src->getPrimitiveSizeInBits();
820   if (Opcode == Instruction::Load && ST->hasVSX() && IsAltivecType &&
821       (MemBytes == 64 || (ST->hasP8Vector() && MemBytes == 32)))
822     return 1;
823 
824   // Aligned loads and stores are easy.
825   unsigned SrcBytes = LT.second.getStoreSize();
826   if (!SrcBytes || !Alignment || *Alignment >= SrcBytes)
827     return Cost;
828 
829   // If we can use the permutation-based load sequence, then this is also
830   // relatively cheap (not counting loop-invariant instructions): one load plus
831   // one permute (the last load in a series has extra cost, but we're
832   // neglecting that here). Note that on the P7, we could do unaligned loads
833   // for Altivec types using the VSX instructions, but that's more expensive
834   // than using the permutation-based load sequence. On the P8, that's no
835   // longer true.
836   if (Opcode == Instruction::Load && (!ST->hasP8Vector() && IsAltivecType) &&
837       *Alignment >= LT.second.getScalarType().getStoreSize())
838     return Cost + LT.first; // Add the cost of the permutations.
839 
840   // For VSX, we can do unaligned loads and stores on Altivec/VSX types. On the
841   // P7, unaligned vector loads are more expensive than the permutation-based
842   // load sequence, so that might be used instead, but regardless, the net cost
843   // is about the same (not counting loop-invariant instructions).
844   if (IsVSXType || (ST->hasVSX() && IsAltivecType))
845     return Cost;
846 
847   // Newer PPC supports unaligned memory access.
848   if (TLI->allowsMisalignedMemoryAccesses(LT.second, 0))
849     return Cost;
850 
851   // PPC in general does not support unaligned loads and stores. They'll need
852   // to be decomposed based on the alignment factor.
853 
854   // Add the cost of each scalar load or store.
855   assert(Alignment);
856   Cost += LT.first * ((SrcBytes / Alignment->value()) - 1);
857 
858   // For a vector type, there is also scalarization overhead (only for
859   // stores, loads are expanded using the vector-load + permutation sequence,
860   // which is much less expensive).
861   if (Src->isVectorTy() && Opcode == Instruction::Store)
862     for (int i = 0, e = cast<FixedVectorType>(Src)->getNumElements(); i < e;
863          ++i)
864       Cost += getVectorInstrCost(Instruction::ExtractElement, Src, i);
865 
866   return Cost;
867 }
868 
869 InstructionCost PPCTTIImpl::getInterleavedMemoryOpCost(
870     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
871     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
872     bool UseMaskForCond, bool UseMaskForGaps) {
873   InstructionCost CostFactor =
874       vectorCostAdjustmentFactor(Opcode, VecTy, nullptr);
875   if (!CostFactor.isValid())
876     return InstructionCost::getMax();
877 
878   if (UseMaskForCond || UseMaskForGaps)
879     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
880                                              Alignment, AddressSpace, CostKind,
881                                              UseMaskForCond, UseMaskForGaps);
882 
883   assert(isa<VectorType>(VecTy) &&
884          "Expect a vector type for interleaved memory op");
885 
886   // Legalize the type.
887   std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VecTy);
888 
889   // Firstly, the cost of load/store operation.
890   InstructionCost Cost = getMemoryOpCost(Opcode, VecTy, MaybeAlign(Alignment),
891                                          AddressSpace, CostKind);
892 
893   // PPC, for both Altivec/VSX, support cheap arbitrary permutations
894   // (at least in the sense that there need only be one non-loop-invariant
895   // instruction). For each result vector, we need one shuffle per incoming
896   // vector (except that the first shuffle can take two incoming vectors
897   // because it does not need to take itself).
898   Cost += Factor*(LT.first-1);
899 
900   return Cost;
901 }
902 
903 InstructionCost
904 PPCTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
905                                   TTI::TargetCostKind CostKind) {
906   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
907 }
908 
909 bool PPCTTIImpl::areTypesABICompatible(const Function *Caller,
910                                        const Function *Callee,
911                                        const ArrayRef<Type *> &Types) const {
912 
913   // We need to ensure that argument promotion does not
914   // attempt to promote pointers to MMA types (__vector_pair
915   // and __vector_quad) since these types explicitly cannot be
916   // passed as arguments. Both of these types are larger than
917   // the 128-bit Altivec vectors and have a scalar size of 1 bit.
918   if (!BaseT::areTypesABICompatible(Caller, Callee, Types))
919     return false;
920 
921   return llvm::none_of(Types, [](Type *Ty) {
922     if (Ty->isSized())
923       return Ty->isIntOrIntVectorTy(1) && Ty->getPrimitiveSizeInBits() > 128;
924     return false;
925   });
926 }
927 
928 bool PPCTTIImpl::canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE,
929                             LoopInfo *LI, DominatorTree *DT,
930                             AssumptionCache *AC, TargetLibraryInfo *LibInfo) {
931   // Process nested loops first.
932   for (Loop *I : *L)
933     if (canSaveCmp(I, BI, SE, LI, DT, AC, LibInfo))
934       return false; // Stop search.
935 
936   HardwareLoopInfo HWLoopInfo(L);
937 
938   if (!HWLoopInfo.canAnalyze(*LI))
939     return false;
940 
941   if (!isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo))
942     return false;
943 
944   if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT))
945     return false;
946 
947   *BI = HWLoopInfo.ExitBranch;
948   return true;
949 }
950 
951 bool PPCTTIImpl::isLSRCostLess(const TargetTransformInfo::LSRCost &C1,
952                                const TargetTransformInfo::LSRCost &C2) {
953   // PowerPC default behaviour here is "instruction number 1st priority".
954   // If LsrNoInsnsCost is set, call default implementation.
955   if (!LsrNoInsnsCost)
956     return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost, C1.NumIVMuls,
957                     C1.NumBaseAdds, C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
958            std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost, C2.NumIVMuls,
959                     C2.NumBaseAdds, C2.ScaleCost, C2.ImmCost, C2.SetupCost);
960   else
961     return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
962 }
963 
964 bool PPCTTIImpl::isNumRegsMajorCostOfLSR() {
965   return false;
966 }
967 
968 bool PPCTTIImpl::shouldBuildRelLookupTables() const {
969   const PPCTargetMachine &TM = ST->getTargetMachine();
970   // XCOFF hasn't implemented lowerRelativeReference, disable non-ELF for now.
971   if (!TM.isELFv2ABI())
972     return false;
973   return BaseT::shouldBuildRelLookupTables();
974 }
975 
976 bool PPCTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
977                                     MemIntrinsicInfo &Info) {
978   switch (Inst->getIntrinsicID()) {
979   case Intrinsic::ppc_altivec_lvx:
980   case Intrinsic::ppc_altivec_lvxl:
981   case Intrinsic::ppc_altivec_lvebx:
982   case Intrinsic::ppc_altivec_lvehx:
983   case Intrinsic::ppc_altivec_lvewx:
984   case Intrinsic::ppc_vsx_lxvd2x:
985   case Intrinsic::ppc_vsx_lxvw4x:
986   case Intrinsic::ppc_vsx_lxvd2x_be:
987   case Intrinsic::ppc_vsx_lxvw4x_be:
988   case Intrinsic::ppc_vsx_lxvl:
989   case Intrinsic::ppc_vsx_lxvll:
990   case Intrinsic::ppc_vsx_lxvp: {
991     Info.PtrVal = Inst->getArgOperand(0);
992     Info.ReadMem = true;
993     Info.WriteMem = false;
994     return true;
995   }
996   case Intrinsic::ppc_altivec_stvx:
997   case Intrinsic::ppc_altivec_stvxl:
998   case Intrinsic::ppc_altivec_stvebx:
999   case Intrinsic::ppc_altivec_stvehx:
1000   case Intrinsic::ppc_altivec_stvewx:
1001   case Intrinsic::ppc_vsx_stxvd2x:
1002   case Intrinsic::ppc_vsx_stxvw4x:
1003   case Intrinsic::ppc_vsx_stxvd2x_be:
1004   case Intrinsic::ppc_vsx_stxvw4x_be:
1005   case Intrinsic::ppc_vsx_stxvl:
1006   case Intrinsic::ppc_vsx_stxvll:
1007   case Intrinsic::ppc_vsx_stxvp: {
1008     Info.PtrVal = Inst->getArgOperand(1);
1009     Info.ReadMem = false;
1010     Info.WriteMem = true;
1011     return true;
1012   }
1013   case Intrinsic::ppc_stbcx:
1014   case Intrinsic::ppc_sthcx:
1015   case Intrinsic::ppc_stdcx:
1016   case Intrinsic::ppc_stwcx: {
1017     Info.PtrVal = Inst->getArgOperand(0);
1018     Info.ReadMem = false;
1019     Info.WriteMem = true;
1020     return true;
1021   }
1022   default:
1023     break;
1024   }
1025 
1026   return false;
1027 }
1028 
1029 bool PPCTTIImpl::hasActiveVectorLength(unsigned Opcode, Type *DataType,
1030                                        Align Alignment) const {
1031   // Only load and stores instructions can have variable vector length on Power.
1032   if (Opcode != Instruction::Load && Opcode != Instruction::Store)
1033     return false;
1034   // Loads/stores with length instructions use bits 0-7 of the GPR operand and
1035   // therefore cannot be used in 32-bit mode.
1036   if ((!ST->hasP9Vector() && !ST->hasP10Vector()) || !ST->isPPC64())
1037     return false;
1038   if (isa<FixedVectorType>(DataType)) {
1039     unsigned VecWidth = DataType->getPrimitiveSizeInBits();
1040     return VecWidth == 128;
1041   }
1042   Type *ScalarTy = DataType->getScalarType();
1043 
1044   if (ScalarTy->isPointerTy())
1045     return true;
1046 
1047   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
1048     return true;
1049 
1050   if (!ScalarTy->isIntegerTy())
1051     return false;
1052 
1053   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
1054   return IntWidth == 8 || IntWidth == 16 || IntWidth == 32 || IntWidth == 64;
1055 }
1056 
1057 InstructionCost PPCTTIImpl::getVPMemoryOpCost(unsigned Opcode, Type *Src,
1058                                               Align Alignment,
1059                                               unsigned AddressSpace,
1060                                               TTI::TargetCostKind CostKind,
1061                                               const Instruction *I) {
1062   InstructionCost Cost = BaseT::getVPMemoryOpCost(Opcode, Src, Alignment,
1063                                                   AddressSpace, CostKind, I);
1064   if (TLI->getValueType(DL, Src, true) == MVT::Other)
1065     return Cost;
1066   // TODO: Handle other cost kinds.
1067   if (CostKind != TTI::TCK_RecipThroughput)
1068     return Cost;
1069 
1070   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
1071          "Invalid Opcode");
1072 
1073   auto *SrcVTy = dyn_cast<FixedVectorType>(Src);
1074   assert(SrcVTy && "Expected a vector type for VP memory operations");
1075 
1076   if (hasActiveVectorLength(Opcode, Src, Alignment)) {
1077     std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(SrcVTy);
1078 
1079     InstructionCost CostFactor =
1080         vectorCostAdjustmentFactor(Opcode, Src, nullptr);
1081     if (!CostFactor.isValid())
1082       return InstructionCost::getMax();
1083 
1084     InstructionCost Cost = LT.first * CostFactor;
1085     assert(Cost.isValid() && "Expected valid cost");
1086 
1087     // On P9 but not on P10, if the op is misaligned then it will cause a
1088     // pipeline flush. Otherwise the VSX masked memops cost the same as unmasked
1089     // ones.
1090     const Align DesiredAlignment(16);
1091     if (Alignment >= DesiredAlignment || ST->getCPUDirective() != PPC::DIR_PWR9)
1092       return Cost;
1093 
1094     // Since alignment may be under estimated, we try to compute the probability
1095     // that the actual address is aligned to the desired boundary. For example
1096     // an 8-byte aligned load is assumed to be actually 16-byte aligned half the
1097     // time, while a 4-byte aligned load has a 25% chance of being 16-byte
1098     // aligned.
1099     float AlignmentProb = ((float)Alignment.value()) / DesiredAlignment.value();
1100     float MisalignmentProb = 1.0 - AlignmentProb;
1101     return (MisalignmentProb * P9PipelineFlushEstimate) +
1102            (AlignmentProb * *Cost.getValue());
1103   }
1104 
1105   // Usually we should not get to this point, but the following is an attempt to
1106   // model the cost of legalization. Currently we can only lower intrinsics with
1107   // evl but no mask, on Power 9/10. Otherwise, we must scalarize.
1108   return getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace, CostKind);
1109 }
1110 
1111 bool PPCTTIImpl::supportsTailCallFor(const CallBase *CB) const {
1112   // Subtargets using PC-Relative addressing supported.
1113   if (ST->isUsingPCRelativeCalls())
1114     return true;
1115 
1116   const Function *Callee = CB->getCalledFunction();
1117   // Indirect calls and variadic argument functions not supported.
1118   if (!Callee || Callee->isVarArg())
1119     return false;
1120 
1121   const Function *Caller = CB->getCaller();
1122   // Support if we can share TOC base.
1123   return ST->getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(),
1124                                                      Callee);
1125 }
1126