Table-generated register pressure fixes.
[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/IntEqClasses.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 //                             CodeGenSubRegIndex
27 //===----------------------------------------------------------------------===//
28
29 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
30   : TheDef(R),
31     EnumValue(Enum)
32 {}
33
34 std::string CodeGenSubRegIndex::getNamespace() const {
35   if (TheDef->getValue("Namespace"))
36     return TheDef->getValueAsString("Namespace");
37   else
38     return "";
39 }
40
41 const std::string &CodeGenSubRegIndex::getName() const {
42   return TheDef->getName();
43 }
44
45 std::string CodeGenSubRegIndex::getQualifiedName() const {
46   std::string N = getNamespace();
47   if (!N.empty())
48     N += "::";
49   N += getName();
50   return N;
51 }
52
53 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
54   std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
55   if (Comps.empty())
56     return;
57   if (Comps.size() != 2)
58     throw TGError(TheDef->getLoc(), "ComposedOf must have exactly two entries");
59   CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
60   CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
61   CodeGenSubRegIndex *X = A->addComposite(B, this);
62   if (X)
63     throw TGError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
64 }
65
66 void CodeGenSubRegIndex::cleanComposites() {
67   // Clean out redundant mappings of the form this+X -> X.
68   for (CompMap::iterator i = Composed.begin(), e = Composed.end(); i != e;) {
69     CompMap::iterator j = i;
70     ++i;
71     if (j->first == j->second)
72       Composed.erase(j);
73   }
74 }
75
76 //===----------------------------------------------------------------------===//
77 //                              CodeGenRegister
78 //===----------------------------------------------------------------------===//
79
80 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
81   : TheDef(R),
82     EnumValue(Enum),
83     CostPerUse(R->getValueAsInt("CostPerUse")),
84     CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
85     SubRegsComplete(false)
86 {}
87
88 const std::string &CodeGenRegister::getName() const {
89   return TheDef->getName();
90 }
91
92 namespace {
93 // Iterate over all register units in a set of registers.
94 class RegUnitIterator {
95   CodeGenRegister::Set::const_iterator RegI, RegE;
96   CodeGenRegister::RegUnitList::const_iterator UnitI, UnitE;
97
98 public:
99   RegUnitIterator(const CodeGenRegister::Set &Regs):
100     RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
101
102     if (RegI != RegE) {
103       UnitI = (*RegI)->getRegUnits().begin();
104       UnitE = (*RegI)->getRegUnits().end();
105       advance();
106     }
107   }
108
109   bool isValid() const { return UnitI != UnitE; }
110
111   unsigned operator* () const { assert(isValid()); return *UnitI; };
112
113   const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
114
115   /// Preincrement.  Move to the next unit.
116   void operator++() {
117     assert(isValid() && "Cannot advance beyond the last operand");
118     ++UnitI;
119     advance();
120   }
121
122 protected:
123   void advance() {
124     while (UnitI == UnitE) {
125       if (++RegI == RegE)
126         break;
127       UnitI = (*RegI)->getRegUnits().begin();
128       UnitE = (*RegI)->getRegUnits().end();
129     }
130   }
131 };
132 } // namespace
133
134 // Merge two RegUnitLists maintaining the order and removing duplicates.
135 // Overwrites MergedRU in the process.
136 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
137                           const CodeGenRegister::RegUnitList &RRU) {
138   CodeGenRegister::RegUnitList LRU = MergedRU;
139   MergedRU.clear();
140   std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(),
141                  std::back_inserter(MergedRU));
142 }
143
144 // Return true of this unit appears in RegUnits.
145 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
146   return std::count(RegUnits.begin(), RegUnits.end(), Unit);
147 }
148
149 // Inherit register units from subregisters.
150 // Return true if the RegUnits changed.
151 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
152   unsigned OldNumUnits = RegUnits.size();
153   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
154        I != E; ++I) {
155     // Strangely a register may have itself as a subreg (self-cycle) e.g. XMM.
156     // Only create a unit if no other subregs have units.
157     CodeGenRegister *SR = I->second;
158     if (SR == this) {
159       // RegUnits are only empty during getSubRegs, prior to computing weight.
160       if (RegUnits.empty())
161         RegUnits.push_back(RegBank.newRegUnit(0));
162       continue;
163     }
164     // Merge the subregister's units into this register's RegUnits.
165     mergeRegUnits(RegUnits, SR->RegUnits);
166   }
167   return OldNumUnits != RegUnits.size();
168 }
169
170 const CodeGenRegister::SubRegMap &
171 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) {
172   // Only compute this map once.
173   if (SubRegsComplete)
174     return SubRegs;
175   SubRegsComplete = true;
176
177   std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs");
178   std::vector<Record*> IdxList = TheDef->getValueAsListOfDefs("SubRegIndices");
179   if (SubList.size() != IdxList.size())
180     throw TGError(TheDef->getLoc(), "Register " + getName() +
181                   " SubRegIndices doesn't match SubRegs");
182
183   // First insert the direct subregs and make sure they are fully indexed.
184   SmallVector<CodeGenSubRegIndex*, 8> Indices;
185   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
186     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
187     CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxList[i]);
188     Indices.push_back(Idx);
189     if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
190       throw TGError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
191                     " appears twice in Register " + getName());
192   }
193
194   // Keep track of inherited subregs and how they can be reached.
195   SmallPtrSet<CodeGenRegister*, 8> Orphans;
196
197   // Clone inherited subregs and place duplicate entries in Orphans.
198   // Here the order is important - earlier subregs take precedence.
199   for (unsigned i = 0, e = SubList.size(); i != e; ++i) {
200     CodeGenRegister *SR = RegBank.getReg(SubList[i]);
201     const SubRegMap &Map = SR->getSubRegs(RegBank);
202
203     // Add this as a super-register of SR now all sub-registers are in the list.
204     // This creates a topological ordering, the exact order depends on the
205     // order getSubRegs is called on all registers.
206     SR->SuperRegs.push_back(this);
207
208     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
209          ++SI) {
210       if (!SubRegs.insert(*SI).second)
211         Orphans.insert(SI->second);
212
213       // Noop sub-register indexes are possible, so avoid duplicates.
214       if (SI->second != SR)
215         SI->second->SuperRegs.push_back(this);
216     }
217   }
218
219   // Expand any composed subreg indices.
220   // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
221   // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
222   // expanded subreg indices recursively.
223   for (unsigned i = 0; i != Indices.size(); ++i) {
224     CodeGenSubRegIndex *Idx = Indices[i];
225     const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
226     CodeGenRegister *SR = SubRegs[Idx];
227     const SubRegMap &Map = SR->getSubRegs(RegBank);
228
229     // Look at the possible compositions of Idx.
230     // They may not all be supported by SR.
231     for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
232            E = Comps.end(); I != E; ++I) {
233       SubRegMap::const_iterator SRI = Map.find(I->first);
234       if (SRI == Map.end())
235         continue; // Idx + I->first doesn't exist in SR.
236       // Add I->second as a name for the subreg SRI->second, assuming it is
237       // orphaned, and the name isn't already used for something else.
238       if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
239         continue;
240       // We found a new name for the orphaned sub-register.
241       SubRegs.insert(std::make_pair(I->second, SRI->second));
242       Indices.push_back(I->second);
243     }
244   }
245
246   // Process the composites.
247   ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices");
248   for (unsigned i = 0, e = Comps->size(); i != e; ++i) {
249     DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i));
250     if (!Pat)
251       throw TGError(TheDef->getLoc(), "Invalid dag '" +
252                     Comps->getElement(i)->getAsString() +
253                     "' in CompositeIndices");
254     DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator());
255     if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"))
256       throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
257                     Pat->getAsString());
258     CodeGenSubRegIndex *BaseIdx = RegBank.getSubRegIdx(BaseIdxInit->getDef());
259
260     // Resolve list of subreg indices into R2.
261     CodeGenRegister *R2 = this;
262     for (DagInit::const_arg_iterator di = Pat->arg_begin(),
263          de = Pat->arg_end(); di != de; ++di) {
264       DefInit *IdxInit = dynamic_cast<DefInit*>(*di);
265       if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
266         throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
267                       Pat->getAsString());
268       CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(IdxInit->getDef());
269       const SubRegMap &R2Subs = R2->getSubRegs(RegBank);
270       SubRegMap::const_iterator ni = R2Subs.find(Idx);
271       if (ni == R2Subs.end())
272         throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
273                       " refers to bad index in " + R2->getName());
274       R2 = ni->second;
275     }
276
277     // Insert composite index. Allow overriding inherited indices etc.
278     SubRegs[BaseIdx] = R2;
279
280     // R2 is no longer an orphan.
281     Orphans.erase(R2);
282   }
283
284   // Now Orphans contains the inherited subregisters without a direct index.
285   // Create inferred indexes for all missing entries.
286   // Work backwards in the Indices vector in order to compose subregs bottom-up.
287   // Consider this subreg sequence:
288   //
289   //   qsub_1 -> dsub_0 -> ssub_0
290   //
291   // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
292   // can be reached in two different ways:
293   //
294   //   qsub_1 -> ssub_0
295   //   dsub_2 -> ssub_0
296   //
297   // We pick the latter composition because another register may have [dsub_0,
298   // dsub_1, dsub_2] subregs without neccessarily having a qsub_1 subreg.  The
299   // dsub_2 -> ssub_0 composition can be shared.
300   while (!Indices.empty() && !Orphans.empty()) {
301     CodeGenSubRegIndex *Idx = Indices.pop_back_val();
302     CodeGenRegister *SR = SubRegs[Idx];
303     const SubRegMap &Map = SR->getSubRegs(RegBank);
304     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
305          ++SI)
306       if (Orphans.erase(SI->second))
307         SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
308   }
309
310   // Initialize RegUnitList. A register with no subregisters creates its own
311   // unit. Otherwise, it inherits all its subregister's units. Because
312   // getSubRegs is called recursively, this processes the register hierarchy in
313   // postorder.
314   //
315   // TODO: We currently assume all register units correspond to a named "leaf"
316   // register. We should also unify register units for ad-hoc register
317   // aliases. This can be done by iteratively merging units for aliasing
318   // registers using a worklist.
319   assert(RegUnits.empty() && "Should only initialize RegUnits once");
320   if (SubRegs.empty())
321     RegUnits.push_back(RegBank.newRegUnit(0));
322   else
323     inheritRegUnits(RegBank);
324   return SubRegs;
325 }
326
327 void
328 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
329                                     CodeGenRegBank &RegBank) const {
330   assert(SubRegsComplete && "Must precompute sub-registers");
331   std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices");
332   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
333     CodeGenSubRegIndex *Idx = RegBank.getSubRegIdx(Indices[i]);
334     CodeGenRegister *SR = SubRegs.find(Idx)->second;
335     if (OSet.insert(SR))
336       SR->addSubRegsPreOrder(OSet, RegBank);
337   }
338 }
339
340 // Get the sum of this register's unit weights.
341 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
342   unsigned Weight = 0;
343   for (RegUnitList::const_iterator I = RegUnits.begin(), E = RegUnits.end();
344        I != E; ++I) {
345     Weight += RegBank.getRegUnitWeight(*I);
346   }
347   return Weight;
348 }
349
350 //===----------------------------------------------------------------------===//
351 //                               RegisterTuples
352 //===----------------------------------------------------------------------===//
353
354 // A RegisterTuples def is used to generate pseudo-registers from lists of
355 // sub-registers. We provide a SetTheory expander class that returns the new
356 // registers.
357 namespace {
358 struct TupleExpander : SetTheory::Expander {
359   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) {
360     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
361     unsigned Dim = Indices.size();
362     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
363     if (Dim != SubRegs->getSize())
364       throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
365     if (Dim < 2)
366       throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers");
367
368     // Evaluate the sub-register lists to be zipped.
369     unsigned Length = ~0u;
370     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
371     for (unsigned i = 0; i != Dim; ++i) {
372       ST.evaluate(SubRegs->getElement(i), Lists[i]);
373       Length = std::min(Length, unsigned(Lists[i].size()));
374     }
375
376     if (Length == 0)
377       return;
378
379     // Precompute some types.
380     Record *RegisterCl = Def->getRecords().getClass("Register");
381     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
382     StringInit *BlankName = StringInit::get("");
383
384     // Zip them up.
385     for (unsigned n = 0; n != Length; ++n) {
386       std::string Name;
387       Record *Proto = Lists[0][n];
388       std::vector<Init*> Tuple;
389       unsigned CostPerUse = 0;
390       for (unsigned i = 0; i != Dim; ++i) {
391         Record *Reg = Lists[i][n];
392         if (i) Name += '_';
393         Name += Reg->getName();
394         Tuple.push_back(DefInit::get(Reg));
395         CostPerUse = std::max(CostPerUse,
396                               unsigned(Reg->getValueAsInt("CostPerUse")));
397       }
398
399       // Create a new Record representing the synthesized register. This record
400       // is only for consumption by CodeGenRegister, it is not added to the
401       // RecordKeeper.
402       Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
403       Elts.insert(NewReg);
404
405       // Copy Proto super-classes.
406       for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i)
407         NewReg->addSuperClass(Proto->getSuperClasses()[i]);
408
409       // Copy Proto fields.
410       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
411         RecordVal RV = Proto->getValues()[i];
412
413         // Skip existing fields, like NAME.
414         if (NewReg->getValue(RV.getNameInit()))
415           continue;
416
417         StringRef Field = RV.getName();
418
419         // Replace the sub-register list with Tuple.
420         if (Field == "SubRegs")
421           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
422
423         // Provide a blank AsmName. MC hacks are required anyway.
424         if (Field == "AsmName")
425           RV.setValue(BlankName);
426
427         // CostPerUse is aggregated from all Tuple members.
428         if (Field == "CostPerUse")
429           RV.setValue(IntInit::get(CostPerUse));
430
431         // Composite registers are always covered by sub-registers.
432         if (Field == "CoveredBySubRegs")
433           RV.setValue(BitInit::get(true));
434
435         // Copy fields from the RegisterTuples def.
436         if (Field == "SubRegIndices" ||
437             Field == "CompositeIndices") {
438           NewReg->addValue(*Def->getValue(Field));
439           continue;
440         }
441
442         // Some fields get their default uninitialized value.
443         if (Field == "DwarfNumbers" ||
444             Field == "DwarfAlias" ||
445             Field == "Aliases") {
446           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
447             NewReg->addValue(*DefRV);
448           continue;
449         }
450
451         // Everything else is copied from Proto.
452         NewReg->addValue(RV);
453       }
454     }
455   }
456 };
457 }
458
459 //===----------------------------------------------------------------------===//
460 //                            CodeGenRegisterClass
461 //===----------------------------------------------------------------------===//
462
463 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
464   : TheDef(R), Name(R->getName()), EnumValue(-1) {
465   // Rename anonymous register classes.
466   if (R->getName().size() > 9 && R->getName()[9] == '.') {
467     static unsigned AnonCounter = 0;
468     R->setName("AnonRegClass_"+utostr(AnonCounter++));
469   }
470
471   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
472   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
473     Record *Type = TypeList[i];
474     if (!Type->isSubClassOf("ValueType"))
475       throw "RegTypes list member '" + Type->getName() +
476         "' does not derive from the ValueType class!";
477     VTs.push_back(getValueType(Type));
478   }
479   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
480
481   // Allocation order 0 is the full set. AltOrders provides others.
482   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
483   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
484   Orders.resize(1 + AltOrders->size());
485
486   // Default allocation order always contains all registers.
487   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
488     Orders[0].push_back((*Elements)[i]);
489     Members.insert(RegBank.getReg((*Elements)[i]));
490   }
491
492   // Alternative allocation orders may be subsets.
493   SetTheory::RecSet Order;
494   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
495     RegBank.getSets().evaluate(AltOrders->getElement(i), Order);
496     Orders[1 + i].append(Order.begin(), Order.end());
497     // Verify that all altorder members are regclass members.
498     while (!Order.empty()) {
499       CodeGenRegister *Reg = RegBank.getReg(Order.back());
500       Order.pop_back();
501       if (!contains(Reg))
502         throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() +
503                       " is not a class member");
504     }
505   }
506
507   // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags.
508   ListInit *SRC = R->getValueAsListInit("SubRegClasses");
509   for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) {
510     DagInit *DAG = dynamic_cast<DagInit*>(*i);
511     if (!DAG) throw "SubRegClasses must contain DAGs";
512     DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator());
513     Record *RCRec;
514     if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass"))
515       throw "Operator '" + DAG->getOperator()->getAsString() +
516         "' in SubRegClasses is not a RegisterClass";
517     // Iterate over args, all SubRegIndex instances.
518     for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end();
519          ai != ae; ++ai) {
520       DefInit *Idx = dynamic_cast<DefInit*>(*ai);
521       Record *IdxRec;
522       if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex"))
523         throw "Argument '" + (*ai)->getAsString() +
524           "' in SubRegClasses is not a SubRegIndex";
525       if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second)
526         throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice";
527     }
528   }
529
530   // Allow targets to override the size in bits of the RegisterClass.
531   unsigned Size = R->getValueAsInt("Size");
532
533   Namespace = R->getValueAsString("Namespace");
534   SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits();
535   SpillAlignment = R->getValueAsInt("Alignment");
536   CopyCost = R->getValueAsInt("CopyCost");
537   Allocatable = R->getValueAsBit("isAllocatable");
538   AltOrderSelect = R->getValueAsString("AltOrderSelect");
539 }
540
541 // Create an inferred register class that was missing from the .td files.
542 // Most properties will be inherited from the closest super-class after the
543 // class structure has been computed.
544 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props)
545   : Members(*Props.Members),
546     TheDef(0),
547     Name(Name),
548     EnumValue(-1),
549     SpillSize(Props.SpillSize),
550     SpillAlignment(Props.SpillAlignment),
551     CopyCost(0),
552     Allocatable(true) {
553 }
554
555 // Compute inherited propertied for a synthesized register class.
556 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
557   assert(!getDef() && "Only synthesized classes can inherit properties");
558   assert(!SuperClasses.empty() && "Synthesized class without super class");
559
560   // The last super-class is the smallest one.
561   CodeGenRegisterClass &Super = *SuperClasses.back();
562
563   // Most properties are copied directly.
564   // Exceptions are members, size, and alignment
565   Namespace = Super.Namespace;
566   VTs = Super.VTs;
567   CopyCost = Super.CopyCost;
568   Allocatable = Super.Allocatable;
569   AltOrderSelect = Super.AltOrderSelect;
570
571   // Copy all allocation orders, filter out foreign registers from the larger
572   // super-class.
573   Orders.resize(Super.Orders.size());
574   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
575     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
576       if (contains(RegBank.getReg(Super.Orders[i][j])))
577         Orders[i].push_back(Super.Orders[i][j]);
578 }
579
580 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
581   return Members.count(Reg);
582 }
583
584 namespace llvm {
585   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
586     OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment;
587     for (CodeGenRegister::Set::const_iterator I = K.Members->begin(),
588          E = K.Members->end(); I != E; ++I)
589       OS << ", " << (*I)->getName();
590     return OS << " }";
591   }
592 }
593
594 // This is a simple lexicographical order that can be used to search for sets.
595 // It is not the same as the topological order provided by TopoOrderRC.
596 bool CodeGenRegisterClass::Key::
597 operator<(const CodeGenRegisterClass::Key &B) const {
598   assert(Members && B.Members);
599   if (*Members != *B.Members)
600     return *Members < *B.Members;
601   if (SpillSize != B.SpillSize)
602     return SpillSize < B.SpillSize;
603   return SpillAlignment < B.SpillAlignment;
604 }
605
606 // Returns true if RC is a strict subclass.
607 // RC is a sub-class of this class if it is a valid replacement for any
608 // instruction operand where a register of this classis required. It must
609 // satisfy these conditions:
610 //
611 // 1. All RC registers are also in this.
612 // 2. The RC spill size must not be smaller than our spill size.
613 // 3. RC spill alignment must be compatible with ours.
614 //
615 static bool testSubClass(const CodeGenRegisterClass *A,
616                          const CodeGenRegisterClass *B) {
617   return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
618     A->SpillSize <= B->SpillSize &&
619     std::includes(A->getMembers().begin(), A->getMembers().end(),
620                   B->getMembers().begin(), B->getMembers().end(),
621                   CodeGenRegister::Less());
622 }
623
624 /// Sorting predicate for register classes.  This provides a topological
625 /// ordering that arranges all register classes before their sub-classes.
626 ///
627 /// Register classes with the same registers, spill size, and alignment form a
628 /// clique.  They will be ordered alphabetically.
629 ///
630 static int TopoOrderRC(const void *PA, const void *PB) {
631   const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA;
632   const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB;
633   if (A == B)
634     return 0;
635
636   // Order by descending set size.  Note that the classes' allocation order may
637   // not have been computed yet.  The Members set is always vaild.
638   if (A->getMembers().size() > B->getMembers().size())
639     return -1;
640   if (A->getMembers().size() < B->getMembers().size())
641     return 1;
642
643   // Order by ascending spill size.
644   if (A->SpillSize < B->SpillSize)
645     return -1;
646   if (A->SpillSize > B->SpillSize)
647     return 1;
648
649   // Order by ascending spill alignment.
650   if (A->SpillAlignment < B->SpillAlignment)
651     return -1;
652   if (A->SpillAlignment > B->SpillAlignment)
653     return 1;
654
655   // Finally order by name as a tie breaker.
656   return StringRef(A->getName()).compare(B->getName());
657 }
658
659 std::string CodeGenRegisterClass::getQualifiedName() const {
660   if (Namespace.empty())
661     return getName();
662   else
663     return Namespace + "::" + getName();
664 }
665
666 // Compute sub-classes of all register classes.
667 // Assume the classes are ordered topologically.
668 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
669   ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses();
670
671   // Visit backwards so sub-classes are seen first.
672   for (unsigned rci = RegClasses.size(); rci; --rci) {
673     CodeGenRegisterClass &RC = *RegClasses[rci - 1];
674     RC.SubClasses.resize(RegClasses.size());
675     RC.SubClasses.set(RC.EnumValue);
676
677     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
678     for (unsigned s = rci; s != RegClasses.size(); ++s) {
679       if (RC.SubClasses.test(s))
680         continue;
681       CodeGenRegisterClass *SubRC = RegClasses[s];
682       if (!testSubClass(&RC, SubRC))
683         continue;
684       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
685       // check them again.
686       RC.SubClasses |= SubRC->SubClasses;
687     }
688
689     // Sweep up missed clique members.  They will be immediately preceeding RC.
690     for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s)
691       RC.SubClasses.set(s - 1);
692   }
693
694   // Compute the SuperClasses lists from the SubClasses vectors.
695   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
696     const BitVector &SC = RegClasses[rci]->getSubClasses();
697     for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) {
698       if (unsigned(s) == rci)
699         continue;
700       RegClasses[s]->SuperClasses.push_back(RegClasses[rci]);
701     }
702   }
703
704   // With the class hierarchy in place, let synthesized register classes inherit
705   // properties from their closest super-class. The iteration order here can
706   // propagate properties down multiple levels.
707   for (unsigned rci = 0; rci != RegClasses.size(); ++rci)
708     if (!RegClasses[rci]->getDef())
709       RegClasses[rci]->inheritProperties(RegBank);
710 }
711
712 void
713 CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
714                                          BitVector &Out) const {
715   DenseMap<CodeGenSubRegIndex*,
716            SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
717     FindI = SuperRegClasses.find(SubIdx);
718   if (FindI == SuperRegClasses.end())
719     return;
720   for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =
721        FindI->second.begin(), E = FindI->second.end(); I != E; ++I)
722     Out.set((*I)->EnumValue);
723 }
724
725
726 //===----------------------------------------------------------------------===//
727 //                               CodeGenRegBank
728 //===----------------------------------------------------------------------===//
729
730 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
731   // Configure register Sets to understand register classes and tuples.
732   Sets.addFieldExpander("RegisterClass", "MemberList");
733   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
734   Sets.addExpander("RegisterTuples", new TupleExpander());
735
736   // Read in the user-defined (named) sub-register indices.
737   // More indices will be synthesized later.
738   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
739   std::sort(SRIs.begin(), SRIs.end(), LessRecord());
740   NumNamedIndices = SRIs.size();
741   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
742     getSubRegIdx(SRIs[i]);
743   // Build composite maps from ComposedOf fields.
744   for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
745     SubRegIndices[i]->updateComponents(*this);
746
747   // Read in the register definitions.
748   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
749   std::sort(Regs.begin(), Regs.end(), LessRecord());
750   Registers.reserve(Regs.size());
751   // Assign the enumeration values.
752   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
753     getReg(Regs[i]);
754
755   // Expand tuples and number the new registers.
756   std::vector<Record*> Tups =
757     Records.getAllDerivedDefinitions("RegisterTuples");
758   for (unsigned i = 0, e = Tups.size(); i != e; ++i) {
759     const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]);
760     for (unsigned j = 0, je = TupRegs->size(); j != je; ++j)
761       getReg((*TupRegs)[j]);
762   }
763
764   // Precompute all sub-register maps now all the registers are known.
765   // This will create Composite entries for all inferred sub-register indices.
766   NumRegUnits = 0;
767   for (unsigned i = 0, e = Registers.size(); i != e; ++i)
768     Registers[i]->getSubRegs(*this);
769
770   // Native register units are associated with a leaf register. They've all been
771   // discovered now.
772   NumNativeRegUnits = NumRegUnits;
773
774   // Read in register class definitions.
775   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
776   if (RCs.empty())
777     throw std::string("No 'RegisterClass' subclasses defined!");
778
779   // Allocate user-defined register classes.
780   RegClasses.reserve(RCs.size());
781   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
782     addToMaps(new CodeGenRegisterClass(*this, RCs[i]));
783
784   // Infer missing classes to create a full algebra.
785   computeInferredRegisterClasses();
786
787   // Order register classes topologically and assign enum values.
788   array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC);
789   for (unsigned i = 0, e = RegClasses.size(); i != e; ++i)
790     RegClasses[i]->EnumValue = i;
791   CodeGenRegisterClass::computeSubClasses(*this);
792 }
793
794 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
795   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
796   if (Idx)
797     return Idx;
798   Idx = new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
799   SubRegIndices.push_back(Idx);
800   return Idx;
801 }
802
803 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
804   CodeGenRegister *&Reg = Def2Reg[Def];
805   if (Reg)
806     return Reg;
807   Reg = new CodeGenRegister(Def, Registers.size() + 1);
808   Registers.push_back(Reg);
809   return Reg;
810 }
811
812 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
813   RegClasses.push_back(RC);
814
815   if (Record *Def = RC->getDef())
816     Def2RC.insert(std::make_pair(Def, RC));
817
818   // Duplicate classes are rejected by insert().
819   // That's OK, we only care about the properties handled by CGRC::Key.
820   CodeGenRegisterClass::Key K(*RC);
821   Key2RC.insert(std::make_pair(K, RC));
822 }
823
824 // Create a synthetic sub-class if it is missing.
825 CodeGenRegisterClass*
826 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
827                                     const CodeGenRegister::Set *Members,
828                                     StringRef Name) {
829   // Synthetic sub-class has the same size and alignment as RC.
830   CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
831   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
832   if (FoundI != Key2RC.end())
833     return FoundI->second;
834
835   // Sub-class doesn't exist, create a new one.
836   CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K);
837   addToMaps(NewRC);
838   return NewRC;
839 }
840
841 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
842   if (CodeGenRegisterClass *RC = Def2RC[Def])
843     return RC;
844
845   throw TGError(Def->getLoc(), "Not a known RegisterClass!");
846 }
847
848 CodeGenSubRegIndex*
849 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
850                                         CodeGenSubRegIndex *B) {
851   // Look for an existing entry.
852   CodeGenSubRegIndex *Comp = A->compose(B);
853   if (Comp)
854     return Comp;
855
856   // None exists, synthesize one.
857   std::string Name = A->getName() + "_then_" + B->getName();
858   Comp = getSubRegIdx(new Record(Name, SMLoc(), Records));
859   A->addComposite(B, Comp);
860   return Comp;
861 }
862
863 void CodeGenRegBank::computeComposites() {
864   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
865     CodeGenRegister *Reg1 = Registers[i];
866     const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs();
867     for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
868          e1 = SRM1.end(); i1 != e1; ++i1) {
869       CodeGenSubRegIndex *Idx1 = i1->first;
870       CodeGenRegister *Reg2 = i1->second;
871       // Ignore identity compositions.
872       if (Reg1 == Reg2)
873         continue;
874       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
875       // Try composing Idx1 with another SubRegIndex.
876       for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
877            e2 = SRM2.end(); i2 != e2; ++i2) {
878       CodeGenSubRegIndex *Idx2 = i2->first;
879         CodeGenRegister *Reg3 = i2->second;
880         // Ignore identity compositions.
881         if (Reg2 == Reg3)
882           continue;
883         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
884         for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(),
885              e1d = SRM1.end(); i1d != e1d; ++i1d) {
886           if (i1d->second == Reg3) {
887             // Conflicting composition? Emit a warning but allow it.
888             if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, i1d->first))
889               errs() << "Warning: SubRegIndex " << Idx1->getQualifiedName()
890                      << " and " << Idx2->getQualifiedName()
891                      << " compose ambiguously as "
892                      << Prev->getQualifiedName() << " or "
893                      << i1d->first->getQualifiedName() << "\n";
894           }
895         }
896       }
897     }
898   }
899
900   // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid
901   // compositions, so remove any mappings of that form.
902   for (unsigned i = 0, e = SubRegIndices.size(); i != e; ++i)
903     SubRegIndices[i]->cleanComposites();
904 }
905
906 namespace {
907 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
908 // the transitive closure of the union of overlapping register
909 // classes. Together, the UberRegSets form a partition of the registers. If we
910 // consider overlapping register classes to be connected, then each UberRegSet
911 // is a set of connected components.
912 //
913 // An UberRegSet will likely be a horizontal slice of register names of
914 // the same width. Nontrivial subregisters should then be in a separate
915 // UberRegSet. But this property isn't required for valid computation of
916 // register unit weights.
917 //
918 // A Weight field caches the max per-register unit weight in each UberRegSet.
919 //
920 // A set of SingularDeterminants flags single units of some register in this set
921 // for which the unit weight equals the set weight. These units should not have
922 // their weight increased.
923 struct UberRegSet {
924   CodeGenRegister::Set Regs;
925   unsigned Weight;
926   CodeGenRegister::RegUnitList SingularDeterminants;
927
928   UberRegSet(): Weight(0) {}
929 };
930 } // namespace
931
932 // Partition registers into UberRegSets, where each set is the transitive
933 // closure of the union of overlapping register classes.
934 //
935 // UberRegSets[0] is a special non-allocatable set.
936 static void computeUberSets(std::vector<UberRegSet> &UberSets,
937                             std::vector<UberRegSet*> &RegSets,
938                             CodeGenRegBank &RegBank) {
939
940   const std::vector<CodeGenRegister*> &Registers = RegBank.getRegisters();
941
942   // The Register EnumValue is one greater than its index into Registers.
943   assert(Registers.size() == Registers[Registers.size()-1]->EnumValue &&
944          "register enum value mismatch");
945
946   // For simplicitly make the SetID the same as EnumValue.
947   IntEqClasses UberSetIDs(Registers.size()+1);
948   std::set<unsigned> AllocatableRegs;
949   for (unsigned i = 0, e = RegBank.getRegClasses().size(); i != e; ++i) {
950
951     CodeGenRegisterClass *RegClass = RegBank.getRegClasses()[i];
952     if (!RegClass->Allocatable)
953       continue;
954
955     const CodeGenRegister::Set &Regs = RegClass->getMembers();
956     if (Regs.empty())
957       continue;
958
959     unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
960     assert(USetID && "register number 0 is invalid");
961
962     AllocatableRegs.insert((*Regs.begin())->EnumValue);
963     for (CodeGenRegister::Set::const_iterator I = llvm::next(Regs.begin()),
964            E = Regs.end(); I != E; ++I) {
965       AllocatableRegs.insert((*I)->EnumValue);
966       UberSetIDs.join(USetID, (*I)->EnumValue);
967     }
968   }
969   // Combine non-allocatable regs.
970   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
971     unsigned RegNum = Registers[i]->EnumValue;
972     if (AllocatableRegs.count(RegNum))
973       continue;
974
975     UberSetIDs.join(0, RegNum);
976   }
977   UberSetIDs.compress();
978
979   // Make the first UberSet a special unallocatable set.
980   unsigned ZeroID = UberSetIDs[0];
981
982   // Insert Registers into the UberSets formed by union-find.
983   // Do not resize after this.
984   UberSets.resize(UberSetIDs.getNumClasses());
985   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
986     const CodeGenRegister *Reg = Registers[i];
987     unsigned USetID = UberSetIDs[Reg->EnumValue];
988     if (!USetID)
989       USetID = ZeroID;
990     else if (USetID == ZeroID)
991       USetID = 0;
992
993     UberRegSet *USet = &UberSets[USetID];
994     USet->Regs.insert(Reg);
995     RegSets[i] = USet;
996   }
997 }
998
999 // Recompute each UberSet weight after changing unit weights.
1000 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1001                                CodeGenRegBank &RegBank) {
1002   // Skip the first unallocatable set.
1003   for (std::vector<UberRegSet>::iterator I = llvm::next(UberSets.begin()),
1004          E = UberSets.end(); I != E; ++I) {
1005
1006     // Initialize all unit weights in this set, and remember the max units/reg.
1007     const CodeGenRegister *Reg = 0;
1008     unsigned MaxWeight = 0, Weight = 0;
1009     for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1010       if (Reg != UnitI.getReg()) {
1011         if (Weight > MaxWeight)
1012           MaxWeight = Weight;
1013         Reg = UnitI.getReg();
1014         Weight = 0;
1015       }
1016       unsigned UWeight = RegBank.getRegUnitWeight(*UnitI);
1017       if (!UWeight) {
1018         UWeight = 1;
1019         RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1020       }
1021       Weight += UWeight;
1022     }
1023     if (Weight > MaxWeight)
1024       MaxWeight = Weight;
1025
1026     // Update the set weight.
1027     I->Weight = MaxWeight;
1028
1029     // Find singular determinants.
1030     for (CodeGenRegister::Set::iterator RegI = I->Regs.begin(),
1031            RegE = I->Regs.end(); RegI != RegE; ++RegI) {
1032       if ((*RegI)->getRegUnits().size() == 1
1033           && (*RegI)->getWeight(RegBank) == I->Weight)
1034         mergeRegUnits(I->SingularDeterminants, (*RegI)->getRegUnits());
1035     }
1036   }
1037 }
1038
1039 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1040 // a register and its subregisters so that they have the same weight as their
1041 // UberSet. Self-recursion processes the subregister tree in postorder so
1042 // subregisters are normalized first.
1043 //
1044 // Side effects:
1045 // - creates new adopted register units
1046 // - causes superregisters to inherit adopted units
1047 // - increases the weight of "singular" units
1048 // - induces recomputation of UberWeights.
1049 static bool normalizeWeight(CodeGenRegister *Reg,
1050                             std::vector<UberRegSet> &UberSets,
1051                             std::vector<UberRegSet*> &RegSets,
1052                             CodeGenRegister::RegUnitList &NormalUnits,
1053                             CodeGenRegBank &RegBank) {
1054   bool Changed = false;
1055   const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1056   for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1057          SRE = SRM.end(); SRI != SRE; ++SRI) {
1058     if (SRI->second == Reg)
1059       continue; // self-cycles happen
1060
1061     Changed |=
1062       normalizeWeight(SRI->second, UberSets, RegSets, NormalUnits, RegBank);
1063   }
1064   // Postorder register normalization.
1065
1066   // Inherit register units newly adopted by subregisters.
1067   if (Reg->inheritRegUnits(RegBank))
1068     computeUberWeights(UberSets, RegBank);
1069
1070   // Check if this register is too skinny for its UberRegSet.
1071   UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1072
1073   unsigned RegWeight = Reg->getWeight(RegBank);
1074   if (UberSet->Weight > RegWeight) {
1075     // A register unit's weight can be adjusted only if it is the singular unit
1076     // for this register, has not been used to normalize a subregister's set,
1077     // and has not already been used to singularly determine this UberRegSet.
1078     unsigned AdjustUnit = Reg->getRegUnits().front();
1079     if (Reg->getRegUnits().size() != 1
1080         || hasRegUnit(NormalUnits, AdjustUnit)
1081         || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1082       // We don't have an adjustable unit, so adopt a new one.
1083       AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1084       Reg->adoptRegUnit(AdjustUnit);
1085       // Adopting a unit does not immediately require recomputing set weights.
1086     }
1087     else {
1088       // Adjust the existing single unit.
1089       RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1090       // The unit may be shared among sets and registers within this set.
1091       computeUberWeights(UberSets, RegBank);
1092     }
1093     Changed = true;
1094   }
1095
1096   // Mark these units normalized so superregisters can't change their weights.
1097   mergeRegUnits(NormalUnits, Reg->getRegUnits());
1098
1099   return Changed;
1100 }
1101
1102 // Compute a weight for each register unit created during getSubRegs.
1103 //
1104 // The goal is that two registers in the same class will have the same weight,
1105 // where each register's weight is defined as sum of its units' weights.
1106 void CodeGenRegBank::computeRegUnitWeights() {
1107   assert(RegUnitWeights.empty() && "Only initialize RegUnitWeights once");
1108
1109   // Only allocatable units will be initialized to nonzero weight.
1110   RegUnitWeights.resize(NumRegUnits);
1111
1112   std::vector<UberRegSet> UberSets;
1113   std::vector<UberRegSet*> RegSets(Registers.size());
1114   computeUberSets(UberSets, RegSets, *this);
1115   // UberSets and RegSets are now immutable.
1116
1117   computeUberWeights(UberSets, *this);
1118
1119   // Iterate over each Register, normalizing the unit weights until reaching
1120   // a fix point.
1121   unsigned NumIters = 0;
1122   for (bool Changed = true; Changed; ++NumIters) {
1123     assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1124     Changed = false;
1125     for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1126       CodeGenRegister::RegUnitList NormalUnits;
1127       Changed |=
1128         normalizeWeight(Registers[i], UberSets, RegSets, NormalUnits, *this);
1129     }
1130   }
1131 }
1132
1133 // Populate a unique sorted list of units from a register set.
1134 static void buildRegUnitSet(const CodeGenRegister::Set &Regs,
1135                             std::vector<unsigned> &RegUnits) {
1136   std::vector<unsigned> TmpUnits;
1137   for (RegUnitIterator UnitI(Regs); UnitI.isValid(); ++UnitI)
1138     TmpUnits.push_back(*UnitI);
1139   std::sort(TmpUnits.begin(), TmpUnits.end());
1140   std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
1141                    std::back_inserter(RegUnits));
1142 }
1143
1144 // Find a set in UniqueSets with the same elements as Set.
1145 // Return an iterator into UniqueSets.
1146 static std::vector<RegUnitSet>::const_iterator
1147 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1148                const RegUnitSet &Set) {
1149   std::vector<RegUnitSet>::const_iterator
1150     I = UniqueSets.begin(), E = UniqueSets.end();
1151   for(;I != E; ++I) {
1152     if (I->Units == Set.Units)
1153       break;
1154   }
1155   return I;
1156 }
1157
1158 // Return true if the RUSubSet is a subset of RUSuperSet.
1159 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1160                             const std::vector<unsigned> &RUSuperSet) {
1161   return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1162                        RUSubSet.begin(), RUSubSet.end());
1163 }
1164
1165 // Iteratively prune unit sets.
1166 void CodeGenRegBank::pruneUnitSets() {
1167   assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1168
1169   // Form an equivalence class of UnitSets with no significant difference.
1170   // Populate PrunedUnitSets with each equivalence class's superset.
1171   std::vector<RegUnitSet> PrunedUnitSets;
1172   for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1173        SubIdx != EndIdx; ++SubIdx) {
1174     const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1175     unsigned SuperIdx = 0;
1176     for (; SuperIdx != EndIdx; ++SuperIdx) {
1177       if (SuperIdx == SubIdx)
1178         continue;
1179       const RegUnitSet *SuperSet = 0;
1180       if (SuperIdx > SubIdx)
1181         SuperSet = &RegUnitSets[SuperIdx];
1182       else {
1183         // Compare with already-pruned sets.
1184         if (SuperIdx >= PrunedUnitSets.size())
1185           continue;
1186         SuperSet = &PrunedUnitSets[SuperIdx];
1187       }
1188       if (isRegUnitSubSet(SubSet.Units, SuperSet->Units)
1189           && (SubSet.Units.size() + 3 > SuperSet->Units.size())) {
1190         break;
1191       }
1192     }
1193     if (SuperIdx != EndIdx)
1194       continue;
1195     PrunedUnitSets.resize(PrunedUnitSets.size()+1);
1196     PrunedUnitSets.back().Name = RegUnitSets[SubIdx].Name;
1197     PrunedUnitSets.back().Units.swap(RegUnitSets[SubIdx].Units);
1198   }
1199   RegUnitSets.swap(PrunedUnitSets);
1200 }
1201
1202 // Create a RegUnitSet for each RegClass that contains all units in the class
1203 // including adopted units that are necessary to model register pressure. Then
1204 // iteratively compute RegUnitSets such that the union of any two overlapping
1205 // RegUnitSets is repreresented.
1206 //
1207 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1208 // RegUnitSet that is a superset of that RegUnitClass.
1209 void CodeGenRegBank::computeRegUnitSets() {
1210
1211   // Compute a unique RegUnitSet for each RegClass.
1212   const ArrayRef<CodeGenRegisterClass*> &RegClasses = getRegClasses();
1213   unsigned NumRegClasses = RegClasses.size();
1214   for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1215     if (!RegClasses[RCIdx]->Allocatable)
1216       continue;
1217
1218     // Speculatively grow the RegUnitSets to hold the new set.
1219     RegUnitSets.resize(RegUnitSets.size() + 1);
1220     RegUnitSets.back().Name = RegClasses[RCIdx]->getName();
1221
1222     // Compute a sorted list of units in this class.
1223     buildRegUnitSet(RegClasses[RCIdx]->getMembers(), RegUnitSets.back().Units);
1224
1225     // Find an existing RegUnitSet.
1226     std::vector<RegUnitSet>::const_iterator SetI =
1227       findRegUnitSet(RegUnitSets, RegUnitSets.back());
1228     if (SetI != llvm::prior(RegUnitSets.end()))
1229       RegUnitSets.pop_back();
1230   }
1231
1232   // Iteratively prune unit sets.
1233   pruneUnitSets();
1234
1235   // Iterate over all unit sets, including new ones added by this loop.
1236   unsigned NumRegUnitSubSets = RegUnitSets.size();
1237   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1238     // In theory, this is combinatorial. In practice, it needs to be bounded
1239     // by a small number of sets for regpressure to be efficient.
1240     // If the assert is hit, we need to implement pruning.
1241     assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1242
1243     // Compare new sets with all original classes.
1244     for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1245          SearchIdx != EndIdx; ++SearchIdx) {
1246       std::set<unsigned> Intersection;
1247       std::set_intersection(RegUnitSets[Idx].Units.begin(),
1248                             RegUnitSets[Idx].Units.end(),
1249                             RegUnitSets[SearchIdx].Units.begin(),
1250                             RegUnitSets[SearchIdx].Units.end(),
1251                             std::inserter(Intersection, Intersection.begin()));
1252       if (Intersection.empty())
1253         continue;
1254
1255       // Speculatively grow the RegUnitSets to hold the new set.
1256       RegUnitSets.resize(RegUnitSets.size() + 1);
1257       RegUnitSets.back().Name =
1258         RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1259
1260       std::set_union(RegUnitSets[Idx].Units.begin(),
1261                      RegUnitSets[Idx].Units.end(),
1262                      RegUnitSets[SearchIdx].Units.begin(),
1263                      RegUnitSets[SearchIdx].Units.end(),
1264                      std::inserter(RegUnitSets.back().Units,
1265                                    RegUnitSets.back().Units.begin()));
1266
1267       // Find an existing RegUnitSet, or add the union to the unique sets.
1268       std::vector<RegUnitSet>::const_iterator SetI =
1269         findRegUnitSet(RegUnitSets, RegUnitSets.back());
1270       if (SetI != llvm::prior(RegUnitSets.end()))
1271         RegUnitSets.pop_back();
1272     }
1273   }
1274
1275   // Iteratively prune unit sets after inferring supersets.
1276   pruneUnitSets();
1277
1278   // For each register class, list the UnitSets that are supersets.
1279   RegClassUnitSets.resize(NumRegClasses);
1280   for (unsigned RCIdx = 0, RCEnd = NumRegClasses; RCIdx != RCEnd; ++RCIdx) {
1281     if (!RegClasses[RCIdx]->Allocatable)
1282       continue;
1283
1284     // Recompute the sorted list of units in this class.
1285     std::vector<unsigned> RegUnits;
1286     buildRegUnitSet(RegClasses[RCIdx]->getMembers(), RegUnits);
1287
1288     // Don't increase pressure for unallocatable regclasses.
1289     if (RegUnits.empty())
1290       continue;
1291
1292     // Find all supersets.
1293     for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1294          USIdx != USEnd; ++USIdx) {
1295       if (isRegUnitSubSet(RegUnits, RegUnitSets[USIdx].Units))
1296         RegClassUnitSets[RCIdx].push_back(USIdx);
1297     }
1298     assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1299   }
1300 }
1301
1302 // Compute sets of overlapping registers.
1303 //
1304 // The standard set is all super-registers and all sub-registers, but the
1305 // target description can add arbitrary overlapping registers via the 'Aliases'
1306 // field. This complicates things, but we can compute overlapping sets using
1307 // the following rules:
1308 //
1309 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive.
1310 //
1311 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B).
1312 //
1313 // Alternatively:
1314 //
1315 //    overlap(A, B) iff there exists:
1316 //    A' in { A, subregs(A) } and B' in { B, subregs(B) } such that:
1317 //    A' = B' or A' in aliases(B') or B' in aliases(A').
1318 //
1319 // Here subregs(A) is the full flattened sub-register set returned by
1320 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the
1321 // description of register A.
1322 //
1323 // This also implies that registers with a common sub-register are considered
1324 // overlapping. This can happen when forming register pairs:
1325 //
1326 //    P0 = (R0, R1)
1327 //    P1 = (R1, R2)
1328 //    P2 = (R2, R3)
1329 //
1330 // In this case, we will infer an overlap between P0 and P1 because of the
1331 // shared sub-register R1. There is no overlap between P0 and P2.
1332 //
1333 void CodeGenRegBank::
1334 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) {
1335   assert(Map.empty());
1336
1337   // Collect overlaps that don't follow from rule 2.
1338   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1339     CodeGenRegister *Reg = Registers[i];
1340     CodeGenRegister::Set &Overlaps = Map[Reg];
1341
1342     // Reg overlaps itself.
1343     Overlaps.insert(Reg);
1344
1345     // All super-registers overlap.
1346     const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs();
1347     Overlaps.insert(Supers.begin(), Supers.end());
1348
1349     // Form symmetrical relations from the special Aliases[] lists.
1350     std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases");
1351     for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) {
1352       CodeGenRegister *Reg2 = getReg(RegList[i2]);
1353       CodeGenRegister::Set &Overlaps2 = Map[Reg2];
1354       const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs();
1355       // Reg overlaps Reg2 which implies it overlaps supers(Reg2).
1356       Overlaps.insert(Reg2);
1357       Overlaps.insert(Supers2.begin(), Supers2.end());
1358       Overlaps2.insert(Reg);
1359       Overlaps2.insert(Supers.begin(), Supers.end());
1360     }
1361   }
1362
1363   // Apply rule 2. and inherit all sub-register overlaps.
1364   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
1365     CodeGenRegister *Reg = Registers[i];
1366     CodeGenRegister::Set &Overlaps = Map[Reg];
1367     const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1368     for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(),
1369          e2 = SRM.end(); i2 != e2; ++i2) {
1370       CodeGenRegister::Set &Overlaps2 = Map[i2->second];
1371       Overlaps.insert(Overlaps2.begin(), Overlaps2.end());
1372     }
1373   }
1374 }
1375
1376 void CodeGenRegBank::computeDerivedInfo() {
1377   computeComposites();
1378
1379   // Compute a weight for each register unit created during getSubRegs.
1380   // This may create adopted register units (with unit # >= NumNativeRegUnits).
1381   computeRegUnitWeights();
1382
1383   // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1384   // supersets for the union of overlapping sets.
1385   computeRegUnitSets();
1386 }
1387
1388 //
1389 // Synthesize missing register class intersections.
1390 //
1391 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1392 // returns a maximal register class for all X.
1393 //
1394 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1395   for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) {
1396     CodeGenRegisterClass *RC1 = RC;
1397     CodeGenRegisterClass *RC2 = RegClasses[rci];
1398     if (RC1 == RC2)
1399       continue;
1400
1401     // Compute the set intersection of RC1 and RC2.
1402     const CodeGenRegister::Set &Memb1 = RC1->getMembers();
1403     const CodeGenRegister::Set &Memb2 = RC2->getMembers();
1404     CodeGenRegister::Set Intersection;
1405     std::set_intersection(Memb1.begin(), Memb1.end(),
1406                           Memb2.begin(), Memb2.end(),
1407                           std::inserter(Intersection, Intersection.begin()),
1408                           CodeGenRegister::Less());
1409
1410     // Skip disjoint class pairs.
1411     if (Intersection.empty())
1412       continue;
1413
1414     // If RC1 and RC2 have different spill sizes or alignments, use the
1415     // larger size for sub-classing.  If they are equal, prefer RC1.
1416     if (RC2->SpillSize > RC1->SpillSize ||
1417         (RC2->SpillSize == RC1->SpillSize &&
1418          RC2->SpillAlignment > RC1->SpillAlignment))
1419       std::swap(RC1, RC2);
1420
1421     getOrCreateSubClass(RC1, &Intersection,
1422                         RC1->getName() + "_and_" + RC2->getName());
1423   }
1424 }
1425
1426 //
1427 // Synthesize missing sub-classes for getSubClassWithSubReg().
1428 //
1429 // Make sure that the set of registers in RC with a given SubIdx sub-register
1430 // form a register class.  Update RC->SubClassWithSubReg.
1431 //
1432 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1433   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1434   typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
1435                    CodeGenSubRegIndex::Less> SubReg2SetMap;
1436
1437   // Compute the set of registers supporting each SubRegIndex.
1438   SubReg2SetMap SRSets;
1439   for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1440        RE = RC->getMembers().end(); RI != RE; ++RI) {
1441     const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
1442     for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1443          E = SRM.end(); I != E; ++I)
1444       SRSets[I->first].insert(*RI);
1445   }
1446
1447   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
1448   // numerical order to visit synthetic indices last.
1449   for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1450     CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1451     SubReg2SetMap::const_iterator I = SRSets.find(SubIdx);
1452     // Unsupported SubRegIndex. Skip it.
1453     if (I == SRSets.end())
1454       continue;
1455     // In most cases, all RC registers support the SubRegIndex.
1456     if (I->second.size() == RC->getMembers().size()) {
1457       RC->setSubClassWithSubReg(SubIdx, RC);
1458       continue;
1459     }
1460     // This is a real subset.  See if we have a matching class.
1461     CodeGenRegisterClass *SubRC =
1462       getOrCreateSubClass(RC, &I->second,
1463                           RC->getName() + "_with_" + I->first->getName());
1464     RC->setSubClassWithSubReg(SubIdx, SubRC);
1465   }
1466 }
1467
1468 //
1469 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1470 //
1471 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1472 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1473 //
1474
1475 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1476                                                 unsigned FirstSubRegRC) {
1477   SmallVector<std::pair<const CodeGenRegister*,
1478                         const CodeGenRegister*>, 16> SSPairs;
1479
1480   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1481   for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) {
1482     CodeGenSubRegIndex *SubIdx = SubRegIndices[sri];
1483     // Skip indexes that aren't fully supported by RC's registers. This was
1484     // computed by inferSubClassWithSubReg() above which should have been
1485     // called first.
1486     if (RC->getSubClassWithSubReg(SubIdx) != RC)
1487       continue;
1488
1489     // Build list of (Super, Sub) pairs for this SubIdx.
1490     SSPairs.clear();
1491     for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1492          RE = RC->getMembers().end(); RI != RE; ++RI) {
1493       const CodeGenRegister *Super = *RI;
1494       const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second;
1495       assert(Sub && "Missing sub-register");
1496       SSPairs.push_back(std::make_pair(Super, Sub));
1497     }
1498
1499     // Iterate over sub-register class candidates.  Ignore classes created by
1500     // this loop. They will never be useful.
1501     for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce;
1502          ++rci) {
1503       CodeGenRegisterClass *SubRC = RegClasses[rci];
1504       // Compute the subset of RC that maps into SubRC.
1505       CodeGenRegister::Set SubSet;
1506       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1507         if (SubRC->contains(SSPairs[i].second))
1508           SubSet.insert(SSPairs[i].first);
1509       if (SubSet.empty())
1510         continue;
1511       // RC injects completely into SubRC.
1512       if (SubSet.size() == SSPairs.size()) {
1513         SubRC->addSuperRegClass(SubIdx, RC);
1514         continue;
1515       }
1516       // Only a subset of RC maps into SubRC. Make sure it is represented by a
1517       // class.
1518       getOrCreateSubClass(RC, &SubSet, RC->getName() +
1519                           "_with_" + SubIdx->getName() +
1520                           "_in_" + SubRC->getName());
1521     }
1522   }
1523 }
1524
1525
1526 //
1527 // Infer missing register classes.
1528 //
1529 void CodeGenRegBank::computeInferredRegisterClasses() {
1530   // When this function is called, the register classes have not been sorted
1531   // and assigned EnumValues yet.  That means getSubClasses(),
1532   // getSuperClasses(), and hasSubClass() functions are defunct.
1533   unsigned FirstNewRC = RegClasses.size();
1534
1535   // Visit all register classes, including the ones being added by the loop.
1536   for (unsigned rci = 0; rci != RegClasses.size(); ++rci) {
1537     CodeGenRegisterClass *RC = RegClasses[rci];
1538
1539     // Synthesize answers for getSubClassWithSubReg().
1540     inferSubClassWithSubReg(RC);
1541
1542     // Synthesize answers for getCommonSubClass().
1543     inferCommonSubClass(RC);
1544
1545     // Synthesize answers for getMatchingSuperRegClass().
1546     inferMatchingSuperRegClass(RC);
1547
1548     // New register classes are created while this loop is running, and we need
1549     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
1550     // to match old super-register classes with sub-register classes created
1551     // after inferMatchingSuperRegClass was called.  At this point,
1552     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
1553     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
1554     if (rci + 1 == FirstNewRC) {
1555       unsigned NextNewRC = RegClasses.size();
1556       for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2)
1557         inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
1558       FirstNewRC = NextNewRC;
1559     }
1560   }
1561 }
1562
1563 /// getRegisterClassForRegister - Find the register class that contains the
1564 /// specified physical register.  If the register is not in a register class,
1565 /// return null. If the register is in multiple classes, and the classes have a
1566 /// superset-subset relationship and the same set of types, return the
1567 /// superclass.  Otherwise return null.
1568 const CodeGenRegisterClass*
1569 CodeGenRegBank::getRegClassForRegister(Record *R) {
1570   const CodeGenRegister *Reg = getReg(R);
1571   ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses();
1572   const CodeGenRegisterClass *FoundRC = 0;
1573   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
1574     const CodeGenRegisterClass &RC = *RCs[i];
1575     if (!RC.contains(Reg))
1576       continue;
1577
1578     // If this is the first class that contains the register,
1579     // make a note of it and go on to the next class.
1580     if (!FoundRC) {
1581       FoundRC = &RC;
1582       continue;
1583     }
1584
1585     // If a register's classes have different types, return null.
1586     if (RC.getValueTypes() != FoundRC->getValueTypes())
1587       return 0;
1588
1589     // Check to see if the previously found class that contains
1590     // the register is a subclass of the current class. If so,
1591     // prefer the superclass.
1592     if (RC.hasSubClass(FoundRC)) {
1593       FoundRC = &RC;
1594       continue;
1595     }
1596
1597     // Check to see if the previously found class that contains
1598     // the register is a superclass of the current class. If so,
1599     // prefer the superclass.
1600     if (FoundRC->hasSubClass(&RC))
1601       continue;
1602
1603     // Multiple classes, and neither is a superclass of the other.
1604     // Return null.
1605     return 0;
1606   }
1607   return FoundRC;
1608 }
1609
1610 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
1611   SetVector<const CodeGenRegister*> Set;
1612
1613   // First add Regs with all sub-registers.
1614   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1615     CodeGenRegister *Reg = getReg(Regs[i]);
1616     if (Set.insert(Reg))
1617       // Reg is new, add all sub-registers.
1618       // The pre-ordering is not important here.
1619       Reg->addSubRegsPreOrder(Set, *this);
1620   }
1621
1622   // Second, find all super-registers that are completely covered by the set.
1623   for (unsigned i = 0; i != Set.size(); ++i) {
1624     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
1625     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
1626       const CodeGenRegister *Super = SR[j];
1627       if (!Super->CoveredBySubRegs || Set.count(Super))
1628         continue;
1629       // This new super-register is covered by its sub-registers.
1630       bool AllSubsInSet = true;
1631       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
1632       for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1633              E = SRM.end(); I != E; ++I)
1634         if (!Set.count(I->second)) {
1635           AllSubsInSet = false;
1636           break;
1637         }
1638       // All sub-registers in Set, add Super as well.
1639       // We will visit Super later to recheck its super-registers.
1640       if (AllSubsInSet)
1641         Set.insert(Super);
1642     }
1643   }
1644
1645   // Convert to BitVector.
1646   BitVector BV(Registers.size() + 1);
1647   for (unsigned i = 0, e = Set.size(); i != e; ++i)
1648     BV.set(Set[i]->EnumValue);
1649   return BV;
1650 }