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