1 //===-- PPCTargetTransformInfo.cpp - PPC specific TTI ---------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
20 #define DEBUG_TYPE "ppctti"
22 static cl::opt<bool> DisablePPCConstHoist("disable-ppc-constant-hoisting",
23 cl::desc("disable constant hoisting on PPC"), cl::init(false), cl::Hidden);
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"));
32 EnablePPCColdCC("ppc-enable-coldcc", cl::Hidden, cl::init(false),
33 cl::desc("Enable using coldcc calling conv for cold "
34 "internal functions"));
36 // The latency of mtctr is only justified if there are more than 4
37 // comparisons that will be removed as a result.
38 static cl::opt<unsigned>
39 SmallCTRLoopThreshold("min-ctr-loop-threshold", cl::init(4), cl::Hidden,
40 cl::desc("Loops with a constant trip count smaller than "
41 "this value will not use the count register."));
43 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 TargetTransformInfo::PopcntSupportKind
50 PPCTTIImpl::getPopcntSupport(unsigned TyWidth) {
51 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
52 if (ST->hasPOPCNTD() != PPCSubtarget::POPCNTD_Unavailable && TyWidth <= 64)
53 return ST->hasPOPCNTD() == PPCSubtarget::POPCNTD_Slow ?
54 TTI::PSK_SlowHardware : TTI::PSK_FastHardware;
55 return TTI::PSK_Software;
58 int PPCTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
59 if (DisablePPCConstHoist)
60 return BaseT::getIntImmCost(Imm, Ty);
62 assert(Ty->isIntegerTy());
64 unsigned BitSize = Ty->getPrimitiveSizeInBits();
71 if (Imm.getBitWidth() <= 64) {
72 if (isInt<16>(Imm.getSExtValue()))
73 return TTI::TCC_Basic;
75 if (isInt<32>(Imm.getSExtValue())) {
76 // A constant that can be materialized using lis.
77 if ((Imm.getZExtValue() & 0xFFFF) == 0)
78 return TTI::TCC_Basic;
80 return 2 * TTI::TCC_Basic;
84 return 4 * TTI::TCC_Basic;
87 int PPCTTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
89 if (DisablePPCConstHoist)
90 return BaseT::getIntImmCost(IID, Idx, Imm, Ty);
92 assert(Ty->isIntegerTy());
94 unsigned BitSize = Ty->getPrimitiveSizeInBits();
100 return TTI::TCC_Free;
101 case Intrinsic::sadd_with_overflow:
102 case Intrinsic::uadd_with_overflow:
103 case Intrinsic::ssub_with_overflow:
104 case Intrinsic::usub_with_overflow:
105 if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<16>(Imm.getSExtValue()))
106 return TTI::TCC_Free;
108 case Intrinsic::experimental_stackmap:
109 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
110 return TTI::TCC_Free;
112 case Intrinsic::experimental_patchpoint_void:
113 case Intrinsic::experimental_patchpoint_i64:
114 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
115 return TTI::TCC_Free;
118 return PPCTTIImpl::getIntImmCost(Imm, Ty);
121 int PPCTTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
123 if (DisablePPCConstHoist)
124 return BaseT::getIntImmCost(Opcode, Idx, Imm, Ty);
126 assert(Ty->isIntegerTy());
128 unsigned BitSize = Ty->getPrimitiveSizeInBits();
132 unsigned ImmIdx = ~0U;
133 bool ShiftedFree = false, RunFree = false, UnsignedFree = false,
137 return TTI::TCC_Free;
138 case Instruction::GetElementPtr:
139 // Always hoist the base address of a GetElementPtr. This prevents the
140 // creation of new constants for every base constant that gets constant
141 // folded with the offset.
143 return 2 * TTI::TCC_Basic;
144 return TTI::TCC_Free;
145 case Instruction::And:
146 RunFree = true; // (for the rotate-and-mask instructions)
148 case Instruction::Add:
149 case Instruction::Or:
150 case Instruction::Xor:
153 case Instruction::Sub:
154 case Instruction::Mul:
155 case Instruction::Shl:
156 case Instruction::LShr:
157 case Instruction::AShr:
160 case Instruction::ICmp:
163 // Zero comparisons can use record-form instructions.
165 case Instruction::Select:
168 case Instruction::PHI:
169 case Instruction::Call:
170 case Instruction::Ret:
171 case Instruction::Load:
172 case Instruction::Store:
176 if (ZeroFree && Imm == 0)
177 return TTI::TCC_Free;
179 if (Idx == ImmIdx && Imm.getBitWidth() <= 64) {
180 if (isInt<16>(Imm.getSExtValue()))
181 return TTI::TCC_Free;
184 if (Imm.getBitWidth() <= 32 &&
185 (isShiftedMask_32(Imm.getZExtValue()) ||
186 isShiftedMask_32(~Imm.getZExtValue())))
187 return TTI::TCC_Free;
190 (isShiftedMask_64(Imm.getZExtValue()) ||
191 isShiftedMask_64(~Imm.getZExtValue())))
192 return TTI::TCC_Free;
195 if (UnsignedFree && isUInt<16>(Imm.getZExtValue()))
196 return TTI::TCC_Free;
198 if (ShiftedFree && (Imm.getZExtValue() & 0xFFFF) == 0)
199 return TTI::TCC_Free;
202 return PPCTTIImpl::getIntImmCost(Imm, Ty);
205 unsigned PPCTTIImpl::getUserCost(const User *U,
206 ArrayRef<const Value *> Operands) {
207 if (U->getType()->isVectorTy()) {
208 // Instructions that need to be split should cost more.
209 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, U->getType());
210 return LT.first * BaseT::getUserCost(U, Operands);
213 return BaseT::getUserCost(U, Operands);
216 bool PPCTTIImpl::mightUseCTR(BasicBlock *BB,
217 TargetLibraryInfo *LibInfo) {
218 const PPCTargetMachine &TM = ST->getTargetMachine();
220 // Loop through the inline asm constraints and look for something that
222 auto asmClobbersCTR = [](InlineAsm *IA) {
223 InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
224 for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
225 InlineAsm::ConstraintInfo &C = CIV[i];
226 if (C.Type != InlineAsm::isInput)
227 for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
228 if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
234 // Determining the address of a TLS variable results in a function call in
235 // certain TLS models.
236 std::function<bool(const Value*)> memAddrUsesCTR =
237 [&memAddrUsesCTR, &TM](const Value *MemAddr) -> bool {
238 const auto *GV = dyn_cast<GlobalValue>(MemAddr);
240 // Recurse to check for constants that refer to TLS global variables.
241 if (const auto *CV = dyn_cast<Constant>(MemAddr))
242 for (const auto &CO : CV->operands())
243 if (memAddrUsesCTR(CO))
249 if (!GV->isThreadLocal())
251 TLSModel::Model Model = TM.getTLSModel(GV);
252 return Model == TLSModel::GeneralDynamic ||
253 Model == TLSModel::LocalDynamic;
256 auto isLargeIntegerTy = [](bool Is32Bit, Type *Ty) {
257 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
258 return ITy->getBitWidth() > (Is32Bit ? 32U : 64U);
263 for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
265 if (CallInst *CI = dyn_cast<CallInst>(J)) {
266 // Inline ASM is okay, unless it clobbers the ctr register.
267 if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
268 if (asmClobbersCTR(IA))
273 if (Function *F = CI->getCalledFunction()) {
274 // Most intrinsics don't become function calls, but some might.
275 // sin, cos, exp and log are always calls.
277 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
278 switch (F->getIntrinsicID()) {
280 // If we have a call to ppc_is_decremented_ctr_nonzero, or ppc_mtctr
281 // we're definitely using CTR.
282 case Intrinsic::set_loop_iterations:
283 case Intrinsic::loop_decrement:
286 // VisualStudio defines setjmp as _setjmp
287 #if defined(_MSC_VER) && defined(setjmp) && \
288 !defined(setjmp_undefined_for_msvc)
289 # pragma push_macro("setjmp")
291 # define setjmp_undefined_for_msvc
294 case Intrinsic::setjmp:
296 #if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
297 // let's return it to _setjmp state
298 # pragma pop_macro("setjmp")
299 # undef setjmp_undefined_for_msvc
302 case Intrinsic::longjmp:
304 // Exclude eh_sjlj_setjmp; we don't need to exclude eh_sjlj_longjmp
305 // because, although it does clobber the counter register, the
306 // control can't then return to inside the loop unless there is also
307 // an eh_sjlj_setjmp.
308 case Intrinsic::eh_sjlj_setjmp:
310 case Intrinsic::memcpy:
311 case Intrinsic::memmove:
312 case Intrinsic::memset:
313 case Intrinsic::powi:
315 case Intrinsic::log2:
316 case Intrinsic::log10:
318 case Intrinsic::exp2:
323 case Intrinsic::copysign:
324 if (CI->getArgOperand(0)->getType()->getScalarType()->
328 continue; // ISD::FCOPYSIGN is never a library call.
329 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
330 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
331 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
332 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
333 case Intrinsic::rint: Opcode = ISD::FRINT; break;
334 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
335 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
336 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
337 case Intrinsic::round: Opcode = ISD::FROUND; break;
338 case Intrinsic::lround: Opcode = ISD::LROUND; break;
339 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
340 case Intrinsic::minnum: Opcode = ISD::FMINNUM; break;
341 case Intrinsic::maxnum: Opcode = ISD::FMAXNUM; break;
342 case Intrinsic::umul_with_overflow: Opcode = ISD::UMULO; break;
343 case Intrinsic::smul_with_overflow: Opcode = ISD::SMULO; break;
347 // PowerPC does not use [US]DIVREM or other library calls for
348 // operations on regular types which are not otherwise library calls
349 // (i.e. soft float or atomics). If adapting for targets that do,
350 // additional care is required here.
353 if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
354 LibInfo->getLibFunc(F->getName(), Func) &&
355 LibInfo->hasOptimizedCodeGen(Func)) {
356 // Non-read-only functions are never treated as intrinsics.
357 if (!CI->onlyReadsMemory())
360 // Conversion happens only for FP calls.
361 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
365 default: return true;
366 case LibFunc_copysign:
367 case LibFunc_copysignf:
368 continue; // ISD::FCOPYSIGN is never a library call.
369 case LibFunc_copysignl:
374 continue; // ISD::FABS is never a library call.
378 Opcode = ISD::FSQRT; break;
382 Opcode = ISD::FFLOOR; break;
383 case LibFunc_nearbyint:
384 case LibFunc_nearbyintf:
385 case LibFunc_nearbyintl:
386 Opcode = ISD::FNEARBYINT; break;
390 Opcode = ISD::FCEIL; break;
394 Opcode = ISD::FRINT; break;
398 Opcode = ISD::FROUND; break;
402 Opcode = ISD::FTRUNC; break;
406 Opcode = ISD::FMINNUM; break;
410 Opcode = ISD::FMAXNUM; break;
416 TLI->getValueType(DL, CI->getArgOperand(0)->getType(), true);
418 if (EVTy == MVT::Other)
421 if (TLI->isOperationLegalOrCustom(Opcode, EVTy))
423 else if (EVTy.isVector() &&
424 TLI->isOperationLegalOrCustom(Opcode, EVTy.getScalarType()))
432 } else if (isa<BinaryOperator>(J) &&
433 J->getType()->getScalarType()->isPPC_FP128Ty()) {
434 // Most operations on ppc_f128 values become calls.
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()))
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)) {
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.
459 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
460 // On PowerPC, indirect jumps use the counter register.
462 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
463 if (SI->getNumCases() + 1 >= (unsigned)TLI->getMinimumJumpTableEntries())
467 // FREM is always a call.
468 if (J->getOpcode() == Instruction::FRem)
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:
488 for (Value *Operand : J->operands())
489 if (memAddrUsesCTR(Operand))
496 bool PPCTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
498 TargetLibraryInfo *LibInfo,
499 HardwareLoopInfo &HWLoopInfo) {
500 const PPCTargetMachine &TM = ST->getTargetMachine();
501 TargetSchedModel SchedModel;
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);
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()))
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 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
521 if (mightUseCTR(*I, LibInfo))
524 SmallVector<BasicBlock*, 4> ExitingBlocks;
525 L->getExitingBlocks(ExitingBlocks);
527 // If there is an exit edge known to be frequently taken,
528 // we should not transform this loop.
529 for (auto &BB : ExitingBlocks) {
530 Instruction *TI = BB->getTerminator();
533 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
534 uint64_t TrueWeight = 0, FalseWeight = 0;
535 if (!BI->isConditional() ||
536 !BI->extractProfMetadata(TrueWeight, FalseWeight))
539 // If the exit path is more frequent than the loop path,
540 // we return here without further analysis for this loop.
541 bool TrueIsExit = !L->contains(BI->getSuccessor(0));
542 if (( TrueIsExit && FalseWeight < TrueWeight) ||
543 (!TrueIsExit && FalseWeight > TrueWeight))
548 LLVMContext &C = L->getHeader()->getContext();
549 HWLoopInfo.CountType = TM.isPPC64() ?
550 Type::getInt64Ty(C) : Type::getInt32Ty(C);
551 HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
555 void PPCTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
556 TTI::UnrollingPreferences &UP) {
557 if (ST->getDarwinDirective() == PPC::DIR_A2) {
558 // The A2 is in-order with a deep pipeline, and concatenation unrolling
559 // helps expose latency-hiding opportunities to the instruction scheduler.
560 UP.Partial = UP.Runtime = true;
562 // We unroll a lot on the A2 (hundreds of instructions), and the benefits
563 // often outweigh the cost of a division to compute the trip count.
564 UP.AllowExpensiveTripCount = true;
567 BaseT::getUnrollingPreferences(L, SE, UP);
570 // This function returns true to allow using coldcc calling convention.
571 // Returning true results in coldcc being used for functions which are cold at
572 // all call sites when the callers of the functions are not calling any other
573 // non coldcc functions.
574 bool PPCTTIImpl::useColdCCForColdCall(Function &F) {
575 return EnablePPCColdCC;
578 bool PPCTTIImpl::enableAggressiveInterleaving(bool LoopHasReductions) {
579 // On the A2, always unroll aggressively. For QPX unaligned loads, we depend
580 // on combining the loads generated for consecutive accesses, and failure to
581 // do so is particularly expensive. This makes it much more likely (compared
582 // to only using concatenation unrolling).
583 if (ST->getDarwinDirective() == PPC::DIR_A2)
586 return LoopHasReductions;
589 PPCTTIImpl::TTI::MemCmpExpansionOptions
590 PPCTTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
591 TTI::MemCmpExpansionOptions Options;
592 Options.LoadSizes = {8, 4, 2, 1};
593 Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
597 bool PPCTTIImpl::enableInterleavedAccessVectorization() {
601 unsigned PPCTTIImpl::getNumberOfRegisters(bool Vector) {
602 if (Vector && !ST->hasAltivec() && !ST->hasQPX())
604 return ST->hasVSX() ? 64 : 32;
607 unsigned PPCTTIImpl::getRegisterBitWidth(bool Vector) const {
609 if (ST->hasQPX()) return 256;
610 if (ST->hasAltivec()) return 128;
620 unsigned PPCTTIImpl::getCacheLineSize() {
621 // Check first if the user specified a custom line size.
622 if (CacheLineSize.getNumOccurrences() > 0)
623 return CacheLineSize;
625 // On P7, P8 or P9 we have a cache line size of 128.
626 unsigned Directive = ST->getDarwinDirective();
627 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
628 Directive == PPC::DIR_PWR9)
631 // On other processors return a default of 64 bytes.
635 unsigned PPCTTIImpl::getPrefetchDistance() {
636 // This seems like a reasonable default for the BG/Q (this pass is enabled, by
637 // default, only on the BG/Q).
641 unsigned PPCTTIImpl::getMaxInterleaveFactor(unsigned VF) {
642 unsigned Directive = ST->getDarwinDirective();
643 // The 440 has no SIMD support, but floating-point instructions
644 // have a 5-cycle latency, so unroll by 5x for latency hiding.
645 if (Directive == PPC::DIR_440)
648 // The A2 has no SIMD support, but floating-point instructions
649 // have a 6-cycle latency, so unroll by 6x for latency hiding.
650 if (Directive == PPC::DIR_A2)
653 // FIXME: For lack of any better information, do no harm...
654 if (Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500)
657 // For P7 and P8, floating-point instructions have a 6-cycle latency and
658 // there are two execution units, so unroll by 12x for latency hiding.
659 // FIXME: the same for P9 as previous gen until POWER9 scheduling is ready
660 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
661 Directive == PPC::DIR_PWR9)
664 // For most things, modern systems have two execution units (and
665 // out-of-order execution).
669 // Adjust the cost of vector instructions on targets which there is overlap
670 // between the vector and scalar units, thereby reducing the overall throughput
671 // of vector code wrt. scalar code.
672 int PPCTTIImpl::vectorCostAdjustment(int Cost, unsigned Opcode, Type *Ty1,
674 if (!ST->vectorsUseTwoUnits() || !Ty1->isVectorTy())
677 std::pair<int, MVT> LT1 = TLI->getTypeLegalizationCost(DL, Ty1);
678 // If type legalization involves splitting the vector, we don't want to
679 // double the cost at every step - only the last step.
680 if (LT1.first != 1 || !LT1.second.isVector())
683 int ISD = TLI->InstructionOpcodeToISD(Opcode);
684 if (TLI->isOperationExpand(ISD, LT1.second))
688 std::pair<int, MVT> LT2 = TLI->getTypeLegalizationCost(DL, Ty2);
689 if (LT2.first != 1 || !LT2.second.isVector())
696 int PPCTTIImpl::getArithmeticInstrCost(
697 unsigned Opcode, Type *Ty, TTI::OperandValueKind Op1Info,
698 TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
699 TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args) {
700 assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
702 // Fallback to the default implementation.
703 int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info,
704 Opd1PropInfo, Opd2PropInfo);
705 return vectorCostAdjustment(Cost, Opcode, Ty, nullptr);
708 int PPCTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
710 // Legalize the type.
711 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
713 // PPC, for both Altivec/VSX and QPX, support cheap arbitrary permutations
714 // (at least in the sense that there need only be one non-loop-invariant
715 // instruction). We need one such shuffle instruction for each actual
716 // register (this is not true for arbitrary shuffles, but is true for the
717 // structured types of shuffles covered by TTI::ShuffleKind).
718 return vectorCostAdjustment(LT.first, Instruction::ShuffleVector, Tp,
722 int PPCTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
723 const Instruction *I) {
724 assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
726 int Cost = BaseT::getCastInstrCost(Opcode, Dst, Src);
727 return vectorCostAdjustment(Cost, Opcode, Dst, Src);
730 int PPCTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
731 const Instruction *I) {
732 int Cost = BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
733 return vectorCostAdjustment(Cost, Opcode, ValTy, nullptr);
736 int PPCTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
737 assert(Val->isVectorTy() && "This must be a vector type");
739 int ISD = TLI->InstructionOpcodeToISD(Opcode);
740 assert(ISD && "Invalid opcode");
742 int Cost = BaseT::getVectorInstrCost(Opcode, Val, Index);
743 Cost = vectorCostAdjustment(Cost, Opcode, Val, nullptr);
745 if (ST->hasVSX() && Val->getScalarType()->isDoubleTy()) {
746 // Double-precision scalars are already located in index #0 (or #1 if LE).
747 if (ISD == ISD::EXTRACT_VECTOR_ELT &&
748 Index == (ST->isLittleEndian() ? 1 : 0))
753 } else if (ST->hasQPX() && Val->getScalarType()->isFloatingPointTy()) {
754 // Floating point scalars are already located in index #0.
761 // Estimated cost of a load-hit-store delay. This was obtained
762 // experimentally as a minimum needed to prevent unprofitable
763 // vectorization for the paq8p benchmark. It may need to be
764 // raised further if other unprofitable cases remain.
765 unsigned LHSPenalty = 2;
766 if (ISD == ISD::INSERT_VECTOR_ELT)
769 // Vector element insert/extract with Altivec is very expensive,
770 // because they require store and reload with the attendant
771 // processor stall for load-hit-store. Until VSX is available,
772 // these need to be estimated as very costly.
773 if (ISD == ISD::EXTRACT_VECTOR_ELT ||
774 ISD == ISD::INSERT_VECTOR_ELT)
775 return LHSPenalty + Cost;
780 int PPCTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
781 unsigned AddressSpace, const Instruction *I) {
782 // Legalize the type.
783 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
784 assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
787 int Cost = BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
788 Cost = vectorCostAdjustment(Cost, Opcode, Src, nullptr);
790 bool IsAltivecType = ST->hasAltivec() &&
791 (LT.second == MVT::v16i8 || LT.second == MVT::v8i16 ||
792 LT.second == MVT::v4i32 || LT.second == MVT::v4f32);
793 bool IsVSXType = ST->hasVSX() &&
794 (LT.second == MVT::v2f64 || LT.second == MVT::v2i64);
795 bool IsQPXType = ST->hasQPX() &&
796 (LT.second == MVT::v4f64 || LT.second == MVT::v4f32);
798 // VSX has 32b/64b load instructions. Legalization can handle loading of
799 // 32b/64b to VSR correctly and cheaply. But BaseT::getMemoryOpCost and
800 // PPCTargetLowering can't compute the cost appropriately. So here we
801 // explicitly check this case.
802 unsigned MemBytes = Src->getPrimitiveSizeInBits();
803 if (Opcode == Instruction::Load && ST->hasVSX() && IsAltivecType &&
804 (MemBytes == 64 || (ST->hasP8Vector() && MemBytes == 32)))
807 // Aligned loads and stores are easy.
808 unsigned SrcBytes = LT.second.getStoreSize();
809 if (!SrcBytes || !Alignment || Alignment >= SrcBytes)
812 // If we can use the permutation-based load sequence, then this is also
813 // relatively cheap (not counting loop-invariant instructions): one load plus
814 // one permute (the last load in a series has extra cost, but we're
815 // neglecting that here). Note that on the P7, we could do unaligned loads
816 // for Altivec types using the VSX instructions, but that's more expensive
817 // than using the permutation-based load sequence. On the P8, that's no
819 if (Opcode == Instruction::Load &&
820 ((!ST->hasP8Vector() && IsAltivecType) || IsQPXType) &&
821 Alignment >= LT.second.getScalarType().getStoreSize())
822 return Cost + LT.first; // Add the cost of the permutations.
824 // For VSX, we can do unaligned loads and stores on Altivec/VSX types. On the
825 // P7, unaligned vector loads are more expensive than the permutation-based
826 // load sequence, so that might be used instead, but regardless, the net cost
827 // is about the same (not counting loop-invariant instructions).
828 if (IsVSXType || (ST->hasVSX() && IsAltivecType))
831 // Newer PPC supports unaligned memory access.
832 if (TLI->allowsMisalignedMemoryAccesses(LT.second, 0))
835 // PPC in general does not support unaligned loads and stores. They'll need
836 // to be decomposed based on the alignment factor.
838 // Add the cost of each scalar load or store.
839 Cost += LT.first*(SrcBytes/Alignment-1);
841 // For a vector type, there is also scalarization overhead (only for
842 // stores, loads are expanded using the vector-load + permutation sequence,
843 // which is much less expensive).
844 if (Src->isVectorTy() && Opcode == Instruction::Store)
845 for (int i = 0, e = Src->getVectorNumElements(); i < e; ++i)
846 Cost += getVectorInstrCost(Instruction::ExtractElement, Src, i);
851 int PPCTTIImpl::getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
853 ArrayRef<unsigned> Indices,
855 unsigned AddressSpace,
857 bool UseMaskForGaps) {
858 if (UseMaskForCond || UseMaskForGaps)
859 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
860 Alignment, AddressSpace,
861 UseMaskForCond, UseMaskForGaps);
863 assert(isa<VectorType>(VecTy) &&
864 "Expect a vector type for interleaved memory op");
866 // Legalize the type.
867 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, VecTy);
869 // Firstly, the cost of load/store operation.
870 int Cost = getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace);
872 // PPC, for both Altivec/VSX and QPX, support cheap arbitrary permutations
873 // (at least in the sense that there need only be one non-loop-invariant
874 // instruction). For each result vector, we need one shuffle per incoming
875 // vector (except that the first shuffle can take two incoming vectors
876 // because it does not need to take itself).
877 Cost += Factor*(LT.first-1);
882 bool PPCTTIImpl::canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE,
883 LoopInfo *LI, DominatorTree *DT,
884 AssumptionCache *AC, TargetLibraryInfo *LibInfo) {
885 // Process nested loops first.
886 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
887 if (canSaveCmp(*I, BI, SE, LI, DT, AC, LibInfo))
888 return false; // Stop search.
890 HardwareLoopInfo HWLoopInfo(L);
892 if (!HWLoopInfo.canAnalyze(*LI))
895 if (!isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo))
898 if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT))
901 *BI = HWLoopInfo.ExitBranch;