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