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