1 //===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===// 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 tablegen backend emits subtarget enumerations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenTarget.h" 15 #include "CodeGenSchedule.h" 16 #include "llvm/ADT/SmallPtrSet.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/MC/MCInstrItineraries.h" 21 #include "llvm/MC/MCSchedule.h" 22 #include "llvm/MC/SubtargetFeature.h" 23 #include "llvm/Support/Debug.h" 24 #include "llvm/Support/Format.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/TableGen/Error.h" 27 #include "llvm/TableGen/Record.h" 28 #include "llvm/TableGen/TableGenBackend.h" 29 #include <algorithm> 30 #include <cassert> 31 #include <cstdint> 32 #include <iterator> 33 #include <map> 34 #include <string> 35 #include <vector> 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "subtarget-emitter" 40 41 namespace { 42 43 class SubtargetEmitter { 44 // Each processor has a SchedClassDesc table with an entry for each SchedClass. 45 // The SchedClassDesc table indexes into a global write resource table, write 46 // latency table, and read advance table. 47 struct SchedClassTables { 48 std::vector<std::vector<MCSchedClassDesc>> ProcSchedClasses; 49 std::vector<MCWriteProcResEntry> WriteProcResources; 50 std::vector<MCWriteLatencyEntry> WriteLatencies; 51 std::vector<std::string> WriterNames; 52 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries; 53 54 // Reserve an invalid entry at index 0 55 SchedClassTables() { 56 ProcSchedClasses.resize(1); 57 WriteProcResources.resize(1); 58 WriteLatencies.resize(1); 59 WriterNames.push_back("InvalidWrite"); 60 ReadAdvanceEntries.resize(1); 61 } 62 }; 63 64 struct LessWriteProcResources { 65 bool operator()(const MCWriteProcResEntry &LHS, 66 const MCWriteProcResEntry &RHS) { 67 return LHS.ProcResourceIdx < RHS.ProcResourceIdx; 68 } 69 }; 70 71 const CodeGenTarget &TGT; 72 RecordKeeper &Records; 73 CodeGenSchedModels &SchedModels; 74 std::string Target; 75 76 void Enumeration(raw_ostream &OS); 77 unsigned FeatureKeyValues(raw_ostream &OS); 78 unsigned CPUKeyValues(raw_ostream &OS); 79 void FormItineraryStageString(const std::string &Names, 80 Record *ItinData, std::string &ItinString, 81 unsigned &NStages); 82 void FormItineraryOperandCycleString(Record *ItinData, std::string &ItinString, 83 unsigned &NOperandCycles); 84 void FormItineraryBypassString(const std::string &Names, 85 Record *ItinData, 86 std::string &ItinString, unsigned NOperandCycles); 87 void EmitStageAndOperandCycleData(raw_ostream &OS, 88 std::vector<std::vector<InstrItinerary>> 89 &ProcItinLists); 90 void EmitItineraries(raw_ostream &OS, 91 std::vector<std::vector<InstrItinerary>> 92 &ProcItinLists); 93 void EmitProcessorProp(raw_ostream &OS, const Record *R, StringRef Name, 94 char Separator); 95 void EmitProcessorResourceSubUnits(const CodeGenProcModel &ProcModel, 96 raw_ostream &OS); 97 void EmitProcessorResources(const CodeGenProcModel &ProcModel, 98 raw_ostream &OS); 99 Record *FindWriteResources(const CodeGenSchedRW &SchedWrite, 100 const CodeGenProcModel &ProcModel); 101 Record *FindReadAdvance(const CodeGenSchedRW &SchedRead, 102 const CodeGenProcModel &ProcModel); 103 void ExpandProcResources(RecVec &PRVec, std::vector<int64_t> &Cycles, 104 const CodeGenProcModel &ProcModel); 105 void GenSchedClassTables(const CodeGenProcModel &ProcModel, 106 SchedClassTables &SchedTables); 107 void EmitSchedClassTables(SchedClassTables &SchedTables, raw_ostream &OS); 108 void EmitProcessorModels(raw_ostream &OS); 109 void EmitProcessorLookup(raw_ostream &OS); 110 void EmitSchedModelHelpers(const std::string &ClassName, raw_ostream &OS); 111 void EmitSchedModel(raw_ostream &OS); 112 void EmitHwModeCheck(const std::string &ClassName, raw_ostream &OS); 113 void ParseFeaturesFunction(raw_ostream &OS, unsigned NumFeatures, 114 unsigned NumProcs); 115 116 public: 117 SubtargetEmitter(RecordKeeper &R, CodeGenTarget &TGT) 118 : TGT(TGT), Records(R), SchedModels(TGT.getSchedModels()), 119 Target(TGT.getName()) {} 120 121 void run(raw_ostream &o); 122 }; 123 124 } // end anonymous namespace 125 126 // 127 // Enumeration - Emit the specified class as an enumeration. 128 // 129 void SubtargetEmitter::Enumeration(raw_ostream &OS) { 130 // Get all records of class and sort 131 std::vector<Record*> DefList = 132 Records.getAllDerivedDefinitions("SubtargetFeature"); 133 std::sort(DefList.begin(), DefList.end(), LessRecord()); 134 135 unsigned N = DefList.size(); 136 if (N == 0) 137 return; 138 if (N > MAX_SUBTARGET_FEATURES) 139 PrintFatalError("Too many subtarget features! Bump MAX_SUBTARGET_FEATURES."); 140 141 OS << "namespace " << Target << " {\n"; 142 143 // Open enumeration. 144 OS << "enum {\n"; 145 146 // For each record 147 for (unsigned i = 0; i < N; ++i) { 148 // Next record 149 Record *Def = DefList[i]; 150 151 // Get and emit name 152 OS << " " << Def->getName() << " = " << i << ",\n"; 153 } 154 155 // Close enumeration and namespace 156 OS << "};\n"; 157 OS << "} // end namespace " << Target << "\n"; 158 } 159 160 // 161 // FeatureKeyValues - Emit data of all the subtarget features. Used by the 162 // command line. 163 // 164 unsigned SubtargetEmitter::FeatureKeyValues(raw_ostream &OS) { 165 // Gather and sort all the features 166 std::vector<Record*> FeatureList = 167 Records.getAllDerivedDefinitions("SubtargetFeature"); 168 169 if (FeatureList.empty()) 170 return 0; 171 172 std::sort(FeatureList.begin(), FeatureList.end(), LessRecordFieldName()); 173 174 // Begin feature table 175 OS << "// Sorted (by key) array of values for CPU features.\n" 176 << "extern const llvm::SubtargetFeatureKV " << Target 177 << "FeatureKV[] = {\n"; 178 179 // For each feature 180 unsigned NumFeatures = 0; 181 for (unsigned i = 0, N = FeatureList.size(); i < N; ++i) { 182 // Next feature 183 Record *Feature = FeatureList[i]; 184 185 StringRef Name = Feature->getName(); 186 StringRef CommandLineName = Feature->getValueAsString("Name"); 187 StringRef Desc = Feature->getValueAsString("Desc"); 188 189 if (CommandLineName.empty()) continue; 190 191 // Emit as { "feature", "description", { featureEnum }, { i1 , i2 , ... , in } } 192 OS << " { " 193 << "\"" << CommandLineName << "\", " 194 << "\"" << Desc << "\", " 195 << "{ " << Target << "::" << Name << " }, "; 196 197 RecVec ImpliesList = Feature->getValueAsListOfDefs("Implies"); 198 199 OS << "{"; 200 for (unsigned j = 0, M = ImpliesList.size(); j < M;) { 201 OS << " " << Target << "::" << ImpliesList[j]->getName(); 202 if (++j < M) OS << ","; 203 } 204 OS << " } },\n"; 205 ++NumFeatures; 206 } 207 208 // End feature table 209 OS << "};\n"; 210 211 return NumFeatures; 212 } 213 214 // 215 // CPUKeyValues - Emit data of all the subtarget processors. Used by command 216 // line. 217 // 218 unsigned SubtargetEmitter::CPUKeyValues(raw_ostream &OS) { 219 // Gather and sort processor information 220 std::vector<Record*> ProcessorList = 221 Records.getAllDerivedDefinitions("Processor"); 222 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName()); 223 224 // Begin processor table 225 OS << "// Sorted (by key) array of values for CPU subtype.\n" 226 << "extern const llvm::SubtargetFeatureKV " << Target 227 << "SubTypeKV[] = {\n"; 228 229 // For each processor 230 for (Record *Processor : ProcessorList) { 231 StringRef Name = Processor->getValueAsString("Name"); 232 RecVec FeatureList = Processor->getValueAsListOfDefs("Features"); 233 234 // Emit as { "cpu", "description", { f1 , f2 , ... fn } }, 235 OS << " { " 236 << "\"" << Name << "\", " 237 << "\"Select the " << Name << " processor\", "; 238 239 OS << "{"; 240 for (unsigned j = 0, M = FeatureList.size(); j < M;) { 241 OS << " " << Target << "::" << FeatureList[j]->getName(); 242 if (++j < M) OS << ","; 243 } 244 // The { } is for the "implies" section of this data structure. 245 OS << " }, { } },\n"; 246 } 247 248 // End processor table 249 OS << "};\n"; 250 251 return ProcessorList.size(); 252 } 253 254 // 255 // FormItineraryStageString - Compose a string containing the stage 256 // data initialization for the specified itinerary. N is the number 257 // of stages. 258 // 259 void SubtargetEmitter::FormItineraryStageString(const std::string &Name, 260 Record *ItinData, 261 std::string &ItinString, 262 unsigned &NStages) { 263 // Get states list 264 RecVec StageList = ItinData->getValueAsListOfDefs("Stages"); 265 266 // For each stage 267 unsigned N = NStages = StageList.size(); 268 for (unsigned i = 0; i < N;) { 269 // Next stage 270 const Record *Stage = StageList[i]; 271 272 // Form string as ,{ cycles, u1 | u2 | ... | un, timeinc, kind } 273 int Cycles = Stage->getValueAsInt("Cycles"); 274 ItinString += " { " + itostr(Cycles) + ", "; 275 276 // Get unit list 277 RecVec UnitList = Stage->getValueAsListOfDefs("Units"); 278 279 // For each unit 280 for (unsigned j = 0, M = UnitList.size(); j < M;) { 281 // Add name and bitwise or 282 ItinString += Name + "FU::" + UnitList[j]->getName().str(); 283 if (++j < M) ItinString += " | "; 284 } 285 286 int TimeInc = Stage->getValueAsInt("TimeInc"); 287 ItinString += ", " + itostr(TimeInc); 288 289 int Kind = Stage->getValueAsInt("Kind"); 290 ItinString += ", (llvm::InstrStage::ReservationKinds)" + itostr(Kind); 291 292 // Close off stage 293 ItinString += " }"; 294 if (++i < N) ItinString += ", "; 295 } 296 } 297 298 // 299 // FormItineraryOperandCycleString - Compose a string containing the 300 // operand cycle initialization for the specified itinerary. N is the 301 // number of operands that has cycles specified. 302 // 303 void SubtargetEmitter::FormItineraryOperandCycleString(Record *ItinData, 304 std::string &ItinString, unsigned &NOperandCycles) { 305 // Get operand cycle list 306 std::vector<int64_t> OperandCycleList = 307 ItinData->getValueAsListOfInts("OperandCycles"); 308 309 // For each operand cycle 310 unsigned N = NOperandCycles = OperandCycleList.size(); 311 for (unsigned i = 0; i < N;) { 312 // Next operand cycle 313 const int OCycle = OperandCycleList[i]; 314 315 ItinString += " " + itostr(OCycle); 316 if (++i < N) ItinString += ", "; 317 } 318 } 319 320 void SubtargetEmitter::FormItineraryBypassString(const std::string &Name, 321 Record *ItinData, 322 std::string &ItinString, 323 unsigned NOperandCycles) { 324 RecVec BypassList = ItinData->getValueAsListOfDefs("Bypasses"); 325 unsigned N = BypassList.size(); 326 unsigned i = 0; 327 for (; i < N;) { 328 ItinString += Name + "Bypass::" + BypassList[i]->getName().str(); 329 if (++i < NOperandCycles) ItinString += ", "; 330 } 331 for (; i < NOperandCycles;) { 332 ItinString += " 0"; 333 if (++i < NOperandCycles) ItinString += ", "; 334 } 335 } 336 337 // 338 // EmitStageAndOperandCycleData - Generate unique itinerary stages and operand 339 // cycle tables. Create a list of InstrItinerary objects (ProcItinLists) indexed 340 // by CodeGenSchedClass::Index. 341 // 342 void SubtargetEmitter:: 343 EmitStageAndOperandCycleData(raw_ostream &OS, 344 std::vector<std::vector<InstrItinerary>> 345 &ProcItinLists) { 346 // Multiple processor models may share an itinerary record. Emit it once. 347 SmallPtrSet<Record*, 8> ItinsDefSet; 348 349 // Emit functional units for all the itineraries. 350 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { 351 352 if (!ItinsDefSet.insert(ProcModel.ItinsDef).second) 353 continue; 354 355 RecVec FUs = ProcModel.ItinsDef->getValueAsListOfDefs("FU"); 356 if (FUs.empty()) 357 continue; 358 359 StringRef Name = ProcModel.ItinsDef->getName(); 360 OS << "\n// Functional units for \"" << Name << "\"\n" 361 << "namespace " << Name << "FU {\n"; 362 363 for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j) 364 OS << " const unsigned " << FUs[j]->getName() 365 << " = 1 << " << j << ";\n"; 366 367 OS << "} // end namespace " << Name << "FU\n"; 368 369 RecVec BPs = ProcModel.ItinsDef->getValueAsListOfDefs("BP"); 370 if (!BPs.empty()) { 371 OS << "\n// Pipeline forwarding paths for itineraries \"" << Name 372 << "\"\n" << "namespace " << Name << "Bypass {\n"; 373 374 OS << " const unsigned NoBypass = 0;\n"; 375 for (unsigned j = 0, BPN = BPs.size(); j < BPN; ++j) 376 OS << " const unsigned " << BPs[j]->getName() 377 << " = 1 << " << j << ";\n"; 378 379 OS << "} // end namespace " << Name << "Bypass\n"; 380 } 381 } 382 383 // Begin stages table 384 std::string StageTable = "\nextern const llvm::InstrStage " + Target + 385 "Stages[] = {\n"; 386 StageTable += " { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n"; 387 388 // Begin operand cycle table 389 std::string OperandCycleTable = "extern const unsigned " + Target + 390 "OperandCycles[] = {\n"; 391 OperandCycleTable += " 0, // No itinerary\n"; 392 393 // Begin pipeline bypass table 394 std::string BypassTable = "extern const unsigned " + Target + 395 "ForwardingPaths[] = {\n"; 396 BypassTable += " 0, // No itinerary\n"; 397 398 // For each Itinerary across all processors, add a unique entry to the stages, 399 // operand cycles, and pipeline bypass tables. Then add the new Itinerary 400 // object with computed offsets to the ProcItinLists result. 401 unsigned StageCount = 1, OperandCycleCount = 1; 402 std::map<std::string, unsigned> ItinStageMap, ItinOperandMap; 403 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { 404 // Add process itinerary to the list. 405 ProcItinLists.resize(ProcItinLists.size()+1); 406 407 // If this processor defines no itineraries, then leave the itinerary list 408 // empty. 409 std::vector<InstrItinerary> &ItinList = ProcItinLists.back(); 410 if (!ProcModel.hasItineraries()) 411 continue; 412 413 StringRef Name = ProcModel.ItinsDef->getName(); 414 415 ItinList.resize(SchedModels.numInstrSchedClasses()); 416 assert(ProcModel.ItinDefList.size() == ItinList.size() && "bad Itins"); 417 418 for (unsigned SchedClassIdx = 0, SchedClassEnd = ItinList.size(); 419 SchedClassIdx < SchedClassEnd; ++SchedClassIdx) { 420 421 // Next itinerary data 422 Record *ItinData = ProcModel.ItinDefList[SchedClassIdx]; 423 424 // Get string and stage count 425 std::string ItinStageString; 426 unsigned NStages = 0; 427 if (ItinData) 428 FormItineraryStageString(Name, ItinData, ItinStageString, NStages); 429 430 // Get string and operand cycle count 431 std::string ItinOperandCycleString; 432 unsigned NOperandCycles = 0; 433 std::string ItinBypassString; 434 if (ItinData) { 435 FormItineraryOperandCycleString(ItinData, ItinOperandCycleString, 436 NOperandCycles); 437 438 FormItineraryBypassString(Name, ItinData, ItinBypassString, 439 NOperandCycles); 440 } 441 442 // Check to see if stage already exists and create if it doesn't 443 uint16_t FindStage = 0; 444 if (NStages > 0) { 445 FindStage = ItinStageMap[ItinStageString]; 446 if (FindStage == 0) { 447 // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // indices 448 StageTable += ItinStageString + ", // " + itostr(StageCount); 449 if (NStages > 1) 450 StageTable += "-" + itostr(StageCount + NStages - 1); 451 StageTable += "\n"; 452 // Record Itin class number. 453 ItinStageMap[ItinStageString] = FindStage = StageCount; 454 StageCount += NStages; 455 } 456 } 457 458 // Check to see if operand cycle already exists and create if it doesn't 459 uint16_t FindOperandCycle = 0; 460 if (NOperandCycles > 0) { 461 std::string ItinOperandString = ItinOperandCycleString+ItinBypassString; 462 FindOperandCycle = ItinOperandMap[ItinOperandString]; 463 if (FindOperandCycle == 0) { 464 // Emit as cycle, // index 465 OperandCycleTable += ItinOperandCycleString + ", // "; 466 std::string OperandIdxComment = itostr(OperandCycleCount); 467 if (NOperandCycles > 1) 468 OperandIdxComment += "-" 469 + itostr(OperandCycleCount + NOperandCycles - 1); 470 OperandCycleTable += OperandIdxComment + "\n"; 471 // Record Itin class number. 472 ItinOperandMap[ItinOperandCycleString] = 473 FindOperandCycle = OperandCycleCount; 474 // Emit as bypass, // index 475 BypassTable += ItinBypassString + ", // " + OperandIdxComment + "\n"; 476 OperandCycleCount += NOperandCycles; 477 } 478 } 479 480 // Set up itinerary as location and location + stage count 481 int16_t NumUOps = ItinData ? ItinData->getValueAsInt("NumMicroOps") : 0; 482 InstrItinerary Intinerary = { 483 NumUOps, 484 FindStage, 485 uint16_t(FindStage + NStages), 486 FindOperandCycle, 487 uint16_t(FindOperandCycle + NOperandCycles), 488 }; 489 490 // Inject - empty slots will be 0, 0 491 ItinList[SchedClassIdx] = Intinerary; 492 } 493 } 494 495 // Closing stage 496 StageTable += " { 0, 0, 0, llvm::InstrStage::Required } // End stages\n"; 497 StageTable += "};\n"; 498 499 // Closing operand cycles 500 OperandCycleTable += " 0 // End operand cycles\n"; 501 OperandCycleTable += "};\n"; 502 503 BypassTable += " 0 // End bypass tables\n"; 504 BypassTable += "};\n"; 505 506 // Emit tables. 507 OS << StageTable; 508 OS << OperandCycleTable; 509 OS << BypassTable; 510 } 511 512 // 513 // EmitProcessorData - Generate data for processor itineraries that were 514 // computed during EmitStageAndOperandCycleData(). ProcItinLists lists all 515 // Itineraries for each processor. The Itinerary lists are indexed on 516 // CodeGenSchedClass::Index. 517 // 518 void SubtargetEmitter:: 519 EmitItineraries(raw_ostream &OS, 520 std::vector<std::vector<InstrItinerary>> &ProcItinLists) { 521 // Multiple processor models may share an itinerary record. Emit it once. 522 SmallPtrSet<Record*, 8> ItinsDefSet; 523 524 // For each processor's machine model 525 std::vector<std::vector<InstrItinerary>>::iterator 526 ProcItinListsIter = ProcItinLists.begin(); 527 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(), 528 PE = SchedModels.procModelEnd(); PI != PE; ++PI, ++ProcItinListsIter) { 529 530 Record *ItinsDef = PI->ItinsDef; 531 if (!ItinsDefSet.insert(ItinsDef).second) 532 continue; 533 534 // Get the itinerary list for the processor. 535 assert(ProcItinListsIter != ProcItinLists.end() && "bad iterator"); 536 std::vector<InstrItinerary> &ItinList = *ProcItinListsIter; 537 538 // Empty itineraries aren't referenced anywhere in the tablegen output 539 // so don't emit them. 540 if (ItinList.empty()) 541 continue; 542 543 OS << "\n"; 544 OS << "static const llvm::InstrItinerary "; 545 546 // Begin processor itinerary table 547 OS << ItinsDef->getName() << "[] = {\n"; 548 549 // For each itinerary class in CodeGenSchedClass::Index order. 550 for (unsigned j = 0, M = ItinList.size(); j < M; ++j) { 551 InstrItinerary &Intinerary = ItinList[j]; 552 553 // Emit Itinerary in the form of 554 // { firstStage, lastStage, firstCycle, lastCycle } // index 555 OS << " { " << 556 Intinerary.NumMicroOps << ", " << 557 Intinerary.FirstStage << ", " << 558 Intinerary.LastStage << ", " << 559 Intinerary.FirstOperandCycle << ", " << 560 Intinerary.LastOperandCycle << " }" << 561 ", // " << j << " " << SchedModels.getSchedClass(j).Name << "\n"; 562 } 563 // End processor itinerary table 564 OS << " { 0, uint16_t(~0U), uint16_t(~0U), uint16_t(~0U), uint16_t(~0U) }" 565 "// end marker\n"; 566 OS << "};\n"; 567 } 568 } 569 570 // Emit either the value defined in the TableGen Record, or the default 571 // value defined in the C++ header. The Record is null if the processor does not 572 // define a model. 573 void SubtargetEmitter::EmitProcessorProp(raw_ostream &OS, const Record *R, 574 StringRef Name, char Separator) { 575 OS << " "; 576 int V = R ? R->getValueAsInt(Name) : -1; 577 if (V >= 0) 578 OS << V << Separator << " // " << Name; 579 else 580 OS << "MCSchedModel::Default" << Name << Separator; 581 OS << '\n'; 582 } 583 584 void SubtargetEmitter::EmitProcessorResourceSubUnits( 585 const CodeGenProcModel &ProcModel, raw_ostream &OS) { 586 OS << "\nstatic const unsigned " << ProcModel.ModelName 587 << "ProcResourceSubUnits[] = {\n" 588 << " 0, // Invalid\n"; 589 590 for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) { 591 Record *PRDef = ProcModel.ProcResourceDefs[i]; 592 if (!PRDef->isSubClassOf("ProcResGroup")) 593 continue; 594 RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources"); 595 for (Record *RUDef : ResUnits) { 596 Record *const RU = 597 SchedModels.findProcResUnits(RUDef, ProcModel, PRDef->getLoc()); 598 for (unsigned J = 0; J < RU->getValueAsInt("NumUnits"); ++J) { 599 OS << " " << ProcModel.getProcResourceIdx(RU) << ", "; 600 } 601 } 602 OS << " // " << PRDef->getName() << "\n"; 603 } 604 OS << "};\n"; 605 } 606 607 void SubtargetEmitter::EmitProcessorResources(const CodeGenProcModel &ProcModel, 608 raw_ostream &OS) { 609 EmitProcessorResourceSubUnits(ProcModel, OS); 610 611 OS << "\n// {Name, NumUnits, SuperIdx, IsBuffered, SubUnitsIdxBegin}\n"; 612 OS << "static const llvm::MCProcResourceDesc " << ProcModel.ModelName 613 << "ProcResources" 614 << "[] = {\n" 615 << " {\"InvalidUnit\", 0, 0, 0, 0},\n"; 616 617 unsigned SubUnitsOffset = 1; 618 for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) { 619 Record *PRDef = ProcModel.ProcResourceDefs[i]; 620 621 Record *SuperDef = nullptr; 622 unsigned SuperIdx = 0; 623 unsigned NumUnits = 0; 624 const unsigned SubUnitsBeginOffset = SubUnitsOffset; 625 int BufferSize = PRDef->getValueAsInt("BufferSize"); 626 if (PRDef->isSubClassOf("ProcResGroup")) { 627 RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources"); 628 for (Record *RU : ResUnits) { 629 NumUnits += RU->getValueAsInt("NumUnits"); 630 SubUnitsOffset += RU->getValueAsInt("NumUnits"); 631 } 632 } 633 else { 634 // Find the SuperIdx 635 if (PRDef->getValueInit("Super")->isComplete()) { 636 SuperDef = 637 SchedModels.findProcResUnits(PRDef->getValueAsDef("Super"), 638 ProcModel, PRDef->getLoc()); 639 SuperIdx = ProcModel.getProcResourceIdx(SuperDef); 640 } 641 NumUnits = PRDef->getValueAsInt("NumUnits"); 642 } 643 // Emit the ProcResourceDesc 644 OS << " {\"" << PRDef->getName() << "\", "; 645 if (PRDef->getName().size() < 15) 646 OS.indent(15 - PRDef->getName().size()); 647 OS << NumUnits << ", " << SuperIdx << ", " << BufferSize << ", "; 648 if (SubUnitsBeginOffset != SubUnitsOffset) { 649 OS << ProcModel.ModelName << "ProcResourceSubUnits + " 650 << SubUnitsBeginOffset; 651 } else { 652 OS << "nullptr"; 653 } 654 OS << "}, // #" << i+1; 655 if (SuperDef) 656 OS << ", Super=" << SuperDef->getName(); 657 OS << "\n"; 658 } 659 OS << "};\n"; 660 } 661 662 // Find the WriteRes Record that defines processor resources for this 663 // SchedWrite. 664 Record *SubtargetEmitter::FindWriteResources( 665 const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) { 666 667 // Check if the SchedWrite is already subtarget-specific and directly 668 // specifies a set of processor resources. 669 if (SchedWrite.TheDef->isSubClassOf("SchedWriteRes")) 670 return SchedWrite.TheDef; 671 672 Record *AliasDef = nullptr; 673 for (Record *A : SchedWrite.Aliases) { 674 const CodeGenSchedRW &AliasRW = 675 SchedModels.getSchedRW(A->getValueAsDef("AliasRW")); 676 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) { 677 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel"); 678 if (&SchedModels.getProcModel(ModelDef) != &ProcModel) 679 continue; 680 } 681 if (AliasDef) 682 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases " 683 "defined for processor " + ProcModel.ModelName + 684 " Ensure only one SchedAlias exists per RW."); 685 AliasDef = AliasRW.TheDef; 686 } 687 if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes")) 688 return AliasDef; 689 690 // Check this processor's list of write resources. 691 Record *ResDef = nullptr; 692 for (Record *WR : ProcModel.WriteResDefs) { 693 if (!WR->isSubClassOf("WriteRes")) 694 continue; 695 if (AliasDef == WR->getValueAsDef("WriteType") 696 || SchedWrite.TheDef == WR->getValueAsDef("WriteType")) { 697 if (ResDef) { 698 PrintFatalError(WR->getLoc(), "Resources are defined for both " 699 "SchedWrite and its alias on processor " + 700 ProcModel.ModelName); 701 } 702 ResDef = WR; 703 } 704 } 705 // TODO: If ProcModel has a base model (previous generation processor), 706 // then call FindWriteResources recursively with that model here. 707 if (!ResDef) { 708 PrintFatalError(ProcModel.ModelDef->getLoc(), 709 Twine("Processor does not define resources for ") + 710 SchedWrite.TheDef->getName()); 711 } 712 return ResDef; 713 } 714 715 /// Find the ReadAdvance record for the given SchedRead on this processor or 716 /// return NULL. 717 Record *SubtargetEmitter::FindReadAdvance(const CodeGenSchedRW &SchedRead, 718 const CodeGenProcModel &ProcModel) { 719 // Check for SchedReads that directly specify a ReadAdvance. 720 if (SchedRead.TheDef->isSubClassOf("SchedReadAdvance")) 721 return SchedRead.TheDef; 722 723 // Check this processor's list of aliases for SchedRead. 724 Record *AliasDef = nullptr; 725 for (Record *A : SchedRead.Aliases) { 726 const CodeGenSchedRW &AliasRW = 727 SchedModels.getSchedRW(A->getValueAsDef("AliasRW")); 728 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) { 729 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel"); 730 if (&SchedModels.getProcModel(ModelDef) != &ProcModel) 731 continue; 732 } 733 if (AliasDef) 734 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases " 735 "defined for processor " + ProcModel.ModelName + 736 " Ensure only one SchedAlias exists per RW."); 737 AliasDef = AliasRW.TheDef; 738 } 739 if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance")) 740 return AliasDef; 741 742 // Check this processor's ReadAdvanceList. 743 Record *ResDef = nullptr; 744 for (Record *RA : ProcModel.ReadAdvanceDefs) { 745 if (!RA->isSubClassOf("ReadAdvance")) 746 continue; 747 if (AliasDef == RA->getValueAsDef("ReadType") 748 || SchedRead.TheDef == RA->getValueAsDef("ReadType")) { 749 if (ResDef) { 750 PrintFatalError(RA->getLoc(), "Resources are defined for both " 751 "SchedRead and its alias on processor " + 752 ProcModel.ModelName); 753 } 754 ResDef = RA; 755 } 756 } 757 // TODO: If ProcModel has a base model (previous generation processor), 758 // then call FindReadAdvance recursively with that model here. 759 if (!ResDef && SchedRead.TheDef->getName() != "ReadDefault") { 760 PrintFatalError(ProcModel.ModelDef->getLoc(), 761 Twine("Processor does not define resources for ") + 762 SchedRead.TheDef->getName()); 763 } 764 return ResDef; 765 } 766 767 // Expand an explicit list of processor resources into a full list of implied 768 // resource groups and super resources that cover them. 769 void SubtargetEmitter::ExpandProcResources(RecVec &PRVec, 770 std::vector<int64_t> &Cycles, 771 const CodeGenProcModel &PM) { 772 // Default to 1 resource cycle. 773 Cycles.resize(PRVec.size(), 1); 774 for (unsigned i = 0, e = PRVec.size(); i != e; ++i) { 775 Record *PRDef = PRVec[i]; 776 RecVec SubResources; 777 if (PRDef->isSubClassOf("ProcResGroup")) 778 SubResources = PRDef->getValueAsListOfDefs("Resources"); 779 else { 780 SubResources.push_back(PRDef); 781 PRDef = SchedModels.findProcResUnits(PRDef, PM, PRDef->getLoc()); 782 for (Record *SubDef = PRDef; 783 SubDef->getValueInit("Super")->isComplete();) { 784 if (SubDef->isSubClassOf("ProcResGroup")) { 785 // Disallow this for simplicitly. 786 PrintFatalError(SubDef->getLoc(), "Processor resource group " 787 " cannot be a super resources."); 788 } 789 Record *SuperDef = 790 SchedModels.findProcResUnits(SubDef->getValueAsDef("Super"), PM, 791 SubDef->getLoc()); 792 PRVec.push_back(SuperDef); 793 Cycles.push_back(Cycles[i]); 794 SubDef = SuperDef; 795 } 796 } 797 for (Record *PR : PM.ProcResourceDefs) { 798 if (PR == PRDef || !PR->isSubClassOf("ProcResGroup")) 799 continue; 800 RecVec SuperResources = PR->getValueAsListOfDefs("Resources"); 801 RecIter SubI = SubResources.begin(), SubE = SubResources.end(); 802 for( ; SubI != SubE; ++SubI) { 803 if (!is_contained(SuperResources, *SubI)) { 804 break; 805 } 806 } 807 if (SubI == SubE) { 808 PRVec.push_back(PR); 809 Cycles.push_back(Cycles[i]); 810 } 811 } 812 } 813 } 814 815 // Generate the SchedClass table for this processor and update global 816 // tables. Must be called for each processor in order. 817 void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel, 818 SchedClassTables &SchedTables) { 819 SchedTables.ProcSchedClasses.resize(SchedTables.ProcSchedClasses.size() + 1); 820 if (!ProcModel.hasInstrSchedModel()) 821 return; 822 823 std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back(); 824 DEBUG(dbgs() << "\n+++ SCHED CLASSES (GenSchedClassTables) +++\n"); 825 for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) { 826 DEBUG(SC.dump(&SchedModels)); 827 828 SCTab.resize(SCTab.size() + 1); 829 MCSchedClassDesc &SCDesc = SCTab.back(); 830 // SCDesc.Name is guarded by NDEBUG 831 SCDesc.NumMicroOps = 0; 832 SCDesc.BeginGroup = false; 833 SCDesc.EndGroup = false; 834 SCDesc.WriteProcResIdx = 0; 835 SCDesc.WriteLatencyIdx = 0; 836 SCDesc.ReadAdvanceIdx = 0; 837 838 // A Variant SchedClass has no resources of its own. 839 bool HasVariants = false; 840 for (const CodeGenSchedTransition &CGT : 841 make_range(SC.Transitions.begin(), SC.Transitions.end())) { 842 if (CGT.ProcIndices[0] == 0 || 843 is_contained(CGT.ProcIndices, ProcModel.Index)) { 844 HasVariants = true; 845 break; 846 } 847 } 848 if (HasVariants) { 849 SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps; 850 continue; 851 } 852 853 // Determine if the SchedClass is actually reachable on this processor. If 854 // not don't try to locate the processor resources, it will fail. 855 // If ProcIndices contains 0, this class applies to all processors. 856 assert(!SC.ProcIndices.empty() && "expect at least one procidx"); 857 if (SC.ProcIndices[0] != 0) { 858 if (!is_contained(SC.ProcIndices, ProcModel.Index)) 859 continue; 860 } 861 IdxVec Writes = SC.Writes; 862 IdxVec Reads = SC.Reads; 863 if (!SC.InstRWs.empty()) { 864 // This class has a default ReadWrite list which can be overridden by 865 // InstRW definitions. 866 Record *RWDef = nullptr; 867 for (Record *RW : SC.InstRWs) { 868 Record *RWModelDef = RW->getValueAsDef("SchedModel"); 869 if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) { 870 RWDef = RW; 871 break; 872 } 873 } 874 if (RWDef) { 875 Writes.clear(); 876 Reads.clear(); 877 SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"), 878 Writes, Reads); 879 } 880 } 881 if (Writes.empty()) { 882 // Check this processor's itinerary class resources. 883 for (Record *I : ProcModel.ItinRWDefs) { 884 RecVec Matched = I->getValueAsListOfDefs("MatchedItinClasses"); 885 if (is_contained(Matched, SC.ItinClassDef)) { 886 SchedModels.findRWs(I->getValueAsListOfDefs("OperandReadWrites"), 887 Writes, Reads); 888 break; 889 } 890 } 891 if (Writes.empty()) { 892 DEBUG(dbgs() << ProcModel.ModelName 893 << " does not have resources for class " << SC.Name << '\n'); 894 } 895 } 896 // Sum resources across all operand writes. 897 std::vector<MCWriteProcResEntry> WriteProcResources; 898 std::vector<MCWriteLatencyEntry> WriteLatencies; 899 std::vector<std::string> WriterNames; 900 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries; 901 for (unsigned W : Writes) { 902 IdxVec WriteSeq; 903 SchedModels.expandRWSeqForProc(W, WriteSeq, /*IsRead=*/false, 904 ProcModel); 905 906 // For each operand, create a latency entry. 907 MCWriteLatencyEntry WLEntry; 908 WLEntry.Cycles = 0; 909 unsigned WriteID = WriteSeq.back(); 910 WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name); 911 // If this Write is not referenced by a ReadAdvance, don't distinguish it 912 // from other WriteLatency entries. 913 if (!SchedModels.hasReadOfWrite( 914 SchedModels.getSchedWrite(WriteID).TheDef)) { 915 WriteID = 0; 916 } 917 WLEntry.WriteResourceID = WriteID; 918 919 for (unsigned WS : WriteSeq) { 920 921 Record *WriteRes = 922 FindWriteResources(SchedModels.getSchedWrite(WS), ProcModel); 923 924 // Mark the parent class as invalid for unsupported write types. 925 if (WriteRes->getValueAsBit("Unsupported")) { 926 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps; 927 break; 928 } 929 WLEntry.Cycles += WriteRes->getValueAsInt("Latency"); 930 SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps"); 931 SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup"); 932 SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup"); 933 SCDesc.BeginGroup |= WriteRes->getValueAsBit("SingleIssue"); 934 SCDesc.EndGroup |= WriteRes->getValueAsBit("SingleIssue"); 935 936 // Create an entry for each ProcResource listed in WriteRes. 937 RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources"); 938 std::vector<int64_t> Cycles = 939 WriteRes->getValueAsListOfInts("ResourceCycles"); 940 941 ExpandProcResources(PRVec, Cycles, ProcModel); 942 943 for (unsigned PRIdx = 0, PREnd = PRVec.size(); 944 PRIdx != PREnd; ++PRIdx) { 945 MCWriteProcResEntry WPREntry; 946 WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]); 947 assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx"); 948 WPREntry.Cycles = Cycles[PRIdx]; 949 // If this resource is already used in this sequence, add the current 950 // entry's cycles so that the same resource appears to be used 951 // serially, rather than multiple parallel uses. This is important for 952 // in-order machine where the resource consumption is a hazard. 953 unsigned WPRIdx = 0, WPREnd = WriteProcResources.size(); 954 for( ; WPRIdx != WPREnd; ++WPRIdx) { 955 if (WriteProcResources[WPRIdx].ProcResourceIdx 956 == WPREntry.ProcResourceIdx) { 957 WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles; 958 break; 959 } 960 } 961 if (WPRIdx == WPREnd) 962 WriteProcResources.push_back(WPREntry); 963 } 964 } 965 WriteLatencies.push_back(WLEntry); 966 } 967 // Create an entry for each operand Read in this SchedClass. 968 // Entries must be sorted first by UseIdx then by WriteResourceID. 969 for (unsigned UseIdx = 0, EndIdx = Reads.size(); 970 UseIdx != EndIdx; ++UseIdx) { 971 Record *ReadAdvance = 972 FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel); 973 if (!ReadAdvance) 974 continue; 975 976 // Mark the parent class as invalid for unsupported write types. 977 if (ReadAdvance->getValueAsBit("Unsupported")) { 978 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps; 979 break; 980 } 981 RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites"); 982 IdxVec WriteIDs; 983 if (ValidWrites.empty()) 984 WriteIDs.push_back(0); 985 else { 986 for (Record *VW : ValidWrites) { 987 WriteIDs.push_back(SchedModels.getSchedRWIdx(VW, /*IsRead=*/false)); 988 } 989 } 990 std::sort(WriteIDs.begin(), WriteIDs.end()); 991 for(unsigned W : WriteIDs) { 992 MCReadAdvanceEntry RAEntry; 993 RAEntry.UseIdx = UseIdx; 994 RAEntry.WriteResourceID = W; 995 RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles"); 996 ReadAdvanceEntries.push_back(RAEntry); 997 } 998 } 999 if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) { 1000 WriteProcResources.clear(); 1001 WriteLatencies.clear(); 1002 ReadAdvanceEntries.clear(); 1003 } 1004 // Add the information for this SchedClass to the global tables using basic 1005 // compression. 1006 // 1007 // WritePrecRes entries are sorted by ProcResIdx. 1008 std::sort(WriteProcResources.begin(), WriteProcResources.end(), 1009 LessWriteProcResources()); 1010 1011 SCDesc.NumWriteProcResEntries = WriteProcResources.size(); 1012 std::vector<MCWriteProcResEntry>::iterator WPRPos = 1013 std::search(SchedTables.WriteProcResources.begin(), 1014 SchedTables.WriteProcResources.end(), 1015 WriteProcResources.begin(), WriteProcResources.end()); 1016 if (WPRPos != SchedTables.WriteProcResources.end()) 1017 SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin(); 1018 else { 1019 SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size(); 1020 SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(), 1021 WriteProcResources.end()); 1022 } 1023 // Latency entries must remain in operand order. 1024 SCDesc.NumWriteLatencyEntries = WriteLatencies.size(); 1025 std::vector<MCWriteLatencyEntry>::iterator WLPos = 1026 std::search(SchedTables.WriteLatencies.begin(), 1027 SchedTables.WriteLatencies.end(), 1028 WriteLatencies.begin(), WriteLatencies.end()); 1029 if (WLPos != SchedTables.WriteLatencies.end()) { 1030 unsigned idx = WLPos - SchedTables.WriteLatencies.begin(); 1031 SCDesc.WriteLatencyIdx = idx; 1032 for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i) 1033 if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) == 1034 std::string::npos) { 1035 SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i]; 1036 } 1037 } 1038 else { 1039 SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size(); 1040 SchedTables.WriteLatencies.insert(SchedTables.WriteLatencies.end(), 1041 WriteLatencies.begin(), 1042 WriteLatencies.end()); 1043 SchedTables.WriterNames.insert(SchedTables.WriterNames.end(), 1044 WriterNames.begin(), WriterNames.end()); 1045 } 1046 // ReadAdvanceEntries must remain in operand order. 1047 SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size(); 1048 std::vector<MCReadAdvanceEntry>::iterator RAPos = 1049 std::search(SchedTables.ReadAdvanceEntries.begin(), 1050 SchedTables.ReadAdvanceEntries.end(), 1051 ReadAdvanceEntries.begin(), ReadAdvanceEntries.end()); 1052 if (RAPos != SchedTables.ReadAdvanceEntries.end()) 1053 SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin(); 1054 else { 1055 SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size(); 1056 SchedTables.ReadAdvanceEntries.insert(RAPos, ReadAdvanceEntries.begin(), 1057 ReadAdvanceEntries.end()); 1058 } 1059 } 1060 } 1061 1062 // Emit SchedClass tables for all processors and associated global tables. 1063 void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables, 1064 raw_ostream &OS) { 1065 // Emit global WriteProcResTable. 1066 OS << "\n// {ProcResourceIdx, Cycles}\n" 1067 << "extern const llvm::MCWriteProcResEntry " 1068 << Target << "WriteProcResTable[] = {\n" 1069 << " { 0, 0}, // Invalid\n"; 1070 for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size(); 1071 WPRIdx != WPREnd; ++WPRIdx) { 1072 MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx]; 1073 OS << " {" << format("%2d", WPREntry.ProcResourceIdx) << ", " 1074 << format("%2d", WPREntry.Cycles) << "}"; 1075 if (WPRIdx + 1 < WPREnd) 1076 OS << ','; 1077 OS << " // #" << WPRIdx << '\n'; 1078 } 1079 OS << "}; // " << Target << "WriteProcResTable\n"; 1080 1081 // Emit global WriteLatencyTable. 1082 OS << "\n// {Cycles, WriteResourceID}\n" 1083 << "extern const llvm::MCWriteLatencyEntry " 1084 << Target << "WriteLatencyTable[] = {\n" 1085 << " { 0, 0}, // Invalid\n"; 1086 for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size(); 1087 WLIdx != WLEnd; ++WLIdx) { 1088 MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx]; 1089 OS << " {" << format("%2d", WLEntry.Cycles) << ", " 1090 << format("%2d", WLEntry.WriteResourceID) << "}"; 1091 if (WLIdx + 1 < WLEnd) 1092 OS << ','; 1093 OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n'; 1094 } 1095 OS << "}; // " << Target << "WriteLatencyTable\n"; 1096 1097 // Emit global ReadAdvanceTable. 1098 OS << "\n// {UseIdx, WriteResourceID, Cycles}\n" 1099 << "extern const llvm::MCReadAdvanceEntry " 1100 << Target << "ReadAdvanceTable[] = {\n" 1101 << " {0, 0, 0}, // Invalid\n"; 1102 for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size(); 1103 RAIdx != RAEnd; ++RAIdx) { 1104 MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx]; 1105 OS << " {" << RAEntry.UseIdx << ", " 1106 << format("%2d", RAEntry.WriteResourceID) << ", " 1107 << format("%2d", RAEntry.Cycles) << "}"; 1108 if (RAIdx + 1 < RAEnd) 1109 OS << ','; 1110 OS << " // #" << RAIdx << '\n'; 1111 } 1112 OS << "}; // " << Target << "ReadAdvanceTable\n"; 1113 1114 // Emit a SchedClass table for each processor. 1115 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(), 1116 PE = SchedModels.procModelEnd(); PI != PE; ++PI) { 1117 if (!PI->hasInstrSchedModel()) 1118 continue; 1119 1120 std::vector<MCSchedClassDesc> &SCTab = 1121 SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())]; 1122 1123 OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup," 1124 << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n"; 1125 OS << "static const llvm::MCSchedClassDesc " 1126 << PI->ModelName << "SchedClasses[] = {\n"; 1127 1128 // The first class is always invalid. We no way to distinguish it except by 1129 // name and position. 1130 assert(SchedModels.getSchedClass(0).Name == "NoInstrModel" 1131 && "invalid class not first"); 1132 OS << " {DBGFIELD(\"InvalidSchedClass\") " 1133 << MCSchedClassDesc::InvalidNumMicroOps 1134 << ", false, false, 0, 0, 0, 0, 0, 0},\n"; 1135 1136 for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) { 1137 MCSchedClassDesc &MCDesc = SCTab[SCIdx]; 1138 const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx); 1139 OS << " {DBGFIELD(\"" << SchedClass.Name << "\") "; 1140 if (SchedClass.Name.size() < 18) 1141 OS.indent(18 - SchedClass.Name.size()); 1142 OS << MCDesc.NumMicroOps 1143 << ", " << ( MCDesc.BeginGroup ? "true" : "false" ) 1144 << ", " << ( MCDesc.EndGroup ? "true" : "false" ) 1145 << ", " << format("%2d", MCDesc.WriteProcResIdx) 1146 << ", " << MCDesc.NumWriteProcResEntries 1147 << ", " << format("%2d", MCDesc.WriteLatencyIdx) 1148 << ", " << MCDesc.NumWriteLatencyEntries 1149 << ", " << format("%2d", MCDesc.ReadAdvanceIdx) 1150 << ", " << MCDesc.NumReadAdvanceEntries 1151 << "}, // #" << SCIdx << '\n'; 1152 } 1153 OS << "}; // " << PI->ModelName << "SchedClasses\n"; 1154 } 1155 } 1156 1157 void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) { 1158 // For each processor model. 1159 for (const CodeGenProcModel &PM : SchedModels.procModels()) { 1160 // Emit processor resource table. 1161 if (PM.hasInstrSchedModel()) 1162 EmitProcessorResources(PM, OS); 1163 else if(!PM.ProcResourceDefs.empty()) 1164 PrintFatalError(PM.ModelDef->getLoc(), "SchedMachineModel defines " 1165 "ProcResources without defining WriteRes SchedWriteRes"); 1166 1167 // Begin processor itinerary properties 1168 OS << "\n"; 1169 OS << "static const llvm::MCSchedModel " << PM.ModelName << " = {\n"; 1170 EmitProcessorProp(OS, PM.ModelDef, "IssueWidth", ','); 1171 EmitProcessorProp(OS, PM.ModelDef, "MicroOpBufferSize", ','); 1172 EmitProcessorProp(OS, PM.ModelDef, "LoopMicroOpBufferSize", ','); 1173 EmitProcessorProp(OS, PM.ModelDef, "LoadLatency", ','); 1174 EmitProcessorProp(OS, PM.ModelDef, "HighLatency", ','); 1175 EmitProcessorProp(OS, PM.ModelDef, "MispredictPenalty", ','); 1176 1177 bool PostRAScheduler = 1178 (PM.ModelDef ? PM.ModelDef->getValueAsBit("PostRAScheduler") : false); 1179 1180 OS << " " << (PostRAScheduler ? "true" : "false") << ", // " 1181 << "PostRAScheduler\n"; 1182 1183 bool CompleteModel = 1184 (PM.ModelDef ? PM.ModelDef->getValueAsBit("CompleteModel") : false); 1185 1186 OS << " " << (CompleteModel ? "true" : "false") << ", // " 1187 << "CompleteModel\n"; 1188 1189 OS << " " << PM.Index << ", // Processor ID\n"; 1190 if (PM.hasInstrSchedModel()) 1191 OS << " " << PM.ModelName << "ProcResources" << ",\n" 1192 << " " << PM.ModelName << "SchedClasses" << ",\n" 1193 << " " << PM.ProcResourceDefs.size()+1 << ",\n" 1194 << " " << (SchedModels.schedClassEnd() 1195 - SchedModels.schedClassBegin()) << ",\n"; 1196 else 1197 OS << " nullptr, nullptr, 0, 0," 1198 << " // No instruction-level machine model.\n"; 1199 if (PM.hasItineraries()) 1200 OS << " " << PM.ItinsDef->getName() << "\n"; 1201 else 1202 OS << " nullptr // No Itinerary\n"; 1203 OS << "};\n"; 1204 } 1205 } 1206 1207 // 1208 // EmitProcessorLookup - generate cpu name to itinerary lookup table. 1209 // 1210 void SubtargetEmitter::EmitProcessorLookup(raw_ostream &OS) { 1211 // Gather and sort processor information 1212 std::vector<Record*> ProcessorList = 1213 Records.getAllDerivedDefinitions("Processor"); 1214 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName()); 1215 1216 // Begin processor table 1217 OS << "\n"; 1218 OS << "// Sorted (by key) array of itineraries for CPU subtype.\n" 1219 << "extern const llvm::SubtargetInfoKV " 1220 << Target << "ProcSchedKV[] = {\n"; 1221 1222 // For each processor 1223 for (Record *Processor : ProcessorList) { 1224 StringRef Name = Processor->getValueAsString("Name"); 1225 const std::string &ProcModelName = 1226 SchedModels.getModelForProc(Processor).ModelName; 1227 1228 // Emit as { "cpu", procinit }, 1229 OS << " { \"" << Name << "\", (const void *)&" << ProcModelName << " },\n"; 1230 } 1231 1232 // End processor table 1233 OS << "};\n"; 1234 } 1235 1236 // 1237 // EmitSchedModel - Emits all scheduling model tables, folding common patterns. 1238 // 1239 void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) { 1240 OS << "#ifdef DBGFIELD\n" 1241 << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n" 1242 << "#endif\n" 1243 << "#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)\n" 1244 << "#define DBGFIELD(x) x,\n" 1245 << "#else\n" 1246 << "#define DBGFIELD(x)\n" 1247 << "#endif\n"; 1248 1249 if (SchedModels.hasItineraries()) { 1250 std::vector<std::vector<InstrItinerary>> ProcItinLists; 1251 // Emit the stage data 1252 EmitStageAndOperandCycleData(OS, ProcItinLists); 1253 EmitItineraries(OS, ProcItinLists); 1254 } 1255 OS << "\n// ===============================================================\n" 1256 << "// Data tables for the new per-operand machine model.\n"; 1257 1258 SchedClassTables SchedTables; 1259 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { 1260 GenSchedClassTables(ProcModel, SchedTables); 1261 } 1262 EmitSchedClassTables(SchedTables, OS); 1263 1264 // Emit the processor machine model 1265 EmitProcessorModels(OS); 1266 // Emit the processor lookup data 1267 EmitProcessorLookup(OS); 1268 1269 OS << "\n#undef DBGFIELD"; 1270 } 1271 1272 void SubtargetEmitter::EmitSchedModelHelpers(const std::string &ClassName, 1273 raw_ostream &OS) { 1274 OS << "unsigned " << ClassName 1275 << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI," 1276 << " const TargetSchedModel *SchedModel) const {\n"; 1277 1278 std::vector<Record*> Prologs = Records.getAllDerivedDefinitions("PredicateProlog"); 1279 std::sort(Prologs.begin(), Prologs.end(), LessRecord()); 1280 for (Record *P : Prologs) { 1281 OS << P->getValueAsString("Code") << '\n'; 1282 } 1283 IdxVec VariantClasses; 1284 for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) { 1285 if (SC.Transitions.empty()) 1286 continue; 1287 VariantClasses.push_back(SC.Index); 1288 } 1289 if (!VariantClasses.empty()) { 1290 OS << " switch (SchedClass) {\n"; 1291 for (unsigned VC : VariantClasses) { 1292 const CodeGenSchedClass &SC = SchedModels.getSchedClass(VC); 1293 OS << " case " << VC << ": // " << SC.Name << '\n'; 1294 IdxVec ProcIndices; 1295 for (const CodeGenSchedTransition &T : SC.Transitions) { 1296 IdxVec PI; 1297 std::set_union(T.ProcIndices.begin(), T.ProcIndices.end(), 1298 ProcIndices.begin(), ProcIndices.end(), 1299 std::back_inserter(PI)); 1300 ProcIndices.swap(PI); 1301 } 1302 for (unsigned PI : ProcIndices) { 1303 OS << " "; 1304 if (PI != 0) 1305 OS << "if (SchedModel->getProcessorID() == " << PI << ") "; 1306 OS << "{ // " << (SchedModels.procModelBegin() + PI)->ModelName 1307 << '\n'; 1308 for (const CodeGenSchedTransition &T : SC.Transitions) { 1309 if (PI != 0 && !std::count(T.ProcIndices.begin(), 1310 T.ProcIndices.end(), PI)) { 1311 continue; 1312 } 1313 OS << " if ("; 1314 for (RecIter RI = T.PredTerm.begin(), RE = T.PredTerm.end(); 1315 RI != RE; ++RI) { 1316 if (RI != T.PredTerm.begin()) 1317 OS << "\n && "; 1318 OS << "(" << (*RI)->getValueAsString("Predicate") << ")"; 1319 } 1320 OS << ")\n" 1321 << " return " << T.ToClassIdx << "; // " 1322 << SchedModels.getSchedClass(T.ToClassIdx).Name << '\n'; 1323 } 1324 OS << " }\n"; 1325 if (PI == 0) 1326 break; 1327 } 1328 if (SC.isInferred()) 1329 OS << " return " << SC.Index << ";\n"; 1330 OS << " break;\n"; 1331 } 1332 OS << " };\n"; 1333 } 1334 OS << " report_fatal_error(\"Expected a variant SchedClass\");\n" 1335 << "} // " << ClassName << "::resolveSchedClass\n"; 1336 } 1337 1338 void SubtargetEmitter::EmitHwModeCheck(const std::string &ClassName, 1339 raw_ostream &OS) { 1340 const CodeGenHwModes &CGH = TGT.getHwModes(); 1341 assert(CGH.getNumModeIds() > 0); 1342 if (CGH.getNumModeIds() == 1) 1343 return; 1344 1345 OS << "unsigned " << ClassName << "::getHwMode() const {\n"; 1346 for (unsigned M = 1, NumModes = CGH.getNumModeIds(); M != NumModes; ++M) { 1347 const HwMode &HM = CGH.getMode(M); 1348 OS << " if (checkFeatures(\"" << HM.Features 1349 << "\")) return " << M << ";\n"; 1350 } 1351 OS << " return 0;\n}\n"; 1352 } 1353 1354 // 1355 // ParseFeaturesFunction - Produces a subtarget specific function for parsing 1356 // the subtarget features string. 1357 // 1358 void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS, 1359 unsigned NumFeatures, 1360 unsigned NumProcs) { 1361 std::vector<Record*> Features = 1362 Records.getAllDerivedDefinitions("SubtargetFeature"); 1363 std::sort(Features.begin(), Features.end(), LessRecord()); 1364 1365 OS << "// ParseSubtargetFeatures - Parses features string setting specified\n" 1366 << "// subtarget options.\n" 1367 << "void llvm::"; 1368 OS << Target; 1369 OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef FS) {\n" 1370 << " DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n" 1371 << " DEBUG(dbgs() << \"\\nCPU:\" << CPU << \"\\n\\n\");\n"; 1372 1373 if (Features.empty()) { 1374 OS << "}\n"; 1375 return; 1376 } 1377 1378 OS << " InitMCProcessorInfo(CPU, FS);\n" 1379 << " const FeatureBitset& Bits = getFeatureBits();\n"; 1380 1381 for (Record *R : Features) { 1382 // Next record 1383 StringRef Instance = R->getName(); 1384 StringRef Value = R->getValueAsString("Value"); 1385 StringRef Attribute = R->getValueAsString("Attribute"); 1386 1387 if (Value=="true" || Value=="false") 1388 OS << " if (Bits[" << Target << "::" 1389 << Instance << "]) " 1390 << Attribute << " = " << Value << ";\n"; 1391 else 1392 OS << " if (Bits[" << Target << "::" 1393 << Instance << "] && " 1394 << Attribute << " < " << Value << ") " 1395 << Attribute << " = " << Value << ";\n"; 1396 } 1397 1398 OS << "}\n"; 1399 } 1400 1401 // 1402 // SubtargetEmitter::run - Main subtarget enumeration emitter. 1403 // 1404 void SubtargetEmitter::run(raw_ostream &OS) { 1405 emitSourceFileHeader("Subtarget Enumeration Source Fragment", OS); 1406 1407 OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n"; 1408 OS << "#undef GET_SUBTARGETINFO_ENUM\n\n"; 1409 1410 OS << "namespace llvm {\n"; 1411 Enumeration(OS); 1412 OS << "} // end namespace llvm\n\n"; 1413 OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n"; 1414 1415 OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n"; 1416 OS << "#undef GET_SUBTARGETINFO_MC_DESC\n\n"; 1417 1418 OS << "namespace llvm {\n"; 1419 #if 0 1420 OS << "namespace {\n"; 1421 #endif 1422 unsigned NumFeatures = FeatureKeyValues(OS); 1423 OS << "\n"; 1424 unsigned NumProcs = CPUKeyValues(OS); 1425 OS << "\n"; 1426 EmitSchedModel(OS); 1427 OS << "\n"; 1428 #if 0 1429 OS << "} // end anonymous namespace\n\n"; 1430 #endif 1431 1432 // MCInstrInfo initialization routine. 1433 OS << "\nstatic inline MCSubtargetInfo *create" << Target 1434 << "MCSubtargetInfoImpl(" 1435 << "const Triple &TT, StringRef CPU, StringRef FS) {\n"; 1436 OS << " return new MCSubtargetInfo(TT, CPU, FS, "; 1437 if (NumFeatures) 1438 OS << Target << "FeatureKV, "; 1439 else 1440 OS << "None, "; 1441 if (NumProcs) 1442 OS << Target << "SubTypeKV, "; 1443 else 1444 OS << "None, "; 1445 OS << '\n'; OS.indent(22); 1446 OS << Target << "ProcSchedKV, " 1447 << Target << "WriteProcResTable, " 1448 << Target << "WriteLatencyTable, " 1449 << Target << "ReadAdvanceTable, "; 1450 OS << '\n'; OS.indent(22); 1451 if (SchedModels.hasItineraries()) { 1452 OS << Target << "Stages, " 1453 << Target << "OperandCycles, " 1454 << Target << "ForwardingPaths"; 1455 } else 1456 OS << "nullptr, nullptr, nullptr"; 1457 OS << ");\n}\n\n"; 1458 1459 OS << "} // end namespace llvm\n\n"; 1460 1461 OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n"; 1462 1463 OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n"; 1464 OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n\n"; 1465 1466 OS << "#include \"llvm/Support/Debug.h\"\n"; 1467 OS << "#include \"llvm/Support/raw_ostream.h\"\n\n"; 1468 ParseFeaturesFunction(OS, NumFeatures, NumProcs); 1469 1470 OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n"; 1471 1472 // Create a TargetSubtargetInfo subclass to hide the MC layer initialization. 1473 OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n"; 1474 OS << "#undef GET_SUBTARGETINFO_HEADER\n\n"; 1475 1476 std::string ClassName = Target + "GenSubtargetInfo"; 1477 OS << "namespace llvm {\n"; 1478 OS << "class DFAPacketizer;\n"; 1479 OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n" 1480 << " explicit " << ClassName << "(const Triple &TT, StringRef CPU, " 1481 << "StringRef FS);\n" 1482 << "public:\n" 1483 << " unsigned resolveSchedClass(unsigned SchedClass, " 1484 << " const MachineInstr *DefMI," 1485 << " const TargetSchedModel *SchedModel) const override;\n" 1486 << " DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)" 1487 << " const;\n"; 1488 if (TGT.getHwModes().getNumModeIds() > 1) 1489 OS << " unsigned getHwMode() const override;\n"; 1490 OS << "};\n" 1491 << "} // end namespace llvm\n\n"; 1492 1493 OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n"; 1494 1495 OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n"; 1496 OS << "#undef GET_SUBTARGETINFO_CTOR\n\n"; 1497 1498 OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n\n"; 1499 OS << "namespace llvm {\n"; 1500 OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n"; 1501 OS << "extern const llvm::SubtargetFeatureKV " << Target << "SubTypeKV[];\n"; 1502 OS << "extern const llvm::SubtargetInfoKV " << Target << "ProcSchedKV[];\n"; 1503 OS << "extern const llvm::MCWriteProcResEntry " 1504 << Target << "WriteProcResTable[];\n"; 1505 OS << "extern const llvm::MCWriteLatencyEntry " 1506 << Target << "WriteLatencyTable[];\n"; 1507 OS << "extern const llvm::MCReadAdvanceEntry " 1508 << Target << "ReadAdvanceTable[];\n"; 1509 1510 if (SchedModels.hasItineraries()) { 1511 OS << "extern const llvm::InstrStage " << Target << "Stages[];\n"; 1512 OS << "extern const unsigned " << Target << "OperandCycles[];\n"; 1513 OS << "extern const unsigned " << Target << "ForwardingPaths[];\n"; 1514 } 1515 1516 OS << ClassName << "::" << ClassName << "(const Triple &TT, StringRef CPU, " 1517 << "StringRef FS)\n" 1518 << " : TargetSubtargetInfo(TT, CPU, FS, "; 1519 if (NumFeatures) 1520 OS << "makeArrayRef(" << Target << "FeatureKV, " << NumFeatures << "), "; 1521 else 1522 OS << "None, "; 1523 if (NumProcs) 1524 OS << "makeArrayRef(" << Target << "SubTypeKV, " << NumProcs << "), "; 1525 else 1526 OS << "None, "; 1527 OS << '\n'; OS.indent(24); 1528 OS << Target << "ProcSchedKV, " 1529 << Target << "WriteProcResTable, " 1530 << Target << "WriteLatencyTable, " 1531 << Target << "ReadAdvanceTable, "; 1532 OS << '\n'; OS.indent(24); 1533 if (SchedModels.hasItineraries()) { 1534 OS << Target << "Stages, " 1535 << Target << "OperandCycles, " 1536 << Target << "ForwardingPaths"; 1537 } else 1538 OS << "nullptr, nullptr, nullptr"; 1539 OS << ") {}\n\n"; 1540 1541 EmitSchedModelHelpers(ClassName, OS); 1542 EmitHwModeCheck(ClassName, OS); 1543 1544 OS << "} // end namespace llvm\n\n"; 1545 1546 OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n"; 1547 } 1548 1549 namespace llvm { 1550 1551 void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) { 1552 CodeGenTarget CGTarget(RK); 1553 SubtargetEmitter(RK, CGTarget).run(OS); 1554 } 1555 1556 } // end namespace llvm 1557