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