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 // Replace the sub-register list with Tuple. 219 if (RV.getName() == "SubRegs") 220 RV.setValue(ListInit::get(Tuple, RegisterRecTy)); 221 222 // Provide a blank AsmName. MC hacks are required anyway. 223 if (RV.getName() == "AsmName") 224 RV.setValue(BlankName); 225 226 // CostPerUse is aggregated from all Tuple members. 227 if (RV.getName() == "CostPerUse") 228 RV.setValue(IntInit::get(CostPerUse)); 229 230 // Copy fields from the RegisterTuples def. 231 if (RV.getName() == "SubRegIndices" || 232 RV.getName() == "CompositeIndices") { 233 NewReg->addValue(*Def->getValue(RV.getName())); 234 continue; 235 } 236 237 // Some fields get their default uninitialized value. 238 if (RV.getName() == "DwarfNumbers" || 239 RV.getName() == "DwarfAlias" || 240 RV.getName() == "Aliases") { 241 if (const RecordVal *DefRV = RegisterCl->getValue(RV.getName())) 242 NewReg->addValue(*DefRV); 243 continue; 244 } 245 246 // Everything else is copied from Proto. 247 NewReg->addValue(RV); 248 } 249 } 250 } 251 }; 252 } 253 254 //===----------------------------------------------------------------------===// 255 // CodeGenRegisterClass 256 //===----------------------------------------------------------------------===// 257 258 CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R) 259 : TheDef(R), Name(R->getName()), EnumValue(-1) { 260 // Rename anonymous register classes. 261 if (R->getName().size() > 9 && R->getName()[9] == '.') { 262 static unsigned AnonCounter = 0; 263 R->setName("AnonRegClass_"+utostr(AnonCounter++)); 264 } 265 266 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes"); 267 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 268 Record *Type = TypeList[i]; 269 if (!Type->isSubClassOf("ValueType")) 270 throw "RegTypes list member '" + Type->getName() + 271 "' does not derive from the ValueType class!"; 272 VTs.push_back(getValueType(Type)); 273 } 274 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!"); 275 276 // Allocation order 0 is the full set. AltOrders provides others. 277 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R); 278 ListInit *AltOrders = R->getValueAsListInit("AltOrders"); 279 Orders.resize(1 + AltOrders->size()); 280 281 // Default allocation order always contains all registers. 282 for (unsigned i = 0, e = Elements->size(); i != e; ++i) { 283 Orders[0].push_back((*Elements)[i]); 284 Members.insert(RegBank.getReg((*Elements)[i])); 285 } 286 287 // Alternative allocation orders may be subsets. 288 SetTheory::RecSet Order; 289 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) { 290 RegBank.getSets().evaluate(AltOrders->getElement(i), Order); 291 Orders[1 + i].append(Order.begin(), Order.end()); 292 // Verify that all altorder members are regclass members. 293 while (!Order.empty()) { 294 CodeGenRegister *Reg = RegBank.getReg(Order.back()); 295 Order.pop_back(); 296 if (!contains(Reg)) 297 throw TGError(R->getLoc(), " AltOrder register " + Reg->getName() + 298 " is not a class member"); 299 } 300 } 301 302 // SubRegClasses is a list<dag> containing (RC, subregindex, ...) dags. 303 ListInit *SRC = R->getValueAsListInit("SubRegClasses"); 304 for (ListInit::const_iterator i = SRC->begin(), e = SRC->end(); i != e; ++i) { 305 DagInit *DAG = dynamic_cast<DagInit*>(*i); 306 if (!DAG) throw "SubRegClasses must contain DAGs"; 307 DefInit *DAGOp = dynamic_cast<DefInit*>(DAG->getOperator()); 308 Record *RCRec; 309 if (!DAGOp || !(RCRec = DAGOp->getDef())->isSubClassOf("RegisterClass")) 310 throw "Operator '" + DAG->getOperator()->getAsString() + 311 "' in SubRegClasses is not a RegisterClass"; 312 // Iterate over args, all SubRegIndex instances. 313 for (DagInit::const_arg_iterator ai = DAG->arg_begin(), ae = DAG->arg_end(); 314 ai != ae; ++ai) { 315 DefInit *Idx = dynamic_cast<DefInit*>(*ai); 316 Record *IdxRec; 317 if (!Idx || !(IdxRec = Idx->getDef())->isSubClassOf("SubRegIndex")) 318 throw "Argument '" + (*ai)->getAsString() + 319 "' in SubRegClasses is not a SubRegIndex"; 320 if (!SubRegClasses.insert(std::make_pair(IdxRec, RCRec)).second) 321 throw "SubRegIndex '" + IdxRec->getName() + "' mentioned twice"; 322 } 323 } 324 325 // Allow targets to override the size in bits of the RegisterClass. 326 unsigned Size = R->getValueAsInt("Size"); 327 328 Namespace = R->getValueAsString("Namespace"); 329 SpillSize = Size ? Size : EVT(VTs[0]).getSizeInBits(); 330 SpillAlignment = R->getValueAsInt("Alignment"); 331 CopyCost = R->getValueAsInt("CopyCost"); 332 Allocatable = R->getValueAsBit("isAllocatable"); 333 AltOrderSelect = R->getValueAsCode("AltOrderSelect"); 334 } 335 336 // Create an inferred register class that was missing from the .td files. 337 // Most properties will be inherited from the closest super-class after the 338 // class structure has been computed. 339 CodeGenRegisterClass::CodeGenRegisterClass(StringRef Name, Key Props) 340 : Members(*Props.Members), 341 TheDef(0), 342 Name(Name), 343 EnumValue(-1), 344 SpillSize(Props.SpillSize), 345 SpillAlignment(Props.SpillAlignment), 346 CopyCost(0), 347 Allocatable(true) { 348 } 349 350 // Compute inherited propertied for a synthesized register class. 351 void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) { 352 assert(!getDef() && "Only synthesized classes can inherit properties"); 353 assert(!SuperClasses.empty() && "Synthesized class without super class"); 354 355 // The last super-class is the smallest one. 356 CodeGenRegisterClass &Super = *SuperClasses.back(); 357 358 // Most properties are copied directly. 359 // Exceptions are members, size, and alignment 360 Namespace = Super.Namespace; 361 VTs = Super.VTs; 362 CopyCost = Super.CopyCost; 363 Allocatable = Super.Allocatable; 364 AltOrderSelect = Super.AltOrderSelect; 365 366 // Copy all allocation orders, filter out foreign registers from the larger 367 // super-class. 368 Orders.resize(Super.Orders.size()); 369 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i) 370 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j) 371 if (contains(RegBank.getReg(Super.Orders[i][j]))) 372 Orders[i].push_back(Super.Orders[i][j]); 373 } 374 375 bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const { 376 return Members.count(Reg); 377 } 378 379 namespace llvm { 380 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) { 381 OS << "{ S=" << K.SpillSize << ", A=" << K.SpillAlignment; 382 for (CodeGenRegister::Set::const_iterator I = K.Members->begin(), 383 E = K.Members->end(); I != E; ++I) 384 OS << ", " << (*I)->getName(); 385 return OS << " }"; 386 } 387 } 388 389 // This is a simple lexicographical order that can be used to search for sets. 390 // It is not the same as the topological order provided by TopoOrderRC. 391 bool CodeGenRegisterClass::Key:: 392 operator<(const CodeGenRegisterClass::Key &B) const { 393 assert(Members && B.Members); 394 if (*Members != *B.Members) 395 return *Members < *B.Members; 396 if (SpillSize != B.SpillSize) 397 return SpillSize < B.SpillSize; 398 return SpillAlignment < B.SpillAlignment; 399 } 400 401 // Returns true if RC is a strict subclass. 402 // RC is a sub-class of this class if it is a valid replacement for any 403 // instruction operand where a register of this classis required. It must 404 // satisfy these conditions: 405 // 406 // 1. All RC registers are also in this. 407 // 2. The RC spill size must not be smaller than our spill size. 408 // 3. RC spill alignment must be compatible with ours. 409 // 410 static bool testSubClass(const CodeGenRegisterClass *A, 411 const CodeGenRegisterClass *B) { 412 return A->SpillAlignment && B->SpillAlignment % A->SpillAlignment == 0 && 413 A->SpillSize <= B->SpillSize && 414 std::includes(A->getMembers().begin(), A->getMembers().end(), 415 B->getMembers().begin(), B->getMembers().end(), 416 CodeGenRegister::Less()); 417 } 418 419 /// Sorting predicate for register classes. This provides a topological 420 /// ordering that arranges all register classes before their sub-classes. 421 /// 422 /// Register classes with the same registers, spill size, and alignment form a 423 /// clique. They will be ordered alphabetically. 424 /// 425 static int TopoOrderRC(const void *PA, const void *PB) { 426 const CodeGenRegisterClass *A = *(const CodeGenRegisterClass* const*)PA; 427 const CodeGenRegisterClass *B = *(const CodeGenRegisterClass* const*)PB; 428 if (A == B) 429 return 0; 430 431 // Order by descending set size. Note that the classes' allocation order may 432 // not have been computed yet. The Members set is always vaild. 433 if (A->getMembers().size() > B->getMembers().size()) 434 return -1; 435 if (A->getMembers().size() < B->getMembers().size()) 436 return 1; 437 438 // Order by ascending spill size. 439 if (A->SpillSize < B->SpillSize) 440 return -1; 441 if (A->SpillSize > B->SpillSize) 442 return 1; 443 444 // Order by ascending spill alignment. 445 if (A->SpillAlignment < B->SpillAlignment) 446 return -1; 447 if (A->SpillAlignment > B->SpillAlignment) 448 return 1; 449 450 // Finally order by name as a tie breaker. 451 return A->getName() < B->getName(); 452 } 453 454 std::string CodeGenRegisterClass::getQualifiedName() const { 455 if (Namespace.empty()) 456 return getName(); 457 else 458 return Namespace + "::" + getName(); 459 } 460 461 // Compute sub-classes of all register classes. 462 // Assume the classes are ordered topologically. 463 void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) { 464 ArrayRef<CodeGenRegisterClass*> RegClasses = RegBank.getRegClasses(); 465 466 // Visit backwards so sub-classes are seen first. 467 for (unsigned rci = RegClasses.size(); rci; --rci) { 468 CodeGenRegisterClass &RC = *RegClasses[rci - 1]; 469 RC.SubClasses.resize(RegClasses.size()); 470 RC.SubClasses.set(RC.EnumValue); 471 472 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique. 473 for (unsigned s = rci; s != RegClasses.size(); ++s) { 474 if (RC.SubClasses.test(s)) 475 continue; 476 CodeGenRegisterClass *SubRC = RegClasses[s]; 477 if (!testSubClass(&RC, SubRC)) 478 continue; 479 // SubRC is a sub-class. Grap all its sub-classes so we won't have to 480 // check them again. 481 RC.SubClasses |= SubRC->SubClasses; 482 } 483 484 // Sweep up missed clique members. They will be immediately preceeding RC. 485 for (unsigned s = rci - 1; s && testSubClass(&RC, RegClasses[s - 1]); --s) 486 RC.SubClasses.set(s - 1); 487 } 488 489 // Compute the SuperClasses lists from the SubClasses vectors. 490 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) { 491 const BitVector &SC = RegClasses[rci]->getSubClasses(); 492 for (int s = SC.find_first(); s >= 0; s = SC.find_next(s)) { 493 if (unsigned(s) == rci) 494 continue; 495 RegClasses[s]->SuperClasses.push_back(RegClasses[rci]); 496 } 497 } 498 499 // With the class hierarchy in place, let synthesized register classes inherit 500 // properties from their closest super-class. The iteration order here can 501 // propagate properties down multiple levels. 502 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) 503 if (!RegClasses[rci]->getDef()) 504 RegClasses[rci]->inheritProperties(RegBank); 505 } 506 507 //===----------------------------------------------------------------------===// 508 // CodeGenRegBank 509 //===----------------------------------------------------------------------===// 510 511 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) { 512 // Configure register Sets to understand register classes and tuples. 513 Sets.addFieldExpander("RegisterClass", "MemberList"); 514 Sets.addExpander("RegisterTuples", new TupleExpander()); 515 516 // Read in the user-defined (named) sub-register indices. 517 // More indices will be synthesized later. 518 SubRegIndices = Records.getAllDerivedDefinitions("SubRegIndex"); 519 std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord()); 520 NumNamedIndices = SubRegIndices.size(); 521 522 // Read in the register definitions. 523 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register"); 524 std::sort(Regs.begin(), Regs.end(), LessRecord()); 525 Registers.reserve(Regs.size()); 526 // Assign the enumeration values. 527 for (unsigned i = 0, e = Regs.size(); i != e; ++i) 528 getReg(Regs[i]); 529 530 // Expand tuples and number the new registers. 531 std::vector<Record*> Tups = 532 Records.getAllDerivedDefinitions("RegisterTuples"); 533 for (unsigned i = 0, e = Tups.size(); i != e; ++i) { 534 const std::vector<Record*> *TupRegs = Sets.expand(Tups[i]); 535 for (unsigned j = 0, je = TupRegs->size(); j != je; ++j) 536 getReg((*TupRegs)[j]); 537 } 538 539 // Precompute all sub-register maps now all the registers are known. 540 // This will create Composite entries for all inferred sub-register indices. 541 for (unsigned i = 0, e = Registers.size(); i != e; ++i) 542 Registers[i]->getSubRegs(*this); 543 544 // Read in register class definitions. 545 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass"); 546 if (RCs.empty()) 547 throw std::string("No 'RegisterClass' subclasses defined!"); 548 549 // Allocate user-defined register classes. 550 RegClasses.reserve(RCs.size()); 551 for (unsigned i = 0, e = RCs.size(); i != e; ++i) 552 addToMaps(new CodeGenRegisterClass(*this, RCs[i])); 553 554 // Infer missing classes to create a full algebra. 555 computeInferredRegisterClasses(); 556 557 // Order register classes topologically and assign enum values. 558 array_pod_sort(RegClasses.begin(), RegClasses.end(), TopoOrderRC); 559 for (unsigned i = 0, e = RegClasses.size(); i != e; ++i) 560 RegClasses[i]->EnumValue = i; 561 CodeGenRegisterClass::computeSubClasses(*this); 562 } 563 564 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) { 565 CodeGenRegister *&Reg = Def2Reg[Def]; 566 if (Reg) 567 return Reg; 568 Reg = new CodeGenRegister(Def, Registers.size() + 1); 569 Registers.push_back(Reg); 570 return Reg; 571 } 572 573 void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) { 574 RegClasses.push_back(RC); 575 576 if (Record *Def = RC->getDef()) 577 Def2RC.insert(std::make_pair(Def, RC)); 578 579 // Duplicate classes are rejected by insert(). 580 // That's OK, we only care about the properties handled by CGRC::Key. 581 CodeGenRegisterClass::Key K(*RC); 582 Key2RC.insert(std::make_pair(K, RC)); 583 } 584 585 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) { 586 if (CodeGenRegisterClass *RC = Def2RC[Def]) 587 return RC; 588 589 throw TGError(Def->getLoc(), "Not a known RegisterClass!"); 590 } 591 592 Record *CodeGenRegBank::getCompositeSubRegIndex(Record *A, Record *B, 593 bool create) { 594 // Look for an existing entry. 595 Record *&Comp = Composite[std::make_pair(A, B)]; 596 if (Comp || !create) 597 return Comp; 598 599 // None exists, synthesize one. 600 std::string Name = A->getName() + "_then_" + B->getName(); 601 Comp = new Record(Name, SMLoc(), Records); 602 SubRegIndices.push_back(Comp); 603 return Comp; 604 } 605 606 unsigned CodeGenRegBank::getSubRegIndexNo(Record *idx) { 607 std::vector<Record*>::const_iterator i = 608 std::find(SubRegIndices.begin(), SubRegIndices.end(), idx); 609 assert(i != SubRegIndices.end() && "Not a SubRegIndex"); 610 return (i - SubRegIndices.begin()) + 1; 611 } 612 613 void CodeGenRegBank::computeComposites() { 614 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 615 CodeGenRegister *Reg1 = Registers[i]; 616 const CodeGenRegister::SubRegMap &SRM1 = Reg1->getSubRegs(); 617 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(), 618 e1 = SRM1.end(); i1 != e1; ++i1) { 619 Record *Idx1 = i1->first; 620 CodeGenRegister *Reg2 = i1->second; 621 // Ignore identity compositions. 622 if (Reg1 == Reg2) 623 continue; 624 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs(); 625 // Try composing Idx1 with another SubRegIndex. 626 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(), 627 e2 = SRM2.end(); i2 != e2; ++i2) { 628 std::pair<Record*, Record*> IdxPair(Idx1, i2->first); 629 CodeGenRegister *Reg3 = i2->second; 630 // Ignore identity compositions. 631 if (Reg2 == Reg3) 632 continue; 633 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3. 634 for (CodeGenRegister::SubRegMap::const_iterator i1d = SRM1.begin(), 635 e1d = SRM1.end(); i1d != e1d; ++i1d) { 636 if (i1d->second == Reg3) { 637 std::pair<CompositeMap::iterator, bool> Ins = 638 Composite.insert(std::make_pair(IdxPair, i1d->first)); 639 // Conflicting composition? Emit a warning but allow it. 640 if (!Ins.second && Ins.first->second != i1d->first) { 641 errs() << "Warning: SubRegIndex " << getQualifiedName(Idx1) 642 << " and " << getQualifiedName(IdxPair.second) 643 << " compose ambiguously as " 644 << getQualifiedName(Ins.first->second) << " or " 645 << getQualifiedName(i1d->first) << "\n"; 646 } 647 } 648 } 649 } 650 } 651 } 652 653 // We don't care about the difference between (Idx1, Idx2) -> Idx2 and invalid 654 // compositions, so remove any mappings of that form. 655 for (CompositeMap::iterator i = Composite.begin(), e = Composite.end(); 656 i != e;) { 657 CompositeMap::iterator j = i; 658 ++i; 659 if (j->first.second == j->second) 660 Composite.erase(j); 661 } 662 } 663 664 // Compute sets of overlapping registers. 665 // 666 // The standard set is all super-registers and all sub-registers, but the 667 // target description can add arbitrary overlapping registers via the 'Aliases' 668 // field. This complicates things, but we can compute overlapping sets using 669 // the following rules: 670 // 671 // 1. The relation overlap(A, B) is reflexive and symmetric but not transitive. 672 // 673 // 2. overlap(A, B) implies overlap(A, S) for all S in supers(B). 674 // 675 // Alternatively: 676 // 677 // overlap(A, B) iff there exists: 678 // A' in { A, subregs(A) } and B' in { B, subregs(B) } such that: 679 // A' = B' or A' in aliases(B') or B' in aliases(A'). 680 // 681 // Here subregs(A) is the full flattened sub-register set returned by 682 // A.getSubRegs() while aliases(A) is simply the special 'Aliases' field in the 683 // description of register A. 684 // 685 // This also implies that registers with a common sub-register are considered 686 // overlapping. This can happen when forming register pairs: 687 // 688 // P0 = (R0, R1) 689 // P1 = (R1, R2) 690 // P2 = (R2, R3) 691 // 692 // In this case, we will infer an overlap between P0 and P1 because of the 693 // shared sub-register R1. There is no overlap between P0 and P2. 694 // 695 void CodeGenRegBank:: 696 computeOverlaps(std::map<const CodeGenRegister*, CodeGenRegister::Set> &Map) { 697 assert(Map.empty()); 698 699 // Collect overlaps that don't follow from rule 2. 700 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 701 CodeGenRegister *Reg = Registers[i]; 702 CodeGenRegister::Set &Overlaps = Map[Reg]; 703 704 // Reg overlaps itself. 705 Overlaps.insert(Reg); 706 707 // All super-registers overlap. 708 const CodeGenRegister::SuperRegList &Supers = Reg->getSuperRegs(); 709 Overlaps.insert(Supers.begin(), Supers.end()); 710 711 // Form symmetrical relations from the special Aliases[] lists. 712 std::vector<Record*> RegList = Reg->TheDef->getValueAsListOfDefs("Aliases"); 713 for (unsigned i2 = 0, e2 = RegList.size(); i2 != e2; ++i2) { 714 CodeGenRegister *Reg2 = getReg(RegList[i2]); 715 CodeGenRegister::Set &Overlaps2 = Map[Reg2]; 716 const CodeGenRegister::SuperRegList &Supers2 = Reg2->getSuperRegs(); 717 // Reg overlaps Reg2 which implies it overlaps supers(Reg2). 718 Overlaps.insert(Reg2); 719 Overlaps.insert(Supers2.begin(), Supers2.end()); 720 Overlaps2.insert(Reg); 721 Overlaps2.insert(Supers.begin(), Supers.end()); 722 } 723 } 724 725 // Apply rule 2. and inherit all sub-register overlaps. 726 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 727 CodeGenRegister *Reg = Registers[i]; 728 CodeGenRegister::Set &Overlaps = Map[Reg]; 729 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs(); 730 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM.begin(), 731 e2 = SRM.end(); i2 != e2; ++i2) { 732 CodeGenRegister::Set &Overlaps2 = Map[i2->second]; 733 Overlaps.insert(Overlaps2.begin(), Overlaps2.end()); 734 } 735 } 736 } 737 738 void CodeGenRegBank::computeDerivedInfo() { 739 computeComposites(); 740 } 741 742 // Infer missing register classes. 743 // 744 // For every register class RC, make sure that the set of registers in RC with 745 // a given SubIxx sub-register form a register class. 746 void CodeGenRegBank::computeInferredRegisterClasses() { 747 // When this function is called, the register classes have not been sorted 748 // and assigned EnumValues yet. That means getSubClasses(), 749 // getSuperClasses(), and hasSubClass() functions are defunct. 750 751 // Map SubRegIndex to register set. 752 typedef std::map<Record*, CodeGenRegister::Set, LessRecord> SubReg2SetMap; 753 754 // Visit all register classes, including the ones being added by the loop. 755 for (unsigned rci = 0; rci != RegClasses.size(); ++rci) { 756 CodeGenRegisterClass &RC = *RegClasses[rci]; 757 758 // Compute the set of registers supporting each SubRegIndex. 759 SubReg2SetMap SRSets; 760 for (CodeGenRegister::Set::const_iterator RI = RC.getMembers().begin(), 761 RE = RC.getMembers().end(); RI != RE; ++RI) { 762 const CodeGenRegister::SubRegMap &SRM = (*RI)->getSubRegs(); 763 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(), 764 E = SRM.end(); I != E; ++I) 765 SRSets[I->first].insert(*RI); 766 } 767 768 // Find matching classes for all SRSets entries. Iterate in SubRegIndex 769 // numerical order to visit synthetic indices last. 770 for (unsigned sri = 0, sre = SubRegIndices.size(); sri != sre; ++sri) { 771 Record *SubIdx = SubRegIndices[sri]; 772 SubReg2SetMap::const_iterator I = SRSets.find(SubIdx); 773 // Unsupported SubRegIndex. Skip it. 774 if (I == SRSets.end()) 775 continue; 776 // In most cases, all RC registers support the SubRegIndex. 777 if (I->second.size() == RC.getMembers().size()) { 778 RC.setSubClassWithSubReg(SubIdx, &RC); 779 continue; 780 } 781 782 // This is a real subset. See if we have a matching class. 783 CodeGenRegisterClass::Key K(&I->second, RC.SpillSize, RC.SpillAlignment); 784 RCKeyMap::const_iterator FoundI = Key2RC.find(K); 785 if (FoundI != Key2RC.end()) { 786 RC.setSubClassWithSubReg(SubIdx, FoundI->second); 787 continue; 788 } 789 790 // Class doesn't exist. 791 CodeGenRegisterClass *NewRC = 792 new CodeGenRegisterClass(RC.getName() + "_with_" + 793 I->first->getName(), K); 794 addToMaps(NewRC); 795 RC.setSubClassWithSubReg(SubIdx, NewRC); 796 } 797 } 798 } 799 800 /// getRegisterClassForRegister - Find the register class that contains the 801 /// specified physical register. If the register is not in a register class, 802 /// return null. If the register is in multiple classes, and the classes have a 803 /// superset-subset relationship and the same set of types, return the 804 /// superclass. Otherwise return null. 805 const CodeGenRegisterClass* 806 CodeGenRegBank::getRegClassForRegister(Record *R) { 807 const CodeGenRegister *Reg = getReg(R); 808 ArrayRef<CodeGenRegisterClass*> RCs = getRegClasses(); 809 const CodeGenRegisterClass *FoundRC = 0; 810 for (unsigned i = 0, e = RCs.size(); i != e; ++i) { 811 const CodeGenRegisterClass &RC = *RCs[i]; 812 if (!RC.contains(Reg)) 813 continue; 814 815 // If this is the first class that contains the register, 816 // make a note of it and go on to the next class. 817 if (!FoundRC) { 818 FoundRC = &RC; 819 continue; 820 } 821 822 // If a register's classes have different types, return null. 823 if (RC.getValueTypes() != FoundRC->getValueTypes()) 824 return 0; 825 826 // Check to see if the previously found class that contains 827 // the register is a subclass of the current class. If so, 828 // prefer the superclass. 829 if (RC.hasSubClass(FoundRC)) { 830 FoundRC = &RC; 831 continue; 832 } 833 834 // Check to see if the previously found class that contains 835 // the register is a superclass of the current class. If so, 836 // prefer the superclass. 837 if (FoundRC->hasSubClass(&RC)) 838 continue; 839 840 // Multiple classes, and neither is a superclass of the other. 841 // Return null. 842 return 0; 843 } 844 return FoundRC; 845 } 846