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