1 //===- RegisterInfoEmitter.cpp - Generate a Register File Desc. -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is responsible for emitting a description of a target
11 // register file for a code generator. It uses instances of the Register,
12 // RegisterAliases, and RegisterClass classes to gather this information.
14 //===----------------------------------------------------------------------===//
16 #include "CodeGenRegisters.h"
17 #include "CodeGenTarget.h"
19 #include "SequenceToOffsetTable.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/SparseBitVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/CodeGen/MachineValueType.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/TableGen/Error.h"
32 #include "llvm/TableGen/Record.h"
33 #include "llvm/TableGen/SetTheory.h"
34 #include "llvm/TableGen/TableGenBackend.h"
49 class RegisterInfoEmitter {
50 RecordKeeper &Records;
53 RegisterInfoEmitter(RecordKeeper &R) : Records(R) {}
55 // runEnums - Print out enum values for all of the registers.
56 void runEnums(raw_ostream &o, CodeGenTarget &Target, CodeGenRegBank &Bank);
58 // runMCDesc - Print out MC register descriptions.
59 void runMCDesc(raw_ostream &o, CodeGenTarget &Target, CodeGenRegBank &Bank);
61 // runTargetHeader - Emit a header fragment for the register info emitter.
62 void runTargetHeader(raw_ostream &o, CodeGenTarget &Target,
63 CodeGenRegBank &Bank);
65 // runTargetDesc - Output the target register and register file descriptions.
66 void runTargetDesc(raw_ostream &o, CodeGenTarget &Target,
67 CodeGenRegBank &Bank);
69 // run - Output the register file description.
70 void run(raw_ostream &o);
73 void EmitRegMapping(raw_ostream &o, const std::deque<CodeGenRegister> &Regs,
75 void EmitRegMappingTables(raw_ostream &o,
76 const std::deque<CodeGenRegister> &Regs,
78 void EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank,
79 const std::string &ClassName);
80 void emitComposeSubRegIndices(raw_ostream &OS, CodeGenRegBank &RegBank,
81 const std::string &ClassName);
82 void emitComposeSubRegIndexLaneMask(raw_ostream &OS, CodeGenRegBank &RegBank,
83 const std::string &ClassName);
86 } // end anonymous namespace
88 // runEnums - Print out enum values for all of the registers.
89 void RegisterInfoEmitter::runEnums(raw_ostream &OS,
90 CodeGenTarget &Target, CodeGenRegBank &Bank) {
91 const auto &Registers = Bank.getRegisters();
93 // Register enums are stored as uint16_t in the tables. Make sure we'll fit.
94 assert(Registers.size() <= 0xffff && "Too many regs to fit in tables");
96 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace");
98 emitSourceFileHeader("Target Register Enum Values", OS);
100 OS << "\n#ifdef GET_REGINFO_ENUM\n";
101 OS << "#undef GET_REGINFO_ENUM\n\n";
103 OS << "namespace llvm {\n\n";
105 OS << "class MCRegisterClass;\n"
106 << "extern const MCRegisterClass " << Target.getName()
107 << "MCRegisterClasses[];\n\n";
109 if (!Namespace.empty())
110 OS << "namespace " << Namespace << " {\n";
111 OS << "enum {\n NoRegister,\n";
113 for (const auto &Reg : Registers)
114 OS << " " << Reg.getName() << " = " << Reg.EnumValue << ",\n";
115 assert(Registers.size() == Registers.back().EnumValue &&
116 "Register enum value mismatch!");
117 OS << " NUM_TARGET_REGS \t// " << Registers.size()+1 << "\n";
119 if (!Namespace.empty())
120 OS << "} // end namespace " << Namespace << "\n";
122 const auto &RegisterClasses = Bank.getRegClasses();
123 if (!RegisterClasses.empty()) {
125 // RegisterClass enums are stored as uint16_t in the tables.
126 assert(RegisterClasses.size() <= 0xffff &&
127 "Too many register classes to fit in tables");
129 OS << "\n// Register classes\n\n";
130 if (!Namespace.empty())
131 OS << "namespace " << Namespace << " {\n";
133 for (const auto &RC : RegisterClasses)
134 OS << " " << RC.getName() << "RegClassID"
135 << " = " << RC.EnumValue << ",\n";
137 if (!Namespace.empty())
138 OS << "} // end namespace " << Namespace << "\n\n";
141 const std::vector<Record*> &RegAltNameIndices = Target.getRegAltNameIndices();
142 // If the only definition is the default NoRegAltName, we don't need to
144 if (RegAltNameIndices.size() > 1) {
145 OS << "\n// Register alternate name indices\n\n";
146 if (!Namespace.empty())
147 OS << "namespace " << Namespace << " {\n";
149 for (unsigned i = 0, e = RegAltNameIndices.size(); i != e; ++i)
150 OS << " " << RegAltNameIndices[i]->getName() << ",\t// " << i << "\n";
151 OS << " NUM_TARGET_REG_ALT_NAMES = " << RegAltNameIndices.size() << "\n";
153 if (!Namespace.empty())
154 OS << "} // end namespace " << Namespace << "\n\n";
157 auto &SubRegIndices = Bank.getSubRegIndices();
158 if (!SubRegIndices.empty()) {
159 OS << "\n// Subregister indices\n\n";
160 std::string Namespace = SubRegIndices.front().getNamespace();
161 if (!Namespace.empty())
162 OS << "namespace " << Namespace << " {\n";
163 OS << "enum {\n NoSubRegister,\n";
165 for (const auto &Idx : SubRegIndices)
166 OS << " " << Idx.getName() << ",\t// " << ++i << "\n";
167 OS << " NUM_TARGET_SUBREGS\n};\n";
168 if (!Namespace.empty())
169 OS << "} // end namespace " << Namespace << "\n\n";
172 OS << "} // end namespace llvm\n\n";
173 OS << "#endif // GET_REGINFO_ENUM\n\n";
176 static void printInt(raw_ostream &OS, int Val) {
180 void RegisterInfoEmitter::
181 EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank,
182 const std::string &ClassName) {
183 unsigned NumRCs = RegBank.getRegClasses().size();
184 unsigned NumSets = RegBank.getNumRegPressureSets();
186 OS << "/// Get the weight in units of pressure for this register class.\n"
187 << "const RegClassWeight &" << ClassName << "::\n"
188 << "getRegClassWeight(const TargetRegisterClass *RC) const {\n"
189 << " static const RegClassWeight RCWeightTable[] = {\n";
190 for (const auto &RC : RegBank.getRegClasses()) {
191 const CodeGenRegister::Vec &Regs = RC.getMembers();
195 std::vector<unsigned> RegUnits;
196 RC.buildRegUnitSet(RegUnits);
197 OS << " {" << (*Regs.begin())->getWeight(RegBank)
198 << ", " << RegBank.getRegUnitSetWeight(RegUnits);
200 OS << "}, \t// " << RC.getName() << "\n";
203 << " return RCWeightTable[RC->getID()];\n"
206 // Reasonable targets (not ARMv7) have unit weight for all units, so don't
207 // bother generating a table.
208 bool RegUnitsHaveUnitWeight = true;
209 for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
210 UnitIdx < UnitEnd; ++UnitIdx) {
211 if (RegBank.getRegUnit(UnitIdx).Weight > 1)
212 RegUnitsHaveUnitWeight = false;
214 OS << "/// Get the weight in units of pressure for this register unit.\n"
215 << "unsigned " << ClassName << "::\n"
216 << "getRegUnitWeight(unsigned RegUnit) const {\n"
217 << " assert(RegUnit < " << RegBank.getNumNativeRegUnits()
218 << " && \"invalid register unit\");\n";
219 if (!RegUnitsHaveUnitWeight) {
220 OS << " static const uint8_t RUWeightTable[] = {\n ";
221 for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
222 UnitIdx < UnitEnd; ++UnitIdx) {
223 const RegUnit &RU = RegBank.getRegUnit(UnitIdx);
224 assert(RU.Weight < 256 && "RegUnit too heavy");
225 OS << RU.Weight << ", ";
228 << " return RUWeightTable[RegUnit];\n";
231 OS << " // All register units have unit weight.\n"
237 << "// Get the number of dimensions of register pressure.\n"
238 << "unsigned " << ClassName << "::getNumRegPressureSets() const {\n"
239 << " return " << NumSets << ";\n}\n\n";
241 OS << "// Get the name of this register unit pressure set.\n"
242 << "const char *" << ClassName << "::\n"
243 << "getRegPressureSetName(unsigned Idx) const {\n"
244 << " static const char *const PressureNameTable[] = {\n";
245 unsigned MaxRegUnitWeight = 0;
246 for (unsigned i = 0; i < NumSets; ++i ) {
247 const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
248 MaxRegUnitWeight = std::max(MaxRegUnitWeight, RegUnits.Weight);
249 OS << " \"" << RegUnits.Name << "\",\n";
252 << " return PressureNameTable[Idx];\n"
255 OS << "// Get the register unit pressure limit for this dimension.\n"
256 << "// This limit must be adjusted dynamically for reserved registers.\n"
257 << "unsigned " << ClassName << "::\n"
258 << "getRegPressureSetLimit(const MachineFunction &MF, unsigned Idx) const "
260 << " static const " << getMinimalTypeForRange(MaxRegUnitWeight, 32)
261 << " PressureLimitTable[] = {\n";
262 for (unsigned i = 0; i < NumSets; ++i ) {
263 const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
264 OS << " " << RegUnits.Weight << ", \t// " << i << ": "
265 << RegUnits.Name << "\n";
268 << " return PressureLimitTable[Idx];\n"
271 SequenceToOffsetTable<std::vector<int>> PSetsSeqs;
273 // This table may be larger than NumRCs if some register units needed a list
274 // of unit sets that did not correspond to a register class.
275 unsigned NumRCUnitSets = RegBank.getNumRegClassPressureSetLists();
276 std::vector<std::vector<int>> PSets(NumRCUnitSets);
278 for (unsigned i = 0, e = NumRCUnitSets; i != e; ++i) {
279 ArrayRef<unsigned> PSetIDs = RegBank.getRCPressureSetIDs(i);
280 PSets[i].reserve(PSetIDs.size());
281 for (ArrayRef<unsigned>::iterator PSetI = PSetIDs.begin(),
282 PSetE = PSetIDs.end(); PSetI != PSetE; ++PSetI) {
283 PSets[i].push_back(RegBank.getRegPressureSet(*PSetI).Order);
285 std::sort(PSets[i].begin(), PSets[i].end());
286 PSetsSeqs.add(PSets[i]);
291 OS << "/// Table of pressure sets per register class or unit.\n"
292 << "static const int RCSetsTable[] = {\n";
293 PSetsSeqs.emit(OS, printInt, "-1");
296 OS << "/// Get the dimensions of register pressure impacted by this "
297 << "register class.\n"
298 << "/// Returns a -1 terminated array of pressure set IDs\n"
299 << "const int* " << ClassName << "::\n"
300 << "getRegClassPressureSets(const TargetRegisterClass *RC) const {\n";
301 OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size() - 1, 32)
302 << " RCSetStartTable[] = {\n ";
303 for (unsigned i = 0, e = NumRCs; i != e; ++i) {
304 OS << PSetsSeqs.get(PSets[i]) << ",";
307 << " return &RCSetsTable[RCSetStartTable[RC->getID()]];\n"
310 OS << "/// Get the dimensions of register pressure impacted by this "
311 << "register unit.\n"
312 << "/// Returns a -1 terminated array of pressure set IDs\n"
313 << "const int* " << ClassName << "::\n"
314 << "getRegUnitPressureSets(unsigned RegUnit) const {\n"
315 << " assert(RegUnit < " << RegBank.getNumNativeRegUnits()
316 << " && \"invalid register unit\");\n";
317 OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size() - 1, 32)
318 << " RUSetStartTable[] = {\n ";
319 for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
320 UnitIdx < UnitEnd; ++UnitIdx) {
321 OS << PSetsSeqs.get(PSets[RegBank.getRegUnit(UnitIdx).RegClassUnitSetsIdx])
325 << " return &RCSetsTable[RUSetStartTable[RegUnit]];\n"
329 void RegisterInfoEmitter::EmitRegMappingTables(
330 raw_ostream &OS, const std::deque<CodeGenRegister> &Regs, bool isCtor) {
331 // Collect all information about dwarf register numbers
332 typedef std::map<Record*, std::vector<int64_t>, LessRecordRegister> DwarfRegNumsMapTy;
333 DwarfRegNumsMapTy DwarfRegNums;
335 // First, just pull all provided information to the map
336 unsigned maxLength = 0;
337 for (auto &RE : Regs) {
338 Record *Reg = RE.TheDef;
339 std::vector<int64_t> RegNums = Reg->getValueAsListOfInts("DwarfNumbers");
340 maxLength = std::max((size_t)maxLength, RegNums.size());
341 if (DwarfRegNums.count(Reg))
342 PrintWarning(Reg->getLoc(), Twine("DWARF numbers for register ") +
343 getQualifiedName(Reg) + "specified multiple times");
344 DwarfRegNums[Reg] = RegNums;
350 // Now we know maximal length of number list. Append -1's, where needed
351 for (DwarfRegNumsMapTy::iterator
352 I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I)
353 for (unsigned i = I->second.size(), e = maxLength; i != e; ++i)
354 I->second.push_back(-1);
356 StringRef Namespace = Regs.front().TheDef->getValueAsString("Namespace");
358 OS << "// " << Namespace << " Dwarf<->LLVM register mappings.\n";
360 // Emit reverse information about the dwarf register numbers.
361 for (unsigned j = 0; j < 2; ++j) {
362 for (unsigned i = 0, e = maxLength; i != e; ++i) {
363 OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
364 OS << (j == 0 ? "DwarfFlavour" : "EHFlavour");
365 OS << i << "Dwarf2L[]";
370 // Store the mapping sorted by the LLVM reg num so lookup can be done
371 // with a binary search.
372 std::map<uint64_t, Record*> Dwarf2LMap;
373 for (DwarfRegNumsMapTy::iterator
374 I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I) {
375 int DwarfRegNo = I->second[i];
378 Dwarf2LMap[DwarfRegNo] = I->first;
381 for (std::map<uint64_t, Record*>::iterator
382 I = Dwarf2LMap.begin(), E = Dwarf2LMap.end(); I != E; ++I)
383 OS << " { " << I->first << "U, " << getQualifiedName(I->second)
391 // We have to store the size in a const global, it's used in multiple
393 OS << "extern const unsigned " << Namespace
394 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "Dwarf2LSize";
396 OS << " = array_lengthof(" << Namespace
397 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
404 for (auto &RE : Regs) {
405 Record *Reg = RE.TheDef;
406 const RecordVal *V = Reg->getValue("DwarfAlias");
407 if (!V || !V->getValue())
410 DefInit *DI = cast<DefInit>(V->getValue());
411 Record *Alias = DI->getDef();
412 DwarfRegNums[Reg] = DwarfRegNums[Alias];
415 // Emit information about the dwarf register numbers.
416 for (unsigned j = 0; j < 2; ++j) {
417 for (unsigned i = 0, e = maxLength; i != e; ++i) {
418 OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
419 OS << (j == 0 ? "DwarfFlavour" : "EHFlavour");
420 OS << i << "L2Dwarf[]";
423 // Store the mapping sorted by the Dwarf reg num so lookup can be done
424 // with a binary search.
425 for (DwarfRegNumsMapTy::iterator
426 I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I) {
427 int RegNo = I->second[i];
428 if (RegNo == -1) // -1 is the default value, don't emit a mapping.
431 OS << " { " << getQualifiedName(I->first) << ", " << RegNo
439 // We have to store the size in a const global, it's used in multiple
441 OS << "extern const unsigned " << Namespace
442 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2DwarfSize";
444 OS << " = array_lengthof(" << Namespace
445 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2Dwarf);\n\n";
452 void RegisterInfoEmitter::EmitRegMapping(
453 raw_ostream &OS, const std::deque<CodeGenRegister> &Regs, bool isCtor) {
454 // Emit the initializer so the tables from EmitRegMappingTables get wired up
455 // to the MCRegisterInfo object.
456 unsigned maxLength = 0;
457 for (auto &RE : Regs) {
458 Record *Reg = RE.TheDef;
459 maxLength = std::max((size_t)maxLength,
460 Reg->getValueAsListOfInts("DwarfNumbers").size());
466 StringRef Namespace = Regs.front().TheDef->getValueAsString("Namespace");
468 // Emit reverse information about the dwarf register numbers.
469 for (unsigned j = 0; j < 2; ++j) {
472 OS << "DwarfFlavour";
477 << " llvm_unreachable(\"Unknown DWARF flavour\");\n";
479 for (unsigned i = 0, e = maxLength; i != e; ++i) {
480 OS << " case " << i << ":\n";
485 raw_string_ostream(Tmp) << Namespace
486 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
488 OS << "mapDwarfRegsToLLVMRegs(" << Tmp << ", " << Tmp << "Size, ";
499 // Emit information about the dwarf register numbers.
500 for (unsigned j = 0; j < 2; ++j) {
503 OS << "DwarfFlavour";
508 << " llvm_unreachable(\"Unknown DWARF flavour\");\n";
510 for (unsigned i = 0, e = maxLength; i != e; ++i) {
511 OS << " case " << i << ":\n";
516 raw_string_ostream(Tmp) << Namespace
517 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
519 OS << "mapLLVMRegsToDwarfRegs(" << Tmp << ", " << Tmp << "Size, ";
531 // Print a BitVector as a sequence of hex numbers using a little-endian mapping.
532 // Width is the number of bits per hex number.
533 static void printBitVectorAsHex(raw_ostream &OS,
534 const BitVector &Bits,
536 assert(Width <= 32 && "Width too large");
537 unsigned Digits = (Width + 3) / 4;
538 for (unsigned i = 0, e = Bits.size(); i < e; i += Width) {
540 for (unsigned j = 0; j != Width && i + j != e; ++j)
541 Value |= Bits.test(i + j) << j;
542 OS << format("0x%0*x, ", Digits, Value);
546 // Helper to emit a set of bits into a constant byte array.
547 class BitVectorEmitter {
550 void add(unsigned v) {
551 if (v >= Values.size())
552 Values.resize(((v/8)+1)*8); // Round up to the next byte.
556 void print(raw_ostream &OS) {
557 printBitVectorAsHex(OS, Values, 8);
561 static void printSimpleValueType(raw_ostream &OS, MVT::SimpleValueType VT) {
562 OS << getEnumName(VT);
565 static void printSubRegIndex(raw_ostream &OS, const CodeGenSubRegIndex *Idx) {
566 OS << Idx->EnumValue;
569 // Differentially encoded register and regunit lists allow for better
570 // compression on regular register banks. The sequence is computed from the
571 // differential list as:
574 // out[n+1] = out[n] + diff[n]; // n = 0, 1, ...
576 // The initial value depends on the specific list. The list is terminated by a
577 // 0 differential which means we can't encode repeated elements.
579 typedef SmallVector<uint16_t, 4> DiffVec;
580 typedef SmallVector<LaneBitmask, 4> MaskVec;
582 // Differentially encode a sequence of numbers into V. The starting value and
583 // terminating 0 are not added to V, so it will have the same size as List.
585 DiffVec &diffEncode(DiffVec &V, unsigned InitVal, SparseBitVector<> List) {
586 assert(V.empty() && "Clear DiffVec before diffEncode.");
587 uint16_t Val = uint16_t(InitVal);
589 for (uint16_t Cur : List) {
590 V.push_back(Cur - Val);
596 template<typename Iter>
598 DiffVec &diffEncode(DiffVec &V, unsigned InitVal, Iter Begin, Iter End) {
599 assert(V.empty() && "Clear DiffVec before diffEncode.");
600 uint16_t Val = uint16_t(InitVal);
601 for (Iter I = Begin; I != End; ++I) {
602 uint16_t Cur = (*I)->EnumValue;
603 V.push_back(Cur - Val);
609 static void printDiff16(raw_ostream &OS, uint16_t Val) {
613 static void printMask(raw_ostream &OS, LaneBitmask Val) {
614 OS << "LaneBitmask(0x" << PrintLaneMask(Val) << ')';
617 // Try to combine Idx's compose map into Vec if it is compatible.
618 // Return false if it's not possible.
619 static bool combine(const CodeGenSubRegIndex *Idx,
620 SmallVectorImpl<CodeGenSubRegIndex*> &Vec) {
621 const CodeGenSubRegIndex::CompMap &Map = Idx->getComposites();
622 for (const auto &I : Map) {
623 CodeGenSubRegIndex *&Entry = Vec[I.first->EnumValue - 1];
624 if (Entry && Entry != I.second)
628 // All entries are compatible. Make it so.
629 for (const auto &I : Map) {
630 auto *&Entry = Vec[I.first->EnumValue - 1];
631 assert((!Entry || Entry == I.second) &&
632 "Expected EnumValue to be unique");
639 RegisterInfoEmitter::emitComposeSubRegIndices(raw_ostream &OS,
640 CodeGenRegBank &RegBank,
641 const std::string &ClName) {
642 const auto &SubRegIndices = RegBank.getSubRegIndices();
643 OS << "unsigned " << ClName
644 << "::composeSubRegIndicesImpl(unsigned IdxA, unsigned IdxB) const {\n";
646 // Many sub-register indexes are composition-compatible, meaning that
648 // compose(IdxA, IdxB) == compose(IdxA', IdxB)
650 // for many IdxA, IdxA' pairs. Not all sub-register indexes can be composed.
651 // The illegal entries can be use as wildcards to compress the table further.
653 // Map each Sub-register index to a compatible table row.
654 SmallVector<unsigned, 4> RowMap;
655 SmallVector<SmallVector<CodeGenSubRegIndex*, 4>, 4> Rows;
657 auto SubRegIndicesSize =
658 std::distance(SubRegIndices.begin(), SubRegIndices.end());
659 for (const auto &Idx : SubRegIndices) {
660 unsigned Found = ~0u;
661 for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
662 if (combine(&Idx, Rows[r])) {
669 Rows.resize(Found + 1);
670 Rows.back().resize(SubRegIndicesSize);
671 combine(&Idx, Rows.back());
673 RowMap.push_back(Found);
676 // Output the row map if there is multiple rows.
677 if (Rows.size() > 1) {
678 OS << " static const " << getMinimalTypeForRange(Rows.size(), 32)
679 << " RowMap[" << SubRegIndicesSize << "] = {\n ";
680 for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
681 OS << RowMap[i] << ", ";
686 OS << " static const " << getMinimalTypeForRange(SubRegIndicesSize + 1, 32)
687 << " Rows[" << Rows.size() << "][" << SubRegIndicesSize << "] = {\n";
688 for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
690 for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
692 OS << Rows[r][i]->EnumValue << ", ";
699 OS << " --IdxA; assert(IdxA < " << SubRegIndicesSize << ");\n"
700 << " --IdxB; assert(IdxB < " << SubRegIndicesSize << ");\n";
702 OS << " return Rows[RowMap[IdxA]][IdxB];\n";
704 OS << " return Rows[0][IdxB];\n";
709 RegisterInfoEmitter::emitComposeSubRegIndexLaneMask(raw_ostream &OS,
710 CodeGenRegBank &RegBank,
711 const std::string &ClName) {
712 // See the comments in computeSubRegLaneMasks() for our goal here.
713 const auto &SubRegIndices = RegBank.getSubRegIndices();
715 // Create a list of Mask+Rotate operations, with equivalent entries merged.
716 SmallVector<unsigned, 4> SubReg2SequenceIndexMap;
717 SmallVector<SmallVector<MaskRolPair, 1>, 4> Sequences;
718 for (const auto &Idx : SubRegIndices) {
719 const SmallVector<MaskRolPair, 1> &IdxSequence
720 = Idx.CompositionLaneMaskTransform;
722 unsigned Found = ~0u;
725 for (size_t s = 0, se = Sequences.size(); s != se; ++s, SIdx = NextSIdx) {
726 SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
727 NextSIdx = SIdx + Sequence.size() + 1;
728 if (Sequence == IdxSequence) {
734 Sequences.push_back(IdxSequence);
737 SubReg2SequenceIndexMap.push_back(Found);
740 OS << " struct MaskRolOp {\n"
741 " LaneBitmask Mask;\n"
742 " uint8_t RotateLeft;\n"
744 " static const MaskRolOp LaneMaskComposeSequences[] = {\n";
746 for (size_t s = 0, se = Sequences.size(); s != se; ++s) {
748 const SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
749 for (size_t p = 0, pe = Sequence.size(); p != pe; ++p) {
750 const MaskRolPair &P = Sequence[p];
751 printMask(OS << "{ ", P.Mask);
752 OS << format(", %2u }, ", P.RotateLeft);
754 OS << "{ LaneBitmask::getNone(), 0 }";
757 OS << " // Sequence " << Idx << "\n";
758 Idx += Sequence.size() + 1;
761 " static const MaskRolOp *const CompositeSequences[] = {\n";
762 for (size_t i = 0, e = SubRegIndices.size(); i != e; ++i) {
764 unsigned Idx = SubReg2SequenceIndexMap[i];
765 OS << format("&LaneMaskComposeSequences[%u]", Idx);
768 OS << " // to " << SubRegIndices[i].getName() << "\n";
772 OS << "LaneBitmask " << ClName
773 << "::composeSubRegIndexLaneMaskImpl(unsigned IdxA, LaneBitmask LaneMask)"
775 " --IdxA; assert(IdxA < " << SubRegIndices.size()
776 << " && \"Subregister index out of bounds\");\n"
777 " LaneBitmask Result;\n"
778 " for (const MaskRolOp *Ops = CompositeSequences[IdxA]; Ops->Mask.any(); ++Ops) {\n"
779 " LaneBitmask::Type M = LaneMask.getAsInteger() & Ops->Mask.getAsInteger();\n"
780 " if (unsigned S = Ops->RotateLeft)\n"
781 " Result |= LaneBitmask((M << S) | (M >> (LaneBitmask::BitWidth - S)));\n"
783 " Result |= LaneBitmask(M);\n"
788 OS << "LaneBitmask " << ClName
789 << "::reverseComposeSubRegIndexLaneMaskImpl(unsigned IdxA, "
790 " LaneBitmask LaneMask) const {\n"
791 " LaneMask &= getSubRegIndexLaneMask(IdxA);\n"
792 " --IdxA; assert(IdxA < " << SubRegIndices.size()
793 << " && \"Subregister index out of bounds\");\n"
794 " LaneBitmask Result;\n"
795 " for (const MaskRolOp *Ops = CompositeSequences[IdxA]; Ops->Mask.any(); ++Ops) {\n"
796 " LaneBitmask::Type M = LaneMask.getAsInteger();\n"
797 " if (unsigned S = Ops->RotateLeft)\n"
798 " Result |= LaneBitmask((M >> S) | (M << (LaneBitmask::BitWidth - S)));\n"
800 " Result |= LaneBitmask(M);\n"
807 // runMCDesc - Print out MC register descriptions.
810 RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target,
811 CodeGenRegBank &RegBank) {
812 emitSourceFileHeader("MC Register Information", OS);
814 OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
815 OS << "#undef GET_REGINFO_MC_DESC\n\n";
817 const auto &Regs = RegBank.getRegisters();
819 auto &SubRegIndices = RegBank.getSubRegIndices();
820 // The lists of sub-registers and super-registers go in the same array. That
821 // allows us to share suffixes.
822 typedef std::vector<const CodeGenRegister*> RegVec;
824 // Differentially encoded lists.
825 SequenceToOffsetTable<DiffVec> DiffSeqs;
826 SmallVector<DiffVec, 4> SubRegLists(Regs.size());
827 SmallVector<DiffVec, 4> SuperRegLists(Regs.size());
828 SmallVector<DiffVec, 4> RegUnitLists(Regs.size());
829 SmallVector<unsigned, 4> RegUnitInitScale(Regs.size());
831 // List of lane masks accompanying register unit sequences.
832 SequenceToOffsetTable<MaskVec> LaneMaskSeqs;
833 SmallVector<MaskVec, 4> RegUnitLaneMasks(Regs.size());
835 // Keep track of sub-register names as well. These are not differentially
837 typedef SmallVector<const CodeGenSubRegIndex*, 4> SubRegIdxVec;
838 SequenceToOffsetTable<SubRegIdxVec, deref<llvm::less>> SubRegIdxSeqs;
839 SmallVector<SubRegIdxVec, 4> SubRegIdxLists(Regs.size());
841 SequenceToOffsetTable<std::string> RegStrings;
843 // Precompute register lists for the SequenceToOffsetTable.
845 for (auto I = Regs.begin(), E = Regs.end(); I != E; ++I, ++i) {
846 const auto &Reg = *I;
847 RegStrings.add(Reg.getName());
849 // Compute the ordered sub-register list.
850 SetVector<const CodeGenRegister*> SR;
851 Reg.addSubRegsPreOrder(SR, RegBank);
852 diffEncode(SubRegLists[i], Reg.EnumValue, SR.begin(), SR.end());
853 DiffSeqs.add(SubRegLists[i]);
855 // Compute the corresponding sub-register indexes.
856 SubRegIdxVec &SRIs = SubRegIdxLists[i];
857 for (unsigned j = 0, je = SR.size(); j != je; ++j)
858 SRIs.push_back(Reg.getSubRegIndex(SR[j]));
859 SubRegIdxSeqs.add(SRIs);
861 // Super-registers are already computed.
862 const RegVec &SuperRegList = Reg.getSuperRegs();
863 diffEncode(SuperRegLists[i], Reg.EnumValue, SuperRegList.begin(),
865 DiffSeqs.add(SuperRegLists[i]);
867 // Differentially encode the register unit list, seeded by register number.
868 // First compute a scale factor that allows more diff-lists to be reused:
873 // A scale factor of 2 allows D0 and D1 to share a diff-list. The initial
874 // value for the differential decoder is the register number multiplied by
877 // Check the neighboring registers for arithmetic progressions.
878 unsigned ScaleA = ~0u, ScaleB = ~0u;
879 SparseBitVector<> RUs = Reg.getNativeRegUnits();
880 if (I != Regs.begin() &&
881 std::prev(I)->getNativeRegUnits().count() == RUs.count())
882 ScaleB = *RUs.begin() - *std::prev(I)->getNativeRegUnits().begin();
883 if (std::next(I) != Regs.end() &&
884 std::next(I)->getNativeRegUnits().count() == RUs.count())
885 ScaleA = *std::next(I)->getNativeRegUnits().begin() - *RUs.begin();
886 unsigned Scale = std::min(ScaleB, ScaleA);
887 // Default the scale to 0 if it can't be encoded in 4 bits.
890 RegUnitInitScale[i] = Scale;
891 DiffSeqs.add(diffEncode(RegUnitLists[i], Scale * Reg.EnumValue, RUs));
893 const auto &RUMasks = Reg.getRegUnitLaneMasks();
894 MaskVec &LaneMaskVec = RegUnitLaneMasks[i];
895 assert(LaneMaskVec.empty());
896 LaneMaskVec.insert(LaneMaskVec.begin(), RUMasks.begin(), RUMasks.end());
897 // Terminator mask should not be used inside of the list.
899 for (LaneBitmask M : LaneMaskVec) {
900 assert(!M.all() && "terminator mask should not be part of the list");
903 LaneMaskSeqs.add(LaneMaskVec);
906 // Compute the final layout of the sequence table.
908 LaneMaskSeqs.layout();
909 SubRegIdxSeqs.layout();
911 OS << "namespace llvm {\n\n";
913 const std::string &TargetName = Target.getName();
915 // Emit the shared table of differential lists.
916 OS << "extern const MCPhysReg " << TargetName << "RegDiffLists[] = {\n";
917 DiffSeqs.emit(OS, printDiff16);
920 // Emit the shared table of regunit lane mask sequences.
921 OS << "extern const LaneBitmask " << TargetName << "LaneMaskLists[] = {\n";
922 LaneMaskSeqs.emit(OS, printMask, "LaneBitmask::getAll()");
925 // Emit the table of sub-register indexes.
926 OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[] = {\n";
927 SubRegIdxSeqs.emit(OS, printSubRegIndex);
930 // Emit the table of sub-register index sizes.
931 OS << "extern const MCRegisterInfo::SubRegCoveredBits "
932 << TargetName << "SubRegIdxRanges[] = {\n";
933 OS << " { " << (uint16_t)-1 << ", " << (uint16_t)-1 << " },\n";
934 for (const auto &Idx : SubRegIndices) {
935 OS << " { " << Idx.Offset << ", " << Idx.Size << " },\t// "
936 << Idx.getName() << "\n";
940 // Emit the string table.
942 OS << "extern const char " << TargetName << "RegStrings[] = {\n";
943 RegStrings.emit(OS, printChar);
946 OS << "extern const MCRegisterDesc " << TargetName
947 << "RegDesc[] = { // Descriptors\n";
948 OS << " { " << RegStrings.get("") << ", 0, 0, 0, 0, 0 },\n";
950 // Emit the register descriptors now.
952 for (const auto &Reg : Regs) {
953 OS << " { " << RegStrings.get(Reg.getName()) << ", "
954 << DiffSeqs.get(SubRegLists[i]) << ", " << DiffSeqs.get(SuperRegLists[i])
955 << ", " << SubRegIdxSeqs.get(SubRegIdxLists[i]) << ", "
956 << (DiffSeqs.get(RegUnitLists[i]) * 16 + RegUnitInitScale[i]) << ", "
957 << LaneMaskSeqs.get(RegUnitLaneMasks[i]) << " },\n";
960 OS << "};\n\n"; // End of register descriptors...
962 // Emit the table of register unit roots. Each regunit has one or two root
964 OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2] = {\n";
965 for (unsigned i = 0, e = RegBank.getNumNativeRegUnits(); i != e; ++i) {
966 ArrayRef<const CodeGenRegister*> Roots = RegBank.getRegUnit(i).getRoots();
967 assert(!Roots.empty() && "All regunits must have a root register.");
968 assert(Roots.size() <= 2 && "More than two roots not supported yet.");
969 OS << " { " << getQualifiedName(Roots.front()->TheDef);
970 for (unsigned r = 1; r != Roots.size(); ++r)
971 OS << ", " << getQualifiedName(Roots[r]->TheDef);
976 const auto &RegisterClasses = RegBank.getRegClasses();
978 // Loop over all of the register classes... emitting each one.
979 OS << "namespace { // Register classes...\n";
981 SequenceToOffsetTable<std::string> RegClassStrings;
983 // Emit the register enum value arrays for each RegisterClass
984 for (const auto &RC : RegisterClasses) {
985 ArrayRef<Record*> Order = RC.getOrder();
987 // Give the register class a legal C name if it's anonymous.
988 const std::string &Name = RC.getName();
990 RegClassStrings.add(Name);
992 // Emit the register list now.
993 OS << " // " << Name << " Register Class...\n"
994 << " const MCPhysReg " << Name
996 for (unsigned i = 0, e = Order.size(); i != e; ++i) {
997 Record *Reg = Order[i];
998 OS << getQualifiedName(Reg) << ", ";
1002 OS << " // " << Name << " Bit set.\n"
1003 << " const uint8_t " << Name
1005 BitVectorEmitter BVE;
1006 for (unsigned i = 0, e = Order.size(); i != e; ++i) {
1007 Record *Reg = Order[i];
1008 BVE.add(Target.getRegBank().getReg(Reg)->EnumValue);
1014 OS << "} // end anonymous namespace\n\n";
1016 RegClassStrings.layout();
1017 OS << "extern const char " << TargetName << "RegClassStrings[] = {\n";
1018 RegClassStrings.emit(OS, printChar);
1021 OS << "extern const MCRegisterClass " << TargetName
1022 << "MCRegisterClasses[] = {\n";
1024 for (const auto &RC : RegisterClasses) {
1025 assert(isInt<8>(RC.CopyCost) && "Copy cost too large.");
1026 // Register size and spill size will become independent, but are not at
1027 // the moment. For now use SpillSize as the register size.
1028 OS << " { " << RC.getName() << ", " << RC.getName() << "Bits, "
1029 << RegClassStrings.get(RC.getName()) << ", "
1030 << RC.getOrder().size() << ", sizeof(" << RC.getName() << "Bits), "
1031 << RC.getQualifiedName() + "RegClassID" << ", "
1032 << RC.SpillSize/8 << ", "
1033 << RC.CopyCost << ", "
1034 << ( RC.Allocatable ? "true" : "false" ) << " },\n";
1039 EmitRegMappingTables(OS, Regs, false);
1041 // Emit Reg encoding table
1042 OS << "extern const uint16_t " << TargetName;
1043 OS << "RegEncodingTable[] = {\n";
1044 // Add entry for NoRegister
1046 for (const auto &RE : Regs) {
1047 Record *Reg = RE.TheDef;
1048 BitsInit *BI = Reg->getValueAsBitsInit("HWEncoding");
1050 for (unsigned b = 0, be = BI->getNumBits(); b != be; ++b) {
1051 if (BitInit *B = dyn_cast<BitInit>(BI->getBit(b)))
1052 Value |= (uint64_t)B->getValue() << b;
1054 OS << " " << Value << ",\n";
1056 OS << "};\n"; // End of HW encoding table
1058 // MCRegisterInfo initialization routine.
1059 OS << "static inline void Init" << TargetName
1060 << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
1061 << "unsigned DwarfFlavour = 0, unsigned EHFlavour = 0, unsigned PC = 0) "
1063 << " RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
1064 << Regs.size() + 1 << ", RA, PC, " << TargetName << "MCRegisterClasses, "
1065 << RegisterClasses.size() << ", " << TargetName << "RegUnitRoots, "
1066 << RegBank.getNumNativeRegUnits() << ", " << TargetName << "RegDiffLists, "
1067 << TargetName << "LaneMaskLists, " << TargetName << "RegStrings, "
1068 << TargetName << "RegClassStrings, " << TargetName << "SubRegIdxLists, "
1069 << (std::distance(SubRegIndices.begin(), SubRegIndices.end()) + 1) << ",\n"
1070 << TargetName << "SubRegIdxRanges, " << TargetName
1071 << "RegEncodingTable);\n\n";
1073 EmitRegMapping(OS, Regs, false);
1077 OS << "} // end namespace llvm\n\n";
1078 OS << "#endif // GET_REGINFO_MC_DESC\n\n";
1082 RegisterInfoEmitter::runTargetHeader(raw_ostream &OS, CodeGenTarget &Target,
1083 CodeGenRegBank &RegBank) {
1084 emitSourceFileHeader("Register Information Header Fragment", OS);
1086 OS << "\n#ifdef GET_REGINFO_HEADER\n";
1087 OS << "#undef GET_REGINFO_HEADER\n\n";
1089 const std::string &TargetName = Target.getName();
1090 std::string ClassName = TargetName + "GenRegisterInfo";
1092 OS << "#include \"llvm/Target/TargetRegisterInfo.h\"\n\n";
1094 OS << "namespace llvm {\n\n";
1096 OS << "class " << TargetName << "FrameLowering;\n\n";
1098 OS << "struct " << ClassName << " : public TargetRegisterInfo {\n"
1099 << " explicit " << ClassName
1100 << "(unsigned RA, unsigned D = 0, unsigned E = 0, unsigned PC = 0);\n";
1101 if (!RegBank.getSubRegIndices().empty()) {
1102 OS << " unsigned composeSubRegIndicesImpl"
1103 << "(unsigned, unsigned) const override;\n"
1104 << " LaneBitmask composeSubRegIndexLaneMaskImpl"
1105 << "(unsigned, LaneBitmask) const override;\n"
1106 << " LaneBitmask reverseComposeSubRegIndexLaneMaskImpl"
1107 << "(unsigned, LaneBitmask) const override;\n"
1108 << " const TargetRegisterClass *getSubClassWithSubReg"
1109 << "(const TargetRegisterClass*, unsigned) const override;\n";
1111 OS << " const RegClassWeight &getRegClassWeight("
1112 << "const TargetRegisterClass *RC) const override;\n"
1113 << " unsigned getRegUnitWeight(unsigned RegUnit) const override;\n"
1114 << " unsigned getNumRegPressureSets() const override;\n"
1115 << " const char *getRegPressureSetName(unsigned Idx) const override;\n"
1116 << " unsigned getRegPressureSetLimit(const MachineFunction &MF, unsigned "
1117 "Idx) const override;\n"
1118 << " const int *getRegClassPressureSets("
1119 << "const TargetRegisterClass *RC) const override;\n"
1120 << " const int *getRegUnitPressureSets("
1121 << "unsigned RegUnit) const override;\n"
1122 << " ArrayRef<const char *> getRegMaskNames() const override;\n"
1123 << " ArrayRef<const uint32_t *> getRegMasks() const override;\n"
1124 << " /// Devirtualized TargetFrameLowering.\n"
1125 << " static const " << TargetName << "FrameLowering *getFrameLowering(\n"
1126 << " const MachineFunction &MF);\n"
1129 const auto &RegisterClasses = RegBank.getRegClasses();
1131 if (!RegisterClasses.empty()) {
1132 OS << "namespace " << RegisterClasses.front().Namespace
1133 << " { // Register classes\n";
1135 for (const auto &RC : RegisterClasses) {
1136 const std::string &Name = RC.getName();
1138 // Output the extern for the instance.
1139 OS << " extern const TargetRegisterClass " << Name << "RegClass;\n";
1141 OS << "} // end namespace " << RegisterClasses.front().Namespace << "\n\n";
1143 OS << "} // end namespace llvm\n\n";
1144 OS << "#endif // GET_REGINFO_HEADER\n\n";
1148 // runTargetDesc - Output the target register and register file descriptions.
1151 RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target,
1152 CodeGenRegBank &RegBank){
1153 emitSourceFileHeader("Target Register and Register Classes Information", OS);
1155 OS << "\n#ifdef GET_REGINFO_TARGET_DESC\n";
1156 OS << "#undef GET_REGINFO_TARGET_DESC\n\n";
1158 OS << "namespace llvm {\n\n";
1160 // Get access to MCRegisterClass data.
1161 OS << "extern const MCRegisterClass " << Target.getName()
1162 << "MCRegisterClasses[];\n";
1164 // Start out by emitting each of the register classes.
1165 const auto &RegisterClasses = RegBank.getRegClasses();
1166 const auto &SubRegIndices = RegBank.getSubRegIndices();
1168 // Collect all registers belonging to any allocatable class.
1169 std::set<Record*> AllocatableRegs;
1171 // Collect allocatable registers.
1172 for (const auto &RC : RegisterClasses) {
1173 ArrayRef<Record*> Order = RC.getOrder();
1176 AllocatableRegs.insert(Order.begin(), Order.end());
1179 // Build a shared array of value types.
1180 SequenceToOffsetTable<SmallVector<MVT::SimpleValueType, 4> > VTSeqs;
1181 for (const auto &RC : RegisterClasses)
1184 OS << "\nstatic const MVT::SimpleValueType VTLists[] = {\n";
1185 VTSeqs.emit(OS, printSimpleValueType, "MVT::Other");
1188 // Emit SubRegIndex names, skipping 0.
1189 OS << "\nstatic const char *const SubRegIndexNameTable[] = { \"";
1191 for (const auto &Idx : SubRegIndices) {
1192 OS << Idx.getName();
1197 // Emit SubRegIndex lane masks, including 0.
1198 OS << "\nstatic const LaneBitmask SubRegIndexLaneMaskTable[] = {\n "
1199 "LaneBitmask::getAll(),\n";
1200 for (const auto &Idx : SubRegIndices) {
1201 printMask(OS << " ", Idx.LaneMask);
1202 OS << ", // " << Idx.getName() << '\n';
1208 // Now that all of the structs have been emitted, emit the instances.
1209 if (!RegisterClasses.empty()) {
1210 OS << "\nstatic const TargetRegisterClass *const "
1211 << "NullRegClasses[] = { nullptr };\n\n";
1213 // Emit register class bit mask tables. The first bit mask emitted for a
1214 // register class, RC, is the set of sub-classes, including RC itself.
1216 // If RC has super-registers, also create a list of subreg indices and bit
1217 // masks, (Idx, Mask). The bit mask has a bit for every superreg regclass,
1218 // SuperRC, that satisfies:
1220 // For all SuperReg in SuperRC: SuperReg:Idx in RC
1222 // The 0-terminated list of subreg indices starts at:
1224 // RC->getSuperRegIndices() = SuperRegIdxSeqs + ...
1226 // The corresponding bitmasks follow the sub-class mask in memory. Each
1227 // mask has RCMaskWords uint32_t entries.
1229 // Every bit mask present in the list has at least one bit set.
1231 // Compress the sub-reg index lists.
1232 typedef std::vector<const CodeGenSubRegIndex*> IdxList;
1233 SmallVector<IdxList, 8> SuperRegIdxLists(RegisterClasses.size());
1234 SequenceToOffsetTable<IdxList, deref<llvm::less>> SuperRegIdxSeqs;
1235 BitVector MaskBV(RegisterClasses.size());
1237 for (const auto &RC : RegisterClasses) {
1238 OS << "static const uint32_t " << RC.getName()
1239 << "SubClassMask[] = {\n ";
1240 printBitVectorAsHex(OS, RC.getSubClasses(), 32);
1242 // Emit super-reg class masks for any relevant SubRegIndices that can
1244 IdxList &SRIList = SuperRegIdxLists[RC.EnumValue];
1245 for (auto &Idx : SubRegIndices) {
1247 RC.getSuperRegClasses(&Idx, MaskBV);
1250 SRIList.push_back(&Idx);
1252 printBitVectorAsHex(OS, MaskBV, 32);
1253 OS << "// " << Idx.getName();
1255 SuperRegIdxSeqs.add(SRIList);
1259 OS << "static const uint16_t SuperRegIdxSeqs[] = {\n";
1260 SuperRegIdxSeqs.layout();
1261 SuperRegIdxSeqs.emit(OS, printSubRegIndex);
1264 // Emit NULL terminated super-class lists.
1265 for (const auto &RC : RegisterClasses) {
1266 ArrayRef<CodeGenRegisterClass*> Supers = RC.getSuperClasses();
1268 // Skip classes without supers. We can reuse NullRegClasses.
1272 OS << "static const TargetRegisterClass *const "
1273 << RC.getName() << "Superclasses[] = {\n";
1274 for (const auto *Super : Supers)
1275 OS << " &" << Super->getQualifiedName() << "RegClass,\n";
1276 OS << " nullptr\n};\n\n";
1280 for (const auto &RC : RegisterClasses) {
1281 if (!RC.AltOrderSelect.empty()) {
1282 OS << "\nstatic inline unsigned " << RC.getName()
1283 << "AltOrderSelect(const MachineFunction &MF) {"
1284 << RC.AltOrderSelect << "}\n\n"
1285 << "static ArrayRef<MCPhysReg> " << RC.getName()
1286 << "GetRawAllocationOrder(const MachineFunction &MF) {\n";
1287 for (unsigned oi = 1 , oe = RC.getNumOrders(); oi != oe; ++oi) {
1288 ArrayRef<Record*> Elems = RC.getOrder(oi);
1289 if (!Elems.empty()) {
1290 OS << " static const MCPhysReg AltOrder" << oi << "[] = {";
1291 for (unsigned elem = 0; elem != Elems.size(); ++elem)
1292 OS << (elem ? ", " : " ") << getQualifiedName(Elems[elem]);
1296 OS << " const MCRegisterClass &MCR = " << Target.getName()
1297 << "MCRegisterClasses[" << RC.getQualifiedName() + "RegClassID];\n"
1298 << " const ArrayRef<MCPhysReg> Order[] = {\n"
1299 << " makeArrayRef(MCR.begin(), MCR.getNumRegs()";
1300 for (unsigned oi = 1, oe = RC.getNumOrders(); oi != oe; ++oi)
1301 if (RC.getOrder(oi).empty())
1302 OS << "),\n ArrayRef<MCPhysReg>(";
1304 OS << "),\n makeArrayRef(AltOrder" << oi;
1305 OS << ")\n };\n const unsigned Select = " << RC.getName()
1306 << "AltOrderSelect(MF);\n assert(Select < " << RC.getNumOrders()
1307 << ");\n return Order[Select];\n}\n";
1311 // Now emit the actual value-initialized register class instances.
1312 OS << "\nnamespace " << RegisterClasses.front().Namespace
1313 << " { // Register class instances\n";
1315 for (const auto &RC : RegisterClasses) {
1316 assert(isUInt<16>(RC.SpillSize/8) && "SpillSize too large.");
1317 assert(isUInt<16>(RC.SpillAlignment/8) && "SpillAlignment too large.");
1318 OS << " extern const TargetRegisterClass " << RC.getName()
1319 << "RegClass = {\n " << '&' << Target.getName()
1320 << "MCRegisterClasses[" << RC.getName() << "RegClassID],\n "
1321 << RC.SpillSize/8 << ", /* SpillSize */\n "
1322 << RC.SpillAlignment/8 << ", /* SpillAlignment */\n "
1323 << "VTLists + " << VTSeqs.get(RC.VTs) << ",\n " << RC.getName()
1324 << "SubClassMask,\n SuperRegIdxSeqs + "
1325 << SuperRegIdxSeqs.get(SuperRegIdxLists[RC.EnumValue]) << ",\n ";
1326 printMask(OS, RC.LaneMask);
1327 OS << ",\n " << (unsigned)RC.AllocationPriority << ",\n "
1328 << (RC.HasDisjunctSubRegs?"true":"false")
1329 << ", /* HasDisjunctSubRegs */\n "
1330 << (RC.CoveredBySubRegs?"true":"false")
1331 << ", /* CoveredBySubRegs */\n ";
1332 if (RC.getSuperClasses().empty())
1333 OS << "NullRegClasses,\n ";
1335 OS << RC.getName() << "Superclasses,\n ";
1336 if (RC.AltOrderSelect.empty())
1339 OS << RC.getName() << "GetRawAllocationOrder\n";
1343 OS << "} // end namespace " << RegisterClasses.front().Namespace << "\n";
1346 OS << "\nnamespace {\n";
1347 OS << " const TargetRegisterClass* const RegisterClasses[] = {\n";
1348 for (const auto &RC : RegisterClasses)
1349 OS << " &" << RC.getQualifiedName() << "RegClass,\n";
1351 OS << "} // end anonymous namespace\n";
1353 // Emit extra information about registers.
1354 const std::string &TargetName = Target.getName();
1355 OS << "\nstatic const TargetRegisterInfoDesc "
1356 << TargetName << "RegInfoDesc[] = { // Extra Descriptors\n";
1357 OS << " { 0, false },\n";
1359 const auto &Regs = RegBank.getRegisters();
1360 for (const auto &Reg : Regs) {
1362 OS << Reg.CostPerUse << ", "
1363 << ( AllocatableRegs.count(Reg.TheDef) != 0 ? "true" : "false" )
1366 OS << "};\n"; // End of register descriptors...
1369 std::string ClassName = Target.getName().str() + "GenRegisterInfo";
1371 auto SubRegIndicesSize =
1372 std::distance(SubRegIndices.begin(), SubRegIndices.end());
1374 if (!SubRegIndices.empty()) {
1375 emitComposeSubRegIndices(OS, RegBank, ClassName);
1376 emitComposeSubRegIndexLaneMask(OS, RegBank, ClassName);
1379 // Emit getSubClassWithSubReg.
1380 if (!SubRegIndices.empty()) {
1381 OS << "const TargetRegisterClass *" << ClassName
1382 << "::getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx)"
1384 // Use the smallest type that can hold a regclass ID with room for a
1386 if (RegisterClasses.size() < UINT8_MAX)
1387 OS << " static const uint8_t Table[";
1388 else if (RegisterClasses.size() < UINT16_MAX)
1389 OS << " static const uint16_t Table[";
1391 PrintFatalError("Too many register classes.");
1392 OS << RegisterClasses.size() << "][" << SubRegIndicesSize << "] = {\n";
1393 for (const auto &RC : RegisterClasses) {
1394 OS << " {\t// " << RC.getName() << "\n";
1395 for (auto &Idx : SubRegIndices) {
1396 if (CodeGenRegisterClass *SRC = RC.getSubClassWithSubReg(&Idx))
1397 OS << " " << SRC->EnumValue + 1 << ",\t// " << Idx.getName()
1398 << " -> " << SRC->getName() << "\n";
1400 OS << " 0,\t// " << Idx.getName() << "\n";
1404 OS << " };\n assert(RC && \"Missing regclass\");\n"
1405 << " if (!Idx) return RC;\n --Idx;\n"
1406 << " assert(Idx < " << SubRegIndicesSize << " && \"Bad subreg\");\n"
1407 << " unsigned TV = Table[RC->getID()][Idx];\n"
1408 << " return TV ? getRegClass(TV - 1) : nullptr;\n}\n\n";
1411 EmitRegUnitPressure(OS, RegBank, ClassName);
1413 // Emit the constructor of the class...
1414 OS << "extern const MCRegisterDesc " << TargetName << "RegDesc[];\n";
1415 OS << "extern const MCPhysReg " << TargetName << "RegDiffLists[];\n";
1416 OS << "extern const LaneBitmask " << TargetName << "LaneMaskLists[];\n";
1417 OS << "extern const char " << TargetName << "RegStrings[];\n";
1418 OS << "extern const char " << TargetName << "RegClassStrings[];\n";
1419 OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2];\n";
1420 OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[];\n";
1421 OS << "extern const MCRegisterInfo::SubRegCoveredBits "
1422 << TargetName << "SubRegIdxRanges[];\n";
1423 OS << "extern const uint16_t " << TargetName << "RegEncodingTable[];\n";
1425 EmitRegMappingTables(OS, Regs, true);
1427 OS << ClassName << "::\n" << ClassName
1428 << "(unsigned RA, unsigned DwarfFlavour, unsigned EHFlavour, unsigned PC)\n"
1429 << " : TargetRegisterInfo(" << TargetName << "RegInfoDesc"
1430 << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() <<",\n"
1431 << " SubRegIndexNameTable, SubRegIndexLaneMaskTable, ";
1432 printMask(OS, RegBank.CoveringLanes);
1434 << " InitMCRegisterInfo(" << TargetName << "RegDesc, " << Regs.size() + 1
1435 << ", RA, PC,\n " << TargetName
1436 << "MCRegisterClasses, " << RegisterClasses.size() << ",\n"
1437 << " " << TargetName << "RegUnitRoots,\n"
1438 << " " << RegBank.getNumNativeRegUnits() << ",\n"
1439 << " " << TargetName << "RegDiffLists,\n"
1440 << " " << TargetName << "LaneMaskLists,\n"
1441 << " " << TargetName << "RegStrings,\n"
1442 << " " << TargetName << "RegClassStrings,\n"
1443 << " " << TargetName << "SubRegIdxLists,\n"
1444 << " " << SubRegIndicesSize + 1 << ",\n"
1445 << " " << TargetName << "SubRegIdxRanges,\n"
1446 << " " << TargetName << "RegEncodingTable);\n\n";
1448 EmitRegMapping(OS, Regs, true);
1452 // Emit CalleeSavedRegs information.
1453 std::vector<Record*> CSRSets =
1454 Records.getAllDerivedDefinitions("CalleeSavedRegs");
1455 for (unsigned i = 0, e = CSRSets.size(); i != e; ++i) {
1456 Record *CSRSet = CSRSets[i];
1457 const SetTheory::RecVec *Regs = RegBank.getSets().expand(CSRSet);
1458 assert(Regs && "Cannot expand CalleeSavedRegs instance");
1460 // Emit the *_SaveList list of callee-saved registers.
1461 OS << "static const MCPhysReg " << CSRSet->getName()
1462 << "_SaveList[] = { ";
1463 for (unsigned r = 0, re = Regs->size(); r != re; ++r)
1464 OS << getQualifiedName((*Regs)[r]) << ", ";
1467 // Emit the *_RegMask bit mask of call-preserved registers.
1468 BitVector Covered = RegBank.computeCoveredRegisters(*Regs);
1470 // Check for an optional OtherPreserved set.
1471 // Add those registers to RegMask, but not to SaveList.
1472 if (DagInit *OPDag =
1473 dyn_cast<DagInit>(CSRSet->getValueInit("OtherPreserved"))) {
1474 SetTheory::RecSet OPSet;
1475 RegBank.getSets().evaluate(OPDag, OPSet, CSRSet->getLoc());
1476 Covered |= RegBank.computeCoveredRegisters(
1477 ArrayRef<Record*>(OPSet.begin(), OPSet.end()));
1480 OS << "static const uint32_t " << CSRSet->getName()
1481 << "_RegMask[] = { ";
1482 printBitVectorAsHex(OS, Covered, 32);
1487 OS << "ArrayRef<const uint32_t *> " << ClassName
1488 << "::getRegMasks() const {\n";
1489 if (!CSRSets.empty()) {
1490 OS << " static const uint32_t *const Masks[] = {\n";
1491 for (Record *CSRSet : CSRSets)
1492 OS << " " << CSRSet->getName() << "_RegMask,\n";
1494 OS << " return makeArrayRef(Masks);\n";
1496 OS << " return None;\n";
1500 OS << "ArrayRef<const char *> " << ClassName
1501 << "::getRegMaskNames() const {\n";
1502 if (!CSRSets.empty()) {
1503 OS << " static const char *const Names[] = {\n";
1504 for (Record *CSRSet : CSRSets)
1505 OS << " " << '"' << CSRSet->getName() << '"' << ",\n";
1507 OS << " return makeArrayRef(Names);\n";
1509 OS << " return None;\n";
1513 OS << "const " << TargetName << "FrameLowering *\n" << TargetName
1514 << "GenRegisterInfo::getFrameLowering(const MachineFunction &MF) {\n"
1515 << " return static_cast<const " << TargetName << "FrameLowering *>(\n"
1516 << " MF.getSubtarget().getFrameLowering());\n"
1519 OS << "} // end namespace llvm\n\n";
1520 OS << "#endif // GET_REGINFO_TARGET_DESC\n\n";
1523 void RegisterInfoEmitter::run(raw_ostream &OS) {
1524 CodeGenTarget Target(Records);
1525 CodeGenRegBank &RegBank = Target.getRegBank();
1526 RegBank.computeDerivedInfo();
1528 runEnums(OS, Target, RegBank);
1529 runMCDesc(OS, Target, RegBank);
1530 runTargetHeader(OS, Target, RegBank);
1531 runTargetDesc(OS, Target, RegBank);
1536 void EmitRegisterInfo(RecordKeeper &RK, raw_ostream &OS) {
1537 RegisterInfoEmitter(RK).run(OS);
1540 } // end namespace llvm