PPCTargetTransformInfo.cpp 49 KB

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