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