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