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