10b57cec5SDimitry Andric //===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines structures to encapsulate information gleaned from the
100b57cec5SDimitry Andric // target register and register class definitions.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "CodeGenRegisters.h"
150b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
160b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/IntEqClasses.h"
1981ad6265SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
230b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
240b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
250b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
260b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
270b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
280b57cec5SDimitry Andric #include "llvm/TableGen/Error.h"
290b57cec5SDimitry Andric #include "llvm/TableGen/Record.h"
300b57cec5SDimitry Andric #include <algorithm>
310b57cec5SDimitry Andric #include <cassert>
320b57cec5SDimitry Andric #include <cstdint>
330b57cec5SDimitry Andric #include <iterator>
340b57cec5SDimitry Andric #include <map>
350b57cec5SDimitry Andric #include <queue>
360b57cec5SDimitry Andric #include <set>
370b57cec5SDimitry Andric #include <string>
380b57cec5SDimitry Andric #include <tuple>
390b57cec5SDimitry Andric #include <utility>
400b57cec5SDimitry Andric #include <vector>
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric using namespace llvm;
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric #define DEBUG_TYPE "regalloc-emitter"
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
470b57cec5SDimitry Andric //                             CodeGenSubRegIndex
480b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
490b57cec5SDimitry Andric 
CodeGenSubRegIndex(Record * R,unsigned Enum)500b57cec5SDimitry Andric CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
510b57cec5SDimitry Andric   : TheDef(R), EnumValue(Enum), AllSuperRegsCovered(true), Artificial(true) {
525ffd83dbSDimitry Andric   Name = std::string(R->getName());
530b57cec5SDimitry Andric   if (R->getValue("Namespace"))
545ffd83dbSDimitry Andric     Namespace = std::string(R->getValueAsString("Namespace"));
550b57cec5SDimitry Andric   Size = R->getValueAsInt("Size");
560b57cec5SDimitry Andric   Offset = R->getValueAsInt("Offset");
570b57cec5SDimitry Andric }
580b57cec5SDimitry Andric 
CodeGenSubRegIndex(StringRef N,StringRef Nspace,unsigned Enum)590b57cec5SDimitry Andric CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
600b57cec5SDimitry Andric                                        unsigned Enum)
615ffd83dbSDimitry Andric     : TheDef(nullptr), Name(std::string(N)), Namespace(std::string(Nspace)),
625ffd83dbSDimitry Andric       Size(-1), Offset(-1), EnumValue(Enum), AllSuperRegsCovered(true),
635ffd83dbSDimitry Andric       Artificial(true) {}
640b57cec5SDimitry Andric 
getQualifiedName() const650b57cec5SDimitry Andric std::string CodeGenSubRegIndex::getQualifiedName() const {
660b57cec5SDimitry Andric   std::string N = getNamespace();
670b57cec5SDimitry Andric   if (!N.empty())
680b57cec5SDimitry Andric     N += "::";
690b57cec5SDimitry Andric   N += getName();
700b57cec5SDimitry Andric   return N;
710b57cec5SDimitry Andric }
720b57cec5SDimitry Andric 
updateComponents(CodeGenRegBank & RegBank)730b57cec5SDimitry Andric void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
740b57cec5SDimitry Andric   if (!TheDef)
750b57cec5SDimitry Andric     return;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric   std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
780b57cec5SDimitry Andric   if (!Comps.empty()) {
790b57cec5SDimitry Andric     if (Comps.size() != 2)
800b57cec5SDimitry Andric       PrintFatalError(TheDef->getLoc(),
810b57cec5SDimitry Andric                       "ComposedOf must have exactly two entries");
820b57cec5SDimitry Andric     CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
830b57cec5SDimitry Andric     CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
840b57cec5SDimitry Andric     CodeGenSubRegIndex *X = A->addComposite(B, this);
850b57cec5SDimitry Andric     if (X)
860b57cec5SDimitry Andric       PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
870b57cec5SDimitry Andric   }
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric   std::vector<Record*> Parts =
900b57cec5SDimitry Andric     TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
910b57cec5SDimitry Andric   if (!Parts.empty()) {
920b57cec5SDimitry Andric     if (Parts.size() < 2)
930b57cec5SDimitry Andric       PrintFatalError(TheDef->getLoc(),
940b57cec5SDimitry Andric                       "CoveredBySubRegs must have two or more entries");
950b57cec5SDimitry Andric     SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
960b57cec5SDimitry Andric     for (Record *Part : Parts)
970b57cec5SDimitry Andric       IdxParts.push_back(RegBank.getSubRegIdx(Part));
980b57cec5SDimitry Andric     setConcatenationOf(IdxParts);
990b57cec5SDimitry Andric   }
1000b57cec5SDimitry Andric }
1010b57cec5SDimitry Andric 
computeLaneMask() const1020b57cec5SDimitry Andric LaneBitmask CodeGenSubRegIndex::computeLaneMask() const {
1030b57cec5SDimitry Andric   // Already computed?
1040b57cec5SDimitry Andric   if (LaneMask.any())
1050b57cec5SDimitry Andric     return LaneMask;
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric   // Recursion guard, shouldn't be required.
1080b57cec5SDimitry Andric   LaneMask = LaneBitmask::getAll();
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   // The lane mask is simply the union of all sub-indices.
1110b57cec5SDimitry Andric   LaneBitmask M;
1120b57cec5SDimitry Andric   for (const auto &C : Composed)
1130b57cec5SDimitry Andric     M |= C.second->computeLaneMask();
1140b57cec5SDimitry Andric   assert(M.any() && "Missing lane mask, sub-register cycle?");
1150b57cec5SDimitry Andric   LaneMask = M;
1160b57cec5SDimitry Andric   return LaneMask;
1170b57cec5SDimitry Andric }
1180b57cec5SDimitry Andric 
setConcatenationOf(ArrayRef<CodeGenSubRegIndex * > Parts)1190b57cec5SDimitry Andric void CodeGenSubRegIndex::setConcatenationOf(
1200b57cec5SDimitry Andric     ArrayRef<CodeGenSubRegIndex*> Parts) {
1210b57cec5SDimitry Andric   if (ConcatenationOf.empty())
1220b57cec5SDimitry Andric     ConcatenationOf.assign(Parts.begin(), Parts.end());
1230b57cec5SDimitry Andric   else
1240b57cec5SDimitry Andric     assert(std::equal(Parts.begin(), Parts.end(),
1250b57cec5SDimitry Andric                       ConcatenationOf.begin()) && "parts consistent");
1260b57cec5SDimitry Andric }
1270b57cec5SDimitry Andric 
computeConcatTransitiveClosure()1280b57cec5SDimitry Andric void CodeGenSubRegIndex::computeConcatTransitiveClosure() {
1290b57cec5SDimitry Andric   for (SmallVectorImpl<CodeGenSubRegIndex*>::iterator
1300b57cec5SDimitry Andric        I = ConcatenationOf.begin(); I != ConcatenationOf.end(); /*empty*/) {
1310b57cec5SDimitry Andric     CodeGenSubRegIndex *SubIdx = *I;
1320b57cec5SDimitry Andric     SubIdx->computeConcatTransitiveClosure();
1330b57cec5SDimitry Andric #ifndef NDEBUG
1340b57cec5SDimitry Andric     for (CodeGenSubRegIndex *SRI : SubIdx->ConcatenationOf)
1350b57cec5SDimitry Andric       assert(SRI->ConcatenationOf.empty() && "No transitive closure?");
1360b57cec5SDimitry Andric #endif
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric     if (SubIdx->ConcatenationOf.empty()) {
1390b57cec5SDimitry Andric       ++I;
1400b57cec5SDimitry Andric     } else {
1410b57cec5SDimitry Andric       I = ConcatenationOf.erase(I);
1420b57cec5SDimitry Andric       I = ConcatenationOf.insert(I, SubIdx->ConcatenationOf.begin(),
1430b57cec5SDimitry Andric                                  SubIdx->ConcatenationOf.end());
1440b57cec5SDimitry Andric       I += SubIdx->ConcatenationOf.size();
1450b57cec5SDimitry Andric     }
1460b57cec5SDimitry Andric   }
1470b57cec5SDimitry Andric }
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1500b57cec5SDimitry Andric //                              CodeGenRegister
1510b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1520b57cec5SDimitry Andric 
CodeGenRegister(Record * R,unsigned Enum)1530b57cec5SDimitry Andric CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
154fe6060f1SDimitry Andric     : TheDef(R), EnumValue(Enum),
155fe6060f1SDimitry Andric       CostPerUse(R->getValueAsListOfInts("CostPerUse")),
1560b57cec5SDimitry Andric       CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
157bdd1243dSDimitry Andric       HasDisjunctSubRegs(false), Constant(R->getValueAsBit("isConstant")),
158bdd1243dSDimitry Andric       SubRegsComplete(false), SuperRegsComplete(false), TopoSig(~0u) {
1590b57cec5SDimitry Andric   Artificial = R->getValueAsBit("isArtificial");
1600b57cec5SDimitry Andric }
1610b57cec5SDimitry Andric 
buildObjectGraph(CodeGenRegBank & RegBank)1620b57cec5SDimitry Andric void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
1630b57cec5SDimitry Andric   std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
1640b57cec5SDimitry Andric   std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   if (SRIs.size() != SRs.size())
1670b57cec5SDimitry Andric     PrintFatalError(TheDef->getLoc(),
1680b57cec5SDimitry Andric                     "SubRegs and SubRegIndices must have the same size");
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
1710b57cec5SDimitry Andric     ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
1720b57cec5SDimitry Andric     ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
1730b57cec5SDimitry Andric   }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   // Also compute leading super-registers. Each register has a list of
1760b57cec5SDimitry Andric   // covered-by-subregs super-registers where it appears as the first explicit
1770b57cec5SDimitry Andric   // sub-register.
1780b57cec5SDimitry Andric   //
1790b57cec5SDimitry Andric   // This is used by computeSecondarySubRegs() to find candidates.
1800b57cec5SDimitry Andric   if (CoveredBySubRegs && !ExplicitSubRegs.empty())
1810b57cec5SDimitry Andric     ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric   // Add ad hoc alias links. This is a symmetric relationship between two
1840b57cec5SDimitry Andric   // registers, so build a symmetric graph by adding links in both ends.
1850b57cec5SDimitry Andric   std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
1860b57cec5SDimitry Andric   for (Record *Alias : Aliases) {
1870b57cec5SDimitry Andric     CodeGenRegister *Reg = RegBank.getReg(Alias);
1880b57cec5SDimitry Andric     ExplicitAliases.push_back(Reg);
1890b57cec5SDimitry Andric     Reg->ExplicitAliases.push_back(this);
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric }
1920b57cec5SDimitry Andric 
getName() const193e8d8bef9SDimitry Andric StringRef CodeGenRegister::getName() const {
1940b57cec5SDimitry Andric   assert(TheDef && "no def");
1950b57cec5SDimitry Andric   return TheDef->getName();
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric namespace {
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric // Iterate over all register units in a set of registers.
2010b57cec5SDimitry Andric class RegUnitIterator {
2020b57cec5SDimitry Andric   CodeGenRegister::Vec::const_iterator RegI, RegE;
2030b57cec5SDimitry Andric   CodeGenRegister::RegUnitList::iterator UnitI, UnitE;
20481ad6265SDimitry Andric   static CodeGenRegister::RegUnitList Sentinel;
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric public:
RegUnitIterator(const CodeGenRegister::Vec & Regs)2070b57cec5SDimitry Andric   RegUnitIterator(const CodeGenRegister::Vec &Regs):
2080b57cec5SDimitry Andric     RegI(Regs.begin()), RegE(Regs.end()) {
2090b57cec5SDimitry Andric 
21081ad6265SDimitry Andric     if (RegI == RegE) {
21181ad6265SDimitry Andric       UnitI = Sentinel.end();
21281ad6265SDimitry Andric       UnitE = Sentinel.end();
21381ad6265SDimitry Andric     } else {
2140b57cec5SDimitry Andric       UnitI = (*RegI)->getRegUnits().begin();
2150b57cec5SDimitry Andric       UnitE = (*RegI)->getRegUnits().end();
2160b57cec5SDimitry Andric       advance();
2170b57cec5SDimitry Andric     }
2180b57cec5SDimitry Andric   }
2190b57cec5SDimitry Andric 
isValid() const2200b57cec5SDimitry Andric   bool isValid() const { return UnitI != UnitE; }
2210b57cec5SDimitry Andric 
operator *() const2220b57cec5SDimitry Andric   unsigned operator* () const { assert(isValid()); return *UnitI; }
2230b57cec5SDimitry Andric 
getReg() const2240b57cec5SDimitry Andric   const CodeGenRegister *getReg() const { assert(isValid()); return *RegI; }
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   /// Preincrement.  Move to the next unit.
operator ++()2270b57cec5SDimitry Andric   void operator++() {
2280b57cec5SDimitry Andric     assert(isValid() && "Cannot advance beyond the last operand");
2290b57cec5SDimitry Andric     ++UnitI;
2300b57cec5SDimitry Andric     advance();
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric protected:
advance()2340b57cec5SDimitry Andric   void advance() {
2350b57cec5SDimitry Andric     while (UnitI == UnitE) {
2360b57cec5SDimitry Andric       if (++RegI == RegE)
2370b57cec5SDimitry Andric         break;
2380b57cec5SDimitry Andric       UnitI = (*RegI)->getRegUnits().begin();
2390b57cec5SDimitry Andric       UnitE = (*RegI)->getRegUnits().end();
2400b57cec5SDimitry Andric     }
2410b57cec5SDimitry Andric   }
2420b57cec5SDimitry Andric };
2430b57cec5SDimitry Andric 
24481ad6265SDimitry Andric CodeGenRegister::RegUnitList RegUnitIterator::Sentinel;
24581ad6265SDimitry Andric 
2460b57cec5SDimitry Andric } // end anonymous namespace
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric // Return true of this unit appears in RegUnits.
hasRegUnit(CodeGenRegister::RegUnitList & RegUnits,unsigned Unit)2490b57cec5SDimitry Andric static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
2500b57cec5SDimitry Andric   return RegUnits.test(Unit);
2510b57cec5SDimitry Andric }
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric // Inherit register units from subregisters.
2540b57cec5SDimitry Andric // Return true if the RegUnits changed.
inheritRegUnits(CodeGenRegBank & RegBank)2550b57cec5SDimitry Andric bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
2560b57cec5SDimitry Andric   bool changed = false;
2570b57cec5SDimitry Andric   for (const auto &SubReg : SubRegs) {
2580b57cec5SDimitry Andric     CodeGenRegister *SR = SubReg.second;
2590b57cec5SDimitry Andric     // Merge the subregister's units into this register's RegUnits.
2600b57cec5SDimitry Andric     changed |= (RegUnits |= SR->RegUnits);
2610b57cec5SDimitry Andric   }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   return changed;
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric const CodeGenRegister::SubRegMap &
computeSubRegs(CodeGenRegBank & RegBank)2670b57cec5SDimitry Andric CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
2680b57cec5SDimitry Andric   // Only compute this map once.
2690b57cec5SDimitry Andric   if (SubRegsComplete)
2700b57cec5SDimitry Andric     return SubRegs;
2710b57cec5SDimitry Andric   SubRegsComplete = true;
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   HasDisjunctSubRegs = ExplicitSubRegs.size() > 1;
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   // First insert the explicit subregs and make sure they are fully indexed.
2760b57cec5SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
2770b57cec5SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
2780b57cec5SDimitry Andric     CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
2790b57cec5SDimitry Andric     if (!SR->Artificial)
2800b57cec5SDimitry Andric       Idx->Artificial = false;
2810b57cec5SDimitry Andric     if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
2820b57cec5SDimitry Andric       PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
2830b57cec5SDimitry Andric                       " appears twice in Register " + getName());
2840b57cec5SDimitry Andric     // Map explicit sub-registers first, so the names take precedence.
2850b57cec5SDimitry Andric     // The inherited sub-registers are mapped below.
2860b57cec5SDimitry Andric     SubReg2Idx.insert(std::make_pair(SR, Idx));
2870b57cec5SDimitry Andric   }
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric   // Keep track of inherited subregs and how they can be reached.
2900b57cec5SDimitry Andric   SmallPtrSet<CodeGenRegister*, 8> Orphans;
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric   // Clone inherited subregs and place duplicate entries in Orphans.
2930b57cec5SDimitry Andric   // Here the order is important - earlier subregs take precedence.
2940b57cec5SDimitry Andric   for (CodeGenRegister *ESR : ExplicitSubRegs) {
2950b57cec5SDimitry Andric     const SubRegMap &Map = ESR->computeSubRegs(RegBank);
2960b57cec5SDimitry Andric     HasDisjunctSubRegs |= ESR->HasDisjunctSubRegs;
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric     for (const auto &SR : Map) {
2990b57cec5SDimitry Andric       if (!SubRegs.insert(SR).second)
3000b57cec5SDimitry Andric         Orphans.insert(SR.second);
3010b57cec5SDimitry Andric     }
3020b57cec5SDimitry Andric   }
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric   // Expand any composed subreg indices.
3050b57cec5SDimitry Andric   // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
3060b57cec5SDimitry Andric   // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
3070b57cec5SDimitry Andric   // expanded subreg indices recursively.
3080b57cec5SDimitry Andric   SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
3090b57cec5SDimitry Andric   for (unsigned i = 0; i != Indices.size(); ++i) {
3100b57cec5SDimitry Andric     CodeGenSubRegIndex *Idx = Indices[i];
3110b57cec5SDimitry Andric     const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
3120b57cec5SDimitry Andric     CodeGenRegister *SR = SubRegs[Idx];
3130b57cec5SDimitry Andric     const SubRegMap &Map = SR->computeSubRegs(RegBank);
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric     // Look at the possible compositions of Idx.
3160b57cec5SDimitry Andric     // They may not all be supported by SR.
317fe6060f1SDimitry Andric     for (auto Comp : Comps) {
318fe6060f1SDimitry Andric       SubRegMap::const_iterator SRI = Map.find(Comp.first);
3190b57cec5SDimitry Andric       if (SRI == Map.end())
3200b57cec5SDimitry Andric         continue; // Idx + I->first doesn't exist in SR.
3210b57cec5SDimitry Andric       // Add I->second as a name for the subreg SRI->second, assuming it is
3220b57cec5SDimitry Andric       // orphaned, and the name isn't already used for something else.
323fe6060f1SDimitry Andric       if (SubRegs.count(Comp.second) || !Orphans.erase(SRI->second))
3240b57cec5SDimitry Andric         continue;
3250b57cec5SDimitry Andric       // We found a new name for the orphaned sub-register.
326fe6060f1SDimitry Andric       SubRegs.insert(std::make_pair(Comp.second, SRI->second));
327fe6060f1SDimitry Andric       Indices.push_back(Comp.second);
3280b57cec5SDimitry Andric     }
3290b57cec5SDimitry Andric   }
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   // Now Orphans contains the inherited subregisters without a direct index.
3320b57cec5SDimitry Andric   // Create inferred indexes for all missing entries.
3330b57cec5SDimitry Andric   // Work backwards in the Indices vector in order to compose subregs bottom-up.
3340b57cec5SDimitry Andric   // Consider this subreg sequence:
3350b57cec5SDimitry Andric   //
3360b57cec5SDimitry Andric   //   qsub_1 -> dsub_0 -> ssub_0
3370b57cec5SDimitry Andric   //
3380b57cec5SDimitry Andric   // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
3390b57cec5SDimitry Andric   // can be reached in two different ways:
3400b57cec5SDimitry Andric   //
3410b57cec5SDimitry Andric   //   qsub_1 -> ssub_0
3420b57cec5SDimitry Andric   //   dsub_2 -> ssub_0
3430b57cec5SDimitry Andric   //
3440b57cec5SDimitry Andric   // We pick the latter composition because another register may have [dsub_0,
3450b57cec5SDimitry Andric   // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg.  The
3460b57cec5SDimitry Andric   // dsub_2 -> ssub_0 composition can be shared.
3470b57cec5SDimitry Andric   while (!Indices.empty() && !Orphans.empty()) {
3480b57cec5SDimitry Andric     CodeGenSubRegIndex *Idx = Indices.pop_back_val();
3490b57cec5SDimitry Andric     CodeGenRegister *SR = SubRegs[Idx];
3500b57cec5SDimitry Andric     const SubRegMap &Map = SR->computeSubRegs(RegBank);
3510b57cec5SDimitry Andric     for (const auto &SubReg : Map)
3520b57cec5SDimitry Andric       if (Orphans.erase(SubReg.second))
3530b57cec5SDimitry Andric         SubRegs[RegBank.getCompositeSubRegIndex(Idx, SubReg.first)] = SubReg.second;
3540b57cec5SDimitry Andric   }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   // Compute the inverse SubReg -> Idx map.
3570b57cec5SDimitry Andric   for (const auto &SubReg : SubRegs) {
3580b57cec5SDimitry Andric     if (SubReg.second == this) {
3590b57cec5SDimitry Andric       ArrayRef<SMLoc> Loc;
3600b57cec5SDimitry Andric       if (TheDef)
3610b57cec5SDimitry Andric         Loc = TheDef->getLoc();
3620b57cec5SDimitry Andric       PrintFatalError(Loc, "Register " + getName() +
3630b57cec5SDimitry Andric                       " has itself as a sub-register");
3640b57cec5SDimitry Andric     }
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric     // Compute AllSuperRegsCovered.
3670b57cec5SDimitry Andric     if (!CoveredBySubRegs)
3680b57cec5SDimitry Andric       SubReg.first->AllSuperRegsCovered = false;
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric     // Ensure that every sub-register has a unique name.
3710b57cec5SDimitry Andric     DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
3720b57cec5SDimitry Andric       SubReg2Idx.insert(std::make_pair(SubReg.second, SubReg.first)).first;
3730b57cec5SDimitry Andric     if (Ins->second == SubReg.first)
3740b57cec5SDimitry Andric       continue;
3750b57cec5SDimitry Andric     // Trouble: Two different names for SubReg.second.
3760b57cec5SDimitry Andric     ArrayRef<SMLoc> Loc;
3770b57cec5SDimitry Andric     if (TheDef)
3780b57cec5SDimitry Andric       Loc = TheDef->getLoc();
3790b57cec5SDimitry Andric     PrintFatalError(Loc, "Sub-register can't have two names: " +
3800b57cec5SDimitry Andric                   SubReg.second->getName() + " available as " +
3810b57cec5SDimitry Andric                   SubReg.first->getName() + " and " + Ins->second->getName());
3820b57cec5SDimitry Andric   }
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric   // Derive possible names for sub-register concatenations from any explicit
3850b57cec5SDimitry Andric   // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
3860b57cec5SDimitry Andric   // that getConcatSubRegIndex() won't invent any concatenated indices that the
3870b57cec5SDimitry Andric   // user already specified.
3880b57cec5SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
3890b57cec5SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
3900b57cec5SDimitry Andric     if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1 ||
3910b57cec5SDimitry Andric         SR->Artificial)
3920b57cec5SDimitry Andric       continue;
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric     // SR is composed of multiple sub-regs. Find their names in this register.
3950b57cec5SDimitry Andric     SmallVector<CodeGenSubRegIndex*, 8> Parts;
3960b57cec5SDimitry Andric     for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j) {
3970b57cec5SDimitry Andric       CodeGenSubRegIndex &I = *SR->ExplicitSubRegIndices[j];
3980b57cec5SDimitry Andric       if (!I.Artificial)
3990b57cec5SDimitry Andric         Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
4000b57cec5SDimitry Andric     }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric     // Offer this as an existing spelling for the concatenation of Parts.
4030b57cec5SDimitry Andric     CodeGenSubRegIndex &Idx = *ExplicitSubRegIndices[i];
4040b57cec5SDimitry Andric     Idx.setConcatenationOf(Parts);
4050b57cec5SDimitry Andric   }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   // Initialize RegUnitList. Because getSubRegs is called recursively, this
4080b57cec5SDimitry Andric   // processes the register hierarchy in postorder.
4090b57cec5SDimitry Andric   //
4100b57cec5SDimitry Andric   // Inherit all sub-register units. It is good enough to look at the explicit
4110b57cec5SDimitry Andric   // sub-registers, the other registers won't contribute any more units.
4120b57cec5SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
4130b57cec5SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
4140b57cec5SDimitry Andric     RegUnits |= SR->RegUnits;
4150b57cec5SDimitry Andric   }
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   // Absent any ad hoc aliasing, we create one register unit per leaf register.
4180b57cec5SDimitry Andric   // These units correspond to the maximal cliques in the register overlap
4190b57cec5SDimitry Andric   // graph which is optimal.
4200b57cec5SDimitry Andric   //
4210b57cec5SDimitry Andric   // When there is ad hoc aliasing, we simply create one unit per edge in the
4220b57cec5SDimitry Andric   // undirected ad hoc aliasing graph. Technically, we could do better by
4230b57cec5SDimitry Andric   // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
4240b57cec5SDimitry Andric   // are extremely rare anyway (I've never seen one), so we don't bother with
4250b57cec5SDimitry Andric   // the added complexity.
4260b57cec5SDimitry Andric   for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
4270b57cec5SDimitry Andric     CodeGenRegister *AR = ExplicitAliases[i];
4280b57cec5SDimitry Andric     // Only visit each edge once.
4290b57cec5SDimitry Andric     if (AR->SubRegsComplete)
4300b57cec5SDimitry Andric       continue;
4310b57cec5SDimitry Andric     // Create a RegUnit representing this alias edge, and add it to both
4320b57cec5SDimitry Andric     // registers.
4330b57cec5SDimitry Andric     unsigned Unit = RegBank.newRegUnit(this, AR);
4340b57cec5SDimitry Andric     RegUnits.set(Unit);
4350b57cec5SDimitry Andric     AR->RegUnits.set(Unit);
4360b57cec5SDimitry Andric   }
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   // Finally, create units for leaf registers without ad hoc aliases. Note that
4390b57cec5SDimitry Andric   // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
4400b57cec5SDimitry Andric   // necessary. This means the aliasing leaf registers can share a single unit.
4410b57cec5SDimitry Andric   if (RegUnits.empty())
4420b57cec5SDimitry Andric     RegUnits.set(RegBank.newRegUnit(this));
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   // We have now computed the native register units. More may be adopted later
4450b57cec5SDimitry Andric   // for balancing purposes.
4460b57cec5SDimitry Andric   NativeRegUnits = RegUnits;
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric   return SubRegs;
4490b57cec5SDimitry Andric }
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric // In a register that is covered by its sub-registers, try to find redundant
4520b57cec5SDimitry Andric // sub-registers. For example:
4530b57cec5SDimitry Andric //
4540b57cec5SDimitry Andric //   QQ0 = {Q0, Q1}
4550b57cec5SDimitry Andric //   Q0 = {D0, D1}
4560b57cec5SDimitry Andric //   Q1 = {D2, D3}
4570b57cec5SDimitry Andric //
4580b57cec5SDimitry Andric // We can infer that D1_D2 is also a sub-register, even if it wasn't named in
4590b57cec5SDimitry Andric // the register definition.
4600b57cec5SDimitry Andric //
4610b57cec5SDimitry Andric // The explicitly specified registers form a tree. This function discovers
4620b57cec5SDimitry Andric // sub-register relationships that would force a DAG.
4630b57cec5SDimitry Andric //
computeSecondarySubRegs(CodeGenRegBank & RegBank)4640b57cec5SDimitry Andric void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
4650b57cec5SDimitry Andric   SmallVector<SubRegMap::value_type, 8> NewSubRegs;
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   std::queue<std::pair<CodeGenSubRegIndex*,CodeGenRegister*>> SubRegQueue;
4680b57cec5SDimitry Andric   for (std::pair<CodeGenSubRegIndex*,CodeGenRegister*> P : SubRegs)
4690b57cec5SDimitry Andric     SubRegQueue.push(P);
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric   // Look at the leading super-registers of each sub-register. Those are the
4720b57cec5SDimitry Andric   // candidates for new sub-registers, assuming they are fully contained in
4730b57cec5SDimitry Andric   // this register.
4740b57cec5SDimitry Andric   while (!SubRegQueue.empty()) {
4750b57cec5SDimitry Andric     CodeGenSubRegIndex *SubRegIdx;
4760b57cec5SDimitry Andric     const CodeGenRegister *SubReg;
4770b57cec5SDimitry Andric     std::tie(SubRegIdx, SubReg) = SubRegQueue.front();
4780b57cec5SDimitry Andric     SubRegQueue.pop();
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric     const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
4810b57cec5SDimitry Andric     for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
4820b57cec5SDimitry Andric       CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
4830b57cec5SDimitry Andric       // Already got this sub-register?
4840b57cec5SDimitry Andric       if (Cand == this || getSubRegIndex(Cand))
4850b57cec5SDimitry Andric         continue;
4860b57cec5SDimitry Andric       // Check if each component of Cand is already a sub-register.
4870b57cec5SDimitry Andric       assert(!Cand->ExplicitSubRegs.empty() &&
4880b57cec5SDimitry Andric              "Super-register has no sub-registers");
4890b57cec5SDimitry Andric       if (Cand->ExplicitSubRegs.size() == 1)
4900b57cec5SDimitry Andric         continue;
4910b57cec5SDimitry Andric       SmallVector<CodeGenSubRegIndex*, 8> Parts;
4920b57cec5SDimitry Andric       // We know that the first component is (SubRegIdx,SubReg). However we
4930b57cec5SDimitry Andric       // may still need to split it into smaller subregister parts.
4940b57cec5SDimitry Andric       assert(Cand->ExplicitSubRegs[0] == SubReg && "LeadingSuperRegs correct");
4950b57cec5SDimitry Andric       assert(getSubRegIndex(SubReg) == SubRegIdx && "LeadingSuperRegs correct");
4960b57cec5SDimitry Andric       for (CodeGenRegister *SubReg : Cand->ExplicitSubRegs) {
4970b57cec5SDimitry Andric         if (CodeGenSubRegIndex *SubRegIdx = getSubRegIndex(SubReg)) {
498e8d8bef9SDimitry Andric           if (SubRegIdx->ConcatenationOf.empty())
4990b57cec5SDimitry Andric             Parts.push_back(SubRegIdx);
500e8d8bef9SDimitry Andric           else
501e8d8bef9SDimitry Andric             append_range(Parts, SubRegIdx->ConcatenationOf);
5020b57cec5SDimitry Andric         } else {
5030b57cec5SDimitry Andric           // Sub-register doesn't exist.
5040b57cec5SDimitry Andric           Parts.clear();
5050b57cec5SDimitry Andric           break;
5060b57cec5SDimitry Andric         }
5070b57cec5SDimitry Andric       }
5080b57cec5SDimitry Andric       // There is nothing to do if some Cand sub-register is not part of this
5090b57cec5SDimitry Andric       // register.
5100b57cec5SDimitry Andric       if (Parts.empty())
5110b57cec5SDimitry Andric         continue;
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric       // Each part of Cand is a sub-register of this. Make the full Cand also
5140b57cec5SDimitry Andric       // a sub-register with a concatenated sub-register index.
5150b57cec5SDimitry Andric       CodeGenSubRegIndex *Concat = RegBank.getConcatSubRegIndex(Parts);
5160b57cec5SDimitry Andric       std::pair<CodeGenSubRegIndex*,CodeGenRegister*> NewSubReg =
5170b57cec5SDimitry Andric           std::make_pair(Concat, Cand);
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric       if (!SubRegs.insert(NewSubReg).second)
5200b57cec5SDimitry Andric         continue;
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric       // We inserted a new subregister.
5230b57cec5SDimitry Andric       NewSubRegs.push_back(NewSubReg);
5240b57cec5SDimitry Andric       SubRegQueue.push(NewSubReg);
5250b57cec5SDimitry Andric       SubReg2Idx.insert(std::make_pair(Cand, Concat));
5260b57cec5SDimitry Andric     }
5270b57cec5SDimitry Andric   }
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric   // Create sub-register index composition maps for the synthesized indices.
5300b57cec5SDimitry Andric   for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
5310b57cec5SDimitry Andric     CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
5320b57cec5SDimitry Andric     CodeGenRegister *NewSubReg = NewSubRegs[i].second;
533fe6060f1SDimitry Andric     for (auto SubReg : NewSubReg->SubRegs) {
534fe6060f1SDimitry Andric       CodeGenSubRegIndex *SubIdx = getSubRegIndex(SubReg.second);
5350b57cec5SDimitry Andric       if (!SubIdx)
5360b57cec5SDimitry Andric         PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
537fe6060f1SDimitry Andric                                               SubReg.second->getName() +
538fe6060f1SDimitry Andric                                               " in " + getName());
539fe6060f1SDimitry Andric       NewIdx->addComposite(SubReg.first, SubIdx);
5400b57cec5SDimitry Andric     }
5410b57cec5SDimitry Andric   }
5420b57cec5SDimitry Andric }
5430b57cec5SDimitry Andric 
computeSuperRegs(CodeGenRegBank & RegBank)5440b57cec5SDimitry Andric void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
5450b57cec5SDimitry Andric   // Only visit each register once.
5460b57cec5SDimitry Andric   if (SuperRegsComplete)
5470b57cec5SDimitry Andric     return;
5480b57cec5SDimitry Andric   SuperRegsComplete = true;
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   // Make sure all sub-registers have been visited first, so the super-reg
5510b57cec5SDimitry Andric   // lists will be topologically ordered.
552fe6060f1SDimitry Andric   for (auto SubReg : SubRegs)
553fe6060f1SDimitry Andric     SubReg.second->computeSuperRegs(RegBank);
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric   // Now add this as a super-register on all sub-registers.
5560b57cec5SDimitry Andric   // Also compute the TopoSigId in post-order.
5570b57cec5SDimitry Andric   TopoSigId Id;
558fe6060f1SDimitry Andric   for (auto SubReg : SubRegs) {
5590b57cec5SDimitry Andric     // Topological signature computed from SubIdx, TopoId(SubReg).
5600b57cec5SDimitry Andric     // Loops and idempotent indices have TopoSig = ~0u.
561fe6060f1SDimitry Andric     Id.push_back(SubReg.first->EnumValue);
562fe6060f1SDimitry Andric     Id.push_back(SubReg.second->TopoSig);
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric     // Don't add duplicate entries.
565fe6060f1SDimitry Andric     if (!SubReg.second->SuperRegs.empty() &&
566fe6060f1SDimitry Andric         SubReg.second->SuperRegs.back() == this)
5670b57cec5SDimitry Andric       continue;
568fe6060f1SDimitry Andric     SubReg.second->SuperRegs.push_back(this);
5690b57cec5SDimitry Andric   }
5700b57cec5SDimitry Andric   TopoSig = RegBank.getTopoSig(Id);
5710b57cec5SDimitry Andric }
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric void
addSubRegsPreOrder(SetVector<const CodeGenRegister * > & OSet,CodeGenRegBank & RegBank) const5740b57cec5SDimitry Andric CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
5750b57cec5SDimitry Andric                                     CodeGenRegBank &RegBank) const {
5760b57cec5SDimitry Andric   assert(SubRegsComplete && "Must precompute sub-registers");
5770b57cec5SDimitry Andric   for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
5780b57cec5SDimitry Andric     CodeGenRegister *SR = ExplicitSubRegs[i];
5790b57cec5SDimitry Andric     if (OSet.insert(SR))
5800b57cec5SDimitry Andric       SR->addSubRegsPreOrder(OSet, RegBank);
5810b57cec5SDimitry Andric   }
5820b57cec5SDimitry Andric   // Add any secondary sub-registers that weren't part of the explicit tree.
583fe6060f1SDimitry Andric   for (auto SubReg : SubRegs)
584fe6060f1SDimitry Andric     OSet.insert(SubReg.second);
5850b57cec5SDimitry Andric }
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric // Get the sum of this register's unit weights.
getWeight(const CodeGenRegBank & RegBank) const5880b57cec5SDimitry Andric unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
5890b57cec5SDimitry Andric   unsigned Weight = 0;
590fe6060f1SDimitry Andric   for (unsigned RegUnit : RegUnits) {
591fe6060f1SDimitry Andric     Weight += RegBank.getRegUnit(RegUnit).Weight;
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric   return Weight;
5940b57cec5SDimitry Andric }
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5970b57cec5SDimitry Andric //                               RegisterTuples
5980b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric // A RegisterTuples def is used to generate pseudo-registers from lists of
6010b57cec5SDimitry Andric // sub-registers. We provide a SetTheory expander class that returns the new
6020b57cec5SDimitry Andric // registers.
6030b57cec5SDimitry Andric namespace {
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric struct TupleExpander : SetTheory::Expander {
6060b57cec5SDimitry Andric   // Reference to SynthDefs in the containing CodeGenRegBank, to keep track of
6070b57cec5SDimitry Andric   // the synthesized definitions for their lifetime.
6080b57cec5SDimitry Andric   std::vector<std::unique_ptr<Record>> &SynthDefs;
6090b57cec5SDimitry Andric 
TupleExpander__anonc56e56b00211::TupleExpander6100b57cec5SDimitry Andric   TupleExpander(std::vector<std::unique_ptr<Record>> &SynthDefs)
6110b57cec5SDimitry Andric       : SynthDefs(SynthDefs) {}
6120b57cec5SDimitry Andric 
expand__anonc56e56b00211::TupleExpander6130b57cec5SDimitry Andric   void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
6140b57cec5SDimitry Andric     std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
6150b57cec5SDimitry Andric     unsigned Dim = Indices.size();
6160b57cec5SDimitry Andric     ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
6170b57cec5SDimitry Andric     if (Dim != SubRegs->size())
6180b57cec5SDimitry Andric       PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
6190b57cec5SDimitry Andric     if (Dim < 2)
6200b57cec5SDimitry Andric       PrintFatalError(Def->getLoc(),
6210b57cec5SDimitry Andric                       "Tuples must have at least 2 sub-registers");
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric     // Evaluate the sub-register lists to be zipped.
6240b57cec5SDimitry Andric     unsigned Length = ~0u;
6250b57cec5SDimitry Andric     SmallVector<SetTheory::RecSet, 4> Lists(Dim);
6260b57cec5SDimitry Andric     for (unsigned i = 0; i != Dim; ++i) {
6270b57cec5SDimitry Andric       ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
6280b57cec5SDimitry Andric       Length = std::min(Length, unsigned(Lists[i].size()));
6290b57cec5SDimitry Andric     }
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric     if (Length == 0)
6320b57cec5SDimitry Andric       return;
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric     // Precompute some types.
6350b57cec5SDimitry Andric     Record *RegisterCl = Def->getRecords().getClass("Register");
6360b57cec5SDimitry Andric     RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
6378bcb0991SDimitry Andric     std::vector<StringRef> RegNames =
6388bcb0991SDimitry Andric       Def->getValueAsListOfStrings("RegAsmNames");
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric     // Zip them up.
64181ad6265SDimitry Andric     RecordKeeper &RK = Def->getRecords();
6420b57cec5SDimitry Andric     for (unsigned n = 0; n != Length; ++n) {
6430b57cec5SDimitry Andric       std::string Name;
6440b57cec5SDimitry Andric       Record *Proto = Lists[0][n];
6450b57cec5SDimitry Andric       std::vector<Init*> Tuple;
6460b57cec5SDimitry Andric       for (unsigned i = 0; i != Dim; ++i) {
6470b57cec5SDimitry Andric         Record *Reg = Lists[i][n];
6480b57cec5SDimitry Andric         if (i) Name += '_';
6490b57cec5SDimitry Andric         Name += Reg->getName();
6500b57cec5SDimitry Andric         Tuple.push_back(DefInit::get(Reg));
6510b57cec5SDimitry Andric       }
6520b57cec5SDimitry Andric 
653fe6060f1SDimitry Andric       // Take the cost list of the first register in the tuple.
654fe6060f1SDimitry Andric       ListInit *CostList = Proto->getValueAsListInit("CostPerUse");
655fe6060f1SDimitry Andric       SmallVector<Init *, 2> CostPerUse;
656fe6060f1SDimitry Andric       CostPerUse.insert(CostPerUse.end(), CostList->begin(), CostList->end());
657fe6060f1SDimitry Andric 
65881ad6265SDimitry Andric       StringInit *AsmName = StringInit::get(RK, "");
6598bcb0991SDimitry Andric       if (!RegNames.empty()) {
6608bcb0991SDimitry Andric         if (RegNames.size() <= n)
6618bcb0991SDimitry Andric           PrintFatalError(Def->getLoc(),
6628bcb0991SDimitry Andric                           "Register tuple definition missing name for '" +
6638bcb0991SDimitry Andric                             Name + "'.");
66481ad6265SDimitry Andric         AsmName = StringInit::get(RK, RegNames[n]);
6658bcb0991SDimitry Andric       }
6668bcb0991SDimitry Andric 
6670b57cec5SDimitry Andric       // Create a new Record representing the synthesized register. This record
6680b57cec5SDimitry Andric       // is only for consumption by CodeGenRegister, it is not added to the
6690b57cec5SDimitry Andric       // RecordKeeper.
6700b57cec5SDimitry Andric       SynthDefs.emplace_back(
6718bcb0991SDimitry Andric           std::make_unique<Record>(Name, Def->getLoc(), Def->getRecords()));
6720b57cec5SDimitry Andric       Record *NewReg = SynthDefs.back().get();
6730b57cec5SDimitry Andric       Elts.insert(NewReg);
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric       // Copy Proto super-classes.
6760b57cec5SDimitry Andric       ArrayRef<std::pair<Record *, SMRange>> Supers = Proto->getSuperClasses();
6770b57cec5SDimitry Andric       for (const auto &SuperPair : Supers)
6780b57cec5SDimitry Andric         NewReg->addSuperClass(SuperPair.first, SuperPair.second);
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric       // Copy Proto fields.
6810b57cec5SDimitry Andric       for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
6820b57cec5SDimitry Andric         RecordVal RV = Proto->getValues()[i];
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric         // Skip existing fields, like NAME.
6850b57cec5SDimitry Andric         if (NewReg->getValue(RV.getNameInit()))
6860b57cec5SDimitry Andric           continue;
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric         StringRef Field = RV.getName();
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric         // Replace the sub-register list with Tuple.
6910b57cec5SDimitry Andric         if (Field == "SubRegs")
6920b57cec5SDimitry Andric           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric         if (Field == "AsmName")
6958bcb0991SDimitry Andric           RV.setValue(AsmName);
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric         // CostPerUse is aggregated from all Tuple members.
6980b57cec5SDimitry Andric         if (Field == "CostPerUse")
699fe6060f1SDimitry Andric           RV.setValue(ListInit::get(CostPerUse, CostList->getElementType()));
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric         // Composite registers are always covered by sub-registers.
7020b57cec5SDimitry Andric         if (Field == "CoveredBySubRegs")
70381ad6265SDimitry Andric           RV.setValue(BitInit::get(RK, true));
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric         // Copy fields from the RegisterTuples def.
7060b57cec5SDimitry Andric         if (Field == "SubRegIndices" ||
7070b57cec5SDimitry Andric             Field == "CompositeIndices") {
7080b57cec5SDimitry Andric           NewReg->addValue(*Def->getValue(Field));
7090b57cec5SDimitry Andric           continue;
7100b57cec5SDimitry Andric         }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric         // Some fields get their default uninitialized value.
7130b57cec5SDimitry Andric         if (Field == "DwarfNumbers" ||
7140b57cec5SDimitry Andric             Field == "DwarfAlias" ||
7150b57cec5SDimitry Andric             Field == "Aliases") {
7160b57cec5SDimitry Andric           if (const RecordVal *DefRV = RegisterCl->getValue(Field))
7170b57cec5SDimitry Andric             NewReg->addValue(*DefRV);
7180b57cec5SDimitry Andric           continue;
7190b57cec5SDimitry Andric         }
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric         // Everything else is copied from Proto.
7220b57cec5SDimitry Andric         NewReg->addValue(RV);
7230b57cec5SDimitry Andric       }
7240b57cec5SDimitry Andric     }
7250b57cec5SDimitry Andric   }
7260b57cec5SDimitry Andric };
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric } // end anonymous namespace
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7310b57cec5SDimitry Andric //                            CodeGenRegisterClass
7320b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7330b57cec5SDimitry Andric 
sortAndUniqueRegisters(CodeGenRegister::Vec & M)7340b57cec5SDimitry Andric static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
7358bcb0991SDimitry Andric   llvm::sort(M, deref<std::less<>>());
7368bcb0991SDimitry Andric   M.erase(std::unique(M.begin(), M.end(), deref<std::equal_to<>>()), M.end());
7370b57cec5SDimitry Andric }
7380b57cec5SDimitry Andric 
CodeGenRegisterClass(CodeGenRegBank & RegBank,Record * R)7390b57cec5SDimitry Andric CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
7405ffd83dbSDimitry Andric     : TheDef(R), Name(std::string(R->getName())),
741349cc55cSDimitry Andric       TopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1), TSFlags(0) {
7425ffd83dbSDimitry Andric   GeneratePressureSet = R->getValueAsBit("GeneratePressureSet");
7430b57cec5SDimitry Andric   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
744e8d8bef9SDimitry Andric   if (TypeList.empty())
745e8d8bef9SDimitry Andric     PrintFatalError(R->getLoc(), "RegTypes list must not be empty!");
7460b57cec5SDimitry Andric   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
7470b57cec5SDimitry Andric     Record *Type = TypeList[i];
7480b57cec5SDimitry Andric     if (!Type->isSubClassOf("ValueType"))
7490b57cec5SDimitry Andric       PrintFatalError(R->getLoc(),
7500b57cec5SDimitry Andric                       "RegTypes list member '" + Type->getName() +
7510b57cec5SDimitry Andric                           "' does not derive from the ValueType class!");
7520b57cec5SDimitry Andric     VTs.push_back(getValueTypeByHwMode(Type, RegBank.getHwModes()));
7530b57cec5SDimitry Andric   }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   // Allocation order 0 is the full set. AltOrders provides others.
7560b57cec5SDimitry Andric   const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
7570b57cec5SDimitry Andric   ListInit *AltOrders = R->getValueAsListInit("AltOrders");
7580b57cec5SDimitry Andric   Orders.resize(1 + AltOrders->size());
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   // Default allocation order always contains all registers.
7610b57cec5SDimitry Andric   Artificial = true;
7620b57cec5SDimitry Andric   for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
7630b57cec5SDimitry Andric     Orders[0].push_back((*Elements)[i]);
7640b57cec5SDimitry Andric     const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
7650b57cec5SDimitry Andric     Members.push_back(Reg);
7660b57cec5SDimitry Andric     Artificial &= Reg->Artificial;
7670b57cec5SDimitry Andric     TopoSigs.set(Reg->getTopoSig());
7680b57cec5SDimitry Andric   }
7690b57cec5SDimitry Andric   sortAndUniqueRegisters(Members);
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric   // Alternative allocation orders may be subsets.
7720b57cec5SDimitry Andric   SetTheory::RecSet Order;
7730b57cec5SDimitry Andric   for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
7740b57cec5SDimitry Andric     RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
7750b57cec5SDimitry Andric     Orders[1 + i].append(Order.begin(), Order.end());
7760b57cec5SDimitry Andric     // Verify that all altorder members are regclass members.
7770b57cec5SDimitry Andric     while (!Order.empty()) {
7780b57cec5SDimitry Andric       CodeGenRegister *Reg = RegBank.getReg(Order.back());
7790b57cec5SDimitry Andric       Order.pop_back();
7800b57cec5SDimitry Andric       if (!contains(Reg))
7810b57cec5SDimitry Andric         PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
7820b57cec5SDimitry Andric                       " is not a class member");
7830b57cec5SDimitry Andric     }
7840b57cec5SDimitry Andric   }
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric   Namespace = R->getValueAsString("Namespace");
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric   if (const RecordVal *RV = R->getValue("RegInfos"))
7890b57cec5SDimitry Andric     if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue()))
7900b57cec5SDimitry Andric       RSI = RegSizeInfoByHwMode(DI->getDef(), RegBank.getHwModes());
7910b57cec5SDimitry Andric   unsigned Size = R->getValueAsInt("Size");
7920b57cec5SDimitry Andric   assert((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&
7930b57cec5SDimitry Andric          "Impossible to determine register size");
7940b57cec5SDimitry Andric   if (!RSI.hasDefault()) {
7950b57cec5SDimitry Andric     RegSizeInfo RI;
7960b57cec5SDimitry Andric     RI.RegSize = RI.SpillSize = Size ? Size
7970b57cec5SDimitry Andric                                      : VTs[0].getSimple().getSizeInBits();
7980b57cec5SDimitry Andric     RI.SpillAlignment = R->getValueAsInt("Alignment");
799fe6060f1SDimitry Andric     RSI.insertRegSizeForMode(DefaultMode, RI);
8000b57cec5SDimitry Andric   }
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric   CopyCost = R->getValueAsInt("CopyCost");
8030b57cec5SDimitry Andric   Allocatable = R->getValueAsBit("isAllocatable");
8040b57cec5SDimitry Andric   AltOrderSelect = R->getValueAsString("AltOrderSelect");
8050b57cec5SDimitry Andric   int AllocationPriority = R->getValueAsInt("AllocationPriority");
806bdd1243dSDimitry Andric   if (!isUInt<5>(AllocationPriority))
807bdd1243dSDimitry Andric     PrintFatalError(R->getLoc(), "AllocationPriority out of range [0,31]");
8080b57cec5SDimitry Andric   this->AllocationPriority = AllocationPriority;
809349cc55cSDimitry Andric 
810bdd1243dSDimitry Andric   GlobalPriority = R->getValueAsBit("GlobalPriority");
811bdd1243dSDimitry Andric 
812349cc55cSDimitry Andric   BitsInit *TSF = R->getValueAsBitsInit("TSFlags");
813349cc55cSDimitry Andric   for (unsigned I = 0, E = TSF->getNumBits(); I != E; ++I) {
814349cc55cSDimitry Andric     BitInit *Bit = cast<BitInit>(TSF->getBit(I));
815349cc55cSDimitry Andric     TSFlags |= uint8_t(Bit->getValue()) << I;
816349cc55cSDimitry Andric   }
8170b57cec5SDimitry Andric }
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric // Create an inferred register class that was missing from the .td files.
8200b57cec5SDimitry Andric // Most properties will be inherited from the closest super-class after the
8210b57cec5SDimitry Andric // class structure has been computed.
CodeGenRegisterClass(CodeGenRegBank & RegBank,StringRef Name,Key Props)8220b57cec5SDimitry Andric CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
8230b57cec5SDimitry Andric                                            StringRef Name, Key Props)
8245ffd83dbSDimitry Andric     : Members(*Props.Members), TheDef(nullptr), Name(std::string(Name)),
8255ffd83dbSDimitry Andric       TopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1), RSI(Props.RSI),
826bdd1243dSDimitry Andric       CopyCost(0), Allocatable(true), AllocationPriority(0),
827bdd1243dSDimitry Andric       GlobalPriority(false), TSFlags(0) {
8280b57cec5SDimitry Andric   Artificial = true;
8295ffd83dbSDimitry Andric   GeneratePressureSet = false;
8300b57cec5SDimitry Andric   for (const auto R : Members) {
8310b57cec5SDimitry Andric     TopoSigs.set(R->getTopoSig());
8320b57cec5SDimitry Andric     Artificial &= R->Artificial;
8330b57cec5SDimitry Andric   }
8340b57cec5SDimitry Andric }
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric // Compute inherited propertied for a synthesized register class.
inheritProperties(CodeGenRegBank & RegBank)8370b57cec5SDimitry Andric void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
8380b57cec5SDimitry Andric   assert(!getDef() && "Only synthesized classes can inherit properties");
8390b57cec5SDimitry Andric   assert(!SuperClasses.empty() && "Synthesized class without super class");
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   // The last super-class is the smallest one.
8420b57cec5SDimitry Andric   CodeGenRegisterClass &Super = *SuperClasses.back();
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric   // Most properties are copied directly.
8450b57cec5SDimitry Andric   // Exceptions are members, size, and alignment
8460b57cec5SDimitry Andric   Namespace = Super.Namespace;
8470b57cec5SDimitry Andric   VTs = Super.VTs;
8480b57cec5SDimitry Andric   CopyCost = Super.CopyCost;
849fe6060f1SDimitry Andric   // Check for allocatable superclasses.
850fe6060f1SDimitry Andric   Allocatable = any_of(SuperClasses, [&](const CodeGenRegisterClass *S) {
851fe6060f1SDimitry Andric     return S->Allocatable;
852fe6060f1SDimitry Andric   });
8530b57cec5SDimitry Andric   AltOrderSelect = Super.AltOrderSelect;
8540b57cec5SDimitry Andric   AllocationPriority = Super.AllocationPriority;
855bdd1243dSDimitry Andric   GlobalPriority = Super.GlobalPriority;
856349cc55cSDimitry Andric   TSFlags = Super.TSFlags;
8575ffd83dbSDimitry Andric   GeneratePressureSet |= Super.GeneratePressureSet;
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric   // Copy all allocation orders, filter out foreign registers from the larger
8600b57cec5SDimitry Andric   // super-class.
8610b57cec5SDimitry Andric   Orders.resize(Super.Orders.size());
8620b57cec5SDimitry Andric   for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
8630b57cec5SDimitry Andric     for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
8640b57cec5SDimitry Andric       if (contains(RegBank.getReg(Super.Orders[i][j])))
8650b57cec5SDimitry Andric         Orders[i].push_back(Super.Orders[i][j]);
8660b57cec5SDimitry Andric }
8670b57cec5SDimitry Andric 
hasType(const ValueTypeByHwMode & VT) const868753f127fSDimitry Andric bool CodeGenRegisterClass::hasType(const ValueTypeByHwMode &VT) const {
869753f127fSDimitry Andric   if (llvm::is_contained(VTs, VT))
870753f127fSDimitry Andric     return true;
871753f127fSDimitry Andric 
872753f127fSDimitry Andric   // If VT is not identical to any of this class's types, but is a simple
873753f127fSDimitry Andric   // type, check if any of the types for this class contain it under some
874753f127fSDimitry Andric   // mode.
87506c3fb27SDimitry Andric   // The motivating example came from RISC-V, where (likely because of being
876753f127fSDimitry Andric   // guarded by "64-bit" predicate), the type of X5 was {*:[i64]}, but the
877753f127fSDimitry Andric   // type in GRC was {*:[i32], m1:[i64]}.
878753f127fSDimitry Andric   if (VT.isSimple()) {
879753f127fSDimitry Andric     MVT T = VT.getSimple();
880753f127fSDimitry Andric     for (const ValueTypeByHwMode &OurVT : VTs) {
881753f127fSDimitry Andric       if (llvm::count_if(OurVT, [T](auto &&P) { return P.second == T; }))
882753f127fSDimitry Andric         return true;
883753f127fSDimitry Andric     }
884753f127fSDimitry Andric   }
885753f127fSDimitry Andric   return false;
886753f127fSDimitry Andric }
887753f127fSDimitry Andric 
contains(const CodeGenRegister * Reg) const8880b57cec5SDimitry Andric bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
8890b57cec5SDimitry Andric   return std::binary_search(Members.begin(), Members.end(), Reg,
8908bcb0991SDimitry Andric                             deref<std::less<>>());
8910b57cec5SDimitry Andric }
8920b57cec5SDimitry Andric 
getWeight(const CodeGenRegBank & RegBank) const8935ffd83dbSDimitry Andric unsigned CodeGenRegisterClass::getWeight(const CodeGenRegBank& RegBank) const {
8945ffd83dbSDimitry Andric   if (TheDef && !TheDef->isValueUnset("Weight"))
8955ffd83dbSDimitry Andric     return TheDef->getValueAsInt("Weight");
8965ffd83dbSDimitry Andric 
8975ffd83dbSDimitry Andric   if (Members.empty() || Artificial)
8985ffd83dbSDimitry Andric     return 0;
8995ffd83dbSDimitry Andric 
9005ffd83dbSDimitry Andric   return (*Members.begin())->getWeight(RegBank);
9015ffd83dbSDimitry Andric }
9025ffd83dbSDimitry Andric 
9030b57cec5SDimitry Andric namespace llvm {
9040b57cec5SDimitry Andric 
operator <<(raw_ostream & OS,const CodeGenRegisterClass::Key & K)9050b57cec5SDimitry Andric   raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
9060b57cec5SDimitry Andric     OS << "{ " << K.RSI;
9070b57cec5SDimitry Andric     for (const auto R : *K.Members)
9080b57cec5SDimitry Andric       OS << ", " << R->getName();
9090b57cec5SDimitry Andric     return OS << " }";
9100b57cec5SDimitry Andric   }
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric } // end namespace llvm
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric // This is a simple lexicographical order that can be used to search for sets.
9150b57cec5SDimitry Andric // It is not the same as the topological order provided by TopoOrderRC.
9160b57cec5SDimitry Andric bool CodeGenRegisterClass::Key::
operator <(const CodeGenRegisterClass::Key & B) const9170b57cec5SDimitry Andric operator<(const CodeGenRegisterClass::Key &B) const {
9180b57cec5SDimitry Andric   assert(Members && B.Members);
9190b57cec5SDimitry Andric   return std::tie(*Members, RSI) < std::tie(*B.Members, B.RSI);
9200b57cec5SDimitry Andric }
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric // Returns true if RC is a strict subclass.
9230b57cec5SDimitry Andric // RC is a sub-class of this class if it is a valid replacement for any
9240b57cec5SDimitry Andric // instruction operand where a register of this classis required. It must
9250b57cec5SDimitry Andric // satisfy these conditions:
9260b57cec5SDimitry Andric //
9270b57cec5SDimitry Andric // 1. All RC registers are also in this.
9280b57cec5SDimitry Andric // 2. The RC spill size must not be smaller than our spill size.
9290b57cec5SDimitry Andric // 3. RC spill alignment must be compatible with ours.
9300b57cec5SDimitry Andric //
testSubClass(const CodeGenRegisterClass * A,const CodeGenRegisterClass * B)9310b57cec5SDimitry Andric static bool testSubClass(const CodeGenRegisterClass *A,
9320b57cec5SDimitry Andric                          const CodeGenRegisterClass *B) {
9330b57cec5SDimitry Andric   return A->RSI.isSubClassOf(B->RSI) &&
9340b57cec5SDimitry Andric          std::includes(A->getMembers().begin(), A->getMembers().end(),
9350b57cec5SDimitry Andric                        B->getMembers().begin(), B->getMembers().end(),
9368bcb0991SDimitry Andric                        deref<std::less<>>());
9370b57cec5SDimitry Andric }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric /// Sorting predicate for register classes.  This provides a topological
9400b57cec5SDimitry Andric /// ordering that arranges all register classes before their sub-classes.
9410b57cec5SDimitry Andric ///
9420b57cec5SDimitry Andric /// Register classes with the same registers, spill size, and alignment form a
9430b57cec5SDimitry Andric /// clique.  They will be ordered alphabetically.
9440b57cec5SDimitry Andric ///
TopoOrderRC(const CodeGenRegisterClass & PA,const CodeGenRegisterClass & PB)9450b57cec5SDimitry Andric static bool TopoOrderRC(const CodeGenRegisterClass &PA,
9460b57cec5SDimitry Andric                         const CodeGenRegisterClass &PB) {
9470b57cec5SDimitry Andric   auto *A = &PA;
9480b57cec5SDimitry Andric   auto *B = &PB;
9490b57cec5SDimitry Andric   if (A == B)
9500b57cec5SDimitry Andric     return false;
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric   if (A->RSI < B->RSI)
9530b57cec5SDimitry Andric     return true;
9540b57cec5SDimitry Andric   if (A->RSI != B->RSI)
9550b57cec5SDimitry Andric     return false;
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric   // Order by descending set size.  Note that the classes' allocation order may
9580b57cec5SDimitry Andric   // not have been computed yet.  The Members set is always vaild.
9590b57cec5SDimitry Andric   if (A->getMembers().size() > B->getMembers().size())
9600b57cec5SDimitry Andric     return true;
9610b57cec5SDimitry Andric   if (A->getMembers().size() < B->getMembers().size())
9620b57cec5SDimitry Andric     return false;
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric   // Finally order by name as a tie breaker.
9650b57cec5SDimitry Andric   return StringRef(A->getName()) < B->getName();
9660b57cec5SDimitry Andric }
9670b57cec5SDimitry Andric 
getNamespaceQualification() const9685f757f3fSDimitry Andric std::string CodeGenRegisterClass::getNamespaceQualification() const {
9695f757f3fSDimitry Andric   return Namespace.empty() ? "" : (Namespace + "::").str();
9705f757f3fSDimitry Andric }
9715f757f3fSDimitry Andric 
getQualifiedName() const9720b57cec5SDimitry Andric std::string CodeGenRegisterClass::getQualifiedName() const {
9735f757f3fSDimitry Andric   return getNamespaceQualification() + getName();
9745f757f3fSDimitry Andric }
9755f757f3fSDimitry Andric 
getIdName() const9765f757f3fSDimitry Andric std::string CodeGenRegisterClass::getIdName() const {
9775f757f3fSDimitry Andric   return getName() + "RegClassID";
9785f757f3fSDimitry Andric }
9795f757f3fSDimitry Andric 
getQualifiedIdName() const9805f757f3fSDimitry Andric std::string CodeGenRegisterClass::getQualifiedIdName() const {
9815f757f3fSDimitry Andric   return getNamespaceQualification() + getIdName();
9820b57cec5SDimitry Andric }
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric // Compute sub-classes of all register classes.
9850b57cec5SDimitry Andric // Assume the classes are ordered topologically.
computeSubClasses(CodeGenRegBank & RegBank)9860b57cec5SDimitry Andric void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
9870b57cec5SDimitry Andric   auto &RegClasses = RegBank.getRegClasses();
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric   // Visit backwards so sub-classes are seen first.
9900b57cec5SDimitry Andric   for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
9910b57cec5SDimitry Andric     CodeGenRegisterClass &RC = *I;
9920b57cec5SDimitry Andric     RC.SubClasses.resize(RegClasses.size());
9930b57cec5SDimitry Andric     RC.SubClasses.set(RC.EnumValue);
9940b57cec5SDimitry Andric     if (RC.Artificial)
9950b57cec5SDimitry Andric       continue;
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric     // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
9980b57cec5SDimitry Andric     for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
9990b57cec5SDimitry Andric       CodeGenRegisterClass &SubRC = *I2;
10000b57cec5SDimitry Andric       if (RC.SubClasses.test(SubRC.EnumValue))
10010b57cec5SDimitry Andric         continue;
10020b57cec5SDimitry Andric       if (!testSubClass(&RC, &SubRC))
10030b57cec5SDimitry Andric         continue;
10040b57cec5SDimitry Andric       // SubRC is a sub-class. Grap all its sub-classes so we won't have to
10050b57cec5SDimitry Andric       // check them again.
10060b57cec5SDimitry Andric       RC.SubClasses |= SubRC.SubClasses;
10070b57cec5SDimitry Andric     }
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric     // Sweep up missed clique members.  They will be immediately preceding RC.
10100b57cec5SDimitry Andric     for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
10110b57cec5SDimitry Andric       RC.SubClasses.set(I2->EnumValue);
10120b57cec5SDimitry Andric   }
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric   // Compute the SuperClasses lists from the SubClasses vectors.
10150b57cec5SDimitry Andric   for (auto &RC : RegClasses) {
10160b57cec5SDimitry Andric     const BitVector &SC = RC.getSubClasses();
10170b57cec5SDimitry Andric     auto I = RegClasses.begin();
10180b57cec5SDimitry Andric     for (int s = 0, next_s = SC.find_first(); next_s != -1;
10190b57cec5SDimitry Andric          next_s = SC.find_next(s)) {
10200b57cec5SDimitry Andric       std::advance(I, next_s - s);
10210b57cec5SDimitry Andric       s = next_s;
10220b57cec5SDimitry Andric       if (&*I == &RC)
10230b57cec5SDimitry Andric         continue;
10240b57cec5SDimitry Andric       I->SuperClasses.push_back(&RC);
10250b57cec5SDimitry Andric     }
10260b57cec5SDimitry Andric   }
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric   // With the class hierarchy in place, let synthesized register classes inherit
10290b57cec5SDimitry Andric   // properties from their closest super-class. The iteration order here can
10300b57cec5SDimitry Andric   // propagate properties down multiple levels.
10310b57cec5SDimitry Andric   for (auto &RC : RegClasses)
10320b57cec5SDimitry Andric     if (!RC.getDef())
10330b57cec5SDimitry Andric       RC.inheritProperties(RegBank);
10340b57cec5SDimitry Andric }
10350b57cec5SDimitry Andric 
1036bdd1243dSDimitry Andric std::optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
getMatchingSubClassWithSubRegs(CodeGenRegBank & RegBank,const CodeGenSubRegIndex * SubIdx) const10370b57cec5SDimitry Andric CodeGenRegisterClass::getMatchingSubClassWithSubRegs(
10380b57cec5SDimitry Andric     CodeGenRegBank &RegBank, const CodeGenSubRegIndex *SubIdx) const {
10395f757f3fSDimitry Andric   auto WeakSizeOrder = [this](const CodeGenRegisterClass *A,
10400b57cec5SDimitry Andric                               const CodeGenRegisterClass *B) {
10415ffd83dbSDimitry Andric     // If there are multiple, identical register classes, prefer the original
10425ffd83dbSDimitry Andric     // register class.
1043e8d8bef9SDimitry Andric     if (A == B)
1044e8d8bef9SDimitry Andric       return false;
10455ffd83dbSDimitry Andric     if (A->getMembers().size() == B->getMembers().size())
10465ffd83dbSDimitry Andric       return A == this;
10470b57cec5SDimitry Andric     return A->getMembers().size() > B->getMembers().size();
10480b57cec5SDimitry Andric   };
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric   auto &RegClasses = RegBank.getRegClasses();
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric   // Find all the subclasses of this one that fully support the sub-register
10530b57cec5SDimitry Andric   // index and order them by size. BiggestSuperRC should always be first.
10540b57cec5SDimitry Andric   CodeGenRegisterClass *BiggestSuperRegRC = getSubClassWithSubReg(SubIdx);
10550b57cec5SDimitry Andric   if (!BiggestSuperRegRC)
1056bdd1243dSDimitry Andric     return std::nullopt;
10570b57cec5SDimitry Andric   BitVector SuperRegRCsBV = BiggestSuperRegRC->getSubClasses();
10580b57cec5SDimitry Andric   std::vector<CodeGenRegisterClass *> SuperRegRCs;
10590b57cec5SDimitry Andric   for (auto &RC : RegClasses)
10600b57cec5SDimitry Andric     if (SuperRegRCsBV[RC.EnumValue])
10610b57cec5SDimitry Andric       SuperRegRCs.emplace_back(&RC);
10625f757f3fSDimitry Andric   llvm::stable_sort(SuperRegRCs, WeakSizeOrder);
10635ffd83dbSDimitry Andric 
10645ffd83dbSDimitry Andric   assert(SuperRegRCs.front() == BiggestSuperRegRC &&
10655ffd83dbSDimitry Andric          "Biggest class wasn't first");
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric   // Find all the subreg classes and order them by size too.
10680b57cec5SDimitry Andric   std::vector<std::pair<CodeGenRegisterClass *, BitVector>> SuperRegClasses;
10690b57cec5SDimitry Andric   for (auto &RC: RegClasses) {
10700b57cec5SDimitry Andric     BitVector SuperRegClassesBV(RegClasses.size());
10710b57cec5SDimitry Andric     RC.getSuperRegClasses(SubIdx, SuperRegClassesBV);
10720b57cec5SDimitry Andric     if (SuperRegClassesBV.any())
10730b57cec5SDimitry Andric       SuperRegClasses.push_back(std::make_pair(&RC, SuperRegClassesBV));
10740b57cec5SDimitry Andric   }
10755f757f3fSDimitry Andric   llvm::stable_sort(SuperRegClasses,
10760b57cec5SDimitry Andric                     [&](const std::pair<CodeGenRegisterClass *, BitVector> &A,
10770b57cec5SDimitry Andric                         const std::pair<CodeGenRegisterClass *, BitVector> &B) {
10785f757f3fSDimitry Andric                       return WeakSizeOrder(A.first, B.first);
10790b57cec5SDimitry Andric                     });
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   // Find the biggest subclass and subreg class such that R:subidx is in the
10820b57cec5SDimitry Andric   // subreg class for all R in subclass.
10830b57cec5SDimitry Andric   //
10840b57cec5SDimitry Andric   // For example:
10850b57cec5SDimitry Andric   // All registers in X86's GR64 have a sub_32bit subregister but no class
10860b57cec5SDimitry Andric   // exists that contains all the 32-bit subregisters because GR64 contains RIP
10870b57cec5SDimitry Andric   // but GR32 does not contain EIP. Instead, we constrain SuperRegRC to
10880b57cec5SDimitry Andric   // GR32_with_sub_8bit (which is identical to GR32_with_sub_32bit) and then,
10890b57cec5SDimitry Andric   // having excluded RIP, we are able to find a SubRegRC (GR32).
10900b57cec5SDimitry Andric   CodeGenRegisterClass *ChosenSuperRegClass = nullptr;
10910b57cec5SDimitry Andric   CodeGenRegisterClass *SubRegRC = nullptr;
10920b57cec5SDimitry Andric   for (auto *SuperRegRC : SuperRegRCs) {
10930b57cec5SDimitry Andric     for (const auto &SuperRegClassPair : SuperRegClasses) {
10940b57cec5SDimitry Andric       const BitVector &SuperRegClassBV = SuperRegClassPair.second;
10950b57cec5SDimitry Andric       if (SuperRegClassBV[SuperRegRC->EnumValue]) {
10960b57cec5SDimitry Andric         SubRegRC = SuperRegClassPair.first;
10970b57cec5SDimitry Andric         ChosenSuperRegClass = SuperRegRC;
10980b57cec5SDimitry Andric 
10990b57cec5SDimitry Andric         // If SubRegRC is bigger than SuperRegRC then there are members of
11000b57cec5SDimitry Andric         // SubRegRC that don't have super registers via SubIdx. Keep looking to
11010b57cec5SDimitry Andric         // find a better fit and fall back on this one if there isn't one.
11020b57cec5SDimitry Andric         //
11030b57cec5SDimitry Andric         // This is intended to prevent X86 from making odd choices such as
11040b57cec5SDimitry Andric         // picking LOW32_ADDR_ACCESS_RBP instead of GR32 in the example above.
11050b57cec5SDimitry Andric         // LOW32_ADDR_ACCESS_RBP is a valid choice but contains registers that
11060b57cec5SDimitry Andric         // aren't subregisters of SuperRegRC whereas GR32 has a direct 1:1
11070b57cec5SDimitry Andric         // mapping.
11080b57cec5SDimitry Andric         if (SuperRegRC->getMembers().size() >= SubRegRC->getMembers().size())
11090b57cec5SDimitry Andric           return std::make_pair(ChosenSuperRegClass, SubRegRC);
11100b57cec5SDimitry Andric       }
11110b57cec5SDimitry Andric     }
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric     // If we found a fit but it wasn't quite ideal because SubRegRC had excess
11140b57cec5SDimitry Andric     // registers, then we're done.
11150b57cec5SDimitry Andric     if (ChosenSuperRegClass)
11160b57cec5SDimitry Andric       return std::make_pair(ChosenSuperRegClass, SubRegRC);
11170b57cec5SDimitry Andric   }
11180b57cec5SDimitry Andric 
1119bdd1243dSDimitry Andric   return std::nullopt;
11200b57cec5SDimitry Andric }
11210b57cec5SDimitry Andric 
getSuperRegClasses(const CodeGenSubRegIndex * SubIdx,BitVector & Out) const11220b57cec5SDimitry Andric void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
11230b57cec5SDimitry Andric                                               BitVector &Out) const {
11240b57cec5SDimitry Andric   auto FindI = SuperRegClasses.find(SubIdx);
11250b57cec5SDimitry Andric   if (FindI == SuperRegClasses.end())
11260b57cec5SDimitry Andric     return;
11270b57cec5SDimitry Andric   for (CodeGenRegisterClass *RC : FindI->second)
11280b57cec5SDimitry Andric     Out.set(RC->EnumValue);
11290b57cec5SDimitry Andric }
11300b57cec5SDimitry Andric 
11310b57cec5SDimitry Andric // Populate a unique sorted list of units from a register set.
buildRegUnitSet(const CodeGenRegBank & RegBank,std::vector<unsigned> & RegUnits) const11320b57cec5SDimitry Andric void CodeGenRegisterClass::buildRegUnitSet(const CodeGenRegBank &RegBank,
11330b57cec5SDimitry Andric   std::vector<unsigned> &RegUnits) const {
11340b57cec5SDimitry Andric   std::vector<unsigned> TmpUnits;
11350b57cec5SDimitry Andric   for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI) {
11360b57cec5SDimitry Andric     const RegUnit &RU = RegBank.getRegUnit(*UnitI);
11370b57cec5SDimitry Andric     if (!RU.Artificial)
11380b57cec5SDimitry Andric       TmpUnits.push_back(*UnitI);
11390b57cec5SDimitry Andric   }
11400b57cec5SDimitry Andric   llvm::sort(TmpUnits);
11410b57cec5SDimitry Andric   std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
11420b57cec5SDimitry Andric                    std::back_inserter(RegUnits));
11430b57cec5SDimitry Andric }
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
114681ad6265SDimitry Andric //                           CodeGenRegisterCategory
114781ad6265SDimitry Andric //===----------------------------------------------------------------------===//
114881ad6265SDimitry Andric 
CodeGenRegisterCategory(CodeGenRegBank & RegBank,Record * R)114981ad6265SDimitry Andric CodeGenRegisterCategory::CodeGenRegisterCategory(CodeGenRegBank &RegBank,
115081ad6265SDimitry Andric                                                  Record *R)
115181ad6265SDimitry Andric     : TheDef(R), Name(std::string(R->getName())) {
115281ad6265SDimitry Andric   for (Record *RegClass : R->getValueAsListOfDefs("Classes"))
115381ad6265SDimitry Andric     Classes.push_back(RegBank.getRegClass(RegClass));
115481ad6265SDimitry Andric }
115581ad6265SDimitry Andric 
115681ad6265SDimitry Andric //===----------------------------------------------------------------------===//
11570b57cec5SDimitry Andric //                               CodeGenRegBank
11580b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11590b57cec5SDimitry Andric 
CodeGenRegBank(RecordKeeper & Records,const CodeGenHwModes & Modes)11600b57cec5SDimitry Andric CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records,
11610b57cec5SDimitry Andric                                const CodeGenHwModes &Modes) : CGH(Modes) {
11620b57cec5SDimitry Andric   // Configure register Sets to understand register classes and tuples.
11630b57cec5SDimitry Andric   Sets.addFieldExpander("RegisterClass", "MemberList");
11640b57cec5SDimitry Andric   Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
11650b57cec5SDimitry Andric   Sets.addExpander("RegisterTuples",
11668bcb0991SDimitry Andric                    std::make_unique<TupleExpander>(SynthDefs));
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   // Read in the user-defined (named) sub-register indices.
11690b57cec5SDimitry Andric   // More indices will be synthesized later.
11700b57cec5SDimitry Andric   std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
11710b57cec5SDimitry Andric   llvm::sort(SRIs, LessRecord());
11720b57cec5SDimitry Andric   for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
11730b57cec5SDimitry Andric     getSubRegIdx(SRIs[i]);
11740b57cec5SDimitry Andric   // Build composite maps from ComposedOf fields.
11750b57cec5SDimitry Andric   for (auto &Idx : SubRegIndices)
11760b57cec5SDimitry Andric     Idx.updateComponents(*this);
11770b57cec5SDimitry Andric 
11785f757f3fSDimitry Andric   // Read in the register and register tuple definitions.
11790b57cec5SDimitry Andric   std::vector<Record *> Regs = Records.getAllDerivedDefinitions("Register");
11805f757f3fSDimitry Andric   if (!Regs.empty() && Regs[0]->isSubClassOf("X86Reg")) {
11815f757f3fSDimitry Andric     // For X86, we need to sort Registers and RegisterTuples together to list
11825f757f3fSDimitry Andric     // new registers and register tuples at a later position. So that we can
11835f757f3fSDimitry Andric     // reduce unnecessary iterations on unsupported registers in LiveVariables.
11845f757f3fSDimitry Andric     // TODO: Remove this logic when migrate from LiveVariables to LiveIntervals
11855f757f3fSDimitry Andric     // completely.
11865f757f3fSDimitry Andric     std::vector<Record *> Tups =
11875f757f3fSDimitry Andric         Records.getAllDerivedDefinitions("RegisterTuples");
11885f757f3fSDimitry Andric     for (Record *R : Tups) {
11895f757f3fSDimitry Andric       // Expand tuples and merge the vectors
11905f757f3fSDimitry Andric       std::vector<Record *> TupRegs = *Sets.expand(R);
11915f757f3fSDimitry Andric       Regs.insert(Regs.end(), TupRegs.begin(), TupRegs.end());
11925f757f3fSDimitry Andric     }
11935f757f3fSDimitry Andric 
11945f757f3fSDimitry Andric     llvm::sort(Regs, LessRecordRegister());
11955f757f3fSDimitry Andric     // Assign the enumeration values.
11965f757f3fSDimitry Andric     for (unsigned i = 0, e = Regs.size(); i != e; ++i)
11975f757f3fSDimitry Andric       getReg(Regs[i]);
11985f757f3fSDimitry Andric   } else {
11990b57cec5SDimitry Andric     llvm::sort(Regs, LessRecordRegister());
12000b57cec5SDimitry Andric     // Assign the enumeration values.
12010b57cec5SDimitry Andric     for (unsigned i = 0, e = Regs.size(); i != e; ++i)
12020b57cec5SDimitry Andric       getReg(Regs[i]);
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric     // Expand tuples and number the new registers.
12050b57cec5SDimitry Andric     std::vector<Record *> Tups =
12060b57cec5SDimitry Andric         Records.getAllDerivedDefinitions("RegisterTuples");
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric     for (Record *R : Tups) {
12090b57cec5SDimitry Andric       std::vector<Record *> TupRegs = *Sets.expand(R);
12100b57cec5SDimitry Andric       llvm::sort(TupRegs, LessRecordRegister());
12110b57cec5SDimitry Andric       for (Record *RC : TupRegs)
12120b57cec5SDimitry Andric         getReg(RC);
12130b57cec5SDimitry Andric     }
12145f757f3fSDimitry Andric   }
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric   // Now all the registers are known. Build the object graph of explicit
12170b57cec5SDimitry Andric   // register-register references.
12180b57cec5SDimitry Andric   for (auto &Reg : Registers)
12190b57cec5SDimitry Andric     Reg.buildObjectGraph(*this);
12200b57cec5SDimitry Andric 
12210b57cec5SDimitry Andric   // Compute register name map.
12220b57cec5SDimitry Andric   for (auto &Reg : Registers)
12230b57cec5SDimitry Andric     // FIXME: This could just be RegistersByName[name] = register, except that
12240b57cec5SDimitry Andric     // causes some failures in MIPS - perhaps they have duplicate register name
12250b57cec5SDimitry Andric     // entries? (or maybe there's a reason for it - I don't know much about this
12260b57cec5SDimitry Andric     // code, just drive-by refactoring)
12270b57cec5SDimitry Andric     RegistersByName.insert(
12280b57cec5SDimitry Andric         std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   // Precompute all sub-register maps.
12310b57cec5SDimitry Andric   // This will create Composite entries for all inferred sub-register indices.
12320b57cec5SDimitry Andric   for (auto &Reg : Registers)
12330b57cec5SDimitry Andric     Reg.computeSubRegs(*this);
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric   // Compute transitive closure of subregister index ConcatenationOf vectors
12360b57cec5SDimitry Andric   // and initialize ConcatIdx map.
12370b57cec5SDimitry Andric   for (CodeGenSubRegIndex &SRI : SubRegIndices) {
12380b57cec5SDimitry Andric     SRI.computeConcatTransitiveClosure();
12390b57cec5SDimitry Andric     if (!SRI.ConcatenationOf.empty())
12400b57cec5SDimitry Andric       ConcatIdx.insert(std::make_pair(
12410b57cec5SDimitry Andric           SmallVector<CodeGenSubRegIndex*,8>(SRI.ConcatenationOf.begin(),
12420b57cec5SDimitry Andric                                              SRI.ConcatenationOf.end()), &SRI));
12430b57cec5SDimitry Andric   }
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric   // Infer even more sub-registers by combining leading super-registers.
12460b57cec5SDimitry Andric   for (auto &Reg : Registers)
12470b57cec5SDimitry Andric     if (Reg.CoveredBySubRegs)
12480b57cec5SDimitry Andric       Reg.computeSecondarySubRegs(*this);
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric   // After the sub-register graph is complete, compute the topologically
12510b57cec5SDimitry Andric   // ordered SuperRegs list.
12520b57cec5SDimitry Andric   for (auto &Reg : Registers)
12530b57cec5SDimitry Andric     Reg.computeSuperRegs(*this);
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric   // For each pair of Reg:SR, if both are non-artificial, mark the
12560b57cec5SDimitry Andric   // corresponding sub-register index as non-artificial.
12570b57cec5SDimitry Andric   for (auto &Reg : Registers) {
12580b57cec5SDimitry Andric     if (Reg.Artificial)
12590b57cec5SDimitry Andric       continue;
12600b57cec5SDimitry Andric     for (auto P : Reg.getSubRegs()) {
12610b57cec5SDimitry Andric       const CodeGenRegister *SR = P.second;
12620b57cec5SDimitry Andric       if (!SR->Artificial)
12630b57cec5SDimitry Andric         P.first->Artificial = false;
12640b57cec5SDimitry Andric     }
12650b57cec5SDimitry Andric   }
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric   // Native register units are associated with a leaf register. They've all been
12680b57cec5SDimitry Andric   // discovered now.
12690b57cec5SDimitry Andric   NumNativeRegUnits = RegUnits.size();
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric   // Read in register class definitions.
12720b57cec5SDimitry Andric   std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
12730b57cec5SDimitry Andric   if (RCs.empty())
12740b57cec5SDimitry Andric     PrintFatalError("No 'RegisterClass' subclasses defined!");
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric   // Allocate user-defined register classes.
12770b57cec5SDimitry Andric   for (auto *R : RCs) {
12780b57cec5SDimitry Andric     RegClasses.emplace_back(*this, R);
12790b57cec5SDimitry Andric     CodeGenRegisterClass &RC = RegClasses.back();
12800b57cec5SDimitry Andric     if (!RC.Artificial)
12810b57cec5SDimitry Andric       addToMaps(&RC);
12820b57cec5SDimitry Andric   }
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   // Infer missing classes to create a full algebra.
12850b57cec5SDimitry Andric   computeInferredRegisterClasses();
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric   // Order register classes topologically and assign enum values.
12880b57cec5SDimitry Andric   RegClasses.sort(TopoOrderRC);
12890b57cec5SDimitry Andric   unsigned i = 0;
12900b57cec5SDimitry Andric   for (auto &RC : RegClasses)
12910b57cec5SDimitry Andric     RC.EnumValue = i++;
12920b57cec5SDimitry Andric   CodeGenRegisterClass::computeSubClasses(*this);
129381ad6265SDimitry Andric 
129481ad6265SDimitry Andric   // Read in the register category definitions.
129581ad6265SDimitry Andric   std::vector<Record *> RCats =
129681ad6265SDimitry Andric       Records.getAllDerivedDefinitions("RegisterCategory");
129781ad6265SDimitry Andric   for (auto *R : RCats)
129881ad6265SDimitry Andric     RegCategories.emplace_back(*this, R);
12990b57cec5SDimitry Andric }
13000b57cec5SDimitry Andric 
13010b57cec5SDimitry Andric // Create a synthetic CodeGenSubRegIndex without a corresponding Record.
13020b57cec5SDimitry Andric CodeGenSubRegIndex*
createSubRegIndex(StringRef Name,StringRef Namespace)13030b57cec5SDimitry Andric CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
13040b57cec5SDimitry Andric   SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
13050b57cec5SDimitry Andric   return &SubRegIndices.back();
13060b57cec5SDimitry Andric }
13070b57cec5SDimitry Andric 
getSubRegIdx(Record * Def)13080b57cec5SDimitry Andric CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
13090b57cec5SDimitry Andric   CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
13100b57cec5SDimitry Andric   if (Idx)
13110b57cec5SDimitry Andric     return Idx;
13120b57cec5SDimitry Andric   SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
13130b57cec5SDimitry Andric   Idx = &SubRegIndices.back();
13140b57cec5SDimitry Andric   return Idx;
13150b57cec5SDimitry Andric }
13160b57cec5SDimitry Andric 
13175ffd83dbSDimitry Andric const CodeGenSubRegIndex *
findSubRegIdx(const Record * Def) const13185ffd83dbSDimitry Andric CodeGenRegBank::findSubRegIdx(const Record* Def) const {
1319e8d8bef9SDimitry Andric   return Def2SubRegIdx.lookup(Def);
13205ffd83dbSDimitry Andric }
13215ffd83dbSDimitry Andric 
getReg(Record * Def)13220b57cec5SDimitry Andric CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
13230b57cec5SDimitry Andric   CodeGenRegister *&Reg = Def2Reg[Def];
13240b57cec5SDimitry Andric   if (Reg)
13250b57cec5SDimitry Andric     return Reg;
13260b57cec5SDimitry Andric   Registers.emplace_back(Def, Registers.size() + 1);
13270b57cec5SDimitry Andric   Reg = &Registers.back();
13280b57cec5SDimitry Andric   return Reg;
13290b57cec5SDimitry Andric }
13300b57cec5SDimitry Andric 
addToMaps(CodeGenRegisterClass * RC)13310b57cec5SDimitry Andric void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
13320b57cec5SDimitry Andric   if (Record *Def = RC->getDef())
13330b57cec5SDimitry Andric     Def2RC.insert(std::make_pair(Def, RC));
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric   // Duplicate classes are rejected by insert().
13360b57cec5SDimitry Andric   // That's OK, we only care about the properties handled by CGRC::Key.
13370b57cec5SDimitry Andric   CodeGenRegisterClass::Key K(*RC);
13380b57cec5SDimitry Andric   Key2RC.insert(std::make_pair(K, RC));
13390b57cec5SDimitry Andric }
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric // Create a synthetic sub-class if it is missing.
13420b57cec5SDimitry Andric CodeGenRegisterClass*
getOrCreateSubClass(const CodeGenRegisterClass * RC,const CodeGenRegister::Vec * Members,StringRef Name)13430b57cec5SDimitry Andric CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
13440b57cec5SDimitry Andric                                     const CodeGenRegister::Vec *Members,
13450b57cec5SDimitry Andric                                     StringRef Name) {
13460b57cec5SDimitry Andric   // Synthetic sub-class has the same size and alignment as RC.
13470b57cec5SDimitry Andric   CodeGenRegisterClass::Key K(Members, RC->RSI);
13480b57cec5SDimitry Andric   RCKeyMap::const_iterator FoundI = Key2RC.find(K);
13490b57cec5SDimitry Andric   if (FoundI != Key2RC.end())
13500b57cec5SDimitry Andric     return FoundI->second;
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric   // Sub-class doesn't exist, create a new one.
13530b57cec5SDimitry Andric   RegClasses.emplace_back(*this, Name, K);
13540b57cec5SDimitry Andric   addToMaps(&RegClasses.back());
13550b57cec5SDimitry Andric   return &RegClasses.back();
13560b57cec5SDimitry Andric }
13570b57cec5SDimitry Andric 
getRegClass(const Record * Def) const13585ffd83dbSDimitry Andric CodeGenRegisterClass *CodeGenRegBank::getRegClass(const Record *Def) const {
13595ffd83dbSDimitry Andric   if (CodeGenRegisterClass *RC = Def2RC.lookup(Def))
13600b57cec5SDimitry Andric     return RC;
13610b57cec5SDimitry Andric 
13620b57cec5SDimitry Andric   PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
13630b57cec5SDimitry Andric }
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric CodeGenSubRegIndex*
getCompositeSubRegIndex(CodeGenSubRegIndex * A,CodeGenSubRegIndex * B)13660b57cec5SDimitry Andric CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
13670b57cec5SDimitry Andric                                         CodeGenSubRegIndex *B) {
13680b57cec5SDimitry Andric   // Look for an existing entry.
13690b57cec5SDimitry Andric   CodeGenSubRegIndex *Comp = A->compose(B);
13700b57cec5SDimitry Andric   if (Comp)
13710b57cec5SDimitry Andric     return Comp;
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric   // None exists, synthesize one.
13740b57cec5SDimitry Andric   std::string Name = A->getName() + "_then_" + B->getName();
13750b57cec5SDimitry Andric   Comp = createSubRegIndex(Name, A->getNamespace());
13760b57cec5SDimitry Andric   A->addComposite(B, Comp);
13770b57cec5SDimitry Andric   return Comp;
13780b57cec5SDimitry Andric }
13790b57cec5SDimitry Andric 
13800b57cec5SDimitry Andric CodeGenSubRegIndex *CodeGenRegBank::
getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *,8> & Parts)13810b57cec5SDimitry Andric getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
13820b57cec5SDimitry Andric   assert(Parts.size() > 1 && "Need two parts to concatenate");
13830b57cec5SDimitry Andric #ifndef NDEBUG
13840b57cec5SDimitry Andric   for (CodeGenSubRegIndex *Idx : Parts) {
13850b57cec5SDimitry Andric     assert(Idx->ConcatenationOf.empty() && "No transitive closure?");
13860b57cec5SDimitry Andric   }
13870b57cec5SDimitry Andric #endif
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric   // Look for an existing entry.
13900b57cec5SDimitry Andric   CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
13910b57cec5SDimitry Andric   if (Idx)
13920b57cec5SDimitry Andric     return Idx;
13930b57cec5SDimitry Andric 
13940b57cec5SDimitry Andric   // None exists, synthesize one.
13950b57cec5SDimitry Andric   std::string Name = Parts.front()->getName();
13960b57cec5SDimitry Andric   // Determine whether all parts are contiguous.
13970b57cec5SDimitry Andric   bool isContinuous = true;
13980b57cec5SDimitry Andric   unsigned Size = Parts.front()->Size;
13990b57cec5SDimitry Andric   unsigned LastOffset = Parts.front()->Offset;
14000b57cec5SDimitry Andric   unsigned LastSize = Parts.front()->Size;
1401bdd1243dSDimitry Andric   unsigned UnknownSize = (uint16_t)-1;
14020b57cec5SDimitry Andric   for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
14030b57cec5SDimitry Andric     Name += '_';
14040b57cec5SDimitry Andric     Name += Parts[i]->getName();
1405bdd1243dSDimitry Andric     if (Size == UnknownSize || Parts[i]->Size == UnknownSize)
1406bdd1243dSDimitry Andric       Size = UnknownSize;
1407bdd1243dSDimitry Andric     else
14080b57cec5SDimitry Andric       Size += Parts[i]->Size;
1409bdd1243dSDimitry Andric     if (LastSize == UnknownSize || Parts[i]->Offset != (LastOffset + LastSize))
14100b57cec5SDimitry Andric       isContinuous = false;
14110b57cec5SDimitry Andric     LastOffset = Parts[i]->Offset;
14120b57cec5SDimitry Andric     LastSize = Parts[i]->Size;
14130b57cec5SDimitry Andric   }
14140b57cec5SDimitry Andric   Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
14150b57cec5SDimitry Andric   Idx->Size = Size;
14160b57cec5SDimitry Andric   Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
14170b57cec5SDimitry Andric   Idx->ConcatenationOf.assign(Parts.begin(), Parts.end());
14180b57cec5SDimitry Andric   return Idx;
14190b57cec5SDimitry Andric }
14200b57cec5SDimitry Andric 
computeComposites()14210b57cec5SDimitry Andric void CodeGenRegBank::computeComposites() {
14220b57cec5SDimitry Andric   using RegMap = std::map<const CodeGenRegister*, const CodeGenRegister*>;
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric   // Subreg -> { Reg->Reg }, where the right-hand side is the mapping from
14250b57cec5SDimitry Andric   // register to (sub)register associated with the action of the left-hand
14260b57cec5SDimitry Andric   // side subregister.
14270b57cec5SDimitry Andric   std::map<const CodeGenSubRegIndex*, RegMap> SubRegAction;
14280b57cec5SDimitry Andric   for (const CodeGenRegister &R : Registers) {
14290b57cec5SDimitry Andric     const CodeGenRegister::SubRegMap &SM = R.getSubRegs();
14300b57cec5SDimitry Andric     for (std::pair<const CodeGenSubRegIndex*, const CodeGenRegister*> P : SM)
14310b57cec5SDimitry Andric       SubRegAction[P.first].insert({&R, P.second});
14320b57cec5SDimitry Andric   }
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric   // Calculate the composition of two subregisters as compositions of their
14350b57cec5SDimitry Andric   // associated actions.
14360b57cec5SDimitry Andric   auto compose = [&SubRegAction] (const CodeGenSubRegIndex *Sub1,
14370b57cec5SDimitry Andric                                   const CodeGenSubRegIndex *Sub2) {
14380b57cec5SDimitry Andric     RegMap C;
14390b57cec5SDimitry Andric     const RegMap &Img1 = SubRegAction.at(Sub1);
14400b57cec5SDimitry Andric     const RegMap &Img2 = SubRegAction.at(Sub2);
14410b57cec5SDimitry Andric     for (std::pair<const CodeGenRegister*, const CodeGenRegister*> P : Img1) {
14420b57cec5SDimitry Andric       auto F = Img2.find(P.second);
14430b57cec5SDimitry Andric       if (F != Img2.end())
14440b57cec5SDimitry Andric         C.insert({P.first, F->second});
14450b57cec5SDimitry Andric     }
14460b57cec5SDimitry Andric     return C;
14470b57cec5SDimitry Andric   };
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric   // Check if the two maps agree on the intersection of their domains.
14500b57cec5SDimitry Andric   auto agree = [] (const RegMap &Map1, const RegMap &Map2) {
14510b57cec5SDimitry Andric     // Technically speaking, an empty map agrees with any other map, but
14520b57cec5SDimitry Andric     // this could flag false positives. We're interested in non-vacuous
14530b57cec5SDimitry Andric     // agreements.
14540b57cec5SDimitry Andric     if (Map1.empty() || Map2.empty())
14550b57cec5SDimitry Andric       return false;
14560b57cec5SDimitry Andric     for (std::pair<const CodeGenRegister*, const CodeGenRegister*> P : Map1) {
14570b57cec5SDimitry Andric       auto F = Map2.find(P.first);
14580b57cec5SDimitry Andric       if (F == Map2.end() || P.second != F->second)
14590b57cec5SDimitry Andric         return false;
14600b57cec5SDimitry Andric     }
14610b57cec5SDimitry Andric     return true;
14620b57cec5SDimitry Andric   };
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric   using CompositePair = std::pair<const CodeGenSubRegIndex*,
14650b57cec5SDimitry Andric                                   const CodeGenSubRegIndex*>;
14660b57cec5SDimitry Andric   SmallSet<CompositePair,4> UserDefined;
14670b57cec5SDimitry Andric   for (const CodeGenSubRegIndex &Idx : SubRegIndices)
14680b57cec5SDimitry Andric     for (auto P : Idx.getComposites())
14690b57cec5SDimitry Andric       UserDefined.insert(std::make_pair(&Idx, P.first));
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric   // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
14720b57cec5SDimitry Andric   // and many registers will share TopoSigs on regular architectures.
14730b57cec5SDimitry Andric   BitVector TopoSigs(getNumTopoSigs());
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric   for (const auto &Reg1 : Registers) {
14760b57cec5SDimitry Andric     // Skip identical subreg structures already processed.
14770b57cec5SDimitry Andric     if (TopoSigs.test(Reg1.getTopoSig()))
14780b57cec5SDimitry Andric       continue;
14790b57cec5SDimitry Andric     TopoSigs.set(Reg1.getTopoSig());
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric     const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1482fe6060f1SDimitry Andric     for (auto I1 : SRM1) {
1483fe6060f1SDimitry Andric       CodeGenSubRegIndex *Idx1 = I1.first;
1484fe6060f1SDimitry Andric       CodeGenRegister *Reg2 = I1.second;
14850b57cec5SDimitry Andric       // Ignore identity compositions.
14860b57cec5SDimitry Andric       if (&Reg1 == Reg2)
14870b57cec5SDimitry Andric         continue;
14880b57cec5SDimitry Andric       const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
14890b57cec5SDimitry Andric       // Try composing Idx1 with another SubRegIndex.
1490fe6060f1SDimitry Andric       for (auto I2 : SRM2) {
1491fe6060f1SDimitry Andric         CodeGenSubRegIndex *Idx2 = I2.first;
1492fe6060f1SDimitry Andric         CodeGenRegister *Reg3 = I2.second;
14930b57cec5SDimitry Andric         // Ignore identity compositions.
14940b57cec5SDimitry Andric         if (Reg2 == Reg3)
14950b57cec5SDimitry Andric           continue;
14960b57cec5SDimitry Andric         // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
14970b57cec5SDimitry Andric         CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
14980b57cec5SDimitry Andric         assert(Idx3 && "Sub-register doesn't have an index");
14990b57cec5SDimitry Andric 
15000b57cec5SDimitry Andric         // Conflicting composition? Emit a warning but allow it.
15010b57cec5SDimitry Andric         if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3)) {
15020b57cec5SDimitry Andric           // If the composition was not user-defined, always emit a warning.
15030b57cec5SDimitry Andric           if (!UserDefined.count({Idx1, Idx2}) ||
15040b57cec5SDimitry Andric               agree(compose(Idx1, Idx2), SubRegAction.at(Idx3)))
15050b57cec5SDimitry Andric             PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
15060b57cec5SDimitry Andric                          " and " + Idx2->getQualifiedName() +
15070b57cec5SDimitry Andric                          " compose ambiguously as " + Prev->getQualifiedName() +
15080b57cec5SDimitry Andric                          " or " + Idx3->getQualifiedName());
15090b57cec5SDimitry Andric         }
15100b57cec5SDimitry Andric       }
15110b57cec5SDimitry Andric     }
15120b57cec5SDimitry Andric   }
15130b57cec5SDimitry Andric }
15140b57cec5SDimitry Andric 
15150b57cec5SDimitry Andric // Compute lane masks. This is similar to register units, but at the
15160b57cec5SDimitry Andric // sub-register index level. Each bit in the lane mask is like a register unit
15170b57cec5SDimitry Andric // class, and two lane masks will have a bit in common if two sub-register
15180b57cec5SDimitry Andric // indices overlap in some register.
15190b57cec5SDimitry Andric //
15200b57cec5SDimitry Andric // Conservatively share a lane mask bit if two sub-register indices overlap in
15210b57cec5SDimitry Andric // some registers, but not in others. That shouldn't happen a lot.
computeSubRegLaneMasks()15220b57cec5SDimitry Andric void CodeGenRegBank::computeSubRegLaneMasks() {
15230b57cec5SDimitry Andric   // First assign individual bits to all the leaf indices.
15240b57cec5SDimitry Andric   unsigned Bit = 0;
15250b57cec5SDimitry Andric   // Determine mask of lanes that cover their registers.
15260b57cec5SDimitry Andric   CoveringLanes = LaneBitmask::getAll();
15270b57cec5SDimitry Andric   for (auto &Idx : SubRegIndices) {
15280b57cec5SDimitry Andric     if (Idx.getComposites().empty()) {
15290b57cec5SDimitry Andric       if (Bit > LaneBitmask::BitWidth) {
15300b57cec5SDimitry Andric         PrintFatalError(
15310b57cec5SDimitry Andric           Twine("Ran out of lanemask bits to represent subregister ")
15320b57cec5SDimitry Andric           + Idx.getName());
15330b57cec5SDimitry Andric       }
15340b57cec5SDimitry Andric       Idx.LaneMask = LaneBitmask::getLane(Bit);
15350b57cec5SDimitry Andric       ++Bit;
15360b57cec5SDimitry Andric     } else {
15370b57cec5SDimitry Andric       Idx.LaneMask = LaneBitmask::getNone();
15380b57cec5SDimitry Andric     }
15390b57cec5SDimitry Andric   }
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric   // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
15420b57cec5SDimitry Andric   // here is that for each possible target subregister we look at the leafs
15430b57cec5SDimitry Andric   // in the subregister graph that compose for this target and create
15440b57cec5SDimitry Andric   // transformation sequences for the lanemasks. Each step in the sequence
15450b57cec5SDimitry Andric   // consists of a bitmask and a bitrotate operation. As the rotation amounts
15460b57cec5SDimitry Andric   // are usually the same for many subregisters we can easily combine the steps
15470b57cec5SDimitry Andric   // by combining the masks.
15480b57cec5SDimitry Andric   for (const auto &Idx : SubRegIndices) {
15490b57cec5SDimitry Andric     const auto &Composites = Idx.getComposites();
15500b57cec5SDimitry Andric     auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
15510b57cec5SDimitry Andric 
15520b57cec5SDimitry Andric     if (Composites.empty()) {
15530b57cec5SDimitry Andric       // Moving from a class with no subregisters we just had a single lane:
15540b57cec5SDimitry Andric       // The subregister must be a leaf subregister and only occupies 1 bit.
15550b57cec5SDimitry Andric       // Move the bit from the class without subregisters into that position.
15560b57cec5SDimitry Andric       unsigned DstBit = Idx.LaneMask.getHighestLane();
15570b57cec5SDimitry Andric       assert(Idx.LaneMask == LaneBitmask::getLane(DstBit) &&
15580b57cec5SDimitry Andric              "Must be a leaf subregister");
15590b57cec5SDimitry Andric       MaskRolPair MaskRol = { LaneBitmask::getLane(0), (uint8_t)DstBit };
15600b57cec5SDimitry Andric       LaneTransforms.push_back(MaskRol);
15610b57cec5SDimitry Andric     } else {
15620b57cec5SDimitry Andric       // Go through all leaf subregisters and find the ones that compose with
15630b57cec5SDimitry Andric       // Idx. These make out all possible valid bits in the lane mask we want to
15640b57cec5SDimitry Andric       // transform. Looking only at the leafs ensure that only a single bit in
15650b57cec5SDimitry Andric       // the mask is set.
15660b57cec5SDimitry Andric       unsigned NextBit = 0;
15670b57cec5SDimitry Andric       for (auto &Idx2 : SubRegIndices) {
15680b57cec5SDimitry Andric         // Skip non-leaf subregisters.
15690b57cec5SDimitry Andric         if (!Idx2.getComposites().empty())
15700b57cec5SDimitry Andric           continue;
15710b57cec5SDimitry Andric         // Replicate the behaviour from the lane mask generation loop above.
15720b57cec5SDimitry Andric         unsigned SrcBit = NextBit;
15730b57cec5SDimitry Andric         LaneBitmask SrcMask = LaneBitmask::getLane(SrcBit);
15740b57cec5SDimitry Andric         if (NextBit < LaneBitmask::BitWidth-1)
15750b57cec5SDimitry Andric           ++NextBit;
15760b57cec5SDimitry Andric         assert(Idx2.LaneMask == SrcMask);
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric         // Get the composed subregister if there is any.
15790b57cec5SDimitry Andric         auto C = Composites.find(&Idx2);
15800b57cec5SDimitry Andric         if (C == Composites.end())
15810b57cec5SDimitry Andric           continue;
15820b57cec5SDimitry Andric         const CodeGenSubRegIndex *Composite = C->second;
15830b57cec5SDimitry Andric         // The Composed subreg should be a leaf subreg too
15840b57cec5SDimitry Andric         assert(Composite->getComposites().empty());
15850b57cec5SDimitry Andric 
15860b57cec5SDimitry Andric         // Create Mask+Rotate operation and merge with existing ops if possible.
15870b57cec5SDimitry Andric         unsigned DstBit = Composite->LaneMask.getHighestLane();
15880b57cec5SDimitry Andric         int Shift = DstBit - SrcBit;
15890b57cec5SDimitry Andric         uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift
15900b57cec5SDimitry Andric                                         : LaneBitmask::BitWidth + Shift;
15910b57cec5SDimitry Andric         for (auto &I : LaneTransforms) {
15920b57cec5SDimitry Andric           if (I.RotateLeft == RotateLeft) {
15930b57cec5SDimitry Andric             I.Mask |= SrcMask;
15940b57cec5SDimitry Andric             SrcMask = LaneBitmask::getNone();
15950b57cec5SDimitry Andric           }
15960b57cec5SDimitry Andric         }
15970b57cec5SDimitry Andric         if (SrcMask.any()) {
15980b57cec5SDimitry Andric           MaskRolPair MaskRol = { SrcMask, RotateLeft };
15990b57cec5SDimitry Andric           LaneTransforms.push_back(MaskRol);
16000b57cec5SDimitry Andric         }
16010b57cec5SDimitry Andric       }
16020b57cec5SDimitry Andric     }
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric     // Optimize if the transformation consists of one step only: Set mask to
16050b57cec5SDimitry Andric     // 0xffffffff (including some irrelevant invalid bits) so that it should
16060b57cec5SDimitry Andric     // merge with more entries later while compressing the table.
16070b57cec5SDimitry Andric     if (LaneTransforms.size() == 1)
16080b57cec5SDimitry Andric       LaneTransforms[0].Mask = LaneBitmask::getAll();
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric     // Further compression optimization: For invalid compositions resulting
16110b57cec5SDimitry Andric     // in a sequence with 0 entries we can just pick any other. Choose
16120b57cec5SDimitry Andric     // Mask 0xffffffff with Rotation 0.
16130b57cec5SDimitry Andric     if (LaneTransforms.size() == 0) {
16140b57cec5SDimitry Andric       MaskRolPair P = { LaneBitmask::getAll(), 0 };
16150b57cec5SDimitry Andric       LaneTransforms.push_back(P);
16160b57cec5SDimitry Andric     }
16170b57cec5SDimitry Andric   }
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric   // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
16200b57cec5SDimitry Andric   // by the sub-register graph? This doesn't occur in any known targets.
16210b57cec5SDimitry Andric 
16220b57cec5SDimitry Andric   // Inherit lanes from composites.
16230b57cec5SDimitry Andric   for (const auto &Idx : SubRegIndices) {
16240b57cec5SDimitry Andric     LaneBitmask Mask = Idx.computeLaneMask();
16250b57cec5SDimitry Andric     // If some super-registers without CoveredBySubRegs use this index, we can
16260b57cec5SDimitry Andric     // no longer assume that the lanes are covering their registers.
16270b57cec5SDimitry Andric     if (!Idx.AllSuperRegsCovered)
16280b57cec5SDimitry Andric       CoveringLanes &= ~Mask;
16290b57cec5SDimitry Andric   }
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric   // Compute lane mask combinations for register classes.
16320b57cec5SDimitry Andric   for (auto &RegClass : RegClasses) {
16330b57cec5SDimitry Andric     LaneBitmask LaneMask;
16340b57cec5SDimitry Andric     for (const auto &SubRegIndex : SubRegIndices) {
16350b57cec5SDimitry Andric       if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)
16360b57cec5SDimitry Andric         continue;
16370b57cec5SDimitry Andric       LaneMask |= SubRegIndex.LaneMask;
16380b57cec5SDimitry Andric     }
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric     // For classes without any subregisters set LaneMask to 1 instead of 0.
16410b57cec5SDimitry Andric     // This makes it easier for client code to handle classes uniformly.
16420b57cec5SDimitry Andric     if (LaneMask.none())
16430b57cec5SDimitry Andric       LaneMask = LaneBitmask::getLane(0);
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric     RegClass.LaneMask = LaneMask;
16460b57cec5SDimitry Andric   }
16470b57cec5SDimitry Andric }
16480b57cec5SDimitry Andric 
16490b57cec5SDimitry Andric namespace {
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric // UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
16520b57cec5SDimitry Andric // the transitive closure of the union of overlapping register
16530b57cec5SDimitry Andric // classes. Together, the UberRegSets form a partition of the registers. If we
16540b57cec5SDimitry Andric // consider overlapping register classes to be connected, then each UberRegSet
16550b57cec5SDimitry Andric // is a set of connected components.
16560b57cec5SDimitry Andric //
16570b57cec5SDimitry Andric // An UberRegSet will likely be a horizontal slice of register names of
16580b57cec5SDimitry Andric // the same width. Nontrivial subregisters should then be in a separate
16590b57cec5SDimitry Andric // UberRegSet. But this property isn't required for valid computation of
16600b57cec5SDimitry Andric // register unit weights.
16610b57cec5SDimitry Andric //
16620b57cec5SDimitry Andric // A Weight field caches the max per-register unit weight in each UberRegSet.
16630b57cec5SDimitry Andric //
16640b57cec5SDimitry Andric // A set of SingularDeterminants flags single units of some register in this set
16650b57cec5SDimitry Andric // for which the unit weight equals the set weight. These units should not have
16660b57cec5SDimitry Andric // their weight increased.
16670b57cec5SDimitry Andric struct UberRegSet {
16680b57cec5SDimitry Andric   CodeGenRegister::Vec Regs;
16690b57cec5SDimitry Andric   unsigned Weight = 0;
16700b57cec5SDimitry Andric   CodeGenRegister::RegUnitList SingularDeterminants;
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric   UberRegSet() = default;
16730b57cec5SDimitry Andric };
16740b57cec5SDimitry Andric 
16750b57cec5SDimitry Andric } // end anonymous namespace
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric // Partition registers into UberRegSets, where each set is the transitive
16780b57cec5SDimitry Andric // closure of the union of overlapping register classes.
16790b57cec5SDimitry Andric //
16800b57cec5SDimitry Andric // UberRegSets[0] is a special non-allocatable set.
computeUberSets(std::vector<UberRegSet> & UberSets,std::vector<UberRegSet * > & RegSets,CodeGenRegBank & RegBank)16810b57cec5SDimitry Andric static void computeUberSets(std::vector<UberRegSet> &UberSets,
16820b57cec5SDimitry Andric                             std::vector<UberRegSet*> &RegSets,
16830b57cec5SDimitry Andric                             CodeGenRegBank &RegBank) {
16840b57cec5SDimitry Andric   const auto &Registers = RegBank.getRegisters();
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric   // The Register EnumValue is one greater than its index into Registers.
16870b57cec5SDimitry Andric   assert(Registers.size() == Registers.back().EnumValue &&
16880b57cec5SDimitry Andric          "register enum value mismatch");
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric   // For simplicitly make the SetID the same as EnumValue.
16910b57cec5SDimitry Andric   IntEqClasses UberSetIDs(Registers.size() + 1);
169206c3fb27SDimitry Andric   BitVector AllocatableRegs(Registers.size() + 1);
16930b57cec5SDimitry Andric   for (auto &RegClass : RegBank.getRegClasses()) {
16940b57cec5SDimitry Andric     if (!RegClass.Allocatable)
16950b57cec5SDimitry Andric       continue;
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric     const CodeGenRegister::Vec &Regs = RegClass.getMembers();
16980b57cec5SDimitry Andric     if (Regs.empty())
16990b57cec5SDimitry Andric       continue;
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric     unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
17020b57cec5SDimitry Andric     assert(USetID && "register number 0 is invalid");
17030b57cec5SDimitry Andric 
170406c3fb27SDimitry Andric     AllocatableRegs.set((*Regs.begin())->EnumValue);
1705349cc55cSDimitry Andric     for (const CodeGenRegister *CGR : llvm::drop_begin(Regs)) {
170606c3fb27SDimitry Andric       AllocatableRegs.set(CGR->EnumValue);
1707349cc55cSDimitry Andric       UberSetIDs.join(USetID, CGR->EnumValue);
17080b57cec5SDimitry Andric     }
17090b57cec5SDimitry Andric   }
17100b57cec5SDimitry Andric   // Combine non-allocatable regs.
17110b57cec5SDimitry Andric   for (const auto &Reg : Registers) {
17120b57cec5SDimitry Andric     unsigned RegNum = Reg.EnumValue;
171306c3fb27SDimitry Andric     if (AllocatableRegs.test(RegNum))
17140b57cec5SDimitry Andric       continue;
17150b57cec5SDimitry Andric 
17160b57cec5SDimitry Andric     UberSetIDs.join(0, RegNum);
17170b57cec5SDimitry Andric   }
17180b57cec5SDimitry Andric   UberSetIDs.compress();
17190b57cec5SDimitry Andric 
17200b57cec5SDimitry Andric   // Make the first UberSet a special unallocatable set.
17210b57cec5SDimitry Andric   unsigned ZeroID = UberSetIDs[0];
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   // Insert Registers into the UberSets formed by union-find.
17240b57cec5SDimitry Andric   // Do not resize after this.
17250b57cec5SDimitry Andric   UberSets.resize(UberSetIDs.getNumClasses());
17260b57cec5SDimitry Andric   unsigned i = 0;
17270b57cec5SDimitry Andric   for (const CodeGenRegister &Reg : Registers) {
17280b57cec5SDimitry Andric     unsigned USetID = UberSetIDs[Reg.EnumValue];
17290b57cec5SDimitry Andric     if (!USetID)
17300b57cec5SDimitry Andric       USetID = ZeroID;
17310b57cec5SDimitry Andric     else if (USetID == ZeroID)
17320b57cec5SDimitry Andric       USetID = 0;
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric     UberRegSet *USet = &UberSets[USetID];
17350b57cec5SDimitry Andric     USet->Regs.push_back(&Reg);
17360b57cec5SDimitry Andric     RegSets[i++] = USet;
17370b57cec5SDimitry Andric   }
17380b57cec5SDimitry Andric }
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric // Recompute each UberSet weight after changing unit weights.
computeUberWeights(std::vector<UberRegSet> & UberSets,CodeGenRegBank & RegBank)17410b57cec5SDimitry Andric static void computeUberWeights(std::vector<UberRegSet> &UberSets,
17420b57cec5SDimitry Andric                                CodeGenRegBank &RegBank) {
17430b57cec5SDimitry Andric   // Skip the first unallocatable set.
17440b57cec5SDimitry Andric   for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
17450b57cec5SDimitry Andric          E = UberSets.end(); I != E; ++I) {
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric     // Initialize all unit weights in this set, and remember the max units/reg.
17480b57cec5SDimitry Andric     const CodeGenRegister *Reg = nullptr;
17490b57cec5SDimitry Andric     unsigned MaxWeight = 0, Weight = 0;
17500b57cec5SDimitry Andric     for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
17510b57cec5SDimitry Andric       if (Reg != UnitI.getReg()) {
17520b57cec5SDimitry Andric         if (Weight > MaxWeight)
17530b57cec5SDimitry Andric           MaxWeight = Weight;
17540b57cec5SDimitry Andric         Reg = UnitI.getReg();
17550b57cec5SDimitry Andric         Weight = 0;
17560b57cec5SDimitry Andric       }
17570b57cec5SDimitry Andric       if (!RegBank.getRegUnit(*UnitI).Artificial) {
17580b57cec5SDimitry Andric         unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
17590b57cec5SDimitry Andric         if (!UWeight) {
17600b57cec5SDimitry Andric           UWeight = 1;
17610b57cec5SDimitry Andric           RegBank.increaseRegUnitWeight(*UnitI, UWeight);
17620b57cec5SDimitry Andric         }
17630b57cec5SDimitry Andric         Weight += UWeight;
17640b57cec5SDimitry Andric       }
17650b57cec5SDimitry Andric     }
17660b57cec5SDimitry Andric     if (Weight > MaxWeight)
17670b57cec5SDimitry Andric       MaxWeight = Weight;
17680b57cec5SDimitry Andric     if (I->Weight != MaxWeight) {
17690b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "UberSet " << I - UberSets.begin() << " Weight "
17700b57cec5SDimitry Andric                         << MaxWeight;
17710b57cec5SDimitry Andric                  for (auto &Unit
17720b57cec5SDimitry Andric                       : I->Regs) dbgs()
17730b57cec5SDimitry Andric                  << " " << Unit->getName();
17740b57cec5SDimitry Andric                  dbgs() << "\n");
17750b57cec5SDimitry Andric       // Update the set weight.
17760b57cec5SDimitry Andric       I->Weight = MaxWeight;
17770b57cec5SDimitry Andric     }
17780b57cec5SDimitry Andric 
17790b57cec5SDimitry Andric     // Find singular determinants.
17800b57cec5SDimitry Andric     for (const auto R : I->Regs) {
17810b57cec5SDimitry Andric       if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
17820b57cec5SDimitry Andric         I->SingularDeterminants |= R->getRegUnits();
17830b57cec5SDimitry Andric       }
17840b57cec5SDimitry Andric     }
17850b57cec5SDimitry Andric   }
17860b57cec5SDimitry Andric }
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric // normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
17890b57cec5SDimitry Andric // a register and its subregisters so that they have the same weight as their
17900b57cec5SDimitry Andric // UberSet. Self-recursion processes the subregister tree in postorder so
17910b57cec5SDimitry Andric // subregisters are normalized first.
17920b57cec5SDimitry Andric //
17930b57cec5SDimitry Andric // Side effects:
17940b57cec5SDimitry Andric // - creates new adopted register units
17950b57cec5SDimitry Andric // - causes superregisters to inherit adopted units
17960b57cec5SDimitry Andric // - increases the weight of "singular" units
17970b57cec5SDimitry Andric // - induces recomputation of UberWeights.
normalizeWeight(CodeGenRegister * Reg,std::vector<UberRegSet> & UberSets,std::vector<UberRegSet * > & RegSets,BitVector & NormalRegs,CodeGenRegister::RegUnitList & NormalUnits,CodeGenRegBank & RegBank)17980b57cec5SDimitry Andric static bool normalizeWeight(CodeGenRegister *Reg,
17990b57cec5SDimitry Andric                             std::vector<UberRegSet> &UberSets,
18000b57cec5SDimitry Andric                             std::vector<UberRegSet*> &RegSets,
18010b57cec5SDimitry Andric                             BitVector &NormalRegs,
18020b57cec5SDimitry Andric                             CodeGenRegister::RegUnitList &NormalUnits,
18030b57cec5SDimitry Andric                             CodeGenRegBank &RegBank) {
18040b57cec5SDimitry Andric   NormalRegs.resize(std::max(Reg->EnumValue + 1, NormalRegs.size()));
18050b57cec5SDimitry Andric   if (NormalRegs.test(Reg->EnumValue))
18060b57cec5SDimitry Andric     return false;
18070b57cec5SDimitry Andric   NormalRegs.set(Reg->EnumValue);
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   bool Changed = false;
18100b57cec5SDimitry Andric   const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1811fe6060f1SDimitry Andric   for (auto SRI : SRM) {
1812fe6060f1SDimitry Andric     if (SRI.second == Reg)
18130b57cec5SDimitry Andric       continue; // self-cycles happen
18140b57cec5SDimitry Andric 
1815fe6060f1SDimitry Andric     Changed |= normalizeWeight(SRI.second, UberSets, RegSets, NormalRegs,
1816fe6060f1SDimitry Andric                                NormalUnits, RegBank);
18170b57cec5SDimitry Andric   }
18180b57cec5SDimitry Andric   // Postorder register normalization.
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   // Inherit register units newly adopted by subregisters.
18210b57cec5SDimitry Andric   if (Reg->inheritRegUnits(RegBank))
18220b57cec5SDimitry Andric     computeUberWeights(UberSets, RegBank);
18230b57cec5SDimitry Andric 
18240b57cec5SDimitry Andric   // Check if this register is too skinny for its UberRegSet.
18250b57cec5SDimitry Andric   UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric   unsigned RegWeight = Reg->getWeight(RegBank);
18280b57cec5SDimitry Andric   if (UberSet->Weight > RegWeight) {
18290b57cec5SDimitry Andric     // A register unit's weight can be adjusted only if it is the singular unit
18300b57cec5SDimitry Andric     // for this register, has not been used to normalize a subregister's set,
18310b57cec5SDimitry Andric     // and has not already been used to singularly determine this UberRegSet.
18320b57cec5SDimitry Andric     unsigned AdjustUnit = *Reg->getRegUnits().begin();
18330b57cec5SDimitry Andric     if (Reg->getRegUnits().count() != 1
18340b57cec5SDimitry Andric         || hasRegUnit(NormalUnits, AdjustUnit)
18350b57cec5SDimitry Andric         || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
18360b57cec5SDimitry Andric       // We don't have an adjustable unit, so adopt a new one.
18370b57cec5SDimitry Andric       AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
18380b57cec5SDimitry Andric       Reg->adoptRegUnit(AdjustUnit);
18390b57cec5SDimitry Andric       // Adopting a unit does not immediately require recomputing set weights.
18400b57cec5SDimitry Andric     }
18410b57cec5SDimitry Andric     else {
18420b57cec5SDimitry Andric       // Adjust the existing single unit.
18430b57cec5SDimitry Andric       if (!RegBank.getRegUnit(AdjustUnit).Artificial)
18440b57cec5SDimitry Andric         RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
18450b57cec5SDimitry Andric       // The unit may be shared among sets and registers within this set.
18460b57cec5SDimitry Andric       computeUberWeights(UberSets, RegBank);
18470b57cec5SDimitry Andric     }
18480b57cec5SDimitry Andric     Changed = true;
18490b57cec5SDimitry Andric   }
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   // Mark these units normalized so superregisters can't change their weights.
18520b57cec5SDimitry Andric   NormalUnits |= Reg->getRegUnits();
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric   return Changed;
18550b57cec5SDimitry Andric }
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric // Compute a weight for each register unit created during getSubRegs.
18580b57cec5SDimitry Andric //
18590b57cec5SDimitry Andric // The goal is that two registers in the same class will have the same weight,
18600b57cec5SDimitry Andric // where each register's weight is defined as sum of its units' weights.
computeRegUnitWeights()18610b57cec5SDimitry Andric void CodeGenRegBank::computeRegUnitWeights() {
18620b57cec5SDimitry Andric   std::vector<UberRegSet> UberSets;
18630b57cec5SDimitry Andric   std::vector<UberRegSet*> RegSets(Registers.size());
18640b57cec5SDimitry Andric   computeUberSets(UberSets, RegSets, *this);
18650b57cec5SDimitry Andric   // UberSets and RegSets are now immutable.
18660b57cec5SDimitry Andric 
18670b57cec5SDimitry Andric   computeUberWeights(UberSets, *this);
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric   // Iterate over each Register, normalizing the unit weights until reaching
18700b57cec5SDimitry Andric   // a fix point.
18710b57cec5SDimitry Andric   unsigned NumIters = 0;
18720b57cec5SDimitry Andric   for (bool Changed = true; Changed; ++NumIters) {
18730b57cec5SDimitry Andric     assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");
187481ad6265SDimitry Andric     (void) NumIters;
18750b57cec5SDimitry Andric     Changed = false;
18760b57cec5SDimitry Andric     for (auto &Reg : Registers) {
18770b57cec5SDimitry Andric       CodeGenRegister::RegUnitList NormalUnits;
18780b57cec5SDimitry Andric       BitVector NormalRegs;
18790b57cec5SDimitry Andric       Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
18800b57cec5SDimitry Andric                                  NormalUnits, *this);
18810b57cec5SDimitry Andric     }
18820b57cec5SDimitry Andric   }
18830b57cec5SDimitry Andric }
18840b57cec5SDimitry Andric 
18850b57cec5SDimitry Andric // Find a set in UniqueSets with the same elements as Set.
18860b57cec5SDimitry Andric // Return an iterator into UniqueSets.
18870b57cec5SDimitry Andric static std::vector<RegUnitSet>::const_iterator
findRegUnitSet(const std::vector<RegUnitSet> & UniqueSets,const RegUnitSet & Set)18880b57cec5SDimitry Andric findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
18890b57cec5SDimitry Andric                const RegUnitSet &Set) {
18900b57cec5SDimitry Andric   std::vector<RegUnitSet>::const_iterator
18910b57cec5SDimitry Andric     I = UniqueSets.begin(), E = UniqueSets.end();
18920b57cec5SDimitry Andric   for(;I != E; ++I) {
18930b57cec5SDimitry Andric     if (I->Units == Set.Units)
18940b57cec5SDimitry Andric       break;
18950b57cec5SDimitry Andric   }
18960b57cec5SDimitry Andric   return I;
18970b57cec5SDimitry Andric }
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric // Return true if the RUSubSet is a subset of RUSuperSet.
isRegUnitSubSet(const std::vector<unsigned> & RUSubSet,const std::vector<unsigned> & RUSuperSet)19000b57cec5SDimitry Andric static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
19010b57cec5SDimitry Andric                             const std::vector<unsigned> &RUSuperSet) {
19020b57cec5SDimitry Andric   return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
19030b57cec5SDimitry Andric                        RUSubSet.begin(), RUSubSet.end());
19040b57cec5SDimitry Andric }
19050b57cec5SDimitry Andric 
19060b57cec5SDimitry Andric /// Iteratively prune unit sets. Prune subsets that are close to the superset,
19070b57cec5SDimitry Andric /// but with one or two registers removed. We occasionally have registers like
19080b57cec5SDimitry Andric /// APSR and PC thrown in with the general registers. We also see many
19090b57cec5SDimitry Andric /// special-purpose register subsets, such as tail-call and Thumb
19100b57cec5SDimitry Andric /// encodings. Generating all possible overlapping sets is combinatorial and
19110b57cec5SDimitry Andric /// overkill for modeling pressure. Ideally we could fix this statically in
19120b57cec5SDimitry Andric /// tablegen by (1) having the target define register classes that only include
19130b57cec5SDimitry Andric /// the allocatable registers and marking other classes as non-allocatable and
19140b57cec5SDimitry Andric /// (2) having a way to mark special purpose classes as "don't-care" classes for
19150b57cec5SDimitry Andric /// the purpose of pressure.  However, we make an attempt to handle targets that
19160b57cec5SDimitry Andric /// are not nicely defined by merging nearly identical register unit sets
19170b57cec5SDimitry Andric /// statically. This generates smaller tables. Then, dynamically, we adjust the
19180b57cec5SDimitry Andric /// set limit by filtering the reserved registers.
19190b57cec5SDimitry Andric ///
19200b57cec5SDimitry Andric /// Merge sets only if the units have the same weight. For example, on ARM,
19210b57cec5SDimitry Andric /// Q-tuples with ssub index 0 include all S regs but also include D16+. We
19220b57cec5SDimitry Andric /// should not expand the S set to include D regs.
pruneUnitSets()19230b57cec5SDimitry Andric void CodeGenRegBank::pruneUnitSets() {
19240b57cec5SDimitry Andric   assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric   // Form an equivalence class of UnitSets with no significant difference.
19270b57cec5SDimitry Andric   std::vector<unsigned> SuperSetIDs;
19280b57cec5SDimitry Andric   for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
19290b57cec5SDimitry Andric        SubIdx != EndIdx; ++SubIdx) {
19300b57cec5SDimitry Andric     const RegUnitSet &SubSet = RegUnitSets[SubIdx];
19310b57cec5SDimitry Andric     unsigned SuperIdx = 0;
19320b57cec5SDimitry Andric     for (; SuperIdx != EndIdx; ++SuperIdx) {
19330b57cec5SDimitry Andric       if (SuperIdx == SubIdx)
19340b57cec5SDimitry Andric         continue;
19350b57cec5SDimitry Andric 
19360b57cec5SDimitry Andric       unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
19370b57cec5SDimitry Andric       const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
19380b57cec5SDimitry Andric       if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
19390b57cec5SDimitry Andric           && (SubSet.Units.size() + 3 > SuperSet.Units.size())
19400b57cec5SDimitry Andric           && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
19410b57cec5SDimitry Andric           && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
19420b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx
19430b57cec5SDimitry Andric                           << "\n");
19440b57cec5SDimitry Andric         // We can pick any of the set names for the merged set. Go for the
19450b57cec5SDimitry Andric         // shortest one to avoid picking the name of one of the classes that are
19460b57cec5SDimitry Andric         // artificially created by tablegen. So "FPR128_lo" instead of
19470b57cec5SDimitry Andric         // "QQQQ_with_qsub3_in_FPR128_lo".
19480b57cec5SDimitry Andric         if (RegUnitSets[SubIdx].Name.size() < RegUnitSets[SuperIdx].Name.size())
19490b57cec5SDimitry Andric           RegUnitSets[SuperIdx].Name = RegUnitSets[SubIdx].Name;
19500b57cec5SDimitry Andric         break;
19510b57cec5SDimitry Andric       }
19520b57cec5SDimitry Andric     }
19530b57cec5SDimitry Andric     if (SuperIdx == EndIdx)
19540b57cec5SDimitry Andric       SuperSetIDs.push_back(SubIdx);
19550b57cec5SDimitry Andric   }
19560b57cec5SDimitry Andric   // Populate PrunedUnitSets with each equivalence class's superset.
19570b57cec5SDimitry Andric   std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
19580b57cec5SDimitry Andric   for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
19590b57cec5SDimitry Andric     unsigned SuperIdx = SuperSetIDs[i];
19600b57cec5SDimitry Andric     PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
19610b57cec5SDimitry Andric     PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
19620b57cec5SDimitry Andric   }
19630b57cec5SDimitry Andric   RegUnitSets.swap(PrunedUnitSets);
19640b57cec5SDimitry Andric }
19650b57cec5SDimitry Andric 
19660b57cec5SDimitry Andric // Create a RegUnitSet for each RegClass that contains all units in the class
19670b57cec5SDimitry Andric // including adopted units that are necessary to model register pressure. Then
19680b57cec5SDimitry Andric // iteratively compute RegUnitSets such that the union of any two overlapping
19690b57cec5SDimitry Andric // RegUnitSets is repreresented.
19700b57cec5SDimitry Andric //
19710b57cec5SDimitry Andric // RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
19720b57cec5SDimitry Andric // RegUnitSet that is a superset of that RegUnitClass.
computeRegUnitSets()19730b57cec5SDimitry Andric void CodeGenRegBank::computeRegUnitSets() {
19740b57cec5SDimitry Andric   assert(RegUnitSets.empty() && "dirty RegUnitSets");
19750b57cec5SDimitry Andric 
19760b57cec5SDimitry Andric   // Compute a unique RegUnitSet for each RegClass.
19770b57cec5SDimitry Andric   auto &RegClasses = getRegClasses();
19780b57cec5SDimitry Andric   for (auto &RC : RegClasses) {
19795ffd83dbSDimitry Andric     if (!RC.Allocatable || RC.Artificial || !RC.GeneratePressureSet)
19800b57cec5SDimitry Andric       continue;
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric     // Speculatively grow the RegUnitSets to hold the new set.
19830b57cec5SDimitry Andric     RegUnitSets.resize(RegUnitSets.size() + 1);
19840b57cec5SDimitry Andric     RegUnitSets.back().Name = RC.getName();
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric     // Compute a sorted list of units in this class.
19870b57cec5SDimitry Andric     RC.buildRegUnitSet(*this, RegUnitSets.back().Units);
19880b57cec5SDimitry Andric 
19890b57cec5SDimitry Andric     // Find an existing RegUnitSet.
19900b57cec5SDimitry Andric     std::vector<RegUnitSet>::const_iterator SetI =
19910b57cec5SDimitry Andric       findRegUnitSet(RegUnitSets, RegUnitSets.back());
19920b57cec5SDimitry Andric     if (SetI != std::prev(RegUnitSets.end()))
19930b57cec5SDimitry Andric       RegUnitSets.pop_back();
19940b57cec5SDimitry Andric   }
19950b57cec5SDimitry Andric 
1996349cc55cSDimitry Andric   if (RegUnitSets.empty())
1997349cc55cSDimitry Andric     PrintFatalError("RegUnitSets cannot be empty!");
1998349cc55cSDimitry Andric 
19990b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nBefore pruning:\n"; for (unsigned USIdx = 0,
20000b57cec5SDimitry Andric                                                    USEnd = RegUnitSets.size();
20010b57cec5SDimitry Andric                                                    USIdx < USEnd; ++USIdx) {
20020b57cec5SDimitry Andric     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
20030b57cec5SDimitry Andric     for (auto &U : RegUnitSets[USIdx].Units)
20040b57cec5SDimitry Andric       printRegUnitName(U);
20050b57cec5SDimitry Andric     dbgs() << "\n";
20060b57cec5SDimitry Andric   });
20070b57cec5SDimitry Andric 
20080b57cec5SDimitry Andric   // Iteratively prune unit sets.
20090b57cec5SDimitry Andric   pruneUnitSets();
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nBefore union:\n"; for (unsigned USIdx = 0,
20120b57cec5SDimitry Andric                                                  USEnd = RegUnitSets.size();
20130b57cec5SDimitry Andric                                                  USIdx < USEnd; ++USIdx) {
20140b57cec5SDimitry Andric     dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
20150b57cec5SDimitry Andric     for (auto &U : RegUnitSets[USIdx].Units)
20160b57cec5SDimitry Andric       printRegUnitName(U);
20170b57cec5SDimitry Andric     dbgs() << "\n";
20180b57cec5SDimitry Andric   } dbgs() << "\nUnion sets:\n");
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric   // Iterate over all unit sets, including new ones added by this loop.
20210b57cec5SDimitry Andric   unsigned NumRegUnitSubSets = RegUnitSets.size();
20220b57cec5SDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
20230b57cec5SDimitry Andric     // In theory, this is combinatorial. In practice, it needs to be bounded
20240b57cec5SDimitry Andric     // by a small number of sets for regpressure to be efficient.
20250b57cec5SDimitry Andric     // If the assert is hit, we need to implement pruning.
20260b57cec5SDimitry Andric     assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric     // Compare new sets with all original classes.
20290b57cec5SDimitry Andric     for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
20300b57cec5SDimitry Andric          SearchIdx != EndIdx; ++SearchIdx) {
20310b57cec5SDimitry Andric       std::set<unsigned> Intersection;
20320b57cec5SDimitry Andric       std::set_intersection(RegUnitSets[Idx].Units.begin(),
20330b57cec5SDimitry Andric                             RegUnitSets[Idx].Units.end(),
20340b57cec5SDimitry Andric                             RegUnitSets[SearchIdx].Units.begin(),
20350b57cec5SDimitry Andric                             RegUnitSets[SearchIdx].Units.end(),
20360b57cec5SDimitry Andric                             std::inserter(Intersection, Intersection.begin()));
20370b57cec5SDimitry Andric       if (Intersection.empty())
20380b57cec5SDimitry Andric         continue;
20390b57cec5SDimitry Andric 
20400b57cec5SDimitry Andric       // Speculatively grow the RegUnitSets to hold the new set.
20410b57cec5SDimitry Andric       RegUnitSets.resize(RegUnitSets.size() + 1);
20420b57cec5SDimitry Andric       RegUnitSets.back().Name =
20435ffd83dbSDimitry Andric         RegUnitSets[Idx].Name + "_with_" + RegUnitSets[SearchIdx].Name;
20440b57cec5SDimitry Andric 
20450b57cec5SDimitry Andric       std::set_union(RegUnitSets[Idx].Units.begin(),
20460b57cec5SDimitry Andric                      RegUnitSets[Idx].Units.end(),
20470b57cec5SDimitry Andric                      RegUnitSets[SearchIdx].Units.begin(),
20480b57cec5SDimitry Andric                      RegUnitSets[SearchIdx].Units.end(),
20490b57cec5SDimitry Andric                      std::inserter(RegUnitSets.back().Units,
20500b57cec5SDimitry Andric                                    RegUnitSets.back().Units.begin()));
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric       // Find an existing RegUnitSet, or add the union to the unique sets.
20530b57cec5SDimitry Andric       std::vector<RegUnitSet>::const_iterator SetI =
20540b57cec5SDimitry Andric         findRegUnitSet(RegUnitSets, RegUnitSets.back());
20550b57cec5SDimitry Andric       if (SetI != std::prev(RegUnitSets.end()))
20560b57cec5SDimitry Andric         RegUnitSets.pop_back();
20570b57cec5SDimitry Andric       else {
20580b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "UnitSet " << RegUnitSets.size() - 1 << " "
20590b57cec5SDimitry Andric                           << RegUnitSets.back().Name << ":";
20600b57cec5SDimitry Andric                    for (auto &U
20610b57cec5SDimitry Andric                         : RegUnitSets.back().Units) printRegUnitName(U);
20620b57cec5SDimitry Andric                    dbgs() << "\n";);
20630b57cec5SDimitry Andric       }
20640b57cec5SDimitry Andric     }
20650b57cec5SDimitry Andric   }
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric   // Iteratively prune unit sets after inferring supersets.
20680b57cec5SDimitry Andric   pruneUnitSets();
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric   LLVM_DEBUG(
20710b57cec5SDimitry Andric       dbgs() << "\n"; for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
20720b57cec5SDimitry Andric                            USIdx < USEnd; ++USIdx) {
20730b57cec5SDimitry Andric         dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";
20740b57cec5SDimitry Andric         for (auto &U : RegUnitSets[USIdx].Units)
20750b57cec5SDimitry Andric           printRegUnitName(U);
20760b57cec5SDimitry Andric         dbgs() << "\n";
20770b57cec5SDimitry Andric       });
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric   // For each register class, list the UnitSets that are supersets.
20800b57cec5SDimitry Andric   RegClassUnitSets.resize(RegClasses.size());
20810b57cec5SDimitry Andric   int RCIdx = -1;
20820b57cec5SDimitry Andric   for (auto &RC : RegClasses) {
20830b57cec5SDimitry Andric     ++RCIdx;
20840b57cec5SDimitry Andric     if (!RC.Allocatable)
20850b57cec5SDimitry Andric       continue;
20860b57cec5SDimitry Andric 
20870b57cec5SDimitry Andric     // Recompute the sorted list of units in this class.
20880b57cec5SDimitry Andric     std::vector<unsigned> RCRegUnits;
20890b57cec5SDimitry Andric     RC.buildRegUnitSet(*this, RCRegUnits);
20900b57cec5SDimitry Andric 
20910b57cec5SDimitry Andric     // Don't increase pressure for unallocatable regclasses.
20920b57cec5SDimitry Andric     if (RCRegUnits.empty())
20930b57cec5SDimitry Andric       continue;
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "RC " << RC.getName() << " Units:\n";
20960b57cec5SDimitry Andric                for (auto U
20970b57cec5SDimitry Andric                     : RCRegUnits) printRegUnitName(U);
20980b57cec5SDimitry Andric                dbgs() << "\n  UnitSetIDs:");
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric     // Find all supersets.
21010b57cec5SDimitry Andric     for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
21020b57cec5SDimitry Andric          USIdx != USEnd; ++USIdx) {
21030b57cec5SDimitry Andric       if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
21040b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << " " << USIdx);
21050b57cec5SDimitry Andric         RegClassUnitSets[RCIdx].push_back(USIdx);
21060b57cec5SDimitry Andric       }
21070b57cec5SDimitry Andric     }
21080b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
2109349cc55cSDimitry Andric     assert((!RegClassUnitSets[RCIdx].empty() || !RC.GeneratePressureSet) &&
2110349cc55cSDimitry Andric            "missing unit set for regclass");
21110b57cec5SDimitry Andric   }
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric   // For each register unit, ensure that we have the list of UnitSets that
21140b57cec5SDimitry Andric   // contain the unit. Normally, this matches an existing list of UnitSets for a
21150b57cec5SDimitry Andric   // register class. If not, we create a new entry in RegClassUnitSets as a
21160b57cec5SDimitry Andric   // "fake" register class.
21170b57cec5SDimitry Andric   for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
21180b57cec5SDimitry Andric        UnitIdx < UnitEnd; ++UnitIdx) {
21190b57cec5SDimitry Andric     std::vector<unsigned> RUSets;
21200b57cec5SDimitry Andric     for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
21210b57cec5SDimitry Andric       RegUnitSet &RUSet = RegUnitSets[i];
21220b57cec5SDimitry Andric       if (!is_contained(RUSet.Units, UnitIdx))
21230b57cec5SDimitry Andric         continue;
21240b57cec5SDimitry Andric       RUSets.push_back(i);
21250b57cec5SDimitry Andric     }
21260b57cec5SDimitry Andric     unsigned RCUnitSetsIdx = 0;
21270b57cec5SDimitry Andric     for (unsigned e = RegClassUnitSets.size();
21280b57cec5SDimitry Andric          RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
21290b57cec5SDimitry Andric       if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
21300b57cec5SDimitry Andric         break;
21310b57cec5SDimitry Andric       }
21320b57cec5SDimitry Andric     }
21330b57cec5SDimitry Andric     RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
21340b57cec5SDimitry Andric     if (RCUnitSetsIdx == RegClassUnitSets.size()) {
21350b57cec5SDimitry Andric       // Create a new list of UnitSets as a "fake" register class.
21360b57cec5SDimitry Andric       RegClassUnitSets.resize(RCUnitSetsIdx + 1);
21370b57cec5SDimitry Andric       RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
21380b57cec5SDimitry Andric     }
21390b57cec5SDimitry Andric   }
21400b57cec5SDimitry Andric }
21410b57cec5SDimitry Andric 
computeRegUnitLaneMasks()21420b57cec5SDimitry Andric void CodeGenRegBank::computeRegUnitLaneMasks() {
21430b57cec5SDimitry Andric   for (auto &Register : Registers) {
21440b57cec5SDimitry Andric     // Create an initial lane mask for all register units.
21450b57cec5SDimitry Andric     const auto &RegUnits = Register.getRegUnits();
21465f757f3fSDimitry Andric     CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(
21475f757f3fSDimitry Andric         RegUnits.count(), LaneBitmask::getAll());
21480b57cec5SDimitry Andric     // Iterate through SubRegisters.
21490b57cec5SDimitry Andric     typedef CodeGenRegister::SubRegMap SubRegMap;
21500b57cec5SDimitry Andric     const SubRegMap &SubRegs = Register.getSubRegs();
2151fe6060f1SDimitry Andric     for (auto S : SubRegs) {
2152fe6060f1SDimitry Andric       CodeGenRegister *SubReg = S.second;
21530b57cec5SDimitry Andric       // Ignore non-leaf subregisters, their lane masks are fully covered by
21540b57cec5SDimitry Andric       // the leaf subregisters anyway.
21550b57cec5SDimitry Andric       if (!SubReg->getSubRegs().empty())
21560b57cec5SDimitry Andric         continue;
2157fe6060f1SDimitry Andric       CodeGenSubRegIndex *SubRegIndex = S.first;
2158fe6060f1SDimitry Andric       const CodeGenRegister *SubRegister = S.second;
21590b57cec5SDimitry Andric       LaneBitmask LaneMask = SubRegIndex->LaneMask;
21600b57cec5SDimitry Andric       // Distribute LaneMask to Register Units touched.
21610b57cec5SDimitry Andric       for (unsigned SUI : SubRegister->getRegUnits()) {
21620b57cec5SDimitry Andric         bool Found = false;
21630b57cec5SDimitry Andric         unsigned u = 0;
21640b57cec5SDimitry Andric         for (unsigned RU : RegUnits) {
21650b57cec5SDimitry Andric           if (SUI == RU) {
21665f757f3fSDimitry Andric             RegUnitLaneMasks[u] &= LaneMask;
21670b57cec5SDimitry Andric             assert(!Found);
21680b57cec5SDimitry Andric             Found = true;
21690b57cec5SDimitry Andric           }
21700b57cec5SDimitry Andric           ++u;
21710b57cec5SDimitry Andric         }
21720b57cec5SDimitry Andric         (void)Found;
21730b57cec5SDimitry Andric         assert(Found);
21740b57cec5SDimitry Andric       }
21750b57cec5SDimitry Andric     }
21760b57cec5SDimitry Andric     Register.setRegUnitLaneMasks(RegUnitLaneMasks);
21770b57cec5SDimitry Andric   }
21780b57cec5SDimitry Andric }
21790b57cec5SDimitry Andric 
computeDerivedInfo()21800b57cec5SDimitry Andric void CodeGenRegBank::computeDerivedInfo() {
21810b57cec5SDimitry Andric   computeComposites();
21820b57cec5SDimitry Andric   computeSubRegLaneMasks();
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric   // Compute a weight for each register unit created during getSubRegs.
21850b57cec5SDimitry Andric   // This may create adopted register units (with unit # >= NumNativeRegUnits).
21860b57cec5SDimitry Andric   computeRegUnitWeights();
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric   // Compute a unique set of RegUnitSets. One for each RegClass and inferred
21890b57cec5SDimitry Andric   // supersets for the union of overlapping sets.
21900b57cec5SDimitry Andric   computeRegUnitSets();
21910b57cec5SDimitry Andric 
21920b57cec5SDimitry Andric   computeRegUnitLaneMasks();
21930b57cec5SDimitry Andric 
21940b57cec5SDimitry Andric   // Compute register class HasDisjunctSubRegs/CoveredBySubRegs flag.
21950b57cec5SDimitry Andric   for (CodeGenRegisterClass &RC : RegClasses) {
21960b57cec5SDimitry Andric     RC.HasDisjunctSubRegs = false;
21970b57cec5SDimitry Andric     RC.CoveredBySubRegs = true;
21980b57cec5SDimitry Andric     for (const CodeGenRegister *Reg : RC.getMembers()) {
21990b57cec5SDimitry Andric       RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;
22000b57cec5SDimitry Andric       RC.CoveredBySubRegs &= Reg->CoveredBySubRegs;
22010b57cec5SDimitry Andric     }
22020b57cec5SDimitry Andric   }
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric   // Get the weight of each set.
22050b57cec5SDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
22060b57cec5SDimitry Andric     RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric   // Find the order of each set.
22090b57cec5SDimitry Andric   RegUnitSetOrder.reserve(RegUnitSets.size());
22100b57cec5SDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
22110b57cec5SDimitry Andric     RegUnitSetOrder.push_back(Idx);
22120b57cec5SDimitry Andric 
22130b57cec5SDimitry Andric   llvm::stable_sort(RegUnitSetOrder, [this](unsigned ID1, unsigned ID2) {
22140b57cec5SDimitry Andric     return getRegPressureSet(ID1).Units.size() <
22150b57cec5SDimitry Andric            getRegPressureSet(ID2).Units.size();
22160b57cec5SDimitry Andric   });
22170b57cec5SDimitry Andric   for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
22180b57cec5SDimitry Andric     RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
22190b57cec5SDimitry Andric   }
22200b57cec5SDimitry Andric }
22210b57cec5SDimitry Andric 
22220b57cec5SDimitry Andric //
22230b57cec5SDimitry Andric // Synthesize missing register class intersections.
22240b57cec5SDimitry Andric //
22250b57cec5SDimitry Andric // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
22260b57cec5SDimitry Andric // returns a maximal register class for all X.
22270b57cec5SDimitry Andric //
inferCommonSubClass(CodeGenRegisterClass * RC)22280b57cec5SDimitry Andric void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
22290b57cec5SDimitry Andric   assert(!RegClasses.empty());
22300b57cec5SDimitry Andric   // Stash the iterator to the last element so that this loop doesn't visit
22310b57cec5SDimitry Andric   // elements added by the getOrCreateSubClass call within it.
22320b57cec5SDimitry Andric   for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
22330b57cec5SDimitry Andric        I != std::next(E); ++I) {
22340b57cec5SDimitry Andric     CodeGenRegisterClass *RC1 = RC;
22350b57cec5SDimitry Andric     CodeGenRegisterClass *RC2 = &*I;
22360b57cec5SDimitry Andric     if (RC1 == RC2)
22370b57cec5SDimitry Andric       continue;
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric     // Compute the set intersection of RC1 and RC2.
22400b57cec5SDimitry Andric     const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
22410b57cec5SDimitry Andric     const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
22420b57cec5SDimitry Andric     CodeGenRegister::Vec Intersection;
22438bcb0991SDimitry Andric     std::set_intersection(Memb1.begin(), Memb1.end(), Memb2.begin(),
22448bcb0991SDimitry Andric                           Memb2.end(),
22458bcb0991SDimitry Andric                           std::inserter(Intersection, Intersection.begin()),
22468bcb0991SDimitry Andric                           deref<std::less<>>());
22470b57cec5SDimitry Andric 
22480b57cec5SDimitry Andric     // Skip disjoint class pairs.
22490b57cec5SDimitry Andric     if (Intersection.empty())
22500b57cec5SDimitry Andric       continue;
22510b57cec5SDimitry Andric 
22520b57cec5SDimitry Andric     // If RC1 and RC2 have different spill sizes or alignments, use the
22530b57cec5SDimitry Andric     // stricter one for sub-classing.  If they are equal, prefer RC1.
22540b57cec5SDimitry Andric     if (RC2->RSI.hasStricterSpillThan(RC1->RSI))
22550b57cec5SDimitry Andric       std::swap(RC1, RC2);
22560b57cec5SDimitry Andric 
22570b57cec5SDimitry Andric     getOrCreateSubClass(RC1, &Intersection,
22580b57cec5SDimitry Andric                         RC1->getName() + "_and_" + RC2->getName());
22590b57cec5SDimitry Andric   }
22600b57cec5SDimitry Andric }
22610b57cec5SDimitry Andric 
22620b57cec5SDimitry Andric //
22630b57cec5SDimitry Andric // Synthesize missing sub-classes for getSubClassWithSubReg().
22640b57cec5SDimitry Andric //
22650b57cec5SDimitry Andric // Make sure that the set of registers in RC with a given SubIdx sub-register
22660b57cec5SDimitry Andric // form a register class.  Update RC->SubClassWithSubReg.
22670b57cec5SDimitry Andric //
inferSubClassWithSubReg(CodeGenRegisterClass * RC)22680b57cec5SDimitry Andric void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
22690b57cec5SDimitry Andric   // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
22700b57cec5SDimitry Andric   typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
22718bcb0991SDimitry Andric                    deref<std::less<>>>
22728bcb0991SDimitry Andric       SubReg2SetMap;
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric   // Compute the set of registers supporting each SubRegIndex.
22750b57cec5SDimitry Andric   SubReg2SetMap SRSets;
22760b57cec5SDimitry Andric   for (const auto R : RC->getMembers()) {
22770b57cec5SDimitry Andric     if (R->Artificial)
22780b57cec5SDimitry Andric       continue;
22790b57cec5SDimitry Andric     const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
2280fe6060f1SDimitry Andric     for (auto I : SRM) {
2281fe6060f1SDimitry Andric       if (!I.first->Artificial)
2282fe6060f1SDimitry Andric         SRSets[I.first].push_back(R);
22830b57cec5SDimitry Andric     }
22840b57cec5SDimitry Andric   }
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric   for (auto I : SRSets)
22870b57cec5SDimitry Andric     sortAndUniqueRegisters(I.second);
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric   // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
22900b57cec5SDimitry Andric   // numerical order to visit synthetic indices last.
22910b57cec5SDimitry Andric   for (const auto &SubIdx : SubRegIndices) {
22920b57cec5SDimitry Andric     if (SubIdx.Artificial)
22930b57cec5SDimitry Andric       continue;
22940b57cec5SDimitry Andric     SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
22950b57cec5SDimitry Andric     // Unsupported SubRegIndex. Skip it.
22960b57cec5SDimitry Andric     if (I == SRSets.end())
22970b57cec5SDimitry Andric       continue;
22980b57cec5SDimitry Andric     // In most cases, all RC registers support the SubRegIndex.
22990b57cec5SDimitry Andric     if (I->second.size() == RC->getMembers().size()) {
23000b57cec5SDimitry Andric       RC->setSubClassWithSubReg(&SubIdx, RC);
23010b57cec5SDimitry Andric       continue;
23020b57cec5SDimitry Andric     }
23030b57cec5SDimitry Andric     // This is a real subset.  See if we have a matching class.
23040b57cec5SDimitry Andric     CodeGenRegisterClass *SubRC =
23050b57cec5SDimitry Andric       getOrCreateSubClass(RC, &I->second,
23060b57cec5SDimitry Andric                           RC->getName() + "_with_" + I->first->getName());
23070b57cec5SDimitry Andric     RC->setSubClassWithSubReg(&SubIdx, SubRC);
23080b57cec5SDimitry Andric   }
23090b57cec5SDimitry Andric }
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric //
23120b57cec5SDimitry Andric // Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
23130b57cec5SDimitry Andric //
23140b57cec5SDimitry Andric // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
23150b57cec5SDimitry Andric // has a maximal result for any SubIdx and any X >= FirstSubRegRC.
23160b57cec5SDimitry Andric //
23170b57cec5SDimitry Andric 
inferMatchingSuperRegClass(CodeGenRegisterClass * RC,std::list<CodeGenRegisterClass>::iterator FirstSubRegRC)23180b57cec5SDimitry Andric void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
23190b57cec5SDimitry Andric                                                 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
23205f757f3fSDimitry Andric   DenseMap<const CodeGenRegister *, std::vector<const CodeGenRegister *>>
23215f757f3fSDimitry Andric       SubToSuperRegs;
23220b57cec5SDimitry Andric   BitVector TopoSigs(getNumTopoSigs());
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric   // Iterate in SubRegIndex numerical order to visit synthetic indices last.
23250b57cec5SDimitry Andric   for (auto &SubIdx : SubRegIndices) {
23260b57cec5SDimitry Andric     // Skip indexes that aren't fully supported by RC's registers. This was
23270b57cec5SDimitry Andric     // computed by inferSubClassWithSubReg() above which should have been
23280b57cec5SDimitry Andric     // called first.
23290b57cec5SDimitry Andric     if (RC->getSubClassWithSubReg(&SubIdx) != RC)
23300b57cec5SDimitry Andric       continue;
23310b57cec5SDimitry Andric 
23320b57cec5SDimitry Andric     // Build list of (Super, Sub) pairs for this SubIdx.
23335f757f3fSDimitry Andric     SubToSuperRegs.clear();
23340b57cec5SDimitry Andric     TopoSigs.reset();
23350b57cec5SDimitry Andric     for (const auto Super : RC->getMembers()) {
23360b57cec5SDimitry Andric       const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
23370b57cec5SDimitry Andric       assert(Sub && "Missing sub-register");
23385f757f3fSDimitry Andric       SubToSuperRegs[Sub].push_back(Super);
23390b57cec5SDimitry Andric       TopoSigs.set(Sub->getTopoSig());
23400b57cec5SDimitry Andric     }
23410b57cec5SDimitry Andric 
23420b57cec5SDimitry Andric     // Iterate over sub-register class candidates.  Ignore classes created by
23430b57cec5SDimitry Andric     // this loop. They will never be useful.
23440b57cec5SDimitry Andric     // Store an iterator to the last element (not end) so that this loop doesn't
23450b57cec5SDimitry Andric     // visit newly inserted elements.
23460b57cec5SDimitry Andric     assert(!RegClasses.empty());
23470b57cec5SDimitry Andric     for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
23480b57cec5SDimitry Andric          I != std::next(E); ++I) {
23490b57cec5SDimitry Andric       CodeGenRegisterClass &SubRC = *I;
23500b57cec5SDimitry Andric       if (SubRC.Artificial)
23510b57cec5SDimitry Andric         continue;
23520b57cec5SDimitry Andric       // Topological shortcut: SubRC members have the wrong shape.
23530b57cec5SDimitry Andric       if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
23540b57cec5SDimitry Andric         continue;
23550b57cec5SDimitry Andric       // Compute the subset of RC that maps into SubRC.
23560b57cec5SDimitry Andric       CodeGenRegister::Vec SubSetVec;
23575f757f3fSDimitry Andric       for (const CodeGenRegister *R : SubRC.getMembers()) {
23585f757f3fSDimitry Andric         auto It = SubToSuperRegs.find(R);
23595f757f3fSDimitry Andric         if (It != SubToSuperRegs.end()) {
23605f757f3fSDimitry Andric           const std::vector<const CodeGenRegister *> &SuperRegs = It->second;
23615f757f3fSDimitry Andric           SubSetVec.insert(SubSetVec.end(), SuperRegs.begin(), SuperRegs.end());
23625f757f3fSDimitry Andric         }
23635f757f3fSDimitry Andric       }
23640b57cec5SDimitry Andric 
23650b57cec5SDimitry Andric       if (SubSetVec.empty())
23660b57cec5SDimitry Andric         continue;
23670b57cec5SDimitry Andric 
23680b57cec5SDimitry Andric       // RC injects completely into SubRC.
23690b57cec5SDimitry Andric       sortAndUniqueRegisters(SubSetVec);
23705f757f3fSDimitry Andric       if (SubSetVec.size() == RC->getMembers().size()) {
23710b57cec5SDimitry Andric         SubRC.addSuperRegClass(&SubIdx, RC);
23720b57cec5SDimitry Andric         continue;
23730b57cec5SDimitry Andric       }
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric       // Only a subset of RC maps into SubRC. Make sure it is represented by a
23760b57cec5SDimitry Andric       // class.
23770b57cec5SDimitry Andric       getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
23780b57cec5SDimitry Andric                                           SubIdx.getName() + "_in_" +
23790b57cec5SDimitry Andric                                           SubRC.getName());
23800b57cec5SDimitry Andric     }
23810b57cec5SDimitry Andric   }
23820b57cec5SDimitry Andric }
23830b57cec5SDimitry Andric 
23840b57cec5SDimitry Andric //
23850b57cec5SDimitry Andric // Infer missing register classes.
23860b57cec5SDimitry Andric //
computeInferredRegisterClasses()23870b57cec5SDimitry Andric void CodeGenRegBank::computeInferredRegisterClasses() {
23880b57cec5SDimitry Andric   assert(!RegClasses.empty());
23890b57cec5SDimitry Andric   // When this function is called, the register classes have not been sorted
23900b57cec5SDimitry Andric   // and assigned EnumValues yet.  That means getSubClasses(),
23910b57cec5SDimitry Andric   // getSuperClasses(), and hasSubClass() functions are defunct.
23920b57cec5SDimitry Andric 
23930b57cec5SDimitry Andric   // Use one-before-the-end so it doesn't move forward when new elements are
23940b57cec5SDimitry Andric   // added.
23950b57cec5SDimitry Andric   auto FirstNewRC = std::prev(RegClasses.end());
23960b57cec5SDimitry Andric 
23970b57cec5SDimitry Andric   // Visit all register classes, including the ones being added by the loop.
23980b57cec5SDimitry Andric   // Watch out for iterator invalidation here.
23990b57cec5SDimitry Andric   for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
24000b57cec5SDimitry Andric     CodeGenRegisterClass *RC = &*I;
24010b57cec5SDimitry Andric     if (RC->Artificial)
24020b57cec5SDimitry Andric       continue;
24030b57cec5SDimitry Andric 
24040b57cec5SDimitry Andric     // Synthesize answers for getSubClassWithSubReg().
24050b57cec5SDimitry Andric     inferSubClassWithSubReg(RC);
24060b57cec5SDimitry Andric 
24070b57cec5SDimitry Andric     // Synthesize answers for getCommonSubClass().
24080b57cec5SDimitry Andric     inferCommonSubClass(RC);
24090b57cec5SDimitry Andric 
24100b57cec5SDimitry Andric     // Synthesize answers for getMatchingSuperRegClass().
24110b57cec5SDimitry Andric     inferMatchingSuperRegClass(RC);
24120b57cec5SDimitry Andric 
24130b57cec5SDimitry Andric     // New register classes are created while this loop is running, and we need
24140b57cec5SDimitry Andric     // to visit all of them.  I  particular, inferMatchingSuperRegClass needs
24150b57cec5SDimitry Andric     // to match old super-register classes with sub-register classes created
24160b57cec5SDimitry Andric     // after inferMatchingSuperRegClass was called.  At this point,
24170b57cec5SDimitry Andric     // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
24180b57cec5SDimitry Andric     // [0..FirstNewRC).  We need to cover SubRC = [FirstNewRC..rci].
24190b57cec5SDimitry Andric     if (I == FirstNewRC) {
24200b57cec5SDimitry Andric       auto NextNewRC = std::prev(RegClasses.end());
24210b57cec5SDimitry Andric       for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
24220b57cec5SDimitry Andric            ++I2)
24230b57cec5SDimitry Andric         inferMatchingSuperRegClass(&*I2, E2);
24240b57cec5SDimitry Andric       FirstNewRC = NextNewRC;
24250b57cec5SDimitry Andric     }
24260b57cec5SDimitry Andric   }
24270b57cec5SDimitry Andric }
24280b57cec5SDimitry Andric 
24290b57cec5SDimitry Andric /// getRegisterClassForRegister - Find the register class that contains the
24300b57cec5SDimitry Andric /// specified physical register.  If the register is not in a register class,
24310b57cec5SDimitry Andric /// return null. If the register is in multiple classes, and the classes have a
24320b57cec5SDimitry Andric /// superset-subset relationship and the same set of types, return the
24330b57cec5SDimitry Andric /// superclass.  Otherwise return null.
24340b57cec5SDimitry Andric const CodeGenRegisterClass*
getRegClassForRegister(Record * R)24350b57cec5SDimitry Andric CodeGenRegBank::getRegClassForRegister(Record *R) {
24360b57cec5SDimitry Andric   const CodeGenRegister *Reg = getReg(R);
24370b57cec5SDimitry Andric   const CodeGenRegisterClass *FoundRC = nullptr;
24380b57cec5SDimitry Andric   for (const auto &RC : getRegClasses()) {
24390b57cec5SDimitry Andric     if (!RC.contains(Reg))
24400b57cec5SDimitry Andric       continue;
24410b57cec5SDimitry Andric 
24420b57cec5SDimitry Andric     // If this is the first class that contains the register,
24430b57cec5SDimitry Andric     // make a note of it and go on to the next class.
24440b57cec5SDimitry Andric     if (!FoundRC) {
24450b57cec5SDimitry Andric       FoundRC = &RC;
24460b57cec5SDimitry Andric       continue;
24470b57cec5SDimitry Andric     }
24480b57cec5SDimitry Andric 
24490b57cec5SDimitry Andric     // If a register's classes have different types, return null.
24500b57cec5SDimitry Andric     if (RC.getValueTypes() != FoundRC->getValueTypes())
24510b57cec5SDimitry Andric       return nullptr;
24520b57cec5SDimitry Andric 
24530b57cec5SDimitry Andric     // Check to see if the previously found class that contains
24540b57cec5SDimitry Andric     // the register is a subclass of the current class. If so,
24550b57cec5SDimitry Andric     // prefer the superclass.
24560b57cec5SDimitry Andric     if (RC.hasSubClass(FoundRC)) {
24570b57cec5SDimitry Andric       FoundRC = &RC;
24580b57cec5SDimitry Andric       continue;
24590b57cec5SDimitry Andric     }
24600b57cec5SDimitry Andric 
24610b57cec5SDimitry Andric     // Check to see if the previously found class that contains
24620b57cec5SDimitry Andric     // the register is a superclass of the current class. If so,
24630b57cec5SDimitry Andric     // prefer the superclass.
24640b57cec5SDimitry Andric     if (FoundRC->hasSubClass(&RC))
24650b57cec5SDimitry Andric       continue;
24660b57cec5SDimitry Andric 
24670b57cec5SDimitry Andric     // Multiple classes, and neither is a superclass of the other.
24680b57cec5SDimitry Andric     // Return null.
24690b57cec5SDimitry Andric     return nullptr;
24700b57cec5SDimitry Andric   }
24710b57cec5SDimitry Andric   return FoundRC;
24720b57cec5SDimitry Andric }
24730b57cec5SDimitry Andric 
24748bcb0991SDimitry Andric const CodeGenRegisterClass *
getMinimalPhysRegClass(Record * RegRecord,ValueTypeByHwMode * VT)24758bcb0991SDimitry Andric CodeGenRegBank::getMinimalPhysRegClass(Record *RegRecord,
24768bcb0991SDimitry Andric                                        ValueTypeByHwMode *VT) {
24778bcb0991SDimitry Andric   const CodeGenRegister *Reg = getReg(RegRecord);
24788bcb0991SDimitry Andric   const CodeGenRegisterClass *BestRC = nullptr;
24798bcb0991SDimitry Andric   for (const auto &RC : getRegClasses()) {
24808bcb0991SDimitry Andric     if ((!VT || RC.hasType(*VT)) &&
24818bcb0991SDimitry Andric         RC.contains(Reg) && (!BestRC || BestRC->hasSubClass(&RC)))
24828bcb0991SDimitry Andric       BestRC = &RC;
24838bcb0991SDimitry Andric   }
24848bcb0991SDimitry Andric 
24858bcb0991SDimitry Andric   assert(BestRC && "Couldn't find the register class");
24868bcb0991SDimitry Andric   return BestRC;
24878bcb0991SDimitry Andric }
24888bcb0991SDimitry Andric 
computeCoveredRegisters(ArrayRef<Record * > Regs)24890b57cec5SDimitry Andric BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
24900b57cec5SDimitry Andric   SetVector<const CodeGenRegister*> Set;
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric   // First add Regs with all sub-registers.
24930b57cec5SDimitry Andric   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
24940b57cec5SDimitry Andric     CodeGenRegister *Reg = getReg(Regs[i]);
24950b57cec5SDimitry Andric     if (Set.insert(Reg))
24960b57cec5SDimitry Andric       // Reg is new, add all sub-registers.
24970b57cec5SDimitry Andric       // The pre-ordering is not important here.
24980b57cec5SDimitry Andric       Reg->addSubRegsPreOrder(Set, *this);
24990b57cec5SDimitry Andric   }
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric   // Second, find all super-registers that are completely covered by the set.
25020b57cec5SDimitry Andric   for (unsigned i = 0; i != Set.size(); ++i) {
25030b57cec5SDimitry Andric     const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
25040b57cec5SDimitry Andric     for (unsigned j = 0, e = SR.size(); j != e; ++j) {
25050b57cec5SDimitry Andric       const CodeGenRegister *Super = SR[j];
25060b57cec5SDimitry Andric       if (!Super->CoveredBySubRegs || Set.count(Super))
25070b57cec5SDimitry Andric         continue;
25080b57cec5SDimitry Andric       // This new super-register is covered by its sub-registers.
25090b57cec5SDimitry Andric       bool AllSubsInSet = true;
25100b57cec5SDimitry Andric       const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2511fe6060f1SDimitry Andric       for (auto I : SRM)
2512fe6060f1SDimitry Andric         if (!Set.count(I.second)) {
25130b57cec5SDimitry Andric           AllSubsInSet = false;
25140b57cec5SDimitry Andric           break;
25150b57cec5SDimitry Andric         }
25160b57cec5SDimitry Andric       // All sub-registers in Set, add Super as well.
25170b57cec5SDimitry Andric       // We will visit Super later to recheck its super-registers.
25180b57cec5SDimitry Andric       if (AllSubsInSet)
25190b57cec5SDimitry Andric         Set.insert(Super);
25200b57cec5SDimitry Andric     }
25210b57cec5SDimitry Andric   }
25220b57cec5SDimitry Andric 
25230b57cec5SDimitry Andric   // Convert to BitVector.
25240b57cec5SDimitry Andric   BitVector BV(Registers.size() + 1);
25250b57cec5SDimitry Andric   for (unsigned i = 0, e = Set.size(); i != e; ++i)
25260b57cec5SDimitry Andric     BV.set(Set[i]->EnumValue);
25270b57cec5SDimitry Andric   return BV;
25280b57cec5SDimitry Andric }
25290b57cec5SDimitry Andric 
printRegUnitName(unsigned Unit) const25300b57cec5SDimitry Andric void CodeGenRegBank::printRegUnitName(unsigned Unit) const {
25310b57cec5SDimitry Andric   if (Unit < NumNativeRegUnits)
25320b57cec5SDimitry Andric     dbgs() << ' ' << RegUnits[Unit].Roots[0]->getName();
25330b57cec5SDimitry Andric   else
25340b57cec5SDimitry Andric     dbgs() << " #" << Unit;
25350b57cec5SDimitry Andric }
2536