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