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/IntEqClasses.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Twine.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
31 : TheDef(R), EnumValue(Enum) {
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) {
42 std::string CodeGenSubRegIndex::getQualifiedName() const {
43 std::string N = getNamespace();
50 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")),
85 SubRegsComplete(false),
86 SuperRegsComplete(false),
90 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
91 std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
92 std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
94 if (SRIs.size() != SRs.size())
95 throw TGError(TheDef->getLoc(),
96 "SubRegs and SubRegIndices must have the same size");
98 for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
99 ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
100 ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
103 // Also compute leading super-registers. Each register has a list of
104 // covered-by-subregs super-registers where it appears as the first explicit
107 // This is used by computeSecondarySubRegs() to find candidates.
108 if (CoveredBySubRegs && !ExplicitSubRegs.empty())
109 ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
111 // Add ad hoc alias links. This is a symmetric relationship between two
112 // registers, so build a symmetric graph by adding links in both ends.
113 std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
114 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
115 CodeGenRegister *Reg = RegBank.getReg(Aliases[i]);
116 ExplicitAliases.push_back(Reg);
117 Reg->ExplicitAliases.push_back(this);
121 const std::string &CodeGenRegister::getName() const {
122 return TheDef->getName();
126 // Iterate over all register units in a set of registers.
127 class RegUnitIterator {
128 CodeGenRegister::Set::const_iterator RegI, RegE;
129 CodeGenRegister::RegUnitList::const_iterator UnitI, UnitE;
132 RegUnitIterator(const CodeGenRegister::Set &Regs):
133 RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
136 UnitI = (*RegI)->getRegUnits().begin();
137 UnitE = (*RegI)->getRegUnits().end();
142 bool isValid() const { return UnitI != UnitE; }
144 unsigned operator* () const { assert(isValid()); return *UnitI; }
146 const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
148 /// Preincrement. Move to the next unit.
150 assert(isValid() && "Cannot advance beyond the last operand");
157 while (UnitI == UnitE) {
160 UnitI = (*RegI)->getRegUnits().begin();
161 UnitE = (*RegI)->getRegUnits().end();
167 // Merge two RegUnitLists maintaining the order and removing duplicates.
168 // Overwrites MergedRU in the process.
169 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
170 const CodeGenRegister::RegUnitList &RRU) {
171 CodeGenRegister::RegUnitList LRU = MergedRU;
173 std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(),
174 std::back_inserter(MergedRU));
177 // Return true of this unit appears in RegUnits.
178 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
179 return std::count(RegUnits.begin(), RegUnits.end(), Unit);
182 // Inherit register units from subregisters.
183 // Return true if the RegUnits changed.
184 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
185 unsigned OldNumUnits = RegUnits.size();
186 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
188 CodeGenRegister *SR = I->second;
189 // Merge the subregister's units into this register's RegUnits.
190 mergeRegUnits(RegUnits, SR->RegUnits);
192 return OldNumUnits != RegUnits.size();
195 const CodeGenRegister::SubRegMap &
196 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
197 // Only compute this map once.
200 SubRegsComplete = true;
202 // First insert the explicit subregs and make sure they are fully indexed.
203 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
204 CodeGenRegister *SR = ExplicitSubRegs[i];
205 CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
206 if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
207 throw TGError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
208 " appears twice in Register " + getName());
209 // Map explicit sub-registers first, so the names take precedence.
210 // The inherited sub-registers are mapped below.
211 SubReg2Idx.insert(std::make_pair(SR, Idx));
214 // Keep track of inherited subregs and how they can be reached.
215 SmallPtrSet<CodeGenRegister*, 8> Orphans;
217 // Clone inherited subregs and place duplicate entries in Orphans.
218 // Here the order is important - earlier subregs take precedence.
219 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
220 CodeGenRegister *SR = ExplicitSubRegs[i];
221 const SubRegMap &Map = SR->computeSubRegs(RegBank);
223 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
225 if (!SubRegs.insert(*SI).second)
226 Orphans.insert(SI->second);
230 // Expand any composed subreg indices.
231 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
232 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
233 // expanded subreg indices recursively.
234 SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
235 for (unsigned i = 0; i != Indices.size(); ++i) {
236 CodeGenSubRegIndex *Idx = Indices[i];
237 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
238 CodeGenRegister *SR = SubRegs[Idx];
239 const SubRegMap &Map = SR->computeSubRegs(RegBank);
241 // Look at the possible compositions of Idx.
242 // They may not all be supported by SR.
243 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
244 E = Comps.end(); I != E; ++I) {
245 SubRegMap::const_iterator SRI = Map.find(I->first);
246 if (SRI == Map.end())
247 continue; // Idx + I->first doesn't exist in SR.
248 // Add I->second as a name for the subreg SRI->second, assuming it is
249 // orphaned, and the name isn't already used for something else.
250 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
252 // We found a new name for the orphaned sub-register.
253 SubRegs.insert(std::make_pair(I->second, SRI->second));
254 Indices.push_back(I->second);
258 // Now Orphans contains the inherited subregisters without a direct index.
259 // Create inferred indexes for all missing entries.
260 // Work backwards in the Indices vector in order to compose subregs bottom-up.
261 // Consider this subreg sequence:
263 // qsub_1 -> dsub_0 -> ssub_0
265 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
266 // can be reached in two different ways:
271 // We pick the latter composition because another register may have [dsub_0,
272 // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The
273 // dsub_2 -> ssub_0 composition can be shared.
274 while (!Indices.empty() && !Orphans.empty()) {
275 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
276 CodeGenRegister *SR = SubRegs[Idx];
277 const SubRegMap &Map = SR->computeSubRegs(RegBank);
278 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
280 if (Orphans.erase(SI->second))
281 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
284 // Compute the inverse SubReg -> Idx map.
285 for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end();
287 if (SI->second == this) {
290 Loc = TheDef->getLoc();
291 throw TGError(Loc, "Register " + getName() +
292 " has itself as a sub-register");
294 // Ensure that every sub-register has a unique name.
295 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
296 SubReg2Idx.insert(std::make_pair(SI->second, SI->first)).first;
297 if (Ins->second == SI->first)
299 // Trouble: Two different names for SI->second.
302 Loc = TheDef->getLoc();
303 throw TGError(Loc, "Sub-register can't have two names: " +
304 SI->second->getName() + " available as " +
305 SI->first->getName() + " and " + Ins->second->getName());
308 // Derive possible names for sub-register concatenations from any explicit
309 // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
310 // that getConcatSubRegIndex() won't invent any concatenated indices that the
311 // user already specified.
312 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
313 CodeGenRegister *SR = ExplicitSubRegs[i];
314 if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1)
317 // SR is composed of multiple sub-regs. Find their names in this register.
318 SmallVector<CodeGenSubRegIndex*, 8> Parts;
319 for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j)
320 Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
322 // Offer this as an existing spelling for the concatenation of Parts.
323 RegBank.addConcatSubRegIndex(Parts, ExplicitSubRegIndices[i]);
326 // Initialize RegUnitList. Because getSubRegs is called recursively, this
327 // processes the register hierarchy in postorder.
329 // Inherit all sub-register units. It is good enough to look at the explicit
330 // sub-registers, the other registers won't contribute any more units.
331 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
332 CodeGenRegister *SR = ExplicitSubRegs[i];
333 // Explicit sub-registers are usually disjoint, so this is a good way of
334 // computing the union. We may pick up a few duplicates that will be
336 unsigned N = RegUnits.size();
337 RegUnits.append(SR->RegUnits.begin(), SR->RegUnits.end());
338 std::inplace_merge(RegUnits.begin(), RegUnits.begin() + N, RegUnits.end());
340 RegUnits.erase(std::unique(RegUnits.begin(), RegUnits.end()), RegUnits.end());
342 // Absent any ad hoc aliasing, we create one register unit per leaf register.
343 // These units correspond to the maximal cliques in the register overlap
344 // graph which is optimal.
346 // When there is ad hoc aliasing, we simply create one unit per edge in the
347 // undirected ad hoc aliasing graph. Technically, we could do better by
348 // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
349 // are extremely rare anyway (I've never seen one), so we don't bother with
350 // the added complexity.
351 for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
352 CodeGenRegister *AR = ExplicitAliases[i];
353 // Only visit each edge once.
354 if (AR->SubRegsComplete)
356 // Create a RegUnit representing this alias edge, and add it to both
358 unsigned Unit = RegBank.newRegUnit(this, AR);
359 RegUnits.push_back(Unit);
360 AR->RegUnits.push_back(Unit);
363 // Finally, create units for leaf registers without ad hoc aliases. Note that
364 // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
365 // necessary. This means the aliasing leaf registers can share a single unit.
366 if (RegUnits.empty())
367 RegUnits.push_back(RegBank.newRegUnit(this));
369 // We have now computed the native register units. More may be adopted later
370 // for balancing purposes.
371 NumNativeRegUnits = RegUnits.size();
376 // In a register that is covered by its sub-registers, try to find redundant
377 // sub-registers. For example:
383 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
384 // the register definition.
386 // The explicitly specified registers form a tree. This function discovers
387 // sub-register relationships that would force a DAG.
389 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
390 // Collect new sub-registers first, add them later.
391 SmallVector<SubRegMap::value_type, 8> NewSubRegs;
393 // Look at the leading super-registers of each sub-register. Those are the
394 // candidates for new sub-registers, assuming they are fully contained in
396 for (SubRegMap::iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I){
397 const CodeGenRegister *SubReg = I->second;
398 const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
399 for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
400 CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
401 // Already got this sub-register?
402 if (Cand == this || getSubRegIndex(Cand))
404 // Check if each component of Cand is already a sub-register.
405 // We know that the first component is I->second, and is present with the
407 SmallVector<CodeGenSubRegIndex*, 8> Parts(1, I->first);
408 assert(!Cand->ExplicitSubRegs.empty() &&
409 "Super-register has no sub-registers");
410 for (unsigned j = 1, e = Cand->ExplicitSubRegs.size(); j != e; ++j) {
411 if (CodeGenSubRegIndex *Idx = getSubRegIndex(Cand->ExplicitSubRegs[j]))
412 Parts.push_back(Idx);
414 // Sub-register doesn't exist.
419 // If some Cand sub-register is not part of this register, or if Cand only
420 // has one sub-register, there is nothing to do.
421 if (Parts.size() <= 1)
424 // Each part of Cand is a sub-register of this. Make the full Cand also
425 // a sub-register with a concatenated sub-register index.
426 CodeGenSubRegIndex *Concat= RegBank.getConcatSubRegIndex(Parts);
427 NewSubRegs.push_back(std::make_pair(Concat, Cand));
431 // Now add all the new sub-registers.
432 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
433 // Don't add Cand if another sub-register is already using the index.
434 if (!SubRegs.insert(NewSubRegs[i]).second)
437 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
438 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
439 SubReg2Idx.insert(std::make_pair(NewSubReg, NewIdx));
442 // Create sub-register index composition maps for the synthesized indices.
443 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
444 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
445 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
446 for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
447 SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
448 CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
450 throw TGError(TheDef->getLoc(), "No SubRegIndex for " +
451 SI->second->getName() + " in " + getName());
452 NewIdx->addComposite(SI->first, SubIdx);
457 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
458 // Only visit each register once.
459 if (SuperRegsComplete)
461 SuperRegsComplete = true;
463 // Make sure all sub-registers have been visited first, so the super-reg
464 // lists will be topologically ordered.
465 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
467 I->second->computeSuperRegs(RegBank);
469 // Now add this as a super-register on all sub-registers.
470 // Also compute the TopoSigId in post-order.
472 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
474 // Topological signature computed from SubIdx, TopoId(SubReg).
475 // Loops and idempotent indices have TopoSig = ~0u.
476 Id.push_back(I->first->EnumValue);
477 Id.push_back(I->second->TopoSig);
479 // Don't add duplicate entries.
480 if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
482 I->second->SuperRegs.push_back(this);
484 TopoSig = RegBank.getTopoSig(Id);
488 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
489 CodeGenRegBank &RegBank) const {
490 assert(SubRegsComplete && "Must precompute sub-registers");
491 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
492 CodeGenRegister *SR = ExplicitSubRegs[i];
494 SR->addSubRegsPreOrder(OSet, RegBank);
496 // Add any secondary sub-registers that weren't part of the explicit tree.
497 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
499 OSet.insert(I->second);
502 // Compute overlapping registers.
504 // The standard set is all super-registers and all sub-registers, but the
505 // target description can add arbitrary overlapping registers via the 'Aliases'
506 // field. This complicates things, but we can compute overlapping sets using
507 // the following rules:
509 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
511 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
515 // overlap(A, B) iff there exists:
516 // A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
517 // A' = B' or A' in aliases(B') or B' in aliases(A').
519 // Here subregs(A) is the full flattened sub-register set returned by
520 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
521 // description of register A.
523 // This also implies that registers with a common sub-register are considered
524 // overlapping. This can happen when forming register pairs:
530 // In this case, we will infer an overlap between P0 and P1 because of the
531 // shared sub-register R1. There is no overlap between P0 and P2.
533 void CodeGenRegister::computeOverlaps(CodeGenRegister::Set &Overlaps,
534 const CodeGenRegBank &RegBank) const {
535 assert(!RegUnits.empty() && "Compute register units before overlaps.");
537 // Register units are assigned such that the overlapping registers are the
538 // super-registers of the root registers of the register units.
539 for (unsigned rui = 0, rue = RegUnits.size(); rui != rue; ++rui) {
540 const RegUnit &RU = RegBank.getRegUnit(RegUnits[rui]);
541 ArrayRef<const CodeGenRegister*> Roots = RU.getRoots();
542 for (unsigned ri = 0, re = Roots.size(); ri != re; ++ri) {
543 const CodeGenRegister *Root = Roots[ri];
544 Overlaps.insert(Root);
545 ArrayRef<const CodeGenRegister*> Supers = Root->getSuperRegs();
546 Overlaps.insert(Supers.begin(), Supers.end());
551 // Get the sum of this register's unit weights.
552 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
554 for (RegUnitList::const_iterator I = RegUnits.begin(), E = RegUnits.end();
556 Weight += RegBank.getRegUnit(*I).Weight;
561 //===----------------------------------------------------------------------===//
563 //===----------------------------------------------------------------------===//
565 // A RegisterTuples def is used to generate pseudo-registers from lists of
566 // sub-registers. We provide a SetTheory expander class that returns the new
569 struct TupleExpander : SetTheory::Expander {
570 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
571 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
572 unsigned Dim = Indices.size();
573 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
574 if (Dim != SubRegs->getSize())
575 throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
577 throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
579 // Evaluate the sub-register lists to be zipped.
580 unsigned Length = ~0u;
581 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
582 for (unsigned i = 0; i != Dim; ++i) {
583 ST.evaluate(SubRegs->getElement(i), Lists[i]);
584 Length = std::min(Length, unsigned(Lists[i].size()));
590 // Precompute some types.
591 Record *RegisterCl = Def->getRecords().getClass("Register");
592 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
593 StringInit *BlankName = StringInit::get("");
596 for (unsigned n = 0; n != Length; ++n) {
598 Record *Proto = Lists[0][n];
599 std::vector<Init*> Tuple;
600 unsigned CostPerUse = 0;
601 for (unsigned i = 0; i != Dim; ++i) {
602 Record *Reg = Lists[i][n];
604 Name += Reg->getName();
605 Tuple.push_back(DefInit::get(Reg));
606 CostPerUse = std::max(CostPerUse,
607 unsigned(Reg->getValueAsInt("CostPerUse")));
610 // Create a new Record representing the synthesized register. This record
611 // is only for consumption by CodeGenRegister, it is not added to the
613 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
616 // Copy Proto super-classes.
617 for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
618 NewReg->addSuperClass(Proto->getSuperClasses()[i]);
620 // Copy Proto fields.
621 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
622 RecordVal RV = Proto->getValues()[i];
624 // Skip existing fields, like NAME.
625 if (NewReg->getValue(RV.getNameInit()))
628 StringRef Field = RV.getName();
630 // Replace the sub-register list with Tuple.
631 if (Field == "SubRegs")
632 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
634 // Provide a blank AsmName. MC hacks are required anyway.
635 if (Field == "AsmName")
636 RV.setValue(BlankName);
638 // CostPerUse is aggregated from all Tuple members.
639 if (Field == "CostPerUse")
640 RV.setValue(IntInit::get(CostPerUse));
642 // Composite registers are always covered by sub-registers.
643 if (Field == "CoveredBySubRegs")
644 RV.setValue(BitInit::get(true));
646 // Copy fields from the RegisterTuples def.
647 if (Field == "SubRegIndices" ||
648 Field == "CompositeIndices") {
649 NewReg->addValue(*Def->getValue(Field));
653 // Some fields get their default uninitialized value.
654 if (Field == "DwarfNumbers" ||
655 Field == "DwarfAlias" ||
656 Field == "Aliases") {
657 if (const RecordVal *DefRV = RegisterCl->getValue(Field))
658 NewReg->addValue(*DefRV);
662 // Everything else is copied from Proto.
663 NewReg->addValue(RV);
670 //===----------------------------------------------------------------------===//
671 // CodeGenRegisterClass
672 //===----------------------------------------------------------------------===//
674 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
677 TopoSigs(RegBank.getNumTopoSigs()),
679 // Rename anonymous register classes.
680 if (R->getName().size() > 9 && R->getName()[9] == '.') {
681 static unsigned AnonCounter = 0;
682 R->setName("AnonRegClass_"+utostr(AnonCounter++));
685 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
686 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
687 Record *Type = TypeList[i];
688 if (!Type->isSubClassOf("ValueType"))
689 throw "RegTypes list member '" + Type->getName() +
690 "' does not derive from the ValueType class!";
691 VTs.push_back(getValueType(Type));
693 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
695 // Allocation order 0 is the full set. AltOrders provides others.
696 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
697 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
698 Orders.resize(1 + AltOrders->size());
700 // Default allocation order always contains all registers.
701 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
702 Orders[0].push_back((*Elements)[i]);
703 const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
705 TopoSigs.set(Reg->getTopoSig());
708 // Alternative allocation orders may be subsets.
709 SetTheory::RecSet Order;
710 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
711 RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
712 Orders[1 + i].append(Order.begin(), Order.end());
713 // Verify that all altorder members are regclass members.
714 while (!Order.empty()) {
715 CodeGenRegister *Reg = RegBank.getReg(Order.back());
718 throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
719 " is not a class member");
723 // Allow targets to override the size in bits of the RegisterClass.
724 unsigned Size = R->getValueAsInt("Size");
726 Namespace = R->getValueAsString("Namespace");
727 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
728 SpillAlignment = R->getValueAsInt("Alignment");
729 CopyCost = R->getValueAsInt("CopyCost");
730 Allocatable = R->getValueAsBit("isAllocatable");
731 AltOrderSelect = R->getValueAsString("AltOrderSelect");
734 // Create an inferred register class that was missing from the .td files.
735 // Most properties will be inherited from the closest super-class after the
736 // class structure has been computed.
737 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
738 StringRef Name, Key Props)
739 : Members(*Props.Members),
742 TopoSigs(RegBank.getNumTopoSigs()),
744 SpillSize(Props.SpillSize),
745 SpillAlignment(Props.SpillAlignment),
748 for (CodeGenRegister::Set::iterator I = Members.begin(), E = Members.end();
750 TopoSigs.set((*I)->getTopoSig());
753 // Compute inherited propertied for a synthesized register class.
754 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
755 assert(!getDef() && "Only synthesized classes can inherit properties");
756 assert(!SuperClasses.empty() && "Synthesized class without super class");
758 // The last super-class is the smallest one.
759 CodeGenRegisterClass &Super = *SuperClasses.back();
761 // Most properties are copied directly.
762 // Exceptions are members, size, and alignment
763 Namespace = Super.Namespace;
765 CopyCost = Super.CopyCost;
766 Allocatable = Super.Allocatable;
767 AltOrderSelect = Super.AltOrderSelect;
769 // Copy all allocation orders, filter out foreign registers from the larger
771 Orders.resize(Super.Orders.size());
772 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
773 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
774 if (contains(RegBank.getReg(Super.Orders[i][j])))
775 Orders[i].push_back(Super.Orders[i][j]);
778 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
779 return Members.count(Reg);
783 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
784 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
785 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
786 E = K.Members->end(); I != E; ++I)
787 OS << ", " << (*I)->getName();
792 // This is a simple lexicographical order that can be used to search for sets.
793 // It is not the same as the topological order provided by TopoOrderRC.
794 bool CodeGenRegisterClass::Key::
795 operator<(const CodeGenRegisterClass::Key &B) const {
796 assert(Members && B.Members);
797 if (*Members != *B.Members)
798 return *Members < *B.Members;
799 if (SpillSize != B.SpillSize)
800 return SpillSize < B.SpillSize;
801 return SpillAlignment < B.SpillAlignment;
804 // Returns true if RC is a strict subclass.
805 // RC is a sub-class of this class if it is a valid replacement for any
806 // instruction operand where a register of this classis required. It must
807 // satisfy these conditions:
809 // 1. All RC registers are also in this.
810 // 2. The RC spill size must not be smaller than our spill size.
811 // 3. RC spill alignment must be compatible with ours.
813 static bool testSubClass(const CodeGenRegisterClass *A,
814 const CodeGenRegisterClass *B) {
815 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
816 A->SpillSize <= B->SpillSize &&
817 std::includes(A->getMembers().begin(), A->getMembers().end(),
818 B->getMembers().begin(), B->getMembers().end(),
819 CodeGenRegister::Less());
822 /// Sorting predicate for register classes. This provides a topological
823 /// ordering that arranges all register classes before their sub-classes.
825 /// Register classes with the same registers, spill size, and alignment form a
826 /// clique. They will be ordered alphabetically.
828 static int TopoOrderRC(const void *PA, const void *PB) {
829 const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
830 const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
834 // Order by ascending spill size.
835 if (A->SpillSize < B->SpillSize)
837 if (A->SpillSize > B->SpillSize)
840 // Order by ascending spill alignment.
841 if (A->SpillAlignment < B->SpillAlignment)
843 if (A->SpillAlignment > B->SpillAlignment)
846 // Order by descending set size. Note that the classes' allocation order may
847 // not have been computed yet. The Members set is always vaild.
848 if (A->getMembers().size() > B->getMembers().size())
850 if (A->getMembers().size() < B->getMembers().size())
853 // Finally order by name as a tie breaker.
854 return StringRef(A->getName()).compare(B->getName());
857 std::string CodeGenRegisterClass::getQualifiedName() const {
858 if (Namespace.empty())
861 return Namespace + "::" + getName();
864 // Compute sub-classes of all register classes.
865 // Assume the classes are ordered topologically.
866 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
867 ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
869 // Visit backwards so sub-classes are seen first.
870 for (unsigned rci = RegClasses.size(); rci; --rci) {
871 CodeGenRegisterClass &RC = *RegClasses[rci - 1];
872 RC.SubClasses.resize(RegClasses.size());
873 RC.SubClasses.set(RC.EnumValue);
875 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
876 for (unsigned s = rci; s != RegClasses.size(); ++s) {
877 if (RC.SubClasses.test(s))
879 CodeGenRegisterClass *SubRC = RegClasses[s];
880 if (!testSubClass(&RC, SubRC))
882 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
884 RC.SubClasses |= SubRC->SubClasses;
887 // Sweep up missed clique members. They will be immediately preceding RC.
888 for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
889 RC.SubClasses.set(s - 1);
892 // Compute the SuperClasses lists from the SubClasses vectors.
893 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
894 const BitVector &SC = RegClasses[rci]->getSubClasses();
895 for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
896 if (unsigned(s) == rci)
898 RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
902 // With the class hierarchy in place, let synthesized register classes inherit
903 // properties from their closest super-class. The iteration order here can
904 // propagate properties down multiple levels.
905 for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
906 if (!RegClasses[rci]->getDef())
907 RegClasses[rci]->inheritProperties(RegBank);
911 CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
912 BitVector &Out) const {
913 DenseMap<CodeGenSubRegIndex*,
914 SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
915 FindI = SuperRegClasses.find(SubIdx);
916 if (FindI == SuperRegClasses.end())
918 for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
919 FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
920 Out.set((*I)->EnumValue);
923 // Populate a unique sorted list of units from a register set.
924 void CodeGenRegisterClass::buildRegUnitSet(
925 std::vector<unsigned> &RegUnits) const {
926 std::vector<unsigned> TmpUnits;
927 for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
928 TmpUnits.push_back(*UnitI);
929 std::sort(TmpUnits.begin(), TmpUnits.end());
930 std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
931 std::back_inserter(RegUnits));
934 //===----------------------------------------------------------------------===//
936 //===----------------------------------------------------------------------===//
938 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) {
939 // Configure register Sets to understand register classes and tuples.
940 Sets.addFieldExpander("RegisterClass", "MemberList");
941 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
942 Sets.addExpander("RegisterTuples", new TupleExpander());
944 // Read in the user-defined (named) sub-register indices.
945 // More indices will be synthesized later.
946 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
947 std::sort(SRIs.begin(), SRIs.end(), LessRecord());
948 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
949 getSubRegIdx(SRIs[i]);
950 // Build composite maps from ComposedOf fields.
951 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
952 SubRegIndices[i]->updateComponents(*this);
954 // Read in the register definitions.
955 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
956 std::sort(Regs.begin(), Regs.end(), LessRecord());
957 Registers.reserve(Regs.size());
958 // Assign the enumeration values.
959 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
962 // Expand tuples and number the new registers.
963 std::vector<Record*> Tups =
964 Records.getAllDerivedDefinitions("RegisterTuples");
965 for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
966 const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
967 for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
968 getReg((*TupRegs)[j]);
971 // Now all the registers are known. Build the object graph of explicit
972 // register-register references.
973 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
974 Registers[i]->buildObjectGraph(*this);
976 // Precompute all sub-register maps.
977 // This will create Composite entries for all inferred sub-register indices.
978 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
979 Registers[i]->computeSubRegs(*this);
981 // Infer even more sub-registers by combining leading super-registers.
982 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
983 if (Registers[i]->CoveredBySubRegs)
984 Registers[i]->computeSecondarySubRegs(*this);
986 // After the sub-register graph is complete, compute the topologically
987 // ordered SuperRegs list.
988 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
989 Registers[i]->computeSuperRegs(*this);
991 // Native register units are associated with a leaf register. They've all been
993 NumNativeRegUnits = RegUnits.size();
995 // Read in register class definitions.
996 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
998 throw std::string("No 'RegisterClass' subclasses defined!");
1000 // Allocate user-defined register classes.
1001 RegClasses.reserve(RCs.size());
1002 for (unsigned i = 0, e = RCs.size(); i != e; ++i)
1003 addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
1005 // Infer missing classes to create a full algebra.
1006 computeInferredRegisterClasses();
1008 // Order register classes topologically and assign enum values.
1009 array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
1010 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
1011 RegClasses[i]->EnumValue = i;
1012 CodeGenRegisterClass::computeSubClasses(*this);
1015 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1017 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1018 CodeGenSubRegIndex *Idx = new CodeGenSubRegIndex(Name, Namespace,
1019 SubRegIndices.size() + 1);
1020 SubRegIndices.push_back(Idx);
1024 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1025 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1028 Idx = new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
1029 SubRegIndices.push_back(Idx);
1033 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1034 CodeGenRegister *&Reg = Def2Reg[Def];
1037 Reg = new CodeGenRegister(Def, Registers.size() + 1);
1038 Registers.push_back(Reg);
1042 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1043 RegClasses.push_back(RC);
1045 if (Record *Def = RC->getDef())
1046 Def2RC.insert(std::make_pair(Def, RC));
1048 // Duplicate classes are rejected by insert().
1049 // That's OK, we only care about the properties handled by CGRC::Key.
1050 CodeGenRegisterClass::Key K(*RC);
1051 Key2RC.insert(std::make_pair(K, RC));
1054 // Create a synthetic sub-class if it is missing.
1055 CodeGenRegisterClass*
1056 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1057 const CodeGenRegister::Set *Members,
1059 // Synthetic sub-class has the same size and alignment as RC.
1060 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
1061 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1062 if (FoundI != Key2RC.end())
1063 return FoundI->second;
1065 // Sub-class doesn't exist, create a new one.
1066 CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(*this, Name, K);
1071 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1072 if (CodeGenRegisterClass *RC = Def2RC[Def])
1075 throw TGError(Def->getLoc(), "Not a known RegisterClass!");
1079 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1080 CodeGenSubRegIndex *B) {
1081 // Look for an existing entry.
1082 CodeGenSubRegIndex *Comp = A->compose(B);
1086 // None exists, synthesize one.
1087 std::string Name = A->getName() + "_then_" + B->getName();
1088 Comp = createSubRegIndex(Name, A->getNamespace());
1089 A->addComposite(B, Comp);
1093 CodeGenSubRegIndex *CodeGenRegBank::
1094 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex*, 8> &Parts) {
1095 assert(Parts.size() > 1 && "Need two parts to concatenate");
1097 // Look for an existing entry.
1098 CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1102 // None exists, synthesize one.
1103 std::string Name = Parts.front()->getName();
1104 for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1106 Name += Parts[i]->getName();
1108 return Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1111 void CodeGenRegBank::computeComposites() {
1112 // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1113 // and many registers will share TopoSigs on regular architectures.
1114 BitVector TopoSigs(getNumTopoSigs());
1116 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1117 CodeGenRegister *Reg1 = Registers[i];
1119 // Skip identical subreg structures already processed.
1120 if (TopoSigs.test(Reg1->getTopoSig()))
1122 TopoSigs.set(Reg1->getTopoSig());
1124 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
1125 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1126 e1 = SRM1.end(); i1 != e1; ++i1) {
1127 CodeGenSubRegIndex *Idx1 = i1->first;
1128 CodeGenRegister *Reg2 = i1->second;
1129 // Ignore identity compositions.
1132 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1133 // Try composing Idx1 with another SubRegIndex.
1134 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1135 e2 = SRM2.end(); i2 != e2; ++i2) {
1136 CodeGenSubRegIndex *Idx2 = i2->first;
1137 CodeGenRegister *Reg3 = i2->second;
1138 // Ignore identity compositions.
1141 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1142 CodeGenSubRegIndex *Idx3 = Reg1->getSubRegIndex(Reg3);
1143 assert(Idx3 && "Sub-register doesn't have an index");
1145 // Conflicting composition? Emit a warning but allow it.
1146 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3))
1147 PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1148 " and " + Idx2->getQualifiedName() +
1149 " compose ambiguously as " + Prev->getQualifiedName() +
1150 " or " + Idx3->getQualifiedName());
1155 // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
1156 // compositions, so remove any mappings of that form.
1157 for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
1158 SubRegIndices[i]->cleanComposites();
1162 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1163 // the transitive closure of the union of overlapping register
1164 // classes. Together, the UberRegSets form a partition of the registers. If we
1165 // consider overlapping register classes to be connected, then each UberRegSet
1166 // is a set of connected components.
1168 // An UberRegSet will likely be a horizontal slice of register names of
1169 // the same width. Nontrivial subregisters should then be in a separate
1170 // UberRegSet. But this property isn't required for valid computation of
1171 // register unit weights.
1173 // A Weight field caches the max per-register unit weight in each UberRegSet.
1175 // A set of SingularDeterminants flags single units of some register in this set
1176 // for which the unit weight equals the set weight. These units should not have
1177 // their weight increased.
1179 CodeGenRegister::Set Regs;
1181 CodeGenRegister::RegUnitList SingularDeterminants;
1183 UberRegSet(): Weight(0) {}
1187 // Partition registers into UberRegSets, where each set is the transitive
1188 // closure of the union of overlapping register classes.
1190 // UberRegSets[0] is a special non-allocatable set.
1191 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1192 std::vector<UberRegSet*> &RegSets,
1193 CodeGenRegBank &RegBank) {
1195 const std::vector<CodeGenRegister*> &Registers = RegBank.getRegisters();
1197 // The Register EnumValue is one greater than its index into Registers.
1198 assert(Registers.size() == Registers[Registers.size()-1]->EnumValue &&
1199 "register enum value mismatch");
1201 // For simplicitly make the SetID the same as EnumValue.
1202 IntEqClasses UberSetIDs(Registers.size()+1);
1203 std::set<unsigned> AllocatableRegs;
1204 for (unsigned i = 0, e = RegBank.getRegClasses().size(); i != e; ++i) {
1206 CodeGenRegisterClass *RegClass = RegBank.getRegClasses()[i];
1207 if (!RegClass->Allocatable)
1210 const CodeGenRegister::Set &Regs = RegClass->getMembers();
1214 unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1215 assert(USetID && "register number 0 is invalid");
1217 AllocatableRegs.insert((*Regs.begin())->EnumValue);
1218 for (CodeGenRegister::Set::const_iterator I = llvm::next(Regs.begin()),
1219 E = Regs.end(); I != E; ++I) {
1220 AllocatableRegs.insert((*I)->EnumValue);
1221 UberSetIDs.join(USetID, (*I)->EnumValue);
1224 // Combine non-allocatable regs.
1225 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1226 unsigned RegNum = Registers[i]->EnumValue;
1227 if (AllocatableRegs.count(RegNum))
1230 UberSetIDs.join(0, RegNum);
1232 UberSetIDs.compress();
1234 // Make the first UberSet a special unallocatable set.
1235 unsigned ZeroID = UberSetIDs[0];
1237 // Insert Registers into the UberSets formed by union-find.
1238 // Do not resize after this.
1239 UberSets.resize(UberSetIDs.getNumClasses());
1240 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1241 const CodeGenRegister *Reg = Registers[i];
1242 unsigned USetID = UberSetIDs[Reg->EnumValue];
1245 else if (USetID == ZeroID)
1248 UberRegSet *USet = &UberSets[USetID];
1249 USet->Regs.insert(Reg);
1254 // Recompute each UberSet weight after changing unit weights.
1255 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1256 CodeGenRegBank &RegBank) {
1257 // Skip the first unallocatable set.
1258 for (std::vector<UberRegSet>::iterator I = llvm::next(UberSets.begin()),
1259 E = UberSets.end(); I != E; ++I) {
1261 // Initialize all unit weights in this set, and remember the max units/reg.
1262 const CodeGenRegister *Reg = 0;
1263 unsigned MaxWeight = 0, Weight = 0;
1264 for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1265 if (Reg != UnitI.getReg()) {
1266 if (Weight > MaxWeight)
1268 Reg = UnitI.getReg();
1271 unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1274 RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1278 if (Weight > MaxWeight)
1281 // Update the set weight.
1282 I->Weight = MaxWeight;
1284 // Find singular determinants.
1285 for (CodeGenRegister::Set::iterator RegI = I->Regs.begin(),
1286 RegE = I->Regs.end(); RegI != RegE; ++RegI) {
1287 if ((*RegI)->getRegUnits().size() == 1
1288 && (*RegI)->getWeight(RegBank) == I->Weight)
1289 mergeRegUnits(I->SingularDeterminants, (*RegI)->getRegUnits());
1294 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1295 // a register and its subregisters so that they have the same weight as their
1296 // UberSet. Self-recursion processes the subregister tree in postorder so
1297 // subregisters are normalized first.
1300 // - creates new adopted register units
1301 // - causes superregisters to inherit adopted units
1302 // - increases the weight of "singular" units
1303 // - induces recomputation of UberWeights.
1304 static bool normalizeWeight(CodeGenRegister *Reg,
1305 std::vector<UberRegSet> &UberSets,
1306 std::vector<UberRegSet*> &RegSets,
1307 std::set<unsigned> &NormalRegs,
1308 CodeGenRegister::RegUnitList &NormalUnits,
1309 CodeGenRegBank &RegBank) {
1310 bool Changed = false;
1311 if (!NormalRegs.insert(Reg->EnumValue).second)
1314 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1315 for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1316 SRE = SRM.end(); SRI != SRE; ++SRI) {
1317 if (SRI->second == Reg)
1318 continue; // self-cycles happen
1320 Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1321 NormalRegs, NormalUnits, RegBank);
1323 // Postorder register normalization.
1325 // Inherit register units newly adopted by subregisters.
1326 if (Reg->inheritRegUnits(RegBank))
1327 computeUberWeights(UberSets, RegBank);
1329 // Check if this register is too skinny for its UberRegSet.
1330 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1332 unsigned RegWeight = Reg->getWeight(RegBank);
1333 if (UberSet->Weight > RegWeight) {
1334 // A register unit's weight can be adjusted only if it is the singular unit
1335 // for this register, has not been used to normalize a subregister's set,
1336 // and has not already been used to singularly determine this UberRegSet.
1337 unsigned AdjustUnit = Reg->getRegUnits().front();
1338 if (Reg->getRegUnits().size() != 1
1339 || hasRegUnit(NormalUnits, AdjustUnit)
1340 || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1341 // We don't have an adjustable unit, so adopt a new one.
1342 AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1343 Reg->adoptRegUnit(AdjustUnit);
1344 // Adopting a unit does not immediately require recomputing set weights.
1347 // Adjust the existing single unit.
1348 RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1349 // The unit may be shared among sets and registers within this set.
1350 computeUberWeights(UberSets, RegBank);
1355 // Mark these units normalized so superregisters can't change their weights.
1356 mergeRegUnits(NormalUnits, Reg->getRegUnits());
1361 // Compute a weight for each register unit created during getSubRegs.
1363 // The goal is that two registers in the same class will have the same weight,
1364 // where each register's weight is defined as sum of its units' weights.
1365 void CodeGenRegBank::computeRegUnitWeights() {
1366 std::vector<UberRegSet> UberSets;
1367 std::vector<UberRegSet*> RegSets(Registers.size());
1368 computeUberSets(UberSets, RegSets, *this);
1369 // UberSets and RegSets are now immutable.
1371 computeUberWeights(UberSets, *this);
1373 // Iterate over each Register, normalizing the unit weights until reaching
1375 unsigned NumIters = 0;
1376 for (bool Changed = true; Changed; ++NumIters) {
1377 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1379 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1380 CodeGenRegister::RegUnitList NormalUnits;
1381 std::set<unsigned> NormalRegs;
1382 Changed |= normalizeWeight(Registers[i], UberSets, RegSets,
1383 NormalRegs, NormalUnits, *this);
1388 // Find a set in UniqueSets with the same elements as Set.
1389 // Return an iterator into UniqueSets.
1390 static std::vector<RegUnitSet>::const_iterator
1391 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1392 const RegUnitSet &Set) {
1393 std::vector<RegUnitSet>::const_iterator
1394 I = UniqueSets.begin(), E = UniqueSets.end();
1396 if (I->Units == Set.Units)
1402 // Return true if the RUSubSet is a subset of RUSuperSet.
1403 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1404 const std::vector<unsigned> &RUSuperSet) {
1405 return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1406 RUSubSet.begin(), RUSubSet.end());
1409 // Iteratively prune unit sets.
1410 void CodeGenRegBank::pruneUnitSets() {
1411 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1413 // Form an equivalence class of UnitSets with no significant difference.
1414 std::vector<unsigned> SuperSetIDs;
1415 for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1416 SubIdx != EndIdx; ++SubIdx) {
1417 const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1418 unsigned SuperIdx = 0;
1419 for (; SuperIdx != EndIdx; ++SuperIdx) {
1420 if (SuperIdx == SubIdx)
1423 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1424 if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1425 && (SubSet.Units.size() + 3 > SuperSet.Units.size())) {
1429 if (SuperIdx == EndIdx)
1430 SuperSetIDs.push_back(SubIdx);
1432 // Populate PrunedUnitSets with each equivalence class's superset.
1433 std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1434 for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1435 unsigned SuperIdx = SuperSetIDs[i];
1436 PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1437 PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1439 RegUnitSets.swap(PrunedUnitSets);
1442 // Create a RegUnitSet for each RegClass that contains all units in the class
1443 // including adopted units that are necessary to model register pressure. Then
1444 // iteratively compute RegUnitSets such that the union of any two overlapping
1445 // RegUnitSets is repreresented.
1447 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1448 // RegUnitSet that is a superset of that RegUnitClass.
1449 void CodeGenRegBank::computeRegUnitSets() {
1451 // Compute a unique RegUnitSet for each RegClass.
1452 const ArrayRef<CodeGenRegisterClass*> &RegClasses = getRegClasses();
1453 unsigned NumRegClasses = RegClasses.size();
1454 for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1455 if (!RegClasses[RCIdx]->Allocatable)
1458 // Speculatively grow the RegUnitSets to hold the new set.
1459 RegUnitSets.resize(RegUnitSets.size() + 1);
1460 RegUnitSets.back().Name = RegClasses[RCIdx]->getName();
1462 // Compute a sorted list of units in this class.
1463 RegClasses[RCIdx]->buildRegUnitSet(RegUnitSets.back().Units);
1465 // Find an existing RegUnitSet.
1466 std::vector<RegUnitSet>::const_iterator SetI =
1467 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1468 if (SetI != llvm::prior(RegUnitSets.end()))
1469 RegUnitSets.pop_back();
1472 // Iteratively prune unit sets.
1475 // Iterate over all unit sets, including new ones added by this loop.
1476 unsigned NumRegUnitSubSets = RegUnitSets.size();
1477 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1478 // In theory, this is combinatorial. In practice, it needs to be bounded
1479 // by a small number of sets for regpressure to be efficient.
1480 // If the assert is hit, we need to implement pruning.
1481 assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1483 // Compare new sets with all original classes.
1484 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1485 SearchIdx != EndIdx; ++SearchIdx) {
1486 std::set<unsigned> Intersection;
1487 std::set_intersection(RegUnitSets[Idx].Units.begin(),
1488 RegUnitSets[Idx].Units.end(),
1489 RegUnitSets[SearchIdx].Units.begin(),
1490 RegUnitSets[SearchIdx].Units.end(),
1491 std::inserter(Intersection, Intersection.begin()));
1492 if (Intersection.empty())
1495 // Speculatively grow the RegUnitSets to hold the new set.
1496 RegUnitSets.resize(RegUnitSets.size() + 1);
1497 RegUnitSets.back().Name =
1498 RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1500 std::set_union(RegUnitSets[Idx].Units.begin(),
1501 RegUnitSets[Idx].Units.end(),
1502 RegUnitSets[SearchIdx].Units.begin(),
1503 RegUnitSets[SearchIdx].Units.end(),
1504 std::inserter(RegUnitSets.back().Units,
1505 RegUnitSets.back().Units.begin()));
1507 // Find an existing RegUnitSet, or add the union to the unique sets.
1508 std::vector<RegUnitSet>::const_iterator SetI =
1509 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1510 if (SetI != llvm::prior(RegUnitSets.end()))
1511 RegUnitSets.pop_back();
1515 // Iteratively prune unit sets after inferring supersets.
1518 // For each register class, list the UnitSets that are supersets.
1519 RegClassUnitSets.resize(NumRegClasses);
1520 for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1521 if (!RegClasses[RCIdx]->Allocatable)
1524 // Recompute the sorted list of units in this class.
1525 std::vector<unsigned> RegUnits;
1526 RegClasses[RCIdx]->buildRegUnitSet(RegUnits);
1528 // Don't increase pressure for unallocatable regclasses.
1529 if (RegUnits.empty())
1532 // Find all supersets.
1533 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1534 USIdx != USEnd; ++USIdx) {
1535 if (isRegUnitSubSet(RegUnits, RegUnitSets[USIdx].Units))
1536 RegClassUnitSets[RCIdx].push_back(USIdx);
1538 assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1542 void CodeGenRegBank::computeDerivedInfo() {
1543 computeComposites();
1545 // Compute a weight for each register unit created during getSubRegs.
1546 // This may create adopted register units (with unit # >= NumNativeRegUnits).
1547 computeRegUnitWeights();
1549 // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1550 // supersets for the union of overlapping sets.
1551 computeRegUnitSets();
1555 // Synthesize missing register class intersections.
1557 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1558 // returns a maximal register class for all X.
1560 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1561 for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
1562 CodeGenRegisterClass *RC1 = RC;
1563 CodeGenRegisterClass *RC2 = RegClasses[rci];
1567 // Compute the set intersection of RC1 and RC2.
1568 const CodeGenRegister::Set &Memb1 = RC1->getMembers();
1569 const CodeGenRegister::Set &Memb2 = RC2->getMembers();
1570 CodeGenRegister::Set Intersection;
1571 std::set_intersection(Memb1.begin(), Memb1.end(),
1572 Memb2.begin(), Memb2.end(),
1573 std::inserter(Intersection, Intersection.begin()),
1574 CodeGenRegister::Less());
1576 // Skip disjoint class pairs.
1577 if (Intersection.empty())
1580 // If RC1 and RC2 have different spill sizes or alignments, use the
1581 // larger size for sub-classing. If they are equal, prefer RC1.
1582 if (RC2->SpillSize > RC1->SpillSize ||
1583 (RC2->SpillSize == RC1->SpillSize &&
1584 RC2->SpillAlignment > RC1->SpillAlignment))
1585 std::swap(RC1, RC2);
1587 getOrCreateSubClass(RC1, &Intersection,
1588 RC1->getName() + "_and_" + RC2->getName());
1593 // Synthesize missing sub-classes for getSubClassWithSubReg().
1595 // Make sure that the set of registers in RC with a given SubIdx sub-register
1596 // form a register class. Update RC->SubClassWithSubReg.
1598 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1599 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1600 typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
1601 CodeGenSubRegIndex::Less> SubReg2SetMap;
1603 // Compute the set of registers supporting each SubRegIndex.
1604 SubReg2SetMap SRSets;
1605 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1606 RE = RC->getMembers().end(); RI != RE; ++RI) {
1607 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
1608 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1609 E = SRM.end(); I != E; ++I)
1610 SRSets[I->first].insert(*RI);
1613 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
1614 // numerical order to visit synthetic indices last.
1615 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1616 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1617 SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
1618 // Unsupported SubRegIndex. Skip it.
1619 if (I == SRSets.end())
1621 // In most cases, all RC registers support the SubRegIndex.
1622 if (I->second.size() == RC->getMembers().size()) {
1623 RC->setSubClassWithSubReg(SubIdx, RC);
1626 // This is a real subset. See if we have a matching class.
1627 CodeGenRegisterClass *SubRC =
1628 getOrCreateSubClass(RC, &I->second,
1629 RC->getName() + "_with_" + I->first->getName());
1630 RC->setSubClassWithSubReg(SubIdx, SubRC);
1635 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1637 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1638 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1641 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1642 unsigned FirstSubRegRC) {
1643 SmallVector<std::pair<const CodeGenRegister*,
1644 const CodeGenRegister*>, 16> SSPairs;
1645 BitVector TopoSigs(getNumTopoSigs());
1647 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1648 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1649 CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1650 // Skip indexes that aren't fully supported by RC's registers. This was
1651 // computed by inferSubClassWithSubReg() above which should have been
1653 if (RC->getSubClassWithSubReg(SubIdx) != RC)
1656 // Build list of (Super, Sub) pairs for this SubIdx.
1659 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1660 RE = RC->getMembers().end(); RI != RE; ++RI) {
1661 const CodeGenRegister *Super = *RI;
1662 const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
1663 assert(Sub && "Missing sub-register");
1664 SSPairs.push_back(std::make_pair(Super, Sub));
1665 TopoSigs.set(Sub->getTopoSig());
1668 // Iterate over sub-register class candidates. Ignore classes created by
1669 // this loop. They will never be useful.
1670 for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
1672 CodeGenRegisterClass *SubRC = RegClasses[rci];
1673 // Topological shortcut: SubRC members have the wrong shape.
1674 if (!TopoSigs.anyCommon(SubRC->getTopoSigs()))
1676 // Compute the subset of RC that maps into SubRC.
1677 CodeGenRegister::Set SubSet;
1678 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1679 if (SubRC->contains(SSPairs[i].second))
1680 SubSet.insert(SSPairs[i].first);
1683 // RC injects completely into SubRC.
1684 if (SubSet.size() == SSPairs.size()) {
1685 SubRC->addSuperRegClass(SubIdx, RC);
1688 // Only a subset of RC maps into SubRC. Make sure it is represented by a
1690 getOrCreateSubClass(RC, &SubSet, RC->getName() +
1691 "_with_" + SubIdx->getName() +
1692 "_in_" + SubRC->getName());
1699 // Infer missing register classes.
1701 void CodeGenRegBank::computeInferredRegisterClasses() {
1702 // When this function is called, the register classes have not been sorted
1703 // and assigned EnumValues yet. That means getSubClasses(),
1704 // getSuperClasses(), and hasSubClass() functions are defunct.
1705 unsigned FirstNewRC = RegClasses.size();
1707 // Visit all register classes, including the ones being added by the loop.
1708 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
1709 CodeGenRegisterClass *RC = RegClasses[rci];
1711 // Synthesize answers for getSubClassWithSubReg().
1712 inferSubClassWithSubReg(RC);
1714 // Synthesize answers for getCommonSubClass().
1715 inferCommonSubClass(RC);
1717 // Synthesize answers for getMatchingSuperRegClass().
1718 inferMatchingSuperRegClass(RC);
1720 // New register classes are created while this loop is running, and we need
1721 // to visit all of them. I particular, inferMatchingSuperRegClass needs
1722 // to match old super-register classes with sub-register classes created
1723 // after inferMatchingSuperRegClass was called. At this point,
1724 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
1725 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
1726 if (rci + 1 == FirstNewRC) {
1727 unsigned NextNewRC = RegClasses.size();
1728 for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
1729 inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
1730 FirstNewRC = NextNewRC;
1735 /// getRegisterClassForRegister - Find the register class that contains the
1736 /// specified physical register. If the register is not in a register class,
1737 /// return null. If the register is in multiple classes, and the classes have a
1738 /// superset-subset relationship and the same set of types, return the
1739 /// superclass. Otherwise return null.
1740 const CodeGenRegisterClass*
1741 CodeGenRegBank::getRegClassForRegister(Record *R) {
1742 const CodeGenRegister *Reg = getReg(R);
1743 ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
1744 const CodeGenRegisterClass *FoundRC = 0;
1745 for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
1746 const CodeGenRegisterClass &RC = *RCs[i];
1747 if (!RC.contains(Reg))
1750 // If this is the first class that contains the register,
1751 // make a note of it and go on to the next class.
1757 // If a register's classes have different types, return null.
1758 if (RC.getValueTypes() != FoundRC->getValueTypes())
1761 // Check to see if the previously found class that contains
1762 // the register is a subclass of the current class. If so,
1763 // prefer the superclass.
1764 if (RC.hasSubClass(FoundRC)) {
1769 // Check to see if the previously found class that contains
1770 // the register is a superclass of the current class. If so,
1771 // prefer the superclass.
1772 if (FoundRC->hasSubClass(&RC))
1775 // Multiple classes, and neither is a superclass of the other.
1782 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1783 SetVector<const CodeGenRegister*> Set;
1785 // First add Regs with all sub-registers.
1786 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1787 CodeGenRegister *Reg = getReg(Regs[i]);
1788 if (Set.insert(Reg))
1789 // Reg is new, add all sub-registers.
1790 // The pre-ordering is not important here.
1791 Reg->addSubRegsPreOrder(Set, *this);
1794 // Second, find all super-registers that are completely covered by the set.
1795 for (unsigned i = 0; i != Set.size(); ++i) {
1796 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1797 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1798 const CodeGenRegister *Super = SR[j];
1799 if (!Super->CoveredBySubRegs || Set.count(Super))
1801 // This new super-register is covered by its sub-registers.
1802 bool AllSubsInSet = true;
1803 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1804 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1805 E = SRM.end(); I != E; ++I)
1806 if (!Set.count(I->second)) {
1807 AllSubsInSet = false;
1810 // All sub-registers in Set, add Super as well.
1811 // We will visit Super later to recheck its super-registers.
1817 // Convert to BitVector.
1818 BitVector BV(Registers.size() + 1);
1819 for (unsigned i = 0, e = Set.size(); i != e; ++i)
1820 BV.set(Set[i]->EnumValue);