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/SmallVector.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/StringExtras.h" 21 22 using namespace llvm; 23 24 //===----------------------------------------------------------------------===// 25 // CodeGenRegister 26 //===----------------------------------------------------------------------===// 27 28 CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum) 29 : TheDef(R), 30 EnumValue(Enum), 31 CostPerUse(R->getValueAsInt("CostPerUse")), 32 SubRegsComplete(false) 33 {} 34 35 const std::string &CodeGenRegister::getName() const { 36 return TheDef->getName(); 37 } 38 39 namespace { 40 struct Orphan { 41 CodeGenRegister *SubReg; 42 Record *First, *Second; 43 Orphan(CodeGenRegister *r, Record *a, Record *b) 44 : SubReg(r), First(a), Second(b) {} 45 }; 46 } 47 48 const CodeGenRegister::SubRegMap & 49 CodeGenRegister::getSubRegs(CodeGenRegBank &RegBank) { 50 // Only compute this map once. 51 if (SubRegsComplete) 52 return SubRegs; 53 SubRegsComplete = true; 54 55 std::vector<Record*> SubList = TheDef->getValueAsListOfDefs("SubRegs"); 56 std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices"); 57 if (SubList.size() != Indices.size()) 58 throw TGError(TheDef->getLoc(), "Register " + getName() + 59 " SubRegIndices doesn't match SubRegs"); 60 61 // First insert the direct subregs and make sure they are fully indexed. 62 for (unsigned i = 0, e = SubList.size(); i != e; ++i) { 63 CodeGenRegister *SR = RegBank.getReg(SubList[i]); 64 if (!SubRegs.insert(std::make_pair(Indices[i], SR)).second) 65 throw TGError(TheDef->getLoc(), "SubRegIndex " + Indices[i]->getName() + 66 " appears twice in Register " + getName()); 67 } 68 69 // Keep track of inherited subregs and how they can be reached. 70 SmallVector<Orphan, 8> Orphans; 71 72 // Clone inherited subregs and place duplicate entries on Orphans. 73 // Here the order is important - earlier subregs take precedence. 74 for (unsigned i = 0, e = SubList.size(); i != e; ++i) { 75 CodeGenRegister *SR = RegBank.getReg(SubList[i]); 76 const SubRegMap &Map = SR->getSubRegs(RegBank); 77 78 // Add this as a super-register of SR now all sub-registers are in the list. 79 // This creates a topological ordering, the exact order depends on the 80 // order getSubRegs is called on all registers. 81 SR->SuperRegs.push_back(this); 82 83 for (SubRegMap::const_iterator SI = Map.begin(), SE = Map.end(); SI != SE; 84 ++SI) { 85 if (!SubRegs.insert(*SI).second) 86 Orphans.push_back(Orphan(SI->second, Indices[i], SI->first)); 87 88 // Noop sub-register indexes are possible, so avoid duplicates. 89 if (SI->second != SR) 90 SI->second->SuperRegs.push_back(this); 91 } 92 } 93 94 // Process the composites. 95 ListInit *Comps = TheDef->getValueAsListInit("CompositeIndices"); 96 for (unsigned i = 0, e = Comps->size(); i != e; ++i) { 97 DagInit *Pat = dynamic_cast<DagInit*>(Comps->getElement(i)); 98 if (!Pat) 99 throw TGError(TheDef->getLoc(), "Invalid dag '" + 100 Comps->getElement(i)->getAsString() + 101 "' in CompositeIndices"); 102 DefInit *BaseIdxInit = dynamic_cast<DefInit*>(Pat->getOperator()); 103 if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex")) 104 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " + 105 Pat->getAsString()); 106 107 // Resolve list of subreg indices into R2. 108 CodeGenRegister *R2 = this; 109 for (DagInit::const_arg_iterator di = Pat->arg_begin(), 110 de = Pat->arg_end(); di != de; ++di) { 111 DefInit *IdxInit = dynamic_cast<DefInit*>(*di); 112 if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex")) 113 throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " + 114 Pat->getAsString()); 115 const SubRegMap &R2Subs = R2->getSubRegs(RegBank); 116 SubRegMap::const_iterator ni = R2Subs.find(IdxInit->getDef()); 117 if (ni == R2Subs.end()) 118 throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() + 119 " refers to bad index in " + R2->getName()); 120 R2 = ni->second; 121 } 122 123 // Insert composite index. Allow overriding inherited indices etc. 124 SubRegs[BaseIdxInit->getDef()] = R2; 125 126 // R2 is no longer an orphan. 127 for (unsigned j = 0, je = Orphans.size(); j != je; ++j) 128 if (Orphans[j].SubReg == R2) 129 Orphans[j].SubReg = 0; 130 } 131 132 // Now Orphans contains the inherited subregisters without a direct index. 133 // Create inferred indexes for all missing entries. 134 for (unsigned i = 0, e = Orphans.size(); i != e; ++i) { 135 Orphan &O = Orphans[i]; 136 if (!O.SubReg) 137 continue; 138 SubRegs[RegBank.getCompositeSubRegIndex(O.First, O.Second, true)] = 139 O.SubReg; 140 } 141 return SubRegs; 142 } 143 144 void 145 CodeGenRegister::addSubRegsPreOrder(SetVector<CodeGenRegister*> &OSet) const { 146 assert(SubRegsComplete && "Must precompute sub-registers"); 147 std::vector<Record*> Indices = TheDef->getValueAsListOfDefs("SubRegIndices"); 148 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 149 CodeGenRegister *SR = SubRegs.find(Indices[i])->second; 150 if (OSet.insert(SR)) 151 SR->addSubRegsPreOrder(OSet); 152 } 153 } 154 155 //===----------------------------------------------------------------------===// 156 // RegisterTuples 157 //===----------------------------------------------------------------------===// 158 159 // A RegisterTuples def is used to generate pseudo-registers from lists of 160 // sub-registers. We provide a SetTheory expander class that returns the new 161 // registers. 162 namespace { 163 struct TupleExpander : SetTheory::Expander { 164 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) { 165 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices"); 166 unsigned Dim = Indices.size(); 167 ListInit *SubRegs = Def->getValueAsListInit("SubRegs"); 168 if (Dim != SubRegs->getSize()) 169 throw TGError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch"); 170 if (Dim < 2) 171 throw TGError(Def->getLoc(), "Tuples must have at least 2 sub-registers"); 172 173 // Evaluate the sub-register lists to be zipped. 174 unsigned Length = ~0u; 175 SmallVector<SetTheory::RecSet, 4> Lists(Dim); 176 for (unsigned i = 0; i != Dim; ++i) { 177 ST.evaluate(SubRegs->getElement(i), Lists[i]); 178 Length = std::min(Length, unsigned(Lists[i].size())); 179 } 180 181 if (Length == 0) 182 return; 183 184 // Precompute some types. 185 Record *RegisterCl = Def->getRecords().getClass("Register"); 186 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl); 187 StringInit *BlankName = StringInit::get(""); 188 189 // Zip them up. 190 for (unsigned n = 0; n != Length; ++n) { 191 std::string Name; 192 Record *Proto = Lists[0][n]; 193 std::vector<Init*> Tuple; 194 unsigned CostPerUse = 0; 195 for (unsigned i = 0; i != Dim; ++i) { 196 Record *Reg = Lists[i][n]; 197 if (i) Name += '_'; 198 Name += Reg->getName(); 199 Tuple.push_back(DefInit::get(Reg)); 200 CostPerUse = std::max(CostPerUse, 201 unsigned(Reg->getValueAsInt("CostPerUse"))); 202 } 203 204 // Create a new Record representing the synthesized register. This record 205 // is only for consumption by CodeGenRegister, it is not added to the 206 // RecordKeeper. 207 Record *NewReg = new Record(Name, Def->getLoc(), Def->getRecords()); 208 Elts.insert(NewReg); 209 210 // Copy Proto super-classes. 211 for (unsigned i = 0, e = Proto->getSuperClasses().size(); i != e; ++i) 212 NewReg->addSuperClass(Proto->getSuperClasses()[i]); 213 214 // Copy Proto fields. 215 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) { 216 RecordVal RV = Proto->getValues()[i]; 217 218 if (RV.getName() == "NAME") 219 continue; 220 221 // Replace the sub-register list with Tuple. 222 if (RV.getName() == "SubRegs") 223 RV.setValue(ListInit::get(Tuple, RegisterRecTy)); 224 225 // Provide a blank AsmName. MC hacks are required anyway. 226 if (RV.getName() == "AsmName") 227 RV.setValue(BlankName); 228 229 // CostPerUse is aggregated from all Tuple members. 230 if (RV.getName() == "CostPerUse") 231 RV.setValue(IntInit::get(CostPerUse)); 232 233 // Copy fields from the RegisterTuples def. 234 if (RV.getName() == "SubRegIndices" || 235 RV.getName() == "CompositeIndices") { 236 NewReg->addValue(*Def->getValue(RV.getName())); 237 continue; 238 } 239 240 // Some fields get their default uninitialized value. 241 if (RV.getName() == "DwarfNumbers" || 242 RV.getName() == "DwarfAlias" || 243 RV.getName() == "Aliases") { 244 if (const RecordVal *DefRV = RegisterCl->getValue(RV.getName())) 245 NewReg->addValue(*DefRV); 246 continue; 247 } 248 249 // Everything else is copied from Proto. 250 NewReg->addValue(RV); 251 } 252 } 253 } 254 }; 255 } 256 257 //===----------------------------------------------------------------------===// 258 // CodeGenRegisterClass 259 //===----------------------------------------------------------------------===// 260 261 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R) 262 : TheDef(R), Name(R->getName()), EnumValue(-1) { 263 // Rename anonymous register classes. 264 if (R->getName().size() > 9 && R->getName()[9] == '.') { 265 static unsigned AnonCounter = 0; 266 R->setName("AnonRegClass_"+utostr(AnonCounter++)); 267 } 268 269 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes"); 270 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 271 Record *Type = TypeList[i]; 272 if (!Type->isSubClassOf("ValueType")) 273 throw "RegTypes list member '" + Type->getName() + 274 "' does not derive from the ValueType class!"; 275 VTs.push_back(getValueType(Type)); 276 } 277 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!"); 278 279 // Allocation order 0 is the full set. AltOrders provides others. 280 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R); 281 ListInit *AltOrders = R->getValueAsListInit("AltOrders"); 282 Orders.resize(1 + AltOrders->size()); 283 284 // Default allocation order always contains all registers. 285 for (unsigned i = 0, e = Elements->size(); i != e; ++i) { 286 Orders[0].push_back((*Elements)[i]); 287 Members.insert(RegBank.getReg((*Elements)[i])); 288 } 289 290 // Alternative allocation orders may be subsets. 291 SetTheory::RecSet Order; 292 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) { 293 RegBank.getSets().evaluate(AltOrders->getElement(i), Order); 294 Orders[1 + i].append(Order.begin(), Order.end()); 295 // Verify that all altorder members are regclass members. 296 while (!Order.empty()) { 297 CodeGenRegister *Reg = RegBank.getReg(Order.back()); 298 Order.pop_back(); 299 if (!contains(Reg)) 300 throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() + 301 " is not a class member"); 302 } 303 } 304 305 // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags. 306 ListInit *SRC = R->getValueAsListInit("SubRegClasses"); 307 for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) { 308 DagInit *DAG = dynamic_cast<DagInit*>(*i); 309 if (!DAG) throw "SubRegClasses must contain DAGs"; 310 DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator()); 311 Record *RCRec; 312 if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass")) 313 throw "Operator '" + DAG->getOperator()->getAsString() + 314 "' in SubRegClasses is not a RegisterClass"; 315 // Iterate over args, all SubRegIndex instances. 316 for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end(); 317 ai != ae; ++ai) { 318 DefInit *Idx = dynamic_cast<DefInit*>(*ai); 319 Record *IdxRec; 320 if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex")) 321 throw "Argument '" + (*ai)->getAsString() + 322 "' in SubRegClasses is not a SubRegIndex"; 323 if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second) 324 throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice"; 325 } 326 } 327 328 // Allow targets to override the size in bits of the RegisterClass. 329 unsigned Size = R->getValueAsInt("Size"); 330 331 Namespace = R->getValueAsString("Namespace"); 332 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits(); 333 SpillAlignment = R->getValueAsInt("Alignment"); 334 CopyCost = R->getValueAsInt("CopyCost"); 335 Allocatable = R->getValueAsBit("isAllocatable"); 336 AltOrderSelect = R->getValueAsString("AltOrderSelect"); 337 } 338 339 // Create an inferred register class that was missing from the .td files. 340 // Most properties will be inherited from the closest super-class after the 341 // class structure has been computed. 342 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props) 343 : Members(*Props.Members), 344 TheDef(0), 345 Name(Name), 346 EnumValue(-1), 347 SpillSize(Props.SpillSize), 348 SpillAlignment(Props.SpillAlignment), 349 CopyCost(0), 350 Allocatable(true) { 351 } 352 353 // Compute inherited propertied for a synthesized register class. 354 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) { 355 assert(!getDef() && "Only synthesized classes can inherit properties"); 356 assert(!SuperClasses.empty() && "Synthesized class without super class"); 357 358 // The last super-class is the smallest one. 359 CodeGenRegisterClass &Super = *SuperClasses.back(); 360 361 // Most properties are copied directly. 362 // Exceptions are members, size, and alignment 363 Namespace = Super.Namespace; 364 VTs = Super.VTs; 365 CopyCost = Super.CopyCost; 366 Allocatable = Super.Allocatable; 367 AltOrderSelect = Super.AltOrderSelect; 368 369 // Copy all allocation orders, filter out foreign registers from the larger 370 // super-class. 371 Orders.resize(Super.Orders.size()); 372 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i) 373 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j) 374 if (contains(RegBank.getReg(Super.Orders[i][j]))) 375 Orders[i].push_back(Super.Orders[i][j]); 376 } 377 378 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const { 379 return Members.count(Reg); 380 } 381 382 namespace llvm { 383 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) { 384 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment; 385 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(), 386 E = K.Members->end(); I != E; ++I) 387 OS << ", " << (*I)->getName(); 388 return OS << " }"; 389 } 390 } 391 392 // This is a simple lexicographical order that can be used to search for sets. 393 // It is not the same as the topological order provided by TopoOrderRC. 394 bool CodeGenRegisterClass::Key:: 395 operator<(const CodeGenRegisterClass::Key &B) const { 396 assert(Members && B.Members); 397 if (*Members != *B.Members) 398 return *Members < *B.Members; 399 if (SpillSize != B.SpillSize) 400 return SpillSize < B.SpillSize; 401 return SpillAlignment < B.SpillAlignment; 402 } 403 404 // Returns true if RC is a strict subclass. 405 // RC is a sub-class of this class if it is a valid replacement for any 406 // instruction operand where a register of this classis required. It must 407 // satisfy these conditions: 408 // 409 // 1. All RC registers are also in this. 410 // 2. The RC spill size must not be smaller than our spill size. 411 // 3. RC spill alignment must be compatible with ours. 412 // 413 static bool testSubClass(const CodeGenRegisterClass *A, 414 const CodeGenRegisterClass *B) { 415 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 && 416 A->SpillSize <= B->SpillSize && 417 std::includes(A->getMembers().begin(), A->getMembers().end(), 418 B->getMembers().begin(), B->getMembers().end(), 419 CodeGenRegister::Less()); 420 } 421 422 /// Sorting predicate for register classes. This provides a topological 423 /// ordering that arranges all register classes before their sub-classes. 424 /// 425 /// Register classes with the same registers, spill size, and alignment form a 426 /// clique. They will be ordered alphabetically. 427 /// 428 static int TopoOrderRC(const void *PA, const void *PB) { 429 const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA; 430 const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB; 431 if (A == B) 432 return 0; 433 434 // Order by descending set size. Note that the classes' allocation order may 435 // not have been computed yet. The Members set is always vaild. 436 if (A->getMembers().size() > B->getMembers().size()) 437 return -1; 438 if (A->getMembers().size() < B->getMembers().size()) 439 return 1; 440 441 // Order by ascending spill size. 442 if (A->SpillSize < B->SpillSize) 443 return -1; 444 if (A->SpillSize > B->SpillSize) 445 return 1; 446 447 // Order by ascending spill alignment. 448 if (A->SpillAlignment < B->SpillAlignment) 449 return -1; 450 if (A->SpillAlignment > B->SpillAlignment) 451 return 1; 452 453 // Finally order by name as a tie breaker. 454 return A->getName() < B->getName(); 455 } 456 457 std::string CodeGenRegisterClass::getQualifiedName() const { 458 if (Namespace.empty()) 459 return getName(); 460 else 461 return Namespace + "::" + getName(); 462 } 463 464 // Compute sub-classes of all register classes. 465 // Assume the classes are ordered topologically. 466 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) { 467 ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses(); 468 469 // Visit backwards so sub-classes are seen first. 470 for (unsigned rci = RegClasses.size(); rci; --rci) { 471 CodeGenRegisterClass &RC = *RegClasses[rci - 1]; 472 RC.SubClasses.resize(RegClasses.size()); 473 RC.SubClasses.set(RC.EnumValue); 474 475 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique. 476 for (unsigned s = rci; s != RegClasses.size(); ++s) { 477 if (RC.SubClasses.test(s)) 478 continue; 479 CodeGenRegisterClass *SubRC = RegClasses[s]; 480 if (!testSubClass(&RC, SubRC)) 481 continue; 482 // SubRC is a sub-class. Grap all its sub-classes so we won't have to 483 // check them again. 484 RC.SubClasses |= SubRC->SubClasses; 485 } 486 487 // Sweep up missed clique members. They will be immediately preceeding RC. 488 for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s) 489 RC.SubClasses.set(s - 1); 490 } 491 492 // Compute the SuperClasses lists from the SubClasses vectors. 493 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) { 494 const BitVector &SC = RegClasses[rci]->getSubClasses(); 495 for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) { 496 if (unsigned(s) == rci) 497 continue; 498 RegClasses[s]->SuperClasses.push_back(RegClasses[rci]); 499 } 500 } 501 502 // With the class hierarchy in place, let synthesized register classes inherit 503 // properties from their closest super-class. The iteration order here can 504 // propagate properties down multiple levels. 505 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) 506 if (!RegClasses[rci]->getDef()) 507 RegClasses[rci]->inheritProperties(RegBank); 508 } 509 510 void 511 CodeGenRegisterClass::getSuperRegClasses(Record *SubIdx, BitVector &Out) const { 512 DenseMap<Record*, SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator 513 FindI = SuperRegClasses.find(SubIdx); 514 if (FindI == SuperRegClasses.end()) 515 return; 516 for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I = 517 FindI->second.begin(), E = FindI->second.end(); I != E; ++I) 518 Out.set((*I)->EnumValue); 519 } 520 521 522 //===----------------------------------------------------------------------===// 523 // CodeGenRegBank 524 //===----------------------------------------------------------------------===// 525 526 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) { 527 // Configure register Sets to understand register classes and tuples. 528 Sets.addFieldExpander("RegisterClass", "MemberList"); 529 Sets.addExpander("RegisterTuples", new TupleExpander()); 530 531 // Read in the user-defined (named) sub-register indices. 532 // More indices will be synthesized later. 533 SubRegIndices = Records.getAllDerivedDefinitions("SubRegIndex"); 534 std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord()); 535 NumNamedIndices = SubRegIndices.size(); 536 537 // Read in the register definitions. 538 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register"); 539 std::sort(Regs.begin(), Regs.end(), LessRecord()); 540 Registers.reserve(Regs.size()); 541 // Assign the enumeration values. 542 for (unsigned i = 0, e = Regs.size(); i != e; ++i) 543 getReg(Regs[i]); 544 545 // Expand tuples and number the new registers. 546 std::vector<Record*> Tups = 547 Records.getAllDerivedDefinitions("RegisterTuples"); 548 for (unsigned i = 0, e = Tups.size(); i != e; ++i) { 549 const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]); 550 for (unsigned j = 0, je = TupRegs->size(); j != je; ++j) 551 getReg((*TupRegs)[j]); 552 } 553 554 // Precompute all sub-register maps now all the registers are known. 555 // This will create Composite entries for all inferred sub-register indices. 556 for (unsigned i = 0, e = Registers.size(); i != e; ++i) 557 Registers[i]->getSubRegs(*this); 558 559 // Read in register class definitions. 560 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass"); 561 if (RCs.empty()) 562 throw std::string("No 'RegisterClass' subclasses defined!"); 563 564 // Allocate user-defined register classes. 565 RegClasses.reserve(RCs.size()); 566 for (unsigned i = 0, e = RCs.size(); i != e; ++i) 567 addToMaps(new CodeGenRegisterClass(*this, RCs[i])); 568 569 // Infer missing classes to create a full algebra. 570 computeInferredRegisterClasses(); 571 572 // Order register classes topologically and assign enum values. 573 array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC); 574 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i) 575 RegClasses[i]->EnumValue = i; 576 CodeGenRegisterClass::computeSubClasses(*this); 577 } 578 579 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) { 580 CodeGenRegister *&Reg = Def2Reg[Def]; 581 if (Reg) 582 return Reg; 583 Reg = new CodeGenRegister(Def, Registers.size() + 1); 584 Registers.push_back(Reg); 585 return Reg; 586 } 587 588 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) { 589 RegClasses.push_back(RC); 590 591 if (Record *Def = RC->getDef()) 592 Def2RC.insert(std::make_pair(Def, RC)); 593 594 // Duplicate classes are rejected by insert(). 595 // That's OK, we only care about the properties handled by CGRC::Key. 596 CodeGenRegisterClass::Key K(*RC); 597 Key2RC.insert(std::make_pair(K, RC)); 598 } 599 600 // Create a synthetic sub-class if it is missing. 601 CodeGenRegisterClass* 602 CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC, 603 const CodeGenRegister::Set *Members, 604 StringRef Name) { 605 // Synthetic sub-class has the same size and alignment as RC. 606 CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment); 607 RCKeyMap::const_iterator FoundI = Key2RC.find(K); 608 if (FoundI != Key2RC.end()) 609 return FoundI->second; 610 611 // Sub-class doesn't exist, create a new one. 612 CodeGenRegisterClass *NewRC = new CodeGenRegisterClass(Name, K); 613 addToMaps(NewRC); 614 return NewRC; 615 } 616 617 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) { 618 if (CodeGenRegisterClass *RC = Def2RC[Def]) 619 return RC; 620 621 throw TGError(Def->getLoc(), "Not a known RegisterClass!"); 622 } 623 624 Record *CodeGenRegBank::getCompositeSubRegIndex(Record *A, Record *B, 625 bool create) { 626 // Look for an existing entry. 627 Record *&Comp = Composite[std::make_pair(A, B)]; 628 if (Comp || !create) 629 return Comp; 630 631 // None exists, synthesize one. 632 std::string Name = A->getName() + "_then_" + B->getName(); 633 Comp = new Record(Name, SMLoc(), Records); 634 SubRegIndices.push_back(Comp); 635 return Comp; 636 } 637 638 unsigned CodeGenRegBank::getSubRegIndexNo(Record *idx) { 639 std::vector<Record*>::const_iterator i = 640 std::find(SubRegIndices.begin(), SubRegIndices.end(), idx); 641 assert(i != SubRegIndices.end() && "Not a SubRegIndex"); 642 return (i - SubRegIndices.begin()) + 1; 643 } 644 645 void CodeGenRegBank::computeComposites() { 646 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 647 CodeGenRegister *Reg1 = Registers[i]; 648 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs(); 649 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(), 650 e1 = SRM1.end(); i1 != e1; ++i1) { 651 Record *Idx1 = i1->first; 652 CodeGenRegister *Reg2 = i1->second; 653 // Ignore identity compositions. 654 if (Reg1 == Reg2) 655 continue; 656 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs(); 657 // Try composing Idx1 with another SubRegIndex. 658 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(), 659 e2 = SRM2.end(); i2 != e2; ++i2) { 660 std::pair<Record*, Record*> IdxPair(Idx1, i2->first); 661 CodeGenRegister *Reg3 = i2->second; 662 // Ignore identity compositions. 663 if (Reg2 == Reg3) 664 continue; 665 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3. 666 for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(), 667 e1d = SRM1.end(); i1d != e1d; ++i1d) { 668 if (i1d->second == Reg3) { 669 std::pair<CompositeMap::iterator, bool> Ins = 670 Composite.insert(std::make_pair(IdxPair, i1d->first)); 671 // Conflicting composition? Emit a warning but allow it. 672 if (!Ins.second && Ins.first->second != i1d->first) { 673 errs() << "Warning: SubRegIndex " << getQualifiedName(Idx1) 674 << " and " << getQualifiedName(IdxPair.second) 675 << " compose ambiguously as " 676 << getQualifiedName(Ins.first->second) << " or " 677 << getQualifiedName(i1d->first) << "\n"; 678 } 679 } 680 } 681 } 682 } 683 } 684 685 // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid 686 // compositions, so remove any mappings of that form. 687 for (CompositeMap::iterator i = Composite.begin(), e = Composite.end(); 688 i != e;) { 689 CompositeMap::iterator j = i; 690 ++i; 691 if (j->first.second == j->second) 692 Composite.erase(j); 693 } 694 } 695 696 // Compute sets of overlapping registers. 697 // 698 // The standard set is all super-registers and all sub-registers, but the 699 // target description can add arbitrary overlapping registers via the 'Aliases' 700 // field. This complicates things, but we can compute overlapping sets using 701 // the following rules: 702 // 703 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive. 704 // 705 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B). 706 // 707 // Alternatively: 708 // 709 // overlap(A, B) iff there exists: 710 // A' in { A, subregs(A) } and B' in { B, subregs(B) } such that: 711 // A' = B' or A' in aliases(B') or B' in aliases(A'). 712 // 713 // Here subregs(A) is the full flattened sub-register set returned by 714 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the 715 // description of register A. 716 // 717 // This also implies that registers with a common sub-register are considered 718 // overlapping. This can happen when forming register pairs: 719 // 720 // P0 = (R0, R1) 721 // P1 = (R1, R2) 722 // P2 = (R2, R3) 723 // 724 // In this case, we will infer an overlap between P0 and P1 because of the 725 // shared sub-register R1. There is no overlap between P0 and P2. 726 // 727 void CodeGenRegBank:: 728 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) { 729 assert(Map.empty()); 730 731 // Collect overlaps that don't follow from rule 2. 732 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 733 CodeGenRegister *Reg = Registers[i]; 734 CodeGenRegister::Set &Overlaps = Map[Reg]; 735 736 // Reg overlaps itself. 737 Overlaps.insert(Reg); 738 739 // All super-registers overlap. 740 const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs(); 741 Overlaps.insert(Supers.begin(), Supers.end()); 742 743 // Form symmetrical relations from the special Aliases[] lists. 744 std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases"); 745 for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) { 746 CodeGenRegister *Reg2 = getReg(RegList[i2]); 747 CodeGenRegister::Set &Overlaps2 = Map[Reg2]; 748 const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs(); 749 // Reg overlaps Reg2 which implies it overlaps supers(Reg2). 750 Overlaps.insert(Reg2); 751 Overlaps.insert(Supers2.begin(), Supers2.end()); 752 Overlaps2.insert(Reg); 753 Overlaps2.insert(Supers.begin(), Supers.end()); 754 } 755 } 756 757 // Apply rule 2. and inherit all sub-register overlaps. 758 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 759 CodeGenRegister *Reg = Registers[i]; 760 CodeGenRegister::Set &Overlaps = Map[Reg]; 761 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs(); 762 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(), 763 e2 = SRM.end(); i2 != e2; ++i2) { 764 CodeGenRegister::Set &Overlaps2 = Map[i2->second]; 765 Overlaps.insert(Overlaps2.begin(), Overlaps2.end()); 766 } 767 } 768 } 769 770 void CodeGenRegBank::computeDerivedInfo() { 771 computeComposites(); 772 } 773 774 // 775 // Synthesize missing register class intersections. 776 // 777 // Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X) 778 // returns a maximal register class for all X. 779 // 780 void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) { 781 for (unsigned rci = 0, rce = RegClasses.size(); rci != rce; ++rci) { 782 CodeGenRegisterClass *RC1 = RC; 783 CodeGenRegisterClass *RC2 = RegClasses[rci]; 784 if (RC1 == RC2) 785 continue; 786 787 // Compute the set intersection of RC1 and RC2. 788 const CodeGenRegister::Set &Memb1 = RC1->getMembers(); 789 const CodeGenRegister::Set &Memb2 = RC2->getMembers(); 790 CodeGenRegister::Set Intersection; 791 std::set_intersection(Memb1.begin(), Memb1.end(), 792 Memb2.begin(), Memb2.end(), 793 std::inserter(Intersection, Intersection.begin()), 794 CodeGenRegister::Less()); 795 796 // Skip disjoint class pairs. 797 if (Intersection.empty()) 798 continue; 799 800 // If RC1 and RC2 have different spill sizes or alignments, use the 801 // larger size for sub-classing. If they are equal, prefer RC1. 802 if (RC2->SpillSize > RC1->SpillSize || 803 (RC2->SpillSize == RC1->SpillSize && 804 RC2->SpillAlignment > RC1->SpillAlignment)) 805 std::swap(RC1, RC2); 806 807 getOrCreateSubClass(RC1, &Intersection, 808 RC1->getName() + "_and_" + RC2->getName()); 809 } 810 } 811 812 // 813 // Synthesize missing sub-classes for getSubClassWithSubReg(). 814 // 815 // Make sure that the set of registers in RC with a given SubIdx sub-register 816 // form a register class. Update RC->SubClassWithSubReg. 817 // 818 void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) { 819 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex. 820 typedef std::map<Record*, CodeGenRegister::Set, LessRecord> SubReg2SetMap; 821 822 // Compute the set of registers supporting each SubRegIndex. 823 SubReg2SetMap SRSets; 824 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(), 825 RE = RC->getMembers().end(); RI != RE; ++RI) { 826 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs(); 827 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(), 828 E = SRM.end(); I != E; ++I) 829 SRSets[I->first].insert(*RI); 830 } 831 832 // Find matching classes for all SRSets entries. Iterate in SubRegIndex 833 // numerical order to visit synthetic indices last. 834 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) { 835 Record *SubIdx = SubRegIndices[sri]; 836 SubReg2SetMap::const_iterator I = SRSets.find(SubIdx); 837 // Unsupported SubRegIndex. Skip it. 838 if (I == SRSets.end()) 839 continue; 840 // In most cases, all RC registers support the SubRegIndex. 841 if (I->second.size() == RC->getMembers().size()) { 842 RC->setSubClassWithSubReg(SubIdx, RC); 843 continue; 844 } 845 // This is a real subset. See if we have a matching class. 846 CodeGenRegisterClass *SubRC = 847 getOrCreateSubClass(RC, &I->second, 848 RC->getName() + "_with_" + I->first->getName()); 849 RC->setSubClassWithSubReg(SubIdx, SubRC); 850 } 851 } 852 853 // 854 // Synthesize missing sub-classes of RC for getMatchingSuperRegClass(). 855 // 856 // Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X) 857 // has a maximal result for any SubIdx and any X >= FirstSubRegRC. 858 // 859 860 void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC, 861 unsigned FirstSubRegRC) { 862 SmallVector<std::pair<const CodeGenRegister*, 863 const CodeGenRegister*>, 16> SSPairs; 864 865 // Iterate in SubRegIndex numerical order to visit synthetic indices last. 866 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) { 867 Record *SubIdx = SubRegIndices[sri]; 868 // Skip indexes that aren't fully supported by RC's registers. This was 869 // computed by inferSubClassWithSubReg() above which should have been 870 // called first. 871 if (RC->getSubClassWithSubReg(SubIdx) != RC) 872 continue; 873 874 // Build list of (Super, Sub) pairs for this SubIdx. 875 SSPairs.clear(); 876 for (CodeGenRegister::Set::const_iterator RI = RC->getMembers().begin(), 877 RE = RC->getMembers().end(); RI != RE; ++RI) { 878 const CodeGenRegister *Super = *RI; 879 const CodeGenRegister *Sub = Super->getSubRegs().find(SubIdx)->second; 880 assert(Sub && "Missing sub-register"); 881 SSPairs.push_back(std::make_pair(Super, Sub)); 882 } 883 884 // Iterate over sub-register class candidates. Ignore classes created by 885 // this loop. They will never be useful. 886 for (unsigned rci = FirstSubRegRC, rce = RegClasses.size(); rci != rce; 887 ++rci) { 888 CodeGenRegisterClass *SubRC = RegClasses[rci]; 889 // Compute the subset of RC that maps into SubRC. 890 CodeGenRegister::Set SubSet; 891 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i) 892 if (SubRC->contains(SSPairs[i].second)) 893 SubSet.insert(SSPairs[i].first); 894 if (SubSet.empty()) 895 continue; 896 // RC injects completely into SubRC. 897 if (SubSet.size() == SSPairs.size()) { 898 SubRC->addSuperRegClass(SubIdx, RC); 899 continue; 900 } 901 // Only a subset of RC maps into SubRC. Make sure it is represented by a 902 // class. 903 getOrCreateSubClass(RC, &SubSet, RC->getName() + 904 "_with_" + SubIdx->getName() + 905 "_in_" + SubRC->getName()); 906 } 907 } 908 } 909 910 911 // 912 // Infer missing register classes. 913 // 914 void CodeGenRegBank::computeInferredRegisterClasses() { 915 // When this function is called, the register classes have not been sorted 916 // and assigned EnumValues yet. That means getSubClasses(), 917 // getSuperClasses(), and hasSubClass() functions are defunct. 918 unsigned FirstNewRC = RegClasses.size(); 919 920 // Visit all register classes, including the ones being added by the loop. 921 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) { 922 CodeGenRegisterClass *RC = RegClasses[rci]; 923 924 // Synthesize answers for getSubClassWithSubReg(). 925 inferSubClassWithSubReg(RC); 926 927 // Synthesize answers for getCommonSubClass(). 928 inferCommonSubClass(RC); 929 930 // Synthesize answers for getMatchingSuperRegClass(). 931 inferMatchingSuperRegClass(RC); 932 933 // New register classes are created while this loop is running, and we need 934 // to visit all of them. I particular, inferMatchingSuperRegClass needs 935 // to match old super-register classes with sub-register classes created 936 // after inferMatchingSuperRegClass was called. At this point, 937 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC = 938 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci]. 939 if (rci + 1 == FirstNewRC) { 940 unsigned NextNewRC = RegClasses.size(); 941 for (unsigned rci2 = 0; rci2 != FirstNewRC; ++rci2) 942 inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC); 943 FirstNewRC = NextNewRC; 944 } 945 } 946 } 947 948 /// getRegisterClassForRegister - Find the register class that contains the 949 /// specified physical register. If the register is not in a register class, 950 /// return null. If the register is in multiple classes, and the classes have a 951 /// superset-subset relationship and the same set of types, return the 952 /// superclass. Otherwise return null. 953 const CodeGenRegisterClass* 954 CodeGenRegBank::getRegClassForRegister(Record *R) { 955 const CodeGenRegister *Reg = getReg(R); 956 ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses(); 957 const CodeGenRegisterClass *FoundRC = 0; 958 for (unsigned i = 0, e = RCs.size(); i != e; ++i) { 959 const CodeGenRegisterClass &RC = *RCs[i]; 960 if (!RC.contains(Reg)) 961 continue; 962 963 // If this is the first class that contains the register, 964 // make a note of it and go on to the next class. 965 if (!FoundRC) { 966 FoundRC = &RC; 967 continue; 968 } 969 970 // If a register's classes have different types, return null. 971 if (RC.getValueTypes() != FoundRC->getValueTypes()) 972 return 0; 973 974 // Check to see if the previously found class that contains 975 // the register is a subclass of the current class. If so, 976 // prefer the superclass. 977 if (RC.hasSubClass(FoundRC)) { 978 FoundRC = &RC; 979 continue; 980 } 981 982 // Check to see if the previously found class that contains 983 // the register is a superclass of the current class. If so, 984 // prefer the superclass. 985 if (FoundRC->hasSubClass(&RC)) 986 continue; 987 988 // Multiple classes, and neither is a superclass of the other. 989 // Return null. 990 return 0; 991 } 992 return FoundRC; 993 } 994