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