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