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