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