TargetLoweringBase.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. //===- TargetLoweringBase.cpp - Implement the TargetLoweringBase class ----===//
  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. // This implements the TargetLoweringBase class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/BitVector.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/ADT/Twine.h"
  19. #include "llvm/CodeGen/Analysis.h"
  20. #include "llvm/CodeGen/ISDOpcodes.h"
  21. #include "llvm/CodeGen/MachineBasicBlock.h"
  22. #include "llvm/CodeGen/MachineFrameInfo.h"
  23. #include "llvm/CodeGen/MachineFunction.h"
  24. #include "llvm/CodeGen/MachineInstr.h"
  25. #include "llvm/CodeGen/MachineInstrBuilder.h"
  26. #include "llvm/CodeGen/MachineMemOperand.h"
  27. #include "llvm/CodeGen/MachineOperand.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/CodeGen/RuntimeLibcalls.h"
  30. #include "llvm/CodeGen/StackMaps.h"
  31. #include "llvm/CodeGen/TargetLowering.h"
  32. #include "llvm/CodeGen/TargetOpcodes.h"
  33. #include "llvm/CodeGen/TargetRegisterInfo.h"
  34. #include "llvm/CodeGen/ValueTypes.h"
  35. #include "llvm/IR/Attributes.h"
  36. #include "llvm/IR/CallingConv.h"
  37. #include "llvm/IR/DataLayout.h"
  38. #include "llvm/IR/DerivedTypes.h"
  39. #include "llvm/IR/Function.h"
  40. #include "llvm/IR/GlobalValue.h"
  41. #include "llvm/IR/GlobalVariable.h"
  42. #include "llvm/IR/IRBuilder.h"
  43. #include "llvm/IR/Module.h"
  44. #include "llvm/IR/Type.h"
  45. #include "llvm/Support/BranchProbability.h"
  46. #include "llvm/Support/Casting.h"
  47. #include "llvm/Support/CommandLine.h"
  48. #include "llvm/Support/Compiler.h"
  49. #include "llvm/Support/ErrorHandling.h"
  50. #include "llvm/Support/MachineValueType.h"
  51. #include "llvm/Support/MathExtras.h"
  52. #include "llvm/Target/TargetMachine.h"
  53. #include <algorithm>
  54. #include <cassert>
  55. #include <cstddef>
  56. #include <cstdint>
  57. #include <cstring>
  58. #include <iterator>
  59. #include <string>
  60. #include <tuple>
  61. #include <utility>
  62. using namespace llvm;
  63. static cl::opt<bool> JumpIsExpensiveOverride(
  64. "jump-is-expensive", cl::init(false),
  65. cl::desc("Do not create extra branches to split comparison logic."),
  66. cl::Hidden);
  67. static cl::opt<unsigned> MinimumJumpTableEntries
  68. ("min-jump-table-entries", cl::init(4), cl::Hidden,
  69. cl::desc("Set minimum number of entries to use a jump table."));
  70. static cl::opt<unsigned> MaximumJumpTableSize
  71. ("max-jump-table-size", cl::init(UINT_MAX), cl::Hidden,
  72. cl::desc("Set maximum size of jump tables."));
  73. /// Minimum jump table density for normal functions.
  74. static cl::opt<unsigned>
  75. JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden,
  76. cl::desc("Minimum density for building a jump table in "
  77. "a normal function"));
  78. /// Minimum jump table density for -Os or -Oz functions.
  79. static cl::opt<unsigned> OptsizeJumpTableDensity(
  80. "optsize-jump-table-density", cl::init(40), cl::Hidden,
  81. cl::desc("Minimum density for building a jump table in "
  82. "an optsize function"));
  83. static bool darwinHasSinCos(const Triple &TT) {
  84. assert(TT.isOSDarwin() && "should be called with darwin triple");
  85. // Don't bother with 32 bit x86.
  86. if (TT.getArch() == Triple::x86)
  87. return false;
  88. // Macos < 10.9 has no sincos_stret.
  89. if (TT.isMacOSX())
  90. return !TT.isMacOSXVersionLT(10, 9) && TT.isArch64Bit();
  91. // iOS < 7.0 has no sincos_stret.
  92. if (TT.isiOS())
  93. return !TT.isOSVersionLT(7, 0);
  94. // Any other darwin such as WatchOS/TvOS is new enough.
  95. return true;
  96. }
  97. // Although this default value is arbitrary, it is not random. It is assumed
  98. // that a condition that evaluates the same way by a higher percentage than this
  99. // is best represented as control flow. Therefore, the default value N should be
  100. // set such that the win from N% correct executions is greater than the loss
  101. // from (100 - N)% mispredicted executions for the majority of intended targets.
  102. static cl::opt<int> MinPercentageForPredictableBranch(
  103. "min-predictable-branch", cl::init(99),
  104. cl::desc("Minimum percentage (0-100) that a condition must be either true "
  105. "or false to assume that the condition is predictable"),
  106. cl::Hidden);
  107. void TargetLoweringBase::InitLibcalls(const Triple &TT) {
  108. #define HANDLE_LIBCALL(code, name) \
  109. setLibcallName(RTLIB::code, name);
  110. #include "llvm/IR/RuntimeLibcalls.def"
  111. #undef HANDLE_LIBCALL
  112. // Initialize calling conventions to their default.
  113. for (int LC = 0; LC < RTLIB::UNKNOWN_LIBCALL; ++LC)
  114. setLibcallCallingConv((RTLIB::Libcall)LC, CallingConv::C);
  115. // A few names are different on particular architectures or environments.
  116. if (TT.isOSDarwin()) {
  117. // For f16/f32 conversions, Darwin uses the standard naming scheme, instead
  118. // of the gnueabi-style __gnu_*_ieee.
  119. // FIXME: What about other targets?
  120. setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
  121. setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
  122. // Some darwins have an optimized __bzero/bzero function.
  123. switch (TT.getArch()) {
  124. case Triple::x86:
  125. case Triple::x86_64:
  126. if (TT.isMacOSX() && !TT.isMacOSXVersionLT(10, 6))
  127. setLibcallName(RTLIB::BZERO, "__bzero");
  128. break;
  129. case Triple::aarch64:
  130. setLibcallName(RTLIB::BZERO, "bzero");
  131. break;
  132. default:
  133. break;
  134. }
  135. if (darwinHasSinCos(TT)) {
  136. setLibcallName(RTLIB::SINCOS_STRET_F32, "__sincosf_stret");
  137. setLibcallName(RTLIB::SINCOS_STRET_F64, "__sincos_stret");
  138. if (TT.isWatchABI()) {
  139. setLibcallCallingConv(RTLIB::SINCOS_STRET_F32,
  140. CallingConv::ARM_AAPCS_VFP);
  141. setLibcallCallingConv(RTLIB::SINCOS_STRET_F64,
  142. CallingConv::ARM_AAPCS_VFP);
  143. }
  144. }
  145. } else {
  146. setLibcallName(RTLIB::FPEXT_F16_F32, "__gnu_h2f_ieee");
  147. setLibcallName(RTLIB::FPROUND_F32_F16, "__gnu_f2h_ieee");
  148. }
  149. if (TT.isGNUEnvironment() || TT.isOSFuchsia() ||
  150. (TT.isAndroid() && !TT.isAndroidVersionLT(9))) {
  151. setLibcallName(RTLIB::SINCOS_F32, "sincosf");
  152. setLibcallName(RTLIB::SINCOS_F64, "sincos");
  153. setLibcallName(RTLIB::SINCOS_F80, "sincosl");
  154. setLibcallName(RTLIB::SINCOS_F128, "sincosl");
  155. setLibcallName(RTLIB::SINCOS_PPCF128, "sincosl");
  156. }
  157. if (TT.isOSOpenBSD()) {
  158. setLibcallName(RTLIB::STACKPROTECTOR_CHECK_FAIL, nullptr);
  159. }
  160. }
  161. /// getFPEXT - Return the FPEXT_*_* value for the given types, or
  162. /// UNKNOWN_LIBCALL if there is none.
  163. RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
  164. if (OpVT == MVT::f16) {
  165. if (RetVT == MVT::f32)
  166. return FPEXT_F16_F32;
  167. } else if (OpVT == MVT::f32) {
  168. if (RetVT == MVT::f64)
  169. return FPEXT_F32_F64;
  170. if (RetVT == MVT::f128)
  171. return FPEXT_F32_F128;
  172. if (RetVT == MVT::ppcf128)
  173. return FPEXT_F32_PPCF128;
  174. } else if (OpVT == MVT::f64) {
  175. if (RetVT == MVT::f128)
  176. return FPEXT_F64_F128;
  177. else if (RetVT == MVT::ppcf128)
  178. return FPEXT_F64_PPCF128;
  179. } else if (OpVT == MVT::f80) {
  180. if (RetVT == MVT::f128)
  181. return FPEXT_F80_F128;
  182. }
  183. return UNKNOWN_LIBCALL;
  184. }
  185. /// getFPROUND - Return the FPROUND_*_* value for the given types, or
  186. /// UNKNOWN_LIBCALL if there is none.
  187. RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
  188. if (RetVT == MVT::f16) {
  189. if (OpVT == MVT::f32)
  190. return FPROUND_F32_F16;
  191. if (OpVT == MVT::f64)
  192. return FPROUND_F64_F16;
  193. if (OpVT == MVT::f80)
  194. return FPROUND_F80_F16;
  195. if (OpVT == MVT::f128)
  196. return FPROUND_F128_F16;
  197. if (OpVT == MVT::ppcf128)
  198. return FPROUND_PPCF128_F16;
  199. } else if (RetVT == MVT::f32) {
  200. if (OpVT == MVT::f64)
  201. return FPROUND_F64_F32;
  202. if (OpVT == MVT::f80)
  203. return FPROUND_F80_F32;
  204. if (OpVT == MVT::f128)
  205. return FPROUND_F128_F32;
  206. if (OpVT == MVT::ppcf128)
  207. return FPROUND_PPCF128_F32;
  208. } else if (RetVT == MVT::f64) {
  209. if (OpVT == MVT::f80)
  210. return FPROUND_F80_F64;
  211. if (OpVT == MVT::f128)
  212. return FPROUND_F128_F64;
  213. if (OpVT == MVT::ppcf128)
  214. return FPROUND_PPCF128_F64;
  215. } else if (RetVT == MVT::f80) {
  216. if (OpVT == MVT::f128)
  217. return FPROUND_F128_F80;
  218. }
  219. return UNKNOWN_LIBCALL;
  220. }
  221. /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
  222. /// UNKNOWN_LIBCALL if there is none.
  223. RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
  224. if (OpVT == MVT::f32) {
  225. if (RetVT == MVT::i32)
  226. return FPTOSINT_F32_I32;
  227. if (RetVT == MVT::i64)
  228. return FPTOSINT_F32_I64;
  229. if (RetVT == MVT::i128)
  230. return FPTOSINT_F32_I128;
  231. } else if (OpVT == MVT::f64) {
  232. if (RetVT == MVT::i32)
  233. return FPTOSINT_F64_I32;
  234. if (RetVT == MVT::i64)
  235. return FPTOSINT_F64_I64;
  236. if (RetVT == MVT::i128)
  237. return FPTOSINT_F64_I128;
  238. } else if (OpVT == MVT::f80) {
  239. if (RetVT == MVT::i32)
  240. return FPTOSINT_F80_I32;
  241. if (RetVT == MVT::i64)
  242. return FPTOSINT_F80_I64;
  243. if (RetVT == MVT::i128)
  244. return FPTOSINT_F80_I128;
  245. } else if (OpVT == MVT::f128) {
  246. if (RetVT == MVT::i32)
  247. return FPTOSINT_F128_I32;
  248. if (RetVT == MVT::i64)
  249. return FPTOSINT_F128_I64;
  250. if (RetVT == MVT::i128)
  251. return FPTOSINT_F128_I128;
  252. } else if (OpVT == MVT::ppcf128) {
  253. if (RetVT == MVT::i32)
  254. return FPTOSINT_PPCF128_I32;
  255. if (RetVT == MVT::i64)
  256. return FPTOSINT_PPCF128_I64;
  257. if (RetVT == MVT::i128)
  258. return FPTOSINT_PPCF128_I128;
  259. }
  260. return UNKNOWN_LIBCALL;
  261. }
  262. /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
  263. /// UNKNOWN_LIBCALL if there is none.
  264. RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
  265. if (OpVT == MVT::f32) {
  266. if (RetVT == MVT::i32)
  267. return FPTOUINT_F32_I32;
  268. if (RetVT == MVT::i64)
  269. return FPTOUINT_F32_I64;
  270. if (RetVT == MVT::i128)
  271. return FPTOUINT_F32_I128;
  272. } else if (OpVT == MVT::f64) {
  273. if (RetVT == MVT::i32)
  274. return FPTOUINT_F64_I32;
  275. if (RetVT == MVT::i64)
  276. return FPTOUINT_F64_I64;
  277. if (RetVT == MVT::i128)
  278. return FPTOUINT_F64_I128;
  279. } else if (OpVT == MVT::f80) {
  280. if (RetVT == MVT::i32)
  281. return FPTOUINT_F80_I32;
  282. if (RetVT == MVT::i64)
  283. return FPTOUINT_F80_I64;
  284. if (RetVT == MVT::i128)
  285. return FPTOUINT_F80_I128;
  286. } else if (OpVT == MVT::f128) {
  287. if (RetVT == MVT::i32)
  288. return FPTOUINT_F128_I32;
  289. if (RetVT == MVT::i64)
  290. return FPTOUINT_F128_I64;
  291. if (RetVT == MVT::i128)
  292. return FPTOUINT_F128_I128;
  293. } else if (OpVT == MVT::ppcf128) {
  294. if (RetVT == MVT::i32)
  295. return FPTOUINT_PPCF128_I32;
  296. if (RetVT == MVT::i64)
  297. return FPTOUINT_PPCF128_I64;
  298. if (RetVT == MVT::i128)
  299. return FPTOUINT_PPCF128_I128;
  300. }
  301. return UNKNOWN_LIBCALL;
  302. }
  303. /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
  304. /// UNKNOWN_LIBCALL if there is none.
  305. RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
  306. if (OpVT == MVT::i32) {
  307. if (RetVT == MVT::f32)
  308. return SINTTOFP_I32_F32;
  309. if (RetVT == MVT::f64)
  310. return SINTTOFP_I32_F64;
  311. if (RetVT == MVT::f80)
  312. return SINTTOFP_I32_F80;
  313. if (RetVT == MVT::f128)
  314. return SINTTOFP_I32_F128;
  315. if (RetVT == MVT::ppcf128)
  316. return SINTTOFP_I32_PPCF128;
  317. } else if (OpVT == MVT::i64) {
  318. if (RetVT == MVT::f32)
  319. return SINTTOFP_I64_F32;
  320. if (RetVT == MVT::f64)
  321. return SINTTOFP_I64_F64;
  322. if (RetVT == MVT::f80)
  323. return SINTTOFP_I64_F80;
  324. if (RetVT == MVT::f128)
  325. return SINTTOFP_I64_F128;
  326. if (RetVT == MVT::ppcf128)
  327. return SINTTOFP_I64_PPCF128;
  328. } else if (OpVT == MVT::i128) {
  329. if (RetVT == MVT::f32)
  330. return SINTTOFP_I128_F32;
  331. if (RetVT == MVT::f64)
  332. return SINTTOFP_I128_F64;
  333. if (RetVT == MVT::f80)
  334. return SINTTOFP_I128_F80;
  335. if (RetVT == MVT::f128)
  336. return SINTTOFP_I128_F128;
  337. if (RetVT == MVT::ppcf128)
  338. return SINTTOFP_I128_PPCF128;
  339. }
  340. return UNKNOWN_LIBCALL;
  341. }
  342. /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
  343. /// UNKNOWN_LIBCALL if there is none.
  344. RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
  345. if (OpVT == MVT::i32) {
  346. if (RetVT == MVT::f32)
  347. return UINTTOFP_I32_F32;
  348. if (RetVT == MVT::f64)
  349. return UINTTOFP_I32_F64;
  350. if (RetVT == MVT::f80)
  351. return UINTTOFP_I32_F80;
  352. if (RetVT == MVT::f128)
  353. return UINTTOFP_I32_F128;
  354. if (RetVT == MVT::ppcf128)
  355. return UINTTOFP_I32_PPCF128;
  356. } else if (OpVT == MVT::i64) {
  357. if (RetVT == MVT::f32)
  358. return UINTTOFP_I64_F32;
  359. if (RetVT == MVT::f64)
  360. return UINTTOFP_I64_F64;
  361. if (RetVT == MVT::f80)
  362. return UINTTOFP_I64_F80;
  363. if (RetVT == MVT::f128)
  364. return UINTTOFP_I64_F128;
  365. if (RetVT == MVT::ppcf128)
  366. return UINTTOFP_I64_PPCF128;
  367. } else if (OpVT == MVT::i128) {
  368. if (RetVT == MVT::f32)
  369. return UINTTOFP_I128_F32;
  370. if (RetVT == MVT::f64)
  371. return UINTTOFP_I128_F64;
  372. if (RetVT == MVT::f80)
  373. return UINTTOFP_I128_F80;
  374. if (RetVT == MVT::f128)
  375. return UINTTOFP_I128_F128;
  376. if (RetVT == MVT::ppcf128)
  377. return UINTTOFP_I128_PPCF128;
  378. }
  379. return UNKNOWN_LIBCALL;
  380. }
  381. RTLIB::Libcall RTLIB::getSYNC(unsigned Opc, MVT VT) {
  382. #define OP_TO_LIBCALL(Name, Enum) \
  383. case Name: \
  384. switch (VT.SimpleTy) { \
  385. default: \
  386. return UNKNOWN_LIBCALL; \
  387. case MVT::i8: \
  388. return Enum##_1; \
  389. case MVT::i16: \
  390. return Enum##_2; \
  391. case MVT::i32: \
  392. return Enum##_4; \
  393. case MVT::i64: \
  394. return Enum##_8; \
  395. case MVT::i128: \
  396. return Enum##_16; \
  397. }
  398. switch (Opc) {
  399. OP_TO_LIBCALL(ISD::ATOMIC_SWAP, SYNC_LOCK_TEST_AND_SET)
  400. OP_TO_LIBCALL(ISD::ATOMIC_CMP_SWAP, SYNC_VAL_COMPARE_AND_SWAP)
  401. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_ADD, SYNC_FETCH_AND_ADD)
  402. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_SUB, SYNC_FETCH_AND_SUB)
  403. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_AND, SYNC_FETCH_AND_AND)
  404. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_OR, SYNC_FETCH_AND_OR)
  405. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_XOR, SYNC_FETCH_AND_XOR)
  406. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_NAND, SYNC_FETCH_AND_NAND)
  407. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MAX, SYNC_FETCH_AND_MAX)
  408. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMAX, SYNC_FETCH_AND_UMAX)
  409. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MIN, SYNC_FETCH_AND_MIN)
  410. OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMIN, SYNC_FETCH_AND_UMIN)
  411. }
  412. #undef OP_TO_LIBCALL
  413. return UNKNOWN_LIBCALL;
  414. }
  415. RTLIB::Libcall RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
  416. switch (ElementSize) {
  417. case 1:
  418. return MEMCPY_ELEMENT_UNORDERED_ATOMIC_1;
  419. case 2:
  420. return MEMCPY_ELEMENT_UNORDERED_ATOMIC_2;
  421. case 4:
  422. return MEMCPY_ELEMENT_UNORDERED_ATOMIC_4;
  423. case 8:
  424. return MEMCPY_ELEMENT_UNORDERED_ATOMIC_8;
  425. case 16:
  426. return MEMCPY_ELEMENT_UNORDERED_ATOMIC_16;
  427. default:
  428. return UNKNOWN_LIBCALL;
  429. }
  430. }
  431. RTLIB::Libcall RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
  432. switch (ElementSize) {
  433. case 1:
  434. return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_1;
  435. case 2:
  436. return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_2;
  437. case 4:
  438. return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_4;
  439. case 8:
  440. return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_8;
  441. case 16:
  442. return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_16;
  443. default:
  444. return UNKNOWN_LIBCALL;
  445. }
  446. }
  447. RTLIB::Libcall RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
  448. switch (ElementSize) {
  449. case 1:
  450. return MEMSET_ELEMENT_UNORDERED_ATOMIC_1;
  451. case 2:
  452. return MEMSET_ELEMENT_UNORDERED_ATOMIC_2;
  453. case 4:
  454. return MEMSET_ELEMENT_UNORDERED_ATOMIC_4;
  455. case 8:
  456. return MEMSET_ELEMENT_UNORDERED_ATOMIC_8;
  457. case 16:
  458. return MEMSET_ELEMENT_UNORDERED_ATOMIC_16;
  459. default:
  460. return UNKNOWN_LIBCALL;
  461. }
  462. }
  463. /// InitCmpLibcallCCs - Set default comparison libcall CC.
  464. static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
  465. memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
  466. CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
  467. CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
  468. CCs[RTLIB::OEQ_F128] = ISD::SETEQ;
  469. CCs[RTLIB::OEQ_PPCF128] = ISD::SETEQ;
  470. CCs[RTLIB::UNE_F32] = ISD::SETNE;
  471. CCs[RTLIB::UNE_F64] = ISD::SETNE;
  472. CCs[RTLIB::UNE_F128] = ISD::SETNE;
  473. CCs[RTLIB::UNE_PPCF128] = ISD::SETNE;
  474. CCs[RTLIB::OGE_F32] = ISD::SETGE;
  475. CCs[RTLIB::OGE_F64] = ISD::SETGE;
  476. CCs[RTLIB::OGE_F128] = ISD::SETGE;
  477. CCs[RTLIB::OGE_PPCF128] = ISD::SETGE;
  478. CCs[RTLIB::OLT_F32] = ISD::SETLT;
  479. CCs[RTLIB::OLT_F64] = ISD::SETLT;
  480. CCs[RTLIB::OLT_F128] = ISD::SETLT;
  481. CCs[RTLIB::OLT_PPCF128] = ISD::SETLT;
  482. CCs[RTLIB::OLE_F32] = ISD::SETLE;
  483. CCs[RTLIB::OLE_F64] = ISD::SETLE;
  484. CCs[RTLIB::OLE_F128] = ISD::SETLE;
  485. CCs[RTLIB::OLE_PPCF128] = ISD::SETLE;
  486. CCs[RTLIB::OGT_F32] = ISD::SETGT;
  487. CCs[RTLIB::OGT_F64] = ISD::SETGT;
  488. CCs[RTLIB::OGT_F128] = ISD::SETGT;
  489. CCs[RTLIB::OGT_PPCF128] = ISD::SETGT;
  490. CCs[RTLIB::UO_F32] = ISD::SETNE;
  491. CCs[RTLIB::UO_F64] = ISD::SETNE;
  492. CCs[RTLIB::UO_F128] = ISD::SETNE;
  493. CCs[RTLIB::UO_PPCF128] = ISD::SETNE;
  494. CCs[RTLIB::O_F32] = ISD::SETEQ;
  495. CCs[RTLIB::O_F64] = ISD::SETEQ;
  496. CCs[RTLIB::O_F128] = ISD::SETEQ;
  497. CCs[RTLIB::O_PPCF128] = ISD::SETEQ;
  498. }
  499. /// NOTE: The TargetMachine owns TLOF.
  500. TargetLoweringBase::TargetLoweringBase(const TargetMachine &tm) : TM(tm) {
  501. initActions();
  502. // Perform these initializations only once.
  503. MaxStoresPerMemset = MaxStoresPerMemcpy = MaxStoresPerMemmove =
  504. MaxLoadsPerMemcmp = 8;
  505. MaxGluedStoresPerMemcpy = 0;
  506. MaxStoresPerMemsetOptSize = MaxStoresPerMemcpyOptSize =
  507. MaxStoresPerMemmoveOptSize = MaxLoadsPerMemcmpOptSize = 4;
  508. UseUnderscoreSetJmp = false;
  509. UseUnderscoreLongJmp = false;
  510. HasMultipleConditionRegisters = false;
  511. HasExtractBitsInsn = false;
  512. JumpIsExpensive = JumpIsExpensiveOverride;
  513. PredictableSelectIsExpensive = false;
  514. EnableExtLdPromotion = false;
  515. StackPointerRegisterToSaveRestore = 0;
  516. BooleanContents = UndefinedBooleanContent;
  517. BooleanFloatContents = UndefinedBooleanContent;
  518. BooleanVectorContents = UndefinedBooleanContent;
  519. SchedPreferenceInfo = Sched::ILP;
  520. JumpBufSize = 0;
  521. JumpBufAlignment = 0;
  522. MinFunctionAlignment = 0;
  523. PrefFunctionAlignment = 0;
  524. PrefLoopAlignment = 0;
  525. GatherAllAliasesMaxDepth = 18;
  526. MinStackArgumentAlignment = 1;
  527. // TODO: the default will be switched to 0 in the next commit, along
  528. // with the Target-specific changes necessary.
  529. MaxAtomicSizeInBitsSupported = 1024;
  530. MinCmpXchgSizeInBits = 0;
  531. SupportsUnalignedAtomics = false;
  532. std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr);
  533. InitLibcalls(TM.getTargetTriple());
  534. InitCmpLibcallCCs(CmpLibcallCCs);
  535. }
  536. void TargetLoweringBase::initActions() {
  537. // All operations default to being supported.
  538. memset(OpActions, 0, sizeof(OpActions));
  539. memset(LoadExtActions, 0, sizeof(LoadExtActions));
  540. memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
  541. memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
  542. memset(CondCodeActions, 0, sizeof(CondCodeActions));
  543. std::fill(std::begin(RegClassForVT), std::end(RegClassForVT), nullptr);
  544. std::fill(std::begin(TargetDAGCombineArray),
  545. std::end(TargetDAGCombineArray), 0);
  546. for (MVT VT : MVT::fp_valuetypes()) {
  547. MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
  548. if (IntVT.isValid()) {
  549. setOperationAction(ISD::ATOMIC_SWAP, VT, Promote);
  550. AddPromotedToType(ISD::ATOMIC_SWAP, VT, IntVT);
  551. }
  552. }
  553. // Set default actions for various operations.
  554. for (MVT VT : MVT::all_valuetypes()) {
  555. // Default all indexed load / store to expand.
  556. for (unsigned IM = (unsigned)ISD::PRE_INC;
  557. IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
  558. setIndexedLoadAction(IM, VT, Expand);
  559. setIndexedStoreAction(IM, VT, Expand);
  560. }
  561. // Most backends expect to see the node which just returns the value loaded.
  562. setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand);
  563. // These operations default to expand.
  564. setOperationAction(ISD::FGETSIGN, VT, Expand);
  565. setOperationAction(ISD::CONCAT_VECTORS, VT, Expand);
  566. setOperationAction(ISD::FMINNUM, VT, Expand);
  567. setOperationAction(ISD::FMAXNUM, VT, Expand);
  568. setOperationAction(ISD::FMINNUM_IEEE, VT, Expand);
  569. setOperationAction(ISD::FMAXNUM_IEEE, VT, Expand);
  570. setOperationAction(ISD::FMINIMUM, VT, Expand);
  571. setOperationAction(ISD::FMAXIMUM, VT, Expand);
  572. setOperationAction(ISD::FMAD, VT, Expand);
  573. setOperationAction(ISD::SMIN, VT, Expand);
  574. setOperationAction(ISD::SMAX, VT, Expand);
  575. setOperationAction(ISD::UMIN, VT, Expand);
  576. setOperationAction(ISD::UMAX, VT, Expand);
  577. setOperationAction(ISD::ABS, VT, Expand);
  578. setOperationAction(ISD::FSHL, VT, Expand);
  579. setOperationAction(ISD::FSHR, VT, Expand);
  580. setOperationAction(ISD::SADDSAT, VT, Expand);
  581. setOperationAction(ISD::UADDSAT, VT, Expand);
  582. setOperationAction(ISD::SSUBSAT, VT, Expand);
  583. setOperationAction(ISD::USUBSAT, VT, Expand);
  584. setOperationAction(ISD::SMULFIX, VT, Expand);
  585. setOperationAction(ISD::SMULFIXSAT, VT, Expand);
  586. setOperationAction(ISD::UMULFIX, VT, Expand);
  587. // Overflow operations default to expand
  588. setOperationAction(ISD::SADDO, VT, Expand);
  589. setOperationAction(ISD::SSUBO, VT, Expand);
  590. setOperationAction(ISD::UADDO, VT, Expand);
  591. setOperationAction(ISD::USUBO, VT, Expand);
  592. setOperationAction(ISD::SMULO, VT, Expand);
  593. setOperationAction(ISD::UMULO, VT, Expand);
  594. // ADDCARRY operations default to expand
  595. setOperationAction(ISD::ADDCARRY, VT, Expand);
  596. setOperationAction(ISD::SUBCARRY, VT, Expand);
  597. setOperationAction(ISD::SETCCCARRY, VT, Expand);
  598. // ADDC/ADDE/SUBC/SUBE default to expand.
  599. setOperationAction(ISD::ADDC, VT, Expand);
  600. setOperationAction(ISD::ADDE, VT, Expand);
  601. setOperationAction(ISD::SUBC, VT, Expand);
  602. setOperationAction(ISD::SUBE, VT, Expand);
  603. // These default to Expand so they will be expanded to CTLZ/CTTZ by default.
  604. setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
  605. setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
  606. setOperationAction(ISD::BITREVERSE, VT, Expand);
  607. // These library functions default to expand.
  608. setOperationAction(ISD::FROUND, VT, Expand);
  609. setOperationAction(ISD::FPOWI, VT, Expand);
  610. // These operations default to expand for vector types.
  611. if (VT.isVector()) {
  612. setOperationAction(ISD::FCOPYSIGN, VT, Expand);
  613. setOperationAction(ISD::ANY_EXTEND_VECTOR_INREG, VT, Expand);
  614. setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Expand);
  615. setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Expand);
  616. }
  617. // For most targets @llvm.get.dynamic.area.offset just returns 0.
  618. setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand);
  619. // Vector reduction default to expand.
  620. setOperationAction(ISD::VECREDUCE_FADD, VT, Expand);
  621. setOperationAction(ISD::VECREDUCE_FMUL, VT, Expand);
  622. setOperationAction(ISD::VECREDUCE_ADD, VT, Expand);
  623. setOperationAction(ISD::VECREDUCE_MUL, VT, Expand);
  624. setOperationAction(ISD::VECREDUCE_AND, VT, Expand);
  625. setOperationAction(ISD::VECREDUCE_OR, VT, Expand);
  626. setOperationAction(ISD::VECREDUCE_XOR, VT, Expand);
  627. setOperationAction(ISD::VECREDUCE_SMAX, VT, Expand);
  628. setOperationAction(ISD::VECREDUCE_SMIN, VT, Expand);
  629. setOperationAction(ISD::VECREDUCE_UMAX, VT, Expand);
  630. setOperationAction(ISD::VECREDUCE_UMIN, VT, Expand);
  631. setOperationAction(ISD::VECREDUCE_FMAX, VT, Expand);
  632. setOperationAction(ISD::VECREDUCE_FMIN, VT, Expand);
  633. }
  634. // Most targets ignore the @llvm.prefetch intrinsic.
  635. setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
  636. // Most targets also ignore the @llvm.readcyclecounter intrinsic.
  637. setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
  638. // ConstantFP nodes default to expand. Targets can either change this to
  639. // Legal, in which case all fp constants are legal, or use isFPImmLegal()
  640. // to optimize expansions for certain constants.
  641. setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
  642. setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
  643. setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
  644. setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
  645. setOperationAction(ISD::ConstantFP, MVT::f128, Expand);
  646. // These library functions default to expand.
  647. for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
  648. setOperationAction(ISD::FCBRT, VT, Expand);
  649. setOperationAction(ISD::FLOG , VT, Expand);
  650. setOperationAction(ISD::FLOG2, VT, Expand);
  651. setOperationAction(ISD::FLOG10, VT, Expand);
  652. setOperationAction(ISD::FEXP , VT, Expand);
  653. setOperationAction(ISD::FEXP2, VT, Expand);
  654. setOperationAction(ISD::FFLOOR, VT, Expand);
  655. setOperationAction(ISD::FNEARBYINT, VT, Expand);
  656. setOperationAction(ISD::FCEIL, VT, Expand);
  657. setOperationAction(ISD::FRINT, VT, Expand);
  658. setOperationAction(ISD::FTRUNC, VT, Expand);
  659. setOperationAction(ISD::FROUND, VT, Expand);
  660. setOperationAction(ISD::LROUND, VT, Expand);
  661. setOperationAction(ISD::LLROUND, VT, Expand);
  662. }
  663. // Default ISD::TRAP to expand (which turns it into abort).
  664. setOperationAction(ISD::TRAP, MVT::Other, Expand);
  665. // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
  666. // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
  667. setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
  668. }
  669. MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
  670. EVT) const {
  671. return MVT::getIntegerVT(DL.getPointerSizeInBits(0));
  672. }
  673. EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
  674. bool LegalTypes) const {
  675. assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
  676. if (LHSTy.isVector())
  677. return LHSTy;
  678. return LegalTypes ? getScalarShiftAmountTy(DL, LHSTy)
  679. : getPointerTy(DL);
  680. }
  681. bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
  682. assert(isTypeLegal(VT));
  683. switch (Op) {
  684. default:
  685. return false;
  686. case ISD::SDIV:
  687. case ISD::UDIV:
  688. case ISD::SREM:
  689. case ISD::UREM:
  690. return true;
  691. }
  692. }
  693. void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
  694. // If the command-line option was specified, ignore this request.
  695. if (!JumpIsExpensiveOverride.getNumOccurrences())
  696. JumpIsExpensive = isExpensive;
  697. }
  698. TargetLoweringBase::LegalizeKind
  699. TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
  700. // If this is a simple type, use the ComputeRegisterProp mechanism.
  701. if (VT.isSimple()) {
  702. MVT SVT = VT.getSimpleVT();
  703. assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
  704. MVT NVT = TransformToType[SVT.SimpleTy];
  705. LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
  706. assert((LA == TypeLegal || LA == TypeSoftenFloat ||
  707. ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger) &&
  708. "Promote may not follow Expand or Promote");
  709. if (LA == TypeSplitVector)
  710. return LegalizeKind(LA,
  711. EVT::getVectorVT(Context, SVT.getVectorElementType(),
  712. SVT.getVectorNumElements() / 2));
  713. if (LA == TypeScalarizeVector)
  714. return LegalizeKind(LA, SVT.getVectorElementType());
  715. return LegalizeKind(LA, NVT);
  716. }
  717. // Handle Extended Scalar Types.
  718. if (!VT.isVector()) {
  719. assert(VT.isInteger() && "Float types must be simple");
  720. unsigned BitSize = VT.getSizeInBits();
  721. // First promote to a power-of-two size, then expand if necessary.
  722. if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
  723. EVT NVT = VT.getRoundIntegerType(Context);
  724. assert(NVT != VT && "Unable to round integer VT");
  725. LegalizeKind NextStep = getTypeConversion(Context, NVT);
  726. // Avoid multi-step promotion.
  727. if (NextStep.first == TypePromoteInteger)
  728. return NextStep;
  729. // Return rounded integer type.
  730. return LegalizeKind(TypePromoteInteger, NVT);
  731. }
  732. return LegalizeKind(TypeExpandInteger,
  733. EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
  734. }
  735. // Handle vector types.
  736. unsigned NumElts = VT.getVectorNumElements();
  737. EVT EltVT = VT.getVectorElementType();
  738. // Vectors with only one element are always scalarized.
  739. if (NumElts == 1)
  740. return LegalizeKind(TypeScalarizeVector, EltVT);
  741. // Try to widen vector elements until the element type is a power of two and
  742. // promote it to a legal type later on, for example:
  743. // <3 x i8> -> <4 x i8> -> <4 x i32>
  744. if (EltVT.isInteger()) {
  745. // Vectors with a number of elements that is not a power of two are always
  746. // widened, for example <3 x i8> -> <4 x i8>.
  747. if (!VT.isPow2VectorType()) {
  748. NumElts = (unsigned)NextPowerOf2(NumElts);
  749. EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
  750. return LegalizeKind(TypeWidenVector, NVT);
  751. }
  752. // Examine the element type.
  753. LegalizeKind LK = getTypeConversion(Context, EltVT);
  754. // If type is to be expanded, split the vector.
  755. // <4 x i140> -> <2 x i140>
  756. if (LK.first == TypeExpandInteger)
  757. return LegalizeKind(TypeSplitVector,
  758. EVT::getVectorVT(Context, EltVT, NumElts / 2));
  759. // Promote the integer element types until a legal vector type is found
  760. // or until the element integer type is too big. If a legal type was not
  761. // found, fallback to the usual mechanism of widening/splitting the
  762. // vector.
  763. EVT OldEltVT = EltVT;
  764. while (true) {
  765. // Increase the bitwidth of the element to the next pow-of-two
  766. // (which is greater than 8 bits).
  767. EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
  768. .getRoundIntegerType(Context);
  769. // Stop trying when getting a non-simple element type.
  770. // Note that vector elements may be greater than legal vector element
  771. // types. Example: X86 XMM registers hold 64bit element on 32bit
  772. // systems.
  773. if (!EltVT.isSimple())
  774. break;
  775. // Build a new vector type and check if it is legal.
  776. MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
  777. // Found a legal promoted vector type.
  778. if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
  779. return LegalizeKind(TypePromoteInteger,
  780. EVT::getVectorVT(Context, EltVT, NumElts));
  781. }
  782. // Reset the type to the unexpanded type if we did not find a legal vector
  783. // type with a promoted vector element type.
  784. EltVT = OldEltVT;
  785. }
  786. // Try to widen the vector until a legal type is found.
  787. // If there is no wider legal type, split the vector.
  788. while (true) {
  789. // Round up to the next power of 2.
  790. NumElts = (unsigned)NextPowerOf2(NumElts);
  791. // If there is no simple vector type with this many elements then there
  792. // cannot be a larger legal vector type. Note that this assumes that
  793. // there are no skipped intermediate vector types in the simple types.
  794. if (!EltVT.isSimple())
  795. break;
  796. MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
  797. if (LargerVector == MVT())
  798. break;
  799. // If this type is legal then widen the vector.
  800. if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
  801. return LegalizeKind(TypeWidenVector, LargerVector);
  802. }
  803. // Widen odd vectors to next power of two.
  804. if (!VT.isPow2VectorType()) {
  805. EVT NVT = VT.getPow2VectorType(Context);
  806. return LegalizeKind(TypeWidenVector, NVT);
  807. }
  808. // Vectors with illegal element types are expanded.
  809. EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
  810. return LegalizeKind(TypeSplitVector, NVT);
  811. }
  812. static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
  813. unsigned &NumIntermediates,
  814. MVT &RegisterVT,
  815. TargetLoweringBase *TLI) {
  816. // Figure out the right, legal destination reg to copy into.
  817. unsigned NumElts = VT.getVectorNumElements();
  818. MVT EltTy = VT.getVectorElementType();
  819. unsigned NumVectorRegs = 1;
  820. // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
  821. // could break down into LHS/RHS like LegalizeDAG does.
  822. if (!isPowerOf2_32(NumElts)) {
  823. NumVectorRegs = NumElts;
  824. NumElts = 1;
  825. }
  826. // Divide the input until we get to a supported size. This will always
  827. // end with a scalar if the target doesn't support vectors.
  828. while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
  829. NumElts >>= 1;
  830. NumVectorRegs <<= 1;
  831. }
  832. NumIntermediates = NumVectorRegs;
  833. MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
  834. if (!TLI->isTypeLegal(NewVT))
  835. NewVT = EltTy;
  836. IntermediateVT = NewVT;
  837. unsigned NewVTSize = NewVT.getSizeInBits();
  838. // Convert sizes such as i33 to i64.
  839. if (!isPowerOf2_32(NewVTSize))
  840. NewVTSize = NextPowerOf2(NewVTSize);
  841. MVT DestVT = TLI->getRegisterType(NewVT);
  842. RegisterVT = DestVT;
  843. if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
  844. return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
  845. // Otherwise, promotion or legal types use the same number of registers as
  846. // the vector decimated to the appropriate level.
  847. return NumVectorRegs;
  848. }
  849. /// isLegalRC - Return true if the value types that can be represented by the
  850. /// specified register class are all legal.
  851. bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
  852. const TargetRegisterClass &RC) const {
  853. for (auto I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
  854. if (isTypeLegal(*I))
  855. return true;
  856. return false;
  857. }
  858. /// Replace/modify any TargetFrameIndex operands with a targte-dependent
  859. /// sequence of memory operands that is recognized by PrologEpilogInserter.
  860. MachineBasicBlock *
  861. TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
  862. MachineBasicBlock *MBB) const {
  863. MachineInstr *MI = &InitialMI;
  864. MachineFunction &MF = *MI->getMF();
  865. MachineFrameInfo &MFI = MF.getFrameInfo();
  866. // We're handling multiple types of operands here:
  867. // PATCHPOINT MetaArgs - live-in, read only, direct
  868. // STATEPOINT Deopt Spill - live-through, read only, indirect
  869. // STATEPOINT Deopt Alloca - live-through, read only, direct
  870. // (We're currently conservative and mark the deopt slots read/write in
  871. // practice.)
  872. // STATEPOINT GC Spill - live-through, read/write, indirect
  873. // STATEPOINT GC Alloca - live-through, read/write, direct
  874. // The live-in vs live-through is handled already (the live through ones are
  875. // all stack slots), but we need to handle the different type of stackmap
  876. // operands and memory effects here.
  877. // MI changes inside this loop as we grow operands.
  878. for(unsigned OperIdx = 0; OperIdx != MI->getNumOperands(); ++OperIdx) {
  879. MachineOperand &MO = MI->getOperand(OperIdx);
  880. if (!MO.isFI())
  881. continue;
  882. // foldMemoryOperand builds a new MI after replacing a single FI operand
  883. // with the canonical set of five x86 addressing-mode operands.
  884. int FI = MO.getIndex();
  885. MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
  886. // Copy operands before the frame-index.
  887. for (unsigned i = 0; i < OperIdx; ++i)
  888. MIB.add(MI->getOperand(i));
  889. // Add frame index operands recognized by stackmaps.cpp
  890. if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
  891. // indirect-mem-ref tag, size, #FI, offset.
  892. // Used for spills inserted by StatepointLowering. This codepath is not
  893. // used for patchpoints/stackmaps at all, for these spilling is done via
  894. // foldMemoryOperand callback only.
  895. assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
  896. MIB.addImm(StackMaps::IndirectMemRefOp);
  897. MIB.addImm(MFI.getObjectSize(FI));
  898. MIB.add(MI->getOperand(OperIdx));
  899. MIB.addImm(0);
  900. } else {
  901. // direct-mem-ref tag, #FI, offset.
  902. // Used by patchpoint, and direct alloca arguments to statepoints
  903. MIB.addImm(StackMaps::DirectMemRefOp);
  904. MIB.add(MI->getOperand(OperIdx));
  905. MIB.addImm(0);
  906. }
  907. // Copy the operands after the frame index.
  908. for (unsigned i = OperIdx + 1; i != MI->getNumOperands(); ++i)
  909. MIB.add(MI->getOperand(i));
  910. // Inherit previous memory operands.
  911. MIB.cloneMemRefs(*MI);
  912. assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
  913. // Add a new memory operand for this FI.
  914. assert(MFI.getObjectOffset(FI) != -1);
  915. // Note: STATEPOINT MMOs are added during SelectionDAG. STACKMAP, and
  916. // PATCHPOINT should be updated to do the same. (TODO)
  917. if (MI->getOpcode() != TargetOpcode::STATEPOINT) {
  918. auto Flags = MachineMemOperand::MOLoad;
  919. MachineMemOperand *MMO = MF.getMachineMemOperand(
  920. MachinePointerInfo::getFixedStack(MF, FI), Flags,
  921. MF.getDataLayout().getPointerSize(), MFI.getObjectAlignment(FI));
  922. MIB->addMemOperand(MF, MMO);
  923. }
  924. // Replace the instruction and update the operand index.
  925. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  926. OperIdx += (MIB->getNumOperands() - MI->getNumOperands()) - 1;
  927. MI->eraseFromParent();
  928. MI = MIB;
  929. }
  930. return MBB;
  931. }
  932. MachineBasicBlock *
  933. TargetLoweringBase::emitXRayCustomEvent(MachineInstr &MI,
  934. MachineBasicBlock *MBB) const {
  935. assert(MI.getOpcode() == TargetOpcode::PATCHABLE_EVENT_CALL &&
  936. "Called emitXRayCustomEvent on the wrong MI!");
  937. auto &MF = *MI.getMF();
  938. auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
  939. for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
  940. MIB.add(MI.getOperand(OpIdx));
  941. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  942. MI.eraseFromParent();
  943. return MBB;
  944. }
  945. MachineBasicBlock *
  946. TargetLoweringBase::emitXRayTypedEvent(MachineInstr &MI,
  947. MachineBasicBlock *MBB) const {
  948. assert(MI.getOpcode() == TargetOpcode::PATCHABLE_TYPED_EVENT_CALL &&
  949. "Called emitXRayTypedEvent on the wrong MI!");
  950. auto &MF = *MI.getMF();
  951. auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
  952. for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
  953. MIB.add(MI.getOperand(OpIdx));
  954. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  955. MI.eraseFromParent();
  956. return MBB;
  957. }
  958. /// findRepresentativeClass - Return the largest legal super-reg register class
  959. /// of the register class for the specified type and its associated "cost".
  960. // This function is in TargetLowering because it uses RegClassForVT which would
  961. // need to be moved to TargetRegisterInfo and would necessitate moving
  962. // isTypeLegal over as well - a massive change that would just require
  963. // TargetLowering having a TargetRegisterInfo class member that it would use.
  964. std::pair<const TargetRegisterClass *, uint8_t>
  965. TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
  966. MVT VT) const {
  967. const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
  968. if (!RC)
  969. return std::make_pair(RC, 0);
  970. // Compute the set of all super-register classes.
  971. BitVector SuperRegRC(TRI->getNumRegClasses());
  972. for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
  973. SuperRegRC.setBitsInMask(RCI.getMask());
  974. // Find the first legal register class with the largest spill size.
  975. const TargetRegisterClass *BestRC = RC;
  976. for (unsigned i : SuperRegRC.set_bits()) {
  977. const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
  978. // We want the largest possible spill size.
  979. if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC))
  980. continue;
  981. if (!isLegalRC(*TRI, *SuperRC))
  982. continue;
  983. BestRC = SuperRC;
  984. }
  985. return std::make_pair(BestRC, 1);
  986. }
  987. /// computeRegisterProperties - Once all of the register classes are added,
  988. /// this allows us to compute derived properties we expose.
  989. void TargetLoweringBase::computeRegisterProperties(
  990. const TargetRegisterInfo *TRI) {
  991. static_assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE,
  992. "Too many value types for ValueTypeActions to hold!");
  993. // Everything defaults to needing one register.
  994. for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
  995. NumRegistersForVT[i] = 1;
  996. RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
  997. }
  998. // ...except isVoid, which doesn't need any registers.
  999. NumRegistersForVT[MVT::isVoid] = 0;
  1000. // Find the largest integer register class.
  1001. unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
  1002. for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
  1003. assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
  1004. // Every integer value type larger than this largest register takes twice as
  1005. // many registers to represent as the previous ValueType.
  1006. for (unsigned ExpandedReg = LargestIntReg + 1;
  1007. ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
  1008. NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
  1009. RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
  1010. TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
  1011. ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
  1012. TypeExpandInteger);
  1013. }
  1014. // Inspect all of the ValueType's smaller than the largest integer
  1015. // register to see which ones need promotion.
  1016. unsigned LegalIntReg = LargestIntReg;
  1017. for (unsigned IntReg = LargestIntReg - 1;
  1018. IntReg >= (unsigned)MVT::i1; --IntReg) {
  1019. MVT IVT = (MVT::SimpleValueType)IntReg;
  1020. if (isTypeLegal(IVT)) {
  1021. LegalIntReg = IntReg;
  1022. } else {
  1023. RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
  1024. (MVT::SimpleValueType)LegalIntReg;
  1025. ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
  1026. }
  1027. }
  1028. // ppcf128 type is really two f64's.
  1029. if (!isTypeLegal(MVT::ppcf128)) {
  1030. if (isTypeLegal(MVT::f64)) {
  1031. NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
  1032. RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
  1033. TransformToType[MVT::ppcf128] = MVT::f64;
  1034. ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
  1035. } else {
  1036. NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
  1037. RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
  1038. TransformToType[MVT::ppcf128] = MVT::i128;
  1039. ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
  1040. }
  1041. }
  1042. // Decide how to handle f128. If the target does not have native f128 support,
  1043. // expand it to i128 and we will be generating soft float library calls.
  1044. if (!isTypeLegal(MVT::f128)) {
  1045. NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
  1046. RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
  1047. TransformToType[MVT::f128] = MVT::i128;
  1048. ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
  1049. }
  1050. // Decide how to handle f64. If the target does not have native f64 support,
  1051. // expand it to i64 and we will be generating soft float library calls.
  1052. if (!isTypeLegal(MVT::f64)) {
  1053. NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
  1054. RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
  1055. TransformToType[MVT::f64] = MVT::i64;
  1056. ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
  1057. }
  1058. // Decide how to handle f32. If the target does not have native f32 support,
  1059. // expand it to i32 and we will be generating soft float library calls.
  1060. if (!isTypeLegal(MVT::f32)) {
  1061. NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
  1062. RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
  1063. TransformToType[MVT::f32] = MVT::i32;
  1064. ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
  1065. }
  1066. // Decide how to handle f16. If the target does not have native f16 support,
  1067. // promote it to f32, because there are no f16 library calls (except for
  1068. // conversions).
  1069. if (!isTypeLegal(MVT::f16)) {
  1070. NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
  1071. RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
  1072. TransformToType[MVT::f16] = MVT::f32;
  1073. ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
  1074. }
  1075. // Loop over all of the vector value types to see which need transformations.
  1076. for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
  1077. i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
  1078. MVT VT = (MVT::SimpleValueType) i;
  1079. if (isTypeLegal(VT))
  1080. continue;
  1081. MVT EltVT = VT.getVectorElementType();
  1082. unsigned NElts = VT.getVectorNumElements();
  1083. bool IsLegalWiderType = false;
  1084. LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
  1085. switch (PreferredAction) {
  1086. case TypePromoteInteger:
  1087. // Try to promote the elements of integer vectors. If no legal
  1088. // promotion was found, fall through to the widen-vector method.
  1089. for (unsigned nVT = i + 1; nVT <= MVT::LAST_INTEGER_VECTOR_VALUETYPE; ++nVT) {
  1090. MVT SVT = (MVT::SimpleValueType) nVT;
  1091. // Promote vectors of integers to vectors with the same number
  1092. // of elements, with a wider element type.
  1093. if (SVT.getScalarSizeInBits() > EltVT.getSizeInBits() &&
  1094. SVT.getVectorNumElements() == NElts && isTypeLegal(SVT)) {
  1095. TransformToType[i] = SVT;
  1096. RegisterTypeForVT[i] = SVT;
  1097. NumRegistersForVT[i] = 1;
  1098. ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
  1099. IsLegalWiderType = true;
  1100. break;
  1101. }
  1102. }
  1103. if (IsLegalWiderType)
  1104. break;
  1105. LLVM_FALLTHROUGH;
  1106. case TypeWidenVector:
  1107. // Try to widen the vector.
  1108. for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
  1109. MVT SVT = (MVT::SimpleValueType) nVT;
  1110. if (SVT.getVectorElementType() == EltVT
  1111. && SVT.getVectorNumElements() > NElts && isTypeLegal(SVT)) {
  1112. TransformToType[i] = SVT;
  1113. RegisterTypeForVT[i] = SVT;
  1114. NumRegistersForVT[i] = 1;
  1115. ValueTypeActions.setTypeAction(VT, TypeWidenVector);
  1116. IsLegalWiderType = true;
  1117. break;
  1118. }
  1119. }
  1120. if (IsLegalWiderType)
  1121. break;
  1122. LLVM_FALLTHROUGH;
  1123. case TypeSplitVector:
  1124. case TypeScalarizeVector: {
  1125. MVT IntermediateVT;
  1126. MVT RegisterVT;
  1127. unsigned NumIntermediates;
  1128. NumRegistersForVT[i] = getVectorTypeBreakdownMVT(VT, IntermediateVT,
  1129. NumIntermediates, RegisterVT, this);
  1130. RegisterTypeForVT[i] = RegisterVT;
  1131. MVT NVT = VT.getPow2VectorType();
  1132. if (NVT == VT) {
  1133. // Type is already a power of 2. The default action is to split.
  1134. TransformToType[i] = MVT::Other;
  1135. if (PreferredAction == TypeScalarizeVector)
  1136. ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
  1137. else if (PreferredAction == TypeSplitVector)
  1138. ValueTypeActions.setTypeAction(VT, TypeSplitVector);
  1139. else
  1140. // Set type action according to the number of elements.
  1141. ValueTypeActions.setTypeAction(VT, NElts == 1 ? TypeScalarizeVector
  1142. : TypeSplitVector);
  1143. } else {
  1144. TransformToType[i] = NVT;
  1145. ValueTypeActions.setTypeAction(VT, TypeWidenVector);
  1146. }
  1147. break;
  1148. }
  1149. default:
  1150. llvm_unreachable("Unknown vector legalization action!");
  1151. }
  1152. }
  1153. // Determine the 'representative' register class for each value type.
  1154. // An representative register class is the largest (meaning one which is
  1155. // not a sub-register class / subreg register class) legal register class for
  1156. // a group of value types. For example, on i386, i8, i16, and i32
  1157. // representative would be GR32; while on x86_64 it's GR64.
  1158. for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
  1159. const TargetRegisterClass* RRC;
  1160. uint8_t Cost;
  1161. std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
  1162. RepRegClassForVT[i] = RRC;
  1163. RepRegClassCostForVT[i] = Cost;
  1164. }
  1165. }
  1166. EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
  1167. EVT VT) const {
  1168. assert(!VT.isVector() && "No default SetCC type for vectors!");
  1169. return getPointerTy(DL).SimpleTy;
  1170. }
  1171. MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
  1172. return MVT::i32; // return the default value
  1173. }
  1174. /// getVectorTypeBreakdown - Vector types are broken down into some number of
  1175. /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
  1176. /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
  1177. /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
  1178. ///
  1179. /// This method returns the number of registers needed, and the VT for each
  1180. /// register. It also returns the VT and quantity of the intermediate values
  1181. /// before they are promoted/expanded.
  1182. unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
  1183. EVT &IntermediateVT,
  1184. unsigned &NumIntermediates,
  1185. MVT &RegisterVT) const {
  1186. unsigned NumElts = VT.getVectorNumElements();
  1187. // If there is a wider vector type with the same element type as this one,
  1188. // or a promoted vector type that has the same number of elements which
  1189. // are wider, then we should convert to that legal vector type.
  1190. // This handles things like <2 x float> -> <4 x float> and
  1191. // <4 x i1> -> <4 x i32>.
  1192. LegalizeTypeAction TA = getTypeAction(Context, VT);
  1193. if (NumElts != 1 && (TA == TypeWidenVector || TA == TypePromoteInteger)) {
  1194. EVT RegisterEVT = getTypeToTransformTo(Context, VT);
  1195. if (isTypeLegal(RegisterEVT)) {
  1196. IntermediateVT = RegisterEVT;
  1197. RegisterVT = RegisterEVT.getSimpleVT();
  1198. NumIntermediates = 1;
  1199. return 1;
  1200. }
  1201. }
  1202. // Figure out the right, legal destination reg to copy into.
  1203. EVT EltTy = VT.getVectorElementType();
  1204. unsigned NumVectorRegs = 1;
  1205. // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
  1206. // could break down into LHS/RHS like LegalizeDAG does.
  1207. if (!isPowerOf2_32(NumElts)) {
  1208. NumVectorRegs = NumElts;
  1209. NumElts = 1;
  1210. }
  1211. // Divide the input until we get to a supported size. This will always
  1212. // end with a scalar if the target doesn't support vectors.
  1213. while (NumElts > 1 && !isTypeLegal(
  1214. EVT::getVectorVT(Context, EltTy, NumElts))) {
  1215. NumElts >>= 1;
  1216. NumVectorRegs <<= 1;
  1217. }
  1218. NumIntermediates = NumVectorRegs;
  1219. EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
  1220. if (!isTypeLegal(NewVT))
  1221. NewVT = EltTy;
  1222. IntermediateVT = NewVT;
  1223. MVT DestVT = getRegisterType(Context, NewVT);
  1224. RegisterVT = DestVT;
  1225. unsigned NewVTSize = NewVT.getSizeInBits();
  1226. // Convert sizes such as i33 to i64.
  1227. if (!isPowerOf2_32(NewVTSize))
  1228. NewVTSize = NextPowerOf2(NewVTSize);
  1229. if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
  1230. return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
  1231. // Otherwise, promotion or legal types use the same number of registers as
  1232. // the vector decimated to the appropriate level.
  1233. return NumVectorRegs;
  1234. }
  1235. /// Get the EVTs and ArgFlags collections that represent the legalized return
  1236. /// type of the given function. This does not require a DAG or a return value,
  1237. /// and is suitable for use before any DAGs for the function are constructed.
  1238. /// TODO: Move this out of TargetLowering.cpp.
  1239. void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
  1240. AttributeList attr,
  1241. SmallVectorImpl<ISD::OutputArg> &Outs,
  1242. const TargetLowering &TLI, const DataLayout &DL) {
  1243. SmallVector<EVT, 4> ValueVTs;
  1244. ComputeValueVTs(TLI, DL, ReturnType, ValueVTs);
  1245. unsigned NumValues = ValueVTs.size();
  1246. if (NumValues == 0) return;
  1247. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  1248. EVT VT = ValueVTs[j];
  1249. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1250. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
  1251. ExtendKind = ISD::SIGN_EXTEND;
  1252. else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
  1253. ExtendKind = ISD::ZERO_EXTEND;
  1254. // FIXME: C calling convention requires the return type to be promoted to
  1255. // at least 32-bit. But this is not necessary for non-C calling
  1256. // conventions. The frontend should mark functions whose return values
  1257. // require promoting with signext or zeroext attributes.
  1258. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
  1259. MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
  1260. if (VT.bitsLT(MinVT))
  1261. VT = MinVT;
  1262. }
  1263. unsigned NumParts =
  1264. TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT);
  1265. MVT PartVT =
  1266. TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT);
  1267. // 'inreg' on function refers to return value
  1268. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1269. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::InReg))
  1270. Flags.setInReg();
  1271. // Propagate extension type if any
  1272. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
  1273. Flags.setSExt();
  1274. else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
  1275. Flags.setZExt();
  1276. for (unsigned i = 0; i < NumParts; ++i)
  1277. Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isFixed=*/true, 0, 0));
  1278. }
  1279. }
  1280. /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
  1281. /// function arguments in the caller parameter area. This is the actual
  1282. /// alignment, not its logarithm.
  1283. unsigned TargetLoweringBase::getByValTypeAlignment(Type *Ty,
  1284. const DataLayout &DL) const {
  1285. return DL.getABITypeAlignment(Ty);
  1286. }
  1287. bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
  1288. const DataLayout &DL, EVT VT,
  1289. unsigned AddrSpace,
  1290. unsigned Alignment,
  1291. bool *Fast) const {
  1292. // Check if the specified alignment is sufficient based on the data layout.
  1293. // TODO: While using the data layout works in practice, a better solution
  1294. // would be to implement this check directly (make this a virtual function).
  1295. // For example, the ABI alignment may change based on software platform while
  1296. // this function should only be affected by hardware implementation.
  1297. Type *Ty = VT.getTypeForEVT(Context);
  1298. if (Alignment >= DL.getABITypeAlignment(Ty)) {
  1299. // Assume that an access that meets the ABI-specified alignment is fast.
  1300. if (Fast != nullptr)
  1301. *Fast = true;
  1302. return true;
  1303. }
  1304. // This is a misaligned access.
  1305. return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Fast);
  1306. }
  1307. BranchProbability TargetLoweringBase::getPredictableBranchThreshold() const {
  1308. return BranchProbability(MinPercentageForPredictableBranch, 100);
  1309. }
  1310. //===----------------------------------------------------------------------===//
  1311. // TargetTransformInfo Helpers
  1312. //===----------------------------------------------------------------------===//
  1313. int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
  1314. enum InstructionOpcodes {
  1315. #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
  1316. #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
  1317. #include "llvm/IR/Instruction.def"
  1318. };
  1319. switch (static_cast<InstructionOpcodes>(Opcode)) {
  1320. case Ret: return 0;
  1321. case Br: return 0;
  1322. case Switch: return 0;
  1323. case IndirectBr: return 0;
  1324. case Invoke: return 0;
  1325. case CallBr: return 0;
  1326. case Resume: return 0;
  1327. case Unreachable: return 0;
  1328. case CleanupRet: return 0;
  1329. case CatchRet: return 0;
  1330. case CatchPad: return 0;
  1331. case CatchSwitch: return 0;
  1332. case CleanupPad: return 0;
  1333. case FNeg: return ISD::FNEG;
  1334. case Add: return ISD::ADD;
  1335. case FAdd: return ISD::FADD;
  1336. case Sub: return ISD::SUB;
  1337. case FSub: return ISD::FSUB;
  1338. case Mul: return ISD::MUL;
  1339. case FMul: return ISD::FMUL;
  1340. case UDiv: return ISD::UDIV;
  1341. case SDiv: return ISD::SDIV;
  1342. case FDiv: return ISD::FDIV;
  1343. case URem: return ISD::UREM;
  1344. case SRem: return ISD::SREM;
  1345. case FRem: return ISD::FREM;
  1346. case Shl: return ISD::SHL;
  1347. case LShr: return ISD::SRL;
  1348. case AShr: return ISD::SRA;
  1349. case And: return ISD::AND;
  1350. case Or: return ISD::OR;
  1351. case Xor: return ISD::XOR;
  1352. case Alloca: return 0;
  1353. case Load: return ISD::LOAD;
  1354. case Store: return ISD::STORE;
  1355. case GetElementPtr: return 0;
  1356. case Fence: return 0;
  1357. case AtomicCmpXchg: return 0;
  1358. case AtomicRMW: return 0;
  1359. case Trunc: return ISD::TRUNCATE;
  1360. case ZExt: return ISD::ZERO_EXTEND;
  1361. case SExt: return ISD::SIGN_EXTEND;
  1362. case FPToUI: return ISD::FP_TO_UINT;
  1363. case FPToSI: return ISD::FP_TO_SINT;
  1364. case UIToFP: return ISD::UINT_TO_FP;
  1365. case SIToFP: return ISD::SINT_TO_FP;
  1366. case FPTrunc: return ISD::FP_ROUND;
  1367. case FPExt: return ISD::FP_EXTEND;
  1368. case PtrToInt: return ISD::BITCAST;
  1369. case IntToPtr: return ISD::BITCAST;
  1370. case BitCast: return ISD::BITCAST;
  1371. case AddrSpaceCast: return ISD::ADDRSPACECAST;
  1372. case ICmp: return ISD::SETCC;
  1373. case FCmp: return ISD::SETCC;
  1374. case PHI: return 0;
  1375. case Call: return 0;
  1376. case Select: return ISD::SELECT;
  1377. case UserOp1: return 0;
  1378. case UserOp2: return 0;
  1379. case VAArg: return 0;
  1380. case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
  1381. case InsertElement: return ISD::INSERT_VECTOR_ELT;
  1382. case ShuffleVector: return ISD::VECTOR_SHUFFLE;
  1383. case ExtractValue: return ISD::MERGE_VALUES;
  1384. case InsertValue: return ISD::MERGE_VALUES;
  1385. case LandingPad: return 0;
  1386. }
  1387. llvm_unreachable("Unknown instruction type encountered!");
  1388. }
  1389. std::pair<int, MVT>
  1390. TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL,
  1391. Type *Ty) const {
  1392. LLVMContext &C = Ty->getContext();
  1393. EVT MTy = getValueType(DL, Ty);
  1394. int Cost = 1;
  1395. // We keep legalizing the type until we find a legal kind. We assume that
  1396. // the only operation that costs anything is the split. After splitting
  1397. // we need to handle two types.
  1398. while (true) {
  1399. LegalizeKind LK = getTypeConversion(C, MTy);
  1400. if (LK.first == TypeLegal)
  1401. return std::make_pair(Cost, MTy.getSimpleVT());
  1402. if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger)
  1403. Cost *= 2;
  1404. // Do not loop with f128 type.
  1405. if (MTy == LK.second)
  1406. return std::make_pair(Cost, MTy.getSimpleVT());
  1407. // Keep legalizing the type.
  1408. MTy = LK.second;
  1409. }
  1410. }
  1411. Value *TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
  1412. bool UseTLS) const {
  1413. // compiler-rt provides a variable with a magic name. Targets that do not
  1414. // link with compiler-rt may also provide such a variable.
  1415. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  1416. const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
  1417. auto UnsafeStackPtr =
  1418. dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
  1419. Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
  1420. if (!UnsafeStackPtr) {
  1421. auto TLSModel = UseTLS ?
  1422. GlobalValue::InitialExecTLSModel :
  1423. GlobalValue::NotThreadLocal;
  1424. // The global variable is not defined yet, define it ourselves.
  1425. // We use the initial-exec TLS model because we do not support the
  1426. // variable living anywhere other than in the main executable.
  1427. UnsafeStackPtr = new GlobalVariable(
  1428. *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
  1429. UnsafeStackPtrVar, nullptr, TLSModel);
  1430. } else {
  1431. // The variable exists, check its type and attributes.
  1432. if (UnsafeStackPtr->getValueType() != StackPtrTy)
  1433. report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
  1434. if (UseTLS != UnsafeStackPtr->isThreadLocal())
  1435. report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
  1436. (UseTLS ? "" : "not ") + "be thread-local");
  1437. }
  1438. return UnsafeStackPtr;
  1439. }
  1440. Value *TargetLoweringBase::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
  1441. if (!TM.getTargetTriple().isAndroid())
  1442. return getDefaultSafeStackPointerLocation(IRB, true);
  1443. // Android provides a libc function to retrieve the address of the current
  1444. // thread's unsafe stack pointer.
  1445. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  1446. Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
  1447. FunctionCallee Fn = M->getOrInsertFunction("__safestack_pointer_address",
  1448. StackPtrTy->getPointerTo(0));
  1449. return IRB.CreateCall(Fn);
  1450. }
  1451. //===----------------------------------------------------------------------===//
  1452. // Loop Strength Reduction hooks
  1453. //===----------------------------------------------------------------------===//
  1454. /// isLegalAddressingMode - Return true if the addressing mode represented
  1455. /// by AM is legal for this target, for a load/store of the specified type.
  1456. bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
  1457. const AddrMode &AM, Type *Ty,
  1458. unsigned AS, Instruction *I) const {
  1459. // The default implementation of this implements a conservative RISCy, r+r and
  1460. // r+i addr mode.
  1461. // Allows a sign-extended 16-bit immediate field.
  1462. if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
  1463. return false;
  1464. // No global is ever allowed as a base.
  1465. if (AM.BaseGV)
  1466. return false;
  1467. // Only support r+r,
  1468. switch (AM.Scale) {
  1469. case 0: // "r+i" or just "i", depending on HasBaseReg.
  1470. break;
  1471. case 1:
  1472. if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
  1473. return false;
  1474. // Otherwise we have r+r or r+i.
  1475. break;
  1476. case 2:
  1477. if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
  1478. return false;
  1479. // Allow 2*r as r+r.
  1480. break;
  1481. default: // Don't allow n * r
  1482. return false;
  1483. }
  1484. return true;
  1485. }
  1486. //===----------------------------------------------------------------------===//
  1487. // Stack Protector
  1488. //===----------------------------------------------------------------------===//
  1489. // For OpenBSD return its special guard variable. Otherwise return nullptr,
  1490. // so that SelectionDAG handle SSP.
  1491. Value *TargetLoweringBase::getIRStackGuard(IRBuilder<> &IRB) const {
  1492. if (getTargetMachine().getTargetTriple().isOSOpenBSD()) {
  1493. Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
  1494. PointerType *PtrTy = Type::getInt8PtrTy(M.getContext());
  1495. return M.getOrInsertGlobal("__guard_local", PtrTy);
  1496. }
  1497. return nullptr;
  1498. }
  1499. // Currently only support "standard" __stack_chk_guard.
  1500. // TODO: add LOAD_STACK_GUARD support.
  1501. void TargetLoweringBase::insertSSPDeclarations(Module &M) const {
  1502. if (!M.getNamedValue("__stack_chk_guard"))
  1503. new GlobalVariable(M, Type::getInt8PtrTy(M.getContext()), false,
  1504. GlobalVariable::ExternalLinkage,
  1505. nullptr, "__stack_chk_guard");
  1506. }
  1507. // Currently only support "standard" __stack_chk_guard.
  1508. // TODO: add LOAD_STACK_GUARD support.
  1509. Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const {
  1510. return M.getNamedValue("__stack_chk_guard");
  1511. }
  1512. Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const {
  1513. return nullptr;
  1514. }
  1515. unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
  1516. return MinimumJumpTableEntries;
  1517. }
  1518. void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
  1519. MinimumJumpTableEntries = Val;
  1520. }
  1521. unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const {
  1522. return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
  1523. }
  1524. unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
  1525. return MaximumJumpTableSize;
  1526. }
  1527. void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
  1528. MaximumJumpTableSize = Val;
  1529. }
  1530. //===----------------------------------------------------------------------===//
  1531. // Reciprocal Estimates
  1532. //===----------------------------------------------------------------------===//
  1533. /// Get the reciprocal estimate attribute string for a function that will
  1534. /// override the target defaults.
  1535. static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
  1536. const Function &F = MF.getFunction();
  1537. return F.getFnAttribute("reciprocal-estimates").getValueAsString();
  1538. }
  1539. /// Construct a string for the given reciprocal operation of the given type.
  1540. /// This string should match the corresponding option to the front-end's
  1541. /// "-mrecip" flag assuming those strings have been passed through in an
  1542. /// attribute string. For example, "vec-divf" for a division of a vXf32.
  1543. static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
  1544. std::string Name = VT.isVector() ? "vec-" : "";
  1545. Name += IsSqrt ? "sqrt" : "div";
  1546. // TODO: Handle "half" or other float types?
  1547. if (VT.getScalarType() == MVT::f64) {
  1548. Name += "d";
  1549. } else {
  1550. assert(VT.getScalarType() == MVT::f32 &&
  1551. "Unexpected FP type for reciprocal estimate");
  1552. Name += "f";
  1553. }
  1554. return Name;
  1555. }
  1556. /// Return the character position and value (a single numeric character) of a
  1557. /// customized refinement operation in the input string if it exists. Return
  1558. /// false if there is no customized refinement step count.
  1559. static bool parseRefinementStep(StringRef In, size_t &Position,
  1560. uint8_t &Value) {
  1561. const char RefStepToken = ':';
  1562. Position = In.find(RefStepToken);
  1563. if (Position == StringRef::npos)
  1564. return false;
  1565. StringRef RefStepString = In.substr(Position + 1);
  1566. // Allow exactly one numeric character for the additional refinement
  1567. // step parameter.
  1568. if (RefStepString.size() == 1) {
  1569. char RefStepChar = RefStepString[0];
  1570. if (RefStepChar >= '0' && RefStepChar <= '9') {
  1571. Value = RefStepChar - '0';
  1572. return true;
  1573. }
  1574. }
  1575. report_fatal_error("Invalid refinement step for -recip.");
  1576. }
  1577. /// For the input attribute string, return one of the ReciprocalEstimate enum
  1578. /// status values (enabled, disabled, or not specified) for this operation on
  1579. /// the specified data type.
  1580. static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
  1581. if (Override.empty())
  1582. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1583. SmallVector<StringRef, 4> OverrideVector;
  1584. Override.split(OverrideVector, ',');
  1585. unsigned NumArgs = OverrideVector.size();
  1586. // Check if "all", "none", or "default" was specified.
  1587. if (NumArgs == 1) {
  1588. // Look for an optional setting of the number of refinement steps needed
  1589. // for this type of reciprocal operation.
  1590. size_t RefPos;
  1591. uint8_t RefSteps;
  1592. if (parseRefinementStep(Override, RefPos, RefSteps)) {
  1593. // Split the string for further processing.
  1594. Override = Override.substr(0, RefPos);
  1595. }
  1596. // All reciprocal types are enabled.
  1597. if (Override == "all")
  1598. return TargetLoweringBase::ReciprocalEstimate::Enabled;
  1599. // All reciprocal types are disabled.
  1600. if (Override == "none")
  1601. return TargetLoweringBase::ReciprocalEstimate::Disabled;
  1602. // Target defaults for enablement are used.
  1603. if (Override == "default")
  1604. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1605. }
  1606. // The attribute string may omit the size suffix ('f'/'d').
  1607. std::string VTName = getReciprocalOpName(IsSqrt, VT);
  1608. std::string VTNameNoSize = VTName;
  1609. VTNameNoSize.pop_back();
  1610. static const char DisabledPrefix = '!';
  1611. for (StringRef RecipType : OverrideVector) {
  1612. size_t RefPos;
  1613. uint8_t RefSteps;
  1614. if (parseRefinementStep(RecipType, RefPos, RefSteps))
  1615. RecipType = RecipType.substr(0, RefPos);
  1616. // Ignore the disablement token for string matching.
  1617. bool IsDisabled = RecipType[0] == DisabledPrefix;
  1618. if (IsDisabled)
  1619. RecipType = RecipType.substr(1);
  1620. if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
  1621. return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
  1622. : TargetLoweringBase::ReciprocalEstimate::Enabled;
  1623. }
  1624. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1625. }
  1626. /// For the input attribute string, return the customized refinement step count
  1627. /// for this operation on the specified data type. If the step count does not
  1628. /// exist, return the ReciprocalEstimate enum value for unspecified.
  1629. static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
  1630. if (Override.empty())
  1631. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1632. SmallVector<StringRef, 4> OverrideVector;
  1633. Override.split(OverrideVector, ',');
  1634. unsigned NumArgs = OverrideVector.size();
  1635. // Check if "all", "default", or "none" was specified.
  1636. if (NumArgs == 1) {
  1637. // Look for an optional setting of the number of refinement steps needed
  1638. // for this type of reciprocal operation.
  1639. size_t RefPos;
  1640. uint8_t RefSteps;
  1641. if (!parseRefinementStep(Override, RefPos, RefSteps))
  1642. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1643. // Split the string for further processing.
  1644. Override = Override.substr(0, RefPos);
  1645. assert(Override != "none" &&
  1646. "Disabled reciprocals, but specifed refinement steps?");
  1647. // If this is a general override, return the specified number of steps.
  1648. if (Override == "all" || Override == "default")
  1649. return RefSteps;
  1650. }
  1651. // The attribute string may omit the size suffix ('f'/'d').
  1652. std::string VTName = getReciprocalOpName(IsSqrt, VT);
  1653. std::string VTNameNoSize = VTName;
  1654. VTNameNoSize.pop_back();
  1655. for (StringRef RecipType : OverrideVector) {
  1656. size_t RefPos;
  1657. uint8_t RefSteps;
  1658. if (!parseRefinementStep(RecipType, RefPos, RefSteps))
  1659. continue;
  1660. RecipType = RecipType.substr(0, RefPos);
  1661. if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
  1662. return RefSteps;
  1663. }
  1664. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1665. }
  1666. int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
  1667. MachineFunction &MF) const {
  1668. return getOpEnabled(true, VT, getRecipEstimateForFunc(MF));
  1669. }
  1670. int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
  1671. MachineFunction &MF) const {
  1672. return getOpEnabled(false, VT, getRecipEstimateForFunc(MF));
  1673. }
  1674. int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
  1675. MachineFunction &MF) const {
  1676. return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF));
  1677. }
  1678. int TargetLoweringBase::getDivRefinementSteps(EVT VT,
  1679. MachineFunction &MF) const {
  1680. return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF));
  1681. }
  1682. void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const {
  1683. MF.getRegInfo().freezeReservedRegs(MF);
  1684. }