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