1 //===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This tablegen backend emits subtarget enumerations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenTarget.h" 14 #include "CodeGenSchedule.h" 15 #include "PredicateExpander.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, DenseMap<Record *, unsigned> &FeatureMap); 77 unsigned FeatureKeyValues(raw_ostream &OS, 78 const DenseMap<Record *, unsigned> &FeatureMap); 79 unsigned CPUKeyValues(raw_ostream &OS, 80 const DenseMap<Record *, unsigned> &FeatureMap); 81 void FormItineraryStageString(const std::string &Names, 82 Record *ItinData, std::string &ItinString, 83 unsigned &NStages); 84 void FormItineraryOperandCycleString(Record *ItinData, std::string &ItinString, 85 unsigned &NOperandCycles); 86 void FormItineraryBypassString(const std::string &Names, 87 Record *ItinData, 88 std::string &ItinString, unsigned NOperandCycles); 89 void EmitStageAndOperandCycleData(raw_ostream &OS, 90 std::vector<std::vector<InstrItinerary>> 91 &ProcItinLists); 92 void EmitItineraries(raw_ostream &OS, 93 std::vector<std::vector<InstrItinerary>> 94 &ProcItinLists); 95 unsigned EmitRegisterFileTables(const CodeGenProcModel &ProcModel, 96 raw_ostream &OS); 97 void EmitLoadStoreQueueInfo(const CodeGenProcModel &ProcModel, 98 raw_ostream &OS); 99 void EmitExtraProcessorInfo(const CodeGenProcModel &ProcModel, 100 raw_ostream &OS); 101 void EmitProcessorProp(raw_ostream &OS, const Record *R, StringRef Name, 102 char Separator); 103 void EmitProcessorResourceSubUnits(const CodeGenProcModel &ProcModel, 104 raw_ostream &OS); 105 void EmitProcessorResources(const CodeGenProcModel &ProcModel, 106 raw_ostream &OS); 107 Record *FindWriteResources(const CodeGenSchedRW &SchedWrite, 108 const CodeGenProcModel &ProcModel); 109 Record *FindReadAdvance(const CodeGenSchedRW &SchedRead, 110 const CodeGenProcModel &ProcModel); 111 void ExpandProcResources(RecVec &PRVec, std::vector<int64_t> &Cycles, 112 const CodeGenProcModel &ProcModel); 113 void GenSchedClassTables(const CodeGenProcModel &ProcModel, 114 SchedClassTables &SchedTables); 115 void EmitSchedClassTables(SchedClassTables &SchedTables, raw_ostream &OS); 116 void EmitProcessorModels(raw_ostream &OS); 117 void EmitProcessorLookup(raw_ostream &OS); 118 void EmitSchedModelHelpers(const std::string &ClassName, raw_ostream &OS); 119 void emitSchedModelHelpersImpl(raw_ostream &OS, 120 bool OnlyExpandMCInstPredicates = false); 121 void emitGenMCSubtargetInfo(raw_ostream &OS); 122 void EmitMCInstrAnalysisPredicateFunctions(raw_ostream &OS); 123 124 void EmitSchedModel(raw_ostream &OS); 125 void EmitHwModeCheck(const std::string &ClassName, raw_ostream &OS); 126 void ParseFeaturesFunction(raw_ostream &OS, unsigned NumFeatures, 127 unsigned NumProcs); 128 129 public: 130 SubtargetEmitter(RecordKeeper &R, CodeGenTarget &TGT) 131 : TGT(TGT), Records(R), SchedModels(TGT.getSchedModels()), 132 Target(TGT.getName()) {} 133 134 void run(raw_ostream &o); 135 }; 136 137 } // end anonymous namespace 138 139 // 140 // Enumeration - Emit the specified class as an enumeration. 141 // 142 void SubtargetEmitter::Enumeration(raw_ostream &OS, 143 DenseMap<Record *, unsigned> &FeatureMap) { 144 // Get all records of class and sort 145 std::vector<Record*> DefList = 146 Records.getAllDerivedDefinitions("SubtargetFeature"); 147 llvm::sort(DefList, LessRecord()); 148 149 unsigned N = DefList.size(); 150 if (N == 0) 151 return; 152 if (N + 1 > MAX_SUBTARGET_FEATURES) 153 PrintFatalError("Too many subtarget features! Bump MAX_SUBTARGET_FEATURES."); 154 155 OS << "namespace " << Target << " {\n"; 156 157 // Open enumeration. 158 OS << "enum {\n"; 159 160 // For each record 161 for (unsigned i = 0; i < N; ++i) { 162 // Next record 163 Record *Def = DefList[i]; 164 165 // Get and emit name 166 OS << " " << Def->getName() << " = " << i << ",\n"; 167 168 // Save the index for this feature. 169 FeatureMap[Def] = i; 170 } 171 172 OS << " " 173 << "NumSubtargetFeatures = " << N << "\n"; 174 175 // Close enumeration and namespace 176 OS << "};\n"; 177 OS << "} // end namespace " << Target << "\n"; 178 } 179 180 static void printFeatureMask(raw_ostream &OS, RecVec &FeatureList, 181 const DenseMap<Record *, unsigned> &FeatureMap) { 182 std::array<uint64_t, MAX_SUBTARGET_WORDS> Mask = {}; 183 for (unsigned j = 0, M = FeatureList.size(); j < M; ++j) { 184 unsigned Bit = FeatureMap.lookup(FeatureList[j]); 185 Mask[Bit / 64] |= 1ULL << (Bit % 64); 186 } 187 188 OS << "{ { { "; 189 for (unsigned i = 0; i != Mask.size(); ++i) { 190 OS << "0x"; 191 OS.write_hex(Mask[i]); 192 OS << "ULL, "; 193 } 194 OS << "} } }"; 195 } 196 197 // 198 // FeatureKeyValues - Emit data of all the subtarget features. Used by the 199 // command line. 200 // 201 unsigned SubtargetEmitter::FeatureKeyValues( 202 raw_ostream &OS, const DenseMap<Record *, unsigned> &FeatureMap) { 203 // Gather and sort all the features 204 std::vector<Record*> FeatureList = 205 Records.getAllDerivedDefinitions("SubtargetFeature"); 206 207 if (FeatureList.empty()) 208 return 0; 209 210 llvm::sort(FeatureList, LessRecordFieldName()); 211 212 // Begin feature table 213 OS << "// Sorted (by key) array of values for CPU features.\n" 214 << "extern const llvm::SubtargetFeatureKV " << Target 215 << "FeatureKV[] = {\n"; 216 217 // For each feature 218 unsigned NumFeatures = 0; 219 for (unsigned i = 0, N = FeatureList.size(); i < N; ++i) { 220 // Next feature 221 Record *Feature = FeatureList[i]; 222 223 StringRef Name = Feature->getName(); 224 StringRef CommandLineName = Feature->getValueAsString("Name"); 225 StringRef Desc = Feature->getValueAsString("Desc"); 226 227 if (CommandLineName.empty()) continue; 228 229 // Emit as { "feature", "description", { featureEnum }, { i1 , i2 , ... , in } } 230 OS << " { " 231 << "\"" << CommandLineName << "\", " 232 << "\"" << Desc << "\", " 233 << Target << "::" << Name << ", "; 234 235 RecVec ImpliesList = Feature->getValueAsListOfDefs("Implies"); 236 237 printFeatureMask(OS, ImpliesList, FeatureMap); 238 239 OS << " },\n"; 240 ++NumFeatures; 241 } 242 243 // End feature table 244 OS << "};\n"; 245 246 return NumFeatures; 247 } 248 249 // 250 // CPUKeyValues - Emit data of all the subtarget processors. Used by command 251 // line. 252 // 253 unsigned 254 SubtargetEmitter::CPUKeyValues(raw_ostream &OS, 255 const DenseMap<Record *, unsigned> &FeatureMap) { 256 // Gather and sort processor information 257 std::vector<Record*> ProcessorList = 258 Records.getAllDerivedDefinitions("Processor"); 259 llvm::sort(ProcessorList, LessRecordFieldName()); 260 261 // Begin processor table 262 OS << "// Sorted (by key) array of values for CPU subtype.\n" 263 << "extern const llvm::SubtargetSubTypeKV " << Target 264 << "SubTypeKV[] = {\n"; 265 266 // For each processor 267 for (Record *Processor : ProcessorList) { 268 StringRef Name = Processor->getValueAsString("Name"); 269 RecVec FeatureList = Processor->getValueAsListOfDefs("Features"); 270 271 // Emit as { "cpu", "description", 0, { f1 , f2 , ... fn } }, 272 OS << " { " 273 << "\"" << Name << "\", "; 274 275 printFeatureMask(OS, FeatureList, FeatureMap); 276 277 // Emit the scheduler model pointer. 278 const std::string &ProcModelName = 279 SchedModels.getModelForProc(Processor).ModelName; 280 OS << ", &" << ProcModelName << " },\n"; 281 } 282 283 // End processor table 284 OS << "};\n"; 285 286 return ProcessorList.size(); 287 } 288 289 // 290 // FormItineraryStageString - Compose a string containing the stage 291 // data initialization for the specified itinerary. N is the number 292 // of stages. 293 // 294 void SubtargetEmitter::FormItineraryStageString(const std::string &Name, 295 Record *ItinData, 296 std::string &ItinString, 297 unsigned &NStages) { 298 // Get states list 299 RecVec StageList = ItinData->getValueAsListOfDefs("Stages"); 300 301 // For each stage 302 unsigned N = NStages = StageList.size(); 303 for (unsigned i = 0; i < N;) { 304 // Next stage 305 const Record *Stage = StageList[i]; 306 307 // Form string as ,{ cycles, u1 | u2 | ... | un, timeinc, kind } 308 int Cycles = Stage->getValueAsInt("Cycles"); 309 ItinString += " { " + itostr(Cycles) + ", "; 310 311 // Get unit list 312 RecVec UnitList = Stage->getValueAsListOfDefs("Units"); 313 314 // For each unit 315 for (unsigned j = 0, M = UnitList.size(); j < M;) { 316 // Add name and bitwise or 317 ItinString += Name + "FU::" + UnitList[j]->getName().str(); 318 if (++j < M) ItinString += " | "; 319 } 320 321 int TimeInc = Stage->getValueAsInt("TimeInc"); 322 ItinString += ", " + itostr(TimeInc); 323 324 int Kind = Stage->getValueAsInt("Kind"); 325 ItinString += ", (llvm::InstrStage::ReservationKinds)" + itostr(Kind); 326 327 // Close off stage 328 ItinString += " }"; 329 if (++i < N) ItinString += ", "; 330 } 331 } 332 333 // 334 // FormItineraryOperandCycleString - Compose a string containing the 335 // operand cycle initialization for the specified itinerary. N is the 336 // number of operands that has cycles specified. 337 // 338 void SubtargetEmitter::FormItineraryOperandCycleString(Record *ItinData, 339 std::string &ItinString, unsigned &NOperandCycles) { 340 // Get operand cycle list 341 std::vector<int64_t> OperandCycleList = 342 ItinData->getValueAsListOfInts("OperandCycles"); 343 344 // For each operand cycle 345 unsigned N = NOperandCycles = OperandCycleList.size(); 346 for (unsigned i = 0; i < N;) { 347 // Next operand cycle 348 const int OCycle = OperandCycleList[i]; 349 350 ItinString += " " + itostr(OCycle); 351 if (++i < N) ItinString += ", "; 352 } 353 } 354 355 void SubtargetEmitter::FormItineraryBypassString(const std::string &Name, 356 Record *ItinData, 357 std::string &ItinString, 358 unsigned NOperandCycles) { 359 RecVec BypassList = ItinData->getValueAsListOfDefs("Bypasses"); 360 unsigned N = BypassList.size(); 361 unsigned i = 0; 362 for (; i < N;) { 363 ItinString += Name + "Bypass::" + BypassList[i]->getName().str(); 364 if (++i < NOperandCycles) ItinString += ", "; 365 } 366 for (; i < NOperandCycles;) { 367 ItinString += " 0"; 368 if (++i < NOperandCycles) ItinString += ", "; 369 } 370 } 371 372 // 373 // EmitStageAndOperandCycleData - Generate unique itinerary stages and operand 374 // cycle tables. Create a list of InstrItinerary objects (ProcItinLists) indexed 375 // by CodeGenSchedClass::Index. 376 // 377 void SubtargetEmitter:: 378 EmitStageAndOperandCycleData(raw_ostream &OS, 379 std::vector<std::vector<InstrItinerary>> 380 &ProcItinLists) { 381 // Multiple processor models may share an itinerary record. Emit it once. 382 SmallPtrSet<Record*, 8> ItinsDefSet; 383 384 // Emit functional units for all the itineraries. 385 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { 386 387 if (!ItinsDefSet.insert(ProcModel.ItinsDef).second) 388 continue; 389 390 RecVec FUs = ProcModel.ItinsDef->getValueAsListOfDefs("FU"); 391 if (FUs.empty()) 392 continue; 393 394 StringRef Name = ProcModel.ItinsDef->getName(); 395 OS << "\n// Functional units for \"" << Name << "\"\n" 396 << "namespace " << Name << "FU {\n"; 397 398 for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j) 399 OS << " const InstrStage::FuncUnits " << FUs[j]->getName() 400 << " = 1ULL << " << j << ";\n"; 401 402 OS << "} // end namespace " << Name << "FU\n"; 403 404 RecVec BPs = ProcModel.ItinsDef->getValueAsListOfDefs("BP"); 405 if (!BPs.empty()) { 406 OS << "\n// Pipeline forwarding paths for itineraries \"" << Name 407 << "\"\n" << "namespace " << Name << "Bypass {\n"; 408 409 OS << " const unsigned NoBypass = 0;\n"; 410 for (unsigned j = 0, BPN = BPs.size(); j < BPN; ++j) 411 OS << " const unsigned " << BPs[j]->getName() 412 << " = 1 << " << j << ";\n"; 413 414 OS << "} // end namespace " << Name << "Bypass\n"; 415 } 416 } 417 418 // Begin stages table 419 std::string StageTable = "\nextern const llvm::InstrStage " + Target + 420 "Stages[] = {\n"; 421 StageTable += " { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n"; 422 423 // Begin operand cycle table 424 std::string OperandCycleTable = "extern const unsigned " + Target + 425 "OperandCycles[] = {\n"; 426 OperandCycleTable += " 0, // No itinerary\n"; 427 428 // Begin pipeline bypass table 429 std::string BypassTable = "extern const unsigned " + Target + 430 "ForwardingPaths[] = {\n"; 431 BypassTable += " 0, // No itinerary\n"; 432 433 // For each Itinerary across all processors, add a unique entry to the stages, 434 // operand cycles, and pipeline bypass tables. Then add the new Itinerary 435 // object with computed offsets to the ProcItinLists result. 436 unsigned StageCount = 1, OperandCycleCount = 1; 437 std::map<std::string, unsigned> ItinStageMap, ItinOperandMap; 438 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { 439 // Add process itinerary to the list. 440 ProcItinLists.resize(ProcItinLists.size()+1); 441 442 // If this processor defines no itineraries, then leave the itinerary list 443 // empty. 444 std::vector<InstrItinerary> &ItinList = ProcItinLists.back(); 445 if (!ProcModel.hasItineraries()) 446 continue; 447 448 StringRef Name = ProcModel.ItinsDef->getName(); 449 450 ItinList.resize(SchedModels.numInstrSchedClasses()); 451 assert(ProcModel.ItinDefList.size() == ItinList.size() && "bad Itins"); 452 453 for (unsigned SchedClassIdx = 0, SchedClassEnd = ItinList.size(); 454 SchedClassIdx < SchedClassEnd; ++SchedClassIdx) { 455 456 // Next itinerary data 457 Record *ItinData = ProcModel.ItinDefList[SchedClassIdx]; 458 459 // Get string and stage count 460 std::string ItinStageString; 461 unsigned NStages = 0; 462 if (ItinData) 463 FormItineraryStageString(std::string(Name), ItinData, ItinStageString, 464 NStages); 465 466 // Get string and operand cycle count 467 std::string ItinOperandCycleString; 468 unsigned NOperandCycles = 0; 469 std::string ItinBypassString; 470 if (ItinData) { 471 FormItineraryOperandCycleString(ItinData, ItinOperandCycleString, 472 NOperandCycles); 473 474 FormItineraryBypassString(std::string(Name), ItinData, ItinBypassString, 475 NOperandCycles); 476 } 477 478 // Check to see if stage already exists and create if it doesn't 479 uint16_t FindStage = 0; 480 if (NStages > 0) { 481 FindStage = ItinStageMap[ItinStageString]; 482 if (FindStage == 0) { 483 // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // indices 484 StageTable += ItinStageString + ", // " + itostr(StageCount); 485 if (NStages > 1) 486 StageTable += "-" + itostr(StageCount + NStages - 1); 487 StageTable += "\n"; 488 // Record Itin class number. 489 ItinStageMap[ItinStageString] = FindStage = StageCount; 490 StageCount += NStages; 491 } 492 } 493 494 // Check to see if operand cycle already exists and create if it doesn't 495 uint16_t FindOperandCycle = 0; 496 if (NOperandCycles > 0) { 497 std::string ItinOperandString = ItinOperandCycleString+ItinBypassString; 498 FindOperandCycle = ItinOperandMap[ItinOperandString]; 499 if (FindOperandCycle == 0) { 500 // Emit as cycle, // index 501 OperandCycleTable += ItinOperandCycleString + ", // "; 502 std::string OperandIdxComment = itostr(OperandCycleCount); 503 if (NOperandCycles > 1) 504 OperandIdxComment += "-" 505 + itostr(OperandCycleCount + NOperandCycles - 1); 506 OperandCycleTable += OperandIdxComment + "\n"; 507 // Record Itin class number. 508 ItinOperandMap[ItinOperandCycleString] = 509 FindOperandCycle = OperandCycleCount; 510 // Emit as bypass, // index 511 BypassTable += ItinBypassString + ", // " + OperandIdxComment + "\n"; 512 OperandCycleCount += NOperandCycles; 513 } 514 } 515 516 // Set up itinerary as location and location + stage count 517 int16_t NumUOps = ItinData ? ItinData->getValueAsInt("NumMicroOps") : 0; 518 InstrItinerary Intinerary = { 519 NumUOps, 520 FindStage, 521 uint16_t(FindStage + NStages), 522 FindOperandCycle, 523 uint16_t(FindOperandCycle + NOperandCycles), 524 }; 525 526 // Inject - empty slots will be 0, 0 527 ItinList[SchedClassIdx] = Intinerary; 528 } 529 } 530 531 // Closing stage 532 StageTable += " { 0, 0, 0, llvm::InstrStage::Required } // End stages\n"; 533 StageTable += "};\n"; 534 535 // Closing operand cycles 536 OperandCycleTable += " 0 // End operand cycles\n"; 537 OperandCycleTable += "};\n"; 538 539 BypassTable += " 0 // End bypass tables\n"; 540 BypassTable += "};\n"; 541 542 // Emit tables. 543 OS << StageTable; 544 OS << OperandCycleTable; 545 OS << BypassTable; 546 } 547 548 // 549 // EmitProcessorData - Generate data for processor itineraries that were 550 // computed during EmitStageAndOperandCycleData(). ProcItinLists lists all 551 // Itineraries for each processor. The Itinerary lists are indexed on 552 // CodeGenSchedClass::Index. 553 // 554 void SubtargetEmitter:: 555 EmitItineraries(raw_ostream &OS, 556 std::vector<std::vector<InstrItinerary>> &ProcItinLists) { 557 // Multiple processor models may share an itinerary record. Emit it once. 558 SmallPtrSet<Record*, 8> ItinsDefSet; 559 560 // For each processor's machine model 561 std::vector<std::vector<InstrItinerary>>::iterator 562 ProcItinListsIter = ProcItinLists.begin(); 563 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(), 564 PE = SchedModels.procModelEnd(); PI != PE; ++PI, ++ProcItinListsIter) { 565 566 Record *ItinsDef = PI->ItinsDef; 567 if (!ItinsDefSet.insert(ItinsDef).second) 568 continue; 569 570 // Get the itinerary list for the processor. 571 assert(ProcItinListsIter != ProcItinLists.end() && "bad iterator"); 572 std::vector<InstrItinerary> &ItinList = *ProcItinListsIter; 573 574 // Empty itineraries aren't referenced anywhere in the tablegen output 575 // so don't emit them. 576 if (ItinList.empty()) 577 continue; 578 579 OS << "\n"; 580 OS << "static const llvm::InstrItinerary "; 581 582 // Begin processor itinerary table 583 OS << ItinsDef->getName() << "[] = {\n"; 584 585 // For each itinerary class in CodeGenSchedClass::Index order. 586 for (unsigned j = 0, M = ItinList.size(); j < M; ++j) { 587 InstrItinerary &Intinerary = ItinList[j]; 588 589 // Emit Itinerary in the form of 590 // { firstStage, lastStage, firstCycle, lastCycle } // index 591 OS << " { " << 592 Intinerary.NumMicroOps << ", " << 593 Intinerary.FirstStage << ", " << 594 Intinerary.LastStage << ", " << 595 Intinerary.FirstOperandCycle << ", " << 596 Intinerary.LastOperandCycle << " }" << 597 ", // " << j << " " << SchedModels.getSchedClass(j).Name << "\n"; 598 } 599 // End processor itinerary table 600 OS << " { 0, uint16_t(~0U), uint16_t(~0U), uint16_t(~0U), uint16_t(~0U) }" 601 "// end marker\n"; 602 OS << "};\n"; 603 } 604 } 605 606 // Emit either the value defined in the TableGen Record, or the default 607 // value defined in the C++ header. The Record is null if the processor does not 608 // define a model. 609 void SubtargetEmitter::EmitProcessorProp(raw_ostream &OS, const Record *R, 610 StringRef Name, char Separator) { 611 OS << " "; 612 int V = R ? R->getValueAsInt(Name) : -1; 613 if (V >= 0) 614 OS << V << Separator << " // " << Name; 615 else 616 OS << "MCSchedModel::Default" << Name << Separator; 617 OS << '\n'; 618 } 619 620 void SubtargetEmitter::EmitProcessorResourceSubUnits( 621 const CodeGenProcModel &ProcModel, raw_ostream &OS) { 622 OS << "\nstatic const unsigned " << ProcModel.ModelName 623 << "ProcResourceSubUnits[] = {\n" 624 << " 0, // Invalid\n"; 625 626 for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) { 627 Record *PRDef = ProcModel.ProcResourceDefs[i]; 628 if (!PRDef->isSubClassOf("ProcResGroup")) 629 continue; 630 RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources"); 631 for (Record *RUDef : ResUnits) { 632 Record *const RU = 633 SchedModels.findProcResUnits(RUDef, ProcModel, PRDef->getLoc()); 634 for (unsigned J = 0; J < RU->getValueAsInt("NumUnits"); ++J) { 635 OS << " " << ProcModel.getProcResourceIdx(RU) << ", "; 636 } 637 } 638 OS << " // " << PRDef->getName() << "\n"; 639 } 640 OS << "};\n"; 641 } 642 643 static void EmitRetireControlUnitInfo(const CodeGenProcModel &ProcModel, 644 raw_ostream &OS) { 645 int64_t ReorderBufferSize = 0, MaxRetirePerCycle = 0; 646 if (Record *RCU = ProcModel.RetireControlUnit) { 647 ReorderBufferSize = 648 std::max(ReorderBufferSize, RCU->getValueAsInt("ReorderBufferSize")); 649 MaxRetirePerCycle = 650 std::max(MaxRetirePerCycle, RCU->getValueAsInt("MaxRetirePerCycle")); 651 } 652 653 OS << ReorderBufferSize << ", // ReorderBufferSize\n "; 654 OS << MaxRetirePerCycle << ", // MaxRetirePerCycle\n "; 655 } 656 657 static void EmitRegisterFileInfo(const CodeGenProcModel &ProcModel, 658 unsigned NumRegisterFiles, 659 unsigned NumCostEntries, raw_ostream &OS) { 660 if (NumRegisterFiles) 661 OS << ProcModel.ModelName << "RegisterFiles,\n " << (1 + NumRegisterFiles); 662 else 663 OS << "nullptr,\n 0"; 664 665 OS << ", // Number of register files.\n "; 666 if (NumCostEntries) 667 OS << ProcModel.ModelName << "RegisterCosts,\n "; 668 else 669 OS << "nullptr,\n "; 670 OS << NumCostEntries << ", // Number of register cost entries.\n"; 671 } 672 673 unsigned 674 SubtargetEmitter::EmitRegisterFileTables(const CodeGenProcModel &ProcModel, 675 raw_ostream &OS) { 676 if (llvm::all_of(ProcModel.RegisterFiles, [](const CodeGenRegisterFile &RF) { 677 return RF.hasDefaultCosts(); 678 })) 679 return 0; 680 681 // Print the RegisterCost table first. 682 OS << "\n// {RegisterClassID, Register Cost, AllowMoveElimination }\n"; 683 OS << "static const llvm::MCRegisterCostEntry " << ProcModel.ModelName 684 << "RegisterCosts" 685 << "[] = {\n"; 686 687 for (const CodeGenRegisterFile &RF : ProcModel.RegisterFiles) { 688 // Skip register files with a default cost table. 689 if (RF.hasDefaultCosts()) 690 continue; 691 // Add entries to the cost table. 692 for (const CodeGenRegisterCost &RC : RF.Costs) { 693 OS << " { "; 694 Record *Rec = RC.RCDef; 695 if (Rec->getValue("Namespace")) 696 OS << Rec->getValueAsString("Namespace") << "::"; 697 OS << Rec->getName() << "RegClassID, " << RC.Cost << ", " 698 << RC.AllowMoveElimination << "},\n"; 699 } 700 } 701 OS << "};\n"; 702 703 // Now generate a table with register file info. 704 OS << "\n // {Name, #PhysRegs, #CostEntries, IndexToCostTbl, " 705 << "MaxMovesEliminatedPerCycle, AllowZeroMoveEliminationOnly }\n"; 706 OS << "static const llvm::MCRegisterFileDesc " << ProcModel.ModelName 707 << "RegisterFiles" 708 << "[] = {\n" 709 << " { \"InvalidRegisterFile\", 0, 0, 0, 0, 0 },\n"; 710 unsigned CostTblIndex = 0; 711 712 for (const CodeGenRegisterFile &RD : ProcModel.RegisterFiles) { 713 OS << " { "; 714 OS << '"' << RD.Name << '"' << ", " << RD.NumPhysRegs << ", "; 715 unsigned NumCostEntries = RD.Costs.size(); 716 OS << NumCostEntries << ", " << CostTblIndex << ", " 717 << RD.MaxMovesEliminatedPerCycle << ", " 718 << RD.AllowZeroMoveEliminationOnly << "},\n"; 719 CostTblIndex += NumCostEntries; 720 } 721 OS << "};\n"; 722 723 return CostTblIndex; 724 } 725 726 void SubtargetEmitter::EmitLoadStoreQueueInfo(const CodeGenProcModel &ProcModel, 727 raw_ostream &OS) { 728 unsigned QueueID = 0; 729 if (ProcModel.LoadQueue) { 730 const Record *Queue = ProcModel.LoadQueue->getValueAsDef("QueueDescriptor"); 731 QueueID = 732 1 + std::distance(ProcModel.ProcResourceDefs.begin(), 733 std::find(ProcModel.ProcResourceDefs.begin(), 734 ProcModel.ProcResourceDefs.end(), Queue)); 735 } 736 OS << " " << QueueID << ", // Resource Descriptor for the Load Queue\n"; 737 738 QueueID = 0; 739 if (ProcModel.StoreQueue) { 740 const Record *Queue = 741 ProcModel.StoreQueue->getValueAsDef("QueueDescriptor"); 742 QueueID = 743 1 + std::distance(ProcModel.ProcResourceDefs.begin(), 744 std::find(ProcModel.ProcResourceDefs.begin(), 745 ProcModel.ProcResourceDefs.end(), Queue)); 746 } 747 OS << " " << QueueID << ", // Resource Descriptor for the Store Queue\n"; 748 } 749 750 void SubtargetEmitter::EmitExtraProcessorInfo(const CodeGenProcModel &ProcModel, 751 raw_ostream &OS) { 752 // Generate a table of register file descriptors (one entry per each user 753 // defined register file), and a table of register costs. 754 unsigned NumCostEntries = EmitRegisterFileTables(ProcModel, OS); 755 756 // Now generate a table for the extra processor info. 757 OS << "\nstatic const llvm::MCExtraProcessorInfo " << ProcModel.ModelName 758 << "ExtraInfo = {\n "; 759 760 // Add information related to the retire control unit. 761 EmitRetireControlUnitInfo(ProcModel, OS); 762 763 // Add information related to the register files (i.e. where to find register 764 // file descriptors and register costs). 765 EmitRegisterFileInfo(ProcModel, ProcModel.RegisterFiles.size(), 766 NumCostEntries, OS); 767 768 // Add information about load/store queues. 769 EmitLoadStoreQueueInfo(ProcModel, OS); 770 771 OS << "};\n"; 772 } 773 774 void SubtargetEmitter::EmitProcessorResources(const CodeGenProcModel &ProcModel, 775 raw_ostream &OS) { 776 EmitProcessorResourceSubUnits(ProcModel, OS); 777 778 OS << "\n// {Name, NumUnits, SuperIdx, BufferSize, SubUnitsIdxBegin}\n"; 779 OS << "static const llvm::MCProcResourceDesc " << ProcModel.ModelName 780 << "ProcResources" 781 << "[] = {\n" 782 << " {\"InvalidUnit\", 0, 0, 0, 0},\n"; 783 784 unsigned SubUnitsOffset = 1; 785 for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) { 786 Record *PRDef = ProcModel.ProcResourceDefs[i]; 787 788 Record *SuperDef = nullptr; 789 unsigned SuperIdx = 0; 790 unsigned NumUnits = 0; 791 const unsigned SubUnitsBeginOffset = SubUnitsOffset; 792 int BufferSize = PRDef->getValueAsInt("BufferSize"); 793 if (PRDef->isSubClassOf("ProcResGroup")) { 794 RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources"); 795 for (Record *RU : ResUnits) { 796 NumUnits += RU->getValueAsInt("NumUnits"); 797 SubUnitsOffset += RU->getValueAsInt("NumUnits"); 798 } 799 } 800 else { 801 // Find the SuperIdx 802 if (PRDef->getValueInit("Super")->isComplete()) { 803 SuperDef = 804 SchedModels.findProcResUnits(PRDef->getValueAsDef("Super"), 805 ProcModel, PRDef->getLoc()); 806 SuperIdx = ProcModel.getProcResourceIdx(SuperDef); 807 } 808 NumUnits = PRDef->getValueAsInt("NumUnits"); 809 } 810 // Emit the ProcResourceDesc 811 OS << " {\"" << PRDef->getName() << "\", "; 812 if (PRDef->getName().size() < 15) 813 OS.indent(15 - PRDef->getName().size()); 814 OS << NumUnits << ", " << SuperIdx << ", " << BufferSize << ", "; 815 if (SubUnitsBeginOffset != SubUnitsOffset) { 816 OS << ProcModel.ModelName << "ProcResourceSubUnits + " 817 << SubUnitsBeginOffset; 818 } else { 819 OS << "nullptr"; 820 } 821 OS << "}, // #" << i+1; 822 if (SuperDef) 823 OS << ", Super=" << SuperDef->getName(); 824 OS << "\n"; 825 } 826 OS << "};\n"; 827 } 828 829 // Find the WriteRes Record that defines processor resources for this 830 // SchedWrite. 831 Record *SubtargetEmitter::FindWriteResources( 832 const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) { 833 834 // Check if the SchedWrite is already subtarget-specific and directly 835 // specifies a set of processor resources. 836 if (SchedWrite.TheDef->isSubClassOf("SchedWriteRes")) 837 return SchedWrite.TheDef; 838 839 Record *AliasDef = nullptr; 840 for (Record *A : SchedWrite.Aliases) { 841 const CodeGenSchedRW &AliasRW = 842 SchedModels.getSchedRW(A->getValueAsDef("AliasRW")); 843 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) { 844 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel"); 845 if (&SchedModels.getProcModel(ModelDef) != &ProcModel) 846 continue; 847 } 848 if (AliasDef) 849 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases " 850 "defined for processor " + ProcModel.ModelName + 851 " Ensure only one SchedAlias exists per RW."); 852 AliasDef = AliasRW.TheDef; 853 } 854 if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes")) 855 return AliasDef; 856 857 // Check this processor's list of write resources. 858 Record *ResDef = nullptr; 859 for (Record *WR : ProcModel.WriteResDefs) { 860 if (!WR->isSubClassOf("WriteRes")) 861 continue; 862 if (AliasDef == WR->getValueAsDef("WriteType") 863 || SchedWrite.TheDef == WR->getValueAsDef("WriteType")) { 864 if (ResDef) { 865 PrintFatalError(WR->getLoc(), "Resources are defined for both " 866 "SchedWrite and its alias on processor " + 867 ProcModel.ModelName); 868 } 869 ResDef = WR; 870 } 871 } 872 // TODO: If ProcModel has a base model (previous generation processor), 873 // then call FindWriteResources recursively with that model here. 874 if (!ResDef) { 875 PrintFatalError(ProcModel.ModelDef->getLoc(), 876 Twine("Processor does not define resources for ") + 877 SchedWrite.TheDef->getName()); 878 } 879 return ResDef; 880 } 881 882 /// Find the ReadAdvance record for the given SchedRead on this processor or 883 /// return NULL. 884 Record *SubtargetEmitter::FindReadAdvance(const CodeGenSchedRW &SchedRead, 885 const CodeGenProcModel &ProcModel) { 886 // Check for SchedReads that directly specify a ReadAdvance. 887 if (SchedRead.TheDef->isSubClassOf("SchedReadAdvance")) 888 return SchedRead.TheDef; 889 890 // Check this processor's list of aliases for SchedRead. 891 Record *AliasDef = nullptr; 892 for (Record *A : SchedRead.Aliases) { 893 const CodeGenSchedRW &AliasRW = 894 SchedModels.getSchedRW(A->getValueAsDef("AliasRW")); 895 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) { 896 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel"); 897 if (&SchedModels.getProcModel(ModelDef) != &ProcModel) 898 continue; 899 } 900 if (AliasDef) 901 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases " 902 "defined for processor " + ProcModel.ModelName + 903 " Ensure only one SchedAlias exists per RW."); 904 AliasDef = AliasRW.TheDef; 905 } 906 if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance")) 907 return AliasDef; 908 909 // Check this processor's ReadAdvanceList. 910 Record *ResDef = nullptr; 911 for (Record *RA : ProcModel.ReadAdvanceDefs) { 912 if (!RA->isSubClassOf("ReadAdvance")) 913 continue; 914 if (AliasDef == RA->getValueAsDef("ReadType") 915 || SchedRead.TheDef == RA->getValueAsDef("ReadType")) { 916 if (ResDef) { 917 PrintFatalError(RA->getLoc(), "Resources are defined for both " 918 "SchedRead and its alias on processor " + 919 ProcModel.ModelName); 920 } 921 ResDef = RA; 922 } 923 } 924 // TODO: If ProcModel has a base model (previous generation processor), 925 // then call FindReadAdvance recursively with that model here. 926 if (!ResDef && SchedRead.TheDef->getName() != "ReadDefault") { 927 PrintFatalError(ProcModel.ModelDef->getLoc(), 928 Twine("Processor does not define resources for ") + 929 SchedRead.TheDef->getName()); 930 } 931 return ResDef; 932 } 933 934 // Expand an explicit list of processor resources into a full list of implied 935 // resource groups and super resources that cover them. 936 void SubtargetEmitter::ExpandProcResources(RecVec &PRVec, 937 std::vector<int64_t> &Cycles, 938 const CodeGenProcModel &PM) { 939 assert(PRVec.size() == Cycles.size() && "failed precondition"); 940 for (unsigned i = 0, e = PRVec.size(); i != e; ++i) { 941 Record *PRDef = PRVec[i]; 942 RecVec SubResources; 943 if (PRDef->isSubClassOf("ProcResGroup")) 944 SubResources = PRDef->getValueAsListOfDefs("Resources"); 945 else { 946 SubResources.push_back(PRDef); 947 PRDef = SchedModels.findProcResUnits(PRDef, PM, PRDef->getLoc()); 948 for (Record *SubDef = PRDef; 949 SubDef->getValueInit("Super")->isComplete();) { 950 if (SubDef->isSubClassOf("ProcResGroup")) { 951 // Disallow this for simplicitly. 952 PrintFatalError(SubDef->getLoc(), "Processor resource group " 953 " cannot be a super resources."); 954 } 955 Record *SuperDef = 956 SchedModels.findProcResUnits(SubDef->getValueAsDef("Super"), PM, 957 SubDef->getLoc()); 958 PRVec.push_back(SuperDef); 959 Cycles.push_back(Cycles[i]); 960 SubDef = SuperDef; 961 } 962 } 963 for (Record *PR : PM.ProcResourceDefs) { 964 if (PR == PRDef || !PR->isSubClassOf("ProcResGroup")) 965 continue; 966 RecVec SuperResources = PR->getValueAsListOfDefs("Resources"); 967 RecIter SubI = SubResources.begin(), SubE = SubResources.end(); 968 for( ; SubI != SubE; ++SubI) { 969 if (!is_contained(SuperResources, *SubI)) { 970 break; 971 } 972 } 973 if (SubI == SubE) { 974 PRVec.push_back(PR); 975 Cycles.push_back(Cycles[i]); 976 } 977 } 978 } 979 } 980 981 // Generate the SchedClass table for this processor and update global 982 // tables. Must be called for each processor in order. 983 void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel, 984 SchedClassTables &SchedTables) { 985 SchedTables.ProcSchedClasses.resize(SchedTables.ProcSchedClasses.size() + 1); 986 if (!ProcModel.hasInstrSchedModel()) 987 return; 988 989 std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back(); 990 LLVM_DEBUG(dbgs() << "\n+++ SCHED CLASSES (GenSchedClassTables) +++\n"); 991 for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) { 992 LLVM_DEBUG(SC.dump(&SchedModels)); 993 994 SCTab.resize(SCTab.size() + 1); 995 MCSchedClassDesc &SCDesc = SCTab.back(); 996 // SCDesc.Name is guarded by NDEBUG 997 SCDesc.NumMicroOps = 0; 998 SCDesc.BeginGroup = false; 999 SCDesc.EndGroup = false; 1000 SCDesc.WriteProcResIdx = 0; 1001 SCDesc.WriteLatencyIdx = 0; 1002 SCDesc.ReadAdvanceIdx = 0; 1003 1004 // A Variant SchedClass has no resources of its own. 1005 bool HasVariants = false; 1006 for (const CodeGenSchedTransition &CGT : 1007 make_range(SC.Transitions.begin(), SC.Transitions.end())) { 1008 if (CGT.ProcIndices[0] == 0 || 1009 is_contained(CGT.ProcIndices, ProcModel.Index)) { 1010 HasVariants = true; 1011 break; 1012 } 1013 } 1014 if (HasVariants) { 1015 SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps; 1016 continue; 1017 } 1018 1019 // Determine if the SchedClass is actually reachable on this processor. If 1020 // not don't try to locate the processor resources, it will fail. 1021 // If ProcIndices contains 0, this class applies to all processors. 1022 assert(!SC.ProcIndices.empty() && "expect at least one procidx"); 1023 if (SC.ProcIndices[0] != 0) { 1024 if (!is_contained(SC.ProcIndices, ProcModel.Index)) 1025 continue; 1026 } 1027 IdxVec Writes = SC.Writes; 1028 IdxVec Reads = SC.Reads; 1029 if (!SC.InstRWs.empty()) { 1030 // This class has a default ReadWrite list which can be overridden by 1031 // InstRW definitions. 1032 Record *RWDef = nullptr; 1033 for (Record *RW : SC.InstRWs) { 1034 Record *RWModelDef = RW->getValueAsDef("SchedModel"); 1035 if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) { 1036 RWDef = RW; 1037 break; 1038 } 1039 } 1040 if (RWDef) { 1041 Writes.clear(); 1042 Reads.clear(); 1043 SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"), 1044 Writes, Reads); 1045 } 1046 } 1047 if (Writes.empty()) { 1048 // Check this processor's itinerary class resources. 1049 for (Record *I : ProcModel.ItinRWDefs) { 1050 RecVec Matched = I->getValueAsListOfDefs("MatchedItinClasses"); 1051 if (is_contained(Matched, SC.ItinClassDef)) { 1052 SchedModels.findRWs(I->getValueAsListOfDefs("OperandReadWrites"), 1053 Writes, Reads); 1054 break; 1055 } 1056 } 1057 if (Writes.empty()) { 1058 LLVM_DEBUG(dbgs() << ProcModel.ModelName 1059 << " does not have resources for class " << SC.Name 1060 << '\n'); 1061 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps; 1062 } 1063 } 1064 // Sum resources across all operand writes. 1065 std::vector<MCWriteProcResEntry> WriteProcResources; 1066 std::vector<MCWriteLatencyEntry> WriteLatencies; 1067 std::vector<std::string> WriterNames; 1068 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries; 1069 for (unsigned W : Writes) { 1070 IdxVec WriteSeq; 1071 SchedModels.expandRWSeqForProc(W, WriteSeq, /*IsRead=*/false, 1072 ProcModel); 1073 1074 // For each operand, create a latency entry. 1075 MCWriteLatencyEntry WLEntry; 1076 WLEntry.Cycles = 0; 1077 unsigned WriteID = WriteSeq.back(); 1078 WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name); 1079 // If this Write is not referenced by a ReadAdvance, don't distinguish it 1080 // from other WriteLatency entries. 1081 if (!SchedModels.hasReadOfWrite( 1082 SchedModels.getSchedWrite(WriteID).TheDef)) { 1083 WriteID = 0; 1084 } 1085 WLEntry.WriteResourceID = WriteID; 1086 1087 for (unsigned WS : WriteSeq) { 1088 1089 Record *WriteRes = 1090 FindWriteResources(SchedModels.getSchedWrite(WS), ProcModel); 1091 1092 // Mark the parent class as invalid for unsupported write types. 1093 if (WriteRes->getValueAsBit("Unsupported")) { 1094 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps; 1095 break; 1096 } 1097 WLEntry.Cycles += WriteRes->getValueAsInt("Latency"); 1098 SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps"); 1099 SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup"); 1100 SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup"); 1101 SCDesc.BeginGroup |= WriteRes->getValueAsBit("SingleIssue"); 1102 SCDesc.EndGroup |= WriteRes->getValueAsBit("SingleIssue"); 1103 1104 // Create an entry for each ProcResource listed in WriteRes. 1105 RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources"); 1106 std::vector<int64_t> Cycles = 1107 WriteRes->getValueAsListOfInts("ResourceCycles"); 1108 1109 if (Cycles.empty()) { 1110 // If ResourceCycles is not provided, default to one cycle per 1111 // resource. 1112 Cycles.resize(PRVec.size(), 1); 1113 } else if (Cycles.size() != PRVec.size()) { 1114 // If ResourceCycles is provided, check consistency. 1115 PrintFatalError( 1116 WriteRes->getLoc(), 1117 Twine("Inconsistent resource cycles: !size(ResourceCycles) != " 1118 "!size(ProcResources): ") 1119 .concat(Twine(PRVec.size())) 1120 .concat(" vs ") 1121 .concat(Twine(Cycles.size()))); 1122 } 1123 1124 ExpandProcResources(PRVec, Cycles, ProcModel); 1125 1126 for (unsigned PRIdx = 0, PREnd = PRVec.size(); 1127 PRIdx != PREnd; ++PRIdx) { 1128 MCWriteProcResEntry WPREntry; 1129 WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]); 1130 assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx"); 1131 WPREntry.Cycles = Cycles[PRIdx]; 1132 // If this resource is already used in this sequence, add the current 1133 // entry's cycles so that the same resource appears to be used 1134 // serially, rather than multiple parallel uses. This is important for 1135 // in-order machine where the resource consumption is a hazard. 1136 unsigned WPRIdx = 0, WPREnd = WriteProcResources.size(); 1137 for( ; WPRIdx != WPREnd; ++WPRIdx) { 1138 if (WriteProcResources[WPRIdx].ProcResourceIdx 1139 == WPREntry.ProcResourceIdx) { 1140 WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles; 1141 break; 1142 } 1143 } 1144 if (WPRIdx == WPREnd) 1145 WriteProcResources.push_back(WPREntry); 1146 } 1147 } 1148 WriteLatencies.push_back(WLEntry); 1149 } 1150 // Create an entry for each operand Read in this SchedClass. 1151 // Entries must be sorted first by UseIdx then by WriteResourceID. 1152 for (unsigned UseIdx = 0, EndIdx = Reads.size(); 1153 UseIdx != EndIdx; ++UseIdx) { 1154 Record *ReadAdvance = 1155 FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel); 1156 if (!ReadAdvance) 1157 continue; 1158 1159 // Mark the parent class as invalid for unsupported write types. 1160 if (ReadAdvance->getValueAsBit("Unsupported")) { 1161 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps; 1162 break; 1163 } 1164 RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites"); 1165 IdxVec WriteIDs; 1166 if (ValidWrites.empty()) 1167 WriteIDs.push_back(0); 1168 else { 1169 for (Record *VW : ValidWrites) { 1170 WriteIDs.push_back(SchedModels.getSchedRWIdx(VW, /*IsRead=*/false)); 1171 } 1172 } 1173 llvm::sort(WriteIDs); 1174 for(unsigned W : WriteIDs) { 1175 MCReadAdvanceEntry RAEntry; 1176 RAEntry.UseIdx = UseIdx; 1177 RAEntry.WriteResourceID = W; 1178 RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles"); 1179 ReadAdvanceEntries.push_back(RAEntry); 1180 } 1181 } 1182 if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) { 1183 WriteProcResources.clear(); 1184 WriteLatencies.clear(); 1185 ReadAdvanceEntries.clear(); 1186 } 1187 // Add the information for this SchedClass to the global tables using basic 1188 // compression. 1189 // 1190 // WritePrecRes entries are sorted by ProcResIdx. 1191 llvm::sort(WriteProcResources, LessWriteProcResources()); 1192 1193 SCDesc.NumWriteProcResEntries = WriteProcResources.size(); 1194 std::vector<MCWriteProcResEntry>::iterator WPRPos = 1195 std::search(SchedTables.WriteProcResources.begin(), 1196 SchedTables.WriteProcResources.end(), 1197 WriteProcResources.begin(), WriteProcResources.end()); 1198 if (WPRPos != SchedTables.WriteProcResources.end()) 1199 SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin(); 1200 else { 1201 SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size(); 1202 SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(), 1203 WriteProcResources.end()); 1204 } 1205 // Latency entries must remain in operand order. 1206 SCDesc.NumWriteLatencyEntries = WriteLatencies.size(); 1207 std::vector<MCWriteLatencyEntry>::iterator WLPos = 1208 std::search(SchedTables.WriteLatencies.begin(), 1209 SchedTables.WriteLatencies.end(), 1210 WriteLatencies.begin(), WriteLatencies.end()); 1211 if (WLPos != SchedTables.WriteLatencies.end()) { 1212 unsigned idx = WLPos - SchedTables.WriteLatencies.begin(); 1213 SCDesc.WriteLatencyIdx = idx; 1214 for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i) 1215 if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) == 1216 std::string::npos) { 1217 SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i]; 1218 } 1219 } 1220 else { 1221 SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size(); 1222 SchedTables.WriteLatencies.insert(SchedTables.WriteLatencies.end(), 1223 WriteLatencies.begin(), 1224 WriteLatencies.end()); 1225 SchedTables.WriterNames.insert(SchedTables.WriterNames.end(), 1226 WriterNames.begin(), WriterNames.end()); 1227 } 1228 // ReadAdvanceEntries must remain in operand order. 1229 SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size(); 1230 std::vector<MCReadAdvanceEntry>::iterator RAPos = 1231 std::search(SchedTables.ReadAdvanceEntries.begin(), 1232 SchedTables.ReadAdvanceEntries.end(), 1233 ReadAdvanceEntries.begin(), ReadAdvanceEntries.end()); 1234 if (RAPos != SchedTables.ReadAdvanceEntries.end()) 1235 SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin(); 1236 else { 1237 SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size(); 1238 SchedTables.ReadAdvanceEntries.insert(RAPos, ReadAdvanceEntries.begin(), 1239 ReadAdvanceEntries.end()); 1240 } 1241 } 1242 } 1243 1244 // Emit SchedClass tables for all processors and associated global tables. 1245 void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables, 1246 raw_ostream &OS) { 1247 // Emit global WriteProcResTable. 1248 OS << "\n// {ProcResourceIdx, Cycles}\n" 1249 << "extern const llvm::MCWriteProcResEntry " 1250 << Target << "WriteProcResTable[] = {\n" 1251 << " { 0, 0}, // Invalid\n"; 1252 for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size(); 1253 WPRIdx != WPREnd; ++WPRIdx) { 1254 MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx]; 1255 OS << " {" << format("%2d", WPREntry.ProcResourceIdx) << ", " 1256 << format("%2d", WPREntry.Cycles) << "}"; 1257 if (WPRIdx + 1 < WPREnd) 1258 OS << ','; 1259 OS << " // #" << WPRIdx << '\n'; 1260 } 1261 OS << "}; // " << Target << "WriteProcResTable\n"; 1262 1263 // Emit global WriteLatencyTable. 1264 OS << "\n// {Cycles, WriteResourceID}\n" 1265 << "extern const llvm::MCWriteLatencyEntry " 1266 << Target << "WriteLatencyTable[] = {\n" 1267 << " { 0, 0}, // Invalid\n"; 1268 for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size(); 1269 WLIdx != WLEnd; ++WLIdx) { 1270 MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx]; 1271 OS << " {" << format("%2d", WLEntry.Cycles) << ", " 1272 << format("%2d", WLEntry.WriteResourceID) << "}"; 1273 if (WLIdx + 1 < WLEnd) 1274 OS << ','; 1275 OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n'; 1276 } 1277 OS << "}; // " << Target << "WriteLatencyTable\n"; 1278 1279 // Emit global ReadAdvanceTable. 1280 OS << "\n// {UseIdx, WriteResourceID, Cycles}\n" 1281 << "extern const llvm::MCReadAdvanceEntry " 1282 << Target << "ReadAdvanceTable[] = {\n" 1283 << " {0, 0, 0}, // Invalid\n"; 1284 for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size(); 1285 RAIdx != RAEnd; ++RAIdx) { 1286 MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx]; 1287 OS << " {" << RAEntry.UseIdx << ", " 1288 << format("%2d", RAEntry.WriteResourceID) << ", " 1289 << format("%2d", RAEntry.Cycles) << "}"; 1290 if (RAIdx + 1 < RAEnd) 1291 OS << ','; 1292 OS << " // #" << RAIdx << '\n'; 1293 } 1294 OS << "}; // " << Target << "ReadAdvanceTable\n"; 1295 1296 // Emit a SchedClass table for each processor. 1297 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(), 1298 PE = SchedModels.procModelEnd(); PI != PE; ++PI) { 1299 if (!PI->hasInstrSchedModel()) 1300 continue; 1301 1302 std::vector<MCSchedClassDesc> &SCTab = 1303 SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())]; 1304 1305 OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup," 1306 << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n"; 1307 OS << "static const llvm::MCSchedClassDesc " 1308 << PI->ModelName << "SchedClasses[] = {\n"; 1309 1310 // The first class is always invalid. We no way to distinguish it except by 1311 // name and position. 1312 assert(SchedModels.getSchedClass(0).Name == "NoInstrModel" 1313 && "invalid class not first"); 1314 OS << " {DBGFIELD(\"InvalidSchedClass\") " 1315 << MCSchedClassDesc::InvalidNumMicroOps 1316 << ", false, false, 0, 0, 0, 0, 0, 0},\n"; 1317 1318 for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) { 1319 MCSchedClassDesc &MCDesc = SCTab[SCIdx]; 1320 const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx); 1321 OS << " {DBGFIELD(\"" << SchedClass.Name << "\") "; 1322 if (SchedClass.Name.size() < 18) 1323 OS.indent(18 - SchedClass.Name.size()); 1324 OS << MCDesc.NumMicroOps 1325 << ", " << ( MCDesc.BeginGroup ? "true" : "false" ) 1326 << ", " << ( MCDesc.EndGroup ? "true" : "false" ) 1327 << ", " << format("%2d", MCDesc.WriteProcResIdx) 1328 << ", " << MCDesc.NumWriteProcResEntries 1329 << ", " << format("%2d", MCDesc.WriteLatencyIdx) 1330 << ", " << MCDesc.NumWriteLatencyEntries 1331 << ", " << format("%2d", MCDesc.ReadAdvanceIdx) 1332 << ", " << MCDesc.NumReadAdvanceEntries 1333 << "}, // #" << SCIdx << '\n'; 1334 } 1335 OS << "}; // " << PI->ModelName << "SchedClasses\n"; 1336 } 1337 } 1338 1339 void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) { 1340 // For each processor model. 1341 for (const CodeGenProcModel &PM : SchedModels.procModels()) { 1342 // Emit extra processor info if available. 1343 if (PM.hasExtraProcessorInfo()) 1344 EmitExtraProcessorInfo(PM, OS); 1345 // Emit processor resource table. 1346 if (PM.hasInstrSchedModel()) 1347 EmitProcessorResources(PM, OS); 1348 else if(!PM.ProcResourceDefs.empty()) 1349 PrintFatalError(PM.ModelDef->getLoc(), "SchedMachineModel defines " 1350 "ProcResources without defining WriteRes SchedWriteRes"); 1351 1352 // Begin processor itinerary properties 1353 OS << "\n"; 1354 OS << "static const llvm::MCSchedModel " << PM.ModelName << " = {\n"; 1355 EmitProcessorProp(OS, PM.ModelDef, "IssueWidth", ','); 1356 EmitProcessorProp(OS, PM.ModelDef, "MicroOpBufferSize", ','); 1357 EmitProcessorProp(OS, PM.ModelDef, "LoopMicroOpBufferSize", ','); 1358 EmitProcessorProp(OS, PM.ModelDef, "LoadLatency", ','); 1359 EmitProcessorProp(OS, PM.ModelDef, "HighLatency", ','); 1360 EmitProcessorProp(OS, PM.ModelDef, "MispredictPenalty", ','); 1361 1362 bool PostRAScheduler = 1363 (PM.ModelDef ? PM.ModelDef->getValueAsBit("PostRAScheduler") : false); 1364 1365 OS << " " << (PostRAScheduler ? "true" : "false") << ", // " 1366 << "PostRAScheduler\n"; 1367 1368 bool CompleteModel = 1369 (PM.ModelDef ? PM.ModelDef->getValueAsBit("CompleteModel") : false); 1370 1371 OS << " " << (CompleteModel ? "true" : "false") << ", // " 1372 << "CompleteModel\n"; 1373 1374 OS << " " << PM.Index << ", // Processor ID\n"; 1375 if (PM.hasInstrSchedModel()) 1376 OS << " " << PM.ModelName << "ProcResources" << ",\n" 1377 << " " << PM.ModelName << "SchedClasses" << ",\n" 1378 << " " << PM.ProcResourceDefs.size()+1 << ",\n" 1379 << " " << (SchedModels.schedClassEnd() 1380 - SchedModels.schedClassBegin()) << ",\n"; 1381 else 1382 OS << " nullptr, nullptr, 0, 0," 1383 << " // No instruction-level machine model.\n"; 1384 if (PM.hasItineraries()) 1385 OS << " " << PM.ItinsDef->getName() << ",\n"; 1386 else 1387 OS << " nullptr, // No Itinerary\n"; 1388 if (PM.hasExtraProcessorInfo()) 1389 OS << " &" << PM.ModelName << "ExtraInfo,\n"; 1390 else 1391 OS << " nullptr // No extra processor descriptor\n"; 1392 OS << "};\n"; 1393 } 1394 } 1395 1396 // 1397 // EmitSchedModel - Emits all scheduling model tables, folding common patterns. 1398 // 1399 void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) { 1400 OS << "#ifdef DBGFIELD\n" 1401 << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n" 1402 << "#endif\n" 1403 << "#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)\n" 1404 << "#define DBGFIELD(x) x,\n" 1405 << "#else\n" 1406 << "#define DBGFIELD(x)\n" 1407 << "#endif\n"; 1408 1409 if (SchedModels.hasItineraries()) { 1410 std::vector<std::vector<InstrItinerary>> ProcItinLists; 1411 // Emit the stage data 1412 EmitStageAndOperandCycleData(OS, ProcItinLists); 1413 EmitItineraries(OS, ProcItinLists); 1414 } 1415 OS << "\n// ===============================================================\n" 1416 << "// Data tables for the new per-operand machine model.\n"; 1417 1418 SchedClassTables SchedTables; 1419 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { 1420 GenSchedClassTables(ProcModel, SchedTables); 1421 } 1422 EmitSchedClassTables(SchedTables, OS); 1423 1424 OS << "\n#undef DBGFIELD\n"; 1425 1426 // Emit the processor machine model 1427 EmitProcessorModels(OS); 1428 } 1429 1430 static void emitPredicateProlog(const RecordKeeper &Records, raw_ostream &OS) { 1431 std::string Buffer; 1432 raw_string_ostream Stream(Buffer); 1433 1434 // Collect all the PredicateProlog records and print them to the output 1435 // stream. 1436 std::vector<Record *> Prologs = 1437 Records.getAllDerivedDefinitions("PredicateProlog"); 1438 llvm::sort(Prologs, LessRecord()); 1439 for (Record *P : Prologs) 1440 Stream << P->getValueAsString("Code") << '\n'; 1441 1442 Stream.flush(); 1443 OS << Buffer; 1444 } 1445 1446 static void emitPredicates(const CodeGenSchedTransition &T, 1447 const CodeGenSchedClass &SC, PredicateExpander &PE, 1448 raw_ostream &OS) { 1449 std::string Buffer; 1450 raw_string_ostream SS(Buffer); 1451 1452 auto IsTruePredicate = [](const Record *Rec) { 1453 return Rec->isSubClassOf("MCSchedPredicate") && 1454 Rec->getValueAsDef("Pred")->isSubClassOf("MCTrue"); 1455 }; 1456 1457 // If not all predicates are MCTrue, then we need an if-stmt. 1458 unsigned NumNonTruePreds = 1459 T.PredTerm.size() - count_if(T.PredTerm, IsTruePredicate); 1460 1461 SS.indent(PE.getIndentLevel() * 2); 1462 1463 if (NumNonTruePreds) { 1464 bool FirstNonTruePredicate = true; 1465 SS << "if ("; 1466 1467 PE.setIndentLevel(PE.getIndentLevel() + 2); 1468 1469 for (const Record *Rec : T.PredTerm) { 1470 // Skip predicates that evaluate to "true". 1471 if (IsTruePredicate(Rec)) 1472 continue; 1473 1474 if (FirstNonTruePredicate) { 1475 FirstNonTruePredicate = false; 1476 } else { 1477 SS << "\n"; 1478 SS.indent(PE.getIndentLevel() * 2); 1479 SS << "&& "; 1480 } 1481 1482 if (Rec->isSubClassOf("MCSchedPredicate")) { 1483 PE.expandPredicate(SS, Rec->getValueAsDef("Pred")); 1484 continue; 1485 } 1486 1487 // Expand this legacy predicate and wrap it around braces if there is more 1488 // than one predicate to expand. 1489 SS << ((NumNonTruePreds > 1) ? "(" : "") 1490 << Rec->getValueAsString("Predicate") 1491 << ((NumNonTruePreds > 1) ? ")" : ""); 1492 } 1493 1494 SS << ")\n"; // end of if-stmt 1495 PE.decreaseIndentLevel(); 1496 SS.indent(PE.getIndentLevel() * 2); 1497 PE.decreaseIndentLevel(); 1498 } 1499 1500 SS << "return " << T.ToClassIdx << "; // " << SC.Name << '\n'; 1501 SS.flush(); 1502 OS << Buffer; 1503 } 1504 1505 // Used by method `SubtargetEmitter::emitSchedModelHelpersImpl()` to generate 1506 // epilogue code for the auto-generated helper. 1507 void emitSchedModelHelperEpilogue(raw_ostream &OS, bool ShouldReturnZero) { 1508 if (ShouldReturnZero) { 1509 OS << " // Don't know how to resolve this scheduling class.\n" 1510 << " return 0;\n"; 1511 return; 1512 } 1513 1514 OS << " report_fatal_error(\"Expected a variant SchedClass\");\n"; 1515 } 1516 1517 bool hasMCSchedPredicates(const CodeGenSchedTransition &T) { 1518 return all_of(T.PredTerm, [](const Record *Rec) { 1519 return Rec->isSubClassOf("MCSchedPredicate"); 1520 }); 1521 } 1522 1523 void collectVariantClasses(const CodeGenSchedModels &SchedModels, 1524 IdxVec &VariantClasses, 1525 bool OnlyExpandMCInstPredicates) { 1526 for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) { 1527 // Ignore non-variant scheduling classes. 1528 if (SC.Transitions.empty()) 1529 continue; 1530 1531 if (OnlyExpandMCInstPredicates) { 1532 // Ignore this variant scheduling class no transitions use any meaningful 1533 // MCSchedPredicate definitions. 1534 if (!any_of(SC.Transitions, [](const CodeGenSchedTransition &T) { 1535 return hasMCSchedPredicates(T); 1536 })) 1537 continue; 1538 } 1539 1540 VariantClasses.push_back(SC.Index); 1541 } 1542 } 1543 1544 void collectProcessorIndices(const CodeGenSchedClass &SC, IdxVec &ProcIndices) { 1545 // A variant scheduling class may define transitions for multiple 1546 // processors. This function identifies wich processors are associated with 1547 // transition rules specified by variant class `SC`. 1548 for (const CodeGenSchedTransition &T : SC.Transitions) { 1549 IdxVec PI; 1550 std::set_union(T.ProcIndices.begin(), T.ProcIndices.end(), 1551 ProcIndices.begin(), ProcIndices.end(), 1552 std::back_inserter(PI)); 1553 ProcIndices.swap(PI); 1554 } 1555 } 1556 1557 void SubtargetEmitter::emitSchedModelHelpersImpl( 1558 raw_ostream &OS, bool OnlyExpandMCInstPredicates) { 1559 IdxVec VariantClasses; 1560 collectVariantClasses(SchedModels, VariantClasses, 1561 OnlyExpandMCInstPredicates); 1562 1563 if (VariantClasses.empty()) { 1564 emitSchedModelHelperEpilogue(OS, OnlyExpandMCInstPredicates); 1565 return; 1566 } 1567 1568 // Construct a switch statement where the condition is a check on the 1569 // scheduling class identifier. There is a `case` for every variant class 1570 // defined by the processor models of this target. 1571 // Each `case` implements a number of rules to resolve (i.e. to transition from) 1572 // a variant scheduling class to another scheduling class. Rules are 1573 // described by instances of CodeGenSchedTransition. Note that transitions may 1574 // not be valid for all processors. 1575 OS << " switch (SchedClass) {\n"; 1576 for (unsigned VC : VariantClasses) { 1577 IdxVec ProcIndices; 1578 const CodeGenSchedClass &SC = SchedModels.getSchedClass(VC); 1579 collectProcessorIndices(SC, ProcIndices); 1580 1581 OS << " case " << VC << ": // " << SC.Name << '\n'; 1582 1583 PredicateExpander PE(Target); 1584 PE.setByRef(false); 1585 PE.setExpandForMC(OnlyExpandMCInstPredicates); 1586 for (unsigned PI : ProcIndices) { 1587 OS << " "; 1588 1589 // Emit a guard on the processor ID. 1590 if (PI != 0) { 1591 OS << (OnlyExpandMCInstPredicates 1592 ? "if (CPUID == " 1593 : "if (SchedModel->getProcessorID() == "); 1594 OS << PI << ") "; 1595 OS << "{ // " << (SchedModels.procModelBegin() + PI)->ModelName << '\n'; 1596 } 1597 1598 // Now emit transitions associated with processor PI. 1599 for (const CodeGenSchedTransition &T : SC.Transitions) { 1600 if (PI != 0 && !count(T.ProcIndices, PI)) 1601 continue; 1602 1603 // Emit only transitions based on MCSchedPredicate, if it's the case. 1604 // At least the transition specified by NoSchedPred is emitted, 1605 // which becomes the default transition for those variants otherwise 1606 // not based on MCSchedPredicate. 1607 // FIXME: preferably, llvm-mca should instead assume a reasonable 1608 // default when a variant transition is not based on MCSchedPredicate 1609 // for a given processor. 1610 if (OnlyExpandMCInstPredicates && !hasMCSchedPredicates(T)) 1611 continue; 1612 1613 PE.setIndentLevel(3); 1614 emitPredicates(T, SchedModels.getSchedClass(T.ToClassIdx), PE, OS); 1615 } 1616 1617 OS << " }\n"; 1618 1619 if (PI == 0) 1620 break; 1621 } 1622 1623 if (SC.isInferred()) 1624 OS << " return " << SC.Index << ";\n"; 1625 OS << " break;\n"; 1626 } 1627 1628 OS << " };\n"; 1629 1630 emitSchedModelHelperEpilogue(OS, OnlyExpandMCInstPredicates); 1631 } 1632 1633 void SubtargetEmitter::EmitSchedModelHelpers(const std::string &ClassName, 1634 raw_ostream &OS) { 1635 OS << "unsigned " << ClassName 1636 << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI," 1637 << " const TargetSchedModel *SchedModel) const {\n"; 1638 1639 // Emit the predicate prolog code. 1640 emitPredicateProlog(Records, OS); 1641 1642 // Emit target predicates. 1643 emitSchedModelHelpersImpl(OS); 1644 1645 OS << "} // " << ClassName << "::resolveSchedClass\n\n"; 1646 1647 OS << "unsigned " << ClassName 1648 << "\n::resolveVariantSchedClass(unsigned SchedClass, const MCInst *MI," 1649 << " unsigned CPUID) const {\n" 1650 << " return " << Target << "_MC" 1651 << "::resolveVariantSchedClassImpl(SchedClass, MI, CPUID);\n" 1652 << "} // " << ClassName << "::resolveVariantSchedClass\n\n"; 1653 1654 STIPredicateExpander PE(Target); 1655 PE.setClassPrefix(ClassName); 1656 PE.setExpandDefinition(true); 1657 PE.setByRef(false); 1658 PE.setIndentLevel(0); 1659 1660 for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates()) 1661 PE.expandSTIPredicate(OS, Fn); 1662 } 1663 1664 void SubtargetEmitter::EmitHwModeCheck(const std::string &ClassName, 1665 raw_ostream &OS) { 1666 const CodeGenHwModes &CGH = TGT.getHwModes(); 1667 assert(CGH.getNumModeIds() > 0); 1668 if (CGH.getNumModeIds() == 1) 1669 return; 1670 1671 OS << "unsigned " << ClassName << "::getHwMode() const {\n"; 1672 for (unsigned M = 1, NumModes = CGH.getNumModeIds(); M != NumModes; ++M) { 1673 const HwMode &HM = CGH.getMode(M); 1674 OS << " if (checkFeatures(\"" << HM.Features 1675 << "\")) return " << M << ";\n"; 1676 } 1677 OS << " return 0;\n}\n"; 1678 } 1679 1680 // 1681 // ParseFeaturesFunction - Produces a subtarget specific function for parsing 1682 // the subtarget features string. 1683 // 1684 void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS, 1685 unsigned NumFeatures, 1686 unsigned NumProcs) { 1687 std::vector<Record*> Features = 1688 Records.getAllDerivedDefinitions("SubtargetFeature"); 1689 llvm::sort(Features, LessRecord()); 1690 1691 OS << "// ParseSubtargetFeatures - Parses features string setting specified\n" 1692 << "// subtarget options.\n" 1693 << "void llvm::"; 1694 OS << Target; 1695 OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef FS) {\n" 1696 << " LLVM_DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n" 1697 << " LLVM_DEBUG(dbgs() << \"\\nCPU:\" << CPU << \"\\n\\n\");\n"; 1698 1699 if (Features.empty()) { 1700 OS << "}\n"; 1701 return; 1702 } 1703 1704 OS << " InitMCProcessorInfo(CPU, FS);\n" 1705 << " const FeatureBitset& Bits = getFeatureBits();\n"; 1706 1707 for (Record *R : Features) { 1708 // Next record 1709 StringRef Instance = R->getName(); 1710 StringRef Value = R->getValueAsString("Value"); 1711 StringRef Attribute = R->getValueAsString("Attribute"); 1712 1713 if (Value=="true" || Value=="false") 1714 OS << " if (Bits[" << Target << "::" 1715 << Instance << "]) " 1716 << Attribute << " = " << Value << ";\n"; 1717 else 1718 OS << " if (Bits[" << Target << "::" 1719 << Instance << "] && " 1720 << Attribute << " < " << Value << ") " 1721 << Attribute << " = " << Value << ";\n"; 1722 } 1723 1724 OS << "}\n"; 1725 } 1726 1727 void SubtargetEmitter::emitGenMCSubtargetInfo(raw_ostream &OS) { 1728 OS << "namespace " << Target << "_MC {\n" 1729 << "unsigned resolveVariantSchedClassImpl(unsigned SchedClass,\n" 1730 << " const MCInst *MI, unsigned CPUID) {\n"; 1731 emitSchedModelHelpersImpl(OS, /* OnlyExpandMCPredicates */ true); 1732 OS << "}\n"; 1733 OS << "} // end namespace " << Target << "_MC\n\n"; 1734 1735 OS << "struct " << Target 1736 << "GenMCSubtargetInfo : public MCSubtargetInfo {\n"; 1737 OS << " " << Target << "GenMCSubtargetInfo(const Triple &TT, \n" 1738 << " StringRef CPU, StringRef FS, ArrayRef<SubtargetFeatureKV> PF,\n" 1739 << " ArrayRef<SubtargetSubTypeKV> PD,\n" 1740 << " const MCWriteProcResEntry *WPR,\n" 1741 << " const MCWriteLatencyEntry *WL,\n" 1742 << " const MCReadAdvanceEntry *RA, const InstrStage *IS,\n" 1743 << " const unsigned *OC, const unsigned *FP) :\n" 1744 << " MCSubtargetInfo(TT, CPU, FS, PF, PD,\n" 1745 << " WPR, WL, RA, IS, OC, FP) { }\n\n" 1746 << " unsigned resolveVariantSchedClass(unsigned SchedClass,\n" 1747 << " const MCInst *MI, unsigned CPUID) const override {\n" 1748 << " return " << Target << "_MC" 1749 << "::resolveVariantSchedClassImpl(SchedClass, MI, CPUID); \n"; 1750 OS << " }\n"; 1751 if (TGT.getHwModes().getNumModeIds() > 1) 1752 OS << " unsigned getHwMode() const override;\n"; 1753 OS << "};\n"; 1754 EmitHwModeCheck(Target + "GenMCSubtargetInfo", OS); 1755 } 1756 1757 void SubtargetEmitter::EmitMCInstrAnalysisPredicateFunctions(raw_ostream &OS) { 1758 OS << "\n#ifdef GET_STIPREDICATE_DECLS_FOR_MC_ANALYSIS\n"; 1759 OS << "#undef GET_STIPREDICATE_DECLS_FOR_MC_ANALYSIS\n\n"; 1760 1761 STIPredicateExpander PE(Target); 1762 PE.setExpandForMC(true); 1763 PE.setByRef(true); 1764 for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates()) 1765 PE.expandSTIPredicate(OS, Fn); 1766 1767 OS << "#endif // GET_STIPREDICATE_DECLS_FOR_MC_ANALYSIS\n\n"; 1768 1769 OS << "\n#ifdef GET_STIPREDICATE_DEFS_FOR_MC_ANALYSIS\n"; 1770 OS << "#undef GET_STIPREDICATE_DEFS_FOR_MC_ANALYSIS\n\n"; 1771 1772 std::string ClassPrefix = Target + "MCInstrAnalysis"; 1773 PE.setExpandDefinition(true); 1774 PE.setClassPrefix(ClassPrefix); 1775 PE.setIndentLevel(0); 1776 for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates()) 1777 PE.expandSTIPredicate(OS, Fn); 1778 1779 OS << "#endif // GET_STIPREDICATE_DEFS_FOR_MC_ANALYSIS\n\n"; 1780 } 1781 1782 // 1783 // SubtargetEmitter::run - Main subtarget enumeration emitter. 1784 // 1785 void SubtargetEmitter::run(raw_ostream &OS) { 1786 emitSourceFileHeader("Subtarget Enumeration Source Fragment", OS); 1787 1788 OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n"; 1789 OS << "#undef GET_SUBTARGETINFO_ENUM\n\n"; 1790 1791 DenseMap<Record *, unsigned> FeatureMap; 1792 1793 OS << "namespace llvm {\n"; 1794 Enumeration(OS, FeatureMap); 1795 OS << "} // end namespace llvm\n\n"; 1796 OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n"; 1797 1798 OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n"; 1799 OS << "#undef GET_SUBTARGETINFO_MC_DESC\n\n"; 1800 1801 OS << "namespace llvm {\n"; 1802 #if 0 1803 OS << "namespace {\n"; 1804 #endif 1805 unsigned NumFeatures = FeatureKeyValues(OS, FeatureMap); 1806 OS << "\n"; 1807 EmitSchedModel(OS); 1808 OS << "\n"; 1809 unsigned NumProcs = CPUKeyValues(OS, FeatureMap); 1810 OS << "\n"; 1811 #if 0 1812 OS << "} // end anonymous namespace\n\n"; 1813 #endif 1814 1815 // MCInstrInfo initialization routine. 1816 emitGenMCSubtargetInfo(OS); 1817 1818 OS << "\nstatic inline MCSubtargetInfo *create" << Target 1819 << "MCSubtargetInfoImpl(" 1820 << "const Triple &TT, StringRef CPU, StringRef FS) {\n"; 1821 OS << " return new " << Target << "GenMCSubtargetInfo(TT, CPU, FS, "; 1822 if (NumFeatures) 1823 OS << Target << "FeatureKV, "; 1824 else 1825 OS << "None, "; 1826 if (NumProcs) 1827 OS << Target << "SubTypeKV, "; 1828 else 1829 OS << "None, "; 1830 OS << '\n'; OS.indent(22); 1831 OS << Target << "WriteProcResTable, " 1832 << Target << "WriteLatencyTable, " 1833 << Target << "ReadAdvanceTable, "; 1834 OS << '\n'; OS.indent(22); 1835 if (SchedModels.hasItineraries()) { 1836 OS << Target << "Stages, " 1837 << Target << "OperandCycles, " 1838 << Target << "ForwardingPaths"; 1839 } else 1840 OS << "nullptr, nullptr, nullptr"; 1841 OS << ");\n}\n\n"; 1842 1843 OS << "} // end namespace llvm\n\n"; 1844 1845 OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n"; 1846 1847 OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n"; 1848 OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n\n"; 1849 1850 OS << "#include \"llvm/Support/Debug.h\"\n"; 1851 OS << "#include \"llvm/Support/raw_ostream.h\"\n\n"; 1852 ParseFeaturesFunction(OS, NumFeatures, NumProcs); 1853 1854 OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n"; 1855 1856 // Create a TargetSubtargetInfo subclass to hide the MC layer initialization. 1857 OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n"; 1858 OS << "#undef GET_SUBTARGETINFO_HEADER\n\n"; 1859 1860 std::string ClassName = Target + "GenSubtargetInfo"; 1861 OS << "namespace llvm {\n"; 1862 OS << "class DFAPacketizer;\n"; 1863 OS << "namespace " << Target << "_MC {\n" 1864 << "unsigned resolveVariantSchedClassImpl(unsigned SchedClass," 1865 << " const MCInst *MI, unsigned CPUID);\n" 1866 << "} // end namespace " << Target << "_MC\n\n"; 1867 OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n" 1868 << " explicit " << ClassName << "(const Triple &TT, StringRef CPU, " 1869 << "StringRef FS);\n" 1870 << "public:\n" 1871 << " unsigned resolveSchedClass(unsigned SchedClass, " 1872 << " const MachineInstr *DefMI," 1873 << " const TargetSchedModel *SchedModel) const override;\n" 1874 << " unsigned resolveVariantSchedClass(unsigned SchedClass," 1875 << " const MCInst *MI, unsigned CPUID) const override;\n" 1876 << " DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)" 1877 << " const;\n"; 1878 if (TGT.getHwModes().getNumModeIds() > 1) 1879 OS << " unsigned getHwMode() const override;\n"; 1880 1881 STIPredicateExpander PE(Target); 1882 PE.setByRef(false); 1883 for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates()) 1884 PE.expandSTIPredicate(OS, Fn); 1885 1886 OS << "};\n" 1887 << "} // end namespace llvm\n\n"; 1888 1889 OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n"; 1890 1891 OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n"; 1892 OS << "#undef GET_SUBTARGETINFO_CTOR\n\n"; 1893 1894 OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n\n"; 1895 OS << "namespace llvm {\n"; 1896 OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n"; 1897 OS << "extern const llvm::SubtargetSubTypeKV " << Target << "SubTypeKV[];\n"; 1898 OS << "extern const llvm::MCWriteProcResEntry " 1899 << Target << "WriteProcResTable[];\n"; 1900 OS << "extern const llvm::MCWriteLatencyEntry " 1901 << Target << "WriteLatencyTable[];\n"; 1902 OS << "extern const llvm::MCReadAdvanceEntry " 1903 << Target << "ReadAdvanceTable[];\n"; 1904 1905 if (SchedModels.hasItineraries()) { 1906 OS << "extern const llvm::InstrStage " << Target << "Stages[];\n"; 1907 OS << "extern const unsigned " << Target << "OperandCycles[];\n"; 1908 OS << "extern const unsigned " << Target << "ForwardingPaths[];\n"; 1909 } 1910 1911 OS << ClassName << "::" << ClassName << "(const Triple &TT, StringRef CPU, " 1912 << "StringRef FS)\n" 1913 << " : TargetSubtargetInfo(TT, CPU, FS, "; 1914 if (NumFeatures) 1915 OS << "makeArrayRef(" << Target << "FeatureKV, " << NumFeatures << "), "; 1916 else 1917 OS << "None, "; 1918 if (NumProcs) 1919 OS << "makeArrayRef(" << Target << "SubTypeKV, " << NumProcs << "), "; 1920 else 1921 OS << "None, "; 1922 OS << '\n'; OS.indent(24); 1923 OS << Target << "WriteProcResTable, " 1924 << Target << "WriteLatencyTable, " 1925 << Target << "ReadAdvanceTable, "; 1926 OS << '\n'; OS.indent(24); 1927 if (SchedModels.hasItineraries()) { 1928 OS << Target << "Stages, " 1929 << Target << "OperandCycles, " 1930 << Target << "ForwardingPaths"; 1931 } else 1932 OS << "nullptr, nullptr, nullptr"; 1933 OS << ") {}\n\n"; 1934 1935 EmitSchedModelHelpers(ClassName, OS); 1936 EmitHwModeCheck(ClassName, OS); 1937 1938 OS << "} // end namespace llvm\n\n"; 1939 1940 OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n"; 1941 1942 EmitMCInstrAnalysisPredicateFunctions(OS); 1943 } 1944 1945 namespace llvm { 1946 1947 void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) { 1948 CodeGenTarget CGTarget(RK); 1949 SubtargetEmitter(RK, CGTarget).run(OS); 1950 } 1951 1952 } // end namespace llvm 1953