1 //===- RegisterBankEmitter.cpp - Generate a Register Bank Desc. -*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This tablegen backend is responsible for emitting a description of a target
10 // register bank for a code generator.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenRegisters.h"
15 #include "CodeGenTarget.h"
16 #include "InfoByHwMode.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/TableGen/TableGenBackend.h"
23 #define DEBUG_TYPE "register-bank-emitter"
30 /// A vector of register classes that are included in the register bank.
31 typedef std::vector
<const CodeGenRegisterClass
*> RegisterClassesTy
;
36 /// The register classes that are covered by the register bank.
37 RegisterClassesTy RCs
;
39 /// The register class with the largest register size.
40 std::vector
<const CodeGenRegisterClass
*> RCsWithLargestRegSize
;
43 RegisterBank(const Record
&TheDef
, unsigned NumModeIds
)
44 : TheDef(TheDef
), RCsWithLargestRegSize(NumModeIds
) {}
46 /// Get the human-readable name for the bank.
47 StringRef
getName() const { return TheDef
.getValueAsString("Name"); }
48 /// Get the name of the enumerator in the ID enumeration.
49 std::string
getEnumeratorName() const { return (TheDef
.getName() + "ID").str(); }
51 /// Get the name of the array holding the register class coverage data;
52 std::string
getCoverageArrayName() const {
53 return (TheDef
.getName() + "CoverageData").str();
56 /// Get the name of the global instance variable.
57 StringRef
getInstanceVarName() const { return TheDef
.getName(); }
59 const Record
&getDef() const { return TheDef
; }
61 /// Get the register classes listed in the RegisterBank.RegisterClasses field.
62 std::vector
<const CodeGenRegisterClass
*>
63 getExplicitlySpecifiedRegisterClasses(
64 const CodeGenRegBank
&RegisterClassHierarchy
) const {
65 std::vector
<const CodeGenRegisterClass
*> RCs
;
66 for (const auto *RCDef
: getDef().getValueAsListOfDefs("RegisterClasses"))
67 RCs
.push_back(RegisterClassHierarchy
.getRegClass(RCDef
));
71 /// Add a register class to the bank without duplicates.
72 void addRegisterClass(const CodeGenRegisterClass
*RC
) {
73 if (llvm::is_contained(RCs
, RC
))
76 // FIXME? We really want the register size rather than the spill size
77 // since the spill size may be bigger on some targets with
78 // limited load/store instructions. However, we don't store the
79 // register size anywhere (we could sum the sizes of the subregisters
80 // but there may be additional bits too) and we can't derive it from
81 // the VT's reliably due to Untyped.
82 unsigned NumModeIds
= RCsWithLargestRegSize
.size();
83 for (unsigned M
= 0; M
< NumModeIds
; ++M
) {
84 if (RCsWithLargestRegSize
[M
] == nullptr)
85 RCsWithLargestRegSize
[M
] = RC
;
86 else if (RCsWithLargestRegSize
[M
]->RSI
.get(M
).SpillSize
<
87 RC
->RSI
.get(M
).SpillSize
)
88 RCsWithLargestRegSize
[M
] = RC
;
89 assert(RCsWithLargestRegSize
[M
] && "RC was nullptr?");
95 const CodeGenRegisterClass
*getRCWithLargestRegSize(unsigned HwMode
) const {
96 return RCsWithLargestRegSize
[HwMode
];
99 iterator_range
<typename
RegisterClassesTy::const_iterator
>
100 register_classes() const {
101 return llvm::make_range(RCs
.begin(), RCs
.end());
105 class RegisterBankEmitter
{
107 CodeGenTarget Target
;
108 RecordKeeper
&Records
;
110 void emitHeader(raw_ostream
&OS
, const StringRef TargetName
,
111 const std::vector
<RegisterBank
> &Banks
);
112 void emitBaseClassDefinition(raw_ostream
&OS
, const StringRef TargetName
,
113 const std::vector
<RegisterBank
> &Banks
);
114 void emitBaseClassImplementation(raw_ostream
&OS
, const StringRef TargetName
,
115 std::vector
<RegisterBank
> &Banks
);
118 RegisterBankEmitter(RecordKeeper
&R
) : Target(R
), Records(R
) {}
120 void run(raw_ostream
&OS
);
123 } // end anonymous namespace
125 /// Emit code to declare the ID enumeration and external global instance
127 void RegisterBankEmitter::emitHeader(raw_ostream
&OS
,
128 const StringRef TargetName
,
129 const std::vector
<RegisterBank
> &Banks
) {
130 // <Target>RegisterBankInfo.h
131 OS
<< "namespace llvm {\n"
132 << "namespace " << TargetName
<< " {\n"
133 << "enum : unsigned {\n";
135 OS
<< " InvalidRegBankID = ~0u,\n";
137 for (const auto &Bank
: Banks
)
138 OS
<< " " << Bank
.getEnumeratorName() << " = " << ID
++ << ",\n";
139 OS
<< " NumRegisterBanks,\n"
141 << "} // end namespace " << TargetName
<< "\n"
142 << "} // end namespace llvm\n";
145 /// Emit declarations of the <Target>GenRegisterBankInfo class.
146 void RegisterBankEmitter::emitBaseClassDefinition(
147 raw_ostream
&OS
, const StringRef TargetName
,
148 const std::vector
<RegisterBank
> &Banks
) {
150 << " static const RegisterBank *RegBanks[];\n"
151 << " static const unsigned Sizes[];\n\n"
153 << " " << TargetName
<< "GenRegisterBankInfo(unsigned HwMode = 0);\n"
157 /// Visit each register class belonging to the given register bank.
159 /// A class belongs to the bank iff any of these apply:
160 /// * It is explicitly specified
161 /// * It is a subclass of a class that is a member.
162 /// * It is a class containing subregisters of the registers of a class that
163 /// is a member. This is known as a subreg-class.
165 /// This function must be called for each explicitly specified register class.
167 /// \param RC The register class to search.
168 /// \param Kind A debug string containing the path the visitor took to reach RC.
169 /// \param VisitFn The action to take for each class visited. It may be called
170 /// multiple times for a given class if there are multiple paths
172 static void visitRegisterBankClasses(
173 const CodeGenRegBank
&RegisterClassHierarchy
,
174 const CodeGenRegisterClass
*RC
, const Twine
&Kind
,
175 std::function
<void(const CodeGenRegisterClass
*, StringRef
)> VisitFn
,
176 SmallPtrSetImpl
<const CodeGenRegisterClass
*> &VisitedRCs
) {
178 // Make sure we only visit each class once to avoid infinite loops.
179 if (!VisitedRCs
.insert(RC
).second
)
182 // Visit each explicitly named class.
183 VisitFn(RC
, Kind
.str());
185 for (const auto &PossibleSubclass
: RegisterClassHierarchy
.getRegClasses()) {
186 std::string TmpKind
=
187 (Kind
+ " (" + PossibleSubclass
.getName() + ")").str();
189 // Visit each subclass of an explicitly named class.
190 if (RC
!= &PossibleSubclass
&& RC
->hasSubClass(&PossibleSubclass
))
191 visitRegisterBankClasses(RegisterClassHierarchy
, &PossibleSubclass
,
192 TmpKind
+ " " + RC
->getName() + " subclass",
193 VisitFn
, VisitedRCs
);
195 // Visit each class that contains only subregisters of RC with a common
196 // subregister-index.
198 // More precisely, PossibleSubclass is a subreg-class iff Reg:SubIdx is in
199 // PossibleSubclass for all registers Reg from RC using any
200 // subregister-index SubReg
201 for (const auto &SubIdx
: RegisterClassHierarchy
.getSubRegIndices()) {
202 BitVector
BV(RegisterClassHierarchy
.getRegClasses().size());
203 PossibleSubclass
.getSuperRegClasses(&SubIdx
, BV
);
204 if (BV
.test(RC
->EnumValue
)) {
205 std::string TmpKind2
= (Twine(TmpKind
) + " " + RC
->getName() +
206 " class-with-subregs: " + RC
->getName())
208 VisitFn(&PossibleSubclass
, TmpKind2
);
214 void RegisterBankEmitter::emitBaseClassImplementation(
215 raw_ostream
&OS
, StringRef TargetName
,
216 std::vector
<RegisterBank
> &Banks
) {
217 const CodeGenRegBank
&RegisterClassHierarchy
= Target
.getRegBank();
218 const CodeGenHwModes
&CGH
= Target
.getHwModes();
220 OS
<< "namespace llvm {\n"
221 << "namespace " << TargetName
<< " {\n";
222 for (const auto &Bank
: Banks
) {
223 std::vector
<std::vector
<const CodeGenRegisterClass
*>> RCsGroupedByWord(
224 (RegisterClassHierarchy
.getRegClasses().size() + 31) / 32);
226 for (const auto &RC
: Bank
.register_classes())
227 RCsGroupedByWord
[RC
->EnumValue
/ 32].push_back(RC
);
229 OS
<< "const uint32_t " << Bank
.getCoverageArrayName() << "[] = {\n";
230 unsigned LowestIdxInWord
= 0;
231 for (const auto &RCs
: RCsGroupedByWord
) {
232 OS
<< " // " << LowestIdxInWord
<< "-" << (LowestIdxInWord
+ 31) << "\n";
233 for (const auto &RC
: RCs
) {
234 OS
<< " (1u << (" << RC
->getQualifiedIdName() << " - "
235 << LowestIdxInWord
<< ")) |\n";
238 LowestIdxInWord
+= 32;
244 for (const auto &Bank
: Banks
) {
245 std::string QualifiedBankID
=
246 (TargetName
+ "::" + Bank
.getEnumeratorName()).str();
247 OS
<< "const RegisterBank " << Bank
.getInstanceVarName() << "(/* ID */ "
248 << QualifiedBankID
<< ", /* Name */ \"" << Bank
.getName() << "\", "
249 << "/* CoveredRegClasses */ " << Bank
.getCoverageArrayName()
250 << ", /* NumRegClasses */ "
251 << RegisterClassHierarchy
.getRegClasses().size() << ");\n";
253 OS
<< "} // end namespace " << TargetName
<< "\n"
256 OS
<< "const RegisterBank *" << TargetName
257 << "GenRegisterBankInfo::RegBanks[] = {\n";
258 for (const auto &Bank
: Banks
)
259 OS
<< " &" << TargetName
<< "::" << Bank
.getInstanceVarName() << ",\n";
262 unsigned NumModeIds
= CGH
.getNumModeIds();
263 OS
<< "const unsigned " << TargetName
<< "GenRegisterBankInfo::Sizes[] = {\n";
264 for (unsigned M
= 0; M
< NumModeIds
; ++M
) {
265 OS
<< " // Mode = " << M
<< " (";
266 if (M
== DefaultMode
)
269 OS
<< CGH
.getMode(M
).Name
;
271 for (const auto &Bank
: Banks
) {
272 const CodeGenRegisterClass
&RC
= *Bank
.getRCWithLargestRegSize(M
);
273 unsigned Size
= RC
.RSI
.get(M
).SpillSize
;
274 OS
<< " " << Size
<< ",\n";
279 OS
<< TargetName
<< "GenRegisterBankInfo::" << TargetName
280 << "GenRegisterBankInfo(unsigned HwMode)\n"
281 << " : RegisterBankInfo(RegBanks, " << TargetName
282 << "::NumRegisterBanks, Sizes, HwMode) {\n"
283 << " // Assert that RegBank indices match their ID's\n"
284 << "#ifndef NDEBUG\n"
285 << " for (auto RB : enumerate(RegBanks))\n"
286 << " assert(RB.index() == RB.value()->getID() && \"Index != ID\");\n"
287 << "#endif // NDEBUG\n"
289 << "} // end namespace llvm\n";
292 void RegisterBankEmitter::run(raw_ostream
&OS
) {
293 StringRef TargetName
= Target
.getName();
294 const CodeGenRegBank
&RegisterClassHierarchy
= Target
.getRegBank();
295 const CodeGenHwModes
&CGH
= Target
.getHwModes();
297 Records
.startTimer("Analyze records");
298 std::vector
<RegisterBank
> Banks
;
299 for (const auto &V
: Records
.getAllDerivedDefinitions("RegisterBank")) {
300 SmallPtrSet
<const CodeGenRegisterClass
*, 8> VisitedRCs
;
301 RegisterBank
Bank(*V
, CGH
.getNumModeIds());
303 for (const CodeGenRegisterClass
*RC
:
304 Bank
.getExplicitlySpecifiedRegisterClasses(RegisterClassHierarchy
)) {
305 visitRegisterBankClasses(
306 RegisterClassHierarchy
, RC
, "explicit",
307 [&Bank
](const CodeGenRegisterClass
*RC
, StringRef Kind
) {
309 << "Added " << RC
->getName() << "(" << Kind
<< ")\n");
310 Bank
.addRegisterClass(RC
);
315 Banks
.push_back(Bank
);
318 // Warn about ambiguous MIR caused by register bank/class name clashes.
319 Records
.startTimer("Warn ambiguous");
320 for (const auto &Class
: RegisterClassHierarchy
.getRegClasses()) {
321 for (const auto &Bank
: Banks
) {
322 if (Bank
.getName().lower() == StringRef(Class
.getName()).lower()) {
323 PrintWarning(Bank
.getDef().getLoc(), "Register bank names should be "
324 "distinct from register classes "
325 "to avoid ambiguous MIR");
326 PrintNote(Bank
.getDef().getLoc(), "RegisterBank was declared here");
327 PrintNote(Class
.getDef()->getLoc(), "RegisterClass was declared here");
332 Records
.startTimer("Emit output");
333 emitSourceFileHeader("Register Bank Source Fragments", OS
);
334 OS
<< "#ifdef GET_REGBANK_DECLARATIONS\n"
335 << "#undef GET_REGBANK_DECLARATIONS\n";
336 emitHeader(OS
, TargetName
, Banks
);
337 OS
<< "#endif // GET_REGBANK_DECLARATIONS\n\n"
338 << "#ifdef GET_TARGET_REGBANK_CLASS\n"
339 << "#undef GET_TARGET_REGBANK_CLASS\n";
340 emitBaseClassDefinition(OS
, TargetName
, Banks
);
341 OS
<< "#endif // GET_TARGET_REGBANK_CLASS\n\n"
342 << "#ifdef GET_TARGET_REGBANK_IMPL\n"
343 << "#undef GET_TARGET_REGBANK_IMPL\n";
344 emitBaseClassImplementation(OS
, TargetName
, Banks
);
345 OS
<< "#endif // GET_TARGET_REGBANK_IMPL\n";
348 static TableGen::Emitter::OptClass
<RegisterBankEmitter
>
349 X("gen-register-bank", "Generate registers bank descriptions");