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