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