TargetLoweringBase.cpp 66 KB

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