RegisterInfoEmitter.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915
  1. //===- RegisterInfoEmitter.cpp - Generate a Register File 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 file for a code generator. It uses instances of the Register,
  11. // RegisterAliases, and RegisterClass classes to gather this information.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CodeGenRegisters.h"
  15. #include "CodeGenTarget.h"
  16. #include "SequenceToOffsetTable.h"
  17. #include "Types.h"
  18. #include "llvm/ADT/ArrayRef.h"
  19. #include "llvm/ADT/BitVector.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SetVector.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/SparseBitVector.h"
  24. #include "llvm/ADT/Twine.h"
  25. #include "llvm/Support/Casting.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Format.h"
  28. #include "llvm/Support/MachineValueType.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/TableGen/Error.h"
  31. #include "llvm/TableGen/Record.h"
  32. #include "llvm/TableGen/SetTheory.h"
  33. #include "llvm/TableGen/TableGenBackend.h"
  34. #include <algorithm>
  35. #include <cassert>
  36. #include <cstddef>
  37. #include <cstdint>
  38. #include <deque>
  39. #include <iterator>
  40. #include <set>
  41. #include <string>
  42. #include <vector>
  43. using namespace llvm;
  44. cl::OptionCategory RegisterInfoCat("Options for -gen-register-info");
  45. static cl::opt<bool>
  46. RegisterInfoDebug("register-info-debug", cl::init(false),
  47. cl::desc("Dump register information to help debugging"),
  48. cl::cat(RegisterInfoCat));
  49. namespace {
  50. class RegisterInfoEmitter {
  51. CodeGenTarget Target;
  52. RecordKeeper &Records;
  53. public:
  54. RegisterInfoEmitter(RecordKeeper &R) : Target(R), Records(R) {
  55. CodeGenRegBank &RegBank = Target.getRegBank();
  56. RegBank.computeDerivedInfo();
  57. }
  58. // runEnums - Print out enum values for all of the registers.
  59. void runEnums(raw_ostream &o, CodeGenTarget &Target, CodeGenRegBank &Bank);
  60. // runMCDesc - Print out MC register descriptions.
  61. void runMCDesc(raw_ostream &o, CodeGenTarget &Target, CodeGenRegBank &Bank);
  62. // runTargetHeader - Emit a header fragment for the register info emitter.
  63. void runTargetHeader(raw_ostream &o, CodeGenTarget &Target,
  64. CodeGenRegBank &Bank);
  65. // runTargetDesc - Output the target register and register file descriptions.
  66. void runTargetDesc(raw_ostream &o, CodeGenTarget &Target,
  67. CodeGenRegBank &Bank);
  68. // run - Output the register file description.
  69. void run(raw_ostream &o);
  70. void debugDump(raw_ostream &OS);
  71. private:
  72. void EmitRegMapping(raw_ostream &o, const std::deque<CodeGenRegister> &Regs,
  73. bool isCtor);
  74. void EmitRegMappingTables(raw_ostream &o,
  75. const std::deque<CodeGenRegister> &Regs,
  76. bool isCtor);
  77. void EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank,
  78. const std::string &ClassName);
  79. void emitComposeSubRegIndices(raw_ostream &OS, CodeGenRegBank &RegBank,
  80. const std::string &ClassName);
  81. void emitComposeSubRegIndexLaneMask(raw_ostream &OS, CodeGenRegBank &RegBank,
  82. const std::string &ClassName);
  83. };
  84. } // end anonymous namespace
  85. // runEnums - Print out enum values for all of the registers.
  86. void RegisterInfoEmitter::runEnums(raw_ostream &OS,
  87. CodeGenTarget &Target, CodeGenRegBank &Bank) {
  88. const auto &Registers = Bank.getRegisters();
  89. // Register enums are stored as uint16_t in the tables. Make sure we'll fit.
  90. assert(Registers.size() <= 0xffff && "Too many regs to fit in tables");
  91. StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace");
  92. emitSourceFileHeader("Target Register Enum Values", OS);
  93. OS << "\n#ifdef GET_REGINFO_ENUM\n";
  94. OS << "#undef GET_REGINFO_ENUM\n\n";
  95. OS << "namespace llvm {\n\n";
  96. OS << "class MCRegisterClass;\n"
  97. << "extern const MCRegisterClass " << Target.getName()
  98. << "MCRegisterClasses[];\n\n";
  99. if (!Namespace.empty())
  100. OS << "namespace " << Namespace << " {\n";
  101. OS << "enum {\n NoRegister,\n";
  102. for (const auto &Reg : Registers)
  103. OS << " " << Reg.getName() << " = " << Reg.EnumValue << ",\n";
  104. assert(Registers.size() == Registers.back().EnumValue &&
  105. "Register enum value mismatch!");
  106. OS << " NUM_TARGET_REGS // " << Registers.size()+1 << "\n";
  107. OS << "};\n";
  108. if (!Namespace.empty())
  109. OS << "} // end namespace " << Namespace << "\n";
  110. const auto &RegisterClasses = Bank.getRegClasses();
  111. if (!RegisterClasses.empty()) {
  112. // RegisterClass enums are stored as uint16_t in the tables.
  113. assert(RegisterClasses.size() <= 0xffff &&
  114. "Too many register classes to fit in tables");
  115. OS << "\n// Register classes\n\n";
  116. if (!Namespace.empty())
  117. OS << "namespace " << Namespace << " {\n";
  118. OS << "enum {\n";
  119. for (const auto &RC : RegisterClasses)
  120. OS << " " << RC.getName() << "RegClassID"
  121. << " = " << RC.EnumValue << ",\n";
  122. OS << "\n};\n";
  123. if (!Namespace.empty())
  124. OS << "} // end namespace " << Namespace << "\n\n";
  125. }
  126. const std::vector<Record*> &RegAltNameIndices = Target.getRegAltNameIndices();
  127. // If the only definition is the default NoRegAltName, we don't need to
  128. // emit anything.
  129. if (RegAltNameIndices.size() > 1) {
  130. OS << "\n// Register alternate name indices\n\n";
  131. if (!Namespace.empty())
  132. OS << "namespace " << Namespace << " {\n";
  133. OS << "enum {\n";
  134. for (unsigned i = 0, e = RegAltNameIndices.size(); i != e; ++i)
  135. OS << " " << RegAltNameIndices[i]->getName() << ",\t// " << i << "\n";
  136. OS << " NUM_TARGET_REG_ALT_NAMES = " << RegAltNameIndices.size() << "\n";
  137. OS << "};\n";
  138. if (!Namespace.empty())
  139. OS << "} // end namespace " << Namespace << "\n\n";
  140. }
  141. auto &SubRegIndices = Bank.getSubRegIndices();
  142. if (!SubRegIndices.empty()) {
  143. OS << "\n// Subregister indices\n\n";
  144. std::string Namespace = SubRegIndices.front().getNamespace();
  145. if (!Namespace.empty())
  146. OS << "namespace " << Namespace << " {\n";
  147. OS << "enum : uint16_t {\n NoSubRegister,\n";
  148. unsigned i = 0;
  149. for (const auto &Idx : SubRegIndices)
  150. OS << " " << Idx.getName() << ",\t// " << ++i << "\n";
  151. OS << " NUM_TARGET_SUBREGS\n};\n";
  152. if (!Namespace.empty())
  153. OS << "} // end namespace " << Namespace << "\n\n";
  154. }
  155. OS << "// Register pressure sets enum.\n";
  156. if (!Namespace.empty())
  157. OS << "namespace " << Namespace << " {\n";
  158. OS << "enum RegisterPressureSets {\n";
  159. unsigned NumSets = Bank.getNumRegPressureSets();
  160. for (unsigned i = 0; i < NumSets; ++i ) {
  161. const RegUnitSet &RegUnits = Bank.getRegSetAt(i);
  162. OS << " " << RegUnits.Name << " = " << i << ",\n";
  163. }
  164. OS << "};\n";
  165. if (!Namespace.empty())
  166. OS << "} // end namespace " << Namespace << '\n';
  167. OS << '\n';
  168. OS << "} // end namespace llvm\n\n";
  169. OS << "#endif // GET_REGINFO_ENUM\n\n";
  170. }
  171. static void printInt(raw_ostream &OS, int Val) {
  172. OS << Val;
  173. }
  174. void RegisterInfoEmitter::
  175. EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank,
  176. const std::string &ClassName) {
  177. unsigned NumRCs = RegBank.getRegClasses().size();
  178. unsigned NumSets = RegBank.getNumRegPressureSets();
  179. OS << "/// Get the weight in units of pressure for this register class.\n"
  180. << "const RegClassWeight &" << ClassName << "::\n"
  181. << "getRegClassWeight(const TargetRegisterClass *RC) const {\n"
  182. << " static const RegClassWeight RCWeightTable[] = {\n";
  183. for (const auto &RC : RegBank.getRegClasses()) {
  184. const CodeGenRegister::Vec &Regs = RC.getMembers();
  185. OS << " {" << RC.getWeight(RegBank) << ", ";
  186. if (Regs.empty() || RC.Artificial)
  187. OS << '0';
  188. else {
  189. std::vector<unsigned> RegUnits;
  190. RC.buildRegUnitSet(RegBank, RegUnits);
  191. OS << RegBank.getRegUnitSetWeight(RegUnits);
  192. }
  193. OS << "}, \t// " << RC.getName() << "\n";
  194. }
  195. OS << " };\n"
  196. << " return RCWeightTable[RC->getID()];\n"
  197. << "}\n\n";
  198. // Reasonable targets (not ARMv7) have unit weight for all units, so don't
  199. // bother generating a table.
  200. bool RegUnitsHaveUnitWeight = true;
  201. for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
  202. UnitIdx < UnitEnd; ++UnitIdx) {
  203. if (RegBank.getRegUnit(UnitIdx).Weight > 1)
  204. RegUnitsHaveUnitWeight = false;
  205. }
  206. OS << "/// Get the weight in units of pressure for this register unit.\n"
  207. << "unsigned " << ClassName << "::\n"
  208. << "getRegUnitWeight(unsigned RegUnit) const {\n"
  209. << " assert(RegUnit < " << RegBank.getNumNativeRegUnits()
  210. << " && \"invalid register unit\");\n";
  211. if (!RegUnitsHaveUnitWeight) {
  212. OS << " static const uint8_t RUWeightTable[] = {\n ";
  213. for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
  214. UnitIdx < UnitEnd; ++UnitIdx) {
  215. const RegUnit &RU = RegBank.getRegUnit(UnitIdx);
  216. assert(RU.Weight < 256 && "RegUnit too heavy");
  217. OS << RU.Weight << ", ";
  218. }
  219. OS << "};\n"
  220. << " return RUWeightTable[RegUnit];\n";
  221. }
  222. else {
  223. OS << " // All register units have unit weight.\n"
  224. << " return 1;\n";
  225. }
  226. OS << "}\n\n";
  227. OS << "\n"
  228. << "// Get the number of dimensions of register pressure.\n"
  229. << "unsigned " << ClassName << "::getNumRegPressureSets() const {\n"
  230. << " return " << NumSets << ";\n}\n\n";
  231. OS << "// Get the name of this register unit pressure set.\n"
  232. << "const char *" << ClassName << "::\n"
  233. << "getRegPressureSetName(unsigned Idx) const {\n"
  234. << " static const char *PressureNameTable[] = {\n";
  235. unsigned MaxRegUnitWeight = 0;
  236. for (unsigned i = 0; i < NumSets; ++i ) {
  237. const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
  238. MaxRegUnitWeight = std::max(MaxRegUnitWeight, RegUnits.Weight);
  239. OS << " \"" << RegUnits.Name << "\",\n";
  240. }
  241. OS << " };\n"
  242. << " return PressureNameTable[Idx];\n"
  243. << "}\n\n";
  244. OS << "// Get the register unit pressure limit for this dimension.\n"
  245. << "// This limit must be adjusted dynamically for reserved registers.\n"
  246. << "unsigned " << ClassName << "::\n"
  247. << "getRegPressureSetLimit(const MachineFunction &MF, unsigned Idx) const "
  248. "{\n"
  249. << " static const " << getMinimalTypeForRange(MaxRegUnitWeight, 32)
  250. << " PressureLimitTable[] = {\n";
  251. for (unsigned i = 0; i < NumSets; ++i ) {
  252. const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
  253. OS << " " << RegUnits.Weight << ", \t// " << i << ": "
  254. << RegUnits.Name << "\n";
  255. }
  256. OS << " };\n"
  257. << " return PressureLimitTable[Idx];\n"
  258. << "}\n\n";
  259. SequenceToOffsetTable<std::vector<int>> PSetsSeqs;
  260. // This table may be larger than NumRCs if some register units needed a list
  261. // of unit sets that did not correspond to a register class.
  262. unsigned NumRCUnitSets = RegBank.getNumRegClassPressureSetLists();
  263. std::vector<std::vector<int>> PSets(NumRCUnitSets);
  264. for (unsigned i = 0, e = NumRCUnitSets; i != e; ++i) {
  265. ArrayRef<unsigned> PSetIDs = RegBank.getRCPressureSetIDs(i);
  266. PSets[i].reserve(PSetIDs.size());
  267. for (unsigned PSetID : PSetIDs) {
  268. PSets[i].push_back(RegBank.getRegPressureSet(PSetID).Order);
  269. }
  270. llvm::sort(PSets[i]);
  271. PSetsSeqs.add(PSets[i]);
  272. }
  273. PSetsSeqs.layout();
  274. OS << "/// Table of pressure sets per register class or unit.\n"
  275. << "static const int RCSetsTable[] = {\n";
  276. PSetsSeqs.emit(OS, printInt, "-1");
  277. OS << "};\n\n";
  278. OS << "/// Get the dimensions of register pressure impacted by this "
  279. << "register class.\n"
  280. << "/// Returns a -1 terminated array of pressure set IDs\n"
  281. << "const int *" << ClassName << "::\n"
  282. << "getRegClassPressureSets(const TargetRegisterClass *RC) const {\n";
  283. OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size() - 1, 32)
  284. << " RCSetStartTable[] = {\n ";
  285. for (unsigned i = 0, e = NumRCs; i != e; ++i) {
  286. OS << PSetsSeqs.get(PSets[i]) << ",";
  287. }
  288. OS << "};\n"
  289. << " return &RCSetsTable[RCSetStartTable[RC->getID()]];\n"
  290. << "}\n\n";
  291. OS << "/// Get the dimensions of register pressure impacted by this "
  292. << "register unit.\n"
  293. << "/// Returns a -1 terminated array of pressure set IDs\n"
  294. << "const int *" << ClassName << "::\n"
  295. << "getRegUnitPressureSets(unsigned RegUnit) const {\n"
  296. << " assert(RegUnit < " << RegBank.getNumNativeRegUnits()
  297. << " && \"invalid register unit\");\n";
  298. OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size() - 1, 32)
  299. << " RUSetStartTable[] = {\n ";
  300. for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
  301. UnitIdx < UnitEnd; ++UnitIdx) {
  302. OS << PSetsSeqs.get(PSets[RegBank.getRegUnit(UnitIdx).RegClassUnitSetsIdx])
  303. << ",";
  304. }
  305. OS << "};\n"
  306. << " return &RCSetsTable[RUSetStartTable[RegUnit]];\n"
  307. << "}\n\n";
  308. }
  309. using DwarfRegNumsMapPair = std::pair<Record*, std::vector<int64_t>>;
  310. using DwarfRegNumsVecTy = std::vector<DwarfRegNumsMapPair>;
  311. static void finalizeDwarfRegNumsKeys(DwarfRegNumsVecTy &DwarfRegNums) {
  312. // Sort and unique to get a map-like vector. We want the last assignment to
  313. // match previous behaviour.
  314. llvm::stable_sort(DwarfRegNums, on_first<LessRecordRegister>());
  315. // Warn about duplicate assignments.
  316. const Record *LastSeenReg = nullptr;
  317. for (const auto &X : DwarfRegNums) {
  318. const auto &Reg = X.first;
  319. // The only way LessRecordRegister can return equal is if they're the same
  320. // string. Use simple equality instead.
  321. if (LastSeenReg && Reg->getName() == LastSeenReg->getName())
  322. PrintWarning(Reg->getLoc(), Twine("DWARF numbers for register ") +
  323. getQualifiedName(Reg) +
  324. "specified multiple times");
  325. LastSeenReg = Reg;
  326. }
  327. auto Last = std::unique(
  328. DwarfRegNums.begin(), DwarfRegNums.end(),
  329. [](const DwarfRegNumsMapPair &A, const DwarfRegNumsMapPair &B) {
  330. return A.first->getName() == B.first->getName();
  331. });
  332. DwarfRegNums.erase(Last, DwarfRegNums.end());
  333. }
  334. void RegisterInfoEmitter::EmitRegMappingTables(
  335. raw_ostream &OS, const std::deque<CodeGenRegister> &Regs, bool isCtor) {
  336. // Collect all information about dwarf register numbers
  337. DwarfRegNumsVecTy DwarfRegNums;
  338. // First, just pull all provided information to the map
  339. unsigned maxLength = 0;
  340. for (auto &RE : Regs) {
  341. Record *Reg = RE.TheDef;
  342. std::vector<int64_t> RegNums = Reg->getValueAsListOfInts("DwarfNumbers");
  343. maxLength = std::max((size_t)maxLength, RegNums.size());
  344. DwarfRegNums.emplace_back(Reg, std::move(RegNums));
  345. }
  346. finalizeDwarfRegNumsKeys(DwarfRegNums);
  347. if (!maxLength)
  348. return;
  349. // Now we know maximal length of number list. Append -1's, where needed
  350. for (auto &DwarfRegNum : DwarfRegNums)
  351. for (unsigned I = DwarfRegNum.second.size(), E = maxLength; I != E; ++I)
  352. DwarfRegNum.second.push_back(-1);
  353. StringRef Namespace = Regs.front().TheDef->getValueAsString("Namespace");
  354. OS << "// " << Namespace << " Dwarf<->LLVM register mappings.\n";
  355. // Emit reverse information about the dwarf register numbers.
  356. for (unsigned j = 0; j < 2; ++j) {
  357. for (unsigned I = 0, E = maxLength; I != E; ++I) {
  358. OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
  359. OS << (j == 0 ? "DwarfFlavour" : "EHFlavour");
  360. OS << I << "Dwarf2L[]";
  361. if (!isCtor) {
  362. OS << " = {\n";
  363. // Store the mapping sorted by the LLVM reg num so lookup can be done
  364. // with a binary search.
  365. std::map<uint64_t, Record*> Dwarf2LMap;
  366. for (auto &DwarfRegNum : DwarfRegNums) {
  367. int DwarfRegNo = DwarfRegNum.second[I];
  368. if (DwarfRegNo < 0)
  369. continue;
  370. Dwarf2LMap[DwarfRegNo] = DwarfRegNum.first;
  371. }
  372. for (auto &I : Dwarf2LMap)
  373. OS << " { " << I.first << "U, " << getQualifiedName(I.second)
  374. << " },\n";
  375. OS << "};\n";
  376. } else {
  377. OS << ";\n";
  378. }
  379. // We have to store the size in a const global, it's used in multiple
  380. // places.
  381. OS << "extern const unsigned " << Namespace
  382. << (j == 0 ? "DwarfFlavour" : "EHFlavour") << I << "Dwarf2LSize";
  383. if (!isCtor)
  384. OS << " = std::size(" << Namespace
  385. << (j == 0 ? "DwarfFlavour" : "EHFlavour") << I << "Dwarf2L);\n\n";
  386. else
  387. OS << ";\n\n";
  388. }
  389. }
  390. for (auto &RE : Regs) {
  391. Record *Reg = RE.TheDef;
  392. const RecordVal *V = Reg->getValue("DwarfAlias");
  393. if (!V || !V->getValue())
  394. continue;
  395. DefInit *DI = cast<DefInit>(V->getValue());
  396. Record *Alias = DI->getDef();
  397. const auto &AliasIter = llvm::lower_bound(
  398. DwarfRegNums, Alias, [](const DwarfRegNumsMapPair &A, const Record *B) {
  399. return LessRecordRegister()(A.first, B);
  400. });
  401. assert(AliasIter != DwarfRegNums.end() && AliasIter->first == Alias &&
  402. "Expected Alias to be present in map");
  403. const auto &RegIter = llvm::lower_bound(
  404. DwarfRegNums, Reg, [](const DwarfRegNumsMapPair &A, const Record *B) {
  405. return LessRecordRegister()(A.first, B);
  406. });
  407. assert(RegIter != DwarfRegNums.end() && RegIter->first == Reg &&
  408. "Expected Reg to be present in map");
  409. RegIter->second = AliasIter->second;
  410. }
  411. // Emit information about the dwarf register numbers.
  412. for (unsigned j = 0; j < 2; ++j) {
  413. for (unsigned i = 0, e = maxLength; i != e; ++i) {
  414. OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
  415. OS << (j == 0 ? "DwarfFlavour" : "EHFlavour");
  416. OS << i << "L2Dwarf[]";
  417. if (!isCtor) {
  418. OS << " = {\n";
  419. // Store the mapping sorted by the Dwarf reg num so lookup can be done
  420. // with a binary search.
  421. for (auto &DwarfRegNum : DwarfRegNums) {
  422. int RegNo = DwarfRegNum.second[i];
  423. if (RegNo == -1) // -1 is the default value, don't emit a mapping.
  424. continue;
  425. OS << " { " << getQualifiedName(DwarfRegNum.first) << ", " << RegNo
  426. << "U },\n";
  427. }
  428. OS << "};\n";
  429. } else {
  430. OS << ";\n";
  431. }
  432. // We have to store the size in a const global, it's used in multiple
  433. // places.
  434. OS << "extern const unsigned " << Namespace
  435. << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2DwarfSize";
  436. if (!isCtor)
  437. OS << " = std::size(" << Namespace
  438. << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2Dwarf);\n\n";
  439. else
  440. OS << ";\n\n";
  441. }
  442. }
  443. }
  444. void RegisterInfoEmitter::EmitRegMapping(
  445. raw_ostream &OS, const std::deque<CodeGenRegister> &Regs, bool isCtor) {
  446. // Emit the initializer so the tables from EmitRegMappingTables get wired up
  447. // to the MCRegisterInfo object.
  448. unsigned maxLength = 0;
  449. for (auto &RE : Regs) {
  450. Record *Reg = RE.TheDef;
  451. maxLength = std::max((size_t)maxLength,
  452. Reg->getValueAsListOfInts("DwarfNumbers").size());
  453. }
  454. if (!maxLength)
  455. return;
  456. StringRef Namespace = Regs.front().TheDef->getValueAsString("Namespace");
  457. // Emit reverse information about the dwarf register numbers.
  458. for (unsigned j = 0; j < 2; ++j) {
  459. OS << " switch (";
  460. if (j == 0)
  461. OS << "DwarfFlavour";
  462. else
  463. OS << "EHFlavour";
  464. OS << ") {\n"
  465. << " default:\n"
  466. << " llvm_unreachable(\"Unknown DWARF flavour\");\n";
  467. for (unsigned i = 0, e = maxLength; i != e; ++i) {
  468. OS << " case " << i << ":\n";
  469. OS << " ";
  470. if (!isCtor)
  471. OS << "RI->";
  472. std::string Tmp;
  473. raw_string_ostream(Tmp) << Namespace
  474. << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
  475. << "Dwarf2L";
  476. OS << "mapDwarfRegsToLLVMRegs(" << Tmp << ", " << Tmp << "Size, ";
  477. if (j == 0)
  478. OS << "false";
  479. else
  480. OS << "true";
  481. OS << ");\n";
  482. OS << " break;\n";
  483. }
  484. OS << " }\n";
  485. }
  486. // Emit information about the dwarf register numbers.
  487. for (unsigned j = 0; j < 2; ++j) {
  488. OS << " switch (";
  489. if (j == 0)
  490. OS << "DwarfFlavour";
  491. else
  492. OS << "EHFlavour";
  493. OS << ") {\n"
  494. << " default:\n"
  495. << " llvm_unreachable(\"Unknown DWARF flavour\");\n";
  496. for (unsigned i = 0, e = maxLength; i != e; ++i) {
  497. OS << " case " << i << ":\n";
  498. OS << " ";
  499. if (!isCtor)
  500. OS << "RI->";
  501. std::string Tmp;
  502. raw_string_ostream(Tmp) << Namespace
  503. << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
  504. << "L2Dwarf";
  505. OS << "mapLLVMRegsToDwarfRegs(" << Tmp << ", " << Tmp << "Size, ";
  506. if (j == 0)
  507. OS << "false";
  508. else
  509. OS << "true";
  510. OS << ");\n";
  511. OS << " break;\n";
  512. }
  513. OS << " }\n";
  514. }
  515. }
  516. // Print a BitVector as a sequence of hex numbers using a little-endian mapping.
  517. // Width is the number of bits per hex number.
  518. static void printBitVectorAsHex(raw_ostream &OS,
  519. const BitVector &Bits,
  520. unsigned Width) {
  521. assert(Width <= 32 && "Width too large");
  522. unsigned Digits = (Width + 3) / 4;
  523. for (unsigned i = 0, e = Bits.size(); i < e; i += Width) {
  524. unsigned Value = 0;
  525. for (unsigned j = 0; j != Width && i + j != e; ++j)
  526. Value |= Bits.test(i + j) << j;
  527. OS << format("0x%0*x, ", Digits, Value);
  528. }
  529. }
  530. // Helper to emit a set of bits into a constant byte array.
  531. class BitVectorEmitter {
  532. BitVector Values;
  533. public:
  534. void add(unsigned v) {
  535. if (v >= Values.size())
  536. Values.resize(((v/8)+1)*8); // Round up to the next byte.
  537. Values[v] = true;
  538. }
  539. void print(raw_ostream &OS) {
  540. printBitVectorAsHex(OS, Values, 8);
  541. }
  542. };
  543. static void printSimpleValueType(raw_ostream &OS, MVT::SimpleValueType VT) {
  544. OS << getEnumName(VT);
  545. }
  546. static void printSubRegIndex(raw_ostream &OS, const CodeGenSubRegIndex *Idx) {
  547. OS << Idx->EnumValue;
  548. }
  549. // Differentially encoded register and regunit lists allow for better
  550. // compression on regular register banks. The sequence is computed from the
  551. // differential list as:
  552. //
  553. // out[0] = InitVal;
  554. // out[n+1] = out[n] + diff[n]; // n = 0, 1, ...
  555. //
  556. // The initial value depends on the specific list. The list is terminated by a
  557. // 0 differential which means we can't encode repeated elements.
  558. typedef SmallVector<uint16_t, 4> DiffVec;
  559. typedef SmallVector<LaneBitmask, 4> MaskVec;
  560. // Differentially encode a sequence of numbers into V. The starting value and
  561. // terminating 0 are not added to V, so it will have the same size as List.
  562. static
  563. DiffVec &diffEncode(DiffVec &V, unsigned InitVal, SparseBitVector<> List) {
  564. assert(V.empty() && "Clear DiffVec before diffEncode.");
  565. uint16_t Val = uint16_t(InitVal);
  566. for (uint16_t Cur : List) {
  567. V.push_back(Cur - Val);
  568. Val = Cur;
  569. }
  570. return V;
  571. }
  572. template<typename Iter>
  573. static
  574. DiffVec &diffEncode(DiffVec &V, unsigned InitVal, Iter Begin, Iter End) {
  575. assert(V.empty() && "Clear DiffVec before diffEncode.");
  576. uint16_t Val = uint16_t(InitVal);
  577. for (Iter I = Begin; I != End; ++I) {
  578. uint16_t Cur = (*I)->EnumValue;
  579. V.push_back(Cur - Val);
  580. Val = Cur;
  581. }
  582. return V;
  583. }
  584. static void printDiff16(raw_ostream &OS, uint16_t Val) {
  585. OS << Val;
  586. }
  587. static void printMask(raw_ostream &OS, LaneBitmask Val) {
  588. OS << "LaneBitmask(0x" << PrintLaneMask(Val) << ')';
  589. }
  590. // Try to combine Idx's compose map into Vec if it is compatible.
  591. // Return false if it's not possible.
  592. static bool combine(const CodeGenSubRegIndex *Idx,
  593. SmallVectorImpl<CodeGenSubRegIndex*> &Vec) {
  594. const CodeGenSubRegIndex::CompMap &Map = Idx->getComposites();
  595. for (const auto &I : Map) {
  596. CodeGenSubRegIndex *&Entry = Vec[I.first->EnumValue - 1];
  597. if (Entry && Entry != I.second)
  598. return false;
  599. }
  600. // All entries are compatible. Make it so.
  601. for (const auto &I : Map) {
  602. auto *&Entry = Vec[I.first->EnumValue - 1];
  603. assert((!Entry || Entry == I.second) &&
  604. "Expected EnumValue to be unique");
  605. Entry = I.second;
  606. }
  607. return true;
  608. }
  609. void
  610. RegisterInfoEmitter::emitComposeSubRegIndices(raw_ostream &OS,
  611. CodeGenRegBank &RegBank,
  612. const std::string &ClName) {
  613. const auto &SubRegIndices = RegBank.getSubRegIndices();
  614. OS << "unsigned " << ClName
  615. << "::composeSubRegIndicesImpl(unsigned IdxA, unsigned IdxB) const {\n";
  616. // Many sub-register indexes are composition-compatible, meaning that
  617. //
  618. // compose(IdxA, IdxB) == compose(IdxA', IdxB)
  619. //
  620. // for many IdxA, IdxA' pairs. Not all sub-register indexes can be composed.
  621. // The illegal entries can be use as wildcards to compress the table further.
  622. // Map each Sub-register index to a compatible table row.
  623. SmallVector<unsigned, 4> RowMap;
  624. SmallVector<SmallVector<CodeGenSubRegIndex*, 4>, 4> Rows;
  625. auto SubRegIndicesSize =
  626. std::distance(SubRegIndices.begin(), SubRegIndices.end());
  627. for (const auto &Idx : SubRegIndices) {
  628. unsigned Found = ~0u;
  629. for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
  630. if (combine(&Idx, Rows[r])) {
  631. Found = r;
  632. break;
  633. }
  634. }
  635. if (Found == ~0u) {
  636. Found = Rows.size();
  637. Rows.resize(Found + 1);
  638. Rows.back().resize(SubRegIndicesSize);
  639. combine(&Idx, Rows.back());
  640. }
  641. RowMap.push_back(Found);
  642. }
  643. // Output the row map if there is multiple rows.
  644. if (Rows.size() > 1) {
  645. OS << " static const " << getMinimalTypeForRange(Rows.size(), 32)
  646. << " RowMap[" << SubRegIndicesSize << "] = {\n ";
  647. for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
  648. OS << RowMap[i] << ", ";
  649. OS << "\n };\n";
  650. }
  651. // Output the rows.
  652. OS << " static const " << getMinimalTypeForRange(SubRegIndicesSize + 1, 32)
  653. << " Rows[" << Rows.size() << "][" << SubRegIndicesSize << "] = {\n";
  654. for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
  655. OS << " { ";
  656. for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
  657. if (Rows[r][i])
  658. OS << Rows[r][i]->getQualifiedName() << ", ";
  659. else
  660. OS << "0, ";
  661. OS << "},\n";
  662. }
  663. OS << " };\n\n";
  664. OS << " --IdxA; assert(IdxA < " << SubRegIndicesSize << "); (void) IdxA;\n"
  665. << " --IdxB; assert(IdxB < " << SubRegIndicesSize << ");\n";
  666. if (Rows.size() > 1)
  667. OS << " return Rows[RowMap[IdxA]][IdxB];\n";
  668. else
  669. OS << " return Rows[0][IdxB];\n";
  670. OS << "}\n\n";
  671. }
  672. void
  673. RegisterInfoEmitter::emitComposeSubRegIndexLaneMask(raw_ostream &OS,
  674. CodeGenRegBank &RegBank,
  675. const std::string &ClName) {
  676. // See the comments in computeSubRegLaneMasks() for our goal here.
  677. const auto &SubRegIndices = RegBank.getSubRegIndices();
  678. // Create a list of Mask+Rotate operations, with equivalent entries merged.
  679. SmallVector<unsigned, 4> SubReg2SequenceIndexMap;
  680. SmallVector<SmallVector<MaskRolPair, 1>, 4> Sequences;
  681. for (const auto &Idx : SubRegIndices) {
  682. const SmallVector<MaskRolPair, 1> &IdxSequence
  683. = Idx.CompositionLaneMaskTransform;
  684. unsigned Found = ~0u;
  685. unsigned SIdx = 0;
  686. unsigned NextSIdx;
  687. for (size_t s = 0, se = Sequences.size(); s != se; ++s, SIdx = NextSIdx) {
  688. SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
  689. NextSIdx = SIdx + Sequence.size() + 1;
  690. if (Sequence == IdxSequence) {
  691. Found = SIdx;
  692. break;
  693. }
  694. }
  695. if (Found == ~0u) {
  696. Sequences.push_back(IdxSequence);
  697. Found = SIdx;
  698. }
  699. SubReg2SequenceIndexMap.push_back(Found);
  700. }
  701. OS << " struct MaskRolOp {\n"
  702. " LaneBitmask Mask;\n"
  703. " uint8_t RotateLeft;\n"
  704. " };\n"
  705. " static const MaskRolOp LaneMaskComposeSequences[] = {\n";
  706. unsigned Idx = 0;
  707. for (size_t s = 0, se = Sequences.size(); s != se; ++s) {
  708. OS << " ";
  709. const SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
  710. for (size_t p = 0, pe = Sequence.size(); p != pe; ++p) {
  711. const MaskRolPair &P = Sequence[p];
  712. printMask(OS << "{ ", P.Mask);
  713. OS << format(", %2u }, ", P.RotateLeft);
  714. }
  715. OS << "{ LaneBitmask::getNone(), 0 }";
  716. if (s+1 != se)
  717. OS << ", ";
  718. OS << " // Sequence " << Idx << "\n";
  719. Idx += Sequence.size() + 1;
  720. }
  721. auto *IntType = getMinimalTypeForRange(*std::max_element(
  722. SubReg2SequenceIndexMap.begin(), SubReg2SequenceIndexMap.end()));
  723. OS << " };\n"
  724. " static const "
  725. << IntType << " CompositeSequences[] = {\n";
  726. for (size_t i = 0, e = SubRegIndices.size(); i != e; ++i) {
  727. OS << " ";
  728. OS << SubReg2SequenceIndexMap[i];
  729. if (i+1 != e)
  730. OS << ",";
  731. OS << " // to " << SubRegIndices[i].getName() << "\n";
  732. }
  733. OS << " };\n\n";
  734. OS << "LaneBitmask " << ClName
  735. << "::composeSubRegIndexLaneMaskImpl(unsigned IdxA, LaneBitmask LaneMask)"
  736. " const {\n"
  737. " --IdxA; assert(IdxA < " << SubRegIndices.size()
  738. << " && \"Subregister index out of bounds\");\n"
  739. " LaneBitmask Result;\n"
  740. " for (const MaskRolOp *Ops =\n"
  741. " &LaneMaskComposeSequences[CompositeSequences[IdxA]];\n"
  742. " Ops->Mask.any(); ++Ops) {\n"
  743. " LaneBitmask::Type M = LaneMask.getAsInteger() & Ops->Mask.getAsInteger();\n"
  744. " if (unsigned S = Ops->RotateLeft)\n"
  745. " Result |= LaneBitmask((M << S) | (M >> (LaneBitmask::BitWidth - S)));\n"
  746. " else\n"
  747. " Result |= LaneBitmask(M);\n"
  748. " }\n"
  749. " return Result;\n"
  750. "}\n\n";
  751. OS << "LaneBitmask " << ClName
  752. << "::reverseComposeSubRegIndexLaneMaskImpl(unsigned IdxA, "
  753. " LaneBitmask LaneMask) const {\n"
  754. " LaneMask &= getSubRegIndexLaneMask(IdxA);\n"
  755. " --IdxA; assert(IdxA < " << SubRegIndices.size()
  756. << " && \"Subregister index out of bounds\");\n"
  757. " LaneBitmask Result;\n"
  758. " for (const MaskRolOp *Ops =\n"
  759. " &LaneMaskComposeSequences[CompositeSequences[IdxA]];\n"
  760. " Ops->Mask.any(); ++Ops) {\n"
  761. " LaneBitmask::Type M = LaneMask.getAsInteger();\n"
  762. " if (unsigned S = Ops->RotateLeft)\n"
  763. " Result |= LaneBitmask((M >> S) | (M << (LaneBitmask::BitWidth - S)));\n"
  764. " else\n"
  765. " Result |= LaneBitmask(M);\n"
  766. " }\n"
  767. " return Result;\n"
  768. "}\n\n";
  769. }
  770. //
  771. // runMCDesc - Print out MC register descriptions.
  772. //
  773. void
  774. RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target,
  775. CodeGenRegBank &RegBank) {
  776. emitSourceFileHeader("MC Register Information", OS);
  777. OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
  778. OS << "#undef GET_REGINFO_MC_DESC\n\n";
  779. const auto &Regs = RegBank.getRegisters();
  780. auto &SubRegIndices = RegBank.getSubRegIndices();
  781. // The lists of sub-registers and super-registers go in the same array. That
  782. // allows us to share suffixes.
  783. typedef std::vector<const CodeGenRegister*> RegVec;
  784. // Differentially encoded lists.
  785. SequenceToOffsetTable<DiffVec> DiffSeqs;
  786. SmallVector<DiffVec, 4> SubRegLists(Regs.size());
  787. SmallVector<DiffVec, 4> SuperRegLists(Regs.size());
  788. SmallVector<DiffVec, 4> RegUnitLists(Regs.size());
  789. SmallVector<unsigned, 4> RegUnitInitScale(Regs.size());
  790. // List of lane masks accompanying register unit sequences.
  791. SequenceToOffsetTable<MaskVec> LaneMaskSeqs;
  792. SmallVector<MaskVec, 4> RegUnitLaneMasks(Regs.size());
  793. // Keep track of sub-register names as well. These are not differentially
  794. // encoded.
  795. typedef SmallVector<const CodeGenSubRegIndex*, 4> SubRegIdxVec;
  796. SequenceToOffsetTable<SubRegIdxVec, deref<std::less<>>> SubRegIdxSeqs;
  797. SmallVector<SubRegIdxVec, 4> SubRegIdxLists(Regs.size());
  798. SequenceToOffsetTable<std::string> RegStrings;
  799. // Precompute register lists for the SequenceToOffsetTable.
  800. unsigned i = 0;
  801. for (auto I = Regs.begin(), E = Regs.end(); I != E; ++I, ++i) {
  802. const auto &Reg = *I;
  803. RegStrings.add(std::string(Reg.getName()));
  804. // Compute the ordered sub-register list.
  805. SetVector<const CodeGenRegister*> SR;
  806. Reg.addSubRegsPreOrder(SR, RegBank);
  807. diffEncode(SubRegLists[i], Reg.EnumValue, SR.begin(), SR.end());
  808. DiffSeqs.add(SubRegLists[i]);
  809. // Compute the corresponding sub-register indexes.
  810. SubRegIdxVec &SRIs = SubRegIdxLists[i];
  811. for (const CodeGenRegister *S : SR)
  812. SRIs.push_back(Reg.getSubRegIndex(S));
  813. SubRegIdxSeqs.add(SRIs);
  814. // Super-registers are already computed.
  815. const RegVec &SuperRegList = Reg.getSuperRegs();
  816. diffEncode(SuperRegLists[i], Reg.EnumValue, SuperRegList.begin(),
  817. SuperRegList.end());
  818. DiffSeqs.add(SuperRegLists[i]);
  819. // Differentially encode the register unit list, seeded by register number.
  820. // First compute a scale factor that allows more diff-lists to be reused:
  821. //
  822. // D0 -> (S0, S1)
  823. // D1 -> (S2, S3)
  824. //
  825. // A scale factor of 2 allows D0 and D1 to share a diff-list. The initial
  826. // value for the differential decoder is the register number multiplied by
  827. // the scale.
  828. //
  829. // Check the neighboring registers for arithmetic progressions.
  830. unsigned ScaleA = ~0u, ScaleB = ~0u;
  831. SparseBitVector<> RUs = Reg.getNativeRegUnits();
  832. if (I != Regs.begin() &&
  833. std::prev(I)->getNativeRegUnits().count() == RUs.count())
  834. ScaleB = *RUs.begin() - *std::prev(I)->getNativeRegUnits().begin();
  835. if (std::next(I) != Regs.end() &&
  836. std::next(I)->getNativeRegUnits().count() == RUs.count())
  837. ScaleA = *std::next(I)->getNativeRegUnits().begin() - *RUs.begin();
  838. unsigned Scale = std::min(ScaleB, ScaleA);
  839. // Default the scale to 0 if it can't be encoded in 4 bits.
  840. if (Scale >= 16)
  841. Scale = 0;
  842. RegUnitInitScale[i] = Scale;
  843. DiffSeqs.add(diffEncode(RegUnitLists[i], Scale * Reg.EnumValue, RUs));
  844. const auto &RUMasks = Reg.getRegUnitLaneMasks();
  845. MaskVec &LaneMaskVec = RegUnitLaneMasks[i];
  846. assert(LaneMaskVec.empty());
  847. llvm::append_range(LaneMaskVec, RUMasks);
  848. // Terminator mask should not be used inside of the list.
  849. #ifndef NDEBUG
  850. for (LaneBitmask M : LaneMaskVec) {
  851. assert(!M.all() && "terminator mask should not be part of the list");
  852. }
  853. #endif
  854. LaneMaskSeqs.add(LaneMaskVec);
  855. }
  856. // Compute the final layout of the sequence table.
  857. DiffSeqs.layout();
  858. LaneMaskSeqs.layout();
  859. SubRegIdxSeqs.layout();
  860. OS << "namespace llvm {\n\n";
  861. const std::string &TargetName = std::string(Target.getName());
  862. // Emit the shared table of differential lists.
  863. OS << "extern const MCPhysReg " << TargetName << "RegDiffLists[] = {\n";
  864. DiffSeqs.emit(OS, printDiff16);
  865. OS << "};\n\n";
  866. // Emit the shared table of regunit lane mask sequences.
  867. OS << "extern const LaneBitmask " << TargetName << "LaneMaskLists[] = {\n";
  868. LaneMaskSeqs.emit(OS, printMask, "LaneBitmask::getAll()");
  869. OS << "};\n\n";
  870. // Emit the table of sub-register indexes.
  871. OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[] = {\n";
  872. SubRegIdxSeqs.emit(OS, printSubRegIndex);
  873. OS << "};\n\n";
  874. // Emit the table of sub-register index sizes.
  875. OS << "extern const MCRegisterInfo::SubRegCoveredBits "
  876. << TargetName << "SubRegIdxRanges[] = {\n";
  877. OS << " { " << (uint16_t)-1 << ", " << (uint16_t)-1 << " },\n";
  878. for (const auto &Idx : SubRegIndices) {
  879. OS << " { " << Idx.Offset << ", " << Idx.Size << " },\t// "
  880. << Idx.getName() << "\n";
  881. }
  882. OS << "};\n\n";
  883. // Emit the string table.
  884. RegStrings.layout();
  885. RegStrings.emitStringLiteralDef(OS, Twine("extern const char ") + TargetName +
  886. "RegStrings[]");
  887. OS << "extern const MCRegisterDesc " << TargetName
  888. << "RegDesc[] = { // Descriptors\n";
  889. OS << " { " << RegStrings.get("") << ", 0, 0, 0, 0, 0 },\n";
  890. // Emit the register descriptors now.
  891. i = 0;
  892. for (const auto &Reg : Regs) {
  893. OS << " { " << RegStrings.get(std::string(Reg.getName())) << ", "
  894. << DiffSeqs.get(SubRegLists[i]) << ", " << DiffSeqs.get(SuperRegLists[i])
  895. << ", " << SubRegIdxSeqs.get(SubRegIdxLists[i]) << ", "
  896. << (DiffSeqs.get(RegUnitLists[i]) * 16 + RegUnitInitScale[i]) << ", "
  897. << LaneMaskSeqs.get(RegUnitLaneMasks[i]) << " },\n";
  898. ++i;
  899. }
  900. OS << "};\n\n"; // End of register descriptors...
  901. // Emit the table of register unit roots. Each regunit has one or two root
  902. // registers.
  903. OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2] = {\n";
  904. for (unsigned i = 0, e = RegBank.getNumNativeRegUnits(); i != e; ++i) {
  905. ArrayRef<const CodeGenRegister*> Roots = RegBank.getRegUnit(i).getRoots();
  906. assert(!Roots.empty() && "All regunits must have a root register.");
  907. assert(Roots.size() <= 2 && "More than two roots not supported yet.");
  908. OS << " { ";
  909. ListSeparator LS;
  910. for (const CodeGenRegister *R : Roots)
  911. OS << LS << getQualifiedName(R->TheDef);
  912. OS << " },\n";
  913. }
  914. OS << "};\n\n";
  915. const auto &RegisterClasses = RegBank.getRegClasses();
  916. // Loop over all of the register classes... emitting each one.
  917. OS << "namespace { // Register classes...\n";
  918. SequenceToOffsetTable<std::string> RegClassStrings;
  919. // Emit the register enum value arrays for each RegisterClass
  920. for (const auto &RC : RegisterClasses) {
  921. ArrayRef<Record*> Order = RC.getOrder();
  922. // Give the register class a legal C name if it's anonymous.
  923. const std::string &Name = RC.getName();
  924. RegClassStrings.add(Name);
  925. // Emit the register list now (unless it would be a zero-length array).
  926. if (!Order.empty()) {
  927. OS << " // " << Name << " Register Class...\n"
  928. << " const MCPhysReg " << Name << "[] = {\n ";
  929. for (Record *Reg : Order) {
  930. OS << getQualifiedName(Reg) << ", ";
  931. }
  932. OS << "\n };\n\n";
  933. OS << " // " << Name << " Bit set.\n"
  934. << " const uint8_t " << Name << "Bits[] = {\n ";
  935. BitVectorEmitter BVE;
  936. for (Record *Reg : Order) {
  937. BVE.add(Target.getRegBank().getReg(Reg)->EnumValue);
  938. }
  939. BVE.print(OS);
  940. OS << "\n };\n\n";
  941. }
  942. }
  943. OS << "} // end anonymous namespace\n\n";
  944. RegClassStrings.layout();
  945. RegClassStrings.emitStringLiteralDef(
  946. OS, Twine("extern const char ") + TargetName + "RegClassStrings[]");
  947. OS << "extern const MCRegisterClass " << TargetName
  948. << "MCRegisterClasses[] = {\n";
  949. for (const auto &RC : RegisterClasses) {
  950. ArrayRef<Record *> Order = RC.getOrder();
  951. std::string RCName = Order.empty() ? "nullptr" : RC.getName();
  952. std::string RCBitsName = Order.empty() ? "nullptr" : RC.getName() + "Bits";
  953. std::string RCBitsSize = Order.empty() ? "0" : "sizeof(" + RCBitsName + ")";
  954. assert(isInt<8>(RC.CopyCost) && "Copy cost too large.");
  955. uint32_t RegSize = 0;
  956. if (RC.RSI.isSimple())
  957. RegSize = RC.RSI.getSimple().RegSize;
  958. OS << " { " << RCName << ", " << RCBitsName << ", "
  959. << RegClassStrings.get(RC.getName()) << ", " << RC.getOrder().size()
  960. << ", " << RCBitsSize << ", " << RC.getQualifiedName() + "RegClassID"
  961. << ", " << RegSize << ", " << RC.CopyCost << ", "
  962. << (RC.Allocatable ? "true" : "false") << " },\n";
  963. }
  964. OS << "};\n\n";
  965. EmitRegMappingTables(OS, Regs, false);
  966. // Emit Reg encoding table
  967. OS << "extern const uint16_t " << TargetName;
  968. OS << "RegEncodingTable[] = {\n";
  969. // Add entry for NoRegister
  970. OS << " 0,\n";
  971. for (const auto &RE : Regs) {
  972. Record *Reg = RE.TheDef;
  973. BitsInit *BI = Reg->getValueAsBitsInit("HWEncoding");
  974. uint64_t Value = 0;
  975. for (unsigned b = 0, be = BI->getNumBits(); b != be; ++b) {
  976. if (BitInit *B = dyn_cast<BitInit>(BI->getBit(b)))
  977. Value |= (uint64_t)B->getValue() << b;
  978. }
  979. OS << " " << Value << ",\n";
  980. }
  981. OS << "};\n"; // End of HW encoding table
  982. // MCRegisterInfo initialization routine.
  983. OS << "static inline void Init" << TargetName
  984. << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
  985. << "unsigned DwarfFlavour = 0, unsigned EHFlavour = 0, unsigned PC = 0) "
  986. "{\n"
  987. << " RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
  988. << Regs.size() + 1 << ", RA, PC, " << TargetName << "MCRegisterClasses, "
  989. << RegisterClasses.size() << ", " << TargetName << "RegUnitRoots, "
  990. << RegBank.getNumNativeRegUnits() << ", " << TargetName << "RegDiffLists, "
  991. << TargetName << "LaneMaskLists, " << TargetName << "RegStrings, "
  992. << TargetName << "RegClassStrings, " << TargetName << "SubRegIdxLists, "
  993. << (std::distance(SubRegIndices.begin(), SubRegIndices.end()) + 1) << ",\n"
  994. << TargetName << "SubRegIdxRanges, " << TargetName
  995. << "RegEncodingTable);\n\n";
  996. EmitRegMapping(OS, Regs, false);
  997. OS << "}\n\n";
  998. OS << "} // end namespace llvm\n\n";
  999. OS << "#endif // GET_REGINFO_MC_DESC\n\n";
  1000. }
  1001. void
  1002. RegisterInfoEmitter::runTargetHeader(raw_ostream &OS, CodeGenTarget &Target,
  1003. CodeGenRegBank &RegBank) {
  1004. emitSourceFileHeader("Register Information Header Fragment", OS);
  1005. OS << "\n#ifdef GET_REGINFO_HEADER\n";
  1006. OS << "#undef GET_REGINFO_HEADER\n\n";
  1007. const std::string &TargetName = std::string(Target.getName());
  1008. std::string ClassName = TargetName + "GenRegisterInfo";
  1009. OS << "#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n\n";
  1010. OS << "namespace llvm {\n\n";
  1011. OS << "class " << TargetName << "FrameLowering;\n\n";
  1012. OS << "struct " << ClassName << " : public TargetRegisterInfo {\n"
  1013. << " explicit " << ClassName
  1014. << "(unsigned RA, unsigned D = 0, unsigned E = 0,\n"
  1015. << " unsigned PC = 0, unsigned HwMode = 0);\n";
  1016. if (!RegBank.getSubRegIndices().empty()) {
  1017. OS << " unsigned composeSubRegIndicesImpl"
  1018. << "(unsigned, unsigned) const override;\n"
  1019. << " LaneBitmask composeSubRegIndexLaneMaskImpl"
  1020. << "(unsigned, LaneBitmask) const override;\n"
  1021. << " LaneBitmask reverseComposeSubRegIndexLaneMaskImpl"
  1022. << "(unsigned, LaneBitmask) const override;\n"
  1023. << " const TargetRegisterClass *getSubClassWithSubReg"
  1024. << "(const TargetRegisterClass *, unsigned) const override;\n"
  1025. << " const TargetRegisterClass *getSubRegisterClass"
  1026. << "(const TargetRegisterClass *, unsigned) const override;\n";
  1027. }
  1028. OS << " const RegClassWeight &getRegClassWeight("
  1029. << "const TargetRegisterClass *RC) const override;\n"
  1030. << " unsigned getRegUnitWeight(unsigned RegUnit) const override;\n"
  1031. << " unsigned getNumRegPressureSets() const override;\n"
  1032. << " const char *getRegPressureSetName(unsigned Idx) const override;\n"
  1033. << " unsigned getRegPressureSetLimit(const MachineFunction &MF, unsigned "
  1034. "Idx) const override;\n"
  1035. << " const int *getRegClassPressureSets("
  1036. << "const TargetRegisterClass *RC) const override;\n"
  1037. << " const int *getRegUnitPressureSets("
  1038. << "unsigned RegUnit) const override;\n"
  1039. << " ArrayRef<const char *> getRegMaskNames() const override;\n"
  1040. << " ArrayRef<const uint32_t *> getRegMasks() const override;\n"
  1041. << " bool isGeneralPurposeRegister(const MachineFunction &, "
  1042. << "MCRegister) const override;\n"
  1043. << " bool isFixedRegister(const MachineFunction &, "
  1044. << "MCRegister) const override;\n"
  1045. << " bool isArgumentRegister(const MachineFunction &, "
  1046. << "MCRegister) const override;\n"
  1047. << " bool isConstantPhysReg(MCRegister PhysReg) const override final;\n"
  1048. << " /// Devirtualized TargetFrameLowering.\n"
  1049. << " static const " << TargetName << "FrameLowering *getFrameLowering(\n"
  1050. << " const MachineFunction &MF);\n";
  1051. const auto &RegisterClasses = RegBank.getRegClasses();
  1052. if (llvm::any_of(RegisterClasses, [](const auto &RC) { return RC.getBaseClassOrder(); })) {
  1053. OS << " const TargetRegisterClass *getPhysRegBaseClass(MCRegister Reg) const override;\n";
  1054. }
  1055. OS << "};\n\n";
  1056. if (!RegisterClasses.empty()) {
  1057. OS << "namespace " << RegisterClasses.front().Namespace
  1058. << " { // Register classes\n";
  1059. for (const auto &RC : RegisterClasses) {
  1060. const std::string &Name = RC.getName();
  1061. // Output the extern for the instance.
  1062. OS << " extern const TargetRegisterClass " << Name << "RegClass;\n";
  1063. }
  1064. OS << "} // end namespace " << RegisterClasses.front().Namespace << "\n\n";
  1065. }
  1066. OS << "} // end namespace llvm\n\n";
  1067. OS << "#endif // GET_REGINFO_HEADER\n\n";
  1068. }
  1069. //
  1070. // runTargetDesc - Output the target register and register file descriptions.
  1071. //
  1072. void
  1073. RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target,
  1074. CodeGenRegBank &RegBank){
  1075. emitSourceFileHeader("Target Register and Register Classes Information", OS);
  1076. OS << "\n#ifdef GET_REGINFO_TARGET_DESC\n";
  1077. OS << "#undef GET_REGINFO_TARGET_DESC\n\n";
  1078. OS << "namespace llvm {\n\n";
  1079. // Get access to MCRegisterClass data.
  1080. OS << "extern const MCRegisterClass " << Target.getName()
  1081. << "MCRegisterClasses[];\n";
  1082. // Start out by emitting each of the register classes.
  1083. const auto &RegisterClasses = RegBank.getRegClasses();
  1084. const auto &SubRegIndices = RegBank.getSubRegIndices();
  1085. // Collect all registers belonging to any allocatable class.
  1086. std::set<Record*> AllocatableRegs;
  1087. // Collect allocatable registers.
  1088. for (const auto &RC : RegisterClasses) {
  1089. ArrayRef<Record*> Order = RC.getOrder();
  1090. if (RC.Allocatable)
  1091. AllocatableRegs.insert(Order.begin(), Order.end());
  1092. }
  1093. const CodeGenHwModes &CGH = Target.getHwModes();
  1094. unsigned NumModes = CGH.getNumModeIds();
  1095. // Build a shared array of value types.
  1096. SequenceToOffsetTable<std::vector<MVT::SimpleValueType>> VTSeqs;
  1097. for (unsigned M = 0; M < NumModes; ++M) {
  1098. for (const auto &RC : RegisterClasses) {
  1099. std::vector<MVT::SimpleValueType> S;
  1100. for (const ValueTypeByHwMode &VVT : RC.VTs)
  1101. S.push_back(VVT.get(M).SimpleTy);
  1102. VTSeqs.add(S);
  1103. }
  1104. }
  1105. VTSeqs.layout();
  1106. OS << "\nstatic const MVT::SimpleValueType VTLists[] = {\n";
  1107. VTSeqs.emit(OS, printSimpleValueType, "MVT::Other");
  1108. OS << "};\n";
  1109. // Emit SubRegIndex names, skipping 0.
  1110. OS << "\nstatic const char *SubRegIndexNameTable[] = { \"";
  1111. for (const auto &Idx : SubRegIndices) {
  1112. OS << Idx.getName();
  1113. OS << "\", \"";
  1114. }
  1115. OS << "\" };\n\n";
  1116. // Emit SubRegIndex lane masks, including 0.
  1117. OS << "\nstatic const LaneBitmask SubRegIndexLaneMaskTable[] = {\n "
  1118. "LaneBitmask::getAll(),\n";
  1119. for (const auto &Idx : SubRegIndices) {
  1120. printMask(OS << " ", Idx.LaneMask);
  1121. OS << ", // " << Idx.getName() << '\n';
  1122. }
  1123. OS << " };\n\n";
  1124. OS << "\n";
  1125. // Now that all of the structs have been emitted, emit the instances.
  1126. if (!RegisterClasses.empty()) {
  1127. OS << "\nstatic const TargetRegisterInfo::RegClassInfo RegClassInfos[]"
  1128. << " = {\n";
  1129. for (unsigned M = 0; M < NumModes; ++M) {
  1130. unsigned EV = 0;
  1131. OS << " // Mode = " << M << " (";
  1132. if (M == 0)
  1133. OS << "Default";
  1134. else
  1135. OS << CGH.getMode(M).Name;
  1136. OS << ")\n";
  1137. for (const auto &RC : RegisterClasses) {
  1138. assert(RC.EnumValue == EV && "Unexpected order of register classes");
  1139. ++EV;
  1140. (void)EV;
  1141. const RegSizeInfo &RI = RC.RSI.get(M);
  1142. OS << " { " << RI.RegSize << ", " << RI.SpillSize << ", "
  1143. << RI.SpillAlignment;
  1144. std::vector<MVT::SimpleValueType> VTs;
  1145. for (const ValueTypeByHwMode &VVT : RC.VTs)
  1146. VTs.push_back(VVT.get(M).SimpleTy);
  1147. OS << ", VTLists+" << VTSeqs.get(VTs) << " }, // "
  1148. << RC.getName() << '\n';
  1149. }
  1150. }
  1151. OS << "};\n";
  1152. OS << "\nstatic const TargetRegisterClass *const "
  1153. << "NullRegClasses[] = { nullptr };\n\n";
  1154. // Emit register class bit mask tables. The first bit mask emitted for a
  1155. // register class, RC, is the set of sub-classes, including RC itself.
  1156. //
  1157. // If RC has super-registers, also create a list of subreg indices and bit
  1158. // masks, (Idx, Mask). The bit mask has a bit for every superreg regclass,
  1159. // SuperRC, that satisfies:
  1160. //
  1161. // For all SuperReg in SuperRC: SuperReg:Idx in RC
  1162. //
  1163. // The 0-terminated list of subreg indices starts at:
  1164. //
  1165. // RC->getSuperRegIndices() = SuperRegIdxSeqs + ...
  1166. //
  1167. // The corresponding bitmasks follow the sub-class mask in memory. Each
  1168. // mask has RCMaskWords uint32_t entries.
  1169. //
  1170. // Every bit mask present in the list has at least one bit set.
  1171. // Compress the sub-reg index lists.
  1172. typedef std::vector<const CodeGenSubRegIndex*> IdxList;
  1173. SmallVector<IdxList, 8> SuperRegIdxLists(RegisterClasses.size());
  1174. SequenceToOffsetTable<IdxList, deref<std::less<>>> SuperRegIdxSeqs;
  1175. BitVector MaskBV(RegisterClasses.size());
  1176. for (const auto &RC : RegisterClasses) {
  1177. OS << "static const uint32_t " << RC.getName()
  1178. << "SubClassMask[] = {\n ";
  1179. printBitVectorAsHex(OS, RC.getSubClasses(), 32);
  1180. // Emit super-reg class masks for any relevant SubRegIndices that can
  1181. // project into RC.
  1182. IdxList &SRIList = SuperRegIdxLists[RC.EnumValue];
  1183. for (auto &Idx : SubRegIndices) {
  1184. MaskBV.reset();
  1185. RC.getSuperRegClasses(&Idx, MaskBV);
  1186. if (MaskBV.none())
  1187. continue;
  1188. SRIList.push_back(&Idx);
  1189. OS << "\n ";
  1190. printBitVectorAsHex(OS, MaskBV, 32);
  1191. OS << "// " << Idx.getName();
  1192. }
  1193. SuperRegIdxSeqs.add(SRIList);
  1194. OS << "\n};\n\n";
  1195. }
  1196. OS << "static const uint16_t SuperRegIdxSeqs[] = {\n";
  1197. SuperRegIdxSeqs.layout();
  1198. SuperRegIdxSeqs.emit(OS, printSubRegIndex);
  1199. OS << "};\n\n";
  1200. // Emit NULL terminated super-class lists.
  1201. for (const auto &RC : RegisterClasses) {
  1202. ArrayRef<CodeGenRegisterClass*> Supers = RC.getSuperClasses();
  1203. // Skip classes without supers. We can reuse NullRegClasses.
  1204. if (Supers.empty())
  1205. continue;
  1206. OS << "static const TargetRegisterClass *const "
  1207. << RC.getName() << "Superclasses[] = {\n";
  1208. for (const auto *Super : Supers)
  1209. OS << " &" << Super->getQualifiedName() << "RegClass,\n";
  1210. OS << " nullptr\n};\n\n";
  1211. }
  1212. // Emit methods.
  1213. for (const auto &RC : RegisterClasses) {
  1214. if (!RC.AltOrderSelect.empty()) {
  1215. OS << "\nstatic inline unsigned " << RC.getName()
  1216. << "AltOrderSelect(const MachineFunction &MF) {"
  1217. << RC.AltOrderSelect << "}\n\n"
  1218. << "static ArrayRef<MCPhysReg> " << RC.getName()
  1219. << "GetRawAllocationOrder(const MachineFunction &MF) {\n";
  1220. for (unsigned oi = 1 , oe = RC.getNumOrders(); oi != oe; ++oi) {
  1221. ArrayRef<Record*> Elems = RC.getOrder(oi);
  1222. if (!Elems.empty()) {
  1223. OS << " static const MCPhysReg AltOrder" << oi << "[] = {";
  1224. for (unsigned elem = 0; elem != Elems.size(); ++elem)
  1225. OS << (elem ? ", " : " ") << getQualifiedName(Elems[elem]);
  1226. OS << " };\n";
  1227. }
  1228. }
  1229. OS << " const MCRegisterClass &MCR = " << Target.getName()
  1230. << "MCRegisterClasses[" << RC.getQualifiedName() + "RegClassID];\n"
  1231. << " const ArrayRef<MCPhysReg> Order[] = {\n"
  1232. << " ArrayRef(MCR.begin(), MCR.getNumRegs()";
  1233. for (unsigned oi = 1, oe = RC.getNumOrders(); oi != oe; ++oi)
  1234. if (RC.getOrder(oi).empty())
  1235. OS << "),\n ArrayRef<MCPhysReg>(";
  1236. else
  1237. OS << "),\n ArrayRef(AltOrder" << oi;
  1238. OS << ")\n };\n const unsigned Select = " << RC.getName()
  1239. << "AltOrderSelect(MF);\n assert(Select < " << RC.getNumOrders()
  1240. << ");\n return Order[Select];\n}\n";
  1241. }
  1242. }
  1243. // Now emit the actual value-initialized register class instances.
  1244. OS << "\nnamespace " << RegisterClasses.front().Namespace
  1245. << " { // Register class instances\n";
  1246. for (const auto &RC : RegisterClasses) {
  1247. OS << " extern const TargetRegisterClass " << RC.getName()
  1248. << "RegClass = {\n " << '&' << Target.getName()
  1249. << "MCRegisterClasses[" << RC.getName() << "RegClassID],\n "
  1250. << RC.getName() << "SubClassMask,\n SuperRegIdxSeqs + "
  1251. << SuperRegIdxSeqs.get(SuperRegIdxLists[RC.EnumValue]) << ",\n ";
  1252. printMask(OS, RC.LaneMask);
  1253. OS << ",\n " << (unsigned)RC.AllocationPriority << ",\n "
  1254. << (RC.GlobalPriority ? "true" : "false") << ",\n "
  1255. << format("0x%02x", RC.TSFlags) << ", /* TSFlags */\n "
  1256. << (RC.HasDisjunctSubRegs ? "true" : "false")
  1257. << ", /* HasDisjunctSubRegs */\n "
  1258. << (RC.CoveredBySubRegs ? "true" : "false")
  1259. << ", /* CoveredBySubRegs */\n ";
  1260. if (RC.getSuperClasses().empty())
  1261. OS << "NullRegClasses,\n ";
  1262. else
  1263. OS << RC.getName() << "Superclasses,\n ";
  1264. if (RC.AltOrderSelect.empty())
  1265. OS << "nullptr\n";
  1266. else
  1267. OS << RC.getName() << "GetRawAllocationOrder\n";
  1268. OS << " };\n\n";
  1269. }
  1270. OS << "} // end namespace " << RegisterClasses.front().Namespace << "\n";
  1271. }
  1272. OS << "\nnamespace {\n";
  1273. OS << " const TargetRegisterClass *const RegisterClasses[] = {\n";
  1274. for (const auto &RC : RegisterClasses)
  1275. OS << " &" << RC.getQualifiedName() << "RegClass,\n";
  1276. OS << " };\n";
  1277. OS << "} // end anonymous namespace\n";
  1278. // Emit extra information about registers.
  1279. const std::string &TargetName = std::string(Target.getName());
  1280. const auto &Regs = RegBank.getRegisters();
  1281. unsigned NumRegCosts = 1;
  1282. for (const auto &Reg : Regs)
  1283. NumRegCosts = std::max((size_t)NumRegCosts, Reg.CostPerUse.size());
  1284. std::vector<unsigned> AllRegCostPerUse;
  1285. llvm::BitVector InAllocClass(Regs.size() + 1, false);
  1286. AllRegCostPerUse.insert(AllRegCostPerUse.end(), NumRegCosts, 0);
  1287. // Populate the vector RegCosts with the CostPerUse list of the registers
  1288. // in the order they are read. Have at most NumRegCosts entries for
  1289. // each register. Fill with zero for values which are not explicitly given.
  1290. for (const auto &Reg : Regs) {
  1291. auto Costs = Reg.CostPerUse;
  1292. AllRegCostPerUse.insert(AllRegCostPerUse.end(), Costs.begin(), Costs.end());
  1293. if (NumRegCosts > Costs.size())
  1294. AllRegCostPerUse.insert(AllRegCostPerUse.end(),
  1295. NumRegCosts - Costs.size(), 0);
  1296. if (AllocatableRegs.count(Reg.TheDef))
  1297. InAllocClass.set(Reg.EnumValue);
  1298. }
  1299. // Emit the cost values as a 1D-array after grouping them by their indices,
  1300. // i.e. the costs for all registers corresponds to index 0, 1, 2, etc.
  1301. // Size of the emitted array should be NumRegCosts * (Regs.size() + 1).
  1302. OS << "\nstatic const uint8_t "
  1303. << "CostPerUseTable[] = { \n";
  1304. for (unsigned int I = 0; I < NumRegCosts; ++I) {
  1305. for (unsigned J = I, E = AllRegCostPerUse.size(); J < E; J += NumRegCosts)
  1306. OS << AllRegCostPerUse[J] << ", ";
  1307. }
  1308. OS << "};\n\n";
  1309. OS << "\nstatic const bool "
  1310. << "InAllocatableClassTable[] = { \n";
  1311. for (unsigned I = 0, E = InAllocClass.size(); I < E; ++I) {
  1312. OS << (InAllocClass[I] ? "true" : "false") << ", ";
  1313. }
  1314. OS << "};\n\n";
  1315. OS << "\nstatic const TargetRegisterInfoDesc " << TargetName
  1316. << "RegInfoDesc = { // Extra Descriptors\n";
  1317. OS << "CostPerUseTable, " << NumRegCosts << ", "
  1318. << "InAllocatableClassTable";
  1319. OS << "};\n\n"; // End of register descriptors...
  1320. std::string ClassName = Target.getName().str() + "GenRegisterInfo";
  1321. auto SubRegIndicesSize =
  1322. std::distance(SubRegIndices.begin(), SubRegIndices.end());
  1323. if (!SubRegIndices.empty()) {
  1324. emitComposeSubRegIndices(OS, RegBank, ClassName);
  1325. emitComposeSubRegIndexLaneMask(OS, RegBank, ClassName);
  1326. }
  1327. if (!SubRegIndices.empty()) {
  1328. // Emit getSubClassWithSubReg.
  1329. OS << "const TargetRegisterClass *" << ClassName
  1330. << "::getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx)"
  1331. << " const {\n";
  1332. // Use the smallest type that can hold a regclass ID with room for a
  1333. // sentinel.
  1334. if (RegisterClasses.size() <= UINT8_MAX)
  1335. OS << " static const uint8_t Table[";
  1336. else if (RegisterClasses.size() <= UINT16_MAX)
  1337. OS << " static const uint16_t Table[";
  1338. else
  1339. PrintFatalError("Too many register classes.");
  1340. OS << RegisterClasses.size() << "][" << SubRegIndicesSize << "] = {\n";
  1341. for (const auto &RC : RegisterClasses) {
  1342. OS << " {\t// " << RC.getName() << "\n";
  1343. for (auto &Idx : SubRegIndices) {
  1344. if (CodeGenRegisterClass *SRC = RC.getSubClassWithSubReg(&Idx))
  1345. OS << " " << SRC->EnumValue + 1 << ",\t// " << Idx.getName()
  1346. << " -> " << SRC->getName() << "\n";
  1347. else
  1348. OS << " 0,\t// " << Idx.getName() << "\n";
  1349. }
  1350. OS << " },\n";
  1351. }
  1352. OS << " };\n assert(RC && \"Missing regclass\");\n"
  1353. << " if (!Idx) return RC;\n --Idx;\n"
  1354. << " assert(Idx < " << SubRegIndicesSize << " && \"Bad subreg\");\n"
  1355. << " unsigned TV = Table[RC->getID()][Idx];\n"
  1356. << " return TV ? getRegClass(TV - 1) : nullptr;\n}\n\n";
  1357. // Emit getSubRegisterClass
  1358. OS << "const TargetRegisterClass *" << ClassName
  1359. << "::getSubRegisterClass(const TargetRegisterClass *RC, unsigned Idx)"
  1360. << " const {\n";
  1361. // Use the smallest type that can hold a regclass ID with room for a
  1362. // sentinel.
  1363. if (RegisterClasses.size() <= UINT8_MAX)
  1364. OS << " static const uint8_t Table[";
  1365. else if (RegisterClasses.size() <= UINT16_MAX)
  1366. OS << " static const uint16_t Table[";
  1367. else
  1368. PrintFatalError("Too many register classes.");
  1369. OS << RegisterClasses.size() << "][" << SubRegIndicesSize << "] = {\n";
  1370. for (const auto &RC : RegisterClasses) {
  1371. OS << " {\t// " << RC.getName() << '\n';
  1372. for (auto &Idx : SubRegIndices) {
  1373. std::optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
  1374. MatchingSubClass = RC.getMatchingSubClassWithSubRegs(RegBank, &Idx);
  1375. unsigned EnumValue = 0;
  1376. if (MatchingSubClass) {
  1377. CodeGenRegisterClass *SubRegClass = MatchingSubClass->second;
  1378. EnumValue = SubRegClass->EnumValue + 1;
  1379. }
  1380. OS << " " << EnumValue << ",\t// "
  1381. << RC.getName() << ':' << Idx.getName();
  1382. if (MatchingSubClass) {
  1383. CodeGenRegisterClass *SubRegClass = MatchingSubClass->second;
  1384. OS << " -> " << SubRegClass->getName();
  1385. }
  1386. OS << '\n';
  1387. }
  1388. OS << " },\n";
  1389. }
  1390. OS << " };\n assert(RC && \"Missing regclass\");\n"
  1391. << " if (!Idx) return RC;\n --Idx;\n"
  1392. << " assert(Idx < " << SubRegIndicesSize << " && \"Bad subreg\");\n"
  1393. << " unsigned TV = Table[RC->getID()][Idx];\n"
  1394. << " return TV ? getRegClass(TV - 1) : nullptr;\n}\n\n";
  1395. }
  1396. EmitRegUnitPressure(OS, RegBank, ClassName);
  1397. // Emit register base class mapper
  1398. if (!RegisterClasses.empty()) {
  1399. // Collect base classes
  1400. SmallVector<const CodeGenRegisterClass*> BaseClasses;
  1401. for (const auto &RC : RegisterClasses) {
  1402. if (RC.getBaseClassOrder())
  1403. BaseClasses.push_back(&RC);
  1404. }
  1405. if (!BaseClasses.empty()) {
  1406. // Represent class indexes with uint8_t and allocate one index for nullptr
  1407. assert(BaseClasses.size() <= UINT8_MAX && "Too many base register classes");
  1408. // Apply order
  1409. struct BaseClassOrdering {
  1410. bool operator()(const CodeGenRegisterClass *LHS, const CodeGenRegisterClass *RHS) const {
  1411. return std::pair(*LHS->getBaseClassOrder(), LHS->EnumValue)
  1412. < std::pair(*RHS->getBaseClassOrder(), RHS->EnumValue);
  1413. }
  1414. };
  1415. llvm::stable_sort(BaseClasses, BaseClassOrdering());
  1416. // Build mapping for Regs (+1 for NoRegister)
  1417. std::vector<uint8_t> Mapping(Regs.size() + 1, 0);
  1418. for (int RCIdx = BaseClasses.size() - 1; RCIdx >= 0; --RCIdx) {
  1419. for (const auto Reg : BaseClasses[RCIdx]->getMembers())
  1420. Mapping[Reg->EnumValue] = RCIdx + 1;
  1421. }
  1422. OS << "\n// Register to base register class mapping\n\n";
  1423. OS << "\n";
  1424. OS << "const TargetRegisterClass *" << ClassName
  1425. << "::getPhysRegBaseClass(MCRegister Reg)"
  1426. << " const {\n";
  1427. OS << " static const TargetRegisterClass *BaseClasses[" << (BaseClasses.size() + 1) << "] = {\n";
  1428. OS << " nullptr,\n";
  1429. for (const auto RC : BaseClasses)
  1430. OS << " &" << RC->getQualifiedName() << "RegClass,\n";
  1431. OS << " };\n";
  1432. OS << " static const uint8_t Mapping[" << Mapping.size() << "] = {\n ";
  1433. for (const uint8_t Value : Mapping)
  1434. OS << (unsigned)Value << ",";
  1435. OS << " };\n\n";
  1436. OS << " assert(Reg < sizeof(Mapping));\n";
  1437. OS << " return BaseClasses[Mapping[Reg]];\n";
  1438. OS << "}\n";
  1439. }
  1440. }
  1441. // Emit the constructor of the class...
  1442. OS << "extern const MCRegisterDesc " << TargetName << "RegDesc[];\n";
  1443. OS << "extern const MCPhysReg " << TargetName << "RegDiffLists[];\n";
  1444. OS << "extern const LaneBitmask " << TargetName << "LaneMaskLists[];\n";
  1445. OS << "extern const char " << TargetName << "RegStrings[];\n";
  1446. OS << "extern const char " << TargetName << "RegClassStrings[];\n";
  1447. OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2];\n";
  1448. OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[];\n";
  1449. OS << "extern const MCRegisterInfo::SubRegCoveredBits "
  1450. << TargetName << "SubRegIdxRanges[];\n";
  1451. OS << "extern const uint16_t " << TargetName << "RegEncodingTable[];\n";
  1452. EmitRegMappingTables(OS, Regs, true);
  1453. OS << ClassName << "::\n"
  1454. << ClassName
  1455. << "(unsigned RA, unsigned DwarfFlavour, unsigned EHFlavour,\n"
  1456. " unsigned PC, unsigned HwMode)\n"
  1457. << " : TargetRegisterInfo(&" << TargetName << "RegInfoDesc"
  1458. << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() << ",\n"
  1459. << " SubRegIndexNameTable, SubRegIndexLaneMaskTable,\n"
  1460. << " ";
  1461. printMask(OS, RegBank.CoveringLanes);
  1462. OS << ", RegClassInfos, HwMode) {\n"
  1463. << " InitMCRegisterInfo(" << TargetName << "RegDesc, " << Regs.size() + 1
  1464. << ", RA, PC,\n " << TargetName
  1465. << "MCRegisterClasses, " << RegisterClasses.size() << ",\n"
  1466. << " " << TargetName << "RegUnitRoots,\n"
  1467. << " " << RegBank.getNumNativeRegUnits() << ",\n"
  1468. << " " << TargetName << "RegDiffLists,\n"
  1469. << " " << TargetName << "LaneMaskLists,\n"
  1470. << " " << TargetName << "RegStrings,\n"
  1471. << " " << TargetName << "RegClassStrings,\n"
  1472. << " " << TargetName << "SubRegIdxLists,\n"
  1473. << " " << SubRegIndicesSize + 1 << ",\n"
  1474. << " " << TargetName << "SubRegIdxRanges,\n"
  1475. << " " << TargetName << "RegEncodingTable);\n\n";
  1476. EmitRegMapping(OS, Regs, true);
  1477. OS << "}\n\n";
  1478. // Emit CalleeSavedRegs information.
  1479. std::vector<Record*> CSRSets =
  1480. Records.getAllDerivedDefinitions("CalleeSavedRegs");
  1481. for (unsigned i = 0, e = CSRSets.size(); i != e; ++i) {
  1482. Record *CSRSet = CSRSets[i];
  1483. const SetTheory::RecVec *Regs = RegBank.getSets().expand(CSRSet);
  1484. assert(Regs && "Cannot expand CalleeSavedRegs instance");
  1485. // Emit the *_SaveList list of callee-saved registers.
  1486. OS << "static const MCPhysReg " << CSRSet->getName()
  1487. << "_SaveList[] = { ";
  1488. for (unsigned r = 0, re = Regs->size(); r != re; ++r)
  1489. OS << getQualifiedName((*Regs)[r]) << ", ";
  1490. OS << "0 };\n";
  1491. // Emit the *_RegMask bit mask of call-preserved registers.
  1492. BitVector Covered = RegBank.computeCoveredRegisters(*Regs);
  1493. // Check for an optional OtherPreserved set.
  1494. // Add those registers to RegMask, but not to SaveList.
  1495. if (DagInit *OPDag =
  1496. dyn_cast<DagInit>(CSRSet->getValueInit("OtherPreserved"))) {
  1497. SetTheory::RecSet OPSet;
  1498. RegBank.getSets().evaluate(OPDag, OPSet, CSRSet->getLoc());
  1499. Covered |= RegBank.computeCoveredRegisters(
  1500. ArrayRef<Record*>(OPSet.begin(), OPSet.end()));
  1501. }
  1502. // Add all constant physical registers to the preserved mask:
  1503. SetTheory::RecSet ConstantSet;
  1504. for (auto &Reg : RegBank.getRegisters()) {
  1505. if (Reg.Constant)
  1506. ConstantSet.insert(Reg.TheDef);
  1507. }
  1508. Covered |= RegBank.computeCoveredRegisters(
  1509. ArrayRef<Record *>(ConstantSet.begin(), ConstantSet.end()));
  1510. OS << "static const uint32_t " << CSRSet->getName()
  1511. << "_RegMask[] = { ";
  1512. printBitVectorAsHex(OS, Covered, 32);
  1513. OS << "};\n";
  1514. }
  1515. OS << "\n\n";
  1516. OS << "ArrayRef<const uint32_t *> " << ClassName
  1517. << "::getRegMasks() const {\n";
  1518. if (!CSRSets.empty()) {
  1519. OS << " static const uint32_t *const Masks[] = {\n";
  1520. for (Record *CSRSet : CSRSets)
  1521. OS << " " << CSRSet->getName() << "_RegMask,\n";
  1522. OS << " };\n";
  1523. OS << " return ArrayRef(Masks);\n";
  1524. } else {
  1525. OS << " return std::nullopt;\n";
  1526. }
  1527. OS << "}\n\n";
  1528. const std::list<CodeGenRegisterCategory> &RegCategories =
  1529. RegBank.getRegCategories();
  1530. OS << "bool " << ClassName << "::\n"
  1531. << "isGeneralPurposeRegister(const MachineFunction &MF, "
  1532. << "MCRegister PhysReg) const {\n"
  1533. << " return\n";
  1534. for (const CodeGenRegisterCategory &Category : RegCategories)
  1535. if (Category.getName() == "GeneralPurposeRegisters") {
  1536. for (const CodeGenRegisterClass *RC : Category.getClasses())
  1537. OS << " " << RC->getQualifiedName()
  1538. << "RegClass.contains(PhysReg) ||\n";
  1539. break;
  1540. }
  1541. OS << " false;\n";
  1542. OS << "}\n\n";
  1543. OS << "bool " << ClassName << "::\n"
  1544. << "isFixedRegister(const MachineFunction &MF, "
  1545. << "MCRegister PhysReg) const {\n"
  1546. << " return\n";
  1547. for (const CodeGenRegisterCategory &Category : RegCategories)
  1548. if (Category.getName() == "FixedRegisters") {
  1549. for (const CodeGenRegisterClass *RC : Category.getClasses())
  1550. OS << " " << RC->getQualifiedName()
  1551. << "RegClass.contains(PhysReg) ||\n";
  1552. break;
  1553. }
  1554. OS << " false;\n";
  1555. OS << "}\n\n";
  1556. OS << "bool " << ClassName << "::\n"
  1557. << "isArgumentRegister(const MachineFunction &MF, "
  1558. << "MCRegister PhysReg) const {\n"
  1559. << " return\n";
  1560. for (const CodeGenRegisterCategory &Category : RegCategories)
  1561. if (Category.getName() == "ArgumentRegisters") {
  1562. for (const CodeGenRegisterClass *RC : Category.getClasses())
  1563. OS << " " << RC->getQualifiedName()
  1564. << "RegClass.contains(PhysReg) ||\n";
  1565. break;
  1566. }
  1567. OS << " false;\n";
  1568. OS << "}\n\n";
  1569. OS << "bool " << ClassName << "::\n"
  1570. << "isConstantPhysReg(MCRegister PhysReg) const {\n"
  1571. << " return\n";
  1572. for (const auto &Reg : Regs)
  1573. if (Reg.Constant)
  1574. OS << " PhysReg == " << getQualifiedName(Reg.TheDef) << " ||\n";
  1575. OS << " false;\n";
  1576. OS << "}\n\n";
  1577. OS << "ArrayRef<const char *> " << ClassName
  1578. << "::getRegMaskNames() const {\n";
  1579. if (!CSRSets.empty()) {
  1580. OS << " static const char *Names[] = {\n";
  1581. for (Record *CSRSet : CSRSets)
  1582. OS << " " << '"' << CSRSet->getName() << '"' << ",\n";
  1583. OS << " };\n";
  1584. OS << " return ArrayRef(Names);\n";
  1585. } else {
  1586. OS << " return std::nullopt;\n";
  1587. }
  1588. OS << "}\n\n";
  1589. OS << "const " << TargetName << "FrameLowering *\n" << TargetName
  1590. << "GenRegisterInfo::getFrameLowering(const MachineFunction &MF) {\n"
  1591. << " return static_cast<const " << TargetName << "FrameLowering *>(\n"
  1592. << " MF.getSubtarget().getFrameLowering());\n"
  1593. << "}\n\n";
  1594. OS << "} // end namespace llvm\n\n";
  1595. OS << "#endif // GET_REGINFO_TARGET_DESC\n\n";
  1596. }
  1597. void RegisterInfoEmitter::run(raw_ostream &OS) {
  1598. CodeGenRegBank &RegBank = Target.getRegBank();
  1599. Records.startTimer("Print enums");
  1600. runEnums(OS, Target, RegBank);
  1601. Records.startTimer("Print MC registers");
  1602. runMCDesc(OS, Target, RegBank);
  1603. Records.startTimer("Print header fragment");
  1604. runTargetHeader(OS, Target, RegBank);
  1605. Records.startTimer("Print target registers");
  1606. runTargetDesc(OS, Target, RegBank);
  1607. if (RegisterInfoDebug)
  1608. debugDump(errs());
  1609. }
  1610. void RegisterInfoEmitter::debugDump(raw_ostream &OS) {
  1611. CodeGenRegBank &RegBank = Target.getRegBank();
  1612. const CodeGenHwModes &CGH = Target.getHwModes();
  1613. unsigned NumModes = CGH.getNumModeIds();
  1614. auto getModeName = [CGH] (unsigned M) -> StringRef {
  1615. if (M == 0)
  1616. return "Default";
  1617. return CGH.getMode(M).Name;
  1618. };
  1619. for (const CodeGenRegisterClass &RC : RegBank.getRegClasses()) {
  1620. OS << "RegisterClass " << RC.getName() << ":\n";
  1621. OS << "\tSpillSize: {";
  1622. for (unsigned M = 0; M != NumModes; ++M)
  1623. OS << ' ' << getModeName(M) << ':' << RC.RSI.get(M).SpillSize;
  1624. OS << " }\n\tSpillAlignment: {";
  1625. for (unsigned M = 0; M != NumModes; ++M)
  1626. OS << ' ' << getModeName(M) << ':' << RC.RSI.get(M).SpillAlignment;
  1627. OS << " }\n\tNumRegs: " << RC.getMembers().size() << '\n';
  1628. OS << "\tLaneMask: " << PrintLaneMask(RC.LaneMask) << '\n';
  1629. OS << "\tHasDisjunctSubRegs: " << RC.HasDisjunctSubRegs << '\n';
  1630. OS << "\tCoveredBySubRegs: " << RC.CoveredBySubRegs << '\n';
  1631. OS << "\tAllocatable: " << RC.Allocatable << '\n';
  1632. OS << "\tAllocationPriority: " << unsigned(RC.AllocationPriority) << '\n';
  1633. OS << "\tRegs:";
  1634. for (const CodeGenRegister *R : RC.getMembers()) {
  1635. OS << " " << R->getName();
  1636. }
  1637. OS << '\n';
  1638. OS << "\tSubClasses:";
  1639. const BitVector &SubClasses = RC.getSubClasses();
  1640. for (const CodeGenRegisterClass &SRC : RegBank.getRegClasses()) {
  1641. if (!SubClasses.test(SRC.EnumValue))
  1642. continue;
  1643. OS << " " << SRC.getName();
  1644. }
  1645. OS << '\n';
  1646. OS << "\tSuperClasses:";
  1647. for (const CodeGenRegisterClass *SRC : RC.getSuperClasses()) {
  1648. OS << " " << SRC->getName();
  1649. }
  1650. OS << '\n';
  1651. }
  1652. for (const CodeGenSubRegIndex &SRI : RegBank.getSubRegIndices()) {
  1653. OS << "SubRegIndex " << SRI.getName() << ":\n";
  1654. OS << "\tLaneMask: " << PrintLaneMask(SRI.LaneMask) << '\n';
  1655. OS << "\tAllSuperRegsCovered: " << SRI.AllSuperRegsCovered << '\n';
  1656. OS << "\tOffset, Size: " << SRI.Offset << ", " << SRI.Size << '\n';
  1657. }
  1658. for (const CodeGenRegister &R : RegBank.getRegisters()) {
  1659. OS << "Register " << R.getName() << ":\n";
  1660. OS << "\tCostPerUse: ";
  1661. for (const auto &Cost : R.CostPerUse)
  1662. OS << Cost << " ";
  1663. OS << '\n';
  1664. OS << "\tCoveredBySubregs: " << R.CoveredBySubRegs << '\n';
  1665. OS << "\tHasDisjunctSubRegs: " << R.HasDisjunctSubRegs << '\n';
  1666. for (std::pair<CodeGenSubRegIndex*,CodeGenRegister*> P : R.getSubRegs()) {
  1667. OS << "\tSubReg " << P.first->getName()
  1668. << " = " << P.second->getName() << '\n';
  1669. }
  1670. }
  1671. }
  1672. namespace llvm {
  1673. void EmitRegisterInfo(RecordKeeper &RK, raw_ostream &OS) {
  1674. RegisterInfoEmitter(RK).run(OS);
  1675. }
  1676. } // end namespace llvm