CodeGenTarget.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper -------------------===//
  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 class wraps target description classes used by the various code
  10. // generation TableGen backends. This makes it easier to access the data and
  11. // provides a single place that needs to check it for validity. All of these
  12. // classes abort on error conditions.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "CodeGenTarget.h"
  16. #include "CodeGenInstruction.h"
  17. #include "CodeGenIntrinsics.h"
  18. #include "CodeGenSchedule.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/Support/CommandLine.h"
  21. #include "llvm/TableGen/Error.h"
  22. #include "llvm/TableGen/Record.h"
  23. #include <algorithm>
  24. using namespace llvm;
  25. cl::OptionCategory AsmParserCat("Options for -gen-asm-parser");
  26. cl::OptionCategory AsmWriterCat("Options for -gen-asm-writer");
  27. static cl::opt<unsigned>
  28. AsmParserNum("asmparsernum", cl::init(0),
  29. cl::desc("Make -gen-asm-parser emit assembly parser #N"),
  30. cl::cat(AsmParserCat));
  31. static cl::opt<unsigned>
  32. AsmWriterNum("asmwriternum", cl::init(0),
  33. cl::desc("Make -gen-asm-writer emit assembly writer #N"),
  34. cl::cat(AsmWriterCat));
  35. /// getValueType - Return the MVT::SimpleValueType that the specified TableGen
  36. /// record corresponds to.
  37. MVT::SimpleValueType llvm::getValueType(Record *Rec) {
  38. return (MVT::SimpleValueType)Rec->getValueAsInt("Value");
  39. }
  40. StringRef llvm::getName(MVT::SimpleValueType T) {
  41. switch (T) {
  42. case MVT::Other: return "UNKNOWN";
  43. case MVT::iPTR: return "TLI.getPointerTy()";
  44. case MVT::iPTRAny: return "TLI.getPointerTy()";
  45. default: return getEnumName(T);
  46. }
  47. }
  48. StringRef llvm::getEnumName(MVT::SimpleValueType T) {
  49. // clang-format off
  50. switch (T) {
  51. case MVT::Other: return "MVT::Other";
  52. case MVT::i1: return "MVT::i1";
  53. case MVT::i2: return "MVT::i2";
  54. case MVT::i4: return "MVT::i4";
  55. case MVT::i8: return "MVT::i8";
  56. case MVT::i16: return "MVT::i16";
  57. case MVT::i32: return "MVT::i32";
  58. case MVT::i64: return "MVT::i64";
  59. case MVT::i128: return "MVT::i128";
  60. case MVT::Any: return "MVT::Any";
  61. case MVT::iAny: return "MVT::iAny";
  62. case MVT::fAny: return "MVT::fAny";
  63. case MVT::vAny: return "MVT::vAny";
  64. case MVT::f16: return "MVT::f16";
  65. case MVT::bf16: return "MVT::bf16";
  66. case MVT::f32: return "MVT::f32";
  67. case MVT::f64: return "MVT::f64";
  68. case MVT::f80: return "MVT::f80";
  69. case MVT::f128: return "MVT::f128";
  70. case MVT::ppcf128: return "MVT::ppcf128";
  71. case MVT::x86mmx: return "MVT::x86mmx";
  72. case MVT::x86amx: return "MVT::x86amx";
  73. case MVT::i64x8: return "MVT::i64x8";
  74. case MVT::Glue: return "MVT::Glue";
  75. case MVT::isVoid: return "MVT::isVoid";
  76. case MVT::v1i1: return "MVT::v1i1";
  77. case MVT::v2i1: return "MVT::v2i1";
  78. case MVT::v4i1: return "MVT::v4i1";
  79. case MVT::v8i1: return "MVT::v8i1";
  80. case MVT::v16i1: return "MVT::v16i1";
  81. case MVT::v32i1: return "MVT::v32i1";
  82. case MVT::v64i1: return "MVT::v64i1";
  83. case MVT::v128i1: return "MVT::v128i1";
  84. case MVT::v256i1: return "MVT::v256i1";
  85. case MVT::v512i1: return "MVT::v512i1";
  86. case MVT::v1024i1: return "MVT::v1024i1";
  87. case MVT::v2048i1: return "MVT::v2048i1";
  88. case MVT::v128i2: return "MVT::v128i2";
  89. case MVT::v256i2: return "MVT::v256i2";
  90. case MVT::v64i4: return "MVT::v64i4";
  91. case MVT::v128i4: return "MVT::v128i4";
  92. case MVT::v1i8: return "MVT::v1i8";
  93. case MVT::v2i8: return "MVT::v2i8";
  94. case MVT::v4i8: return "MVT::v4i8";
  95. case MVT::v8i8: return "MVT::v8i8";
  96. case MVT::v16i8: return "MVT::v16i8";
  97. case MVT::v32i8: return "MVT::v32i8";
  98. case MVT::v64i8: return "MVT::v64i8";
  99. case MVT::v128i8: return "MVT::v128i8";
  100. case MVT::v256i8: return "MVT::v256i8";
  101. case MVT::v512i8: return "MVT::v512i8";
  102. case MVT::v1024i8: return "MVT::v1024i8";
  103. case MVT::v1i16: return "MVT::v1i16";
  104. case MVT::v2i16: return "MVT::v2i16";
  105. case MVT::v3i16: return "MVT::v3i16";
  106. case MVT::v4i16: return "MVT::v4i16";
  107. case MVT::v8i16: return "MVT::v8i16";
  108. case MVT::v16i16: return "MVT::v16i16";
  109. case MVT::v32i16: return "MVT::v32i16";
  110. case MVT::v64i16: return "MVT::v64i16";
  111. case MVT::v128i16: return "MVT::v128i16";
  112. case MVT::v256i16: return "MVT::v256i16";
  113. case MVT::v512i16: return "MVT::v512i16";
  114. case MVT::v1i32: return "MVT::v1i32";
  115. case MVT::v2i32: return "MVT::v2i32";
  116. case MVT::v3i32: return "MVT::v3i32";
  117. case MVT::v4i32: return "MVT::v4i32";
  118. case MVT::v5i32: return "MVT::v5i32";
  119. case MVT::v6i32: return "MVT::v6i32";
  120. case MVT::v7i32: return "MVT::v7i32";
  121. case MVT::v8i32: return "MVT::v8i32";
  122. case MVT::v9i32: return "MVT::v9i32";
  123. case MVT::v10i32: return "MVT::v10i32";
  124. case MVT::v11i32: return "MVT::v11i32";
  125. case MVT::v12i32: return "MVT::v12i32";
  126. case MVT::v16i32: return "MVT::v16i32";
  127. case MVT::v32i32: return "MVT::v32i32";
  128. case MVT::v64i32: return "MVT::v64i32";
  129. case MVT::v128i32: return "MVT::v128i32";
  130. case MVT::v256i32: return "MVT::v256i32";
  131. case MVT::v512i32: return "MVT::v512i32";
  132. case MVT::v1024i32: return "MVT::v1024i32";
  133. case MVT::v2048i32: return "MVT::v2048i32";
  134. case MVT::v1i64: return "MVT::v1i64";
  135. case MVT::v2i64: return "MVT::v2i64";
  136. case MVT::v3i64: return "MVT::v3i64";
  137. case MVT::v4i64: return "MVT::v4i64";
  138. case MVT::v8i64: return "MVT::v8i64";
  139. case MVT::v16i64: return "MVT::v16i64";
  140. case MVT::v32i64: return "MVT::v32i64";
  141. case MVT::v64i64: return "MVT::v64i64";
  142. case MVT::v128i64: return "MVT::v128i64";
  143. case MVT::v256i64: return "MVT::v256i64";
  144. case MVT::v1i128: return "MVT::v1i128";
  145. case MVT::v1f16: return "MVT::v1f16";
  146. case MVT::v2f16: return "MVT::v2f16";
  147. case MVT::v3f16: return "MVT::v3f16";
  148. case MVT::v4f16: return "MVT::v4f16";
  149. case MVT::v8f16: return "MVT::v8f16";
  150. case MVT::v16f16: return "MVT::v16f16";
  151. case MVT::v32f16: return "MVT::v32f16";
  152. case MVT::v64f16: return "MVT::v64f16";
  153. case MVT::v128f16: return "MVT::v128f16";
  154. case MVT::v256f16: return "MVT::v256f16";
  155. case MVT::v512f16: return "MVT::v512f16";
  156. case MVT::v2bf16: return "MVT::v2bf16";
  157. case MVT::v3bf16: return "MVT::v3bf16";
  158. case MVT::v4bf16: return "MVT::v4bf16";
  159. case MVT::v8bf16: return "MVT::v8bf16";
  160. case MVT::v16bf16: return "MVT::v16bf16";
  161. case MVT::v32bf16: return "MVT::v32bf16";
  162. case MVT::v64bf16: return "MVT::v64bf16";
  163. case MVT::v128bf16: return "MVT::v128bf16";
  164. case MVT::v1f32: return "MVT::v1f32";
  165. case MVT::v2f32: return "MVT::v2f32";
  166. case MVT::v3f32: return "MVT::v3f32";
  167. case MVT::v4f32: return "MVT::v4f32";
  168. case MVT::v5f32: return "MVT::v5f32";
  169. case MVT::v6f32: return "MVT::v6f32";
  170. case MVT::v7f32: return "MVT::v7f32";
  171. case MVT::v8f32: return "MVT::v8f32";
  172. case MVT::v9f32: return "MVT::v9f32";
  173. case MVT::v10f32: return "MVT::v10f32";
  174. case MVT::v11f32: return "MVT::v11f32";
  175. case MVT::v12f32: return "MVT::v12f32";
  176. case MVT::v16f32: return "MVT::v16f32";
  177. case MVT::v32f32: return "MVT::v32f32";
  178. case MVT::v64f32: return "MVT::v64f32";
  179. case MVT::v128f32: return "MVT::v128f32";
  180. case MVT::v256f32: return "MVT::v256f32";
  181. case MVT::v512f32: return "MVT::v512f32";
  182. case MVT::v1024f32: return "MVT::v1024f32";
  183. case MVT::v2048f32: return "MVT::v2048f32";
  184. case MVT::v1f64: return "MVT::v1f64";
  185. case MVT::v2f64: return "MVT::v2f64";
  186. case MVT::v3f64: return "MVT::v3f64";
  187. case MVT::v4f64: return "MVT::v4f64";
  188. case MVT::v8f64: return "MVT::v8f64";
  189. case MVT::v16f64: return "MVT::v16f64";
  190. case MVT::v32f64: return "MVT::v32f64";
  191. case MVT::v64f64: return "MVT::v64f64";
  192. case MVT::v128f64: return "MVT::v128f64";
  193. case MVT::v256f64: return "MVT::v256f64";
  194. case MVT::nxv1i1: return "MVT::nxv1i1";
  195. case MVT::nxv2i1: return "MVT::nxv2i1";
  196. case MVT::nxv4i1: return "MVT::nxv4i1";
  197. case MVT::nxv8i1: return "MVT::nxv8i1";
  198. case MVT::nxv16i1: return "MVT::nxv16i1";
  199. case MVT::nxv32i1: return "MVT::nxv32i1";
  200. case MVT::nxv64i1: return "MVT::nxv64i1";
  201. case MVT::nxv1i8: return "MVT::nxv1i8";
  202. case MVT::nxv2i8: return "MVT::nxv2i8";
  203. case MVT::nxv4i8: return "MVT::nxv4i8";
  204. case MVT::nxv8i8: return "MVT::nxv8i8";
  205. case MVT::nxv16i8: return "MVT::nxv16i8";
  206. case MVT::nxv32i8: return "MVT::nxv32i8";
  207. case MVT::nxv64i8: return "MVT::nxv64i8";
  208. case MVT::nxv1i16: return "MVT::nxv1i16";
  209. case MVT::nxv2i16: return "MVT::nxv2i16";
  210. case MVT::nxv4i16: return "MVT::nxv4i16";
  211. case MVT::nxv8i16: return "MVT::nxv8i16";
  212. case MVT::nxv16i16: return "MVT::nxv16i16";
  213. case MVT::nxv32i16: return "MVT::nxv32i16";
  214. case MVT::nxv1i32: return "MVT::nxv1i32";
  215. case MVT::nxv2i32: return "MVT::nxv2i32";
  216. case MVT::nxv4i32: return "MVT::nxv4i32";
  217. case MVT::nxv8i32: return "MVT::nxv8i32";
  218. case MVT::nxv16i32: return "MVT::nxv16i32";
  219. case MVT::nxv32i32: return "MVT::nxv32i32";
  220. case MVT::nxv1i64: return "MVT::nxv1i64";
  221. case MVT::nxv2i64: return "MVT::nxv2i64";
  222. case MVT::nxv4i64: return "MVT::nxv4i64";
  223. case MVT::nxv8i64: return "MVT::nxv8i64";
  224. case MVT::nxv16i64: return "MVT::nxv16i64";
  225. case MVT::nxv32i64: return "MVT::nxv32i64";
  226. case MVT::nxv1f16: return "MVT::nxv1f16";
  227. case MVT::nxv2f16: return "MVT::nxv2f16";
  228. case MVT::nxv4f16: return "MVT::nxv4f16";
  229. case MVT::nxv8f16: return "MVT::nxv8f16";
  230. case MVT::nxv16f16: return "MVT::nxv16f16";
  231. case MVT::nxv32f16: return "MVT::nxv32f16";
  232. case MVT::nxv1bf16: return "MVT::nxv1bf16";
  233. case MVT::nxv2bf16: return "MVT::nxv2bf16";
  234. case MVT::nxv4bf16: return "MVT::nxv4bf16";
  235. case MVT::nxv8bf16: return "MVT::nxv8bf16";
  236. case MVT::nxv16bf16: return "MVT::nxv16bf16";
  237. case MVT::nxv32bf16: return "MVT::nxv32bf16";
  238. case MVT::nxv1f32: return "MVT::nxv1f32";
  239. case MVT::nxv2f32: return "MVT::nxv2f32";
  240. case MVT::nxv4f32: return "MVT::nxv4f32";
  241. case MVT::nxv8f32: return "MVT::nxv8f32";
  242. case MVT::nxv16f32: return "MVT::nxv16f32";
  243. case MVT::nxv1f64: return "MVT::nxv1f64";
  244. case MVT::nxv2f64: return "MVT::nxv2f64";
  245. case MVT::nxv4f64: return "MVT::nxv4f64";
  246. case MVT::nxv8f64: return "MVT::nxv8f64";
  247. case MVT::token: return "MVT::token";
  248. case MVT::Metadata: return "MVT::Metadata";
  249. case MVT::iPTR: return "MVT::iPTR";
  250. case MVT::iPTRAny: return "MVT::iPTRAny";
  251. case MVT::Untyped: return "MVT::Untyped";
  252. case MVT::funcref: return "MVT::funcref";
  253. case MVT::externref: return "MVT::externref";
  254. default: llvm_unreachable("ILLEGAL VALUE TYPE!");
  255. }
  256. // clang-format on
  257. }
  258. /// getQualifiedName - Return the name of the specified record, with a
  259. /// namespace qualifier if the record contains one.
  260. ///
  261. std::string llvm::getQualifiedName(const Record *R) {
  262. std::string Namespace;
  263. if (R->getValue("Namespace"))
  264. Namespace = std::string(R->getValueAsString("Namespace"));
  265. if (Namespace.empty())
  266. return std::string(R->getName());
  267. return Namespace + "::" + R->getName().str();
  268. }
  269. /// getTarget - Return the current instance of the Target class.
  270. ///
  271. CodeGenTarget::CodeGenTarget(RecordKeeper &records)
  272. : Records(records), CGH(records) {
  273. std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
  274. if (Targets.size() == 0)
  275. PrintFatalError("No 'Target' subclasses defined!");
  276. if (Targets.size() != 1)
  277. PrintFatalError("Multiple subclasses of Target defined!");
  278. TargetRec = Targets[0];
  279. }
  280. CodeGenTarget::~CodeGenTarget() {
  281. }
  282. StringRef CodeGenTarget::getName() const { return TargetRec->getName(); }
  283. /// getInstNamespace - Find and return the target machine's instruction
  284. /// namespace. The namespace is cached because it is requested multiple times.
  285. StringRef CodeGenTarget::getInstNamespace() const {
  286. if (InstNamespace.empty()) {
  287. for (const CodeGenInstruction *Inst : getInstructionsByEnumValue()) {
  288. // We are not interested in the "TargetOpcode" namespace.
  289. if (Inst->Namespace != "TargetOpcode") {
  290. InstNamespace = Inst->Namespace;
  291. break;
  292. }
  293. }
  294. }
  295. return InstNamespace;
  296. }
  297. StringRef CodeGenTarget::getRegNamespace() const {
  298. auto &RegClasses = RegBank->getRegClasses();
  299. return RegClasses.size() > 0 ? RegClasses.front().Namespace : "";
  300. }
  301. Record *CodeGenTarget::getInstructionSet() const {
  302. return TargetRec->getValueAsDef("InstructionSet");
  303. }
  304. bool CodeGenTarget::getAllowRegisterRenaming() const {
  305. return TargetRec->getValueAsInt("AllowRegisterRenaming");
  306. }
  307. /// getAsmParser - Return the AssemblyParser definition for this target.
  308. ///
  309. Record *CodeGenTarget::getAsmParser() const {
  310. std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyParsers");
  311. if (AsmParserNum >= LI.size())
  312. PrintFatalError("Target does not have an AsmParser #" +
  313. Twine(AsmParserNum) + "!");
  314. return LI[AsmParserNum];
  315. }
  316. /// getAsmParserVariant - Return the AssemblyParserVariant definition for
  317. /// this target.
  318. ///
  319. Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
  320. std::vector<Record*> LI =
  321. TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
  322. if (i >= LI.size())
  323. PrintFatalError("Target does not have an AsmParserVariant #" + Twine(i) +
  324. "!");
  325. return LI[i];
  326. }
  327. /// getAsmParserVariantCount - Return the AssemblyParserVariant definition
  328. /// available for this target.
  329. ///
  330. unsigned CodeGenTarget::getAsmParserVariantCount() const {
  331. std::vector<Record*> LI =
  332. TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
  333. return LI.size();
  334. }
  335. /// getAsmWriter - Return the AssemblyWriter definition for this target.
  336. ///
  337. Record *CodeGenTarget::getAsmWriter() const {
  338. std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
  339. if (AsmWriterNum >= LI.size())
  340. PrintFatalError("Target does not have an AsmWriter #" +
  341. Twine(AsmWriterNum) + "!");
  342. return LI[AsmWriterNum];
  343. }
  344. CodeGenRegBank &CodeGenTarget::getRegBank() const {
  345. if (!RegBank)
  346. RegBank = std::make_unique<CodeGenRegBank>(Records, getHwModes());
  347. return *RegBank;
  348. }
  349. std::optional<CodeGenRegisterClass *> CodeGenTarget::getSuperRegForSubReg(
  350. const ValueTypeByHwMode &ValueTy, CodeGenRegBank &RegBank,
  351. const CodeGenSubRegIndex *SubIdx, bool MustBeAllocatable) const {
  352. std::vector<CodeGenRegisterClass *> Candidates;
  353. auto &RegClasses = RegBank.getRegClasses();
  354. // Try to find a register class which supports ValueTy, and also contains
  355. // SubIdx.
  356. for (CodeGenRegisterClass &RC : RegClasses) {
  357. // Is there a subclass of this class which contains this subregister index?
  358. CodeGenRegisterClass *SubClassWithSubReg = RC.getSubClassWithSubReg(SubIdx);
  359. if (!SubClassWithSubReg)
  360. continue;
  361. // We have a class. Check if it supports this value type.
  362. if (!llvm::is_contained(SubClassWithSubReg->VTs, ValueTy))
  363. continue;
  364. // If necessary, check that it is allocatable.
  365. if (MustBeAllocatable && !SubClassWithSubReg->Allocatable)
  366. continue;
  367. // We have a register class which supports both the value type and
  368. // subregister index. Remember it.
  369. Candidates.push_back(SubClassWithSubReg);
  370. }
  371. // If we didn't find anything, we're done.
  372. if (Candidates.empty())
  373. return std::nullopt;
  374. // Find and return the largest of our candidate classes.
  375. llvm::stable_sort(Candidates, [&](const CodeGenRegisterClass *A,
  376. const CodeGenRegisterClass *B) {
  377. if (A->getMembers().size() > B->getMembers().size())
  378. return true;
  379. if (A->getMembers().size() < B->getMembers().size())
  380. return false;
  381. // Order by name as a tie-breaker.
  382. return StringRef(A->getName()) < B->getName();
  383. });
  384. return Candidates[0];
  385. }
  386. void CodeGenTarget::ReadRegAltNameIndices() const {
  387. RegAltNameIndices = Records.getAllDerivedDefinitions("RegAltNameIndex");
  388. llvm::sort(RegAltNameIndices, LessRecord());
  389. }
  390. /// getRegisterByName - If there is a register with the specific AsmName,
  391. /// return it.
  392. const CodeGenRegister *CodeGenTarget::getRegisterByName(StringRef Name) const {
  393. return getRegBank().getRegistersByName().lookup(Name);
  394. }
  395. std::vector<ValueTypeByHwMode> CodeGenTarget::getRegisterVTs(Record *R)
  396. const {
  397. const CodeGenRegister *Reg = getRegBank().getReg(R);
  398. std::vector<ValueTypeByHwMode> Result;
  399. for (const auto &RC : getRegBank().getRegClasses()) {
  400. if (RC.contains(Reg)) {
  401. ArrayRef<ValueTypeByHwMode> InVTs = RC.getValueTypes();
  402. llvm::append_range(Result, InVTs);
  403. }
  404. }
  405. // Remove duplicates.
  406. llvm::sort(Result);
  407. Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
  408. return Result;
  409. }
  410. void CodeGenTarget::ReadLegalValueTypes() const {
  411. for (const auto &RC : getRegBank().getRegClasses())
  412. llvm::append_range(LegalValueTypes, RC.VTs);
  413. // Remove duplicates.
  414. llvm::sort(LegalValueTypes);
  415. LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
  416. LegalValueTypes.end()),
  417. LegalValueTypes.end());
  418. }
  419. CodeGenSchedModels &CodeGenTarget::getSchedModels() const {
  420. if (!SchedModels)
  421. SchedModels = std::make_unique<CodeGenSchedModels>(Records, *this);
  422. return *SchedModels;
  423. }
  424. void CodeGenTarget::ReadInstructions() const {
  425. std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
  426. if (Insts.size() <= 2)
  427. PrintFatalError("No 'Instruction' subclasses defined!");
  428. // Parse the instructions defined in the .td file.
  429. for (unsigned i = 0, e = Insts.size(); i != e; ++i)
  430. Instructions[Insts[i]] = std::make_unique<CodeGenInstruction>(Insts[i]);
  431. }
  432. static const CodeGenInstruction *
  433. GetInstByName(const char *Name,
  434. const DenseMap<const Record*,
  435. std::unique_ptr<CodeGenInstruction>> &Insts,
  436. RecordKeeper &Records) {
  437. const Record *Rec = Records.getDef(Name);
  438. const auto I = Insts.find(Rec);
  439. if (!Rec || I == Insts.end())
  440. PrintFatalError(Twine("Could not find '") + Name + "' instruction!");
  441. return I->second.get();
  442. }
  443. static const char *FixedInstrs[] = {
  444. #define HANDLE_TARGET_OPCODE(OPC) #OPC,
  445. #include "llvm/Support/TargetOpcodes.def"
  446. nullptr};
  447. unsigned CodeGenTarget::getNumFixedInstructions() {
  448. return std::size(FixedInstrs) - 1;
  449. }
  450. /// Return all of the instructions defined by the target, ordered by
  451. /// their enum value.
  452. void CodeGenTarget::ComputeInstrsByEnum() const {
  453. const auto &Insts = getInstructions();
  454. for (const char *const *p = FixedInstrs; *p; ++p) {
  455. const CodeGenInstruction *Instr = GetInstByName(*p, Insts, Records);
  456. assert(Instr && "Missing target independent instruction");
  457. assert(Instr->Namespace == "TargetOpcode" && "Bad namespace");
  458. InstrsByEnum.push_back(Instr);
  459. }
  460. unsigned EndOfPredefines = InstrsByEnum.size();
  461. assert(EndOfPredefines == getNumFixedInstructions() &&
  462. "Missing generic opcode");
  463. for (const auto &I : Insts) {
  464. const CodeGenInstruction *CGI = I.second.get();
  465. if (CGI->Namespace != "TargetOpcode") {
  466. InstrsByEnum.push_back(CGI);
  467. if (CGI->TheDef->getValueAsBit("isPseudo"))
  468. ++NumPseudoInstructions;
  469. }
  470. }
  471. assert(InstrsByEnum.size() == Insts.size() && "Missing predefined instr");
  472. // All of the instructions are now in random order based on the map iteration.
  473. llvm::sort(
  474. InstrsByEnum.begin() + EndOfPredefines, InstrsByEnum.end(),
  475. [](const CodeGenInstruction *Rec1, const CodeGenInstruction *Rec2) {
  476. const auto &D1 = *Rec1->TheDef;
  477. const auto &D2 = *Rec2->TheDef;
  478. return std::make_tuple(!D1.getValueAsBit("isPseudo"), D1.getName()) <
  479. std::make_tuple(!D2.getValueAsBit("isPseudo"), D2.getName());
  480. });
  481. }
  482. /// isLittleEndianEncoding - Return whether this target encodes its instruction
  483. /// in little-endian format, i.e. bits laid out in the order [0..n]
  484. ///
  485. bool CodeGenTarget::isLittleEndianEncoding() const {
  486. return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
  487. }
  488. /// reverseBitsForLittleEndianEncoding - For little-endian instruction bit
  489. /// encodings, reverse the bit order of all instructions.
  490. void CodeGenTarget::reverseBitsForLittleEndianEncoding() {
  491. if (!isLittleEndianEncoding())
  492. return;
  493. std::vector<Record *> Insts =
  494. Records.getAllDerivedDefinitions("InstructionEncoding");
  495. for (Record *R : Insts) {
  496. if (R->getValueAsString("Namespace") == "TargetOpcode" ||
  497. R->getValueAsBit("isPseudo"))
  498. continue;
  499. BitsInit *BI = R->getValueAsBitsInit("Inst");
  500. unsigned numBits = BI->getNumBits();
  501. SmallVector<Init *, 16> NewBits(numBits);
  502. for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
  503. unsigned bitSwapIdx = numBits - bit - 1;
  504. Init *OrigBit = BI->getBit(bit);
  505. Init *BitSwap = BI->getBit(bitSwapIdx);
  506. NewBits[bit] = BitSwap;
  507. NewBits[bitSwapIdx] = OrigBit;
  508. }
  509. if (numBits % 2) {
  510. unsigned middle = (numBits + 1) / 2;
  511. NewBits[middle] = BI->getBit(middle);
  512. }
  513. BitsInit *NewBI = BitsInit::get(Records, NewBits);
  514. // Update the bits in reversed order so that emitInstrOpBits will get the
  515. // correct endianness.
  516. R->getValue("Inst")->setValue(NewBI);
  517. }
  518. }
  519. /// guessInstructionProperties - Return true if it's OK to guess instruction
  520. /// properties instead of raising an error.
  521. ///
  522. /// This is configurable as a temporary migration aid. It will eventually be
  523. /// permanently false.
  524. bool CodeGenTarget::guessInstructionProperties() const {
  525. return getInstructionSet()->getValueAsBit("guessInstructionProperties");
  526. }
  527. //===----------------------------------------------------------------------===//
  528. // ComplexPattern implementation
  529. //
  530. ComplexPattern::ComplexPattern(Record *R) {
  531. Ty = R->getValueAsDef("Ty");
  532. NumOperands = R->getValueAsInt("NumOperands");
  533. SelectFunc = std::string(R->getValueAsString("SelectFunc"));
  534. RootNodes = R->getValueAsListOfDefs("RootNodes");
  535. // FIXME: This is a hack to statically increase the priority of patterns which
  536. // maps a sub-dag to a complex pattern. e.g. favors LEA over ADD. To get best
  537. // possible pattern match we'll need to dynamically calculate the complexity
  538. // of all patterns a dag can potentially map to.
  539. int64_t RawComplexity = R->getValueAsInt("Complexity");
  540. if (RawComplexity == -1)
  541. Complexity = NumOperands * 3;
  542. else
  543. Complexity = RawComplexity;
  544. // FIXME: Why is this different from parseSDPatternOperatorProperties?
  545. // Parse the properties.
  546. Properties = 0;
  547. std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
  548. for (unsigned i = 0, e = PropList.size(); i != e; ++i)
  549. if (PropList[i]->getName() == "SDNPHasChain") {
  550. Properties |= 1 << SDNPHasChain;
  551. } else if (PropList[i]->getName() == "SDNPOptInGlue") {
  552. Properties |= 1 << SDNPOptInGlue;
  553. } else if (PropList[i]->getName() == "SDNPMayStore") {
  554. Properties |= 1 << SDNPMayStore;
  555. } else if (PropList[i]->getName() == "SDNPMayLoad") {
  556. Properties |= 1 << SDNPMayLoad;
  557. } else if (PropList[i]->getName() == "SDNPSideEffect") {
  558. Properties |= 1 << SDNPSideEffect;
  559. } else if (PropList[i]->getName() == "SDNPMemOperand") {
  560. Properties |= 1 << SDNPMemOperand;
  561. } else if (PropList[i]->getName() == "SDNPVariadic") {
  562. Properties |= 1 << SDNPVariadic;
  563. } else if (PropList[i]->getName() == "SDNPWantRoot") {
  564. Properties |= 1 << SDNPWantRoot;
  565. } else if (PropList[i]->getName() == "SDNPWantParent") {
  566. Properties |= 1 << SDNPWantParent;
  567. } else {
  568. PrintFatalError(R->getLoc(), "Unsupported SD Node property '" +
  569. PropList[i]->getName() +
  570. "' on ComplexPattern '" + R->getName() +
  571. "'!");
  572. }
  573. }
  574. //===----------------------------------------------------------------------===//
  575. // CodeGenIntrinsic Implementation
  576. //===----------------------------------------------------------------------===//
  577. CodeGenIntrinsicTable::CodeGenIntrinsicTable(const RecordKeeper &RC) {
  578. std::vector<Record *> IntrProperties =
  579. RC.getAllDerivedDefinitions("IntrinsicProperty");
  580. std::vector<Record *> DefaultProperties;
  581. for (Record *Rec : IntrProperties)
  582. if (Rec->getValueAsBit("IsDefault"))
  583. DefaultProperties.push_back(Rec);
  584. std::vector<Record *> Defs = RC.getAllDerivedDefinitions("Intrinsic");
  585. Intrinsics.reserve(Defs.size());
  586. for (unsigned I = 0, e = Defs.size(); I != e; ++I)
  587. Intrinsics.push_back(CodeGenIntrinsic(Defs[I], DefaultProperties));
  588. llvm::sort(Intrinsics,
  589. [](const CodeGenIntrinsic &LHS, const CodeGenIntrinsic &RHS) {
  590. return std::tie(LHS.TargetPrefix, LHS.Name) <
  591. std::tie(RHS.TargetPrefix, RHS.Name);
  592. });
  593. Targets.push_back({"", 0, 0});
  594. for (size_t I = 0, E = Intrinsics.size(); I < E; ++I)
  595. if (Intrinsics[I].TargetPrefix != Targets.back().Name) {
  596. Targets.back().Count = I - Targets.back().Offset;
  597. Targets.push_back({Intrinsics[I].TargetPrefix, I, 0});
  598. }
  599. Targets.back().Count = Intrinsics.size() - Targets.back().Offset;
  600. }
  601. CodeGenIntrinsic::CodeGenIntrinsic(Record *R,
  602. std::vector<Record *> DefaultProperties) {
  603. TheDef = R;
  604. std::string DefName = std::string(R->getName());
  605. ArrayRef<SMLoc> DefLoc = R->getLoc();
  606. Properties = 0;
  607. isOverloaded = false;
  608. isCommutative = false;
  609. canThrow = false;
  610. isNoReturn = false;
  611. isNoCallback = false;
  612. isNoSync = false;
  613. isNoFree = false;
  614. isWillReturn = false;
  615. isCold = false;
  616. isNoDuplicate = false;
  617. isNoMerge = false;
  618. isConvergent = false;
  619. isSpeculatable = false;
  620. hasSideEffects = false;
  621. if (DefName.size() <= 4 || DefName.substr(0, 4) != "int_")
  622. PrintFatalError(DefLoc,
  623. "Intrinsic '" + DefName + "' does not start with 'int_'!");
  624. EnumName = DefName.substr(4);
  625. if (R->getValue("ClangBuiltinName")) // Ignore a missing ClangBuiltinName field.
  626. ClangBuiltinName = std::string(R->getValueAsString("ClangBuiltinName"));
  627. if (R->getValue("MSBuiltinName")) // Ignore a missing MSBuiltinName field.
  628. MSBuiltinName = std::string(R->getValueAsString("MSBuiltinName"));
  629. TargetPrefix = std::string(R->getValueAsString("TargetPrefix"));
  630. Name = std::string(R->getValueAsString("LLVMName"));
  631. if (Name == "") {
  632. // If an explicit name isn't specified, derive one from the DefName.
  633. Name = "llvm.";
  634. for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
  635. Name += (EnumName[i] == '_') ? '.' : EnumName[i];
  636. } else {
  637. // Verify it starts with "llvm.".
  638. if (Name.size() <= 5 || Name.substr(0, 5) != "llvm.")
  639. PrintFatalError(DefLoc, "Intrinsic '" + DefName +
  640. "'s name does not start with 'llvm.'!");
  641. }
  642. // If TargetPrefix is specified, make sure that Name starts with
  643. // "llvm.<targetprefix>.".
  644. if (!TargetPrefix.empty()) {
  645. if (Name.size() < 6+TargetPrefix.size() ||
  646. Name.substr(5, 1 + TargetPrefix.size()) != (TargetPrefix + "."))
  647. PrintFatalError(DefLoc, "Intrinsic '" + DefName +
  648. "' does not start with 'llvm." +
  649. TargetPrefix + ".'!");
  650. }
  651. ListInit *RetTypes = R->getValueAsListInit("RetTypes");
  652. ListInit *ParamTypes = R->getValueAsListInit("ParamTypes");
  653. // First collate a list of overloaded types.
  654. std::vector<MVT::SimpleValueType> OverloadedVTs;
  655. for (ListInit *TypeList : {RetTypes, ParamTypes}) {
  656. for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
  657. Record *TyEl = TypeList->getElementAsRecord(i);
  658. assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
  659. if (TyEl->isSubClassOf("LLVMMatchType"))
  660. continue;
  661. MVT::SimpleValueType VT = getValueType(TyEl->getValueAsDef("VT"));
  662. if (MVT(VT).isOverloaded()) {
  663. OverloadedVTs.push_back(VT);
  664. isOverloaded = true;
  665. }
  666. }
  667. }
  668. // Parse the list of return types.
  669. ListInit *TypeList = RetTypes;
  670. for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
  671. Record *TyEl = TypeList->getElementAsRecord(i);
  672. assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
  673. MVT::SimpleValueType VT;
  674. if (TyEl->isSubClassOf("LLVMMatchType")) {
  675. unsigned MatchTy = TyEl->getValueAsInt("Number");
  676. assert(MatchTy < OverloadedVTs.size() &&
  677. "Invalid matching number!");
  678. VT = OverloadedVTs[MatchTy];
  679. // It only makes sense to use the extended and truncated vector element
  680. // variants with iAny types; otherwise, if the intrinsic is not
  681. // overloaded, all the types can be specified directly.
  682. assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
  683. !TyEl->isSubClassOf("LLVMTruncatedType")) ||
  684. VT == MVT::iAny || VT == MVT::vAny) &&
  685. "Expected iAny or vAny type");
  686. } else {
  687. VT = getValueType(TyEl->getValueAsDef("VT"));
  688. }
  689. // Reject invalid types.
  690. if (VT == MVT::isVoid)
  691. PrintFatalError(DefLoc, "Intrinsic '" + DefName +
  692. " has void in result type list!");
  693. IS.RetVTs.push_back(VT);
  694. IS.RetTypeDefs.push_back(TyEl);
  695. }
  696. // Parse the list of parameter types.
  697. TypeList = ParamTypes;
  698. for (unsigned i = 0, e = TypeList->size(); i != e; ++i) {
  699. Record *TyEl = TypeList->getElementAsRecord(i);
  700. assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
  701. MVT::SimpleValueType VT;
  702. if (TyEl->isSubClassOf("LLVMMatchType")) {
  703. unsigned MatchTy = TyEl->getValueAsInt("Number");
  704. if (MatchTy >= OverloadedVTs.size()) {
  705. PrintError(R->getLoc(),
  706. "Parameter #" + Twine(i) + " has out of bounds matching "
  707. "number " + Twine(MatchTy));
  708. PrintFatalError(DefLoc,
  709. Twine("ParamTypes is ") + TypeList->getAsString());
  710. }
  711. VT = OverloadedVTs[MatchTy];
  712. // It only makes sense to use the extended and truncated vector element
  713. // variants with iAny types; otherwise, if the intrinsic is not
  714. // overloaded, all the types can be specified directly.
  715. assert(((!TyEl->isSubClassOf("LLVMExtendedType") &&
  716. !TyEl->isSubClassOf("LLVMTruncatedType")) ||
  717. VT == MVT::iAny || VT == MVT::vAny) &&
  718. "Expected iAny or vAny type");
  719. } else
  720. VT = getValueType(TyEl->getValueAsDef("VT"));
  721. // Reject invalid types.
  722. if (VT == MVT::isVoid && i != e-1 /*void at end means varargs*/)
  723. PrintFatalError(DefLoc, "Intrinsic '" + DefName +
  724. " has void in result type list!");
  725. IS.ParamVTs.push_back(VT);
  726. IS.ParamTypeDefs.push_back(TyEl);
  727. }
  728. // Parse the intrinsic properties.
  729. ListInit *PropList = R->getValueAsListInit("IntrProperties");
  730. for (unsigned i = 0, e = PropList->size(); i != e; ++i) {
  731. Record *Property = PropList->getElementAsRecord(i);
  732. assert(Property->isSubClassOf("IntrinsicProperty") &&
  733. "Expected a property!");
  734. setProperty(Property);
  735. }
  736. // Set default properties to true.
  737. setDefaultProperties(R, DefaultProperties);
  738. // Also record the SDPatternOperator Properties.
  739. Properties = parseSDPatternOperatorProperties(R);
  740. // Sort the argument attributes for later benefit.
  741. for (auto &Attrs : ArgumentAttributes)
  742. llvm::sort(Attrs);
  743. }
  744. void CodeGenIntrinsic::setDefaultProperties(
  745. Record *R, std::vector<Record *> DefaultProperties) {
  746. // opt-out of using default attributes.
  747. if (R->getValueAsBit("DisableDefaultAttributes"))
  748. return;
  749. for (Record *Rec : DefaultProperties)
  750. setProperty(Rec);
  751. }
  752. void CodeGenIntrinsic::setProperty(Record *R) {
  753. if (R->getName() == "IntrNoMem")
  754. ME = MemoryEffects::none();
  755. else if (R->getName() == "IntrReadMem") {
  756. if (ME.onlyWritesMemory())
  757. PrintFatalError(TheDef->getLoc(),
  758. Twine("IntrReadMem cannot be used after IntrNoMem or "
  759. "IntrWriteMem. Default is ReadWrite"));
  760. ME &= MemoryEffects::readOnly();
  761. } else if (R->getName() == "IntrWriteMem") {
  762. if (ME.onlyReadsMemory())
  763. PrintFatalError(TheDef->getLoc(),
  764. Twine("IntrWriteMem cannot be used after IntrNoMem or "
  765. "IntrReadMem. Default is ReadWrite"));
  766. ME &= MemoryEffects::writeOnly();
  767. } else if (R->getName() == "IntrArgMemOnly")
  768. ME &= MemoryEffects::argMemOnly();
  769. else if (R->getName() == "IntrInaccessibleMemOnly")
  770. ME &= MemoryEffects::inaccessibleMemOnly();
  771. else if (R->getName() == "IntrInaccessibleMemOrArgMemOnly")
  772. ME &= MemoryEffects::inaccessibleOrArgMemOnly();
  773. else if (R->getName() == "Commutative")
  774. isCommutative = true;
  775. else if (R->getName() == "Throws")
  776. canThrow = true;
  777. else if (R->getName() == "IntrNoDuplicate")
  778. isNoDuplicate = true;
  779. else if (R->getName() == "IntrNoMerge")
  780. isNoMerge = true;
  781. else if (R->getName() == "IntrConvergent")
  782. isConvergent = true;
  783. else if (R->getName() == "IntrNoReturn")
  784. isNoReturn = true;
  785. else if (R->getName() == "IntrNoCallback")
  786. isNoCallback = true;
  787. else if (R->getName() == "IntrNoSync")
  788. isNoSync = true;
  789. else if (R->getName() == "IntrNoFree")
  790. isNoFree = true;
  791. else if (R->getName() == "IntrWillReturn")
  792. isWillReturn = !isNoReturn;
  793. else if (R->getName() == "IntrCold")
  794. isCold = true;
  795. else if (R->getName() == "IntrSpeculatable")
  796. isSpeculatable = true;
  797. else if (R->getName() == "IntrHasSideEffects")
  798. hasSideEffects = true;
  799. else if (R->isSubClassOf("NoCapture")) {
  800. unsigned ArgNo = R->getValueAsInt("ArgNo");
  801. addArgAttribute(ArgNo, NoCapture);
  802. } else if (R->isSubClassOf("NoAlias")) {
  803. unsigned ArgNo = R->getValueAsInt("ArgNo");
  804. addArgAttribute(ArgNo, NoAlias);
  805. } else if (R->isSubClassOf("NoUndef")) {
  806. unsigned ArgNo = R->getValueAsInt("ArgNo");
  807. addArgAttribute(ArgNo, NoUndef);
  808. } else if (R->isSubClassOf("NonNull")) {
  809. unsigned ArgNo = R->getValueAsInt("ArgNo");
  810. addArgAttribute(ArgNo, NonNull);
  811. } else if (R->isSubClassOf("Returned")) {
  812. unsigned ArgNo = R->getValueAsInt("ArgNo");
  813. addArgAttribute(ArgNo, Returned);
  814. } else if (R->isSubClassOf("ReadOnly")) {
  815. unsigned ArgNo = R->getValueAsInt("ArgNo");
  816. addArgAttribute(ArgNo, ReadOnly);
  817. } else if (R->isSubClassOf("WriteOnly")) {
  818. unsigned ArgNo = R->getValueAsInt("ArgNo");
  819. addArgAttribute(ArgNo, WriteOnly);
  820. } else if (R->isSubClassOf("ReadNone")) {
  821. unsigned ArgNo = R->getValueAsInt("ArgNo");
  822. addArgAttribute(ArgNo, ReadNone);
  823. } else if (R->isSubClassOf("ImmArg")) {
  824. unsigned ArgNo = R->getValueAsInt("ArgNo");
  825. addArgAttribute(ArgNo, ImmArg);
  826. } else if (R->isSubClassOf("Align")) {
  827. unsigned ArgNo = R->getValueAsInt("ArgNo");
  828. uint64_t Align = R->getValueAsInt("Align");
  829. addArgAttribute(ArgNo, Alignment, Align);
  830. } else
  831. llvm_unreachable("Unknown property!");
  832. }
  833. bool CodeGenIntrinsic::isParamAPointer(unsigned ParamIdx) const {
  834. if (ParamIdx >= IS.ParamVTs.size())
  835. return false;
  836. MVT ParamType = MVT(IS.ParamVTs[ParamIdx]);
  837. return ParamType == MVT::iPTR || ParamType == MVT::iPTRAny;
  838. }
  839. bool CodeGenIntrinsic::isParamImmArg(unsigned ParamIdx) const {
  840. // Convert argument index to attribute index starting from `FirstArgIndex`.
  841. ++ParamIdx;
  842. if (ParamIdx >= ArgumentAttributes.size())
  843. return false;
  844. ArgAttribute Val{ImmArg, 0};
  845. return std::binary_search(ArgumentAttributes[ParamIdx].begin(),
  846. ArgumentAttributes[ParamIdx].end(), Val);
  847. }
  848. void CodeGenIntrinsic::addArgAttribute(unsigned Idx, ArgAttrKind AK,
  849. uint64_t V) {
  850. if (Idx >= ArgumentAttributes.size())
  851. ArgumentAttributes.resize(Idx + 1);
  852. ArgumentAttributes[Idx].emplace_back(AK, V);
  853. }