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