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