1 //===- CodeGenSchedule.h - Scheduling Machine Models ------------*- C++ -*-===//
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 file defines structures to encapsulate the machine model as described in
11 // the target description.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_UTILS_TABLEGEN_CODEGENSCHEDULE_H
16 #define LLVM_UTILS_TABLEGEN_CODEGENSCHEDULE_H
17 
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/TableGen/Record.h"
22 #include "llvm/TableGen/SetTheory.h"
23 
24 namespace llvm {
25 
26 class CodeGenTarget;
27 class CodeGenSchedModels;
28 class CodeGenInstruction;
29 class CodeGenRegisterClass;
30 
31 using RecVec = std::vector<Record*>;
32 using RecIter = std::vector<Record*>::const_iterator;
33 
34 using IdxVec = std::vector<unsigned>;
35 using IdxIter = std::vector<unsigned>::const_iterator;
36 
37 /// We have two kinds of SchedReadWrites. Explicitly defined and inferred
38 /// sequences.  TheDef is nonnull for explicit SchedWrites, but Sequence may or
39 /// may not be empty. TheDef is null for inferred sequences, and Sequence must
40 /// be nonempty.
41 ///
42 /// IsVariadic controls whether the variants are expanded into multiple operands
43 /// or a sequence of writes on one operand.
44 struct CodeGenSchedRW {
45   unsigned Index;
46   std::string Name;
47   Record *TheDef;
48   bool IsRead;
49   bool IsAlias;
50   bool HasVariants;
51   bool IsVariadic;
52   bool IsSequence;
53   IdxVec Sequence;
54   RecVec Aliases;
55 
56   CodeGenSchedRW()
57     : Index(0), TheDef(nullptr), IsRead(false), IsAlias(false),
58       HasVariants(false), IsVariadic(false), IsSequence(false) {}
59   CodeGenSchedRW(unsigned Idx, Record *Def)
60     : Index(Idx), TheDef(Def), IsAlias(false), IsVariadic(false) {
61     Name = Def->getName();
62     IsRead = Def->isSubClassOf("SchedRead");
63     HasVariants = Def->isSubClassOf("SchedVariant");
64     if (HasVariants)
65       IsVariadic = Def->getValueAsBit("Variadic");
66 
67     // Read records don't currently have sequences, but it can be easily
68     // added. Note that implicit Reads (from ReadVariant) may have a Sequence
69     // (but no record).
70     IsSequence = Def->isSubClassOf("WriteSequence");
71   }
72 
73   CodeGenSchedRW(unsigned Idx, bool Read, ArrayRef<unsigned> Seq,
74                  const std::string &Name)
75       : Index(Idx), Name(Name), TheDef(nullptr), IsRead(Read), IsAlias(false),
76         HasVariants(false), IsVariadic(false), IsSequence(true), Sequence(Seq) {
77     assert(Sequence.size() > 1 && "implied sequence needs >1 RWs");
78   }
79 
80   bool isValid() const {
81     assert((!HasVariants || TheDef) && "Variant write needs record def");
82     assert((!IsVariadic || HasVariants) && "Variadic write needs variants");
83     assert((!IsSequence || !HasVariants) && "Sequence can't have variant");
84     assert((!IsSequence || !Sequence.empty()) && "Sequence should be nonempty");
85     assert((!IsAlias || Aliases.empty()) && "Alias cannot have aliases");
86     return TheDef || !Sequence.empty();
87   }
88 
89 #ifndef NDEBUG
90   void dump() const;
91 #endif
92 };
93 
94 /// Represent a transition between SchedClasses induced by SchedVariant.
95 struct CodeGenSchedTransition {
96   unsigned ToClassIdx;
97   IdxVec ProcIndices;
98   RecVec PredTerm;
99 };
100 
101 /// Scheduling class.
102 ///
103 /// Each instruction description will be mapped to a scheduling class. There are
104 /// four types of classes:
105 ///
106 /// 1) An explicitly defined itinerary class with ItinClassDef set.
107 /// Writes and ReadDefs are empty. ProcIndices contains 0 for any processor.
108 ///
109 /// 2) An implied class with a list of SchedWrites and SchedReads that are
110 /// defined in an instruction definition and which are common across all
111 /// subtargets. ProcIndices contains 0 for any processor.
112 ///
113 /// 3) An implied class with a list of InstRW records that map instructions to
114 /// SchedWrites and SchedReads per-processor. InstrClassMap should map the same
115 /// instructions to this class. ProcIndices contains all the processors that
116 /// provided InstrRW records for this class. ItinClassDef or Writes/Reads may
117 /// still be defined for processors with no InstRW entry.
118 ///
119 /// 4) An inferred class represents a variant of another class that may be
120 /// resolved at runtime. ProcIndices contains the set of processors that may
121 /// require the class. ProcIndices are propagated through SchedClasses as
122 /// variants are expanded. Multiple SchedClasses may be inferred from an
123 /// itinerary class. Each inherits the processor index from the ItinRW record
124 /// that mapped the itinerary class to the variant Writes or Reads.
125 struct CodeGenSchedClass {
126   unsigned Index;
127   std::string Name;
128   Record *ItinClassDef;
129 
130   IdxVec Writes;
131   IdxVec Reads;
132   // Sorted list of ProcIdx, where ProcIdx==0 implies any processor.
133   IdxVec ProcIndices;
134 
135   std::vector<CodeGenSchedTransition> Transitions;
136 
137   // InstRW records associated with this class. These records may refer to an
138   // Instruction no longer mapped to this class by InstrClassMap. These
139   // Instructions should be ignored by this class because they have been split
140   // off to join another inferred class.
141   RecVec InstRWs;
142 
143   CodeGenSchedClass(unsigned Index, std::string Name, Record *ItinClassDef)
144     : Index(Index), Name(std::move(Name)), ItinClassDef(ItinClassDef) {}
145 
146   bool isKeyEqual(Record *IC, ArrayRef<unsigned> W,
147                   ArrayRef<unsigned> R) const {
148     return ItinClassDef == IC && makeArrayRef(Writes) == W &&
149            makeArrayRef(Reads) == R;
150   }
151 
152   // Is this class generated from a variants if existing classes? Instructions
153   // are never mapped directly to inferred scheduling classes.
154   bool isInferred() const { return !ItinClassDef; }
155 
156 #ifndef NDEBUG
157   void dump(const CodeGenSchedModels *SchedModels) const;
158 #endif
159 };
160 
161 /// Represent the cost of allocating a register of register class RCDef.
162 ///
163 /// The cost of allocating a register is equivalent to the number of physical
164 /// registers used by the register renamer. Register costs are defined at
165 /// register class granularity.
166 struct CodeGenRegisterCost {
167   Record *RCDef;
168   unsigned Cost;
169   CodeGenRegisterCost(Record *RC, unsigned RegisterCost)
170       : RCDef(RC), Cost(RegisterCost) {}
171   CodeGenRegisterCost(const CodeGenRegisterCost &) = default;
172   CodeGenRegisterCost &operator=(const CodeGenRegisterCost &) = delete;
173 };
174 
175 /// A processor register file.
176 ///
177 /// This class describes a processor register file. Register file information is
178 /// currently consumed by external tools like llvm-mca to predict dispatch
179 /// stalls due to register pressure.
180 struct CodeGenRegisterFile {
181   std::string Name;
182   Record *RegisterFileDef;
183 
184   unsigned NumPhysRegs;
185   std::vector<CodeGenRegisterCost> Costs;
186 
187   CodeGenRegisterFile(StringRef name, Record *def)
188       : Name(name), RegisterFileDef(def), NumPhysRegs(0) {}
189 
190   bool hasDefaultCosts() const { return Costs.empty(); }
191 };
192 
193 // Processor model.
194 //
195 // ModelName is a unique name used to name an instantiation of MCSchedModel.
196 //
197 // ModelDef is NULL for inferred Models. This happens when a processor defines
198 // an itinerary but no machine model. If the processor defines neither a machine
199 // model nor itinerary, then ModelDef remains pointing to NoModel. NoModel has
200 // the special "NoModel" field set to true.
201 //
202 // ItinsDef always points to a valid record definition, but may point to the
203 // default NoItineraries. NoItineraries has an empty list of InstrItinData
204 // records.
205 //
206 // ItinDefList orders this processor's InstrItinData records by SchedClass idx.
207 struct CodeGenProcModel {
208   unsigned Index;
209   std::string ModelName;
210   Record *ModelDef;
211   Record *ItinsDef;
212 
213   // Derived members...
214 
215   // Array of InstrItinData records indexed by a CodeGenSchedClass index.
216   // This list is empty if the Processor has no value for Itineraries.
217   // Initialized by collectProcItins().
218   RecVec ItinDefList;
219 
220   // Map itinerary classes to per-operand resources.
221   // This list is empty if no ItinRW refers to this Processor.
222   RecVec ItinRWDefs;
223 
224   // List of unsupported feature.
225   // This list is empty if the Processor has no UnsupportedFeatures.
226   RecVec UnsupportedFeaturesDefs;
227 
228   // All read/write resources associated with this processor.
229   RecVec WriteResDefs;
230   RecVec ReadAdvanceDefs;
231 
232   // Per-operand machine model resources associated with this processor.
233   RecVec ProcResourceDefs;
234 
235   // List of Register Files.
236   std::vector<CodeGenRegisterFile> RegisterFiles;
237 
238   CodeGenProcModel(unsigned Idx, std::string Name, Record *MDef,
239                    Record *IDef) :
240     Index(Idx), ModelName(std::move(Name)), ModelDef(MDef), ItinsDef(IDef) {}
241 
242   bool hasItineraries() const {
243     return !ItinsDef->getValueAsListOfDefs("IID").empty();
244   }
245 
246   bool hasInstrSchedModel() const {
247     return !WriteResDefs.empty() || !ItinRWDefs.empty();
248   }
249 
250   bool hasExtraProcessorInfo() const {
251     return !RegisterFiles.empty();
252   }
253 
254   unsigned getProcResourceIdx(Record *PRDef) const;
255 
256   bool isUnsupported(const CodeGenInstruction &Inst) const;
257 
258 #ifndef NDEBUG
259   void dump() const;
260 #endif
261 };
262 
263 /// Top level container for machine model data.
264 class CodeGenSchedModels {
265   RecordKeeper &Records;
266   const CodeGenTarget &Target;
267 
268   // Map dag expressions to Instruction lists.
269   SetTheory Sets;
270 
271   // List of unique processor models.
272   std::vector<CodeGenProcModel> ProcModels;
273 
274   // Map Processor's MachineModel or ProcItin to a CodeGenProcModel index.
275   using ProcModelMapTy = DenseMap<Record*, unsigned>;
276   ProcModelMapTy ProcModelMap;
277 
278   // Per-operand SchedReadWrite types.
279   std::vector<CodeGenSchedRW> SchedWrites;
280   std::vector<CodeGenSchedRW> SchedReads;
281 
282   // List of unique SchedClasses.
283   std::vector<CodeGenSchedClass> SchedClasses;
284 
285   // Any inferred SchedClass has an index greater than NumInstrSchedClassses.
286   unsigned NumInstrSchedClasses;
287 
288   RecVec ProcResourceDefs;
289   RecVec ProcResGroups;
290 
291   // Map each instruction to its unique SchedClass index considering the
292   // combination of it's itinerary class, SchedRW list, and InstRW records.
293   using InstClassMapTy = DenseMap<Record*, unsigned>;
294   InstClassMapTy InstrClassMap;
295 
296 public:
297   CodeGenSchedModels(RecordKeeper& RK, const CodeGenTarget &TGT);
298 
299   // iterator access to the scheduling classes.
300   using class_iterator = std::vector<CodeGenSchedClass>::iterator;
301   using const_class_iterator = std::vector<CodeGenSchedClass>::const_iterator;
302   class_iterator classes_begin() { return SchedClasses.begin(); }
303   const_class_iterator classes_begin() const { return SchedClasses.begin(); }
304   class_iterator classes_end() { return SchedClasses.end(); }
305   const_class_iterator classes_end() const { return SchedClasses.end(); }
306   iterator_range<class_iterator> classes() {
307    return make_range(classes_begin(), classes_end());
308   }
309   iterator_range<const_class_iterator> classes() const {
310    return make_range(classes_begin(), classes_end());
311   }
312   iterator_range<class_iterator> explicit_classes() {
313     return make_range(classes_begin(), classes_begin() + NumInstrSchedClasses);
314   }
315   iterator_range<const_class_iterator> explicit_classes() const {
316     return make_range(classes_begin(), classes_begin() + NumInstrSchedClasses);
317   }
318 
319   Record *getModelOrItinDef(Record *ProcDef) const {
320     Record *ModelDef = ProcDef->getValueAsDef("SchedModel");
321     Record *ItinsDef = ProcDef->getValueAsDef("ProcItin");
322     if (!ItinsDef->getValueAsListOfDefs("IID").empty()) {
323       assert(ModelDef->getValueAsBit("NoModel")
324              && "Itineraries must be defined within SchedMachineModel");
325       return ItinsDef;
326     }
327     return ModelDef;
328   }
329 
330   const CodeGenProcModel &getModelForProc(Record *ProcDef) const {
331     Record *ModelDef = getModelOrItinDef(ProcDef);
332     ProcModelMapTy::const_iterator I = ProcModelMap.find(ModelDef);
333     assert(I != ProcModelMap.end() && "missing machine model");
334     return ProcModels[I->second];
335   }
336 
337   CodeGenProcModel &getProcModel(Record *ModelDef) {
338     ProcModelMapTy::const_iterator I = ProcModelMap.find(ModelDef);
339     assert(I != ProcModelMap.end() && "missing machine model");
340     return ProcModels[I->second];
341   }
342   const CodeGenProcModel &getProcModel(Record *ModelDef) const {
343     return const_cast<CodeGenSchedModels*>(this)->getProcModel(ModelDef);
344   }
345 
346   // Iterate over the unique processor models.
347   using ProcIter = std::vector<CodeGenProcModel>::const_iterator;
348   ProcIter procModelBegin() const { return ProcModels.begin(); }
349   ProcIter procModelEnd() const { return ProcModels.end(); }
350   ArrayRef<CodeGenProcModel> procModels() const { return ProcModels; }
351 
352   // Return true if any processors have itineraries.
353   bool hasItineraries() const;
354 
355   // Get a SchedWrite from its index.
356   const CodeGenSchedRW &getSchedWrite(unsigned Idx) const {
357     assert(Idx < SchedWrites.size() && "bad SchedWrite index");
358     assert(SchedWrites[Idx].isValid() && "invalid SchedWrite");
359     return SchedWrites[Idx];
360   }
361   // Get a SchedWrite from its index.
362   const CodeGenSchedRW &getSchedRead(unsigned Idx) const {
363     assert(Idx < SchedReads.size() && "bad SchedRead index");
364     assert(SchedReads[Idx].isValid() && "invalid SchedRead");
365     return SchedReads[Idx];
366   }
367 
368   const CodeGenSchedRW &getSchedRW(unsigned Idx, bool IsRead) const {
369     return IsRead ? getSchedRead(Idx) : getSchedWrite(Idx);
370   }
371   CodeGenSchedRW &getSchedRW(Record *Def) {
372     bool IsRead = Def->isSubClassOf("SchedRead");
373     unsigned Idx = getSchedRWIdx(Def, IsRead);
374     return const_cast<CodeGenSchedRW&>(
375       IsRead ? getSchedRead(Idx) : getSchedWrite(Idx));
376   }
377   const CodeGenSchedRW &getSchedRW(Record*Def) const {
378     return const_cast<CodeGenSchedModels&>(*this).getSchedRW(Def);
379   }
380 
381   unsigned getSchedRWIdx(Record *Def, bool IsRead) const;
382 
383   // Return true if the given write record is referenced by a ReadAdvance.
384   bool hasReadOfWrite(Record *WriteDef) const;
385 
386   // Get a SchedClass from its index.
387   CodeGenSchedClass &getSchedClass(unsigned Idx) {
388     assert(Idx < SchedClasses.size() && "bad SchedClass index");
389     return SchedClasses[Idx];
390   }
391   const CodeGenSchedClass &getSchedClass(unsigned Idx) const {
392     assert(Idx < SchedClasses.size() && "bad SchedClass index");
393     return SchedClasses[Idx];
394   }
395 
396   // Get the SchedClass index for an instruction. Instructions with no
397   // itinerary, no SchedReadWrites, and no InstrReadWrites references return 0
398   // for NoItinerary.
399   unsigned getSchedClassIdx(const CodeGenInstruction &Inst) const;
400 
401   using SchedClassIter = std::vector<CodeGenSchedClass>::const_iterator;
402   SchedClassIter schedClassBegin() const { return SchedClasses.begin(); }
403   SchedClassIter schedClassEnd() const { return SchedClasses.end(); }
404   ArrayRef<CodeGenSchedClass> schedClasses() const { return SchedClasses; }
405 
406   unsigned numInstrSchedClasses() const { return NumInstrSchedClasses; }
407 
408   void findRWs(const RecVec &RWDefs, IdxVec &Writes, IdxVec &Reads) const;
409   void findRWs(const RecVec &RWDefs, IdxVec &RWs, bool IsRead) const;
410   void expandRWSequence(unsigned RWIdx, IdxVec &RWSeq, bool IsRead) const;
411   void expandRWSeqForProc(unsigned RWIdx, IdxVec &RWSeq, bool IsRead,
412                           const CodeGenProcModel &ProcModel) const;
413 
414   unsigned addSchedClass(Record *ItinDef, ArrayRef<unsigned> OperWrites,
415                          ArrayRef<unsigned> OperReads,
416                          ArrayRef<unsigned> ProcIndices);
417 
418   unsigned findOrInsertRW(ArrayRef<unsigned> Seq, bool IsRead);
419 
420   unsigned findSchedClassIdx(Record *ItinClassDef, ArrayRef<unsigned> Writes,
421                              ArrayRef<unsigned> Reads) const;
422 
423   Record *findProcResUnits(Record *ProcResKind, const CodeGenProcModel &PM,
424                            ArrayRef<SMLoc> Loc) const;
425 
426 private:
427   void collectProcModels();
428 
429   // Initialize a new processor model if it is unique.
430   void addProcModel(Record *ProcDef);
431 
432   void collectSchedRW();
433 
434   std::string genRWName(ArrayRef<unsigned> Seq, bool IsRead);
435   unsigned findRWForSequence(ArrayRef<unsigned> Seq, bool IsRead);
436 
437   void collectSchedClasses();
438 
439   void collectRegisterFiles();
440 
441   std::string createSchedClassName(Record *ItinClassDef,
442                                    ArrayRef<unsigned> OperWrites,
443                                    ArrayRef<unsigned> OperReads);
444   std::string createSchedClassName(const RecVec &InstDefs);
445   void createInstRWClass(Record *InstRWDef);
446 
447   void collectProcItins();
448 
449   void collectProcItinRW();
450 
451   void collectProcUnsupportedFeatures();
452 
453   void inferSchedClasses();
454 
455   void checkCompleteness();
456 
457   void inferFromRW(ArrayRef<unsigned> OperWrites, ArrayRef<unsigned> OperReads,
458                    unsigned FromClassIdx, ArrayRef<unsigned> ProcIndices);
459   void inferFromItinClass(Record *ItinClassDef, unsigned FromClassIdx);
460   void inferFromInstRWs(unsigned SCIdx);
461 
462   bool hasSuperGroup(RecVec &SubUnits, CodeGenProcModel &PM);
463   void verifyProcResourceGroups(CodeGenProcModel &PM);
464 
465   void collectProcResources();
466 
467   void collectItinProcResources(Record *ItinClassDef);
468 
469   void collectRWResources(unsigned RWIdx, bool IsRead,
470                           ArrayRef<unsigned> ProcIndices);
471 
472   void collectRWResources(ArrayRef<unsigned> Writes, ArrayRef<unsigned> Reads,
473                           ArrayRef<unsigned> ProcIndices);
474 
475   void addProcResource(Record *ProcResourceKind, CodeGenProcModel &PM,
476                        ArrayRef<SMLoc> Loc);
477 
478   void addWriteRes(Record *ProcWriteResDef, unsigned PIdx);
479 
480   void addReadAdvance(Record *ProcReadAdvanceDef, unsigned PIdx);
481 };
482 
483 } // namespace llvm
484 
485 #endif
486