1 //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines structures to encapsulate information gleaned from the
10 // target register and register class definitions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenRegisters.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/IntEqClasses.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/TableGen/Error.h"
29 #include "llvm/TableGen/Record.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <cstdint>
33 #include <iterator>
34 #include <map>
35 #include <queue>
36 #include <set>
37 #include <string>
38 #include <tuple>
39 #include <utility>
40 #include <vector>
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "regalloc-emitter"
45 
46 //===----------------------------------------------------------------------===//
47 //                             CodeGenSubRegIndex
48 //===----------------------------------------------------------------------===//
49 
50 CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
51   : TheDef(R), EnumValue(Enum), AllSuperRegsCovered(true), Artificial(true) {
52   Name = std::string(R->getName());
53   if (R->getValue("Namespace"))
54     Namespace = std::string(R->getValueAsString("Namespace"));
55   Size = R->getValueAsInt("Size");
56   Offset = R->getValueAsInt("Offset");
57 }
58 
59 CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
60                                        unsigned Enum)
61     : TheDef(nullptr), Name(std::string(N)), Namespace(std::string(Nspace)),
62       Size(-1), Offset(-1), EnumValue(Enum), AllSuperRegsCovered(true),
63       Artificial(true) {}
64 
65 std::string CodeGenSubRegIndex::getQualifiedName() const {
66   std::string N = getNamespace();
67   if (!N.empty())
68     N += "::";
69   N += getName();
70   return N;
71 }
72 
73 void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
74   if (!TheDef)
75     return;
76 
77   std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
78   if (!Comps.empty()) {
79     if (Comps.size() != 2)
80       PrintFatalError(TheDef->getLoc(),
81                       "ComposedOf must have exactly two entries");
82     CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
83     CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
84     CodeGenSubRegIndex *X = A->addComposite(B, this);
85     if (X)
86       PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
87   }
88 
89   std::vector<Record*> Parts =
90     TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
91   if (!Parts.empty()) {
92     if (Parts.size() < 2)
93       PrintFatalError(TheDef->getLoc(),
94                       "CoveredBySubRegs must have two or more entries");
95     SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
96     for (Record *Part : Parts)
97       IdxParts.push_back(RegBank.getSubRegIdx(Part));
98     setConcatenationOf(IdxParts);
99   }
100 }
101 
102 LaneBitmask CodeGenSubRegIndex::computeLaneMask() const {
103   // Already computed?
104   if (LaneMask.any())
105     return LaneMask;
106 
107   // Recursion guard, shouldn't be required.
108   LaneMask = LaneBitmask::getAll();
109 
110   // The lane mask is simply the union of all sub-indices.
111   LaneBitmask M;
112   for (const auto &C : Composed)
113     M |= C.second->computeLaneMask();
114   assert(M.any() && "Missing lane mask, sub-register cycle?");
115   LaneMask = M;
116   return LaneMask;
117 }
118 
119 void CodeGenSubRegIndex::setConcatenationOf(
120     ArrayRef<CodeGenSubRegIndex*> Parts) {
121   if (ConcatenationOf.empty())
122     ConcatenationOf.assign(Parts.begin(), Parts.end());
123   else
124     assert(std::equal(Parts.begin(), Parts.end(),
125                       ConcatenationOf.begin()) && "parts consistent");
126 }
127 
128 void CodeGenSubRegIndex::computeConcatTransitiveClosure() {
129   for (SmallVectorImpl<CodeGenSubRegIndex*>::iterator
130        I = ConcatenationOf.begin(); I != ConcatenationOf.end(); /*empty*/) {
131     CodeGenSubRegIndex *SubIdx = *I;
132     SubIdx->computeConcatTransitiveClosure();
133 #ifndef NDEBUG
134     for (CodeGenSubRegIndex *SRI : SubIdx->ConcatenationOf)
135       assert(SRI->ConcatenationOf.empty() && "No transitive closure?");
136 #endif
137 
138     if (SubIdx->ConcatenationOf.empty()) {
139       ++I;
140     } else {
141       I = ConcatenationOf.erase(I);
142       I = ConcatenationOf.insert(I, SubIdx->ConcatenationOf.begin(),
143                                  SubIdx->ConcatenationOf.end());
144       I += SubIdx->ConcatenationOf.size();
145     }
146   }
147 }
148 
149 //===----------------------------------------------------------------------===//
150 //                              CodeGenRegister
151 //===----------------------------------------------------------------------===//
152 
153 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
154     : TheDef(R), EnumValue(Enum),
155       CostPerUse(R->getValueAsListOfInts("CostPerUse")),
156       CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
157       HasDisjunctSubRegs(false), SubRegsComplete(false),
158       SuperRegsComplete(false), TopoSig(~0u) {
159   Artificial = R->getValueAsBit("isArtificial");
160 }
161 
162 void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
163   std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
164   std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
165 
166   if (SRIs.size() != SRs.size())
167     PrintFatalError(TheDef->getLoc(),
168                     "SubRegs and SubRegIndices must have the same size");
169 
170   for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
171     ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
172     ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
173   }
174 
175   // Also compute leading super-registers. Each register has a list of
176   // covered-by-subregs super-registers where it appears as the first explicit
177   // sub-register.
178   //
179   // This is used by computeSecondarySubRegs() to find candidates.
180   if (CoveredBySubRegs && !ExplicitSubRegs.empty())
181     ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
182 
183   // Add ad hoc alias links. This is a symmetric relationship between two
184   // registers, so build a symmetric graph by adding links in both ends.
185   std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
186   for (Record *Alias : Aliases) {
187     CodeGenRegister *Reg = RegBank.getReg(Alias);
188     ExplicitAliases.push_back(Reg);
189     Reg->ExplicitAliases.push_back(this);
190   }
191 }
192 
193 StringRef CodeGenRegister::getName() const {
194   assert(TheDef && "no def");
195   return TheDef->getName();
196 }
197 
198 namespace {
199 
200 // Iterate over all register units in a set of registers.
201 class RegUnitIterator {
202   CodeGenRegister::Vec::const_iterator RegI, RegE;
203   CodeGenRegister::RegUnitList::iterator UnitI, UnitE;
204   static CodeGenRegister::RegUnitList Sentinel;
205 
206 public:
207   RegUnitIterator(const CodeGenRegister::Vec &Regs):
208     RegI(Regs.begin()), RegE(Regs.end()) {
209 
210     if (RegI == RegE) {
211       UnitI = Sentinel.end();
212       UnitE = Sentinel.end();
213     } else {
214       UnitI = (*RegI)->getRegUnits().begin();
215       UnitE = (*RegI)->getRegUnits().end();
216       advance();
217     }
218   }
219 
220   bool isValid() const { return UnitI != UnitE; }
221 
222   unsigned operator* () const { assert(isValid()); return *UnitI; }
223 
224   const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
225 
226   /// Preincrement.  Move to the next unit.
227   void operator++() {
228     assert(isValid() && "Cannot advance beyond the last operand");
229     ++UnitI;
230     advance();
231   }
232 
233 protected:
234   void advance() {
235     while (UnitI == UnitE) {
236       if (++RegI == RegE)
237         break;
238       UnitI = (*RegI)->getRegUnits().begin();
239       UnitE = (*RegI)->getRegUnits().end();
240     }
241   }
242 };
243 
244 CodeGenRegister::RegUnitList RegUnitIterator::Sentinel;
245 
246 } // end anonymous namespace
247 
248 // Return true of this unit appears in RegUnits.
249 static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
250   return RegUnits.test(Unit);
251 }
252 
253 // Inherit register units from subregisters.
254 // Return true if the RegUnits changed.
255 bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
256   bool changed = false;
257   for (const auto &SubReg : SubRegs) {
258     CodeGenRegister *SR = SubReg.second;
259     // Merge the subregister's units into this register's RegUnits.
260     changed |= (RegUnits |= SR->RegUnits);
261   }
262 
263   return changed;
264 }
265 
266 const CodeGenRegister::SubRegMap &
267 CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
268   // Only compute this map once.
269   if (SubRegsComplete)
270     return SubRegs;
271   SubRegsComplete = true;
272 
273   HasDisjunctSubRegs = ExplicitSubRegs.size() > 1;
274 
275   // First insert the explicit subregs and make sure they are fully indexed.
276   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
277     CodeGenRegister *SR = ExplicitSubRegs[i];
278     CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
279     if (!SR->Artificial)
280       Idx->Artificial = false;
281     if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
282       PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
283                       " appears twice in Register " + getName());
284     // Map explicit sub-registers first, so the names take precedence.
285     // The inherited sub-registers are mapped below.
286     SubReg2Idx.insert(std::make_pair(SR, Idx));
287   }
288 
289   // Keep track of inherited subregs and how they can be reached.
290   SmallPtrSet<CodeGenRegister*, 8> Orphans;
291 
292   // Clone inherited subregs and place duplicate entries in Orphans.
293   // Here the order is important - earlier subregs take precedence.
294   for (CodeGenRegister *ESR : ExplicitSubRegs) {
295     const SubRegMap &Map = ESR->computeSubRegs(RegBank);
296     HasDisjunctSubRegs |= ESR->HasDisjunctSubRegs;
297 
298     for (const auto &SR : Map) {
299       if (!SubRegs.insert(SR).second)
300         Orphans.insert(SR.second);
301     }
302   }
303 
304   // Expand any composed subreg indices.
305   // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
306   // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
307   // expanded subreg indices recursively.
308   SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
309   for (unsigned i = 0; i != Indices.size(); ++i) {
310     CodeGenSubRegIndex *Idx = Indices[i];
311     const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
312     CodeGenRegister *SR = SubRegs[Idx];
313     const SubRegMap &Map = SR->computeSubRegs(RegBank);
314 
315     // Look at the possible compositions of Idx.
316     // They may not all be supported by SR.
317     for (auto Comp : Comps) {
318       SubRegMap::const_iterator SRI = Map.find(Comp.first);
319       if (SRI == Map.end())
320         continue; // Idx + I->first doesn't exist in SR.
321       // Add I->second as a name for the subreg SRI->second, assuming it is
322       // orphaned, and the name isn't already used for something else.
323       if (SubRegs.count(Comp.second) || !Orphans.erase(SRI->second))
324         continue;
325       // We found a new name for the orphaned sub-register.
326       SubRegs.insert(std::make_pair(Comp.second, SRI->second));
327       Indices.push_back(Comp.second);
328     }
329   }
330 
331   // Now Orphans contains the inherited subregisters without a direct index.
332   // Create inferred indexes for all missing entries.
333   // Work backwards in the Indices vector in order to compose subregs bottom-up.
334   // Consider this subreg sequence:
335   //
336   //   qsub_1 -> dsub_0 -> ssub_0
337   //
338   // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
339   // can be reached in two different ways:
340   //
341   //   qsub_1 -> ssub_0
342   //   dsub_2 -> ssub_0
343   //
344   // We pick the latter composition because another register may have [dsub_0,
345   // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg.  The
346   // dsub_2 -> ssub_0 composition can be shared.
347   while (!Indices.empty() && !Orphans.empty()) {
348     CodeGenSubRegIndex *Idx = Indices.pop_back_val();
349     CodeGenRegister *SR = SubRegs[Idx];
350     const SubRegMap &Map = SR->computeSubRegs(RegBank);
351     for (const auto &SubReg : Map)
352       if (Orphans.erase(SubReg.second))
353         SubRegs[RegBank.getCompositeSubRegIndex(Idx, SubReg.first)] = SubReg.second;
354   }
355 
356   // Compute the inverse SubReg -> Idx map.
357   for (const auto &SubReg : SubRegs) {
358     if (SubReg.second == this) {
359       ArrayRef<SMLoc> Loc;
360       if (TheDef)
361         Loc = TheDef->getLoc();
362       PrintFatalError(Loc, "Register " + getName() +
363                       " has itself as a sub-register");
364     }
365 
366     // Compute AllSuperRegsCovered.
367     if (!CoveredBySubRegs)
368       SubReg.first->AllSuperRegsCovered = false;
369 
370     // Ensure that every sub-register has a unique name.
371     DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
372       SubReg2Idx.insert(std::make_pair(SubReg.second, SubReg.first)).first;
373     if (Ins->second == SubReg.first)
374       continue;
375     // Trouble: Two different names for SubReg.second.
376     ArrayRef<SMLoc> Loc;
377     if (TheDef)
378       Loc = TheDef->getLoc();
379     PrintFatalError(Loc, "Sub-register can't have two names: " +
380                   SubReg.second->getName() + " available as " +
381                   SubReg.first->getName() + " and " + Ins->second->getName());
382   }
383 
384   // Derive possible names for sub-register concatenations from any explicit
385   // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
386   // that getConcatSubRegIndex() won't invent any concatenated indices that the
387   // user already specified.
388   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
389     CodeGenRegister *SR = ExplicitSubRegs[i];
390     if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1 ||
391         SR->Artificial)
392       continue;
393 
394     // SR is composed of multiple sub-regs. Find their names in this register.
395     SmallVector<CodeGenSubRegIndex*, 8> Parts;
396     for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j) {
397       CodeGenSubRegIndex &I = *SR->ExplicitSubRegIndices[j];
398       if (!I.Artificial)
399         Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
400     }
401 
402     // Offer this as an existing spelling for the concatenation of Parts.
403     CodeGenSubRegIndex &Idx = *ExplicitSubRegIndices[i];
404     Idx.setConcatenationOf(Parts);
405   }
406 
407   // Initialize RegUnitList. Because getSubRegs is called recursively, this
408   // processes the register hierarchy in postorder.
409   //
410   // Inherit all sub-register units. It is good enough to look at the explicit
411   // sub-registers, the other registers won't contribute any more units.
412   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
413     CodeGenRegister *SR = ExplicitSubRegs[i];
414     RegUnits |= SR->RegUnits;
415   }
416 
417   // Absent any ad hoc aliasing, we create one register unit per leaf register.
418   // These units correspond to the maximal cliques in the register overlap
419   // graph which is optimal.
420   //
421   // When there is ad hoc aliasing, we simply create one unit per edge in the
422   // undirected ad hoc aliasing graph. Technically, we could do better by
423   // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
424   // are extremely rare anyway (I've never seen one), so we don't bother with
425   // the added complexity.
426   for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
427     CodeGenRegister *AR = ExplicitAliases[i];
428     // Only visit each edge once.
429     if (AR->SubRegsComplete)
430       continue;
431     // Create a RegUnit representing this alias edge, and add it to both
432     // registers.
433     unsigned Unit = RegBank.newRegUnit(this, AR);
434     RegUnits.set(Unit);
435     AR->RegUnits.set(Unit);
436   }
437 
438   // Finally, create units for leaf registers without ad hoc aliases. Note that
439   // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
440   // necessary. This means the aliasing leaf registers can share a single unit.
441   if (RegUnits.empty())
442     RegUnits.set(RegBank.newRegUnit(this));
443 
444   // We have now computed the native register units. More may be adopted later
445   // for balancing purposes.
446   NativeRegUnits = RegUnits;
447 
448   return SubRegs;
449 }
450 
451 // In a register that is covered by its sub-registers, try to find redundant
452 // sub-registers. For example:
453 //
454 //   QQ0 = {Q0, Q1}
455 //   Q0 = {D0, D1}
456 //   Q1 = {D2, D3}
457 //
458 // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
459 // the register definition.
460 //
461 // The explicitly specified registers form a tree. This function discovers
462 // sub-register relationships that would force a DAG.
463 //
464 void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
465   SmallVector<SubRegMap::value_type, 8> NewSubRegs;
466 
467   std::queue<std::pair<CodeGenSubRegIndex*,CodeGenRegister*>> SubRegQueue;
468   for (std::pair<CodeGenSubRegIndex*,CodeGenRegister*> P : SubRegs)
469     SubRegQueue.push(P);
470 
471   // Look at the leading super-registers of each sub-register. Those are the
472   // candidates for new sub-registers, assuming they are fully contained in
473   // this register.
474   while (!SubRegQueue.empty()) {
475     CodeGenSubRegIndex *SubRegIdx;
476     const CodeGenRegister *SubReg;
477     std::tie(SubRegIdx, SubReg) = SubRegQueue.front();
478     SubRegQueue.pop();
479 
480     const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
481     for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
482       CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
483       // Already got this sub-register?
484       if (Cand == this || getSubRegIndex(Cand))
485         continue;
486       // Check if each component of Cand is already a sub-register.
487       assert(!Cand->ExplicitSubRegs.empty() &&
488              "Super-register has no sub-registers");
489       if (Cand->ExplicitSubRegs.size() == 1)
490         continue;
491       SmallVector<CodeGenSubRegIndex*, 8> Parts;
492       // We know that the first component is (SubRegIdx,SubReg). However we
493       // may still need to split it into smaller subregister parts.
494       assert(Cand->ExplicitSubRegs[0] == SubReg && "LeadingSuperRegs correct");
495       assert(getSubRegIndex(SubReg) == SubRegIdx && "LeadingSuperRegs correct");
496       for (CodeGenRegister *SubReg : Cand->ExplicitSubRegs) {
497         if (CodeGenSubRegIndex *SubRegIdx = getSubRegIndex(SubReg)) {
498           if (SubRegIdx->ConcatenationOf.empty())
499             Parts.push_back(SubRegIdx);
500           else
501             append_range(Parts, SubRegIdx->ConcatenationOf);
502         } else {
503           // Sub-register doesn't exist.
504           Parts.clear();
505           break;
506         }
507       }
508       // There is nothing to do if some Cand sub-register is not part of this
509       // register.
510       if (Parts.empty())
511         continue;
512 
513       // Each part of Cand is a sub-register of this. Make the full Cand also
514       // a sub-register with a concatenated sub-register index.
515       CodeGenSubRegIndex *Concat = RegBank.getConcatSubRegIndex(Parts);
516       std::pair<CodeGenSubRegIndex*,CodeGenRegister*> NewSubReg =
517           std::make_pair(Concat, Cand);
518 
519       if (!SubRegs.insert(NewSubReg).second)
520         continue;
521 
522       // We inserted a new subregister.
523       NewSubRegs.push_back(NewSubReg);
524       SubRegQueue.push(NewSubReg);
525       SubReg2Idx.insert(std::make_pair(Cand, Concat));
526     }
527   }
528 
529   // Create sub-register index composition maps for the synthesized indices.
530   for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
531     CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
532     CodeGenRegister *NewSubReg = NewSubRegs[i].second;
533     for (auto SubReg : NewSubReg->SubRegs) {
534       CodeGenSubRegIndex *SubIdx = getSubRegIndex(SubReg.second);
535       if (!SubIdx)
536         PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
537                                               SubReg.second->getName() +
538                                               " in " + getName());
539       NewIdx->addComposite(SubReg.first, SubIdx);
540     }
541   }
542 }
543 
544 void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
545   // Only visit each register once.
546   if (SuperRegsComplete)
547     return;
548   SuperRegsComplete = true;
549 
550   // Make sure all sub-registers have been visited first, so the super-reg
551   // lists will be topologically ordered.
552   for (auto SubReg : SubRegs)
553     SubReg.second->computeSuperRegs(RegBank);
554 
555   // Now add this as a super-register on all sub-registers.
556   // Also compute the TopoSigId in post-order.
557   TopoSigId Id;
558   for (auto SubReg : SubRegs) {
559     // Topological signature computed from SubIdx, TopoId(SubReg).
560     // Loops and idempotent indices have TopoSig = ~0u.
561     Id.push_back(SubReg.first->EnumValue);
562     Id.push_back(SubReg.second->TopoSig);
563 
564     // Don't add duplicate entries.
565     if (!SubReg.second->SuperRegs.empty() &&
566         SubReg.second->SuperRegs.back() == this)
567       continue;
568     SubReg.second->SuperRegs.push_back(this);
569   }
570   TopoSig = RegBank.getTopoSig(Id);
571 }
572 
573 void
574 CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
575                                     CodeGenRegBank &RegBank) const {
576   assert(SubRegsComplete && "Must precompute sub-registers");
577   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
578     CodeGenRegister *SR = ExplicitSubRegs[i];
579     if (OSet.insert(SR))
580       SR->addSubRegsPreOrder(OSet, RegBank);
581   }
582   // Add any secondary sub-registers that weren't part of the explicit tree.
583   for (auto SubReg : SubRegs)
584     OSet.insert(SubReg.second);
585 }
586 
587 // Get the sum of this register's unit weights.
588 unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
589   unsigned Weight = 0;
590   for (unsigned RegUnit : RegUnits) {
591     Weight += RegBank.getRegUnit(RegUnit).Weight;
592   }
593   return Weight;
594 }
595 
596 //===----------------------------------------------------------------------===//
597 //                               RegisterTuples
598 //===----------------------------------------------------------------------===//
599 
600 // A RegisterTuples def is used to generate pseudo-registers from lists of
601 // sub-registers. We provide a SetTheory expander class that returns the new
602 // registers.
603 namespace {
604 
605 struct TupleExpander : SetTheory::Expander {
606   // Reference to SynthDefs in the containing CodeGenRegBank, to keep track of
607   // the synthesized definitions for their lifetime.
608   std::vector<std::unique_ptr<Record>> &SynthDefs;
609 
610   TupleExpander(std::vector<std::unique_ptr<Record>> &SynthDefs)
611       : SynthDefs(SynthDefs) {}
612 
613   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
614     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
615     unsigned Dim = Indices.size();
616     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
617     if (Dim != SubRegs->size())
618       PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
619     if (Dim < 2)
620       PrintFatalError(Def->getLoc(),
621                       "Tuples must have at least 2 sub-registers");
622 
623     // Evaluate the sub-register lists to be zipped.
624     unsigned Length = ~0u;
625     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
626     for (unsigned i = 0; i != Dim; ++i) {
627       ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
628       Length = std::min(Length, unsigned(Lists[i].size()));
629     }
630 
631     if (Length == 0)
632       return;
633 
634     // Precompute some types.
635     Record *RegisterCl = Def->getRecords().getClass("Register");
636     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
637     std::vector<StringRef> RegNames =
638       Def->getValueAsListOfStrings("RegAsmNames");
639 
640     // Zip them up.
641     for (unsigned n = 0; n != Length; ++n) {
642       std::string Name;
643       Record *Proto = Lists[0][n];
644       std::vector<Init*> Tuple;
645       for (unsigned i = 0; i != Dim; ++i) {
646         Record *Reg = Lists[i][n];
647         if (i) Name += '_';
648         Name += Reg->getName();
649         Tuple.push_back(DefInit::get(Reg));
650       }
651 
652       // Take the cost list of the first register in the tuple.
653       ListInit *CostList = Proto->getValueAsListInit("CostPerUse");
654       SmallVector<Init *, 2> CostPerUse;
655       CostPerUse.insert(CostPerUse.end(), CostList->begin(), CostList->end());
656 
657       StringInit *AsmName = StringInit::get("");
658       if (!RegNames.empty()) {
659         if (RegNames.size() <= n)
660           PrintFatalError(Def->getLoc(),
661                           "Register tuple definition missing name for '" +
662                             Name + "'.");
663         AsmName = StringInit::get(RegNames[n]);
664       }
665 
666       // Create a new Record representing the synthesized register. This record
667       // is only for consumption by CodeGenRegister, it is not added to the
668       // RecordKeeper.
669       SynthDefs.emplace_back(
670           std::make_unique<Record>(Name, Def->getLoc(), Def->getRecords()));
671       Record *NewReg = SynthDefs.back().get();
672       Elts.insert(NewReg);
673 
674       // Copy Proto super-classes.
675       ArrayRef<std::pair<Record *, SMRange>> Supers = Proto->getSuperClasses();
676       for (const auto &SuperPair : Supers)
677         NewReg->addSuperClass(SuperPair.first, SuperPair.second);
678 
679       // Copy Proto fields.
680       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
681         RecordVal RV = Proto->getValues()[i];
682 
683         // Skip existing fields, like NAME.
684         if (NewReg->getValue(RV.getNameInit()))
685           continue;
686 
687         StringRef Field = RV.getName();
688 
689         // Replace the sub-register list with Tuple.
690         if (Field == "SubRegs")
691           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
692 
693         if (Field == "AsmName")
694           RV.setValue(AsmName);
695 
696         // CostPerUse is aggregated from all Tuple members.
697         if (Field == "CostPerUse")
698           RV.setValue(ListInit::get(CostPerUse, CostList->getElementType()));
699 
700         // Composite registers are always covered by sub-registers.
701         if (Field == "CoveredBySubRegs")
702           RV.setValue(BitInit::get(true));
703 
704         // Copy fields from the RegisterTuples def.
705         if (Field == "SubRegIndices" ||
706             Field == "CompositeIndices") {
707           NewReg->addValue(*Def->getValue(Field));
708           continue;
709         }
710 
711         // Some fields get their default uninitialized value.
712         if (Field == "DwarfNumbers" ||
713             Field == "DwarfAlias" ||
714             Field == "Aliases") {
715           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
716             NewReg->addValue(*DefRV);
717           continue;
718         }
719 
720         // Everything else is copied from Proto.
721         NewReg->addValue(RV);
722       }
723     }
724   }
725 };
726 
727 } // end anonymous namespace
728 
729 //===----------------------------------------------------------------------===//
730 //                            CodeGenRegisterClass
731 //===----------------------------------------------------------------------===//
732 
733 static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
734   llvm::sort(M, deref<std::less<>>());
735   M.erase(std::unique(M.begin(), M.end(), deref<std::equal_to<>>()), M.end());
736 }
737 
738 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
739     : TheDef(R), Name(std::string(R->getName())),
740       TopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1), TSFlags(0) {
741   GeneratePressureSet = R->getValueAsBit("GeneratePressureSet");
742   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
743   if (TypeList.empty())
744     PrintFatalError(R->getLoc(), "RegTypes list must not be empty!");
745   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
746     Record *Type = TypeList[i];
747     if (!Type->isSubClassOf("ValueType"))
748       PrintFatalError(R->getLoc(),
749                       "RegTypes list member '" + Type->getName() +
750                           "' does not derive from the ValueType class!");
751     VTs.push_back(getValueTypeByHwMode(Type, RegBank.getHwModes()));
752   }
753 
754   // Allocation order 0 is the full set. AltOrders provides others.
755   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
756   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
757   Orders.resize(1 + AltOrders->size());
758 
759   // Default allocation order always contains all registers.
760   Artificial = true;
761   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
762     Orders[0].push_back((*Elements)[i]);
763     const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
764     Members.push_back(Reg);
765     Artificial &= Reg->Artificial;
766     TopoSigs.set(Reg->getTopoSig());
767   }
768   sortAndUniqueRegisters(Members);
769 
770   // Alternative allocation orders may be subsets.
771   SetTheory::RecSet Order;
772   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
773     RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
774     Orders[1 + i].append(Order.begin(), Order.end());
775     // Verify that all altorder members are regclass members.
776     while (!Order.empty()) {
777       CodeGenRegister *Reg = RegBank.getReg(Order.back());
778       Order.pop_back();
779       if (!contains(Reg))
780         PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
781                       " is not a class member");
782     }
783   }
784 
785   Namespace = R->getValueAsString("Namespace");
786 
787   if (const RecordVal *RV = R->getValue("RegInfos"))
788     if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue()))
789       RSI = RegSizeInfoByHwMode(DI->getDef(), RegBank.getHwModes());
790   unsigned Size = R->getValueAsInt("Size");
791   assert((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&
792          "Impossible to determine register size");
793   if (!RSI.hasDefault()) {
794     RegSizeInfo RI;
795     RI.RegSize = RI.SpillSize = Size ? Size
796                                      : VTs[0].getSimple().getSizeInBits();
797     RI.SpillAlignment = R->getValueAsInt("Alignment");
798     RSI.insertRegSizeForMode(DefaultMode, RI);
799   }
800 
801   CopyCost = R->getValueAsInt("CopyCost");
802   Allocatable = R->getValueAsBit("isAllocatable");
803   AltOrderSelect = R->getValueAsString("AltOrderSelect");
804   int AllocationPriority = R->getValueAsInt("AllocationPriority");
805   if (AllocationPriority < 0 || AllocationPriority > 63)
806     PrintFatalError(R->getLoc(), "AllocationPriority out of range [0,63]");
807   this->AllocationPriority = AllocationPriority;
808 
809   BitsInit *TSF = R->getValueAsBitsInit("TSFlags");
810   for (unsigned I = 0, E = TSF->getNumBits(); I != E; ++I) {
811     BitInit *Bit = cast<BitInit>(TSF->getBit(I));
812     TSFlags |= uint8_t(Bit->getValue()) << I;
813   }
814 }
815 
816 // Create an inferred register class that was missing from the .td files.
817 // Most properties will be inherited from the closest super-class after the
818 // class structure has been computed.
819 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
820                                            StringRef Name, Key Props)
821     : Members(*Props.Members), TheDef(nullptr), Name(std::string(Name)),
822       TopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1), RSI(Props.RSI),
823       CopyCost(0), Allocatable(true), AllocationPriority(0), TSFlags(0) {
824   Artificial = true;
825   GeneratePressureSet = false;
826   for (const auto R : Members) {
827     TopoSigs.set(R->getTopoSig());
828     Artificial &= R->Artificial;
829   }
830 }
831 
832 // Compute inherited propertied for a synthesized register class.
833 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
834   assert(!getDef() && "Only synthesized classes can inherit properties");
835   assert(!SuperClasses.empty() && "Synthesized class without super class");
836 
837   // The last super-class is the smallest one.
838   CodeGenRegisterClass &Super = *SuperClasses.back();
839 
840   // Most properties are copied directly.
841   // Exceptions are members, size, and alignment
842   Namespace = Super.Namespace;
843   VTs = Super.VTs;
844   CopyCost = Super.CopyCost;
845   // Check for allocatable superclasses.
846   Allocatable = any_of(SuperClasses, [&](const CodeGenRegisterClass *S) {
847     return S->Allocatable;
848   });
849   AltOrderSelect = Super.AltOrderSelect;
850   AllocationPriority = Super.AllocationPriority;
851   TSFlags = Super.TSFlags;
852   GeneratePressureSet |= Super.GeneratePressureSet;
853 
854   // Copy all allocation orders, filter out foreign registers from the larger
855   // super-class.
856   Orders.resize(Super.Orders.size());
857   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
858     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
859       if (contains(RegBank.getReg(Super.Orders[i][j])))
860         Orders[i].push_back(Super.Orders[i][j]);
861 }
862 
863 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
864   return std::binary_search(Members.begin(), Members.end(), Reg,
865                             deref<std::less<>>());
866 }
867 
868 unsigned CodeGenRegisterClass::getWeight(const CodeGenRegBank& RegBank) const {
869   if (TheDef && !TheDef->isValueUnset("Weight"))
870     return TheDef->getValueAsInt("Weight");
871 
872   if (Members.empty() || Artificial)
873     return 0;
874 
875   return (*Members.begin())->getWeight(RegBank);
876 }
877 
878 namespace llvm {
879 
880   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
881     OS << "{ " << K.RSI;
882     for (const auto R : *K.Members)
883       OS << ", " << R->getName();
884     return OS << " }";
885   }
886 
887 } // end namespace llvm
888 
889 // This is a simple lexicographical order that can be used to search for sets.
890 // It is not the same as the topological order provided by TopoOrderRC.
891 bool CodeGenRegisterClass::Key::
892 operator<(const CodeGenRegisterClass::Key &B) const {
893   assert(Members && B.Members);
894   return std::tie(*Members, RSI) < std::tie(*B.Members, B.RSI);
895 }
896 
897 // Returns true if RC is a strict subclass.
898 // RC is a sub-class of this class if it is a valid replacement for any
899 // instruction operand where a register of this classis required. It must
900 // satisfy these conditions:
901 //
902 // 1. All RC registers are also in this.
903 // 2. The RC spill size must not be smaller than our spill size.
904 // 3. RC spill alignment must be compatible with ours.
905 //
906 static bool testSubClass(const CodeGenRegisterClass *A,
907                          const CodeGenRegisterClass *B) {
908   return A->RSI.isSubClassOf(B->RSI) &&
909          std::includes(A->getMembers().begin(), A->getMembers().end(),
910                        B->getMembers().begin(), B->getMembers().end(),
911                        deref<std::less<>>());
912 }
913 
914 /// Sorting predicate for register classes.  This provides a topological
915 /// ordering that arranges all register classes before their sub-classes.
916 ///
917 /// Register classes with the same registers, spill size, and alignment form a
918 /// clique.  They will be ordered alphabetically.
919 ///
920 static bool TopoOrderRC(const CodeGenRegisterClass &PA,
921                         const CodeGenRegisterClass &PB) {
922   auto *A = &PA;
923   auto *B = &PB;
924   if (A == B)
925     return false;
926 
927   if (A->RSI < B->RSI)
928     return true;
929   if (A->RSI != B->RSI)
930     return false;
931 
932   // Order by descending set size.  Note that the classes' allocation order may
933   // not have been computed yet.  The Members set is always vaild.
934   if (A->getMembers().size() > B->getMembers().size())
935     return true;
936   if (A->getMembers().size() < B->getMembers().size())
937     return false;
938 
939   // Finally order by name as a tie breaker.
940   return StringRef(A->getName()) < B->getName();
941 }
942 
943 std::string CodeGenRegisterClass::getQualifiedName() const {
944   if (Namespace.empty())
945     return getName();
946   else
947     return (Namespace + "::" + getName()).str();
948 }
949 
950 // Compute sub-classes of all register classes.
951 // Assume the classes are ordered topologically.
952 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
953   auto &RegClasses = RegBank.getRegClasses();
954 
955   // Visit backwards so sub-classes are seen first.
956   for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
957     CodeGenRegisterClass &RC = *I;
958     RC.SubClasses.resize(RegClasses.size());
959     RC.SubClasses.set(RC.EnumValue);
960     if (RC.Artificial)
961       continue;
962 
963     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
964     for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
965       CodeGenRegisterClass &SubRC = *I2;
966       if (RC.SubClasses.test(SubRC.EnumValue))
967         continue;
968       if (!testSubClass(&RC, &SubRC))
969         continue;
970       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
971       // check them again.
972       RC.SubClasses |= SubRC.SubClasses;
973     }
974 
975     // Sweep up missed clique members.  They will be immediately preceding RC.
976     for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
977       RC.SubClasses.set(I2->EnumValue);
978   }
979 
980   // Compute the SuperClasses lists from the SubClasses vectors.
981   for (auto &RC : RegClasses) {
982     const BitVector &SC = RC.getSubClasses();
983     auto I = RegClasses.begin();
984     for (int s = 0, next_s = SC.find_first(); next_s != -1;
985          next_s = SC.find_next(s)) {
986       std::advance(I, next_s - s);
987       s = next_s;
988       if (&*I == &RC)
989         continue;
990       I->SuperClasses.push_back(&RC);
991     }
992   }
993 
994   // With the class hierarchy in place, let synthesized register classes inherit
995   // properties from their closest super-class. The iteration order here can
996   // propagate properties down multiple levels.
997   for (auto &RC : RegClasses)
998     if (!RC.getDef())
999       RC.inheritProperties(RegBank);
1000 }
1001 
1002 Optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
1003 CodeGenRegisterClass::getMatchingSubClassWithSubRegs(
1004     CodeGenRegBank &RegBank, const CodeGenSubRegIndex *SubIdx) const {
1005   auto SizeOrder = [this](const CodeGenRegisterClass *A,
1006                       const CodeGenRegisterClass *B) {
1007     // If there are multiple, identical register classes, prefer the original
1008     // register class.
1009     if (A == B)
1010       return false;
1011     if (A->getMembers().size() == B->getMembers().size())
1012       return A == this;
1013     return A->getMembers().size() > B->getMembers().size();
1014   };
1015 
1016   auto &RegClasses = RegBank.getRegClasses();
1017 
1018   // Find all the subclasses of this one that fully support the sub-register
1019   // index and order them by size. BiggestSuperRC should always be first.
1020   CodeGenRegisterClass *BiggestSuperRegRC = getSubClassWithSubReg(SubIdx);
1021   if (!BiggestSuperRegRC)
1022     return None;
1023   BitVector SuperRegRCsBV = BiggestSuperRegRC->getSubClasses();
1024   std::vector<CodeGenRegisterClass *> SuperRegRCs;
1025   for (auto &RC : RegClasses)
1026     if (SuperRegRCsBV[RC.EnumValue])
1027       SuperRegRCs.emplace_back(&RC);
1028   llvm::stable_sort(SuperRegRCs, SizeOrder);
1029 
1030   assert(SuperRegRCs.front() == BiggestSuperRegRC &&
1031          "Biggest class wasn't first");
1032 
1033   // Find all the subreg classes and order them by size too.
1034   std::vector<std::pair<CodeGenRegisterClass *, BitVector>> SuperRegClasses;
1035   for (auto &RC: RegClasses) {
1036     BitVector SuperRegClassesBV(RegClasses.size());
1037     RC.getSuperRegClasses(SubIdx, SuperRegClassesBV);
1038     if (SuperRegClassesBV.any())
1039       SuperRegClasses.push_back(std::make_pair(&RC, SuperRegClassesBV));
1040   }
1041   llvm::sort(SuperRegClasses,
1042              [&](const std::pair<CodeGenRegisterClass *, BitVector> &A,
1043                  const std::pair<CodeGenRegisterClass *, BitVector> &B) {
1044                return SizeOrder(A.first, B.first);
1045              });
1046 
1047   // Find the biggest subclass and subreg class such that R:subidx is in the
1048   // subreg class for all R in subclass.
1049   //
1050   // For example:
1051   // All registers in X86's GR64 have a sub_32bit subregister but no class
1052   // exists that contains all the 32-bit subregisters because GR64 contains RIP
1053   // but GR32 does not contain EIP. Instead, we constrain SuperRegRC to
1054   // GR32_with_sub_8bit (which is identical to GR32_with_sub_32bit) and then,
1055   // having excluded RIP, we are able to find a SubRegRC (GR32).
1056   CodeGenRegisterClass *ChosenSuperRegClass = nullptr;
1057   CodeGenRegisterClass *SubRegRC = nullptr;
1058   for (auto *SuperRegRC : SuperRegRCs) {
1059     for (const auto &SuperRegClassPair : SuperRegClasses) {
1060       const BitVector &SuperRegClassBV = SuperRegClassPair.second;
1061       if (SuperRegClassBV[SuperRegRC->EnumValue]) {
1062         SubRegRC = SuperRegClassPair.first;
1063         ChosenSuperRegClass = SuperRegRC;
1064 
1065         // If SubRegRC is bigger than SuperRegRC then there are members of
1066         // SubRegRC that don't have super registers via SubIdx. Keep looking to
1067         // find a better fit and fall back on this one if there isn't one.
1068         //
1069         // This is intended to prevent X86 from making odd choices such as
1070         // picking LOW32_ADDR_ACCESS_RBP instead of GR32 in the example above.
1071         // LOW32_ADDR_ACCESS_RBP is a valid choice but contains registers that
1072         // aren't subregisters of SuperRegRC whereas GR32 has a direct 1:1
1073         // mapping.
1074         if (SuperRegRC->getMembers().size() >= SubRegRC->getMembers().size())
1075           return std::make_pair(ChosenSuperRegClass, SubRegRC);
1076       }
1077     }
1078 
1079     // If we found a fit but it wasn't quite ideal because SubRegRC had excess
1080     // registers, then we're done.
1081     if (ChosenSuperRegClass)
1082       return std::make_pair(ChosenSuperRegClass, SubRegRC);
1083   }
1084 
1085   return None;
1086 }
1087 
1088 void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
1089                                               BitVector &Out) const {
1090   auto FindI = SuperRegClasses.find(SubIdx);
1091   if (FindI == SuperRegClasses.end())
1092     return;
1093   for (CodeGenRegisterClass *RC : FindI->second)
1094     Out.set(RC->EnumValue);
1095 }
1096 
1097 // Populate a unique sorted list of units from a register set.
1098 void CodeGenRegisterClass::buildRegUnitSet(const CodeGenRegBank &RegBank,
1099   std::vector<unsigned> &RegUnits) const {
1100   std::vector<unsigned> TmpUnits;
1101   for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI) {
1102     const RegUnit &RU = RegBank.getRegUnit(*UnitI);
1103     if (!RU.Artificial)
1104       TmpUnits.push_back(*UnitI);
1105   }
1106   llvm::sort(TmpUnits);
1107   std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
1108                    std::back_inserter(RegUnits));
1109 }
1110 
1111 //===----------------------------------------------------------------------===//
1112 //                           CodeGenRegisterCategory
1113 //===----------------------------------------------------------------------===//
1114 
1115 CodeGenRegisterCategory::CodeGenRegisterCategory(CodeGenRegBank &RegBank,
1116                                                  Record *R)
1117     : TheDef(R), Name(std::string(R->getName())) {
1118   for (Record *RegClass : R->getValueAsListOfDefs("Classes"))
1119     Classes.push_back(RegBank.getRegClass(RegClass));
1120 }
1121 
1122 //===----------------------------------------------------------------------===//
1123 //                               CodeGenRegBank
1124 //===----------------------------------------------------------------------===//
1125 
1126 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records,
1127                                const CodeGenHwModes &Modes) : CGH(Modes) {
1128   // Configure register Sets to understand register classes and tuples.
1129   Sets.addFieldExpander("RegisterClass", "MemberList");
1130   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
1131   Sets.addExpander("RegisterTuples",
1132                    std::make_unique<TupleExpander>(SynthDefs));
1133 
1134   // Read in the user-defined (named) sub-register indices.
1135   // More indices will be synthesized later.
1136   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
1137   llvm::sort(SRIs, LessRecord());
1138   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
1139     getSubRegIdx(SRIs[i]);
1140   // Build composite maps from ComposedOf fields.
1141   for (auto &Idx : SubRegIndices)
1142     Idx.updateComponents(*this);
1143 
1144   // Read in the register definitions.
1145   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
1146   llvm::sort(Regs, LessRecordRegister());
1147   // Assign the enumeration values.
1148   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1149     getReg(Regs[i]);
1150 
1151   // Expand tuples and number the new registers.
1152   std::vector<Record*> Tups =
1153     Records.getAllDerivedDefinitions("RegisterTuples");
1154 
1155   for (Record *R : Tups) {
1156     std::vector<Record *> TupRegs = *Sets.expand(R);
1157     llvm::sort(TupRegs, LessRecordRegister());
1158     for (Record *RC : TupRegs)
1159       getReg(RC);
1160   }
1161 
1162   // Now all the registers are known. Build the object graph of explicit
1163   // register-register references.
1164   for (auto &Reg : Registers)
1165     Reg.buildObjectGraph(*this);
1166 
1167   // Compute register name map.
1168   for (auto &Reg : Registers)
1169     // FIXME: This could just be RegistersByName[name] = register, except that
1170     // causes some failures in MIPS - perhaps they have duplicate register name
1171     // entries? (or maybe there's a reason for it - I don't know much about this
1172     // code, just drive-by refactoring)
1173     RegistersByName.insert(
1174         std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
1175 
1176   // Precompute all sub-register maps.
1177   // This will create Composite entries for all inferred sub-register indices.
1178   for (auto &Reg : Registers)
1179     Reg.computeSubRegs(*this);
1180 
1181   // Compute transitive closure of subregister index ConcatenationOf vectors
1182   // and initialize ConcatIdx map.
1183   for (CodeGenSubRegIndex &SRI : SubRegIndices) {
1184     SRI.computeConcatTransitiveClosure();
1185     if (!SRI.ConcatenationOf.empty())
1186       ConcatIdx.insert(std::make_pair(
1187           SmallVector<CodeGenSubRegIndex*,8>(SRI.ConcatenationOf.begin(),
1188                                              SRI.ConcatenationOf.end()), &SRI));
1189   }
1190 
1191   // Infer even more sub-registers by combining leading super-registers.
1192   for (auto &Reg : Registers)
1193     if (Reg.CoveredBySubRegs)
1194       Reg.computeSecondarySubRegs(*this);
1195 
1196   // After the sub-register graph is complete, compute the topologically
1197   // ordered SuperRegs list.
1198   for (auto &Reg : Registers)
1199     Reg.computeSuperRegs(*this);
1200 
1201   // For each pair of Reg:SR, if both are non-artificial, mark the
1202   // corresponding sub-register index as non-artificial.
1203   for (auto &Reg : Registers) {
1204     if (Reg.Artificial)
1205       continue;
1206     for (auto P : Reg.getSubRegs()) {
1207       const CodeGenRegister *SR = P.second;
1208       if (!SR->Artificial)
1209         P.first->Artificial = false;
1210     }
1211   }
1212 
1213   // Native register units are associated with a leaf register. They've all been
1214   // discovered now.
1215   NumNativeRegUnits = RegUnits.size();
1216 
1217   // Read in register class definitions.
1218   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
1219   if (RCs.empty())
1220     PrintFatalError("No 'RegisterClass' subclasses defined!");
1221 
1222   // Allocate user-defined register classes.
1223   for (auto *R : RCs) {
1224     RegClasses.emplace_back(*this, R);
1225     CodeGenRegisterClass &RC = RegClasses.back();
1226     if (!RC.Artificial)
1227       addToMaps(&RC);
1228   }
1229 
1230   // Infer missing classes to create a full algebra.
1231   computeInferredRegisterClasses();
1232 
1233   // Order register classes topologically and assign enum values.
1234   RegClasses.sort(TopoOrderRC);
1235   unsigned i = 0;
1236   for (auto &RC : RegClasses)
1237     RC.EnumValue = i++;
1238   CodeGenRegisterClass::computeSubClasses(*this);
1239 
1240   // Read in the register category definitions.
1241   std::vector<Record *> RCats =
1242       Records.getAllDerivedDefinitions("RegisterCategory");
1243   for (auto *R : RCats)
1244     RegCategories.emplace_back(*this, R);
1245 }
1246 
1247 // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1248 CodeGenSubRegIndex*
1249 CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1250   SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
1251   return &SubRegIndices.back();
1252 }
1253 
1254 CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1255   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1256   if (Idx)
1257     return Idx;
1258   SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
1259   Idx = &SubRegIndices.back();
1260   return Idx;
1261 }
1262 
1263 const CodeGenSubRegIndex *
1264 CodeGenRegBank::findSubRegIdx(const Record* Def) const {
1265   return Def2SubRegIdx.lookup(Def);
1266 }
1267 
1268 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1269   CodeGenRegister *&Reg = Def2Reg[Def];
1270   if (Reg)
1271     return Reg;
1272   Registers.emplace_back(Def, Registers.size() + 1);
1273   Reg = &Registers.back();
1274   return Reg;
1275 }
1276 
1277 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1278   if (Record *Def = RC->getDef())
1279     Def2RC.insert(std::make_pair(Def, RC));
1280 
1281   // Duplicate classes are rejected by insert().
1282   // That's OK, we only care about the properties handled by CGRC::Key.
1283   CodeGenRegisterClass::Key K(*RC);
1284   Key2RC.insert(std::make_pair(K, RC));
1285 }
1286 
1287 // Create a synthetic sub-class if it is missing.
1288 CodeGenRegisterClass*
1289 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1290                                     const CodeGenRegister::Vec *Members,
1291                                     StringRef Name) {
1292   // Synthetic sub-class has the same size and alignment as RC.
1293   CodeGenRegisterClass::Key K(Members, RC->RSI);
1294   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1295   if (FoundI != Key2RC.end())
1296     return FoundI->second;
1297 
1298   // Sub-class doesn't exist, create a new one.
1299   RegClasses.emplace_back(*this, Name, K);
1300   addToMaps(&RegClasses.back());
1301   return &RegClasses.back();
1302 }
1303 
1304 CodeGenRegisterClass *CodeGenRegBank::getRegClass(const Record *Def) const {
1305   if (CodeGenRegisterClass *RC = Def2RC.lookup(Def))
1306     return RC;
1307 
1308   PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1309 }
1310 
1311 CodeGenSubRegIndex*
1312 CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1313                                         CodeGenSubRegIndex *B) {
1314   // Look for an existing entry.
1315   CodeGenSubRegIndex *Comp = A->compose(B);
1316   if (Comp)
1317     return Comp;
1318 
1319   // None exists, synthesize one.
1320   std::string Name = A->getName() + "_then_" + B->getName();
1321   Comp = createSubRegIndex(Name, A->getNamespace());
1322   A->addComposite(B, Comp);
1323   return Comp;
1324 }
1325 
1326 CodeGenSubRegIndex *CodeGenRegBank::
1327 getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1328   assert(Parts.size() > 1 && "Need two parts to concatenate");
1329 #ifndef NDEBUG
1330   for (CodeGenSubRegIndex *Idx : Parts) {
1331     assert(Idx->ConcatenationOf.empty() && "No transitive closure?");
1332   }
1333 #endif
1334 
1335   // Look for an existing entry.
1336   CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1337   if (Idx)
1338     return Idx;
1339 
1340   // None exists, synthesize one.
1341   std::string Name = Parts.front()->getName();
1342   // Determine whether all parts are contiguous.
1343   bool isContinuous = true;
1344   unsigned Size = Parts.front()->Size;
1345   unsigned LastOffset = Parts.front()->Offset;
1346   unsigned LastSize = Parts.front()->Size;
1347   for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1348     Name += '_';
1349     Name += Parts[i]->getName();
1350     Size += Parts[i]->Size;
1351     if (Parts[i]->Offset != (LastOffset + LastSize))
1352       isContinuous = false;
1353     LastOffset = Parts[i]->Offset;
1354     LastSize = Parts[i]->Size;
1355   }
1356   Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1357   Idx->Size = Size;
1358   Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1359   Idx->ConcatenationOf.assign(Parts.begin(), Parts.end());
1360   return Idx;
1361 }
1362 
1363 void CodeGenRegBank::computeComposites() {
1364   using RegMap = std::map<const CodeGenRegister*, const CodeGenRegister*>;
1365 
1366   // Subreg -> { Reg->Reg }, where the right-hand side is the mapping from
1367   // register to (sub)register associated with the action of the left-hand
1368   // side subregister.
1369   std::map<const CodeGenSubRegIndex*, RegMap> SubRegAction;
1370   for (const CodeGenRegister &R : Registers) {
1371     const CodeGenRegister::SubRegMap &SM = R.getSubRegs();
1372     for (std::pair<const CodeGenSubRegIndex*, const CodeGenRegister*> P : SM)
1373       SubRegAction[P.first].insert({&R, P.second});
1374   }
1375 
1376   // Calculate the composition of two subregisters as compositions of their
1377   // associated actions.
1378   auto compose = [&SubRegAction] (const CodeGenSubRegIndex *Sub1,
1379                                   const CodeGenSubRegIndex *Sub2) {
1380     RegMap C;
1381     const RegMap &Img1 = SubRegAction.at(Sub1);
1382     const RegMap &Img2 = SubRegAction.at(Sub2);
1383     for (std::pair<const CodeGenRegister*, const CodeGenRegister*> P : Img1) {
1384       auto F = Img2.find(P.second);
1385       if (F != Img2.end())
1386         C.insert({P.first, F->second});
1387     }
1388     return C;
1389   };
1390 
1391   // Check if the two maps agree on the intersection of their domains.
1392   auto agree = [] (const RegMap &Map1, const RegMap &Map2) {
1393     // Technically speaking, an empty map agrees with any other map, but
1394     // this could flag false positives. We're interested in non-vacuous
1395     // agreements.
1396     if (Map1.empty() || Map2.empty())
1397       return false;
1398     for (std::pair<const CodeGenRegister*, const CodeGenRegister*> P : Map1) {
1399       auto F = Map2.find(P.first);
1400       if (F == Map2.end() || P.second != F->second)
1401         return false;
1402     }
1403     return true;
1404   };
1405 
1406   using CompositePair = std::pair<const CodeGenSubRegIndex*,
1407                                   const CodeGenSubRegIndex*>;
1408   SmallSet<CompositePair,4> UserDefined;
1409   for (const CodeGenSubRegIndex &Idx : SubRegIndices)
1410     for (auto P : Idx.getComposites())
1411       UserDefined.insert(std::make_pair(&Idx, P.first));
1412 
1413   // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1414   // and many registers will share TopoSigs on regular architectures.
1415   BitVector TopoSigs(getNumTopoSigs());
1416 
1417   for (const auto &Reg1 : Registers) {
1418     // Skip identical subreg structures already processed.
1419     if (TopoSigs.test(Reg1.getTopoSig()))
1420       continue;
1421     TopoSigs.set(Reg1.getTopoSig());
1422 
1423     const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1424     for (auto I1 : SRM1) {
1425       CodeGenSubRegIndex *Idx1 = I1.first;
1426       CodeGenRegister *Reg2 = I1.second;
1427       // Ignore identity compositions.
1428       if (&Reg1 == Reg2)
1429         continue;
1430       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1431       // Try composing Idx1 with another SubRegIndex.
1432       for (auto I2 : SRM2) {
1433         CodeGenSubRegIndex *Idx2 = I2.first;
1434         CodeGenRegister *Reg3 = I2.second;
1435         // Ignore identity compositions.
1436         if (Reg2 == Reg3)
1437           continue;
1438         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1439         CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
1440         assert(Idx3 && "Sub-register doesn't have an index");
1441 
1442         // Conflicting composition? Emit a warning but allow it.
1443         if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3)) {
1444           // If the composition was not user-defined, always emit a warning.
1445           if (!UserDefined.count({Idx1, Idx2}) ||
1446               agree(compose(Idx1, Idx2), SubRegAction.at(Idx3)))
1447             PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1448                          " and " + Idx2->getQualifiedName() +
1449                          " compose ambiguously as " + Prev->getQualifiedName() +
1450                          " or " + Idx3->getQualifiedName());
1451         }
1452       }
1453     }
1454   }
1455 }
1456 
1457 // Compute lane masks. This is similar to register units, but at the
1458 // sub-register index level. Each bit in the lane mask is like a register unit
1459 // class, and two lane masks will have a bit in common if two sub-register
1460 // indices overlap in some register.
1461 //
1462 // Conservatively share a lane mask bit if two sub-register indices overlap in
1463 // some registers, but not in others. That shouldn't happen a lot.
1464 void CodeGenRegBank::computeSubRegLaneMasks() {
1465   // First assign individual bits to all the leaf indices.
1466   unsigned Bit = 0;
1467   // Determine mask of lanes that cover their registers.
1468   CoveringLanes = LaneBitmask::getAll();
1469   for (auto &Idx : SubRegIndices) {
1470     if (Idx.getComposites().empty()) {
1471       if (Bit > LaneBitmask::BitWidth) {
1472         PrintFatalError(
1473           Twine("Ran out of lanemask bits to represent subregister ")
1474           + Idx.getName());
1475       }
1476       Idx.LaneMask = LaneBitmask::getLane(Bit);
1477       ++Bit;
1478     } else {
1479       Idx.LaneMask = LaneBitmask::getNone();
1480     }
1481   }
1482 
1483   // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
1484   // here is that for each possible target subregister we look at the leafs
1485   // in the subregister graph that compose for this target and create
1486   // transformation sequences for the lanemasks. Each step in the sequence
1487   // consists of a bitmask and a bitrotate operation. As the rotation amounts
1488   // are usually the same for many subregisters we can easily combine the steps
1489   // by combining the masks.
1490   for (const auto &Idx : SubRegIndices) {
1491     const auto &Composites = Idx.getComposites();
1492     auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
1493 
1494     if (Composites.empty()) {
1495       // Moving from a class with no subregisters we just had a single lane:
1496       // The subregister must be a leaf subregister and only occupies 1 bit.
1497       // Move the bit from the class without subregisters into that position.
1498       unsigned DstBit = Idx.LaneMask.getHighestLane();
1499       assert(Idx.LaneMask == LaneBitmask::getLane(DstBit) &&
1500              "Must be a leaf subregister");
1501       MaskRolPair MaskRol = { LaneBitmask::getLane(0), (uint8_t)DstBit };
1502       LaneTransforms.push_back(MaskRol);
1503     } else {
1504       // Go through all leaf subregisters and find the ones that compose with
1505       // Idx. These make out all possible valid bits in the lane mask we want to
1506       // transform. Looking only at the leafs ensure that only a single bit in
1507       // the mask is set.
1508       unsigned NextBit = 0;
1509       for (auto &Idx2 : SubRegIndices) {
1510         // Skip non-leaf subregisters.
1511         if (!Idx2.getComposites().empty())
1512           continue;
1513         // Replicate the behaviour from the lane mask generation loop above.
1514         unsigned SrcBit = NextBit;
1515         LaneBitmask SrcMask = LaneBitmask::getLane(SrcBit);
1516         if (NextBit < LaneBitmask::BitWidth-1)
1517           ++NextBit;
1518         assert(Idx2.LaneMask == SrcMask);
1519 
1520         // Get the composed subregister if there is any.
1521         auto C = Composites.find(&Idx2);
1522         if (C == Composites.end())
1523           continue;
1524         const CodeGenSubRegIndex *Composite = C->second;
1525         // The Composed subreg should be a leaf subreg too
1526         assert(Composite->getComposites().empty());
1527 
1528         // Create Mask+Rotate operation and merge with existing ops if possible.
1529         unsigned DstBit = Composite->LaneMask.getHighestLane();
1530         int Shift = DstBit - SrcBit;
1531         uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift
1532                                         : LaneBitmask::BitWidth + Shift;
1533         for (auto &I : LaneTransforms) {
1534           if (I.RotateLeft == RotateLeft) {
1535             I.Mask |= SrcMask;
1536             SrcMask = LaneBitmask::getNone();
1537           }
1538         }
1539         if (SrcMask.any()) {
1540           MaskRolPair MaskRol = { SrcMask, RotateLeft };
1541           LaneTransforms.push_back(MaskRol);
1542         }
1543       }
1544     }
1545 
1546     // Optimize if the transformation consists of one step only: Set mask to
1547     // 0xffffffff (including some irrelevant invalid bits) so that it should
1548     // merge with more entries later while compressing the table.
1549     if (LaneTransforms.size() == 1)
1550       LaneTransforms[0].Mask = LaneBitmask::getAll();
1551 
1552     // Further compression optimization: For invalid compositions resulting
1553     // in a sequence with 0 entries we can just pick any other. Choose
1554     // Mask 0xffffffff with Rotation 0.
1555     if (LaneTransforms.size() == 0) {
1556       MaskRolPair P = { LaneBitmask::getAll(), 0 };
1557       LaneTransforms.push_back(P);
1558     }
1559   }
1560 
1561   // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1562   // by the sub-register graph? This doesn't occur in any known targets.
1563 
1564   // Inherit lanes from composites.
1565   for (const auto &Idx : SubRegIndices) {
1566     LaneBitmask Mask = Idx.computeLaneMask();
1567     // If some super-registers without CoveredBySubRegs use this index, we can
1568     // no longer assume that the lanes are covering their registers.
1569     if (!Idx.AllSuperRegsCovered)
1570       CoveringLanes &= ~Mask;
1571   }
1572 
1573   // Compute lane mask combinations for register classes.
1574   for (auto &RegClass : RegClasses) {
1575     LaneBitmask LaneMask;
1576     for (const auto &SubRegIndex : SubRegIndices) {
1577       if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)
1578         continue;
1579       LaneMask |= SubRegIndex.LaneMask;
1580     }
1581 
1582     // For classes without any subregisters set LaneMask to 1 instead of 0.
1583     // This makes it easier for client code to handle classes uniformly.
1584     if (LaneMask.none())
1585       LaneMask = LaneBitmask::getLane(0);
1586 
1587     RegClass.LaneMask = LaneMask;
1588   }
1589 }
1590 
1591 namespace {
1592 
1593 // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1594 // the transitive closure of the union of overlapping register
1595 // classes. Together, the UberRegSets form a partition of the registers. If we
1596 // consider overlapping register classes to be connected, then each UberRegSet
1597 // is a set of connected components.
1598 //
1599 // An UberRegSet will likely be a horizontal slice of register names of
1600 // the same width. Nontrivial subregisters should then be in a separate
1601 // UberRegSet. But this property isn't required for valid computation of
1602 // register unit weights.
1603 //
1604 // A Weight field caches the max per-register unit weight in each UberRegSet.
1605 //
1606 // A set of SingularDeterminants flags single units of some register in this set
1607 // for which the unit weight equals the set weight. These units should not have
1608 // their weight increased.
1609 struct UberRegSet {
1610   CodeGenRegister::Vec Regs;
1611   unsigned Weight = 0;
1612   CodeGenRegister::RegUnitList SingularDeterminants;
1613 
1614   UberRegSet() = default;
1615 };
1616 
1617 } // end anonymous namespace
1618 
1619 // Partition registers into UberRegSets, where each set is the transitive
1620 // closure of the union of overlapping register classes.
1621 //
1622 // UberRegSets[0] is a special non-allocatable set.
1623 static void computeUberSets(std::vector<UberRegSet> &UberSets,
1624                             std::vector<UberRegSet*> &RegSets,
1625                             CodeGenRegBank &RegBank) {
1626   const auto &Registers = RegBank.getRegisters();
1627 
1628   // The Register EnumValue is one greater than its index into Registers.
1629   assert(Registers.size() == Registers.back().EnumValue &&
1630          "register enum value mismatch");
1631 
1632   // For simplicitly make the SetID the same as EnumValue.
1633   IntEqClasses UberSetIDs(Registers.size()+1);
1634   std::set<unsigned> AllocatableRegs;
1635   for (auto &RegClass : RegBank.getRegClasses()) {
1636     if (!RegClass.Allocatable)
1637       continue;
1638 
1639     const CodeGenRegister::Vec &Regs = RegClass.getMembers();
1640     if (Regs.empty())
1641       continue;
1642 
1643     unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1644     assert(USetID && "register number 0 is invalid");
1645 
1646     AllocatableRegs.insert((*Regs.begin())->EnumValue);
1647     for (const CodeGenRegister *CGR : llvm::drop_begin(Regs)) {
1648       AllocatableRegs.insert(CGR->EnumValue);
1649       UberSetIDs.join(USetID, CGR->EnumValue);
1650     }
1651   }
1652   // Combine non-allocatable regs.
1653   for (const auto &Reg : Registers) {
1654     unsigned RegNum = Reg.EnumValue;
1655     if (AllocatableRegs.count(RegNum))
1656       continue;
1657 
1658     UberSetIDs.join(0, RegNum);
1659   }
1660   UberSetIDs.compress();
1661 
1662   // Make the first UberSet a special unallocatable set.
1663   unsigned ZeroID = UberSetIDs[0];
1664 
1665   // Insert Registers into the UberSets formed by union-find.
1666   // Do not resize after this.
1667   UberSets.resize(UberSetIDs.getNumClasses());
1668   unsigned i = 0;
1669   for (const CodeGenRegister &Reg : Registers) {
1670     unsigned USetID = UberSetIDs[Reg.EnumValue];
1671     if (!USetID)
1672       USetID = ZeroID;
1673     else if (USetID == ZeroID)
1674       USetID = 0;
1675 
1676     UberRegSet *USet = &UberSets[USetID];
1677     USet->Regs.push_back(&Reg);
1678     sortAndUniqueRegisters(USet->Regs);
1679     RegSets[i++] = USet;
1680   }
1681 }
1682 
1683 // Recompute each UberSet weight after changing unit weights.
1684 static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1685                                CodeGenRegBank &RegBank) {
1686   // Skip the first unallocatable set.
1687   for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1688          E = UberSets.end(); I != E; ++I) {
1689 
1690     // Initialize all unit weights in this set, and remember the max units/reg.
1691     const CodeGenRegister *Reg = nullptr;
1692     unsigned MaxWeight = 0, Weight = 0;
1693     for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1694       if (Reg != UnitI.getReg()) {
1695         if (Weight > MaxWeight)
1696           MaxWeight = Weight;
1697         Reg = UnitI.getReg();
1698         Weight = 0;
1699       }
1700       if (!RegBank.getRegUnit(*UnitI).Artificial) {
1701         unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1702         if (!UWeight) {
1703           UWeight = 1;
1704           RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1705         }
1706         Weight += UWeight;
1707       }
1708     }
1709     if (Weight > MaxWeight)
1710       MaxWeight = Weight;
1711     if (I->Weight != MaxWeight) {
1712       LLVM_DEBUG(dbgs() << "UberSet " << I - UberSets.begin() << " Weight "
1713                         << MaxWeight;
1714                  for (auto &Unit
1715                       : I->Regs) dbgs()
1716                  << " " << Unit->getName();
1717                  dbgs() << "\n");
1718       // Update the set weight.
1719       I->Weight = MaxWeight;
1720     }
1721 
1722     // Find singular determinants.
1723     for (const auto R : I->Regs) {
1724       if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
1725         I->SingularDeterminants |= R->getRegUnits();
1726       }
1727     }
1728   }
1729 }
1730 
1731 // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1732 // a register and its subregisters so that they have the same weight as their
1733 // UberSet. Self-recursion processes the subregister tree in postorder so
1734 // subregisters are normalized first.
1735 //
1736 // Side effects:
1737 // - creates new adopted register units
1738 // - causes superregisters to inherit adopted units
1739 // - increases the weight of "singular" units
1740 // - induces recomputation of UberWeights.
1741 static bool normalizeWeight(CodeGenRegister *Reg,
1742                             std::vector<UberRegSet> &UberSets,
1743                             std::vector<UberRegSet*> &RegSets,
1744                             BitVector &NormalRegs,
1745                             CodeGenRegister::RegUnitList &NormalUnits,
1746                             CodeGenRegBank &RegBank) {
1747   NormalRegs.resize(std::max(Reg->EnumValue + 1, NormalRegs.size()));
1748   if (NormalRegs.test(Reg->EnumValue))
1749     return false;
1750   NormalRegs.set(Reg->EnumValue);
1751 
1752   bool Changed = false;
1753   const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1754   for (auto SRI : SRM) {
1755     if (SRI.second == Reg)
1756       continue; // self-cycles happen
1757 
1758     Changed |= normalizeWeight(SRI.second, UberSets, RegSets, NormalRegs,
1759                                NormalUnits, RegBank);
1760   }
1761   // Postorder register normalization.
1762 
1763   // Inherit register units newly adopted by subregisters.
1764   if (Reg->inheritRegUnits(RegBank))
1765     computeUberWeights(UberSets, RegBank);
1766 
1767   // Check if this register is too skinny for its UberRegSet.
1768   UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1769 
1770   unsigned RegWeight = Reg->getWeight(RegBank);
1771   if (UberSet->Weight > RegWeight) {
1772     // A register unit's weight can be adjusted only if it is the singular unit
1773     // for this register, has not been used to normalize a subregister's set,
1774     // and has not already been used to singularly determine this UberRegSet.
1775     unsigned AdjustUnit = *Reg->getRegUnits().begin();
1776     if (Reg->getRegUnits().count() != 1
1777         || hasRegUnit(NormalUnits, AdjustUnit)
1778         || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1779       // We don't have an adjustable unit, so adopt a new one.
1780       AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1781       Reg->adoptRegUnit(AdjustUnit);
1782       // Adopting a unit does not immediately require recomputing set weights.
1783     }
1784     else {
1785       // Adjust the existing single unit.
1786       if (!RegBank.getRegUnit(AdjustUnit).Artificial)
1787         RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1788       // The unit may be shared among sets and registers within this set.
1789       computeUberWeights(UberSets, RegBank);
1790     }
1791     Changed = true;
1792   }
1793 
1794   // Mark these units normalized so superregisters can't change their weights.
1795   NormalUnits |= Reg->getRegUnits();
1796 
1797   return Changed;
1798 }
1799 
1800 // Compute a weight for each register unit created during getSubRegs.
1801 //
1802 // The goal is that two registers in the same class will have the same weight,
1803 // where each register's weight is defined as sum of its units' weights.
1804 void CodeGenRegBank::computeRegUnitWeights() {
1805   std::vector<UberRegSet> UberSets;
1806   std::vector<UberRegSet*> RegSets(Registers.size());
1807   computeUberSets(UberSets, RegSets, *this);
1808   // UberSets and RegSets are now immutable.
1809 
1810   computeUberWeights(UberSets, *this);
1811 
1812   // Iterate over each Register, normalizing the unit weights until reaching
1813   // a fix point.
1814   unsigned NumIters = 0;
1815   for (bool Changed = true; Changed; ++NumIters) {
1816     assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
1817     Changed = false;
1818     for (auto &Reg : Registers) {
1819       CodeGenRegister::RegUnitList NormalUnits;
1820       BitVector NormalRegs;
1821       Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
1822                                  NormalUnits, *this);
1823     }
1824   }
1825 }
1826 
1827 // Find a set in UniqueSets with the same elements as Set.
1828 // Return an iterator into UniqueSets.
1829 static std::vector<RegUnitSet>::const_iterator
1830 findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1831                const RegUnitSet &Set) {
1832   std::vector<RegUnitSet>::const_iterator
1833     I = UniqueSets.begin(), E = UniqueSets.end();
1834   for(;I != E; ++I) {
1835     if (I->Units == Set.Units)
1836       break;
1837   }
1838   return I;
1839 }
1840 
1841 // Return true if the RUSubSet is a subset of RUSuperSet.
1842 static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1843                             const std::vector<unsigned> &RUSuperSet) {
1844   return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1845                        RUSubSet.begin(), RUSubSet.end());
1846 }
1847 
1848 /// Iteratively prune unit sets. Prune subsets that are close to the superset,
1849 /// but with one or two registers removed. We occasionally have registers like
1850 /// APSR and PC thrown in with the general registers. We also see many
1851 /// special-purpose register subsets, such as tail-call and Thumb
1852 /// encodings. Generating all possible overlapping sets is combinatorial and
1853 /// overkill for modeling pressure. Ideally we could fix this statically in
1854 /// tablegen by (1) having the target define register classes that only include
1855 /// the allocatable registers and marking other classes as non-allocatable and
1856 /// (2) having a way to mark special purpose classes as "don't-care" classes for
1857 /// the purpose of pressure.  However, we make an attempt to handle targets that
1858 /// are not nicely defined by merging nearly identical register unit sets
1859 /// statically. This generates smaller tables. Then, dynamically, we adjust the
1860 /// set limit by filtering the reserved registers.
1861 ///
1862 /// Merge sets only if the units have the same weight. For example, on ARM,
1863 /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1864 /// should not expand the S set to include D regs.
1865 void CodeGenRegBank::pruneUnitSets() {
1866   assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
1867 
1868   // Form an equivalence class of UnitSets with no significant difference.
1869   std::vector<unsigned> SuperSetIDs;
1870   for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1871        SubIdx != EndIdx; ++SubIdx) {
1872     const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1873     unsigned SuperIdx = 0;
1874     for (; SuperIdx != EndIdx; ++SuperIdx) {
1875       if (SuperIdx == SubIdx)
1876         continue;
1877 
1878       unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1879       const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1880       if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1881           && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1882           && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1883           && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1884         LLVM_DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
1885                           << "\n");
1886         // We can pick any of the set names for the merged set. Go for the
1887         // shortest one to avoid picking the name of one of the classes that are
1888         // artificially created by tablegen. So "FPR128_lo" instead of
1889         // "QQQQ_with_qsub3_in_FPR128_lo".
1890         if (RegUnitSets[SubIdx].Name.size() < RegUnitSets[SuperIdx].Name.size())
1891           RegUnitSets[SuperIdx].Name = RegUnitSets[SubIdx].Name;
1892         break;
1893       }
1894     }
1895     if (SuperIdx == EndIdx)
1896       SuperSetIDs.push_back(SubIdx);
1897   }
1898   // Populate PrunedUnitSets with each equivalence class's superset.
1899   std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1900   for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1901     unsigned SuperIdx = SuperSetIDs[i];
1902     PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1903     PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1904   }
1905   RegUnitSets.swap(PrunedUnitSets);
1906 }
1907 
1908 // Create a RegUnitSet for each RegClass that contains all units in the class
1909 // including adopted units that are necessary to model register pressure. Then
1910 // iteratively compute RegUnitSets such that the union of any two overlapping
1911 // RegUnitSets is repreresented.
1912 //
1913 // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1914 // RegUnitSet that is a superset of that RegUnitClass.
1915 void CodeGenRegBank::computeRegUnitSets() {
1916   assert(RegUnitSets.empty() && "dirty RegUnitSets");
1917 
1918   // Compute a unique RegUnitSet for each RegClass.
1919   auto &RegClasses = getRegClasses();
1920   for (auto &RC : RegClasses) {
1921     if (!RC.Allocatable || RC.Artificial || !RC.GeneratePressureSet)
1922       continue;
1923 
1924     // Speculatively grow the RegUnitSets to hold the new set.
1925     RegUnitSets.resize(RegUnitSets.size() + 1);
1926     RegUnitSets.back().Name = RC.getName();
1927 
1928     // Compute a sorted list of units in this class.
1929     RC.buildRegUnitSet(*this, RegUnitSets.back().Units);
1930 
1931     // Find an existing RegUnitSet.
1932     std::vector<RegUnitSet>::const_iterator SetI =
1933       findRegUnitSet(RegUnitSets, RegUnitSets.back());
1934     if (SetI != std::prev(RegUnitSets.end()))
1935       RegUnitSets.pop_back();
1936   }
1937 
1938   if (RegUnitSets.empty())
1939     PrintFatalError("RegUnitSets cannot be empty!");
1940 
1941   LLVM_DEBUG(dbgs() << "\nBefore pruning:\n"; for (unsigned USIdx = 0,
1942                                                    USEnd = RegUnitSets.size();
1943                                                    USIdx < USEnd; ++USIdx) {
1944     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
1945     for (auto &U : RegUnitSets[USIdx].Units)
1946       printRegUnitName(U);
1947     dbgs() << "\n";
1948   });
1949 
1950   // Iteratively prune unit sets.
1951   pruneUnitSets();
1952 
1953   LLVM_DEBUG(dbgs() << "\nBefore union:\n"; for (unsigned USIdx = 0,
1954                                                  USEnd = RegUnitSets.size();
1955                                                  USIdx < USEnd; ++USIdx) {
1956     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
1957     for (auto &U : RegUnitSets[USIdx].Units)
1958       printRegUnitName(U);
1959     dbgs() << "\n";
1960   } dbgs() << "\nUnion sets:\n");
1961 
1962   // Iterate over all unit sets, including new ones added by this loop.
1963   unsigned NumRegUnitSubSets = RegUnitSets.size();
1964   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1965     // In theory, this is combinatorial. In practice, it needs to be bounded
1966     // by a small number of sets for regpressure to be efficient.
1967     // If the assert is hit, we need to implement pruning.
1968     assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
1969 
1970     // Compare new sets with all original classes.
1971     for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1972          SearchIdx != EndIdx; ++SearchIdx) {
1973       std::set<unsigned> Intersection;
1974       std::set_intersection(RegUnitSets[Idx].Units.begin(),
1975                             RegUnitSets[Idx].Units.end(),
1976                             RegUnitSets[SearchIdx].Units.begin(),
1977                             RegUnitSets[SearchIdx].Units.end(),
1978                             std::inserter(Intersection, Intersection.begin()));
1979       if (Intersection.empty())
1980         continue;
1981 
1982       // Speculatively grow the RegUnitSets to hold the new set.
1983       RegUnitSets.resize(RegUnitSets.size() + 1);
1984       RegUnitSets.back().Name =
1985         RegUnitSets[Idx].Name + "_with_" + RegUnitSets[SearchIdx].Name;
1986 
1987       std::set_union(RegUnitSets[Idx].Units.begin(),
1988                      RegUnitSets[Idx].Units.end(),
1989                      RegUnitSets[SearchIdx].Units.begin(),
1990                      RegUnitSets[SearchIdx].Units.end(),
1991                      std::inserter(RegUnitSets.back().Units,
1992                                    RegUnitSets.back().Units.begin()));
1993 
1994       // Find an existing RegUnitSet, or add the union to the unique sets.
1995       std::vector<RegUnitSet>::const_iterator SetI =
1996         findRegUnitSet(RegUnitSets, RegUnitSets.back());
1997       if (SetI != std::prev(RegUnitSets.end()))
1998         RegUnitSets.pop_back();
1999       else {
2000         LLVM_DEBUG(dbgs() << "UnitSet " << RegUnitSets.size() - 1 << " "
2001                           << RegUnitSets.back().Name << ":";
2002                    for (auto &U
2003                         : RegUnitSets.back().Units) printRegUnitName(U);
2004                    dbgs() << "\n";);
2005       }
2006     }
2007   }
2008 
2009   // Iteratively prune unit sets after inferring supersets.
2010   pruneUnitSets();
2011 
2012   LLVM_DEBUG(
2013       dbgs() << "\n"; for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
2014                            USIdx < USEnd; ++USIdx) {
2015         dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
2016         for (auto &U : RegUnitSets[USIdx].Units)
2017           printRegUnitName(U);
2018         dbgs() << "\n";
2019       });
2020 
2021   // For each register class, list the UnitSets that are supersets.
2022   RegClassUnitSets.resize(RegClasses.size());
2023   int RCIdx = -1;
2024   for (auto &RC : RegClasses) {
2025     ++RCIdx;
2026     if (!RC.Allocatable)
2027       continue;
2028 
2029     // Recompute the sorted list of units in this class.
2030     std::vector<unsigned> RCRegUnits;
2031     RC.buildRegUnitSet(*this, RCRegUnits);
2032 
2033     // Don't increase pressure for unallocatable regclasses.
2034     if (RCRegUnits.empty())
2035       continue;
2036 
2037     LLVM_DEBUG(dbgs() << "RC " << RC.getName() << " Units:\n";
2038                for (auto U
2039                     : RCRegUnits) printRegUnitName(U);
2040                dbgs() << "\n  UnitSetIDs:");
2041 
2042     // Find all supersets.
2043     for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
2044          USIdx != USEnd; ++USIdx) {
2045       if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
2046         LLVM_DEBUG(dbgs() << " " << USIdx);
2047         RegClassUnitSets[RCIdx].push_back(USIdx);
2048       }
2049     }
2050     LLVM_DEBUG(dbgs() << "\n");
2051     assert((!RegClassUnitSets[RCIdx].empty() || !RC.GeneratePressureSet) &&
2052            "missing unit set for regclass");
2053   }
2054 
2055   // For each register unit, ensure that we have the list of UnitSets that
2056   // contain the unit. Normally, this matches an existing list of UnitSets for a
2057   // register class. If not, we create a new entry in RegClassUnitSets as a
2058   // "fake" register class.
2059   for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
2060        UnitIdx < UnitEnd; ++UnitIdx) {
2061     std::vector<unsigned> RUSets;
2062     for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
2063       RegUnitSet &RUSet = RegUnitSets[i];
2064       if (!is_contained(RUSet.Units, UnitIdx))
2065         continue;
2066       RUSets.push_back(i);
2067     }
2068     unsigned RCUnitSetsIdx = 0;
2069     for (unsigned e = RegClassUnitSets.size();
2070          RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
2071       if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
2072         break;
2073       }
2074     }
2075     RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
2076     if (RCUnitSetsIdx == RegClassUnitSets.size()) {
2077       // Create a new list of UnitSets as a "fake" register class.
2078       RegClassUnitSets.resize(RCUnitSetsIdx + 1);
2079       RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
2080     }
2081   }
2082 }
2083 
2084 void CodeGenRegBank::computeRegUnitLaneMasks() {
2085   for (auto &Register : Registers) {
2086     // Create an initial lane mask for all register units.
2087     const auto &RegUnits = Register.getRegUnits();
2088     CodeGenRegister::RegUnitLaneMaskList
2089         RegUnitLaneMasks(RegUnits.count(), LaneBitmask::getNone());
2090     // Iterate through SubRegisters.
2091     typedef CodeGenRegister::SubRegMap SubRegMap;
2092     const SubRegMap &SubRegs = Register.getSubRegs();
2093     for (auto S : SubRegs) {
2094       CodeGenRegister *SubReg = S.second;
2095       // Ignore non-leaf subregisters, their lane masks are fully covered by
2096       // the leaf subregisters anyway.
2097       if (!SubReg->getSubRegs().empty())
2098         continue;
2099       CodeGenSubRegIndex *SubRegIndex = S.first;
2100       const CodeGenRegister *SubRegister = S.second;
2101       LaneBitmask LaneMask = SubRegIndex->LaneMask;
2102       // Distribute LaneMask to Register Units touched.
2103       for (unsigned SUI : SubRegister->getRegUnits()) {
2104         bool Found = false;
2105         unsigned u = 0;
2106         for (unsigned RU : RegUnits) {
2107           if (SUI == RU) {
2108             RegUnitLaneMasks[u] |= LaneMask;
2109             assert(!Found);
2110             Found = true;
2111           }
2112           ++u;
2113         }
2114         (void)Found;
2115         assert(Found);
2116       }
2117     }
2118     Register.setRegUnitLaneMasks(RegUnitLaneMasks);
2119   }
2120 }
2121 
2122 void CodeGenRegBank::computeDerivedInfo() {
2123   computeComposites();
2124   computeSubRegLaneMasks();
2125 
2126   // Compute a weight for each register unit created during getSubRegs.
2127   // This may create adopted register units (with unit # >= NumNativeRegUnits).
2128   computeRegUnitWeights();
2129 
2130   // Compute a unique set of RegUnitSets. One for each RegClass and inferred
2131   // supersets for the union of overlapping sets.
2132   computeRegUnitSets();
2133 
2134   computeRegUnitLaneMasks();
2135 
2136   // Compute register class HasDisjunctSubRegs/CoveredBySubRegs flag.
2137   for (CodeGenRegisterClass &RC : RegClasses) {
2138     RC.HasDisjunctSubRegs = false;
2139     RC.CoveredBySubRegs = true;
2140     for (const CodeGenRegister *Reg : RC.getMembers()) {
2141       RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;
2142       RC.CoveredBySubRegs &= Reg->CoveredBySubRegs;
2143     }
2144   }
2145 
2146   // Get the weight of each set.
2147   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2148     RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
2149 
2150   // Find the order of each set.
2151   RegUnitSetOrder.reserve(RegUnitSets.size());
2152   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2153     RegUnitSetOrder.push_back(Idx);
2154 
2155   llvm::stable_sort(RegUnitSetOrder, [this](unsigned ID1, unsigned ID2) {
2156     return getRegPressureSet(ID1).Units.size() <
2157            getRegPressureSet(ID2).Units.size();
2158   });
2159   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
2160     RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
2161   }
2162 }
2163 
2164 //
2165 // Synthesize missing register class intersections.
2166 //
2167 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
2168 // returns a maximal register class for all X.
2169 //
2170 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
2171   assert(!RegClasses.empty());
2172   // Stash the iterator to the last element so that this loop doesn't visit
2173   // elements added by the getOrCreateSubClass call within it.
2174   for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
2175        I != std::next(E); ++I) {
2176     CodeGenRegisterClass *RC1 = RC;
2177     CodeGenRegisterClass *RC2 = &*I;
2178     if (RC1 == RC2)
2179       continue;
2180 
2181     // Compute the set intersection of RC1 and RC2.
2182     const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
2183     const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
2184     CodeGenRegister::Vec Intersection;
2185     std::set_intersection(Memb1.begin(), Memb1.end(), Memb2.begin(),
2186                           Memb2.end(),
2187                           std::inserter(Intersection, Intersection.begin()),
2188                           deref<std::less<>>());
2189 
2190     // Skip disjoint class pairs.
2191     if (Intersection.empty())
2192       continue;
2193 
2194     // If RC1 and RC2 have different spill sizes or alignments, use the
2195     // stricter one for sub-classing.  If they are equal, prefer RC1.
2196     if (RC2->RSI.hasStricterSpillThan(RC1->RSI))
2197       std::swap(RC1, RC2);
2198 
2199     getOrCreateSubClass(RC1, &Intersection,
2200                         RC1->getName() + "_and_" + RC2->getName());
2201   }
2202 }
2203 
2204 //
2205 // Synthesize missing sub-classes for getSubClassWithSubReg().
2206 //
2207 // Make sure that the set of registers in RC with a given SubIdx sub-register
2208 // form a register class.  Update RC->SubClassWithSubReg.
2209 //
2210 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
2211   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
2212   typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
2213                    deref<std::less<>>>
2214       SubReg2SetMap;
2215 
2216   // Compute the set of registers supporting each SubRegIndex.
2217   SubReg2SetMap SRSets;
2218   for (const auto R : RC->getMembers()) {
2219     if (R->Artificial)
2220       continue;
2221     const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
2222     for (auto I : SRM) {
2223       if (!I.first->Artificial)
2224         SRSets[I.first].push_back(R);
2225     }
2226   }
2227 
2228   for (auto I : SRSets)
2229     sortAndUniqueRegisters(I.second);
2230 
2231   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
2232   // numerical order to visit synthetic indices last.
2233   for (const auto &SubIdx : SubRegIndices) {
2234     if (SubIdx.Artificial)
2235       continue;
2236     SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
2237     // Unsupported SubRegIndex. Skip it.
2238     if (I == SRSets.end())
2239       continue;
2240     // In most cases, all RC registers support the SubRegIndex.
2241     if (I->second.size() == RC->getMembers().size()) {
2242       RC->setSubClassWithSubReg(&SubIdx, RC);
2243       continue;
2244     }
2245     // This is a real subset.  See if we have a matching class.
2246     CodeGenRegisterClass *SubRC =
2247       getOrCreateSubClass(RC, &I->second,
2248                           RC->getName() + "_with_" + I->first->getName());
2249     RC->setSubClassWithSubReg(&SubIdx, SubRC);
2250   }
2251 }
2252 
2253 //
2254 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
2255 //
2256 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
2257 // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
2258 //
2259 
2260 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
2261                                                 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
2262   SmallVector<std::pair<const CodeGenRegister*,
2263                         const CodeGenRegister*>, 16> SSPairs;
2264   BitVector TopoSigs(getNumTopoSigs());
2265 
2266   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
2267   for (auto &SubIdx : SubRegIndices) {
2268     // Skip indexes that aren't fully supported by RC's registers. This was
2269     // computed by inferSubClassWithSubReg() above which should have been
2270     // called first.
2271     if (RC->getSubClassWithSubReg(&SubIdx) != RC)
2272       continue;
2273 
2274     // Build list of (Super, Sub) pairs for this SubIdx.
2275     SSPairs.clear();
2276     TopoSigs.reset();
2277     for (const auto Super : RC->getMembers()) {
2278       const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
2279       assert(Sub && "Missing sub-register");
2280       SSPairs.push_back(std::make_pair(Super, Sub));
2281       TopoSigs.set(Sub->getTopoSig());
2282     }
2283 
2284     // Iterate over sub-register class candidates.  Ignore classes created by
2285     // this loop. They will never be useful.
2286     // Store an iterator to the last element (not end) so that this loop doesn't
2287     // visit newly inserted elements.
2288     assert(!RegClasses.empty());
2289     for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
2290          I != std::next(E); ++I) {
2291       CodeGenRegisterClass &SubRC = *I;
2292       if (SubRC.Artificial)
2293         continue;
2294       // Topological shortcut: SubRC members have the wrong shape.
2295       if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
2296         continue;
2297       // Compute the subset of RC that maps into SubRC.
2298       CodeGenRegister::Vec SubSetVec;
2299       for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
2300         if (SubRC.contains(SSPairs[i].second))
2301           SubSetVec.push_back(SSPairs[i].first);
2302 
2303       if (SubSetVec.empty())
2304         continue;
2305 
2306       // RC injects completely into SubRC.
2307       sortAndUniqueRegisters(SubSetVec);
2308       if (SubSetVec.size() == SSPairs.size()) {
2309         SubRC.addSuperRegClass(&SubIdx, RC);
2310         continue;
2311       }
2312 
2313       // Only a subset of RC maps into SubRC. Make sure it is represented by a
2314       // class.
2315       getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
2316                                           SubIdx.getName() + "_in_" +
2317                                           SubRC.getName());
2318     }
2319   }
2320 }
2321 
2322 //
2323 // Infer missing register classes.
2324 //
2325 void CodeGenRegBank::computeInferredRegisterClasses() {
2326   assert(!RegClasses.empty());
2327   // When this function is called, the register classes have not been sorted
2328   // and assigned EnumValues yet.  That means getSubClasses(),
2329   // getSuperClasses(), and hasSubClass() functions are defunct.
2330 
2331   // Use one-before-the-end so it doesn't move forward when new elements are
2332   // added.
2333   auto FirstNewRC = std::prev(RegClasses.end());
2334 
2335   // Visit all register classes, including the ones being added by the loop.
2336   // Watch out for iterator invalidation here.
2337   for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
2338     CodeGenRegisterClass *RC = &*I;
2339     if (RC->Artificial)
2340       continue;
2341 
2342     // Synthesize answers for getSubClassWithSubReg().
2343     inferSubClassWithSubReg(RC);
2344 
2345     // Synthesize answers for getCommonSubClass().
2346     inferCommonSubClass(RC);
2347 
2348     // Synthesize answers for getMatchingSuperRegClass().
2349     inferMatchingSuperRegClass(RC);
2350 
2351     // New register classes are created while this loop is running, and we need
2352     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
2353     // to match old super-register classes with sub-register classes created
2354     // after inferMatchingSuperRegClass was called.  At this point,
2355     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2356     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
2357     if (I == FirstNewRC) {
2358       auto NextNewRC = std::prev(RegClasses.end());
2359       for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
2360            ++I2)
2361         inferMatchingSuperRegClass(&*I2, E2);
2362       FirstNewRC = NextNewRC;
2363     }
2364   }
2365 }
2366 
2367 /// getRegisterClassForRegister - Find the register class that contains the
2368 /// specified physical register.  If the register is not in a register class,
2369 /// return null. If the register is in multiple classes, and the classes have a
2370 /// superset-subset relationship and the same set of types, return the
2371 /// superclass.  Otherwise return null.
2372 const CodeGenRegisterClass*
2373 CodeGenRegBank::getRegClassForRegister(Record *R) {
2374   const CodeGenRegister *Reg = getReg(R);
2375   const CodeGenRegisterClass *FoundRC = nullptr;
2376   for (const auto &RC : getRegClasses()) {
2377     if (!RC.contains(Reg))
2378       continue;
2379 
2380     // If this is the first class that contains the register,
2381     // make a note of it and go on to the next class.
2382     if (!FoundRC) {
2383       FoundRC = &RC;
2384       continue;
2385     }
2386 
2387     // If a register's classes have different types, return null.
2388     if (RC.getValueTypes() != FoundRC->getValueTypes())
2389       return nullptr;
2390 
2391     // Check to see if the previously found class that contains
2392     // the register is a subclass of the current class. If so,
2393     // prefer the superclass.
2394     if (RC.hasSubClass(FoundRC)) {
2395       FoundRC = &RC;
2396       continue;
2397     }
2398 
2399     // Check to see if the previously found class that contains
2400     // the register is a superclass of the current class. If so,
2401     // prefer the superclass.
2402     if (FoundRC->hasSubClass(&RC))
2403       continue;
2404 
2405     // Multiple classes, and neither is a superclass of the other.
2406     // Return null.
2407     return nullptr;
2408   }
2409   return FoundRC;
2410 }
2411 
2412 const CodeGenRegisterClass *
2413 CodeGenRegBank::getMinimalPhysRegClass(Record *RegRecord,
2414                                        ValueTypeByHwMode *VT) {
2415   const CodeGenRegister *Reg = getReg(RegRecord);
2416   const CodeGenRegisterClass *BestRC = nullptr;
2417   for (const auto &RC : getRegClasses()) {
2418     if ((!VT || RC.hasType(*VT)) &&
2419         RC.contains(Reg) && (!BestRC || BestRC->hasSubClass(&RC)))
2420       BestRC = &RC;
2421   }
2422 
2423   assert(BestRC && "Couldn't find the register class");
2424   return BestRC;
2425 }
2426 
2427 BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
2428   SetVector<const CodeGenRegister*> Set;
2429 
2430   // First add Regs with all sub-registers.
2431   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2432     CodeGenRegister *Reg = getReg(Regs[i]);
2433     if (Set.insert(Reg))
2434       // Reg is new, add all sub-registers.
2435       // The pre-ordering is not important here.
2436       Reg->addSubRegsPreOrder(Set, *this);
2437   }
2438 
2439   // Second, find all super-registers that are completely covered by the set.
2440   for (unsigned i = 0; i != Set.size(); ++i) {
2441     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
2442     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
2443       const CodeGenRegister *Super = SR[j];
2444       if (!Super->CoveredBySubRegs || Set.count(Super))
2445         continue;
2446       // This new super-register is covered by its sub-registers.
2447       bool AllSubsInSet = true;
2448       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2449       for (auto I : SRM)
2450         if (!Set.count(I.second)) {
2451           AllSubsInSet = false;
2452           break;
2453         }
2454       // All sub-registers in Set, add Super as well.
2455       // We will visit Super later to recheck its super-registers.
2456       if (AllSubsInSet)
2457         Set.insert(Super);
2458     }
2459   }
2460 
2461   // Convert to BitVector.
2462   BitVector BV(Registers.size() + 1);
2463   for (unsigned i = 0, e = Set.size(); i != e; ++i)
2464     BV.set(Set[i]->EnumValue);
2465   return BV;
2466 }
2467 
2468 void CodeGenRegBank::printRegUnitName(unsigned Unit) const {
2469   if (Unit < NumNativeRegUnits)
2470     dbgs() << ' ' << RegUnits[Unit].Roots[0]->getName();
2471   else
2472     dbgs() << " #" << Unit;
2473 }
2474