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