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) {
33 if (R->getValue("Namespace"))
34 Namespace = R->getValueAsString("Namespace");
37 CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
39 : TheDef(0), Name(N), Namespace(Nspace), EnumValue(Enum), LaneMask(0) {
42 std::string CodeGenSubRegIndex::getQualifiedName() const {
43 std::string N = getNamespace();
50 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
54 std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
56 if (Comps.size() != 2)
57 PrintFatalError(TheDef->getLoc(),
58 "ComposedOf must have exactly two entries");
59 CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
60 CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
61 CodeGenSubRegIndex *X = A->addComposite(B, this);
63 PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
66 std::vector<Record*> Parts =
67 TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
70 PrintFatalError(TheDef->getLoc(),
71 "CoveredBySubRegs must have two or more entries");
72 SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
73 for (unsigned i = 0, e = Parts.size(); i != e; ++i)
74 IdxParts.push_back(RegBank.getSubRegIdx(Parts[i]));
75 RegBank.addConcatSubRegIndex(IdxParts, this);
79 unsigned CodeGenSubRegIndex::computeLaneMask() {
84 // Recursion guard, shouldn't be required.
87 // The lane mask is simply the union of all sub-indices.
89 for (CompMap::iterator I = Composed.begin(), E = Composed.end(); I != E; ++I)
90 M |= I->second->computeLaneMask();
91 assert(M && "Missing lane mask, sub-register cycle?");
96 //===----------------------------------------------------------------------===//
98 //===----------------------------------------------------------------------===//
100 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
103 CostPerUse(R->getValueAsInt("CostPerUse")),
104 CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
105 NumNativeRegUnits(0),
106 SubRegsComplete(false),
107 SuperRegsComplete(false),
111 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
112 std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
113 std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
115 if (SRIs.size() != SRs.size())
116 PrintFatalError(TheDef->getLoc(),
117 "SubRegs and SubRegIndices must have the same size");
119 for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
120 ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
121 ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
124 // Also compute leading super-registers. Each register has a list of
125 // covered-by-subregs super-registers where it appears as the first explicit
128 // This is used by computeSecondarySubRegs() to find candidates.
129 if (CoveredBySubRegs && !ExplicitSubRegs.empty())
130 ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
132 // Add ad hoc alias links. This is a symmetric relationship between two
133 // registers, so build a symmetric graph by adding links in both ends.
134 std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
135 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
136 CodeGenRegister *Reg = RegBank.getReg(Aliases[i]);
137 ExplicitAliases.push_back(Reg);
138 Reg->ExplicitAliases.push_back(this);
142 const std::string &CodeGenRegister::getName() const {
143 return TheDef->getName();
147 // Iterate over all register units in a set of registers.
148 class RegUnitIterator {
149 CodeGenRegister::Set::const_iterator RegI, RegE;
150 CodeGenRegister::RegUnitList::const_iterator UnitI, UnitE;
153 RegUnitIterator(const CodeGenRegister::Set &Regs):
154 RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
157 UnitI = (*RegI)->getRegUnits().begin();
158 UnitE = (*RegI)->getRegUnits().end();
163 bool isValid() const { return UnitI != UnitE; }
165 unsigned operator* () const { assert(isValid()); return *UnitI; }
167 const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
169 /// Preincrement. Move to the next unit.
171 assert(isValid() && "Cannot advance beyond the last operand");
178 while (UnitI == UnitE) {
181 UnitI = (*RegI)->getRegUnits().begin();
182 UnitE = (*RegI)->getRegUnits().end();
188 // Merge two RegUnitLists maintaining the order and removing duplicates.
189 // Overwrites MergedRU in the process.
190 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
191 const CodeGenRegister::RegUnitList &RRU) {
192 CodeGenRegister::RegUnitList LRU = MergedRU;
194 std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(),
195 std::back_inserter(MergedRU));
198 // Return true of this unit appears in RegUnits.
199 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
200 return std::count(RegUnits.begin(), RegUnits.end(), Unit);
203 // Inherit register units from subregisters.
204 // Return true if the RegUnits changed.
205 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
206 unsigned OldNumUnits = RegUnits.size();
207 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
209 CodeGenRegister *SR = I->second;
210 // Merge the subregister's units into this register's RegUnits.
211 mergeRegUnits(RegUnits, SR->RegUnits);
213 return OldNumUnits != RegUnits.size();
216 const CodeGenRegister::SubRegMap &
217 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
218 // Only compute this map once.
221 SubRegsComplete = true;
223 // First insert the explicit subregs and make sure they are fully indexed.
224 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
225 CodeGenRegister *SR = ExplicitSubRegs[i];
226 CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
227 if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
228 PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
229 " appears twice in Register " + getName());
230 // Map explicit sub-registers first, so the names take precedence.
231 // The inherited sub-registers are mapped below.
232 SubReg2Idx.insert(std::make_pair(SR, Idx));
235 // Keep track of inherited subregs and how they can be reached.
236 SmallPtrSet<CodeGenRegister*, 8> Orphans;
238 // Clone inherited subregs and place duplicate entries in Orphans.
239 // Here the order is important - earlier subregs take precedence.
240 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
241 CodeGenRegister *SR = ExplicitSubRegs[i];
242 const SubRegMap &Map = SR->computeSubRegs(RegBank);
244 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
246 if (!SubRegs.insert(*SI).second)
247 Orphans.insert(SI->second);
251 // Expand any composed subreg indices.
252 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
253 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
254 // expanded subreg indices recursively.
255 SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
256 for (unsigned i = 0; i != Indices.size(); ++i) {
257 CodeGenSubRegIndex *Idx = Indices[i];
258 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
259 CodeGenRegister *SR = SubRegs[Idx];
260 const SubRegMap &Map = SR->computeSubRegs(RegBank);
262 // Look at the possible compositions of Idx.
263 // They may not all be supported by SR.
264 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
265 E = Comps.end(); I != E; ++I) {
266 SubRegMap::const_iterator SRI = Map.find(I->first);
267 if (SRI == Map.end())
268 continue; // Idx + I->first doesn't exist in SR.
269 // Add I->second as a name for the subreg SRI->second, assuming it is
270 // orphaned, and the name isn't already used for something else.
271 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
273 // We found a new name for the orphaned sub-register.
274 SubRegs.insert(std::make_pair(I->second, SRI->second));
275 Indices.push_back(I->second);
279 // Now Orphans contains the inherited subregisters without a direct index.
280 // Create inferred indexes for all missing entries.
281 // Work backwards in the Indices vector in order to compose subregs bottom-up.
282 // Consider this subreg sequence:
284 // qsub_1 -> dsub_0 -> ssub_0
286 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
287 // can be reached in two different ways:
292 // We pick the latter composition because another register may have [dsub_0,
293 // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The
294 // dsub_2 -> ssub_0 composition can be shared.
295 while (!Indices.empty() && !Orphans.empty()) {
296 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
297 CodeGenRegister *SR = SubRegs[Idx];
298 const SubRegMap &Map = SR->computeSubRegs(RegBank);
299 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
301 if (Orphans.erase(SI->second))
302 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
305 // Compute the inverse SubReg -> Idx map.
306 for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end();
308 if (SI->second == this) {
311 Loc = TheDef->getLoc();
312 PrintFatalError(Loc, "Register " + getName() +
313 " has itself as a sub-register");
315 // Ensure that every sub-register has a unique name.
316 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
317 SubReg2Idx.insert(std::make_pair(SI->second, SI->first)).first;
318 if (Ins->second == SI->first)
320 // Trouble: Two different names for SI->second.
323 Loc = TheDef->getLoc();
324 PrintFatalError(Loc, "Sub-register can't have two names: " +
325 SI->second->getName() + " available as " +
326 SI->first->getName() + " and " + Ins->second->getName());
329 // Derive possible names for sub-register concatenations from any explicit
330 // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
331 // that getConcatSubRegIndex() won't invent any concatenated indices that the
332 // user already specified.
333 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
334 CodeGenRegister *SR = ExplicitSubRegs[i];
335 if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1)
338 // SR is composed of multiple sub-regs. Find their names in this register.
339 SmallVector<CodeGenSubRegIndex*, 8> Parts;
340 for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j)
341 Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
343 // Offer this as an existing spelling for the concatenation of Parts.
344 RegBank.addConcatSubRegIndex(Parts, ExplicitSubRegIndices[i]);
347 // Initialize RegUnitList. Because getSubRegs is called recursively, this
348 // processes the register hierarchy in postorder.
350 // Inherit all sub-register units. It is good enough to look at the explicit
351 // sub-registers, the other registers won't contribute any more units.
352 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
353 CodeGenRegister *SR = ExplicitSubRegs[i];
354 // Explicit sub-registers are usually disjoint, so this is a good way of
355 // computing the union. We may pick up a few duplicates that will be
357 unsigned N = RegUnits.size();
358 RegUnits.append(SR->RegUnits.begin(), SR->RegUnits.end());
359 std::inplace_merge(RegUnits.begin(), RegUnits.begin() + N, RegUnits.end());
361 RegUnits.erase(std::unique(RegUnits.begin(), RegUnits.end()), RegUnits.end());
363 // Absent any ad hoc aliasing, we create one register unit per leaf register.
364 // These units correspond to the maximal cliques in the register overlap
365 // graph which is optimal.
367 // When there is ad hoc aliasing, we simply create one unit per edge in the
368 // undirected ad hoc aliasing graph. Technically, we could do better by
369 // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
370 // are extremely rare anyway (I've never seen one), so we don't bother with
371 // the added complexity.
372 for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
373 CodeGenRegister *AR = ExplicitAliases[i];
374 // Only visit each edge once.
375 if (AR->SubRegsComplete)
377 // Create a RegUnit representing this alias edge, and add it to both
379 unsigned Unit = RegBank.newRegUnit(this, AR);
380 RegUnits.push_back(Unit);
381 AR->RegUnits.push_back(Unit);
384 // Finally, create units for leaf registers without ad hoc aliases. Note that
385 // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
386 // necessary. This means the aliasing leaf registers can share a single unit.
387 if (RegUnits.empty())
388 RegUnits.push_back(RegBank.newRegUnit(this));
390 // We have now computed the native register units. More may be adopted later
391 // for balancing purposes.
392 NumNativeRegUnits = RegUnits.size();
397 // In a register that is covered by its sub-registers, try to find redundant
398 // sub-registers. For example:
404 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
405 // the register definition.
407 // The explicitly specified registers form a tree. This function discovers
408 // sub-register relationships that would force a DAG.
410 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
411 // Collect new sub-registers first, add them later.
412 SmallVector<SubRegMap::value_type, 8> NewSubRegs;
414 // Look at the leading super-registers of each sub-register. Those are the
415 // candidates for new sub-registers, assuming they are fully contained in
417 for (SubRegMap::iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I){
418 const CodeGenRegister *SubReg = I->second;
419 const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
420 for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
421 CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
422 // Already got this sub-register?
423 if (Cand == this || getSubRegIndex(Cand))
425 // Check if each component of Cand is already a sub-register.
426 // We know that the first component is I->second, and is present with the
428 SmallVector<CodeGenSubRegIndex*, 8> Parts(1, I->first);
429 assert(!Cand->ExplicitSubRegs.empty() &&
430 "Super-register has no sub-registers");
431 for (unsigned j = 1, e = Cand->ExplicitSubRegs.size(); j != e; ++j) {
432 if (CodeGenSubRegIndex *Idx = getSubRegIndex(Cand->ExplicitSubRegs[j]))
433 Parts.push_back(Idx);
435 // Sub-register doesn't exist.
440 // If some Cand sub-register is not part of this register, or if Cand only
441 // has one sub-register, there is nothing to do.
442 if (Parts.size() <= 1)
445 // Each part of Cand is a sub-register of this. Make the full Cand also
446 // a sub-register with a concatenated sub-register index.
447 CodeGenSubRegIndex *Concat= RegBank.getConcatSubRegIndex(Parts);
448 NewSubRegs.push_back(std::make_pair(Concat, Cand));
452 // Now add all the new sub-registers.
453 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
454 // Don't add Cand if another sub-register is already using the index.
455 if (!SubRegs.insert(NewSubRegs[i]).second)
458 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
459 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
460 SubReg2Idx.insert(std::make_pair(NewSubReg, NewIdx));
463 // Create sub-register index composition maps for the synthesized indices.
464 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
465 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
466 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
467 for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
468 SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
469 CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
471 PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
472 SI->second->getName() + " in " + getName());
473 NewIdx->addComposite(SI->first, SubIdx);
478 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
479 // Only visit each register once.
480 if (SuperRegsComplete)
482 SuperRegsComplete = true;
484 // Make sure all sub-registers have been visited first, so the super-reg
485 // lists will be topologically ordered.
486 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
488 I->second->computeSuperRegs(RegBank);
490 // Now add this as a super-register on all sub-registers.
491 // Also compute the TopoSigId in post-order.
493 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
495 // Topological signature computed from SubIdx, TopoId(SubReg).
496 // Loops and idempotent indices have TopoSig = ~0u.
497 Id.push_back(I->first->EnumValue);
498 Id.push_back(I->second->TopoSig);
500 // Don't add duplicate entries.
501 if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
503 I->second->SuperRegs.push_back(this);
505 TopoSig = RegBank.getTopoSig(Id);
509 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
510 CodeGenRegBank &RegBank) const {
511 assert(SubRegsComplete && "Must precompute sub-registers");
512 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
513 CodeGenRegister *SR = ExplicitSubRegs[i];
515 SR->addSubRegsPreOrder(OSet, RegBank);
517 // Add any secondary sub-registers that weren't part of the explicit tree.
518 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
520 OSet.insert(I->second);
523 // Compute overlapping registers.
525 // The standard set is all super-registers and all sub-registers, but the
526 // target description can add arbitrary overlapping registers via the 'Aliases'
527 // field. This complicates things, but we can compute overlapping sets using
528 // the following rules:
530 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
532 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
536 // overlap(A, B) iff there exists:
537 // A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
538 // A' = B' or A' in aliases(B') or B' in aliases(A').
540 // Here subregs(A) is the full flattened sub-register set returned by
541 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
542 // description of register A.
544 // This also implies that registers with a common sub-register are considered
545 // overlapping. This can happen when forming register pairs:
551 // In this case, we will infer an overlap between P0 and P1 because of the
552 // shared sub-register R1. There is no overlap between P0 and P2.
554 void CodeGenRegister::computeOverlaps(CodeGenRegister::Set &Overlaps,
555 const CodeGenRegBank &RegBank) const {
556 assert(!RegUnits.empty() && "Compute register units before overlaps.");
558 // Register units are assigned such that the overlapping registers are the
559 // super-registers of the root registers of the register units.
560 for (unsigned rui = 0, rue = RegUnits.size(); rui != rue; ++rui) {
561 const RegUnit &RU = RegBank.getRegUnit(RegUnits[rui]);
562 ArrayRef<const CodeGenRegister*> Roots = RU.getRoots();
563 for (unsigned ri = 0, re = Roots.size(); ri != re; ++ri) {
564 const CodeGenRegister *Root = Roots[ri];
565 Overlaps.insert(Root);
566 ArrayRef<const CodeGenRegister*> Supers = Root->getSuperRegs();
567 Overlaps.insert(Supers.begin(), Supers.end());
572 // Get the sum of this register's unit weights.
573 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
575 for (RegUnitList::const_iterator I = RegUnits.begin(), E = RegUnits.end();
577 Weight += RegBank.getRegUnit(*I).Weight;
582 //===----------------------------------------------------------------------===//
584 //===----------------------------------------------------------------------===//
586 // A RegisterTuples def is used to generate pseudo-registers from lists of
587 // sub-registers. We provide a SetTheory expander class that returns the new
590 struct TupleExpander : SetTheory::Expander {
591 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
592 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
593 unsigned Dim = Indices.size();
594 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
595 if (Dim != SubRegs->getSize())
596 PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
598 PrintFatalError(Def->getLoc(),
599 "Tuples must have at least 2 sub-registers");
601 // Evaluate the sub-register lists to be zipped.
602 unsigned Length = ~0u;
603 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
604 for (unsigned i = 0; i != Dim; ++i) {
605 ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
606 Length = std::min(Length, unsigned(Lists[i].size()));
612 // Precompute some types.
613 Record *RegisterCl = Def->getRecords().getClass("Register");
614 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
615 StringInit *BlankName = StringInit::get("");
618 for (unsigned n = 0; n != Length; ++n) {
620 Record *Proto = Lists[0][n];
621 std::vector<Init*> Tuple;
622 unsigned CostPerUse = 0;
623 for (unsigned i = 0; i != Dim; ++i) {
624 Record *Reg = Lists[i][n];
626 Name += Reg->getName();
627 Tuple.push_back(DefInit::get(Reg));
628 CostPerUse = std::max(CostPerUse,
629 unsigned(Reg->getValueAsInt("CostPerUse")));
632 // Create a new Record representing the synthesized register. This record
633 // is only for consumption by CodeGenRegister, it is not added to the
635 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
638 // Copy Proto super-classes.
639 ArrayRef<Record *> Supers = Proto->getSuperClasses();
640 ArrayRef<SMRange> Ranges = Proto->getSuperClassRanges();
641 for (unsigned i = 0, e = Supers.size(); i != e; ++i)
642 NewReg->addSuperClass(Supers[i], Ranges[i]);
644 // Copy Proto fields.
645 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
646 RecordVal RV = Proto->getValues()[i];
648 // Skip existing fields, like NAME.
649 if (NewReg->getValue(RV.getNameInit()))
652 StringRef Field = RV.getName();
654 // Replace the sub-register list with Tuple.
655 if (Field == "SubRegs")
656 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
658 // Provide a blank AsmName. MC hacks are required anyway.
659 if (Field == "AsmName")
660 RV.setValue(BlankName);
662 // CostPerUse is aggregated from all Tuple members.
663 if (Field == "CostPerUse")
664 RV.setValue(IntInit::get(CostPerUse));
666 // Composite registers are always covered by sub-registers.
667 if (Field == "CoveredBySubRegs")
668 RV.setValue(BitInit::get(true));
670 // Copy fields from the RegisterTuples def.
671 if (Field == "SubRegIndices" ||
672 Field == "CompositeIndices") {
673 NewReg->addValue(*Def->getValue(Field));
677 // Some fields get their default uninitialized value.
678 if (Field == "DwarfNumbers" ||
679 Field == "DwarfAlias" ||
680 Field == "Aliases") {
681 if (const RecordVal *DefRV = RegisterCl->getValue(Field))
682 NewReg->addValue(*DefRV);
686 // Everything else is copied from Proto.
687 NewReg->addValue(RV);
694 //===----------------------------------------------------------------------===//
695 // CodeGenRegisterClass
696 //===----------------------------------------------------------------------===//
698 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
701 TopoSigs(RegBank.getNumTopoSigs()),
703 // Rename anonymous register classes.
704 if (R->getName().size() > 9 && R->getName()[9] == '.') {
705 static unsigned AnonCounter = 0;
706 R->setName("AnonRegClass_"+utostr(AnonCounter++));
709 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
710 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
711 Record *Type = TypeList[i];
712 if (!Type->isSubClassOf("ValueType"))
713 PrintFatalError("RegTypes list member '" + Type->getName() +
714 "' does not derive from the ValueType class!");
715 VTs.push_back(getValueType(Type));
717 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
719 // Allocation order 0 is the full set. AltOrders provides others.
720 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
721 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
722 Orders.resize(1 + AltOrders->size());
724 // Default allocation order always contains all registers.
725 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
726 Orders[0].push_back((*Elements)[i]);
727 const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
729 TopoSigs.set(Reg->getTopoSig());
732 // Alternative allocation orders may be subsets.
733 SetTheory::RecSet Order;
734 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
735 RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
736 Orders[1 + i].append(Order.begin(), Order.end());
737 // Verify that all altorder members are regclass members.
738 while (!Order.empty()) {
739 CodeGenRegister *Reg = RegBank.getReg(Order.back());
742 PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
743 " is not a class member");
747 // Allow targets to override the size in bits of the RegisterClass.
748 unsigned Size = R->getValueAsInt("Size");
750 Namespace = R->getValueAsString("Namespace");
751 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
752 SpillAlignment = R->getValueAsInt("Alignment");
753 CopyCost = R->getValueAsInt("CopyCost");
754 Allocatable = R->getValueAsBit("isAllocatable");
755 AltOrderSelect = R->getValueAsString("AltOrderSelect");
758 // Create an inferred register class that was missing from the .td files.
759 // Most properties will be inherited from the closest super-class after the
760 // class structure has been computed.
761 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
762 StringRef Name, Key Props)
763 : Members(*Props.Members),
766 TopoSigs(RegBank.getNumTopoSigs()),
768 SpillSize(Props.SpillSize),
769 SpillAlignment(Props.SpillAlignment),
772 for (CodeGenRegister::Set::iterator I = Members.begin(), E = Members.end();
774 TopoSigs.set((*I)->getTopoSig());
777 // Compute inherited propertied for a synthesized register class.
778 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
779 assert(!getDef() && "Only synthesized classes can inherit properties");
780 assert(!SuperClasses.empty() && "Synthesized class without super class");
782 // The last super-class is the smallest one.
783 CodeGenRegisterClass &Super = *SuperClasses.back();
785 // Most properties are copied directly.
786 // Exceptions are members, size, and alignment
787 Namespace = Super.Namespace;
789 CopyCost = Super.CopyCost;
790 Allocatable = Super.Allocatable;
791 AltOrderSelect = Super.AltOrderSelect;
793 // Copy all allocation orders, filter out foreign registers from the larger
795 Orders.resize(Super.Orders.size());
796 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
797 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
798 if (contains(RegBank.getReg(Super.Orders[i][j])))
799 Orders[i].push_back(Super.Orders[i][j]);
802 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
803 return Members.count(Reg);
807 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
808 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
809 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
810 E = K.Members->end(); I != E; ++I)
811 OS << ", " << (*I)->getName();
816 // This is a simple lexicographical order that can be used to search for sets.
817 // It is not the same as the topological order provided by TopoOrderRC.
818 bool CodeGenRegisterClass::Key::
819 operator<(const CodeGenRegisterClass::Key &B) const {
820 assert(Members && B.Members);
821 if (*Members != *B.Members)
822 return *Members < *B.Members;
823 if (SpillSize != B.SpillSize)
824 return SpillSize < B.SpillSize;
825 return SpillAlignment < B.SpillAlignment;
828 // Returns true if RC is a strict subclass.
829 // RC is a sub-class of this class if it is a valid replacement for any
830 // instruction operand where a register of this classis required. It must
831 // satisfy these conditions:
833 // 1. All RC registers are also in this.
834 // 2. The RC spill size must not be smaller than our spill size.
835 // 3. RC spill alignment must be compatible with ours.
837 static bool testSubClass(const CodeGenRegisterClass *A,
838 const CodeGenRegisterClass *B) {
839 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
840 A->SpillSize <= B->SpillSize &&
841 std::includes(A->getMembers().begin(), A->getMembers().end(),
842 B->getMembers().begin(), B->getMembers().end(),
843 CodeGenRegister::Less());
846 /// Sorting predicate for register classes. This provides a topological
847 /// ordering that arranges all register classes before their sub-classes.
849 /// Register classes with the same registers, spill size, and alignment form a
850 /// clique. They will be ordered alphabetically.
852 static int TopoOrderRC(const void *PA, const void *PB) {
853 const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
854 const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
858 // Order by ascending spill size.
859 if (A->SpillSize < B->SpillSize)
861 if (A->SpillSize > B->SpillSize)
864 // Order by ascending spill alignment.
865 if (A->SpillAlignment < B->SpillAlignment)
867 if (A->SpillAlignment > B->SpillAlignment)
870 // Order by descending set size. Note that the classes' allocation order may
871 // not have been computed yet. The Members set is always vaild.
872 if (A->getMembers().size() > B->getMembers().size())
874 if (A->getMembers().size() < B->getMembers().size())
877 // Finally order by name as a tie breaker.
878 return StringRef(A->getName()).compare(B->getName());
881 std::string CodeGenRegisterClass::getQualifiedName() const {
882 if (Namespace.empty())
885 return Namespace + "::" + getName();
888 // Compute sub-classes of all register classes.
889 // Assume the classes are ordered topologically.
890 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
891 ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
893 // Visit backwards so sub-classes are seen first.
894 for (unsigned rci = RegClasses.size(); rci; --rci) {
895 CodeGenRegisterClass &RC = *RegClasses[rci - 1];
896 RC.SubClasses.resize(RegClasses.size());
897 RC.SubClasses.set(RC.EnumValue);
899 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
900 for (unsigned s = rci; s != RegClasses.size(); ++s) {
901 if (RC.SubClasses.test(s))
903 CodeGenRegisterClass *SubRC = RegClasses[s];
904 if (!testSubClass(&RC, SubRC))
906 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
908 RC.SubClasses |= SubRC->SubClasses;
911 // Sweep up missed clique members. They will be immediately preceding RC.
912 for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
913 RC.SubClasses.set(s - 1);
916 // Compute the SuperClasses lists from the SubClasses vectors.
917 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
918 const BitVector &SC = RegClasses[rci]->getSubClasses();
919 for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
920 if (unsigned(s) == rci)
922 RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
926 // With the class hierarchy in place, let synthesized register classes inherit
927 // properties from their closest super-class. The iteration order here can
928 // propagate properties down multiple levels.
929 for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
930 if (!RegClasses[rci]->getDef())
931 RegClasses[rci]->inheritProperties(RegBank);
935 CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
936 BitVector &Out) const {
937 DenseMap<CodeGenSubRegIndex*,
938 SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
939 FindI = SuperRegClasses.find(SubIdx);
940 if (FindI == SuperRegClasses.end())
942 for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
943 FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
944 Out.set((*I)->EnumValue);
947 // Populate a unique sorted list of units from a register set.
948 void CodeGenRegisterClass::buildRegUnitSet(
949 std::vector<unsigned> &RegUnits) const {
950 std::vector<unsigned> TmpUnits;
951 for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
952 TmpUnits.push_back(*UnitI);
953 std::sort(TmpUnits.begin(), TmpUnits.end());
954 std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
955 std::back_inserter(RegUnits));
958 //===----------------------------------------------------------------------===//
960 //===----------------------------------------------------------------------===//
962 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) {
963 // Configure register Sets to understand register classes and tuples.
964 Sets.addFieldExpander("RegisterClass", "MemberList");
965 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
966 Sets.addExpander("RegisterTuples", new TupleExpander());
968 // Read in the user-defined (named) sub-register indices.
969 // More indices will be synthesized later.
970 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
971 std::sort(SRIs.begin(), SRIs.end(), LessRecord());
972 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
973 getSubRegIdx(SRIs[i]);
974 // Build composite maps from ComposedOf fields.
975 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
976 SubRegIndices[i]->updateComponents(*this);
978 // Read in the register definitions.
979 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
980 std::sort(Regs.begin(), Regs.end(), LessRecord());
981 Registers.reserve(Regs.size());
982 // Assign the enumeration values.
983 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
986 // Expand tuples and number the new registers.
987 std::vector<Record*> Tups =
988 Records.getAllDerivedDefinitions("RegisterTuples");
989 for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
990 const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
991 for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
992 getReg((*TupRegs)[j]);
995 // Now all the registers are known. Build the object graph of explicit
996 // register-register references.
997 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
998 Registers[i]->buildObjectGraph(*this);
1000 // Compute register name map.
1001 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
1002 RegistersByName.GetOrCreateValue(
1003 Registers[i]->TheDef->getValueAsString("AsmName"),
1006 // Precompute all sub-register maps.
1007 // This will create Composite entries for all inferred sub-register indices.
1008 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
1009 Registers[i]->computeSubRegs(*this);
1011 // Infer even more sub-registers by combining leading super-registers.
1012 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
1013 if (Registers[i]->CoveredBySubRegs)
1014 Registers[i]->computeSecondarySubRegs(*this);
1016 // After the sub-register graph is complete, compute the topologically
1017 // ordered SuperRegs list.
1018 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
1019 Registers[i]->computeSuperRegs(*this);
1021 // Native register units are associated with a leaf register. They've all been
1023 NumNativeRegUnits = RegUnits.size();
1025 // Read in register class definitions.
1026 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
1028 PrintFatalError(std::string("No 'RegisterClass' subclasses defined!"));
1030 // Allocate user-defined register classes.
1031 RegClasses.reserve(RCs.size());
1032 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
1033 addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
1035 // Infer missing classes to create a full algebra.
1036 computeInferredRegisterClasses();
1038 // Order register classes topologically and assign enum values.
1039 array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
1040 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
1041 RegClasses[i]->EnumValue = i;
1042 CodeGenRegisterClass::computeSubClasses(*this);
1045 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1047 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1048 CodeGenSubRegIndex *Idx = new CodeGenSubRegIndex(Name, Namespace,
1049 SubRegIndices.size() + 1);
1050 SubRegIndices.push_back(Idx);
1054 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1055 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1058 Idx = new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
1059 SubRegIndices.push_back(Idx);
1063 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1064 CodeGenRegister *&Reg = Def2Reg[Def];
1067 Reg = new CodeGenRegister(Def, Registers.size() + 1);
1068 Registers.push_back(Reg);
1072 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1073 RegClasses.push_back(RC);
1075 if (Record *Def = RC->getDef())
1076 Def2RC.insert(std::make_pair(Def, RC));
1078 // Duplicate classes are rejected by insert().
1079 // That's OK, we only care about the properties handled by CGRC::Key.
1080 CodeGenRegisterClass::Key K(*RC);
1081 Key2RC.insert(std::make_pair(K, RC));
1084 // Create a synthetic sub-class if it is missing.
1085 CodeGenRegisterClass*
1086 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1087 const CodeGenRegister::Set *Members,
1089 // Synthetic sub-class has the same size and alignment as RC.
1090 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
1091 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1092 if (FoundI != Key2RC.end())
1093 return FoundI->second;
1095 // Sub-class doesn't exist, create a new one.
1096 CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(*this, Name, K);
1101 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1102 if (CodeGenRegisterClass *RC = Def2RC[Def])
1105 PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1109 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1110 CodeGenSubRegIndex *B) {
1111 // Look for an existing entry.
1112 CodeGenSubRegIndex *Comp = A->compose(B);
1116 // None exists, synthesize one.
1117 std::string Name = A->getName() + "_then_" + B->getName();
1118 Comp = createSubRegIndex(Name, A->getNamespace());
1119 A->addComposite(B, Comp);
1123 CodeGenSubRegIndex *CodeGenRegBank::
1124 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex*, 8> &Parts) {
1125 assert(Parts.size() > 1 && "Need two parts to concatenate");
1127 // Look for an existing entry.
1128 CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1132 // None exists, synthesize one.
1133 std::string Name = Parts.front()->getName();
1134 for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1136 Name += Parts[i]->getName();
1138 return Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1141 void CodeGenRegBank::computeComposites() {
1142 // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1143 // and many registers will share TopoSigs on regular architectures.
1144 BitVector TopoSigs(getNumTopoSigs());
1146 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1147 CodeGenRegister *Reg1 = Registers[i];
1149 // Skip identical subreg structures already processed.
1150 if (TopoSigs.test(Reg1->getTopoSig()))
1152 TopoSigs.set(Reg1->getTopoSig());
1154 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
1155 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1156 e1 = SRM1.end(); i1 != e1; ++i1) {
1157 CodeGenSubRegIndex *Idx1 = i1->first;
1158 CodeGenRegister *Reg2 = i1->second;
1159 // Ignore identity compositions.
1162 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1163 // Try composing Idx1 with another SubRegIndex.
1164 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1165 e2 = SRM2.end(); i2 != e2; ++i2) {
1166 CodeGenSubRegIndex *Idx2 = i2->first;
1167 CodeGenRegister *Reg3 = i2->second;
1168 // Ignore identity compositions.
1171 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1172 CodeGenSubRegIndex *Idx3 = Reg1->getSubRegIndex(Reg3);
1173 assert(Idx3 && "Sub-register doesn't have an index");
1175 // Conflicting composition? Emit a warning but allow it.
1176 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
1177 PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1178 " and " + Idx2->getQualifiedName() +
1179 " compose ambiguously as " + Prev->getQualifiedName() +
1180 " or " + Idx3->getQualifiedName());
1186 // Compute lane masks. This is similar to register units, but at the
1187 // sub-register index level. Each bit in the lane mask is like a register unit
1188 // class, and two lane masks will have a bit in common if two sub-register
1189 // indices overlap in some register.
1191 // Conservatively share a lane mask bit if two sub-register indices overlap in
1192 // some registers, but not in others. That shouldn't happen a lot.
1193 void CodeGenRegBank::computeSubRegIndexLaneMasks() {
1194 // First assign individual bits to all the leaf indices.
1196 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i) {
1197 CodeGenSubRegIndex *Idx = SubRegIndices[i];
1198 if (Idx->getComposites().empty()) {
1199 Idx->LaneMask = 1u << Bit;
1200 // Share bit 31 in the unlikely case there are more than 32 leafs.
1201 if (Bit < 31) ++Bit;
1207 // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1208 // by the sub-register graph? This doesn't occur in any known targets.
1210 // Inherit lanes from composites.
1211 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
1212 SubRegIndices[i]->computeLaneMask();
1216 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1217 // the transitive closure of the union of overlapping register
1218 // classes. Together, the UberRegSets form a partition of the registers. If we
1219 // consider overlapping register classes to be connected, then each UberRegSet
1220 // is a set of connected components.
1222 // An UberRegSet will likely be a horizontal slice of register names of
1223 // the same width. Nontrivial subregisters should then be in a separate
1224 // UberRegSet. But this property isn't required for valid computation of
1225 // register unit weights.
1227 // A Weight field caches the max per-register unit weight in each UberRegSet.
1229 // A set of SingularDeterminants flags single units of some register in this set
1230 // for which the unit weight equals the set weight. These units should not have
1231 // their weight increased.
1233 CodeGenRegister::Set Regs;
1235 CodeGenRegister::RegUnitList SingularDeterminants;
1237 UberRegSet(): Weight(0) {}
1241 // Partition registers into UberRegSets, where each set is the transitive
1242 // closure of the union of overlapping register classes.
1244 // UberRegSets[0] is a special non-allocatable set.
1245 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1246 std::vector<UberRegSet*> &RegSets,
1247 CodeGenRegBank &RegBank) {
1249 const std::vector<CodeGenRegister*> &Registers = RegBank.getRegisters();
1251 // The Register EnumValue is one greater than its index into Registers.
1252 assert(Registers.size() == Registers[Registers.size()-1]->EnumValue &&
1253 "register enum value mismatch");
1255 // For simplicitly make the SetID the same as EnumValue.
1256 IntEqClasses UberSetIDs(Registers.size()+1);
1257 std::set<unsigned> AllocatableRegs;
1258 for (unsigned i = 0, e = RegBank.getRegClasses().size(); i != e; ++i) {
1260 CodeGenRegisterClass *RegClass = RegBank.getRegClasses()[i];
1261 if (!RegClass->Allocatable)
1264 const CodeGenRegister::Set &Regs = RegClass->getMembers();
1268 unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1269 assert(USetID && "register number 0 is invalid");
1271 AllocatableRegs.insert((*Regs.begin())->EnumValue);
1272 for (CodeGenRegister::Set::const_iterator I = llvm::next(Regs.begin()),
1273 E = Regs.end(); I != E; ++I) {
1274 AllocatableRegs.insert((*I)->EnumValue);
1275 UberSetIDs.join(USetID, (*I)->EnumValue);
1278 // Combine non-allocatable regs.
1279 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1280 unsigned RegNum = Registers[i]->EnumValue;
1281 if (AllocatableRegs.count(RegNum))
1284 UberSetIDs.join(0, RegNum);
1286 UberSetIDs.compress();
1288 // Make the first UberSet a special unallocatable set.
1289 unsigned ZeroID = UberSetIDs[0];
1291 // Insert Registers into the UberSets formed by union-find.
1292 // Do not resize after this.
1293 UberSets.resize(UberSetIDs.getNumClasses());
1294 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1295 const CodeGenRegister *Reg = Registers[i];
1296 unsigned USetID = UberSetIDs[Reg->EnumValue];
1299 else if (USetID == ZeroID)
1302 UberRegSet *USet = &UberSets[USetID];
1303 USet->Regs.insert(Reg);
1308 // Recompute each UberSet weight after changing unit weights.
1309 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1310 CodeGenRegBank &RegBank) {
1311 // Skip the first unallocatable set.
1312 for (std::vector<UberRegSet>::iterator I = llvm::next(UberSets.begin()),
1313 E = UberSets.end(); I != E; ++I) {
1315 // Initialize all unit weights in this set, and remember the max units/reg.
1316 const CodeGenRegister *Reg = 0;
1317 unsigned MaxWeight = 0, Weight = 0;
1318 for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1319 if (Reg != UnitI.getReg()) {
1320 if (Weight > MaxWeight)
1322 Reg = UnitI.getReg();
1325 unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1328 RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1332 if (Weight > MaxWeight)
1335 // Update the set weight.
1336 I->Weight = MaxWeight;
1338 // Find singular determinants.
1339 for (CodeGenRegister::Set::iterator RegI = I->Regs.begin(),
1340 RegE = I->Regs.end(); RegI != RegE; ++RegI) {
1341 if ((*RegI)->getRegUnits().size() == 1
1342 && (*RegI)->getWeight(RegBank) == I->Weight)
1343 mergeRegUnits(I->SingularDeterminants, (*RegI)->getRegUnits());
1348 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1349 // a register and its subregisters so that they have the same weight as their
1350 // UberSet. Self-recursion processes the subregister tree in postorder so
1351 // subregisters are normalized first.
1354 // - creates new adopted register units
1355 // - causes superregisters to inherit adopted units
1356 // - increases the weight of "singular" units
1357 // - induces recomputation of UberWeights.
1358 static bool normalizeWeight(CodeGenRegister *Reg,
1359 std::vector<UberRegSet> &UberSets,
1360 std::vector<UberRegSet*> &RegSets,
1361 std::set<unsigned> &NormalRegs,
1362 CodeGenRegister::RegUnitList &NormalUnits,
1363 CodeGenRegBank &RegBank) {
1364 bool Changed = false;
1365 if (!NormalRegs.insert(Reg->EnumValue).second)
1368 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1369 for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1370 SRE = SRM.end(); SRI != SRE; ++SRI) {
1371 if (SRI->second == Reg)
1372 continue; // self-cycles happen
1374 Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1375 NormalRegs, NormalUnits, RegBank);
1377 // Postorder register normalization.
1379 // Inherit register units newly adopted by subregisters.
1380 if (Reg->inheritRegUnits(RegBank))
1381 computeUberWeights(UberSets, RegBank);
1383 // Check if this register is too skinny for its UberRegSet.
1384 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1386 unsigned RegWeight = Reg->getWeight(RegBank);
1387 if (UberSet->Weight > RegWeight) {
1388 // A register unit's weight can be adjusted only if it is the singular unit
1389 // for this register, has not been used to normalize a subregister's set,
1390 // and has not already been used to singularly determine this UberRegSet.
1391 unsigned AdjustUnit = Reg->getRegUnits().front();
1392 if (Reg->getRegUnits().size() != 1
1393 || hasRegUnit(NormalUnits, AdjustUnit)
1394 || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1395 // We don't have an adjustable unit, so adopt a new one.
1396 AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1397 Reg->adoptRegUnit(AdjustUnit);
1398 // Adopting a unit does not immediately require recomputing set weights.
1401 // Adjust the existing single unit.
1402 RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1403 // The unit may be shared among sets and registers within this set.
1404 computeUberWeights(UberSets, RegBank);
1409 // Mark these units normalized so superregisters can't change their weights.
1410 mergeRegUnits(NormalUnits, Reg->getRegUnits());
1415 // Compute a weight for each register unit created during getSubRegs.
1417 // The goal is that two registers in the same class will have the same weight,
1418 // where each register's weight is defined as sum of its units' weights.
1419 void CodeGenRegBank::computeRegUnitWeights() {
1420 std::vector<UberRegSet> UberSets;
1421 std::vector<UberRegSet*> RegSets(Registers.size());
1422 computeUberSets(UberSets, RegSets, *this);
1423 // UberSets and RegSets are now immutable.
1425 computeUberWeights(UberSets, *this);
1427 // Iterate over each Register, normalizing the unit weights until reaching
1429 unsigned NumIters = 0;
1430 for (bool Changed = true; Changed; ++NumIters) {
1431 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1433 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1434 CodeGenRegister::RegUnitList NormalUnits;
1435 std::set<unsigned> NormalRegs;
1436 Changed |= normalizeWeight(Registers[i], UberSets, RegSets,
1437 NormalRegs, NormalUnits, *this);
1442 // Find a set in UniqueSets with the same elements as Set.
1443 // Return an iterator into UniqueSets.
1444 static std::vector<RegUnitSet>::const_iterator
1445 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1446 const RegUnitSet &Set) {
1447 std::vector<RegUnitSet>::const_iterator
1448 I = UniqueSets.begin(), E = UniqueSets.end();
1450 if (I->Units == Set.Units)
1456 // Return true if the RUSubSet is a subset of RUSuperSet.
1457 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1458 const std::vector<unsigned> &RUSuperSet) {
1459 return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1460 RUSubSet.begin(), RUSubSet.end());
1463 // Iteratively prune unit sets.
1464 void CodeGenRegBank::pruneUnitSets() {
1465 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1467 // Form an equivalence class of UnitSets with no significant difference.
1468 std::vector<unsigned> SuperSetIDs;
1469 for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1470 SubIdx != EndIdx; ++SubIdx) {
1471 const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1472 unsigned SuperIdx = 0;
1473 for (; SuperIdx != EndIdx; ++SuperIdx) {
1474 if (SuperIdx == SubIdx)
1477 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1478 if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1479 && (SubSet.Units.size() + 3 > SuperSet.Units.size())) {
1483 if (SuperIdx == EndIdx)
1484 SuperSetIDs.push_back(SubIdx);
1486 // Populate PrunedUnitSets with each equivalence class's superset.
1487 std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1488 for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1489 unsigned SuperIdx = SuperSetIDs[i];
1490 PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1491 PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1493 RegUnitSets.swap(PrunedUnitSets);
1496 // Create a RegUnitSet for each RegClass that contains all units in the class
1497 // including adopted units that are necessary to model register pressure. Then
1498 // iteratively compute RegUnitSets such that the union of any two overlapping
1499 // RegUnitSets is repreresented.
1501 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1502 // RegUnitSet that is a superset of that RegUnitClass.
1503 void CodeGenRegBank::computeRegUnitSets() {
1505 // Compute a unique RegUnitSet for each RegClass.
1506 const ArrayRef<CodeGenRegisterClass*> &RegClasses = getRegClasses();
1507 unsigned NumRegClasses = RegClasses.size();
1508 for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1509 if (!RegClasses[RCIdx]->Allocatable)
1512 // Speculatively grow the RegUnitSets to hold the new set.
1513 RegUnitSets.resize(RegUnitSets.size() + 1);
1514 RegUnitSets.back().Name = RegClasses[RCIdx]->getName();
1516 // Compute a sorted list of units in this class.
1517 RegClasses[RCIdx]->buildRegUnitSet(RegUnitSets.back().Units);
1519 // Find an existing RegUnitSet.
1520 std::vector<RegUnitSet>::const_iterator SetI =
1521 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1522 if (SetI != llvm::prior(RegUnitSets.end()))
1523 RegUnitSets.pop_back();
1526 // Iteratively prune unit sets.
1529 // Iterate over all unit sets, including new ones added by this loop.
1530 unsigned NumRegUnitSubSets = RegUnitSets.size();
1531 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1532 // In theory, this is combinatorial. In practice, it needs to be bounded
1533 // by a small number of sets for regpressure to be efficient.
1534 // If the assert is hit, we need to implement pruning.
1535 assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1537 // Compare new sets with all original classes.
1538 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1539 SearchIdx != EndIdx; ++SearchIdx) {
1540 std::set<unsigned> Intersection;
1541 std::set_intersection(RegUnitSets[Idx].Units.begin(),
1542 RegUnitSets[Idx].Units.end(),
1543 RegUnitSets[SearchIdx].Units.begin(),
1544 RegUnitSets[SearchIdx].Units.end(),
1545 std::inserter(Intersection, Intersection.begin()));
1546 if (Intersection.empty())
1549 // Speculatively grow the RegUnitSets to hold the new set.
1550 RegUnitSets.resize(RegUnitSets.size() + 1);
1551 RegUnitSets.back().Name =
1552 RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1554 std::set_union(RegUnitSets[Idx].Units.begin(),
1555 RegUnitSets[Idx].Units.end(),
1556 RegUnitSets[SearchIdx].Units.begin(),
1557 RegUnitSets[SearchIdx].Units.end(),
1558 std::inserter(RegUnitSets.back().Units,
1559 RegUnitSets.back().Units.begin()));
1561 // Find an existing RegUnitSet, or add the union to the unique sets.
1562 std::vector<RegUnitSet>::const_iterator SetI =
1563 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1564 if (SetI != llvm::prior(RegUnitSets.end()))
1565 RegUnitSets.pop_back();
1569 // Iteratively prune unit sets after inferring supersets.
1572 // For each register class, list the UnitSets that are supersets.
1573 RegClassUnitSets.resize(NumRegClasses);
1574 for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1575 if (!RegClasses[RCIdx]->Allocatable)
1578 // Recompute the sorted list of units in this class.
1579 std::vector<unsigned> RegUnits;
1580 RegClasses[RCIdx]->buildRegUnitSet(RegUnits);
1582 // Don't increase pressure for unallocatable regclasses.
1583 if (RegUnits.empty())
1586 // Find all supersets.
1587 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1588 USIdx != USEnd; ++USIdx) {
1589 if (isRegUnitSubSet(RegUnits, RegUnitSets[USIdx].Units))
1590 RegClassUnitSets[RCIdx].push_back(USIdx);
1592 assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1595 // For each register unit, ensure that we have the list of UnitSets that
1596 // contain the unit. Normally, this matches an existing list of UnitSets for a
1597 // register class. If not, we create a new entry in RegClassUnitSets as a
1598 // "fake" register class.
1599 for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
1600 UnitIdx < UnitEnd; ++UnitIdx) {
1601 std::vector<unsigned> RUSets;
1602 for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
1603 RegUnitSet &RUSet = RegUnitSets[i];
1604 if (std::find(RUSet.Units.begin(), RUSet.Units.end(), UnitIdx)
1605 == RUSet.Units.end())
1607 RUSets.push_back(i);
1609 unsigned RCUnitSetsIdx = 0;
1610 for (unsigned e = RegClassUnitSets.size();
1611 RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
1612 if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
1616 RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
1617 if (RCUnitSetsIdx == RegClassUnitSets.size()) {
1618 // Create a new list of UnitSets as a "fake" register class.
1619 RegClassUnitSets.resize(RCUnitSetsIdx + 1);
1620 RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
1625 void CodeGenRegBank::computeDerivedInfo() {
1626 computeComposites();
1627 computeSubRegIndexLaneMasks();
1629 // Compute a weight for each register unit created during getSubRegs.
1630 // This may create adopted register units (with unit # >= NumNativeRegUnits).
1631 computeRegUnitWeights();
1633 // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1634 // supersets for the union of overlapping sets.
1635 computeRegUnitSets();
1639 // Synthesize missing register class intersections.
1641 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1642 // returns a maximal register class for all X.
1644 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1645 for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
1646 CodeGenRegisterClass *RC1 = RC;
1647 CodeGenRegisterClass *RC2 = RegClasses[rci];
1651 // Compute the set intersection of RC1 and RC2.
1652 const CodeGenRegister::Set &Memb1 = RC1->getMembers();
1653 const CodeGenRegister::Set &Memb2 = RC2->getMembers();
1654 CodeGenRegister::Set Intersection;
1655 std::set_intersection(Memb1.begin(), Memb1.end(),
1656 Memb2.begin(), Memb2.end(),
1657 std::inserter(Intersection, Intersection.begin()),
1658 CodeGenRegister::Less());
1660 // Skip disjoint class pairs.
1661 if (Intersection.empty())
1664 // If RC1 and RC2 have different spill sizes or alignments, use the
1665 // larger size for sub-classing. If they are equal, prefer RC1.
1666 if (RC2->SpillSize > RC1->SpillSize ||
1667 (RC2->SpillSize == RC1->SpillSize &&
1668 RC2->SpillAlignment > RC1->SpillAlignment))
1669 std::swap(RC1, RC2);
1671 getOrCreateSubClass(RC1, &Intersection,
1672 RC1->getName() + "_and_" + RC2->getName());
1677 // Synthesize missing sub-classes for getSubClassWithSubReg().
1679 // Make sure that the set of registers in RC with a given SubIdx sub-register
1680 // form a register class. Update RC->SubClassWithSubReg.
1682 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1683 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1684 typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
1685 CodeGenSubRegIndex::Less> SubReg2SetMap;
1687 // Compute the set of registers supporting each SubRegIndex.
1688 SubReg2SetMap SRSets;
1689 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1690 RE = RC->getMembers().end(); RI != RE; ++RI) {
1691 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
1692 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1693 E = SRM.end(); I != E; ++I)
1694 SRSets[I->first].insert(*RI);
1697 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
1698 // numerical order to visit synthetic indices last.
1699 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1700 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1701 SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
1702 // Unsupported SubRegIndex. Skip it.
1703 if (I == SRSets.end())
1705 // In most cases, all RC registers support the SubRegIndex.
1706 if (I->second.size() == RC->getMembers().size()) {
1707 RC->setSubClassWithSubReg(SubIdx, RC);
1710 // This is a real subset. See if we have a matching class.
1711 CodeGenRegisterClass *SubRC =
1712 getOrCreateSubClass(RC, &I->second,
1713 RC->getName() + "_with_" + I->first->getName());
1714 RC->setSubClassWithSubReg(SubIdx, SubRC);
1719 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1721 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1722 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1725 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1726 unsigned FirstSubRegRC) {
1727 SmallVector<std::pair<const CodeGenRegister*,
1728 const CodeGenRegister*>, 16> SSPairs;
1729 BitVector TopoSigs(getNumTopoSigs());
1731 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1732 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1733 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1734 // Skip indexes that aren't fully supported by RC's registers. This was
1735 // computed by inferSubClassWithSubReg() above which should have been
1737 if (RC->getSubClassWithSubReg(SubIdx) != RC)
1740 // Build list of (Super, Sub) pairs for this SubIdx.
1743 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1744 RE = RC->getMembers().end(); RI != RE; ++RI) {
1745 const CodeGenRegister *Super = *RI;
1746 const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
1747 assert(Sub && "Missing sub-register");
1748 SSPairs.push_back(std::make_pair(Super, Sub));
1749 TopoSigs.set(Sub->getTopoSig());
1752 // Iterate over sub-register class candidates. Ignore classes created by
1753 // this loop. They will never be useful.
1754 for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
1756 CodeGenRegisterClass *SubRC = RegClasses[rci];
1757 // Topological shortcut: SubRC members have the wrong shape.
1758 if (!TopoSigs.anyCommon(SubRC->getTopoSigs()))
1760 // Compute the subset of RC that maps into SubRC.
1761 CodeGenRegister::Set SubSet;
1762 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1763 if (SubRC->contains(SSPairs[i].second))
1764 SubSet.insert(SSPairs[i].first);
1767 // RC injects completely into SubRC.
1768 if (SubSet.size() == SSPairs.size()) {
1769 SubRC->addSuperRegClass(SubIdx, RC);
1772 // Only a subset of RC maps into SubRC. Make sure it is represented by a
1774 getOrCreateSubClass(RC, &SubSet, RC->getName() +
1775 "_with_" + SubIdx->getName() +
1776 "_in_" + SubRC->getName());
1783 // Infer missing register classes.
1785 void CodeGenRegBank::computeInferredRegisterClasses() {
1786 // When this function is called, the register classes have not been sorted
1787 // and assigned EnumValues yet. That means getSubClasses(),
1788 // getSuperClasses(), and hasSubClass() functions are defunct.
1789 unsigned FirstNewRC = RegClasses.size();
1791 // Visit all register classes, including the ones being added by the loop.
1792 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
1793 CodeGenRegisterClass *RC = RegClasses[rci];
1795 // Synthesize answers for getSubClassWithSubReg().
1796 inferSubClassWithSubReg(RC);
1798 // Synthesize answers for getCommonSubClass().
1799 inferCommonSubClass(RC);
1801 // Synthesize answers for getMatchingSuperRegClass().
1802 inferMatchingSuperRegClass(RC);
1804 // New register classes are created while this loop is running, and we need
1805 // to visit all of them. I particular, inferMatchingSuperRegClass needs
1806 // to match old super-register classes with sub-register classes created
1807 // after inferMatchingSuperRegClass was called. At this point,
1808 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
1809 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
1810 if (rci + 1 == FirstNewRC) {
1811 unsigned NextNewRC = RegClasses.size();
1812 for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
1813 inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
1814 FirstNewRC = NextNewRC;
1819 /// getRegisterClassForRegister - Find the register class that contains the
1820 /// specified physical register. If the register is not in a register class,
1821 /// return null. If the register is in multiple classes, and the classes have a
1822 /// superset-subset relationship and the same set of types, return the
1823 /// superclass. Otherwise return null.
1824 const CodeGenRegisterClass*
1825 CodeGenRegBank::getRegClassForRegister(Record *R) {
1826 const CodeGenRegister *Reg = getReg(R);
1827 ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
1828 const CodeGenRegisterClass *FoundRC = 0;
1829 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
1830 const CodeGenRegisterClass &RC = *RCs[i];
1831 if (!RC.contains(Reg))
1834 // If this is the first class that contains the register,
1835 // make a note of it and go on to the next class.
1841 // If a register's classes have different types, return null.
1842 if (RC.getValueTypes() != FoundRC->getValueTypes())
1845 // Check to see if the previously found class that contains
1846 // the register is a subclass of the current class. If so,
1847 // prefer the superclass.
1848 if (RC.hasSubClass(FoundRC)) {
1853 // Check to see if the previously found class that contains
1854 // the register is a superclass of the current class. If so,
1855 // prefer the superclass.
1856 if (FoundRC->hasSubClass(&RC))
1859 // Multiple classes, and neither is a superclass of the other.
1866 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1867 SetVector<const CodeGenRegister*> Set;
1869 // First add Regs with all sub-registers.
1870 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1871 CodeGenRegister *Reg = getReg(Regs[i]);
1872 if (Set.insert(Reg))
1873 // Reg is new, add all sub-registers.
1874 // The pre-ordering is not important here.
1875 Reg->addSubRegsPreOrder(Set, *this);
1878 // Second, find all super-registers that are completely covered by the set.
1879 for (unsigned i = 0; i != Set.size(); ++i) {
1880 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1881 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1882 const CodeGenRegister *Super = SR[j];
1883 if (!Super->CoveredBySubRegs || Set.count(Super))
1885 // This new super-register is covered by its sub-registers.
1886 bool AllSubsInSet = true;
1887 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1888 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1889 E = SRM.end(); I != E; ++I)
1890 if (!Set.count(I->second)) {
1891 AllSubsInSet = false;
1894 // All sub-registers in Set, add Super as well.
1895 // We will visit Super later to recheck its super-registers.
1901 // Convert to BitVector.
1902 BitVector BV(Registers.size() + 1);
1903 for (unsigned i = 0, e = Set.size(); i != e; ++i)
1904 BV.set(Set[i]->EnumValue);