RegisterBankEmitter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //===- RegisterBankEmitter.cpp - Generate a Register Bank Desc. -*- C++ -*-===//
  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 tablegen backend is responsible for emitting a description of a target
  10. // register bank for a code generator.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/BitVector.h"
  14. #include "llvm/Support/Debug.h"
  15. #include "llvm/TableGen/Error.h"
  16. #include "llvm/TableGen/Record.h"
  17. #include "llvm/TableGen/TableGenBackend.h"
  18. #include "CodeGenRegisters.h"
  19. #include "CodeGenTarget.h"
  20. #define DEBUG_TYPE "register-bank-emitter"
  21. using namespace llvm;
  22. namespace {
  23. class RegisterBank {
  24. /// A vector of register classes that are included in the register bank.
  25. typedef std::vector<const CodeGenRegisterClass *> RegisterClassesTy;
  26. private:
  27. const Record &TheDef;
  28. /// The register classes that are covered by the register bank.
  29. RegisterClassesTy RCs;
  30. /// The register class with the largest register size.
  31. const CodeGenRegisterClass *RCWithLargestRegsSize;
  32. public:
  33. RegisterBank(const Record &TheDef)
  34. : TheDef(TheDef), RCWithLargestRegsSize(nullptr) {}
  35. /// Get the human-readable name for the bank.
  36. StringRef getName() const { return TheDef.getValueAsString("Name"); }
  37. /// Get the name of the enumerator in the ID enumeration.
  38. std::string getEnumeratorName() const { return (TheDef.getName() + "ID").str(); }
  39. /// Get the name of the array holding the register class coverage data;
  40. std::string getCoverageArrayName() const {
  41. return (TheDef.getName() + "CoverageData").str();
  42. }
  43. /// Get the name of the global instance variable.
  44. StringRef getInstanceVarName() const { return TheDef.getName(); }
  45. const Record &getDef() const { return TheDef; }
  46. /// Get the register classes listed in the RegisterBank.RegisterClasses field.
  47. std::vector<const CodeGenRegisterClass *>
  48. getExplicitlySpecifiedRegisterClasses(
  49. const CodeGenRegBank &RegisterClassHierarchy) const {
  50. std::vector<const CodeGenRegisterClass *> RCs;
  51. for (const auto *RCDef : getDef().getValueAsListOfDefs("RegisterClasses"))
  52. RCs.push_back(RegisterClassHierarchy.getRegClass(RCDef));
  53. return RCs;
  54. }
  55. /// Add a register class to the bank without duplicates.
  56. void addRegisterClass(const CodeGenRegisterClass *RC) {
  57. if (llvm::is_contained(RCs, RC))
  58. return;
  59. // FIXME? We really want the register size rather than the spill size
  60. // since the spill size may be bigger on some targets with
  61. // limited load/store instructions. However, we don't store the
  62. // register size anywhere (we could sum the sizes of the subregisters
  63. // but there may be additional bits too) and we can't derive it from
  64. // the VT's reliably due to Untyped.
  65. if (RCWithLargestRegsSize == nullptr)
  66. RCWithLargestRegsSize = RC;
  67. else if (RCWithLargestRegsSize->RSI.get(DefaultMode).SpillSize <
  68. RC->RSI.get(DefaultMode).SpillSize)
  69. RCWithLargestRegsSize = RC;
  70. assert(RCWithLargestRegsSize && "RC was nullptr?");
  71. RCs.emplace_back(RC);
  72. }
  73. const CodeGenRegisterClass *getRCWithLargestRegsSize() const {
  74. return RCWithLargestRegsSize;
  75. }
  76. iterator_range<typename RegisterClassesTy::const_iterator>
  77. register_classes() const {
  78. return llvm::make_range(RCs.begin(), RCs.end());
  79. }
  80. };
  81. class RegisterBankEmitter {
  82. private:
  83. CodeGenTarget Target;
  84. RecordKeeper &Records;
  85. void emitHeader(raw_ostream &OS, const StringRef TargetName,
  86. const std::vector<RegisterBank> &Banks);
  87. void emitBaseClassDefinition(raw_ostream &OS, const StringRef TargetName,
  88. const std::vector<RegisterBank> &Banks);
  89. void emitBaseClassImplementation(raw_ostream &OS, const StringRef TargetName,
  90. std::vector<RegisterBank> &Banks);
  91. public:
  92. RegisterBankEmitter(RecordKeeper &R) : Target(R), Records(R) {}
  93. void run(raw_ostream &OS);
  94. };
  95. } // end anonymous namespace
  96. /// Emit code to declare the ID enumeration and external global instance
  97. /// variables.
  98. void RegisterBankEmitter::emitHeader(raw_ostream &OS,
  99. const StringRef TargetName,
  100. const std::vector<RegisterBank> &Banks) {
  101. // <Target>RegisterBankInfo.h
  102. OS << "namespace llvm {\n"
  103. << "namespace " << TargetName << " {\n"
  104. << "enum : unsigned {\n";
  105. OS << " InvalidRegBankID = ~0u,\n";
  106. unsigned ID = 0;
  107. for (const auto &Bank : Banks)
  108. OS << " " << Bank.getEnumeratorName() << " = " << ID++ << ",\n";
  109. OS << " NumRegisterBanks,\n"
  110. << "};\n"
  111. << "} // end namespace " << TargetName << "\n"
  112. << "} // end namespace llvm\n";
  113. }
  114. /// Emit declarations of the <Target>GenRegisterBankInfo class.
  115. void RegisterBankEmitter::emitBaseClassDefinition(
  116. raw_ostream &OS, const StringRef TargetName,
  117. const std::vector<RegisterBank> &Banks) {
  118. OS << "private:\n"
  119. << " static RegisterBank *RegBanks[];\n\n"
  120. << "protected:\n"
  121. << " " << TargetName << "GenRegisterBankInfo();\n"
  122. << "\n";
  123. }
  124. /// Visit each register class belonging to the given register bank.
  125. ///
  126. /// A class belongs to the bank iff any of these apply:
  127. /// * It is explicitly specified
  128. /// * It is a subclass of a class that is a member.
  129. /// * It is a class containing subregisters of the registers of a class that
  130. /// is a member. This is known as a subreg-class.
  131. ///
  132. /// This function must be called for each explicitly specified register class.
  133. ///
  134. /// \param RC The register class to search.
  135. /// \param Kind A debug string containing the path the visitor took to reach RC.
  136. /// \param VisitFn The action to take for each class visited. It may be called
  137. /// multiple times for a given class if there are multiple paths
  138. /// to the class.
  139. static void visitRegisterBankClasses(
  140. const CodeGenRegBank &RegisterClassHierarchy,
  141. const CodeGenRegisterClass *RC, const Twine &Kind,
  142. std::function<void(const CodeGenRegisterClass *, StringRef)> VisitFn,
  143. SmallPtrSetImpl<const CodeGenRegisterClass *> &VisitedRCs) {
  144. // Make sure we only visit each class once to avoid infinite loops.
  145. if (!VisitedRCs.insert(RC).second)
  146. return;
  147. // Visit each explicitly named class.
  148. VisitFn(RC, Kind.str());
  149. for (const auto &PossibleSubclass : RegisterClassHierarchy.getRegClasses()) {
  150. std::string TmpKind =
  151. (Kind + " (" + PossibleSubclass.getName() + ")").str();
  152. // Visit each subclass of an explicitly named class.
  153. if (RC != &PossibleSubclass && RC->hasSubClass(&PossibleSubclass))
  154. visitRegisterBankClasses(RegisterClassHierarchy, &PossibleSubclass,
  155. TmpKind + " " + RC->getName() + " subclass",
  156. VisitFn, VisitedRCs);
  157. // Visit each class that contains only subregisters of RC with a common
  158. // subregister-index.
  159. //
  160. // More precisely, PossibleSubclass is a subreg-class iff Reg:SubIdx is in
  161. // PossibleSubclass for all registers Reg from RC using any
  162. // subregister-index SubReg
  163. for (const auto &SubIdx : RegisterClassHierarchy.getSubRegIndices()) {
  164. BitVector BV(RegisterClassHierarchy.getRegClasses().size());
  165. PossibleSubclass.getSuperRegClasses(&SubIdx, BV);
  166. if (BV.test(RC->EnumValue)) {
  167. std::string TmpKind2 = (Twine(TmpKind) + " " + RC->getName() +
  168. " class-with-subregs: " + RC->getName())
  169. .str();
  170. VisitFn(&PossibleSubclass, TmpKind2);
  171. }
  172. }
  173. }
  174. }
  175. void RegisterBankEmitter::emitBaseClassImplementation(
  176. raw_ostream &OS, StringRef TargetName,
  177. std::vector<RegisterBank> &Banks) {
  178. const CodeGenRegBank &RegisterClassHierarchy = Target.getRegBank();
  179. OS << "namespace llvm {\n"
  180. << "namespace " << TargetName << " {\n";
  181. for (const auto &Bank : Banks) {
  182. std::vector<std::vector<const CodeGenRegisterClass *>> RCsGroupedByWord(
  183. (RegisterClassHierarchy.getRegClasses().size() + 31) / 32);
  184. for (const auto &RC : Bank.register_classes())
  185. RCsGroupedByWord[RC->EnumValue / 32].push_back(RC);
  186. OS << "const uint32_t " << Bank.getCoverageArrayName() << "[] = {\n";
  187. unsigned LowestIdxInWord = 0;
  188. for (const auto &RCs : RCsGroupedByWord) {
  189. OS << " // " << LowestIdxInWord << "-" << (LowestIdxInWord + 31) << "\n";
  190. for (const auto &RC : RCs) {
  191. std::string QualifiedRegClassID =
  192. (Twine(RC->Namespace) + "::" + RC->getName() + "RegClassID").str();
  193. OS << " (1u << (" << QualifiedRegClassID << " - "
  194. << LowestIdxInWord << ")) |\n";
  195. }
  196. OS << " 0,\n";
  197. LowestIdxInWord += 32;
  198. }
  199. OS << "};\n";
  200. }
  201. OS << "\n";
  202. for (const auto &Bank : Banks) {
  203. std::string QualifiedBankID =
  204. (TargetName + "::" + Bank.getEnumeratorName()).str();
  205. const CodeGenRegisterClass &RC = *Bank.getRCWithLargestRegsSize();
  206. unsigned Size = RC.RSI.get(DefaultMode).SpillSize;
  207. OS << "RegisterBank " << Bank.getInstanceVarName() << "(/* ID */ "
  208. << QualifiedBankID << ", /* Name */ \"" << Bank.getName()
  209. << "\", /* Size */ " << Size << ", "
  210. << "/* CoveredRegClasses */ " << Bank.getCoverageArrayName()
  211. << ", /* NumRegClasses */ "
  212. << RegisterClassHierarchy.getRegClasses().size() << ");\n";
  213. }
  214. OS << "} // end namespace " << TargetName << "\n"
  215. << "\n";
  216. OS << "RegisterBank *" << TargetName
  217. << "GenRegisterBankInfo::RegBanks[] = {\n";
  218. for (const auto &Bank : Banks)
  219. OS << " &" << TargetName << "::" << Bank.getInstanceVarName() << ",\n";
  220. OS << "};\n\n";
  221. OS << TargetName << "GenRegisterBankInfo::" << TargetName
  222. << "GenRegisterBankInfo()\n"
  223. << " : RegisterBankInfo(RegBanks, " << TargetName
  224. << "::NumRegisterBanks) {\n"
  225. << " // Assert that RegBank indices match their ID's\n"
  226. << "#ifndef NDEBUG\n"
  227. << " for (auto RB : enumerate(RegBanks))\n"
  228. << " assert(RB.index() == RB.value()->getID() && \"Index != ID\");\n"
  229. << "#endif // NDEBUG\n"
  230. << "}\n"
  231. << "} // end namespace llvm\n";
  232. }
  233. void RegisterBankEmitter::run(raw_ostream &OS) {
  234. StringRef TargetName = Target.getName();
  235. const CodeGenRegBank &RegisterClassHierarchy = Target.getRegBank();
  236. Records.startTimer("Analyze records");
  237. std::vector<RegisterBank> Banks;
  238. for (const auto &V : Records.getAllDerivedDefinitions("RegisterBank")) {
  239. SmallPtrSet<const CodeGenRegisterClass *, 8> VisitedRCs;
  240. RegisterBank Bank(*V);
  241. for (const CodeGenRegisterClass *RC :
  242. Bank.getExplicitlySpecifiedRegisterClasses(RegisterClassHierarchy)) {
  243. visitRegisterBankClasses(
  244. RegisterClassHierarchy, RC, "explicit",
  245. [&Bank](const CodeGenRegisterClass *RC, StringRef Kind) {
  246. LLVM_DEBUG(dbgs()
  247. << "Added " << RC->getName() << "(" << Kind << ")\n");
  248. Bank.addRegisterClass(RC);
  249. },
  250. VisitedRCs);
  251. }
  252. Banks.push_back(Bank);
  253. }
  254. // Warn about ambiguous MIR caused by register bank/class name clashes.
  255. Records.startTimer("Warn ambiguous");
  256. for (const auto &Class : RegisterClassHierarchy.getRegClasses()) {
  257. for (const auto &Bank : Banks) {
  258. if (Bank.getName().lower() == StringRef(Class.getName()).lower()) {
  259. PrintWarning(Bank.getDef().getLoc(), "Register bank names should be "
  260. "distinct from register classes "
  261. "to avoid ambiguous MIR");
  262. PrintNote(Bank.getDef().getLoc(), "RegisterBank was declared here");
  263. PrintNote(Class.getDef()->getLoc(), "RegisterClass was declared here");
  264. }
  265. }
  266. }
  267. Records.startTimer("Emit output");
  268. emitSourceFileHeader("Register Bank Source Fragments", OS);
  269. OS << "#ifdef GET_REGBANK_DECLARATIONS\n"
  270. << "#undef GET_REGBANK_DECLARATIONS\n";
  271. emitHeader(OS, TargetName, Banks);
  272. OS << "#endif // GET_REGBANK_DECLARATIONS\n\n"
  273. << "#ifdef GET_TARGET_REGBANK_CLASS\n"
  274. << "#undef GET_TARGET_REGBANK_CLASS\n";
  275. emitBaseClassDefinition(OS, TargetName, Banks);
  276. OS << "#endif // GET_TARGET_REGBANK_CLASS\n\n"
  277. << "#ifdef GET_TARGET_REGBANK_IMPL\n"
  278. << "#undef GET_TARGET_REGBANK_IMPL\n";
  279. emitBaseClassImplementation(OS, TargetName, Banks);
  280. OS << "#endif // GET_TARGET_REGBANK_IMPL\n";
  281. }
  282. namespace llvm {
  283. void EmitRegisterBank(RecordKeeper &RK, raw_ostream &OS) {
  284. RegisterBankEmitter(RK).run(OS);
  285. }
  286. } // end namespace llvm