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