1cf260d0ea1e5f74dac41b002bd129a63565dcb5
[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/ADT/IntEqClasses.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/SparseBitVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/TableGen/Error.h"
25
26 using namespace llvm;
27
28 #define DEBUG_TYPE "regalloc-emitter"
29
30 //===----------------------------------------------------------------------===//
31 //                             CodeGenSubRegIndex
32 //===----------------------------------------------------------------------===//
33
34 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
35   : TheDef(R), EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
36   Name = R->getName();
37   if (R->getValue("Namespace"))
38     Namespace = R->getValueAsString("Namespace");
39   Size = R->getValueAsInt("Size");
40   Offset = R->getValueAsInt("Offset");
41 }
42
43 CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
44                                        unsigned Enum)
45   : TheDef(nullptr), Name(N), Namespace(Nspace), Size(-1), Offset(-1),
46     EnumValue(Enum), LaneMask(0), AllSuperRegsCovered(true) {
47 }
48
49 std::string CodeGenSubRegIndex::getQualifiedName() const {
50   std::string N = getNamespace();
51   if (!N.empty())
52     N += "::";
53   N += getName();
54   return N;
55 }
56
57 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
58   if (!TheDef)
59     return;
60
61   std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
62   if (!Comps.empty()) {
63     if (Comps.size() != 2)
64       PrintFatalError(TheDef->getLoc(),
65                       "ComposedOf must have exactly two entries");
66     CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
67     CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
68     CodeGenSubRegIndex *X = A->addComposite(B, this);
69     if (X)
70       PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
71   }
72
73   std::vector<Record*> Parts =
74     TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
75   if (!Parts.empty()) {
76     if (Parts.size() < 2)
77       PrintFatalError(TheDef->getLoc(),
78                       "CoveredBySubRegs must have two or more entries");
79     SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
80     for (unsigned i = 0, e = Parts.size(); i != e; ++i)
81       IdxParts.push_back(RegBank.getSubRegIdx(Parts[i]));
82     RegBank.addConcatSubRegIndex(IdxParts, this);
83   }
84 }
85
86 unsigned CodeGenSubRegIndex::computeLaneMask() const {
87   // Already computed?
88   if (LaneMask)
89     return LaneMask;
90
91   // Recursion guard, shouldn't be required.
92   LaneMask = ~0u;
93
94   // The lane mask is simply the union of all sub-indices.
95   unsigned M = 0;
96   for (const auto &C : Composed)
97     M |= C.second->computeLaneMask();
98   assert(M && "Missing lane mask, sub-register cycle?");
99   LaneMask = M;
100   return LaneMask;
101 }
102
103 //===----------------------------------------------------------------------===//
104 //                              CodeGenRegister
105 //===----------------------------------------------------------------------===//
106
107 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
108   : TheDef(R),
109     EnumValue(Enum),
110     CostPerUse(R->getValueAsInt("CostPerUse")),
111     CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
112     NumNativeRegUnits(0),
113     SubRegsComplete(false),
114     SuperRegsComplete(false),
115     TopoSig(~0u)
116 {}
117
118 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
119   std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
120   std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
121
122   if (SRIs.size() != SRs.size())
123     PrintFatalError(TheDef->getLoc(),
124                     "SubRegs and SubRegIndices must have the same size");
125
126   for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
127     ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
128     ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
129   }
130
131   // Also compute leading super-registers. Each register has a list of
132   // covered-by-subregs super-registers where it appears as the first explicit
133   // sub-register.
134   //
135   // This is used by computeSecondarySubRegs() to find candidates.
136   if (CoveredBySubRegs && !ExplicitSubRegs.empty())
137     ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
138
139   // Add ad hoc alias links. This is a symmetric relationship between two
140   // registers, so build a symmetric graph by adding links in both ends.
141   std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
142   for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
143     CodeGenRegister *Reg = RegBank.getReg(Aliases[i]);
144     ExplicitAliases.push_back(Reg);
145     Reg->ExplicitAliases.push_back(this);
146   }
147 }
148
149 const std::string &CodeGenRegister::getName() const {
150   assert(TheDef && "no def");
151   return TheDef->getName();
152 }
153
154 namespace {
155 // Iterate over all register units in a set of registers.
156 class RegUnitIterator {
157   CodeGenRegister::Set::const_iterator RegI, RegE;
158   CodeGenRegister::RegUnitList::const_iterator UnitI, UnitE;
159
160 public:
161   RegUnitIterator(const CodeGenRegister::Set &Regs):
162     RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
163
164     if (RegI != RegE) {
165       UnitI = (*RegI)->getRegUnits().begin();
166       UnitE = (*RegI)->getRegUnits().end();
167       advance();
168     }
169   }
170
171   bool isValid() const { return UnitI != UnitE; }
172
173   unsigned operator* () const { assert(isValid()); return *UnitI; }
174
175   const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
176
177   /// Preincrement.  Move to the next unit.
178   void operator++() {
179     assert(isValid() && "Cannot advance beyond the last operand");
180     ++UnitI;
181     advance();
182   }
183
184 protected:
185   void advance() {
186     while (UnitI == UnitE) {
187       if (++RegI == RegE)
188         break;
189       UnitI = (*RegI)->getRegUnits().begin();
190       UnitE = (*RegI)->getRegUnits().end();
191     }
192   }
193 };
194 } // namespace
195
196 // Merge two RegUnitLists maintaining the order and removing duplicates.
197 // Overwrites MergedRU in the process.
198 static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
199                           const CodeGenRegister::RegUnitList &RRU) {
200   CodeGenRegister::RegUnitList LRU = MergedRU;
201   MergedRU.clear();
202   std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(),
203                  std::back_inserter(MergedRU));
204 }
205
206 // Return true of this unit appears in RegUnits.
207 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
208   return std::count(RegUnits.begin(), RegUnits.end(), Unit);
209 }
210
211 // Inherit register units from subregisters.
212 // Return true if the RegUnits changed.
213 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
214   unsigned OldNumUnits = RegUnits.size();
215
216   SparseBitVector<> NewUnits;
217   for (unsigned RU : RegUnits)
218     NewUnits.set(RU);
219
220   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
221        I != E; ++I) {
222     CodeGenRegister *SR = I->second;
223     // Merge the subregister's units into this register's RegUnits.
224     for (unsigned RU : SR->RegUnits)
225       NewUnits.set(RU);
226   }
227
228   RegUnits.clear();
229   RegUnits.reserve(NewUnits.count());
230   for (unsigned RU : NewUnits)
231     RegUnits.push_back(RU);
232
233   return OldNumUnits != RegUnits.size();
234 }
235
236 const CodeGenRegister::SubRegMap &
237 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
238   // Only compute this map once.
239   if (SubRegsComplete)
240     return SubRegs;
241   SubRegsComplete = true;
242
243   // First insert the explicit subregs and make sure they are fully indexed.
244   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
245     CodeGenRegister *SR = ExplicitSubRegs[i];
246     CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
247     if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
248       PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
249                       " appears twice in Register " + getName());
250     // Map explicit sub-registers first, so the names take precedence.
251     // The inherited sub-registers are mapped below.
252     SubReg2Idx.insert(std::make_pair(SR, Idx));
253   }
254
255   // Keep track of inherited subregs and how they can be reached.
256   SmallPtrSet<CodeGenRegister*, 8> Orphans;
257
258   // Clone inherited subregs and place duplicate entries in Orphans.
259   // Here the order is important - earlier subregs take precedence.
260   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
261     CodeGenRegister *SR = ExplicitSubRegs[i];
262     const SubRegMap &Map = SR->computeSubRegs(RegBank);
263
264     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
265          ++SI) {
266       if (!SubRegs.insert(*SI).second)
267         Orphans.insert(SI->second);
268     }
269   }
270
271   // Expand any composed subreg indices.
272   // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
273   // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
274   // expanded subreg indices recursively.
275   SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
276   for (unsigned i = 0; i != Indices.size(); ++i) {
277     CodeGenSubRegIndex *Idx = Indices[i];
278     const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
279     CodeGenRegister *SR = SubRegs[Idx];
280     const SubRegMap &Map = SR->computeSubRegs(RegBank);
281
282     // Look at the possible compositions of Idx.
283     // They may not all be supported by SR.
284     for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
285            E = Comps.end(); I != E; ++I) {
286       SubRegMap::const_iterator SRI = Map.find(I->first);
287       if (SRI == Map.end())
288         continue; // Idx + I->first doesn't exist in SR.
289       // Add I->second as a name for the subreg SRI->second, assuming it is
290       // orphaned, and the name isn't already used for something else.
291       if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
292         continue;
293       // We found a new name for the orphaned sub-register.
294       SubRegs.insert(std::make_pair(I->second, SRI->second));
295       Indices.push_back(I->second);
296     }
297   }
298
299   // Now Orphans contains the inherited subregisters without a direct index.
300   // Create inferred indexes for all missing entries.
301   // Work backwards in the Indices vector in order to compose subregs bottom-up.
302   // Consider this subreg sequence:
303   //
304   //   qsub_1 -> dsub_0 -> ssub_0
305   //
306   // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
307   // can be reached in two different ways:
308   //
309   //   qsub_1 -> ssub_0
310   //   dsub_2 -> ssub_0
311   //
312   // We pick the latter composition because another register may have [dsub_0,
313   // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg.  The
314   // dsub_2 -> ssub_0 composition can be shared.
315   while (!Indices.empty() && !Orphans.empty()) {
316     CodeGenSubRegIndex *Idx = Indices.pop_back_val();
317     CodeGenRegister *SR = SubRegs[Idx];
318     const SubRegMap &Map = SR->computeSubRegs(RegBank);
319     for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE;
320          ++SI)
321       if (Orphans.erase(SI->second))
322         SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] = SI->second;
323   }
324
325   // Compute the inverse SubReg -> Idx map.
326   for (SubRegMap::const_iterator SI = SubRegs.begin(), SE = SubRegs.end();
327        SI != SE; ++SI) {
328     if (SI->second == this) {
329       ArrayRef<SMLoc> Loc;
330       if (TheDef)
331         Loc = TheDef->getLoc();
332       PrintFatalError(Loc, "Register " + getName() +
333                       " has itself as a sub-register");
334     }
335
336     // Compute AllSuperRegsCovered.
337     if (!CoveredBySubRegs)
338       SI->first->AllSuperRegsCovered = false;
339
340     // Ensure that every sub-register has a unique name.
341     DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
342       SubReg2Idx.insert(std::make_pair(SI->second, SI->first)).first;
343     if (Ins->second == SI->first)
344       continue;
345     // Trouble: Two different names for SI->second.
346     ArrayRef<SMLoc> Loc;
347     if (TheDef)
348       Loc = TheDef->getLoc();
349     PrintFatalError(Loc, "Sub-register can't have two names: " +
350                   SI->second->getName() + " available as " +
351                   SI->first->getName() + " and " + Ins->second->getName());
352   }
353
354   // Derive possible names for sub-register concatenations from any explicit
355   // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
356   // that getConcatSubRegIndex() won't invent any concatenated indices that the
357   // user already specified.
358   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
359     CodeGenRegister *SR = ExplicitSubRegs[i];
360     if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1)
361       continue;
362
363     // SR is composed of multiple sub-regs. Find their names in this register.
364     SmallVector<CodeGenSubRegIndex*, 8> Parts;
365     for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j)
366       Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
367
368     // Offer this as an existing spelling for the concatenation of Parts.
369     RegBank.addConcatSubRegIndex(Parts, ExplicitSubRegIndices[i]);
370   }
371
372   // Initialize RegUnitList. Because getSubRegs is called recursively, this
373   // processes the register hierarchy in postorder.
374   //
375   // Inherit all sub-register units. It is good enough to look at the explicit
376   // sub-registers, the other registers won't contribute any more units.
377   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
378     CodeGenRegister *SR = ExplicitSubRegs[i];
379     // Explicit sub-registers are usually disjoint, so this is a good way of
380     // computing the union. We may pick up a few duplicates that will be
381     // eliminated below.
382     unsigned N = RegUnits.size();
383     RegUnits.append(SR->RegUnits.begin(), SR->RegUnits.end());
384     std::inplace_merge(RegUnits.begin(), RegUnits.begin() + N, RegUnits.end());
385   }
386   RegUnits.erase(std::unique(RegUnits.begin(), RegUnits.end()), RegUnits.end());
387
388   // Absent any ad hoc aliasing, we create one register unit per leaf register.
389   // These units correspond to the maximal cliques in the register overlap
390   // graph which is optimal.
391   //
392   // When there is ad hoc aliasing, we simply create one unit per edge in the
393   // undirected ad hoc aliasing graph. Technically, we could do better by
394   // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
395   // are extremely rare anyway (I've never seen one), so we don't bother with
396   // the added complexity.
397   for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
398     CodeGenRegister *AR = ExplicitAliases[i];
399     // Only visit each edge once.
400     if (AR->SubRegsComplete)
401       continue;
402     // Create a RegUnit representing this alias edge, and add it to both
403     // registers.
404     unsigned Unit = RegBank.newRegUnit(this, AR);
405     RegUnits.push_back(Unit);
406     AR->RegUnits.push_back(Unit);
407   }
408
409   // Finally, create units for leaf registers without ad hoc aliases. Note that
410   // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
411   // necessary. This means the aliasing leaf registers can share a single unit.
412   if (RegUnits.empty())
413     RegUnits.push_back(RegBank.newRegUnit(this));
414
415   // We have now computed the native register units. More may be adopted later
416   // for balancing purposes.
417   NumNativeRegUnits = RegUnits.size();
418
419   return SubRegs;
420 }
421
422 // In a register that is covered by its sub-registers, try to find redundant
423 // sub-registers. For example:
424 //
425 //   QQ0 = {Q0, Q1}
426 //   Q0 = {D0, D1}
427 //   Q1 = {D2, D3}
428 //
429 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
430 // the register definition.
431 //
432 // The explicitly specified registers form a tree. This function discovers
433 // sub-register relationships that would force a DAG.
434 //
435 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
436   // Collect new sub-registers first, add them later.
437   SmallVector<SubRegMap::value_type, 8> NewSubRegs;
438
439   // Look at the leading super-registers of each sub-register. Those are the
440   // candidates for new sub-registers, assuming they are fully contained in
441   // this register.
442   for (SubRegMap::iterator I = SubRegs.begin(), E = SubRegs.end(); I != E; ++I){
443     const CodeGenRegister *SubReg = I->second;
444     const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
445     for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
446       CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
447       // Already got this sub-register?
448       if (Cand == this || getSubRegIndex(Cand))
449         continue;
450       // Check if each component of Cand is already a sub-register.
451       // We know that the first component is I->second, and is present with the
452       // name I->first.
453       SmallVector<CodeGenSubRegIndex*, 8> Parts(1, I->first);
454       assert(!Cand->ExplicitSubRegs.empty() &&
455              "Super-register has no sub-registers");
456       for (unsigned j = 1, e = Cand->ExplicitSubRegs.size(); j != e; ++j) {
457         if (CodeGenSubRegIndex *Idx = getSubRegIndex(Cand->ExplicitSubRegs[j]))
458           Parts.push_back(Idx);
459         else {
460           // Sub-register doesn't exist.
461           Parts.clear();
462           break;
463         }
464       }
465       // If some Cand sub-register is not part of this register, or if Cand only
466       // has one sub-register, there is nothing to do.
467       if (Parts.size() <= 1)
468         continue;
469
470       // Each part of Cand is a sub-register of this. Make the full Cand also
471       // a sub-register with a concatenated sub-register index.
472       CodeGenSubRegIndex *Concat= RegBank.getConcatSubRegIndex(Parts);
473       NewSubRegs.push_back(std::make_pair(Concat, Cand));
474     }
475   }
476
477   // Now add all the new sub-registers.
478   for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
479     // Don't add Cand if another sub-register is already using the index.
480     if (!SubRegs.insert(NewSubRegs[i]).second)
481       continue;
482
483     CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
484     CodeGenRegister *NewSubReg = NewSubRegs[i].second;
485     SubReg2Idx.insert(std::make_pair(NewSubReg, NewIdx));
486   }
487
488   // Create sub-register index composition maps for the synthesized indices.
489   for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
490     CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
491     CodeGenRegister *NewSubReg = NewSubRegs[i].second;
492     for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
493            SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
494       CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
495       if (!SubIdx)
496         PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
497                         SI->second->getName() + " in " + getName());
498       NewIdx->addComposite(SI->first, SubIdx);
499     }
500   }
501 }
502
503 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
504   // Only visit each register once.
505   if (SuperRegsComplete)
506     return;
507   SuperRegsComplete = true;
508
509   // Make sure all sub-registers have been visited first, so the super-reg
510   // lists will be topologically ordered.
511   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
512        I != E; ++I)
513     I->second->computeSuperRegs(RegBank);
514
515   // Now add this as a super-register on all sub-registers.
516   // Also compute the TopoSigId in post-order.
517   TopoSigId Id;
518   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
519        I != E; ++I) {
520     // Topological signature computed from SubIdx, TopoId(SubReg).
521     // Loops and idempotent indices have TopoSig = ~0u.
522     Id.push_back(I->first->EnumValue);
523     Id.push_back(I->second->TopoSig);
524
525     // Don't add duplicate entries.
526     if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
527       continue;
528     I->second->SuperRegs.push_back(this);
529   }
530   TopoSig = RegBank.getTopoSig(Id);
531 }
532
533 void
534 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
535                                     CodeGenRegBank &RegBank) const {
536   assert(SubRegsComplete && "Must precompute sub-registers");
537   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
538     CodeGenRegister *SR = ExplicitSubRegs[i];
539     if (OSet.insert(SR))
540       SR->addSubRegsPreOrder(OSet, RegBank);
541   }
542   // Add any secondary sub-registers that weren't part of the explicit tree.
543   for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
544        I != E; ++I)
545     OSet.insert(I->second);
546 }
547
548 // Get the sum of this register's unit weights.
549 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
550   unsigned Weight = 0;
551   for (RegUnitList::const_iterator I = RegUnits.begin(), E = RegUnits.end();
552        I != E; ++I) {
553     Weight += RegBank.getRegUnit(*I).Weight;
554   }
555   return Weight;
556 }
557
558 //===----------------------------------------------------------------------===//
559 //                               RegisterTuples
560 //===----------------------------------------------------------------------===//
561
562 // A RegisterTuples def is used to generate pseudo-registers from lists of
563 // sub-registers. We provide a SetTheory expander class that returns the new
564 // registers.
565 namespace {
566 struct TupleExpander : SetTheory::Expander {
567   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
568     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
569     unsigned Dim = Indices.size();
570     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
571     if (Dim != SubRegs->getSize())
572       PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
573     if (Dim < 2)
574       PrintFatalError(Def->getLoc(),
575                       "Tuples must have at least 2 sub-registers");
576
577     // Evaluate the sub-register lists to be zipped.
578     unsigned Length = ~0u;
579     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
580     for (unsigned i = 0; i != Dim; ++i) {
581       ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
582       Length = std::min(Length, unsigned(Lists[i].size()));
583     }
584
585     if (Length == 0)
586       return;
587
588     // Precompute some types.
589     Record *RegisterCl = Def->getRecords().getClass("Register");
590     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
591     StringInit *BlankName = StringInit::get("");
592
593     // Zip them up.
594     for (unsigned n = 0; n != Length; ++n) {
595       std::string Name;
596       Record *Proto = Lists[0][n];
597       std::vector<Init*> Tuple;
598       unsigned CostPerUse = 0;
599       for (unsigned i = 0; i != Dim; ++i) {
600         Record *Reg = Lists[i][n];
601         if (i) Name += '_';
602         Name += Reg->getName();
603         Tuple.push_back(DefInit::get(Reg));
604         CostPerUse = std::max(CostPerUse,
605                               unsigned(Reg->getValueAsInt("CostPerUse")));
606       }
607
608       // Create a new Record representing the synthesized register. This record
609       // is only for consumption by CodeGenRegister, it is not added to the
610       // RecordKeeper.
611       Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords());
612       Elts.insert(NewReg);
613
614       // Copy Proto super-classes.
615       ArrayRef<Record *> Supers = Proto->getSuperClasses();
616       ArrayRef<SMRange> Ranges = Proto->getSuperClassRanges();
617       for (unsigned i = 0, e = Supers.size(); i != e; ++i)
618         NewReg->addSuperClass(Supers[i], Ranges[i]);
619
620       // Copy Proto fields.
621       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
622         RecordVal RV = Proto->getValues()[i];
623
624         // Skip existing fields, like NAME.
625         if (NewReg->getValue(RV.getNameInit()))
626           continue;
627
628         StringRef Field = RV.getName();
629
630         // Replace the sub-register list with Tuple.
631         if (Field == "SubRegs")
632           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
633
634         // Provide a blank AsmName. MC hacks are required anyway.
635         if (Field == "AsmName")
636           RV.setValue(BlankName);
637
638         // CostPerUse is aggregated from all Tuple members.
639         if (Field == "CostPerUse")
640           RV.setValue(IntInit::get(CostPerUse));
641
642         // Composite registers are always covered by sub-registers.
643         if (Field == "CoveredBySubRegs")
644           RV.setValue(BitInit::get(true));
645
646         // Copy fields from the RegisterTuples def.
647         if (Field == "SubRegIndices" ||
648             Field == "CompositeIndices") {
649           NewReg->addValue(*Def->getValue(Field));
650           continue;
651         }
652
653         // Some fields get their default uninitialized value.
654         if (Field == "DwarfNumbers" ||
655             Field == "DwarfAlias" ||
656             Field == "Aliases") {
657           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
658             NewReg->addValue(*DefRV);
659           continue;
660         }
661
662         // Everything else is copied from Proto.
663         NewReg->addValue(RV);
664       }
665     }
666   }
667 };
668 }
669
670 //===----------------------------------------------------------------------===//
671 //                            CodeGenRegisterClass
672 //===----------------------------------------------------------------------===//
673
674 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
675   : TheDef(R),
676     Name(R->getName()),
677     TopoSigs(RegBank.getNumTopoSigs()),
678     EnumValue(-1),
679     LaneMask(0) {
680   // Rename anonymous register classes.
681   if (R->getName().size() > 9 && R->getName()[9] == '.') {
682     static unsigned AnonCounter = 0;
683     R->setName("AnonRegClass_" + utostr(AnonCounter));
684     // MSVC2012 ICEs if AnonCounter++ is directly passed to utostr.
685     ++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       PrintFatalError("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, R->getLoc());
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         PrintFatalError(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 : MVT(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(nullptr),
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   return std::tie(*Members, SpillSize, SpillAlignment) <
801          std::tie(*B.Members, B.SpillSize, B.SpillAlignment);
802 }
803
804 // Returns true if RC is a strict subclass.
805 // RC is a sub-class of this class if it is a valid replacement for any
806 // instruction operand where a register of this classis required. It must
807 // satisfy these conditions:
808 //
809 // 1. All RC registers are also in this.
810 // 2. The RC spill size must not be smaller than our spill size.
811 // 3. RC spill alignment must be compatible with ours.
812 //
813 static bool testSubClass(const CodeGenRegisterClass *A,
814                          const CodeGenRegisterClass *B) {
815   return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 &&
816     A->SpillSize <= B->SpillSize &&
817     std::includes(A->getMembers().begin(), A->getMembers().end(),
818                   B->getMembers().begin(), B->getMembers().end(),
819                   CodeGenRegister::Less());
820 }
821
822 /// Sorting predicate for register classes.  This provides a topological
823 /// ordering that arranges all register classes before their sub-classes.
824 ///
825 /// Register classes with the same registers, spill size, and alignment form a
826 /// clique.  They will be ordered alphabetically.
827 ///
828 static bool TopoOrderRC(const CodeGenRegisterClass &PA,
829                         const CodeGenRegisterClass &PB) {
830   auto *A = &PA;
831   auto *B = &PB;
832   if (A == B)
833     return 0;
834
835   // Order by ascending spill size.
836   if (A->SpillSize < B->SpillSize)
837     return true;
838   if (A->SpillSize > B->SpillSize)
839     return false;
840
841   // Order by ascending spill alignment.
842   if (A->SpillAlignment < B->SpillAlignment)
843     return true;
844   if (A->SpillAlignment > B->SpillAlignment)
845     return false;
846
847   // Order by descending set size.  Note that the classes' allocation order may
848   // not have been computed yet.  The Members set is always vaild.
849   if (A->getMembers().size() > B->getMembers().size())
850     return true;
851   if (A->getMembers().size() < B->getMembers().size())
852     return false;
853
854   // Finally order by name as a tie breaker.
855   return StringRef(A->getName()) < B->getName();
856 }
857
858 std::string CodeGenRegisterClass::getQualifiedName() const {
859   if (Namespace.empty())
860     return getName();
861   else
862     return Namespace + "::" + getName();
863 }
864
865 // Compute sub-classes of all register classes.
866 // Assume the classes are ordered topologically.
867 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
868   auto &RegClasses = RegBank.getRegClasses();
869
870   // Visit backwards so sub-classes are seen first.
871   for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
872     CodeGenRegisterClass &RC = *I;
873     RC.SubClasses.resize(RegClasses.size());
874     RC.SubClasses.set(RC.EnumValue);
875
876     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
877     for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
878       CodeGenRegisterClass &SubRC = *I2;
879       if (RC.SubClasses.test(SubRC.EnumValue))
880         continue;
881       if (!testSubClass(&RC, &SubRC))
882         continue;
883       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
884       // check them again.
885       RC.SubClasses |= SubRC.SubClasses;
886     }
887
888     // Sweep up missed clique members.  They will be immediately preceding RC.
889     for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
890       RC.SubClasses.set(I2->EnumValue);
891   }
892
893   // Compute the SuperClasses lists from the SubClasses vectors.
894   for (auto &RC : RegClasses) {
895     const BitVector &SC = RC.getSubClasses();
896     auto I = RegClasses.begin();
897     for (int s = 0, next_s = SC.find_first(); next_s != -1;
898          next_s = SC.find_next(s)) {
899       std::advance(I, next_s - s);
900       s = next_s;
901       if (&*I == &RC)
902         continue;
903       I->SuperClasses.push_back(&RC);
904     }
905   }
906
907   // With the class hierarchy in place, let synthesized register classes inherit
908   // properties from their closest super-class. The iteration order here can
909   // propagate properties down multiple levels.
910   for (auto &RC : RegClasses)
911     if (!RC.getDef())
912       RC.inheritProperties(RegBank);
913 }
914
915 void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
916                                               BitVector &Out) const {
917   auto FindI = SuperRegClasses.find(SubIdx);
918   if (FindI == SuperRegClasses.end())
919     return;
920   for (CodeGenRegisterClass *RC : FindI->second)
921     Out.set(RC->EnumValue);
922 }
923
924 // Populate a unique sorted list of units from a register set.
925 void CodeGenRegisterClass::buildRegUnitSet(
926   std::vector<unsigned> &RegUnits) const {
927   std::vector<unsigned> TmpUnits;
928   for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
929     TmpUnits.push_back(*UnitI);
930   std::sort(TmpUnits.begin(), TmpUnits.end());
931   std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
932                    std::back_inserter(RegUnits));
933 }
934
935 //===----------------------------------------------------------------------===//
936 //                               CodeGenRegBank
937 //===----------------------------------------------------------------------===//
938
939 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) {
940   // Configure register Sets to understand register classes and tuples.
941   Sets.addFieldExpander("RegisterClass", "MemberList");
942   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
943   Sets.addExpander("RegisterTuples", new TupleExpander());
944
945   // Read in the user-defined (named) sub-register indices.
946   // More indices will be synthesized later.
947   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
948   std::sort(SRIs.begin(), SRIs.end(), LessRecord());
949   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
950     getSubRegIdx(SRIs[i]);
951   // Build composite maps from ComposedOf fields.
952   for (auto &Idx : SubRegIndices)
953     Idx.updateComponents(*this);
954
955   // Read in the register definitions.
956   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
957   std::sort(Regs.begin(), Regs.end(), LessRecordRegister());
958   // Assign the enumeration values.
959   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
960     getReg(Regs[i]);
961
962   // Expand tuples and number the new registers.
963   std::vector<Record*> Tups =
964     Records.getAllDerivedDefinitions("RegisterTuples");
965
966   for (Record *R : Tups) {
967     std::vector<Record *> TupRegs = *Sets.expand(R);
968     std::sort(TupRegs.begin(), TupRegs.end(), LessRecordRegister());
969     for (Record *RC : TupRegs)
970       getReg(RC);
971   }
972
973   // Now all the registers are known. Build the object graph of explicit
974   // register-register references.
975   for (auto &Reg : Registers)
976     Reg.buildObjectGraph(*this);
977
978   // Compute register name map.
979   for (auto &Reg : Registers)
980     // FIXME: This could just be RegistersByName[name] = register, except that
981     // causes some failures in MIPS - perhaps they have duplicate register name
982     // entries? (or maybe there's a reason for it - I don't know much about this
983     // code, just drive-by refactoring)
984     RegistersByName.insert(
985         std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
986
987   // Precompute all sub-register maps.
988   // This will create Composite entries for all inferred sub-register indices.
989   for (auto &Reg : Registers)
990     Reg.computeSubRegs(*this);
991
992   // Infer even more sub-registers by combining leading super-registers.
993   for (auto &Reg : Registers)
994     if (Reg.CoveredBySubRegs)
995       Reg.computeSecondarySubRegs(*this);
996
997   // After the sub-register graph is complete, compute the topologically
998   // ordered SuperRegs list.
999   for (auto &Reg : Registers)
1000     Reg.computeSuperRegs(*this);
1001
1002   // Native register units are associated with a leaf register. They've all been
1003   // discovered now.
1004   NumNativeRegUnits = RegUnits.size();
1005
1006   // Read in register class definitions.
1007   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
1008   if (RCs.empty())
1009     PrintFatalError("No 'RegisterClass' subclasses defined!");
1010
1011   // Allocate user-defined register classes.
1012   for (auto *RC : RCs) {
1013     RegClasses.push_back(CodeGenRegisterClass(*this, RC));
1014     addToMaps(&RegClasses.back());
1015   }
1016
1017   // Infer missing classes to create a full algebra.
1018   computeInferredRegisterClasses();
1019
1020   // Order register classes topologically and assign enum values.
1021   RegClasses.sort(TopoOrderRC);
1022   unsigned i = 0;
1023   for (auto &RC : RegClasses)
1024     RC.EnumValue = i++;
1025   CodeGenRegisterClass::computeSubClasses(*this);
1026 }
1027
1028 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1029 CodeGenSubRegIndex*
1030 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1031   SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
1032   return &SubRegIndices.back();
1033 }
1034
1035 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1036   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1037   if (Idx)
1038     return Idx;
1039   SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
1040   Idx = &SubRegIndices.back();
1041   return Idx;
1042 }
1043
1044 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1045   CodeGenRegister *&Reg = Def2Reg[Def];
1046   if (Reg)
1047     return Reg;
1048   Registers.emplace_back(Def, Registers.size() + 1);
1049   Reg = &Registers.back();
1050   return Reg;
1051 }
1052
1053 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1054   if (Record *Def = RC->getDef())
1055     Def2RC.insert(std::make_pair(Def, RC));
1056
1057   // Duplicate classes are rejected by insert().
1058   // That's OK, we only care about the properties handled by CGRC::Key.
1059   CodeGenRegisterClass::Key K(*RC);
1060   Key2RC.insert(std::make_pair(K, RC));
1061 }
1062
1063 // Create a synthetic sub-class if it is missing.
1064 CodeGenRegisterClass*
1065 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1066                                     const CodeGenRegister::Set *Members,
1067                                     StringRef Name) {
1068   // Synthetic sub-class has the same size and alignment as RC.
1069   CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
1070   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1071   if (FoundI != Key2RC.end())
1072     return FoundI->second;
1073
1074   // Sub-class doesn't exist, create a new one.
1075   RegClasses.push_back(CodeGenRegisterClass(*this, Name, K));
1076   addToMaps(&RegClasses.back());
1077   return &RegClasses.back();
1078 }
1079
1080 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1081   if (CodeGenRegisterClass *RC = Def2RC[Def])
1082     return RC;
1083
1084   PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1085 }
1086
1087 CodeGenSubRegIndex*
1088 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1089                                         CodeGenSubRegIndex *B) {
1090   // Look for an existing entry.
1091   CodeGenSubRegIndex *Comp = A->compose(B);
1092   if (Comp)
1093     return Comp;
1094
1095   // None exists, synthesize one.
1096   std::string Name = A->getName() + "_then_" + B->getName();
1097   Comp = createSubRegIndex(Name, A->getNamespace());
1098   A->addComposite(B, Comp);
1099   return Comp;
1100 }
1101
1102 CodeGenSubRegIndex *CodeGenRegBank::
1103 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1104   assert(Parts.size() > 1 && "Need two parts to concatenate");
1105
1106   // Look for an existing entry.
1107   CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1108   if (Idx)
1109     return Idx;
1110
1111   // None exists, synthesize one.
1112   std::string Name = Parts.front()->getName();
1113   // Determine whether all parts are contiguous.
1114   bool isContinuous = true;
1115   unsigned Size = Parts.front()->Size;
1116   unsigned LastOffset = Parts.front()->Offset;
1117   unsigned LastSize = Parts.front()->Size;
1118   for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1119     Name += '_';
1120     Name += Parts[i]->getName();
1121     Size += Parts[i]->Size;
1122     if (Parts[i]->Offset != (LastOffset + LastSize))
1123       isContinuous = false;
1124     LastOffset = Parts[i]->Offset;
1125     LastSize = Parts[i]->Size;
1126   }
1127   Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1128   Idx->Size = Size;
1129   Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1130   return Idx;
1131 }
1132
1133 void CodeGenRegBank::computeComposites() {
1134   // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1135   // and many registers will share TopoSigs on regular architectures.
1136   BitVector TopoSigs(getNumTopoSigs());
1137
1138   for (const auto &Reg1 : Registers) {
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::computeSubRegLaneMasks() {
1184   // First assign individual bits to all the leaf indices.
1185   unsigned Bit = 0;
1186   // Determine mask of lanes that cover their registers.
1187   CoveringLanes = ~0u;
1188   for (auto &Idx : SubRegIndices) {
1189     if (Idx.getComposites().empty()) {
1190       Idx.LaneMask = 1u << Bit;
1191       // Share bit 31 in the unlikely case there are more than 32 leafs.
1192       //
1193       // Sharing bits is harmless; it allows graceful degradation in targets
1194       // with more than 32 vector lanes. They simply get a limited resolution
1195       // view of lanes beyond the 32nd.
1196       //
1197       // See also the comment for getSubRegIndexLaneMask().
1198       if (Bit < 31)
1199         ++Bit;
1200       else
1201         // Once bit 31 is shared among multiple leafs, the 'lane' it represents
1202         // is no longer covering its registers.
1203         CoveringLanes &= ~(1u << Bit);
1204     } else {
1205       Idx.LaneMask = 0;
1206     }
1207   }
1208
1209   // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
1210   // here is that for each possible target subregister we look at the leafs
1211   // in the subregister graph that compose for this target and create
1212   // transformation sequences for the lanemasks. Each step in the sequence
1213   // consists of a bitmask and a bitrotate operation. As the rotation amounts
1214   // are usually the same for many subregisters we can easily combine the steps
1215   // by combining the masks.
1216   for (const auto &Idx : SubRegIndices) {
1217     const auto &Composites = Idx.getComposites();
1218     auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
1219     // Go through all leaf subregisters and find the ones that compose with Idx.
1220     // These make out all possible valid bits in the lane mask we want to
1221     // transform. Looking only at the leafs ensure that only a single bit in
1222     // the mask is set.
1223     unsigned NextBit = 0;
1224     for (auto &Idx2 : SubRegIndices) {
1225       // Skip non-leaf subregisters.
1226       if (!Idx2.getComposites().empty())
1227         continue;
1228       // Replicate the behaviour from the lane mask generation loop above.
1229       unsigned SrcBit = NextBit;
1230       unsigned SrcMask = 1u << SrcBit;
1231       if (NextBit < 31)
1232         ++NextBit;
1233       assert(Idx2.LaneMask == SrcMask);
1234
1235       // Get the composed subregister if there is any.
1236       auto C = Composites.find(&Idx2);
1237       if (C == Composites.end())
1238         continue;
1239       const CodeGenSubRegIndex *Composite = C->second;
1240       // The Composed subreg should be a leaf subreg too
1241       assert(Composite->getComposites().empty());
1242
1243       // Create Mask+Rotate operation and merge with existing ops if possible.
1244       unsigned DstBit = Log2_32(Composite->LaneMask);
1245       int Shift = DstBit - SrcBit;
1246       uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift : 32+Shift;
1247       for (auto &I : LaneTransforms) {
1248         if (I.RotateLeft == RotateLeft) {
1249           I.Mask |= SrcMask;
1250           SrcMask = 0;
1251         }
1252       }
1253       if (SrcMask != 0) {
1254         MaskRolPair MaskRol = { SrcMask, RotateLeft };
1255         LaneTransforms.push_back(MaskRol);
1256       }
1257     }
1258     // Optimize if the transformation consists of one step only: Set mask to
1259     // 0xffffffff (including some irrelevant invalid bits) so that it should
1260     // merge with more entries later while compressing the table.
1261     if (LaneTransforms.size() == 1)
1262       LaneTransforms[0].Mask = ~0u;
1263
1264     // Further compression optimization: For invalid compositions resulting
1265     // in a sequence with 0 entries we can just pick any other. Choose
1266     // Mask 0xffffffff with Rotation 0.
1267     if (LaneTransforms.size() == 0) {
1268       MaskRolPair P = { ~0u, 0 };
1269       LaneTransforms.push_back(P);
1270     }
1271   }
1272
1273   // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1274   // by the sub-register graph? This doesn't occur in any known targets.
1275
1276   // Inherit lanes from composites.
1277   for (const auto &Idx : SubRegIndices) {
1278     unsigned Mask = Idx.computeLaneMask();
1279     // If some super-registers without CoveredBySubRegs use this index, we can
1280     // no longer assume that the lanes are covering their registers.
1281     if (!Idx.AllSuperRegsCovered)
1282       CoveringLanes &= ~Mask;
1283   }
1284
1285   // Compute lane mask combinations for register classes.
1286   for (auto &RegClass : RegClasses) {
1287     unsigned LaneMask = 0;
1288     for (const auto &SubRegIndex : SubRegIndices) {
1289       if (RegClass.getSubClassWithSubReg(&SubRegIndex) != &RegClass)
1290         continue;
1291       LaneMask |= SubRegIndex.LaneMask;
1292     }
1293     RegClass.LaneMask = LaneMask;
1294   }
1295 }
1296
1297 namespace {
1298 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1299 // the transitive closure of the union of overlapping register
1300 // classes. Together, the UberRegSets form a partition of the registers. If we
1301 // consider overlapping register classes to be connected, then each UberRegSet
1302 // is a set of connected components.
1303 //
1304 // An UberRegSet will likely be a horizontal slice of register names of
1305 // the same width. Nontrivial subregisters should then be in a separate
1306 // UberRegSet. But this property isn't required for valid computation of
1307 // register unit weights.
1308 //
1309 // A Weight field caches the max per-register unit weight in each UberRegSet.
1310 //
1311 // A set of SingularDeterminants flags single units of some register in this set
1312 // for which the unit weight equals the set weight. These units should not have
1313 // their weight increased.
1314 struct UberRegSet {
1315   CodeGenRegister::Set Regs;
1316   unsigned Weight;
1317   CodeGenRegister::RegUnitList SingularDeterminants;
1318
1319   UberRegSet(): Weight(0) {}
1320 };
1321 } // namespace
1322
1323 // Partition registers into UberRegSets, where each set is the transitive
1324 // closure of the union of overlapping register classes.
1325 //
1326 // UberRegSets[0] is a special non-allocatable set.
1327 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1328                             std::vector<UberRegSet*> &RegSets,
1329                             CodeGenRegBank &RegBank) {
1330
1331   const auto &Registers = RegBank.getRegisters();
1332
1333   // The Register EnumValue is one greater than its index into Registers.
1334   assert(Registers.size() == Registers.back().EnumValue &&
1335          "register enum value mismatch");
1336
1337   // For simplicitly make the SetID the same as EnumValue.
1338   IntEqClasses UberSetIDs(Registers.size()+1);
1339   std::set<unsigned> AllocatableRegs;
1340   for (auto &RegClass : RegBank.getRegClasses()) {
1341     if (!RegClass.Allocatable)
1342       continue;
1343
1344     const CodeGenRegister::Set &Regs = RegClass.getMembers();
1345     if (Regs.empty())
1346       continue;
1347
1348     unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1349     assert(USetID && "register number 0 is invalid");
1350
1351     AllocatableRegs.insert((*Regs.begin())->EnumValue);
1352     for (CodeGenRegister::Set::const_iterator I = std::next(Regs.begin()),
1353            E = Regs.end(); I != E; ++I) {
1354       AllocatableRegs.insert((*I)->EnumValue);
1355       UberSetIDs.join(USetID, (*I)->EnumValue);
1356     }
1357   }
1358   // Combine non-allocatable regs.
1359   for (const auto &Reg : Registers) {
1360     unsigned RegNum = Reg.EnumValue;
1361     if (AllocatableRegs.count(RegNum))
1362       continue;
1363
1364     UberSetIDs.join(0, RegNum);
1365   }
1366   UberSetIDs.compress();
1367
1368   // Make the first UberSet a special unallocatable set.
1369   unsigned ZeroID = UberSetIDs[0];
1370
1371   // Insert Registers into the UberSets formed by union-find.
1372   // Do not resize after this.
1373   UberSets.resize(UberSetIDs.getNumClasses());
1374   unsigned i = 0;
1375   for (const CodeGenRegister &Reg : Registers) {
1376     unsigned USetID = UberSetIDs[Reg.EnumValue];
1377     if (!USetID)
1378       USetID = ZeroID;
1379     else if (USetID == ZeroID)
1380       USetID = 0;
1381
1382     UberRegSet *USet = &UberSets[USetID];
1383     USet->Regs.insert(&Reg);
1384     RegSets[i++] = USet;
1385   }
1386 }
1387
1388 // Recompute each UberSet weight after changing unit weights.
1389 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1390                                CodeGenRegBank &RegBank) {
1391   // Skip the first unallocatable set.
1392   for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1393          E = UberSets.end(); I != E; ++I) {
1394
1395     // Initialize all unit weights in this set, and remember the max units/reg.
1396     const CodeGenRegister *Reg = nullptr;
1397     unsigned MaxWeight = 0, Weight = 0;
1398     for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1399       if (Reg != UnitI.getReg()) {
1400         if (Weight > MaxWeight)
1401           MaxWeight = Weight;
1402         Reg = UnitI.getReg();
1403         Weight = 0;
1404       }
1405       unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1406       if (!UWeight) {
1407         UWeight = 1;
1408         RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1409       }
1410       Weight += UWeight;
1411     }
1412     if (Weight > MaxWeight)
1413       MaxWeight = Weight;
1414     if (I->Weight != MaxWeight) {
1415       DEBUG(
1416         dbgs() << "UberSet " << I - UberSets.begin() << " Weight " << MaxWeight;
1417         for (auto &Unit : I->Regs)
1418           dbgs() << " " << Unit->getName();
1419         dbgs() << "\n");
1420       // Update the set weight.
1421       I->Weight = MaxWeight;
1422     }
1423
1424     // Find singular determinants.
1425     for (CodeGenRegister::Set::iterator RegI = I->Regs.begin(),
1426            RegE = I->Regs.end(); RegI != RegE; ++RegI) {
1427       if ((*RegI)->getRegUnits().size() == 1
1428           && (*RegI)->getWeight(RegBank) == I->Weight)
1429         mergeRegUnits(I->SingularDeterminants, (*RegI)->getRegUnits());
1430     }
1431   }
1432 }
1433
1434 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1435 // a register and its subregisters so that they have the same weight as their
1436 // UberSet. Self-recursion processes the subregister tree in postorder so
1437 // subregisters are normalized first.
1438 //
1439 // Side effects:
1440 // - creates new adopted register units
1441 // - causes superregisters to inherit adopted units
1442 // - increases the weight of "singular" units
1443 // - induces recomputation of UberWeights.
1444 static bool normalizeWeight(CodeGenRegister *Reg,
1445                             std::vector<UberRegSet> &UberSets,
1446                             std::vector<UberRegSet*> &RegSets,
1447                             std::set<unsigned> &NormalRegs,
1448                             CodeGenRegister::RegUnitList &NormalUnits,
1449                             CodeGenRegBank &RegBank) {
1450   bool Changed = false;
1451   if (!NormalRegs.insert(Reg->EnumValue).second)
1452     return Changed;
1453
1454   const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1455   for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1456          SRE = SRM.end(); SRI != SRE; ++SRI) {
1457     if (SRI->second == Reg)
1458       continue; // self-cycles happen
1459
1460     Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1461                                NormalRegs, NormalUnits, RegBank);
1462   }
1463   // Postorder register normalization.
1464
1465   // Inherit register units newly adopted by subregisters.
1466   if (Reg->inheritRegUnits(RegBank))
1467     computeUberWeights(UberSets, RegBank);
1468
1469   // Check if this register is too skinny for its UberRegSet.
1470   UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1471
1472   unsigned RegWeight = Reg->getWeight(RegBank);
1473   if (UberSet->Weight > RegWeight) {
1474     // A register unit's weight can be adjusted only if it is the singular unit
1475     // for this register, has not been used to normalize a subregister's set,
1476     // and has not already been used to singularly determine this UberRegSet.
1477     unsigned AdjustUnit = Reg->getRegUnits().front();
1478     if (Reg->getRegUnits().size() != 1
1479         || hasRegUnit(NormalUnits, AdjustUnit)
1480         || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1481       // We don't have an adjustable unit, so adopt a new one.
1482       AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1483       Reg->adoptRegUnit(AdjustUnit);
1484       // Adopting a unit does not immediately require recomputing set weights.
1485     }
1486     else {
1487       // Adjust the existing single unit.
1488       RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1489       // The unit may be shared among sets and registers within this set.
1490       computeUberWeights(UberSets, RegBank);
1491     }
1492     Changed = true;
1493   }
1494
1495   // Mark these units normalized so superregisters can't change their weights.
1496   mergeRegUnits(NormalUnits, Reg->getRegUnits());
1497
1498   return Changed;
1499 }
1500
1501 // Compute a weight for each register unit created during getSubRegs.
1502 //
1503 // The goal is that two registers in the same class will have the same weight,
1504 // where each register's weight is defined as sum of its units' weights.
1505 void CodeGenRegBank::computeRegUnitWeights() {
1506   std::vector<UberRegSet> UberSets;
1507   std::vector<UberRegSet*> RegSets(Registers.size());
1508   computeUberSets(UberSets, RegSets, *this);
1509   // UberSets and RegSets are now immutable.
1510
1511   computeUberWeights(UberSets, *this);
1512
1513   // Iterate over each Register, normalizing the unit weights until reaching
1514   // a fix point.
1515   unsigned NumIters = 0;
1516   for (bool Changed = true; Changed; ++NumIters) {
1517     assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1518     Changed = false;
1519     for (auto &Reg : Registers) {
1520       CodeGenRegister::RegUnitList NormalUnits;
1521       std::set<unsigned> NormalRegs;
1522       Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
1523                                  NormalUnits, *this);
1524     }
1525   }
1526 }
1527
1528 // Find a set in UniqueSets with the same elements as Set.
1529 // Return an iterator into UniqueSets.
1530 static std::vector<RegUnitSet>::const_iterator
1531 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1532                const RegUnitSet &Set) {
1533   std::vector<RegUnitSet>::const_iterator
1534     I = UniqueSets.begin(), E = UniqueSets.end();
1535   for(;I != E; ++I) {
1536     if (I->Units == Set.Units)
1537       break;
1538   }
1539   return I;
1540 }
1541
1542 // Return true if the RUSubSet is a subset of RUSuperSet.
1543 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1544                             const std::vector<unsigned> &RUSuperSet) {
1545   return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1546                        RUSubSet.begin(), RUSubSet.end());
1547 }
1548
1549 /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1550 /// but with one or two registers removed. We occasionally have registers like
1551 /// APSR and PC thrown in with the general registers. We also see many
1552 /// special-purpose register subsets, such as tail-call and Thumb
1553 /// encodings. Generating all possible overlapping sets is combinatorial and
1554 /// overkill for modeling pressure. Ideally we could fix this statically in
1555 /// tablegen by (1) having the target define register classes that only include
1556 /// the allocatable registers and marking other classes as non-allocatable and
1557 /// (2) having a way to mark special purpose classes as "don't-care" classes for
1558 /// the purpose of pressure.  However, we make an attempt to handle targets that
1559 /// are not nicely defined by merging nearly identical register unit sets
1560 /// statically. This generates smaller tables. Then, dynamically, we adjust the
1561 /// set limit by filtering the reserved registers.
1562 ///
1563 /// Merge sets only if the units have the same weight. For example, on ARM,
1564 /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1565 /// should not expand the S set to include D regs.
1566 void CodeGenRegBank::pruneUnitSets() {
1567   assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1568
1569   // Form an equivalence class of UnitSets with no significant difference.
1570   std::vector<unsigned> SuperSetIDs;
1571   for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1572        SubIdx != EndIdx; ++SubIdx) {
1573     const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1574     unsigned SuperIdx = 0;
1575     for (; SuperIdx != EndIdx; ++SuperIdx) {
1576       if (SuperIdx == SubIdx)
1577         continue;
1578
1579       unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1580       const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1581       if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1582           && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1583           && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1584           && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1585         DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1586               << "\n");
1587         break;
1588       }
1589     }
1590     if (SuperIdx == EndIdx)
1591       SuperSetIDs.push_back(SubIdx);
1592   }
1593   // Populate PrunedUnitSets with each equivalence class's superset.
1594   std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1595   for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1596     unsigned SuperIdx = SuperSetIDs[i];
1597     PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1598     PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1599   }
1600   RegUnitSets.swap(PrunedUnitSets);
1601 }
1602
1603 // Create a RegUnitSet for each RegClass that contains all units in the class
1604 // including adopted units that are necessary to model register pressure. Then
1605 // iteratively compute RegUnitSets such that the union of any two overlapping
1606 // RegUnitSets is repreresented.
1607 //
1608 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1609 // RegUnitSet that is a superset of that RegUnitClass.
1610 void CodeGenRegBank::computeRegUnitSets() {
1611   assert(RegUnitSets.empty() && "dirty RegUnitSets");
1612
1613   // Compute a unique RegUnitSet for each RegClass.
1614   auto &RegClasses = getRegClasses();
1615   for (auto &RC : RegClasses) {
1616     if (!RC.Allocatable)
1617       continue;
1618
1619     // Speculatively grow the RegUnitSets to hold the new set.
1620     RegUnitSets.resize(RegUnitSets.size() + 1);
1621     RegUnitSets.back().Name = RC.getName();
1622
1623     // Compute a sorted list of units in this class.
1624     RC.buildRegUnitSet(RegUnitSets.back().Units);
1625
1626     // Find an existing RegUnitSet.
1627     std::vector<RegUnitSet>::const_iterator SetI =
1628       findRegUnitSet(RegUnitSets, RegUnitSets.back());
1629     if (SetI != std::prev(RegUnitSets.end()))
1630       RegUnitSets.pop_back();
1631   }
1632
1633   DEBUG(dbgs() << "\nBefore pruning:\n";
1634         for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1635              USIdx < USEnd; ++USIdx) {
1636           dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1637                  << ":";
1638           for (auto &U : RegUnitSets[USIdx].Units)
1639             dbgs() << " " << RegUnits[U].Roots[0]->getName();
1640           dbgs() << "\n";
1641         });
1642
1643   // Iteratively prune unit sets.
1644   pruneUnitSets();
1645
1646   DEBUG(dbgs() << "\nBefore union:\n";
1647         for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1648              USIdx < USEnd; ++USIdx) {
1649           dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1650                  << ":";
1651           for (auto &U : RegUnitSets[USIdx].Units)
1652             dbgs() << " " << RegUnits[U].Roots[0]->getName();
1653           dbgs() << "\n";
1654         }
1655         dbgs() << "\nUnion sets:\n");
1656
1657   // Iterate over all unit sets, including new ones added by this loop.
1658   unsigned NumRegUnitSubSets = RegUnitSets.size();
1659   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1660     // In theory, this is combinatorial. In practice, it needs to be bounded
1661     // by a small number of sets for regpressure to be efficient.
1662     // If the assert is hit, we need to implement pruning.
1663     assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1664
1665     // Compare new sets with all original classes.
1666     for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1667          SearchIdx != EndIdx; ++SearchIdx) {
1668       std::set<unsigned> Intersection;
1669       std::set_intersection(RegUnitSets[Idx].Units.begin(),
1670                             RegUnitSets[Idx].Units.end(),
1671                             RegUnitSets[SearchIdx].Units.begin(),
1672                             RegUnitSets[SearchIdx].Units.end(),
1673                             std::inserter(Intersection, Intersection.begin()));
1674       if (Intersection.empty())
1675         continue;
1676
1677       // Speculatively grow the RegUnitSets to hold the new set.
1678       RegUnitSets.resize(RegUnitSets.size() + 1);
1679       RegUnitSets.back().Name =
1680         RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
1681
1682       std::set_union(RegUnitSets[Idx].Units.begin(),
1683                      RegUnitSets[Idx].Units.end(),
1684                      RegUnitSets[SearchIdx].Units.begin(),
1685                      RegUnitSets[SearchIdx].Units.end(),
1686                      std::inserter(RegUnitSets.back().Units,
1687                                    RegUnitSets.back().Units.begin()));
1688
1689       // Find an existing RegUnitSet, or add the union to the unique sets.
1690       std::vector<RegUnitSet>::const_iterator SetI =
1691         findRegUnitSet(RegUnitSets, RegUnitSets.back());
1692       if (SetI != std::prev(RegUnitSets.end()))
1693         RegUnitSets.pop_back();
1694       else {
1695         DEBUG(dbgs() << "UnitSet " << RegUnitSets.size()-1
1696               << " " << RegUnitSets.back().Name << ":";
1697               for (auto &U : RegUnitSets.back().Units)
1698                 dbgs() << " " << RegUnits[U].Roots[0]->getName();
1699               dbgs() << "\n";);
1700       }
1701     }
1702   }
1703
1704   // Iteratively prune unit sets after inferring supersets.
1705   pruneUnitSets();
1706
1707   DEBUG(dbgs() << "\n";
1708         for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1709              USIdx < USEnd; ++USIdx) {
1710           dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name
1711                  << ":";
1712           for (auto &U : RegUnitSets[USIdx].Units)
1713             dbgs() << " " << RegUnits[U].Roots[0]->getName();
1714           dbgs() << "\n";
1715         });
1716
1717   // For each register class, list the UnitSets that are supersets.
1718   RegClassUnitSets.resize(RegClasses.size());
1719   int RCIdx = -1;
1720   for (auto &RC : RegClasses) {
1721     ++RCIdx;
1722     if (!RC.Allocatable)
1723       continue;
1724
1725     // Recompute the sorted list of units in this class.
1726     std::vector<unsigned> RCRegUnits;
1727     RC.buildRegUnitSet(RCRegUnits);
1728
1729     // Don't increase pressure for unallocatable regclasses.
1730     if (RCRegUnits.empty())
1731       continue;
1732
1733     DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";
1734           for (auto &U : RCRegUnits)
1735             dbgs() << RegUnits[U].getRoots()[0]->getName() << " ";
1736           dbgs() << "\n  UnitSetIDs:");
1737
1738     // Find all supersets.
1739     for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
1740          USIdx != USEnd; ++USIdx) {
1741       if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
1742         DEBUG(dbgs() << " " << USIdx);
1743         RegClassUnitSets[RCIdx].push_back(USIdx);
1744       }
1745     }
1746     DEBUG(dbgs() << "\n");
1747     assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass");
1748   }
1749
1750   // For each register unit, ensure that we have the list of UnitSets that
1751   // contain the unit. Normally, this matches an existing list of UnitSets for a
1752   // register class. If not, we create a new entry in RegClassUnitSets as a
1753   // "fake" register class.
1754   for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
1755        UnitIdx < UnitEnd; ++UnitIdx) {
1756     std::vector<unsigned> RUSets;
1757     for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
1758       RegUnitSet &RUSet = RegUnitSets[i];
1759       if (std::find(RUSet.Units.begin(), RUSet.Units.end(), UnitIdx)
1760           == RUSet.Units.end())
1761         continue;
1762       RUSets.push_back(i);
1763     }
1764     unsigned RCUnitSetsIdx = 0;
1765     for (unsigned e = RegClassUnitSets.size();
1766          RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
1767       if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
1768         break;
1769       }
1770     }
1771     RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
1772     if (RCUnitSetsIdx == RegClassUnitSets.size()) {
1773       // Create a new list of UnitSets as a "fake" register class.
1774       RegClassUnitSets.resize(RCUnitSetsIdx + 1);
1775       RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
1776     }
1777   }
1778 }
1779
1780 void CodeGenRegBank::computeRegUnitLaneMasks() {
1781   for (auto &Register : Registers) {
1782     // Create an initial lane mask for all register units.
1783     const auto &RegUnits = Register.getRegUnits();
1784     CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(RegUnits.size(), 0);
1785     // Iterate through SubRegisters.
1786     typedef CodeGenRegister::SubRegMap SubRegMap;
1787     const SubRegMap &SubRegs = Register.getSubRegs();
1788     for (SubRegMap::const_iterator S = SubRegs.begin(),
1789          SE = SubRegs.end(); S != SE; ++S) {
1790       CodeGenRegister *SubReg = S->second;
1791       // Ignore non-leaf subregisters, their lane masks are fully covered by
1792       // the leaf subregisters anyway.
1793       if (SubReg->getSubRegs().size() != 0)
1794         continue;
1795       CodeGenSubRegIndex *SubRegIndex = S->first;
1796       const CodeGenRegister *SubRegister = S->second;
1797       unsigned LaneMask = SubRegIndex->LaneMask;
1798       // Distribute LaneMask to Register Units touched.
1799       for (const auto &SUI : SubRegister->getRegUnits()) {
1800         bool Found = false;
1801         for (size_t u = 0, ue = RegUnits.size(); u < ue; ++u) {
1802           if (SUI == RegUnits[u]) {
1803             RegUnitLaneMasks[u] |= LaneMask;
1804             assert(!Found);
1805             Found = true;
1806           }
1807         }
1808         assert(Found);
1809       }
1810     }
1811     Register.setRegUnitLaneMasks(RegUnitLaneMasks);
1812   }
1813 }
1814
1815 void CodeGenRegBank::computeDerivedInfo() {
1816   computeComposites();
1817   computeSubRegLaneMasks();
1818
1819   // Compute a weight for each register unit created during getSubRegs.
1820   // This may create adopted register units (with unit # >= NumNativeRegUnits).
1821   computeRegUnitWeights();
1822
1823   // Compute a unique set of RegUnitSets. One for each RegClass and inferred
1824   // supersets for the union of overlapping sets.
1825   computeRegUnitSets();
1826
1827   computeRegUnitLaneMasks();
1828
1829   // Get the weight of each set.
1830   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1831     RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
1832
1833   // Find the order of each set.
1834   RegUnitSetOrder.reserve(RegUnitSets.size());
1835   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
1836     RegUnitSetOrder.push_back(Idx);
1837
1838   std::stable_sort(RegUnitSetOrder.begin(), RegUnitSetOrder.end(),
1839                    [this](unsigned ID1, unsigned ID2) {
1840     return getRegPressureSet(ID1).Units.size() <
1841            getRegPressureSet(ID2).Units.size();
1842   });
1843   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1844     RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
1845   }
1846 }
1847
1848 //
1849 // Synthesize missing register class intersections.
1850 //
1851 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
1852 // returns a maximal register class for all X.
1853 //
1854 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
1855   assert(!RegClasses.empty());
1856   // Stash the iterator to the last element so that this loop doesn't visit
1857   // elements added by the getOrCreateSubClass call within it.
1858   for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
1859        I != std::next(E); ++I) {
1860     CodeGenRegisterClass *RC1 = RC;
1861     CodeGenRegisterClass *RC2 = &*I;
1862     if (RC1 == RC2)
1863       continue;
1864
1865     // Compute the set intersection of RC1 and RC2.
1866     const CodeGenRegister::Set &Memb1 = RC1->getMembers();
1867     const CodeGenRegister::Set &Memb2 = RC2->getMembers();
1868     CodeGenRegister::Set Intersection;
1869     std::set_intersection(Memb1.begin(), Memb1.end(),
1870                           Memb2.begin(), Memb2.end(),
1871                           std::inserter(Intersection, Intersection.begin()),
1872                           CodeGenRegister::Less());
1873
1874     // Skip disjoint class pairs.
1875     if (Intersection.empty())
1876       continue;
1877
1878     // If RC1 and RC2 have different spill sizes or alignments, use the
1879     // larger size for sub-classing.  If they are equal, prefer RC1.
1880     if (RC2->SpillSize > RC1->SpillSize ||
1881         (RC2->SpillSize == RC1->SpillSize &&
1882          RC2->SpillAlignment > RC1->SpillAlignment))
1883       std::swap(RC1, RC2);
1884
1885     getOrCreateSubClass(RC1, &Intersection,
1886                         RC1->getName() + "_and_" + RC2->getName());
1887   }
1888 }
1889
1890 //
1891 // Synthesize missing sub-classes for getSubClassWithSubReg().
1892 //
1893 // Make sure that the set of registers in RC with a given SubIdx sub-register
1894 // form a register class.  Update RC->SubClassWithSubReg.
1895 //
1896 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
1897   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
1898   typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Set,
1899                    CodeGenSubRegIndex::Less> SubReg2SetMap;
1900
1901   // Compute the set of registers supporting each SubRegIndex.
1902   SubReg2SetMap SRSets;
1903   for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1904        RE = RC->getMembers().end(); RI != RE; ++RI) {
1905     const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs();
1906     for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
1907          E = SRM.end(); I != E; ++I)
1908       SRSets[I->first].insert(*RI);
1909   }
1910
1911   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
1912   // numerical order to visit synthetic indices last.
1913   for (const auto &SubIdx : SubRegIndices) {
1914     SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
1915     // Unsupported SubRegIndex. Skip it.
1916     if (I == SRSets.end())
1917       continue;
1918     // In most cases, all RC registers support the SubRegIndex.
1919     if (I->second.size() == RC->getMembers().size()) {
1920       RC->setSubClassWithSubReg(&SubIdx, RC);
1921       continue;
1922     }
1923     // This is a real subset.  See if we have a matching class.
1924     CodeGenRegisterClass *SubRC =
1925       getOrCreateSubClass(RC, &I->second,
1926                           RC->getName() + "_with_" + I->first->getName());
1927     RC->setSubClassWithSubReg(&SubIdx, SubRC);
1928   }
1929 }
1930
1931 //
1932 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
1933 //
1934 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
1935 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
1936 //
1937
1938 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
1939                                                 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
1940   SmallVector<std::pair<const CodeGenRegister*,
1941                         const CodeGenRegister*>, 16> SSPairs;
1942   BitVector TopoSigs(getNumTopoSigs());
1943
1944   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
1945   for (auto &SubIdx : SubRegIndices) {
1946     // Skip indexes that aren't fully supported by RC's registers. This was
1947     // computed by inferSubClassWithSubReg() above which should have been
1948     // called first.
1949     if (RC->getSubClassWithSubReg(&SubIdx) != RC)
1950       continue;
1951
1952     // Build list of (Super, Sub) pairs for this SubIdx.
1953     SSPairs.clear();
1954     TopoSigs.reset();
1955     for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(),
1956          RE = RC->getMembers().end(); RI != RE; ++RI) {
1957       const CodeGenRegister *Super = *RI;
1958       const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
1959       assert(Sub && "Missing sub-register");
1960       SSPairs.push_back(std::make_pair(Super, Sub));
1961       TopoSigs.set(Sub->getTopoSig());
1962     }
1963
1964     // Iterate over sub-register class candidates.  Ignore classes created by
1965     // this loop. They will never be useful.
1966     // Store an iterator to the last element (not end) so that this loop doesn't
1967     // visit newly inserted elements.
1968     assert(!RegClasses.empty());
1969     for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
1970          I != std::next(E); ++I) {
1971       CodeGenRegisterClass &SubRC = *I;
1972       // Topological shortcut: SubRC members have the wrong shape.
1973       if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
1974         continue;
1975       // Compute the subset of RC that maps into SubRC.
1976       CodeGenRegister::Set SubSet;
1977       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
1978         if (SubRC.contains(SSPairs[i].second))
1979           SubSet.insert(SSPairs[i].first);
1980       if (SubSet.empty())
1981         continue;
1982       // RC injects completely into SubRC.
1983       if (SubSet.size() == SSPairs.size()) {
1984         SubRC.addSuperRegClass(&SubIdx, RC);
1985         continue;
1986       }
1987       // Only a subset of RC maps into SubRC. Make sure it is represented by a
1988       // class.
1989       getOrCreateSubClass(RC, &SubSet, RC->getName() + "_with_" +
1990                                            SubIdx.getName() + "_in_" +
1991                                            SubRC.getName());
1992     }
1993   }
1994 }
1995
1996
1997 //
1998 // Infer missing register classes.
1999 //
2000 void CodeGenRegBank::computeInferredRegisterClasses() {
2001   assert(!RegClasses.empty());
2002   // When this function is called, the register classes have not been sorted
2003   // and assigned EnumValues yet.  That means getSubClasses(),
2004   // getSuperClasses(), and hasSubClass() functions are defunct.
2005
2006   // Use one-before-the-end so it doesn't move forward when new elements are
2007   // added.
2008   auto FirstNewRC = std::prev(RegClasses.end());
2009
2010   // Visit all register classes, including the ones being added by the loop.
2011   // Watch out for iterator invalidation here.
2012   for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
2013     CodeGenRegisterClass *RC = &*I;
2014
2015     // Synthesize answers for getSubClassWithSubReg().
2016     inferSubClassWithSubReg(RC);
2017
2018     // Synthesize answers for getCommonSubClass().
2019     inferCommonSubClass(RC);
2020
2021     // Synthesize answers for getMatchingSuperRegClass().
2022     inferMatchingSuperRegClass(RC);
2023
2024     // New register classes are created while this loop is running, and we need
2025     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
2026     // to match old super-register classes with sub-register classes created
2027     // after inferMatchingSuperRegClass was called.  At this point,
2028     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2029     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
2030     if (I == FirstNewRC) {
2031       auto NextNewRC = std::prev(RegClasses.end());
2032       for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
2033            ++I2)
2034         inferMatchingSuperRegClass(&*I2, E2);
2035       FirstNewRC = NextNewRC;
2036     }
2037   }
2038 }
2039
2040 /// getRegisterClassForRegister - Find the register class that contains the
2041 /// specified physical register.  If the register is not in a register class,
2042 /// return null. If the register is in multiple classes, and the classes have a
2043 /// superset-subset relationship and the same set of types, return the
2044 /// superclass.  Otherwise return null.
2045 const CodeGenRegisterClass*
2046 CodeGenRegBank::getRegClassForRegister(Record *R) {
2047   const CodeGenRegister *Reg = getReg(R);
2048   const CodeGenRegisterClass *FoundRC = nullptr;
2049   for (const auto &RC : getRegClasses()) {
2050     if (!RC.contains(Reg))
2051       continue;
2052
2053     // If this is the first class that contains the register,
2054     // make a note of it and go on to the next class.
2055     if (!FoundRC) {
2056       FoundRC = &RC;
2057       continue;
2058     }
2059
2060     // If a register's classes have different types, return null.
2061     if (RC.getValueTypes() != FoundRC->getValueTypes())
2062       return nullptr;
2063
2064     // Check to see if the previously found class that contains
2065     // the register is a subclass of the current class. If so,
2066     // prefer the superclass.
2067     if (RC.hasSubClass(FoundRC)) {
2068       FoundRC = &RC;
2069       continue;
2070     }
2071
2072     // Check to see if the previously found class that contains
2073     // the register is a superclass of the current class. If so,
2074     // prefer the superclass.
2075     if (FoundRC->hasSubClass(&RC))
2076       continue;
2077
2078     // Multiple classes, and neither is a superclass of the other.
2079     // Return null.
2080     return nullptr;
2081   }
2082   return FoundRC;
2083 }
2084
2085 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
2086   SetVector<const CodeGenRegister*> Set;
2087
2088   // First add Regs with all sub-registers.
2089   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2090     CodeGenRegister *Reg = getReg(Regs[i]);
2091     if (Set.insert(Reg))
2092       // Reg is new, add all sub-registers.
2093       // The pre-ordering is not important here.
2094       Reg->addSubRegsPreOrder(Set, *this);
2095   }
2096
2097   // Second, find all super-registers that are completely covered by the set.
2098   for (unsigned i = 0; i != Set.size(); ++i) {
2099     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
2100     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
2101       const CodeGenRegister *Super = SR[j];
2102       if (!Super->CoveredBySubRegs || Set.count(Super))
2103         continue;
2104       // This new super-register is covered by its sub-registers.
2105       bool AllSubsInSet = true;
2106       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2107       for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2108              E = SRM.end(); I != E; ++I)
2109         if (!Set.count(I->second)) {
2110           AllSubsInSet = false;
2111           break;
2112         }
2113       // All sub-registers in Set, add Super as well.
2114       // We will visit Super later to recheck its super-registers.
2115       if (AllSubsInSet)
2116         Set.insert(Super);
2117     }
2118   }
2119
2120   // Convert to BitVector.
2121   BitVector BV(Registers.size() + 1);
2122   for (unsigned i = 0, e = Set.size(); i != e; ++i)
2123     BV.set(Set[i]->EnumValue);
2124   return BV;
2125 }