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