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