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