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