Introduce Register Units: Give each leaf register a number.
[oota-llvm.git] / utils / TableGen / CodeGenRegisters.cpp
1 //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines structures to encapsulate information gleaned from the
11 // target register and register class definitions.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
21
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 //                             CodeGenSubRegIndex
26 //===----------------------------------------------------------------------===//
27
28 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
29   : TheDef(R),
30     EnumValue(Enum)
31 {}
32
33 std::string CodeGenSubRegIndex::getNamespace() const {
34   if (TheDef->getValue("Namespace"))
35     return TheDef->getValueAsString("Namespace");
36   else
37     return "";
38 }
39
40 const std::string &CodeGenSubRegIndex::getName() const {
41   return TheDef->getName();
42 }
43
44 std::string CodeGenSubRegIndex::getQualifiedName() const {
45   std::string N = getNamespace();
46   if (!N.empty())
47     N += "::";
48   N += getName();
49   return N;
50 }
51
52 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
53   std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
54   if (Comps.empty())
55     return;
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);
61   if (X)
62     throw TGError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
63 }
64
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;
69     ++i;
70     if (j->first == j->second)
71       Composed.erase(j);
72   }
73 }
74
75 //===----------------------------------------------------------------------===//
76 //                              CodeGenRegister
77 //===----------------------------------------------------------------------===//
78
79 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
80   : TheDef(R),
81     EnumValue(Enum),
82     CostPerUse(R->getValueAsInt("CostPerUse")),
83     CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
84     SubRegsComplete(false)
85 {}
86
87 const std::string &CodeGenRegister::getName() const {
88   return TheDef->getName();
89 }
90
91 // Merge two RegUnitLists maintining the order and removing duplicates.
92 // Overwrites MergedRU in the process.
93 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
94                           const CodeGenRegister::RegUnitList &RRU)
95 {
96   CodeGenRegister::RegUnitList LRU = MergedRU;
97   MergedRU.clear();
98   for (CodeGenRegister::RegUnitList::const_iterator
99          RI = RRU.begin(), RE = RRU.end(), LI = LRU.begin(), LE = LRU.end();
100        RI != RE || LI != LE;) {
101
102     CodeGenRegister::RegUnitList::const_iterator &NextI =
103       (RI != RE && (LI == LE || *RI < *LI)) ? RI : LI;
104
105     if (MergedRU.empty() || *NextI != MergedRU.back())
106       MergedRU.push_back(*NextI);
107     ++NextI;
108   }
109 }
110
111 const CodeGenRegister::SubRegMap &
112 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
113   // Only compute this map once.
114   if (SubRegsComplete)
115     return SubRegs;
116   SubRegsComplete = true;
117
118   std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
119   std::vector<Record*> IdxList = TheDef->getValueAsListOfDefs("SubRegIndices");
120   if (SubList.size() != IdxList.size())
121     throw TGError(TheDef->getLoc(), "Register " + getName() +
122                   " SubRegIndices doesn't match SubRegs");
123
124   // First insert the direct subregs and make sure they are fully indexed.
125   SmallVector<CodeGenSubRegIndex*, 8> Indices;
126   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
127     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
128     CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxList[i]);
129     Indices.push_back(Idx);
130     if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
131       throw TGError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
132                     " appears twice in Register " + getName());
133   }
134
135   // Keep track of inherited subregs and how they can be reached.
136   SmallPtrSet<CodeGenRegister*, 8> Orphans;
137
138   // Clone inherited subregs and place duplicate entries in Orphans.
139   // Here the order is important - earlier subregs take precedence.
140   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
141     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
142     const SubRegMap &Map = SR->getSubRegs(RegBank);
143
144     // Add this as a super-register of SR now all sub-registers are in the list.
145     // This creates a topological ordering, the exact order depends on the
146     // order getSubRegs is called on all registers.
147     SR->SuperRegs.push_back(this);
148
149     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
150          ++SI) {
151       if (!SubRegs.insert(*SI).second)
152         Orphans.insert(SI->second);
153
154       // Noop sub-register indexes are possible, so avoid duplicates.
155       if (SI->second != SR)
156         SI->second->SuperRegs.push_back(this);
157     }
158   }
159
160   // Expand any composed subreg indices.
161   // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
162   // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
163   // expanded subreg indices recursively.
164   for (unsigned i = 0; i != Indices.size(); ++i) {
165     CodeGenSubRegIndex *Idx = Indices[i];
166     const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
167     CodeGenRegister *SR = SubRegs[Idx];
168     const SubRegMap &Map = SR->getSubRegs(RegBank);
169
170     // Look at the possible compositions of Idx.
171     // They may not all be supported by SR.
172     for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
173            E = Comps.end(); I != E; ++I) {
174       SubRegMap::const_iterator SRI = Map.find(I->first);
175       if (SRI == Map.end())
176         continue; // Idx + I->first doesn't exist in SR.
177       // Add I->second as a name for the subreg SRI->second, assuming it is
178       // orphaned, and the name isn't already used for something else.
179       if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
180         continue;
181       // We found a new name for the orphaned sub-register.
182       SubRegs.insert(std::make_pair(I->second, SRI->second));
183       Indices.push_back(I->second);
184     }
185   }
186
187   // Process the composites.
188   ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
189   for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
190     DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
191     if (!Pat)
192       throw TGError(TheDef->getLoc(), "Invalid dag '" +
193                     Comps->getElement(i)->getAsString() +
194                     "' in CompositeIndices");
195     DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
196     if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
197       throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
198                     Pat->getAsString());
199     CodeGenSubRegIndex *BaseIdx = RegBank.getSubRegIdx(BaseIdxInit->getDef());
200
201     // Resolve list of subreg indices into R2.
202     CodeGenRegister *R2 = this;
203     for (DagInit::const_arg_iterator di = Pat->arg_begin(),
204          de = Pat->arg_end(); di != de; ++di) {
205       DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
206       if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
207         throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
208                       Pat->getAsString());
209       CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxInit->getDef());
210       const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
211       SubRegMap::const_iterator ni = R2Subs.find(Idx);
212       if (ni == R2Subs.end())
213         throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
214                       " refers to bad index in " + R2->getName());
215       R2 = ni->second;
216     }
217
218     // Insert composite index. Allow overriding inherited indices etc.
219     SubRegs[BaseIdx] = R2;
220
221     // R2 is no longer an orphan.
222     Orphans.erase(R2);
223   }
224
225   // Now Orphans contains the inherited subregisters without a direct index.
226   // Create inferred indexes for all missing entries.
227   // Work backwards in the Indices vector in order to compose subregs bottom-up.
228   // Consider this subreg sequence:
229   //
230   //   qsub_1 -> dsub_0 -> ssub_0
231   //
232   // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
233   // can be reached in two different ways:
234   //
235   //   qsub_1 -> ssub_0
236   //   dsub_2 -> ssub_0
237   //
238   // We pick the latter composition because another register may have [dsub_0,
239   // dsub_1, dsub_2] subregs without neccessarily having a qsub_1 subreg.  The
240   // dsub_2 -> ssub_0 composition can be shared.
241   while (!Indices.empty() && !Orphans.empty()) {
242     CodeGenSubRegIndex *Idx = Indices.pop_back_val();
243     CodeGenRegister *SR = SubRegs[Idx];
244     const SubRegMap &Map = SR->getSubRegs(RegBank);
245     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
246          ++SI)
247       if (Orphans.erase(SI->second))
248         SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
249   }
250
251   // Initialize RegUnitList. A register with no subregisters creates its own
252   // unit. Otherwise, it inherits all its subregister's units. Because
253   // getSubRegs is called recursively, this processes the register hierarchy in
254   // postorder.
255   //
256   // TODO: We currently assume all register units correspond to a named "leaf"
257   // register. We should also unify register units for ad-hoc register
258   // aliases. This can be done by iteratively merging units for aliasing
259   // registers using a worklist.
260   assert(RegUnits.empty() && "Should only initialize RegUnits once");
261   if (SubRegs.empty()) {
262     RegUnits.push_back(RegBank.newRegUnit());
263   }
264   else {
265     for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
266          I != E; ++I) {
267       // Strangely a register may have itself as a subreg (self-cycle) e.g. XMM.
268       CodeGenRegister *SR = I->second;
269       if (SR == this) {
270         if (RegUnits.empty())
271           RegUnits.push_back(RegBank.newRegUnit());
272         continue;
273       }
274       // Merge the subregister's units into this register's RegUnits.
275       mergeRegUnits(RegUnits, SR->RegUnits);
276     }
277   }
278   return SubRegs;
279 }
280
281 void
282 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
283                                     CodeGenRegBank &RegBank) const {
284   assert(SubRegsComplete && "Must precompute sub-registers");
285   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
286   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
287     CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(Indices[i]);
288     CodeGenRegister *SR = SubRegs.find(Idx)->second;
289     if (OSet.insert(SR))
290       SR->addSubRegsPreOrder(OSet, RegBank);
291   }
292 }
293
294 //===----------------------------------------------------------------------===//
295 //                               RegisterTuples
296 //===----------------------------------------------------------------------===//
297
298 // A RegisterTuples def is used to generate pseudo-registers from lists of
299 // sub-registers. We provide a SetTheory expander class that returns the new
300 // registers.
301 namespace {
302 struct TupleExpander : SetTheory::Expander {
303   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
304     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
305     unsigned Dim = Indices.size();
306     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
307     if (Dim != SubRegs->getSize())
308       throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
309     if (Dim < 2)
310       throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
311
312     // Evaluate the sub-register lists to be zipped.
313     unsigned Length = ~0u;
314     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
315     for (unsigned i = 0; i != Dim; ++i) {
316       ST.evaluate(SubRegs->getElement(i), Lists[i]);
317       Length = std::min(Length, unsigned(Lists[i].size()));
318     }
319
320     if (Length == 0)
321       return;
322
323     // Precompute some types.
324     Record *RegisterCl = Def->getRecords().getClass("Register");
325     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
326     StringInit *BlankName = StringInit::get("");
327
328     // Zip them up.
329     for (unsigned n = 0; n != Length; ++n) {
330       std::string Name;
331       Record *Proto = Lists[0][n];
332       std::vector<Init*> Tuple;
333       unsigned CostPerUse = 0;
334       for (unsigned i = 0; i != Dim; ++i) {
335         Record *Reg = Lists[i][n];
336         if (i) Name += '_';
337         Name += Reg->getName();
338         Tuple.push_back(DefInit::get(Reg));
339         CostPerUse = std::max(CostPerUse,
340                               unsigned(Reg->getValueAsInt("CostPerUse")));
341       }
342
343       // Create a new Record representing the synthesized register. This record
344       // is only for consumption by CodeGenRegister, it is not added to the
345       // RecordKeeper.
346       Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
347       Elts.insert(NewReg);
348
349       // Copy Proto super-classes.
350       for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
351         NewReg->addSuperClass(Proto->getSuperClasses()[i]);
352
353       // Copy Proto fields.
354       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
355         RecordVal RV = Proto->getValues()[i];
356
357         // Skip existing fields, like NAME.
358         if (NewReg->getValue(RV.getNameInit()))
359           continue;
360
361         StringRef Field = RV.getName();
362
363         // Replace the sub-register list with Tuple.
364         if (Field == "SubRegs")
365           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
366
367         // Provide a blank AsmName. MC hacks are required anyway.
368         if (Field == "AsmName")
369           RV.setValue(BlankName);
370
371         // CostPerUse is aggregated from all Tuple members.
372         if (Field == "CostPerUse")
373           RV.setValue(IntInit::get(CostPerUse));
374
375         // Composite registers are always covered by sub-registers.
376         if (Field == "CoveredBySubRegs")
377           RV.setValue(BitInit::get(true));
378
379         // Copy fields from the RegisterTuples def.
380         if (Field == "SubRegIndices" ||
381             Field == "CompositeIndices") {
382           NewReg->addValue(*Def->getValue(Field));
383           continue;
384         }
385
386         // Some fields get their default uninitialized value.
387         if (Field == "DwarfNumbers" ||
388             Field == "DwarfAlias" ||
389             Field == "Aliases") {
390           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
391             NewReg->addValue(*DefRV);
392           continue;
393         }
394
395         // Everything else is copied from Proto.
396         NewReg->addValue(RV);
397       }
398     }
399   }
400 };
401 }
402
403 //===----------------------------------------------------------------------===//
404 //                            CodeGenRegisterClass
405 //===----------------------------------------------------------------------===//
406
407 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
408   : TheDef(R), Name(R->getName()), EnumValue(-1) {
409   // Rename anonymous register classes.
410   if (R->getName().size() > 9 && R->getName()[9] == '.') {
411     static unsigned AnonCounter = 0;
412     R->setName("AnonRegClass_"+utostr(AnonCounter++));
413   }
414
415   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
416   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
417     Record *Type = TypeList[i];
418     if (!Type->isSubClassOf("ValueType"))
419       throw "RegTypes list member '" + Type->getName() +
420         "' does not derive from the ValueType class!";
421     VTs.push_back(getValueType(Type));
422   }
423   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
424
425   // Allocation order 0 is the full set. AltOrders provides others.
426   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
427   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
428   Orders.resize(1 + AltOrders->size());
429
430   // Default allocation order always contains all registers.
431   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
432     Orders[0].push_back((*Elements)[i]);
433     Members.insert(RegBank.getReg((*Elements)[i]));
434   }
435
436   // Alternative allocation orders may be subsets.
437   SetTheory::RecSet Order;
438   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
439     RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
440     Orders[1 + i].append(Order.begin(), Order.end());
441     // Verify that all altorder members are regclass members.
442     while (!Order.empty()) {
443       CodeGenRegister *Reg = RegBank.getReg(Order.back());
444       Order.pop_back();
445       if (!contains(Reg))
446         throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
447                       " is not a class member");
448     }
449   }
450
451   // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
452   ListInit *SRC = R->getValueAsListInit("SubRegClasses");
453   for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
454     DagInit *DAG = dynamic_cast<DagInit*>(*i);
455     if (!DAG) throw "SubRegClasses must contain DAGs";
456     DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
457     Record *RCRec;
458     if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
459       throw "Operator '" + DAG->getOperator()->getAsString() +
460         "' in SubRegClasses is not a RegisterClass";
461     // Iterate over args, all SubRegIndex instances.
462     for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
463          ai != ae; ++ai) {
464       DefInit *Idx = dynamic_cast<DefInit*>(*ai);
465       Record *IdxRec;
466       if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
467         throw "Argument '" + (*ai)->getAsString() +
468           "' in SubRegClasses is not a SubRegIndex";
469       if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
470         throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
471     }
472   }
473
474   // Allow targets to override the size in bits of the RegisterClass.
475   unsigned Size = R->getValueAsInt("Size");
476
477   Namespace = R->getValueAsString("Namespace");
478   SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
479   SpillAlignment = R->getValueAsInt("Alignment");
480   CopyCost = R->getValueAsInt("CopyCost");
481   Allocatable = R->getValueAsBit("isAllocatable");
482   AltOrderSelect = R->getValueAsString("AltOrderSelect");
483 }
484
485 // Create an inferred register class that was missing from the .td files.
486 // Most properties will be inherited from the closest super-class after the
487 // class structure has been computed.
488 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props)
489   : Members(*Props.Members),
490     TheDef(0),
491     Name(Name),
492     EnumValue(-1),
493     SpillSize(Props.SpillSize),
494     SpillAlignment(Props.SpillAlignment),
495     CopyCost(0),
496     Allocatable(true) {
497 }
498
499 // Compute inherited propertied for a synthesized register class.
500 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
501   assert(!getDef() && "Only synthesized classes can inherit properties");
502   assert(!SuperClasses.empty() && "Synthesized class without super class");
503
504   // The last super-class is the smallest one.
505   CodeGenRegisterClass &Super = *SuperClasses.back();
506
507   // Most properties are copied directly.
508   // Exceptions are members, size, and alignment
509   Namespace = Super.Namespace;
510   VTs = Super.VTs;
511   CopyCost = Super.CopyCost;
512   Allocatable = Super.Allocatable;
513   AltOrderSelect = Super.AltOrderSelect;
514
515   // Copy all allocation orders, filter out foreign registers from the larger
516   // super-class.
517   Orders.resize(Super.Orders.size());
518   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
519     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
520       if (contains(RegBank.getReg(Super.Orders[i][j])))
521         Orders[i].push_back(Super.Orders[i][j]);
522 }
523
524 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
525   return Members.count(Reg);
526 }
527
528 namespace llvm {
529   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
530     OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
531     for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
532          E = K.Members->end(); I != E; ++I)
533       OS << ", " << (*I)->getName();
534     return OS << " }";
535   }
536 }
537
538 // This is a simple lexicographical order that can be used to search for sets.
539 // It is not the same as the topological order provided by TopoOrderRC.
540 bool CodeGenRegisterClass::Key::
541 operator<(const CodeGenRegisterClass::Key &B) const {
542   assert(Members && B.Members);
543   if (*Members != *B.Members)
544     return *Members < *B.Members;
545   if (SpillSize != B.SpillSize)
546     return SpillSize < B.SpillSize;
547   return SpillAlignment < B.SpillAlignment;
548 }
549
550 // Returns true if RC is a strict subclass.
551 // RC is a sub-class of this class if it is a valid replacement for any
552 // instruction operand where a register of this classis required. It must
553 // satisfy these conditions:
554 //
555 // 1. All RC registers are also in this.
556 // 2. The RC spill size must not be smaller than our spill size.
557 // 3. RC spill alignment must be compatible with ours.
558 //
559 static bool testSubClass(const CodeGenRegisterClass *A,
560                          const CodeGenRegisterClass *B) {
561   return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
562     A->SpillSize <= B->SpillSize &&
563     std::includes(A->getMembers().begin(), A->getMembers().end(),
564                   B->getMembers().begin(), B->getMembers().end(),
565                   CodeGenRegister::Less());
566 }
567
568 /// Sorting predicate for register classes.  This provides a topological
569 /// ordering that arranges all register classes before their sub-classes.
570 ///
571 /// Register classes with the same registers, spill size, and alignment form a
572 /// clique.  They will be ordered alphabetically.
573 ///
574 static int TopoOrderRC(const void *PA, const void *PB) {
575   const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
576   const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
577   if (A == B)
578     return 0;
579
580   // Order by descending set size.  Note that the classes' allocation order may
581   // not have been computed yet.  The Members set is always vaild.
582   if (A->getMembers().size() > B->getMembers().size())
583     return -1;
584   if (A->getMembers().size() < B->getMembers().size())
585     return 1;
586
587   // Order by ascending spill size.
588   if (A->SpillSize < B->SpillSize)
589     return -1;
590   if (A->SpillSize > B->SpillSize)
591     return 1;
592
593   // Order by ascending spill alignment.
594   if (A->SpillAlignment < B->SpillAlignment)
595     return -1;
596   if (A->SpillAlignment > B->SpillAlignment)
597     return 1;
598
599   // Finally order by name as a tie breaker.
600   return StringRef(A->getName()).compare(B->getName());
601 }
602
603 std::string CodeGenRegisterClass::getQualifiedName() const {
604   if (Namespace.empty())
605     return getName();
606   else
607     return Namespace + "::" + getName();
608 }
609
610 // Compute sub-classes of all register classes.
611 // Assume the classes are ordered topologically.
612 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
613   ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
614
615   // Visit backwards so sub-classes are seen first.
616   for (unsigned rci = RegClasses.size(); rci; --rci) {
617     CodeGenRegisterClass &RC = *RegClasses[rci - 1];
618     RC.SubClasses.resize(RegClasses.size());
619     RC.SubClasses.set(RC.EnumValue);
620
621     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
622     for (unsigned s = rci; s != RegClasses.size(); ++s) {
623       if (RC.SubClasses.test(s))
624         continue;
625       CodeGenRegisterClass *SubRC = RegClasses[s];
626       if (!testSubClass(&RC, SubRC))
627         continue;
628       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
629       // check them again.
630       RC.SubClasses |= SubRC->SubClasses;
631     }
632
633     // Sweep up missed clique members.  They will be immediately preceeding RC.
634     for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
635       RC.SubClasses.set(s - 1);
636   }
637
638   // Compute the SuperClasses lists from the SubClasses vectors.
639   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
640     const BitVector &SC = RegClasses[rci]->getSubClasses();
641     for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
642       if (unsigned(s) == rci)
643         continue;
644       RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
645     }
646   }
647
648   // With the class hierarchy in place, let synthesized register classes inherit
649   // properties from their closest super-class. The iteration order here can
650   // propagate properties down multiple levels.
651   for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
652     if (!RegClasses[rci]->getDef())
653       RegClasses[rci]->inheritProperties(RegBank);
654 }
655
656 void
657 CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
658                                          BitVector &Out) const {
659   DenseMap<CodeGenSubRegIndex*,
660            SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
661     FindI = SuperRegClasses.find(SubIdx);
662   if (FindI == SuperRegClasses.end())
663     return;
664   for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
665        FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
666     Out.set((*I)->EnumValue);
667 }
668
669
670 //===----------------------------------------------------------------------===//
671 //                               CodeGenRegBank
672 //===----------------------------------------------------------------------===//
673
674 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
675   // Configure register Sets to understand register classes and tuples.
676   Sets.addFieldExpander("RegisterClass", "MemberList");
677   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
678   Sets.addExpander("RegisterTuples", new TupleExpander());
679
680   // Read in the user-defined (named) sub-register indices.
681   // More indices will be synthesized later.
682   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
683   std::sort(SRIs.begin(), SRIs.end(), LessRecord());
684   NumNamedIndices = SRIs.size();
685   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
686     getSubRegIdx(SRIs[i]);
687   // Build composite maps from ComposedOf fields.
688   for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
689     SubRegIndices[i]->updateComponents(*this);
690
691   // Read in the register definitions.
692   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
693   std::sort(Regs.begin(), Regs.end(), LessRecord());
694   Registers.reserve(Regs.size());
695   // Assign the enumeration values.
696   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
697     getReg(Regs[i]);
698
699   // Expand tuples and number the new registers.
700   std::vector<Record*> Tups =
701     Records.getAllDerivedDefinitions("RegisterTuples");
702   for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
703     const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
704     for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
705       getReg((*TupRegs)[j]);
706   }
707
708   // Precompute all sub-register maps now all the registers are known.
709   // This will create Composite entries for all inferred sub-register indices.
710   NumRegUnits = 0;
711   for (unsigned i = 0, e = Registers.size(); i != e; ++i)
712     Registers[i]->getSubRegs(*this);
713
714   // Read in register class definitions.
715   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
716   if (RCs.empty())
717     throw std::string("No 'RegisterClass' subclasses defined!");
718
719   // Allocate user-defined register classes.
720   RegClasses.reserve(RCs.size());
721   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
722     addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
723
724   // Infer missing classes to create a full algebra.
725   computeInferredRegisterClasses();
726
727   // Order register classes topologically and assign enum values.
728   array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
729   for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
730     RegClasses[i]->EnumValue = i;
731   CodeGenRegisterClass::computeSubClasses(*this);
732 }
733
734 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
735   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
736   if (Idx)
737     return Idx;
738   Idx = new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
739   SubRegIndices.push_back(Idx);
740   return Idx;
741 }
742
743 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
744   CodeGenRegister *&Reg = Def2Reg[Def];
745   if (Reg)
746     return Reg;
747   Reg = new CodeGenRegister(Def, Registers.size() + 1);
748   Registers.push_back(Reg);
749   return Reg;
750 }
751
752 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
753   RegClasses.push_back(RC);
754
755   if (Record *Def = RC->getDef())
756     Def2RC.insert(std::make_pair(Def, RC));
757
758   // Duplicate classes are rejected by insert().
759   // That's OK, we only care about the properties handled by CGRC::Key.
760   CodeGenRegisterClass::Key K(*RC);
761   Key2RC.insert(std::make_pair(K, RC));
762 }
763
764 // Create a synthetic sub-class if it is missing.
765 CodeGenRegisterClass*
766 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
767                                     const CodeGenRegister::Set *Members,
768                                     StringRef Name) {
769   // Synthetic sub-class has the same size and alignment as RC.
770   CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
771   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
772   if (FoundI != Key2RC.end())
773     return FoundI->second;
774
775   // Sub-class doesn't exist, create a new one.
776   CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K);
777   addToMaps(NewRC);
778   return NewRC;
779 }
780
781 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
782   if (CodeGenRegisterClass *RC = Def2RC[Def])
783     return RC;
784
785   throw TGError(Def->getLoc(), "Not a known RegisterClass!");
786 }
787
788 CodeGenSubRegIndex*
789 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
790                                         CodeGenSubRegIndex *B) {
791   // Look for an existing entry.
792   CodeGenSubRegIndex *Comp = A->compose(B);
793   if (Comp)
794     return Comp;
795
796   // None exists, synthesize one.
797   std::string Name = A->getName() + "_then_" + B->getName();
798   Comp = getSubRegIdx(new Record(Name, SMLoc(), Records));
799   A->addComposite(B, Comp);
800   return Comp;
801 }
802
803 void CodeGenRegBank::computeComposites() {
804   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
805     CodeGenRegister *Reg1 = Registers[i];
806     const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
807     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
808          e1 = SRM1.end(); i1 != e1; ++i1) {
809       CodeGenSubRegIndex *Idx1 = i1->first;
810       CodeGenRegister *Reg2 = i1->second;
811       // Ignore identity compositions.
812       if (Reg1 == Reg2)
813         continue;
814       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
815       // Try composing Idx1 with another SubRegIndex.
816       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
817            e2 = SRM2.end(); i2 != e2; ++i2) {
818       CodeGenSubRegIndex *Idx2 = i2->first;
819         CodeGenRegister *Reg3 = i2->second;
820         // Ignore identity compositions.
821         if (Reg2 == Reg3)
822           continue;
823         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
824         for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
825              e1d = SRM1.end(); i1d != e1d; ++i1d) {
826           if (i1d->second == Reg3) {
827             // Conflicting composition? Emit a warning but allow it.
828             if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, i1d->first))
829               errs() << "Warning: SubRegIndex " << Idx1->getQualifiedName()
830                      << " and " << Idx2->getQualifiedName()
831                      << " compose ambiguously as "
832                      << Prev->getQualifiedName() << " or "
833                      << i1d->first->getQualifiedName() << "\n";
834           }
835         }
836       }
837     }
838   }
839
840   // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
841   // compositions, so remove any mappings of that form.
842   for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
843     SubRegIndices[i]->cleanComposites();
844 }
845
846 // Compute sets of overlapping registers.
847 //
848 // The standard set is all super-registers and all sub-registers, but the
849 // target description can add arbitrary overlapping registers via the 'Aliases'
850 // field. This complicates things, but we can compute overlapping sets using
851 // the following rules:
852 //
853 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
854 //
855 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
856 //
857 // Alternatively:
858 //
859 //    overlap(A, B) iff there exists:
860 //    A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
861 //    A' = B' or A' in aliases(B') or B' in aliases(A').
862 //
863 // Here subregs(A) is the full flattened sub-register set returned by
864 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
865 // description of register A.
866 //
867 // This also implies that registers with a common sub-register are considered
868 // overlapping. This can happen when forming register pairs:
869 //
870 //    P0 = (R0, R1)
871 //    P1 = (R1, R2)
872 //    P2 = (R2, R3)
873 //
874 // In this case, we will infer an overlap between P0 and P1 because of the
875 // shared sub-register R1. There is no overlap between P0 and P2.
876 //
877 void CodeGenRegBank::
878 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
879   assert(Map.empty());
880
881   // Collect overlaps that don't follow from rule 2.
882   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
883     CodeGenRegister *Reg = Registers[i];
884     CodeGenRegister::Set &Overlaps = Map[Reg];
885
886     // Reg overlaps itself.
887     Overlaps.insert(Reg);
888
889     // All super-registers overlap.
890     const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
891     Overlaps.insert(Supers.begin(), Supers.end());
892
893     // Form symmetrical relations from the special Aliases[] lists.
894     std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
895     for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
896       CodeGenRegister *Reg2 = getReg(RegList[i2]);
897       CodeGenRegister::Set &Overlaps2 = Map[Reg2];
898       const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
899       // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
900       Overlaps.insert(Reg2);
901       Overlaps.insert(Supers2.begin(), Supers2.end());
902       Overlaps2.insert(Reg);
903       Overlaps2.insert(Supers.begin(), Supers.end());
904     }
905   }
906
907   // Apply rule 2. and inherit all sub-register overlaps.
908   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
909     CodeGenRegister *Reg = Registers[i];
910     CodeGenRegister::Set &Overlaps = Map[Reg];
911     const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
912     for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
913          e2 = SRM.end(); i2 != e2; ++i2) {
914       CodeGenRegister::Set &Overlaps2 = Map[i2->second];
915       Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
916     }
917   }
918 }
919
920 void CodeGenRegBank::computeDerivedInfo() {
921   computeComposites();
922 }
923
924 //
925 // Synthesize missing register class intersections.
926 //
927 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
928 // returns a maximal register class for all X.
929 //
930 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
931   for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
932     CodeGenRegisterClass *RC1 = RC;
933     CodeGenRegisterClass *RC2 = RegClasses[rci];
934     if (RC1 == RC2)
935       continue;
936
937     // Compute the set intersection of RC1 and RC2.
938     const CodeGenRegister::Set &Memb1 = RC1->getMembers();
939     const CodeGenRegister::Set &Memb2 = RC2->getMembers();
940     CodeGenRegister::Set Intersection;
941     std::set_intersection(Memb1.begin(), Memb1.end(),
942                           Memb2.begin(), Memb2.end(),
943                           std::inserter(Intersection, Intersection.begin()),
944                           CodeGenRegister::Less());
945
946     // Skip disjoint class pairs.
947     if (Intersection.empty())
948       continue;
949
950     // If RC1 and RC2 have different spill sizes or alignments, use the
951     // larger size for sub-classing.  If they are equal, prefer RC1.
952     if (RC2->SpillSize > RC1->SpillSize ||
953         (RC2->SpillSize == RC1->SpillSize &&
954          RC2->SpillAlignment > RC1->SpillAlignment))
955       std::swap(RC1, RC2);
956
957     getOrCreateSubClass(RC1, &Intersection,
958                         RC1->getName() + "_and_" + RC2->getName());
959   }
960 }
961
962 //
963 // Synthesize missing sub-classes for getSubClassWithSubReg().
964 //
965 // Make sure that the set of registers in RC with a given SubIdx sub-register
966 // form a register class.  Update RC->SubClassWithSubReg.
967 //
968 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
969   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
970   typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
971                    CodeGenSubRegIndex::Less> SubReg2SetMap;
972
973   // Compute the set of registers supporting each SubRegIndex.
974   SubReg2SetMap SRSets;
975   for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
976        RE = RC->getMembers().end(); RI != RE; ++RI) {
977     const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
978     for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
979          E = SRM.end(); I != E; ++I)
980       SRSets[I->first].insert(*RI);
981   }
982
983   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
984   // numerical order to visit synthetic indices last.
985   for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
986     CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
987     SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
988     // Unsupported SubRegIndex. Skip it.
989     if (I == SRSets.end())
990       continue;
991     // In most cases, all RC registers support the SubRegIndex.
992     if (I->second.size() == RC->getMembers().size()) {
993       RC->setSubClassWithSubReg(SubIdx, RC);
994       continue;
995     }
996     // This is a real subset.  See if we have a matching class.
997     CodeGenRegisterClass *SubRC =
998       getOrCreateSubClass(RC, &I->second,
999                           RC->getName() + "_with_" + I->first->getName());
1000     RC->setSubClassWithSubReg(SubIdx, SubRC);
1001   }
1002 }
1003
1004 //
1005 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1006 //
1007 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1008 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1009 //
1010
1011 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1012                                                 unsigned FirstSubRegRC) {
1013   SmallVector<std::pair<const CodeGenRegister*,
1014                         const CodeGenRegister*>, 16> SSPairs;
1015
1016   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1017   for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1018     CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1019     // Skip indexes that aren't fully supported by RC's registers. This was
1020     // computed by inferSubClassWithSubReg() above which should have been
1021     // called first.
1022     if (RC->getSubClassWithSubReg(SubIdx) != RC)
1023       continue;
1024
1025     // Build list of (Super, Sub) pairs for this SubIdx.
1026     SSPairs.clear();
1027     for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1028          RE = RC->getMembers().end(); RI != RE; ++RI) {
1029       const CodeGenRegister *Super = *RI;
1030       const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
1031       assert(Sub && "Missing sub-register");
1032       SSPairs.push_back(std::make_pair(Super, Sub));
1033     }
1034
1035     // Iterate over sub-register class candidates.  Ignore classes created by
1036     // this loop. They will never be useful.
1037     for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
1038          ++rci) {
1039       CodeGenRegisterClass *SubRC = RegClasses[rci];
1040       // Compute the subset of RC that maps into SubRC.
1041       CodeGenRegister::Set SubSet;
1042       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1043         if (SubRC->contains(SSPairs[i].second))
1044           SubSet.insert(SSPairs[i].first);
1045       if (SubSet.empty())
1046         continue;
1047       // RC injects completely into SubRC.
1048       if (SubSet.size() == SSPairs.size()) {
1049         SubRC->addSuperRegClass(SubIdx, RC);
1050         continue;
1051       }
1052       // Only a subset of RC maps into SubRC. Make sure it is represented by a
1053       // class.
1054       getOrCreateSubClass(RC, &SubSet, RC->getName() +
1055                           "_with_" + SubIdx->getName() +
1056                           "_in_" + SubRC->getName());
1057     }
1058   }
1059 }
1060
1061
1062 //
1063 // Infer missing register classes.
1064 //
1065 void CodeGenRegBank::computeInferredRegisterClasses() {
1066   // When this function is called, the register classes have not been sorted
1067   // and assigned EnumValues yet.  That means getSubClasses(),
1068   // getSuperClasses(), and hasSubClass() functions are defunct.
1069   unsigned FirstNewRC = RegClasses.size();
1070
1071   // Visit all register classes, including the ones being added by the loop.
1072   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
1073     CodeGenRegisterClass *RC = RegClasses[rci];
1074
1075     // Synthesize answers for getSubClassWithSubReg().
1076     inferSubClassWithSubReg(RC);
1077
1078     // Synthesize answers for getCommonSubClass().
1079     inferCommonSubClass(RC);
1080
1081     // Synthesize answers for getMatchingSuperRegClass().
1082     inferMatchingSuperRegClass(RC);
1083
1084     // New register classes are created while this loop is running, and we need
1085     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
1086     // to match old super-register classes with sub-register classes created
1087     // after inferMatchingSuperRegClass was called.  At this point,
1088     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
1089     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
1090     if (rci + 1 == FirstNewRC) {
1091       unsigned NextNewRC = RegClasses.size();
1092       for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
1093         inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
1094       FirstNewRC = NextNewRC;
1095     }
1096   }
1097 }
1098
1099 /// getRegisterClassForRegister - Find the register class that contains the
1100 /// specified physical register.  If the register is not in a register class,
1101 /// return null. If the register is in multiple classes, and the classes have a
1102 /// superset-subset relationship and the same set of types, return the
1103 /// superclass.  Otherwise return null.
1104 const CodeGenRegisterClass*
1105 CodeGenRegBank::getRegClassForRegister(Record *R) {
1106   const CodeGenRegister *Reg = getReg(R);
1107   ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
1108   const CodeGenRegisterClass *FoundRC = 0;
1109   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
1110     const CodeGenRegisterClass &RC = *RCs[i];
1111     if (!RC.contains(Reg))
1112       continue;
1113
1114     // If this is the first class that contains the register,
1115     // make a note of it and go on to the next class.
1116     if (!FoundRC) {
1117       FoundRC = &RC;
1118       continue;
1119     }
1120
1121     // If a register's classes have different types, return null.
1122     if (RC.getValueTypes() != FoundRC->getValueTypes())
1123       return 0;
1124
1125     // Check to see if the previously found class that contains
1126     // the register is a subclass of the current class. If so,
1127     // prefer the superclass.
1128     if (RC.hasSubClass(FoundRC)) {
1129       FoundRC = &RC;
1130       continue;
1131     }
1132
1133     // Check to see if the previously found class that contains
1134     // the register is a superclass of the current class. If so,
1135     // prefer the superclass.
1136     if (FoundRC->hasSubClass(&RC))
1137       continue;
1138
1139     // Multiple classes, and neither is a superclass of the other.
1140     // Return null.
1141     return 0;
1142   }
1143   return FoundRC;
1144 }
1145
1146 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1147   SetVector<const CodeGenRegister*> Set;
1148
1149   // First add Regs with all sub-registers.
1150   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1151     CodeGenRegister *Reg = getReg(Regs[i]);
1152     if (Set.insert(Reg))
1153       // Reg is new, add all sub-registers.
1154       // The pre-ordering is not important here.
1155       Reg->addSubRegsPreOrder(Set, *this);
1156   }
1157
1158   // Second, find all super-registers that are completely covered by the set.
1159   for (unsigned i = 0; i != Set.size(); ++i) {
1160     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1161     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1162       const CodeGenRegister *Super = SR[j];
1163       if (!Super->CoveredBySubRegs || Set.count(Super))
1164         continue;
1165       // This new super-register is covered by its sub-registers.
1166       bool AllSubsInSet = true;
1167       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1168       for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1169              E = SRM.end(); I != E; ++I)
1170         if (!Set.count(I->second)) {
1171           AllSubsInSet = false;
1172           break;
1173         }
1174       // All sub-registers in Set, add Super as well.
1175       // We will visit Super later to recheck its super-registers.
1176       if (AllSubsInSet)
1177         Set.insert(Super);
1178     }
1179   }
1180
1181   // Convert to BitVector.
1182   BitVector BV(Registers.size() + 1);
1183   for (unsigned i = 0, e = Set.size(); i != e; ++i)
1184     BV.set(Set[i]->EnumValue);
1185   return BV;
1186 }