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