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 const CodeGenRegister::SubRegMap &
92 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
93 // Only compute this map once.
96 SubRegsComplete = true;
98 std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
99 std::vector<Record*> IdxList = TheDef->getValueAsListOfDefs("SubRegIndices");
100 if (SubList.size() != IdxList.size())
101 throw TGError(TheDef->getLoc(), "Register " + getName() +
102 " SubRegIndices doesn't match SubRegs");
104 // First insert the direct subregs and make sure they are fully indexed.
105 SmallVector<CodeGenSubRegIndex*, 8> Indices;
106 for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
107 CodeGenRegister *SR = RegBank.getReg(SubList[i]);
108 CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxList[i]);
109 Indices.push_back(Idx);
110 if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
111 throw TGError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
112 " appears twice in Register " + getName());
115 // Keep track of inherited subregs and how they can be reached.
116 SmallPtrSet<CodeGenRegister*, 8> Orphans;
118 // Clone inherited subregs and place duplicate entries in Orphans.
119 // Here the order is important - earlier subregs take precedence.
120 for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
121 CodeGenRegister *SR = RegBank.getReg(SubList[i]);
122 const SubRegMap &Map = SR->getSubRegs(RegBank);
124 // Add this as a super-register of SR now all sub-registers are in the list.
125 // This creates a topological ordering, the exact order depends on the
126 // order getSubRegs is called on all registers.
127 SR->SuperRegs.push_back(this);
129 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
131 if (!SubRegs.insert(*SI).second)
132 Orphans.insert(SI->second);
134 // Noop sub-register indexes are possible, so avoid duplicates.
135 if (SI->second != SR)
136 SI->second->SuperRegs.push_back(this);
140 // Expand any composed subreg indices.
141 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
142 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
143 // expanded subreg indices recursively.
144 for (unsigned i = 0; i != Indices.size(); ++i) {
145 CodeGenSubRegIndex *Idx = Indices[i];
146 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
147 CodeGenRegister *SR = SubRegs[Idx];
148 const SubRegMap &Map = SR->getSubRegs(RegBank);
150 // Look at the possible compositions of Idx.
151 // They may not all be supported by SR.
152 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
153 E = Comps.end(); I != E; ++I) {
154 SubRegMap::const_iterator SRI = Map.find(I->first);
155 if (SRI == Map.end())
156 continue; // Idx + I->first doesn't exist in SR.
157 // Add I->second as a name for the subreg SRI->second, assuming it is
158 // orphaned, and the name isn't already used for something else.
159 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
161 // We found a new name for the orphaned sub-register.
162 SubRegs.insert(std::make_pair(I->second, SRI->second));
163 Indices.push_back(I->second);
167 // Process the composites.
168 ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
169 for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
170 DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
172 throw TGError(TheDef->getLoc(), "Invalid dag '" +
173 Comps->getElement(i)->getAsString() +
174 "' in CompositeIndices");
175 DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
176 if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
177 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
179 CodeGenSubRegIndex *BaseIdx = RegBank.getSubRegIdx(BaseIdxInit->getDef());
181 // Resolve list of subreg indices into R2.
182 CodeGenRegister *R2 = this;
183 for (DagInit::const_arg_iterator di = Pat->arg_begin(),
184 de = Pat->arg_end(); di != de; ++di) {
185 DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
186 if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
187 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
189 CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxInit->getDef());
190 const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
191 SubRegMap::const_iterator ni = R2Subs.find(Idx);
192 if (ni == R2Subs.end())
193 throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
194 " refers to bad index in " + R2->getName());
198 // Insert composite index. Allow overriding inherited indices etc.
199 SubRegs[BaseIdx] = R2;
201 // R2 is no longer an orphan.
205 // Now Orphans contains the inherited subregisters without a direct index.
206 // Create inferred indexes for all missing entries.
207 // Work backwards in the Indices vector in order to compose subregs bottom-up.
208 // Consider this subreg sequence:
210 // qsub_1 -> dsub_0 -> ssub_0
212 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
213 // can be reached in two different ways:
218 // We pick the latter composition because another register may have [dsub_0,
219 // dsub_1, dsub_2] subregs without neccessarily having a qsub_1 subreg. The
220 // dsub_2 -> ssub_0 composition can be shared.
221 while (!Indices.empty() && !Orphans.empty()) {
222 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
223 CodeGenRegister *SR = SubRegs[Idx];
224 const SubRegMap &Map = SR->getSubRegs(RegBank);
225 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
227 if (Orphans.erase(SI->second))
228 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
234 CodeGenRegister::addSubRegsPreOrder(SetVector<CodeGenRegister*> &OSet,
235 CodeGenRegBank &RegBank) const {
236 assert(SubRegsComplete && "Must precompute sub-registers");
237 std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
238 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
239 CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(Indices[i]);
240 CodeGenRegister *SR = SubRegs.find(Idx)->second;
242 SR->addSubRegsPreOrder(OSet, RegBank);
246 //===----------------------------------------------------------------------===//
248 //===----------------------------------------------------------------------===//
250 // A RegisterTuples def is used to generate pseudo-registers from lists of
251 // sub-registers. We provide a SetTheory expander class that returns the new
254 struct TupleExpander : SetTheory::Expander {
255 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
256 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
257 unsigned Dim = Indices.size();
258 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
259 if (Dim != SubRegs->getSize())
260 throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
262 throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
264 // Evaluate the sub-register lists to be zipped.
265 unsigned Length = ~0u;
266 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
267 for (unsigned i = 0; i != Dim; ++i) {
268 ST.evaluate(SubRegs->getElement(i), Lists[i]);
269 Length = std::min(Length, unsigned(Lists[i].size()));
275 // Precompute some types.
276 Record *RegisterCl = Def->getRecords().getClass("Register");
277 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
278 StringInit *BlankName = StringInit::get("");
281 for (unsigned n = 0; n != Length; ++n) {
283 Record *Proto = Lists[0][n];
284 std::vector<Init*> Tuple;
285 unsigned CostPerUse = 0;
286 for (unsigned i = 0; i != Dim; ++i) {
287 Record *Reg = Lists[i][n];
289 Name += Reg->getName();
290 Tuple.push_back(DefInit::get(Reg));
291 CostPerUse = std::max(CostPerUse,
292 unsigned(Reg->getValueAsInt("CostPerUse")));
295 // Create a new Record representing the synthesized register. This record
296 // is only for consumption by CodeGenRegister, it is not added to the
298 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
301 // Copy Proto super-classes.
302 for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
303 NewReg->addSuperClass(Proto->getSuperClasses()[i]);
305 // Copy Proto fields.
306 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
307 RecordVal RV = Proto->getValues()[i];
309 // Skip existing fields, like NAME.
310 if (NewReg->getValue(RV.getNameInit()))
313 StringRef Field = RV.getName();
315 // Replace the sub-register list with Tuple.
316 if (Field == "SubRegs")
317 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
319 // Provide a blank AsmName. MC hacks are required anyway.
320 if (Field == "AsmName")
321 RV.setValue(BlankName);
323 // CostPerUse is aggregated from all Tuple members.
324 if (Field == "CostPerUse")
325 RV.setValue(IntInit::get(CostPerUse));
327 // Composite registers are always covered by sub-registers.
328 if (Field == "CoveredBySubRegs")
329 RV.setValue(BitInit::get(true));
331 // Copy fields from the RegisterTuples def.
332 if (Field == "SubRegIndices" ||
333 Field == "CompositeIndices") {
334 NewReg->addValue(*Def->getValue(Field));
338 // Some fields get their default uninitialized value.
339 if (Field == "DwarfNumbers" ||
340 Field == "DwarfAlias" ||
341 Field == "Aliases") {
342 if (const RecordVal *DefRV = RegisterCl->getValue(Field))
343 NewReg->addValue(*DefRV);
347 // Everything else is copied from Proto.
348 NewReg->addValue(RV);
355 //===----------------------------------------------------------------------===//
356 // CodeGenRegisterClass
357 //===----------------------------------------------------------------------===//
359 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
360 : TheDef(R), Name(R->getName()), EnumValue(-1) {
361 // Rename anonymous register classes.
362 if (R->getName().size() > 9 && R->getName()[9] == '.') {
363 static unsigned AnonCounter = 0;
364 R->setName("AnonRegClass_"+utostr(AnonCounter++));
367 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
368 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
369 Record *Type = TypeList[i];
370 if (!Type->isSubClassOf("ValueType"))
371 throw "RegTypes list member '" + Type->getName() +
372 "' does not derive from the ValueType class!";
373 VTs.push_back(getValueType(Type));
375 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
377 // Allocation order 0 is the full set. AltOrders provides others.
378 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
379 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
380 Orders.resize(1 + AltOrders->size());
382 // Default allocation order always contains all registers.
383 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
384 Orders[0].push_back((*Elements)[i]);
385 Members.insert(RegBank.getReg((*Elements)[i]));
388 // Alternative allocation orders may be subsets.
389 SetTheory::RecSet Order;
390 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
391 RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
392 Orders[1 + i].append(Order.begin(), Order.end());
393 // Verify that all altorder members are regclass members.
394 while (!Order.empty()) {
395 CodeGenRegister *Reg = RegBank.getReg(Order.back());
398 throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
399 " is not a class member");
403 // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
404 ListInit *SRC = R->getValueAsListInit("SubRegClasses");
405 for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
406 DagInit *DAG = dynamic_cast<DagInit*>(*i);
407 if (!DAG) throw "SubRegClasses must contain DAGs";
408 DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
410 if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
411 throw "Operator '" + DAG->getOperator()->getAsString() +
412 "' in SubRegClasses is not a RegisterClass";
413 // Iterate over args, all SubRegIndex instances.
414 for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
416 DefInit *Idx = dynamic_cast<DefInit*>(*ai);
418 if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
419 throw "Argument '" + (*ai)->getAsString() +
420 "' in SubRegClasses is not a SubRegIndex";
421 if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
422 throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
426 // Allow targets to override the size in bits of the RegisterClass.
427 unsigned Size = R->getValueAsInt("Size");
429 Namespace = R->getValueAsString("Namespace");
430 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
431 SpillAlignment = R->getValueAsInt("Alignment");
432 CopyCost = R->getValueAsInt("CopyCost");
433 Allocatable = R->getValueAsBit("isAllocatable");
434 AltOrderSelect = R->getValueAsString("AltOrderSelect");
437 // Create an inferred register class that was missing from the .td files.
438 // Most properties will be inherited from the closest super-class after the
439 // class structure has been computed.
440 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props)
441 : Members(*Props.Members),
445 SpillSize(Props.SpillSize),
446 SpillAlignment(Props.SpillAlignment),
451 // Compute inherited propertied for a synthesized register class.
452 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
453 assert(!getDef() && "Only synthesized classes can inherit properties");
454 assert(!SuperClasses.empty() && "Synthesized class without super class");
456 // The last super-class is the smallest one.
457 CodeGenRegisterClass &Super = *SuperClasses.back();
459 // Most properties are copied directly.
460 // Exceptions are members, size, and alignment
461 Namespace = Super.Namespace;
463 CopyCost = Super.CopyCost;
464 Allocatable = Super.Allocatable;
465 AltOrderSelect = Super.AltOrderSelect;
467 // Copy all allocation orders, filter out foreign registers from the larger
469 Orders.resize(Super.Orders.size());
470 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
471 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
472 if (contains(RegBank.getReg(Super.Orders[i][j])))
473 Orders[i].push_back(Super.Orders[i][j]);
476 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
477 return Members.count(Reg);
481 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
482 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
483 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
484 E = K.Members->end(); I != E; ++I)
485 OS << ", " << (*I)->getName();
490 // This is a simple lexicographical order that can be used to search for sets.
491 // It is not the same as the topological order provided by TopoOrderRC.
492 bool CodeGenRegisterClass::Key::
493 operator<(const CodeGenRegisterClass::Key &B) const {
494 assert(Members && B.Members);
495 if (*Members != *B.Members)
496 return *Members < *B.Members;
497 if (SpillSize != B.SpillSize)
498 return SpillSize < B.SpillSize;
499 return SpillAlignment < B.SpillAlignment;
502 // Returns true if RC is a strict subclass.
503 // RC is a sub-class of this class if it is a valid replacement for any
504 // instruction operand where a register of this classis required. It must
505 // satisfy these conditions:
507 // 1. All RC registers are also in this.
508 // 2. The RC spill size must not be smaller than our spill size.
509 // 3. RC spill alignment must be compatible with ours.
511 static bool testSubClass(const CodeGenRegisterClass *A,
512 const CodeGenRegisterClass *B) {
513 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
514 A->SpillSize <= B->SpillSize &&
515 std::includes(A->getMembers().begin(), A->getMembers().end(),
516 B->getMembers().begin(), B->getMembers().end(),
517 CodeGenRegister::Less());
520 /// Sorting predicate for register classes. This provides a topological
521 /// ordering that arranges all register classes before their sub-classes.
523 /// Register classes with the same registers, spill size, and alignment form a
524 /// clique. They will be ordered alphabetically.
526 static int TopoOrderRC(const void *PA, const void *PB) {
527 const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
528 const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
532 // Order by descending set size. Note that the classes' allocation order may
533 // not have been computed yet. The Members set is always vaild.
534 if (A->getMembers().size() > B->getMembers().size())
536 if (A->getMembers().size() < B->getMembers().size())
539 // Order by ascending spill size.
540 if (A->SpillSize < B->SpillSize)
542 if (A->SpillSize > B->SpillSize)
545 // Order by ascending spill alignment.
546 if (A->SpillAlignment < B->SpillAlignment)
548 if (A->SpillAlignment > B->SpillAlignment)
551 // Finally order by name as a tie breaker.
552 return StringRef(A->getName()).compare(B->getName());
555 std::string CodeGenRegisterClass::getQualifiedName() const {
556 if (Namespace.empty())
559 return Namespace + "::" + getName();
562 // Compute sub-classes of all register classes.
563 // Assume the classes are ordered topologically.
564 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
565 ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
567 // Visit backwards so sub-classes are seen first.
568 for (unsigned rci = RegClasses.size(); rci; --rci) {
569 CodeGenRegisterClass &RC = *RegClasses[rci - 1];
570 RC.SubClasses.resize(RegClasses.size());
571 RC.SubClasses.set(RC.EnumValue);
573 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
574 for (unsigned s = rci; s != RegClasses.size(); ++s) {
575 if (RC.SubClasses.test(s))
577 CodeGenRegisterClass *SubRC = RegClasses[s];
578 if (!testSubClass(&RC, SubRC))
580 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
582 RC.SubClasses |= SubRC->SubClasses;
585 // Sweep up missed clique members. They will be immediately preceeding RC.
586 for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
587 RC.SubClasses.set(s - 1);
590 // Compute the SuperClasses lists from the SubClasses vectors.
591 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
592 const BitVector &SC = RegClasses[rci]->getSubClasses();
593 for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
594 if (unsigned(s) == rci)
596 RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
600 // With the class hierarchy in place, let synthesized register classes inherit
601 // properties from their closest super-class. The iteration order here can
602 // propagate properties down multiple levels.
603 for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
604 if (!RegClasses[rci]->getDef())
605 RegClasses[rci]->inheritProperties(RegBank);
609 CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
610 BitVector &Out) const {
611 DenseMap<CodeGenSubRegIndex*,
612 SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
613 FindI = SuperRegClasses.find(SubIdx);
614 if (FindI == SuperRegClasses.end())
616 for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
617 FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
618 Out.set((*I)->EnumValue);
622 //===----------------------------------------------------------------------===//
624 //===----------------------------------------------------------------------===//
626 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
627 // Configure register Sets to understand register classes and tuples.
628 Sets.addFieldExpander("RegisterClass", "MemberList");
629 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
630 Sets.addExpander("RegisterTuples", new TupleExpander());
632 // Read in the user-defined (named) sub-register indices.
633 // More indices will be synthesized later.
634 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
635 std::sort(SRIs.begin(), SRIs.end(), LessRecord());
636 NumNamedIndices = SRIs.size();
637 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
638 getSubRegIdx(SRIs[i]);
639 // Build composite maps from ComposedOf fields.
640 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
641 SubRegIndices[i]->updateComponents(*this);
643 // Read in the register definitions.
644 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
645 std::sort(Regs.begin(), Regs.end(), LessRecord());
646 Registers.reserve(Regs.size());
647 // Assign the enumeration values.
648 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
651 // Expand tuples and number the new registers.
652 std::vector<Record*> Tups =
653 Records.getAllDerivedDefinitions("RegisterTuples");
654 for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
655 const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
656 for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
657 getReg((*TupRegs)[j]);
660 // Precompute all sub-register maps now all the registers are known.
661 // This will create Composite entries for all inferred sub-register indices.
662 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
663 Registers[i]->getSubRegs(*this);
665 // Read in register class definitions.
666 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
668 throw std::string("No 'RegisterClass' subclasses defined!");
670 // Allocate user-defined register classes.
671 RegClasses.reserve(RCs.size());
672 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
673 addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
675 // Infer missing classes to create a full algebra.
676 computeInferredRegisterClasses();
678 // Order register classes topologically and assign enum values.
679 array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
680 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
681 RegClasses[i]->EnumValue = i;
682 CodeGenRegisterClass::computeSubClasses(*this);
685 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
686 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
689 Idx = new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
690 SubRegIndices.push_back(Idx);
694 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
695 CodeGenRegister *&Reg = Def2Reg[Def];
698 Reg = new CodeGenRegister(Def, Registers.size() + 1);
699 Registers.push_back(Reg);
703 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
704 RegClasses.push_back(RC);
706 if (Record *Def = RC->getDef())
707 Def2RC.insert(std::make_pair(Def, RC));
709 // Duplicate classes are rejected by insert().
710 // That's OK, we only care about the properties handled by CGRC::Key.
711 CodeGenRegisterClass::Key K(*RC);
712 Key2RC.insert(std::make_pair(K, RC));
715 // Create a synthetic sub-class if it is missing.
716 CodeGenRegisterClass*
717 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
718 const CodeGenRegister::Set *Members,
720 // Synthetic sub-class has the same size and alignment as RC.
721 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
722 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
723 if (FoundI != Key2RC.end())
724 return FoundI->second;
726 // Sub-class doesn't exist, create a new one.
727 CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K);
732 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
733 if (CodeGenRegisterClass *RC = Def2RC[Def])
736 throw TGError(Def->getLoc(), "Not a known RegisterClass!");
740 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
741 CodeGenSubRegIndex *B) {
742 // Look for an existing entry.
743 CodeGenSubRegIndex *Comp = A->compose(B);
747 // None exists, synthesize one.
748 std::string Name = A->getName() + "_then_" + B->getName();
749 Comp = getSubRegIdx(new Record(Name, SMLoc(), Records));
750 A->addComposite(B, Comp);
754 void CodeGenRegBank::computeComposites() {
755 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
756 CodeGenRegister *Reg1 = Registers[i];
757 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
758 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
759 e1 = SRM1.end(); i1 != e1; ++i1) {
760 CodeGenSubRegIndex *Idx1 = i1->first;
761 CodeGenRegister *Reg2 = i1->second;
762 // Ignore identity compositions.
765 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
766 // Try composing Idx1 with another SubRegIndex.
767 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
768 e2 = SRM2.end(); i2 != e2; ++i2) {
769 CodeGenSubRegIndex *Idx2 = i2->first;
770 CodeGenRegister *Reg3 = i2->second;
771 // Ignore identity compositions.
774 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
775 for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
776 e1d = SRM1.end(); i1d != e1d; ++i1d) {
777 if (i1d->second == Reg3) {
778 // Conflicting composition? Emit a warning but allow it.
779 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, i1d->first))
780 errs() << "Warning: SubRegIndex " << Idx1->getQualifiedName()
781 << " and " << Idx2->getQualifiedName()
782 << " compose ambiguously as "
783 << Prev->getQualifiedName() << " or "
784 << i1d->first->getQualifiedName() << "\n";
791 // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
792 // compositions, so remove any mappings of that form.
793 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
794 SubRegIndices[i]->cleanComposites();
797 // Compute sets of overlapping registers.
799 // The standard set is all super-registers and all sub-registers, but the
800 // target description can add arbitrary overlapping registers via the 'Aliases'
801 // field. This complicates things, but we can compute overlapping sets using
802 // the following rules:
804 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
806 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
810 // overlap(A, B) iff there exists:
811 // A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
812 // A' = B' or A' in aliases(B') or B' in aliases(A').
814 // Here subregs(A) is the full flattened sub-register set returned by
815 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
816 // description of register A.
818 // This also implies that registers with a common sub-register are considered
819 // overlapping. This can happen when forming register pairs:
825 // In this case, we will infer an overlap between P0 and P1 because of the
826 // shared sub-register R1. There is no overlap between P0 and P2.
828 void CodeGenRegBank::
829 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
832 // Collect overlaps that don't follow from rule 2.
833 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
834 CodeGenRegister *Reg = Registers[i];
835 CodeGenRegister::Set &Overlaps = Map[Reg];
837 // Reg overlaps itself.
838 Overlaps.insert(Reg);
840 // All super-registers overlap.
841 const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
842 Overlaps.insert(Supers.begin(), Supers.end());
844 // Form symmetrical relations from the special Aliases[] lists.
845 std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
846 for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
847 CodeGenRegister *Reg2 = getReg(RegList[i2]);
848 CodeGenRegister::Set &Overlaps2 = Map[Reg2];
849 const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
850 // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
851 Overlaps.insert(Reg2);
852 Overlaps.insert(Supers2.begin(), Supers2.end());
853 Overlaps2.insert(Reg);
854 Overlaps2.insert(Supers.begin(), Supers.end());
858 // Apply rule 2. and inherit all sub-register overlaps.
859 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
860 CodeGenRegister *Reg = Registers[i];
861 CodeGenRegister::Set &Overlaps = Map[Reg];
862 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
863 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
864 e2 = SRM.end(); i2 != e2; ++i2) {
865 CodeGenRegister::Set &Overlaps2 = Map[i2->second];
866 Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
871 void CodeGenRegBank::computeDerivedInfo() {
876 // Synthesize missing register class intersections.
878 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
879 // returns a maximal register class for all X.
881 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
882 for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
883 CodeGenRegisterClass *RC1 = RC;
884 CodeGenRegisterClass *RC2 = RegClasses[rci];
888 // Compute the set intersection of RC1 and RC2.
889 const CodeGenRegister::Set &Memb1 = RC1->getMembers();
890 const CodeGenRegister::Set &Memb2 = RC2->getMembers();
891 CodeGenRegister::Set Intersection;
892 std::set_intersection(Memb1.begin(), Memb1.end(),
893 Memb2.begin(), Memb2.end(),
894 std::inserter(Intersection, Intersection.begin()),
895 CodeGenRegister::Less());
897 // Skip disjoint class pairs.
898 if (Intersection.empty())
901 // If RC1 and RC2 have different spill sizes or alignments, use the
902 // larger size for sub-classing. If they are equal, prefer RC1.
903 if (RC2->SpillSize > RC1->SpillSize ||
904 (RC2->SpillSize == RC1->SpillSize &&
905 RC2->SpillAlignment > RC1->SpillAlignment))
908 getOrCreateSubClass(RC1, &Intersection,
909 RC1->getName() + "_and_" + RC2->getName());
914 // Synthesize missing sub-classes for getSubClassWithSubReg().
916 // Make sure that the set of registers in RC with a given SubIdx sub-register
917 // form a register class. Update RC->SubClassWithSubReg.
919 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
920 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
921 typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
922 CodeGenSubRegIndex::Less> SubReg2SetMap;
924 // Compute the set of registers supporting each SubRegIndex.
925 SubReg2SetMap SRSets;
926 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
927 RE = RC->getMembers().end(); RI != RE; ++RI) {
928 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
929 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
930 E = SRM.end(); I != E; ++I)
931 SRSets[I->first].insert(*RI);
934 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
935 // numerical order to visit synthetic indices last.
936 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
937 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
938 SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
939 // Unsupported SubRegIndex. Skip it.
940 if (I == SRSets.end())
942 // In most cases, all RC registers support the SubRegIndex.
943 if (I->second.size() == RC->getMembers().size()) {
944 RC->setSubClassWithSubReg(SubIdx, RC);
947 // This is a real subset. See if we have a matching class.
948 CodeGenRegisterClass *SubRC =
949 getOrCreateSubClass(RC, &I->second,
950 RC->getName() + "_with_" + I->first->getName());
951 RC->setSubClassWithSubReg(SubIdx, SubRC);
956 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
958 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
959 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
962 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
963 unsigned FirstSubRegRC) {
964 SmallVector<std::pair<const CodeGenRegister*,
965 const CodeGenRegister*>, 16> SSPairs;
967 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
968 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
969 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
970 // Skip indexes that aren't fully supported by RC's registers. This was
971 // computed by inferSubClassWithSubReg() above which should have been
973 if (RC->getSubClassWithSubReg(SubIdx) != RC)
976 // Build list of (Super, Sub) pairs for this SubIdx.
978 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
979 RE = RC->getMembers().end(); RI != RE; ++RI) {
980 const CodeGenRegister *Super = *RI;
981 const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
982 assert(Sub && "Missing sub-register");
983 SSPairs.push_back(std::make_pair(Super, Sub));
986 // Iterate over sub-register class candidates. Ignore classes created by
987 // this loop. They will never be useful.
988 for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
990 CodeGenRegisterClass *SubRC = RegClasses[rci];
991 // Compute the subset of RC that maps into SubRC.
992 CodeGenRegister::Set SubSet;
993 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
994 if (SubRC->contains(SSPairs[i].second))
995 SubSet.insert(SSPairs[i].first);
998 // RC injects completely into SubRC.
999 if (SubSet.size() == SSPairs.size()) {
1000 SubRC->addSuperRegClass(SubIdx, RC);
1003 // Only a subset of RC maps into SubRC. Make sure it is represented by a
1005 getOrCreateSubClass(RC, &SubSet, RC->getName() +
1006 "_with_" + SubIdx->getName() +
1007 "_in_" + SubRC->getName());
1014 // Infer missing register classes.
1016 void CodeGenRegBank::computeInferredRegisterClasses() {
1017 // When this function is called, the register classes have not been sorted
1018 // and assigned EnumValues yet. That means getSubClasses(),
1019 // getSuperClasses(), and hasSubClass() functions are defunct.
1020 unsigned FirstNewRC = RegClasses.size();
1022 // Visit all register classes, including the ones being added by the loop.
1023 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
1024 CodeGenRegisterClass *RC = RegClasses[rci];
1026 // Synthesize answers for getSubClassWithSubReg().
1027 inferSubClassWithSubReg(RC);
1029 // Synthesize answers for getCommonSubClass().
1030 inferCommonSubClass(RC);
1032 // Synthesize answers for getMatchingSuperRegClass().
1033 inferMatchingSuperRegClass(RC);
1035 // New register classes are created while this loop is running, and we need
1036 // to visit all of them. I particular, inferMatchingSuperRegClass needs
1037 // to match old super-register classes with sub-register classes created
1038 // after inferMatchingSuperRegClass was called. At this point,
1039 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
1040 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
1041 if (rci + 1 == FirstNewRC) {
1042 unsigned NextNewRC = RegClasses.size();
1043 for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
1044 inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
1045 FirstNewRC = NextNewRC;
1050 /// getRegisterClassForRegister - Find the register class that contains the
1051 /// specified physical register. If the register is not in a register class,
1052 /// return null. If the register is in multiple classes, and the classes have a
1053 /// superset-subset relationship and the same set of types, return the
1054 /// superclass. Otherwise return null.
1055 const CodeGenRegisterClass*
1056 CodeGenRegBank::getRegClassForRegister(Record *R) {
1057 const CodeGenRegister *Reg = getReg(R);
1058 ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
1059 const CodeGenRegisterClass *FoundRC = 0;
1060 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
1061 const CodeGenRegisterClass &RC = *RCs[i];
1062 if (!RC.contains(Reg))
1065 // If this is the first class that contains the register,
1066 // make a note of it and go on to the next class.
1072 // If a register's classes have different types, return null.
1073 if (RC.getValueTypes() != FoundRC->getValueTypes())
1076 // Check to see if the previously found class that contains
1077 // the register is a subclass of the current class. If so,
1078 // prefer the superclass.
1079 if (RC.hasSubClass(FoundRC)) {
1084 // Check to see if the previously found class that contains
1085 // the register is a superclass of the current class. If so,
1086 // prefer the superclass.
1087 if (FoundRC->hasSubClass(&RC))
1090 // Multiple classes, and neither is a superclass of the other.
1097 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1098 SetVector<CodeGenRegister*> Set;
1100 // First add Regs with all sub-registers.
1101 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1102 CodeGenRegister *Reg = getReg(Regs[i]);
1103 if (Set.insert(Reg))
1104 // Reg is new, add all sub-registers.
1105 // The pre-ordering is not important here.
1106 Reg->addSubRegsPreOrder(Set, *this);
1109 // Second, find all super-registers that are completely covered by the set.
1110 for (unsigned i = 0; i != Set.size(); ++i) {
1111 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1112 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1113 CodeGenRegister *Super = SR[j];
1114 if (!Super->CoveredBySubRegs || Set.count(Super))
1116 // This new super-register is covered by its sub-registers.
1117 bool AllSubsInSet = true;
1118 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1119 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1120 E = SRM.end(); I != E; ++I)
1121 if (!Set.count(I->second)) {
1122 AllSubsInSet = false;
1125 // All sub-registers in Set, add Super as well.
1126 // We will visit Super later to recheck its super-registers.
1132 // Convert to BitVector.
1133 BitVector BV(Registers.size() + 1);
1134 for (unsigned i = 0, e = Set.size(); i != e; ++i)
1135 BV.set(Set[i]->EnumValue);