BasicTTIImpl.h 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177
  1. //===- BasicTTIImpl.h -------------------------------------------*- C++ -*-===//
  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. /// \file
  10. /// This file provides a helper that implements much of the TTI interface in
  11. /// terms of the target-independent code generator and TargetLowering
  12. /// interfaces.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #ifndef LLVM_CODEGEN_BASICTTIIMPL_H
  16. #define LLVM_CODEGEN_BASICTTIIMPL_H
  17. #include "llvm/ADT/APInt.h"
  18. #include "llvm/ADT/ArrayRef.h"
  19. #include "llvm/ADT/BitVector.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/Analysis/LoopInfo.h"
  23. #include "llvm/Analysis/TargetTransformInfo.h"
  24. #include "llvm/Analysis/TargetTransformInfoImpl.h"
  25. #include "llvm/CodeGen/ISDOpcodes.h"
  26. #include "llvm/CodeGen/TargetLowering.h"
  27. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  28. #include "llvm/CodeGen/ValueTypes.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/IR/Constant.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/DerivedTypes.h"
  34. #include "llvm/IR/InstrTypes.h"
  35. #include "llvm/IR/Instruction.h"
  36. #include "llvm/IR/Instructions.h"
  37. #include "llvm/IR/Intrinsics.h"
  38. #include "llvm/IR/Operator.h"
  39. #include "llvm/IR/Type.h"
  40. #include "llvm/IR/Value.h"
  41. #include "llvm/Support/Casting.h"
  42. #include "llvm/Support/CommandLine.h"
  43. #include "llvm/Support/ErrorHandling.h"
  44. #include "llvm/Support/MachineValueType.h"
  45. #include "llvm/Support/MathExtras.h"
  46. #include "llvm/Target/TargetMachine.h"
  47. #include <algorithm>
  48. #include <cassert>
  49. #include <cstdint>
  50. #include <limits>
  51. #include <utility>
  52. namespace llvm {
  53. class Function;
  54. class GlobalValue;
  55. class LLVMContext;
  56. class ScalarEvolution;
  57. class SCEV;
  58. class TargetMachine;
  59. extern cl::opt<unsigned> PartialUnrollingThreshold;
  60. /// Base class which can be used to help build a TTI implementation.
  61. ///
  62. /// This class provides as much implementation of the TTI interface as is
  63. /// possible using the target independent parts of the code generator.
  64. ///
  65. /// In order to subclass it, your class must implement a getST() method to
  66. /// return the subtarget, and a getTLI() method to return the target lowering.
  67. /// We need these methods implemented in the derived class so that this class
  68. /// doesn't have to duplicate storage for them.
  69. template <typename T>
  70. class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
  71. private:
  72. using BaseT = TargetTransformInfoImplCRTPBase<T>;
  73. using TTI = TargetTransformInfo;
  74. /// Helper function to access this as a T.
  75. T *thisT() { return static_cast<T *>(this); }
  76. /// Estimate a cost of Broadcast as an extract and sequence of insert
  77. /// operations.
  78. InstructionCost getBroadcastShuffleOverhead(FixedVectorType *VTy) {
  79. InstructionCost Cost = 0;
  80. // Broadcast cost is equal to the cost of extracting the zero'th element
  81. // plus the cost of inserting it into every element of the result vector.
  82. Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, VTy, 0);
  83. for (int i = 0, e = VTy->getNumElements(); i < e; ++i) {
  84. Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, VTy, i);
  85. }
  86. return Cost;
  87. }
  88. /// Estimate a cost of shuffle as a sequence of extract and insert
  89. /// operations.
  90. InstructionCost getPermuteShuffleOverhead(FixedVectorType *VTy) {
  91. InstructionCost Cost = 0;
  92. // Shuffle cost is equal to the cost of extracting element from its argument
  93. // plus the cost of inserting them onto the result vector.
  94. // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
  95. // index 0 of first vector, index 1 of second vector,index 2 of first
  96. // vector and finally index 3 of second vector and insert them at index
  97. // <0,1,2,3> of result vector.
  98. for (int i = 0, e = VTy->getNumElements(); i < e; ++i) {
  99. Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, VTy, i);
  100. Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, VTy, i);
  101. }
  102. return Cost;
  103. }
  104. /// Estimate a cost of subvector extraction as a sequence of extract and
  105. /// insert operations.
  106. InstructionCost getExtractSubvectorOverhead(VectorType *VTy, int Index,
  107. FixedVectorType *SubVTy) {
  108. assert(VTy && SubVTy &&
  109. "Can only extract subvectors from vectors");
  110. int NumSubElts = SubVTy->getNumElements();
  111. assert((!isa<FixedVectorType>(VTy) ||
  112. (Index + NumSubElts) <=
  113. (int)cast<FixedVectorType>(VTy)->getNumElements()) &&
  114. "SK_ExtractSubvector index out of range");
  115. InstructionCost Cost = 0;
  116. // Subvector extraction cost is equal to the cost of extracting element from
  117. // the source type plus the cost of inserting them into the result vector
  118. // type.
  119. for (int i = 0; i != NumSubElts; ++i) {
  120. Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, VTy,
  121. i + Index);
  122. Cost +=
  123. thisT()->getVectorInstrCost(Instruction::InsertElement, SubVTy, i);
  124. }
  125. return Cost;
  126. }
  127. /// Estimate a cost of subvector insertion as a sequence of extract and
  128. /// insert operations.
  129. InstructionCost getInsertSubvectorOverhead(VectorType *VTy, int Index,
  130. FixedVectorType *SubVTy) {
  131. assert(VTy && SubVTy &&
  132. "Can only insert subvectors into vectors");
  133. int NumSubElts = SubVTy->getNumElements();
  134. assert((!isa<FixedVectorType>(VTy) ||
  135. (Index + NumSubElts) <=
  136. (int)cast<FixedVectorType>(VTy)->getNumElements()) &&
  137. "SK_InsertSubvector index out of range");
  138. InstructionCost Cost = 0;
  139. // Subvector insertion cost is equal to the cost of extracting element from
  140. // the source type plus the cost of inserting them into the result vector
  141. // type.
  142. for (int i = 0; i != NumSubElts; ++i) {
  143. Cost +=
  144. thisT()->getVectorInstrCost(Instruction::ExtractElement, SubVTy, i);
  145. Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, VTy,
  146. i + Index);
  147. }
  148. return Cost;
  149. }
  150. /// Local query method delegates up to T which *must* implement this!
  151. const TargetSubtargetInfo *getST() const {
  152. return static_cast<const T *>(this)->getST();
  153. }
  154. /// Local query method delegates up to T which *must* implement this!
  155. const TargetLoweringBase *getTLI() const {
  156. return static_cast<const T *>(this)->getTLI();
  157. }
  158. static ISD::MemIndexedMode getISDIndexedMode(TTI::MemIndexedMode M) {
  159. switch (M) {
  160. case TTI::MIM_Unindexed:
  161. return ISD::UNINDEXED;
  162. case TTI::MIM_PreInc:
  163. return ISD::PRE_INC;
  164. case TTI::MIM_PreDec:
  165. return ISD::PRE_DEC;
  166. case TTI::MIM_PostInc:
  167. return ISD::POST_INC;
  168. case TTI::MIM_PostDec:
  169. return ISD::POST_DEC;
  170. }
  171. llvm_unreachable("Unexpected MemIndexedMode");
  172. }
  173. InstructionCost getCommonMaskedMemoryOpCost(unsigned Opcode, Type *DataTy,
  174. Align Alignment,
  175. bool VariableMask,
  176. bool IsGatherScatter,
  177. TTI::TargetCostKind CostKind) {
  178. auto *VT = cast<FixedVectorType>(DataTy);
  179. // Assume the target does not have support for gather/scatter operations
  180. // and provide a rough estimate.
  181. //
  182. // First, compute the cost of the individual memory operations.
  183. InstructionCost AddrExtractCost =
  184. IsGatherScatter
  185. ? getVectorInstrCost(Instruction::ExtractElement,
  186. FixedVectorType::get(
  187. PointerType::get(VT->getElementType(), 0),
  188. VT->getNumElements()),
  189. -1)
  190. : 0;
  191. InstructionCost LoadCost =
  192. VT->getNumElements() *
  193. (AddrExtractCost +
  194. getMemoryOpCost(Opcode, VT->getElementType(), Alignment, 0, CostKind));
  195. // Next, compute the cost of packing the result in a vector.
  196. InstructionCost PackingCost = getScalarizationOverhead(
  197. VT, Opcode != Instruction::Store, Opcode == Instruction::Store);
  198. InstructionCost ConditionalCost = 0;
  199. if (VariableMask) {
  200. // Compute the cost of conditionally executing the memory operations with
  201. // variable masks. This includes extracting the individual conditions, a
  202. // branches and PHIs to combine the results.
  203. // NOTE: Estimating the cost of conditionally executing the memory
  204. // operations accurately is quite difficult and the current solution
  205. // provides a very rough estimate only.
  206. ConditionalCost =
  207. VT->getNumElements() *
  208. (getVectorInstrCost(
  209. Instruction::ExtractElement,
  210. FixedVectorType::get(Type::getInt1Ty(DataTy->getContext()),
  211. VT->getNumElements()),
  212. -1) +
  213. getCFInstrCost(Instruction::Br, CostKind) +
  214. getCFInstrCost(Instruction::PHI, CostKind));
  215. }
  216. return LoadCost + PackingCost + ConditionalCost;
  217. }
  218. protected:
  219. explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
  220. : BaseT(DL) {}
  221. virtual ~BasicTTIImplBase() = default;
  222. using TargetTransformInfoImplBase::DL;
  223. public:
  224. /// \name Scalar TTI Implementations
  225. /// @{
  226. bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth,
  227. unsigned AddressSpace, Align Alignment,
  228. bool *Fast) const {
  229. EVT E = EVT::getIntegerVT(Context, BitWidth);
  230. return getTLI()->allowsMisalignedMemoryAccesses(
  231. E, AddressSpace, Alignment, MachineMemOperand::MONone, Fast);
  232. }
  233. bool hasBranchDivergence() { return false; }
  234. bool useGPUDivergenceAnalysis() { return false; }
  235. bool isSourceOfDivergence(const Value *V) { return false; }
  236. bool isAlwaysUniform(const Value *V) { return false; }
  237. unsigned getFlatAddressSpace() {
  238. // Return an invalid address space.
  239. return -1;
  240. }
  241. bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
  242. Intrinsic::ID IID) const {
  243. return false;
  244. }
  245. bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const {
  246. return getTLI()->getTargetMachine().isNoopAddrSpaceCast(FromAS, ToAS);
  247. }
  248. unsigned getAssumedAddrSpace(const Value *V) const {
  249. return getTLI()->getTargetMachine().getAssumedAddrSpace(V);
  250. }
  251. Value *rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV,
  252. Value *NewV) const {
  253. return nullptr;
  254. }
  255. bool isLegalAddImmediate(int64_t imm) {
  256. return getTLI()->isLegalAddImmediate(imm);
  257. }
  258. bool isLegalICmpImmediate(int64_t imm) {
  259. return getTLI()->isLegalICmpImmediate(imm);
  260. }
  261. bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
  262. bool HasBaseReg, int64_t Scale,
  263. unsigned AddrSpace, Instruction *I = nullptr) {
  264. TargetLoweringBase::AddrMode AM;
  265. AM.BaseGV = BaseGV;
  266. AM.BaseOffs = BaseOffset;
  267. AM.HasBaseReg = HasBaseReg;
  268. AM.Scale = Scale;
  269. return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace, I);
  270. }
  271. bool isIndexedLoadLegal(TTI::MemIndexedMode M, Type *Ty,
  272. const DataLayout &DL) const {
  273. EVT VT = getTLI()->getValueType(DL, Ty);
  274. return getTLI()->isIndexedLoadLegal(getISDIndexedMode(M), VT);
  275. }
  276. bool isIndexedStoreLegal(TTI::MemIndexedMode M, Type *Ty,
  277. const DataLayout &DL) const {
  278. EVT VT = getTLI()->getValueType(DL, Ty);
  279. return getTLI()->isIndexedStoreLegal(getISDIndexedMode(M), VT);
  280. }
  281. bool isLSRCostLess(TTI::LSRCost C1, TTI::LSRCost C2) {
  282. return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
  283. }
  284. bool isNumRegsMajorCostOfLSR() {
  285. return TargetTransformInfoImplBase::isNumRegsMajorCostOfLSR();
  286. }
  287. bool isProfitableLSRChainElement(Instruction *I) {
  288. return TargetTransformInfoImplBase::isProfitableLSRChainElement(I);
  289. }
  290. InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
  291. int64_t BaseOffset, bool HasBaseReg,
  292. int64_t Scale, unsigned AddrSpace) {
  293. TargetLoweringBase::AddrMode AM;
  294. AM.BaseGV = BaseGV;
  295. AM.BaseOffs = BaseOffset;
  296. AM.HasBaseReg = HasBaseReg;
  297. AM.Scale = Scale;
  298. return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
  299. }
  300. bool isTruncateFree(Type *Ty1, Type *Ty2) {
  301. return getTLI()->isTruncateFree(Ty1, Ty2);
  302. }
  303. bool isProfitableToHoist(Instruction *I) {
  304. return getTLI()->isProfitableToHoist(I);
  305. }
  306. bool useAA() const { return getST()->useAA(); }
  307. bool isTypeLegal(Type *Ty) {
  308. EVT VT = getTLI()->getValueType(DL, Ty);
  309. return getTLI()->isTypeLegal(VT);
  310. }
  311. InstructionCost getRegUsageForType(Type *Ty) {
  312. InstructionCost Val = getTLI()->getTypeLegalizationCost(DL, Ty).first;
  313. assert(Val >= 0 && "Negative cost!");
  314. return Val;
  315. }
  316. InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr,
  317. ArrayRef<const Value *> Operands) {
  318. return BaseT::getGEPCost(PointeeType, Ptr, Operands);
  319. }
  320. unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
  321. unsigned &JumpTableSize,
  322. ProfileSummaryInfo *PSI,
  323. BlockFrequencyInfo *BFI) {
  324. /// Try to find the estimated number of clusters. Note that the number of
  325. /// clusters identified in this function could be different from the actual
  326. /// numbers found in lowering. This function ignore switches that are
  327. /// lowered with a mix of jump table / bit test / BTree. This function was
  328. /// initially intended to be used when estimating the cost of switch in
  329. /// inline cost heuristic, but it's a generic cost model to be used in other
  330. /// places (e.g., in loop unrolling).
  331. unsigned N = SI.getNumCases();
  332. const TargetLoweringBase *TLI = getTLI();
  333. const DataLayout &DL = this->getDataLayout();
  334. JumpTableSize = 0;
  335. bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
  336. // Early exit if both a jump table and bit test are not allowed.
  337. if (N < 1 || (!IsJTAllowed && DL.getIndexSizeInBits(0u) < N))
  338. return N;
  339. APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
  340. APInt MinCaseVal = MaxCaseVal;
  341. for (auto CI : SI.cases()) {
  342. const APInt &CaseVal = CI.getCaseValue()->getValue();
  343. if (CaseVal.sgt(MaxCaseVal))
  344. MaxCaseVal = CaseVal;
  345. if (CaseVal.slt(MinCaseVal))
  346. MinCaseVal = CaseVal;
  347. }
  348. // Check if suitable for a bit test
  349. if (N <= DL.getIndexSizeInBits(0u)) {
  350. SmallPtrSet<const BasicBlock *, 4> Dests;
  351. for (auto I : SI.cases())
  352. Dests.insert(I.getCaseSuccessor());
  353. if (TLI->isSuitableForBitTests(Dests.size(), N, MinCaseVal, MaxCaseVal,
  354. DL))
  355. return 1;
  356. }
  357. // Check if suitable for a jump table.
  358. if (IsJTAllowed) {
  359. if (N < 2 || N < TLI->getMinimumJumpTableEntries())
  360. return N;
  361. uint64_t Range =
  362. (MaxCaseVal - MinCaseVal)
  363. .getLimitedValue(std::numeric_limits<uint64_t>::max() - 1) + 1;
  364. // Check whether a range of clusters is dense enough for a jump table
  365. if (TLI->isSuitableForJumpTable(&SI, N, Range, PSI, BFI)) {
  366. JumpTableSize = Range;
  367. return 1;
  368. }
  369. }
  370. return N;
  371. }
  372. bool shouldBuildLookupTables() {
  373. const TargetLoweringBase *TLI = getTLI();
  374. return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  375. TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
  376. }
  377. bool shouldBuildRelLookupTables() const {
  378. const TargetMachine &TM = getTLI()->getTargetMachine();
  379. // If non-PIC mode, do not generate a relative lookup table.
  380. if (!TM.isPositionIndependent())
  381. return false;
  382. /// Relative lookup table entries consist of 32-bit offsets.
  383. /// Do not generate relative lookup tables for large code models
  384. /// in 64-bit achitectures where 32-bit offsets might not be enough.
  385. if (TM.getCodeModel() == CodeModel::Medium ||
  386. TM.getCodeModel() == CodeModel::Large)
  387. return false;
  388. Triple TargetTriple = TM.getTargetTriple();
  389. if (!TargetTriple.isArch64Bit())
  390. return false;
  391. // TODO: Triggers issues on aarch64 on darwin, so temporarily disable it
  392. // there.
  393. if (TargetTriple.getArch() == Triple::aarch64 && TargetTriple.isOSDarwin())
  394. return false;
  395. return true;
  396. }
  397. bool haveFastSqrt(Type *Ty) {
  398. const TargetLoweringBase *TLI = getTLI();
  399. EVT VT = TLI->getValueType(DL, Ty);
  400. return TLI->isTypeLegal(VT) &&
  401. TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
  402. }
  403. bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
  404. return true;
  405. }
  406. InstructionCost getFPOpCost(Type *Ty) {
  407. // Check whether FADD is available, as a proxy for floating-point in
  408. // general.
  409. const TargetLoweringBase *TLI = getTLI();
  410. EVT VT = TLI->getValueType(DL, Ty);
  411. if (TLI->isOperationLegalOrCustomOrPromote(ISD::FADD, VT))
  412. return TargetTransformInfo::TCC_Basic;
  413. return TargetTransformInfo::TCC_Expensive;
  414. }
  415. unsigned getInliningThresholdMultiplier() { return 1; }
  416. unsigned adjustInliningThreshold(const CallBase *CB) { return 0; }
  417. int getInlinerVectorBonusPercent() { return 150; }
  418. void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
  419. TTI::UnrollingPreferences &UP) {
  420. // This unrolling functionality is target independent, but to provide some
  421. // motivation for its intended use, for x86:
  422. // According to the Intel 64 and IA-32 Architectures Optimization Reference
  423. // Manual, Intel Core models and later have a loop stream detector (and
  424. // associated uop queue) that can benefit from partial unrolling.
  425. // The relevant requirements are:
  426. // - The loop must have no more than 4 (8 for Nehalem and later) branches
  427. // taken, and none of them may be calls.
  428. // - The loop can have no more than 18 (28 for Nehalem and later) uops.
  429. // According to the Software Optimization Guide for AMD Family 15h
  430. // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
  431. // and loop buffer which can benefit from partial unrolling.
  432. // The relevant requirements are:
  433. // - The loop must have fewer than 16 branches
  434. // - The loop must have less than 40 uops in all executed loop branches
  435. // The number of taken branches in a loop is hard to estimate here, and
  436. // benchmarking has revealed that it is better not to be conservative when
  437. // estimating the branch count. As a result, we'll ignore the branch limits
  438. // until someone finds a case where it matters in practice.
  439. unsigned MaxOps;
  440. const TargetSubtargetInfo *ST = getST();
  441. if (PartialUnrollingThreshold.getNumOccurrences() > 0)
  442. MaxOps = PartialUnrollingThreshold;
  443. else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
  444. MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
  445. else
  446. return;
  447. // Scan the loop: don't unroll loops with calls.
  448. for (BasicBlock *BB : L->blocks()) {
  449. for (Instruction &I : *BB) {
  450. if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
  451. if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
  452. if (!thisT()->isLoweredToCall(F))
  453. continue;
  454. }
  455. return;
  456. }
  457. }
  458. }
  459. // Enable runtime and partial unrolling up to the specified size.
  460. // Enable using trip count upper bound to unroll loops.
  461. UP.Partial = UP.Runtime = UP.UpperBound = true;
  462. UP.PartialThreshold = MaxOps;
  463. // Avoid unrolling when optimizing for size.
  464. UP.OptSizeThreshold = 0;
  465. UP.PartialOptSizeThreshold = 0;
  466. // Set number of instructions optimized when "back edge"
  467. // becomes "fall through" to default value of 2.
  468. UP.BEInsns = 2;
  469. }
  470. void getPeelingPreferences(Loop *L, ScalarEvolution &SE,
  471. TTI::PeelingPreferences &PP) {
  472. PP.PeelCount = 0;
  473. PP.AllowPeeling = true;
  474. PP.AllowLoopNestsPeeling = false;
  475. PP.PeelProfiledIterations = true;
  476. }
  477. bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
  478. AssumptionCache &AC,
  479. TargetLibraryInfo *LibInfo,
  480. HardwareLoopInfo &HWLoopInfo) {
  481. return BaseT::isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo);
  482. }
  483. bool preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
  484. AssumptionCache &AC, TargetLibraryInfo *TLI,
  485. DominatorTree *DT,
  486. const LoopAccessInfo *LAI) {
  487. return BaseT::preferPredicateOverEpilogue(L, LI, SE, AC, TLI, DT, LAI);
  488. }
  489. bool emitGetActiveLaneMask() {
  490. return BaseT::emitGetActiveLaneMask();
  491. }
  492. Optional<Instruction *> instCombineIntrinsic(InstCombiner &IC,
  493. IntrinsicInst &II) {
  494. return BaseT::instCombineIntrinsic(IC, II);
  495. }
  496. Optional<Value *> simplifyDemandedUseBitsIntrinsic(InstCombiner &IC,
  497. IntrinsicInst &II,
  498. APInt DemandedMask,
  499. KnownBits &Known,
  500. bool &KnownBitsComputed) {
  501. return BaseT::simplifyDemandedUseBitsIntrinsic(IC, II, DemandedMask, Known,
  502. KnownBitsComputed);
  503. }
  504. Optional<Value *> simplifyDemandedVectorEltsIntrinsic(
  505. InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
  506. APInt &UndefElts2, APInt &UndefElts3,
  507. std::function<void(Instruction *, unsigned, APInt, APInt &)>
  508. SimplifyAndSetOp) {
  509. return BaseT::simplifyDemandedVectorEltsIntrinsic(
  510. IC, II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
  511. SimplifyAndSetOp);
  512. }
  513. InstructionCost getInstructionLatency(const Instruction *I) {
  514. if (isa<LoadInst>(I))
  515. return getST()->getSchedModel().DefaultLoadLatency;
  516. return BaseT::getInstructionLatency(I);
  517. }
  518. virtual Optional<unsigned>
  519. getCacheSize(TargetTransformInfo::CacheLevel Level) const {
  520. return Optional<unsigned>(
  521. getST()->getCacheSize(static_cast<unsigned>(Level)));
  522. }
  523. virtual Optional<unsigned>
  524. getCacheAssociativity(TargetTransformInfo::CacheLevel Level) const {
  525. Optional<unsigned> TargetResult =
  526. getST()->getCacheAssociativity(static_cast<unsigned>(Level));
  527. if (TargetResult)
  528. return TargetResult;
  529. return BaseT::getCacheAssociativity(Level);
  530. }
  531. virtual unsigned getCacheLineSize() const {
  532. return getST()->getCacheLineSize();
  533. }
  534. virtual unsigned getPrefetchDistance() const {
  535. return getST()->getPrefetchDistance();
  536. }
  537. virtual unsigned getMinPrefetchStride(unsigned NumMemAccesses,
  538. unsigned NumStridedMemAccesses,
  539. unsigned NumPrefetches,
  540. bool HasCall) const {
  541. return getST()->getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
  542. NumPrefetches, HasCall);
  543. }
  544. virtual unsigned getMaxPrefetchIterationsAhead() const {
  545. return getST()->getMaxPrefetchIterationsAhead();
  546. }
  547. virtual bool enableWritePrefetching() const {
  548. return getST()->enableWritePrefetching();
  549. }
  550. /// @}
  551. /// \name Vector TTI Implementations
  552. /// @{
  553. TypeSize getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
  554. return TypeSize::getFixed(32);
  555. }
  556. Optional<unsigned> getMaxVScale() const { return None; }
  557. /// Estimate the overhead of scalarizing an instruction. Insert and Extract
  558. /// are set if the demanded result elements need to be inserted and/or
  559. /// extracted from vectors.
  560. InstructionCost getScalarizationOverhead(VectorType *InTy,
  561. const APInt &DemandedElts,
  562. bool Insert, bool Extract) {
  563. /// FIXME: a bitfield is not a reasonable abstraction for talking about
  564. /// which elements are needed from a scalable vector
  565. auto *Ty = cast<FixedVectorType>(InTy);
  566. assert(DemandedElts.getBitWidth() == Ty->getNumElements() &&
  567. "Vector size mismatch");
  568. InstructionCost Cost = 0;
  569. for (int i = 0, e = Ty->getNumElements(); i < e; ++i) {
  570. if (!DemandedElts[i])
  571. continue;
  572. if (Insert)
  573. Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, Ty, i);
  574. if (Extract)
  575. Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
  576. }
  577. return Cost;
  578. }
  579. /// Helper wrapper for the DemandedElts variant of getScalarizationOverhead.
  580. InstructionCost getScalarizationOverhead(VectorType *InTy, bool Insert,
  581. bool Extract) {
  582. auto *Ty = cast<FixedVectorType>(InTy);
  583. APInt DemandedElts = APInt::getAllOnesValue(Ty->getNumElements());
  584. return thisT()->getScalarizationOverhead(Ty, DemandedElts, Insert, Extract);
  585. }
  586. /// Estimate the overhead of scalarizing an instructions unique
  587. /// non-constant operands. The (potentially vector) types to use for each of
  588. /// argument are passes via Tys.
  589. InstructionCost getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
  590. ArrayRef<Type *> Tys) {
  591. assert(Args.size() == Tys.size() && "Expected matching Args and Tys");
  592. InstructionCost Cost = 0;
  593. SmallPtrSet<const Value*, 4> UniqueOperands;
  594. for (int I = 0, E = Args.size(); I != E; I++) {
  595. // Disregard things like metadata arguments.
  596. const Value *A = Args[I];
  597. Type *Ty = Tys[I];
  598. if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy() &&
  599. !Ty->isPtrOrPtrVectorTy())
  600. continue;
  601. if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
  602. if (auto *VecTy = dyn_cast<VectorType>(Ty))
  603. Cost += getScalarizationOverhead(VecTy, false, true);
  604. }
  605. }
  606. return Cost;
  607. }
  608. /// Estimate the overhead of scalarizing the inputs and outputs of an
  609. /// instruction, with return type RetTy and arguments Args of type Tys. If
  610. /// Args are unknown (empty), then the cost associated with one argument is
  611. /// added as a heuristic.
  612. InstructionCost getScalarizationOverhead(VectorType *RetTy,
  613. ArrayRef<const Value *> Args,
  614. ArrayRef<Type *> Tys) {
  615. InstructionCost Cost = getScalarizationOverhead(RetTy, true, false);
  616. if (!Args.empty())
  617. Cost += getOperandsScalarizationOverhead(Args, Tys);
  618. else
  619. // When no information on arguments is provided, we add the cost
  620. // associated with one argument as a heuristic.
  621. Cost += getScalarizationOverhead(RetTy, false, true);
  622. return Cost;
  623. }
  624. unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
  625. InstructionCost getArithmeticInstrCost(
  626. unsigned Opcode, Type *Ty,
  627. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
  628. TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
  629. TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
  630. TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
  631. TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
  632. ArrayRef<const Value *> Args = ArrayRef<const Value *>(),
  633. const Instruction *CxtI = nullptr) {
  634. // Check if any of the operands are vector operands.
  635. const TargetLoweringBase *TLI = getTLI();
  636. int ISD = TLI->InstructionOpcodeToISD(Opcode);
  637. assert(ISD && "Invalid opcode");
  638. // TODO: Handle more cost kinds.
  639. if (CostKind != TTI::TCK_RecipThroughput)
  640. return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind,
  641. Opd1Info, Opd2Info,
  642. Opd1PropInfo, Opd2PropInfo,
  643. Args, CxtI);
  644. std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
  645. bool IsFloat = Ty->isFPOrFPVectorTy();
  646. // Assume that floating point arithmetic operations cost twice as much as
  647. // integer operations.
  648. InstructionCost OpCost = (IsFloat ? 2 : 1);
  649. if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
  650. // The operation is legal. Assume it costs 1.
  651. // TODO: Once we have extract/insert subvector cost we need to use them.
  652. return LT.first * OpCost;
  653. }
  654. if (!TLI->isOperationExpand(ISD, LT.second)) {
  655. // If the operation is custom lowered, then assume that the code is twice
  656. // as expensive.
  657. return LT.first * 2 * OpCost;
  658. }
  659. // Else, assume that we need to scalarize this op.
  660. // TODO: If one of the types get legalized by splitting, handle this
  661. // similarly to what getCastInstrCost() does.
  662. if (auto *VTy = dyn_cast<VectorType>(Ty)) {
  663. unsigned Num = cast<FixedVectorType>(VTy)->getNumElements();
  664. InstructionCost Cost = thisT()->getArithmeticInstrCost(
  665. Opcode, VTy->getScalarType(), CostKind, Opd1Info, Opd2Info,
  666. Opd1PropInfo, Opd2PropInfo, Args, CxtI);
  667. // Return the cost of multiple scalar invocation plus the cost of
  668. // inserting and extracting the values.
  669. SmallVector<Type *> Tys(Args.size(), Ty);
  670. return getScalarizationOverhead(VTy, Args, Tys) + Num * Cost;
  671. }
  672. // We don't know anything about this scalar instruction.
  673. return OpCost;
  674. }
  675. TTI::ShuffleKind improveShuffleKindFromMask(TTI::ShuffleKind Kind,
  676. ArrayRef<int> Mask) const {
  677. int Limit = Mask.size() * 2;
  678. if (Mask.empty() ||
  679. // Extra check required by isSingleSourceMaskImpl function (called by
  680. // ShuffleVectorInst::isSingleSourceMask).
  681. any_of(Mask, [Limit](int I) { return I >= Limit; }))
  682. return Kind;
  683. switch (Kind) {
  684. case TTI::SK_PermuteSingleSrc:
  685. if (ShuffleVectorInst::isReverseMask(Mask))
  686. return TTI::SK_Reverse;
  687. if (ShuffleVectorInst::isZeroEltSplatMask(Mask))
  688. return TTI::SK_Broadcast;
  689. break;
  690. case TTI::SK_PermuteTwoSrc:
  691. if (ShuffleVectorInst::isSelectMask(Mask))
  692. return TTI::SK_Select;
  693. if (ShuffleVectorInst::isTransposeMask(Mask))
  694. return TTI::SK_Transpose;
  695. break;
  696. case TTI::SK_Select:
  697. case TTI::SK_Reverse:
  698. case TTI::SK_Broadcast:
  699. case TTI::SK_Transpose:
  700. case TTI::SK_InsertSubvector:
  701. case TTI::SK_ExtractSubvector:
  702. break;
  703. }
  704. return Kind;
  705. }
  706. InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
  707. ArrayRef<int> Mask, int Index,
  708. VectorType *SubTp) {
  709. switch (improveShuffleKindFromMask(Kind, Mask)) {
  710. case TTI::SK_Broadcast:
  711. return getBroadcastShuffleOverhead(cast<FixedVectorType>(Tp));
  712. case TTI::SK_Select:
  713. case TTI::SK_Reverse:
  714. case TTI::SK_Transpose:
  715. case TTI::SK_PermuteSingleSrc:
  716. case TTI::SK_PermuteTwoSrc:
  717. return getPermuteShuffleOverhead(cast<FixedVectorType>(Tp));
  718. case TTI::SK_ExtractSubvector:
  719. return getExtractSubvectorOverhead(Tp, Index,
  720. cast<FixedVectorType>(SubTp));
  721. case TTI::SK_InsertSubvector:
  722. return getInsertSubvectorOverhead(Tp, Index,
  723. cast<FixedVectorType>(SubTp));
  724. }
  725. llvm_unreachable("Unknown TTI::ShuffleKind");
  726. }
  727. InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
  728. TTI::CastContextHint CCH,
  729. TTI::TargetCostKind CostKind,
  730. const Instruction *I = nullptr) {
  731. if (BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I) == 0)
  732. return 0;
  733. const TargetLoweringBase *TLI = getTLI();
  734. int ISD = TLI->InstructionOpcodeToISD(Opcode);
  735. assert(ISD && "Invalid opcode");
  736. std::pair<InstructionCost, MVT> SrcLT =
  737. TLI->getTypeLegalizationCost(DL, Src);
  738. std::pair<InstructionCost, MVT> DstLT =
  739. TLI->getTypeLegalizationCost(DL, Dst);
  740. TypeSize SrcSize = SrcLT.second.getSizeInBits();
  741. TypeSize DstSize = DstLT.second.getSizeInBits();
  742. bool IntOrPtrSrc = Src->isIntegerTy() || Src->isPointerTy();
  743. bool IntOrPtrDst = Dst->isIntegerTy() || Dst->isPointerTy();
  744. switch (Opcode) {
  745. default:
  746. break;
  747. case Instruction::Trunc:
  748. // Check for NOOP conversions.
  749. if (TLI->isTruncateFree(SrcLT.second, DstLT.second))
  750. return 0;
  751. LLVM_FALLTHROUGH;
  752. case Instruction::BitCast:
  753. // Bitcast between types that are legalized to the same type are free and
  754. // assume int to/from ptr of the same size is also free.
  755. if (SrcLT.first == DstLT.first && IntOrPtrSrc == IntOrPtrDst &&
  756. SrcSize == DstSize)
  757. return 0;
  758. break;
  759. case Instruction::FPExt:
  760. if (I && getTLI()->isExtFree(I))
  761. return 0;
  762. break;
  763. case Instruction::ZExt:
  764. if (TLI->isZExtFree(SrcLT.second, DstLT.second))
  765. return 0;
  766. LLVM_FALLTHROUGH;
  767. case Instruction::SExt:
  768. if (I && getTLI()->isExtFree(I))
  769. return 0;
  770. // If this is a zext/sext of a load, return 0 if the corresponding
  771. // extending load exists on target and the result type is legal.
  772. if (CCH == TTI::CastContextHint::Normal) {
  773. EVT ExtVT = EVT::getEVT(Dst);
  774. EVT LoadVT = EVT::getEVT(Src);
  775. unsigned LType =
  776. ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
  777. if (DstLT.first == SrcLT.first &&
  778. TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
  779. return 0;
  780. }
  781. break;
  782. case Instruction::AddrSpaceCast:
  783. if (TLI->isFreeAddrSpaceCast(Src->getPointerAddressSpace(),
  784. Dst->getPointerAddressSpace()))
  785. return 0;
  786. break;
  787. }
  788. auto *SrcVTy = dyn_cast<VectorType>(Src);
  789. auto *DstVTy = dyn_cast<VectorType>(Dst);
  790. // If the cast is marked as legal (or promote) then assume low cost.
  791. if (SrcLT.first == DstLT.first &&
  792. TLI->isOperationLegalOrPromote(ISD, DstLT.second))
  793. return SrcLT.first;
  794. // Handle scalar conversions.
  795. if (!SrcVTy && !DstVTy) {
  796. // Just check the op cost. If the operation is legal then assume it costs
  797. // 1.
  798. if (!TLI->isOperationExpand(ISD, DstLT.second))
  799. return 1;
  800. // Assume that illegal scalar instruction are expensive.
  801. return 4;
  802. }
  803. // Check vector-to-vector casts.
  804. if (DstVTy && SrcVTy) {
  805. // If the cast is between same-sized registers, then the check is simple.
  806. if (SrcLT.first == DstLT.first && SrcSize == DstSize) {
  807. // Assume that Zext is done using AND.
  808. if (Opcode == Instruction::ZExt)
  809. return SrcLT.first;
  810. // Assume that sext is done using SHL and SRA.
  811. if (Opcode == Instruction::SExt)
  812. return SrcLT.first * 2;
  813. // Just check the op cost. If the operation is legal then assume it
  814. // costs
  815. // 1 and multiply by the type-legalization overhead.
  816. if (!TLI->isOperationExpand(ISD, DstLT.second))
  817. return SrcLT.first * 1;
  818. }
  819. // If we are legalizing by splitting, query the concrete TTI for the cost
  820. // of casting the original vector twice. We also need to factor in the
  821. // cost of the split itself. Count that as 1, to be consistent with
  822. // TLI->getTypeLegalizationCost().
  823. bool SplitSrc =
  824. TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
  825. TargetLowering::TypeSplitVector;
  826. bool SplitDst =
  827. TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
  828. TargetLowering::TypeSplitVector;
  829. if ((SplitSrc || SplitDst) && SrcVTy->getElementCount().isVector() &&
  830. DstVTy->getElementCount().isVector()) {
  831. Type *SplitDstTy = VectorType::getHalfElementsVectorType(DstVTy);
  832. Type *SplitSrcTy = VectorType::getHalfElementsVectorType(SrcVTy);
  833. T *TTI = static_cast<T *>(this);
  834. // If both types need to be split then the split is free.
  835. InstructionCost SplitCost =
  836. (!SplitSrc || !SplitDst) ? TTI->getVectorSplitCost() : 0;
  837. return SplitCost +
  838. (2 * TTI->getCastInstrCost(Opcode, SplitDstTy, SplitSrcTy, CCH,
  839. CostKind, I));
  840. }
  841. // In other cases where the source or destination are illegal, assume
  842. // the operation will get scalarized.
  843. unsigned Num = cast<FixedVectorType>(DstVTy)->getNumElements();
  844. InstructionCost Cost = thisT()->getCastInstrCost(
  845. Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind, I);
  846. // Return the cost of multiple scalar invocation plus the cost of
  847. // inserting and extracting the values.
  848. return getScalarizationOverhead(DstVTy, true, true) + Num * Cost;
  849. }
  850. // We already handled vector-to-vector and scalar-to-scalar conversions.
  851. // This
  852. // is where we handle bitcast between vectors and scalars. We need to assume
  853. // that the conversion is scalarized in one way or another.
  854. if (Opcode == Instruction::BitCast) {
  855. // Illegal bitcasts are done by storing and loading from a stack slot.
  856. return (SrcVTy ? getScalarizationOverhead(SrcVTy, false, true) : 0) +
  857. (DstVTy ? getScalarizationOverhead(DstVTy, true, false) : 0);
  858. }
  859. llvm_unreachable("Unhandled cast");
  860. }
  861. InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
  862. VectorType *VecTy, unsigned Index) {
  863. return thisT()->getVectorInstrCost(Instruction::ExtractElement, VecTy,
  864. Index) +
  865. thisT()->getCastInstrCost(Opcode, Dst, VecTy->getElementType(),
  866. TTI::CastContextHint::None,
  867. TTI::TCK_RecipThroughput);
  868. }
  869. InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind,
  870. const Instruction *I = nullptr) {
  871. return BaseT::getCFInstrCost(Opcode, CostKind, I);
  872. }
  873. InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
  874. CmpInst::Predicate VecPred,
  875. TTI::TargetCostKind CostKind,
  876. const Instruction *I = nullptr) {
  877. const TargetLoweringBase *TLI = getTLI();
  878. int ISD = TLI->InstructionOpcodeToISD(Opcode);
  879. assert(ISD && "Invalid opcode");
  880. // TODO: Handle other cost kinds.
  881. if (CostKind != TTI::TCK_RecipThroughput)
  882. return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
  883. I);
  884. // Selects on vectors are actually vector selects.
  885. if (ISD == ISD::SELECT) {
  886. assert(CondTy && "CondTy must exist");
  887. if (CondTy->isVectorTy())
  888. ISD = ISD::VSELECT;
  889. }
  890. std::pair<InstructionCost, MVT> LT =
  891. TLI->getTypeLegalizationCost(DL, ValTy);
  892. if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
  893. !TLI->isOperationExpand(ISD, LT.second)) {
  894. // The operation is legal. Assume it costs 1. Multiply
  895. // by the type-legalization overhead.
  896. return LT.first * 1;
  897. }
  898. // Otherwise, assume that the cast is scalarized.
  899. // TODO: If one of the types get legalized by splitting, handle this
  900. // similarly to what getCastInstrCost() does.
  901. if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
  902. unsigned Num = cast<FixedVectorType>(ValVTy)->getNumElements();
  903. if (CondTy)
  904. CondTy = CondTy->getScalarType();
  905. InstructionCost Cost = thisT()->getCmpSelInstrCost(
  906. Opcode, ValVTy->getScalarType(), CondTy, VecPred, CostKind, I);
  907. // Return the cost of multiple scalar invocation plus the cost of
  908. // inserting and extracting the values.
  909. return getScalarizationOverhead(ValVTy, true, false) + Num * Cost;
  910. }
  911. // Unknown scalar opcode.
  912. return 1;
  913. }
  914. InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
  915. unsigned Index) {
  916. std::pair<InstructionCost, MVT> LT =
  917. getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
  918. return LT.first;
  919. }
  920. InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src,
  921. MaybeAlign Alignment, unsigned AddressSpace,
  922. TTI::TargetCostKind CostKind,
  923. const Instruction *I = nullptr) {
  924. assert(!Src->isVoidTy() && "Invalid type");
  925. // Assume types, such as structs, are expensive.
  926. if (getTLI()->getValueType(DL, Src, true) == MVT::Other)
  927. return 4;
  928. std::pair<InstructionCost, MVT> LT =
  929. getTLI()->getTypeLegalizationCost(DL, Src);
  930. // Assuming that all loads of legal types cost 1.
  931. InstructionCost Cost = LT.first;
  932. if (CostKind != TTI::TCK_RecipThroughput)
  933. return Cost;
  934. if (Src->isVectorTy() &&
  935. // In practice it's not currently possible to have a change in lane
  936. // length for extending loads or truncating stores so both types should
  937. // have the same scalable property.
  938. TypeSize::isKnownLT(Src->getPrimitiveSizeInBits(),
  939. LT.second.getSizeInBits())) {
  940. // This is a vector load that legalizes to a larger type than the vector
  941. // itself. Unless the corresponding extending load or truncating store is
  942. // legal, then this will scalarize.
  943. TargetLowering::LegalizeAction LA = TargetLowering::Expand;
  944. EVT MemVT = getTLI()->getValueType(DL, Src);
  945. if (Opcode == Instruction::Store)
  946. LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
  947. else
  948. LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
  949. if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
  950. // This is a vector load/store for some illegal type that is scalarized.
  951. // We must account for the cost of building or decomposing the vector.
  952. Cost += getScalarizationOverhead(cast<VectorType>(Src),
  953. Opcode != Instruction::Store,
  954. Opcode == Instruction::Store);
  955. }
  956. }
  957. return Cost;
  958. }
  959. InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *DataTy,
  960. Align Alignment, unsigned AddressSpace,
  961. TTI::TargetCostKind CostKind) {
  962. return getCommonMaskedMemoryOpCost(Opcode, DataTy, Alignment, true, false,
  963. CostKind);
  964. }
  965. InstructionCost getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
  966. const Value *Ptr, bool VariableMask,
  967. Align Alignment,
  968. TTI::TargetCostKind CostKind,
  969. const Instruction *I = nullptr) {
  970. return getCommonMaskedMemoryOpCost(Opcode, DataTy, Alignment, VariableMask,
  971. true, CostKind);
  972. }
  973. InstructionCost getInterleavedMemoryOpCost(
  974. unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
  975. Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
  976. bool UseMaskForCond = false, bool UseMaskForGaps = false) {
  977. auto *VT = cast<FixedVectorType>(VecTy);
  978. unsigned NumElts = VT->getNumElements();
  979. assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
  980. unsigned NumSubElts = NumElts / Factor;
  981. auto *SubVT = FixedVectorType::get(VT->getElementType(), NumSubElts);
  982. // Firstly, the cost of load/store operation.
  983. InstructionCost Cost;
  984. if (UseMaskForCond || UseMaskForGaps)
  985. Cost = thisT()->getMaskedMemoryOpCost(Opcode, VecTy, Alignment,
  986. AddressSpace, CostKind);
  987. else
  988. Cost = thisT()->getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace,
  989. CostKind);
  990. // Legalize the vector type, and get the legalized and unlegalized type
  991. // sizes.
  992. MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
  993. unsigned VecTySize = thisT()->getDataLayout().getTypeStoreSize(VecTy);
  994. unsigned VecTyLTSize = VecTyLT.getStoreSize();
  995. // Scale the cost of the memory operation by the fraction of legalized
  996. // instructions that will actually be used. We shouldn't account for the
  997. // cost of dead instructions since they will be removed.
  998. //
  999. // E.g., An interleaved load of factor 8:
  1000. // %vec = load <16 x i64>, <16 x i64>* %ptr
  1001. // %v0 = shufflevector %vec, undef, <0, 8>
  1002. //
  1003. // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
  1004. // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
  1005. // type). The other loads are unused.
  1006. //
  1007. // We only scale the cost of loads since interleaved store groups aren't
  1008. // allowed to have gaps.
  1009. if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
  1010. // The number of loads of a legal type it will take to represent a load
  1011. // of the unlegalized vector type.
  1012. unsigned NumLegalInsts = divideCeil(VecTySize, VecTyLTSize);
  1013. // The number of elements of the unlegalized type that correspond to a
  1014. // single legal instruction.
  1015. unsigned NumEltsPerLegalInst = divideCeil(NumElts, NumLegalInsts);
  1016. // Determine which legal instructions will be used.
  1017. BitVector UsedInsts(NumLegalInsts, false);
  1018. for (unsigned Index : Indices)
  1019. for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
  1020. UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
  1021. // Scale the cost of the load by the fraction of legal instructions that
  1022. // will be used.
  1023. Cost *= UsedInsts.count() / NumLegalInsts;
  1024. }
  1025. // Then plus the cost of interleave operation.
  1026. if (Opcode == Instruction::Load) {
  1027. // The interleave cost is similar to extract sub vectors' elements
  1028. // from the wide vector, and insert them into sub vectors.
  1029. //
  1030. // E.g. An interleaved load of factor 2 (with one member of index 0):
  1031. // %vec = load <8 x i32>, <8 x i32>* %ptr
  1032. // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
  1033. // The cost is estimated as extract elements at 0, 2, 4, 6 from the
  1034. // <8 x i32> vector and insert them into a <4 x i32> vector.
  1035. assert(Indices.size() <= Factor &&
  1036. "Interleaved memory op has too many members");
  1037. for (unsigned Index : Indices) {
  1038. assert(Index < Factor && "Invalid index for interleaved memory op");
  1039. // Extract elements from loaded vector for each sub vector.
  1040. for (unsigned i = 0; i < NumSubElts; i++)
  1041. Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, VT,
  1042. Index + i * Factor);
  1043. }
  1044. InstructionCost InsSubCost = 0;
  1045. for (unsigned i = 0; i < NumSubElts; i++)
  1046. InsSubCost +=
  1047. thisT()->getVectorInstrCost(Instruction::InsertElement, SubVT, i);
  1048. Cost += Indices.size() * InsSubCost;
  1049. } else {
  1050. // The interleave cost is extract all elements from sub vectors, and
  1051. // insert them into the wide vector.
  1052. //
  1053. // E.g. An interleaved store of factor 2:
  1054. // %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
  1055. // store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
  1056. // The cost is estimated as extract all elements from both <4 x i32>
  1057. // vectors and insert into the <8 x i32> vector.
  1058. InstructionCost ExtSubCost = 0;
  1059. for (unsigned i = 0; i < NumSubElts; i++)
  1060. ExtSubCost +=
  1061. thisT()->getVectorInstrCost(Instruction::ExtractElement, SubVT, i);
  1062. Cost += ExtSubCost * Factor;
  1063. for (unsigned i = 0; i < NumElts; i++)
  1064. Cost += static_cast<T *>(this)
  1065. ->getVectorInstrCost(Instruction::InsertElement, VT, i);
  1066. }
  1067. if (!UseMaskForCond)
  1068. return Cost;
  1069. Type *I8Type = Type::getInt8Ty(VT->getContext());
  1070. auto *MaskVT = FixedVectorType::get(I8Type, NumElts);
  1071. SubVT = FixedVectorType::get(I8Type, NumSubElts);
  1072. // The Mask shuffling cost is extract all the elements of the Mask
  1073. // and insert each of them Factor times into the wide vector:
  1074. //
  1075. // E.g. an interleaved group with factor 3:
  1076. // %mask = icmp ult <8 x i32> %vec1, %vec2
  1077. // %interleaved.mask = shufflevector <8 x i1> %mask, <8 x i1> undef,
  1078. // <24 x i32> <0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7>
  1079. // The cost is estimated as extract all mask elements from the <8xi1> mask
  1080. // vector and insert them factor times into the <24xi1> shuffled mask
  1081. // vector.
  1082. for (unsigned i = 0; i < NumSubElts; i++)
  1083. Cost +=
  1084. thisT()->getVectorInstrCost(Instruction::ExtractElement, SubVT, i);
  1085. for (unsigned i = 0; i < NumElts; i++)
  1086. Cost +=
  1087. thisT()->getVectorInstrCost(Instruction::InsertElement, MaskVT, i);
  1088. // The Gaps mask is invariant and created outside the loop, therefore the
  1089. // cost of creating it is not accounted for here. However if we have both
  1090. // a MaskForGaps and some other mask that guards the execution of the
  1091. // memory access, we need to account for the cost of And-ing the two masks
  1092. // inside the loop.
  1093. if (UseMaskForGaps)
  1094. Cost += thisT()->getArithmeticInstrCost(BinaryOperator::And, MaskVT,
  1095. CostKind);
  1096. return Cost;
  1097. }
  1098. /// Get intrinsic cost based on arguments.
  1099. InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
  1100. TTI::TargetCostKind CostKind) {
  1101. // Check for generically free intrinsics.
  1102. if (BaseT::getIntrinsicInstrCost(ICA, CostKind) == 0)
  1103. return 0;
  1104. // Assume that target intrinsics are cheap.
  1105. Intrinsic::ID IID = ICA.getID();
  1106. if (Function::isTargetIntrinsic(IID))
  1107. return TargetTransformInfo::TCC_Basic;
  1108. if (ICA.isTypeBasedOnly())
  1109. return getTypeBasedIntrinsicInstrCost(ICA, CostKind);
  1110. Type *RetTy = ICA.getReturnType();
  1111. ElementCount RetVF =
  1112. (RetTy->isVectorTy() ? cast<VectorType>(RetTy)->getElementCount()
  1113. : ElementCount::getFixed(1));
  1114. const IntrinsicInst *I = ICA.getInst();
  1115. const SmallVectorImpl<const Value *> &Args = ICA.getArgs();
  1116. FastMathFlags FMF = ICA.getFlags();
  1117. switch (IID) {
  1118. default:
  1119. break;
  1120. case Intrinsic::cttz:
  1121. // FIXME: If necessary, this should go in target-specific overrides.
  1122. if (RetVF.isScalar() && getTLI()->isCheapToSpeculateCttz())
  1123. return TargetTransformInfo::TCC_Basic;
  1124. break;
  1125. case Intrinsic::ctlz:
  1126. // FIXME: If necessary, this should go in target-specific overrides.
  1127. if (RetVF.isScalar() && getTLI()->isCheapToSpeculateCtlz())
  1128. return TargetTransformInfo::TCC_Basic;
  1129. break;
  1130. case Intrinsic::memcpy:
  1131. return thisT()->getMemcpyCost(ICA.getInst());
  1132. case Intrinsic::masked_scatter: {
  1133. const Value *Mask = Args[3];
  1134. bool VarMask = !isa<Constant>(Mask);
  1135. Align Alignment = cast<ConstantInt>(Args[2])->getAlignValue();
  1136. return thisT()->getGatherScatterOpCost(Instruction::Store,
  1137. ICA.getArgTypes()[0], Args[1],
  1138. VarMask, Alignment, CostKind, I);
  1139. }
  1140. case Intrinsic::masked_gather: {
  1141. const Value *Mask = Args[2];
  1142. bool VarMask = !isa<Constant>(Mask);
  1143. Align Alignment = cast<ConstantInt>(Args[1])->getAlignValue();
  1144. return thisT()->getGatherScatterOpCost(Instruction::Load, RetTy, Args[0],
  1145. VarMask, Alignment, CostKind, I);
  1146. }
  1147. case Intrinsic::experimental_stepvector: {
  1148. if (isa<ScalableVectorType>(RetTy))
  1149. return BaseT::getIntrinsicInstrCost(ICA, CostKind);
  1150. // The cost of materialising a constant integer vector.
  1151. return TargetTransformInfo::TCC_Basic;
  1152. }
  1153. case Intrinsic::experimental_vector_extract: {
  1154. // FIXME: Handle case where a scalable vector is extracted from a scalable
  1155. // vector
  1156. if (isa<ScalableVectorType>(RetTy))
  1157. return BaseT::getIntrinsicInstrCost(ICA, CostKind);
  1158. unsigned Index = cast<ConstantInt>(Args[1])->getZExtValue();
  1159. return thisT()->getShuffleCost(TTI::SK_ExtractSubvector,
  1160. cast<VectorType>(Args[0]->getType()), None,
  1161. Index, cast<VectorType>(RetTy));
  1162. }
  1163. case Intrinsic::experimental_vector_insert: {
  1164. // FIXME: Handle case where a scalable vector is inserted into a scalable
  1165. // vector
  1166. if (isa<ScalableVectorType>(Args[1]->getType()))
  1167. return BaseT::getIntrinsicInstrCost(ICA, CostKind);
  1168. unsigned Index = cast<ConstantInt>(Args[2])->getZExtValue();
  1169. return thisT()->getShuffleCost(
  1170. TTI::SK_InsertSubvector, cast<VectorType>(Args[0]->getType()), None,
  1171. Index, cast<VectorType>(Args[1]->getType()));
  1172. }
  1173. case Intrinsic::experimental_vector_reverse: {
  1174. return thisT()->getShuffleCost(TTI::SK_Reverse,
  1175. cast<VectorType>(Args[0]->getType()), None,
  1176. 0, cast<VectorType>(RetTy));
  1177. }
  1178. case Intrinsic::vector_reduce_add:
  1179. case Intrinsic::vector_reduce_mul:
  1180. case Intrinsic::vector_reduce_and:
  1181. case Intrinsic::vector_reduce_or:
  1182. case Intrinsic::vector_reduce_xor:
  1183. case Intrinsic::vector_reduce_smax:
  1184. case Intrinsic::vector_reduce_smin:
  1185. case Intrinsic::vector_reduce_fmax:
  1186. case Intrinsic::vector_reduce_fmin:
  1187. case Intrinsic::vector_reduce_umax:
  1188. case Intrinsic::vector_reduce_umin: {
  1189. IntrinsicCostAttributes Attrs(IID, RetTy, Args[0]->getType(), FMF, I, 1);
  1190. return getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
  1191. }
  1192. case Intrinsic::vector_reduce_fadd:
  1193. case Intrinsic::vector_reduce_fmul: {
  1194. IntrinsicCostAttributes Attrs(
  1195. IID, RetTy, {Args[0]->getType(), Args[1]->getType()}, FMF, I, 1);
  1196. return getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
  1197. }
  1198. case Intrinsic::fshl:
  1199. case Intrinsic::fshr: {
  1200. if (isa<ScalableVectorType>(RetTy))
  1201. return BaseT::getIntrinsicInstrCost(ICA, CostKind);
  1202. const Value *X = Args[0];
  1203. const Value *Y = Args[1];
  1204. const Value *Z = Args[2];
  1205. TTI::OperandValueProperties OpPropsX, OpPropsY, OpPropsZ, OpPropsBW;
  1206. TTI::OperandValueKind OpKindX = TTI::getOperandInfo(X, OpPropsX);
  1207. TTI::OperandValueKind OpKindY = TTI::getOperandInfo(Y, OpPropsY);
  1208. TTI::OperandValueKind OpKindZ = TTI::getOperandInfo(Z, OpPropsZ);
  1209. TTI::OperandValueKind OpKindBW = TTI::OK_UniformConstantValue;
  1210. OpPropsBW = isPowerOf2_32(RetTy->getScalarSizeInBits()) ? TTI::OP_PowerOf2
  1211. : TTI::OP_None;
  1212. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  1213. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  1214. InstructionCost Cost = 0;
  1215. Cost +=
  1216. thisT()->getArithmeticInstrCost(BinaryOperator::Or, RetTy, CostKind);
  1217. Cost +=
  1218. thisT()->getArithmeticInstrCost(BinaryOperator::Sub, RetTy, CostKind);
  1219. Cost += thisT()->getArithmeticInstrCost(
  1220. BinaryOperator::Shl, RetTy, CostKind, OpKindX, OpKindZ, OpPropsX);
  1221. Cost += thisT()->getArithmeticInstrCost(
  1222. BinaryOperator::LShr, RetTy, CostKind, OpKindY, OpKindZ, OpPropsY);
  1223. // Non-constant shift amounts requires a modulo.
  1224. if (OpKindZ != TTI::OK_UniformConstantValue &&
  1225. OpKindZ != TTI::OK_NonUniformConstantValue)
  1226. Cost += thisT()->getArithmeticInstrCost(BinaryOperator::URem, RetTy,
  1227. CostKind, OpKindZ, OpKindBW,
  1228. OpPropsZ, OpPropsBW);
  1229. // For non-rotates (X != Y) we must add shift-by-zero handling costs.
  1230. if (X != Y) {
  1231. Type *CondTy = RetTy->getWithNewBitWidth(1);
  1232. Cost +=
  1233. thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
  1234. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1235. Cost +=
  1236. thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
  1237. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1238. }
  1239. return Cost;
  1240. }
  1241. }
  1242. // Assume that we need to scalarize this intrinsic.
  1243. // Compute the scalarization overhead based on Args for a vector
  1244. // intrinsic.
  1245. InstructionCost ScalarizationCost = InstructionCost::getInvalid();
  1246. if (RetVF.isVector() && !RetVF.isScalable()) {
  1247. ScalarizationCost = 0;
  1248. if (!RetTy->isVoidTy())
  1249. ScalarizationCost +=
  1250. getScalarizationOverhead(cast<VectorType>(RetTy), true, false);
  1251. ScalarizationCost +=
  1252. getOperandsScalarizationOverhead(Args, ICA.getArgTypes());
  1253. }
  1254. IntrinsicCostAttributes Attrs(IID, RetTy, ICA.getArgTypes(), FMF, I,
  1255. ScalarizationCost);
  1256. return thisT()->getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
  1257. }
  1258. /// Get intrinsic cost based on argument types.
  1259. /// If ScalarizationCostPassed is std::numeric_limits<unsigned>::max(), the
  1260. /// cost of scalarizing the arguments and the return value will be computed
  1261. /// based on types.
  1262. InstructionCost
  1263. getTypeBasedIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
  1264. TTI::TargetCostKind CostKind) {
  1265. Intrinsic::ID IID = ICA.getID();
  1266. Type *RetTy = ICA.getReturnType();
  1267. const SmallVectorImpl<Type *> &Tys = ICA.getArgTypes();
  1268. FastMathFlags FMF = ICA.getFlags();
  1269. InstructionCost ScalarizationCostPassed = ICA.getScalarizationCost();
  1270. bool SkipScalarizationCost = ICA.skipScalarizationCost();
  1271. VectorType *VecOpTy = nullptr;
  1272. if (!Tys.empty()) {
  1273. // The vector reduction operand is operand 0 except for fadd/fmul.
  1274. // Their operand 0 is a scalar start value, so the vector op is operand 1.
  1275. unsigned VecTyIndex = 0;
  1276. if (IID == Intrinsic::vector_reduce_fadd ||
  1277. IID == Intrinsic::vector_reduce_fmul)
  1278. VecTyIndex = 1;
  1279. assert(Tys.size() > VecTyIndex && "Unexpected IntrinsicCostAttributes");
  1280. VecOpTy = dyn_cast<VectorType>(Tys[VecTyIndex]);
  1281. }
  1282. // Library call cost - other than size, make it expensive.
  1283. unsigned SingleCallCost = CostKind == TTI::TCK_CodeSize ? 1 : 10;
  1284. SmallVector<unsigned, 2> ISDs;
  1285. switch (IID) {
  1286. default: {
  1287. // Scalable vectors cannot be scalarized, so return Invalid.
  1288. if (isa<ScalableVectorType>(RetTy) || any_of(Tys, [](const Type *Ty) {
  1289. return isa<ScalableVectorType>(Ty);
  1290. }))
  1291. return InstructionCost::getInvalid();
  1292. // Assume that we need to scalarize this intrinsic.
  1293. InstructionCost ScalarizationCost =
  1294. SkipScalarizationCost ? ScalarizationCostPassed : 0;
  1295. unsigned ScalarCalls = 1;
  1296. Type *ScalarRetTy = RetTy;
  1297. if (auto *RetVTy = dyn_cast<VectorType>(RetTy)) {
  1298. if (!SkipScalarizationCost)
  1299. ScalarizationCost = getScalarizationOverhead(RetVTy, true, false);
  1300. ScalarCalls = std::max(ScalarCalls,
  1301. cast<FixedVectorType>(RetVTy)->getNumElements());
  1302. ScalarRetTy = RetTy->getScalarType();
  1303. }
  1304. SmallVector<Type *, 4> ScalarTys;
  1305. for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
  1306. Type *Ty = Tys[i];
  1307. if (auto *VTy = dyn_cast<VectorType>(Ty)) {
  1308. if (!SkipScalarizationCost)
  1309. ScalarizationCost += getScalarizationOverhead(VTy, false, true);
  1310. ScalarCalls = std::max(ScalarCalls,
  1311. cast<FixedVectorType>(VTy)->getNumElements());
  1312. Ty = Ty->getScalarType();
  1313. }
  1314. ScalarTys.push_back(Ty);
  1315. }
  1316. if (ScalarCalls == 1)
  1317. return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
  1318. IntrinsicCostAttributes ScalarAttrs(IID, ScalarRetTy, ScalarTys, FMF);
  1319. InstructionCost ScalarCost =
  1320. thisT()->getIntrinsicInstrCost(ScalarAttrs, CostKind);
  1321. return ScalarCalls * ScalarCost + ScalarizationCost;
  1322. }
  1323. // Look for intrinsics that can be lowered directly or turned into a scalar
  1324. // intrinsic call.
  1325. case Intrinsic::sqrt:
  1326. ISDs.push_back(ISD::FSQRT);
  1327. break;
  1328. case Intrinsic::sin:
  1329. ISDs.push_back(ISD::FSIN);
  1330. break;
  1331. case Intrinsic::cos:
  1332. ISDs.push_back(ISD::FCOS);
  1333. break;
  1334. case Intrinsic::exp:
  1335. ISDs.push_back(ISD::FEXP);
  1336. break;
  1337. case Intrinsic::exp2:
  1338. ISDs.push_back(ISD::FEXP2);
  1339. break;
  1340. case Intrinsic::log:
  1341. ISDs.push_back(ISD::FLOG);
  1342. break;
  1343. case Intrinsic::log10:
  1344. ISDs.push_back(ISD::FLOG10);
  1345. break;
  1346. case Intrinsic::log2:
  1347. ISDs.push_back(ISD::FLOG2);
  1348. break;
  1349. case Intrinsic::fabs:
  1350. ISDs.push_back(ISD::FABS);
  1351. break;
  1352. case Intrinsic::canonicalize:
  1353. ISDs.push_back(ISD::FCANONICALIZE);
  1354. break;
  1355. case Intrinsic::minnum:
  1356. ISDs.push_back(ISD::FMINNUM);
  1357. break;
  1358. case Intrinsic::maxnum:
  1359. ISDs.push_back(ISD::FMAXNUM);
  1360. break;
  1361. case Intrinsic::minimum:
  1362. ISDs.push_back(ISD::FMINIMUM);
  1363. break;
  1364. case Intrinsic::maximum:
  1365. ISDs.push_back(ISD::FMAXIMUM);
  1366. break;
  1367. case Intrinsic::copysign:
  1368. ISDs.push_back(ISD::FCOPYSIGN);
  1369. break;
  1370. case Intrinsic::floor:
  1371. ISDs.push_back(ISD::FFLOOR);
  1372. break;
  1373. case Intrinsic::ceil:
  1374. ISDs.push_back(ISD::FCEIL);
  1375. break;
  1376. case Intrinsic::trunc:
  1377. ISDs.push_back(ISD::FTRUNC);
  1378. break;
  1379. case Intrinsic::nearbyint:
  1380. ISDs.push_back(ISD::FNEARBYINT);
  1381. break;
  1382. case Intrinsic::rint:
  1383. ISDs.push_back(ISD::FRINT);
  1384. break;
  1385. case Intrinsic::round:
  1386. ISDs.push_back(ISD::FROUND);
  1387. break;
  1388. case Intrinsic::roundeven:
  1389. ISDs.push_back(ISD::FROUNDEVEN);
  1390. break;
  1391. case Intrinsic::pow:
  1392. ISDs.push_back(ISD::FPOW);
  1393. break;
  1394. case Intrinsic::fma:
  1395. ISDs.push_back(ISD::FMA);
  1396. break;
  1397. case Intrinsic::fmuladd:
  1398. ISDs.push_back(ISD::FMA);
  1399. break;
  1400. case Intrinsic::experimental_constrained_fmuladd:
  1401. ISDs.push_back(ISD::STRICT_FMA);
  1402. break;
  1403. // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
  1404. case Intrinsic::lifetime_start:
  1405. case Intrinsic::lifetime_end:
  1406. case Intrinsic::sideeffect:
  1407. case Intrinsic::pseudoprobe:
  1408. return 0;
  1409. case Intrinsic::masked_store: {
  1410. Type *Ty = Tys[0];
  1411. Align TyAlign = thisT()->DL.getABITypeAlign(Ty);
  1412. return thisT()->getMaskedMemoryOpCost(Instruction::Store, Ty, TyAlign, 0,
  1413. CostKind);
  1414. }
  1415. case Intrinsic::masked_load: {
  1416. Type *Ty = RetTy;
  1417. Align TyAlign = thisT()->DL.getABITypeAlign(Ty);
  1418. return thisT()->getMaskedMemoryOpCost(Instruction::Load, Ty, TyAlign, 0,
  1419. CostKind);
  1420. }
  1421. case Intrinsic::vector_reduce_add:
  1422. return thisT()->getArithmeticReductionCost(Instruction::Add, VecOpTy,
  1423. /*IsPairwiseForm=*/false,
  1424. CostKind);
  1425. case Intrinsic::vector_reduce_mul:
  1426. return thisT()->getArithmeticReductionCost(Instruction::Mul, VecOpTy,
  1427. /*IsPairwiseForm=*/false,
  1428. CostKind);
  1429. case Intrinsic::vector_reduce_and:
  1430. return thisT()->getArithmeticReductionCost(Instruction::And, VecOpTy,
  1431. /*IsPairwiseForm=*/false,
  1432. CostKind);
  1433. case Intrinsic::vector_reduce_or:
  1434. return thisT()->getArithmeticReductionCost(Instruction::Or, VecOpTy,
  1435. /*IsPairwiseForm=*/false,
  1436. CostKind);
  1437. case Intrinsic::vector_reduce_xor:
  1438. return thisT()->getArithmeticReductionCost(Instruction::Xor, VecOpTy,
  1439. /*IsPairwiseForm=*/false,
  1440. CostKind);
  1441. case Intrinsic::vector_reduce_fadd:
  1442. // FIXME: Add new flag for cost of strict reductions.
  1443. return thisT()->getArithmeticReductionCost(Instruction::FAdd, VecOpTy,
  1444. /*IsPairwiseForm=*/false,
  1445. CostKind);
  1446. case Intrinsic::vector_reduce_fmul:
  1447. // FIXME: Add new flag for cost of strict reductions.
  1448. return thisT()->getArithmeticReductionCost(Instruction::FMul, VecOpTy,
  1449. /*IsPairwiseForm=*/false,
  1450. CostKind);
  1451. case Intrinsic::vector_reduce_smax:
  1452. case Intrinsic::vector_reduce_smin:
  1453. case Intrinsic::vector_reduce_fmax:
  1454. case Intrinsic::vector_reduce_fmin:
  1455. return thisT()->getMinMaxReductionCost(
  1456. VecOpTy, cast<VectorType>(CmpInst::makeCmpResultType(VecOpTy)),
  1457. /*IsPairwiseForm=*/false,
  1458. /*IsUnsigned=*/false, CostKind);
  1459. case Intrinsic::vector_reduce_umax:
  1460. case Intrinsic::vector_reduce_umin:
  1461. return thisT()->getMinMaxReductionCost(
  1462. VecOpTy, cast<VectorType>(CmpInst::makeCmpResultType(VecOpTy)),
  1463. /*IsPairwiseForm=*/false,
  1464. /*IsUnsigned=*/true, CostKind);
  1465. case Intrinsic::abs:
  1466. case Intrinsic::smax:
  1467. case Intrinsic::smin:
  1468. case Intrinsic::umax:
  1469. case Intrinsic::umin: {
  1470. // abs(X) = select(icmp(X,0),X,sub(0,X))
  1471. // minmax(X,Y) = select(icmp(X,Y),X,Y)
  1472. Type *CondTy = RetTy->getWithNewBitWidth(1);
  1473. InstructionCost Cost = 0;
  1474. // TODO: Ideally getCmpSelInstrCost would accept an icmp condition code.
  1475. Cost +=
  1476. thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
  1477. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1478. Cost +=
  1479. thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
  1480. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1481. // TODO: Should we add an OperandValueProperties::OP_Zero property?
  1482. if (IID == Intrinsic::abs)
  1483. Cost += thisT()->getArithmeticInstrCost(
  1484. BinaryOperator::Sub, RetTy, CostKind, TTI::OK_UniformConstantValue);
  1485. return Cost;
  1486. }
  1487. case Intrinsic::sadd_sat:
  1488. case Intrinsic::ssub_sat: {
  1489. Type *CondTy = RetTy->getWithNewBitWidth(1);
  1490. Type *OpTy = StructType::create({RetTy, CondTy});
  1491. Intrinsic::ID OverflowOp = IID == Intrinsic::sadd_sat
  1492. ? Intrinsic::sadd_with_overflow
  1493. : Intrinsic::ssub_with_overflow;
  1494. // SatMax -> Overflow && SumDiff < 0
  1495. // SatMin -> Overflow && SumDiff >= 0
  1496. InstructionCost Cost = 0;
  1497. IntrinsicCostAttributes Attrs(OverflowOp, OpTy, {RetTy, RetTy}, FMF,
  1498. nullptr, ScalarizationCostPassed);
  1499. Cost += thisT()->getIntrinsicInstrCost(Attrs, CostKind);
  1500. Cost +=
  1501. thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
  1502. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1503. Cost += 2 * thisT()->getCmpSelInstrCost(
  1504. BinaryOperator::Select, RetTy, CondTy,
  1505. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1506. return Cost;
  1507. }
  1508. case Intrinsic::uadd_sat:
  1509. case Intrinsic::usub_sat: {
  1510. Type *CondTy = RetTy->getWithNewBitWidth(1);
  1511. Type *OpTy = StructType::create({RetTy, CondTy});
  1512. Intrinsic::ID OverflowOp = IID == Intrinsic::uadd_sat
  1513. ? Intrinsic::uadd_with_overflow
  1514. : Intrinsic::usub_with_overflow;
  1515. InstructionCost Cost = 0;
  1516. IntrinsicCostAttributes Attrs(OverflowOp, OpTy, {RetTy, RetTy}, FMF,
  1517. nullptr, ScalarizationCostPassed);
  1518. Cost += thisT()->getIntrinsicInstrCost(Attrs, CostKind);
  1519. Cost +=
  1520. thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
  1521. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1522. return Cost;
  1523. }
  1524. case Intrinsic::smul_fix:
  1525. case Intrinsic::umul_fix: {
  1526. unsigned ExtSize = RetTy->getScalarSizeInBits() * 2;
  1527. Type *ExtTy = RetTy->getWithNewBitWidth(ExtSize);
  1528. unsigned ExtOp =
  1529. IID == Intrinsic::smul_fix ? Instruction::SExt : Instruction::ZExt;
  1530. TTI::CastContextHint CCH = TTI::CastContextHint::None;
  1531. InstructionCost Cost = 0;
  1532. Cost += 2 * thisT()->getCastInstrCost(ExtOp, ExtTy, RetTy, CCH, CostKind);
  1533. Cost +=
  1534. thisT()->getArithmeticInstrCost(Instruction::Mul, ExtTy, CostKind);
  1535. Cost += 2 * thisT()->getCastInstrCost(Instruction::Trunc, RetTy, ExtTy,
  1536. CCH, CostKind);
  1537. Cost += thisT()->getArithmeticInstrCost(Instruction::LShr, RetTy,
  1538. CostKind, TTI::OK_AnyValue,
  1539. TTI::OK_UniformConstantValue);
  1540. Cost += thisT()->getArithmeticInstrCost(Instruction::Shl, RetTy, CostKind,
  1541. TTI::OK_AnyValue,
  1542. TTI::OK_UniformConstantValue);
  1543. Cost += thisT()->getArithmeticInstrCost(Instruction::Or, RetTy, CostKind);
  1544. return Cost;
  1545. }
  1546. case Intrinsic::sadd_with_overflow:
  1547. case Intrinsic::ssub_with_overflow: {
  1548. Type *SumTy = RetTy->getContainedType(0);
  1549. Type *OverflowTy = RetTy->getContainedType(1);
  1550. unsigned Opcode = IID == Intrinsic::sadd_with_overflow
  1551. ? BinaryOperator::Add
  1552. : BinaryOperator::Sub;
  1553. // LHSSign -> LHS >= 0
  1554. // RHSSign -> RHS >= 0
  1555. // SumSign -> Sum >= 0
  1556. //
  1557. // Add:
  1558. // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
  1559. // Sub:
  1560. // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
  1561. InstructionCost Cost = 0;
  1562. Cost += thisT()->getArithmeticInstrCost(Opcode, SumTy, CostKind);
  1563. Cost += 3 * thisT()->getCmpSelInstrCost(
  1564. Instruction::ICmp, SumTy, OverflowTy,
  1565. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1566. Cost += 2 * thisT()->getCmpSelInstrCost(
  1567. Instruction::Select, OverflowTy, OverflowTy,
  1568. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1569. Cost += thisT()->getArithmeticInstrCost(BinaryOperator::And, OverflowTy,
  1570. CostKind);
  1571. return Cost;
  1572. }
  1573. case Intrinsic::uadd_with_overflow:
  1574. case Intrinsic::usub_with_overflow: {
  1575. Type *SumTy = RetTy->getContainedType(0);
  1576. Type *OverflowTy = RetTy->getContainedType(1);
  1577. unsigned Opcode = IID == Intrinsic::uadd_with_overflow
  1578. ? BinaryOperator::Add
  1579. : BinaryOperator::Sub;
  1580. InstructionCost Cost = 0;
  1581. Cost += thisT()->getArithmeticInstrCost(Opcode, SumTy, CostKind);
  1582. Cost +=
  1583. thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, SumTy, OverflowTy,
  1584. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1585. return Cost;
  1586. }
  1587. case Intrinsic::smul_with_overflow:
  1588. case Intrinsic::umul_with_overflow: {
  1589. Type *MulTy = RetTy->getContainedType(0);
  1590. Type *OverflowTy = RetTy->getContainedType(1);
  1591. unsigned ExtSize = MulTy->getScalarSizeInBits() * 2;
  1592. Type *ExtTy = MulTy->getWithNewBitWidth(ExtSize);
  1593. unsigned ExtOp =
  1594. IID == Intrinsic::smul_fix ? Instruction::SExt : Instruction::ZExt;
  1595. TTI::CastContextHint CCH = TTI::CastContextHint::None;
  1596. InstructionCost Cost = 0;
  1597. Cost += 2 * thisT()->getCastInstrCost(ExtOp, ExtTy, MulTy, CCH, CostKind);
  1598. Cost +=
  1599. thisT()->getArithmeticInstrCost(Instruction::Mul, ExtTy, CostKind);
  1600. Cost += 2 * thisT()->getCastInstrCost(Instruction::Trunc, MulTy, ExtTy,
  1601. CCH, CostKind);
  1602. Cost += thisT()->getArithmeticInstrCost(Instruction::LShr, MulTy,
  1603. CostKind, TTI::OK_AnyValue,
  1604. TTI::OK_UniformConstantValue);
  1605. if (IID == Intrinsic::smul_with_overflow)
  1606. Cost += thisT()->getArithmeticInstrCost(Instruction::AShr, MulTy,
  1607. CostKind, TTI::OK_AnyValue,
  1608. TTI::OK_UniformConstantValue);
  1609. Cost +=
  1610. thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, MulTy, OverflowTy,
  1611. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1612. return Cost;
  1613. }
  1614. case Intrinsic::ctpop:
  1615. ISDs.push_back(ISD::CTPOP);
  1616. // In case of legalization use TCC_Expensive. This is cheaper than a
  1617. // library call but still not a cheap instruction.
  1618. SingleCallCost = TargetTransformInfo::TCC_Expensive;
  1619. break;
  1620. case Intrinsic::ctlz:
  1621. ISDs.push_back(ISD::CTLZ);
  1622. break;
  1623. case Intrinsic::cttz:
  1624. ISDs.push_back(ISD::CTTZ);
  1625. break;
  1626. case Intrinsic::bswap:
  1627. ISDs.push_back(ISD::BSWAP);
  1628. break;
  1629. case Intrinsic::bitreverse:
  1630. ISDs.push_back(ISD::BITREVERSE);
  1631. break;
  1632. }
  1633. const TargetLoweringBase *TLI = getTLI();
  1634. std::pair<InstructionCost, MVT> LT =
  1635. TLI->getTypeLegalizationCost(DL, RetTy);
  1636. SmallVector<InstructionCost, 2> LegalCost;
  1637. SmallVector<InstructionCost, 2> CustomCost;
  1638. for (unsigned ISD : ISDs) {
  1639. if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
  1640. if (IID == Intrinsic::fabs && LT.second.isFloatingPoint() &&
  1641. TLI->isFAbsFree(LT.second)) {
  1642. return 0;
  1643. }
  1644. // The operation is legal. Assume it costs 1.
  1645. // If the type is split to multiple registers, assume that there is some
  1646. // overhead to this.
  1647. // TODO: Once we have extract/insert subvector cost we need to use them.
  1648. if (LT.first > 1)
  1649. LegalCost.push_back(LT.first * 2);
  1650. else
  1651. LegalCost.push_back(LT.first * 1);
  1652. } else if (!TLI->isOperationExpand(ISD, LT.second)) {
  1653. // If the operation is custom lowered then assume
  1654. // that the code is twice as expensive.
  1655. CustomCost.push_back(LT.first * 2);
  1656. }
  1657. }
  1658. auto *MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
  1659. if (MinLegalCostI != LegalCost.end())
  1660. return *MinLegalCostI;
  1661. auto MinCustomCostI =
  1662. std::min_element(CustomCost.begin(), CustomCost.end());
  1663. if (MinCustomCostI != CustomCost.end())
  1664. return *MinCustomCostI;
  1665. // If we can't lower fmuladd into an FMA estimate the cost as a floating
  1666. // point mul followed by an add.
  1667. if (IID == Intrinsic::fmuladd)
  1668. return thisT()->getArithmeticInstrCost(BinaryOperator::FMul, RetTy,
  1669. CostKind) +
  1670. thisT()->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy,
  1671. CostKind);
  1672. if (IID == Intrinsic::experimental_constrained_fmuladd) {
  1673. IntrinsicCostAttributes FMulAttrs(
  1674. Intrinsic::experimental_constrained_fmul, RetTy, Tys);
  1675. IntrinsicCostAttributes FAddAttrs(
  1676. Intrinsic::experimental_constrained_fadd, RetTy, Tys);
  1677. return thisT()->getIntrinsicInstrCost(FMulAttrs, CostKind) +
  1678. thisT()->getIntrinsicInstrCost(FAddAttrs, CostKind);
  1679. }
  1680. // Else, assume that we need to scalarize this intrinsic. For math builtins
  1681. // this will emit a costly libcall, adding call overhead and spills. Make it
  1682. // very expensive.
  1683. if (auto *RetVTy = dyn_cast<VectorType>(RetTy)) {
  1684. // Scalable vectors cannot be scalarized, so return Invalid.
  1685. if (isa<ScalableVectorType>(RetTy) || any_of(Tys, [](const Type *Ty) {
  1686. return isa<ScalableVectorType>(Ty);
  1687. }))
  1688. return InstructionCost::getInvalid();
  1689. InstructionCost ScalarizationCost =
  1690. SkipScalarizationCost ? ScalarizationCostPassed
  1691. : getScalarizationOverhead(RetVTy, true, false);
  1692. unsigned ScalarCalls = cast<FixedVectorType>(RetVTy)->getNumElements();
  1693. SmallVector<Type *, 4> ScalarTys;
  1694. for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
  1695. Type *Ty = Tys[i];
  1696. if (Ty->isVectorTy())
  1697. Ty = Ty->getScalarType();
  1698. ScalarTys.push_back(Ty);
  1699. }
  1700. IntrinsicCostAttributes Attrs(IID, RetTy->getScalarType(), ScalarTys, FMF);
  1701. InstructionCost ScalarCost =
  1702. thisT()->getIntrinsicInstrCost(Attrs, CostKind);
  1703. for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
  1704. if (auto *VTy = dyn_cast<VectorType>(Tys[i])) {
  1705. if (!ICA.skipScalarizationCost())
  1706. ScalarizationCost += getScalarizationOverhead(VTy, false, true);
  1707. ScalarCalls = std::max(ScalarCalls,
  1708. cast<FixedVectorType>(VTy)->getNumElements());
  1709. }
  1710. }
  1711. return ScalarCalls * ScalarCost + ScalarizationCost;
  1712. }
  1713. // This is going to be turned into a library call, make it expensive.
  1714. return SingleCallCost;
  1715. }
  1716. /// Compute a cost of the given call instruction.
  1717. ///
  1718. /// Compute the cost of calling function F with return type RetTy and
  1719. /// argument types Tys. F might be nullptr, in this case the cost of an
  1720. /// arbitrary call with the specified signature will be returned.
  1721. /// This is used, for instance, when we estimate call of a vector
  1722. /// counterpart of the given function.
  1723. /// \param F Called function, might be nullptr.
  1724. /// \param RetTy Return value types.
  1725. /// \param Tys Argument types.
  1726. /// \returns The cost of Call instruction.
  1727. InstructionCost
  1728. getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys,
  1729. TTI::TargetCostKind CostKind = TTI::TCK_SizeAndLatency) {
  1730. return 10;
  1731. }
  1732. unsigned getNumberOfParts(Type *Tp) {
  1733. std::pair<InstructionCost, MVT> LT =
  1734. getTLI()->getTypeLegalizationCost(DL, Tp);
  1735. return *LT.first.getValue();
  1736. }
  1737. InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *,
  1738. const SCEV *) {
  1739. return 0;
  1740. }
  1741. /// Try to calculate arithmetic and shuffle op costs for reduction operations.
  1742. /// We're assuming that reduction operation are performing the following way:
  1743. /// 1. Non-pairwise reduction
  1744. /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
  1745. /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
  1746. /// \----------------v-------------/ \----------v------------/
  1747. /// n/2 elements n/2 elements
  1748. /// %red1 = op <n x t> %val, <n x t> val1
  1749. /// After this operation we have a vector %red1 where only the first n/2
  1750. /// elements are meaningful, the second n/2 elements are undefined and can be
  1751. /// dropped. All other operations are actually working with the vector of
  1752. /// length n/2, not n, though the real vector length is still n.
  1753. /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
  1754. /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
  1755. /// \----------------v-------------/ \----------v------------/
  1756. /// n/4 elements 3*n/4 elements
  1757. /// %red2 = op <n x t> %red1, <n x t> val2 - working with the vector of
  1758. /// length n/2, the resulting vector has length n/4 etc.
  1759. /// 2. Pairwise reduction:
  1760. /// Everything is the same except for an additional shuffle operation which
  1761. /// is used to produce operands for pairwise kind of reductions.
  1762. /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
  1763. /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
  1764. /// \-------------v----------/ \----------v------------/
  1765. /// n/2 elements n/2 elements
  1766. /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
  1767. /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
  1768. /// \-------------v----------/ \----------v------------/
  1769. /// n/2 elements n/2 elements
  1770. /// %red1 = op <n x t> %val1, <n x t> val2
  1771. /// Again, the operation is performed on <n x t> vector, but the resulting
  1772. /// vector %red1 is <n/2 x t> vector.
  1773. ///
  1774. /// The cost model should take into account that the actual length of the
  1775. /// vector is reduced on each iteration.
  1776. InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
  1777. bool IsPairwise,
  1778. TTI::TargetCostKind CostKind) {
  1779. Type *ScalarTy = Ty->getElementType();
  1780. unsigned NumVecElts = cast<FixedVectorType>(Ty)->getNumElements();
  1781. if ((Opcode == Instruction::Or || Opcode == Instruction::And) &&
  1782. ScalarTy == IntegerType::getInt1Ty(Ty->getContext()) &&
  1783. NumVecElts >= 2) {
  1784. // Or reduction for i1 is represented as:
  1785. // %val = bitcast <ReduxWidth x i1> to iReduxWidth
  1786. // %res = cmp ne iReduxWidth %val, 0
  1787. // And reduction for i1 is represented as:
  1788. // %val = bitcast <ReduxWidth x i1> to iReduxWidth
  1789. // %res = cmp eq iReduxWidth %val, 11111
  1790. Type *ValTy = IntegerType::get(Ty->getContext(), NumVecElts);
  1791. return thisT()->getCastInstrCost(Instruction::BitCast, ValTy, Ty,
  1792. TTI::CastContextHint::None, CostKind) +
  1793. thisT()->getCmpSelInstrCost(Instruction::ICmp, ValTy,
  1794. CmpInst::makeCmpResultType(ValTy),
  1795. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1796. }
  1797. unsigned NumReduxLevels = Log2_32(NumVecElts);
  1798. InstructionCost ArithCost = 0;
  1799. InstructionCost ShuffleCost = 0;
  1800. std::pair<InstructionCost, MVT> LT =
  1801. thisT()->getTLI()->getTypeLegalizationCost(DL, Ty);
  1802. unsigned LongVectorCount = 0;
  1803. unsigned MVTLen =
  1804. LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
  1805. while (NumVecElts > MVTLen) {
  1806. NumVecElts /= 2;
  1807. VectorType *SubTy = FixedVectorType::get(ScalarTy, NumVecElts);
  1808. // Assume the pairwise shuffles add a cost.
  1809. ShuffleCost += (IsPairwise + 1) *
  1810. thisT()->getShuffleCost(TTI::SK_ExtractSubvector, Ty, None,
  1811. NumVecElts, SubTy);
  1812. ArithCost += thisT()->getArithmeticInstrCost(Opcode, SubTy, CostKind);
  1813. Ty = SubTy;
  1814. ++LongVectorCount;
  1815. }
  1816. NumReduxLevels -= LongVectorCount;
  1817. // The minimal length of the vector is limited by the real length of vector
  1818. // operations performed on the current platform. That's why several final
  1819. // reduction operations are performed on the vectors with the same
  1820. // architecture-dependent length.
  1821. // Non pairwise reductions need one shuffle per reduction level. Pairwise
  1822. // reductions need two shuffles on every level, but the last one. On that
  1823. // level one of the shuffles is <0, u, u, ...> which is identity.
  1824. unsigned NumShuffles = NumReduxLevels;
  1825. if (IsPairwise && NumReduxLevels >= 1)
  1826. NumShuffles += NumReduxLevels - 1;
  1827. ShuffleCost += NumShuffles * thisT()->getShuffleCost(
  1828. TTI::SK_PermuteSingleSrc, Ty, None, 0, Ty);
  1829. ArithCost += NumReduxLevels * thisT()->getArithmeticInstrCost(Opcode, Ty);
  1830. return ShuffleCost + ArithCost +
  1831. thisT()->getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
  1832. }
  1833. /// Try to calculate op costs for min/max reduction operations.
  1834. /// \param CondTy Conditional type for the Select instruction.
  1835. InstructionCost getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
  1836. bool IsPairwise, bool IsUnsigned,
  1837. TTI::TargetCostKind CostKind) {
  1838. Type *ScalarTy = Ty->getElementType();
  1839. Type *ScalarCondTy = CondTy->getElementType();
  1840. unsigned NumVecElts = cast<FixedVectorType>(Ty)->getNumElements();
  1841. unsigned NumReduxLevels = Log2_32(NumVecElts);
  1842. unsigned CmpOpcode;
  1843. if (Ty->isFPOrFPVectorTy()) {
  1844. CmpOpcode = Instruction::FCmp;
  1845. } else {
  1846. assert(Ty->isIntOrIntVectorTy() &&
  1847. "expecting floating point or integer type for min/max reduction");
  1848. CmpOpcode = Instruction::ICmp;
  1849. }
  1850. InstructionCost MinMaxCost = 0;
  1851. InstructionCost ShuffleCost = 0;
  1852. std::pair<InstructionCost, MVT> LT =
  1853. thisT()->getTLI()->getTypeLegalizationCost(DL, Ty);
  1854. unsigned LongVectorCount = 0;
  1855. unsigned MVTLen =
  1856. LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
  1857. while (NumVecElts > MVTLen) {
  1858. NumVecElts /= 2;
  1859. auto *SubTy = FixedVectorType::get(ScalarTy, NumVecElts);
  1860. CondTy = FixedVectorType::get(ScalarCondTy, NumVecElts);
  1861. // Assume the pairwise shuffles add a cost.
  1862. ShuffleCost += (IsPairwise + 1) *
  1863. thisT()->getShuffleCost(TTI::SK_ExtractSubvector, Ty, None,
  1864. NumVecElts, SubTy);
  1865. MinMaxCost +=
  1866. thisT()->getCmpSelInstrCost(CmpOpcode, SubTy, CondTy,
  1867. CmpInst::BAD_ICMP_PREDICATE, CostKind) +
  1868. thisT()->getCmpSelInstrCost(Instruction::Select, SubTy, CondTy,
  1869. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  1870. Ty = SubTy;
  1871. ++LongVectorCount;
  1872. }
  1873. NumReduxLevels -= LongVectorCount;
  1874. // The minimal length of the vector is limited by the real length of vector
  1875. // operations performed on the current platform. That's why several final
  1876. // reduction opertions are perfomed on the vectors with the same
  1877. // architecture-dependent length.
  1878. // Non pairwise reductions need one shuffle per reduction level. Pairwise
  1879. // reductions need two shuffles on every level, but the last one. On that
  1880. // level one of the shuffles is <0, u, u, ...> which is identity.
  1881. unsigned NumShuffles = NumReduxLevels;
  1882. if (IsPairwise && NumReduxLevels >= 1)
  1883. NumShuffles += NumReduxLevels - 1;
  1884. ShuffleCost += NumShuffles * thisT()->getShuffleCost(
  1885. TTI::SK_PermuteSingleSrc, Ty, None, 0, Ty);
  1886. MinMaxCost +=
  1887. NumReduxLevels *
  1888. (thisT()->getCmpSelInstrCost(CmpOpcode, Ty, CondTy,
  1889. CmpInst::BAD_ICMP_PREDICATE, CostKind) +
  1890. thisT()->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
  1891. CmpInst::BAD_ICMP_PREDICATE, CostKind));
  1892. // The last min/max should be in vector registers and we counted it above.
  1893. // So just need a single extractelement.
  1894. return ShuffleCost + MinMaxCost +
  1895. thisT()->getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
  1896. }
  1897. InstructionCost getExtendedAddReductionCost(bool IsMLA, bool IsUnsigned,
  1898. Type *ResTy, VectorType *Ty,
  1899. TTI::TargetCostKind CostKind) {
  1900. // Without any native support, this is equivalent to the cost of
  1901. // vecreduce.add(ext) or if IsMLA vecreduce.add(mul(ext, ext))
  1902. VectorType *ExtTy = VectorType::get(ResTy, Ty);
  1903. InstructionCost RedCost = thisT()->getArithmeticReductionCost(
  1904. Instruction::Add, ExtTy, false, CostKind);
  1905. InstructionCost MulCost = 0;
  1906. InstructionCost ExtCost = thisT()->getCastInstrCost(
  1907. IsUnsigned ? Instruction::ZExt : Instruction::SExt, ExtTy, Ty,
  1908. TTI::CastContextHint::None, CostKind);
  1909. if (IsMLA) {
  1910. MulCost =
  1911. thisT()->getArithmeticInstrCost(Instruction::Mul, ExtTy, CostKind);
  1912. ExtCost *= 2;
  1913. }
  1914. return RedCost + MulCost + ExtCost;
  1915. }
  1916. InstructionCost getVectorSplitCost() { return 1; }
  1917. /// @}
  1918. };
  1919. /// Concrete BasicTTIImpl that can be used if no further customization
  1920. /// is needed.
  1921. class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
  1922. using BaseT = BasicTTIImplBase<BasicTTIImpl>;
  1923. friend class BasicTTIImplBase<BasicTTIImpl>;
  1924. const TargetSubtargetInfo *ST;
  1925. const TargetLoweringBase *TLI;
  1926. const TargetSubtargetInfo *getST() const { return ST; }
  1927. const TargetLoweringBase *getTLI() const { return TLI; }
  1928. public:
  1929. explicit BasicTTIImpl(const TargetMachine *TM, const Function &F);
  1930. };
  1931. } // end namespace llvm
  1932. #endif // LLVM_CODEGEN_BASICTTIIMPL_H