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 void SubtargetEmitter::EmitExtraProcessorInfo(const CodeGenProcModel &ProcModel,
691                                               raw_ostream &OS) {
692   // Generate a table of register file descriptors (one entry per each user
693   // defined register file), and a table of register costs.
694   unsigned NumCostEntries = EmitRegisterFileTables(ProcModel, OS);
695 
696   // Now generate a table for the extra processor info.
697   OS << "\nstatic const llvm::MCExtraProcessorInfo " << ProcModel.ModelName
698      << "ExtraInfo = {\n  ";
699 
700   // Add information related to the retire control unit.
701   EmitRetireControlUnitInfo(ProcModel, OS);
702 
703   // Add information related to the register files (i.e. where to find register
704   // file descriptors and register costs).
705   EmitRegisterFileInfo(ProcModel, ProcModel.RegisterFiles.size(),
706                        NumCostEntries, OS);
707 
708   OS << "};\n";
709 }
710 
711 void SubtargetEmitter::EmitProcessorResources(const CodeGenProcModel &ProcModel,
712                                               raw_ostream &OS) {
713   EmitProcessorResourceSubUnits(ProcModel, OS);
714 
715   OS << "\n// {Name, NumUnits, SuperIdx, IsBuffered, SubUnitsIdxBegin}\n";
716   OS << "static const llvm::MCProcResourceDesc " << ProcModel.ModelName
717      << "ProcResources"
718      << "[] = {\n"
719      << "  {\"InvalidUnit\", 0, 0, 0, 0},\n";
720 
721   unsigned SubUnitsOffset = 1;
722   for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) {
723     Record *PRDef = ProcModel.ProcResourceDefs[i];
724 
725     Record *SuperDef = nullptr;
726     unsigned SuperIdx = 0;
727     unsigned NumUnits = 0;
728     const unsigned SubUnitsBeginOffset = SubUnitsOffset;
729     int BufferSize = PRDef->getValueAsInt("BufferSize");
730     if (PRDef->isSubClassOf("ProcResGroup")) {
731       RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources");
732       for (Record *RU : ResUnits) {
733         NumUnits += RU->getValueAsInt("NumUnits");
734         SubUnitsOffset += RU->getValueAsInt("NumUnits");
735       }
736     }
737     else {
738       // Find the SuperIdx
739       if (PRDef->getValueInit("Super")->isComplete()) {
740         SuperDef =
741             SchedModels.findProcResUnits(PRDef->getValueAsDef("Super"),
742                                          ProcModel, PRDef->getLoc());
743         SuperIdx = ProcModel.getProcResourceIdx(SuperDef);
744       }
745       NumUnits = PRDef->getValueAsInt("NumUnits");
746     }
747     // Emit the ProcResourceDesc
748     OS << "  {\"" << PRDef->getName() << "\", ";
749     if (PRDef->getName().size() < 15)
750       OS.indent(15 - PRDef->getName().size());
751     OS << NumUnits << ", " << SuperIdx << ", " << BufferSize << ", ";
752     if (SubUnitsBeginOffset != SubUnitsOffset) {
753       OS << ProcModel.ModelName << "ProcResourceSubUnits + "
754          << SubUnitsBeginOffset;
755     } else {
756       OS << "nullptr";
757     }
758     OS << "}, // #" << i+1;
759     if (SuperDef)
760       OS << ", Super=" << SuperDef->getName();
761     OS << "\n";
762   }
763   OS << "};\n";
764 }
765 
766 // Find the WriteRes Record that defines processor resources for this
767 // SchedWrite.
768 Record *SubtargetEmitter::FindWriteResources(
769   const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) {
770 
771   // Check if the SchedWrite is already subtarget-specific and directly
772   // specifies a set of processor resources.
773   if (SchedWrite.TheDef->isSubClassOf("SchedWriteRes"))
774     return SchedWrite.TheDef;
775 
776   Record *AliasDef = nullptr;
777   for (Record *A : SchedWrite.Aliases) {
778     const CodeGenSchedRW &AliasRW =
779       SchedModels.getSchedRW(A->getValueAsDef("AliasRW"));
780     if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
781       Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
782       if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
783         continue;
784     }
785     if (AliasDef)
786       PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
787                     "defined for processor " + ProcModel.ModelName +
788                     " Ensure only one SchedAlias exists per RW.");
789     AliasDef = AliasRW.TheDef;
790   }
791   if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes"))
792     return AliasDef;
793 
794   // Check this processor's list of write resources.
795   Record *ResDef = nullptr;
796   for (Record *WR : ProcModel.WriteResDefs) {
797     if (!WR->isSubClassOf("WriteRes"))
798       continue;
799     if (AliasDef == WR->getValueAsDef("WriteType")
800         || SchedWrite.TheDef == WR->getValueAsDef("WriteType")) {
801       if (ResDef) {
802         PrintFatalError(WR->getLoc(), "Resources are defined for both "
803                       "SchedWrite and its alias on processor " +
804                       ProcModel.ModelName);
805       }
806       ResDef = WR;
807     }
808   }
809   // TODO: If ProcModel has a base model (previous generation processor),
810   // then call FindWriteResources recursively with that model here.
811   if (!ResDef) {
812     PrintFatalError(ProcModel.ModelDef->getLoc(),
813                     Twine("Processor does not define resources for ") +
814                     SchedWrite.TheDef->getName());
815   }
816   return ResDef;
817 }
818 
819 /// Find the ReadAdvance record for the given SchedRead on this processor or
820 /// return NULL.
821 Record *SubtargetEmitter::FindReadAdvance(const CodeGenSchedRW &SchedRead,
822                                           const CodeGenProcModel &ProcModel) {
823   // Check for SchedReads that directly specify a ReadAdvance.
824   if (SchedRead.TheDef->isSubClassOf("SchedReadAdvance"))
825     return SchedRead.TheDef;
826 
827   // Check this processor's list of aliases for SchedRead.
828   Record *AliasDef = nullptr;
829   for (Record *A : SchedRead.Aliases) {
830     const CodeGenSchedRW &AliasRW =
831       SchedModels.getSchedRW(A->getValueAsDef("AliasRW"));
832     if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
833       Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
834       if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
835         continue;
836     }
837     if (AliasDef)
838       PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
839                     "defined for processor " + ProcModel.ModelName +
840                     " Ensure only one SchedAlias exists per RW.");
841     AliasDef = AliasRW.TheDef;
842   }
843   if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance"))
844     return AliasDef;
845 
846   // Check this processor's ReadAdvanceList.
847   Record *ResDef = nullptr;
848   for (Record *RA : ProcModel.ReadAdvanceDefs) {
849     if (!RA->isSubClassOf("ReadAdvance"))
850       continue;
851     if (AliasDef == RA->getValueAsDef("ReadType")
852         || SchedRead.TheDef == RA->getValueAsDef("ReadType")) {
853       if (ResDef) {
854         PrintFatalError(RA->getLoc(), "Resources are defined for both "
855                       "SchedRead and its alias on processor " +
856                       ProcModel.ModelName);
857       }
858       ResDef = RA;
859     }
860   }
861   // TODO: If ProcModel has a base model (previous generation processor),
862   // then call FindReadAdvance recursively with that model here.
863   if (!ResDef && SchedRead.TheDef->getName() != "ReadDefault") {
864     PrintFatalError(ProcModel.ModelDef->getLoc(),
865                     Twine("Processor does not define resources for ") +
866                     SchedRead.TheDef->getName());
867   }
868   return ResDef;
869 }
870 
871 // Expand an explicit list of processor resources into a full list of implied
872 // resource groups and super resources that cover them.
873 void SubtargetEmitter::ExpandProcResources(RecVec &PRVec,
874                                            std::vector<int64_t> &Cycles,
875                                            const CodeGenProcModel &PM) {
876   // Default to 1 resource cycle.
877   Cycles.resize(PRVec.size(), 1);
878   for (unsigned i = 0, e = PRVec.size(); i != e; ++i) {
879     Record *PRDef = PRVec[i];
880     RecVec SubResources;
881     if (PRDef->isSubClassOf("ProcResGroup"))
882       SubResources = PRDef->getValueAsListOfDefs("Resources");
883     else {
884       SubResources.push_back(PRDef);
885       PRDef = SchedModels.findProcResUnits(PRDef, PM, PRDef->getLoc());
886       for (Record *SubDef = PRDef;
887            SubDef->getValueInit("Super")->isComplete();) {
888         if (SubDef->isSubClassOf("ProcResGroup")) {
889           // Disallow this for simplicitly.
890           PrintFatalError(SubDef->getLoc(), "Processor resource group "
891                           " cannot be a super resources.");
892         }
893         Record *SuperDef =
894             SchedModels.findProcResUnits(SubDef->getValueAsDef("Super"), PM,
895                                          SubDef->getLoc());
896         PRVec.push_back(SuperDef);
897         Cycles.push_back(Cycles[i]);
898         SubDef = SuperDef;
899       }
900     }
901     for (Record *PR : PM.ProcResourceDefs) {
902       if (PR == PRDef || !PR->isSubClassOf("ProcResGroup"))
903         continue;
904       RecVec SuperResources = PR->getValueAsListOfDefs("Resources");
905       RecIter SubI = SubResources.begin(), SubE = SubResources.end();
906       for( ; SubI != SubE; ++SubI) {
907         if (!is_contained(SuperResources, *SubI)) {
908           break;
909         }
910       }
911       if (SubI == SubE) {
912         PRVec.push_back(PR);
913         Cycles.push_back(Cycles[i]);
914       }
915     }
916   }
917 }
918 
919 // Generate the SchedClass table for this processor and update global
920 // tables. Must be called for each processor in order.
921 void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel,
922                                            SchedClassTables &SchedTables) {
923   SchedTables.ProcSchedClasses.resize(SchedTables.ProcSchedClasses.size() + 1);
924   if (!ProcModel.hasInstrSchedModel())
925     return;
926 
927   std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back();
928   DEBUG(dbgs() << "\n+++ SCHED CLASSES (GenSchedClassTables) +++\n");
929   for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) {
930     DEBUG(SC.dump(&SchedModels));
931 
932     SCTab.resize(SCTab.size() + 1);
933     MCSchedClassDesc &SCDesc = SCTab.back();
934     // SCDesc.Name is guarded by NDEBUG
935     SCDesc.NumMicroOps = 0;
936     SCDesc.BeginGroup = false;
937     SCDesc.EndGroup = false;
938     SCDesc.WriteProcResIdx = 0;
939     SCDesc.WriteLatencyIdx = 0;
940     SCDesc.ReadAdvanceIdx = 0;
941 
942     // A Variant SchedClass has no resources of its own.
943     bool HasVariants = false;
944     for (const CodeGenSchedTransition &CGT :
945            make_range(SC.Transitions.begin(), SC.Transitions.end())) {
946       if (CGT.ProcIndices[0] == 0 ||
947           is_contained(CGT.ProcIndices, ProcModel.Index)) {
948         HasVariants = true;
949         break;
950       }
951     }
952     if (HasVariants) {
953       SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps;
954       continue;
955     }
956 
957     // Determine if the SchedClass is actually reachable on this processor. If
958     // not don't try to locate the processor resources, it will fail.
959     // If ProcIndices contains 0, this class applies to all processors.
960     assert(!SC.ProcIndices.empty() && "expect at least one procidx");
961     if (SC.ProcIndices[0] != 0) {
962       if (!is_contained(SC.ProcIndices, ProcModel.Index))
963         continue;
964     }
965     IdxVec Writes = SC.Writes;
966     IdxVec Reads = SC.Reads;
967     if (!SC.InstRWs.empty()) {
968       // This class has a default ReadWrite list which can be overridden by
969       // InstRW definitions.
970       Record *RWDef = nullptr;
971       for (Record *RW : SC.InstRWs) {
972         Record *RWModelDef = RW->getValueAsDef("SchedModel");
973         if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) {
974           RWDef = RW;
975           break;
976         }
977       }
978       if (RWDef) {
979         Writes.clear();
980         Reads.clear();
981         SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
982                             Writes, Reads);
983       }
984     }
985     if (Writes.empty()) {
986       // Check this processor's itinerary class resources.
987       for (Record *I : ProcModel.ItinRWDefs) {
988         RecVec Matched = I->getValueAsListOfDefs("MatchedItinClasses");
989         if (is_contained(Matched, SC.ItinClassDef)) {
990           SchedModels.findRWs(I->getValueAsListOfDefs("OperandReadWrites"),
991                               Writes, Reads);
992           break;
993         }
994       }
995       if (Writes.empty()) {
996         DEBUG(dbgs() << ProcModel.ModelName
997               << " does not have resources for class " << SC.Name << '\n');
998       }
999     }
1000     // Sum resources across all operand writes.
1001     std::vector<MCWriteProcResEntry> WriteProcResources;
1002     std::vector<MCWriteLatencyEntry> WriteLatencies;
1003     std::vector<std::string> WriterNames;
1004     std::vector<MCReadAdvanceEntry> ReadAdvanceEntries;
1005     for (unsigned W : Writes) {
1006       IdxVec WriteSeq;
1007       SchedModels.expandRWSeqForProc(W, WriteSeq, /*IsRead=*/false,
1008                                      ProcModel);
1009 
1010       // For each operand, create a latency entry.
1011       MCWriteLatencyEntry WLEntry;
1012       WLEntry.Cycles = 0;
1013       unsigned WriteID = WriteSeq.back();
1014       WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name);
1015       // If this Write is not referenced by a ReadAdvance, don't distinguish it
1016       // from other WriteLatency entries.
1017       if (!SchedModels.hasReadOfWrite(
1018             SchedModels.getSchedWrite(WriteID).TheDef)) {
1019         WriteID = 0;
1020       }
1021       WLEntry.WriteResourceID = WriteID;
1022 
1023       for (unsigned WS : WriteSeq) {
1024 
1025         Record *WriteRes =
1026           FindWriteResources(SchedModels.getSchedWrite(WS), ProcModel);
1027 
1028         // Mark the parent class as invalid for unsupported write types.
1029         if (WriteRes->getValueAsBit("Unsupported")) {
1030           SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
1031           break;
1032         }
1033         WLEntry.Cycles += WriteRes->getValueAsInt("Latency");
1034         SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps");
1035         SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup");
1036         SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup");
1037         SCDesc.BeginGroup |= WriteRes->getValueAsBit("SingleIssue");
1038         SCDesc.EndGroup |= WriteRes->getValueAsBit("SingleIssue");
1039 
1040         // Create an entry for each ProcResource listed in WriteRes.
1041         RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources");
1042         std::vector<int64_t> Cycles =
1043           WriteRes->getValueAsListOfInts("ResourceCycles");
1044 
1045         ExpandProcResources(PRVec, Cycles, ProcModel);
1046 
1047         for (unsigned PRIdx = 0, PREnd = PRVec.size();
1048              PRIdx != PREnd; ++PRIdx) {
1049           MCWriteProcResEntry WPREntry;
1050           WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]);
1051           assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx");
1052           WPREntry.Cycles = Cycles[PRIdx];
1053           // If this resource is already used in this sequence, add the current
1054           // entry's cycles so that the same resource appears to be used
1055           // serially, rather than multiple parallel uses. This is important for
1056           // in-order machine where the resource consumption is a hazard.
1057           unsigned WPRIdx = 0, WPREnd = WriteProcResources.size();
1058           for( ; WPRIdx != WPREnd; ++WPRIdx) {
1059             if (WriteProcResources[WPRIdx].ProcResourceIdx
1060                 == WPREntry.ProcResourceIdx) {
1061               WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles;
1062               break;
1063             }
1064           }
1065           if (WPRIdx == WPREnd)
1066             WriteProcResources.push_back(WPREntry);
1067         }
1068       }
1069       WriteLatencies.push_back(WLEntry);
1070     }
1071     // Create an entry for each operand Read in this SchedClass.
1072     // Entries must be sorted first by UseIdx then by WriteResourceID.
1073     for (unsigned UseIdx = 0, EndIdx = Reads.size();
1074          UseIdx != EndIdx; ++UseIdx) {
1075       Record *ReadAdvance =
1076         FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel);
1077       if (!ReadAdvance)
1078         continue;
1079 
1080       // Mark the parent class as invalid for unsupported write types.
1081       if (ReadAdvance->getValueAsBit("Unsupported")) {
1082         SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
1083         break;
1084       }
1085       RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites");
1086       IdxVec WriteIDs;
1087       if (ValidWrites.empty())
1088         WriteIDs.push_back(0);
1089       else {
1090         for (Record *VW : ValidWrites) {
1091           WriteIDs.push_back(SchedModels.getSchedRWIdx(VW, /*IsRead=*/false));
1092         }
1093       }
1094       llvm::sort(WriteIDs.begin(), WriteIDs.end());
1095       for(unsigned W : WriteIDs) {
1096         MCReadAdvanceEntry RAEntry;
1097         RAEntry.UseIdx = UseIdx;
1098         RAEntry.WriteResourceID = W;
1099         RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles");
1100         ReadAdvanceEntries.push_back(RAEntry);
1101       }
1102     }
1103     if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) {
1104       WriteProcResources.clear();
1105       WriteLatencies.clear();
1106       ReadAdvanceEntries.clear();
1107     }
1108     // Add the information for this SchedClass to the global tables using basic
1109     // compression.
1110     //
1111     // WritePrecRes entries are sorted by ProcResIdx.
1112     llvm::sort(WriteProcResources.begin(), WriteProcResources.end(),
1113                LessWriteProcResources());
1114 
1115     SCDesc.NumWriteProcResEntries = WriteProcResources.size();
1116     std::vector<MCWriteProcResEntry>::iterator WPRPos =
1117       std::search(SchedTables.WriteProcResources.begin(),
1118                   SchedTables.WriteProcResources.end(),
1119                   WriteProcResources.begin(), WriteProcResources.end());
1120     if (WPRPos != SchedTables.WriteProcResources.end())
1121       SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin();
1122     else {
1123       SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size();
1124       SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(),
1125                                             WriteProcResources.end());
1126     }
1127     // Latency entries must remain in operand order.
1128     SCDesc.NumWriteLatencyEntries = WriteLatencies.size();
1129     std::vector<MCWriteLatencyEntry>::iterator WLPos =
1130       std::search(SchedTables.WriteLatencies.begin(),
1131                   SchedTables.WriteLatencies.end(),
1132                   WriteLatencies.begin(), WriteLatencies.end());
1133     if (WLPos != SchedTables.WriteLatencies.end()) {
1134       unsigned idx = WLPos - SchedTables.WriteLatencies.begin();
1135       SCDesc.WriteLatencyIdx = idx;
1136       for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i)
1137         if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) ==
1138             std::string::npos) {
1139           SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i];
1140         }
1141     }
1142     else {
1143       SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size();
1144       SchedTables.WriteLatencies.insert(SchedTables.WriteLatencies.end(),
1145                                         WriteLatencies.begin(),
1146                                         WriteLatencies.end());
1147       SchedTables.WriterNames.insert(SchedTables.WriterNames.end(),
1148                                      WriterNames.begin(), WriterNames.end());
1149     }
1150     // ReadAdvanceEntries must remain in operand order.
1151     SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size();
1152     std::vector<MCReadAdvanceEntry>::iterator RAPos =
1153       std::search(SchedTables.ReadAdvanceEntries.begin(),
1154                   SchedTables.ReadAdvanceEntries.end(),
1155                   ReadAdvanceEntries.begin(), ReadAdvanceEntries.end());
1156     if (RAPos != SchedTables.ReadAdvanceEntries.end())
1157       SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin();
1158     else {
1159       SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size();
1160       SchedTables.ReadAdvanceEntries.insert(RAPos, ReadAdvanceEntries.begin(),
1161                                             ReadAdvanceEntries.end());
1162     }
1163   }
1164 }
1165 
1166 // Emit SchedClass tables for all processors and associated global tables.
1167 void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables,
1168                                             raw_ostream &OS) {
1169   // Emit global WriteProcResTable.
1170   OS << "\n// {ProcResourceIdx, Cycles}\n"
1171      << "extern const llvm::MCWriteProcResEntry "
1172      << Target << "WriteProcResTable[] = {\n"
1173      << "  { 0,  0}, // Invalid\n";
1174   for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size();
1175        WPRIdx != WPREnd; ++WPRIdx) {
1176     MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx];
1177     OS << "  {" << format("%2d", WPREntry.ProcResourceIdx) << ", "
1178        << format("%2d", WPREntry.Cycles) << "}";
1179     if (WPRIdx + 1 < WPREnd)
1180       OS << ',';
1181     OS << " // #" << WPRIdx << '\n';
1182   }
1183   OS << "}; // " << Target << "WriteProcResTable\n";
1184 
1185   // Emit global WriteLatencyTable.
1186   OS << "\n// {Cycles, WriteResourceID}\n"
1187      << "extern const llvm::MCWriteLatencyEntry "
1188      << Target << "WriteLatencyTable[] = {\n"
1189      << "  { 0,  0}, // Invalid\n";
1190   for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size();
1191        WLIdx != WLEnd; ++WLIdx) {
1192     MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx];
1193     OS << "  {" << format("%2d", WLEntry.Cycles) << ", "
1194        << format("%2d", WLEntry.WriteResourceID) << "}";
1195     if (WLIdx + 1 < WLEnd)
1196       OS << ',';
1197     OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n';
1198   }
1199   OS << "}; // " << Target << "WriteLatencyTable\n";
1200 
1201   // Emit global ReadAdvanceTable.
1202   OS << "\n// {UseIdx, WriteResourceID, Cycles}\n"
1203      << "extern const llvm::MCReadAdvanceEntry "
1204      << Target << "ReadAdvanceTable[] = {\n"
1205      << "  {0,  0,  0}, // Invalid\n";
1206   for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size();
1207        RAIdx != RAEnd; ++RAIdx) {
1208     MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx];
1209     OS << "  {" << RAEntry.UseIdx << ", "
1210        << format("%2d", RAEntry.WriteResourceID) << ", "
1211        << format("%2d", RAEntry.Cycles) << "}";
1212     if (RAIdx + 1 < RAEnd)
1213       OS << ',';
1214     OS << " // #" << RAIdx << '\n';
1215   }
1216   OS << "}; // " << Target << "ReadAdvanceTable\n";
1217 
1218   // Emit a SchedClass table for each processor.
1219   for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
1220          PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
1221     if (!PI->hasInstrSchedModel())
1222       continue;
1223 
1224     std::vector<MCSchedClassDesc> &SCTab =
1225       SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())];
1226 
1227     OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup,"
1228        << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n";
1229     OS << "static const llvm::MCSchedClassDesc "
1230        << PI->ModelName << "SchedClasses[] = {\n";
1231 
1232     // The first class is always invalid. We no way to distinguish it except by
1233     // name and position.
1234     assert(SchedModels.getSchedClass(0).Name == "NoInstrModel"
1235            && "invalid class not first");
1236     OS << "  {DBGFIELD(\"InvalidSchedClass\")  "
1237        << MCSchedClassDesc::InvalidNumMicroOps
1238        << ", false, false,  0, 0,  0, 0,  0, 0},\n";
1239 
1240     for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) {
1241       MCSchedClassDesc &MCDesc = SCTab[SCIdx];
1242       const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx);
1243       OS << "  {DBGFIELD(\"" << SchedClass.Name << "\") ";
1244       if (SchedClass.Name.size() < 18)
1245         OS.indent(18 - SchedClass.Name.size());
1246       OS << MCDesc.NumMicroOps
1247          << ", " << ( MCDesc.BeginGroup ? "true" : "false" )
1248          << ", " << ( MCDesc.EndGroup ? "true" : "false" )
1249          << ", " << format("%2d", MCDesc.WriteProcResIdx)
1250          << ", " << MCDesc.NumWriteProcResEntries
1251          << ", " << format("%2d", MCDesc.WriteLatencyIdx)
1252          << ", " << MCDesc.NumWriteLatencyEntries
1253          << ", " << format("%2d", MCDesc.ReadAdvanceIdx)
1254          << ", " << MCDesc.NumReadAdvanceEntries
1255          << "}, // #" << SCIdx << '\n';
1256     }
1257     OS << "}; // " << PI->ModelName << "SchedClasses\n";
1258   }
1259 }
1260 
1261 void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) {
1262   // For each processor model.
1263   for (const CodeGenProcModel &PM : SchedModels.procModels()) {
1264     // Emit extra processor info if available.
1265     if (PM.hasExtraProcessorInfo())
1266       EmitExtraProcessorInfo(PM, OS);
1267     // Emit processor resource table.
1268     if (PM.hasInstrSchedModel())
1269       EmitProcessorResources(PM, OS);
1270     else if(!PM.ProcResourceDefs.empty())
1271       PrintFatalError(PM.ModelDef->getLoc(), "SchedMachineModel defines "
1272                     "ProcResources without defining WriteRes SchedWriteRes");
1273 
1274     // Begin processor itinerary properties
1275     OS << "\n";
1276     OS << "static const llvm::MCSchedModel " << PM.ModelName << " = {\n";
1277     EmitProcessorProp(OS, PM.ModelDef, "IssueWidth", ',');
1278     EmitProcessorProp(OS, PM.ModelDef, "MicroOpBufferSize", ',');
1279     EmitProcessorProp(OS, PM.ModelDef, "LoopMicroOpBufferSize", ',');
1280     EmitProcessorProp(OS, PM.ModelDef, "LoadLatency", ',');
1281     EmitProcessorProp(OS, PM.ModelDef, "HighLatency", ',');
1282     EmitProcessorProp(OS, PM.ModelDef, "MispredictPenalty", ',');
1283 
1284     bool PostRAScheduler =
1285       (PM.ModelDef ? PM.ModelDef->getValueAsBit("PostRAScheduler") : false);
1286 
1287     OS << "  " << (PostRAScheduler ? "true" : "false")  << ", // "
1288        << "PostRAScheduler\n";
1289 
1290     bool CompleteModel =
1291       (PM.ModelDef ? PM.ModelDef->getValueAsBit("CompleteModel") : false);
1292 
1293     OS << "  " << (CompleteModel ? "true" : "false") << ", // "
1294        << "CompleteModel\n";
1295 
1296     OS << "  " << PM.Index << ", // Processor ID\n";
1297     if (PM.hasInstrSchedModel())
1298       OS << "  " << PM.ModelName << "ProcResources" << ",\n"
1299          << "  " << PM.ModelName << "SchedClasses" << ",\n"
1300          << "  " << PM.ProcResourceDefs.size()+1 << ",\n"
1301          << "  " << (SchedModels.schedClassEnd()
1302                      - SchedModels.schedClassBegin()) << ",\n";
1303     else
1304       OS << "  nullptr, nullptr, 0, 0,"
1305          << " // No instruction-level machine model.\n";
1306     if (PM.hasItineraries())
1307       OS << "  " << PM.ItinsDef->getName() << ",\n";
1308     else
1309       OS << "  nullptr, // No Itinerary\n";
1310     if (PM.hasExtraProcessorInfo())
1311       OS << "  &" << PM.ModelName << "ExtraInfo\n";
1312     else
1313       OS << "  nullptr  // No extra processor descriptor\n";
1314     OS << "};\n";
1315   }
1316 }
1317 
1318 //
1319 // EmitProcessorLookup - generate cpu name to itinerary lookup table.
1320 //
1321 void SubtargetEmitter::EmitProcessorLookup(raw_ostream &OS) {
1322   // Gather and sort processor information
1323   std::vector<Record*> ProcessorList =
1324                           Records.getAllDerivedDefinitions("Processor");
1325   llvm::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
1326 
1327   // Begin processor table
1328   OS << "\n";
1329   OS << "// Sorted (by key) array of itineraries for CPU subtype.\n"
1330      << "extern const llvm::SubtargetInfoKV "
1331      << Target << "ProcSchedKV[] = {\n";
1332 
1333   // For each processor
1334   for (Record *Processor : ProcessorList) {
1335     StringRef Name = Processor->getValueAsString("Name");
1336     const std::string &ProcModelName =
1337       SchedModels.getModelForProc(Processor).ModelName;
1338 
1339     // Emit as { "cpu", procinit },
1340     OS << "  { \"" << Name << "\", (const void *)&" << ProcModelName << " },\n";
1341   }
1342 
1343   // End processor table
1344   OS << "};\n";
1345 }
1346 
1347 //
1348 // EmitSchedModel - Emits all scheduling model tables, folding common patterns.
1349 //
1350 void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) {
1351   OS << "#ifdef DBGFIELD\n"
1352      << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n"
1353      << "#endif\n"
1354      << "#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)\n"
1355      << "#define DBGFIELD(x) x,\n"
1356      << "#else\n"
1357      << "#define DBGFIELD(x)\n"
1358      << "#endif\n";
1359 
1360   if (SchedModels.hasItineraries()) {
1361     std::vector<std::vector<InstrItinerary>> ProcItinLists;
1362     // Emit the stage data
1363     EmitStageAndOperandCycleData(OS, ProcItinLists);
1364     EmitItineraries(OS, ProcItinLists);
1365   }
1366   OS << "\n// ===============================================================\n"
1367      << "// Data tables for the new per-operand machine model.\n";
1368 
1369   SchedClassTables SchedTables;
1370   for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
1371     GenSchedClassTables(ProcModel, SchedTables);
1372   }
1373   EmitSchedClassTables(SchedTables, OS);
1374 
1375   // Emit the processor machine model
1376   EmitProcessorModels(OS);
1377   // Emit the processor lookup data
1378   EmitProcessorLookup(OS);
1379 
1380   OS << "\n#undef DBGFIELD";
1381 }
1382 
1383 void SubtargetEmitter::EmitSchedModelHelpers(const std::string &ClassName,
1384                                              raw_ostream &OS) {
1385   OS << "unsigned " << ClassName
1386      << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI,"
1387      << " const TargetSchedModel *SchedModel) const {\n";
1388 
1389   std::vector<Record*> Prologs = Records.getAllDerivedDefinitions("PredicateProlog");
1390   llvm::sort(Prologs.begin(), Prologs.end(), LessRecord());
1391   for (Record *P : Prologs) {
1392     OS << P->getValueAsString("Code") << '\n';
1393   }
1394   IdxVec VariantClasses;
1395   for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) {
1396     if (SC.Transitions.empty())
1397       continue;
1398     VariantClasses.push_back(SC.Index);
1399   }
1400   if (!VariantClasses.empty()) {
1401     OS << "  switch (SchedClass) {\n";
1402     for (unsigned VC : VariantClasses) {
1403       const CodeGenSchedClass &SC = SchedModels.getSchedClass(VC);
1404       OS << "  case " << VC << ": // " << SC.Name << '\n';
1405       IdxVec ProcIndices;
1406       for (const CodeGenSchedTransition &T : SC.Transitions) {
1407         IdxVec PI;
1408         std::set_union(T.ProcIndices.begin(), T.ProcIndices.end(),
1409                        ProcIndices.begin(), ProcIndices.end(),
1410                        std::back_inserter(PI));
1411         ProcIndices.swap(PI);
1412       }
1413       for (unsigned PI : ProcIndices) {
1414         OS << "    ";
1415         if (PI != 0)
1416           OS << "if (SchedModel->getProcessorID() == " << PI << ") ";
1417         OS << "{ // " << (SchedModels.procModelBegin() + PI)->ModelName
1418            << '\n';
1419         for (const CodeGenSchedTransition &T : SC.Transitions) {
1420           if (PI != 0 && !std::count(T.ProcIndices.begin(),
1421                                      T.ProcIndices.end(), PI)) {
1422               continue;
1423           }
1424           OS << "      if (";
1425           for (RecIter RI = T.PredTerm.begin(), RE = T.PredTerm.end();
1426                RI != RE; ++RI) {
1427             if (RI != T.PredTerm.begin())
1428               OS << "\n          && ";
1429             OS << "(" << (*RI)->getValueAsString("Predicate") << ")";
1430           }
1431           OS << ")\n"
1432              << "        return " << T.ToClassIdx << "; // "
1433              << SchedModels.getSchedClass(T.ToClassIdx).Name << '\n';
1434         }
1435         OS << "    }\n";
1436         if (PI == 0)
1437           break;
1438       }
1439       if (SC.isInferred())
1440         OS << "    return " << SC.Index << ";\n";
1441       OS << "    break;\n";
1442     }
1443     OS << "  };\n";
1444   }
1445   OS << "  report_fatal_error(\"Expected a variant SchedClass\");\n"
1446      << "} // " << ClassName << "::resolveSchedClass\n";
1447 }
1448 
1449 void SubtargetEmitter::EmitHwModeCheck(const std::string &ClassName,
1450                                        raw_ostream &OS) {
1451   const CodeGenHwModes &CGH = TGT.getHwModes();
1452   assert(CGH.getNumModeIds() > 0);
1453   if (CGH.getNumModeIds() == 1)
1454     return;
1455 
1456   OS << "unsigned " << ClassName << "::getHwMode() const {\n";
1457   for (unsigned M = 1, NumModes = CGH.getNumModeIds(); M != NumModes; ++M) {
1458     const HwMode &HM = CGH.getMode(M);
1459     OS << "  if (checkFeatures(\"" << HM.Features
1460        << "\")) return " << M << ";\n";
1461   }
1462   OS << "  return 0;\n}\n";
1463 }
1464 
1465 //
1466 // ParseFeaturesFunction - Produces a subtarget specific function for parsing
1467 // the subtarget features string.
1468 //
1469 void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS,
1470                                              unsigned NumFeatures,
1471                                              unsigned NumProcs) {
1472   std::vector<Record*> Features =
1473                        Records.getAllDerivedDefinitions("SubtargetFeature");
1474   llvm::sort(Features.begin(), Features.end(), LessRecord());
1475 
1476   OS << "// ParseSubtargetFeatures - Parses features string setting specified\n"
1477      << "// subtarget options.\n"
1478      << "void llvm::";
1479   OS << Target;
1480   OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef FS) {\n"
1481      << "  DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n"
1482      << "  DEBUG(dbgs() << \"\\nCPU:\" << CPU << \"\\n\\n\");\n";
1483 
1484   if (Features.empty()) {
1485     OS << "}\n";
1486     return;
1487   }
1488 
1489   OS << "  InitMCProcessorInfo(CPU, FS);\n"
1490      << "  const FeatureBitset& Bits = getFeatureBits();\n";
1491 
1492   for (Record *R : Features) {
1493     // Next record
1494     StringRef Instance = R->getName();
1495     StringRef Value = R->getValueAsString("Value");
1496     StringRef Attribute = R->getValueAsString("Attribute");
1497 
1498     if (Value=="true" || Value=="false")
1499       OS << "  if (Bits[" << Target << "::"
1500          << Instance << "]) "
1501          << Attribute << " = " << Value << ";\n";
1502     else
1503       OS << "  if (Bits[" << Target << "::"
1504          << Instance << "] && "
1505          << Attribute << " < " << Value << ") "
1506          << Attribute << " = " << Value << ";\n";
1507   }
1508 
1509   OS << "}\n";
1510 }
1511 
1512 //
1513 // SubtargetEmitter::run - Main subtarget enumeration emitter.
1514 //
1515 void SubtargetEmitter::run(raw_ostream &OS) {
1516   emitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);
1517 
1518   OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n";
1519   OS << "#undef GET_SUBTARGETINFO_ENUM\n\n";
1520 
1521   OS << "namespace llvm {\n";
1522   Enumeration(OS);
1523   OS << "} // end namespace llvm\n\n";
1524   OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n";
1525 
1526   OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n";
1527   OS << "#undef GET_SUBTARGETINFO_MC_DESC\n\n";
1528 
1529   OS << "namespace llvm {\n";
1530 #if 0
1531   OS << "namespace {\n";
1532 #endif
1533   unsigned NumFeatures = FeatureKeyValues(OS);
1534   OS << "\n";
1535   unsigned NumProcs = CPUKeyValues(OS);
1536   OS << "\n";
1537   EmitSchedModel(OS);
1538   OS << "\n";
1539 #if 0
1540   OS << "} // end anonymous namespace\n\n";
1541 #endif
1542 
1543   // MCInstrInfo initialization routine.
1544   OS << "\nstatic inline MCSubtargetInfo *create" << Target
1545      << "MCSubtargetInfoImpl("
1546      << "const Triple &TT, StringRef CPU, StringRef FS) {\n";
1547   OS << "  return new MCSubtargetInfo(TT, CPU, FS, ";
1548   if (NumFeatures)
1549     OS << Target << "FeatureKV, ";
1550   else
1551     OS << "None, ";
1552   if (NumProcs)
1553     OS << Target << "SubTypeKV, ";
1554   else
1555     OS << "None, ";
1556   OS << '\n'; OS.indent(22);
1557   OS << Target << "ProcSchedKV, "
1558      << Target << "WriteProcResTable, "
1559      << Target << "WriteLatencyTable, "
1560      << Target << "ReadAdvanceTable, ";
1561   OS << '\n'; OS.indent(22);
1562   if (SchedModels.hasItineraries()) {
1563     OS << Target << "Stages, "
1564        << Target << "OperandCycles, "
1565        << Target << "ForwardingPaths";
1566   } else
1567     OS << "nullptr, nullptr, nullptr";
1568   OS << ");\n}\n\n";
1569 
1570   OS << "} // end namespace llvm\n\n";
1571 
1572   OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n";
1573 
1574   OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n";
1575   OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n\n";
1576 
1577   OS << "#include \"llvm/Support/Debug.h\"\n";
1578   OS << "#include \"llvm/Support/raw_ostream.h\"\n\n";
1579   ParseFeaturesFunction(OS, NumFeatures, NumProcs);
1580 
1581   OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n";
1582 
1583   // Create a TargetSubtargetInfo subclass to hide the MC layer initialization.
1584   OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n";
1585   OS << "#undef GET_SUBTARGETINFO_HEADER\n\n";
1586 
1587   std::string ClassName = Target + "GenSubtargetInfo";
1588   OS << "namespace llvm {\n";
1589   OS << "class DFAPacketizer;\n";
1590   OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n"
1591      << "  explicit " << ClassName << "(const Triple &TT, StringRef CPU, "
1592      << "StringRef FS);\n"
1593      << "public:\n"
1594      << "  unsigned resolveSchedClass(unsigned SchedClass, "
1595      << " const MachineInstr *DefMI,"
1596      << " const TargetSchedModel *SchedModel) const override;\n"
1597      << "  DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)"
1598      << " const;\n";
1599   if (TGT.getHwModes().getNumModeIds() > 1)
1600     OS << "  unsigned getHwMode() const override;\n";
1601   OS << "};\n"
1602      << "} // end namespace llvm\n\n";
1603 
1604   OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n";
1605 
1606   OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n";
1607   OS << "#undef GET_SUBTARGETINFO_CTOR\n\n";
1608 
1609   OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n\n";
1610   OS << "namespace llvm {\n";
1611   OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n";
1612   OS << "extern const llvm::SubtargetFeatureKV " << Target << "SubTypeKV[];\n";
1613   OS << "extern const llvm::SubtargetInfoKV " << Target << "ProcSchedKV[];\n";
1614   OS << "extern const llvm::MCWriteProcResEntry "
1615      << Target << "WriteProcResTable[];\n";
1616   OS << "extern const llvm::MCWriteLatencyEntry "
1617      << Target << "WriteLatencyTable[];\n";
1618   OS << "extern const llvm::MCReadAdvanceEntry "
1619      << Target << "ReadAdvanceTable[];\n";
1620 
1621   if (SchedModels.hasItineraries()) {
1622     OS << "extern const llvm::InstrStage " << Target << "Stages[];\n";
1623     OS << "extern const unsigned " << Target << "OperandCycles[];\n";
1624     OS << "extern const unsigned " << Target << "ForwardingPaths[];\n";
1625   }
1626 
1627   OS << ClassName << "::" << ClassName << "(const Triple &TT, StringRef CPU, "
1628      << "StringRef FS)\n"
1629      << "  : TargetSubtargetInfo(TT, CPU, FS, ";
1630   if (NumFeatures)
1631     OS << "makeArrayRef(" << Target << "FeatureKV, " << NumFeatures << "), ";
1632   else
1633     OS << "None, ";
1634   if (NumProcs)
1635     OS << "makeArrayRef(" << Target << "SubTypeKV, " << NumProcs << "), ";
1636   else
1637     OS << "None, ";
1638   OS << '\n'; OS.indent(24);
1639   OS << Target << "ProcSchedKV, "
1640      << Target << "WriteProcResTable, "
1641      << Target << "WriteLatencyTable, "
1642      << Target << "ReadAdvanceTable, ";
1643   OS << '\n'; OS.indent(24);
1644   if (SchedModels.hasItineraries()) {
1645     OS << Target << "Stages, "
1646        << Target << "OperandCycles, "
1647        << Target << "ForwardingPaths";
1648   } else
1649     OS << "nullptr, nullptr, nullptr";
1650   OS << ") {}\n\n";
1651 
1652   EmitSchedModelHelpers(ClassName, OS);
1653   EmitHwModeCheck(ClassName, OS);
1654 
1655   OS << "} // end namespace llvm\n\n";
1656 
1657   OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n";
1658 }
1659 
1660 namespace llvm {
1661 
1662 void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) {
1663   CodeGenTarget CGTarget(RK);
1664   SubtargetEmitter(RK, CGTarget).run(OS);
1665 }
1666 
1667 } // end namespace llvm
1668