1 //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines structures to encapsulate information gleaned from the
11 // target register and register class definitions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenRegisters.h"
16 #include "CodeGenTarget.h"
17 #include "llvm/ADT/IntEqClasses.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/TableGen/Error.h"
27 #define DEBUG_TYPE "regalloc-emitter"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
34 : TheDef(R), EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
36 if (R->getValue("Namespace"))
37 Namespace = R->getValueAsString("Namespace");
38 Size = R->getValueAsInt("Size");
39 Offset = R->getValueAsInt("Offset");
42 CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
44 : TheDef(nullptr), Name(N), Namespace(Nspace), Size(-1), Offset(-1),
45 EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
48 std::string CodeGenSubRegIndex::getQualifiedName() const {
49 std::string N = getNamespace();
56 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
60 std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
62 if (Comps.size() != 2)
63 PrintFatalError(TheDef->getLoc(),
64 "ComposedOf must have exactly two entries");
65 CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
66 CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
67 CodeGenSubRegIndex *X = A->addComposite(B, this);
69 PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
72 std::vector<Record*> Parts =
73 TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
76 PrintFatalError(TheDef->getLoc(),
77 "CoveredBySubRegs must have two or more entries");
78 SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
79 for (unsigned i = 0, e = Parts.size(); i != e; ++i)
80 IdxParts.push_back(RegBank.getSubRegIdx(Parts[i]));
81 RegBank.addConcatSubRegIndex(IdxParts, this);
85 unsigned CodeGenSubRegIndex::computeLaneMask() const {
90 // Recursion guard, shouldn't be required.
93 // The lane mask is simply the union of all sub-indices.
95 for (const auto &C : Composed)
96 M |= C.second->computeLaneMask();
97 assert(M && "Missing lane mask, sub-register cycle?");
102 //===----------------------------------------------------------------------===//
104 //===----------------------------------------------------------------------===//
106 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
109 CostPerUse(R->getValueAsInt("CostPerUse")),
110 CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
111 SubRegsComplete(false),
112 SuperRegsComplete(false),
116 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
117 std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
118 std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
120 if (SRIs.size() != SRs.size())
121 PrintFatalError(TheDef->getLoc(),
122 "SubRegs and SubRegIndices must have the same size");
124 for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
125 ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
126 ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
129 // Also compute leading super-registers. Each register has a list of
130 // covered-by-subregs super-registers where it appears as the first explicit
133 // This is used by computeSecondarySubRegs() to find candidates.
134 if (CoveredBySubRegs && !ExplicitSubRegs.empty())
135 ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
137 // Add ad hoc alias links. This is a symmetric relationship between two
138 // registers, so build a symmetric graph by adding links in both ends.
139 std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
140 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
141 CodeGenRegister *Reg = RegBank.getReg(Aliases[i]);
142 ExplicitAliases.push_back(Reg);
143 Reg->ExplicitAliases.push_back(this);
147 const std::string &CodeGenRegister::getName() const {
148 assert(TheDef && "no def");
149 return TheDef->getName();
153 // Iterate over all register units in a set of registers.
154 class RegUnitIterator {
155 CodeGenRegister::Vec::const_iterator RegI, RegE;
156 CodeGenRegister::RegUnitList::iterator UnitI, UnitE;
159 RegUnitIterator(const CodeGenRegister::Vec &Regs):
160 RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
163 UnitI = (*RegI)->getRegUnits().begin();
164 UnitE = (*RegI)->getRegUnits().end();
169 bool isValid() const { return UnitI != UnitE; }
171 unsigned operator* () const { assert(isValid()); return *UnitI; }
173 const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
175 /// Preincrement. Move to the next unit.
177 assert(isValid() && "Cannot advance beyond the last operand");
184 while (UnitI == UnitE) {
187 UnitI = (*RegI)->getRegUnits().begin();
188 UnitE = (*RegI)->getRegUnits().end();
194 // Return true of this unit appears in RegUnits.
195 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
196 return RegUnits.test(Unit);
199 // Inherit register units from subregisters.
200 // Return true if the RegUnits changed.
201 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
202 bool changed = false;
203 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
205 CodeGenRegister *SR = I->second;
206 // Merge the subregister's units into this register's RegUnits.
207 changed |= (RegUnits |= SR->RegUnits);
213 const CodeGenRegister::SubRegMap &
214 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
215 // Only compute this map once.
218 SubRegsComplete = true;
220 // First insert the explicit subregs and make sure they are fully indexed.
221 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
222 CodeGenRegister *SR = ExplicitSubRegs[i];
223 CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
224 if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
225 PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
226 " appears twice in Register " + getName());
227 // Map explicit sub-registers first, so the names take precedence.
228 // The inherited sub-registers are mapped below.
229 SubReg2Idx.insert(std::make_pair(SR, Idx));
232 // Keep track of inherited subregs and how they can be reached.
233 SmallPtrSet<CodeGenRegister*, 8> Orphans;
235 // Clone inherited subregs and place duplicate entries in Orphans.
236 // Here the order is important - earlier subregs take precedence.
237 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
238 CodeGenRegister *SR = ExplicitSubRegs[i];
239 const SubRegMap &Map = SR->computeSubRegs(RegBank);
241 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
243 if (!SubRegs.insert(*SI).second)
244 Orphans.insert(SI->second);
248 // Expand any composed subreg indices.
249 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
250 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
251 // expanded subreg indices recursively.
252 SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
253 for (unsigned i = 0; i != Indices.size(); ++i) {
254 CodeGenSubRegIndex *Idx = Indices[i];
255 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
256 CodeGenRegister *SR = SubRegs[Idx];
257 const SubRegMap &Map = SR->computeSubRegs(RegBank);
259 // Look at the possible compositions of Idx.
260 // They may not all be supported by SR.
261 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
262 E = Comps.end(); I != E; ++I) {
263 SubRegMap::const_iterator SRI = Map.find(I->first);
264 if (SRI == Map.end())
265 continue; // Idx + I->first doesn't exist in SR.
266 // Add I->second as a name for the subreg SRI->second, assuming it is
267 // orphaned, and the name isn't already used for something else.
268 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
270 // We found a new name for the orphaned sub-register.
271 SubRegs.insert(std::make_pair(I->second, SRI->second));
272 Indices.push_back(I->second);
276 // Now Orphans contains the inherited subregisters without a direct index.
277 // Create inferred indexes for all missing entries.
278 // Work backwards in the Indices vector in order to compose subregs bottom-up.
279 // Consider this subreg sequence:
281 // qsub_1 -> dsub_0 -> ssub_0
283 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
284 // can be reached in two different ways:
289 // We pick the latter composition because another register may have [dsub_0,
290 // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The
291 // dsub_2 -> ssub_0 composition can be shared.
292 while (!Indices.empty() && !Orphans.empty()) {
293 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
294 CodeGenRegister *SR = SubRegs[Idx];
295 const SubRegMap &Map = SR->computeSubRegs(RegBank);
296 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
298 if (Orphans.erase(SI->second))
299 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
302 // Compute the inverse SubReg -> Idx map.
303 for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end();
305 if (SI->second == this) {
308 Loc = TheDef->getLoc();
309 PrintFatalError(Loc, "Register " + getName() +
310 " has itself as a sub-register");
313 // Compute AllSuperRegsCovered.
314 if (!CoveredBySubRegs)
315 SI->first->AllSuperRegsCovered = false;
317 // Ensure that every sub-register has a unique name.
318 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
319 SubReg2Idx.insert(std::make_pair(SI->second, SI->first)).first;
320 if (Ins->second == SI->first)
322 // Trouble: Two different names for SI->second.
325 Loc = TheDef->getLoc();
326 PrintFatalError(Loc, "Sub-register can't have two names: " +
327 SI->second->getName() + " available as " +
328 SI->first->getName() + " and " + Ins->second->getName());
331 // Derive possible names for sub-register concatenations from any explicit
332 // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
333 // that getConcatSubRegIndex() won't invent any concatenated indices that the
334 // user already specified.
335 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
336 CodeGenRegister *SR = ExplicitSubRegs[i];
337 if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1)
340 // SR is composed of multiple sub-regs. Find their names in this register.
341 SmallVector<CodeGenSubRegIndex*, 8> Parts;
342 for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j)
343 Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
345 // Offer this as an existing spelling for the concatenation of Parts.
346 RegBank.addConcatSubRegIndex(Parts, ExplicitSubRegIndices[i]);
349 // Initialize RegUnitList. Because getSubRegs is called recursively, this
350 // processes the register hierarchy in postorder.
352 // Inherit all sub-register units. It is good enough to look at the explicit
353 // sub-registers, the other registers won't contribute any more units.
354 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
355 CodeGenRegister *SR = ExplicitSubRegs[i];
356 RegUnits |= SR->RegUnits;
359 // Absent any ad hoc aliasing, we create one register unit per leaf register.
360 // These units correspond to the maximal cliques in the register overlap
361 // graph which is optimal.
363 // When there is ad hoc aliasing, we simply create one unit per edge in the
364 // undirected ad hoc aliasing graph. Technically, we could do better by
365 // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
366 // are extremely rare anyway (I've never seen one), so we don't bother with
367 // the added complexity.
368 for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
369 CodeGenRegister *AR = ExplicitAliases[i];
370 // Only visit each edge once.
371 if (AR->SubRegsComplete)
373 // Create a RegUnit representing this alias edge, and add it to both
375 unsigned Unit = RegBank.newRegUnit(this, AR);
377 AR->RegUnits.set(Unit);
380 // Finally, create units for leaf registers without ad hoc aliases. Note that
381 // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
382 // necessary. This means the aliasing leaf registers can share a single unit.
383 if (RegUnits.empty())
384 RegUnits.set(RegBank.newRegUnit(this));
386 // We have now computed the native register units. More may be adopted later
387 // for balancing purposes.
388 NativeRegUnits = RegUnits;
393 // In a register that is covered by its sub-registers, try to find redundant
394 // sub-registers. For example:
400 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
401 // the register definition.
403 // The explicitly specified registers form a tree. This function discovers
404 // sub-register relationships that would force a DAG.
406 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
407 // Collect new sub-registers first, add them later.
408 SmallVector<SubRegMap::value_type, 8> NewSubRegs;
410 // Look at the leading super-registers of each sub-register. Those are the
411 // candidates for new sub-registers, assuming they are fully contained in
413 for (SubRegMap::iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I){
414 const CodeGenRegister *SubReg = I->second;
415 const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
416 for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
417 CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
418 // Already got this sub-register?
419 if (Cand == this || getSubRegIndex(Cand))
421 // Check if each component of Cand is already a sub-register.
422 // We know that the first component is I->second, and is present with the
424 SmallVector<CodeGenSubRegIndex*, 8> Parts(1, I->first);
425 assert(!Cand->ExplicitSubRegs.empty() &&
426 "Super-register has no sub-registers");
427 for (unsigned j = 1, e = Cand->ExplicitSubRegs.size(); j != e; ++j) {
428 if (CodeGenSubRegIndex *Idx = getSubRegIndex(Cand->ExplicitSubRegs[j]))
429 Parts.push_back(Idx);
431 // Sub-register doesn't exist.
436 // If some Cand sub-register is not part of this register, or if Cand only
437 // has one sub-register, there is nothing to do.
438 if (Parts.size() <= 1)
441 // Each part of Cand is a sub-register of this. Make the full Cand also
442 // a sub-register with a concatenated sub-register index.
443 CodeGenSubRegIndex *Concat= RegBank.getConcatSubRegIndex(Parts);
444 NewSubRegs.push_back(std::make_pair(Concat, Cand));
448 // Now add all the new sub-registers.
449 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
450 // Don't add Cand if another sub-register is already using the index.
451 if (!SubRegs.insert(NewSubRegs[i]).second)
454 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
455 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
456 SubReg2Idx.insert(std::make_pair(NewSubReg, NewIdx));
459 // Create sub-register index composition maps for the synthesized indices.
460 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
461 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
462 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
463 for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
464 SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
465 CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
467 PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
468 SI->second->getName() + " in " + getName());
469 NewIdx->addComposite(SI->first, SubIdx);
474 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
475 // Only visit each register once.
476 if (SuperRegsComplete)
478 SuperRegsComplete = true;
480 // Make sure all sub-registers have been visited first, so the super-reg
481 // lists will be topologically ordered.
482 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
484 I->second->computeSuperRegs(RegBank);
486 // Now add this as a super-register on all sub-registers.
487 // Also compute the TopoSigId in post-order.
489 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
491 // Topological signature computed from SubIdx, TopoId(SubReg).
492 // Loops and idempotent indices have TopoSig = ~0u.
493 Id.push_back(I->first->EnumValue);
494 Id.push_back(I->second->TopoSig);
496 // Don't add duplicate entries.
497 if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
499 I->second->SuperRegs.push_back(this);
501 TopoSig = RegBank.getTopoSig(Id);
505 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
506 CodeGenRegBank &RegBank) const {
507 assert(SubRegsComplete && "Must precompute sub-registers");
508 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
509 CodeGenRegister *SR = ExplicitSubRegs[i];
511 SR->addSubRegsPreOrder(OSet, RegBank);
513 // Add any secondary sub-registers that weren't part of the explicit tree.
514 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
516 OSet.insert(I->second);
519 // Get the sum of this register's unit weights.
520 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
522 for (RegUnitList::iterator I = RegUnits.begin(), E = RegUnits.end();
524 Weight += RegBank.getRegUnit(*I).Weight;
529 //===----------------------------------------------------------------------===//
531 //===----------------------------------------------------------------------===//
533 // A RegisterTuples def is used to generate pseudo-registers from lists of
534 // sub-registers. We provide a SetTheory expander class that returns the new
537 struct TupleExpander : SetTheory::Expander {
538 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
539 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
540 unsigned Dim = Indices.size();
541 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
542 if (Dim != SubRegs->getSize())
543 PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
545 PrintFatalError(Def->getLoc(),
546 "Tuples must have at least 2 sub-registers");
548 // Evaluate the sub-register lists to be zipped.
549 unsigned Length = ~0u;
550 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
551 for (unsigned i = 0; i != Dim; ++i) {
552 ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
553 Length = std::min(Length, unsigned(Lists[i].size()));
559 // Precompute some types.
560 Record *RegisterCl = Def->getRecords().getClass("Register");
561 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
562 StringInit *BlankName = StringInit::get("");
565 for (unsigned n = 0; n != Length; ++n) {
567 Record *Proto = Lists[0][n];
568 std::vector<Init*> Tuple;
569 unsigned CostPerUse = 0;
570 for (unsigned i = 0; i != Dim; ++i) {
571 Record *Reg = Lists[i][n];
573 Name += Reg->getName();
574 Tuple.push_back(DefInit::get(Reg));
575 CostPerUse = std::max(CostPerUse,
576 unsigned(Reg->getValueAsInt("CostPerUse")));
579 // Create a new Record representing the synthesized register. This record
580 // is only for consumption by CodeGenRegister, it is not added to the
582 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
585 // Copy Proto super-classes.
586 ArrayRef<Record *> Supers = Proto->getSuperClasses();
587 ArrayRef<SMRange> Ranges = Proto->getSuperClassRanges();
588 for (unsigned i = 0, e = Supers.size(); i != e; ++i)
589 NewReg->addSuperClass(Supers[i], Ranges[i]);
591 // Copy Proto fields.
592 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
593 RecordVal RV = Proto->getValues()[i];
595 // Skip existing fields, like NAME.
596 if (NewReg->getValue(RV.getNameInit()))
599 StringRef Field = RV.getName();
601 // Replace the sub-register list with Tuple.
602 if (Field == "SubRegs")
603 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
605 // Provide a blank AsmName. MC hacks are required anyway.
606 if (Field == "AsmName")
607 RV.setValue(BlankName);
609 // CostPerUse is aggregated from all Tuple members.
610 if (Field == "CostPerUse")
611 RV.setValue(IntInit::get(CostPerUse));
613 // Composite registers are always covered by sub-registers.
614 if (Field == "CoveredBySubRegs")
615 RV.setValue(BitInit::get(true));
617 // Copy fields from the RegisterTuples def.
618 if (Field == "SubRegIndices" ||
619 Field == "CompositeIndices") {
620 NewReg->addValue(*Def->getValue(Field));
624 // Some fields get their default uninitialized value.
625 if (Field == "DwarfNumbers" ||
626 Field == "DwarfAlias" ||
627 Field == "Aliases") {
628 if (const RecordVal *DefRV = RegisterCl->getValue(Field))
629 NewReg->addValue(*DefRV);
633 // Everything else is copied from Proto.
634 NewReg->addValue(RV);
641 //===----------------------------------------------------------------------===//
642 // CodeGenRegisterClass
643 //===----------------------------------------------------------------------===//
645 static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
646 std::sort(M.begin(), M.end(), deref<llvm::less>());
647 M.erase(std::unique(M.begin(), M.end(), deref<llvm::equal>()), M.end());
650 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
653 TopoSigs(RegBank.getNumTopoSigs()),
656 // Rename anonymous register classes.
657 if (R->getName().size() > 9 && R->getName()[9] == '.') {
658 static unsigned AnonCounter = 0;
659 R->setName("AnonRegClass_" + utostr(AnonCounter++));
662 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
663 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
664 Record *Type = TypeList[i];
665 if (!Type->isSubClassOf("ValueType"))
666 PrintFatalError("RegTypes list member '" + Type->getName() +
667 "' does not derive from the ValueType class!");
668 VTs.push_back(getValueType(Type));
670 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
672 // Allocation order 0 is the full set. AltOrders provides others.
673 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
674 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
675 Orders.resize(1 + AltOrders->size());
677 // Default allocation order always contains all registers.
678 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
679 Orders[0].push_back((*Elements)[i]);
680 const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
681 Members.push_back(Reg);
682 TopoSigs.set(Reg->getTopoSig());
684 sortAndUniqueRegisters(Members);
686 // Alternative allocation orders may be subsets.
687 SetTheory::RecSet Order;
688 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
689 RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
690 Orders[1 + i].append(Order.begin(), Order.end());
691 // Verify that all altorder members are regclass members.
692 while (!Order.empty()) {
693 CodeGenRegister *Reg = RegBank.getReg(Order.back());
696 PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
697 " is not a class member");
701 // Allow targets to override the size in bits of the RegisterClass.
702 unsigned Size = R->getValueAsInt("Size");
704 Namespace = R->getValueAsString("Namespace");
705 SpillSize = Size ? Size : MVT(VTs[0]).getSizeInBits();
706 SpillAlignment = R->getValueAsInt("Alignment");
707 CopyCost = R->getValueAsInt("CopyCost");
708 Allocatable = R->getValueAsBit("isAllocatable");
709 AltOrderSelect = R->getValueAsString("AltOrderSelect");
712 // Create an inferred register class that was missing from the .td files.
713 // Most properties will be inherited from the closest super-class after the
714 // class structure has been computed.
715 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
716 StringRef Name, Key Props)
717 : Members(*Props.Members),
720 TopoSigs(RegBank.getNumTopoSigs()),
722 SpillSize(Props.SpillSize),
723 SpillAlignment(Props.SpillAlignment),
726 for (const auto R : Members)
727 TopoSigs.set(R->getTopoSig());
730 // Compute inherited propertied for a synthesized register class.
731 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
732 assert(!getDef() && "Only synthesized classes can inherit properties");
733 assert(!SuperClasses.empty() && "Synthesized class without super class");
735 // The last super-class is the smallest one.
736 CodeGenRegisterClass &Super = *SuperClasses.back();
738 // Most properties are copied directly.
739 // Exceptions are members, size, and alignment
740 Namespace = Super.Namespace;
742 CopyCost = Super.CopyCost;
743 Allocatable = Super.Allocatable;
744 AltOrderSelect = Super.AltOrderSelect;
746 // Copy all allocation orders, filter out foreign registers from the larger
748 Orders.resize(Super.Orders.size());
749 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
750 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
751 if (contains(RegBank.getReg(Super.Orders[i][j])))
752 Orders[i].push_back(Super.Orders[i][j]);
755 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
756 return std::binary_search(Members.begin(), Members.end(), Reg,
757 deref<llvm::less>());
761 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
762 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
763 for (const auto R : *K.Members)
764 OS << ", " << R->getName();
769 // This is a simple lexicographical order that can be used to search for sets.
770 // It is not the same as the topological order provided by TopoOrderRC.
771 bool CodeGenRegisterClass::Key::
772 operator<(const CodeGenRegisterClass::Key &B) const {
773 assert(Members && B.Members);
774 return std::tie(*Members, SpillSize, SpillAlignment) <
775 std::tie(*B.Members, B.SpillSize, B.SpillAlignment);
778 // Returns true if RC is a strict subclass.
779 // RC is a sub-class of this class if it is a valid replacement for any
780 // instruction operand where a register of this classis required. It must
781 // satisfy these conditions:
783 // 1. All RC registers are also in this.
784 // 2. The RC spill size must not be smaller than our spill size.
785 // 3. RC spill alignment must be compatible with ours.
787 static bool testSubClass(const CodeGenRegisterClass *A,
788 const CodeGenRegisterClass *B) {
789 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
790 A->SpillSize <= B->SpillSize &&
791 std::includes(A->getMembers().begin(), A->getMembers().end(),
792 B->getMembers().begin(), B->getMembers().end(),
793 deref<llvm::less>());
796 /// Sorting predicate for register classes. This provides a topological
797 /// ordering that arranges all register classes before their sub-classes.
799 /// Register classes with the same registers, spill size, and alignment form a
800 /// clique. They will be ordered alphabetically.
802 static bool TopoOrderRC(const CodeGenRegisterClass &PA,
803 const CodeGenRegisterClass &PB) {
809 // Order by ascending spill size.
810 if (A->SpillSize < B->SpillSize)
812 if (A->SpillSize > B->SpillSize)
815 // Order by ascending spill alignment.
816 if (A->SpillAlignment < B->SpillAlignment)
818 if (A->SpillAlignment > B->SpillAlignment)
821 // Order by descending set size. Note that the classes' allocation order may
822 // not have been computed yet. The Members set is always vaild.
823 if (A->getMembers().size() > B->getMembers().size())
825 if (A->getMembers().size() < B->getMembers().size())
828 // Finally order by name as a tie breaker.
829 return StringRef(A->getName()) < B->getName();
832 std::string CodeGenRegisterClass::getQualifiedName() const {
833 if (Namespace.empty())
836 return Namespace + "::" + getName();
839 // Compute sub-classes of all register classes.
840 // Assume the classes are ordered topologically.
841 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
842 auto &RegClasses = RegBank.getRegClasses();
844 // Visit backwards so sub-classes are seen first.
845 for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
846 CodeGenRegisterClass &RC = *I;
847 RC.SubClasses.resize(RegClasses.size());
848 RC.SubClasses.set(RC.EnumValue);
850 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
851 for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
852 CodeGenRegisterClass &SubRC = *I2;
853 if (RC.SubClasses.test(SubRC.EnumValue))
855 if (!testSubClass(&RC, &SubRC))
857 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
859 RC.SubClasses |= SubRC.SubClasses;
862 // Sweep up missed clique members. They will be immediately preceding RC.
863 for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
864 RC.SubClasses.set(I2->EnumValue);
867 // Compute the SuperClasses lists from the SubClasses vectors.
868 for (auto &RC : RegClasses) {
869 const BitVector &SC = RC.getSubClasses();
870 auto I = RegClasses.begin();
871 for (int s = 0, next_s = SC.find_first(); next_s != -1;
872 next_s = SC.find_next(s)) {
873 std::advance(I, next_s - s);
877 I->SuperClasses.push_back(&RC);
881 // With the class hierarchy in place, let synthesized register classes inherit
882 // properties from their closest super-class. The iteration order here can
883 // propagate properties down multiple levels.
884 for (auto &RC : RegClasses)
886 RC.inheritProperties(RegBank);
889 void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
890 BitVector &Out) const {
891 auto FindI = SuperRegClasses.find(SubIdx);
892 if (FindI == SuperRegClasses.end())
894 for (CodeGenRegisterClass *RC : FindI->second)
895 Out.set(RC->EnumValue);
898 // Populate a unique sorted list of units from a register set.
899 void CodeGenRegisterClass::buildRegUnitSet(
900 std::vector<unsigned> &RegUnits) const {
901 std::vector<unsigned> TmpUnits;
902 for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
903 TmpUnits.push_back(*UnitI);
904 std::sort(TmpUnits.begin(), TmpUnits.end());
905 std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
906 std::back_inserter(RegUnits));
909 //===----------------------------------------------------------------------===//
911 //===----------------------------------------------------------------------===//
913 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) {
914 // Configure register Sets to understand register classes and tuples.
915 Sets.addFieldExpander("RegisterClass", "MemberList");
916 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
917 Sets.addExpander("RegisterTuples", new TupleExpander());
919 // Read in the user-defined (named) sub-register indices.
920 // More indices will be synthesized later.
921 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
922 std::sort(SRIs.begin(), SRIs.end(), LessRecord());
923 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
924 getSubRegIdx(SRIs[i]);
925 // Build composite maps from ComposedOf fields.
926 for (auto &Idx : SubRegIndices)
927 Idx.updateComponents(*this);
929 // Read in the register definitions.
930 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
931 std::sort(Regs.begin(), Regs.end(), LessRecordRegister());
932 // Assign the enumeration values.
933 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
936 // Expand tuples and number the new registers.
937 std::vector<Record*> Tups =
938 Records.getAllDerivedDefinitions("RegisterTuples");
940 for (Record *R : Tups) {
941 std::vector<Record *> TupRegs = *Sets.expand(R);
942 std::sort(TupRegs.begin(), TupRegs.end(), LessRecordRegister());
943 for (Record *RC : TupRegs)
947 // Now all the registers are known. Build the object graph of explicit
948 // register-register references.
949 for (auto &Reg : Registers)
950 Reg.buildObjectGraph(*this);
952 // Compute register name map.
953 for (auto &Reg : Registers)
954 // FIXME: This could just be RegistersByName[name] = register, except that
955 // causes some failures in MIPS - perhaps they have duplicate register name
956 // entries? (or maybe there's a reason for it - I don't know much about this
957 // code, just drive-by refactoring)
958 RegistersByName.insert(
959 std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
961 // Precompute all sub-register maps.
962 // This will create Composite entries for all inferred sub-register indices.
963 for (auto &Reg : Registers)
964 Reg.computeSubRegs(*this);
966 // Infer even more sub-registers by combining leading super-registers.
967 for (auto &Reg : Registers)
968 if (Reg.CoveredBySubRegs)
969 Reg.computeSecondarySubRegs(*this);
971 // After the sub-register graph is complete, compute the topologically
972 // ordered SuperRegs list.
973 for (auto &Reg : Registers)
974 Reg.computeSuperRegs(*this);
976 // Native register units are associated with a leaf register. They've all been
978 NumNativeRegUnits = RegUnits.size();
980 // Read in register class definitions.
981 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
983 PrintFatalError("No 'RegisterClass' subclasses defined!");
985 // Allocate user-defined register classes.
986 for (auto *RC : RCs) {
987 RegClasses.push_back(CodeGenRegisterClass(*this, RC));
988 addToMaps(&RegClasses.back());
991 // Infer missing classes to create a full algebra.
992 computeInferredRegisterClasses();
994 // Order register classes topologically and assign enum values.
995 RegClasses.sort(TopoOrderRC);
997 for (auto &RC : RegClasses)
999 CodeGenRegisterClass::computeSubClasses(*this);
1002 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1004 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1005 SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
1006 return &SubRegIndices.back();
1009 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1010 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1013 SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
1014 Idx = &SubRegIndices.back();
1018 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1019 CodeGenRegister *&Reg = Def2Reg[Def];
1022 Registers.emplace_back(Def, Registers.size() + 1);
1023 Reg = &Registers.back();
1027 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1028 if (Record *Def = RC->getDef())
1029 Def2RC.insert(std::make_pair(Def, RC));
1031 // Duplicate classes are rejected by insert().
1032 // That's OK, we only care about the properties handled by CGRC::Key.
1033 CodeGenRegisterClass::Key K(*RC);
1034 Key2RC.insert(std::make_pair(K, RC));
1037 // Create a synthetic sub-class if it is missing.
1038 CodeGenRegisterClass*
1039 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1040 const CodeGenRegister::Vec *Members,
1042 // Synthetic sub-class has the same size and alignment as RC.
1043 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
1044 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1045 if (FoundI != Key2RC.end())
1046 return FoundI->second;
1048 // Sub-class doesn't exist, create a new one.
1049 RegClasses.push_back(CodeGenRegisterClass(*this, Name, K));
1050 addToMaps(&RegClasses.back());
1051 return &RegClasses.back();
1054 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1055 if (CodeGenRegisterClass *RC = Def2RC[Def])
1058 PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1062 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1063 CodeGenSubRegIndex *B) {
1064 // Look for an existing entry.
1065 CodeGenSubRegIndex *Comp = A->compose(B);
1069 // None exists, synthesize one.
1070 std::string Name = A->getName() + "_then_" + B->getName();
1071 Comp = createSubRegIndex(Name, A->getNamespace());
1072 A->addComposite(B, Comp);
1076 CodeGenSubRegIndex *CodeGenRegBank::
1077 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1078 assert(Parts.size() > 1 && "Need two parts to concatenate");
1080 // Look for an existing entry.
1081 CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1085 // None exists, synthesize one.
1086 std::string Name = Parts.front()->getName();
1087 // Determine whether all parts are contiguous.
1088 bool isContinuous = true;
1089 unsigned Size = Parts.front()->Size;
1090 unsigned LastOffset = Parts.front()->Offset;
1091 unsigned LastSize = Parts.front()->Size;
1092 for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1094 Name += Parts[i]->getName();
1095 Size += Parts[i]->Size;
1096 if (Parts[i]->Offset != (LastOffset + LastSize))
1097 isContinuous = false;
1098 LastOffset = Parts[i]->Offset;
1099 LastSize = Parts[i]->Size;
1101 Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1103 Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1107 void CodeGenRegBank::computeComposites() {
1108 // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1109 // and many registers will share TopoSigs on regular architectures.
1110 BitVector TopoSigs(getNumTopoSigs());
1112 for (const auto &Reg1 : Registers) {
1113 // Skip identical subreg structures already processed.
1114 if (TopoSigs.test(Reg1.getTopoSig()))
1116 TopoSigs.set(Reg1.getTopoSig());
1118 const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1119 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1120 e1 = SRM1.end(); i1 != e1; ++i1) {
1121 CodeGenSubRegIndex *Idx1 = i1->first;
1122 CodeGenRegister *Reg2 = i1->second;
1123 // Ignore identity compositions.
1126 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1127 // Try composing Idx1 with another SubRegIndex.
1128 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1129 e2 = SRM2.end(); i2 != e2; ++i2) {
1130 CodeGenSubRegIndex *Idx2 = i2->first;
1131 CodeGenRegister *Reg3 = i2->second;
1132 // Ignore identity compositions.
1135 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1136 CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
1137 assert(Idx3 && "Sub-register doesn't have an index");
1139 // Conflicting composition? Emit a warning but allow it.
1140 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
1141 PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1142 " and " + Idx2->getQualifiedName() +
1143 " compose ambiguously as " + Prev->getQualifiedName() +
1144 " or " + Idx3->getQualifiedName());
1150 // Compute lane masks. This is similar to register units, but at the
1151 // sub-register index level. Each bit in the lane mask is like a register unit
1152 // class, and two lane masks will have a bit in common if two sub-register
1153 // indices overlap in some register.
1155 // Conservatively share a lane mask bit if two sub-register indices overlap in
1156 // some registers, but not in others. That shouldn't happen a lot.
1157 void CodeGenRegBank::computeSubRegLaneMasks() {
1158 // First assign individual bits to all the leaf indices.
1160 // Determine mask of lanes that cover their registers.
1161 CoveringLanes = ~0u;
1162 for (auto &Idx : SubRegIndices) {
1163 if (Idx.getComposites().empty()) {
1164 Idx.LaneMask = 1u << Bit;
1165 // Share bit 31 in the unlikely case there are more than 32 leafs.
1167 // Sharing bits is harmless; it allows graceful degradation in targets
1168 // with more than 32 vector lanes. They simply get a limited resolution
1169 // view of lanes beyond the 32nd.
1171 // See also the comment for getSubRegIndexLaneMask().
1175 // Once bit 31 is shared among multiple leafs, the 'lane' it represents
1176 // is no longer covering its registers.
1177 CoveringLanes &= ~(1u << Bit);
1183 // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
1184 // here is that for each possible target subregister we look at the leafs
1185 // in the subregister graph that compose for this target and create
1186 // transformation sequences for the lanemasks. Each step in the sequence
1187 // consists of a bitmask and a bitrotate operation. As the rotation amounts
1188 // are usually the same for many subregisters we can easily combine the steps
1189 // by combining the masks.
1190 for (const auto &Idx : SubRegIndices) {
1191 const auto &Composites = Idx.getComposites();
1192 auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
1193 // Go through all leaf subregisters and find the ones that compose with Idx.
1194 // These make out all possible valid bits in the lane mask we want to
1195 // transform. Looking only at the leafs ensure that only a single bit in
1197 unsigned NextBit = 0;
1198 for (auto &Idx2 : SubRegIndices) {
1199 // Skip non-leaf subregisters.
1200 if (!Idx2.getComposites().empty())
1202 // Replicate the behaviour from the lane mask generation loop above.
1203 unsigned SrcBit = NextBit;
1204 unsigned SrcMask = 1u << SrcBit;
1207 assert(Idx2.LaneMask == SrcMask);
1209 // Get the composed subregister if there is any.
1210 auto C = Composites.find(&Idx2);
1211 if (C == Composites.end())
1213 const CodeGenSubRegIndex *Composite = C->second;
1214 // The Composed subreg should be a leaf subreg too
1215 assert(Composite->getComposites().empty());
1217 // Create Mask+Rotate operation and merge with existing ops if possible.
1218 unsigned DstBit = Log2_32(Composite->LaneMask);
1219 int Shift = DstBit - SrcBit;
1220 uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift : 32+Shift;
1221 for (auto &I : LaneTransforms) {
1222 if (I.RotateLeft == RotateLeft) {
1228 MaskRolPair MaskRol = { SrcMask, RotateLeft };
1229 LaneTransforms.push_back(MaskRol);
1232 // Optimize if the transformation consists of one step only: Set mask to
1233 // 0xffffffff (including some irrelevant invalid bits) so that it should
1234 // merge with more entries later while compressing the table.
1235 if (LaneTransforms.size() == 1)
1236 LaneTransforms[0].Mask = ~0u;
1238 // Further compression optimization: For invalid compositions resulting
1239 // in a sequence with 0 entries we can just pick any other. Choose
1240 // Mask 0xffffffff with Rotation 0.
1241 if (LaneTransforms.size() == 0) {
1242 MaskRolPair P = { ~0u, 0 };
1243 LaneTransforms.push_back(P);
1247 // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1248 // by the sub-register graph? This doesn't occur in any known targets.
1250 // Inherit lanes from composites.
1251 for (const auto &Idx : SubRegIndices) {
1252 unsigned Mask = Idx.computeLaneMask();
1253 // If some super-registers without CoveredBySubRegs use this index, we can
1254 // no longer assume that the lanes are covering their registers.
1255 if (!Idx.AllSuperRegsCovered)
1256 CoveringLanes &= ~Mask;
1259 // Compute lane mask combinations for register classes.
1260 for (auto &RegClass : RegClasses) {
1261 unsigned LaneMask = 0;
1262 for (const auto &SubRegIndex : SubRegIndices) {
1263 if (RegClass.getSubClassWithSubReg(&SubRegIndex) != &RegClass)
1265 LaneMask |= SubRegIndex.LaneMask;
1267 RegClass.LaneMask = LaneMask;
1272 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1273 // the transitive closure of the union of overlapping register
1274 // classes. Together, the UberRegSets form a partition of the registers. If we
1275 // consider overlapping register classes to be connected, then each UberRegSet
1276 // is a set of connected components.
1278 // An UberRegSet will likely be a horizontal slice of register names of
1279 // the same width. Nontrivial subregisters should then be in a separate
1280 // UberRegSet. But this property isn't required for valid computation of
1281 // register unit weights.
1283 // A Weight field caches the max per-register unit weight in each UberRegSet.
1285 // A set of SingularDeterminants flags single units of some register in this set
1286 // for which the unit weight equals the set weight. These units should not have
1287 // their weight increased.
1289 CodeGenRegister::Vec Regs;
1291 CodeGenRegister::RegUnitList SingularDeterminants;
1293 UberRegSet(): Weight(0) {}
1297 // Partition registers into UberRegSets, where each set is the transitive
1298 // closure of the union of overlapping register classes.
1300 // UberRegSets[0] is a special non-allocatable set.
1301 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1302 std::vector<UberRegSet*> &RegSets,
1303 CodeGenRegBank &RegBank) {
1305 const auto &Registers = RegBank.getRegisters();
1307 // The Register EnumValue is one greater than its index into Registers.
1308 assert(Registers.size() == Registers.back().EnumValue &&
1309 "register enum value mismatch");
1311 // For simplicitly make the SetID the same as EnumValue.
1312 IntEqClasses UberSetIDs(Registers.size()+1);
1313 std::set<unsigned> AllocatableRegs;
1314 for (auto &RegClass : RegBank.getRegClasses()) {
1315 if (!RegClass.Allocatable)
1318 const CodeGenRegister::Vec &Regs = RegClass.getMembers();
1322 unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1323 assert(USetID && "register number 0 is invalid");
1325 AllocatableRegs.insert((*Regs.begin())->EnumValue);
1326 for (auto I = std::next(Regs.begin()), E = Regs.end(); I != E; ++I) {
1327 AllocatableRegs.insert((*I)->EnumValue);
1328 UberSetIDs.join(USetID, (*I)->EnumValue);
1331 // Combine non-allocatable regs.
1332 for (const auto &Reg : Registers) {
1333 unsigned RegNum = Reg.EnumValue;
1334 if (AllocatableRegs.count(RegNum))
1337 UberSetIDs.join(0, RegNum);
1339 UberSetIDs.compress();
1341 // Make the first UberSet a special unallocatable set.
1342 unsigned ZeroID = UberSetIDs[0];
1344 // Insert Registers into the UberSets formed by union-find.
1345 // Do not resize after this.
1346 UberSets.resize(UberSetIDs.getNumClasses());
1348 for (const CodeGenRegister &Reg : Registers) {
1349 unsigned USetID = UberSetIDs[Reg.EnumValue];
1352 else if (USetID == ZeroID)
1355 UberRegSet *USet = &UberSets[USetID];
1356 USet->Regs.push_back(&Reg);
1357 sortAndUniqueRegisters(USet->Regs);
1358 RegSets[i++] = USet;
1362 // Recompute each UberSet weight after changing unit weights.
1363 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1364 CodeGenRegBank &RegBank) {
1365 // Skip the first unallocatable set.
1366 for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1367 E = UberSets.end(); I != E; ++I) {
1369 // Initialize all unit weights in this set, and remember the max units/reg.
1370 const CodeGenRegister *Reg = nullptr;
1371 unsigned MaxWeight = 0, Weight = 0;
1372 for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1373 if (Reg != UnitI.getReg()) {
1374 if (Weight > MaxWeight)
1376 Reg = UnitI.getReg();
1379 unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1382 RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1386 if (Weight > MaxWeight)
1388 if (I->Weight != MaxWeight) {
1390 dbgs() << "UberSet " << I - UberSets.begin() << " Weight " << MaxWeight;
1391 for (auto &Unit : I->Regs)
1392 dbgs() << " " << Unit->getName();
1394 // Update the set weight.
1395 I->Weight = MaxWeight;
1398 // Find singular determinants.
1399 for (const auto R : I->Regs) {
1400 if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
1401 I->SingularDeterminants |= R->getRegUnits();
1407 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1408 // a register and its subregisters so that they have the same weight as their
1409 // UberSet. Self-recursion processes the subregister tree in postorder so
1410 // subregisters are normalized first.
1413 // - creates new adopted register units
1414 // - causes superregisters to inherit adopted units
1415 // - increases the weight of "singular" units
1416 // - induces recomputation of UberWeights.
1417 static bool normalizeWeight(CodeGenRegister *Reg,
1418 std::vector<UberRegSet> &UberSets,
1419 std::vector<UberRegSet*> &RegSets,
1420 SparseBitVector<> &NormalRegs,
1421 CodeGenRegister::RegUnitList &NormalUnits,
1422 CodeGenRegBank &RegBank) {
1423 if (NormalRegs.test(Reg->EnumValue))
1425 NormalRegs.set(Reg->EnumValue);
1427 bool Changed = false;
1428 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1429 for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1430 SRE = SRM.end(); SRI != SRE; ++SRI) {
1431 if (SRI->second == Reg)
1432 continue; // self-cycles happen
1434 Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1435 NormalRegs, NormalUnits, RegBank);
1437 // Postorder register normalization.
1439 // Inherit register units newly adopted by subregisters.
1440 if (Reg->inheritRegUnits(RegBank))
1441 computeUberWeights(UberSets, RegBank);
1443 // Check if this register is too skinny for its UberRegSet.
1444 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1446 unsigned RegWeight = Reg->getWeight(RegBank);
1447 if (UberSet->Weight > RegWeight) {
1448 // A register unit's weight can be adjusted only if it is the singular unit
1449 // for this register, has not been used to normalize a subregister's set,
1450 // and has not already been used to singularly determine this UberRegSet.
1451 unsigned AdjustUnit = *Reg->getRegUnits().begin();
1452 if (Reg->getRegUnits().count() != 1
1453 || hasRegUnit(NormalUnits, AdjustUnit)
1454 || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1455 // We don't have an adjustable unit, so adopt a new one.
1456 AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1457 Reg->adoptRegUnit(AdjustUnit);
1458 // Adopting a unit does not immediately require recomputing set weights.
1461 // Adjust the existing single unit.
1462 RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1463 // The unit may be shared among sets and registers within this set.
1464 computeUberWeights(UberSets, RegBank);
1469 // Mark these units normalized so superregisters can't change their weights.
1470 NormalUnits |= Reg->getRegUnits();
1475 // Compute a weight for each register unit created during getSubRegs.
1477 // The goal is that two registers in the same class will have the same weight,
1478 // where each register's weight is defined as sum of its units' weights.
1479 void CodeGenRegBank::computeRegUnitWeights() {
1480 std::vector<UberRegSet> UberSets;
1481 std::vector<UberRegSet*> RegSets(Registers.size());
1482 computeUberSets(UberSets, RegSets, *this);
1483 // UberSets and RegSets are now immutable.
1485 computeUberWeights(UberSets, *this);
1487 // Iterate over each Register, normalizing the unit weights until reaching
1489 unsigned NumIters = 0;
1490 for (bool Changed = true; Changed; ++NumIters) {
1491 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1493 for (auto &Reg : Registers) {
1494 CodeGenRegister::RegUnitList NormalUnits;
1495 SparseBitVector<> NormalRegs;
1496 Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
1497 NormalUnits, *this);
1502 // Find a set in UniqueSets with the same elements as Set.
1503 // Return an iterator into UniqueSets.
1504 static std::vector<RegUnitSet>::const_iterator
1505 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1506 const RegUnitSet &Set) {
1507 std::vector<RegUnitSet>::const_iterator
1508 I = UniqueSets.begin(), E = UniqueSets.end();
1510 if (I->Units == Set.Units)
1516 // Return true if the RUSubSet is a subset of RUSuperSet.
1517 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1518 const std::vector<unsigned> &RUSuperSet) {
1519 return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1520 RUSubSet.begin(), RUSubSet.end());
1523 /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1524 /// but with one or two registers removed. We occasionally have registers like
1525 /// APSR and PC thrown in with the general registers. We also see many
1526 /// special-purpose register subsets, such as tail-call and Thumb
1527 /// encodings. Generating all possible overlapping sets is combinatorial and
1528 /// overkill for modeling pressure. Ideally we could fix this statically in
1529 /// tablegen by (1) having the target define register classes that only include
1530 /// the allocatable registers and marking other classes as non-allocatable and
1531 /// (2) having a way to mark special purpose classes as "don't-care" classes for
1532 /// the purpose of pressure. However, we make an attempt to handle targets that
1533 /// are not nicely defined by merging nearly identical register unit sets
1534 /// statically. This generates smaller tables. Then, dynamically, we adjust the
1535 /// set limit by filtering the reserved registers.
1537 /// Merge sets only if the units have the same weight. For example, on ARM,
1538 /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1539 /// should not expand the S set to include D regs.
1540 void CodeGenRegBank::pruneUnitSets() {
1541 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1543 // Form an equivalence class of UnitSets with no significant difference.
1544 std::vector<unsigned> SuperSetIDs;
1545 for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1546 SubIdx != EndIdx; ++SubIdx) {
1547 const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1548 unsigned SuperIdx = 0;
1549 for (; SuperIdx != EndIdx; ++SuperIdx) {
1550 if (SuperIdx == SubIdx)
1553 unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1554 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1555 if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1556 && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1557 && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1558 && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1559 DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1564 if (SuperIdx == EndIdx)
1565 SuperSetIDs.push_back(SubIdx);
1567 // Populate PrunedUnitSets with each equivalence class's superset.
1568 std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1569 for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1570 unsigned SuperIdx = SuperSetIDs[i];
1571 PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1572 PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1574 RegUnitSets.swap(PrunedUnitSets);
1577 // Create a RegUnitSet for each RegClass that contains all units in the class
1578 // including adopted units that are necessary to model register pressure. Then
1579 // iteratively compute RegUnitSets such that the union of any two overlapping
1580 // RegUnitSets is repreresented.
1582 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1583 // RegUnitSet that is a superset of that RegUnitClass.
1584 void CodeGenRegBank::computeRegUnitSets() {
1585 assert(RegUnitSets.empty() && "dirty RegUnitSets");
1587 // Compute a unique RegUnitSet for each RegClass.
1588 auto &RegClasses = getRegClasses();
1589 for (auto &RC : RegClasses) {
1590 if (!RC.Allocatable)
1593 // Speculatively grow the RegUnitSets to hold the new set.
1594 RegUnitSets.resize(RegUnitSets.size() + 1);
1595 RegUnitSets.back().Name = RC.getName();
1597 // Compute a sorted list of units in this class.
1598 RC.buildRegUnitSet(RegUnitSets.back().Units);
1600 // Find an existing RegUnitSet.
1601 std::vector<RegUnitSet>::const_iterator SetI =
1602 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1603 if (SetI != std::prev(RegUnitSets.end()))
1604 RegUnitSets.pop_back();
1607 DEBUG(dbgs() << "\nBefore pruning:\n";
1608 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1609 USIdx < USEnd; ++USIdx) {
1610 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1612 for (auto &U : RegUnitSets[USIdx].Units)
1613 dbgs() << " " << RegUnits[U].Roots[0]->getName();
1617 // Iteratively prune unit sets.
1620 DEBUG(dbgs() << "\nBefore union:\n";
1621 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1622 USIdx < USEnd; ++USIdx) {
1623 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1625 for (auto &U : RegUnitSets[USIdx].Units)
1626 dbgs() << " " << RegUnits[U].Roots[0]->getName();
1629 dbgs() << "\nUnion sets:\n");
1631 // Iterate over all unit sets, including new ones added by this loop.
1632 unsigned NumRegUnitSubSets = RegUnitSets.size();
1633 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1634 // In theory, this is combinatorial. In practice, it needs to be bounded
1635 // by a small number of sets for regpressure to be efficient.
1636 // If the assert is hit, we need to implement pruning.
1637 assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1639 // Compare new sets with all original classes.
1640 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1641 SearchIdx != EndIdx; ++SearchIdx) {
1642 std::set<unsigned> Intersection;
1643 std::set_intersection(RegUnitSets[Idx].Units.begin(),
1644 RegUnitSets[Idx].Units.end(),
1645 RegUnitSets[SearchIdx].Units.begin(),
1646 RegUnitSets[SearchIdx].Units.end(),
1647 std::inserter(Intersection, Intersection.begin()));
1648 if (Intersection.empty())
1651 // Speculatively grow the RegUnitSets to hold the new set.
1652 RegUnitSets.resize(RegUnitSets.size() + 1);
1653 RegUnitSets.back().Name =
1654 RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1656 std::set_union(RegUnitSets[Idx].Units.begin(),
1657 RegUnitSets[Idx].Units.end(),
1658 RegUnitSets[SearchIdx].Units.begin(),
1659 RegUnitSets[SearchIdx].Units.end(),
1660 std::inserter(RegUnitSets.back().Units,
1661 RegUnitSets.back().Units.begin()));
1663 // Find an existing RegUnitSet, or add the union to the unique sets.
1664 std::vector<RegUnitSet>::const_iterator SetI =
1665 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1666 if (SetI != std::prev(RegUnitSets.end()))
1667 RegUnitSets.pop_back();
1669 DEBUG(dbgs() << "UnitSet " << RegUnitSets.size()-1
1670 << " " << RegUnitSets.back().Name << ":";
1671 for (auto &U : RegUnitSets.back().Units)
1672 dbgs() << " " << RegUnits[U].Roots[0]->getName();
1678 // Iteratively prune unit sets after inferring supersets.
1681 DEBUG(dbgs() << "\n";
1682 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1683 USIdx < USEnd; ++USIdx) {
1684 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1686 for (auto &U : RegUnitSets[USIdx].Units)
1687 dbgs() << " " << RegUnits[U].Roots[0]->getName();
1691 // For each register class, list the UnitSets that are supersets.
1692 RegClassUnitSets.resize(RegClasses.size());
1694 for (auto &RC : RegClasses) {
1696 if (!RC.Allocatable)
1699 // Recompute the sorted list of units in this class.
1700 std::vector<unsigned> RCRegUnits;
1701 RC.buildRegUnitSet(RCRegUnits);
1703 // Don't increase pressure for unallocatable regclasses.
1704 if (RCRegUnits.empty())
1707 DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";
1708 for (auto &U : RCRegUnits)
1709 dbgs() << RegUnits[U].getRoots()[0]->getName() << " ";
1710 dbgs() << "\n UnitSetIDs:");
1712 // Find all supersets.
1713 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1714 USIdx != USEnd; ++USIdx) {
1715 if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
1716 DEBUG(dbgs() << " " << USIdx);
1717 RegClassUnitSets[RCIdx].push_back(USIdx);
1720 DEBUG(dbgs() << "\n");
1721 assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1724 // For each register unit, ensure that we have the list of UnitSets that
1725 // contain the unit. Normally, this matches an existing list of UnitSets for a
1726 // register class. If not, we create a new entry in RegClassUnitSets as a
1727 // "fake" register class.
1728 for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
1729 UnitIdx < UnitEnd; ++UnitIdx) {
1730 std::vector<unsigned> RUSets;
1731 for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
1732 RegUnitSet &RUSet = RegUnitSets[i];
1733 if (std::find(RUSet.Units.begin(), RUSet.Units.end(), UnitIdx)
1734 == RUSet.Units.end())
1736 RUSets.push_back(i);
1738 unsigned RCUnitSetsIdx = 0;
1739 for (unsigned e = RegClassUnitSets.size();
1740 RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
1741 if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
1745 RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
1746 if (RCUnitSetsIdx == RegClassUnitSets.size()) {
1747 // Create a new list of UnitSets as a "fake" register class.
1748 RegClassUnitSets.resize(RCUnitSetsIdx + 1);
1749 RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
1754 void CodeGenRegBank::computeRegUnitLaneMasks() {
1755 for (auto &Register : Registers) {
1756 // Create an initial lane mask for all register units.
1757 const auto &RegUnits = Register.getRegUnits();
1758 CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(RegUnits.count(), 0);
1759 // Iterate through SubRegisters.
1760 typedef CodeGenRegister::SubRegMap SubRegMap;
1761 const SubRegMap &SubRegs = Register.getSubRegs();
1762 for (SubRegMap::const_iterator S = SubRegs.begin(),
1763 SE = SubRegs.end(); S != SE; ++S) {
1764 CodeGenRegister *SubReg = S->second;
1765 // Ignore non-leaf subregisters, their lane masks are fully covered by
1766 // the leaf subregisters anyway.
1767 if (SubReg->getSubRegs().size() != 0)
1769 CodeGenSubRegIndex *SubRegIndex = S->first;
1770 const CodeGenRegister *SubRegister = S->second;
1771 unsigned LaneMask = SubRegIndex->LaneMask;
1772 // Distribute LaneMask to Register Units touched.
1773 for (const auto &SUI : SubRegister->getRegUnits()) {
1776 for (unsigned RU : RegUnits) {
1778 RegUnitLaneMasks[u] |= LaneMask;
1787 Register.setRegUnitLaneMasks(RegUnitLaneMasks);
1791 void CodeGenRegBank::computeDerivedInfo() {
1792 computeComposites();
1793 computeSubRegLaneMasks();
1795 // Compute a weight for each register unit created during getSubRegs.
1796 // This may create adopted register units (with unit # >= NumNativeRegUnits).
1797 computeRegUnitWeights();
1799 // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1800 // supersets for the union of overlapping sets.
1801 computeRegUnitSets();
1803 computeRegUnitLaneMasks();
1805 // Get the weight of each set.
1806 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1807 RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
1809 // Find the order of each set.
1810 RegUnitSetOrder.reserve(RegUnitSets.size());
1811 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1812 RegUnitSetOrder.push_back(Idx);
1814 std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
1815 [this](unsigned ID1, unsigned ID2) {
1816 return getRegPressureSet(ID1).Units.size() <
1817 getRegPressureSet(ID2).Units.size();
1819 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1820 RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
1825 // Synthesize missing register class intersections.
1827 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1828 // returns a maximal register class for all X.
1830 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1831 assert(!RegClasses.empty());
1832 // Stash the iterator to the last element so that this loop doesn't visit
1833 // elements added by the getOrCreateSubClass call within it.
1834 for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
1835 I != std::next(E); ++I) {
1836 CodeGenRegisterClass *RC1 = RC;
1837 CodeGenRegisterClass *RC2 = &*I;
1841 // Compute the set intersection of RC1 and RC2.
1842 const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
1843 const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
1844 CodeGenRegister::Vec Intersection;
1845 std::set_intersection(
1846 Memb1.begin(), Memb1.end(), Memb2.begin(), Memb2.end(),
1847 std::inserter(Intersection, Intersection.begin()), deref<llvm::less>());
1849 // Skip disjoint class pairs.
1850 if (Intersection.empty())
1853 // If RC1 and RC2 have different spill sizes or alignments, use the
1854 // larger size for sub-classing. If they are equal, prefer RC1.
1855 if (RC2->SpillSize > RC1->SpillSize ||
1856 (RC2->SpillSize == RC1->SpillSize &&
1857 RC2->SpillAlignment > RC1->SpillAlignment))
1858 std::swap(RC1, RC2);
1860 getOrCreateSubClass(RC1, &Intersection,
1861 RC1->getName() + "_and_" + RC2->getName());
1866 // Synthesize missing sub-classes for getSubClassWithSubReg().
1868 // Make sure that the set of registers in RC with a given SubIdx sub-register
1869 // form a register class. Update RC->SubClassWithSubReg.
1871 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1872 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1873 typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
1874 deref<llvm::less>> SubReg2SetMap;
1876 // Compute the set of registers supporting each SubRegIndex.
1877 SubReg2SetMap SRSets;
1878 for (const auto R : RC->getMembers()) {
1879 const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
1880 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1881 E = SRM.end(); I != E; ++I)
1882 SRSets[I->first].push_back(R);
1885 for (auto I : SRSets)
1886 sortAndUniqueRegisters(I.second);
1888 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
1889 // numerical order to visit synthetic indices last.
1890 for (const auto &SubIdx : SubRegIndices) {
1891 SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
1892 // Unsupported SubRegIndex. Skip it.
1893 if (I == SRSets.end())
1895 // In most cases, all RC registers support the SubRegIndex.
1896 if (I->second.size() == RC->getMembers().size()) {
1897 RC->setSubClassWithSubReg(&SubIdx, RC);
1900 // This is a real subset. See if we have a matching class.
1901 CodeGenRegisterClass *SubRC =
1902 getOrCreateSubClass(RC, &I->second,
1903 RC->getName() + "_with_" + I->first->getName());
1904 RC->setSubClassWithSubReg(&SubIdx, SubRC);
1909 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1911 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1912 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1915 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1916 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
1917 SmallVector<std::pair<const CodeGenRegister*,
1918 const CodeGenRegister*>, 16> SSPairs;
1919 BitVector TopoSigs(getNumTopoSigs());
1921 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1922 for (auto &SubIdx : SubRegIndices) {
1923 // Skip indexes that aren't fully supported by RC's registers. This was
1924 // computed by inferSubClassWithSubReg() above which should have been
1926 if (RC->getSubClassWithSubReg(&SubIdx) != RC)
1929 // Build list of (Super, Sub) pairs for this SubIdx.
1932 for (const auto Super : RC->getMembers()) {
1933 const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
1934 assert(Sub && "Missing sub-register");
1935 SSPairs.push_back(std::make_pair(Super, Sub));
1936 TopoSigs.set(Sub->getTopoSig());
1939 // Iterate over sub-register class candidates. Ignore classes created by
1940 // this loop. They will never be useful.
1941 // Store an iterator to the last element (not end) so that this loop doesn't
1942 // visit newly inserted elements.
1943 assert(!RegClasses.empty());
1944 for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
1945 I != std::next(E); ++I) {
1946 CodeGenRegisterClass &SubRC = *I;
1947 // Topological shortcut: SubRC members have the wrong shape.
1948 if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
1950 // Compute the subset of RC that maps into SubRC.
1951 CodeGenRegister::Vec SubSetVec;
1952 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1953 if (SubRC.contains(SSPairs[i].second))
1954 SubSetVec.push_back(SSPairs[i].first);
1956 if (SubSetVec.empty())
1959 // RC injects completely into SubRC.
1960 sortAndUniqueRegisters(SubSetVec);
1961 if (SubSetVec.size() == SSPairs.size()) {
1962 SubRC.addSuperRegClass(&SubIdx, RC);
1966 // Only a subset of RC maps into SubRC. Make sure it is represented by a
1968 getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
1969 SubIdx.getName() + "_in_" +
1977 // Infer missing register classes.
1979 void CodeGenRegBank::computeInferredRegisterClasses() {
1980 assert(!RegClasses.empty());
1981 // When this function is called, the register classes have not been sorted
1982 // and assigned EnumValues yet. That means getSubClasses(),
1983 // getSuperClasses(), and hasSubClass() functions are defunct.
1985 // Use one-before-the-end so it doesn't move forward when new elements are
1987 auto FirstNewRC = std::prev(RegClasses.end());
1989 // Visit all register classes, including the ones being added by the loop.
1990 // Watch out for iterator invalidation here.
1991 for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
1992 CodeGenRegisterClass *RC = &*I;
1994 // Synthesize answers for getSubClassWithSubReg().
1995 inferSubClassWithSubReg(RC);
1997 // Synthesize answers for getCommonSubClass().
1998 inferCommonSubClass(RC);
2000 // Synthesize answers for getMatchingSuperRegClass().
2001 inferMatchingSuperRegClass(RC);
2003 // New register classes are created while this loop is running, and we need
2004 // to visit all of them. I particular, inferMatchingSuperRegClass needs
2005 // to match old super-register classes with sub-register classes created
2006 // after inferMatchingSuperRegClass was called. At this point,
2007 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2008 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
2009 if (I == FirstNewRC) {
2010 auto NextNewRC = std::prev(RegClasses.end());
2011 for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
2013 inferMatchingSuperRegClass(&*I2, E2);
2014 FirstNewRC = NextNewRC;
2019 /// getRegisterClassForRegister - Find the register class that contains the
2020 /// specified physical register. If the register is not in a register class,
2021 /// return null. If the register is in multiple classes, and the classes have a
2022 /// superset-subset relationship and the same set of types, return the
2023 /// superclass. Otherwise return null.
2024 const CodeGenRegisterClass*
2025 CodeGenRegBank::getRegClassForRegister(Record *R) {
2026 const CodeGenRegister *Reg = getReg(R);
2027 const CodeGenRegisterClass *FoundRC = nullptr;
2028 for (const auto &RC : getRegClasses()) {
2029 if (!RC.contains(Reg))
2032 // If this is the first class that contains the register,
2033 // make a note of it and go on to the next class.
2039 // If a register's classes have different types, return null.
2040 if (RC.getValueTypes() != FoundRC->getValueTypes())
2043 // Check to see if the previously found class that contains
2044 // the register is a subclass of the current class. If so,
2045 // prefer the superclass.
2046 if (RC.hasSubClass(FoundRC)) {
2051 // Check to see if the previously found class that contains
2052 // the register is a superclass of the current class. If so,
2053 // prefer the superclass.
2054 if (FoundRC->hasSubClass(&RC))
2057 // Multiple classes, and neither is a superclass of the other.
2064 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
2065 SetVector<const CodeGenRegister*> Set;
2067 // First add Regs with all sub-registers.
2068 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2069 CodeGenRegister *Reg = getReg(Regs[i]);
2070 if (Set.insert(Reg))
2071 // Reg is new, add all sub-registers.
2072 // The pre-ordering is not important here.
2073 Reg->addSubRegsPreOrder(Set, *this);
2076 // Second, find all super-registers that are completely covered by the set.
2077 for (unsigned i = 0; i != Set.size(); ++i) {
2078 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
2079 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
2080 const CodeGenRegister *Super = SR[j];
2081 if (!Super->CoveredBySubRegs || Set.count(Super))
2083 // This new super-register is covered by its sub-registers.
2084 bool AllSubsInSet = true;
2085 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2086 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2087 E = SRM.end(); I != E; ++I)
2088 if (!Set.count(I->second)) {
2089 AllSubsInSet = false;
2092 // All sub-registers in Set, add Super as well.
2093 // We will visit Super later to recheck its super-registers.
2099 // Convert to BitVector.
2100 BitVector BV(Registers.size() + 1);
2101 for (unsigned i = 0, e = Set.size(); i != e; ++i)
2102 BV.set(Set[i]->EnumValue);