1 //===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits subtarget enumerations.
12 //===----------------------------------------------------------------------===//
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"
39 #define DEBUG_TYPE "subtarget-emitter"
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;
54 // Reserve an invalid entry at index 0
56 ProcSchedClasses.resize(1);
57 WriteProcResources.resize(1);
58 WriteLatencies.resize(1);
59 WriterNames.push_back("InvalidWrite");
60 ReadAdvanceEntries.resize(1);
64 struct LessWriteProcResources {
65 bool operator()(const MCWriteProcResEntry &LHS,
66 const MCWriteProcResEntry &RHS) {
67 return LHS.ProcResourceIdx < RHS.ProcResourceIdx;
71 const CodeGenTarget &TGT;
72 RecordKeeper &Records;
73 CodeGenSchedModels &SchedModels;
76 void Enumeration(raw_ostream &OS);
77 unsigned FeatureKeyValues(raw_ostream &OS);
78 unsigned CPUKeyValues(raw_ostream &OS);
79 void FormItineraryStageString(const std::string &Names,
80 Record *ItinData, std::string &ItinString,
82 void FormItineraryOperandCycleString(Record *ItinData, std::string &ItinString,
83 unsigned &NOperandCycles);
84 void FormItineraryBypassString(const std::string &Names,
86 std::string &ItinString, unsigned NOperandCycles);
87 void EmitStageAndOperandCycleData(raw_ostream &OS,
88 std::vector<std::vector<InstrItinerary>>
90 void EmitItineraries(raw_ostream &OS,
91 std::vector<std::vector<InstrItinerary>>
93 void EmitProcessorProp(raw_ostream &OS, const Record *R, StringRef Name,
95 void EmitProcessorResources(const CodeGenProcModel &ProcModel,
97 Record *FindWriteResources(const CodeGenSchedRW &SchedWrite,
98 const CodeGenProcModel &ProcModel);
99 Record *FindReadAdvance(const CodeGenSchedRW &SchedRead,
100 const CodeGenProcModel &ProcModel);
101 void ExpandProcResources(RecVec &PRVec, std::vector<int64_t> &Cycles,
102 const CodeGenProcModel &ProcModel);
103 void GenSchedClassTables(const CodeGenProcModel &ProcModel,
104 SchedClassTables &SchedTables);
105 void EmitSchedClassTables(SchedClassTables &SchedTables, raw_ostream &OS);
106 void EmitProcessorModels(raw_ostream &OS);
107 void EmitProcessorLookup(raw_ostream &OS);
108 void EmitSchedModelHelpers(const std::string &ClassName, raw_ostream &OS);
109 void EmitSchedModel(raw_ostream &OS);
110 void EmitHwModeCheck(const std::string &ClassName, raw_ostream &OS);
111 void ParseFeaturesFunction(raw_ostream &OS, unsigned NumFeatures,
115 SubtargetEmitter(RecordKeeper &R, CodeGenTarget &TGT)
116 : TGT(TGT), Records(R), SchedModels(TGT.getSchedModels()),
117 Target(TGT.getName()) {}
119 void run(raw_ostream &o);
122 } // end anonymous namespace
125 // Enumeration - Emit the specified class as an enumeration.
127 void SubtargetEmitter::Enumeration(raw_ostream &OS) {
128 // Get all records of class and sort
129 std::vector<Record*> DefList =
130 Records.getAllDerivedDefinitions("SubtargetFeature");
131 std::sort(DefList.begin(), DefList.end(), LessRecord());
133 unsigned N = DefList.size();
136 if (N > MAX_SUBTARGET_FEATURES)
137 PrintFatalError("Too many subtarget features! Bump MAX_SUBTARGET_FEATURES.");
139 OS << "namespace " << Target << " {\n";
145 for (unsigned i = 0; i < N; ++i) {
147 Record *Def = DefList[i];
150 OS << " " << Def->getName() << " = " << i << ",\n";
153 // Close enumeration and namespace
155 OS << "} // end namespace " << Target << "\n";
159 // FeatureKeyValues - Emit data of all the subtarget features. Used by the
162 unsigned SubtargetEmitter::FeatureKeyValues(raw_ostream &OS) {
163 // Gather and sort all the features
164 std::vector<Record*> FeatureList =
165 Records.getAllDerivedDefinitions("SubtargetFeature");
167 if (FeatureList.empty())
170 std::sort(FeatureList.begin(), FeatureList.end(), LessRecordFieldName());
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";
178 unsigned NumFeatures = 0;
179 for (unsigned i = 0, N = FeatureList.size(); i < N; ++i) {
181 Record *Feature = FeatureList[i];
183 StringRef Name = Feature->getName();
184 StringRef CommandLineName = Feature->getValueAsString("Name");
185 StringRef Desc = Feature->getValueAsString("Desc");
187 if (CommandLineName.empty()) continue;
189 // Emit as { "feature", "description", { featureEnum }, { i1 , i2 , ... , in } }
191 << "\"" << CommandLineName << "\", "
192 << "\"" << Desc << "\", "
193 << "{ " << Target << "::" << Name << " }, ";
195 const std::vector<Record*> &ImpliesList =
196 Feature->getValueAsListOfDefs("Implies");
199 for (unsigned j = 0, M = ImpliesList.size(); j < M;) {
200 OS << " " << Target << "::" << ImpliesList[j]->getName();
201 if (++j < M) OS << ",";
214 // CPUKeyValues - Emit data of all the subtarget processors. Used by command
217 unsigned SubtargetEmitter::CPUKeyValues(raw_ostream &OS) {
218 // Gather and sort processor information
219 std::vector<Record*> ProcessorList =
220 Records.getAllDerivedDefinitions("Processor");
221 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
223 // Begin processor table
224 OS << "// Sorted (by key) array of values for CPU subtype.\n"
225 << "extern const llvm::SubtargetFeatureKV " << Target
226 << "SubTypeKV[] = {\n";
228 // For each processor
229 for (Record *Processor : ProcessorList) {
230 StringRef Name = Processor->getValueAsString("Name");
231 const std::vector<Record*> &FeatureList =
232 Processor->getValueAsListOfDefs("Features");
234 // Emit as { "cpu", "description", { f1 , f2 , ... fn } },
236 << "\"" << Name << "\", "
237 << "\"Select the " << Name << " processor\", ";
240 for (unsigned j = 0, M = FeatureList.size(); j < M;) {
241 OS << " " << Target << "::" << FeatureList[j]->getName();
242 if (++j < M) OS << ",";
244 // The { } is for the "implies" section of this data structure.
245 OS << " }, { } },\n";
248 // End processor table
251 return ProcessorList.size();
255 // FormItineraryStageString - Compose a string containing the stage
256 // data initialization for the specified itinerary. N is the number
259 void SubtargetEmitter::FormItineraryStageString(const std::string &Name,
261 std::string &ItinString,
264 const std::vector<Record*> &StageList =
265 ItinData->getValueAsListOfDefs("Stages");
268 unsigned N = NStages = StageList.size();
269 for (unsigned i = 0; i < N;) {
271 const Record *Stage = StageList[i];
273 // Form string as ,{ cycles, u1 | u2 | ... | un, timeinc, kind }
274 int Cycles = Stage->getValueAsInt("Cycles");
275 ItinString += " { " + itostr(Cycles) + ", ";
278 const std::vector<Record*> &UnitList = Stage->getValueAsListOfDefs("Units");
281 for (unsigned j = 0, M = UnitList.size(); j < M;) {
282 // Add name and bitwise or
283 ItinString += Name + "FU::" + UnitList[j]->getName().str();
284 if (++j < M) ItinString += " | ";
287 int TimeInc = Stage->getValueAsInt("TimeInc");
288 ItinString += ", " + itostr(TimeInc);
290 int Kind = Stage->getValueAsInt("Kind");
291 ItinString += ", (llvm::InstrStage::ReservationKinds)" + itostr(Kind);
295 if (++i < N) ItinString += ", ";
300 // FormItineraryOperandCycleString - Compose a string containing the
301 // operand cycle initialization for the specified itinerary. N is the
302 // number of operands that has cycles specified.
304 void SubtargetEmitter::FormItineraryOperandCycleString(Record *ItinData,
305 std::string &ItinString, unsigned &NOperandCycles) {
306 // Get operand cycle list
307 const std::vector<int64_t> &OperandCycleList =
308 ItinData->getValueAsListOfInts("OperandCycles");
310 // For each operand cycle
311 unsigned N = NOperandCycles = OperandCycleList.size();
312 for (unsigned i = 0; i < N;) {
313 // Next operand cycle
314 const int OCycle = OperandCycleList[i];
316 ItinString += " " + itostr(OCycle);
317 if (++i < N) ItinString += ", ";
321 void SubtargetEmitter::FormItineraryBypassString(const std::string &Name,
323 std::string &ItinString,
324 unsigned NOperandCycles) {
325 const std::vector<Record*> &BypassList =
326 ItinData->getValueAsListOfDefs("Bypasses");
327 unsigned N = BypassList.size();
330 ItinString += Name + "Bypass::" + BypassList[i]->getName().str();
331 if (++i < NOperandCycles) ItinString += ", ";
333 for (; i < NOperandCycles;) {
335 if (++i < NOperandCycles) ItinString += ", ";
340 // EmitStageAndOperandCycleData - Generate unique itinerary stages and operand
341 // cycle tables. Create a list of InstrItinerary objects (ProcItinLists) indexed
342 // by CodeGenSchedClass::Index.
344 void SubtargetEmitter::
345 EmitStageAndOperandCycleData(raw_ostream &OS,
346 std::vector<std::vector<InstrItinerary>>
348 // Multiple processor models may share an itinerary record. Emit it once.
349 SmallPtrSet<Record*, 8> ItinsDefSet;
351 // Emit functional units for all the itineraries.
352 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
354 if (!ItinsDefSet.insert(ProcModel.ItinsDef).second)
357 std::vector<Record*> FUs = ProcModel.ItinsDef->getValueAsListOfDefs("FU");
361 StringRef Name = ProcModel.ItinsDef->getName();
362 OS << "\n// Functional units for \"" << Name << "\"\n"
363 << "namespace " << Name << "FU {\n";
365 for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j)
366 OS << " const unsigned " << FUs[j]->getName()
367 << " = 1 << " << j << ";\n";
369 OS << "} // end namespace " << Name << "FU\n";
371 std::vector<Record*> BPs = ProcModel.ItinsDef->getValueAsListOfDefs("BP");
373 OS << "\n// Pipeline forwarding pathes for itineraries \"" << Name
374 << "\"\n" << "namespace " << Name << "Bypass {\n";
376 OS << " const unsigned NoBypass = 0;\n";
377 for (unsigned j = 0, BPN = BPs.size(); j < BPN; ++j)
378 OS << " const unsigned " << BPs[j]->getName()
379 << " = 1 << " << j << ";\n";
381 OS << "} // end namespace " << Name << "Bypass\n";
385 // Begin stages table
386 std::string StageTable = "\nextern const llvm::InstrStage " + Target +
388 StageTable += " { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n";
390 // Begin operand cycle table
391 std::string OperandCycleTable = "extern const unsigned " + Target +
392 "OperandCycles[] = {\n";
393 OperandCycleTable += " 0, // No itinerary\n";
395 // Begin pipeline bypass table
396 std::string BypassTable = "extern const unsigned " + Target +
397 "ForwardingPaths[] = {\n";
398 BypassTable += " 0, // No itinerary\n";
400 // For each Itinerary across all processors, add a unique entry to the stages,
401 // operand cycles, and pipeline bypass tables. Then add the new Itinerary
402 // object with computed offsets to the ProcItinLists result.
403 unsigned StageCount = 1, OperandCycleCount = 1;
404 std::map<std::string, unsigned> ItinStageMap, ItinOperandMap;
405 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
406 // Add process itinerary to the list.
407 ProcItinLists.resize(ProcItinLists.size()+1);
409 // If this processor defines no itineraries, then leave the itinerary list
411 std::vector<InstrItinerary> &ItinList = ProcItinLists.back();
412 if (!ProcModel.hasItineraries())
415 StringRef Name = ProcModel.ItinsDef->getName();
417 ItinList.resize(SchedModels.numInstrSchedClasses());
418 assert(ProcModel.ItinDefList.size() == ItinList.size() && "bad Itins");
420 for (unsigned SchedClassIdx = 0, SchedClassEnd = ItinList.size();
421 SchedClassIdx < SchedClassEnd; ++SchedClassIdx) {
423 // Next itinerary data
424 Record *ItinData = ProcModel.ItinDefList[SchedClassIdx];
426 // Get string and stage count
427 std::string ItinStageString;
428 unsigned NStages = 0;
430 FormItineraryStageString(Name, ItinData, ItinStageString, NStages);
432 // Get string and operand cycle count
433 std::string ItinOperandCycleString;
434 unsigned NOperandCycles = 0;
435 std::string ItinBypassString;
437 FormItineraryOperandCycleString(ItinData, ItinOperandCycleString,
440 FormItineraryBypassString(Name, ItinData, ItinBypassString,
444 // Check to see if stage already exists and create if it doesn't
445 unsigned FindStage = 0;
447 FindStage = ItinStageMap[ItinStageString];
448 if (FindStage == 0) {
449 // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // indices
450 StageTable += ItinStageString + ", // " + itostr(StageCount);
452 StageTable += "-" + itostr(StageCount + NStages - 1);
454 // Record Itin class number.
455 ItinStageMap[ItinStageString] = FindStage = StageCount;
456 StageCount += NStages;
460 // Check to see if operand cycle already exists and create if it doesn't
461 unsigned FindOperandCycle = 0;
462 if (NOperandCycles > 0) {
463 std::string ItinOperandString = ItinOperandCycleString+ItinBypassString;
464 FindOperandCycle = ItinOperandMap[ItinOperandString];
465 if (FindOperandCycle == 0) {
466 // Emit as cycle, // index
467 OperandCycleTable += ItinOperandCycleString + ", // ";
468 std::string OperandIdxComment = itostr(OperandCycleCount);
469 if (NOperandCycles > 1)
470 OperandIdxComment += "-"
471 + itostr(OperandCycleCount + NOperandCycles - 1);
472 OperandCycleTable += OperandIdxComment + "\n";
473 // Record Itin class number.
474 ItinOperandMap[ItinOperandCycleString] =
475 FindOperandCycle = OperandCycleCount;
476 // Emit as bypass, // index
477 BypassTable += ItinBypassString + ", // " + OperandIdxComment + "\n";
478 OperandCycleCount += NOperandCycles;
482 // Set up itinerary as location and location + stage count
483 int NumUOps = ItinData ? ItinData->getValueAsInt("NumMicroOps") : 0;
484 InstrItinerary Intinerary = { NumUOps, FindStage, FindStage + NStages,
486 FindOperandCycle + NOperandCycles };
488 // Inject - empty slots will be 0, 0
489 ItinList[SchedClassIdx] = Intinerary;
494 StageTable += " { 0, 0, 0, llvm::InstrStage::Required } // End stages\n";
495 StageTable += "};\n";
497 // Closing operand cycles
498 OperandCycleTable += " 0 // End operand cycles\n";
499 OperandCycleTable += "};\n";
501 BypassTable += " 0 // End bypass tables\n";
502 BypassTable += "};\n";
506 OS << OperandCycleTable;
511 // EmitProcessorData - Generate data for processor itineraries that were
512 // computed during EmitStageAndOperandCycleData(). ProcItinLists lists all
513 // Itineraries for each processor. The Itinerary lists are indexed on
514 // CodeGenSchedClass::Index.
516 void SubtargetEmitter::
517 EmitItineraries(raw_ostream &OS,
518 std::vector<std::vector<InstrItinerary>> &ProcItinLists) {
519 // Multiple processor models may share an itinerary record. Emit it once.
520 SmallPtrSet<Record*, 8> ItinsDefSet;
522 // For each processor's machine model
523 std::vector<std::vector<InstrItinerary>>::iterator
524 ProcItinListsIter = ProcItinLists.begin();
525 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
526 PE = SchedModels.procModelEnd(); PI != PE; ++PI, ++ProcItinListsIter) {
528 Record *ItinsDef = PI->ItinsDef;
529 if (!ItinsDefSet.insert(ItinsDef).second)
532 // Get the itinerary list for the processor.
533 assert(ProcItinListsIter != ProcItinLists.end() && "bad iterator");
534 std::vector<InstrItinerary> &ItinList = *ProcItinListsIter;
536 // Empty itineraries aren't referenced anywhere in the tablegen output
537 // so don't emit them.
538 if (ItinList.empty())
542 OS << "static const llvm::InstrItinerary ";
544 // Begin processor itinerary table
545 OS << ItinsDef->getName() << "[] = {\n";
547 // For each itinerary class in CodeGenSchedClass::Index order.
548 for (unsigned j = 0, M = ItinList.size(); j < M; ++j) {
549 InstrItinerary &Intinerary = ItinList[j];
551 // Emit Itinerary in the form of
552 // { firstStage, lastStage, firstCycle, lastCycle } // index
554 Intinerary.NumMicroOps << ", " <<
555 Intinerary.FirstStage << ", " <<
556 Intinerary.LastStage << ", " <<
557 Intinerary.FirstOperandCycle << ", " <<
558 Intinerary.LastOperandCycle << " }" <<
559 ", // " << j << " " << SchedModels.getSchedClass(j).Name << "\n";
561 // End processor itinerary table
562 OS << " { 0, ~0U, ~0U, ~0U, ~0U } // end marker\n";
567 // Emit either the value defined in the TableGen Record, or the default
568 // value defined in the C++ header. The Record is null if the processor does not
570 void SubtargetEmitter::EmitProcessorProp(raw_ostream &OS, const Record *R,
571 StringRef Name, char Separator) {
573 int V = R ? R->getValueAsInt(Name) : -1;
575 OS << V << Separator << " // " << Name;
577 OS << "MCSchedModel::Default" << Name << Separator;
581 void SubtargetEmitter::EmitProcessorResources(const CodeGenProcModel &ProcModel,
583 OS << "\n// {Name, NumUnits, SuperIdx, IsBuffered}\n";
584 OS << "static const llvm::MCProcResourceDesc "
585 << ProcModel.ModelName << "ProcResources" << "[] = {\n"
586 << " {DBGFIELD(\"InvalidUnit\") 0, 0, 0},\n";
588 for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) {
589 Record *PRDef = ProcModel.ProcResourceDefs[i];
591 Record *SuperDef = nullptr;
592 unsigned SuperIdx = 0;
593 unsigned NumUnits = 0;
594 int BufferSize = PRDef->getValueAsInt("BufferSize");
595 if (PRDef->isSubClassOf("ProcResGroup")) {
596 RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources");
597 for (Record *RU : ResUnits) {
598 NumUnits += RU->getValueAsInt("NumUnits");
603 if (PRDef->getValueInit("Super")->isComplete()) {
605 SchedModels.findProcResUnits(PRDef->getValueAsDef("Super"),
606 ProcModel, PRDef->getLoc());
607 SuperIdx = ProcModel.getProcResourceIdx(SuperDef);
609 NumUnits = PRDef->getValueAsInt("NumUnits");
611 // Emit the ProcResourceDesc
612 OS << " {DBGFIELD(\"" << PRDef->getName() << "\") ";
613 if (PRDef->getName().size() < 15)
614 OS.indent(15 - PRDef->getName().size());
615 OS << NumUnits << ", " << SuperIdx << ", "
616 << BufferSize << "}, // #" << i+1;
618 OS << ", Super=" << SuperDef->getName();
624 // Find the WriteRes Record that defines processor resources for this
626 Record *SubtargetEmitter::FindWriteResources(
627 const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) {
629 // Check if the SchedWrite is already subtarget-specific and directly
630 // specifies a set of processor resources.
631 if (SchedWrite.TheDef->isSubClassOf("SchedWriteRes"))
632 return SchedWrite.TheDef;
634 Record *AliasDef = nullptr;
635 for (Record *A : SchedWrite.Aliases) {
636 const CodeGenSchedRW &AliasRW =
637 SchedModels.getSchedRW(A->getValueAsDef("AliasRW"));
638 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
639 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
640 if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
644 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
645 "defined for processor " + ProcModel.ModelName +
646 " Ensure only one SchedAlias exists per RW.");
647 AliasDef = AliasRW.TheDef;
649 if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes"))
652 // Check this processor's list of write resources.
653 Record *ResDef = nullptr;
654 for (Record *WR : ProcModel.WriteResDefs) {
655 if (!WR->isSubClassOf("WriteRes"))
657 if (AliasDef == WR->getValueAsDef("WriteType")
658 || SchedWrite.TheDef == WR->getValueAsDef("WriteType")) {
660 PrintFatalError(WR->getLoc(), "Resources are defined for both "
661 "SchedWrite and its alias on processor " +
662 ProcModel.ModelName);
667 // TODO: If ProcModel has a base model (previous generation processor),
668 // then call FindWriteResources recursively with that model here.
670 PrintFatalError(ProcModel.ModelDef->getLoc(),
671 Twine("Processor does not define resources for ") +
672 SchedWrite.TheDef->getName());
677 /// Find the ReadAdvance record for the given SchedRead on this processor or
679 Record *SubtargetEmitter::FindReadAdvance(const CodeGenSchedRW &SchedRead,
680 const CodeGenProcModel &ProcModel) {
681 // Check for SchedReads that directly specify a ReadAdvance.
682 if (SchedRead.TheDef->isSubClassOf("SchedReadAdvance"))
683 return SchedRead.TheDef;
685 // Check this processor's list of aliases for SchedRead.
686 Record *AliasDef = nullptr;
687 for (Record *A : SchedRead.Aliases) {
688 const CodeGenSchedRW &AliasRW =
689 SchedModels.getSchedRW(A->getValueAsDef("AliasRW"));
690 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
691 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
692 if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
696 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
697 "defined for processor " + ProcModel.ModelName +
698 " Ensure only one SchedAlias exists per RW.");
699 AliasDef = AliasRW.TheDef;
701 if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance"))
704 // Check this processor's ReadAdvanceList.
705 Record *ResDef = nullptr;
706 for (Record *RA : ProcModel.ReadAdvanceDefs) {
707 if (!RA->isSubClassOf("ReadAdvance"))
709 if (AliasDef == RA->getValueAsDef("ReadType")
710 || SchedRead.TheDef == RA->getValueAsDef("ReadType")) {
712 PrintFatalError(RA->getLoc(), "Resources are defined for both "
713 "SchedRead and its alias on processor " +
714 ProcModel.ModelName);
719 // TODO: If ProcModel has a base model (previous generation processor),
720 // then call FindReadAdvance recursively with that model here.
721 if (!ResDef && SchedRead.TheDef->getName() != "ReadDefault") {
722 PrintFatalError(ProcModel.ModelDef->getLoc(),
723 Twine("Processor does not define resources for ") +
724 SchedRead.TheDef->getName());
729 // Expand an explicit list of processor resources into a full list of implied
730 // resource groups and super resources that cover them.
731 void SubtargetEmitter::ExpandProcResources(RecVec &PRVec,
732 std::vector<int64_t> &Cycles,
733 const CodeGenProcModel &PM) {
734 // Default to 1 resource cycle.
735 Cycles.resize(PRVec.size(), 1);
736 for (unsigned i = 0, e = PRVec.size(); i != e; ++i) {
737 Record *PRDef = PRVec[i];
739 if (PRDef->isSubClassOf("ProcResGroup"))
740 SubResources = PRDef->getValueAsListOfDefs("Resources");
742 SubResources.push_back(PRDef);
743 PRDef = SchedModels.findProcResUnits(PRDef, PM, PRDef->getLoc());
744 for (Record *SubDef = PRDef;
745 SubDef->getValueInit("Super")->isComplete();) {
746 if (SubDef->isSubClassOf("ProcResGroup")) {
747 // Disallow this for simplicitly.
748 PrintFatalError(SubDef->getLoc(), "Processor resource group "
749 " cannot be a super resources.");
752 SchedModels.findProcResUnits(SubDef->getValueAsDef("Super"), PM,
754 PRVec.push_back(SuperDef);
755 Cycles.push_back(Cycles[i]);
759 for (Record *PR : PM.ProcResourceDefs) {
760 if (PR == PRDef || !PR->isSubClassOf("ProcResGroup"))
762 RecVec SuperResources = PR->getValueAsListOfDefs("Resources");
763 RecIter SubI = SubResources.begin(), SubE = SubResources.end();
764 for( ; SubI != SubE; ++SubI) {
765 if (!is_contained(SuperResources, *SubI)) {
771 Cycles.push_back(Cycles[i]);
777 // Generate the SchedClass table for this processor and update global
778 // tables. Must be called for each processor in order.
779 void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel,
780 SchedClassTables &SchedTables) {
781 SchedTables.ProcSchedClasses.resize(SchedTables.ProcSchedClasses.size() + 1);
782 if (!ProcModel.hasInstrSchedModel())
785 std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back();
786 DEBUG(dbgs() << "\n+++ SCHED CLASSES (GenSchedClassTables) +++\n");
787 for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) {
788 DEBUG(SC.dump(&SchedModels));
790 SCTab.resize(SCTab.size() + 1);
791 MCSchedClassDesc &SCDesc = SCTab.back();
792 // SCDesc.Name is guarded by NDEBUG
793 SCDesc.NumMicroOps = 0;
794 SCDesc.BeginGroup = false;
795 SCDesc.EndGroup = false;
796 SCDesc.WriteProcResIdx = 0;
797 SCDesc.WriteLatencyIdx = 0;
798 SCDesc.ReadAdvanceIdx = 0;
800 // A Variant SchedClass has no resources of its own.
801 bool HasVariants = false;
802 for (const CodeGenSchedTransition &CGT :
803 make_range(SC.Transitions.begin(), SC.Transitions.end())) {
804 if (CGT.ProcIndices[0] == 0 ||
805 is_contained(CGT.ProcIndices, ProcModel.Index)) {
811 SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps;
815 // Determine if the SchedClass is actually reachable on this processor. If
816 // not don't try to locate the processor resources, it will fail.
817 // If ProcIndices contains 0, this class applies to all processors.
818 assert(!SC.ProcIndices.empty() && "expect at least one procidx");
819 if (SC.ProcIndices[0] != 0) {
820 if (!is_contained(SC.ProcIndices, ProcModel.Index))
823 IdxVec Writes = SC.Writes;
824 IdxVec Reads = SC.Reads;
825 if (!SC.InstRWs.empty()) {
826 // This class has a default ReadWrite list which can be overriden by
827 // InstRW definitions.
828 Record *RWDef = nullptr;
829 for (Record *RW : SC.InstRWs) {
830 Record *RWModelDef = RW->getValueAsDef("SchedModel");
831 if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) {
839 SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
843 if (Writes.empty()) {
844 // Check this processor's itinerary class resources.
845 for (Record *I : ProcModel.ItinRWDefs) {
846 RecVec Matched = I->getValueAsListOfDefs("MatchedItinClasses");
847 if (is_contained(Matched, SC.ItinClassDef)) {
848 SchedModels.findRWs(I->getValueAsListOfDefs("OperandReadWrites"),
853 if (Writes.empty()) {
854 DEBUG(dbgs() << ProcModel.ModelName
855 << " does not have resources for class " << SC.Name << '\n');
858 // Sum resources across all operand writes.
859 std::vector<MCWriteProcResEntry> WriteProcResources;
860 std::vector<MCWriteLatencyEntry> WriteLatencies;
861 std::vector<std::string> WriterNames;
862 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries;
863 for (unsigned W : Writes) {
865 SchedModels.expandRWSeqForProc(W, WriteSeq, /*IsRead=*/false,
868 // For each operand, create a latency entry.
869 MCWriteLatencyEntry WLEntry;
871 unsigned WriteID = WriteSeq.back();
872 WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name);
873 // If this Write is not referenced by a ReadAdvance, don't distinguish it
874 // from other WriteLatency entries.
875 if (!SchedModels.hasReadOfWrite(
876 SchedModels.getSchedWrite(WriteID).TheDef)) {
879 WLEntry.WriteResourceID = WriteID;
881 for (unsigned WS : WriteSeq) {
884 FindWriteResources(SchedModels.getSchedWrite(WS), ProcModel);
886 // Mark the parent class as invalid for unsupported write types.
887 if (WriteRes->getValueAsBit("Unsupported")) {
888 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
891 WLEntry.Cycles += WriteRes->getValueAsInt("Latency");
892 SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps");
893 SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup");
894 SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup");
895 SCDesc.BeginGroup |= WriteRes->getValueAsBit("SingleIssue");
896 SCDesc.EndGroup |= WriteRes->getValueAsBit("SingleIssue");
898 // Create an entry for each ProcResource listed in WriteRes.
899 RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources");
900 std::vector<int64_t> Cycles =
901 WriteRes->getValueAsListOfInts("ResourceCycles");
903 ExpandProcResources(PRVec, Cycles, ProcModel);
905 for (unsigned PRIdx = 0, PREnd = PRVec.size();
906 PRIdx != PREnd; ++PRIdx) {
907 MCWriteProcResEntry WPREntry;
908 WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]);
909 assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx");
910 WPREntry.Cycles = Cycles[PRIdx];
911 // If this resource is already used in this sequence, add the current
912 // entry's cycles so that the same resource appears to be used
913 // serially, rather than multiple parallel uses. This is important for
914 // in-order machine where the resource consumption is a hazard.
915 unsigned WPRIdx = 0, WPREnd = WriteProcResources.size();
916 for( ; WPRIdx != WPREnd; ++WPRIdx) {
917 if (WriteProcResources[WPRIdx].ProcResourceIdx
918 == WPREntry.ProcResourceIdx) {
919 WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles;
923 if (WPRIdx == WPREnd)
924 WriteProcResources.push_back(WPREntry);
927 WriteLatencies.push_back(WLEntry);
929 // Create an entry for each operand Read in this SchedClass.
930 // Entries must be sorted first by UseIdx then by WriteResourceID.
931 for (unsigned UseIdx = 0, EndIdx = Reads.size();
932 UseIdx != EndIdx; ++UseIdx) {
933 Record *ReadAdvance =
934 FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel);
938 // Mark the parent class as invalid for unsupported write types.
939 if (ReadAdvance->getValueAsBit("Unsupported")) {
940 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
943 RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites");
945 if (ValidWrites.empty())
946 WriteIDs.push_back(0);
948 for (Record *VW : ValidWrites) {
949 WriteIDs.push_back(SchedModels.getSchedRWIdx(VW, /*IsRead=*/false));
952 std::sort(WriteIDs.begin(), WriteIDs.end());
953 for(unsigned W : WriteIDs) {
954 MCReadAdvanceEntry RAEntry;
955 RAEntry.UseIdx = UseIdx;
956 RAEntry.WriteResourceID = W;
957 RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles");
958 ReadAdvanceEntries.push_back(RAEntry);
961 if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) {
962 WriteProcResources.clear();
963 WriteLatencies.clear();
964 ReadAdvanceEntries.clear();
966 // Add the information for this SchedClass to the global tables using basic
969 // WritePrecRes entries are sorted by ProcResIdx.
970 std::sort(WriteProcResources.begin(), WriteProcResources.end(),
971 LessWriteProcResources());
973 SCDesc.NumWriteProcResEntries = WriteProcResources.size();
974 std::vector<MCWriteProcResEntry>::iterator WPRPos =
975 std::search(SchedTables.WriteProcResources.begin(),
976 SchedTables.WriteProcResources.end(),
977 WriteProcResources.begin(), WriteProcResources.end());
978 if (WPRPos != SchedTables.WriteProcResources.end())
979 SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin();
981 SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size();
982 SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(),
983 WriteProcResources.end());
985 // Latency entries must remain in operand order.
986 SCDesc.NumWriteLatencyEntries = WriteLatencies.size();
987 std::vector<MCWriteLatencyEntry>::iterator WLPos =
988 std::search(SchedTables.WriteLatencies.begin(),
989 SchedTables.WriteLatencies.end(),
990 WriteLatencies.begin(), WriteLatencies.end());
991 if (WLPos != SchedTables.WriteLatencies.end()) {
992 unsigned idx = WLPos - SchedTables.WriteLatencies.begin();
993 SCDesc.WriteLatencyIdx = idx;
994 for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i)
995 if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) ==
997 SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i];
1001 SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size();
1002 SchedTables.WriteLatencies.insert(SchedTables.WriteLatencies.end(),
1003 WriteLatencies.begin(),
1004 WriteLatencies.end());
1005 SchedTables.WriterNames.insert(SchedTables.WriterNames.end(),
1006 WriterNames.begin(), WriterNames.end());
1008 // ReadAdvanceEntries must remain in operand order.
1009 SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size();
1010 std::vector<MCReadAdvanceEntry>::iterator RAPos =
1011 std::search(SchedTables.ReadAdvanceEntries.begin(),
1012 SchedTables.ReadAdvanceEntries.end(),
1013 ReadAdvanceEntries.begin(), ReadAdvanceEntries.end());
1014 if (RAPos != SchedTables.ReadAdvanceEntries.end())
1015 SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin();
1017 SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size();
1018 SchedTables.ReadAdvanceEntries.insert(RAPos, ReadAdvanceEntries.begin(),
1019 ReadAdvanceEntries.end());
1024 // Emit SchedClass tables for all processors and associated global tables.
1025 void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables,
1027 // Emit global WriteProcResTable.
1028 OS << "\n// {ProcResourceIdx, Cycles}\n"
1029 << "extern const llvm::MCWriteProcResEntry "
1030 << Target << "WriteProcResTable[] = {\n"
1031 << " { 0, 0}, // Invalid\n";
1032 for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size();
1033 WPRIdx != WPREnd; ++WPRIdx) {
1034 MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx];
1035 OS << " {" << format("%2d", WPREntry.ProcResourceIdx) << ", "
1036 << format("%2d", WPREntry.Cycles) << "}";
1037 if (WPRIdx + 1 < WPREnd)
1039 OS << " // #" << WPRIdx << '\n';
1041 OS << "}; // " << Target << "WriteProcResTable\n";
1043 // Emit global WriteLatencyTable.
1044 OS << "\n// {Cycles, WriteResourceID}\n"
1045 << "extern const llvm::MCWriteLatencyEntry "
1046 << Target << "WriteLatencyTable[] = {\n"
1047 << " { 0, 0}, // Invalid\n";
1048 for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size();
1049 WLIdx != WLEnd; ++WLIdx) {
1050 MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx];
1051 OS << " {" << format("%2d", WLEntry.Cycles) << ", "
1052 << format("%2d", WLEntry.WriteResourceID) << "}";
1053 if (WLIdx + 1 < WLEnd)
1055 OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n';
1057 OS << "}; // " << Target << "WriteLatencyTable\n";
1059 // Emit global ReadAdvanceTable.
1060 OS << "\n// {UseIdx, WriteResourceID, Cycles}\n"
1061 << "extern const llvm::MCReadAdvanceEntry "
1062 << Target << "ReadAdvanceTable[] = {\n"
1063 << " {0, 0, 0}, // Invalid\n";
1064 for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size();
1065 RAIdx != RAEnd; ++RAIdx) {
1066 MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx];
1067 OS << " {" << RAEntry.UseIdx << ", "
1068 << format("%2d", RAEntry.WriteResourceID) << ", "
1069 << format("%2d", RAEntry.Cycles) << "}";
1070 if (RAIdx + 1 < RAEnd)
1072 OS << " // #" << RAIdx << '\n';
1074 OS << "}; // " << Target << "ReadAdvanceTable\n";
1076 // Emit a SchedClass table for each processor.
1077 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
1078 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
1079 if (!PI->hasInstrSchedModel())
1082 std::vector<MCSchedClassDesc> &SCTab =
1083 SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())];
1085 OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup,"
1086 << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n";
1087 OS << "static const llvm::MCSchedClassDesc "
1088 << PI->ModelName << "SchedClasses[] = {\n";
1090 // The first class is always invalid. We no way to distinguish it except by
1091 // name and position.
1092 assert(SchedModels.getSchedClass(0).Name == "NoInstrModel"
1093 && "invalid class not first");
1094 OS << " {DBGFIELD(\"InvalidSchedClass\") "
1095 << MCSchedClassDesc::InvalidNumMicroOps
1096 << ", false, false, 0, 0, 0, 0, 0, 0},\n";
1098 for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) {
1099 MCSchedClassDesc &MCDesc = SCTab[SCIdx];
1100 const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx);
1101 OS << " {DBGFIELD(\"" << SchedClass.Name << "\") ";
1102 if (SchedClass.Name.size() < 18)
1103 OS.indent(18 - SchedClass.Name.size());
1104 OS << MCDesc.NumMicroOps
1105 << ", " << ( MCDesc.BeginGroup ? "true" : "false" )
1106 << ", " << ( MCDesc.EndGroup ? "true" : "false" )
1107 << ", " << format("%2d", MCDesc.WriteProcResIdx)
1108 << ", " << MCDesc.NumWriteProcResEntries
1109 << ", " << format("%2d", MCDesc.WriteLatencyIdx)
1110 << ", " << MCDesc.NumWriteLatencyEntries
1111 << ", " << format("%2d", MCDesc.ReadAdvanceIdx)
1112 << ", " << MCDesc.NumReadAdvanceEntries
1113 << "}, // #" << SCIdx << '\n';
1115 OS << "}; // " << PI->ModelName << "SchedClasses\n";
1119 void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) {
1120 // For each processor model.
1121 for (const CodeGenProcModel &PM : SchedModels.procModels()) {
1122 // Emit processor resource table.
1123 if (PM.hasInstrSchedModel())
1124 EmitProcessorResources(PM, OS);
1125 else if(!PM.ProcResourceDefs.empty())
1126 PrintFatalError(PM.ModelDef->getLoc(), "SchedMachineModel defines "
1127 "ProcResources without defining WriteRes SchedWriteRes");
1129 // Begin processor itinerary properties
1131 OS << "static const llvm::MCSchedModel " << PM.ModelName << " = {\n";
1132 EmitProcessorProp(OS, PM.ModelDef, "IssueWidth", ',');
1133 EmitProcessorProp(OS, PM.ModelDef, "MicroOpBufferSize", ',');
1134 EmitProcessorProp(OS, PM.ModelDef, "LoopMicroOpBufferSize", ',');
1135 EmitProcessorProp(OS, PM.ModelDef, "LoadLatency", ',');
1136 EmitProcessorProp(OS, PM.ModelDef, "HighLatency", ',');
1137 EmitProcessorProp(OS, PM.ModelDef, "MispredictPenalty", ',');
1139 bool PostRAScheduler =
1140 (PM.ModelDef ? PM.ModelDef->getValueAsBit("PostRAScheduler") : false);
1142 OS << " " << (PostRAScheduler ? "true" : "false") << ", // "
1143 << "PostRAScheduler\n";
1145 bool CompleteModel =
1146 (PM.ModelDef ? PM.ModelDef->getValueAsBit("CompleteModel") : false);
1148 OS << " " << (CompleteModel ? "true" : "false") << ", // "
1149 << "CompleteModel\n";
1151 OS << " " << PM.Index << ", // Processor ID\n";
1152 if (PM.hasInstrSchedModel())
1153 OS << " " << PM.ModelName << "ProcResources" << ",\n"
1154 << " " << PM.ModelName << "SchedClasses" << ",\n"
1155 << " " << PM.ProcResourceDefs.size()+1 << ",\n"
1156 << " " << (SchedModels.schedClassEnd()
1157 - SchedModels.schedClassBegin()) << ",\n";
1159 OS << " nullptr, nullptr, 0, 0,"
1160 << " // No instruction-level machine model.\n";
1161 if (PM.hasItineraries())
1162 OS << " " << PM.ItinsDef->getName() << "\n";
1164 OS << " nullptr // No Itinerary\n";
1170 // EmitProcessorLookup - generate cpu name to itinerary lookup table.
1172 void SubtargetEmitter::EmitProcessorLookup(raw_ostream &OS) {
1173 // Gather and sort processor information
1174 std::vector<Record*> ProcessorList =
1175 Records.getAllDerivedDefinitions("Processor");
1176 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
1178 // Begin processor table
1180 OS << "// Sorted (by key) array of itineraries for CPU subtype.\n"
1181 << "extern const llvm::SubtargetInfoKV "
1182 << Target << "ProcSchedKV[] = {\n";
1184 // For each processor
1185 for (Record *Processor : ProcessorList) {
1186 StringRef Name = Processor->getValueAsString("Name");
1187 const std::string &ProcModelName =
1188 SchedModels.getModelForProc(Processor).ModelName;
1190 // Emit as { "cpu", procinit },
1191 OS << " { \"" << Name << "\", (const void *)&" << ProcModelName << " },\n";
1194 // End processor table
1199 // EmitSchedModel - Emits all scheduling model tables, folding common patterns.
1201 void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) {
1202 OS << "#ifdef DBGFIELD\n"
1203 << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n"
1205 << "#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)\n"
1206 << "#define DBGFIELD(x) x,\n"
1208 << "#define DBGFIELD(x)\n"
1211 if (SchedModels.hasItineraries()) {
1212 std::vector<std::vector<InstrItinerary>> ProcItinLists;
1213 // Emit the stage data
1214 EmitStageAndOperandCycleData(OS, ProcItinLists);
1215 EmitItineraries(OS, ProcItinLists);
1217 OS << "\n// ===============================================================\n"
1218 << "// Data tables for the new per-operand machine model.\n";
1220 SchedClassTables SchedTables;
1221 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
1222 GenSchedClassTables(ProcModel, SchedTables);
1224 EmitSchedClassTables(SchedTables, OS);
1226 // Emit the processor machine model
1227 EmitProcessorModels(OS);
1228 // Emit the processor lookup data
1229 EmitProcessorLookup(OS);
1231 OS << "\n#undef DBGFIELD";
1234 void SubtargetEmitter::EmitSchedModelHelpers(const std::string &ClassName,
1236 OS << "unsigned " << ClassName
1237 << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI,"
1238 << " const TargetSchedModel *SchedModel) const {\n";
1240 std::vector<Record*> Prologs = Records.getAllDerivedDefinitions("PredicateProlog");
1241 std::sort(Prologs.begin(), Prologs.end(), LessRecord());
1242 for (Record *P : Prologs) {
1243 OS << P->getValueAsString("Code") << '\n';
1245 IdxVec VariantClasses;
1246 for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) {
1247 if (SC.Transitions.empty())
1249 VariantClasses.push_back(SC.Index);
1251 if (!VariantClasses.empty()) {
1252 OS << " switch (SchedClass) {\n";
1253 for (unsigned VC : VariantClasses) {
1254 const CodeGenSchedClass &SC = SchedModels.getSchedClass(VC);
1255 OS << " case " << VC << ": // " << SC.Name << '\n';
1257 for (const CodeGenSchedTransition &T : SC.Transitions) {
1259 std::set_union(T.ProcIndices.begin(), T.ProcIndices.end(),
1260 ProcIndices.begin(), ProcIndices.end(),
1261 std::back_inserter(PI));
1262 ProcIndices.swap(PI);
1264 for (unsigned PI : ProcIndices) {
1267 OS << "if (SchedModel->getProcessorID() == " << PI << ") ";
1268 OS << "{ // " << (SchedModels.procModelBegin() + PI)->ModelName
1270 for (const CodeGenSchedTransition &T : SC.Transitions) {
1271 if (PI != 0 && !std::count(T.ProcIndices.begin(),
1272 T.ProcIndices.end(), PI)) {
1276 for (RecIter RI = T.PredTerm.begin(), RE = T.PredTerm.end();
1278 if (RI != T.PredTerm.begin())
1280 OS << "(" << (*RI)->getValueAsString("Predicate") << ")";
1283 << " return " << T.ToClassIdx << "; // "
1284 << SchedModels.getSchedClass(T.ToClassIdx).Name << '\n';
1290 if (SC.isInferred())
1291 OS << " return " << SC.Index << ";\n";
1296 OS << " report_fatal_error(\"Expected a variant SchedClass\");\n"
1297 << "} // " << ClassName << "::resolveSchedClass\n";
1300 void SubtargetEmitter::EmitHwModeCheck(const std::string &ClassName,
1302 const CodeGenHwModes &CGH = TGT.getHwModes();
1303 assert(CGH.getNumModeIds() > 0);
1304 if (CGH.getNumModeIds() == 1)
1307 OS << "unsigned " << ClassName << "::getHwMode() const {\n";
1308 for (unsigned M = 1, NumModes = CGH.getNumModeIds(); M != NumModes; ++M) {
1309 const HwMode &HM = CGH.getMode(M);
1310 OS << " if (checkFeatures(\"" << HM.Features
1311 << "\")) return " << M << ";\n";
1313 OS << " return 0;\n}\n";
1317 // ParseFeaturesFunction - Produces a subtarget specific function for parsing
1318 // the subtarget features string.
1320 void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS,
1321 unsigned NumFeatures,
1322 unsigned NumProcs) {
1323 std::vector<Record*> Features =
1324 Records.getAllDerivedDefinitions("SubtargetFeature");
1325 std::sort(Features.begin(), Features.end(), LessRecord());
1327 OS << "// ParseSubtargetFeatures - Parses features string setting specified\n"
1328 << "// subtarget options.\n"
1331 OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef FS) {\n"
1332 << " DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n"
1333 << " DEBUG(dbgs() << \"\\nCPU:\" << CPU << \"\\n\\n\");\n";
1335 if (Features.empty()) {
1340 OS << " InitMCProcessorInfo(CPU, FS);\n"
1341 << " const FeatureBitset& Bits = getFeatureBits();\n";
1343 for (Record *R : Features) {
1345 StringRef Instance = R->getName();
1346 StringRef Value = R->getValueAsString("Value");
1347 StringRef Attribute = R->getValueAsString("Attribute");
1349 if (Value=="true" || Value=="false")
1350 OS << " if (Bits[" << Target << "::"
1351 << Instance << "]) "
1352 << Attribute << " = " << Value << ";\n";
1354 OS << " if (Bits[" << Target << "::"
1355 << Instance << "] && "
1356 << Attribute << " < " << Value << ") "
1357 << Attribute << " = " << Value << ";\n";
1364 // SubtargetEmitter::run - Main subtarget enumeration emitter.
1366 void SubtargetEmitter::run(raw_ostream &OS) {
1367 emitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);
1369 OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n";
1370 OS << "#undef GET_SUBTARGETINFO_ENUM\n\n";
1372 OS << "namespace llvm {\n";
1374 OS << "} // end namespace llvm\n\n";
1375 OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n";
1377 OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n";
1378 OS << "#undef GET_SUBTARGETINFO_MC_DESC\n\n";
1380 OS << "namespace llvm {\n";
1382 OS << "namespace {\n";
1384 unsigned NumFeatures = FeatureKeyValues(OS);
1386 unsigned NumProcs = CPUKeyValues(OS);
1391 OS << "} // end anonymous namespace\n\n";
1394 // MCInstrInfo initialization routine.
1395 OS << "\nstatic inline MCSubtargetInfo *create" << Target
1396 << "MCSubtargetInfoImpl("
1397 << "const Triple &TT, StringRef CPU, StringRef FS) {\n";
1398 OS << " return new MCSubtargetInfo(TT, CPU, FS, ";
1400 OS << Target << "FeatureKV, ";
1404 OS << Target << "SubTypeKV, ";
1407 OS << '\n'; OS.indent(22);
1408 OS << Target << "ProcSchedKV, "
1409 << Target << "WriteProcResTable, "
1410 << Target << "WriteLatencyTable, "
1411 << Target << "ReadAdvanceTable, ";
1412 OS << '\n'; OS.indent(22);
1413 if (SchedModels.hasItineraries()) {
1414 OS << Target << "Stages, "
1415 << Target << "OperandCycles, "
1416 << Target << "ForwardingPaths";
1418 OS << "nullptr, nullptr, nullptr";
1421 OS << "} // end namespace llvm\n\n";
1423 OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n";
1425 OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n";
1426 OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n\n";
1428 OS << "#include \"llvm/Support/Debug.h\"\n";
1429 OS << "#include \"llvm/Support/raw_ostream.h\"\n\n";
1430 ParseFeaturesFunction(OS, NumFeatures, NumProcs);
1432 OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n";
1434 // Create a TargetSubtargetInfo subclass to hide the MC layer initialization.
1435 OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n";
1436 OS << "#undef GET_SUBTARGETINFO_HEADER\n\n";
1438 std::string ClassName = Target + "GenSubtargetInfo";
1439 OS << "namespace llvm {\n";
1440 OS << "class DFAPacketizer;\n";
1441 OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n"
1442 << " explicit " << ClassName << "(const Triple &TT, StringRef CPU, "
1443 << "StringRef FS);\n"
1445 << " unsigned resolveSchedClass(unsigned SchedClass, "
1446 << " const MachineInstr *DefMI,"
1447 << " const TargetSchedModel *SchedModel) const override;\n"
1448 << " DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)"
1450 if (TGT.getHwModes().getNumModeIds() > 1)
1451 OS << " unsigned getHwMode() const override;\n";
1453 << "} // end namespace llvm\n\n";
1455 OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n";
1457 OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n";
1458 OS << "#undef GET_SUBTARGETINFO_CTOR\n\n";
1460 OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n\n";
1461 OS << "namespace llvm {\n";
1462 OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n";
1463 OS << "extern const llvm::SubtargetFeatureKV " << Target << "SubTypeKV[];\n";
1464 OS << "extern const llvm::SubtargetInfoKV " << Target << "ProcSchedKV[];\n";
1465 OS << "extern const llvm::MCWriteProcResEntry "
1466 << Target << "WriteProcResTable[];\n";
1467 OS << "extern const llvm::MCWriteLatencyEntry "
1468 << Target << "WriteLatencyTable[];\n";
1469 OS << "extern const llvm::MCReadAdvanceEntry "
1470 << Target << "ReadAdvanceTable[];\n";
1472 if (SchedModels.hasItineraries()) {
1473 OS << "extern const llvm::InstrStage " << Target << "Stages[];\n";
1474 OS << "extern const unsigned " << Target << "OperandCycles[];\n";
1475 OS << "extern const unsigned " << Target << "ForwardingPaths[];\n";
1478 OS << ClassName << "::" << ClassName << "(const Triple &TT, StringRef CPU, "
1479 << "StringRef FS)\n"
1480 << " : TargetSubtargetInfo(TT, CPU, FS, ";
1482 OS << "makeArrayRef(" << Target << "FeatureKV, " << NumFeatures << "), ";
1486 OS << "makeArrayRef(" << Target << "SubTypeKV, " << NumProcs << "), ";
1489 OS << '\n'; OS.indent(24);
1490 OS << Target << "ProcSchedKV, "
1491 << Target << "WriteProcResTable, "
1492 << Target << "WriteLatencyTable, "
1493 << Target << "ReadAdvanceTable, ";
1494 OS << '\n'; OS.indent(24);
1495 if (SchedModels.hasItineraries()) {
1496 OS << Target << "Stages, "
1497 << Target << "OperandCycles, "
1498 << Target << "ForwardingPaths";
1500 OS << "nullptr, nullptr, nullptr";
1503 EmitSchedModelHelpers(ClassName, OS);
1504 EmitHwModeCheck(ClassName, OS);
1506 OS << "} // end namespace llvm\n\n";
1508 OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n";
1513 void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) {
1514 CodeGenTarget CGTarget(RK);
1515 SubtargetEmitter(RK, CGTarget).run(OS);
1518 } // end namespace llvm