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/TableGen/Error.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringExtras.h"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
33 std::string CodeGenSubRegIndex::getNamespace() const {
34 if (TheDef->getValue("Namespace"))
35 return TheDef->getValueAsString("Namespace");
40 const std::string &CodeGenSubRegIndex::getName() const {
41 return TheDef->getName();
44 std::string CodeGenSubRegIndex::getQualifiedName() const {
45 std::string N = getNamespace();
52 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
53 std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
56 if (Comps.size() != 2)
57 throw TGError(TheDef->getLoc(), "ComposedOf must have exactly two entries");
58 CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
59 CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
60 CodeGenSubRegIndex *X = A->addComposite(B, this);
62 throw TGError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
65 void CodeGenSubRegIndex::cleanComposites() {
66 // Clean out redundant mappings of the form this+X -> X.
67 for (CompMap::iterator i = Composed.begin(), e = Composed.end(); i != e;) {
68 CompMap::iterator j = i;
70 if (j->first == j->second)
75 //===----------------------------------------------------------------------===//
77 //===----------------------------------------------------------------------===//
79 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
82 CostPerUse(R->getValueAsInt("CostPerUse")),
83 CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
84 SubRegsComplete(false)
87 const std::string &CodeGenRegister::getName() const {
88 return TheDef->getName();
91 // Merge two RegUnitLists maintaining the order and removing duplicates.
92 // Overwrites MergedRU in the process.
93 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
94 const CodeGenRegister::RegUnitList &RRU) {
95 CodeGenRegister::RegUnitList LRU = MergedRU;
97 std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(),
98 std::back_inserter(MergedRU));
101 const CodeGenRegister::SubRegMap &
102 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
103 // Only compute this map once.
106 SubRegsComplete = true;
108 std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
109 std::vector<Record*> IdxList = TheDef->getValueAsListOfDefs("SubRegIndices");
110 if (SubList.size() != IdxList.size())
111 throw TGError(TheDef->getLoc(), "Register " + getName() +
112 " SubRegIndices doesn't match SubRegs");
114 // First insert the direct subregs and make sure they are fully indexed.
115 SmallVector<CodeGenSubRegIndex*, 8> Indices;
116 for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
117 CodeGenRegister *SR = RegBank.getReg(SubList[i]);
118 CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxList[i]);
119 Indices.push_back(Idx);
120 if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
121 throw TGError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
122 " appears twice in Register " + getName());
125 // Keep track of inherited subregs and how they can be reached.
126 SmallPtrSet<CodeGenRegister*, 8> Orphans;
128 // Clone inherited subregs and place duplicate entries in Orphans.
129 // Here the order is important - earlier subregs take precedence.
130 for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
131 CodeGenRegister *SR = RegBank.getReg(SubList[i]);
132 const SubRegMap &Map = SR->getSubRegs(RegBank);
134 // Add this as a super-register of SR now all sub-registers are in the list.
135 // This creates a topological ordering, the exact order depends on the
136 // order getSubRegs is called on all registers.
137 SR->SuperRegs.push_back(this);
139 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
141 if (!SubRegs.insert(*SI).second)
142 Orphans.insert(SI->second);
144 // Noop sub-register indexes are possible, so avoid duplicates.
145 if (SI->second != SR)
146 SI->second->SuperRegs.push_back(this);
150 // Expand any composed subreg indices.
151 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
152 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
153 // expanded subreg indices recursively.
154 for (unsigned i = 0; i != Indices.size(); ++i) {
155 CodeGenSubRegIndex *Idx = Indices[i];
156 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
157 CodeGenRegister *SR = SubRegs[Idx];
158 const SubRegMap &Map = SR->getSubRegs(RegBank);
160 // Look at the possible compositions of Idx.
161 // They may not all be supported by SR.
162 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
163 E = Comps.end(); I != E; ++I) {
164 SubRegMap::const_iterator SRI = Map.find(I->first);
165 if (SRI == Map.end())
166 continue; // Idx + I->first doesn't exist in SR.
167 // Add I->second as a name for the subreg SRI->second, assuming it is
168 // orphaned, and the name isn't already used for something else.
169 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
171 // We found a new name for the orphaned sub-register.
172 SubRegs.insert(std::make_pair(I->second, SRI->second));
173 Indices.push_back(I->second);
177 // Process the composites.
178 ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
179 for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
180 DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
182 throw TGError(TheDef->getLoc(), "Invalid dag '" +
183 Comps->getElement(i)->getAsString() +
184 "' in CompositeIndices");
185 DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
186 if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
187 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
189 CodeGenSubRegIndex *BaseIdx = RegBank.getSubRegIdx(BaseIdxInit->getDef());
191 // Resolve list of subreg indices into R2.
192 CodeGenRegister *R2 = this;
193 for (DagInit::const_arg_iterator di = Pat->arg_begin(),
194 de = Pat->arg_end(); di != de; ++di) {
195 DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
196 if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
197 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
199 CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxInit->getDef());
200 const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
201 SubRegMap::const_iterator ni = R2Subs.find(Idx);
202 if (ni == R2Subs.end())
203 throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
204 " refers to bad index in " + R2->getName());
208 // Insert composite index. Allow overriding inherited indices etc.
209 SubRegs[BaseIdx] = R2;
211 // R2 is no longer an orphan.
215 // Now Orphans contains the inherited subregisters without a direct index.
216 // Create inferred indexes for all missing entries.
217 // Work backwards in the Indices vector in order to compose subregs bottom-up.
218 // Consider this subreg sequence:
220 // qsub_1 -> dsub_0 -> ssub_0
222 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
223 // can be reached in two different ways:
228 // We pick the latter composition because another register may have [dsub_0,
229 // dsub_1, dsub_2] subregs without neccessarily having a qsub_1 subreg. The
230 // dsub_2 -> ssub_0 composition can be shared.
231 while (!Indices.empty() && !Orphans.empty()) {
232 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
233 CodeGenRegister *SR = SubRegs[Idx];
234 const SubRegMap &Map = SR->getSubRegs(RegBank);
235 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
237 if (Orphans.erase(SI->second))
238 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
241 // Initialize RegUnitList. A register with no subregisters creates its own
242 // unit. Otherwise, it inherits all its subregister's units. Because
243 // getSubRegs is called recursively, this processes the register hierarchy in
246 // TODO: We currently assume all register units correspond to a named "leaf"
247 // register. We should also unify register units for ad-hoc register
248 // aliases. This can be done by iteratively merging units for aliasing
249 // registers using a worklist.
250 assert(RegUnits.empty() && "Should only initialize RegUnits once");
251 if (SubRegs.empty()) {
252 RegUnits.push_back(RegBank.newRegUnit());
255 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
257 // Strangely a register may have itself as a subreg (self-cycle) e.g. XMM.
258 CodeGenRegister *SR = I->second;
260 if (RegUnits.empty())
261 RegUnits.push_back(RegBank.newRegUnit());
264 // Merge the subregister's units into this register's RegUnits.
265 mergeRegUnits(RegUnits, SR->RegUnits);
272 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
273 CodeGenRegBank &RegBank) const {
274 assert(SubRegsComplete && "Must precompute sub-registers");
275 std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
276 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
277 CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(Indices[i]);
278 CodeGenRegister *SR = SubRegs.find(Idx)->second;
280 SR->addSubRegsPreOrder(OSet, RegBank);
284 //===----------------------------------------------------------------------===//
286 //===----------------------------------------------------------------------===//
288 // A RegisterTuples def is used to generate pseudo-registers from lists of
289 // sub-registers. We provide a SetTheory expander class that returns the new
292 struct TupleExpander : SetTheory::Expander {
293 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
294 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
295 unsigned Dim = Indices.size();
296 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
297 if (Dim != SubRegs->getSize())
298 throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
300 throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
302 // Evaluate the sub-register lists to be zipped.
303 unsigned Length = ~0u;
304 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
305 for (unsigned i = 0; i != Dim; ++i) {
306 ST.evaluate(SubRegs->getElement(i), Lists[i]);
307 Length = std::min(Length, unsigned(Lists[i].size()));
313 // Precompute some types.
314 Record *RegisterCl = Def->getRecords().getClass("Register");
315 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
316 StringInit *BlankName = StringInit::get("");
319 for (unsigned n = 0; n != Length; ++n) {
321 Record *Proto = Lists[0][n];
322 std::vector<Init*> Tuple;
323 unsigned CostPerUse = 0;
324 for (unsigned i = 0; i != Dim; ++i) {
325 Record *Reg = Lists[i][n];
327 Name += Reg->getName();
328 Tuple.push_back(DefInit::get(Reg));
329 CostPerUse = std::max(CostPerUse,
330 unsigned(Reg->getValueAsInt("CostPerUse")));
333 // Create a new Record representing the synthesized register. This record
334 // is only for consumption by CodeGenRegister, it is not added to the
336 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
339 // Copy Proto super-classes.
340 for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
341 NewReg->addSuperClass(Proto->getSuperClasses()[i]);
343 // Copy Proto fields.
344 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
345 RecordVal RV = Proto->getValues()[i];
347 // Skip existing fields, like NAME.
348 if (NewReg->getValue(RV.getNameInit()))
351 StringRef Field = RV.getName();
353 // Replace the sub-register list with Tuple.
354 if (Field == "SubRegs")
355 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
357 // Provide a blank AsmName. MC hacks are required anyway.
358 if (Field == "AsmName")
359 RV.setValue(BlankName);
361 // CostPerUse is aggregated from all Tuple members.
362 if (Field == "CostPerUse")
363 RV.setValue(IntInit::get(CostPerUse));
365 // Composite registers are always covered by sub-registers.
366 if (Field == "CoveredBySubRegs")
367 RV.setValue(BitInit::get(true));
369 // Copy fields from the RegisterTuples def.
370 if (Field == "SubRegIndices" ||
371 Field == "CompositeIndices") {
372 NewReg->addValue(*Def->getValue(Field));
376 // Some fields get their default uninitialized value.
377 if (Field == "DwarfNumbers" ||
378 Field == "DwarfAlias" ||
379 Field == "Aliases") {
380 if (const RecordVal *DefRV = RegisterCl->getValue(Field))
381 NewReg->addValue(*DefRV);
385 // Everything else is copied from Proto.
386 NewReg->addValue(RV);
393 //===----------------------------------------------------------------------===//
394 // CodeGenRegisterClass
395 //===----------------------------------------------------------------------===//
397 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
398 : TheDef(R), Name(R->getName()), EnumValue(-1) {
399 // Rename anonymous register classes.
400 if (R->getName().size() > 9 && R->getName()[9] == '.') {
401 static unsigned AnonCounter = 0;
402 R->setName("AnonRegClass_"+utostr(AnonCounter++));
405 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
406 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
407 Record *Type = TypeList[i];
408 if (!Type->isSubClassOf("ValueType"))
409 throw "RegTypes list member '" + Type->getName() +
410 "' does not derive from the ValueType class!";
411 VTs.push_back(getValueType(Type));
413 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
415 // Allocation order 0 is the full set. AltOrders provides others.
416 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
417 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
418 Orders.resize(1 + AltOrders->size());
420 // Default allocation order always contains all registers.
421 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
422 Orders[0].push_back((*Elements)[i]);
423 Members.insert(RegBank.getReg((*Elements)[i]));
426 // Alternative allocation orders may be subsets.
427 SetTheory::RecSet Order;
428 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
429 RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
430 Orders[1 + i].append(Order.begin(), Order.end());
431 // Verify that all altorder members are regclass members.
432 while (!Order.empty()) {
433 CodeGenRegister *Reg = RegBank.getReg(Order.back());
436 throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
437 " is not a class member");
441 // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
442 ListInit *SRC = R->getValueAsListInit("SubRegClasses");
443 for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
444 DagInit *DAG = dynamic_cast<DagInit*>(*i);
445 if (!DAG) throw "SubRegClasses must contain DAGs";
446 DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
448 if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
449 throw "Operator '" + DAG->getOperator()->getAsString() +
450 "' in SubRegClasses is not a RegisterClass";
451 // Iterate over args, all SubRegIndex instances.
452 for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
454 DefInit *Idx = dynamic_cast<DefInit*>(*ai);
456 if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
457 throw "Argument '" + (*ai)->getAsString() +
458 "' in SubRegClasses is not a SubRegIndex";
459 if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
460 throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
464 // Allow targets to override the size in bits of the RegisterClass.
465 unsigned Size = R->getValueAsInt("Size");
467 Namespace = R->getValueAsString("Namespace");
468 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
469 SpillAlignment = R->getValueAsInt("Alignment");
470 CopyCost = R->getValueAsInt("CopyCost");
471 Allocatable = R->getValueAsBit("isAllocatable");
472 AltOrderSelect = R->getValueAsString("AltOrderSelect");
475 // Create an inferred register class that was missing from the .td files.
476 // Most properties will be inherited from the closest super-class after the
477 // class structure has been computed.
478 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props)
479 : Members(*Props.Members),
483 SpillSize(Props.SpillSize),
484 SpillAlignment(Props.SpillAlignment),
489 // Compute inherited propertied for a synthesized register class.
490 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
491 assert(!getDef() && "Only synthesized classes can inherit properties");
492 assert(!SuperClasses.empty() && "Synthesized class without super class");
494 // The last super-class is the smallest one.
495 CodeGenRegisterClass &Super = *SuperClasses.back();
497 // Most properties are copied directly.
498 // Exceptions are members, size, and alignment
499 Namespace = Super.Namespace;
501 CopyCost = Super.CopyCost;
502 Allocatable = Super.Allocatable;
503 AltOrderSelect = Super.AltOrderSelect;
505 // Copy all allocation orders, filter out foreign registers from the larger
507 Orders.resize(Super.Orders.size());
508 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
509 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
510 if (contains(RegBank.getReg(Super.Orders[i][j])))
511 Orders[i].push_back(Super.Orders[i][j]);
514 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
515 return Members.count(Reg);
519 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
520 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
521 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
522 E = K.Members->end(); I != E; ++I)
523 OS << ", " << (*I)->getName();
528 // This is a simple lexicographical order that can be used to search for sets.
529 // It is not the same as the topological order provided by TopoOrderRC.
530 bool CodeGenRegisterClass::Key::
531 operator<(const CodeGenRegisterClass::Key &B) const {
532 assert(Members && B.Members);
533 if (*Members != *B.Members)
534 return *Members < *B.Members;
535 if (SpillSize != B.SpillSize)
536 return SpillSize < B.SpillSize;
537 return SpillAlignment < B.SpillAlignment;
540 // Returns true if RC is a strict subclass.
541 // RC is a sub-class of this class if it is a valid replacement for any
542 // instruction operand where a register of this classis required. It must
543 // satisfy these conditions:
545 // 1. All RC registers are also in this.
546 // 2. The RC spill size must not be smaller than our spill size.
547 // 3. RC spill alignment must be compatible with ours.
549 static bool testSubClass(const CodeGenRegisterClass *A,
550 const CodeGenRegisterClass *B) {
551 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
552 A->SpillSize <= B->SpillSize &&
553 std::includes(A->getMembers().begin(), A->getMembers().end(),
554 B->getMembers().begin(), B->getMembers().end(),
555 CodeGenRegister::Less());
558 /// Sorting predicate for register classes. This provides a topological
559 /// ordering that arranges all register classes before their sub-classes.
561 /// Register classes with the same registers, spill size, and alignment form a
562 /// clique. They will be ordered alphabetically.
564 static int TopoOrderRC(const void *PA, const void *PB) {
565 const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
566 const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
570 // Order by descending set size. Note that the classes' allocation order may
571 // not have been computed yet. The Members set is always vaild.
572 if (A->getMembers().size() > B->getMembers().size())
574 if (A->getMembers().size() < B->getMembers().size())
577 // Order by ascending spill size.
578 if (A->SpillSize < B->SpillSize)
580 if (A->SpillSize > B->SpillSize)
583 // Order by ascending spill alignment.
584 if (A->SpillAlignment < B->SpillAlignment)
586 if (A->SpillAlignment > B->SpillAlignment)
589 // Finally order by name as a tie breaker.
590 return StringRef(A->getName()).compare(B->getName());
593 std::string CodeGenRegisterClass::getQualifiedName() const {
594 if (Namespace.empty())
597 return Namespace + "::" + getName();
600 // Compute sub-classes of all register classes.
601 // Assume the classes are ordered topologically.
602 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
603 ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
605 // Visit backwards so sub-classes are seen first.
606 for (unsigned rci = RegClasses.size(); rci; --rci) {
607 CodeGenRegisterClass &RC = *RegClasses[rci - 1];
608 RC.SubClasses.resize(RegClasses.size());
609 RC.SubClasses.set(RC.EnumValue);
611 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
612 for (unsigned s = rci; s != RegClasses.size(); ++s) {
613 if (RC.SubClasses.test(s))
615 CodeGenRegisterClass *SubRC = RegClasses[s];
616 if (!testSubClass(&RC, SubRC))
618 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
620 RC.SubClasses |= SubRC->SubClasses;
623 // Sweep up missed clique members. They will be immediately preceeding RC.
624 for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
625 RC.SubClasses.set(s - 1);
628 // Compute the SuperClasses lists from the SubClasses vectors.
629 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
630 const BitVector &SC = RegClasses[rci]->getSubClasses();
631 for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
632 if (unsigned(s) == rci)
634 RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
638 // With the class hierarchy in place, let synthesized register classes inherit
639 // properties from their closest super-class. The iteration order here can
640 // propagate properties down multiple levels.
641 for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
642 if (!RegClasses[rci]->getDef())
643 RegClasses[rci]->inheritProperties(RegBank);
647 CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
648 BitVector &Out) const {
649 DenseMap<CodeGenSubRegIndex*,
650 SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
651 FindI = SuperRegClasses.find(SubIdx);
652 if (FindI == SuperRegClasses.end())
654 for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
655 FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
656 Out.set((*I)->EnumValue);
660 //===----------------------------------------------------------------------===//
662 //===----------------------------------------------------------------------===//
664 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
665 // Configure register Sets to understand register classes and tuples.
666 Sets.addFieldExpander("RegisterClass", "MemberList");
667 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
668 Sets.addExpander("RegisterTuples", new TupleExpander());
670 // Read in the user-defined (named) sub-register indices.
671 // More indices will be synthesized later.
672 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
673 std::sort(SRIs.begin(), SRIs.end(), LessRecord());
674 NumNamedIndices = SRIs.size();
675 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
676 getSubRegIdx(SRIs[i]);
677 // Build composite maps from ComposedOf fields.
678 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
679 SubRegIndices[i]->updateComponents(*this);
681 // Read in the register definitions.
682 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
683 std::sort(Regs.begin(), Regs.end(), LessRecord());
684 Registers.reserve(Regs.size());
685 // Assign the enumeration values.
686 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
689 // Expand tuples and number the new registers.
690 std::vector<Record*> Tups =
691 Records.getAllDerivedDefinitions("RegisterTuples");
692 for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
693 const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
694 for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
695 getReg((*TupRegs)[j]);
698 // Precompute all sub-register maps now all the registers are known.
699 // This will create Composite entries for all inferred sub-register indices.
701 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
702 Registers[i]->getSubRegs(*this);
704 // Read in register class definitions.
705 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
707 throw std::string("No 'RegisterClass' subclasses defined!");
709 // Allocate user-defined register classes.
710 RegClasses.reserve(RCs.size());
711 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
712 addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
714 // Infer missing classes to create a full algebra.
715 computeInferredRegisterClasses();
717 // Order register classes topologically and assign enum values.
718 array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
719 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
720 RegClasses[i]->EnumValue = i;
721 CodeGenRegisterClass::computeSubClasses(*this);
724 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
725 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
728 Idx = new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
729 SubRegIndices.push_back(Idx);
733 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
734 CodeGenRegister *&Reg = Def2Reg[Def];
737 Reg = new CodeGenRegister(Def, Registers.size() + 1);
738 Registers.push_back(Reg);
742 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
743 RegClasses.push_back(RC);
745 if (Record *Def = RC->getDef())
746 Def2RC.insert(std::make_pair(Def, RC));
748 // Duplicate classes are rejected by insert().
749 // That's OK, we only care about the properties handled by CGRC::Key.
750 CodeGenRegisterClass::Key K(*RC);
751 Key2RC.insert(std::make_pair(K, RC));
754 // Create a synthetic sub-class if it is missing.
755 CodeGenRegisterClass*
756 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
757 const CodeGenRegister::Set *Members,
759 // Synthetic sub-class has the same size and alignment as RC.
760 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
761 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
762 if (FoundI != Key2RC.end())
763 return FoundI->second;
765 // Sub-class doesn't exist, create a new one.
766 CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K);
771 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
772 if (CodeGenRegisterClass *RC = Def2RC[Def])
775 throw TGError(Def->getLoc(), "Not a known RegisterClass!");
779 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
780 CodeGenSubRegIndex *B) {
781 // Look for an existing entry.
782 CodeGenSubRegIndex *Comp = A->compose(B);
786 // None exists, synthesize one.
787 std::string Name = A->getName() + "_then_" + B->getName();
788 Comp = getSubRegIdx(new Record(Name, SMLoc(), Records));
789 A->addComposite(B, Comp);
793 void CodeGenRegBank::computeComposites() {
794 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
795 CodeGenRegister *Reg1 = Registers[i];
796 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
797 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
798 e1 = SRM1.end(); i1 != e1; ++i1) {
799 CodeGenSubRegIndex *Idx1 = i1->first;
800 CodeGenRegister *Reg2 = i1->second;
801 // Ignore identity compositions.
804 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
805 // Try composing Idx1 with another SubRegIndex.
806 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
807 e2 = SRM2.end(); i2 != e2; ++i2) {
808 CodeGenSubRegIndex *Idx2 = i2->first;
809 CodeGenRegister *Reg3 = i2->second;
810 // Ignore identity compositions.
813 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
814 for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
815 e1d = SRM1.end(); i1d != e1d; ++i1d) {
816 if (i1d->second == Reg3) {
817 // Conflicting composition? Emit a warning but allow it.
818 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, i1d->first))
819 errs() << "Warning: SubRegIndex " << Idx1->getQualifiedName()
820 << " and " << Idx2->getQualifiedName()
821 << " compose ambiguously as "
822 << Prev->getQualifiedName() << " or "
823 << i1d->first->getQualifiedName() << "\n";
830 // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
831 // compositions, so remove any mappings of that form.
832 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
833 SubRegIndices[i]->cleanComposites();
836 // Compute sets of overlapping registers.
838 // The standard set is all super-registers and all sub-registers, but the
839 // target description can add arbitrary overlapping registers via the 'Aliases'
840 // field. This complicates things, but we can compute overlapping sets using
841 // the following rules:
843 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
845 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
849 // overlap(A, B) iff there exists:
850 // A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
851 // A' = B' or A' in aliases(B') or B' in aliases(A').
853 // Here subregs(A) is the full flattened sub-register set returned by
854 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
855 // description of register A.
857 // This also implies that registers with a common sub-register are considered
858 // overlapping. This can happen when forming register pairs:
864 // In this case, we will infer an overlap between P0 and P1 because of the
865 // shared sub-register R1. There is no overlap between P0 and P2.
867 void CodeGenRegBank::
868 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
871 // Collect overlaps that don't follow from rule 2.
872 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
873 CodeGenRegister *Reg = Registers[i];
874 CodeGenRegister::Set &Overlaps = Map[Reg];
876 // Reg overlaps itself.
877 Overlaps.insert(Reg);
879 // All super-registers overlap.
880 const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
881 Overlaps.insert(Supers.begin(), Supers.end());
883 // Form symmetrical relations from the special Aliases[] lists.
884 std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
885 for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
886 CodeGenRegister *Reg2 = getReg(RegList[i2]);
887 CodeGenRegister::Set &Overlaps2 = Map[Reg2];
888 const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
889 // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
890 Overlaps.insert(Reg2);
891 Overlaps.insert(Supers2.begin(), Supers2.end());
892 Overlaps2.insert(Reg);
893 Overlaps2.insert(Supers.begin(), Supers.end());
897 // Apply rule 2. and inherit all sub-register overlaps.
898 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
899 CodeGenRegister *Reg = Registers[i];
900 CodeGenRegister::Set &Overlaps = Map[Reg];
901 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
902 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
903 e2 = SRM.end(); i2 != e2; ++i2) {
904 CodeGenRegister::Set &Overlaps2 = Map[i2->second];
905 Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
910 void CodeGenRegBank::computeDerivedInfo() {
915 // Synthesize missing register class intersections.
917 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
918 // returns a maximal register class for all X.
920 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
921 for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
922 CodeGenRegisterClass *RC1 = RC;
923 CodeGenRegisterClass *RC2 = RegClasses[rci];
927 // Compute the set intersection of RC1 and RC2.
928 const CodeGenRegister::Set &Memb1 = RC1->getMembers();
929 const CodeGenRegister::Set &Memb2 = RC2->getMembers();
930 CodeGenRegister::Set Intersection;
931 std::set_intersection(Memb1.begin(), Memb1.end(),
932 Memb2.begin(), Memb2.end(),
933 std::inserter(Intersection, Intersection.begin()),
934 CodeGenRegister::Less());
936 // Skip disjoint class pairs.
937 if (Intersection.empty())
940 // If RC1 and RC2 have different spill sizes or alignments, use the
941 // larger size for sub-classing. If they are equal, prefer RC1.
942 if (RC2->SpillSize > RC1->SpillSize ||
943 (RC2->SpillSize == RC1->SpillSize &&
944 RC2->SpillAlignment > RC1->SpillAlignment))
947 getOrCreateSubClass(RC1, &Intersection,
948 RC1->getName() + "_and_" + RC2->getName());
953 // Synthesize missing sub-classes for getSubClassWithSubReg().
955 // Make sure that the set of registers in RC with a given SubIdx sub-register
956 // form a register class. Update RC->SubClassWithSubReg.
958 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
959 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
960 typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
961 CodeGenSubRegIndex::Less> SubReg2SetMap;
963 // Compute the set of registers supporting each SubRegIndex.
964 SubReg2SetMap SRSets;
965 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
966 RE = RC->getMembers().end(); RI != RE; ++RI) {
967 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
968 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
969 E = SRM.end(); I != E; ++I)
970 SRSets[I->first].insert(*RI);
973 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
974 // numerical order to visit synthetic indices last.
975 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
976 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
977 SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
978 // Unsupported SubRegIndex. Skip it.
979 if (I == SRSets.end())
981 // In most cases, all RC registers support the SubRegIndex.
982 if (I->second.size() == RC->getMembers().size()) {
983 RC->setSubClassWithSubReg(SubIdx, RC);
986 // This is a real subset. See if we have a matching class.
987 CodeGenRegisterClass *SubRC =
988 getOrCreateSubClass(RC, &I->second,
989 RC->getName() + "_with_" + I->first->getName());
990 RC->setSubClassWithSubReg(SubIdx, SubRC);
995 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
997 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
998 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1001 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1002 unsigned FirstSubRegRC) {
1003 SmallVector<std::pair<const CodeGenRegister*,
1004 const CodeGenRegister*>, 16> SSPairs;
1006 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1007 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1008 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1009 // Skip indexes that aren't fully supported by RC's registers. This was
1010 // computed by inferSubClassWithSubReg() above which should have been
1012 if (RC->getSubClassWithSubReg(SubIdx) != RC)
1015 // Build list of (Super, Sub) pairs for this SubIdx.
1017 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1018 RE = RC->getMembers().end(); RI != RE; ++RI) {
1019 const CodeGenRegister *Super = *RI;
1020 const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
1021 assert(Sub && "Missing sub-register");
1022 SSPairs.push_back(std::make_pair(Super, Sub));
1025 // Iterate over sub-register class candidates. Ignore classes created by
1026 // this loop. They will never be useful.
1027 for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
1029 CodeGenRegisterClass *SubRC = RegClasses[rci];
1030 // Compute the subset of RC that maps into SubRC.
1031 CodeGenRegister::Set SubSet;
1032 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1033 if (SubRC->contains(SSPairs[i].second))
1034 SubSet.insert(SSPairs[i].first);
1037 // RC injects completely into SubRC.
1038 if (SubSet.size() == SSPairs.size()) {
1039 SubRC->addSuperRegClass(SubIdx, RC);
1042 // Only a subset of RC maps into SubRC. Make sure it is represented by a
1044 getOrCreateSubClass(RC, &SubSet, RC->getName() +
1045 "_with_" + SubIdx->getName() +
1046 "_in_" + SubRC->getName());
1053 // Infer missing register classes.
1055 void CodeGenRegBank::computeInferredRegisterClasses() {
1056 // When this function is called, the register classes have not been sorted
1057 // and assigned EnumValues yet. That means getSubClasses(),
1058 // getSuperClasses(), and hasSubClass() functions are defunct.
1059 unsigned FirstNewRC = RegClasses.size();
1061 // Visit all register classes, including the ones being added by the loop.
1062 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
1063 CodeGenRegisterClass *RC = RegClasses[rci];
1065 // Synthesize answers for getSubClassWithSubReg().
1066 inferSubClassWithSubReg(RC);
1068 // Synthesize answers for getCommonSubClass().
1069 inferCommonSubClass(RC);
1071 // Synthesize answers for getMatchingSuperRegClass().
1072 inferMatchingSuperRegClass(RC);
1074 // New register classes are created while this loop is running, and we need
1075 // to visit all of them. I particular, inferMatchingSuperRegClass needs
1076 // to match old super-register classes with sub-register classes created
1077 // after inferMatchingSuperRegClass was called. At this point,
1078 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
1079 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
1080 if (rci + 1 == FirstNewRC) {
1081 unsigned NextNewRC = RegClasses.size();
1082 for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
1083 inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
1084 FirstNewRC = NextNewRC;
1089 /// getRegisterClassForRegister - Find the register class that contains the
1090 /// specified physical register. If the register is not in a register class,
1091 /// return null. If the register is in multiple classes, and the classes have a
1092 /// superset-subset relationship and the same set of types, return the
1093 /// superclass. Otherwise return null.
1094 const CodeGenRegisterClass*
1095 CodeGenRegBank::getRegClassForRegister(Record *R) {
1096 const CodeGenRegister *Reg = getReg(R);
1097 ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
1098 const CodeGenRegisterClass *FoundRC = 0;
1099 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
1100 const CodeGenRegisterClass &RC = *RCs[i];
1101 if (!RC.contains(Reg))
1104 // If this is the first class that contains the register,
1105 // make a note of it and go on to the next class.
1111 // If a register's classes have different types, return null.
1112 if (RC.getValueTypes() != FoundRC->getValueTypes())
1115 // Check to see if the previously found class that contains
1116 // the register is a subclass of the current class. If so,
1117 // prefer the superclass.
1118 if (RC.hasSubClass(FoundRC)) {
1123 // Check to see if the previously found class that contains
1124 // the register is a superclass of the current class. If so,
1125 // prefer the superclass.
1126 if (FoundRC->hasSubClass(&RC))
1129 // Multiple classes, and neither is a superclass of the other.
1136 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1137 SetVector<const CodeGenRegister*> Set;
1139 // First add Regs with all sub-registers.
1140 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1141 CodeGenRegister *Reg = getReg(Regs[i]);
1142 if (Set.insert(Reg))
1143 // Reg is new, add all sub-registers.
1144 // The pre-ordering is not important here.
1145 Reg->addSubRegsPreOrder(Set, *this);
1148 // Second, find all super-registers that are completely covered by the set.
1149 for (unsigned i = 0; i != Set.size(); ++i) {
1150 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1151 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1152 const CodeGenRegister *Super = SR[j];
1153 if (!Super->CoveredBySubRegs || Set.count(Super))
1155 // This new super-register is covered by its sub-registers.
1156 bool AllSubsInSet = true;
1157 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1158 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1159 E = SRM.end(); I != E; ++I)
1160 if (!Set.count(I->second)) {
1161 AllSubsInSet = false;
1164 // All sub-registers in Set, add Super as well.
1165 // We will visit Super later to recheck its super-registers.
1171 // Convert to BitVector.
1172 BitVector BV(Registers.size() + 1);
1173 for (unsigned i = 0, e = Set.size(); i != e; ++i)
1174 BV.set(Set[i]->EnumValue);