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