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