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/TableGen/Error.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
31 : TheDef(R), EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
33 if (R->getValue("Namespace"))
34 Namespace = R->getValueAsString("Namespace");
35 Size = R->getValueAsInt("Size");
36 Offset = R->getValueAsInt("Offset");
39 CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
41 : TheDef(0), Name(N), Namespace(Nspace), Size(-1), Offset(-1),
42 EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
45 std::string CodeGenSubRegIndex::getQualifiedName() const {
46 std::string N = getNamespace();
53 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
57 std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
59 if (Comps.size() != 2)
60 PrintFatalError(TheDef->getLoc(),
61 "ComposedOf must have exactly two entries");
62 CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
63 CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
64 CodeGenSubRegIndex *X = A->addComposite(B, this);
66 PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
69 std::vector<Record*> Parts =
70 TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
73 PrintFatalError(TheDef->getLoc(),
74 "CoveredBySubRegs must have two or more entries");
75 SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
76 for (unsigned i = 0, e = Parts.size(); i != e; ++i)
77 IdxParts.push_back(RegBank.getSubRegIdx(Parts[i]));
78 RegBank.addConcatSubRegIndex(IdxParts, this);
82 unsigned CodeGenSubRegIndex::computeLaneMask() {
87 // Recursion guard, shouldn't be required.
90 // The lane mask is simply the union of all sub-indices.
92 for (CompMap::iterator I = Composed.begin(), E = Composed.end(); I != E; ++I)
93 M |= I->second->computeLaneMask();
94 assert(M && "Missing lane mask, sub-register cycle?");
99 //===----------------------------------------------------------------------===//
101 //===----------------------------------------------------------------------===//
103 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
106 CostPerUse(R->getValueAsInt("CostPerUse")),
107 CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
108 NumNativeRegUnits(0),
109 SubRegsComplete(false),
110 SuperRegsComplete(false),
114 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
115 std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
116 std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
118 if (SRIs.size() != SRs.size())
119 PrintFatalError(TheDef->getLoc(),
120 "SubRegs and SubRegIndices must have the same size");
122 for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
123 ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
124 ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
127 // Also compute leading super-registers. Each register has a list of
128 // covered-by-subregs super-registers where it appears as the first explicit
131 // This is used by computeSecondarySubRegs() to find candidates.
132 if (CoveredBySubRegs && !ExplicitSubRegs.empty())
133 ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
135 // Add ad hoc alias links. This is a symmetric relationship between two
136 // registers, so build a symmetric graph by adding links in both ends.
137 std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
138 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
139 CodeGenRegister *Reg = RegBank.getReg(Aliases[i]);
140 ExplicitAliases.push_back(Reg);
141 Reg->ExplicitAliases.push_back(this);
145 const std::string &CodeGenRegister::getName() const {
146 return TheDef->getName();
150 // Iterate over all register units in a set of registers.
151 class RegUnitIterator {
152 CodeGenRegister::Set::const_iterator RegI, RegE;
153 CodeGenRegister::RegUnitList::const_iterator UnitI, UnitE;
156 RegUnitIterator(const CodeGenRegister::Set &Regs):
157 RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
160 UnitI = (*RegI)->getRegUnits().begin();
161 UnitE = (*RegI)->getRegUnits().end();
166 bool isValid() const { return UnitI != UnitE; }
168 unsigned operator* () const { assert(isValid()); return *UnitI; }
170 const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
172 /// Preincrement. Move to the next unit.
174 assert(isValid() && "Cannot advance beyond the last operand");
181 while (UnitI == UnitE) {
184 UnitI = (*RegI)->getRegUnits().begin();
185 UnitE = (*RegI)->getRegUnits().end();
191 // Merge two RegUnitLists maintaining the order and removing duplicates.
192 // Overwrites MergedRU in the process.
193 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
194 const CodeGenRegister::RegUnitList &RRU) {
195 CodeGenRegister::RegUnitList LRU = MergedRU;
197 std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(),
198 std::back_inserter(MergedRU));
201 // Return true of this unit appears in RegUnits.
202 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
203 return std::count(RegUnits.begin(), RegUnits.end(), Unit);
206 // Inherit register units from subregisters.
207 // Return true if the RegUnits changed.
208 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
209 unsigned OldNumUnits = RegUnits.size();
210 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
212 CodeGenRegister *SR = I->second;
213 // Merge the subregister's units into this register's RegUnits.
214 mergeRegUnits(RegUnits, SR->RegUnits);
216 return OldNumUnits != RegUnits.size();
219 const CodeGenRegister::SubRegMap &
220 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
221 // Only compute this map once.
224 SubRegsComplete = true;
226 // First insert the explicit subregs and make sure they are fully indexed.
227 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
228 CodeGenRegister *SR = ExplicitSubRegs[i];
229 CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
230 if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
231 PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
232 " appears twice in Register " + getName());
233 // Map explicit sub-registers first, so the names take precedence.
234 // The inherited sub-registers are mapped below.
235 SubReg2Idx.insert(std::make_pair(SR, Idx));
238 // Keep track of inherited subregs and how they can be reached.
239 SmallPtrSet<CodeGenRegister*, 8> Orphans;
241 // Clone inherited subregs and place duplicate entries in Orphans.
242 // Here the order is important - earlier subregs take precedence.
243 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
244 CodeGenRegister *SR = ExplicitSubRegs[i];
245 const SubRegMap &Map = SR->computeSubRegs(RegBank);
247 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
249 if (!SubRegs.insert(*SI).second)
250 Orphans.insert(SI->second);
254 // Expand any composed subreg indices.
255 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
256 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
257 // expanded subreg indices recursively.
258 SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
259 for (unsigned i = 0; i != Indices.size(); ++i) {
260 CodeGenSubRegIndex *Idx = Indices[i];
261 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
262 CodeGenRegister *SR = SubRegs[Idx];
263 const SubRegMap &Map = SR->computeSubRegs(RegBank);
265 // Look at the possible compositions of Idx.
266 // They may not all be supported by SR.
267 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
268 E = Comps.end(); I != E; ++I) {
269 SubRegMap::const_iterator SRI = Map.find(I->first);
270 if (SRI == Map.end())
271 continue; // Idx + I->first doesn't exist in SR.
272 // Add I->second as a name for the subreg SRI->second, assuming it is
273 // orphaned, and the name isn't already used for something else.
274 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
276 // We found a new name for the orphaned sub-register.
277 SubRegs.insert(std::make_pair(I->second, SRI->second));
278 Indices.push_back(I->second);
282 // Now Orphans contains the inherited subregisters without a direct index.
283 // Create inferred indexes for all missing entries.
284 // Work backwards in the Indices vector in order to compose subregs bottom-up.
285 // Consider this subreg sequence:
287 // qsub_1 -> dsub_0 -> ssub_0
289 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
290 // can be reached in two different ways:
295 // We pick the latter composition because another register may have [dsub_0,
296 // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The
297 // dsub_2 -> ssub_0 composition can be shared.
298 while (!Indices.empty() && !Orphans.empty()) {
299 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
300 CodeGenRegister *SR = SubRegs[Idx];
301 const SubRegMap &Map = SR->computeSubRegs(RegBank);
302 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
304 if (Orphans.erase(SI->second))
305 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
308 // Compute the inverse SubReg -> Idx map.
309 for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end();
311 if (SI->second == this) {
314 Loc = TheDef->getLoc();
315 PrintFatalError(Loc, "Register " + getName() +
316 " has itself as a sub-register");
319 // Compute AllSuperRegsCovered.
320 if (!CoveredBySubRegs)
321 SI->first->AllSuperRegsCovered = false;
323 // Ensure that every sub-register has a unique name.
324 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
325 SubReg2Idx.insert(std::make_pair(SI->second, SI->first)).first;
326 if (Ins->second == SI->first)
328 // Trouble: Two different names for SI->second.
331 Loc = TheDef->getLoc();
332 PrintFatalError(Loc, "Sub-register can't have two names: " +
333 SI->second->getName() + " available as " +
334 SI->first->getName() + " and " + Ins->second->getName());
337 // Derive possible names for sub-register concatenations from any explicit
338 // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
339 // that getConcatSubRegIndex() won't invent any concatenated indices that the
340 // user already specified.
341 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
342 CodeGenRegister *SR = ExplicitSubRegs[i];
343 if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1)
346 // SR is composed of multiple sub-regs. Find their names in this register.
347 SmallVector<CodeGenSubRegIndex*, 8> Parts;
348 for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j)
349 Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
351 // Offer this as an existing spelling for the concatenation of Parts.
352 RegBank.addConcatSubRegIndex(Parts, ExplicitSubRegIndices[i]);
355 // Initialize RegUnitList. Because getSubRegs is called recursively, this
356 // processes the register hierarchy in postorder.
358 // Inherit all sub-register units. It is good enough to look at the explicit
359 // sub-registers, the other registers won't contribute any more units.
360 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
361 CodeGenRegister *SR = ExplicitSubRegs[i];
362 // Explicit sub-registers are usually disjoint, so this is a good way of
363 // computing the union. We may pick up a few duplicates that will be
365 unsigned N = RegUnits.size();
366 RegUnits.append(SR->RegUnits.begin(), SR->RegUnits.end());
367 std::inplace_merge(RegUnits.begin(), RegUnits.begin() + N, RegUnits.end());
369 RegUnits.erase(std::unique(RegUnits.begin(), RegUnits.end()), RegUnits.end());
371 // Absent any ad hoc aliasing, we create one register unit per leaf register.
372 // These units correspond to the maximal cliques in the register overlap
373 // graph which is optimal.
375 // When there is ad hoc aliasing, we simply create one unit per edge in the
376 // undirected ad hoc aliasing graph. Technically, we could do better by
377 // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
378 // are extremely rare anyway (I've never seen one), so we don't bother with
379 // the added complexity.
380 for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
381 CodeGenRegister *AR = ExplicitAliases[i];
382 // Only visit each edge once.
383 if (AR->SubRegsComplete)
385 // Create a RegUnit representing this alias edge, and add it to both
387 unsigned Unit = RegBank.newRegUnit(this, AR);
388 RegUnits.push_back(Unit);
389 AR->RegUnits.push_back(Unit);
392 // Finally, create units for leaf registers without ad hoc aliases. Note that
393 // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
394 // necessary. This means the aliasing leaf registers can share a single unit.
395 if (RegUnits.empty())
396 RegUnits.push_back(RegBank.newRegUnit(this));
398 // We have now computed the native register units. More may be adopted later
399 // for balancing purposes.
400 NumNativeRegUnits = RegUnits.size();
405 // In a register that is covered by its sub-registers, try to find redundant
406 // sub-registers. For example:
412 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
413 // the register definition.
415 // The explicitly specified registers form a tree. This function discovers
416 // sub-register relationships that would force a DAG.
418 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
419 // Collect new sub-registers first, add them later.
420 SmallVector<SubRegMap::value_type, 8> NewSubRegs;
422 // Look at the leading super-registers of each sub-register. Those are the
423 // candidates for new sub-registers, assuming they are fully contained in
425 for (SubRegMap::iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I){
426 const CodeGenRegister *SubReg = I->second;
427 const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
428 for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
429 CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
430 // Already got this sub-register?
431 if (Cand == this || getSubRegIndex(Cand))
433 // Check if each component of Cand is already a sub-register.
434 // We know that the first component is I->second, and is present with the
436 SmallVector<CodeGenSubRegIndex*, 8> Parts(1, I->first);
437 assert(!Cand->ExplicitSubRegs.empty() &&
438 "Super-register has no sub-registers");
439 for (unsigned j = 1, e = Cand->ExplicitSubRegs.size(); j != e; ++j) {
440 if (CodeGenSubRegIndex *Idx = getSubRegIndex(Cand->ExplicitSubRegs[j]))
441 Parts.push_back(Idx);
443 // Sub-register doesn't exist.
448 // If some Cand sub-register is not part of this register, or if Cand only
449 // has one sub-register, there is nothing to do.
450 if (Parts.size() <= 1)
453 // Each part of Cand is a sub-register of this. Make the full Cand also
454 // a sub-register with a concatenated sub-register index.
455 CodeGenSubRegIndex *Concat= RegBank.getConcatSubRegIndex(Parts);
456 NewSubRegs.push_back(std::make_pair(Concat, Cand));
460 // Now add all the new sub-registers.
461 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
462 // Don't add Cand if another sub-register is already using the index.
463 if (!SubRegs.insert(NewSubRegs[i]).second)
466 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
467 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
468 SubReg2Idx.insert(std::make_pair(NewSubReg, NewIdx));
471 // Create sub-register index composition maps for the synthesized indices.
472 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
473 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
474 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
475 for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
476 SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
477 CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
479 PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
480 SI->second->getName() + " in " + getName());
481 NewIdx->addComposite(SI->first, SubIdx);
486 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
487 // Only visit each register once.
488 if (SuperRegsComplete)
490 SuperRegsComplete = true;
492 // Make sure all sub-registers have been visited first, so the super-reg
493 // lists will be topologically ordered.
494 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
496 I->second->computeSuperRegs(RegBank);
498 // Now add this as a super-register on all sub-registers.
499 // Also compute the TopoSigId in post-order.
501 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
503 // Topological signature computed from SubIdx, TopoId(SubReg).
504 // Loops and idempotent indices have TopoSig = ~0u.
505 Id.push_back(I->first->EnumValue);
506 Id.push_back(I->second->TopoSig);
508 // Don't add duplicate entries.
509 if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
511 I->second->SuperRegs.push_back(this);
513 TopoSig = RegBank.getTopoSig(Id);
517 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
518 CodeGenRegBank &RegBank) const {
519 assert(SubRegsComplete && "Must precompute sub-registers");
520 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
521 CodeGenRegister *SR = ExplicitSubRegs[i];
523 SR->addSubRegsPreOrder(OSet, RegBank);
525 // Add any secondary sub-registers that weren't part of the explicit tree.
526 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
528 OSet.insert(I->second);
531 // Get the sum of this register's unit weights.
532 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
534 for (RegUnitList::const_iterator I = RegUnits.begin(), E = RegUnits.end();
536 Weight += RegBank.getRegUnit(*I).Weight;
541 //===----------------------------------------------------------------------===//
543 //===----------------------------------------------------------------------===//
545 // A RegisterTuples def is used to generate pseudo-registers from lists of
546 // sub-registers. We provide a SetTheory expander class that returns the new
549 struct TupleExpander : SetTheory::Expander {
550 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
551 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
552 unsigned Dim = Indices.size();
553 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
554 if (Dim != SubRegs->getSize())
555 PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
557 PrintFatalError(Def->getLoc(),
558 "Tuples must have at least 2 sub-registers");
560 // Evaluate the sub-register lists to be zipped.
561 unsigned Length = ~0u;
562 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
563 for (unsigned i = 0; i != Dim; ++i) {
564 ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
565 Length = std::min(Length, unsigned(Lists[i].size()));
571 // Precompute some types.
572 Record *RegisterCl = Def->getRecords().getClass("Register");
573 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
574 StringInit *BlankName = StringInit::get("");
577 for (unsigned n = 0; n != Length; ++n) {
579 Record *Proto = Lists[0][n];
580 std::vector<Init*> Tuple;
581 unsigned CostPerUse = 0;
582 for (unsigned i = 0; i != Dim; ++i) {
583 Record *Reg = Lists[i][n];
585 Name += Reg->getName();
586 Tuple.push_back(DefInit::get(Reg));
587 CostPerUse = std::max(CostPerUse,
588 unsigned(Reg->getValueAsInt("CostPerUse")));
591 // Create a new Record representing the synthesized register. This record
592 // is only for consumption by CodeGenRegister, it is not added to the
594 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
597 // Copy Proto super-classes.
598 ArrayRef<Record *> Supers = Proto->getSuperClasses();
599 ArrayRef<SMRange> Ranges = Proto->getSuperClassRanges();
600 for (unsigned i = 0, e = Supers.size(); i != e; ++i)
601 NewReg->addSuperClass(Supers[i], Ranges[i]);
603 // Copy Proto fields.
604 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
605 RecordVal RV = Proto->getValues()[i];
607 // Skip existing fields, like NAME.
608 if (NewReg->getValue(RV.getNameInit()))
611 StringRef Field = RV.getName();
613 // Replace the sub-register list with Tuple.
614 if (Field == "SubRegs")
615 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
617 // Provide a blank AsmName. MC hacks are required anyway.
618 if (Field == "AsmName")
619 RV.setValue(BlankName);
621 // CostPerUse is aggregated from all Tuple members.
622 if (Field == "CostPerUse")
623 RV.setValue(IntInit::get(CostPerUse));
625 // Composite registers are always covered by sub-registers.
626 if (Field == "CoveredBySubRegs")
627 RV.setValue(BitInit::get(true));
629 // Copy fields from the RegisterTuples def.
630 if (Field == "SubRegIndices" ||
631 Field == "CompositeIndices") {
632 NewReg->addValue(*Def->getValue(Field));
636 // Some fields get their default uninitialized value.
637 if (Field == "DwarfNumbers" ||
638 Field == "DwarfAlias" ||
639 Field == "Aliases") {
640 if (const RecordVal *DefRV = RegisterCl->getValue(Field))
641 NewReg->addValue(*DefRV);
645 // Everything else is copied from Proto.
646 NewReg->addValue(RV);
653 //===----------------------------------------------------------------------===//
654 // CodeGenRegisterClass
655 //===----------------------------------------------------------------------===//
657 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
660 TopoSigs(RegBank.getNumTopoSigs()),
662 // Rename anonymous register classes.
663 if (R->getName().size() > 9 && R->getName()[9] == '.') {
664 static unsigned AnonCounter = 0;
665 R->setName("AnonRegClass_" + utostr(AnonCounter));
666 // MSVC2012 ICEs if AnonCounter++ is directly passed to utostr.
670 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
671 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
672 Record *Type = TypeList[i];
673 if (!Type->isSubClassOf("ValueType"))
674 PrintFatalError("RegTypes list member '" + Type->getName() +
675 "' does not derive from the ValueType class!");
676 VTs.push_back(getValueType(Type));
678 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
680 // Allocation order 0 is the full set. AltOrders provides others.
681 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
682 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
683 Orders.resize(1 + AltOrders->size());
685 // Default allocation order always contains all registers.
686 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
687 Orders[0].push_back((*Elements)[i]);
688 const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
690 TopoSigs.set(Reg->getTopoSig());
693 // Alternative allocation orders may be subsets.
694 SetTheory::RecSet Order;
695 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
696 RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
697 Orders[1 + i].append(Order.begin(), Order.end());
698 // Verify that all altorder members are regclass members.
699 while (!Order.empty()) {
700 CodeGenRegister *Reg = RegBank.getReg(Order.back());
703 PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
704 " is not a class member");
708 // Allow targets to override the size in bits of the RegisterClass.
709 unsigned Size = R->getValueAsInt("Size");
711 Namespace = R->getValueAsString("Namespace");
712 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
713 SpillAlignment = R->getValueAsInt("Alignment");
714 CopyCost = R->getValueAsInt("CopyCost");
715 Allocatable = R->getValueAsBit("isAllocatable");
716 AltOrderSelect = R->getValueAsString("AltOrderSelect");
719 // Create an inferred register class that was missing from the .td files.
720 // Most properties will be inherited from the closest super-class after the
721 // class structure has been computed.
722 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
723 StringRef Name, Key Props)
724 : Members(*Props.Members),
727 TopoSigs(RegBank.getNumTopoSigs()),
729 SpillSize(Props.SpillSize),
730 SpillAlignment(Props.SpillAlignment),
733 for (CodeGenRegister::Set::iterator I = Members.begin(), E = Members.end();
735 TopoSigs.set((*I)->getTopoSig());
738 // Compute inherited propertied for a synthesized register class.
739 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
740 assert(!getDef() && "Only synthesized classes can inherit properties");
741 assert(!SuperClasses.empty() && "Synthesized class without super class");
743 // The last super-class is the smallest one.
744 CodeGenRegisterClass &Super = *SuperClasses.back();
746 // Most properties are copied directly.
747 // Exceptions are members, size, and alignment
748 Namespace = Super.Namespace;
750 CopyCost = Super.CopyCost;
751 Allocatable = Super.Allocatable;
752 AltOrderSelect = Super.AltOrderSelect;
754 // Copy all allocation orders, filter out foreign registers from the larger
756 Orders.resize(Super.Orders.size());
757 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
758 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
759 if (contains(RegBank.getReg(Super.Orders[i][j])))
760 Orders[i].push_back(Super.Orders[i][j]);
763 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
764 return Members.count(Reg);
768 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
769 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
770 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
771 E = K.Members->end(); I != E; ++I)
772 OS << ", " << (*I)->getName();
777 // This is a simple lexicographical order that can be used to search for sets.
778 // It is not the same as the topological order provided by TopoOrderRC.
779 bool CodeGenRegisterClass::Key::
780 operator<(const CodeGenRegisterClass::Key &B) const {
781 assert(Members && B.Members);
782 if (*Members != *B.Members)
783 return *Members < *B.Members;
784 if (SpillSize != B.SpillSize)
785 return SpillSize < B.SpillSize;
786 return SpillAlignment < B.SpillAlignment;
789 // Returns true if RC is a strict subclass.
790 // RC is a sub-class of this class if it is a valid replacement for any
791 // instruction operand where a register of this classis required. It must
792 // satisfy these conditions:
794 // 1. All RC registers are also in this.
795 // 2. The RC spill size must not be smaller than our spill size.
796 // 3. RC spill alignment must be compatible with ours.
798 static bool testSubClass(const CodeGenRegisterClass *A,
799 const CodeGenRegisterClass *B) {
800 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
801 A->SpillSize <= B->SpillSize &&
802 std::includes(A->getMembers().begin(), A->getMembers().end(),
803 B->getMembers().begin(), B->getMembers().end(),
804 CodeGenRegister::Less());
807 /// Sorting predicate for register classes. This provides a topological
808 /// ordering that arranges all register classes before their sub-classes.
810 /// Register classes with the same registers, spill size, and alignment form a
811 /// clique. They will be ordered alphabetically.
813 static int TopoOrderRC(const void *PA, const void *PB) {
814 const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
815 const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
819 // Order by ascending spill size.
820 if (A->SpillSize < B->SpillSize)
822 if (A->SpillSize > B->SpillSize)
825 // Order by ascending spill alignment.
826 if (A->SpillAlignment < B->SpillAlignment)
828 if (A->SpillAlignment > B->SpillAlignment)
831 // Order by descending set size. Note that the classes' allocation order may
832 // not have been computed yet. The Members set is always vaild.
833 if (A->getMembers().size() > B->getMembers().size())
835 if (A->getMembers().size() < B->getMembers().size())
838 // Finally order by name as a tie breaker.
839 return StringRef(A->getName()).compare(B->getName());
842 std::string CodeGenRegisterClass::getQualifiedName() const {
843 if (Namespace.empty())
846 return Namespace + "::" + getName();
849 // Compute sub-classes of all register classes.
850 // Assume the classes are ordered topologically.
851 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
852 ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
854 // Visit backwards so sub-classes are seen first.
855 for (unsigned rci = RegClasses.size(); rci; --rci) {
856 CodeGenRegisterClass &RC = *RegClasses[rci - 1];
857 RC.SubClasses.resize(RegClasses.size());
858 RC.SubClasses.set(RC.EnumValue);
860 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
861 for (unsigned s = rci; s != RegClasses.size(); ++s) {
862 if (RC.SubClasses.test(s))
864 CodeGenRegisterClass *SubRC = RegClasses[s];
865 if (!testSubClass(&RC, SubRC))
867 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
869 RC.SubClasses |= SubRC->SubClasses;
872 // Sweep up missed clique members. They will be immediately preceding RC.
873 for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
874 RC.SubClasses.set(s - 1);
877 // Compute the SuperClasses lists from the SubClasses vectors.
878 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
879 const BitVector &SC = RegClasses[rci]->getSubClasses();
880 for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
881 if (unsigned(s) == rci)
883 RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
887 // With the class hierarchy in place, let synthesized register classes inherit
888 // properties from their closest super-class. The iteration order here can
889 // propagate properties down multiple levels.
890 for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
891 if (!RegClasses[rci]->getDef())
892 RegClasses[rci]->inheritProperties(RegBank);
896 CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
897 BitVector &Out) const {
898 DenseMap<CodeGenSubRegIndex*,
899 SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
900 FindI = SuperRegClasses.find(SubIdx);
901 if (FindI == SuperRegClasses.end())
903 for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
904 FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
905 Out.set((*I)->EnumValue);
908 // Populate a unique sorted list of units from a register set.
909 void CodeGenRegisterClass::buildRegUnitSet(
910 std::vector<unsigned> &RegUnits) const {
911 std::vector<unsigned> TmpUnits;
912 for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
913 TmpUnits.push_back(*UnitI);
914 std::sort(TmpUnits.begin(), TmpUnits.end());
915 std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
916 std::back_inserter(RegUnits));
919 //===----------------------------------------------------------------------===//
921 //===----------------------------------------------------------------------===//
923 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) {
924 // Configure register Sets to understand register classes and tuples.
925 Sets.addFieldExpander("RegisterClass", "MemberList");
926 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
927 Sets.addExpander("RegisterTuples", new TupleExpander());
929 // Read in the user-defined (named) sub-register indices.
930 // More indices will be synthesized later.
931 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
932 std::sort(SRIs.begin(), SRIs.end(), LessRecord());
933 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
934 getSubRegIdx(SRIs[i]);
935 // Build composite maps from ComposedOf fields.
936 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
937 SubRegIndices[i]->updateComponents(*this);
939 // Read in the register definitions.
940 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
941 std::sort(Regs.begin(), Regs.end(), LessRecordRegister());
942 Registers.reserve(Regs.size());
943 // Assign the enumeration values.
944 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
947 // Expand tuples and number the new registers.
948 std::vector<Record*> Tups =
949 Records.getAllDerivedDefinitions("RegisterTuples");
951 std::vector<Record*> TupRegsCopy;
952 for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
953 const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
954 TupRegsCopy.reserve(TupRegs->size());
955 TupRegsCopy.assign(TupRegs->begin(), TupRegs->end());
956 std::sort(TupRegsCopy.begin(), TupRegsCopy.end(), LessRecordRegister());
957 for (unsigned j = 0, je = TupRegsCopy.size(); j != je; ++j)
958 getReg((TupRegsCopy)[j]);
962 // Now all the registers are known. Build the object graph of explicit
963 // register-register references.
964 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
965 Registers[i]->buildObjectGraph(*this);
967 // Compute register name map.
968 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
969 RegistersByName.GetOrCreateValue(
970 Registers[i]->TheDef->getValueAsString("AsmName"),
973 // Precompute all sub-register maps.
974 // This will create Composite entries for all inferred sub-register indices.
975 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
976 Registers[i]->computeSubRegs(*this);
978 // Infer even more sub-registers by combining leading super-registers.
979 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
980 if (Registers[i]->CoveredBySubRegs)
981 Registers[i]->computeSecondarySubRegs(*this);
983 // After the sub-register graph is complete, compute the topologically
984 // ordered SuperRegs list.
985 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
986 Registers[i]->computeSuperRegs(*this);
988 // Native register units are associated with a leaf register. They've all been
990 NumNativeRegUnits = RegUnits.size();
992 // Read in register class definitions.
993 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
995 PrintFatalError(std::string("No 'RegisterClass' subclasses defined!"));
997 // Allocate user-defined register classes.
998 RegClasses.reserve(RCs.size());
999 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
1000 addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
1002 // Infer missing classes to create a full algebra.
1003 computeInferredRegisterClasses();
1005 // Order register classes topologically and assign enum values.
1006 array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
1007 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
1008 RegClasses[i]->EnumValue = i;
1009 CodeGenRegisterClass::computeSubClasses(*this);
1012 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1014 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1015 CodeGenSubRegIndex *Idx = new CodeGenSubRegIndex(Name, Namespace,
1016 SubRegIndices.size() + 1);
1017 SubRegIndices.push_back(Idx);
1021 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1022 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1025 Idx = new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
1026 SubRegIndices.push_back(Idx);
1030 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1031 CodeGenRegister *&Reg = Def2Reg[Def];
1034 Reg = new CodeGenRegister(Def, Registers.size() + 1);
1035 Registers.push_back(Reg);
1039 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1040 RegClasses.push_back(RC);
1042 if (Record *Def = RC->getDef())
1043 Def2RC.insert(std::make_pair(Def, RC));
1045 // Duplicate classes are rejected by insert().
1046 // That's OK, we only care about the properties handled by CGRC::Key.
1047 CodeGenRegisterClass::Key K(*RC);
1048 Key2RC.insert(std::make_pair(K, RC));
1051 // Create a synthetic sub-class if it is missing.
1052 CodeGenRegisterClass*
1053 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1054 const CodeGenRegister::Set *Members,
1056 // Synthetic sub-class has the same size and alignment as RC.
1057 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
1058 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1059 if (FoundI != Key2RC.end())
1060 return FoundI->second;
1062 // Sub-class doesn't exist, create a new one.
1063 CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(*this, Name, K);
1068 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1069 if (CodeGenRegisterClass *RC = Def2RC[Def])
1072 PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1076 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1077 CodeGenSubRegIndex *B) {
1078 // Look for an existing entry.
1079 CodeGenSubRegIndex *Comp = A->compose(B);
1083 // None exists, synthesize one.
1084 std::string Name = A->getName() + "_then_" + B->getName();
1085 Comp = createSubRegIndex(Name, A->getNamespace());
1086 A->addComposite(B, Comp);
1090 CodeGenSubRegIndex *CodeGenRegBank::
1091 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1092 assert(Parts.size() > 1 && "Need two parts to concatenate");
1094 // Look for an existing entry.
1095 CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1099 // None exists, synthesize one.
1100 std::string Name = Parts.front()->getName();
1101 // Determine whether all parts are contiguous.
1102 bool isContinuous = true;
1103 unsigned Size = Parts.front()->Size;
1104 unsigned LastOffset = Parts.front()->Offset;
1105 unsigned LastSize = Parts.front()->Size;
1106 for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1108 Name += Parts[i]->getName();
1109 Size += Parts[i]->Size;
1110 if (Parts[i]->Offset != (LastOffset + LastSize))
1111 isContinuous = false;
1112 LastOffset = Parts[i]->Offset;
1113 LastSize = Parts[i]->Size;
1115 Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1117 Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1121 void CodeGenRegBank::computeComposites() {
1122 // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1123 // and many registers will share TopoSigs on regular architectures.
1124 BitVector TopoSigs(getNumTopoSigs());
1126 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1127 CodeGenRegister *Reg1 = Registers[i];
1129 // Skip identical subreg structures already processed.
1130 if (TopoSigs.test(Reg1->getTopoSig()))
1132 TopoSigs.set(Reg1->getTopoSig());
1134 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
1135 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1136 e1 = SRM1.end(); i1 != e1; ++i1) {
1137 CodeGenSubRegIndex *Idx1 = i1->first;
1138 CodeGenRegister *Reg2 = i1->second;
1139 // Ignore identity compositions.
1142 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1143 // Try composing Idx1 with another SubRegIndex.
1144 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1145 e2 = SRM2.end(); i2 != e2; ++i2) {
1146 CodeGenSubRegIndex *Idx2 = i2->first;
1147 CodeGenRegister *Reg3 = i2->second;
1148 // Ignore identity compositions.
1151 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1152 CodeGenSubRegIndex *Idx3 = Reg1->getSubRegIndex(Reg3);
1153 assert(Idx3 && "Sub-register doesn't have an index");
1155 // Conflicting composition? Emit a warning but allow it.
1156 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
1157 PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1158 " and " + Idx2->getQualifiedName() +
1159 " compose ambiguously as " + Prev->getQualifiedName() +
1160 " or " + Idx3->getQualifiedName());
1166 // Compute lane masks. This is similar to register units, but at the
1167 // sub-register index level. Each bit in the lane mask is like a register unit
1168 // class, and two lane masks will have a bit in common if two sub-register
1169 // indices overlap in some register.
1171 // Conservatively share a lane mask bit if two sub-register indices overlap in
1172 // some registers, but not in others. That shouldn't happen a lot.
1173 void CodeGenRegBank::computeSubRegIndexLaneMasks() {
1174 // First assign individual bits to all the leaf indices.
1176 // Determine mask of lanes that cover their registers.
1177 CoveringLanes = ~0u;
1178 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i) {
1179 CodeGenSubRegIndex *Idx = SubRegIndices[i];
1180 if (Idx->getComposites().empty()) {
1181 Idx->LaneMask = 1u << Bit;
1182 // Share bit 31 in the unlikely case there are more than 32 leafs.
1184 // Sharing bits is harmless; it allows graceful degradation in targets
1185 // with more than 32 vector lanes. They simply get a limited resolution
1186 // view of lanes beyond the 32nd.
1188 // See also the comment for getSubRegIndexLaneMask().
1192 // Once bit 31 is shared among multiple leafs, the 'lane' it represents
1193 // is no longer covering its registers.
1194 CoveringLanes &= ~(1u << Bit);
1200 // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1201 // by the sub-register graph? This doesn't occur in any known targets.
1203 // Inherit lanes from composites.
1204 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i) {
1205 unsigned Mask = SubRegIndices[i]->computeLaneMask();
1206 // If some super-registers without CoveredBySubRegs use this index, we can
1207 // no longer assume that the lanes are covering their registers.
1208 if (!SubRegIndices[i]->AllSuperRegsCovered)
1209 CoveringLanes &= ~Mask;
1214 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1215 // the transitive closure of the union of overlapping register
1216 // classes. Together, the UberRegSets form a partition of the registers. If we
1217 // consider overlapping register classes to be connected, then each UberRegSet
1218 // is a set of connected components.
1220 // An UberRegSet will likely be a horizontal slice of register names of
1221 // the same width. Nontrivial subregisters should then be in a separate
1222 // UberRegSet. But this property isn't required for valid computation of
1223 // register unit weights.
1225 // A Weight field caches the max per-register unit weight in each UberRegSet.
1227 // A set of SingularDeterminants flags single units of some register in this set
1228 // for which the unit weight equals the set weight. These units should not have
1229 // their weight increased.
1231 CodeGenRegister::Set Regs;
1233 CodeGenRegister::RegUnitList SingularDeterminants;
1235 UberRegSet(): Weight(0) {}
1239 // Partition registers into UberRegSets, where each set is the transitive
1240 // closure of the union of overlapping register classes.
1242 // UberRegSets[0] is a special non-allocatable set.
1243 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1244 std::vector<UberRegSet*> &RegSets,
1245 CodeGenRegBank &RegBank) {
1247 const std::vector<CodeGenRegister*> &Registers = RegBank.getRegisters();
1249 // The Register EnumValue is one greater than its index into Registers.
1250 assert(Registers.size() == Registers[Registers.size()-1]->EnumValue &&
1251 "register enum value mismatch");
1253 // For simplicitly make the SetID the same as EnumValue.
1254 IntEqClasses UberSetIDs(Registers.size()+1);
1255 std::set<unsigned> AllocatableRegs;
1256 for (unsigned i = 0, e = RegBank.getRegClasses().size(); i != e; ++i) {
1258 CodeGenRegisterClass *RegClass = RegBank.getRegClasses()[i];
1259 if (!RegClass->Allocatable)
1262 const CodeGenRegister::Set &Regs = RegClass->getMembers();
1266 unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1267 assert(USetID && "register number 0 is invalid");
1269 AllocatableRegs.insert((*Regs.begin())->EnumValue);
1270 for (CodeGenRegister::Set::const_iterator I = llvm::next(Regs.begin()),
1271 E = Regs.end(); I != E; ++I) {
1272 AllocatableRegs.insert((*I)->EnumValue);
1273 UberSetIDs.join(USetID, (*I)->EnumValue);
1276 // Combine non-allocatable regs.
1277 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1278 unsigned RegNum = Registers[i]->EnumValue;
1279 if (AllocatableRegs.count(RegNum))
1282 UberSetIDs.join(0, RegNum);
1284 UberSetIDs.compress();
1286 // Make the first UberSet a special unallocatable set.
1287 unsigned ZeroID = UberSetIDs[0];
1289 // Insert Registers into the UberSets formed by union-find.
1290 // Do not resize after this.
1291 UberSets.resize(UberSetIDs.getNumClasses());
1292 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1293 const CodeGenRegister *Reg = Registers[i];
1294 unsigned USetID = UberSetIDs[Reg->EnumValue];
1297 else if (USetID == ZeroID)
1300 UberRegSet *USet = &UberSets[USetID];
1301 USet->Regs.insert(Reg);
1306 // Recompute each UberSet weight after changing unit weights.
1307 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1308 CodeGenRegBank &RegBank) {
1309 // Skip the first unallocatable set.
1310 for (std::vector<UberRegSet>::iterator I = llvm::next(UberSets.begin()),
1311 E = UberSets.end(); I != E; ++I) {
1313 // Initialize all unit weights in this set, and remember the max units/reg.
1314 const CodeGenRegister *Reg = 0;
1315 unsigned MaxWeight = 0, Weight = 0;
1316 for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1317 if (Reg != UnitI.getReg()) {
1318 if (Weight > MaxWeight)
1320 Reg = UnitI.getReg();
1323 unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1326 RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1330 if (Weight > MaxWeight)
1333 // Update the set weight.
1334 I->Weight = MaxWeight;
1336 // Find singular determinants.
1337 for (CodeGenRegister::Set::iterator RegI = I->Regs.begin(),
1338 RegE = I->Regs.end(); RegI != RegE; ++RegI) {
1339 if ((*RegI)->getRegUnits().size() == 1
1340 && (*RegI)->getWeight(RegBank) == I->Weight)
1341 mergeRegUnits(I->SingularDeterminants, (*RegI)->getRegUnits());
1346 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1347 // a register and its subregisters so that they have the same weight as their
1348 // UberSet. Self-recursion processes the subregister tree in postorder so
1349 // subregisters are normalized first.
1352 // - creates new adopted register units
1353 // - causes superregisters to inherit adopted units
1354 // - increases the weight of "singular" units
1355 // - induces recomputation of UberWeights.
1356 static bool normalizeWeight(CodeGenRegister *Reg,
1357 std::vector<UberRegSet> &UberSets,
1358 std::vector<UberRegSet*> &RegSets,
1359 std::set<unsigned> &NormalRegs,
1360 CodeGenRegister::RegUnitList &NormalUnits,
1361 CodeGenRegBank &RegBank) {
1362 bool Changed = false;
1363 if (!NormalRegs.insert(Reg->EnumValue).second)
1366 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1367 for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1368 SRE = SRM.end(); SRI != SRE; ++SRI) {
1369 if (SRI->second == Reg)
1370 continue; // self-cycles happen
1372 Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1373 NormalRegs, NormalUnits, RegBank);
1375 // Postorder register normalization.
1377 // Inherit register units newly adopted by subregisters.
1378 if (Reg->inheritRegUnits(RegBank))
1379 computeUberWeights(UberSets, RegBank);
1381 // Check if this register is too skinny for its UberRegSet.
1382 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1384 unsigned RegWeight = Reg->getWeight(RegBank);
1385 if (UberSet->Weight > RegWeight) {
1386 // A register unit's weight can be adjusted only if it is the singular unit
1387 // for this register, has not been used to normalize a subregister's set,
1388 // and has not already been used to singularly determine this UberRegSet.
1389 unsigned AdjustUnit = Reg->getRegUnits().front();
1390 if (Reg->getRegUnits().size() != 1
1391 || hasRegUnit(NormalUnits, AdjustUnit)
1392 || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1393 // We don't have an adjustable unit, so adopt a new one.
1394 AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1395 Reg->adoptRegUnit(AdjustUnit);
1396 // Adopting a unit does not immediately require recomputing set weights.
1399 // Adjust the existing single unit.
1400 RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1401 // The unit may be shared among sets and registers within this set.
1402 computeUberWeights(UberSets, RegBank);
1407 // Mark these units normalized so superregisters can't change their weights.
1408 mergeRegUnits(NormalUnits, Reg->getRegUnits());
1413 // Compute a weight for each register unit created during getSubRegs.
1415 // The goal is that two registers in the same class will have the same weight,
1416 // where each register's weight is defined as sum of its units' weights.
1417 void CodeGenRegBank::computeRegUnitWeights() {
1418 std::vector<UberRegSet> UberSets;
1419 std::vector<UberRegSet*> RegSets(Registers.size());
1420 computeUberSets(UberSets, RegSets, *this);
1421 // UberSets and RegSets are now immutable.
1423 computeUberWeights(UberSets, *this);
1425 // Iterate over each Register, normalizing the unit weights until reaching
1427 unsigned NumIters = 0;
1428 for (bool Changed = true; Changed; ++NumIters) {
1429 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1431 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1432 CodeGenRegister::RegUnitList NormalUnits;
1433 std::set<unsigned> NormalRegs;
1434 Changed |= normalizeWeight(Registers[i], UberSets, RegSets,
1435 NormalRegs, NormalUnits, *this);
1440 // Find a set in UniqueSets with the same elements as Set.
1441 // Return an iterator into UniqueSets.
1442 static std::vector<RegUnitSet>::const_iterator
1443 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1444 const RegUnitSet &Set) {
1445 std::vector<RegUnitSet>::const_iterator
1446 I = UniqueSets.begin(), E = UniqueSets.end();
1448 if (I->Units == Set.Units)
1454 // Return true if the RUSubSet is a subset of RUSuperSet.
1455 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1456 const std::vector<unsigned> &RUSuperSet) {
1457 return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1458 RUSubSet.begin(), RUSubSet.end());
1461 // Iteratively prune unit sets.
1462 void CodeGenRegBank::pruneUnitSets() {
1463 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1465 // Form an equivalence class of UnitSets with no significant difference.
1466 std::vector<unsigned> SuperSetIDs;
1467 for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1468 SubIdx != EndIdx; ++SubIdx) {
1469 const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1470 unsigned SuperIdx = 0;
1471 for (; SuperIdx != EndIdx; ++SuperIdx) {
1472 if (SuperIdx == SubIdx)
1475 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1476 if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1477 && (SubSet.Units.size() + 3 > SuperSet.Units.size())) {
1481 if (SuperIdx == EndIdx)
1482 SuperSetIDs.push_back(SubIdx);
1484 // Populate PrunedUnitSets with each equivalence class's superset.
1485 std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1486 for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1487 unsigned SuperIdx = SuperSetIDs[i];
1488 PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1489 PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1491 RegUnitSets.swap(PrunedUnitSets);
1494 // Create a RegUnitSet for each RegClass that contains all units in the class
1495 // including adopted units that are necessary to model register pressure. Then
1496 // iteratively compute RegUnitSets such that the union of any two overlapping
1497 // RegUnitSets is repreresented.
1499 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1500 // RegUnitSet that is a superset of that RegUnitClass.
1501 void CodeGenRegBank::computeRegUnitSets() {
1503 // Compute a unique RegUnitSet for each RegClass.
1504 const ArrayRef<CodeGenRegisterClass*> &RegClasses = getRegClasses();
1505 unsigned NumRegClasses = RegClasses.size();
1506 for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1507 if (!RegClasses[RCIdx]->Allocatable)
1510 // Speculatively grow the RegUnitSets to hold the new set.
1511 RegUnitSets.resize(RegUnitSets.size() + 1);
1512 RegUnitSets.back().Name = RegClasses[RCIdx]->getName();
1514 // Compute a sorted list of units in this class.
1515 RegClasses[RCIdx]->buildRegUnitSet(RegUnitSets.back().Units);
1517 // Find an existing RegUnitSet.
1518 std::vector<RegUnitSet>::const_iterator SetI =
1519 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1520 if (SetI != llvm::prior(RegUnitSets.end()))
1521 RegUnitSets.pop_back();
1524 // Iteratively prune unit sets.
1527 // Iterate over all unit sets, including new ones added by this loop.
1528 unsigned NumRegUnitSubSets = RegUnitSets.size();
1529 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1530 // In theory, this is combinatorial. In practice, it needs to be bounded
1531 // by a small number of sets for regpressure to be efficient.
1532 // If the assert is hit, we need to implement pruning.
1533 assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1535 // Compare new sets with all original classes.
1536 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1537 SearchIdx != EndIdx; ++SearchIdx) {
1538 std::set<unsigned> Intersection;
1539 std::set_intersection(RegUnitSets[Idx].Units.begin(),
1540 RegUnitSets[Idx].Units.end(),
1541 RegUnitSets[SearchIdx].Units.begin(),
1542 RegUnitSets[SearchIdx].Units.end(),
1543 std::inserter(Intersection, Intersection.begin()));
1544 if (Intersection.empty())
1547 // Speculatively grow the RegUnitSets to hold the new set.
1548 RegUnitSets.resize(RegUnitSets.size() + 1);
1549 RegUnitSets.back().Name =
1550 RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1552 std::set_union(RegUnitSets[Idx].Units.begin(),
1553 RegUnitSets[Idx].Units.end(),
1554 RegUnitSets[SearchIdx].Units.begin(),
1555 RegUnitSets[SearchIdx].Units.end(),
1556 std::inserter(RegUnitSets.back().Units,
1557 RegUnitSets.back().Units.begin()));
1559 // Find an existing RegUnitSet, or add the union to the unique sets.
1560 std::vector<RegUnitSet>::const_iterator SetI =
1561 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1562 if (SetI != llvm::prior(RegUnitSets.end()))
1563 RegUnitSets.pop_back();
1567 // Iteratively prune unit sets after inferring supersets.
1570 // For each register class, list the UnitSets that are supersets.
1571 RegClassUnitSets.resize(NumRegClasses);
1572 for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1573 if (!RegClasses[RCIdx]->Allocatable)
1576 // Recompute the sorted list of units in this class.
1577 std::vector<unsigned> RegUnits;
1578 RegClasses[RCIdx]->buildRegUnitSet(RegUnits);
1580 // Don't increase pressure for unallocatable regclasses.
1581 if (RegUnits.empty())
1584 // Find all supersets.
1585 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1586 USIdx != USEnd; ++USIdx) {
1587 if (isRegUnitSubSet(RegUnits, RegUnitSets[USIdx].Units))
1588 RegClassUnitSets[RCIdx].push_back(USIdx);
1590 assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1593 // For each register unit, ensure that we have the list of UnitSets that
1594 // contain the unit. Normally, this matches an existing list of UnitSets for a
1595 // register class. If not, we create a new entry in RegClassUnitSets as a
1596 // "fake" register class.
1597 for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
1598 UnitIdx < UnitEnd; ++UnitIdx) {
1599 std::vector<unsigned> RUSets;
1600 for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
1601 RegUnitSet &RUSet = RegUnitSets[i];
1602 if (std::find(RUSet.Units.begin(), RUSet.Units.end(), UnitIdx)
1603 == RUSet.Units.end())
1605 RUSets.push_back(i);
1607 unsigned RCUnitSetsIdx = 0;
1608 for (unsigned e = RegClassUnitSets.size();
1609 RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
1610 if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
1614 RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
1615 if (RCUnitSetsIdx == RegClassUnitSets.size()) {
1616 // Create a new list of UnitSets as a "fake" register class.
1617 RegClassUnitSets.resize(RCUnitSetsIdx + 1);
1618 RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
1624 const CodeGenRegBank &RegBank;
1625 LessUnits(const CodeGenRegBank &RB): RegBank(RB) {}
1627 bool operator()(unsigned ID1, unsigned ID2) {
1628 return RegBank.getRegPressureSet(ID1).Units.size()
1629 < RegBank.getRegPressureSet(ID2).Units.size();
1633 void CodeGenRegBank::computeDerivedInfo() {
1634 computeComposites();
1635 computeSubRegIndexLaneMasks();
1637 // Compute a weight for each register unit created during getSubRegs.
1638 // This may create adopted register units (with unit # >= NumNativeRegUnits).
1639 computeRegUnitWeights();
1641 // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1642 // supersets for the union of overlapping sets.
1643 computeRegUnitSets();
1645 // Get the weight of each set.
1646 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1647 RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
1649 // Find the order of each set.
1650 RegUnitSetOrder.reserve(RegUnitSets.size());
1651 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1652 RegUnitSetOrder.push_back(Idx);
1654 std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
1656 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1657 RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
1662 // Synthesize missing register class intersections.
1664 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1665 // returns a maximal register class for all X.
1667 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1668 for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
1669 CodeGenRegisterClass *RC1 = RC;
1670 CodeGenRegisterClass *RC2 = RegClasses[rci];
1674 // Compute the set intersection of RC1 and RC2.
1675 const CodeGenRegister::Set &Memb1 = RC1->getMembers();
1676 const CodeGenRegister::Set &Memb2 = RC2->getMembers();
1677 CodeGenRegister::Set Intersection;
1678 std::set_intersection(Memb1.begin(), Memb1.end(),
1679 Memb2.begin(), Memb2.end(),
1680 std::inserter(Intersection, Intersection.begin()),
1681 CodeGenRegister::Less());
1683 // Skip disjoint class pairs.
1684 if (Intersection.empty())
1687 // If RC1 and RC2 have different spill sizes or alignments, use the
1688 // larger size for sub-classing. If they are equal, prefer RC1.
1689 if (RC2->SpillSize > RC1->SpillSize ||
1690 (RC2->SpillSize == RC1->SpillSize &&
1691 RC2->SpillAlignment > RC1->SpillAlignment))
1692 std::swap(RC1, RC2);
1694 getOrCreateSubClass(RC1, &Intersection,
1695 RC1->getName() + "_and_" + RC2->getName());
1700 // Synthesize missing sub-classes for getSubClassWithSubReg().
1702 // Make sure that the set of registers in RC with a given SubIdx sub-register
1703 // form a register class. Update RC->SubClassWithSubReg.
1705 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1706 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1707 typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
1708 CodeGenSubRegIndex::Less> SubReg2SetMap;
1710 // Compute the set of registers supporting each SubRegIndex.
1711 SubReg2SetMap SRSets;
1712 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1713 RE = RC->getMembers().end(); RI != RE; ++RI) {
1714 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
1715 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1716 E = SRM.end(); I != E; ++I)
1717 SRSets[I->first].insert(*RI);
1720 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
1721 // numerical order to visit synthetic indices last.
1722 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1723 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1724 SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
1725 // Unsupported SubRegIndex. Skip it.
1726 if (I == SRSets.end())
1728 // In most cases, all RC registers support the SubRegIndex.
1729 if (I->second.size() == RC->getMembers().size()) {
1730 RC->setSubClassWithSubReg(SubIdx, RC);
1733 // This is a real subset. See if we have a matching class.
1734 CodeGenRegisterClass *SubRC =
1735 getOrCreateSubClass(RC, &I->second,
1736 RC->getName() + "_with_" + I->first->getName());
1737 RC->setSubClassWithSubReg(SubIdx, SubRC);
1742 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1744 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1745 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1748 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1749 unsigned FirstSubRegRC) {
1750 SmallVector<std::pair<const CodeGenRegister*,
1751 const CodeGenRegister*>, 16> SSPairs;
1752 BitVector TopoSigs(getNumTopoSigs());
1754 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1755 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1756 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1757 // Skip indexes that aren't fully supported by RC's registers. This was
1758 // computed by inferSubClassWithSubReg() above which should have been
1760 if (RC->getSubClassWithSubReg(SubIdx) != RC)
1763 // Build list of (Super, Sub) pairs for this SubIdx.
1766 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1767 RE = RC->getMembers().end(); RI != RE; ++RI) {
1768 const CodeGenRegister *Super = *RI;
1769 const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
1770 assert(Sub && "Missing sub-register");
1771 SSPairs.push_back(std::make_pair(Super, Sub));
1772 TopoSigs.set(Sub->getTopoSig());
1775 // Iterate over sub-register class candidates. Ignore classes created by
1776 // this loop. They will never be useful.
1777 for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
1779 CodeGenRegisterClass *SubRC = RegClasses[rci];
1780 // Topological shortcut: SubRC members have the wrong shape.
1781 if (!TopoSigs.anyCommon(SubRC->getTopoSigs()))
1783 // Compute the subset of RC that maps into SubRC.
1784 CodeGenRegister::Set SubSet;
1785 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1786 if (SubRC->contains(SSPairs[i].second))
1787 SubSet.insert(SSPairs[i].first);
1790 // RC injects completely into SubRC.
1791 if (SubSet.size() == SSPairs.size()) {
1792 SubRC->addSuperRegClass(SubIdx, RC);
1795 // Only a subset of RC maps into SubRC. Make sure it is represented by a
1797 getOrCreateSubClass(RC, &SubSet, RC->getName() +
1798 "_with_" + SubIdx->getName() +
1799 "_in_" + SubRC->getName());
1806 // Infer missing register classes.
1808 void CodeGenRegBank::computeInferredRegisterClasses() {
1809 // When this function is called, the register classes have not been sorted
1810 // and assigned EnumValues yet. That means getSubClasses(),
1811 // getSuperClasses(), and hasSubClass() functions are defunct.
1812 unsigned FirstNewRC = RegClasses.size();
1814 // Visit all register classes, including the ones being added by the loop.
1815 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
1816 CodeGenRegisterClass *RC = RegClasses[rci];
1818 // Synthesize answers for getSubClassWithSubReg().
1819 inferSubClassWithSubReg(RC);
1821 // Synthesize answers for getCommonSubClass().
1822 inferCommonSubClass(RC);
1824 // Synthesize answers for getMatchingSuperRegClass().
1825 inferMatchingSuperRegClass(RC);
1827 // New register classes are created while this loop is running, and we need
1828 // to visit all of them. I particular, inferMatchingSuperRegClass needs
1829 // to match old super-register classes with sub-register classes created
1830 // after inferMatchingSuperRegClass was called. At this point,
1831 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
1832 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
1833 if (rci + 1 == FirstNewRC) {
1834 unsigned NextNewRC = RegClasses.size();
1835 for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
1836 inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
1837 FirstNewRC = NextNewRC;
1842 /// getRegisterClassForRegister - Find the register class that contains the
1843 /// specified physical register. If the register is not in a register class,
1844 /// return null. If the register is in multiple classes, and the classes have a
1845 /// superset-subset relationship and the same set of types, return the
1846 /// superclass. Otherwise return null.
1847 const CodeGenRegisterClass*
1848 CodeGenRegBank::getRegClassForRegister(Record *R) {
1849 const CodeGenRegister *Reg = getReg(R);
1850 ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
1851 const CodeGenRegisterClass *FoundRC = 0;
1852 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
1853 const CodeGenRegisterClass &RC = *RCs[i];
1854 if (!RC.contains(Reg))
1857 // If this is the first class that contains the register,
1858 // make a note of it and go on to the next class.
1864 // If a register's classes have different types, return null.
1865 if (RC.getValueTypes() != FoundRC->getValueTypes())
1868 // Check to see if the previously found class that contains
1869 // the register is a subclass of the current class. If so,
1870 // prefer the superclass.
1871 if (RC.hasSubClass(FoundRC)) {
1876 // Check to see if the previously found class that contains
1877 // the register is a superclass of the current class. If so,
1878 // prefer the superclass.
1879 if (FoundRC->hasSubClass(&RC))
1882 // Multiple classes, and neither is a superclass of the other.
1889 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1890 SetVector<const CodeGenRegister*> Set;
1892 // First add Regs with all sub-registers.
1893 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1894 CodeGenRegister *Reg = getReg(Regs[i]);
1895 if (Set.insert(Reg))
1896 // Reg is new, add all sub-registers.
1897 // The pre-ordering is not important here.
1898 Reg->addSubRegsPreOrder(Set, *this);
1901 // Second, find all super-registers that are completely covered by the set.
1902 for (unsigned i = 0; i != Set.size(); ++i) {
1903 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1904 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1905 const CodeGenRegister *Super = SR[j];
1906 if (!Super->CoveredBySubRegs || Set.count(Super))
1908 // This new super-register is covered by its sub-registers.
1909 bool AllSubsInSet = true;
1910 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1911 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1912 E = SRM.end(); I != E; ++I)
1913 if (!Set.count(I->second)) {
1914 AllSubsInSet = false;
1917 // All sub-registers in Set, add Super as well.
1918 // We will visit Super later to recheck its super-registers.
1924 // Convert to BitVector.
1925 BitVector BV(Registers.size() + 1);
1926 for (unsigned i = 0, e = Set.size(); i != e; ++i)
1927 BV.set(Set[i]->EnumValue);