Path: blob/main/contrib/llvm-project/llvm/utils/TableGen/Common/CodeGenRegisters.cpp
96353 views
//===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines structures to encapsulate information gleaned from the9// target register and register class definitions.10//11//===----------------------------------------------------------------------===//1213#include "CodeGenRegisters.h"14#include "llvm/ADT/ArrayRef.h"15#include "llvm/ADT/BitVector.h"16#include "llvm/ADT/DenseMap.h"17#include "llvm/ADT/IntEqClasses.h"18#include "llvm/ADT/STLExtras.h"19#include "llvm/ADT/SetVector.h"20#include "llvm/ADT/SmallPtrSet.h"21#include "llvm/ADT/SmallSet.h"22#include "llvm/ADT/SmallVector.h"23#include "llvm/ADT/StringRef.h"24#include "llvm/ADT/StringSet.h"25#include "llvm/ADT/Twine.h"26#include "llvm/Support/Debug.h"27#include "llvm/Support/raw_ostream.h"28#include "llvm/TableGen/Error.h"29#include "llvm/TableGen/Record.h"30#include <algorithm>31#include <cassert>32#include <cstdint>33#include <iterator>34#include <map>35#include <queue>36#include <set>37#include <string>38#include <tuple>39#include <utility>40#include <vector>4142using namespace llvm;4344#define DEBUG_TYPE "regalloc-emitter"4546//===----------------------------------------------------------------------===//47// CodeGenSubRegIndex48//===----------------------------------------------------------------------===//4950CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum,51const CodeGenHwModes &CGH)52: TheDef(R), EnumValue(Enum), AllSuperRegsCovered(true), Artificial(true) {53Name = std::string(R->getName());54if (R->getValue("Namespace"))55Namespace = std::string(R->getValueAsString("Namespace"));5657if (const RecordVal *RV = R->getValue("SubRegRanges"))58if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue()))59Range = SubRegRangeByHwMode(DI->getDef(), CGH);60if (!Range.hasDefault())61Range.insertSubRegRangeForMode(DefaultMode, SubRegRange(R));62}6364CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,65unsigned Enum)66: TheDef(nullptr), Name(std::string(N)), Namespace(std::string(Nspace)),67Range(SubRegRange(-1, -1)), EnumValue(Enum), AllSuperRegsCovered(true),68Artificial(true) {}6970std::string CodeGenSubRegIndex::getQualifiedName() const {71std::string N = getNamespace();72if (!N.empty())73N += "::";74N += getName();75return N;76}7778void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {79if (!TheDef)80return;8182std::vector<Record *> Comps = TheDef->getValueAsListOfDefs("ComposedOf");83if (!Comps.empty()) {84if (Comps.size() != 2)85PrintFatalError(TheDef->getLoc(),86"ComposedOf must have exactly two entries");87CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);88CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);89CodeGenSubRegIndex *X = A->addComposite(B, this, RegBank.getHwModes());90if (X)91PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");92}9394std::vector<Record *> Parts =95TheDef->getValueAsListOfDefs("CoveringSubRegIndices");96if (!Parts.empty()) {97if (Parts.size() < 2)98PrintFatalError(TheDef->getLoc(),99"CoveredBySubRegs must have two or more entries");100SmallVector<CodeGenSubRegIndex *, 8> IdxParts;101for (Record *Part : Parts)102IdxParts.push_back(RegBank.getSubRegIdx(Part));103setConcatenationOf(IdxParts);104}105}106107LaneBitmask CodeGenSubRegIndex::computeLaneMask() const {108// Already computed?109if (LaneMask.any())110return LaneMask;111112// Recursion guard, shouldn't be required.113LaneMask = LaneBitmask::getAll();114115// The lane mask is simply the union of all sub-indices.116LaneBitmask M;117for (const auto &C : Composed)118M |= C.second->computeLaneMask();119assert(M.any() && "Missing lane mask, sub-register cycle?");120LaneMask = M;121return LaneMask;122}123124void CodeGenSubRegIndex::setConcatenationOf(125ArrayRef<CodeGenSubRegIndex *> Parts) {126if (ConcatenationOf.empty())127ConcatenationOf.assign(Parts.begin(), Parts.end());128else129assert(std::equal(Parts.begin(), Parts.end(), ConcatenationOf.begin()) &&130"parts consistent");131}132133void CodeGenSubRegIndex::computeConcatTransitiveClosure() {134for (SmallVectorImpl<CodeGenSubRegIndex *>::iterator I =135ConcatenationOf.begin();136I != ConcatenationOf.end();137/*empty*/) {138CodeGenSubRegIndex *SubIdx = *I;139SubIdx->computeConcatTransitiveClosure();140#ifndef NDEBUG141for (CodeGenSubRegIndex *SRI : SubIdx->ConcatenationOf)142assert(SRI->ConcatenationOf.empty() && "No transitive closure?");143#endif144145if (SubIdx->ConcatenationOf.empty()) {146++I;147} else {148I = ConcatenationOf.erase(I);149I = ConcatenationOf.insert(I, SubIdx->ConcatenationOf.begin(),150SubIdx->ConcatenationOf.end());151I += SubIdx->ConcatenationOf.size();152}153}154}155156//===----------------------------------------------------------------------===//157// CodeGenRegister158//===----------------------------------------------------------------------===//159160CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)161: TheDef(R), EnumValue(Enum),162CostPerUse(R->getValueAsListOfInts("CostPerUse")),163CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),164HasDisjunctSubRegs(false), Constant(R->getValueAsBit("isConstant")),165SubRegsComplete(false), SuperRegsComplete(false), TopoSig(~0u) {166Artificial = R->getValueAsBit("isArtificial");167}168169void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {170std::vector<Record *> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");171std::vector<Record *> SRs = TheDef->getValueAsListOfDefs("SubRegs");172173if (SRIs.size() != SRs.size())174PrintFatalError(TheDef->getLoc(),175"SubRegs and SubRegIndices must have the same size");176177for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {178ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));179ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));180}181182// Also compute leading super-registers. Each register has a list of183// covered-by-subregs super-registers where it appears as the first explicit184// sub-register.185//186// This is used by computeSecondarySubRegs() to find candidates.187if (CoveredBySubRegs && !ExplicitSubRegs.empty())188ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);189190// Add ad hoc alias links. This is a symmetric relationship between two191// registers, so build a symmetric graph by adding links in both ends.192std::vector<Record *> Aliases = TheDef->getValueAsListOfDefs("Aliases");193for (Record *Alias : Aliases) {194CodeGenRegister *Reg = RegBank.getReg(Alias);195ExplicitAliases.push_back(Reg);196Reg->ExplicitAliases.push_back(this);197}198}199200StringRef CodeGenRegister::getName() const {201assert(TheDef && "no def");202return TheDef->getName();203}204205namespace {206207// Iterate over all register units in a set of registers.208class RegUnitIterator {209CodeGenRegister::Vec::const_iterator RegI, RegE;210CodeGenRegister::RegUnitList::iterator UnitI, UnitE;211static CodeGenRegister::RegUnitList Sentinel;212213public:214RegUnitIterator(const CodeGenRegister::Vec &Regs)215: RegI(Regs.begin()), RegE(Regs.end()) {216217if (RegI == RegE) {218UnitI = Sentinel.end();219UnitE = Sentinel.end();220} else {221UnitI = (*RegI)->getRegUnits().begin();222UnitE = (*RegI)->getRegUnits().end();223advance();224}225}226227bool isValid() const { return UnitI != UnitE; }228229unsigned operator*() const {230assert(isValid());231return *UnitI;232}233234const CodeGenRegister *getReg() const {235assert(isValid());236return *RegI;237}238239/// Preincrement. Move to the next unit.240void operator++() {241assert(isValid() && "Cannot advance beyond the last operand");242++UnitI;243advance();244}245246protected:247void advance() {248while (UnitI == UnitE) {249if (++RegI == RegE)250break;251UnitI = (*RegI)->getRegUnits().begin();252UnitE = (*RegI)->getRegUnits().end();253}254}255};256257CodeGenRegister::RegUnitList RegUnitIterator::Sentinel;258259} // end anonymous namespace260261// Inherit register units from subregisters.262// Return true if the RegUnits changed.263bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {264bool changed = false;265for (const auto &SubReg : SubRegs) {266CodeGenRegister *SR = SubReg.second;267// Merge the subregister's units into this register's RegUnits.268changed |= (RegUnits |= SR->RegUnits);269}270271return changed;272}273274const CodeGenRegister::SubRegMap &275CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {276// Only compute this map once.277if (SubRegsComplete)278return SubRegs;279SubRegsComplete = true;280281HasDisjunctSubRegs = ExplicitSubRegs.size() > 1;282283// First insert the explicit subregs and make sure they are fully indexed.284for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {285CodeGenRegister *SR = ExplicitSubRegs[i];286CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];287if (!SR->Artificial)288Idx->Artificial = false;289if (!SubRegs.insert(std::pair(Idx, SR)).second)290PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +291" appears twice in Register " +292getName());293// Map explicit sub-registers first, so the names take precedence.294// The inherited sub-registers are mapped below.295SubReg2Idx.insert(std::pair(SR, Idx));296}297298// Keep track of inherited subregs and how they can be reached.299SmallPtrSet<CodeGenRegister *, 8> Orphans;300301// Clone inherited subregs and place duplicate entries in Orphans.302// Here the order is important - earlier subregs take precedence.303for (CodeGenRegister *ESR : ExplicitSubRegs) {304const SubRegMap &Map = ESR->computeSubRegs(RegBank);305HasDisjunctSubRegs |= ESR->HasDisjunctSubRegs;306307for (const auto &SR : Map) {308if (!SubRegs.insert(SR).second)309Orphans.insert(SR.second);310}311}312313// Expand any composed subreg indices.314// If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a315// qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process316// expanded subreg indices recursively.317SmallVector<CodeGenSubRegIndex *, 8> Indices = ExplicitSubRegIndices;318for (unsigned i = 0; i != Indices.size(); ++i) {319CodeGenSubRegIndex *Idx = Indices[i];320const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();321CodeGenRegister *SR = SubRegs[Idx];322const SubRegMap &Map = SR->computeSubRegs(RegBank);323324// Look at the possible compositions of Idx.325// They may not all be supported by SR.326for (auto Comp : Comps) {327SubRegMap::const_iterator SRI = Map.find(Comp.first);328if (SRI == Map.end())329continue; // Idx + I->first doesn't exist in SR.330// Add I->second as a name for the subreg SRI->second, assuming it is331// orphaned, and the name isn't already used for something else.332if (SubRegs.count(Comp.second) || !Orphans.erase(SRI->second))333continue;334// We found a new name for the orphaned sub-register.335SubRegs.insert(std::pair(Comp.second, SRI->second));336Indices.push_back(Comp.second);337}338}339340// Now Orphans contains the inherited subregisters without a direct index.341// Create inferred indexes for all missing entries.342// Work backwards in the Indices vector in order to compose subregs bottom-up.343// Consider this subreg sequence:344//345// qsub_1 -> dsub_0 -> ssub_0346//347// The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register348// can be reached in two different ways:349//350// qsub_1 -> ssub_0351// dsub_2 -> ssub_0352//353// We pick the latter composition because another register may have [dsub_0,354// dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The355// dsub_2 -> ssub_0 composition can be shared.356while (!Indices.empty() && !Orphans.empty()) {357CodeGenSubRegIndex *Idx = Indices.pop_back_val();358CodeGenRegister *SR = SubRegs[Idx];359const SubRegMap &Map = SR->computeSubRegs(RegBank);360for (const auto &SubReg : Map)361if (Orphans.erase(SubReg.second))362SubRegs[RegBank.getCompositeSubRegIndex(Idx, SubReg.first)] =363SubReg.second;364}365366// Compute the inverse SubReg -> Idx map.367for (const auto &SubReg : SubRegs) {368if (SubReg.second == this) {369ArrayRef<SMLoc> Loc;370if (TheDef)371Loc = TheDef->getLoc();372PrintFatalError(Loc, "Register " + getName() +373" has itself as a sub-register");374}375376// Compute AllSuperRegsCovered.377if (!CoveredBySubRegs)378SubReg.first->AllSuperRegsCovered = false;379380// Ensure that every sub-register has a unique name.381DenseMap<const CodeGenRegister *, CodeGenSubRegIndex *>::iterator Ins =382SubReg2Idx.insert(std::pair(SubReg.second, SubReg.first)).first;383if (Ins->second == SubReg.first)384continue;385// Trouble: Two different names for SubReg.second.386ArrayRef<SMLoc> Loc;387if (TheDef)388Loc = TheDef->getLoc();389PrintFatalError(390Loc, "Sub-register can't have two names: " + SubReg.second->getName() +391" available as " + SubReg.first->getName() + " and " +392Ins->second->getName());393}394395// Derive possible names for sub-register concatenations from any explicit396// sub-registers. By doing this before computeSecondarySubRegs(), we ensure397// that getConcatSubRegIndex() won't invent any concatenated indices that the398// user already specified.399for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {400CodeGenRegister *SR = ExplicitSubRegs[i];401if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1 ||402SR->Artificial)403continue;404405// SR is composed of multiple sub-regs. Find their names in this register.406SmallVector<CodeGenSubRegIndex *, 8> Parts;407for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j) {408CodeGenSubRegIndex &I = *SR->ExplicitSubRegIndices[j];409if (!I.Artificial)410Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));411}412413// Offer this as an existing spelling for the concatenation of Parts.414CodeGenSubRegIndex &Idx = *ExplicitSubRegIndices[i];415Idx.setConcatenationOf(Parts);416}417418// Initialize RegUnitList. Because getSubRegs is called recursively, this419// processes the register hierarchy in postorder.420//421// Inherit all sub-register units. It is good enough to look at the explicit422// sub-registers, the other registers won't contribute any more units.423for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {424CodeGenRegister *SR = ExplicitSubRegs[i];425RegUnits |= SR->RegUnits;426}427428// Absent any ad hoc aliasing, we create one register unit per leaf register.429// These units correspond to the maximal cliques in the register overlap430// graph which is optimal.431//432// When there is ad hoc aliasing, we simply create one unit per edge in the433// undirected ad hoc aliasing graph. Technically, we could do better by434// identifying maximal cliques in the ad hoc graph, but cliques larger than 2435// are extremely rare anyway (I've never seen one), so we don't bother with436// the added complexity.437for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {438CodeGenRegister *AR = ExplicitAliases[i];439// Only visit each edge once.440if (AR->SubRegsComplete)441continue;442// Create a RegUnit representing this alias edge, and add it to both443// registers.444unsigned Unit = RegBank.newRegUnit(this, AR);445RegUnits.set(Unit);446AR->RegUnits.set(Unit);447}448449// Finally, create units for leaf registers without ad hoc aliases. Note that450// a leaf register with ad hoc aliases doesn't get its own unit - it isn't451// necessary. This means the aliasing leaf registers can share a single unit.452if (RegUnits.empty())453RegUnits.set(RegBank.newRegUnit(this));454455// We have now computed the native register units. More may be adopted later456// for balancing purposes.457NativeRegUnits = RegUnits;458459return SubRegs;460}461462// In a register that is covered by its sub-registers, try to find redundant463// sub-registers. For example:464//465// QQ0 = {Q0, Q1}466// Q0 = {D0, D1}467// Q1 = {D2, D3}468//469// We can infer that D1_D2 is also a sub-register, even if it wasn't named in470// the register definition.471//472// The explicitly specified registers form a tree. This function discovers473// sub-register relationships that would force a DAG.474//475void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {476SmallVector<SubRegMap::value_type, 8> NewSubRegs;477478std::queue<std::pair<CodeGenSubRegIndex *, CodeGenRegister *>> SubRegQueue;479for (std::pair<CodeGenSubRegIndex *, CodeGenRegister *> P : SubRegs)480SubRegQueue.push(P);481482// Look at the leading super-registers of each sub-register. Those are the483// candidates for new sub-registers, assuming they are fully contained in484// this register.485while (!SubRegQueue.empty()) {486CodeGenSubRegIndex *SubRegIdx;487const CodeGenRegister *SubReg;488std::tie(SubRegIdx, SubReg) = SubRegQueue.front();489SubRegQueue.pop();490491const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;492for (unsigned i = 0, e = Leads.size(); i != e; ++i) {493CodeGenRegister *Cand = const_cast<CodeGenRegister *>(Leads[i]);494// Already got this sub-register?495if (Cand == this || getSubRegIndex(Cand))496continue;497// Check if each component of Cand is already a sub-register.498assert(!Cand->ExplicitSubRegs.empty() &&499"Super-register has no sub-registers");500if (Cand->ExplicitSubRegs.size() == 1)501continue;502SmallVector<CodeGenSubRegIndex *, 8> Parts;503// We know that the first component is (SubRegIdx,SubReg). However we504// may still need to split it into smaller subregister parts.505assert(Cand->ExplicitSubRegs[0] == SubReg && "LeadingSuperRegs correct");506assert(getSubRegIndex(SubReg) == SubRegIdx && "LeadingSuperRegs correct");507for (CodeGenRegister *SubReg : Cand->ExplicitSubRegs) {508if (CodeGenSubRegIndex *SubRegIdx = getSubRegIndex(SubReg)) {509if (SubRegIdx->ConcatenationOf.empty())510Parts.push_back(SubRegIdx);511else512append_range(Parts, SubRegIdx->ConcatenationOf);513} else {514// Sub-register doesn't exist.515Parts.clear();516break;517}518}519// There is nothing to do if some Cand sub-register is not part of this520// register.521if (Parts.empty())522continue;523524// Each part of Cand is a sub-register of this. Make the full Cand also525// a sub-register with a concatenated sub-register index.526CodeGenSubRegIndex *Concat =527RegBank.getConcatSubRegIndex(Parts, RegBank.getHwModes());528std::pair<CodeGenSubRegIndex *, CodeGenRegister *> NewSubReg =529std::pair(Concat, Cand);530531if (!SubRegs.insert(NewSubReg).second)532continue;533534// We inserted a new subregister.535NewSubRegs.push_back(NewSubReg);536SubRegQueue.push(NewSubReg);537SubReg2Idx.insert(std::pair(Cand, Concat));538}539}540541// Create sub-register index composition maps for the synthesized indices.542for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {543CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;544CodeGenRegister *NewSubReg = NewSubRegs[i].second;545for (auto SubReg : NewSubReg->SubRegs) {546CodeGenSubRegIndex *SubIdx = getSubRegIndex(SubReg.second);547if (!SubIdx)548PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +549SubReg.second->getName() +550" in " + getName());551NewIdx->addComposite(SubReg.first, SubIdx, RegBank.getHwModes());552}553}554}555556void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {557// Only visit each register once.558if (SuperRegsComplete)559return;560SuperRegsComplete = true;561562// Make sure all sub-registers have been visited first, so the super-reg563// lists will be topologically ordered.564for (auto SubReg : SubRegs)565SubReg.second->computeSuperRegs(RegBank);566567// Now add this as a super-register on all sub-registers.568// Also compute the TopoSigId in post-order.569TopoSigId Id;570for (auto SubReg : SubRegs) {571// Topological signature computed from SubIdx, TopoId(SubReg).572// Loops and idempotent indices have TopoSig = ~0u.573Id.push_back(SubReg.first->EnumValue);574Id.push_back(SubReg.second->TopoSig);575576// Don't add duplicate entries.577if (!SubReg.second->SuperRegs.empty() &&578SubReg.second->SuperRegs.back() == this)579continue;580SubReg.second->SuperRegs.push_back(this);581}582TopoSig = RegBank.getTopoSig(Id);583}584585void CodeGenRegister::addSubRegsPreOrder(586SetVector<const CodeGenRegister *> &OSet, CodeGenRegBank &RegBank) const {587assert(SubRegsComplete && "Must precompute sub-registers");588for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {589CodeGenRegister *SR = ExplicitSubRegs[i];590if (OSet.insert(SR))591SR->addSubRegsPreOrder(OSet, RegBank);592}593// Add any secondary sub-registers that weren't part of the explicit tree.594for (auto SubReg : SubRegs)595OSet.insert(SubReg.second);596}597598// Get the sum of this register's unit weights.599unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {600unsigned Weight = 0;601for (unsigned RegUnit : RegUnits) {602Weight += RegBank.getRegUnit(RegUnit).Weight;603}604return Weight;605}606607//===----------------------------------------------------------------------===//608// RegisterTuples609//===----------------------------------------------------------------------===//610611// A RegisterTuples def is used to generate pseudo-registers from lists of612// sub-registers. We provide a SetTheory expander class that returns the new613// registers.614namespace {615616struct TupleExpander : SetTheory::Expander {617// Reference to SynthDefs in the containing CodeGenRegBank, to keep track of618// the synthesized definitions for their lifetime.619std::vector<std::unique_ptr<Record>> &SynthDefs;620621// Track all synthesized tuple names in order to detect duplicate definitions.622llvm::StringSet<> TupleNames;623624TupleExpander(std::vector<std::unique_ptr<Record>> &SynthDefs)625: SynthDefs(SynthDefs) {}626627void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {628std::vector<Record *> Indices = Def->getValueAsListOfDefs("SubRegIndices");629unsigned Dim = Indices.size();630ListInit *SubRegs = Def->getValueAsListInit("SubRegs");631if (Dim != SubRegs->size())632PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");633if (Dim < 2)634PrintFatalError(Def->getLoc(),635"Tuples must have at least 2 sub-registers");636637// Evaluate the sub-register lists to be zipped.638unsigned Length = ~0u;639SmallVector<SetTheory::RecSet, 4> Lists(Dim);640for (unsigned i = 0; i != Dim; ++i) {641ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());642Length = std::min(Length, unsigned(Lists[i].size()));643}644645if (Length == 0)646return;647648// Precompute some types.649Record *RegisterCl = Def->getRecords().getClass("Register");650RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);651std::vector<StringRef> RegNames =652Def->getValueAsListOfStrings("RegAsmNames");653654// Zip them up.655RecordKeeper &RK = Def->getRecords();656for (unsigned n = 0; n != Length; ++n) {657std::string Name;658Record *Proto = Lists[0][n];659std::vector<Init *> Tuple;660for (unsigned i = 0; i != Dim; ++i) {661Record *Reg = Lists[i][n];662if (i)663Name += '_';664Name += Reg->getName();665Tuple.push_back(DefInit::get(Reg));666}667668// Take the cost list of the first register in the tuple.669ListInit *CostList = Proto->getValueAsListInit("CostPerUse");670SmallVector<Init *, 2> CostPerUse;671CostPerUse.insert(CostPerUse.end(), CostList->begin(), CostList->end());672673StringInit *AsmName = StringInit::get(RK, "");674if (!RegNames.empty()) {675if (RegNames.size() <= n)676PrintFatalError(Def->getLoc(),677"Register tuple definition missing name for '" +678Name + "'.");679AsmName = StringInit::get(RK, RegNames[n]);680}681682// Create a new Record representing the synthesized register. This record683// is only for consumption by CodeGenRegister, it is not added to the684// RecordKeeper.685SynthDefs.emplace_back(686std::make_unique<Record>(Name, Def->getLoc(), Def->getRecords()));687Record *NewReg = SynthDefs.back().get();688Elts.insert(NewReg);689690// Detect duplicates among synthesized registers.691const auto Res = TupleNames.insert(NewReg->getName());692if (!Res.second)693PrintFatalError(Def->getLoc(),694"Register tuple redefines register '" + Name + "'.");695696// Copy Proto super-classes.697ArrayRef<std::pair<Record *, SMRange>> Supers = Proto->getSuperClasses();698for (const auto &SuperPair : Supers)699NewReg->addSuperClass(SuperPair.first, SuperPair.second);700701// Copy Proto fields.702for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {703RecordVal RV = Proto->getValues()[i];704705// Skip existing fields, like NAME.706if (NewReg->getValue(RV.getNameInit()))707continue;708709StringRef Field = RV.getName();710711// Replace the sub-register list with Tuple.712if (Field == "SubRegs")713RV.setValue(ListInit::get(Tuple, RegisterRecTy));714715if (Field == "AsmName")716RV.setValue(AsmName);717718// CostPerUse is aggregated from all Tuple members.719if (Field == "CostPerUse")720RV.setValue(ListInit::get(CostPerUse, CostList->getElementType()));721722// Composite registers are always covered by sub-registers.723if (Field == "CoveredBySubRegs")724RV.setValue(BitInit::get(RK, true));725726// Copy fields from the RegisterTuples def.727if (Field == "SubRegIndices" || Field == "CompositeIndices") {728NewReg->addValue(*Def->getValue(Field));729continue;730}731732// Some fields get their default uninitialized value.733if (Field == "DwarfNumbers" || Field == "DwarfAlias" ||734Field == "Aliases") {735if (const RecordVal *DefRV = RegisterCl->getValue(Field))736NewReg->addValue(*DefRV);737continue;738}739740// Everything else is copied from Proto.741NewReg->addValue(RV);742}743}744}745};746747} // end anonymous namespace748749//===----------------------------------------------------------------------===//750// CodeGenRegisterClass751//===----------------------------------------------------------------------===//752753static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {754llvm::sort(M, deref<std::less<>>());755M.erase(llvm::unique(M, deref<std::equal_to<>>()), M.end());756}757758CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)759: TheDef(R), Name(std::string(R->getName())),760TopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1), TSFlags(0) {761GeneratePressureSet = R->getValueAsBit("GeneratePressureSet");762std::vector<Record *> TypeList = R->getValueAsListOfDefs("RegTypes");763if (TypeList.empty())764PrintFatalError(R->getLoc(), "RegTypes list must not be empty!");765for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {766Record *Type = TypeList[i];767if (!Type->isSubClassOf("ValueType"))768PrintFatalError(R->getLoc(),769"RegTypes list member '" + Type->getName() +770"' does not derive from the ValueType class!");771VTs.push_back(getValueTypeByHwMode(Type, RegBank.getHwModes()));772}773774// Allocation order 0 is the full set. AltOrders provides others.775const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);776ListInit *AltOrders = R->getValueAsListInit("AltOrders");777Orders.resize(1 + AltOrders->size());778779// Default allocation order always contains all registers.780Artificial = true;781for (unsigned i = 0, e = Elements->size(); i != e; ++i) {782Orders[0].push_back((*Elements)[i]);783const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);784Members.push_back(Reg);785Artificial &= Reg->Artificial;786TopoSigs.set(Reg->getTopoSig());787}788sortAndUniqueRegisters(Members);789790// Alternative allocation orders may be subsets.791SetTheory::RecSet Order;792for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {793RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());794Orders[1 + i].append(Order.begin(), Order.end());795// Verify that all altorder members are regclass members.796while (!Order.empty()) {797CodeGenRegister *Reg = RegBank.getReg(Order.back());798Order.pop_back();799if (!contains(Reg))800PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +801" is not a class member");802}803}804805Namespace = R->getValueAsString("Namespace");806807if (const RecordVal *RV = R->getValue("RegInfos"))808if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue()))809RSI = RegSizeInfoByHwMode(DI->getDef(), RegBank.getHwModes());810unsigned Size = R->getValueAsInt("Size");811assert((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&812"Impossible to determine register size");813if (!RSI.hasDefault()) {814RegSizeInfo RI;815RI.RegSize = RI.SpillSize =816Size ? Size : VTs[0].getSimple().getSizeInBits();817RI.SpillAlignment = R->getValueAsInt("Alignment");818RSI.insertRegSizeForMode(DefaultMode, RI);819}820821CopyCost = R->getValueAsInt("CopyCost");822Allocatable = R->getValueAsBit("isAllocatable");823AltOrderSelect = R->getValueAsString("AltOrderSelect");824int AllocationPriority = R->getValueAsInt("AllocationPriority");825if (!isUInt<5>(AllocationPriority))826PrintFatalError(R->getLoc(), "AllocationPriority out of range [0,31]");827this->AllocationPriority = AllocationPriority;828829GlobalPriority = R->getValueAsBit("GlobalPriority");830831BitsInit *TSF = R->getValueAsBitsInit("TSFlags");832for (unsigned I = 0, E = TSF->getNumBits(); I != E; ++I) {833BitInit *Bit = cast<BitInit>(TSF->getBit(I));834TSFlags |= uint8_t(Bit->getValue()) << I;835}836}837838// Create an inferred register class that was missing from the .td files.839// Most properties will be inherited from the closest super-class after the840// class structure has been computed.841CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,842StringRef Name, Key Props)843: Members(*Props.Members), TheDef(nullptr), Name(std::string(Name)),844TopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1), RSI(Props.RSI),845CopyCost(0), Allocatable(true), AllocationPriority(0),846GlobalPriority(false), TSFlags(0) {847Artificial = true;848GeneratePressureSet = false;849for (const auto R : Members) {850TopoSigs.set(R->getTopoSig());851Artificial &= R->Artificial;852}853}854855// Compute inherited propertied for a synthesized register class.856void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {857assert(!getDef() && "Only synthesized classes can inherit properties");858assert(!SuperClasses.empty() && "Synthesized class without super class");859860// The last super-class is the smallest one.861CodeGenRegisterClass &Super = *SuperClasses.back();862863// Most properties are copied directly.864// Exceptions are members, size, and alignment865Namespace = Super.Namespace;866VTs = Super.VTs;867CopyCost = Super.CopyCost;868// Check for allocatable superclasses.869Allocatable = any_of(SuperClasses, [&](const CodeGenRegisterClass *S) {870return S->Allocatable;871});872AltOrderSelect = Super.AltOrderSelect;873AllocationPriority = Super.AllocationPriority;874GlobalPriority = Super.GlobalPriority;875TSFlags = Super.TSFlags;876GeneratePressureSet |= Super.GeneratePressureSet;877878// Copy all allocation orders, filter out foreign registers from the larger879// super-class.880Orders.resize(Super.Orders.size());881for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)882for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)883if (contains(RegBank.getReg(Super.Orders[i][j])))884Orders[i].push_back(Super.Orders[i][j]);885}886887bool CodeGenRegisterClass::hasType(const ValueTypeByHwMode &VT) const {888if (llvm::is_contained(VTs, VT))889return true;890891// If VT is not identical to any of this class's types, but is a simple892// type, check if any of the types for this class contain it under some893// mode.894// The motivating example came from RISC-V, where (likely because of being895// guarded by "64-bit" predicate), the type of X5 was {*:[i64]}, but the896// type in GRC was {*:[i32], m1:[i64]}.897if (VT.isSimple()) {898MVT T = VT.getSimple();899for (const ValueTypeByHwMode &OurVT : VTs) {900if (llvm::count_if(OurVT, [T](auto &&P) { return P.second == T; }))901return true;902}903}904return false;905}906907bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {908return std::binary_search(Members.begin(), Members.end(), Reg,909deref<std::less<>>());910}911912unsigned CodeGenRegisterClass::getWeight(const CodeGenRegBank &RegBank) const {913if (TheDef && !TheDef->isValueUnset("Weight"))914return TheDef->getValueAsInt("Weight");915916if (Members.empty() || Artificial)917return 0;918919return (*Members.begin())->getWeight(RegBank);920}921922namespace llvm {923924raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {925OS << "{ " << K.RSI;926for (const auto R : *K.Members)927OS << ", " << R->getName();928return OS << " }";929}930931} // end namespace llvm932933// This is a simple lexicographical order that can be used to search for sets.934// It is not the same as the topological order provided by TopoOrderRC.935bool CodeGenRegisterClass::Key::operator<(936const CodeGenRegisterClass::Key &B) const {937assert(Members && B.Members);938return std::tie(*Members, RSI) < std::tie(*B.Members, B.RSI);939}940941// Returns true if RC is a strict subclass.942// RC is a sub-class of this class if it is a valid replacement for any943// instruction operand where a register of this classis required. It must944// satisfy these conditions:945//946// 1. All RC registers are also in this.947// 2. The RC spill size must not be smaller than our spill size.948// 3. RC spill alignment must be compatible with ours.949//950static bool testSubClass(const CodeGenRegisterClass *A,951const CodeGenRegisterClass *B) {952return A->RSI.isSubClassOf(B->RSI) &&953std::includes(A->getMembers().begin(), A->getMembers().end(),954B->getMembers().begin(), B->getMembers().end(),955deref<std::less<>>());956}957958/// Sorting predicate for register classes. This provides a topological959/// ordering that arranges all register classes before their sub-classes.960///961/// Register classes with the same registers, spill size, and alignment form a962/// clique. They will be ordered alphabetically.963///964static bool TopoOrderRC(const CodeGenRegisterClass &PA,965const CodeGenRegisterClass &PB) {966auto *A = &PA;967auto *B = &PB;968if (A == B)969return false;970971if (A->RSI < B->RSI)972return true;973if (A->RSI != B->RSI)974return false;975976// Order by descending set size. Note that the classes' allocation order may977// not have been computed yet. The Members set is always vaild.978if (A->getMembers().size() > B->getMembers().size())979return true;980if (A->getMembers().size() < B->getMembers().size())981return false;982983// Finally order by name as a tie breaker.984return StringRef(A->getName()) < B->getName();985}986987std::string CodeGenRegisterClass::getNamespaceQualification() const {988return Namespace.empty() ? "" : (Namespace + "::").str();989}990991std::string CodeGenRegisterClass::getQualifiedName() const {992return getNamespaceQualification() + getName();993}994995std::string CodeGenRegisterClass::getIdName() const {996return getName() + "RegClassID";997}998999std::string CodeGenRegisterClass::getQualifiedIdName() const {1000return getNamespaceQualification() + getIdName();1001}10021003// Compute sub-classes of all register classes.1004// Assume the classes are ordered topologically.1005void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {1006auto &RegClasses = RegBank.getRegClasses();10071008// Visit backwards so sub-classes are seen first.1009for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {1010CodeGenRegisterClass &RC = *I;1011RC.SubClasses.resize(RegClasses.size());1012RC.SubClasses.set(RC.EnumValue);1013if (RC.Artificial)1014continue;10151016// Normally, all subclasses have IDs >= rci, unless RC is part of a clique.1017for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {1018CodeGenRegisterClass &SubRC = *I2;1019if (RC.SubClasses.test(SubRC.EnumValue))1020continue;1021if (!testSubClass(&RC, &SubRC))1022continue;1023// SubRC is a sub-class. Grap all its sub-classes so we won't have to1024// check them again.1025RC.SubClasses |= SubRC.SubClasses;1026}10271028// Sweep up missed clique members. They will be immediately preceding RC.1029for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)1030RC.SubClasses.set(I2->EnumValue);1031}10321033// Compute the SuperClasses lists from the SubClasses vectors.1034for (auto &RC : RegClasses) {1035const BitVector &SC = RC.getSubClasses();1036auto I = RegClasses.begin();1037for (int s = 0, next_s = SC.find_first(); next_s != -1;1038next_s = SC.find_next(s)) {1039std::advance(I, next_s - s);1040s = next_s;1041if (&*I == &RC)1042continue;1043I->SuperClasses.push_back(&RC);1044}1045}10461047// With the class hierarchy in place, let synthesized register classes inherit1048// properties from their closest super-class. The iteration order here can1049// propagate properties down multiple levels.1050for (auto &RC : RegClasses)1051if (!RC.getDef())1052RC.inheritProperties(RegBank);1053}10541055std::optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>1056CodeGenRegisterClass::getMatchingSubClassWithSubRegs(1057CodeGenRegBank &RegBank, const CodeGenSubRegIndex *SubIdx) const {1058auto WeakSizeOrder = [this](const CodeGenRegisterClass *A,1059const CodeGenRegisterClass *B) {1060// If there are multiple, identical register classes, prefer the original1061// register class.1062if (A == B)1063return false;1064if (A->getMembers().size() == B->getMembers().size())1065return A == this;1066return A->getMembers().size() > B->getMembers().size();1067};10681069auto &RegClasses = RegBank.getRegClasses();10701071// Find all the subclasses of this one that fully support the sub-register1072// index and order them by size. BiggestSuperRC should always be first.1073CodeGenRegisterClass *BiggestSuperRegRC = getSubClassWithSubReg(SubIdx);1074if (!BiggestSuperRegRC)1075return std::nullopt;1076BitVector SuperRegRCsBV = BiggestSuperRegRC->getSubClasses();1077std::vector<CodeGenRegisterClass *> SuperRegRCs;1078for (auto &RC : RegClasses)1079if (SuperRegRCsBV[RC.EnumValue])1080SuperRegRCs.emplace_back(&RC);1081llvm::stable_sort(SuperRegRCs, WeakSizeOrder);10821083assert(SuperRegRCs.front() == BiggestSuperRegRC &&1084"Biggest class wasn't first");10851086// Find all the subreg classes and order them by size too.1087std::vector<std::pair<CodeGenRegisterClass *, BitVector>> SuperRegClasses;1088for (auto &RC : RegClasses) {1089BitVector SuperRegClassesBV(RegClasses.size());1090RC.getSuperRegClasses(SubIdx, SuperRegClassesBV);1091if (SuperRegClassesBV.any())1092SuperRegClasses.push_back(std::pair(&RC, SuperRegClassesBV));1093}1094llvm::stable_sort(SuperRegClasses,1095[&](const std::pair<CodeGenRegisterClass *, BitVector> &A,1096const std::pair<CodeGenRegisterClass *, BitVector> &B) {1097return WeakSizeOrder(A.first, B.first);1098});10991100// Find the biggest subclass and subreg class such that R:subidx is in the1101// subreg class for all R in subclass.1102//1103// For example:1104// All registers in X86's GR64 have a sub_32bit subregister but no class1105// exists that contains all the 32-bit subregisters because GR64 contains RIP1106// but GR32 does not contain EIP. Instead, we constrain SuperRegRC to1107// GR32_with_sub_8bit (which is identical to GR32_with_sub_32bit) and then,1108// having excluded RIP, we are able to find a SubRegRC (GR32).1109CodeGenRegisterClass *ChosenSuperRegClass = nullptr;1110CodeGenRegisterClass *SubRegRC = nullptr;1111for (auto *SuperRegRC : SuperRegRCs) {1112for (const auto &SuperRegClassPair : SuperRegClasses) {1113const BitVector &SuperRegClassBV = SuperRegClassPair.second;1114if (SuperRegClassBV[SuperRegRC->EnumValue]) {1115SubRegRC = SuperRegClassPair.first;1116ChosenSuperRegClass = SuperRegRC;11171118// If SubRegRC is bigger than SuperRegRC then there are members of1119// SubRegRC that don't have super registers via SubIdx. Keep looking to1120// find a better fit and fall back on this one if there isn't one.1121//1122// This is intended to prevent X86 from making odd choices such as1123// picking LOW32_ADDR_ACCESS_RBP instead of GR32 in the example above.1124// LOW32_ADDR_ACCESS_RBP is a valid choice but contains registers that1125// aren't subregisters of SuperRegRC whereas GR32 has a direct 1:11126// mapping.1127if (SuperRegRC->getMembers().size() >= SubRegRC->getMembers().size())1128return std::pair(ChosenSuperRegClass, SubRegRC);1129}1130}11311132// If we found a fit but it wasn't quite ideal because SubRegRC had excess1133// registers, then we're done.1134if (ChosenSuperRegClass)1135return std::pair(ChosenSuperRegClass, SubRegRC);1136}11371138return std::nullopt;1139}11401141void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,1142BitVector &Out) const {1143auto FindI = SuperRegClasses.find(SubIdx);1144if (FindI == SuperRegClasses.end())1145return;1146for (CodeGenRegisterClass *RC : FindI->second)1147Out.set(RC->EnumValue);1148}11491150// Populate a unique sorted list of units from a register set.1151void CodeGenRegisterClass::buildRegUnitSet(1152const CodeGenRegBank &RegBank, std::vector<unsigned> &RegUnits) const {1153std::vector<unsigned> TmpUnits;1154for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI) {1155const RegUnit &RU = RegBank.getRegUnit(*UnitI);1156if (!RU.Artificial)1157TmpUnits.push_back(*UnitI);1158}1159llvm::sort(TmpUnits);1160std::unique_copy(TmpUnits.begin(), TmpUnits.end(),1161std::back_inserter(RegUnits));1162}11631164//===----------------------------------------------------------------------===//1165// CodeGenRegisterCategory1166//===----------------------------------------------------------------------===//11671168CodeGenRegisterCategory::CodeGenRegisterCategory(CodeGenRegBank &RegBank,1169Record *R)1170: TheDef(R), Name(std::string(R->getName())) {1171for (Record *RegClass : R->getValueAsListOfDefs("Classes"))1172Classes.push_back(RegBank.getRegClass(RegClass));1173}11741175//===----------------------------------------------------------------------===//1176// CodeGenRegBank1177//===----------------------------------------------------------------------===//11781179CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records,1180const CodeGenHwModes &Modes)1181: CGH(Modes) {1182// Configure register Sets to understand register classes and tuples.1183Sets.addFieldExpander("RegisterClass", "MemberList");1184Sets.addFieldExpander("CalleeSavedRegs", "SaveList");1185Sets.addExpander("RegisterTuples",1186std::make_unique<TupleExpander>(SynthDefs));11871188// Read in the user-defined (named) sub-register indices.1189// More indices will be synthesized later.1190std::vector<Record *> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");1191llvm::sort(SRIs, LessRecord());1192for (unsigned i = 0, e = SRIs.size(); i != e; ++i)1193getSubRegIdx(SRIs[i]);1194// Build composite maps from ComposedOf fields.1195for (auto &Idx : SubRegIndices)1196Idx.updateComponents(*this);11971198// Read in the register and register tuple definitions.1199std::vector<Record *> Regs = Records.getAllDerivedDefinitions("Register");1200if (!Regs.empty() && Regs[0]->isSubClassOf("X86Reg")) {1201// For X86, we need to sort Registers and RegisterTuples together to list1202// new registers and register tuples at a later position. So that we can1203// reduce unnecessary iterations on unsupported registers in LiveVariables.1204// TODO: Remove this logic when migrate from LiveVariables to LiveIntervals1205// completely.1206std::vector<Record *> Tups =1207Records.getAllDerivedDefinitions("RegisterTuples");1208for (Record *R : Tups) {1209// Expand tuples and merge the vectors1210std::vector<Record *> TupRegs = *Sets.expand(R);1211Regs.insert(Regs.end(), TupRegs.begin(), TupRegs.end());1212}12131214llvm::sort(Regs, LessRecordRegister());1215// Assign the enumeration values.1216for (unsigned i = 0, e = Regs.size(); i != e; ++i)1217getReg(Regs[i]);1218} else {1219llvm::sort(Regs, LessRecordRegister());1220// Assign the enumeration values.1221for (unsigned i = 0, e = Regs.size(); i != e; ++i)1222getReg(Regs[i]);12231224// Expand tuples and number the new registers.1225std::vector<Record *> Tups =1226Records.getAllDerivedDefinitions("RegisterTuples");12271228for (Record *R : Tups) {1229std::vector<Record *> TupRegs = *Sets.expand(R);1230llvm::sort(TupRegs, LessRecordRegister());1231for (Record *RC : TupRegs)1232getReg(RC);1233}1234}12351236// Now all the registers are known. Build the object graph of explicit1237// register-register references.1238for (auto &Reg : Registers)1239Reg.buildObjectGraph(*this);12401241// Compute register name map.1242for (auto &Reg : Registers)1243// FIXME: This could just be RegistersByName[name] = register, except that1244// causes some failures in MIPS - perhaps they have duplicate register name1245// entries? (or maybe there's a reason for it - I don't know much about this1246// code, just drive-by refactoring)1247RegistersByName.insert(1248std::pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));12491250// Precompute all sub-register maps.1251// This will create Composite entries for all inferred sub-register indices.1252for (auto &Reg : Registers)1253Reg.computeSubRegs(*this);12541255// Compute transitive closure of subregister index ConcatenationOf vectors1256// and initialize ConcatIdx map.1257for (CodeGenSubRegIndex &SRI : SubRegIndices) {1258SRI.computeConcatTransitiveClosure();1259if (!SRI.ConcatenationOf.empty())1260ConcatIdx.insert(1261std::pair(SmallVector<CodeGenSubRegIndex *, 8>(1262SRI.ConcatenationOf.begin(), SRI.ConcatenationOf.end()),1263&SRI));1264}12651266// Infer even more sub-registers by combining leading super-registers.1267for (auto &Reg : Registers)1268if (Reg.CoveredBySubRegs)1269Reg.computeSecondarySubRegs(*this);12701271// After the sub-register graph is complete, compute the topologically1272// ordered SuperRegs list.1273for (auto &Reg : Registers)1274Reg.computeSuperRegs(*this);12751276// For each pair of Reg:SR, if both are non-artificial, mark the1277// corresponding sub-register index as non-artificial.1278for (auto &Reg : Registers) {1279if (Reg.Artificial)1280continue;1281for (auto P : Reg.getSubRegs()) {1282const CodeGenRegister *SR = P.second;1283if (!SR->Artificial)1284P.first->Artificial = false;1285}1286}12871288// Native register units are associated with a leaf register. They've all been1289// discovered now.1290NumNativeRegUnits = RegUnits.size();12911292// Read in register class definitions.1293std::vector<Record *> RCs = Records.getAllDerivedDefinitions("RegisterClass");1294if (RCs.empty())1295PrintFatalError("No 'RegisterClass' subclasses defined!");12961297// Allocate user-defined register classes.1298for (auto *R : RCs) {1299RegClasses.emplace_back(*this, R);1300CodeGenRegisterClass &RC = RegClasses.back();1301if (!RC.Artificial)1302addToMaps(&RC);1303}13041305// Infer missing classes to create a full algebra.1306computeInferredRegisterClasses();13071308// Order register classes topologically and assign enum values.1309RegClasses.sort(TopoOrderRC);1310unsigned i = 0;1311for (auto &RC : RegClasses)1312RC.EnumValue = i++;1313CodeGenRegisterClass::computeSubClasses(*this);13141315// Read in the register category definitions.1316std::vector<Record *> RCats =1317Records.getAllDerivedDefinitions("RegisterCategory");1318for (auto *R : RCats)1319RegCategories.emplace_back(*this, R);1320}13211322// Create a synthetic CodeGenSubRegIndex without a corresponding Record.1323CodeGenSubRegIndex *CodeGenRegBank::createSubRegIndex(StringRef Name,1324StringRef Namespace) {1325SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);1326return &SubRegIndices.back();1327}13281329CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {1330CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];1331if (Idx)1332return Idx;1333SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1, getHwModes());1334Idx = &SubRegIndices.back();1335return Idx;1336}13371338const CodeGenSubRegIndex *1339CodeGenRegBank::findSubRegIdx(const Record *Def) const {1340return Def2SubRegIdx.lookup(Def);1341}13421343CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {1344CodeGenRegister *&Reg = Def2Reg[Def];1345if (Reg)1346return Reg;1347Registers.emplace_back(Def, Registers.size() + 1);1348Reg = &Registers.back();1349return Reg;1350}13511352void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {1353if (Record *Def = RC->getDef())1354Def2RC.insert(std::pair(Def, RC));13551356// Duplicate classes are rejected by insert().1357// That's OK, we only care about the properties handled by CGRC::Key.1358CodeGenRegisterClass::Key K(*RC);1359Key2RC.insert(std::pair(K, RC));1360}13611362// Create a synthetic sub-class if it is missing.1363CodeGenRegisterClass *1364CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,1365const CodeGenRegister::Vec *Members,1366StringRef Name) {1367// Synthetic sub-class has the same size and alignment as RC.1368CodeGenRegisterClass::Key K(Members, RC->RSI);1369RCKeyMap::const_iterator FoundI = Key2RC.find(K);1370if (FoundI != Key2RC.end())1371return FoundI->second;13721373// Sub-class doesn't exist, create a new one.1374RegClasses.emplace_back(*this, Name, K);1375addToMaps(&RegClasses.back());1376return &RegClasses.back();1377}13781379CodeGenRegisterClass *CodeGenRegBank::getRegClass(const Record *Def) const {1380if (CodeGenRegisterClass *RC = Def2RC.lookup(Def))1381return RC;13821383PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");1384}13851386CodeGenSubRegIndex *1387CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,1388CodeGenSubRegIndex *B) {1389// Look for an existing entry.1390CodeGenSubRegIndex *Comp = A->compose(B);1391if (Comp)1392return Comp;13931394// None exists, synthesize one.1395std::string Name = A->getName() + "_then_" + B->getName();1396Comp = createSubRegIndex(Name, A->getNamespace());1397A->addComposite(B, Comp, getHwModes());1398return Comp;1399}14001401CodeGenSubRegIndex *CodeGenRegBank::getConcatSubRegIndex(1402const SmallVector<CodeGenSubRegIndex *, 8> &Parts,1403const CodeGenHwModes &CGH) {1404assert(Parts.size() > 1 && "Need two parts to concatenate");1405#ifndef NDEBUG1406for (CodeGenSubRegIndex *Idx : Parts) {1407assert(Idx->ConcatenationOf.empty() && "No transitive closure?");1408}1409#endif14101411// Look for an existing entry.1412CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];1413if (Idx)1414return Idx;14151416// None exists, synthesize one.1417std::string Name = Parts.front()->getName();1418const unsigned UnknownSize = (uint16_t)-1;14191420for (unsigned i = 1, e = Parts.size(); i != e; ++i) {1421Name += '_';1422Name += Parts[i]->getName();1423}14241425Idx = createSubRegIndex(Name, Parts.front()->getNamespace());1426Idx->ConcatenationOf.assign(Parts.begin(), Parts.end());14271428unsigned NumModes = CGH.getNumModeIds();1429for (unsigned M = 0; M < NumModes; ++M) {1430const CodeGenSubRegIndex *Part = Parts.front();14311432// Determine whether all parts are contiguous.1433bool IsContinuous = true;1434const SubRegRange &FirstPartRange = Part->Range.get(M);1435unsigned Size = FirstPartRange.Size;1436unsigned LastOffset = FirstPartRange.Offset;1437unsigned LastSize = FirstPartRange.Size;14381439for (unsigned i = 1, e = Parts.size(); i != e; ++i) {1440Part = Parts[i];1441Name += '_';1442Name += Part->getName();14431444const SubRegRange &PartRange = Part->Range.get(M);1445if (Size == UnknownSize || PartRange.Size == UnknownSize)1446Size = UnknownSize;1447else1448Size += PartRange.Size;1449if (LastSize == UnknownSize ||1450PartRange.Offset != (LastOffset + LastSize))1451IsContinuous = false;1452LastOffset = PartRange.Offset;1453LastSize = PartRange.Size;1454}1455unsigned Offset = IsContinuous ? FirstPartRange.Offset : -1;1456Idx->Range.get(M) = SubRegRange(Size, Offset);1457}14581459return Idx;1460}14611462void CodeGenRegBank::computeComposites() {1463using RegMap = std::map<const CodeGenRegister *, const CodeGenRegister *>;14641465// Subreg -> { Reg->Reg }, where the right-hand side is the mapping from1466// register to (sub)register associated with the action of the left-hand1467// side subregister.1468std::map<const CodeGenSubRegIndex *, RegMap> SubRegAction;1469for (const CodeGenRegister &R : Registers) {1470const CodeGenRegister::SubRegMap &SM = R.getSubRegs();1471for (std::pair<const CodeGenSubRegIndex *, const CodeGenRegister *> P : SM)1472SubRegAction[P.first].insert({&R, P.second});1473}14741475// Calculate the composition of two subregisters as compositions of their1476// associated actions.1477auto compose = [&SubRegAction](const CodeGenSubRegIndex *Sub1,1478const CodeGenSubRegIndex *Sub2) {1479RegMap C;1480const RegMap &Img1 = SubRegAction.at(Sub1);1481const RegMap &Img2 = SubRegAction.at(Sub2);1482for (std::pair<const CodeGenRegister *, const CodeGenRegister *> P : Img1) {1483auto F = Img2.find(P.second);1484if (F != Img2.end())1485C.insert({P.first, F->second});1486}1487return C;1488};14891490// Check if the two maps agree on the intersection of their domains.1491auto agree = [](const RegMap &Map1, const RegMap &Map2) {1492// Technically speaking, an empty map agrees with any other map, but1493// this could flag false positives. We're interested in non-vacuous1494// agreements.1495if (Map1.empty() || Map2.empty())1496return false;1497for (std::pair<const CodeGenRegister *, const CodeGenRegister *> P : Map1) {1498auto F = Map2.find(P.first);1499if (F == Map2.end() || P.second != F->second)1500return false;1501}1502return true;1503};15041505using CompositePair =1506std::pair<const CodeGenSubRegIndex *, const CodeGenSubRegIndex *>;1507SmallSet<CompositePair, 4> UserDefined;1508for (const CodeGenSubRegIndex &Idx : SubRegIndices)1509for (auto P : Idx.getComposites())1510UserDefined.insert(std::pair(&Idx, P.first));15111512// Keep track of TopoSigs visited. We only need to visit each TopoSig once,1513// and many registers will share TopoSigs on regular architectures.1514BitVector TopoSigs(getNumTopoSigs());15151516for (const auto &Reg1 : Registers) {1517// Skip identical subreg structures already processed.1518if (TopoSigs.test(Reg1.getTopoSig()))1519continue;1520TopoSigs.set(Reg1.getTopoSig());15211522const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();1523for (auto I1 : SRM1) {1524CodeGenSubRegIndex *Idx1 = I1.first;1525CodeGenRegister *Reg2 = I1.second;1526// Ignore identity compositions.1527if (&Reg1 == Reg2)1528continue;1529const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();1530// Try composing Idx1 with another SubRegIndex.1531for (auto I2 : SRM2) {1532CodeGenSubRegIndex *Idx2 = I2.first;1533CodeGenRegister *Reg3 = I2.second;1534// Ignore identity compositions.1535if (Reg2 == Reg3)1536continue;1537// OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.1538CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);1539assert(Idx3 && "Sub-register doesn't have an index");15401541// Conflicting composition? Emit a warning but allow it.1542if (CodeGenSubRegIndex *Prev =1543Idx1->addComposite(Idx2, Idx3, getHwModes())) {1544// If the composition was not user-defined, always emit a warning.1545if (!UserDefined.count({Idx1, Idx2}) ||1546agree(compose(Idx1, Idx2), SubRegAction.at(Idx3)))1547PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +1548" and " + Idx2->getQualifiedName() +1549" compose ambiguously as " + Prev->getQualifiedName() +1550" or " + Idx3->getQualifiedName());1551}1552}1553}1554}1555}15561557// Compute lane masks. This is similar to register units, but at the1558// sub-register index level. Each bit in the lane mask is like a register unit1559// class, and two lane masks will have a bit in common if two sub-register1560// indices overlap in some register.1561//1562// Conservatively share a lane mask bit if two sub-register indices overlap in1563// some registers, but not in others. That shouldn't happen a lot.1564void CodeGenRegBank::computeSubRegLaneMasks() {1565// First assign individual bits to all the leaf indices.1566unsigned Bit = 0;1567// Determine mask of lanes that cover their registers.1568CoveringLanes = LaneBitmask::getAll();1569for (auto &Idx : SubRegIndices) {1570if (Idx.getComposites().empty()) {1571if (Bit > LaneBitmask::BitWidth) {1572PrintFatalError(1573Twine("Ran out of lanemask bits to represent subregister ") +1574Idx.getName());1575}1576Idx.LaneMask = LaneBitmask::getLane(Bit);1577++Bit;1578} else {1579Idx.LaneMask = LaneBitmask::getNone();1580}1581}15821583// Compute transformation sequences for composeSubRegIndexLaneMask. The idea1584// here is that for each possible target subregister we look at the leafs1585// in the subregister graph that compose for this target and create1586// transformation sequences for the lanemasks. Each step in the sequence1587// consists of a bitmask and a bitrotate operation. As the rotation amounts1588// are usually the same for many subregisters we can easily combine the steps1589// by combining the masks.1590for (const auto &Idx : SubRegIndices) {1591const auto &Composites = Idx.getComposites();1592auto &LaneTransforms = Idx.CompositionLaneMaskTransform;15931594if (Composites.empty()) {1595// Moving from a class with no subregisters we just had a single lane:1596// The subregister must be a leaf subregister and only occupies 1 bit.1597// Move the bit from the class without subregisters into that position.1598unsigned DstBit = Idx.LaneMask.getHighestLane();1599assert(Idx.LaneMask == LaneBitmask::getLane(DstBit) &&1600"Must be a leaf subregister");1601MaskRolPair MaskRol = {LaneBitmask::getLane(0), (uint8_t)DstBit};1602LaneTransforms.push_back(MaskRol);1603} else {1604// Go through all leaf subregisters and find the ones that compose with1605// Idx. These make out all possible valid bits in the lane mask we want to1606// transform. Looking only at the leafs ensure that only a single bit in1607// the mask is set.1608unsigned NextBit = 0;1609for (auto &Idx2 : SubRegIndices) {1610// Skip non-leaf subregisters.1611if (!Idx2.getComposites().empty())1612continue;1613// Replicate the behaviour from the lane mask generation loop above.1614unsigned SrcBit = NextBit;1615LaneBitmask SrcMask = LaneBitmask::getLane(SrcBit);1616if (NextBit < LaneBitmask::BitWidth - 1)1617++NextBit;1618assert(Idx2.LaneMask == SrcMask);16191620// Get the composed subregister if there is any.1621auto C = Composites.find(&Idx2);1622if (C == Composites.end())1623continue;1624const CodeGenSubRegIndex *Composite = C->second;1625// The Composed subreg should be a leaf subreg too1626assert(Composite->getComposites().empty());16271628// Create Mask+Rotate operation and merge with existing ops if possible.1629unsigned DstBit = Composite->LaneMask.getHighestLane();1630int Shift = DstBit - SrcBit;1631uint8_t RotateLeft =1632Shift >= 0 ? (uint8_t)Shift : LaneBitmask::BitWidth + Shift;1633for (auto &I : LaneTransforms) {1634if (I.RotateLeft == RotateLeft) {1635I.Mask |= SrcMask;1636SrcMask = LaneBitmask::getNone();1637}1638}1639if (SrcMask.any()) {1640MaskRolPair MaskRol = {SrcMask, RotateLeft};1641LaneTransforms.push_back(MaskRol);1642}1643}1644}16451646// Optimize if the transformation consists of one step only: Set mask to1647// 0xffffffff (including some irrelevant invalid bits) so that it should1648// merge with more entries later while compressing the table.1649if (LaneTransforms.size() == 1)1650LaneTransforms[0].Mask = LaneBitmask::getAll();16511652// Further compression optimization: For invalid compositions resulting1653// in a sequence with 0 entries we can just pick any other. Choose1654// Mask 0xffffffff with Rotation 0.1655if (LaneTransforms.size() == 0) {1656MaskRolPair P = {LaneBitmask::getAll(), 0};1657LaneTransforms.push_back(P);1658}1659}16601661// FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented1662// by the sub-register graph? This doesn't occur in any known targets.16631664// Inherit lanes from composites.1665for (const auto &Idx : SubRegIndices) {1666LaneBitmask Mask = Idx.computeLaneMask();1667// If some super-registers without CoveredBySubRegs use this index, we can1668// no longer assume that the lanes are covering their registers.1669if (!Idx.AllSuperRegsCovered)1670CoveringLanes &= ~Mask;1671}16721673// Compute lane mask combinations for register classes.1674for (auto &RegClass : RegClasses) {1675LaneBitmask LaneMask;1676for (const auto &SubRegIndex : SubRegIndices) {1677if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)1678continue;1679LaneMask |= SubRegIndex.LaneMask;1680}16811682// For classes without any subregisters set LaneMask to 1 instead of 0.1683// This makes it easier for client code to handle classes uniformly.1684if (LaneMask.none())1685LaneMask = LaneBitmask::getLane(0);16861687RegClass.LaneMask = LaneMask;1688}1689}16901691namespace {16921693// UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is1694// the transitive closure of the union of overlapping register1695// classes. Together, the UberRegSets form a partition of the registers. If we1696// consider overlapping register classes to be connected, then each UberRegSet1697// is a set of connected components.1698//1699// An UberRegSet will likely be a horizontal slice of register names of1700// the same width. Nontrivial subregisters should then be in a separate1701// UberRegSet. But this property isn't required for valid computation of1702// register unit weights.1703//1704// A Weight field caches the max per-register unit weight in each UberRegSet.1705//1706// A set of SingularDeterminants flags single units of some register in this set1707// for which the unit weight equals the set weight. These units should not have1708// their weight increased.1709struct UberRegSet {1710CodeGenRegister::Vec Regs;1711unsigned Weight = 0;1712CodeGenRegister::RegUnitList SingularDeterminants;17131714UberRegSet() = default;1715};17161717} // end anonymous namespace17181719// Partition registers into UberRegSets, where each set is the transitive1720// closure of the union of overlapping register classes.1721//1722// UberRegSets[0] is a special non-allocatable set.1723static void computeUberSets(std::vector<UberRegSet> &UberSets,1724std::vector<UberRegSet *> &RegSets,1725CodeGenRegBank &RegBank) {1726const auto &Registers = RegBank.getRegisters();17271728// The Register EnumValue is one greater than its index into Registers.1729assert(Registers.size() == Registers.back().EnumValue &&1730"register enum value mismatch");17311732// For simplicitly make the SetID the same as EnumValue.1733IntEqClasses UberSetIDs(Registers.size() + 1);1734BitVector AllocatableRegs(Registers.size() + 1);1735for (auto &RegClass : RegBank.getRegClasses()) {1736if (!RegClass.Allocatable)1737continue;17381739const CodeGenRegister::Vec &Regs = RegClass.getMembers();1740if (Regs.empty())1741continue;17421743unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);1744assert(USetID && "register number 0 is invalid");17451746AllocatableRegs.set((*Regs.begin())->EnumValue);1747for (const CodeGenRegister *CGR : llvm::drop_begin(Regs)) {1748AllocatableRegs.set(CGR->EnumValue);1749UberSetIDs.join(USetID, CGR->EnumValue);1750}1751}1752// Combine non-allocatable regs.1753for (const auto &Reg : Registers) {1754unsigned RegNum = Reg.EnumValue;1755if (AllocatableRegs.test(RegNum))1756continue;17571758UberSetIDs.join(0, RegNum);1759}1760UberSetIDs.compress();17611762// Make the first UberSet a special unallocatable set.1763unsigned ZeroID = UberSetIDs[0];17641765// Insert Registers into the UberSets formed by union-find.1766// Do not resize after this.1767UberSets.resize(UberSetIDs.getNumClasses());1768unsigned i = 0;1769for (const CodeGenRegister &Reg : Registers) {1770unsigned USetID = UberSetIDs[Reg.EnumValue];1771if (!USetID)1772USetID = ZeroID;1773else if (USetID == ZeroID)1774USetID = 0;17751776UberRegSet *USet = &UberSets[USetID];1777USet->Regs.push_back(&Reg);1778RegSets[i++] = USet;1779}1780}17811782// Recompute each UberSet weight after changing unit weights.1783static void computeUberWeights(std::vector<UberRegSet> &UberSets,1784CodeGenRegBank &RegBank) {1785// Skip the first unallocatable set.1786for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),1787E = UberSets.end();1788I != E; ++I) {17891790// Initialize all unit weights in this set, and remember the max units/reg.1791const CodeGenRegister *Reg = nullptr;1792unsigned MaxWeight = 0, Weight = 0;1793for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {1794if (Reg != UnitI.getReg()) {1795if (Weight > MaxWeight)1796MaxWeight = Weight;1797Reg = UnitI.getReg();1798Weight = 0;1799}1800if (!RegBank.getRegUnit(*UnitI).Artificial) {1801unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;1802if (!UWeight) {1803UWeight = 1;1804RegBank.increaseRegUnitWeight(*UnitI, UWeight);1805}1806Weight += UWeight;1807}1808}1809if (Weight > MaxWeight)1810MaxWeight = Weight;1811if (I->Weight != MaxWeight) {1812LLVM_DEBUG(dbgs() << "UberSet " << I - UberSets.begin() << " Weight "1813<< MaxWeight;1814for (auto &Unit1815: I->Regs) dbgs()1816<< " " << Unit->getName();1817dbgs() << "\n");1818// Update the set weight.1819I->Weight = MaxWeight;1820}18211822// Find singular determinants.1823for (const auto R : I->Regs) {1824if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {1825I->SingularDeterminants |= R->getRegUnits();1826}1827}1828}1829}18301831// normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of1832// a register and its subregisters so that they have the same weight as their1833// UberSet. Self-recursion processes the subregister tree in postorder so1834// subregisters are normalized first.1835//1836// Side effects:1837// - creates new adopted register units1838// - causes superregisters to inherit adopted units1839// - increases the weight of "singular" units1840// - induces recomputation of UberWeights.1841static bool normalizeWeight(CodeGenRegister *Reg,1842std::vector<UberRegSet> &UberSets,1843std::vector<UberRegSet *> &RegSets,1844BitVector &NormalRegs,1845CodeGenRegister::RegUnitList &NormalUnits,1846CodeGenRegBank &RegBank) {1847NormalRegs.resize(std::max(Reg->EnumValue + 1, NormalRegs.size()));1848if (NormalRegs.test(Reg->EnumValue))1849return false;1850NormalRegs.set(Reg->EnumValue);18511852bool Changed = false;1853const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();1854for (auto SRI : SRM) {1855if (SRI.second == Reg)1856continue; // self-cycles happen18571858Changed |= normalizeWeight(SRI.second, UberSets, RegSets, NormalRegs,1859NormalUnits, RegBank);1860}1861// Postorder register normalization.18621863// Inherit register units newly adopted by subregisters.1864if (Reg->inheritRegUnits(RegBank))1865computeUberWeights(UberSets, RegBank);18661867// Check if this register is too skinny for its UberRegSet.1868UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];18691870unsigned RegWeight = Reg->getWeight(RegBank);1871if (UberSet->Weight > RegWeight) {1872// A register unit's weight can be adjusted only if it is the singular unit1873// for this register, has not been used to normalize a subregister's set,1874// and has not already been used to singularly determine this UberRegSet.1875unsigned AdjustUnit = *Reg->getRegUnits().begin();1876if (Reg->getRegUnits().count() != 1 || NormalUnits.test(AdjustUnit) ||1877UberSet->SingularDeterminants.test(AdjustUnit)) {1878// We don't have an adjustable unit, so adopt a new one.1879AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);1880Reg->adoptRegUnit(AdjustUnit);1881// Adopting a unit does not immediately require recomputing set weights.1882} else {1883// Adjust the existing single unit.1884if (!RegBank.getRegUnit(AdjustUnit).Artificial)1885RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);1886// The unit may be shared among sets and registers within this set.1887computeUberWeights(UberSets, RegBank);1888}1889Changed = true;1890}18911892// Mark these units normalized so superregisters can't change their weights.1893NormalUnits |= Reg->getRegUnits();18941895return Changed;1896}18971898// Compute a weight for each register unit created during getSubRegs.1899//1900// The goal is that two registers in the same class will have the same weight,1901// where each register's weight is defined as sum of its units' weights.1902void CodeGenRegBank::computeRegUnitWeights() {1903std::vector<UberRegSet> UberSets;1904std::vector<UberRegSet *> RegSets(Registers.size());1905computeUberSets(UberSets, RegSets, *this);1906// UberSets and RegSets are now immutable.19071908computeUberWeights(UberSets, *this);19091910// Iterate over each Register, normalizing the unit weights until reaching1911// a fix point.1912unsigned NumIters = 0;1913for (bool Changed = true; Changed; ++NumIters) {1914assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights");1915(void)NumIters;1916Changed = false;1917for (auto &Reg : Registers) {1918CodeGenRegister::RegUnitList NormalUnits;1919BitVector NormalRegs;1920Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,1921NormalUnits, *this);1922}1923}1924}19251926// Find a set in UniqueSets with the same elements as Set.1927// Return an iterator into UniqueSets.1928static std::vector<RegUnitSet>::const_iterator1929findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,1930const RegUnitSet &Set) {1931return find_if(UniqueSets,1932[&Set](const RegUnitSet &I) { return I.Units == Set.Units; });1933}19341935// Return true if the RUSubSet is a subset of RUSuperSet.1936static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,1937const std::vector<unsigned> &RUSuperSet) {1938return std::includes(RUSuperSet.begin(), RUSuperSet.end(), RUSubSet.begin(),1939RUSubSet.end());1940}19411942/// Iteratively prune unit sets. Prune subsets that are close to the superset,1943/// but with one or two registers removed. We occasionally have registers like1944/// APSR and PC thrown in with the general registers. We also see many1945/// special-purpose register subsets, such as tail-call and Thumb1946/// encodings. Generating all possible overlapping sets is combinatorial and1947/// overkill for modeling pressure. Ideally we could fix this statically in1948/// tablegen by (1) having the target define register classes that only include1949/// the allocatable registers and marking other classes as non-allocatable and1950/// (2) having a way to mark special purpose classes as "don't-care" classes for1951/// the purpose of pressure. However, we make an attempt to handle targets that1952/// are not nicely defined by merging nearly identical register unit sets1953/// statically. This generates smaller tables. Then, dynamically, we adjust the1954/// set limit by filtering the reserved registers.1955///1956/// Merge sets only if the units have the same weight. For example, on ARM,1957/// Q-tuples with ssub index 0 include all S regs but also include D16+. We1958/// should not expand the S set to include D regs.1959void CodeGenRegBank::pruneUnitSets() {1960assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");19611962// Form an equivalence class of UnitSets with no significant difference.1963std::vector<unsigned> SuperSetIDs;1964for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size(); SubIdx != EndIdx;1965++SubIdx) {1966const RegUnitSet &SubSet = RegUnitSets[SubIdx];1967unsigned SuperIdx = 0;1968for (; SuperIdx != EndIdx; ++SuperIdx) {1969if (SuperIdx == SubIdx)1970continue;19711972unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;1973const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];1974if (isRegUnitSubSet(SubSet.Units, SuperSet.Units) &&1975(SubSet.Units.size() + 3 > SuperSet.Units.size()) &&1976UnitWeight == RegUnits[SuperSet.Units[0]].Weight &&1977UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {1978LLVM_DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdx1979<< "\n");1980// We can pick any of the set names for the merged set. Go for the1981// shortest one to avoid picking the name of one of the classes that are1982// artificially created by tablegen. So "FPR128_lo" instead of1983// "QQQQ_with_qsub3_in_FPR128_lo".1984if (RegUnitSets[SubIdx].Name.size() < RegUnitSets[SuperIdx].Name.size())1985RegUnitSets[SuperIdx].Name = RegUnitSets[SubIdx].Name;1986break;1987}1988}1989if (SuperIdx == EndIdx)1990SuperSetIDs.push_back(SubIdx);1991}1992// Populate PrunedUnitSets with each equivalence class's superset.1993std::vector<RegUnitSet> PrunedUnitSets;1994PrunedUnitSets.reserve(SuperSetIDs.size());1995for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {1996unsigned SuperIdx = SuperSetIDs[i];1997PrunedUnitSets.emplace_back(RegUnitSets[SuperIdx].Name);1998PrunedUnitSets.back().Units = std::move(RegUnitSets[SuperIdx].Units);1999}2000RegUnitSets = std::move(PrunedUnitSets);2001}20022003// Create a RegUnitSet for each RegClass that contains all units in the class2004// including adopted units that are necessary to model register pressure. Then2005// iteratively compute RegUnitSets such that the union of any two overlapping2006// RegUnitSets is repreresented.2007//2008// RegisterInfoEmitter will map each RegClass to its RegUnitClass and any2009// RegUnitSet that is a superset of that RegUnitClass.2010void CodeGenRegBank::computeRegUnitSets() {2011assert(RegUnitSets.empty() && "dirty RegUnitSets");20122013// Compute a unique RegUnitSet for each RegClass.2014auto &RegClasses = getRegClasses();2015for (auto &RC : RegClasses) {2016if (!RC.Allocatable || RC.Artificial || !RC.GeneratePressureSet)2017continue;20182019// Compute a sorted list of units in this class.2020RegUnitSet RUSet(RC.getName());2021RC.buildRegUnitSet(*this, RUSet.Units);20222023// Find an existing RegUnitSet.2024if (findRegUnitSet(RegUnitSets, RUSet) == RegUnitSets.end())2025RegUnitSets.push_back(std::move(RUSet));2026}20272028if (RegUnitSets.empty())2029PrintFatalError("RegUnitSets cannot be empty!");20302031LLVM_DEBUG(dbgs() << "\nBefore pruning:\n"; for (unsigned USIdx = 0,2032USEnd = RegUnitSets.size();2033USIdx < USEnd; ++USIdx) {2034dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";2035for (auto &U : RegUnitSets[USIdx].Units)2036printRegUnitName(U);2037dbgs() << "\n";2038});20392040// Iteratively prune unit sets.2041pruneUnitSets();20422043LLVM_DEBUG(dbgs() << "\nBefore union:\n"; for (unsigned USIdx = 0,2044USEnd = RegUnitSets.size();2045USIdx < USEnd; ++USIdx) {2046dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";2047for (auto &U : RegUnitSets[USIdx].Units)2048printRegUnitName(U);2049dbgs() << "\n";2050} dbgs() << "\nUnion sets:\n");20512052// Iterate over all unit sets, including new ones added by this loop.2053unsigned NumRegUnitSubSets = RegUnitSets.size();2054for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {2055// In theory, this is combinatorial. In practice, it needs to be bounded2056// by a small number of sets for regpressure to be efficient.2057// If the assert is hit, we need to implement pruning.2058assert(Idx < (2 * NumRegUnitSubSets) && "runaway unit set inference");20592060// Compare new sets with all original classes.2061for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx + 1;2062SearchIdx != EndIdx; ++SearchIdx) {2063std::vector<unsigned> Intersection;2064std::set_intersection(2065RegUnitSets[Idx].Units.begin(), RegUnitSets[Idx].Units.end(),2066RegUnitSets[SearchIdx].Units.begin(),2067RegUnitSets[SearchIdx].Units.end(), std::back_inserter(Intersection));2068if (Intersection.empty())2069continue;20702071RegUnitSet RUSet(RegUnitSets[Idx].Name + "_with_" +2072RegUnitSets[SearchIdx].Name);2073std::set_union(RegUnitSets[Idx].Units.begin(),2074RegUnitSets[Idx].Units.end(),2075RegUnitSets[SearchIdx].Units.begin(),2076RegUnitSets[SearchIdx].Units.end(),2077std::inserter(RUSet.Units, RUSet.Units.begin()));20782079// Find an existing RegUnitSet, or add the union to the unique sets.2080if (findRegUnitSet(RegUnitSets, RUSet) == RegUnitSets.end()) {2081LLVM_DEBUG(dbgs() << "UnitSet " << RegUnitSets.size() << " "2082<< RUSet.Name << ":";2083for (auto &U2084: RUSet.Units) printRegUnitName(U);2085dbgs() << "\n";);2086RegUnitSets.push_back(std::move(RUSet));2087}2088}2089}20902091// Iteratively prune unit sets after inferring supersets.2092pruneUnitSets();20932094LLVM_DEBUG(2095dbgs() << "\n"; for (unsigned USIdx = 0, USEnd = RegUnitSets.size();2096USIdx < USEnd; ++USIdx) {2097dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";2098for (auto &U : RegUnitSets[USIdx].Units)2099printRegUnitName(U);2100dbgs() << "\n";2101});21022103// For each register class, list the UnitSets that are supersets.2104RegClassUnitSets.resize(RegClasses.size());2105int RCIdx = -1;2106for (auto &RC : RegClasses) {2107++RCIdx;2108if (!RC.Allocatable)2109continue;21102111// Recompute the sorted list of units in this class.2112std::vector<unsigned> RCRegUnits;2113RC.buildRegUnitSet(*this, RCRegUnits);21142115// Don't increase pressure for unallocatable regclasses.2116if (RCRegUnits.empty())2117continue;21182119LLVM_DEBUG(dbgs() << "RC " << RC.getName() << " Units:\n";2120for (auto U2121: RCRegUnits) printRegUnitName(U);2122dbgs() << "\n UnitSetIDs:");21232124// Find all supersets.2125for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx != USEnd;2126++USIdx) {2127if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {2128LLVM_DEBUG(dbgs() << " " << USIdx);2129RegClassUnitSets[RCIdx].push_back(USIdx);2130}2131}2132LLVM_DEBUG(dbgs() << "\n");2133assert((!RegClassUnitSets[RCIdx].empty() || !RC.GeneratePressureSet) &&2134"missing unit set for regclass");2135}21362137// For each register unit, ensure that we have the list of UnitSets that2138// contain the unit. Normally, this matches an existing list of UnitSets for a2139// register class. If not, we create a new entry in RegClassUnitSets as a2140// "fake" register class.2141for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits; UnitIdx < UnitEnd;2142++UnitIdx) {2143std::vector<unsigned> RUSets;2144for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {2145if (is_contained(RegUnitSets[i].Units, UnitIdx))2146RUSets.push_back(i);2147}2148unsigned RCUnitSetsIdx = 0;2149for (unsigned e = RegClassUnitSets.size(); RCUnitSetsIdx != e;2150++RCUnitSetsIdx) {2151if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {2152break;2153}2154}2155RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;2156if (RCUnitSetsIdx == RegClassUnitSets.size()) {2157// Create a new list of UnitSets as a "fake" register class.2158RegClassUnitSets.push_back(std::move(RUSets));2159}2160}2161}21622163void CodeGenRegBank::computeRegUnitLaneMasks() {2164for (auto &Register : Registers) {2165// Create an initial lane mask for all register units.2166const auto &RegUnits = Register.getRegUnits();2167CodeGenRegister::RegUnitLaneMaskList RegUnitLaneMasks(2168RegUnits.count(), LaneBitmask::getAll());2169// Iterate through SubRegisters.2170typedef CodeGenRegister::SubRegMap SubRegMap;2171const SubRegMap &SubRegs = Register.getSubRegs();2172for (auto S : SubRegs) {2173CodeGenRegister *SubReg = S.second;2174// Ignore non-leaf subregisters, their lane masks are fully covered by2175// the leaf subregisters anyway.2176if (!SubReg->getSubRegs().empty())2177continue;2178CodeGenSubRegIndex *SubRegIndex = S.first;2179const CodeGenRegister *SubRegister = S.second;2180LaneBitmask LaneMask = SubRegIndex->LaneMask;2181// Distribute LaneMask to Register Units touched.2182for (unsigned SUI : SubRegister->getRegUnits()) {2183bool Found = false;2184unsigned u = 0;2185for (unsigned RU : RegUnits) {2186if (SUI == RU) {2187RegUnitLaneMasks[u] &= LaneMask;2188assert(!Found);2189Found = true;2190}2191++u;2192}2193(void)Found;2194assert(Found);2195}2196}2197Register.setRegUnitLaneMasks(RegUnitLaneMasks);2198}2199}22002201void CodeGenRegBank::computeDerivedInfo() {2202computeComposites();2203computeSubRegLaneMasks();22042205// Compute a weight for each register unit created during getSubRegs.2206// This may create adopted register units (with unit # >= NumNativeRegUnits).2207computeRegUnitWeights();22082209// Compute a unique set of RegUnitSets. One for each RegClass and inferred2210// supersets for the union of overlapping sets.2211computeRegUnitSets();22122213computeRegUnitLaneMasks();22142215// Compute register class HasDisjunctSubRegs/CoveredBySubRegs flag.2216for (CodeGenRegisterClass &RC : RegClasses) {2217RC.HasDisjunctSubRegs = false;2218RC.CoveredBySubRegs = true;2219for (const CodeGenRegister *Reg : RC.getMembers()) {2220RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;2221RC.CoveredBySubRegs &= Reg->CoveredBySubRegs;2222}2223}22242225// Get the weight of each set.2226for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)2227RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);22282229// Find the order of each set.2230RegUnitSetOrder.reserve(RegUnitSets.size());2231for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)2232RegUnitSetOrder.push_back(Idx);22332234llvm::stable_sort(RegUnitSetOrder, [this](unsigned ID1, unsigned ID2) {2235return getRegPressureSet(ID1).Units.size() <2236getRegPressureSet(ID2).Units.size();2237});2238for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {2239RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;2240}2241}22422243//2244// Synthesize missing register class intersections.2245//2246// Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)2247// returns a maximal register class for all X.2248//2249void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {2250assert(!RegClasses.empty());2251// Stash the iterator to the last element so that this loop doesn't visit2252// elements added by the getOrCreateSubClass call within it.2253for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());2254I != std::next(E); ++I) {2255CodeGenRegisterClass *RC1 = RC;2256CodeGenRegisterClass *RC2 = &*I;2257if (RC1 == RC2)2258continue;22592260// Compute the set intersection of RC1 and RC2.2261const CodeGenRegister::Vec &Memb1 = RC1->getMembers();2262const CodeGenRegister::Vec &Memb2 = RC2->getMembers();2263CodeGenRegister::Vec Intersection;2264std::set_intersection(Memb1.begin(), Memb1.end(), Memb2.begin(),2265Memb2.end(),2266std::inserter(Intersection, Intersection.begin()),2267deref<std::less<>>());22682269// Skip disjoint class pairs.2270if (Intersection.empty())2271continue;22722273// If RC1 and RC2 have different spill sizes or alignments, use the2274// stricter one for sub-classing. If they are equal, prefer RC1.2275if (RC2->RSI.hasStricterSpillThan(RC1->RSI))2276std::swap(RC1, RC2);22772278getOrCreateSubClass(RC1, &Intersection,2279RC1->getName() + "_and_" + RC2->getName());2280}2281}22822283//2284// Synthesize missing sub-classes for getSubClassWithSubReg().2285//2286// Make sure that the set of registers in RC with a given SubIdx sub-register2287// form a register class. Update RC->SubClassWithSubReg.2288//2289void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {2290// Map SubRegIndex to set of registers in RC supporting that SubRegIndex.2291typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,2292deref<std::less<>>>2293SubReg2SetMap;22942295// Compute the set of registers supporting each SubRegIndex.2296SubReg2SetMap SRSets;2297for (const auto R : RC->getMembers()) {2298if (R->Artificial)2299continue;2300const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();2301for (auto I : SRM) {2302if (!I.first->Artificial)2303SRSets[I.first].push_back(R);2304}2305}23062307for (auto I : SRSets)2308sortAndUniqueRegisters(I.second);23092310// Find matching classes for all SRSets entries. Iterate in SubRegIndex2311// numerical order to visit synthetic indices last.2312for (const auto &SubIdx : SubRegIndices) {2313if (SubIdx.Artificial)2314continue;2315SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);2316// Unsupported SubRegIndex. Skip it.2317if (I == SRSets.end())2318continue;2319// In most cases, all RC registers support the SubRegIndex.2320if (I->second.size() == RC->getMembers().size()) {2321RC->setSubClassWithSubReg(&SubIdx, RC);2322continue;2323}2324// This is a real subset. See if we have a matching class.2325CodeGenRegisterClass *SubRC = getOrCreateSubClass(2326RC, &I->second, RC->getName() + "_with_" + I->first->getName());2327RC->setSubClassWithSubReg(&SubIdx, SubRC);2328}2329}23302331//2332// Synthesize missing sub-classes of RC for getMatchingSuperRegClass().2333//2334// Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)2335// has a maximal result for any SubIdx and any X >= FirstSubRegRC.2336//23372338void CodeGenRegBank::inferMatchingSuperRegClass(2339CodeGenRegisterClass *RC,2340std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {2341DenseMap<const CodeGenRegister *, std::vector<const CodeGenRegister *>>2342SubToSuperRegs;2343BitVector TopoSigs(getNumTopoSigs());23442345// Iterate in SubRegIndex numerical order to visit synthetic indices last.2346for (auto &SubIdx : SubRegIndices) {2347// Skip indexes that aren't fully supported by RC's registers. This was2348// computed by inferSubClassWithSubReg() above which should have been2349// called first.2350if (RC->getSubClassWithSubReg(&SubIdx) != RC)2351continue;23522353// Build list of (Super, Sub) pairs for this SubIdx.2354SubToSuperRegs.clear();2355TopoSigs.reset();2356for (const auto Super : RC->getMembers()) {2357const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;2358assert(Sub && "Missing sub-register");2359SubToSuperRegs[Sub].push_back(Super);2360TopoSigs.set(Sub->getTopoSig());2361}23622363// Iterate over sub-register class candidates. Ignore classes created by2364// this loop. They will never be useful.2365// Store an iterator to the last element (not end) so that this loop doesn't2366// visit newly inserted elements.2367assert(!RegClasses.empty());2368for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());2369I != std::next(E); ++I) {2370CodeGenRegisterClass &SubRC = *I;2371if (SubRC.Artificial)2372continue;2373// Topological shortcut: SubRC members have the wrong shape.2374if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))2375continue;2376// Compute the subset of RC that maps into SubRC.2377CodeGenRegister::Vec SubSetVec;2378for (const CodeGenRegister *R : SubRC.getMembers()) {2379auto It = SubToSuperRegs.find(R);2380if (It != SubToSuperRegs.end()) {2381const std::vector<const CodeGenRegister *> &SuperRegs = It->second;2382SubSetVec.insert(SubSetVec.end(), SuperRegs.begin(), SuperRegs.end());2383}2384}23852386if (SubSetVec.empty())2387continue;23882389// RC injects completely into SubRC.2390sortAndUniqueRegisters(SubSetVec);2391if (SubSetVec.size() == RC->getMembers().size()) {2392SubRC.addSuperRegClass(&SubIdx, RC);2393continue;2394}23952396// Only a subset of RC maps into SubRC. Make sure it is represented by a2397// class.2398getOrCreateSubClass(RC, &SubSetVec,2399RC->getName() + "_with_" + SubIdx.getName() + "_in_" +2400SubRC.getName());2401}2402}2403}24042405//2406// Infer missing register classes.2407//2408void CodeGenRegBank::computeInferredRegisterClasses() {2409assert(!RegClasses.empty());2410// When this function is called, the register classes have not been sorted2411// and assigned EnumValues yet. That means getSubClasses(),2412// getSuperClasses(), and hasSubClass() functions are defunct.24132414// Use one-before-the-end so it doesn't move forward when new elements are2415// added.2416auto FirstNewRC = std::prev(RegClasses.end());24172418// Visit all register classes, including the ones being added by the loop.2419// Watch out for iterator invalidation here.2420for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {2421CodeGenRegisterClass *RC = &*I;2422if (RC->Artificial)2423continue;24242425// Synthesize answers for getSubClassWithSubReg().2426inferSubClassWithSubReg(RC);24272428// Synthesize answers for getCommonSubClass().2429inferCommonSubClass(RC);24302431// Synthesize answers for getMatchingSuperRegClass().2432inferMatchingSuperRegClass(RC);24332434// New register classes are created while this loop is running, and we need2435// to visit all of them. I particular, inferMatchingSuperRegClass needs2436// to match old super-register classes with sub-register classes created2437// after inferMatchingSuperRegClass was called. At this point,2438// inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =2439// [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].2440if (I == FirstNewRC) {2441auto NextNewRC = std::prev(RegClasses.end());2442for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;2443++I2)2444inferMatchingSuperRegClass(&*I2, E2);2445FirstNewRC = NextNewRC;2446}2447}2448}24492450/// getRegisterClassForRegister - Find the register class that contains the2451/// specified physical register. If the register is not in a register class,2452/// return null. If the register is in multiple classes, and the classes have a2453/// superset-subset relationship and the same set of types, return the2454/// superclass. Otherwise return null.2455const CodeGenRegisterClass *CodeGenRegBank::getRegClassForRegister(Record *R) {2456const CodeGenRegister *Reg = getReg(R);2457const CodeGenRegisterClass *FoundRC = nullptr;2458for (const auto &RC : getRegClasses()) {2459if (!RC.contains(Reg))2460continue;24612462// If this is the first class that contains the register,2463// make a note of it and go on to the next class.2464if (!FoundRC) {2465FoundRC = &RC;2466continue;2467}24682469// If a register's classes have different types, return null.2470if (RC.getValueTypes() != FoundRC->getValueTypes())2471return nullptr;24722473// Check to see if the previously found class that contains2474// the register is a subclass of the current class. If so,2475// prefer the superclass.2476if (RC.hasSubClass(FoundRC)) {2477FoundRC = &RC;2478continue;2479}24802481// Check to see if the previously found class that contains2482// the register is a superclass of the current class. If so,2483// prefer the superclass.2484if (FoundRC->hasSubClass(&RC))2485continue;24862487// Multiple classes, and neither is a superclass of the other.2488// Return null.2489return nullptr;2490}2491return FoundRC;2492}24932494const CodeGenRegisterClass *2495CodeGenRegBank::getMinimalPhysRegClass(Record *RegRecord,2496ValueTypeByHwMode *VT) {2497const CodeGenRegister *Reg = getReg(RegRecord);2498const CodeGenRegisterClass *BestRC = nullptr;2499for (const auto &RC : getRegClasses()) {2500if ((!VT || RC.hasType(*VT)) && RC.contains(Reg) &&2501(!BestRC || BestRC->hasSubClass(&RC)))2502BestRC = &RC;2503}25042505assert(BestRC && "Couldn't find the register class");2506return BestRC;2507}25082509BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record *> Regs) {2510SetVector<const CodeGenRegister *> Set;25112512// First add Regs with all sub-registers.2513for (unsigned i = 0, e = Regs.size(); i != e; ++i) {2514CodeGenRegister *Reg = getReg(Regs[i]);2515if (Set.insert(Reg))2516// Reg is new, add all sub-registers.2517// The pre-ordering is not important here.2518Reg->addSubRegsPreOrder(Set, *this);2519}25202521// Second, find all super-registers that are completely covered by the set.2522for (unsigned i = 0; i != Set.size(); ++i) {2523const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();2524for (unsigned j = 0, e = SR.size(); j != e; ++j) {2525const CodeGenRegister *Super = SR[j];2526if (!Super->CoveredBySubRegs || Set.count(Super))2527continue;2528// This new super-register is covered by its sub-registers.2529bool AllSubsInSet = true;2530const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();2531for (auto I : SRM)2532if (!Set.count(I.second)) {2533AllSubsInSet = false;2534break;2535}2536// All sub-registers in Set, add Super as well.2537// We will visit Super later to recheck its super-registers.2538if (AllSubsInSet)2539Set.insert(Super);2540}2541}25422543// Convert to BitVector.2544BitVector BV(Registers.size() + 1);2545for (unsigned i = 0, e = Set.size(); i != e; ++i)2546BV.set(Set[i]->EnumValue);2547return BV;2548}25492550void CodeGenRegBank::printRegUnitName(unsigned Unit) const {2551if (Unit < NumNativeRegUnits)2552dbgs() << ' ' << RegUnits[Unit].Roots[0]->getName();2553else2554dbgs() << " #" << Unit;2555}255625572558