CodeGenRegisters.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122
  1. //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines structures to encapsulate information gleaned from the
  11. // target register and register class definitions.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CodeGenRegisters.h"
  15. #include "CodeGenTarget.h"
  16. #include "llvm/ADT/IntEqClasses.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/Support/Debug.h"
  22. #include "llvm/TableGen/Error.h"
  23. using namespace llvm;
  24. #define DEBUG_TYPE "regalloc-emitter"
  25. //===----------------------------------------------------------------------===//
  26. // CodeGenSubRegIndex
  27. //===----------------------------------------------------------------------===//
  28. CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
  29. : TheDef(R), EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
  30. Name = R->getName();
  31. if (R->getValue("Namespace"))
  32. Namespace = R->getValueAsString("Namespace");
  33. Size = R->getValueAsInt("Size");
  34. Offset = R->getValueAsInt("Offset");
  35. }
  36. CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
  37. unsigned Enum)
  38. : TheDef(nullptr), Name(N), Namespace(Nspace), Size(-1), Offset(-1),
  39. EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
  40. }
  41. std::string CodeGenSubRegIndex::getQualifiedName() const {
  42. std::string N = getNamespace();
  43. if (!N.empty())
  44. N += "::";
  45. N += getName();
  46. return N;
  47. }
  48. void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
  49. if (!TheDef)
  50. return;
  51. std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
  52. if (!Comps.empty()) {
  53. if (Comps.size() != 2)
  54. PrintFatalError(TheDef->getLoc(),
  55. "ComposedOf must have exactly two entries");
  56. CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
  57. CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
  58. CodeGenSubRegIndex *X = A->addComposite(B, this);
  59. if (X)
  60. PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
  61. }
  62. std::vector<Record*> Parts =
  63. TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
  64. if (!Parts.empty()) {
  65. if (Parts.size() < 2)
  66. PrintFatalError(TheDef->getLoc(),
  67. "CoveredBySubRegs must have two or more entries");
  68. SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
  69. for (unsigned i = 0, e = Parts.size(); i != e; ++i)
  70. IdxParts.push_back(RegBank.getSubRegIdx(Parts[i]));
  71. RegBank.addConcatSubRegIndex(IdxParts, this);
  72. }
  73. }
  74. unsigned CodeGenSubRegIndex::computeLaneMask() const {
  75. // Already computed?
  76. if (LaneMask)
  77. return LaneMask;
  78. // Recursion guard, shouldn't be required.
  79. LaneMask = ~0u;
  80. // The lane mask is simply the union of all sub-indices.
  81. unsigned M = 0;
  82. for (const auto &C : Composed)
  83. M |= C.second->computeLaneMask();
  84. assert(M && "Missing lane mask, sub-register cycle?");
  85. LaneMask = M;
  86. return LaneMask;
  87. }
  88. //===----------------------------------------------------------------------===//
  89. // CodeGenRegister
  90. //===----------------------------------------------------------------------===//
  91. CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
  92. : TheDef(R),
  93. EnumValue(Enum),
  94. CostPerUse(R->getValueAsInt("CostPerUse")),
  95. CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
  96. HasDisjunctSubRegs(false),
  97. SubRegsComplete(false),
  98. SuperRegsComplete(false),
  99. TopoSig(~0u)
  100. {}
  101. void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
  102. std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
  103. std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
  104. if (SRIs.size() != SRs.size())
  105. PrintFatalError(TheDef->getLoc(),
  106. "SubRegs and SubRegIndices must have the same size");
  107. for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
  108. ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
  109. ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
  110. }
  111. // Also compute leading super-registers. Each register has a list of
  112. // covered-by-subregs super-registers where it appears as the first explicit
  113. // sub-register.
  114. //
  115. // This is used by computeSecondarySubRegs() to find candidates.
  116. if (CoveredBySubRegs && !ExplicitSubRegs.empty())
  117. ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
  118. // Add ad hoc alias links. This is a symmetric relationship between two
  119. // registers, so build a symmetric graph by adding links in both ends.
  120. std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
  121. for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
  122. CodeGenRegister *Reg = RegBank.getReg(Aliases[i]);
  123. ExplicitAliases.push_back(Reg);
  124. Reg->ExplicitAliases.push_back(this);
  125. }
  126. }
  127. const std::string &CodeGenRegister::getName() const {
  128. assert(TheDef && "no def");
  129. return TheDef->getName();
  130. }
  131. namespace {
  132. // Iterate over all register units in a set of registers.
  133. class RegUnitIterator {
  134. CodeGenRegister::Vec::const_iterator RegI, RegE;
  135. CodeGenRegister::RegUnitList::iterator UnitI, UnitE;
  136. public:
  137. RegUnitIterator(const CodeGenRegister::Vec &Regs):
  138. RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
  139. if (RegI != RegE) {
  140. UnitI = (*RegI)->getRegUnits().begin();
  141. UnitE = (*RegI)->getRegUnits().end();
  142. advance();
  143. }
  144. }
  145. bool isValid() const { return UnitI != UnitE; }
  146. unsigned operator* () const { assert(isValid()); return *UnitI; }
  147. const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
  148. /// Preincrement. Move to the next unit.
  149. void operator++() {
  150. assert(isValid() && "Cannot advance beyond the last operand");
  151. ++UnitI;
  152. advance();
  153. }
  154. protected:
  155. void advance() {
  156. while (UnitI == UnitE) {
  157. if (++RegI == RegE)
  158. break;
  159. UnitI = (*RegI)->getRegUnits().begin();
  160. UnitE = (*RegI)->getRegUnits().end();
  161. }
  162. }
  163. };
  164. } // namespace
  165. // Return true of this unit appears in RegUnits.
  166. static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
  167. return RegUnits.test(Unit);
  168. }
  169. // Inherit register units from subregisters.
  170. // Return true if the RegUnits changed.
  171. bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
  172. bool changed = false;
  173. for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
  174. I != E; ++I) {
  175. CodeGenRegister *SR = I->second;
  176. // Merge the subregister's units into this register's RegUnits.
  177. changed |= (RegUnits |= SR->RegUnits);
  178. }
  179. return changed;
  180. }
  181. const CodeGenRegister::SubRegMap &
  182. CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
  183. // Only compute this map once.
  184. if (SubRegsComplete)
  185. return SubRegs;
  186. SubRegsComplete = true;
  187. HasDisjunctSubRegs = ExplicitSubRegs.size() > 1;
  188. // First insert the explicit subregs and make sure they are fully indexed.
  189. for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
  190. CodeGenRegister *SR = ExplicitSubRegs[i];
  191. CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
  192. if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
  193. PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
  194. " appears twice in Register " + getName());
  195. // Map explicit sub-registers first, so the names take precedence.
  196. // The inherited sub-registers are mapped below.
  197. SubReg2Idx.insert(std::make_pair(SR, Idx));
  198. }
  199. // Keep track of inherited subregs and how they can be reached.
  200. SmallPtrSet<CodeGenRegister*, 8> Orphans;
  201. // Clone inherited subregs and place duplicate entries in Orphans.
  202. // Here the order is important - earlier subregs take precedence.
  203. for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
  204. CodeGenRegister *SR = ExplicitSubRegs[i];
  205. const SubRegMap &Map = SR->computeSubRegs(RegBank);
  206. HasDisjunctSubRegs |= SR->HasDisjunctSubRegs;
  207. for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
  208. ++SI) {
  209. if (!SubRegs.insert(*SI).second)
  210. Orphans.insert(SI->second);
  211. }
  212. }
  213. // Expand any composed subreg indices.
  214. // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
  215. // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
  216. // expanded subreg indices recursively.
  217. SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
  218. for (unsigned i = 0; i != Indices.size(); ++i) {
  219. CodeGenSubRegIndex *Idx = Indices[i];
  220. const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
  221. CodeGenRegister *SR = SubRegs[Idx];
  222. const SubRegMap &Map = SR->computeSubRegs(RegBank);
  223. // Look at the possible compositions of Idx.
  224. // They may not all be supported by SR.
  225. for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
  226. E = Comps.end(); I != E; ++I) {
  227. SubRegMap::const_iterator SRI = Map.find(I->first);
  228. if (SRI == Map.end())
  229. continue; // Idx + I->first doesn't exist in SR.
  230. // Add I->second as a name for the subreg SRI->second, assuming it is
  231. // orphaned, and the name isn't already used for something else.
  232. if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
  233. continue;
  234. // We found a new name for the orphaned sub-register.
  235. SubRegs.insert(std::make_pair(I->second, SRI->second));
  236. Indices.push_back(I->second);
  237. }
  238. }
  239. // Now Orphans contains the inherited subregisters without a direct index.
  240. // Create inferred indexes for all missing entries.
  241. // Work backwards in the Indices vector in order to compose subregs bottom-up.
  242. // Consider this subreg sequence:
  243. //
  244. // qsub_1 -> dsub_0 -> ssub_0
  245. //
  246. // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
  247. // can be reached in two different ways:
  248. //
  249. // qsub_1 -> ssub_0
  250. // dsub_2 -> ssub_0
  251. //
  252. // We pick the latter composition because another register may have [dsub_0,
  253. // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The
  254. // dsub_2 -> ssub_0 composition can be shared.
  255. while (!Indices.empty() && !Orphans.empty()) {
  256. CodeGenSubRegIndex *Idx = Indices.pop_back_val();
  257. CodeGenRegister *SR = SubRegs[Idx];
  258. const SubRegMap &Map = SR->computeSubRegs(RegBank);
  259. for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
  260. ++SI)
  261. if (Orphans.erase(SI->second))
  262. SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
  263. }
  264. // Compute the inverse SubReg -> Idx map.
  265. for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end();
  266. SI != SE; ++SI) {
  267. if (SI->second == this) {
  268. ArrayRef<SMLoc> Loc;
  269. if (TheDef)
  270. Loc = TheDef->getLoc();
  271. PrintFatalError(Loc, "Register " + getName() +
  272. " has itself as a sub-register");
  273. }
  274. // Compute AllSuperRegsCovered.
  275. if (!CoveredBySubRegs)
  276. SI->first->AllSuperRegsCovered = false;
  277. // Ensure that every sub-register has a unique name.
  278. DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
  279. SubReg2Idx.insert(std::make_pair(SI->second, SI->first)).first;
  280. if (Ins->second == SI->first)
  281. continue;
  282. // Trouble: Two different names for SI->second.
  283. ArrayRef<SMLoc> Loc;
  284. if (TheDef)
  285. Loc = TheDef->getLoc();
  286. PrintFatalError(Loc, "Sub-register can't have two names: " +
  287. SI->second->getName() + " available as " +
  288. SI->first->getName() + " and " + Ins->second->getName());
  289. }
  290. // Derive possible names for sub-register concatenations from any explicit
  291. // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
  292. // that getConcatSubRegIndex() won't invent any concatenated indices that the
  293. // user already specified.
  294. for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
  295. CodeGenRegister *SR = ExplicitSubRegs[i];
  296. if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1)
  297. continue;
  298. // SR is composed of multiple sub-regs. Find their names in this register.
  299. SmallVector<CodeGenSubRegIndex*, 8> Parts;
  300. for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j)
  301. Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
  302. // Offer this as an existing spelling for the concatenation of Parts.
  303. RegBank.addConcatSubRegIndex(Parts, ExplicitSubRegIndices[i]);
  304. }
  305. // Initialize RegUnitList. Because getSubRegs is called recursively, this
  306. // processes the register hierarchy in postorder.
  307. //
  308. // Inherit all sub-register units. It is good enough to look at the explicit
  309. // sub-registers, the other registers won't contribute any more units.
  310. for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
  311. CodeGenRegister *SR = ExplicitSubRegs[i];
  312. RegUnits |= SR->RegUnits;
  313. }
  314. // Absent any ad hoc aliasing, we create one register unit per leaf register.
  315. // These units correspond to the maximal cliques in the register overlap
  316. // graph which is optimal.
  317. //
  318. // When there is ad hoc aliasing, we simply create one unit per edge in the
  319. // undirected ad hoc aliasing graph. Technically, we could do better by
  320. // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
  321. // are extremely rare anyway (I've never seen one), so we don't bother with
  322. // the added complexity.
  323. for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
  324. CodeGenRegister *AR = ExplicitAliases[i];
  325. // Only visit each edge once.
  326. if (AR->SubRegsComplete)
  327. continue;
  328. // Create a RegUnit representing this alias edge, and add it to both
  329. // registers.
  330. unsigned Unit = RegBank.newRegUnit(this, AR);
  331. RegUnits.set(Unit);
  332. AR->RegUnits.set(Unit);
  333. }
  334. // Finally, create units for leaf registers without ad hoc aliases. Note that
  335. // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
  336. // necessary. This means the aliasing leaf registers can share a single unit.
  337. if (RegUnits.empty())
  338. RegUnits.set(RegBank.newRegUnit(this));
  339. // We have now computed the native register units. More may be adopted later
  340. // for balancing purposes.
  341. NativeRegUnits = RegUnits;
  342. return SubRegs;
  343. }
  344. // In a register that is covered by its sub-registers, try to find redundant
  345. // sub-registers. For example:
  346. //
  347. // QQ0 = {Q0, Q1}
  348. // Q0 = {D0, D1}
  349. // Q1 = {D2, D3}
  350. //
  351. // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
  352. // the register definition.
  353. //
  354. // The explicitly specified registers form a tree. This function discovers
  355. // sub-register relationships that would force a DAG.
  356. //
  357. void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
  358. // Collect new sub-registers first, add them later.
  359. SmallVector<SubRegMap::value_type, 8> NewSubRegs;
  360. // Look at the leading super-registers of each sub-register. Those are the
  361. // candidates for new sub-registers, assuming they are fully contained in
  362. // this register.
  363. for (SubRegMap::iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I){
  364. const CodeGenRegister *SubReg = I->second;
  365. const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
  366. for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
  367. CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
  368. // Already got this sub-register?
  369. if (Cand == this || getSubRegIndex(Cand))
  370. continue;
  371. // Check if each component of Cand is already a sub-register.
  372. // We know that the first component is I->second, and is present with the
  373. // name I->first.
  374. SmallVector<CodeGenSubRegIndex*, 8> Parts(1, I->first);
  375. assert(!Cand->ExplicitSubRegs.empty() &&
  376. "Super-register has no sub-registers");
  377. for (unsigned j = 1, e = Cand->ExplicitSubRegs.size(); j != e; ++j) {
  378. if (CodeGenSubRegIndex *Idx = getSubRegIndex(Cand->ExplicitSubRegs[j]))
  379. Parts.push_back(Idx);
  380. else {
  381. // Sub-register doesn't exist.
  382. Parts.clear();
  383. break;
  384. }
  385. }
  386. // If some Cand sub-register is not part of this register, or if Cand only
  387. // has one sub-register, there is nothing to do.
  388. if (Parts.size() <= 1)
  389. continue;
  390. // Each part of Cand is a sub-register of this. Make the full Cand also
  391. // a sub-register with a concatenated sub-register index.
  392. CodeGenSubRegIndex *Concat= RegBank.getConcatSubRegIndex(Parts);
  393. NewSubRegs.push_back(std::make_pair(Concat, Cand));
  394. }
  395. }
  396. // Now add all the new sub-registers.
  397. for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
  398. // Don't add Cand if another sub-register is already using the index.
  399. if (!SubRegs.insert(NewSubRegs[i]).second)
  400. continue;
  401. CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
  402. CodeGenRegister *NewSubReg = NewSubRegs[i].second;
  403. SubReg2Idx.insert(std::make_pair(NewSubReg, NewIdx));
  404. }
  405. // Create sub-register index composition maps for the synthesized indices.
  406. for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
  407. CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
  408. CodeGenRegister *NewSubReg = NewSubRegs[i].second;
  409. for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
  410. SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
  411. CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
  412. if (!SubIdx)
  413. PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
  414. SI->second->getName() + " in " + getName());
  415. NewIdx->addComposite(SI->first, SubIdx);
  416. }
  417. }
  418. }
  419. void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
  420. // Only visit each register once.
  421. if (SuperRegsComplete)
  422. return;
  423. SuperRegsComplete = true;
  424. // Make sure all sub-registers have been visited first, so the super-reg
  425. // lists will be topologically ordered.
  426. for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
  427. I != E; ++I)
  428. I->second->computeSuperRegs(RegBank);
  429. // Now add this as a super-register on all sub-registers.
  430. // Also compute the TopoSigId in post-order.
  431. TopoSigId Id;
  432. for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
  433. I != E; ++I) {
  434. // Topological signature computed from SubIdx, TopoId(SubReg).
  435. // Loops and idempotent indices have TopoSig = ~0u.
  436. Id.push_back(I->first->EnumValue);
  437. Id.push_back(I->second->TopoSig);
  438. // Don't add duplicate entries.
  439. if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
  440. continue;
  441. I->second->SuperRegs.push_back(this);
  442. }
  443. TopoSig = RegBank.getTopoSig(Id);
  444. }
  445. void
  446. CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
  447. CodeGenRegBank &RegBank) const {
  448. assert(SubRegsComplete && "Must precompute sub-registers");
  449. for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
  450. CodeGenRegister *SR = ExplicitSubRegs[i];
  451. if (OSet.insert(SR))
  452. SR->addSubRegsPreOrder(OSet, RegBank);
  453. }
  454. // Add any secondary sub-registers that weren't part of the explicit tree.
  455. for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
  456. I != E; ++I)
  457. OSet.insert(I->second);
  458. }
  459. // Get the sum of this register's unit weights.
  460. unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
  461. unsigned Weight = 0;
  462. for (RegUnitList::iterator I = RegUnits.begin(), E = RegUnits.end();
  463. I != E; ++I) {
  464. Weight += RegBank.getRegUnit(*I).Weight;
  465. }
  466. return Weight;
  467. }
  468. //===----------------------------------------------------------------------===//
  469. // RegisterTuples
  470. //===----------------------------------------------------------------------===//
  471. // A RegisterTuples def is used to generate pseudo-registers from lists of
  472. // sub-registers. We provide a SetTheory expander class that returns the new
  473. // registers.
  474. namespace {
  475. struct TupleExpander : SetTheory::Expander {
  476. void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
  477. std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
  478. unsigned Dim = Indices.size();
  479. ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
  480. if (Dim != SubRegs->size())
  481. PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
  482. if (Dim < 2)
  483. PrintFatalError(Def->getLoc(),
  484. "Tuples must have at least 2 sub-registers");
  485. // Evaluate the sub-register lists to be zipped.
  486. unsigned Length = ~0u;
  487. SmallVector<SetTheory::RecSet, 4> Lists(Dim);
  488. for (unsigned i = 0; i != Dim; ++i) {
  489. ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
  490. Length = std::min(Length, unsigned(Lists[i].size()));
  491. }
  492. if (Length == 0)
  493. return;
  494. // Precompute some types.
  495. Record *RegisterCl = Def->getRecords().getClass("Register");
  496. RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
  497. StringInit *BlankName = StringInit::get("");
  498. // Zip them up.
  499. for (unsigned n = 0; n != Length; ++n) {
  500. std::string Name;
  501. Record *Proto = Lists[0][n];
  502. std::vector<Init*> Tuple;
  503. unsigned CostPerUse = 0;
  504. for (unsigned i = 0; i != Dim; ++i) {
  505. Record *Reg = Lists[i][n];
  506. if (i) Name += '_';
  507. Name += Reg->getName();
  508. Tuple.push_back(DefInit::get(Reg));
  509. CostPerUse = std::max(CostPerUse,
  510. unsigned(Reg->getValueAsInt("CostPerUse")));
  511. }
  512. // Create a new Record representing the synthesized register. This record
  513. // is only for consumption by CodeGenRegister, it is not added to the
  514. // RecordKeeper.
  515. Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
  516. Elts.insert(NewReg);
  517. // Copy Proto super-classes.
  518. ArrayRef<Record *> Supers = Proto->getSuperClasses();
  519. ArrayRef<SMRange> Ranges = Proto->getSuperClassRanges();
  520. for (unsigned i = 0, e = Supers.size(); i != e; ++i)
  521. NewReg->addSuperClass(Supers[i], Ranges[i]);
  522. // Copy Proto fields.
  523. for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
  524. RecordVal RV = Proto->getValues()[i];
  525. // Skip existing fields, like NAME.
  526. if (NewReg->getValue(RV.getNameInit()))
  527. continue;
  528. StringRef Field = RV.getName();
  529. // Replace the sub-register list with Tuple.
  530. if (Field == "SubRegs")
  531. RV.setValue(ListInit::get(Tuple, RegisterRecTy));
  532. // Provide a blank AsmName. MC hacks are required anyway.
  533. if (Field == "AsmName")
  534. RV.setValue(BlankName);
  535. // CostPerUse is aggregated from all Tuple members.
  536. if (Field == "CostPerUse")
  537. RV.setValue(IntInit::get(CostPerUse));
  538. // Composite registers are always covered by sub-registers.
  539. if (Field == "CoveredBySubRegs")
  540. RV.setValue(BitInit::get(true));
  541. // Copy fields from the RegisterTuples def.
  542. if (Field == "SubRegIndices" ||
  543. Field == "CompositeIndices") {
  544. NewReg->addValue(*Def->getValue(Field));
  545. continue;
  546. }
  547. // Some fields get their default uninitialized value.
  548. if (Field == "DwarfNumbers" ||
  549. Field == "DwarfAlias" ||
  550. Field == "Aliases") {
  551. if (const RecordVal *DefRV = RegisterCl->getValue(Field))
  552. NewReg->addValue(*DefRV);
  553. continue;
  554. }
  555. // Everything else is copied from Proto.
  556. NewReg->addValue(RV);
  557. }
  558. }
  559. }
  560. };
  561. }
  562. //===----------------------------------------------------------------------===//
  563. // CodeGenRegisterClass
  564. //===----------------------------------------------------------------------===//
  565. static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
  566. std::sort(M.begin(), M.end(), deref<llvm::less>());
  567. M.erase(std::unique(M.begin(), M.end(), deref<llvm::equal>()), M.end());
  568. }
  569. CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
  570. : TheDef(R),
  571. Name(R->getName()),
  572. TopoSigs(RegBank.getNumTopoSigs()),
  573. EnumValue(-1),
  574. LaneMask(0) {
  575. // Rename anonymous register classes.
  576. if (R->getName().size() > 9 && R->getName()[9] == '.') {
  577. static unsigned AnonCounter = 0;
  578. R->setName("AnonRegClass_" + utostr(AnonCounter++));
  579. }
  580. std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
  581. for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
  582. Record *Type = TypeList[i];
  583. if (!Type->isSubClassOf("ValueType"))
  584. PrintFatalError("RegTypes list member '" + Type->getName() +
  585. "' does not derive from the ValueType class!");
  586. VTs.push_back(getValueType(Type));
  587. }
  588. assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
  589. // Allocation order 0 is the full set. AltOrders provides others.
  590. const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
  591. ListInit *AltOrders = R->getValueAsListInit("AltOrders");
  592. Orders.resize(1 + AltOrders->size());
  593. // Default allocation order always contains all registers.
  594. for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
  595. Orders[0].push_back((*Elements)[i]);
  596. const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
  597. Members.push_back(Reg);
  598. TopoSigs.set(Reg->getTopoSig());
  599. }
  600. sortAndUniqueRegisters(Members);
  601. // Alternative allocation orders may be subsets.
  602. SetTheory::RecSet Order;
  603. for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
  604. RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
  605. Orders[1 + i].append(Order.begin(), Order.end());
  606. // Verify that all altorder members are regclass members.
  607. while (!Order.empty()) {
  608. CodeGenRegister *Reg = RegBank.getReg(Order.back());
  609. Order.pop_back();
  610. if (!contains(Reg))
  611. PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
  612. " is not a class member");
  613. }
  614. }
  615. // Allow targets to override the size in bits of the RegisterClass.
  616. unsigned Size = R->getValueAsInt("Size");
  617. Namespace = R->getValueAsString("Namespace");
  618. SpillSize = Size ? Size : MVT(VTs[0]).getSizeInBits();
  619. SpillAlignment = R->getValueAsInt("Alignment");
  620. CopyCost = R->getValueAsInt("CopyCost");
  621. Allocatable = R->getValueAsBit("isAllocatable");
  622. AltOrderSelect = R->getValueAsString("AltOrderSelect");
  623. int AllocationPriority = R->getValueAsInt("AllocationPriority");
  624. if (AllocationPriority < 0 || AllocationPriority > 63)
  625. PrintFatalError(R->getLoc(), "AllocationPriority out of range [0,63]");
  626. this->AllocationPriority = AllocationPriority;
  627. }
  628. // Create an inferred register class that was missing from the .td files.
  629. // Most properties will be inherited from the closest super-class after the
  630. // class structure has been computed.
  631. CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
  632. StringRef Name, Key Props)
  633. : Members(*Props.Members),
  634. TheDef(nullptr),
  635. Name(Name),
  636. TopoSigs(RegBank.getNumTopoSigs()),
  637. EnumValue(-1),
  638. SpillSize(Props.SpillSize),
  639. SpillAlignment(Props.SpillAlignment),
  640. CopyCost(0),
  641. Allocatable(true),
  642. AllocationPriority(0) {
  643. for (const auto R : Members)
  644. TopoSigs.set(R->getTopoSig());
  645. }
  646. // Compute inherited propertied for a synthesized register class.
  647. void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
  648. assert(!getDef() && "Only synthesized classes can inherit properties");
  649. assert(!SuperClasses.empty() && "Synthesized class without super class");
  650. // The last super-class is the smallest one.
  651. CodeGenRegisterClass &Super = *SuperClasses.back();
  652. // Most properties are copied directly.
  653. // Exceptions are members, size, and alignment
  654. Namespace = Super.Namespace;
  655. VTs = Super.VTs;
  656. CopyCost = Super.CopyCost;
  657. Allocatable = Super.Allocatable;
  658. AltOrderSelect = Super.AltOrderSelect;
  659. AllocationPriority = Super.AllocationPriority;
  660. // Copy all allocation orders, filter out foreign registers from the larger
  661. // super-class.
  662. Orders.resize(Super.Orders.size());
  663. for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
  664. for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
  665. if (contains(RegBank.getReg(Super.Orders[i][j])))
  666. Orders[i].push_back(Super.Orders[i][j]);
  667. }
  668. bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
  669. return std::binary_search(Members.begin(), Members.end(), Reg,
  670. deref<llvm::less>());
  671. }
  672. namespace llvm {
  673. raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
  674. OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
  675. for (const auto R : *K.Members)
  676. OS << ", " << R->getName();
  677. return OS << " }";
  678. }
  679. }
  680. // This is a simple lexicographical order that can be used to search for sets.
  681. // It is not the same as the topological order provided by TopoOrderRC.
  682. bool CodeGenRegisterClass::Key::
  683. operator<(const CodeGenRegisterClass::Key &B) const {
  684. assert(Members && B.Members);
  685. return std::tie(*Members, SpillSize, SpillAlignment) <
  686. std::tie(*B.Members, B.SpillSize, B.SpillAlignment);
  687. }
  688. // Returns true if RC is a strict subclass.
  689. // RC is a sub-class of this class if it is a valid replacement for any
  690. // instruction operand where a register of this classis required. It must
  691. // satisfy these conditions:
  692. //
  693. // 1. All RC registers are also in this.
  694. // 2. The RC spill size must not be smaller than our spill size.
  695. // 3. RC spill alignment must be compatible with ours.
  696. //
  697. static bool testSubClass(const CodeGenRegisterClass *A,
  698. const CodeGenRegisterClass *B) {
  699. return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
  700. A->SpillSize <= B->SpillSize &&
  701. std::includes(A->getMembers().begin(), A->getMembers().end(),
  702. B->getMembers().begin(), B->getMembers().end(),
  703. deref<llvm::less>());
  704. }
  705. /// Sorting predicate for register classes. This provides a topological
  706. /// ordering that arranges all register classes before their sub-classes.
  707. ///
  708. /// Register classes with the same registers, spill size, and alignment form a
  709. /// clique. They will be ordered alphabetically.
  710. ///
  711. static bool __cdecl TopoOrderRC(const CodeGenRegisterClass &PA, // HLSL Change - __cdecl
  712. const CodeGenRegisterClass &PB) {
  713. auto *A = &PA;
  714. auto *B = &PB;
  715. if (A == B)
  716. return 0;
  717. // Order by ascending spill size.
  718. if (A->SpillSize < B->SpillSize)
  719. return true;
  720. if (A->SpillSize > B->SpillSize)
  721. return false;
  722. // Order by ascending spill alignment.
  723. if (A->SpillAlignment < B->SpillAlignment)
  724. return true;
  725. if (A->SpillAlignment > B->SpillAlignment)
  726. return false;
  727. // Order by descending set size. Note that the classes' allocation order may
  728. // not have been computed yet. The Members set is always vaild.
  729. if (A->getMembers().size() > B->getMembers().size())
  730. return true;
  731. if (A->getMembers().size() < B->getMembers().size())
  732. return false;
  733. // Finally order by name as a tie breaker.
  734. return StringRef(A->getName()) < B->getName();
  735. }
  736. std::string CodeGenRegisterClass::getQualifiedName() const {
  737. if (Namespace.empty())
  738. return getName();
  739. else
  740. return Namespace + "::" + getName();
  741. }
  742. // Compute sub-classes of all register classes.
  743. // Assume the classes are ordered topologically.
  744. void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
  745. auto &RegClasses = RegBank.getRegClasses();
  746. // Visit backwards so sub-classes are seen first.
  747. for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
  748. CodeGenRegisterClass &RC = *I;
  749. RC.SubClasses.resize(RegClasses.size());
  750. RC.SubClasses.set(RC.EnumValue);
  751. // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
  752. for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
  753. CodeGenRegisterClass &SubRC = *I2;
  754. if (RC.SubClasses.test(SubRC.EnumValue))
  755. continue;
  756. if (!testSubClass(&RC, &SubRC))
  757. continue;
  758. // SubRC is a sub-class. Grap all its sub-classes so we won't have to
  759. // check them again.
  760. RC.SubClasses |= SubRC.SubClasses;
  761. }
  762. // Sweep up missed clique members. They will be immediately preceding RC.
  763. for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
  764. RC.SubClasses.set(I2->EnumValue);
  765. }
  766. // Compute the SuperClasses lists from the SubClasses vectors.
  767. for (auto &RC : RegClasses) {
  768. const BitVector &SC = RC.getSubClasses();
  769. auto I = RegClasses.begin();
  770. for (int s = 0, next_s = SC.find_first(); next_s != -1;
  771. next_s = SC.find_next(s)) {
  772. std::advance(I, next_s - s);
  773. s = next_s;
  774. if (&*I == &RC)
  775. continue;
  776. I->SuperClasses.push_back(&RC);
  777. }
  778. }
  779. // With the class hierarchy in place, let synthesized register classes inherit
  780. // properties from their closest super-class. The iteration order here can
  781. // propagate properties down multiple levels.
  782. for (auto &RC : RegClasses)
  783. if (!RC.getDef())
  784. RC.inheritProperties(RegBank);
  785. }
  786. void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
  787. BitVector &Out) const {
  788. auto FindI = SuperRegClasses.find(SubIdx);
  789. if (FindI == SuperRegClasses.end())
  790. return;
  791. for (CodeGenRegisterClass *RC : FindI->second)
  792. Out.set(RC->EnumValue);
  793. }
  794. // Populate a unique sorted list of units from a register set.
  795. void CodeGenRegisterClass::buildRegUnitSet(
  796. std::vector<unsigned> &RegUnits) const {
  797. std::vector<unsigned> TmpUnits;
  798. for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
  799. TmpUnits.push_back(*UnitI);
  800. std::sort(TmpUnits.begin(), TmpUnits.end());
  801. std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
  802. std::back_inserter(RegUnits));
  803. }
  804. //===----------------------------------------------------------------------===//
  805. // CodeGenRegBank
  806. //===----------------------------------------------------------------------===//
  807. CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) {
  808. // Configure register Sets to understand register classes and tuples.
  809. Sets.addFieldExpander("RegisterClass", "MemberList");
  810. Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
  811. Sets.addExpander("RegisterTuples", llvm::make_unique<TupleExpander>());
  812. // Read in the user-defined (named) sub-register indices.
  813. // More indices will be synthesized later.
  814. std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
  815. std::sort(SRIs.begin(), SRIs.end(), LessRecord());
  816. for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
  817. getSubRegIdx(SRIs[i]);
  818. // Build composite maps from ComposedOf fields.
  819. for (auto &Idx : SubRegIndices)
  820. Idx.updateComponents(*this);
  821. // Read in the register definitions.
  822. std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
  823. std::sort(Regs.begin(), Regs.end(), LessRecordRegister());
  824. // Assign the enumeration values.
  825. for (unsigned i = 0, e = Regs.size(); i != e; ++i)
  826. getReg(Regs[i]);
  827. // Expand tuples and number the new registers.
  828. std::vector<Record*> Tups =
  829. Records.getAllDerivedDefinitions("RegisterTuples");
  830. for (Record *R : Tups) {
  831. std::vector<Record *> TupRegs = *Sets.expand(R);
  832. std::sort(TupRegs.begin(), TupRegs.end(), LessRecordRegister());
  833. for (Record *RC : TupRegs)
  834. getReg(RC);
  835. }
  836. // Now all the registers are known. Build the object graph of explicit
  837. // register-register references.
  838. for (auto &Reg : Registers)
  839. Reg.buildObjectGraph(*this);
  840. // Compute register name map.
  841. for (auto &Reg : Registers)
  842. // FIXME: This could just be RegistersByName[name] = register, except that
  843. // causes some failures in MIPS - perhaps they have duplicate register name
  844. // entries? (or maybe there's a reason for it - I don't know much about this
  845. // code, just drive-by refactoring)
  846. RegistersByName.insert(
  847. std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
  848. // Precompute all sub-register maps.
  849. // This will create Composite entries for all inferred sub-register indices.
  850. for (auto &Reg : Registers)
  851. Reg.computeSubRegs(*this);
  852. // Infer even more sub-registers by combining leading super-registers.
  853. for (auto &Reg : Registers)
  854. if (Reg.CoveredBySubRegs)
  855. Reg.computeSecondarySubRegs(*this);
  856. // After the sub-register graph is complete, compute the topologically
  857. // ordered SuperRegs list.
  858. for (auto &Reg : Registers)
  859. Reg.computeSuperRegs(*this);
  860. // Native register units are associated with a leaf register. They've all been
  861. // discovered now.
  862. NumNativeRegUnits = RegUnits.size();
  863. // Read in register class definitions.
  864. std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
  865. if (RCs.empty())
  866. PrintFatalError("No 'RegisterClass' subclasses defined!");
  867. // Allocate user-defined register classes.
  868. for (auto *RC : RCs) {
  869. RegClasses.emplace_back(*this, RC);
  870. addToMaps(&RegClasses.back());
  871. }
  872. // Infer missing classes to create a full algebra.
  873. computeInferredRegisterClasses();
  874. // Order register classes topologically and assign enum values.
  875. RegClasses.sort(TopoOrderRC);
  876. unsigned i = 0;
  877. for (auto &RC : RegClasses)
  878. RC.EnumValue = i++;
  879. CodeGenRegisterClass::computeSubClasses(*this);
  880. }
  881. // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
  882. CodeGenSubRegIndex*
  883. CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
  884. SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
  885. return &SubRegIndices.back();
  886. }
  887. CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
  888. CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
  889. if (Idx)
  890. return Idx;
  891. SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
  892. Idx = &SubRegIndices.back();
  893. return Idx;
  894. }
  895. CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
  896. CodeGenRegister *&Reg = Def2Reg[Def];
  897. if (Reg)
  898. return Reg;
  899. Registers.emplace_back(Def, Registers.size() + 1);
  900. Reg = &Registers.back();
  901. return Reg;
  902. }
  903. void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
  904. if (Record *Def = RC->getDef())
  905. Def2RC.insert(std::make_pair(Def, RC));
  906. // Duplicate classes are rejected by insert().
  907. // That's OK, we only care about the properties handled by CGRC::Key.
  908. CodeGenRegisterClass::Key K(*RC);
  909. Key2RC.insert(std::make_pair(K, RC));
  910. }
  911. // Create a synthetic sub-class if it is missing.
  912. CodeGenRegisterClass*
  913. CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
  914. const CodeGenRegister::Vec *Members,
  915. StringRef Name) {
  916. // Synthetic sub-class has the same size and alignment as RC.
  917. CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
  918. RCKeyMap::const_iterator FoundI = Key2RC.find(K);
  919. if (FoundI != Key2RC.end())
  920. return FoundI->second;
  921. // Sub-class doesn't exist, create a new one.
  922. RegClasses.emplace_back(*this, Name, K);
  923. addToMaps(&RegClasses.back());
  924. return &RegClasses.back();
  925. }
  926. CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
  927. if (CodeGenRegisterClass *RC = Def2RC[Def])
  928. return RC;
  929. PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
  930. }
  931. CodeGenSubRegIndex*
  932. CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
  933. CodeGenSubRegIndex *B) {
  934. // Look for an existing entry.
  935. CodeGenSubRegIndex *Comp = A->compose(B);
  936. if (Comp)
  937. return Comp;
  938. // None exists, synthesize one.
  939. std::string Name = A->getName() + "_then_" + B->getName();
  940. Comp = createSubRegIndex(Name, A->getNamespace());
  941. A->addComposite(B, Comp);
  942. return Comp;
  943. }
  944. CodeGenSubRegIndex *CodeGenRegBank::
  945. getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
  946. assert(Parts.size() > 1 && "Need two parts to concatenate");
  947. // Look for an existing entry.
  948. CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
  949. if (Idx)
  950. return Idx;
  951. // None exists, synthesize one.
  952. std::string Name = Parts.front()->getName();
  953. // Determine whether all parts are contiguous.
  954. bool isContinuous = true;
  955. unsigned Size = Parts.front()->Size;
  956. unsigned LastOffset = Parts.front()->Offset;
  957. unsigned LastSize = Parts.front()->Size;
  958. for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
  959. Name += '_';
  960. Name += Parts[i]->getName();
  961. Size += Parts[i]->Size;
  962. if (Parts[i]->Offset != (LastOffset + LastSize))
  963. isContinuous = false;
  964. LastOffset = Parts[i]->Offset;
  965. LastSize = Parts[i]->Size;
  966. }
  967. Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
  968. Idx->Size = Size;
  969. Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
  970. return Idx;
  971. }
  972. void CodeGenRegBank::computeComposites() {
  973. // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
  974. // and many registers will share TopoSigs on regular architectures.
  975. BitVector TopoSigs(getNumTopoSigs());
  976. for (const auto &Reg1 : Registers) {
  977. // Skip identical subreg structures already processed.
  978. if (TopoSigs.test(Reg1.getTopoSig()))
  979. continue;
  980. TopoSigs.set(Reg1.getTopoSig());
  981. const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
  982. for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
  983. e1 = SRM1.end(); i1 != e1; ++i1) {
  984. CodeGenSubRegIndex *Idx1 = i1->first;
  985. CodeGenRegister *Reg2 = i1->second;
  986. // Ignore identity compositions.
  987. if (&Reg1 == Reg2)
  988. continue;
  989. const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
  990. // Try composing Idx1 with another SubRegIndex.
  991. for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
  992. e2 = SRM2.end(); i2 != e2; ++i2) {
  993. CodeGenSubRegIndex *Idx2 = i2->first;
  994. CodeGenRegister *Reg3 = i2->second;
  995. // Ignore identity compositions.
  996. if (Reg2 == Reg3)
  997. continue;
  998. // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
  999. CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
  1000. assert(Idx3 && "Sub-register doesn't have an index");
  1001. // Conflicting composition? Emit a warning but allow it.
  1002. if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
  1003. PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
  1004. " and " + Idx2->getQualifiedName() +
  1005. " compose ambiguously as " + Prev->getQualifiedName() +
  1006. " or " + Idx3->getQualifiedName());
  1007. }
  1008. }
  1009. }
  1010. }
  1011. // Compute lane masks. This is similar to register units, but at the
  1012. // sub-register index level. Each bit in the lane mask is like a register unit
  1013. // class, and two lane masks will have a bit in common if two sub-register
  1014. // indices overlap in some register.
  1015. //
  1016. // Conservatively share a lane mask bit if two sub-register indices overlap in
  1017. // some registers, but not in others. That shouldn't happen a lot.
  1018. void CodeGenRegBank::computeSubRegLaneMasks() {
  1019. // First assign individual bits to all the leaf indices.
  1020. unsigned Bit = 0;
  1021. // Determine mask of lanes that cover their registers.
  1022. CoveringLanes = ~0u;
  1023. for (auto &Idx : SubRegIndices) {
  1024. if (Idx.getComposites().empty()) {
  1025. Idx.LaneMask = 1u << Bit;
  1026. // Share bit 31 in the unlikely case there are more than 32 leafs.
  1027. //
  1028. // Sharing bits is harmless; it allows graceful degradation in targets
  1029. // with more than 32 vector lanes. They simply get a limited resolution
  1030. // view of lanes beyond the 32nd.
  1031. //
  1032. // See also the comment for getSubRegIndexLaneMask().
  1033. if (Bit < 31)
  1034. ++Bit;
  1035. else
  1036. // Once bit 31 is shared among multiple leafs, the 'lane' it represents
  1037. // is no longer covering its registers.
  1038. CoveringLanes &= ~(1u << Bit);
  1039. } else {
  1040. Idx.LaneMask = 0;
  1041. }
  1042. }
  1043. // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
  1044. // here is that for each possible target subregister we look at the leafs
  1045. // in the subregister graph that compose for this target and create
  1046. // transformation sequences for the lanemasks. Each step in the sequence
  1047. // consists of a bitmask and a bitrotate operation. As the rotation amounts
  1048. // are usually the same for many subregisters we can easily combine the steps
  1049. // by combining the masks.
  1050. for (const auto &Idx : SubRegIndices) {
  1051. const auto &Composites = Idx.getComposites();
  1052. auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
  1053. // Go through all leaf subregisters and find the ones that compose with Idx.
  1054. // These make out all possible valid bits in the lane mask we want to
  1055. // transform. Looking only at the leafs ensure that only a single bit in
  1056. // the mask is set.
  1057. unsigned NextBit = 0;
  1058. for (auto &Idx2 : SubRegIndices) {
  1059. // Skip non-leaf subregisters.
  1060. if (!Idx2.getComposites().empty())
  1061. continue;
  1062. // Replicate the behaviour from the lane mask generation loop above.
  1063. unsigned SrcBit = NextBit;
  1064. unsigned SrcMask = 1u << SrcBit;
  1065. if (NextBit < 31)
  1066. ++NextBit;
  1067. assert(Idx2.LaneMask == SrcMask);
  1068. // Get the composed subregister if there is any.
  1069. auto C = Composites.find(&Idx2);
  1070. if (C == Composites.end())
  1071. continue;
  1072. const CodeGenSubRegIndex *Composite = C->second;
  1073. // The Composed subreg should be a leaf subreg too
  1074. assert(Composite->getComposites().empty());
  1075. // Create Mask+Rotate operation and merge with existing ops if possible.
  1076. unsigned DstBit = Log2_32(Composite->LaneMask);
  1077. int Shift = DstBit - SrcBit;
  1078. uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift : 32+Shift;
  1079. for (auto &I : LaneTransforms) {
  1080. if (I.RotateLeft == RotateLeft) {
  1081. I.Mask |= SrcMask;
  1082. SrcMask = 0;
  1083. }
  1084. }
  1085. if (SrcMask != 0) {
  1086. MaskRolPair MaskRol = { SrcMask, RotateLeft };
  1087. LaneTransforms.push_back(MaskRol);
  1088. }
  1089. }
  1090. // Optimize if the transformation consists of one step only: Set mask to
  1091. // 0xffffffff (including some irrelevant invalid bits) so that it should
  1092. // merge with more entries later while compressing the table.
  1093. if (LaneTransforms.size() == 1)
  1094. LaneTransforms[0].Mask = ~0u;
  1095. // Further compression optimization: For invalid compositions resulting
  1096. // in a sequence with 0 entries we can just pick any other. Choose
  1097. // Mask 0xffffffff with Rotation 0.
  1098. if (LaneTransforms.size() == 0) {
  1099. MaskRolPair P = { ~0u, 0 };
  1100. LaneTransforms.push_back(P);
  1101. }
  1102. }
  1103. // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
  1104. // by the sub-register graph? This doesn't occur in any known targets.
  1105. // Inherit lanes from composites.
  1106. for (const auto &Idx : SubRegIndices) {
  1107. unsigned Mask = Idx.computeLaneMask();
  1108. // If some super-registers without CoveredBySubRegs use this index, we can
  1109. // no longer assume that the lanes are covering their registers.
  1110. if (!Idx.AllSuperRegsCovered)
  1111. CoveringLanes &= ~Mask;
  1112. }
  1113. // Compute lane mask combinations for register classes.
  1114. for (auto &RegClass : RegClasses) {
  1115. unsigned LaneMask = 0;
  1116. for (const auto &SubRegIndex : SubRegIndices) {
  1117. if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)
  1118. continue;
  1119. LaneMask |= SubRegIndex.LaneMask;
  1120. }
  1121. RegClass.LaneMask = LaneMask;
  1122. }
  1123. }
  1124. namespace {
  1125. // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
  1126. // the transitive closure of the union of overlapping register
  1127. // classes. Together, the UberRegSets form a partition of the registers. If we
  1128. // consider overlapping register classes to be connected, then each UberRegSet
  1129. // is a set of connected components.
  1130. //
  1131. // An UberRegSet will likely be a horizontal slice of register names of
  1132. // the same width. Nontrivial subregisters should then be in a separate
  1133. // UberRegSet. But this property isn't required for valid computation of
  1134. // register unit weights.
  1135. //
  1136. // A Weight field caches the max per-register unit weight in each UberRegSet.
  1137. //
  1138. // A set of SingularDeterminants flags single units of some register in this set
  1139. // for which the unit weight equals the set weight. These units should not have
  1140. // their weight increased.
  1141. struct UberRegSet {
  1142. CodeGenRegister::Vec Regs;
  1143. unsigned Weight;
  1144. CodeGenRegister::RegUnitList SingularDeterminants;
  1145. UberRegSet(): Weight(0) {}
  1146. };
  1147. } // namespace
  1148. // Partition registers into UberRegSets, where each set is the transitive
  1149. // closure of the union of overlapping register classes.
  1150. //
  1151. // UberRegSets[0] is a special non-allocatable set.
  1152. static void computeUberSets(std::vector<UberRegSet> &UberSets,
  1153. std::vector<UberRegSet*> &RegSets,
  1154. CodeGenRegBank &RegBank) {
  1155. const auto &Registers = RegBank.getRegisters();
  1156. // The Register EnumValue is one greater than its index into Registers.
  1157. assert(Registers.size() == Registers.back().EnumValue &&
  1158. "register enum value mismatch");
  1159. // For simplicitly make the SetID the same as EnumValue.
  1160. IntEqClasses UberSetIDs(Registers.size()+1);
  1161. std::set<unsigned> AllocatableRegs;
  1162. for (auto &RegClass : RegBank.getRegClasses()) {
  1163. if (!RegClass.Allocatable)
  1164. continue;
  1165. const CodeGenRegister::Vec &Regs = RegClass.getMembers();
  1166. if (Regs.empty())
  1167. continue;
  1168. unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
  1169. assert(USetID && "register number 0 is invalid");
  1170. AllocatableRegs.insert((*Regs.begin())->EnumValue);
  1171. for (auto I = std::next(Regs.begin()), E = Regs.end(); I != E; ++I) {
  1172. AllocatableRegs.insert((*I)->EnumValue);
  1173. UberSetIDs.join(USetID, (*I)->EnumValue);
  1174. }
  1175. }
  1176. // Combine non-allocatable regs.
  1177. for (const auto &Reg : Registers) {
  1178. unsigned RegNum = Reg.EnumValue;
  1179. if (AllocatableRegs.count(RegNum))
  1180. continue;
  1181. UberSetIDs.join(0, RegNum);
  1182. }
  1183. UberSetIDs.compress();
  1184. // Make the first UberSet a special unallocatable set.
  1185. unsigned ZeroID = UberSetIDs[0];
  1186. // Insert Registers into the UberSets formed by union-find.
  1187. // Do not resize after this.
  1188. UberSets.resize(UberSetIDs.getNumClasses());
  1189. unsigned i = 0;
  1190. for (const CodeGenRegister &Reg : Registers) {
  1191. unsigned USetID = UberSetIDs[Reg.EnumValue];
  1192. if (!USetID)
  1193. USetID = ZeroID;
  1194. else if (USetID == ZeroID)
  1195. USetID = 0;
  1196. UberRegSet *USet = &UberSets[USetID];
  1197. USet->Regs.push_back(&Reg);
  1198. sortAndUniqueRegisters(USet->Regs);
  1199. RegSets[i++] = USet;
  1200. }
  1201. }
  1202. // Recompute each UberSet weight after changing unit weights.
  1203. static void computeUberWeights(std::vector<UberRegSet> &UberSets,
  1204. CodeGenRegBank &RegBank) {
  1205. // Skip the first unallocatable set.
  1206. for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
  1207. E = UberSets.end(); I != E; ++I) {
  1208. // Initialize all unit weights in this set, and remember the max units/reg.
  1209. const CodeGenRegister *Reg = nullptr;
  1210. unsigned MaxWeight = 0, Weight = 0;
  1211. for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
  1212. if (Reg != UnitI.getReg()) {
  1213. if (Weight > MaxWeight)
  1214. MaxWeight = Weight;
  1215. Reg = UnitI.getReg();
  1216. Weight = 0;
  1217. }
  1218. unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
  1219. if (!UWeight) {
  1220. UWeight = 1;
  1221. RegBank.increaseRegUnitWeight(*UnitI, UWeight);
  1222. }
  1223. Weight += UWeight;
  1224. }
  1225. if (Weight > MaxWeight)
  1226. MaxWeight = Weight;
  1227. if (I->Weight != MaxWeight) {
  1228. DEBUG(
  1229. dbgs() << "UberSet " << I - UberSets.begin() << " Weight " << MaxWeight;
  1230. for (auto &Unit : I->Regs)
  1231. dbgs() << " " << Unit->getName();
  1232. dbgs() << "\n");
  1233. // Update the set weight.
  1234. I->Weight = MaxWeight;
  1235. }
  1236. // Find singular determinants.
  1237. for (const auto R : I->Regs) {
  1238. if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
  1239. I->SingularDeterminants |= R->getRegUnits();
  1240. }
  1241. }
  1242. }
  1243. }
  1244. // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
  1245. // a register and its subregisters so that they have the same weight as their
  1246. // UberSet. Self-recursion processes the subregister tree in postorder so
  1247. // subregisters are normalized first.
  1248. //
  1249. // Side effects:
  1250. // - creates new adopted register units
  1251. // - causes superregisters to inherit adopted units
  1252. // - increases the weight of "singular" units
  1253. // - induces recomputation of UberWeights.
  1254. static bool normalizeWeight(CodeGenRegister *Reg,
  1255. std::vector<UberRegSet> &UberSets,
  1256. std::vector<UberRegSet*> &RegSets,
  1257. SparseBitVector<> &NormalRegs,
  1258. CodeGenRegister::RegUnitList &NormalUnits,
  1259. CodeGenRegBank &RegBank) {
  1260. if (NormalRegs.test(Reg->EnumValue))
  1261. return false;
  1262. NormalRegs.set(Reg->EnumValue);
  1263. bool Changed = false;
  1264. const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
  1265. for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
  1266. SRE = SRM.end(); SRI != SRE; ++SRI) {
  1267. if (SRI->second == Reg)
  1268. continue; // self-cycles happen
  1269. Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
  1270. NormalRegs, NormalUnits, RegBank);
  1271. }
  1272. // Postorder register normalization.
  1273. // Inherit register units newly adopted by subregisters.
  1274. if (Reg->inheritRegUnits(RegBank))
  1275. computeUberWeights(UberSets, RegBank);
  1276. // Check if this register is too skinny for its UberRegSet.
  1277. UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
  1278. unsigned RegWeight = Reg->getWeight(RegBank);
  1279. if (UberSet->Weight > RegWeight) {
  1280. // A register unit's weight can be adjusted only if it is the singular unit
  1281. // for this register, has not been used to normalize a subregister's set,
  1282. // and has not already been used to singularly determine this UberRegSet.
  1283. unsigned AdjustUnit = *Reg->getRegUnits().begin();
  1284. if (Reg->getRegUnits().count() != 1
  1285. || hasRegUnit(NormalUnits, AdjustUnit)
  1286. || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
  1287. // We don't have an adjustable unit, so adopt a new one.
  1288. AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
  1289. Reg->adoptRegUnit(AdjustUnit);
  1290. // Adopting a unit does not immediately require recomputing set weights.
  1291. }
  1292. else {
  1293. // Adjust the existing single unit.
  1294. RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
  1295. // The unit may be shared among sets and registers within this set.
  1296. computeUberWeights(UberSets, RegBank);
  1297. }
  1298. Changed = true;
  1299. }
  1300. // Mark these units normalized so superregisters can't change their weights.
  1301. NormalUnits |= Reg->getRegUnits();
  1302. return Changed;
  1303. }
  1304. // Compute a weight for each register unit created during getSubRegs.
  1305. //
  1306. // The goal is that two registers in the same class will have the same weight,
  1307. // where each register's weight is defined as sum of its units' weights.
  1308. void CodeGenRegBank::computeRegUnitWeights() {
  1309. std::vector<UberRegSet> UberSets;
  1310. std::vector<UberRegSet*> RegSets(Registers.size());
  1311. computeUberSets(UberSets, RegSets, *this);
  1312. // UberSets and RegSets are now immutable.
  1313. computeUberWeights(UberSets, *this);
  1314. // Iterate over each Register, normalizing the unit weights until reaching
  1315. // a fix point.
  1316. unsigned NumIters = 0;
  1317. for (bool Changed = true; Changed; ++NumIters) {
  1318. assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
  1319. Changed = false;
  1320. for (auto &Reg : Registers) {
  1321. CodeGenRegister::RegUnitList NormalUnits;
  1322. SparseBitVector<> NormalRegs;
  1323. Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
  1324. NormalUnits, *this);
  1325. }
  1326. }
  1327. }
  1328. // Find a set in UniqueSets with the same elements as Set.
  1329. // Return an iterator into UniqueSets.
  1330. static std::vector<RegUnitSet>::const_iterator
  1331. findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
  1332. const RegUnitSet &Set) {
  1333. std::vector<RegUnitSet>::const_iterator
  1334. I = UniqueSets.begin(), E = UniqueSets.end();
  1335. for(;I != E; ++I) {
  1336. if (I->Units == Set.Units)
  1337. break;
  1338. }
  1339. return I;
  1340. }
  1341. // Return true if the RUSubSet is a subset of RUSuperSet.
  1342. static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
  1343. const std::vector<unsigned> &RUSuperSet) {
  1344. return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
  1345. RUSubSet.begin(), RUSubSet.end());
  1346. }
  1347. /// Iteratively prune unit sets. Prune subsets that are close to the superset,
  1348. /// but with one or two registers removed. We occasionally have registers like
  1349. /// APSR and PC thrown in with the general registers. We also see many
  1350. /// special-purpose register subsets, such as tail-call and Thumb
  1351. /// encodings. Generating all possible overlapping sets is combinatorial and
  1352. /// overkill for modeling pressure. Ideally we could fix this statically in
  1353. /// tablegen by (1) having the target define register classes that only include
  1354. /// the allocatable registers and marking other classes as non-allocatable and
  1355. /// (2) having a way to mark special purpose classes as "don't-care" classes for
  1356. /// the purpose of pressure. However, we make an attempt to handle targets that
  1357. /// are not nicely defined by merging nearly identical register unit sets
  1358. /// statically. This generates smaller tables. Then, dynamically, we adjust the
  1359. /// set limit by filtering the reserved registers.
  1360. ///
  1361. /// Merge sets only if the units have the same weight. For example, on ARM,
  1362. /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
  1363. /// should not expand the S set to include D regs.
  1364. void CodeGenRegBank::pruneUnitSets() {
  1365. assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
  1366. // Form an equivalence class of UnitSets with no significant difference.
  1367. std::vector<unsigned> SuperSetIDs;
  1368. for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
  1369. SubIdx != EndIdx; ++SubIdx) {
  1370. const RegUnitSet &SubSet = RegUnitSets[SubIdx];
  1371. unsigned SuperIdx = 0;
  1372. for (; SuperIdx != EndIdx; ++SuperIdx) {
  1373. if (SuperIdx == SubIdx)
  1374. continue;
  1375. unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
  1376. const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
  1377. if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
  1378. && (SubSet.Units.size() + 3 > SuperSet.Units.size())
  1379. && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
  1380. && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
  1381. DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
  1382. << "\n");
  1383. break;
  1384. }
  1385. }
  1386. if (SuperIdx == EndIdx)
  1387. SuperSetIDs.push_back(SubIdx);
  1388. }
  1389. // Populate PrunedUnitSets with each equivalence class's superset.
  1390. std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
  1391. for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
  1392. unsigned SuperIdx = SuperSetIDs[i];
  1393. PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
  1394. PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
  1395. }
  1396. RegUnitSets.swap(PrunedUnitSets);
  1397. }
  1398. // Create a RegUnitSet for each RegClass that contains all units in the class
  1399. // including adopted units that are necessary to model register pressure. Then
  1400. // iteratively compute RegUnitSets such that the union of any two overlapping
  1401. // RegUnitSets is repreresented.
  1402. //
  1403. // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
  1404. // RegUnitSet that is a superset of that RegUnitClass.
  1405. void CodeGenRegBank::computeRegUnitSets() {
  1406. assert(RegUnitSets.empty() && "dirty RegUnitSets");
  1407. // Compute a unique RegUnitSet for each RegClass.
  1408. auto &RegClasses = getRegClasses();
  1409. for (auto &RC : RegClasses) {
  1410. if (!RC.Allocatable)
  1411. continue;
  1412. // Speculatively grow the RegUnitSets to hold the new set.
  1413. RegUnitSets.resize(RegUnitSets.size() + 1);
  1414. RegUnitSets.back().Name = RC.getName();
  1415. // Compute a sorted list of units in this class.
  1416. RC.buildRegUnitSet(RegUnitSets.back().Units);
  1417. // Find an existing RegUnitSet.
  1418. std::vector<RegUnitSet>::const_iterator SetI =
  1419. findRegUnitSet(RegUnitSets, RegUnitSets.back());
  1420. if (SetI != std::prev(RegUnitSets.end()))
  1421. RegUnitSets.pop_back();
  1422. }
  1423. DEBUG(dbgs() << "\nBefore pruning:\n";
  1424. for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
  1425. USIdx < USEnd; ++USIdx) {
  1426. dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
  1427. << ":";
  1428. for (auto &U : RegUnitSets[USIdx].Units)
  1429. dbgs() << " " << RegUnits[U].Roots[0]->getName();
  1430. dbgs() << "\n";
  1431. });
  1432. // Iteratively prune unit sets.
  1433. pruneUnitSets();
  1434. DEBUG(dbgs() << "\nBefore union:\n";
  1435. for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
  1436. USIdx < USEnd; ++USIdx) {
  1437. dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
  1438. << ":";
  1439. for (auto &U : RegUnitSets[USIdx].Units)
  1440. dbgs() << " " << RegUnits[U].Roots[0]->getName();
  1441. dbgs() << "\n";
  1442. }
  1443. dbgs() << "\nUnion sets:\n");
  1444. // Iterate over all unit sets, including new ones added by this loop.
  1445. unsigned NumRegUnitSubSets = RegUnitSets.size();
  1446. for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
  1447. // In theory, this is combinatorial. In practice, it needs to be bounded
  1448. // by a small number of sets for regpressure to be efficient.
  1449. // If the assert is hit, we need to implement pruning.
  1450. assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
  1451. // Compare new sets with all original classes.
  1452. for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
  1453. SearchIdx != EndIdx; ++SearchIdx) {
  1454. std::set<unsigned> Intersection;
  1455. std::set_intersection(RegUnitSets[Idx].Units.begin(),
  1456. RegUnitSets[Idx].Units.end(),
  1457. RegUnitSets[SearchIdx].Units.begin(),
  1458. RegUnitSets[SearchIdx].Units.end(),
  1459. std::inserter(Intersection, Intersection.begin()));
  1460. if (Intersection.empty())
  1461. continue;
  1462. // Speculatively grow the RegUnitSets to hold the new set.
  1463. RegUnitSets.resize(RegUnitSets.size() + 1);
  1464. RegUnitSets.back().Name =
  1465. RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
  1466. std::set_union(RegUnitSets[Idx].Units.begin(),
  1467. RegUnitSets[Idx].Units.end(),
  1468. RegUnitSets[SearchIdx].Units.begin(),
  1469. RegUnitSets[SearchIdx].Units.end(),
  1470. std::inserter(RegUnitSets.back().Units,
  1471. RegUnitSets.back().Units.begin()));
  1472. // Find an existing RegUnitSet, or add the union to the unique sets.
  1473. std::vector<RegUnitSet>::const_iterator SetI =
  1474. findRegUnitSet(RegUnitSets, RegUnitSets.back());
  1475. if (SetI != std::prev(RegUnitSets.end()))
  1476. RegUnitSets.pop_back();
  1477. else {
  1478. DEBUG(dbgs() << "UnitSet " << RegUnitSets.size()-1
  1479. << " " << RegUnitSets.back().Name << ":";
  1480. for (auto &U : RegUnitSets.back().Units)
  1481. dbgs() << " " << RegUnits[U].Roots[0]->getName();
  1482. dbgs() << "\n";);
  1483. }
  1484. }
  1485. }
  1486. // Iteratively prune unit sets after inferring supersets.
  1487. pruneUnitSets();
  1488. DEBUG(dbgs() << "\n";
  1489. for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
  1490. USIdx < USEnd; ++USIdx) {
  1491. dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
  1492. << ":";
  1493. for (auto &U : RegUnitSets[USIdx].Units)
  1494. dbgs() << " " << RegUnits[U].Roots[0]->getName();
  1495. dbgs() << "\n";
  1496. });
  1497. // For each register class, list the UnitSets that are supersets.
  1498. RegClassUnitSets.resize(RegClasses.size());
  1499. int RCIdx = -1;
  1500. for (auto &RC : RegClasses) {
  1501. ++RCIdx;
  1502. if (!RC.Allocatable)
  1503. continue;
  1504. // Recompute the sorted list of units in this class.
  1505. std::vector<unsigned> RCRegUnits;
  1506. RC.buildRegUnitSet(RCRegUnits);
  1507. // Don't increase pressure for unallocatable regclasses.
  1508. if (RCRegUnits.empty())
  1509. continue;
  1510. DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";
  1511. for (auto &U : RCRegUnits)
  1512. dbgs() << RegUnits[U].getRoots()[0]->getName() << " ";
  1513. dbgs() << "\n UnitSetIDs:");
  1514. // Find all supersets.
  1515. for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
  1516. USIdx != USEnd; ++USIdx) {
  1517. if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
  1518. DEBUG(dbgs() << " " << USIdx);
  1519. RegClassUnitSets[RCIdx].push_back(USIdx);
  1520. }
  1521. }
  1522. DEBUG(dbgs() << "\n");
  1523. assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
  1524. }
  1525. // For each register unit, ensure that we have the list of UnitSets that
  1526. // contain the unit. Normally, this matches an existing list of UnitSets for a
  1527. // register class. If not, we create a new entry in RegClassUnitSets as a
  1528. // "fake" register class.
  1529. for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
  1530. UnitIdx < UnitEnd; ++UnitIdx) {
  1531. std::vector<unsigned> RUSets;
  1532. for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
  1533. RegUnitSet &RUSet = RegUnitSets[i];
  1534. if (std::find(RUSet.Units.begin(), RUSet.Units.end(), UnitIdx)
  1535. == RUSet.Units.end())
  1536. continue;
  1537. RUSets.push_back(i);
  1538. }
  1539. unsigned RCUnitSetsIdx = 0;
  1540. for (unsigned e = RegClassUnitSets.size();
  1541. RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
  1542. if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
  1543. break;
  1544. }
  1545. }
  1546. RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
  1547. if (RCUnitSetsIdx == RegClassUnitSets.size()) {
  1548. // Create a new list of UnitSets as a "fake" register class.
  1549. RegClassUnitSets.resize(RCUnitSetsIdx + 1);
  1550. RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
  1551. }
  1552. }
  1553. }
  1554. void CodeGenRegBank::computeRegUnitLaneMasks() {
  1555. for (auto &Register : Registers) {
  1556. // Create an initial lane mask for all register units.
  1557. const auto &RegUnits = Register.getRegUnits();
  1558. CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(RegUnits.count(), 0);
  1559. // Iterate through SubRegisters.
  1560. typedef CodeGenRegister::SubRegMap SubRegMap;
  1561. const SubRegMap &SubRegs = Register.getSubRegs();
  1562. for (SubRegMap::const_iterator S = SubRegs.begin(),
  1563. SE = SubRegs.end(); S != SE; ++S) {
  1564. CodeGenRegister *SubReg = S->second;
  1565. // Ignore non-leaf subregisters, their lane masks are fully covered by
  1566. // the leaf subregisters anyway.
  1567. if (SubReg->getSubRegs().size() != 0)
  1568. continue;
  1569. CodeGenSubRegIndex *SubRegIndex = S->first;
  1570. const CodeGenRegister *SubRegister = S->second;
  1571. unsigned LaneMask = SubRegIndex->LaneMask;
  1572. // Distribute LaneMask to Register Units touched.
  1573. for (unsigned SUI : SubRegister->getRegUnits()) {
  1574. bool Found = false;
  1575. unsigned u = 0;
  1576. for (unsigned RU : RegUnits) {
  1577. if (SUI == RU) {
  1578. RegUnitLaneMasks[u] |= LaneMask;
  1579. assert(!Found);
  1580. Found = true;
  1581. }
  1582. ++u;
  1583. }
  1584. (void)Found;
  1585. assert(Found);
  1586. }
  1587. }
  1588. Register.setRegUnitLaneMasks(RegUnitLaneMasks);
  1589. }
  1590. }
  1591. void CodeGenRegBank::computeDerivedInfo() {
  1592. computeComposites();
  1593. computeSubRegLaneMasks();
  1594. // Compute a weight for each register unit created during getSubRegs.
  1595. // This may create adopted register units (with unit # >= NumNativeRegUnits).
  1596. computeRegUnitWeights();
  1597. // Compute a unique set of RegUnitSets. One for each RegClass and inferred
  1598. // supersets for the union of overlapping sets.
  1599. computeRegUnitSets();
  1600. computeRegUnitLaneMasks();
  1601. // Compute register class HasDisjunctSubRegs flag.
  1602. for (CodeGenRegisterClass &RC : RegClasses) {
  1603. RC.HasDisjunctSubRegs = false;
  1604. for (const CodeGenRegister *Reg : RC.getMembers())
  1605. RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;
  1606. }
  1607. // Get the weight of each set.
  1608. for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
  1609. RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
  1610. // Find the order of each set.
  1611. RegUnitSetOrder.reserve(RegUnitSets.size());
  1612. for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
  1613. RegUnitSetOrder.push_back(Idx);
  1614. std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
  1615. [this](unsigned ID1, unsigned ID2) {
  1616. return getRegPressureSet(ID1).Units.size() <
  1617. getRegPressureSet(ID2).Units.size();
  1618. });
  1619. for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
  1620. RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
  1621. }
  1622. }
  1623. //
  1624. // Synthesize missing register class intersections.
  1625. //
  1626. // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
  1627. // returns a maximal register class for all X.
  1628. //
  1629. void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
  1630. assert(!RegClasses.empty());
  1631. // Stash the iterator to the last element so that this loop doesn't visit
  1632. // elements added by the getOrCreateSubClass call within it.
  1633. for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
  1634. I != std::next(E); ++I) {
  1635. CodeGenRegisterClass *RC1 = RC;
  1636. CodeGenRegisterClass *RC2 = &*I;
  1637. if (RC1 == RC2)
  1638. continue;
  1639. // Compute the set intersection of RC1 and RC2.
  1640. const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
  1641. const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
  1642. CodeGenRegister::Vec Intersection;
  1643. std::set_intersection(
  1644. Memb1.begin(), Memb1.end(), Memb2.begin(), Memb2.end(),
  1645. std::inserter(Intersection, Intersection.begin()), deref<llvm::less>());
  1646. // Skip disjoint class pairs.
  1647. if (Intersection.empty())
  1648. continue;
  1649. // If RC1 and RC2 have different spill sizes or alignments, use the
  1650. // larger size for sub-classing. If they are equal, prefer RC1.
  1651. if (RC2->SpillSize > RC1->SpillSize ||
  1652. (RC2->SpillSize == RC1->SpillSize &&
  1653. RC2->SpillAlignment > RC1->SpillAlignment))
  1654. std::swap(RC1, RC2);
  1655. getOrCreateSubClass(RC1, &Intersection,
  1656. RC1->getName() + "_and_" + RC2->getName());
  1657. }
  1658. }
  1659. //
  1660. // Synthesize missing sub-classes for getSubClassWithSubReg().
  1661. //
  1662. // Make sure that the set of registers in RC with a given SubIdx sub-register
  1663. // form a register class. Update RC->SubClassWithSubReg.
  1664. //
  1665. void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
  1666. // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
  1667. typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
  1668. deref<llvm::less>> SubReg2SetMap;
  1669. // Compute the set of registers supporting each SubRegIndex.
  1670. SubReg2SetMap SRSets;
  1671. for (const auto R : RC->getMembers()) {
  1672. const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
  1673. for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
  1674. E = SRM.end(); I != E; ++I)
  1675. SRSets[I->first].push_back(R);
  1676. }
  1677. for (auto I : SRSets)
  1678. sortAndUniqueRegisters(I.second);
  1679. // Find matching classes for all SRSets entries. Iterate in SubRegIndex
  1680. // numerical order to visit synthetic indices last.
  1681. for (const auto &SubIdx : SubRegIndices) {
  1682. SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
  1683. // Unsupported SubRegIndex. Skip it.
  1684. if (I == SRSets.end())
  1685. continue;
  1686. // In most cases, all RC registers support the SubRegIndex.
  1687. if (I->second.size() == RC->getMembers().size()) {
  1688. RC->setSubClassWithSubReg(&SubIdx, RC);
  1689. continue;
  1690. }
  1691. // This is a real subset. See if we have a matching class.
  1692. CodeGenRegisterClass *SubRC =
  1693. getOrCreateSubClass(RC, &I->second,
  1694. RC->getName() + "_with_" + I->first->getName());
  1695. RC->setSubClassWithSubReg(&SubIdx, SubRC);
  1696. }
  1697. }
  1698. //
  1699. // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
  1700. //
  1701. // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
  1702. // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
  1703. //
  1704. void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
  1705. std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
  1706. SmallVector<std::pair<const CodeGenRegister*,
  1707. const CodeGenRegister*>, 16> SSPairs;
  1708. BitVector TopoSigs(getNumTopoSigs());
  1709. // Iterate in SubRegIndex numerical order to visit synthetic indices last.
  1710. for (auto &SubIdx : SubRegIndices) {
  1711. // Skip indexes that aren't fully supported by RC's registers. This was
  1712. // computed by inferSubClassWithSubReg() above which should have been
  1713. // called first.
  1714. if (RC->getSubClassWithSubReg(&SubIdx) != RC)
  1715. continue;
  1716. // Build list of (Super, Sub) pairs for this SubIdx.
  1717. SSPairs.clear();
  1718. TopoSigs.reset();
  1719. for (const auto Super : RC->getMembers()) {
  1720. const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
  1721. assert(Sub && "Missing sub-register");
  1722. SSPairs.push_back(std::make_pair(Super, Sub));
  1723. TopoSigs.set(Sub->getTopoSig());
  1724. }
  1725. // Iterate over sub-register class candidates. Ignore classes created by
  1726. // this loop. They will never be useful.
  1727. // Store an iterator to the last element (not end) so that this loop doesn't
  1728. // visit newly inserted elements.
  1729. assert(!RegClasses.empty());
  1730. for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
  1731. I != std::next(E); ++I) {
  1732. CodeGenRegisterClass &SubRC = *I;
  1733. // Topological shortcut: SubRC members have the wrong shape.
  1734. if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
  1735. continue;
  1736. // Compute the subset of RC that maps into SubRC.
  1737. CodeGenRegister::Vec SubSetVec;
  1738. for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
  1739. if (SubRC.contains(SSPairs[i].second))
  1740. SubSetVec.push_back(SSPairs[i].first);
  1741. if (SubSetVec.empty())
  1742. continue;
  1743. // RC injects completely into SubRC.
  1744. sortAndUniqueRegisters(SubSetVec);
  1745. if (SubSetVec.size() == SSPairs.size()) {
  1746. SubRC.addSuperRegClass(&SubIdx, RC);
  1747. continue;
  1748. }
  1749. // Only a subset of RC maps into SubRC. Make sure it is represented by a
  1750. // class.
  1751. getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
  1752. SubIdx.getName() + "_in_" +
  1753. SubRC.getName());
  1754. }
  1755. }
  1756. }
  1757. //
  1758. // Infer missing register classes.
  1759. //
  1760. void CodeGenRegBank::computeInferredRegisterClasses() {
  1761. assert(!RegClasses.empty());
  1762. // When this function is called, the register classes have not been sorted
  1763. // and assigned EnumValues yet. That means getSubClasses(),
  1764. // getSuperClasses(), and hasSubClass() functions are defunct.
  1765. // Use one-before-the-end so it doesn't move forward when new elements are
  1766. // added.
  1767. auto FirstNewRC = std::prev(RegClasses.end());
  1768. // Visit all register classes, including the ones being added by the loop.
  1769. // Watch out for iterator invalidation here.
  1770. for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
  1771. CodeGenRegisterClass *RC = &*I;
  1772. // Synthesize answers for getSubClassWithSubReg().
  1773. inferSubClassWithSubReg(RC);
  1774. // Synthesize answers for getCommonSubClass().
  1775. inferCommonSubClass(RC);
  1776. // Synthesize answers for getMatchingSuperRegClass().
  1777. inferMatchingSuperRegClass(RC);
  1778. // New register classes are created while this loop is running, and we need
  1779. // to visit all of them. I particular, inferMatchingSuperRegClass needs
  1780. // to match old super-register classes with sub-register classes created
  1781. // after inferMatchingSuperRegClass was called. At this point,
  1782. // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
  1783. // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
  1784. if (I == FirstNewRC) {
  1785. auto NextNewRC = std::prev(RegClasses.end());
  1786. for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
  1787. ++I2)
  1788. inferMatchingSuperRegClass(&*I2, E2);
  1789. FirstNewRC = NextNewRC;
  1790. }
  1791. }
  1792. }
  1793. /// getRegisterClassForRegister - Find the register class that contains the
  1794. /// specified physical register. If the register is not in a register class,
  1795. /// return null. If the register is in multiple classes, and the classes have a
  1796. /// superset-subset relationship and the same set of types, return the
  1797. /// superclass. Otherwise return null.
  1798. const CodeGenRegisterClass*
  1799. CodeGenRegBank::getRegClassForRegister(Record *R) {
  1800. const CodeGenRegister *Reg = getReg(R);
  1801. const CodeGenRegisterClass *FoundRC = nullptr;
  1802. for (const auto &RC : getRegClasses()) {
  1803. if (!RC.contains(Reg))
  1804. continue;
  1805. // If this is the first class that contains the register,
  1806. // make a note of it and go on to the next class.
  1807. if (!FoundRC) {
  1808. FoundRC = &RC;
  1809. continue;
  1810. }
  1811. // If a register's classes have different types, return null.
  1812. if (RC.getValueTypes() != FoundRC->getValueTypes())
  1813. return nullptr;
  1814. // Check to see if the previously found class that contains
  1815. // the register is a subclass of the current class. If so,
  1816. // prefer the superclass.
  1817. if (RC.hasSubClass(FoundRC)) {
  1818. FoundRC = &RC;
  1819. continue;
  1820. }
  1821. // Check to see if the previously found class that contains
  1822. // the register is a superclass of the current class. If so,
  1823. // prefer the superclass.
  1824. if (FoundRC->hasSubClass(&RC))
  1825. continue;
  1826. // Multiple classes, and neither is a superclass of the other.
  1827. // Return null.
  1828. return nullptr;
  1829. }
  1830. return FoundRC;
  1831. }
  1832. BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
  1833. SetVector<const CodeGenRegister*> Set;
  1834. // First add Regs with all sub-registers.
  1835. for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
  1836. CodeGenRegister *Reg = getReg(Regs[i]);
  1837. if (Set.insert(Reg))
  1838. // Reg is new, add all sub-registers.
  1839. // The pre-ordering is not important here.
  1840. Reg->addSubRegsPreOrder(Set, *this);
  1841. }
  1842. // Second, find all super-registers that are completely covered by the set.
  1843. for (unsigned i = 0; i != Set.size(); ++i) {
  1844. const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
  1845. for (unsigned j = 0, e = SR.size(); j != e; ++j) {
  1846. const CodeGenRegister *Super = SR[j];
  1847. if (!Super->CoveredBySubRegs || Set.count(Super))
  1848. continue;
  1849. // This new super-register is covered by its sub-registers.
  1850. bool AllSubsInSet = true;
  1851. const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
  1852. for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
  1853. E = SRM.end(); I != E; ++I)
  1854. if (!Set.count(I->second)) {
  1855. AllSubsInSet = false;
  1856. break;
  1857. }
  1858. // All sub-registers in Set, add Super as well.
  1859. // We will visit Super later to recheck its super-registers.
  1860. if (AllSubsInSet)
  1861. Set.insert(Super);
  1862. }
  1863. }
  1864. // Convert to BitVector.
  1865. BitVector BV(Registers.size() + 1);
  1866. for (unsigned i = 0, e = Set.size(); i != e; ++i)
  1867. BV.set(Set[i]->EnumValue);
  1868. return BV;
  1869. }