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));
660 // MSVC2012 ICEs if AnonCounter++ is directly passed to utostr.
664 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
665 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
666 Record *Type = TypeList[i];
667 if (!Type->isSubClassOf("ValueType"))
668 PrintFatalError("RegTypes list member '" + Type->getName() +
669 "' does not derive from the ValueType class!");
670 VTs.push_back(getValueType(Type));
672 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
674 // Allocation order 0 is the full set. AltOrders provides others.
675 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
676 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
677 Orders.resize(1 + AltOrders->size());
679 // Default allocation order always contains all registers.
680 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
681 Orders[0].push_back((*Elements)[i]);
682 const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
683 Members.push_back(Reg);
684 TopoSigs.set(Reg->getTopoSig());
686 sortAndUniqueRegisters(Members);
688 // Alternative allocation orders may be subsets.
689 SetTheory::RecSet Order;
690 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
691 RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
692 Orders[1 + i].append(Order.begin(), Order.end());
693 // Verify that all altorder members are regclass members.
694 while (!Order.empty()) {
695 CodeGenRegister *Reg = RegBank.getReg(Order.back());
698 PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
699 " is not a class member");
703 // Allow targets to override the size in bits of the RegisterClass.
704 unsigned Size = R->getValueAsInt("Size");
706 Namespace = R->getValueAsString("Namespace");
707 SpillSize = Size ? Size : MVT(VTs[0]).getSizeInBits();
708 SpillAlignment = R->getValueAsInt("Alignment");
709 CopyCost = R->getValueAsInt("CopyCost");
710 Allocatable = R->getValueAsBit("isAllocatable");
711 AltOrderSelect = R->getValueAsString("AltOrderSelect");
714 // Create an inferred register class that was missing from the .td files.
715 // Most properties will be inherited from the closest super-class after the
716 // class structure has been computed.
717 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
718 StringRef Name, Key Props)
719 : Members(*Props.Members),
722 TopoSigs(RegBank.getNumTopoSigs()),
724 SpillSize(Props.SpillSize),
725 SpillAlignment(Props.SpillAlignment),
728 for (const auto R : Members)
729 TopoSigs.set(R->getTopoSig());
732 // Compute inherited propertied for a synthesized register class.
733 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
734 assert(!getDef() && "Only synthesized classes can inherit properties");
735 assert(!SuperClasses.empty() && "Synthesized class without super class");
737 // The last super-class is the smallest one.
738 CodeGenRegisterClass &Super = *SuperClasses.back();
740 // Most properties are copied directly.
741 // Exceptions are members, size, and alignment
742 Namespace = Super.Namespace;
744 CopyCost = Super.CopyCost;
745 Allocatable = Super.Allocatable;
746 AltOrderSelect = Super.AltOrderSelect;
748 // Copy all allocation orders, filter out foreign registers from the larger
750 Orders.resize(Super.Orders.size());
751 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
752 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
753 if (contains(RegBank.getReg(Super.Orders[i][j])))
754 Orders[i].push_back(Super.Orders[i][j]);
757 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
758 return std::binary_search(Members.begin(), Members.end(), Reg,
759 deref<llvm::less>());
763 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
764 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
765 for (const auto R : *K.Members)
766 OS << ", " << R->getName();
771 // This is a simple lexicographical order that can be used to search for sets.
772 // It is not the same as the topological order provided by TopoOrderRC.
773 bool CodeGenRegisterClass::Key::
774 operator<(const CodeGenRegisterClass::Key &B) const {
775 assert(Members && B.Members);
776 return std::tie(*Members, SpillSize, SpillAlignment) <
777 std::tie(*B.Members, B.SpillSize, B.SpillAlignment);
780 // Returns true if RC is a strict subclass.
781 // RC is a sub-class of this class if it is a valid replacement for any
782 // instruction operand where a register of this classis required. It must
783 // satisfy these conditions:
785 // 1. All RC registers are also in this.
786 // 2. The RC spill size must not be smaller than our spill size.
787 // 3. RC spill alignment must be compatible with ours.
789 static bool testSubClass(const CodeGenRegisterClass *A,
790 const CodeGenRegisterClass *B) {
791 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
792 A->SpillSize <= B->SpillSize &&
793 std::includes(A->getMembers().begin(), A->getMembers().end(),
794 B->getMembers().begin(), B->getMembers().end(),
795 deref<llvm::less>());
798 /// Sorting predicate for register classes. This provides a topological
799 /// ordering that arranges all register classes before their sub-classes.
801 /// Register classes with the same registers, spill size, and alignment form a
802 /// clique. They will be ordered alphabetically.
804 static bool TopoOrderRC(const CodeGenRegisterClass &PA,
805 const CodeGenRegisterClass &PB) {
811 // Order by ascending spill size.
812 if (A->SpillSize < B->SpillSize)
814 if (A->SpillSize > B->SpillSize)
817 // Order by ascending spill alignment.
818 if (A->SpillAlignment < B->SpillAlignment)
820 if (A->SpillAlignment > B->SpillAlignment)
823 // Order by descending set size. Note that the classes' allocation order may
824 // not have been computed yet. The Members set is always vaild.
825 if (A->getMembers().size() > B->getMembers().size())
827 if (A->getMembers().size() < B->getMembers().size())
830 // Finally order by name as a tie breaker.
831 return StringRef(A->getName()) < B->getName();
834 std::string CodeGenRegisterClass::getQualifiedName() const {
835 if (Namespace.empty())
838 return Namespace + "::" + getName();
841 // Compute sub-classes of all register classes.
842 // Assume the classes are ordered topologically.
843 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
844 auto &RegClasses = RegBank.getRegClasses();
846 // Visit backwards so sub-classes are seen first.
847 for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
848 CodeGenRegisterClass &RC = *I;
849 RC.SubClasses.resize(RegClasses.size());
850 RC.SubClasses.set(RC.EnumValue);
852 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
853 for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
854 CodeGenRegisterClass &SubRC = *I2;
855 if (RC.SubClasses.test(SubRC.EnumValue))
857 if (!testSubClass(&RC, &SubRC))
859 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
861 RC.SubClasses |= SubRC.SubClasses;
864 // Sweep up missed clique members. They will be immediately preceding RC.
865 for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
866 RC.SubClasses.set(I2->EnumValue);
869 // Compute the SuperClasses lists from the SubClasses vectors.
870 for (auto &RC : RegClasses) {
871 const BitVector &SC = RC.getSubClasses();
872 auto I = RegClasses.begin();
873 for (int s = 0, next_s = SC.find_first(); next_s != -1;
874 next_s = SC.find_next(s)) {
875 std::advance(I, next_s - s);
879 I->SuperClasses.push_back(&RC);
883 // With the class hierarchy in place, let synthesized register classes inherit
884 // properties from their closest super-class. The iteration order here can
885 // propagate properties down multiple levels.
886 for (auto &RC : RegClasses)
888 RC.inheritProperties(RegBank);
891 void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
892 BitVector &Out) const {
893 auto FindI = SuperRegClasses.find(SubIdx);
894 if (FindI == SuperRegClasses.end())
896 for (CodeGenRegisterClass *RC : FindI->second)
897 Out.set(RC->EnumValue);
900 // Populate a unique sorted list of units from a register set.
901 void CodeGenRegisterClass::buildRegUnitSet(
902 std::vector<unsigned> &RegUnits) const {
903 std::vector<unsigned> TmpUnits;
904 for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
905 TmpUnits.push_back(*UnitI);
906 std::sort(TmpUnits.begin(), TmpUnits.end());
907 std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
908 std::back_inserter(RegUnits));
911 //===----------------------------------------------------------------------===//
913 //===----------------------------------------------------------------------===//
915 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) {
916 // Configure register Sets to understand register classes and tuples.
917 Sets.addFieldExpander("RegisterClass", "MemberList");
918 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
919 Sets.addExpander("RegisterTuples", new TupleExpander());
921 // Read in the user-defined (named) sub-register indices.
922 // More indices will be synthesized later.
923 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
924 std::sort(SRIs.begin(), SRIs.end(), LessRecord());
925 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
926 getSubRegIdx(SRIs[i]);
927 // Build composite maps from ComposedOf fields.
928 for (auto &Idx : SubRegIndices)
929 Idx.updateComponents(*this);
931 // Read in the register definitions.
932 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
933 std::sort(Regs.begin(), Regs.end(), LessRecordRegister());
934 // Assign the enumeration values.
935 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
938 // Expand tuples and number the new registers.
939 std::vector<Record*> Tups =
940 Records.getAllDerivedDefinitions("RegisterTuples");
942 for (Record *R : Tups) {
943 std::vector<Record *> TupRegs = *Sets.expand(R);
944 std::sort(TupRegs.begin(), TupRegs.end(), LessRecordRegister());
945 for (Record *RC : TupRegs)
949 // Now all the registers are known. Build the object graph of explicit
950 // register-register references.
951 for (auto &Reg : Registers)
952 Reg.buildObjectGraph(*this);
954 // Compute register name map.
955 for (auto &Reg : Registers)
956 // FIXME: This could just be RegistersByName[name] = register, except that
957 // causes some failures in MIPS - perhaps they have duplicate register name
958 // entries? (or maybe there's a reason for it - I don't know much about this
959 // code, just drive-by refactoring)
960 RegistersByName.insert(
961 std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
963 // Precompute all sub-register maps.
964 // This will create Composite entries for all inferred sub-register indices.
965 for (auto &Reg : Registers)
966 Reg.computeSubRegs(*this);
968 // Infer even more sub-registers by combining leading super-registers.
969 for (auto &Reg : Registers)
970 if (Reg.CoveredBySubRegs)
971 Reg.computeSecondarySubRegs(*this);
973 // After the sub-register graph is complete, compute the topologically
974 // ordered SuperRegs list.
975 for (auto &Reg : Registers)
976 Reg.computeSuperRegs(*this);
978 // Native register units are associated with a leaf register. They've all been
980 NumNativeRegUnits = RegUnits.size();
982 // Read in register class definitions.
983 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
985 PrintFatalError("No 'RegisterClass' subclasses defined!");
987 // Allocate user-defined register classes.
988 for (auto *RC : RCs) {
989 RegClasses.push_back(CodeGenRegisterClass(*this, RC));
990 addToMaps(&RegClasses.back());
993 // Infer missing classes to create a full algebra.
994 computeInferredRegisterClasses();
996 // Order register classes topologically and assign enum values.
997 RegClasses.sort(TopoOrderRC);
999 for (auto &RC : RegClasses)
1001 CodeGenRegisterClass::computeSubClasses(*this);
1004 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1006 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1007 SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
1008 return &SubRegIndices.back();
1011 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1012 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1015 SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
1016 Idx = &SubRegIndices.back();
1020 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1021 CodeGenRegister *&Reg = Def2Reg[Def];
1024 Registers.emplace_back(Def, Registers.size() + 1);
1025 Reg = &Registers.back();
1029 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1030 if (Record *Def = RC->getDef())
1031 Def2RC.insert(std::make_pair(Def, RC));
1033 // Duplicate classes are rejected by insert().
1034 // That's OK, we only care about the properties handled by CGRC::Key.
1035 CodeGenRegisterClass::Key K(*RC);
1036 Key2RC.insert(std::make_pair(K, RC));
1039 // Create a synthetic sub-class if it is missing.
1040 CodeGenRegisterClass*
1041 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1042 const CodeGenRegister::Vec *Members,
1044 // Synthetic sub-class has the same size and alignment as RC.
1045 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
1046 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1047 if (FoundI != Key2RC.end())
1048 return FoundI->second;
1050 // Sub-class doesn't exist, create a new one.
1051 RegClasses.push_back(CodeGenRegisterClass(*this, Name, K));
1052 addToMaps(&RegClasses.back());
1053 return &RegClasses.back();
1056 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1057 if (CodeGenRegisterClass *RC = Def2RC[Def])
1060 PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1064 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1065 CodeGenSubRegIndex *B) {
1066 // Look for an existing entry.
1067 CodeGenSubRegIndex *Comp = A->compose(B);
1071 // None exists, synthesize one.
1072 std::string Name = A->getName() + "_then_" + B->getName();
1073 Comp = createSubRegIndex(Name, A->getNamespace());
1074 A->addComposite(B, Comp);
1078 CodeGenSubRegIndex *CodeGenRegBank::
1079 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1080 assert(Parts.size() > 1 && "Need two parts to concatenate");
1082 // Look for an existing entry.
1083 CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1087 // None exists, synthesize one.
1088 std::string Name = Parts.front()->getName();
1089 // Determine whether all parts are contiguous.
1090 bool isContinuous = true;
1091 unsigned Size = Parts.front()->Size;
1092 unsigned LastOffset = Parts.front()->Offset;
1093 unsigned LastSize = Parts.front()->Size;
1094 for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1096 Name += Parts[i]->getName();
1097 Size += Parts[i]->Size;
1098 if (Parts[i]->Offset != (LastOffset + LastSize))
1099 isContinuous = false;
1100 LastOffset = Parts[i]->Offset;
1101 LastSize = Parts[i]->Size;
1103 Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1105 Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1109 void CodeGenRegBank::computeComposites() {
1110 // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1111 // and many registers will share TopoSigs on regular architectures.
1112 BitVector TopoSigs(getNumTopoSigs());
1114 for (const auto &Reg1 : Registers) {
1115 // Skip identical subreg structures already processed.
1116 if (TopoSigs.test(Reg1.getTopoSig()))
1118 TopoSigs.set(Reg1.getTopoSig());
1120 const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1121 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1122 e1 = SRM1.end(); i1 != e1; ++i1) {
1123 CodeGenSubRegIndex *Idx1 = i1->first;
1124 CodeGenRegister *Reg2 = i1->second;
1125 // Ignore identity compositions.
1128 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1129 // Try composing Idx1 with another SubRegIndex.
1130 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1131 e2 = SRM2.end(); i2 != e2; ++i2) {
1132 CodeGenSubRegIndex *Idx2 = i2->first;
1133 CodeGenRegister *Reg3 = i2->second;
1134 // Ignore identity compositions.
1137 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1138 CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
1139 assert(Idx3 && "Sub-register doesn't have an index");
1141 // Conflicting composition? Emit a warning but allow it.
1142 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
1143 PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1144 " and " + Idx2->getQualifiedName() +
1145 " compose ambiguously as " + Prev->getQualifiedName() +
1146 " or " + Idx3->getQualifiedName());
1152 // Compute lane masks. This is similar to register units, but at the
1153 // sub-register index level. Each bit in the lane mask is like a register unit
1154 // class, and two lane masks will have a bit in common if two sub-register
1155 // indices overlap in some register.
1157 // Conservatively share a lane mask bit if two sub-register indices overlap in
1158 // some registers, but not in others. That shouldn't happen a lot.
1159 void CodeGenRegBank::computeSubRegLaneMasks() {
1160 // First assign individual bits to all the leaf indices.
1162 // Determine mask of lanes that cover their registers.
1163 CoveringLanes = ~0u;
1164 for (auto &Idx : SubRegIndices) {
1165 if (Idx.getComposites().empty()) {
1166 Idx.LaneMask = 1u << Bit;
1167 // Share bit 31 in the unlikely case there are more than 32 leafs.
1169 // Sharing bits is harmless; it allows graceful degradation in targets
1170 // with more than 32 vector lanes. They simply get a limited resolution
1171 // view of lanes beyond the 32nd.
1173 // See also the comment for getSubRegIndexLaneMask().
1177 // Once bit 31 is shared among multiple leafs, the 'lane' it represents
1178 // is no longer covering its registers.
1179 CoveringLanes &= ~(1u << Bit);
1185 // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
1186 // here is that for each possible target subregister we look at the leafs
1187 // in the subregister graph that compose for this target and create
1188 // transformation sequences for the lanemasks. Each step in the sequence
1189 // consists of a bitmask and a bitrotate operation. As the rotation amounts
1190 // are usually the same for many subregisters we can easily combine the steps
1191 // by combining the masks.
1192 for (const auto &Idx : SubRegIndices) {
1193 const auto &Composites = Idx.getComposites();
1194 auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
1195 // Go through all leaf subregisters and find the ones that compose with Idx.
1196 // These make out all possible valid bits in the lane mask we want to
1197 // transform. Looking only at the leafs ensure that only a single bit in
1199 unsigned NextBit = 0;
1200 for (auto &Idx2 : SubRegIndices) {
1201 // Skip non-leaf subregisters.
1202 if (!Idx2.getComposites().empty())
1204 // Replicate the behaviour from the lane mask generation loop above.
1205 unsigned SrcBit = NextBit;
1206 unsigned SrcMask = 1u << SrcBit;
1209 assert(Idx2.LaneMask == SrcMask);
1211 // Get the composed subregister if there is any.
1212 auto C = Composites.find(&Idx2);
1213 if (C == Composites.end())
1215 const CodeGenSubRegIndex *Composite = C->second;
1216 // The Composed subreg should be a leaf subreg too
1217 assert(Composite->getComposites().empty());
1219 // Create Mask+Rotate operation and merge with existing ops if possible.
1220 unsigned DstBit = Log2_32(Composite->LaneMask);
1221 int Shift = DstBit - SrcBit;
1222 uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift : 32+Shift;
1223 for (auto &I : LaneTransforms) {
1224 if (I.RotateLeft == RotateLeft) {
1230 MaskRolPair MaskRol = { SrcMask, RotateLeft };
1231 LaneTransforms.push_back(MaskRol);
1234 // Optimize if the transformation consists of one step only: Set mask to
1235 // 0xffffffff (including some irrelevant invalid bits) so that it should
1236 // merge with more entries later while compressing the table.
1237 if (LaneTransforms.size() == 1)
1238 LaneTransforms[0].Mask = ~0u;
1240 // Further compression optimization: For invalid compositions resulting
1241 // in a sequence with 0 entries we can just pick any other. Choose
1242 // Mask 0xffffffff with Rotation 0.
1243 if (LaneTransforms.size() == 0) {
1244 MaskRolPair P = { ~0u, 0 };
1245 LaneTransforms.push_back(P);
1249 // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1250 // by the sub-register graph? This doesn't occur in any known targets.
1252 // Inherit lanes from composites.
1253 for (const auto &Idx : SubRegIndices) {
1254 unsigned Mask = Idx.computeLaneMask();
1255 // If some super-registers without CoveredBySubRegs use this index, we can
1256 // no longer assume that the lanes are covering their registers.
1257 if (!Idx.AllSuperRegsCovered)
1258 CoveringLanes &= ~Mask;
1261 // Compute lane mask combinations for register classes.
1262 for (auto &RegClass : RegClasses) {
1263 unsigned LaneMask = 0;
1264 for (const auto &SubRegIndex : SubRegIndices) {
1265 if (RegClass.getSubClassWithSubReg(&SubRegIndex) != &RegClass)
1267 LaneMask |= SubRegIndex.LaneMask;
1269 RegClass.LaneMask = LaneMask;
1274 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1275 // the transitive closure of the union of overlapping register
1276 // classes. Together, the UberRegSets form a partition of the registers. If we
1277 // consider overlapping register classes to be connected, then each UberRegSet
1278 // is a set of connected components.
1280 // An UberRegSet will likely be a horizontal slice of register names of
1281 // the same width. Nontrivial subregisters should then be in a separate
1282 // UberRegSet. But this property isn't required for valid computation of
1283 // register unit weights.
1285 // A Weight field caches the max per-register unit weight in each UberRegSet.
1287 // A set of SingularDeterminants flags single units of some register in this set
1288 // for which the unit weight equals the set weight. These units should not have
1289 // their weight increased.
1291 CodeGenRegister::Vec Regs;
1293 CodeGenRegister::RegUnitList SingularDeterminants;
1295 UberRegSet(): Weight(0) {}
1299 // Partition registers into UberRegSets, where each set is the transitive
1300 // closure of the union of overlapping register classes.
1302 // UberRegSets[0] is a special non-allocatable set.
1303 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1304 std::vector<UberRegSet*> &RegSets,
1305 CodeGenRegBank &RegBank) {
1307 const auto &Registers = RegBank.getRegisters();
1309 // The Register EnumValue is one greater than its index into Registers.
1310 assert(Registers.size() == Registers.back().EnumValue &&
1311 "register enum value mismatch");
1313 // For simplicitly make the SetID the same as EnumValue.
1314 IntEqClasses UberSetIDs(Registers.size()+1);
1315 std::set<unsigned> AllocatableRegs;
1316 for (auto &RegClass : RegBank.getRegClasses()) {
1317 if (!RegClass.Allocatable)
1320 const CodeGenRegister::Vec &Regs = RegClass.getMembers();
1324 unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1325 assert(USetID && "register number 0 is invalid");
1327 AllocatableRegs.insert((*Regs.begin())->EnumValue);
1328 for (auto I = std::next(Regs.begin()), E = Regs.end(); I != E; ++I) {
1329 AllocatableRegs.insert((*I)->EnumValue);
1330 UberSetIDs.join(USetID, (*I)->EnumValue);
1333 // Combine non-allocatable regs.
1334 for (const auto &Reg : Registers) {
1335 unsigned RegNum = Reg.EnumValue;
1336 if (AllocatableRegs.count(RegNum))
1339 UberSetIDs.join(0, RegNum);
1341 UberSetIDs.compress();
1343 // Make the first UberSet a special unallocatable set.
1344 unsigned ZeroID = UberSetIDs[0];
1346 // Insert Registers into the UberSets formed by union-find.
1347 // Do not resize after this.
1348 UberSets.resize(UberSetIDs.getNumClasses());
1350 for (const CodeGenRegister &Reg : Registers) {
1351 unsigned USetID = UberSetIDs[Reg.EnumValue];
1354 else if (USetID == ZeroID)
1357 UberRegSet *USet = &UberSets[USetID];
1358 USet->Regs.push_back(&Reg);
1359 sortAndUniqueRegisters(USet->Regs);
1360 RegSets[i++] = USet;
1364 // Recompute each UberSet weight after changing unit weights.
1365 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1366 CodeGenRegBank &RegBank) {
1367 // Skip the first unallocatable set.
1368 for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1369 E = UberSets.end(); I != E; ++I) {
1371 // Initialize all unit weights in this set, and remember the max units/reg.
1372 const CodeGenRegister *Reg = nullptr;
1373 unsigned MaxWeight = 0, Weight = 0;
1374 for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1375 if (Reg != UnitI.getReg()) {
1376 if (Weight > MaxWeight)
1378 Reg = UnitI.getReg();
1381 unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1384 RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1388 if (Weight > MaxWeight)
1390 if (I->Weight != MaxWeight) {
1392 dbgs() << "UberSet " << I - UberSets.begin() << " Weight " << MaxWeight;
1393 for (auto &Unit : I->Regs)
1394 dbgs() << " " << Unit->getName();
1396 // Update the set weight.
1397 I->Weight = MaxWeight;
1400 // Find singular determinants.
1401 for (const auto R : I->Regs) {
1402 if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
1403 I->SingularDeterminants |= R->getRegUnits();
1409 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1410 // a register and its subregisters so that they have the same weight as their
1411 // UberSet. Self-recursion processes the subregister tree in postorder so
1412 // subregisters are normalized first.
1415 // - creates new adopted register units
1416 // - causes superregisters to inherit adopted units
1417 // - increases the weight of "singular" units
1418 // - induces recomputation of UberWeights.
1419 static bool normalizeWeight(CodeGenRegister *Reg,
1420 std::vector<UberRegSet> &UberSets,
1421 std::vector<UberRegSet*> &RegSets,
1422 SparseBitVector<> &NormalRegs,
1423 CodeGenRegister::RegUnitList &NormalUnits,
1424 CodeGenRegBank &RegBank) {
1425 if (NormalRegs.test(Reg->EnumValue))
1427 NormalRegs.set(Reg->EnumValue);
1429 bool Changed = false;
1430 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1431 for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1432 SRE = SRM.end(); SRI != SRE; ++SRI) {
1433 if (SRI->second == Reg)
1434 continue; // self-cycles happen
1436 Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1437 NormalRegs, NormalUnits, RegBank);
1439 // Postorder register normalization.
1441 // Inherit register units newly adopted by subregisters.
1442 if (Reg->inheritRegUnits(RegBank))
1443 computeUberWeights(UberSets, RegBank);
1445 // Check if this register is too skinny for its UberRegSet.
1446 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1448 unsigned RegWeight = Reg->getWeight(RegBank);
1449 if (UberSet->Weight > RegWeight) {
1450 // A register unit's weight can be adjusted only if it is the singular unit
1451 // for this register, has not been used to normalize a subregister's set,
1452 // and has not already been used to singularly determine this UberRegSet.
1453 unsigned AdjustUnit = *Reg->getRegUnits().begin();
1454 if (Reg->getRegUnits().count() != 1
1455 || hasRegUnit(NormalUnits, AdjustUnit)
1456 || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1457 // We don't have an adjustable unit, so adopt a new one.
1458 AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1459 Reg->adoptRegUnit(AdjustUnit);
1460 // Adopting a unit does not immediately require recomputing set weights.
1463 // Adjust the existing single unit.
1464 RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1465 // The unit may be shared among sets and registers within this set.
1466 computeUberWeights(UberSets, RegBank);
1471 // Mark these units normalized so superregisters can't change their weights.
1472 NormalUnits |= Reg->getRegUnits();
1477 // Compute a weight for each register unit created during getSubRegs.
1479 // The goal is that two registers in the same class will have the same weight,
1480 // where each register's weight is defined as sum of its units' weights.
1481 void CodeGenRegBank::computeRegUnitWeights() {
1482 std::vector<UberRegSet> UberSets;
1483 std::vector<UberRegSet*> RegSets(Registers.size());
1484 computeUberSets(UberSets, RegSets, *this);
1485 // UberSets and RegSets are now immutable.
1487 computeUberWeights(UberSets, *this);
1489 // Iterate over each Register, normalizing the unit weights until reaching
1491 unsigned NumIters = 0;
1492 for (bool Changed = true; Changed; ++NumIters) {
1493 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1495 for (auto &Reg : Registers) {
1496 CodeGenRegister::RegUnitList NormalUnits;
1497 SparseBitVector<> NormalRegs;
1498 Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
1499 NormalUnits, *this);
1504 // Find a set in UniqueSets with the same elements as Set.
1505 // Return an iterator into UniqueSets.
1506 static std::vector<RegUnitSet>::const_iterator
1507 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1508 const RegUnitSet &Set) {
1509 std::vector<RegUnitSet>::const_iterator
1510 I = UniqueSets.begin(), E = UniqueSets.end();
1512 if (I->Units == Set.Units)
1518 // Return true if the RUSubSet is a subset of RUSuperSet.
1519 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1520 const std::vector<unsigned> &RUSuperSet) {
1521 return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1522 RUSubSet.begin(), RUSubSet.end());
1525 /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1526 /// but with one or two registers removed. We occasionally have registers like
1527 /// APSR and PC thrown in with the general registers. We also see many
1528 /// special-purpose register subsets, such as tail-call and Thumb
1529 /// encodings. Generating all possible overlapping sets is combinatorial and
1530 /// overkill for modeling pressure. Ideally we could fix this statically in
1531 /// tablegen by (1) having the target define register classes that only include
1532 /// the allocatable registers and marking other classes as non-allocatable and
1533 /// (2) having a way to mark special purpose classes as "don't-care" classes for
1534 /// the purpose of pressure. However, we make an attempt to handle targets that
1535 /// are not nicely defined by merging nearly identical register unit sets
1536 /// statically. This generates smaller tables. Then, dynamically, we adjust the
1537 /// set limit by filtering the reserved registers.
1539 /// Merge sets only if the units have the same weight. For example, on ARM,
1540 /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1541 /// should not expand the S set to include D regs.
1542 void CodeGenRegBank::pruneUnitSets() {
1543 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1545 // Form an equivalence class of UnitSets with no significant difference.
1546 std::vector<unsigned> SuperSetIDs;
1547 for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1548 SubIdx != EndIdx; ++SubIdx) {
1549 const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1550 unsigned SuperIdx = 0;
1551 for (; SuperIdx != EndIdx; ++SuperIdx) {
1552 if (SuperIdx == SubIdx)
1555 unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1556 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1557 if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1558 && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1559 && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1560 && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1561 DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1566 if (SuperIdx == EndIdx)
1567 SuperSetIDs.push_back(SubIdx);
1569 // Populate PrunedUnitSets with each equivalence class's superset.
1570 std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1571 for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1572 unsigned SuperIdx = SuperSetIDs[i];
1573 PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1574 PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1576 RegUnitSets.swap(PrunedUnitSets);
1579 // Create a RegUnitSet for each RegClass that contains all units in the class
1580 // including adopted units that are necessary to model register pressure. Then
1581 // iteratively compute RegUnitSets such that the union of any two overlapping
1582 // RegUnitSets is repreresented.
1584 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1585 // RegUnitSet that is a superset of that RegUnitClass.
1586 void CodeGenRegBank::computeRegUnitSets() {
1587 assert(RegUnitSets.empty() && "dirty RegUnitSets");
1589 // Compute a unique RegUnitSet for each RegClass.
1590 auto &RegClasses = getRegClasses();
1591 for (auto &RC : RegClasses) {
1592 if (!RC.Allocatable)
1595 // Speculatively grow the RegUnitSets to hold the new set.
1596 RegUnitSets.resize(RegUnitSets.size() + 1);
1597 RegUnitSets.back().Name = RC.getName();
1599 // Compute a sorted list of units in this class.
1600 RC.buildRegUnitSet(RegUnitSets.back().Units);
1602 // Find an existing RegUnitSet.
1603 std::vector<RegUnitSet>::const_iterator SetI =
1604 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1605 if (SetI != std::prev(RegUnitSets.end()))
1606 RegUnitSets.pop_back();
1609 DEBUG(dbgs() << "\nBefore pruning:\n";
1610 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1611 USIdx < USEnd; ++USIdx) {
1612 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1614 for (auto &U : RegUnitSets[USIdx].Units)
1615 dbgs() << " " << RegUnits[U].Roots[0]->getName();
1619 // Iteratively prune unit sets.
1622 DEBUG(dbgs() << "\nBefore union:\n";
1623 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1624 USIdx < USEnd; ++USIdx) {
1625 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1627 for (auto &U : RegUnitSets[USIdx].Units)
1628 dbgs() << " " << RegUnits[U].Roots[0]->getName();
1631 dbgs() << "\nUnion sets:\n");
1633 // Iterate over all unit sets, including new ones added by this loop.
1634 unsigned NumRegUnitSubSets = RegUnitSets.size();
1635 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1636 // In theory, this is combinatorial. In practice, it needs to be bounded
1637 // by a small number of sets for regpressure to be efficient.
1638 // If the assert is hit, we need to implement pruning.
1639 assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1641 // Compare new sets with all original classes.
1642 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1643 SearchIdx != EndIdx; ++SearchIdx) {
1644 std::set<unsigned> Intersection;
1645 std::set_intersection(RegUnitSets[Idx].Units.begin(),
1646 RegUnitSets[Idx].Units.end(),
1647 RegUnitSets[SearchIdx].Units.begin(),
1648 RegUnitSets[SearchIdx].Units.end(),
1649 std::inserter(Intersection, Intersection.begin()));
1650 if (Intersection.empty())
1653 // Speculatively grow the RegUnitSets to hold the new set.
1654 RegUnitSets.resize(RegUnitSets.size() + 1);
1655 RegUnitSets.back().Name =
1656 RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1658 std::set_union(RegUnitSets[Idx].Units.begin(),
1659 RegUnitSets[Idx].Units.end(),
1660 RegUnitSets[SearchIdx].Units.begin(),
1661 RegUnitSets[SearchIdx].Units.end(),
1662 std::inserter(RegUnitSets.back().Units,
1663 RegUnitSets.back().Units.begin()));
1665 // Find an existing RegUnitSet, or add the union to the unique sets.
1666 std::vector<RegUnitSet>::const_iterator SetI =
1667 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1668 if (SetI != std::prev(RegUnitSets.end()))
1669 RegUnitSets.pop_back();
1671 DEBUG(dbgs() << "UnitSet " << RegUnitSets.size()-1
1672 << " " << RegUnitSets.back().Name << ":";
1673 for (auto &U : RegUnitSets.back().Units)
1674 dbgs() << " " << RegUnits[U].Roots[0]->getName();
1680 // Iteratively prune unit sets after inferring supersets.
1683 DEBUG(dbgs() << "\n";
1684 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1685 USIdx < USEnd; ++USIdx) {
1686 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1688 for (auto &U : RegUnitSets[USIdx].Units)
1689 dbgs() << " " << RegUnits[U].Roots[0]->getName();
1693 // For each register class, list the UnitSets that are supersets.
1694 RegClassUnitSets.resize(RegClasses.size());
1696 for (auto &RC : RegClasses) {
1698 if (!RC.Allocatable)
1701 // Recompute the sorted list of units in this class.
1702 std::vector<unsigned> RCRegUnits;
1703 RC.buildRegUnitSet(RCRegUnits);
1705 // Don't increase pressure for unallocatable regclasses.
1706 if (RCRegUnits.empty())
1709 DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";
1710 for (auto &U : RCRegUnits)
1711 dbgs() << RegUnits[U].getRoots()[0]->getName() << " ";
1712 dbgs() << "\n UnitSetIDs:");
1714 // Find all supersets.
1715 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1716 USIdx != USEnd; ++USIdx) {
1717 if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
1718 DEBUG(dbgs() << " " << USIdx);
1719 RegClassUnitSets[RCIdx].push_back(USIdx);
1722 DEBUG(dbgs() << "\n");
1723 assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1726 // For each register unit, ensure that we have the list of UnitSets that
1727 // contain the unit. Normally, this matches an existing list of UnitSets for a
1728 // register class. If not, we create a new entry in RegClassUnitSets as a
1729 // "fake" register class.
1730 for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
1731 UnitIdx < UnitEnd; ++UnitIdx) {
1732 std::vector<unsigned> RUSets;
1733 for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
1734 RegUnitSet &RUSet = RegUnitSets[i];
1735 if (std::find(RUSet.Units.begin(), RUSet.Units.end(), UnitIdx)
1736 == RUSet.Units.end())
1738 RUSets.push_back(i);
1740 unsigned RCUnitSetsIdx = 0;
1741 for (unsigned e = RegClassUnitSets.size();
1742 RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
1743 if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
1747 RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
1748 if (RCUnitSetsIdx == RegClassUnitSets.size()) {
1749 // Create a new list of UnitSets as a "fake" register class.
1750 RegClassUnitSets.resize(RCUnitSetsIdx + 1);
1751 RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
1756 void CodeGenRegBank::computeRegUnitLaneMasks() {
1757 for (auto &Register : Registers) {
1758 // Create an initial lane mask for all register units.
1759 const auto &RegUnits = Register.getRegUnits();
1760 CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(RegUnits.count(), 0);
1761 // Iterate through SubRegisters.
1762 typedef CodeGenRegister::SubRegMap SubRegMap;
1763 const SubRegMap &SubRegs = Register.getSubRegs();
1764 for (SubRegMap::const_iterator S = SubRegs.begin(),
1765 SE = SubRegs.end(); S != SE; ++S) {
1766 CodeGenRegister *SubReg = S->second;
1767 // Ignore non-leaf subregisters, their lane masks are fully covered by
1768 // the leaf subregisters anyway.
1769 if (SubReg->getSubRegs().size() != 0)
1771 CodeGenSubRegIndex *SubRegIndex = S->first;
1772 const CodeGenRegister *SubRegister = S->second;
1773 unsigned LaneMask = SubRegIndex->LaneMask;
1774 // Distribute LaneMask to Register Units touched.
1775 for (const auto &SUI : SubRegister->getRegUnits()) {
1778 for (unsigned RU : RegUnits) {
1780 RegUnitLaneMasks[u] |= LaneMask;
1789 Register.setRegUnitLaneMasks(RegUnitLaneMasks);
1793 void CodeGenRegBank::computeDerivedInfo() {
1794 computeComposites();
1795 computeSubRegLaneMasks();
1797 // Compute a weight for each register unit created during getSubRegs.
1798 // This may create adopted register units (with unit # >= NumNativeRegUnits).
1799 computeRegUnitWeights();
1801 // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1802 // supersets for the union of overlapping sets.
1803 computeRegUnitSets();
1805 computeRegUnitLaneMasks();
1807 // Get the weight of each set.
1808 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1809 RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
1811 // Find the order of each set.
1812 RegUnitSetOrder.reserve(RegUnitSets.size());
1813 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1814 RegUnitSetOrder.push_back(Idx);
1816 std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
1817 [this](unsigned ID1, unsigned ID2) {
1818 return getRegPressureSet(ID1).Units.size() <
1819 getRegPressureSet(ID2).Units.size();
1821 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1822 RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
1827 // Synthesize missing register class intersections.
1829 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1830 // returns a maximal register class for all X.
1832 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1833 assert(!RegClasses.empty());
1834 // Stash the iterator to the last element so that this loop doesn't visit
1835 // elements added by the getOrCreateSubClass call within it.
1836 for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
1837 I != std::next(E); ++I) {
1838 CodeGenRegisterClass *RC1 = RC;
1839 CodeGenRegisterClass *RC2 = &*I;
1843 // Compute the set intersection of RC1 and RC2.
1844 const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
1845 const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
1846 CodeGenRegister::Vec Intersection;
1847 std::set_intersection(
1848 Memb1.begin(), Memb1.end(), Memb2.begin(), Memb2.end(),
1849 std::inserter(Intersection, Intersection.begin()), deref<llvm::less>());
1851 // Skip disjoint class pairs.
1852 if (Intersection.empty())
1855 // If RC1 and RC2 have different spill sizes or alignments, use the
1856 // larger size for sub-classing. If they are equal, prefer RC1.
1857 if (RC2->SpillSize > RC1->SpillSize ||
1858 (RC2->SpillSize == RC1->SpillSize &&
1859 RC2->SpillAlignment > RC1->SpillAlignment))
1860 std::swap(RC1, RC2);
1862 getOrCreateSubClass(RC1, &Intersection,
1863 RC1->getName() + "_and_" + RC2->getName());
1868 // Synthesize missing sub-classes for getSubClassWithSubReg().
1870 // Make sure that the set of registers in RC with a given SubIdx sub-register
1871 // form a register class. Update RC->SubClassWithSubReg.
1873 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1874 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1875 typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
1876 deref<llvm::less>> SubReg2SetMap;
1878 // Compute the set of registers supporting each SubRegIndex.
1879 SubReg2SetMap SRSets;
1880 for (const auto R : RC->getMembers()) {
1881 const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
1882 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1883 E = SRM.end(); I != E; ++I)
1884 SRSets[I->first].push_back(R);
1887 for (auto I : SRSets)
1888 sortAndUniqueRegisters(I.second);
1890 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
1891 // numerical order to visit synthetic indices last.
1892 for (const auto &SubIdx : SubRegIndices) {
1893 SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
1894 // Unsupported SubRegIndex. Skip it.
1895 if (I == SRSets.end())
1897 // In most cases, all RC registers support the SubRegIndex.
1898 if (I->second.size() == RC->getMembers().size()) {
1899 RC->setSubClassWithSubReg(&SubIdx, RC);
1902 // This is a real subset. See if we have a matching class.
1903 CodeGenRegisterClass *SubRC =
1904 getOrCreateSubClass(RC, &I->second,
1905 RC->getName() + "_with_" + I->first->getName());
1906 RC->setSubClassWithSubReg(&SubIdx, SubRC);
1911 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1913 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1914 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1917 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1918 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
1919 SmallVector<std::pair<const CodeGenRegister*,
1920 const CodeGenRegister*>, 16> SSPairs;
1921 BitVector TopoSigs(getNumTopoSigs());
1923 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1924 for (auto &SubIdx : SubRegIndices) {
1925 // Skip indexes that aren't fully supported by RC's registers. This was
1926 // computed by inferSubClassWithSubReg() above which should have been
1928 if (RC->getSubClassWithSubReg(&SubIdx) != RC)
1931 // Build list of (Super, Sub) pairs for this SubIdx.
1934 for (const auto Super : RC->getMembers()) {
1935 const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
1936 assert(Sub && "Missing sub-register");
1937 SSPairs.push_back(std::make_pair(Super, Sub));
1938 TopoSigs.set(Sub->getTopoSig());
1941 // Iterate over sub-register class candidates. Ignore classes created by
1942 // this loop. They will never be useful.
1943 // Store an iterator to the last element (not end) so that this loop doesn't
1944 // visit newly inserted elements.
1945 assert(!RegClasses.empty());
1946 for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
1947 I != std::next(E); ++I) {
1948 CodeGenRegisterClass &SubRC = *I;
1949 // Topological shortcut: SubRC members have the wrong shape.
1950 if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
1952 // Compute the subset of RC that maps into SubRC.
1953 CodeGenRegister::Vec SubSetVec;
1954 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1955 if (SubRC.contains(SSPairs[i].second))
1956 SubSetVec.push_back(SSPairs[i].first);
1958 if (SubSetVec.empty())
1961 // RC injects completely into SubRC.
1962 sortAndUniqueRegisters(SubSetVec);
1963 if (SubSetVec.size() == SSPairs.size()) {
1964 SubRC.addSuperRegClass(&SubIdx, RC);
1968 // Only a subset of RC maps into SubRC. Make sure it is represented by a
1970 getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
1971 SubIdx.getName() + "_in_" +
1979 // Infer missing register classes.
1981 void CodeGenRegBank::computeInferredRegisterClasses() {
1982 assert(!RegClasses.empty());
1983 // When this function is called, the register classes have not been sorted
1984 // and assigned EnumValues yet. That means getSubClasses(),
1985 // getSuperClasses(), and hasSubClass() functions are defunct.
1987 // Use one-before-the-end so it doesn't move forward when new elements are
1989 auto FirstNewRC = std::prev(RegClasses.end());
1991 // Visit all register classes, including the ones being added by the loop.
1992 // Watch out for iterator invalidation here.
1993 for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
1994 CodeGenRegisterClass *RC = &*I;
1996 // Synthesize answers for getSubClassWithSubReg().
1997 inferSubClassWithSubReg(RC);
1999 // Synthesize answers for getCommonSubClass().
2000 inferCommonSubClass(RC);
2002 // Synthesize answers for getMatchingSuperRegClass().
2003 inferMatchingSuperRegClass(RC);
2005 // New register classes are created while this loop is running, and we need
2006 // to visit all of them. I particular, inferMatchingSuperRegClass needs
2007 // to match old super-register classes with sub-register classes created
2008 // after inferMatchingSuperRegClass was called. At this point,
2009 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2010 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
2011 if (I == FirstNewRC) {
2012 auto NextNewRC = std::prev(RegClasses.end());
2013 for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
2015 inferMatchingSuperRegClass(&*I2, E2);
2016 FirstNewRC = NextNewRC;
2021 /// getRegisterClassForRegister - Find the register class that contains the
2022 /// specified physical register. If the register is not in a register class,
2023 /// return null. If the register is in multiple classes, and the classes have a
2024 /// superset-subset relationship and the same set of types, return the
2025 /// superclass. Otherwise return null.
2026 const CodeGenRegisterClass*
2027 CodeGenRegBank::getRegClassForRegister(Record *R) {
2028 const CodeGenRegister *Reg = getReg(R);
2029 const CodeGenRegisterClass *FoundRC = nullptr;
2030 for (const auto &RC : getRegClasses()) {
2031 if (!RC.contains(Reg))
2034 // If this is the first class that contains the register,
2035 // make a note of it and go on to the next class.
2041 // If a register's classes have different types, return null.
2042 if (RC.getValueTypes() != FoundRC->getValueTypes())
2045 // Check to see if the previously found class that contains
2046 // the register is a subclass of the current class. If so,
2047 // prefer the superclass.
2048 if (RC.hasSubClass(FoundRC)) {
2053 // Check to see if the previously found class that contains
2054 // the register is a superclass of the current class. If so,
2055 // prefer the superclass.
2056 if (FoundRC->hasSubClass(&RC))
2059 // Multiple classes, and neither is a superclass of the other.
2066 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
2067 SetVector<const CodeGenRegister*> Set;
2069 // First add Regs with all sub-registers.
2070 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2071 CodeGenRegister *Reg = getReg(Regs[i]);
2072 if (Set.insert(Reg))
2073 // Reg is new, add all sub-registers.
2074 // The pre-ordering is not important here.
2075 Reg->addSubRegsPreOrder(Set, *this);
2078 // Second, find all super-registers that are completely covered by the set.
2079 for (unsigned i = 0; i != Set.size(); ++i) {
2080 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
2081 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
2082 const CodeGenRegister *Super = SR[j];
2083 if (!Super->CoveredBySubRegs || Set.count(Super))
2085 // This new super-register is covered by its sub-registers.
2086 bool AllSubsInSet = true;
2087 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2088 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2089 E = SRM.end(); I != E; ++I)
2090 if (!Set.count(I->second)) {
2091 AllSubsInSet = false;
2094 // All sub-registers in Set, add Super as well.
2095 // We will visit Super later to recheck its super-registers.
2101 // Convert to BitVector.
2102 BitVector BV(Registers.size() + 1);
2103 for (unsigned i = 0, e = Set.size(); i != e; ++i)
2104 BV.set(Set[i]->EnumValue);