CodeGenTarget.cpp 35 KB

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