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