TargetLoweringBase.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  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(0), cl::Hidden,
  72. cl::desc("Set maximum size of jump tables; zero for no limit."));
  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. HasFloatingPointExceptions = true;
  516. StackPointerRegisterToSaveRestore = 0;
  517. BooleanContents = UndefinedBooleanContent;
  518. BooleanFloatContents = UndefinedBooleanContent;
  519. BooleanVectorContents = UndefinedBooleanContent;
  520. SchedPreferenceInfo = Sched::ILP;
  521. JumpBufSize = 0;
  522. JumpBufAlignment = 0;
  523. MinFunctionAlignment = 0;
  524. PrefFunctionAlignment = 0;
  525. PrefLoopAlignment = 0;
  526. GatherAllAliasesMaxDepth = 18;
  527. MinStackArgumentAlignment = 1;
  528. // TODO: the default will be switched to 0 in the next commit, along
  529. // with the Target-specific changes necessary.
  530. MaxAtomicSizeInBitsSupported = 1024;
  531. MinCmpXchgSizeInBits = 0;
  532. SupportsUnalignedAtomics = false;
  533. std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr);
  534. InitLibcalls(TM.getTargetTriple());
  535. InitCmpLibcallCCs(CmpLibcallCCs);
  536. }
  537. void TargetLoweringBase::initActions() {
  538. // All operations default to being supported.
  539. memset(OpActions, 0, sizeof(OpActions));
  540. memset(LoadExtActions, 0, sizeof(LoadExtActions));
  541. memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
  542. memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
  543. memset(CondCodeActions, 0, sizeof(CondCodeActions));
  544. std::fill(std::begin(RegClassForVT), std::end(RegClassForVT), nullptr);
  545. std::fill(std::begin(TargetDAGCombineArray),
  546. std::end(TargetDAGCombineArray), 0);
  547. for (MVT VT : MVT::fp_valuetypes()) {
  548. MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
  549. if (IntVT.isValid()) {
  550. setOperationAction(ISD::ATOMIC_SWAP, VT, Promote);
  551. AddPromotedToType(ISD::ATOMIC_SWAP, VT, IntVT);
  552. }
  553. }
  554. // Set default actions for various operations.
  555. for (MVT VT : MVT::all_valuetypes()) {
  556. // Default all indexed load / store to expand.
  557. for (unsigned IM = (unsigned)ISD::PRE_INC;
  558. IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
  559. setIndexedLoadAction(IM, VT, Expand);
  560. setIndexedStoreAction(IM, VT, Expand);
  561. }
  562. // Most backends expect to see the node which just returns the value loaded.
  563. setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand);
  564. // These operations default to expand.
  565. setOperationAction(ISD::FGETSIGN, VT, Expand);
  566. setOperationAction(ISD::CONCAT_VECTORS, VT, Expand);
  567. setOperationAction(ISD::FMINNUM, VT, Expand);
  568. setOperationAction(ISD::FMAXNUM, VT, Expand);
  569. setOperationAction(ISD::FMINNUM_IEEE, VT, Expand);
  570. setOperationAction(ISD::FMAXNUM_IEEE, VT, Expand);
  571. setOperationAction(ISD::FMINIMUM, VT, Expand);
  572. setOperationAction(ISD::FMAXIMUM, VT, Expand);
  573. setOperationAction(ISD::FMAD, VT, Expand);
  574. setOperationAction(ISD::SMIN, VT, Expand);
  575. setOperationAction(ISD::SMAX, VT, Expand);
  576. setOperationAction(ISD::UMIN, VT, Expand);
  577. setOperationAction(ISD::UMAX, VT, Expand);
  578. setOperationAction(ISD::ABS, VT, Expand);
  579. setOperationAction(ISD::FSHL, VT, Expand);
  580. setOperationAction(ISD::FSHR, VT, Expand);
  581. setOperationAction(ISD::SADDSAT, VT, Expand);
  582. setOperationAction(ISD::UADDSAT, VT, Expand);
  583. setOperationAction(ISD::SSUBSAT, VT, Expand);
  584. setOperationAction(ISD::USUBSAT, VT, Expand);
  585. setOperationAction(ISD::SMULFIX, VT, Expand);
  586. // Overflow operations default to expand
  587. setOperationAction(ISD::SADDO, VT, Expand);
  588. setOperationAction(ISD::SSUBO, VT, Expand);
  589. setOperationAction(ISD::UADDO, VT, Expand);
  590. setOperationAction(ISD::USUBO, VT, Expand);
  591. setOperationAction(ISD::SMULO, VT, Expand);
  592. setOperationAction(ISD::UMULO, VT, Expand);
  593. // ADDCARRY operations default to expand
  594. setOperationAction(ISD::ADDCARRY, VT, Expand);
  595. setOperationAction(ISD::SUBCARRY, VT, Expand);
  596. setOperationAction(ISD::SETCCCARRY, VT, Expand);
  597. // ADDC/ADDE/SUBC/SUBE default to expand.
  598. setOperationAction(ISD::ADDC, VT, Expand);
  599. setOperationAction(ISD::ADDE, VT, Expand);
  600. setOperationAction(ISD::SUBC, VT, Expand);
  601. setOperationAction(ISD::SUBE, VT, Expand);
  602. // These default to Expand so they will be expanded to CTLZ/CTTZ by default.
  603. setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
  604. setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
  605. setOperationAction(ISD::BITREVERSE, VT, Expand);
  606. // These library functions default to expand.
  607. setOperationAction(ISD::FROUND, VT, Expand);
  608. setOperationAction(ISD::FPOWI, VT, Expand);
  609. // These operations default to expand for vector types.
  610. if (VT.isVector()) {
  611. setOperationAction(ISD::FCOPYSIGN, VT, Expand);
  612. setOperationAction(ISD::ANY_EXTEND_VECTOR_INREG, VT, Expand);
  613. setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Expand);
  614. setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Expand);
  615. }
  616. // For most targets @llvm.get.dynamic.area.offset just returns 0.
  617. setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand);
  618. }
  619. // Most targets ignore the @llvm.prefetch intrinsic.
  620. setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
  621. // Most targets also ignore the @llvm.readcyclecounter intrinsic.
  622. setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
  623. // ConstantFP nodes default to expand. Targets can either change this to
  624. // Legal, in which case all fp constants are legal, or use isFPImmLegal()
  625. // to optimize expansions for certain constants.
  626. setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
  627. setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
  628. setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
  629. setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
  630. setOperationAction(ISD::ConstantFP, MVT::f128, Expand);
  631. // These library functions default to expand.
  632. for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
  633. setOperationAction(ISD::FCBRT, VT, Expand);
  634. setOperationAction(ISD::FLOG , VT, Expand);
  635. setOperationAction(ISD::FLOG2, VT, Expand);
  636. setOperationAction(ISD::FLOG10, VT, Expand);
  637. setOperationAction(ISD::FEXP , VT, Expand);
  638. setOperationAction(ISD::FEXP2, VT, Expand);
  639. setOperationAction(ISD::FFLOOR, VT, Expand);
  640. setOperationAction(ISD::FNEARBYINT, VT, Expand);
  641. setOperationAction(ISD::FCEIL, VT, Expand);
  642. setOperationAction(ISD::FRINT, VT, Expand);
  643. setOperationAction(ISD::FTRUNC, VT, Expand);
  644. setOperationAction(ISD::FROUND, VT, Expand);
  645. }
  646. // Default ISD::TRAP to expand (which turns it into abort).
  647. setOperationAction(ISD::TRAP, MVT::Other, Expand);
  648. // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
  649. // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
  650. setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
  651. }
  652. MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
  653. EVT) const {
  654. return MVT::getIntegerVT(8 * DL.getPointerSize(0));
  655. }
  656. EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
  657. bool LegalTypes) const {
  658. assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
  659. if (LHSTy.isVector())
  660. return LHSTy;
  661. return LegalTypes ? getScalarShiftAmountTy(DL, LHSTy)
  662. : getPointerTy(DL);
  663. }
  664. bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
  665. assert(isTypeLegal(VT));
  666. switch (Op) {
  667. default:
  668. return false;
  669. case ISD::SDIV:
  670. case ISD::UDIV:
  671. case ISD::SREM:
  672. case ISD::UREM:
  673. return true;
  674. }
  675. }
  676. void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
  677. // If the command-line option was specified, ignore this request.
  678. if (!JumpIsExpensiveOverride.getNumOccurrences())
  679. JumpIsExpensive = isExpensive;
  680. }
  681. TargetLoweringBase::LegalizeKind
  682. TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
  683. // If this is a simple type, use the ComputeRegisterProp mechanism.
  684. if (VT.isSimple()) {
  685. MVT SVT = VT.getSimpleVT();
  686. assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
  687. MVT NVT = TransformToType[SVT.SimpleTy];
  688. LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
  689. assert((LA == TypeLegal || LA == TypeSoftenFloat ||
  690. ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger) &&
  691. "Promote may not follow Expand or Promote");
  692. if (LA == TypeSplitVector)
  693. return LegalizeKind(LA,
  694. EVT::getVectorVT(Context, SVT.getVectorElementType(),
  695. SVT.getVectorNumElements() / 2));
  696. if (LA == TypeScalarizeVector)
  697. return LegalizeKind(LA, SVT.getVectorElementType());
  698. return LegalizeKind(LA, NVT);
  699. }
  700. // Handle Extended Scalar Types.
  701. if (!VT.isVector()) {
  702. assert(VT.isInteger() && "Float types must be simple");
  703. unsigned BitSize = VT.getSizeInBits();
  704. // First promote to a power-of-two size, then expand if necessary.
  705. if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
  706. EVT NVT = VT.getRoundIntegerType(Context);
  707. assert(NVT != VT && "Unable to round integer VT");
  708. LegalizeKind NextStep = getTypeConversion(Context, NVT);
  709. // Avoid multi-step promotion.
  710. if (NextStep.first == TypePromoteInteger)
  711. return NextStep;
  712. // Return rounded integer type.
  713. return LegalizeKind(TypePromoteInteger, NVT);
  714. }
  715. return LegalizeKind(TypeExpandInteger,
  716. EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
  717. }
  718. // Handle vector types.
  719. unsigned NumElts = VT.getVectorNumElements();
  720. EVT EltVT = VT.getVectorElementType();
  721. // Vectors with only one element are always scalarized.
  722. if (NumElts == 1)
  723. return LegalizeKind(TypeScalarizeVector, EltVT);
  724. // Try to widen vector elements until the element type is a power of two and
  725. // promote it to a legal type later on, for example:
  726. // <3 x i8> -> <4 x i8> -> <4 x i32>
  727. if (EltVT.isInteger()) {
  728. // Vectors with a number of elements that is not a power of two are always
  729. // widened, for example <3 x i8> -> <4 x i8>.
  730. if (!VT.isPow2VectorType()) {
  731. NumElts = (unsigned)NextPowerOf2(NumElts);
  732. EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
  733. return LegalizeKind(TypeWidenVector, NVT);
  734. }
  735. // Examine the element type.
  736. LegalizeKind LK = getTypeConversion(Context, EltVT);
  737. // If type is to be expanded, split the vector.
  738. // <4 x i140> -> <2 x i140>
  739. if (LK.first == TypeExpandInteger)
  740. return LegalizeKind(TypeSplitVector,
  741. EVT::getVectorVT(Context, EltVT, NumElts / 2));
  742. // Promote the integer element types until a legal vector type is found
  743. // or until the element integer type is too big. If a legal type was not
  744. // found, fallback to the usual mechanism of widening/splitting the
  745. // vector.
  746. EVT OldEltVT = EltVT;
  747. while (true) {
  748. // Increase the bitwidth of the element to the next pow-of-two
  749. // (which is greater than 8 bits).
  750. EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
  751. .getRoundIntegerType(Context);
  752. // Stop trying when getting a non-simple element type.
  753. // Note that vector elements may be greater than legal vector element
  754. // types. Example: X86 XMM registers hold 64bit element on 32bit
  755. // systems.
  756. if (!EltVT.isSimple())
  757. break;
  758. // Build a new vector type and check if it is legal.
  759. MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
  760. // Found a legal promoted vector type.
  761. if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
  762. return LegalizeKind(TypePromoteInteger,
  763. EVT::getVectorVT(Context, EltVT, NumElts));
  764. }
  765. // Reset the type to the unexpanded type if we did not find a legal vector
  766. // type with a promoted vector element type.
  767. EltVT = OldEltVT;
  768. }
  769. // Try to widen the vector until a legal type is found.
  770. // If there is no wider legal type, split the vector.
  771. while (true) {
  772. // Round up to the next power of 2.
  773. NumElts = (unsigned)NextPowerOf2(NumElts);
  774. // If there is no simple vector type with this many elements then there
  775. // cannot be a larger legal vector type. Note that this assumes that
  776. // there are no skipped intermediate vector types in the simple types.
  777. if (!EltVT.isSimple())
  778. break;
  779. MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
  780. if (LargerVector == MVT())
  781. break;
  782. // If this type is legal then widen the vector.
  783. if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
  784. return LegalizeKind(TypeWidenVector, LargerVector);
  785. }
  786. // Widen odd vectors to next power of two.
  787. if (!VT.isPow2VectorType()) {
  788. EVT NVT = VT.getPow2VectorType(Context);
  789. return LegalizeKind(TypeWidenVector, NVT);
  790. }
  791. // Vectors with illegal element types are expanded.
  792. EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
  793. return LegalizeKind(TypeSplitVector, NVT);
  794. }
  795. static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
  796. unsigned &NumIntermediates,
  797. MVT &RegisterVT,
  798. TargetLoweringBase *TLI) {
  799. // Figure out the right, legal destination reg to copy into.
  800. unsigned NumElts = VT.getVectorNumElements();
  801. MVT EltTy = VT.getVectorElementType();
  802. unsigned NumVectorRegs = 1;
  803. // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
  804. // could break down into LHS/RHS like LegalizeDAG does.
  805. if (!isPowerOf2_32(NumElts)) {
  806. NumVectorRegs = NumElts;
  807. NumElts = 1;
  808. }
  809. // Divide the input until we get to a supported size. This will always
  810. // end with a scalar if the target doesn't support vectors.
  811. while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
  812. NumElts >>= 1;
  813. NumVectorRegs <<= 1;
  814. }
  815. NumIntermediates = NumVectorRegs;
  816. MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
  817. if (!TLI->isTypeLegal(NewVT))
  818. NewVT = EltTy;
  819. IntermediateVT = NewVT;
  820. unsigned NewVTSize = NewVT.getSizeInBits();
  821. // Convert sizes such as i33 to i64.
  822. if (!isPowerOf2_32(NewVTSize))
  823. NewVTSize = NextPowerOf2(NewVTSize);
  824. MVT DestVT = TLI->getRegisterType(NewVT);
  825. RegisterVT = DestVT;
  826. if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
  827. return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
  828. // Otherwise, promotion or legal types use the same number of registers as
  829. // the vector decimated to the appropriate level.
  830. return NumVectorRegs;
  831. }
  832. /// isLegalRC - Return true if the value types that can be represented by the
  833. /// specified register class are all legal.
  834. bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
  835. const TargetRegisterClass &RC) const {
  836. for (auto I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
  837. if (isTypeLegal(*I))
  838. return true;
  839. return false;
  840. }
  841. /// Replace/modify any TargetFrameIndex operands with a targte-dependent
  842. /// sequence of memory operands that is recognized by PrologEpilogInserter.
  843. MachineBasicBlock *
  844. TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
  845. MachineBasicBlock *MBB) const {
  846. MachineInstr *MI = &InitialMI;
  847. MachineFunction &MF = *MI->getMF();
  848. MachineFrameInfo &MFI = MF.getFrameInfo();
  849. // We're handling multiple types of operands here:
  850. // PATCHPOINT MetaArgs - live-in, read only, direct
  851. // STATEPOINT Deopt Spill - live-through, read only, indirect
  852. // STATEPOINT Deopt Alloca - live-through, read only, direct
  853. // (We're currently conservative and mark the deopt slots read/write in
  854. // practice.)
  855. // STATEPOINT GC Spill - live-through, read/write, indirect
  856. // STATEPOINT GC Alloca - live-through, read/write, direct
  857. // The live-in vs live-through is handled already (the live through ones are
  858. // all stack slots), but we need to handle the different type of stackmap
  859. // operands and memory effects here.
  860. // MI changes inside this loop as we grow operands.
  861. for(unsigned OperIdx = 0; OperIdx != MI->getNumOperands(); ++OperIdx) {
  862. MachineOperand &MO = MI->getOperand(OperIdx);
  863. if (!MO.isFI())
  864. continue;
  865. // foldMemoryOperand builds a new MI after replacing a single FI operand
  866. // with the canonical set of five x86 addressing-mode operands.
  867. int FI = MO.getIndex();
  868. MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
  869. // Copy operands before the frame-index.
  870. for (unsigned i = 0; i < OperIdx; ++i)
  871. MIB.add(MI->getOperand(i));
  872. // Add frame index operands recognized by stackmaps.cpp
  873. if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
  874. // indirect-mem-ref tag, size, #FI, offset.
  875. // Used for spills inserted by StatepointLowering. This codepath is not
  876. // used for patchpoints/stackmaps at all, for these spilling is done via
  877. // foldMemoryOperand callback only.
  878. assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
  879. MIB.addImm(StackMaps::IndirectMemRefOp);
  880. MIB.addImm(MFI.getObjectSize(FI));
  881. MIB.add(MI->getOperand(OperIdx));
  882. MIB.addImm(0);
  883. } else {
  884. // direct-mem-ref tag, #FI, offset.
  885. // Used by patchpoint, and direct alloca arguments to statepoints
  886. MIB.addImm(StackMaps::DirectMemRefOp);
  887. MIB.add(MI->getOperand(OperIdx));
  888. MIB.addImm(0);
  889. }
  890. // Copy the operands after the frame index.
  891. for (unsigned i = OperIdx + 1; i != MI->getNumOperands(); ++i)
  892. MIB.add(MI->getOperand(i));
  893. // Inherit previous memory operands.
  894. MIB.cloneMemRefs(*MI);
  895. assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
  896. // Add a new memory operand for this FI.
  897. assert(MFI.getObjectOffset(FI) != -1);
  898. auto Flags = MachineMemOperand::MOLoad;
  899. if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
  900. Flags |= MachineMemOperand::MOStore;
  901. Flags |= MachineMemOperand::MOVolatile;
  902. }
  903. MachineMemOperand *MMO = MF.getMachineMemOperand(
  904. MachinePointerInfo::getFixedStack(MF, FI), Flags,
  905. MF.getDataLayout().getPointerSize(), MFI.getObjectAlignment(FI));
  906. MIB->addMemOperand(MF, MMO);
  907. // Replace the instruction and update the operand index.
  908. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  909. OperIdx += (MIB->getNumOperands() - MI->getNumOperands()) - 1;
  910. MI->eraseFromParent();
  911. MI = MIB;
  912. }
  913. return MBB;
  914. }
  915. MachineBasicBlock *
  916. TargetLoweringBase::emitXRayCustomEvent(MachineInstr &MI,
  917. MachineBasicBlock *MBB) const {
  918. assert(MI.getOpcode() == TargetOpcode::PATCHABLE_EVENT_CALL &&
  919. "Called emitXRayCustomEvent on the wrong MI!");
  920. auto &MF = *MI.getMF();
  921. auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
  922. for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
  923. MIB.add(MI.getOperand(OpIdx));
  924. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  925. MI.eraseFromParent();
  926. return MBB;
  927. }
  928. MachineBasicBlock *
  929. TargetLoweringBase::emitXRayTypedEvent(MachineInstr &MI,
  930. MachineBasicBlock *MBB) const {
  931. assert(MI.getOpcode() == TargetOpcode::PATCHABLE_TYPED_EVENT_CALL &&
  932. "Called emitXRayTypedEvent on the wrong MI!");
  933. auto &MF = *MI.getMF();
  934. auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
  935. for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
  936. MIB.add(MI.getOperand(OpIdx));
  937. MBB->insert(MachineBasicBlock::iterator(MI), MIB);
  938. MI.eraseFromParent();
  939. return MBB;
  940. }
  941. /// findRepresentativeClass - Return the largest legal super-reg register class
  942. /// of the register class for the specified type and its associated "cost".
  943. // This function is in TargetLowering because it uses RegClassForVT which would
  944. // need to be moved to TargetRegisterInfo and would necessitate moving
  945. // isTypeLegal over as well - a massive change that would just require
  946. // TargetLowering having a TargetRegisterInfo class member that it would use.
  947. std::pair<const TargetRegisterClass *, uint8_t>
  948. TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
  949. MVT VT) const {
  950. const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
  951. if (!RC)
  952. return std::make_pair(RC, 0);
  953. // Compute the set of all super-register classes.
  954. BitVector SuperRegRC(TRI->getNumRegClasses());
  955. for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
  956. SuperRegRC.setBitsInMask(RCI.getMask());
  957. // Find the first legal register class with the largest spill size.
  958. const TargetRegisterClass *BestRC = RC;
  959. for (unsigned i : SuperRegRC.set_bits()) {
  960. const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
  961. // We want the largest possible spill size.
  962. if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC))
  963. continue;
  964. if (!isLegalRC(*TRI, *SuperRC))
  965. continue;
  966. BestRC = SuperRC;
  967. }
  968. return std::make_pair(BestRC, 1);
  969. }
  970. /// computeRegisterProperties - Once all of the register classes are added,
  971. /// this allows us to compute derived properties we expose.
  972. void TargetLoweringBase::computeRegisterProperties(
  973. const TargetRegisterInfo *TRI) {
  974. static_assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE,
  975. "Too many value types for ValueTypeActions to hold!");
  976. // Everything defaults to needing one register.
  977. for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
  978. NumRegistersForVT[i] = 1;
  979. RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
  980. }
  981. // ...except isVoid, which doesn't need any registers.
  982. NumRegistersForVT[MVT::isVoid] = 0;
  983. // Find the largest integer register class.
  984. unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
  985. for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
  986. assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
  987. // Every integer value type larger than this largest register takes twice as
  988. // many registers to represent as the previous ValueType.
  989. for (unsigned ExpandedReg = LargestIntReg + 1;
  990. ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
  991. NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
  992. RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
  993. TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
  994. ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
  995. TypeExpandInteger);
  996. }
  997. // Inspect all of the ValueType's smaller than the largest integer
  998. // register to see which ones need promotion.
  999. unsigned LegalIntReg = LargestIntReg;
  1000. for (unsigned IntReg = LargestIntReg - 1;
  1001. IntReg >= (unsigned)MVT::i1; --IntReg) {
  1002. MVT IVT = (MVT::SimpleValueType)IntReg;
  1003. if (isTypeLegal(IVT)) {
  1004. LegalIntReg = IntReg;
  1005. } else {
  1006. RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
  1007. (MVT::SimpleValueType)LegalIntReg;
  1008. ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
  1009. }
  1010. }
  1011. // ppcf128 type is really two f64's.
  1012. if (!isTypeLegal(MVT::ppcf128)) {
  1013. if (isTypeLegal(MVT::f64)) {
  1014. NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
  1015. RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
  1016. TransformToType[MVT::ppcf128] = MVT::f64;
  1017. ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
  1018. } else {
  1019. NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
  1020. RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
  1021. TransformToType[MVT::ppcf128] = MVT::i128;
  1022. ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
  1023. }
  1024. }
  1025. // Decide how to handle f128. If the target does not have native f128 support,
  1026. // expand it to i128 and we will be generating soft float library calls.
  1027. if (!isTypeLegal(MVT::f128)) {
  1028. NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
  1029. RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
  1030. TransformToType[MVT::f128] = MVT::i128;
  1031. ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
  1032. }
  1033. // Decide how to handle f64. If the target does not have native f64 support,
  1034. // expand it to i64 and we will be generating soft float library calls.
  1035. if (!isTypeLegal(MVT::f64)) {
  1036. NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
  1037. RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
  1038. TransformToType[MVT::f64] = MVT::i64;
  1039. ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
  1040. }
  1041. // Decide how to handle f32. If the target does not have native f32 support,
  1042. // expand it to i32 and we will be generating soft float library calls.
  1043. if (!isTypeLegal(MVT::f32)) {
  1044. NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
  1045. RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
  1046. TransformToType[MVT::f32] = MVT::i32;
  1047. ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
  1048. }
  1049. // Decide how to handle f16. If the target does not have native f16 support,
  1050. // promote it to f32, because there are no f16 library calls (except for
  1051. // conversions).
  1052. if (!isTypeLegal(MVT::f16)) {
  1053. NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
  1054. RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
  1055. TransformToType[MVT::f16] = MVT::f32;
  1056. ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
  1057. }
  1058. // Loop over all of the vector value types to see which need transformations.
  1059. for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
  1060. i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
  1061. MVT VT = (MVT::SimpleValueType) i;
  1062. if (isTypeLegal(VT))
  1063. continue;
  1064. MVT EltVT = VT.getVectorElementType();
  1065. unsigned NElts = VT.getVectorNumElements();
  1066. bool IsLegalWiderType = false;
  1067. LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
  1068. switch (PreferredAction) {
  1069. case TypePromoteInteger:
  1070. // Try to promote the elements of integer vectors. If no legal
  1071. // promotion was found, fall through to the widen-vector method.
  1072. for (unsigned nVT = i + 1; nVT <= MVT::LAST_INTEGER_VECTOR_VALUETYPE; ++nVT) {
  1073. MVT SVT = (MVT::SimpleValueType) nVT;
  1074. // Promote vectors of integers to vectors with the same number
  1075. // of elements, with a wider element type.
  1076. if (SVT.getScalarSizeInBits() > EltVT.getSizeInBits() &&
  1077. SVT.getVectorNumElements() == NElts && isTypeLegal(SVT)) {
  1078. TransformToType[i] = SVT;
  1079. RegisterTypeForVT[i] = SVT;
  1080. NumRegistersForVT[i] = 1;
  1081. ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
  1082. IsLegalWiderType = true;
  1083. break;
  1084. }
  1085. }
  1086. if (IsLegalWiderType)
  1087. break;
  1088. LLVM_FALLTHROUGH;
  1089. case TypeWidenVector:
  1090. // Try to widen the vector.
  1091. for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
  1092. MVT SVT = (MVT::SimpleValueType) nVT;
  1093. if (SVT.getVectorElementType() == EltVT
  1094. && SVT.getVectorNumElements() > NElts && isTypeLegal(SVT)) {
  1095. TransformToType[i] = SVT;
  1096. RegisterTypeForVT[i] = SVT;
  1097. NumRegistersForVT[i] = 1;
  1098. ValueTypeActions.setTypeAction(VT, TypeWidenVector);
  1099. IsLegalWiderType = true;
  1100. break;
  1101. }
  1102. }
  1103. if (IsLegalWiderType)
  1104. break;
  1105. LLVM_FALLTHROUGH;
  1106. case TypeSplitVector:
  1107. case TypeScalarizeVector: {
  1108. MVT IntermediateVT;
  1109. MVT RegisterVT;
  1110. unsigned NumIntermediates;
  1111. NumRegistersForVT[i] = getVectorTypeBreakdownMVT(VT, IntermediateVT,
  1112. NumIntermediates, RegisterVT, this);
  1113. RegisterTypeForVT[i] = RegisterVT;
  1114. MVT NVT = VT.getPow2VectorType();
  1115. if (NVT == VT) {
  1116. // Type is already a power of 2. The default action is to split.
  1117. TransformToType[i] = MVT::Other;
  1118. if (PreferredAction == TypeScalarizeVector)
  1119. ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
  1120. else if (PreferredAction == TypeSplitVector)
  1121. ValueTypeActions.setTypeAction(VT, TypeSplitVector);
  1122. else
  1123. // Set type action according to the number of elements.
  1124. ValueTypeActions.setTypeAction(VT, NElts == 1 ? TypeScalarizeVector
  1125. : TypeSplitVector);
  1126. } else {
  1127. TransformToType[i] = NVT;
  1128. ValueTypeActions.setTypeAction(VT, TypeWidenVector);
  1129. }
  1130. break;
  1131. }
  1132. default:
  1133. llvm_unreachable("Unknown vector legalization action!");
  1134. }
  1135. }
  1136. // Determine the 'representative' register class for each value type.
  1137. // An representative register class is the largest (meaning one which is
  1138. // not a sub-register class / subreg register class) legal register class for
  1139. // a group of value types. For example, on i386, i8, i16, and i32
  1140. // representative would be GR32; while on x86_64 it's GR64.
  1141. for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
  1142. const TargetRegisterClass* RRC;
  1143. uint8_t Cost;
  1144. std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
  1145. RepRegClassForVT[i] = RRC;
  1146. RepRegClassCostForVT[i] = Cost;
  1147. }
  1148. }
  1149. EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
  1150. EVT VT) const {
  1151. assert(!VT.isVector() && "No default SetCC type for vectors!");
  1152. return getPointerTy(DL).SimpleTy;
  1153. }
  1154. MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
  1155. return MVT::i32; // return the default value
  1156. }
  1157. /// getVectorTypeBreakdown - Vector types are broken down into some number of
  1158. /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
  1159. /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
  1160. /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
  1161. ///
  1162. /// This method returns the number of registers needed, and the VT for each
  1163. /// register. It also returns the VT and quantity of the intermediate values
  1164. /// before they are promoted/expanded.
  1165. unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
  1166. EVT &IntermediateVT,
  1167. unsigned &NumIntermediates,
  1168. MVT &RegisterVT) const {
  1169. unsigned NumElts = VT.getVectorNumElements();
  1170. // If there is a wider vector type with the same element type as this one,
  1171. // or a promoted vector type that has the same number of elements which
  1172. // are wider, then we should convert to that legal vector type.
  1173. // This handles things like <2 x float> -> <4 x float> and
  1174. // <4 x i1> -> <4 x i32>.
  1175. LegalizeTypeAction TA = getTypeAction(Context, VT);
  1176. if (NumElts != 1 && (TA == TypeWidenVector || TA == TypePromoteInteger)) {
  1177. EVT RegisterEVT = getTypeToTransformTo(Context, VT);
  1178. if (isTypeLegal(RegisterEVT)) {
  1179. IntermediateVT = RegisterEVT;
  1180. RegisterVT = RegisterEVT.getSimpleVT();
  1181. NumIntermediates = 1;
  1182. return 1;
  1183. }
  1184. }
  1185. // Figure out the right, legal destination reg to copy into.
  1186. EVT EltTy = VT.getVectorElementType();
  1187. unsigned NumVectorRegs = 1;
  1188. // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
  1189. // could break down into LHS/RHS like LegalizeDAG does.
  1190. if (!isPowerOf2_32(NumElts)) {
  1191. NumVectorRegs = NumElts;
  1192. NumElts = 1;
  1193. }
  1194. // Divide the input until we get to a supported size. This will always
  1195. // end with a scalar if the target doesn't support vectors.
  1196. while (NumElts > 1 && !isTypeLegal(
  1197. EVT::getVectorVT(Context, EltTy, NumElts))) {
  1198. NumElts >>= 1;
  1199. NumVectorRegs <<= 1;
  1200. }
  1201. NumIntermediates = NumVectorRegs;
  1202. EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
  1203. if (!isTypeLegal(NewVT))
  1204. NewVT = EltTy;
  1205. IntermediateVT = NewVT;
  1206. MVT DestVT = getRegisterType(Context, NewVT);
  1207. RegisterVT = DestVT;
  1208. unsigned NewVTSize = NewVT.getSizeInBits();
  1209. // Convert sizes such as i33 to i64.
  1210. if (!isPowerOf2_32(NewVTSize))
  1211. NewVTSize = NextPowerOf2(NewVTSize);
  1212. if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
  1213. return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
  1214. // Otherwise, promotion or legal types use the same number of registers as
  1215. // the vector decimated to the appropriate level.
  1216. return NumVectorRegs;
  1217. }
  1218. /// Get the EVTs and ArgFlags collections that represent the legalized return
  1219. /// type of the given function. This does not require a DAG or a return value,
  1220. /// and is suitable for use before any DAGs for the function are constructed.
  1221. /// TODO: Move this out of TargetLowering.cpp.
  1222. void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
  1223. AttributeList attr,
  1224. SmallVectorImpl<ISD::OutputArg> &Outs,
  1225. const TargetLowering &TLI, const DataLayout &DL) {
  1226. SmallVector<EVT, 4> ValueVTs;
  1227. ComputeValueVTs(TLI, DL, ReturnType, ValueVTs);
  1228. unsigned NumValues = ValueVTs.size();
  1229. if (NumValues == 0) return;
  1230. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  1231. EVT VT = ValueVTs[j];
  1232. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1233. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
  1234. ExtendKind = ISD::SIGN_EXTEND;
  1235. else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
  1236. ExtendKind = ISD::ZERO_EXTEND;
  1237. // FIXME: C calling convention requires the return type to be promoted to
  1238. // at least 32-bit. But this is not necessary for non-C calling
  1239. // conventions. The frontend should mark functions whose return values
  1240. // require promoting with signext or zeroext attributes.
  1241. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
  1242. MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
  1243. if (VT.bitsLT(MinVT))
  1244. VT = MinVT;
  1245. }
  1246. unsigned NumParts =
  1247. TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT);
  1248. MVT PartVT =
  1249. TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT);
  1250. // 'inreg' on function refers to return value
  1251. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1252. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::InReg))
  1253. Flags.setInReg();
  1254. // Propagate extension type if any
  1255. if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
  1256. Flags.setSExt();
  1257. else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
  1258. Flags.setZExt();
  1259. for (unsigned i = 0; i < NumParts; ++i)
  1260. Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isFixed=*/true, 0, 0));
  1261. }
  1262. }
  1263. /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
  1264. /// function arguments in the caller parameter area. This is the actual
  1265. /// alignment, not its logarithm.
  1266. unsigned TargetLoweringBase::getByValTypeAlignment(Type *Ty,
  1267. const DataLayout &DL) const {
  1268. return DL.getABITypeAlignment(Ty);
  1269. }
  1270. bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
  1271. const DataLayout &DL, EVT VT,
  1272. unsigned AddrSpace,
  1273. unsigned Alignment,
  1274. bool *Fast) const {
  1275. // Check if the specified alignment is sufficient based on the data layout.
  1276. // TODO: While using the data layout works in practice, a better solution
  1277. // would be to implement this check directly (make this a virtual function).
  1278. // For example, the ABI alignment may change based on software platform while
  1279. // this function should only be affected by hardware implementation.
  1280. Type *Ty = VT.getTypeForEVT(Context);
  1281. if (Alignment >= DL.getABITypeAlignment(Ty)) {
  1282. // Assume that an access that meets the ABI-specified alignment is fast.
  1283. if (Fast != nullptr)
  1284. *Fast = true;
  1285. return true;
  1286. }
  1287. // This is a misaligned access.
  1288. return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Fast);
  1289. }
  1290. BranchProbability TargetLoweringBase::getPredictableBranchThreshold() const {
  1291. return BranchProbability(MinPercentageForPredictableBranch, 100);
  1292. }
  1293. //===----------------------------------------------------------------------===//
  1294. // TargetTransformInfo Helpers
  1295. //===----------------------------------------------------------------------===//
  1296. int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
  1297. enum InstructionOpcodes {
  1298. #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
  1299. #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
  1300. #include "llvm/IR/Instruction.def"
  1301. };
  1302. switch (static_cast<InstructionOpcodes>(Opcode)) {
  1303. case Ret: return 0;
  1304. case Br: return 0;
  1305. case Switch: return 0;
  1306. case IndirectBr: return 0;
  1307. case Invoke: return 0;
  1308. case Resume: return 0;
  1309. case Unreachable: return 0;
  1310. case CleanupRet: return 0;
  1311. case CatchRet: return 0;
  1312. case CatchPad: return 0;
  1313. case CatchSwitch: return 0;
  1314. case CleanupPad: return 0;
  1315. case FNeg: return ISD::FNEG;
  1316. case Add: return ISD::ADD;
  1317. case FAdd: return ISD::FADD;
  1318. case Sub: return ISD::SUB;
  1319. case FSub: return ISD::FSUB;
  1320. case Mul: return ISD::MUL;
  1321. case FMul: return ISD::FMUL;
  1322. case UDiv: return ISD::UDIV;
  1323. case SDiv: return ISD::SDIV;
  1324. case FDiv: return ISD::FDIV;
  1325. case URem: return ISD::UREM;
  1326. case SRem: return ISD::SREM;
  1327. case FRem: return ISD::FREM;
  1328. case Shl: return ISD::SHL;
  1329. case LShr: return ISD::SRL;
  1330. case AShr: return ISD::SRA;
  1331. case And: return ISD::AND;
  1332. case Or: return ISD::OR;
  1333. case Xor: return ISD::XOR;
  1334. case Alloca: return 0;
  1335. case Load: return ISD::LOAD;
  1336. case Store: return ISD::STORE;
  1337. case GetElementPtr: return 0;
  1338. case Fence: return 0;
  1339. case AtomicCmpXchg: return 0;
  1340. case AtomicRMW: return 0;
  1341. case Trunc: return ISD::TRUNCATE;
  1342. case ZExt: return ISD::ZERO_EXTEND;
  1343. case SExt: return ISD::SIGN_EXTEND;
  1344. case FPToUI: return ISD::FP_TO_UINT;
  1345. case FPToSI: return ISD::FP_TO_SINT;
  1346. case UIToFP: return ISD::UINT_TO_FP;
  1347. case SIToFP: return ISD::SINT_TO_FP;
  1348. case FPTrunc: return ISD::FP_ROUND;
  1349. case FPExt: return ISD::FP_EXTEND;
  1350. case PtrToInt: return ISD::BITCAST;
  1351. case IntToPtr: return ISD::BITCAST;
  1352. case BitCast: return ISD::BITCAST;
  1353. case AddrSpaceCast: return ISD::ADDRSPACECAST;
  1354. case ICmp: return ISD::SETCC;
  1355. case FCmp: return ISD::SETCC;
  1356. case PHI: return 0;
  1357. case Call: return 0;
  1358. case Select: return ISD::SELECT;
  1359. case UserOp1: return 0;
  1360. case UserOp2: return 0;
  1361. case VAArg: return 0;
  1362. case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
  1363. case InsertElement: return ISD::INSERT_VECTOR_ELT;
  1364. case ShuffleVector: return ISD::VECTOR_SHUFFLE;
  1365. case ExtractValue: return ISD::MERGE_VALUES;
  1366. case InsertValue: return ISD::MERGE_VALUES;
  1367. case LandingPad: return 0;
  1368. }
  1369. llvm_unreachable("Unknown instruction type encountered!");
  1370. }
  1371. std::pair<int, MVT>
  1372. TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL,
  1373. Type *Ty) const {
  1374. LLVMContext &C = Ty->getContext();
  1375. EVT MTy = getValueType(DL, Ty);
  1376. int Cost = 1;
  1377. // We keep legalizing the type until we find a legal kind. We assume that
  1378. // the only operation that costs anything is the split. After splitting
  1379. // we need to handle two types.
  1380. while (true) {
  1381. LegalizeKind LK = getTypeConversion(C, MTy);
  1382. if (LK.first == TypeLegal)
  1383. return std::make_pair(Cost, MTy.getSimpleVT());
  1384. if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger)
  1385. Cost *= 2;
  1386. // Do not loop with f128 type.
  1387. if (MTy == LK.second)
  1388. return std::make_pair(Cost, MTy.getSimpleVT());
  1389. // Keep legalizing the type.
  1390. MTy = LK.second;
  1391. }
  1392. }
  1393. Value *TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
  1394. bool UseTLS) const {
  1395. // compiler-rt provides a variable with a magic name. Targets that do not
  1396. // link with compiler-rt may also provide such a variable.
  1397. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  1398. const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
  1399. auto UnsafeStackPtr =
  1400. dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
  1401. Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
  1402. if (!UnsafeStackPtr) {
  1403. auto TLSModel = UseTLS ?
  1404. GlobalValue::InitialExecTLSModel :
  1405. GlobalValue::NotThreadLocal;
  1406. // The global variable is not defined yet, define it ourselves.
  1407. // We use the initial-exec TLS model because we do not support the
  1408. // variable living anywhere other than in the main executable.
  1409. UnsafeStackPtr = new GlobalVariable(
  1410. *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
  1411. UnsafeStackPtrVar, nullptr, TLSModel);
  1412. } else {
  1413. // The variable exists, check its type and attributes.
  1414. if (UnsafeStackPtr->getValueType() != StackPtrTy)
  1415. report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
  1416. if (UseTLS != UnsafeStackPtr->isThreadLocal())
  1417. report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
  1418. (UseTLS ? "" : "not ") + "be thread-local");
  1419. }
  1420. return UnsafeStackPtr;
  1421. }
  1422. Value *TargetLoweringBase::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
  1423. if (!TM.getTargetTriple().isAndroid())
  1424. return getDefaultSafeStackPointerLocation(IRB, true);
  1425. // Android provides a libc function to retrieve the address of the current
  1426. // thread's unsafe stack pointer.
  1427. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  1428. Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
  1429. FunctionCallee Fn = M->getOrInsertFunction("__safestack_pointer_address",
  1430. StackPtrTy->getPointerTo(0));
  1431. return IRB.CreateCall(Fn);
  1432. }
  1433. //===----------------------------------------------------------------------===//
  1434. // Loop Strength Reduction hooks
  1435. //===----------------------------------------------------------------------===//
  1436. /// isLegalAddressingMode - Return true if the addressing mode represented
  1437. /// by AM is legal for this target, for a load/store of the specified type.
  1438. bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
  1439. const AddrMode &AM, Type *Ty,
  1440. unsigned AS, Instruction *I) const {
  1441. // The default implementation of this implements a conservative RISCy, r+r and
  1442. // r+i addr mode.
  1443. // Allows a sign-extended 16-bit immediate field.
  1444. if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
  1445. return false;
  1446. // No global is ever allowed as a base.
  1447. if (AM.BaseGV)
  1448. return false;
  1449. // Only support r+r,
  1450. switch (AM.Scale) {
  1451. case 0: // "r+i" or just "i", depending on HasBaseReg.
  1452. break;
  1453. case 1:
  1454. if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
  1455. return false;
  1456. // Otherwise we have r+r or r+i.
  1457. break;
  1458. case 2:
  1459. if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
  1460. return false;
  1461. // Allow 2*r as r+r.
  1462. break;
  1463. default: // Don't allow n * r
  1464. return false;
  1465. }
  1466. return true;
  1467. }
  1468. //===----------------------------------------------------------------------===//
  1469. // Stack Protector
  1470. //===----------------------------------------------------------------------===//
  1471. // For OpenBSD return its special guard variable. Otherwise return nullptr,
  1472. // so that SelectionDAG handle SSP.
  1473. Value *TargetLoweringBase::getIRStackGuard(IRBuilder<> &IRB) const {
  1474. if (getTargetMachine().getTargetTriple().isOSOpenBSD()) {
  1475. Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
  1476. PointerType *PtrTy = Type::getInt8PtrTy(M.getContext());
  1477. return M.getOrInsertGlobal("__guard_local", PtrTy);
  1478. }
  1479. return nullptr;
  1480. }
  1481. // Currently only support "standard" __stack_chk_guard.
  1482. // TODO: add LOAD_STACK_GUARD support.
  1483. void TargetLoweringBase::insertSSPDeclarations(Module &M) const {
  1484. if (!M.getNamedValue("__stack_chk_guard"))
  1485. new GlobalVariable(M, Type::getInt8PtrTy(M.getContext()), false,
  1486. GlobalVariable::ExternalLinkage,
  1487. nullptr, "__stack_chk_guard");
  1488. }
  1489. // Currently only support "standard" __stack_chk_guard.
  1490. // TODO: add LOAD_STACK_GUARD support.
  1491. Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const {
  1492. return M.getNamedValue("__stack_chk_guard");
  1493. }
  1494. Value *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const {
  1495. return nullptr;
  1496. }
  1497. unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
  1498. return MinimumJumpTableEntries;
  1499. }
  1500. void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
  1501. MinimumJumpTableEntries = Val;
  1502. }
  1503. unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const {
  1504. return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
  1505. }
  1506. unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
  1507. return MaximumJumpTableSize;
  1508. }
  1509. void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
  1510. MaximumJumpTableSize = Val;
  1511. }
  1512. //===----------------------------------------------------------------------===//
  1513. // Reciprocal Estimates
  1514. //===----------------------------------------------------------------------===//
  1515. /// Get the reciprocal estimate attribute string for a function that will
  1516. /// override the target defaults.
  1517. static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
  1518. const Function &F = MF.getFunction();
  1519. return F.getFnAttribute("reciprocal-estimates").getValueAsString();
  1520. }
  1521. /// Construct a string for the given reciprocal operation of the given type.
  1522. /// This string should match the corresponding option to the front-end's
  1523. /// "-mrecip" flag assuming those strings have been passed through in an
  1524. /// attribute string. For example, "vec-divf" for a division of a vXf32.
  1525. static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
  1526. std::string Name = VT.isVector() ? "vec-" : "";
  1527. Name += IsSqrt ? "sqrt" : "div";
  1528. // TODO: Handle "half" or other float types?
  1529. if (VT.getScalarType() == MVT::f64) {
  1530. Name += "d";
  1531. } else {
  1532. assert(VT.getScalarType() == MVT::f32 &&
  1533. "Unexpected FP type for reciprocal estimate");
  1534. Name += "f";
  1535. }
  1536. return Name;
  1537. }
  1538. /// Return the character position and value (a single numeric character) of a
  1539. /// customized refinement operation in the input string if it exists. Return
  1540. /// false if there is no customized refinement step count.
  1541. static bool parseRefinementStep(StringRef In, size_t &Position,
  1542. uint8_t &Value) {
  1543. const char RefStepToken = ':';
  1544. Position = In.find(RefStepToken);
  1545. if (Position == StringRef::npos)
  1546. return false;
  1547. StringRef RefStepString = In.substr(Position + 1);
  1548. // Allow exactly one numeric character for the additional refinement
  1549. // step parameter.
  1550. if (RefStepString.size() == 1) {
  1551. char RefStepChar = RefStepString[0];
  1552. if (RefStepChar >= '0' && RefStepChar <= '9') {
  1553. Value = RefStepChar - '0';
  1554. return true;
  1555. }
  1556. }
  1557. report_fatal_error("Invalid refinement step for -recip.");
  1558. }
  1559. /// For the input attribute string, return one of the ReciprocalEstimate enum
  1560. /// status values (enabled, disabled, or not specified) for this operation on
  1561. /// the specified data type.
  1562. static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
  1563. if (Override.empty())
  1564. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1565. SmallVector<StringRef, 4> OverrideVector;
  1566. Override.split(OverrideVector, ',');
  1567. unsigned NumArgs = OverrideVector.size();
  1568. // Check if "all", "none", or "default" was specified.
  1569. if (NumArgs == 1) {
  1570. // Look for an optional setting of the number of refinement steps needed
  1571. // for this type of reciprocal operation.
  1572. size_t RefPos;
  1573. uint8_t RefSteps;
  1574. if (parseRefinementStep(Override, RefPos, RefSteps)) {
  1575. // Split the string for further processing.
  1576. Override = Override.substr(0, RefPos);
  1577. }
  1578. // All reciprocal types are enabled.
  1579. if (Override == "all")
  1580. return TargetLoweringBase::ReciprocalEstimate::Enabled;
  1581. // All reciprocal types are disabled.
  1582. if (Override == "none")
  1583. return TargetLoweringBase::ReciprocalEstimate::Disabled;
  1584. // Target defaults for enablement are used.
  1585. if (Override == "default")
  1586. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1587. }
  1588. // The attribute string may omit the size suffix ('f'/'d').
  1589. std::string VTName = getReciprocalOpName(IsSqrt, VT);
  1590. std::string VTNameNoSize = VTName;
  1591. VTNameNoSize.pop_back();
  1592. static const char DisabledPrefix = '!';
  1593. for (StringRef RecipType : OverrideVector) {
  1594. size_t RefPos;
  1595. uint8_t RefSteps;
  1596. if (parseRefinementStep(RecipType, RefPos, RefSteps))
  1597. RecipType = RecipType.substr(0, RefPos);
  1598. // Ignore the disablement token for string matching.
  1599. bool IsDisabled = RecipType[0] == DisabledPrefix;
  1600. if (IsDisabled)
  1601. RecipType = RecipType.substr(1);
  1602. if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
  1603. return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
  1604. : TargetLoweringBase::ReciprocalEstimate::Enabled;
  1605. }
  1606. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1607. }
  1608. /// For the input attribute string, return the customized refinement step count
  1609. /// for this operation on the specified data type. If the step count does not
  1610. /// exist, return the ReciprocalEstimate enum value for unspecified.
  1611. static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
  1612. if (Override.empty())
  1613. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1614. SmallVector<StringRef, 4> OverrideVector;
  1615. Override.split(OverrideVector, ',');
  1616. unsigned NumArgs = OverrideVector.size();
  1617. // Check if "all", "default", or "none" was specified.
  1618. if (NumArgs == 1) {
  1619. // Look for an optional setting of the number of refinement steps needed
  1620. // for this type of reciprocal operation.
  1621. size_t RefPos;
  1622. uint8_t RefSteps;
  1623. if (!parseRefinementStep(Override, RefPos, RefSteps))
  1624. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1625. // Split the string for further processing.
  1626. Override = Override.substr(0, RefPos);
  1627. assert(Override != "none" &&
  1628. "Disabled reciprocals, but specifed refinement steps?");
  1629. // If this is a general override, return the specified number of steps.
  1630. if (Override == "all" || Override == "default")
  1631. return RefSteps;
  1632. }
  1633. // The attribute string may omit the size suffix ('f'/'d').
  1634. std::string VTName = getReciprocalOpName(IsSqrt, VT);
  1635. std::string VTNameNoSize = VTName;
  1636. VTNameNoSize.pop_back();
  1637. for (StringRef RecipType : OverrideVector) {
  1638. size_t RefPos;
  1639. uint8_t RefSteps;
  1640. if (!parseRefinementStep(RecipType, RefPos, RefSteps))
  1641. continue;
  1642. RecipType = RecipType.substr(0, RefPos);
  1643. if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
  1644. return RefSteps;
  1645. }
  1646. return TargetLoweringBase::ReciprocalEstimate::Unspecified;
  1647. }
  1648. int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
  1649. MachineFunction &MF) const {
  1650. return getOpEnabled(true, VT, getRecipEstimateForFunc(MF));
  1651. }
  1652. int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
  1653. MachineFunction &MF) const {
  1654. return getOpEnabled(false, VT, getRecipEstimateForFunc(MF));
  1655. }
  1656. int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
  1657. MachineFunction &MF) const {
  1658. return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF));
  1659. }
  1660. int TargetLoweringBase::getDivRefinementSteps(EVT VT,
  1661. MachineFunction &MF) const {
  1662. return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF));
  1663. }
  1664. void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const {
  1665. MF.getRegInfo().freezeReservedRegs(MF);
  1666. }