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