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