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