1 //===- CodeGenSchedule.cpp - Scheduling MachineModels ---------------------===//
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 #include "CodeGenSchedule.h"
16 #include "CodeGenInstruction.h"
17 #include "CodeGenTarget.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/Regex.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/TableGen/Error.h"
28 #include <algorithm>
29 #include <iterator>
30 #include <utility>
31 
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "subtarget-emitter"
35 
36 #ifndef NDEBUG
37 static void dumpIdxVec(ArrayRef<unsigned> V) {
38   for (unsigned Idx : V)
39     dbgs() << Idx << ", ";
40 }
41 #endif
42 
43 namespace {
44 
45 // (instrs a, b, ...) Evaluate and union all arguments. Identical to AddOp.
46 struct InstrsOp : public SetTheory::Operator {
47   void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
48              ArrayRef<SMLoc> Loc) override {
49     ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts, Loc);
50   }
51 };
52 
53 // (instregex "OpcPat",...) Find all instructions matching an opcode pattern.
54 struct InstRegexOp : public SetTheory::Operator {
55   const CodeGenTarget &Target;
56   InstRegexOp(const CodeGenTarget &t): Target(t) {}
57 
58   /// Remove any text inside of parentheses from S.
59   static std::string removeParens(llvm::StringRef S) {
60     std::string Result;
61     unsigned Paren = 0;
62     // NB: We don't care about escaped parens here.
63     for (char C : S) {
64       switch (C) {
65       case '(':
66         ++Paren;
67         break;
68       case ')':
69         --Paren;
70         break;
71       default:
72         if (Paren == 0)
73           Result += C;
74       }
75     }
76     return Result;
77   }
78 
79   void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
80              ArrayRef<SMLoc> Loc) override {
81     for (Init *Arg : make_range(Expr->arg_begin(), Expr->arg_end())) {
82       StringInit *SI = dyn_cast<StringInit>(Arg);
83       if (!SI)
84         PrintFatalError(Loc, "instregex requires pattern string: " +
85                                  Expr->getAsString());
86       StringRef Original = SI->getValue();
87 
88       // Extract a prefix that we can binary search on.
89       static const char RegexMetachars[] = "()^$|*+?.[]\\{}";
90       auto FirstMeta = Original.find_first_of(RegexMetachars);
91 
92       // Look for top-level | or ?. We cannot optimize them to binary search.
93       if (removeParens(Original).find_first_of("|?") != std::string::npos)
94         FirstMeta = 0;
95 
96       Optional<Regex> Regexpr = None;
97       StringRef Prefix = Original.substr(0, FirstMeta);
98       StringRef PatStr = Original.substr(FirstMeta);
99       if (!PatStr.empty()) {
100         // For the rest use a python-style prefix match.
101         std::string pat = PatStr;
102         if (pat[0] != '^') {
103           pat.insert(0, "^(");
104           pat.insert(pat.end(), ')');
105         }
106         Regexpr = Regex(pat);
107       }
108 
109       int NumMatches = 0;
110 
111       unsigned NumGeneric = Target.getNumFixedInstructions();
112       ArrayRef<const CodeGenInstruction *> Generics =
113           Target.getInstructionsByEnumValue().slice(0, NumGeneric + 1);
114 
115       // The generic opcodes are unsorted, handle them manually.
116       for (auto *Inst : Generics) {
117         StringRef InstName = Inst->TheDef->getName();
118         if (InstName.startswith(Prefix) &&
119             (!Regexpr || Regexpr->match(InstName.substr(Prefix.size())))) {
120           Elts.insert(Inst->TheDef);
121           NumMatches++;
122         }
123       }
124 
125       ArrayRef<const CodeGenInstruction *> Instructions =
126           Target.getInstructionsByEnumValue().slice(NumGeneric + 1);
127 
128       // Target instructions are sorted. Find the range that starts with our
129       // prefix.
130       struct Comp {
131         bool operator()(const CodeGenInstruction *LHS, StringRef RHS) {
132           return LHS->TheDef->getName() < RHS;
133         }
134         bool operator()(StringRef LHS, const CodeGenInstruction *RHS) {
135           return LHS < RHS->TheDef->getName() &&
136                  !RHS->TheDef->getName().startswith(LHS);
137         }
138       };
139       auto Range = std::equal_range(Instructions.begin(), Instructions.end(),
140                                     Prefix, Comp());
141 
142       // For this range we know that it starts with the prefix. Check if there's
143       // a regex that needs to be checked.
144       for (auto *Inst : make_range(Range)) {
145         StringRef InstName = Inst->TheDef->getName();
146         if (!Regexpr || Regexpr->match(InstName.substr(Prefix.size()))) {
147           Elts.insert(Inst->TheDef);
148           NumMatches++;
149         }
150       }
151 
152       if (0 == NumMatches)
153         PrintFatalError(Loc, "instregex has no matches: " + Original);
154     }
155   }
156 };
157 
158 } // end anonymous namespace
159 
160 /// CodeGenModels ctor interprets machine model records and populates maps.
161 CodeGenSchedModels::CodeGenSchedModels(RecordKeeper &RK,
162                                        const CodeGenTarget &TGT):
163   Records(RK), Target(TGT) {
164 
165   Sets.addFieldExpander("InstRW", "Instrs");
166 
167   // Allow Set evaluation to recognize the dags used in InstRW records:
168   // (instrs Op1, Op1...)
169   Sets.addOperator("instrs", llvm::make_unique<InstrsOp>());
170   Sets.addOperator("instregex", llvm::make_unique<InstRegexOp>(Target));
171 
172   // Instantiate a CodeGenProcModel for each SchedMachineModel with the values
173   // that are explicitly referenced in tablegen records. Resources associated
174   // with each processor will be derived later. Populate ProcModelMap with the
175   // CodeGenProcModel instances.
176   collectProcModels();
177 
178   // Instantiate a CodeGenSchedRW for each SchedReadWrite record explicitly
179   // defined, and populate SchedReads and SchedWrites vectors. Implicit
180   // SchedReadWrites that represent sequences derived from expanded variant will
181   // be inferred later.
182   collectSchedRW();
183 
184   // Instantiate a CodeGenSchedClass for each unique SchedRW signature directly
185   // required by an instruction definition, and populate SchedClassIdxMap. Set
186   // NumItineraryClasses to the number of explicit itinerary classes referenced
187   // by instructions. Set NumInstrSchedClasses to the number of itinerary
188   // classes plus any classes implied by instructions that derive from class
189   // Sched and provide SchedRW list. This does not infer any new classes from
190   // SchedVariant.
191   collectSchedClasses();
192 
193   // Find instruction itineraries for each processor. Sort and populate
194   // CodeGenProcModel::ItinDefList. (Cycle-to-cycle itineraries). This requires
195   // all itinerary classes to be discovered.
196   collectProcItins();
197 
198   // Find ItinRW records for each processor and itinerary class.
199   // (For per-operand resources mapped to itinerary classes).
200   collectProcItinRW();
201 
202   // Find UnsupportedFeatures records for each processor.
203   // (For per-operand resources mapped to itinerary classes).
204   collectProcUnsupportedFeatures();
205 
206   // Infer new SchedClasses from SchedVariant.
207   inferSchedClasses();
208 
209   // Populate each CodeGenProcModel's WriteResDefs, ReadAdvanceDefs, and
210   // ProcResourceDefs.
211   DEBUG(dbgs() << "\n+++ RESOURCE DEFINITIONS (collectProcResources) +++\n");
212   collectProcResources();
213 
214   // Find register file definitions for each processor.
215   collectRegisterFiles();
216 
217   checkCompleteness();
218 }
219 
220 /// Gather all processor models.
221 void CodeGenSchedModels::collectProcModels() {
222   RecVec ProcRecords = Records.getAllDerivedDefinitions("Processor");
223   std::sort(ProcRecords.begin(), ProcRecords.end(), LessRecordFieldName());
224 
225   // Reserve space because we can. Reallocation would be ok.
226   ProcModels.reserve(ProcRecords.size()+1);
227 
228   // Use idx=0 for NoModel/NoItineraries.
229   Record *NoModelDef = Records.getDef("NoSchedModel");
230   Record *NoItinsDef = Records.getDef("NoItineraries");
231   ProcModels.emplace_back(0, "NoSchedModel", NoModelDef, NoItinsDef);
232   ProcModelMap[NoModelDef] = 0;
233 
234   // For each processor, find a unique machine model.
235   DEBUG(dbgs() << "+++ PROCESSOR MODELs (addProcModel) +++\n");
236   for (Record *ProcRecord : ProcRecords)
237     addProcModel(ProcRecord);
238 }
239 
240 /// Get a unique processor model based on the defined MachineModel and
241 /// ProcessorItineraries.
242 void CodeGenSchedModels::addProcModel(Record *ProcDef) {
243   Record *ModelKey = getModelOrItinDef(ProcDef);
244   if (!ProcModelMap.insert(std::make_pair(ModelKey, ProcModels.size())).second)
245     return;
246 
247   std::string Name = ModelKey->getName();
248   if (ModelKey->isSubClassOf("SchedMachineModel")) {
249     Record *ItinsDef = ModelKey->getValueAsDef("Itineraries");
250     ProcModels.emplace_back(ProcModels.size(), Name, ModelKey, ItinsDef);
251   }
252   else {
253     // An itinerary is defined without a machine model. Infer a new model.
254     if (!ModelKey->getValueAsListOfDefs("IID").empty())
255       Name = Name + "Model";
256     ProcModels.emplace_back(ProcModels.size(), Name,
257                             ProcDef->getValueAsDef("SchedModel"), ModelKey);
258   }
259   DEBUG(ProcModels.back().dump());
260 }
261 
262 // Recursively find all reachable SchedReadWrite records.
263 static void scanSchedRW(Record *RWDef, RecVec &RWDefs,
264                         SmallPtrSet<Record*, 16> &RWSet) {
265   if (!RWSet.insert(RWDef).second)
266     return;
267   RWDefs.push_back(RWDef);
268   // Reads don't currently have sequence records, but it can be added later.
269   if (RWDef->isSubClassOf("WriteSequence")) {
270     RecVec Seq = RWDef->getValueAsListOfDefs("Writes");
271     for (Record *WSRec : Seq)
272       scanSchedRW(WSRec, RWDefs, RWSet);
273   }
274   else if (RWDef->isSubClassOf("SchedVariant")) {
275     // Visit each variant (guarded by a different predicate).
276     RecVec Vars = RWDef->getValueAsListOfDefs("Variants");
277     for (Record *Variant : Vars) {
278       // Visit each RW in the sequence selected by the current variant.
279       RecVec Selected = Variant->getValueAsListOfDefs("Selected");
280       for (Record *SelDef : Selected)
281         scanSchedRW(SelDef, RWDefs, RWSet);
282     }
283   }
284 }
285 
286 // Collect and sort all SchedReadWrites reachable via tablegen records.
287 // More may be inferred later when inferring new SchedClasses from variants.
288 void CodeGenSchedModels::collectSchedRW() {
289   // Reserve idx=0 for invalid writes/reads.
290   SchedWrites.resize(1);
291   SchedReads.resize(1);
292 
293   SmallPtrSet<Record*, 16> RWSet;
294 
295   // Find all SchedReadWrites referenced by instruction defs.
296   RecVec SWDefs, SRDefs;
297   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
298     Record *SchedDef = Inst->TheDef;
299     if (SchedDef->isValueUnset("SchedRW"))
300       continue;
301     RecVec RWs = SchedDef->getValueAsListOfDefs("SchedRW");
302     for (Record *RW : RWs) {
303       if (RW->isSubClassOf("SchedWrite"))
304         scanSchedRW(RW, SWDefs, RWSet);
305       else {
306         assert(RW->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
307         scanSchedRW(RW, SRDefs, RWSet);
308       }
309     }
310   }
311   // Find all ReadWrites referenced by InstRW.
312   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
313   for (Record *InstRWDef : InstRWDefs) {
314     // For all OperandReadWrites.
315     RecVec RWDefs = InstRWDef->getValueAsListOfDefs("OperandReadWrites");
316     for (Record *RWDef : RWDefs) {
317       if (RWDef->isSubClassOf("SchedWrite"))
318         scanSchedRW(RWDef, SWDefs, RWSet);
319       else {
320         assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
321         scanSchedRW(RWDef, SRDefs, RWSet);
322       }
323     }
324   }
325   // Find all ReadWrites referenced by ItinRW.
326   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
327   for (Record *ItinRWDef : ItinRWDefs) {
328     // For all OperandReadWrites.
329     RecVec RWDefs = ItinRWDef->getValueAsListOfDefs("OperandReadWrites");
330     for (Record *RWDef : RWDefs) {
331       if (RWDef->isSubClassOf("SchedWrite"))
332         scanSchedRW(RWDef, SWDefs, RWSet);
333       else {
334         assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
335         scanSchedRW(RWDef, SRDefs, RWSet);
336       }
337     }
338   }
339   // Find all ReadWrites referenced by SchedAlias. AliasDefs needs to be sorted
340   // for the loop below that initializes Alias vectors.
341   RecVec AliasDefs = Records.getAllDerivedDefinitions("SchedAlias");
342   std::sort(AliasDefs.begin(), AliasDefs.end(), LessRecord());
343   for (Record *ADef : AliasDefs) {
344     Record *MatchDef = ADef->getValueAsDef("MatchRW");
345     Record *AliasDef = ADef->getValueAsDef("AliasRW");
346     if (MatchDef->isSubClassOf("SchedWrite")) {
347       if (!AliasDef->isSubClassOf("SchedWrite"))
348         PrintFatalError(ADef->getLoc(), "SchedWrite Alias must be SchedWrite");
349       scanSchedRW(AliasDef, SWDefs, RWSet);
350     }
351     else {
352       assert(MatchDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
353       if (!AliasDef->isSubClassOf("SchedRead"))
354         PrintFatalError(ADef->getLoc(), "SchedRead Alias must be SchedRead");
355       scanSchedRW(AliasDef, SRDefs, RWSet);
356     }
357   }
358   // Sort and add the SchedReadWrites directly referenced by instructions or
359   // itinerary resources. Index reads and writes in separate domains.
360   std::sort(SWDefs.begin(), SWDefs.end(), LessRecord());
361   for (Record *SWDef : SWDefs) {
362     assert(!getSchedRWIdx(SWDef, /*IsRead=*/false) && "duplicate SchedWrite");
363     SchedWrites.emplace_back(SchedWrites.size(), SWDef);
364   }
365   std::sort(SRDefs.begin(), SRDefs.end(), LessRecord());
366   for (Record *SRDef : SRDefs) {
367     assert(!getSchedRWIdx(SRDef, /*IsRead-*/true) && "duplicate SchedWrite");
368     SchedReads.emplace_back(SchedReads.size(), SRDef);
369   }
370   // Initialize WriteSequence vectors.
371   for (CodeGenSchedRW &CGRW : SchedWrites) {
372     if (!CGRW.IsSequence)
373       continue;
374     findRWs(CGRW.TheDef->getValueAsListOfDefs("Writes"), CGRW.Sequence,
375             /*IsRead=*/false);
376   }
377   // Initialize Aliases vectors.
378   for (Record *ADef : AliasDefs) {
379     Record *AliasDef = ADef->getValueAsDef("AliasRW");
380     getSchedRW(AliasDef).IsAlias = true;
381     Record *MatchDef = ADef->getValueAsDef("MatchRW");
382     CodeGenSchedRW &RW = getSchedRW(MatchDef);
383     if (RW.IsAlias)
384       PrintFatalError(ADef->getLoc(), "Cannot Alias an Alias");
385     RW.Aliases.push_back(ADef);
386   }
387   DEBUG(
388     dbgs() << "\n+++ SCHED READS and WRITES (collectSchedRW) +++\n";
389     for (unsigned WIdx = 0, WEnd = SchedWrites.size(); WIdx != WEnd; ++WIdx) {
390       dbgs() << WIdx << ": ";
391       SchedWrites[WIdx].dump();
392       dbgs() << '\n';
393     }
394     for (unsigned RIdx = 0, REnd = SchedReads.size(); RIdx != REnd; ++RIdx) {
395       dbgs() << RIdx << ": ";
396       SchedReads[RIdx].dump();
397       dbgs() << '\n';
398     }
399     RecVec RWDefs = Records.getAllDerivedDefinitions("SchedReadWrite");
400     for (Record *RWDef : RWDefs) {
401       if (!getSchedRWIdx(RWDef, RWDef->isSubClassOf("SchedRead"))) {
402         StringRef Name = RWDef->getName();
403         if (Name != "NoWrite" && Name != "ReadDefault")
404           dbgs() << "Unused SchedReadWrite " << Name << '\n';
405       }
406     });
407 }
408 
409 /// Compute a SchedWrite name from a sequence of writes.
410 std::string CodeGenSchedModels::genRWName(ArrayRef<unsigned> Seq, bool IsRead) {
411   std::string Name("(");
412   for (auto I = Seq.begin(), E = Seq.end(); I != E; ++I) {
413     if (I != Seq.begin())
414       Name += '_';
415     Name += getSchedRW(*I, IsRead).Name;
416   }
417   Name += ')';
418   return Name;
419 }
420 
421 unsigned CodeGenSchedModels::getSchedRWIdx(Record *Def, bool IsRead) const {
422   const std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
423   for (std::vector<CodeGenSchedRW>::const_iterator I = RWVec.begin(),
424          E = RWVec.end(); I != E; ++I) {
425     if (I->TheDef == Def)
426       return I - RWVec.begin();
427   }
428   return 0;
429 }
430 
431 bool CodeGenSchedModels::hasReadOfWrite(Record *WriteDef) const {
432   for (const CodeGenSchedRW &Read : SchedReads) {
433     Record *ReadDef = Read.TheDef;
434     if (!ReadDef || !ReadDef->isSubClassOf("ProcReadAdvance"))
435       continue;
436 
437     RecVec ValidWrites = ReadDef->getValueAsListOfDefs("ValidWrites");
438     if (is_contained(ValidWrites, WriteDef)) {
439       return true;
440     }
441   }
442   return false;
443 }
444 
445 static void splitSchedReadWrites(const RecVec &RWDefs,
446                                  RecVec &WriteDefs, RecVec &ReadDefs) {
447   for (Record *RWDef : RWDefs) {
448     if (RWDef->isSubClassOf("SchedWrite"))
449       WriteDefs.push_back(RWDef);
450     else {
451       assert(RWDef->isSubClassOf("SchedRead") && "unknown SchedReadWrite");
452       ReadDefs.push_back(RWDef);
453     }
454   }
455 }
456 
457 // Split the SchedReadWrites defs and call findRWs for each list.
458 void CodeGenSchedModels::findRWs(const RecVec &RWDefs,
459                                  IdxVec &Writes, IdxVec &Reads) const {
460     RecVec WriteDefs;
461     RecVec ReadDefs;
462     splitSchedReadWrites(RWDefs, WriteDefs, ReadDefs);
463     findRWs(WriteDefs, Writes, false);
464     findRWs(ReadDefs, Reads, true);
465 }
466 
467 // Call getSchedRWIdx for all elements in a sequence of SchedRW defs.
468 void CodeGenSchedModels::findRWs(const RecVec &RWDefs, IdxVec &RWs,
469                                  bool IsRead) const {
470   for (Record *RWDef : RWDefs) {
471     unsigned Idx = getSchedRWIdx(RWDef, IsRead);
472     assert(Idx && "failed to collect SchedReadWrite");
473     RWs.push_back(Idx);
474   }
475 }
476 
477 void CodeGenSchedModels::expandRWSequence(unsigned RWIdx, IdxVec &RWSeq,
478                                           bool IsRead) const {
479   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
480   if (!SchedRW.IsSequence) {
481     RWSeq.push_back(RWIdx);
482     return;
483   }
484   int Repeat =
485     SchedRW.TheDef ? SchedRW.TheDef->getValueAsInt("Repeat") : 1;
486   for (int i = 0; i < Repeat; ++i) {
487     for (unsigned I : SchedRW.Sequence) {
488       expandRWSequence(I, RWSeq, IsRead);
489     }
490   }
491 }
492 
493 // Expand a SchedWrite as a sequence following any aliases that coincide with
494 // the given processor model.
495 void CodeGenSchedModels::expandRWSeqForProc(
496   unsigned RWIdx, IdxVec &RWSeq, bool IsRead,
497   const CodeGenProcModel &ProcModel) const {
498 
499   const CodeGenSchedRW &SchedWrite = getSchedRW(RWIdx, IsRead);
500   Record *AliasDef = nullptr;
501   for (RecIter AI = SchedWrite.Aliases.begin(), AE = SchedWrite.Aliases.end();
502        AI != AE; ++AI) {
503     const CodeGenSchedRW &AliasRW = getSchedRW((*AI)->getValueAsDef("AliasRW"));
504     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
505       Record *ModelDef = (*AI)->getValueAsDef("SchedModel");
506       if (&getProcModel(ModelDef) != &ProcModel)
507         continue;
508     }
509     if (AliasDef)
510       PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
511                       "defined for processor " + ProcModel.ModelName +
512                       " Ensure only one SchedAlias exists per RW.");
513     AliasDef = AliasRW.TheDef;
514   }
515   if (AliasDef) {
516     expandRWSeqForProc(getSchedRWIdx(AliasDef, IsRead),
517                        RWSeq, IsRead,ProcModel);
518     return;
519   }
520   if (!SchedWrite.IsSequence) {
521     RWSeq.push_back(RWIdx);
522     return;
523   }
524   int Repeat =
525     SchedWrite.TheDef ? SchedWrite.TheDef->getValueAsInt("Repeat") : 1;
526   for (int i = 0; i < Repeat; ++i) {
527     for (unsigned I : SchedWrite.Sequence) {
528       expandRWSeqForProc(I, RWSeq, IsRead, ProcModel);
529     }
530   }
531 }
532 
533 // Find the existing SchedWrite that models this sequence of writes.
534 unsigned CodeGenSchedModels::findRWForSequence(ArrayRef<unsigned> Seq,
535                                                bool IsRead) {
536   std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
537 
538   for (std::vector<CodeGenSchedRW>::iterator I = RWVec.begin(), E = RWVec.end();
539        I != E; ++I) {
540     if (makeArrayRef(I->Sequence) == Seq)
541       return I - RWVec.begin();
542   }
543   // Index zero reserved for invalid RW.
544   return 0;
545 }
546 
547 /// Add this ReadWrite if it doesn't already exist.
548 unsigned CodeGenSchedModels::findOrInsertRW(ArrayRef<unsigned> Seq,
549                                             bool IsRead) {
550   assert(!Seq.empty() && "cannot insert empty sequence");
551   if (Seq.size() == 1)
552     return Seq.back();
553 
554   unsigned Idx = findRWForSequence(Seq, IsRead);
555   if (Idx)
556     return Idx;
557 
558   unsigned RWIdx = IsRead ? SchedReads.size() : SchedWrites.size();
559   CodeGenSchedRW SchedRW(RWIdx, IsRead, Seq, genRWName(Seq, IsRead));
560   if (IsRead)
561     SchedReads.push_back(SchedRW);
562   else
563     SchedWrites.push_back(SchedRW);
564   return RWIdx;
565 }
566 
567 /// Visit all the instruction definitions for this target to gather and
568 /// enumerate the itinerary classes. These are the explicitly specified
569 /// SchedClasses. More SchedClasses may be inferred.
570 void CodeGenSchedModels::collectSchedClasses() {
571 
572   // NoItinerary is always the first class at Idx=0
573   assert(SchedClasses.empty() && "Expected empty sched class");
574   SchedClasses.emplace_back(0, "NoInstrModel",
575                             Records.getDef("NoItinerary"));
576   SchedClasses.back().ProcIndices.push_back(0);
577 
578   // Create a SchedClass for each unique combination of itinerary class and
579   // SchedRW list.
580   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
581     Record *ItinDef = Inst->TheDef->getValueAsDef("Itinerary");
582     IdxVec Writes, Reads;
583     if (!Inst->TheDef->isValueUnset("SchedRW"))
584       findRWs(Inst->TheDef->getValueAsListOfDefs("SchedRW"), Writes, Reads);
585 
586     // ProcIdx == 0 indicates the class applies to all processors.
587     unsigned SCIdx = addSchedClass(ItinDef, Writes, Reads, /*ProcIndices*/{0});
588     InstrClassMap[Inst->TheDef] = SCIdx;
589   }
590   // Create classes for InstRW defs.
591   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
592   std::sort(InstRWDefs.begin(), InstRWDefs.end(), LessRecord());
593   DEBUG(dbgs() << "\n+++ SCHED CLASSES (createInstRWClass) +++\n");
594   for (Record *RWDef : InstRWDefs)
595     createInstRWClass(RWDef);
596 
597   NumInstrSchedClasses = SchedClasses.size();
598 
599   bool EnableDump = false;
600   DEBUG(EnableDump = true);
601   if (!EnableDump)
602     return;
603 
604   dbgs() << "\n+++ ITINERARIES and/or MACHINE MODELS (collectSchedClasses) +++\n";
605   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
606     StringRef InstName = Inst->TheDef->getName();
607     unsigned SCIdx = getSchedClassIdx(*Inst);
608     if (!SCIdx) {
609       if (!Inst->hasNoSchedulingInfo)
610         dbgs() << "No machine model for " << Inst->TheDef->getName() << '\n';
611       continue;
612     }
613     CodeGenSchedClass &SC = getSchedClass(SCIdx);
614     if (SC.ProcIndices[0] != 0)
615       PrintFatalError(Inst->TheDef->getLoc(), "Instruction's sched class "
616                       "must not be subtarget specific.");
617 
618     IdxVec ProcIndices;
619     if (SC.ItinClassDef->getName() != "NoItinerary") {
620       ProcIndices.push_back(0);
621       dbgs() << "Itinerary for " << InstName << ": "
622              << SC.ItinClassDef->getName() << '\n';
623     }
624     if (!SC.Writes.empty()) {
625       ProcIndices.push_back(0);
626       dbgs() << "SchedRW machine model for " << InstName;
627       for (IdxIter WI = SC.Writes.begin(), WE = SC.Writes.end(); WI != WE; ++WI)
628         dbgs() << " " << SchedWrites[*WI].Name;
629       for (IdxIter RI = SC.Reads.begin(), RE = SC.Reads.end(); RI != RE; ++RI)
630         dbgs() << " " << SchedReads[*RI].Name;
631       dbgs() << '\n';
632     }
633     const RecVec &RWDefs = SchedClasses[SCIdx].InstRWs;
634     for (Record *RWDef : RWDefs) {
635       const CodeGenProcModel &ProcModel =
636         getProcModel(RWDef->getValueAsDef("SchedModel"));
637       ProcIndices.push_back(ProcModel.Index);
638       dbgs() << "InstRW on " << ProcModel.ModelName << " for " << InstName;
639       IdxVec Writes;
640       IdxVec Reads;
641       findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
642               Writes, Reads);
643       for (unsigned WIdx : Writes)
644         dbgs() << " " << SchedWrites[WIdx].Name;
645       for (unsigned RIdx : Reads)
646         dbgs() << " " << SchedReads[RIdx].Name;
647       dbgs() << '\n';
648     }
649     // If ProcIndices contains zero, the class applies to all processors.
650     if (!std::count(ProcIndices.begin(), ProcIndices.end(), 0)) {
651       for (const CodeGenProcModel &PM : ProcModels) {
652         if (!std::count(ProcIndices.begin(), ProcIndices.end(), PM.Index))
653           dbgs() << "No machine model for " << Inst->TheDef->getName()
654                  << " on processor " << PM.ModelName << '\n';
655       }
656     }
657   }
658 }
659 
660 /// Find an SchedClass that has been inferred from a per-operand list of
661 /// SchedWrites and SchedReads.
662 unsigned CodeGenSchedModels::findSchedClassIdx(Record *ItinClassDef,
663                                                ArrayRef<unsigned> Writes,
664                                                ArrayRef<unsigned> Reads) const {
665   for (SchedClassIter I = schedClassBegin(), E = schedClassEnd(); I != E; ++I)
666     if (I->isKeyEqual(ItinClassDef, Writes, Reads))
667       return I - schedClassBegin();
668   return 0;
669 }
670 
671 // Get the SchedClass index for an instruction.
672 unsigned CodeGenSchedModels::getSchedClassIdx(
673   const CodeGenInstruction &Inst) const {
674 
675   return InstrClassMap.lookup(Inst.TheDef);
676 }
677 
678 std::string
679 CodeGenSchedModels::createSchedClassName(Record *ItinClassDef,
680                                          ArrayRef<unsigned> OperWrites,
681                                          ArrayRef<unsigned> OperReads) {
682 
683   std::string Name;
684   if (ItinClassDef && ItinClassDef->getName() != "NoItinerary")
685     Name = ItinClassDef->getName();
686   for (unsigned Idx : OperWrites) {
687     if (!Name.empty())
688       Name += '_';
689     Name += SchedWrites[Idx].Name;
690   }
691   for (unsigned Idx : OperReads) {
692     Name += '_';
693     Name += SchedReads[Idx].Name;
694   }
695   return Name;
696 }
697 
698 std::string CodeGenSchedModels::createSchedClassName(const RecVec &InstDefs) {
699 
700   std::string Name;
701   for (RecIter I = InstDefs.begin(), E = InstDefs.end(); I != E; ++I) {
702     if (I != InstDefs.begin())
703       Name += '_';
704     Name += (*I)->getName();
705   }
706   return Name;
707 }
708 
709 /// Add an inferred sched class from an itinerary class and per-operand list of
710 /// SchedWrites and SchedReads. ProcIndices contains the set of IDs of
711 /// processors that may utilize this class.
712 unsigned CodeGenSchedModels::addSchedClass(Record *ItinClassDef,
713                                            ArrayRef<unsigned> OperWrites,
714                                            ArrayRef<unsigned> OperReads,
715                                            ArrayRef<unsigned> ProcIndices) {
716   assert(!ProcIndices.empty() && "expect at least one ProcIdx");
717 
718   unsigned Idx = findSchedClassIdx(ItinClassDef, OperWrites, OperReads);
719   if (Idx || SchedClasses[0].isKeyEqual(ItinClassDef, OperWrites, OperReads)) {
720     IdxVec PI;
721     std::set_union(SchedClasses[Idx].ProcIndices.begin(),
722                    SchedClasses[Idx].ProcIndices.end(),
723                    ProcIndices.begin(), ProcIndices.end(),
724                    std::back_inserter(PI));
725     SchedClasses[Idx].ProcIndices = std::move(PI);
726     return Idx;
727   }
728   Idx = SchedClasses.size();
729   SchedClasses.emplace_back(Idx,
730                             createSchedClassName(ItinClassDef, OperWrites,
731                                                  OperReads),
732                             ItinClassDef);
733   CodeGenSchedClass &SC = SchedClasses.back();
734   SC.Writes = OperWrites;
735   SC.Reads = OperReads;
736   SC.ProcIndices = ProcIndices;
737 
738   return Idx;
739 }
740 
741 // Create classes for each set of opcodes that are in the same InstReadWrite
742 // definition across all processors.
743 void CodeGenSchedModels::createInstRWClass(Record *InstRWDef) {
744   // ClassInstrs will hold an entry for each subset of Instrs in InstRWDef that
745   // intersects with an existing class via a previous InstRWDef. Instrs that do
746   // not intersect with an existing class refer back to their former class as
747   // determined from ItinDef or SchedRW.
748   SmallMapVector<unsigned, SmallVector<Record *, 8>, 4> ClassInstrs;
749   // Sort Instrs into sets.
750   const RecVec *InstDefs = Sets.expand(InstRWDef);
751   if (InstDefs->empty())
752     PrintFatalError(InstRWDef->getLoc(), "No matching instruction opcodes");
753 
754   for (Record *InstDef : *InstDefs) {
755     InstClassMapTy::const_iterator Pos = InstrClassMap.find(InstDef);
756     if (Pos == InstrClassMap.end())
757       PrintFatalError(InstDef->getLoc(), "No sched class for instruction.");
758     unsigned SCIdx = Pos->second;
759     ClassInstrs[SCIdx].push_back(InstDef);
760   }
761   // For each set of Instrs, create a new class if necessary, and map or remap
762   // the Instrs to it.
763   for (auto &Entry : ClassInstrs) {
764     unsigned OldSCIdx = Entry.first;
765     ArrayRef<Record*> InstDefs = Entry.second;
766     // If the all instrs in the current class are accounted for, then leave
767     // them mapped to their old class.
768     if (OldSCIdx) {
769       const RecVec &RWDefs = SchedClasses[OldSCIdx].InstRWs;
770       if (!RWDefs.empty()) {
771         const RecVec *OrigInstDefs = Sets.expand(RWDefs[0]);
772         unsigned OrigNumInstrs =
773           count_if(*OrigInstDefs, [&](Record *OIDef) {
774                      return InstrClassMap[OIDef] == OldSCIdx;
775                    });
776         if (OrigNumInstrs == InstDefs.size()) {
777           assert(SchedClasses[OldSCIdx].ProcIndices[0] == 0 &&
778                  "expected a generic SchedClass");
779           Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
780           // Make sure we didn't already have a InstRW containing this
781           // instruction on this model.
782           for (Record *RWD : RWDefs) {
783             if (RWD->getValueAsDef("SchedModel") == RWModelDef &&
784                 RWModelDef->getValueAsBit("FullInstRWOverlapCheck")) {
785               for (Record *Inst : InstDefs) {
786                 PrintFatalError(InstRWDef->getLoc(), "Overlapping InstRW def " +
787                             Inst->getName() + " also matches " +
788                             RWD->getValue("Instrs")->getValue()->getAsString());
789               }
790             }
791           }
792           DEBUG(dbgs() << "InstRW: Reuse SC " << OldSCIdx << ":"
793                 << SchedClasses[OldSCIdx].Name << " on "
794                 << RWModelDef->getName() << "\n");
795           SchedClasses[OldSCIdx].InstRWs.push_back(InstRWDef);
796           continue;
797         }
798       }
799     }
800     unsigned SCIdx = SchedClasses.size();
801     SchedClasses.emplace_back(SCIdx, createSchedClassName(InstDefs), nullptr);
802     CodeGenSchedClass &SC = SchedClasses.back();
803     DEBUG(dbgs() << "InstRW: New SC " << SCIdx << ":" << SC.Name << " on "
804           << InstRWDef->getValueAsDef("SchedModel")->getName() << "\n");
805 
806     // Preserve ItinDef and Writes/Reads for processors without an InstRW entry.
807     SC.ItinClassDef = SchedClasses[OldSCIdx].ItinClassDef;
808     SC.Writes = SchedClasses[OldSCIdx].Writes;
809     SC.Reads = SchedClasses[OldSCIdx].Reads;
810     SC.ProcIndices.push_back(0);
811     // If we had an old class, copy it's InstRWs to this new class.
812     if (OldSCIdx) {
813       Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
814       for (Record *OldRWDef : SchedClasses[OldSCIdx].InstRWs) {
815         if (OldRWDef->getValueAsDef("SchedModel") == RWModelDef) {
816           for (Record *InstDef : InstDefs) {
817             PrintFatalError(OldRWDef->getLoc(), "Overlapping InstRW def " +
818                        InstDef->getName() + " also matches " +
819                        OldRWDef->getValue("Instrs")->getValue()->getAsString());
820           }
821         }
822         assert(OldRWDef != InstRWDef &&
823                "SchedClass has duplicate InstRW def");
824         SC.InstRWs.push_back(OldRWDef);
825       }
826     }
827     // Map each Instr to this new class.
828     for (Record *InstDef : InstDefs)
829       InstrClassMap[InstDef] = SCIdx;
830     SC.InstRWs.push_back(InstRWDef);
831   }
832 }
833 
834 // True if collectProcItins found anything.
835 bool CodeGenSchedModels::hasItineraries() const {
836   for (const CodeGenProcModel &PM : make_range(procModelBegin(),procModelEnd())) {
837     if (PM.hasItineraries())
838       return true;
839   }
840   return false;
841 }
842 
843 // Gather the processor itineraries.
844 void CodeGenSchedModels::collectProcItins() {
845   DEBUG(dbgs() << "\n+++ PROBLEM ITINERARIES (collectProcItins) +++\n");
846   for (CodeGenProcModel &ProcModel : ProcModels) {
847     if (!ProcModel.hasItineraries())
848       continue;
849 
850     RecVec ItinRecords = ProcModel.ItinsDef->getValueAsListOfDefs("IID");
851     assert(!ItinRecords.empty() && "ProcModel.hasItineraries is incorrect");
852 
853     // Populate ItinDefList with Itinerary records.
854     ProcModel.ItinDefList.resize(NumInstrSchedClasses);
855 
856     // Insert each itinerary data record in the correct position within
857     // the processor model's ItinDefList.
858     for (Record *ItinData : ItinRecords) {
859       Record *ItinDef = ItinData->getValueAsDef("TheClass");
860       bool FoundClass = false;
861       for (SchedClassIter SCI = schedClassBegin(), SCE = schedClassEnd();
862            SCI != SCE; ++SCI) {
863         // Multiple SchedClasses may share an itinerary. Update all of them.
864         if (SCI->ItinClassDef == ItinDef) {
865           ProcModel.ItinDefList[SCI->Index] = ItinData;
866           FoundClass = true;
867         }
868       }
869       if (!FoundClass) {
870         DEBUG(dbgs() << ProcModel.ItinsDef->getName()
871               << " missing class for itinerary " << ItinDef->getName() << '\n');
872       }
873     }
874     // Check for missing itinerary entries.
875     assert(!ProcModel.ItinDefList[0] && "NoItinerary class can't have rec");
876     DEBUG(
877       for (unsigned i = 1, N = ProcModel.ItinDefList.size(); i < N; ++i) {
878         if (!ProcModel.ItinDefList[i])
879           dbgs() << ProcModel.ItinsDef->getName()
880                  << " missing itinerary for class "
881                  << SchedClasses[i].Name << '\n';
882       });
883   }
884 }
885 
886 // Gather the read/write types for each itinerary class.
887 void CodeGenSchedModels::collectProcItinRW() {
888   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
889   std::sort(ItinRWDefs.begin(), ItinRWDefs.end(), LessRecord());
890   for (Record *RWDef  : ItinRWDefs) {
891     if (!RWDef->getValueInit("SchedModel")->isComplete())
892       PrintFatalError(RWDef->getLoc(), "SchedModel is undefined");
893     Record *ModelDef = RWDef->getValueAsDef("SchedModel");
894     ProcModelMapTy::const_iterator I = ProcModelMap.find(ModelDef);
895     if (I == ProcModelMap.end()) {
896       PrintFatalError(RWDef->getLoc(), "Undefined SchedMachineModel "
897                     + ModelDef->getName());
898     }
899     ProcModels[I->second].ItinRWDefs.push_back(RWDef);
900   }
901 }
902 
903 // Gather the unsupported features for processor models.
904 void CodeGenSchedModels::collectProcUnsupportedFeatures() {
905   for (CodeGenProcModel &ProcModel : ProcModels) {
906     for (Record *Pred : ProcModel.ModelDef->getValueAsListOfDefs("UnsupportedFeatures")) {
907        ProcModel.UnsupportedFeaturesDefs.push_back(Pred);
908     }
909   }
910 }
911 
912 /// Infer new classes from existing classes. In the process, this may create new
913 /// SchedWrites from sequences of existing SchedWrites.
914 void CodeGenSchedModels::inferSchedClasses() {
915   DEBUG(dbgs() << "\n+++ INFERRING SCHED CLASSES (inferSchedClasses) +++\n");
916   DEBUG(dbgs() << NumInstrSchedClasses << " instr sched classes.\n");
917 
918   // Visit all existing classes and newly created classes.
919   for (unsigned Idx = 0; Idx != SchedClasses.size(); ++Idx) {
920     assert(SchedClasses[Idx].Index == Idx && "bad SCIdx");
921 
922     if (SchedClasses[Idx].ItinClassDef)
923       inferFromItinClass(SchedClasses[Idx].ItinClassDef, Idx);
924     if (!SchedClasses[Idx].InstRWs.empty())
925       inferFromInstRWs(Idx);
926     if (!SchedClasses[Idx].Writes.empty()) {
927       inferFromRW(SchedClasses[Idx].Writes, SchedClasses[Idx].Reads,
928                   Idx, SchedClasses[Idx].ProcIndices);
929     }
930     assert(SchedClasses.size() < (NumInstrSchedClasses*6) &&
931            "too many SchedVariants");
932   }
933 }
934 
935 /// Infer classes from per-processor itinerary resources.
936 void CodeGenSchedModels::inferFromItinClass(Record *ItinClassDef,
937                                             unsigned FromClassIdx) {
938   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
939     const CodeGenProcModel &PM = ProcModels[PIdx];
940     // For all ItinRW entries.
941     bool HasMatch = false;
942     for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
943          II != IE; ++II) {
944       RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
945       if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
946         continue;
947       if (HasMatch)
948         PrintFatalError((*II)->getLoc(), "Duplicate itinerary class "
949                       + ItinClassDef->getName()
950                       + " in ItinResources for " + PM.ModelName);
951       HasMatch = true;
952       IdxVec Writes, Reads;
953       findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
954       inferFromRW(Writes, Reads, FromClassIdx, PIdx);
955     }
956   }
957 }
958 
959 /// Infer classes from per-processor InstReadWrite definitions.
960 void CodeGenSchedModels::inferFromInstRWs(unsigned SCIdx) {
961   for (unsigned I = 0, E = SchedClasses[SCIdx].InstRWs.size(); I != E; ++I) {
962     assert(SchedClasses[SCIdx].InstRWs.size() == E && "InstrRWs was mutated!");
963     Record *Rec = SchedClasses[SCIdx].InstRWs[I];
964     const RecVec *InstDefs = Sets.expand(Rec);
965     RecIter II = InstDefs->begin(), IE = InstDefs->end();
966     for (; II != IE; ++II) {
967       if (InstrClassMap[*II] == SCIdx)
968         break;
969     }
970     // If this class no longer has any instructions mapped to it, it has become
971     // irrelevant.
972     if (II == IE)
973       continue;
974     IdxVec Writes, Reads;
975     findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
976     unsigned PIdx = getProcModel(Rec->getValueAsDef("SchedModel")).Index;
977     inferFromRW(Writes, Reads, SCIdx, PIdx); // May mutate SchedClasses.
978   }
979 }
980 
981 namespace {
982 
983 // Helper for substituteVariantOperand.
984 struct TransVariant {
985   Record *VarOrSeqDef;  // Variant or sequence.
986   unsigned RWIdx;       // Index of this variant or sequence's matched type.
987   unsigned ProcIdx;     // Processor model index or zero for any.
988   unsigned TransVecIdx; // Index into PredTransitions::TransVec.
989 
990   TransVariant(Record *def, unsigned rwi, unsigned pi, unsigned ti):
991     VarOrSeqDef(def), RWIdx(rwi), ProcIdx(pi), TransVecIdx(ti) {}
992 };
993 
994 // Associate a predicate with the SchedReadWrite that it guards.
995 // RWIdx is the index of the read/write variant.
996 struct PredCheck {
997   bool IsRead;
998   unsigned RWIdx;
999   Record *Predicate;
1000 
1001   PredCheck(bool r, unsigned w, Record *p): IsRead(r), RWIdx(w), Predicate(p) {}
1002 };
1003 
1004 // A Predicate transition is a list of RW sequences guarded by a PredTerm.
1005 struct PredTransition {
1006   // A predicate term is a conjunction of PredChecks.
1007   SmallVector<PredCheck, 4> PredTerm;
1008   SmallVector<SmallVector<unsigned,4>, 16> WriteSequences;
1009   SmallVector<SmallVector<unsigned,4>, 16> ReadSequences;
1010   SmallVector<unsigned, 4> ProcIndices;
1011 };
1012 
1013 // Encapsulate a set of partially constructed transitions.
1014 // The results are built by repeated calls to substituteVariants.
1015 class PredTransitions {
1016   CodeGenSchedModels &SchedModels;
1017 
1018 public:
1019   std::vector<PredTransition> TransVec;
1020 
1021   PredTransitions(CodeGenSchedModels &sm): SchedModels(sm) {}
1022 
1023   void substituteVariantOperand(const SmallVectorImpl<unsigned> &RWSeq,
1024                                 bool IsRead, unsigned StartIdx);
1025 
1026   void substituteVariants(const PredTransition &Trans);
1027 
1028 #ifndef NDEBUG
1029   void dump() const;
1030 #endif
1031 
1032 private:
1033   bool mutuallyExclusive(Record *PredDef, ArrayRef<PredCheck> Term);
1034   void getIntersectingVariants(
1035     const CodeGenSchedRW &SchedRW, unsigned TransIdx,
1036     std::vector<TransVariant> &IntersectingVariants);
1037   void pushVariant(const TransVariant &VInfo, bool IsRead);
1038 };
1039 
1040 } // end anonymous namespace
1041 
1042 // Return true if this predicate is mutually exclusive with a PredTerm. This
1043 // degenerates into checking if the predicate is mutually exclusive with any
1044 // predicate in the Term's conjunction.
1045 //
1046 // All predicates associated with a given SchedRW are considered mutually
1047 // exclusive. This should work even if the conditions expressed by the
1048 // predicates are not exclusive because the predicates for a given SchedWrite
1049 // are always checked in the order they are defined in the .td file. Later
1050 // conditions implicitly negate any prior condition.
1051 bool PredTransitions::mutuallyExclusive(Record *PredDef,
1052                                         ArrayRef<PredCheck> Term) {
1053   for (const PredCheck &PC: Term) {
1054     if (PC.Predicate == PredDef)
1055       return false;
1056 
1057     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(PC.RWIdx, PC.IsRead);
1058     assert(SchedRW.HasVariants && "PredCheck must refer to a SchedVariant");
1059     RecVec Variants = SchedRW.TheDef->getValueAsListOfDefs("Variants");
1060     for (RecIter VI = Variants.begin(), VE = Variants.end(); VI != VE; ++VI) {
1061       if ((*VI)->getValueAsDef("Predicate") == PredDef)
1062         return true;
1063     }
1064   }
1065   return false;
1066 }
1067 
1068 static bool hasAliasedVariants(const CodeGenSchedRW &RW,
1069                                CodeGenSchedModels &SchedModels) {
1070   if (RW.HasVariants)
1071     return true;
1072 
1073   for (Record *Alias : RW.Aliases) {
1074     const CodeGenSchedRW &AliasRW =
1075       SchedModels.getSchedRW(Alias->getValueAsDef("AliasRW"));
1076     if (AliasRW.HasVariants)
1077       return true;
1078     if (AliasRW.IsSequence) {
1079       IdxVec ExpandedRWs;
1080       SchedModels.expandRWSequence(AliasRW.Index, ExpandedRWs, AliasRW.IsRead);
1081       for (IdxIter SI = ExpandedRWs.begin(), SE = ExpandedRWs.end();
1082            SI != SE; ++SI) {
1083         if (hasAliasedVariants(SchedModels.getSchedRW(*SI, AliasRW.IsRead),
1084                                SchedModels)) {
1085           return true;
1086         }
1087       }
1088     }
1089   }
1090   return false;
1091 }
1092 
1093 static bool hasVariant(ArrayRef<PredTransition> Transitions,
1094                        CodeGenSchedModels &SchedModels) {
1095   for (ArrayRef<PredTransition>::iterator
1096          PTI = Transitions.begin(), PTE = Transitions.end();
1097        PTI != PTE; ++PTI) {
1098     for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
1099            WSI = PTI->WriteSequences.begin(), WSE = PTI->WriteSequences.end();
1100          WSI != WSE; ++WSI) {
1101       for (SmallVectorImpl<unsigned>::const_iterator
1102              WI = WSI->begin(), WE = WSI->end(); WI != WE; ++WI) {
1103         if (hasAliasedVariants(SchedModels.getSchedWrite(*WI), SchedModels))
1104           return true;
1105       }
1106     }
1107     for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
1108            RSI = PTI->ReadSequences.begin(), RSE = PTI->ReadSequences.end();
1109          RSI != RSE; ++RSI) {
1110       for (SmallVectorImpl<unsigned>::const_iterator
1111              RI = RSI->begin(), RE = RSI->end(); RI != RE; ++RI) {
1112         if (hasAliasedVariants(SchedModels.getSchedRead(*RI), SchedModels))
1113           return true;
1114       }
1115     }
1116   }
1117   return false;
1118 }
1119 
1120 // Populate IntersectingVariants with any variants or aliased sequences of the
1121 // given SchedRW whose processor indices and predicates are not mutually
1122 // exclusive with the given transition.
1123 void PredTransitions::getIntersectingVariants(
1124   const CodeGenSchedRW &SchedRW, unsigned TransIdx,
1125   std::vector<TransVariant> &IntersectingVariants) {
1126 
1127   bool GenericRW = false;
1128 
1129   std::vector<TransVariant> Variants;
1130   if (SchedRW.HasVariants) {
1131     unsigned VarProcIdx = 0;
1132     if (SchedRW.TheDef->getValueInit("SchedModel")->isComplete()) {
1133       Record *ModelDef = SchedRW.TheDef->getValueAsDef("SchedModel");
1134       VarProcIdx = SchedModels.getProcModel(ModelDef).Index;
1135     }
1136     // Push each variant. Assign TransVecIdx later.
1137     const RecVec VarDefs = SchedRW.TheDef->getValueAsListOfDefs("Variants");
1138     for (Record *VarDef : VarDefs)
1139       Variants.push_back(TransVariant(VarDef, SchedRW.Index, VarProcIdx, 0));
1140     if (VarProcIdx == 0)
1141       GenericRW = true;
1142   }
1143   for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
1144        AI != AE; ++AI) {
1145     // If either the SchedAlias itself or the SchedReadWrite that it aliases
1146     // to is defined within a processor model, constrain all variants to
1147     // that processor.
1148     unsigned AliasProcIdx = 0;
1149     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
1150       Record *ModelDef = (*AI)->getValueAsDef("SchedModel");
1151       AliasProcIdx = SchedModels.getProcModel(ModelDef).Index;
1152     }
1153     const CodeGenSchedRW &AliasRW =
1154       SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
1155 
1156     if (AliasRW.HasVariants) {
1157       const RecVec VarDefs = AliasRW.TheDef->getValueAsListOfDefs("Variants");
1158       for (Record *VD : VarDefs)
1159         Variants.push_back(TransVariant(VD, AliasRW.Index, AliasProcIdx, 0));
1160     }
1161     if (AliasRW.IsSequence) {
1162       Variants.push_back(
1163         TransVariant(AliasRW.TheDef, SchedRW.Index, AliasProcIdx, 0));
1164     }
1165     if (AliasProcIdx == 0)
1166       GenericRW = true;
1167   }
1168   for (TransVariant &Variant : Variants) {
1169     // Don't expand variants if the processor models don't intersect.
1170     // A zero processor index means any processor.
1171     SmallVectorImpl<unsigned> &ProcIndices = TransVec[TransIdx].ProcIndices;
1172     if (ProcIndices[0] && Variant.ProcIdx) {
1173       unsigned Cnt = std::count(ProcIndices.begin(), ProcIndices.end(),
1174                                 Variant.ProcIdx);
1175       if (!Cnt)
1176         continue;
1177       if (Cnt > 1) {
1178         const CodeGenProcModel &PM =
1179           *(SchedModels.procModelBegin() + Variant.ProcIdx);
1180         PrintFatalError(Variant.VarOrSeqDef->getLoc(),
1181                         "Multiple variants defined for processor " +
1182                         PM.ModelName +
1183                         " Ensure only one SchedAlias exists per RW.");
1184       }
1185     }
1186     if (Variant.VarOrSeqDef->isSubClassOf("SchedVar")) {
1187       Record *PredDef = Variant.VarOrSeqDef->getValueAsDef("Predicate");
1188       if (mutuallyExclusive(PredDef, TransVec[TransIdx].PredTerm))
1189         continue;
1190     }
1191     if (IntersectingVariants.empty()) {
1192       // The first variant builds on the existing transition.
1193       Variant.TransVecIdx = TransIdx;
1194       IntersectingVariants.push_back(Variant);
1195     }
1196     else {
1197       // Push another copy of the current transition for more variants.
1198       Variant.TransVecIdx = TransVec.size();
1199       IntersectingVariants.push_back(Variant);
1200       TransVec.push_back(TransVec[TransIdx]);
1201     }
1202   }
1203   if (GenericRW && IntersectingVariants.empty()) {
1204     PrintFatalError(SchedRW.TheDef->getLoc(), "No variant of this type has "
1205                     "a matching predicate on any processor");
1206   }
1207 }
1208 
1209 // Push the Reads/Writes selected by this variant onto the PredTransition
1210 // specified by VInfo.
1211 void PredTransitions::
1212 pushVariant(const TransVariant &VInfo, bool IsRead) {
1213   PredTransition &Trans = TransVec[VInfo.TransVecIdx];
1214 
1215   // If this operand transition is reached through a processor-specific alias,
1216   // then the whole transition is specific to this processor.
1217   if (VInfo.ProcIdx != 0)
1218     Trans.ProcIndices.assign(1, VInfo.ProcIdx);
1219 
1220   IdxVec SelectedRWs;
1221   if (VInfo.VarOrSeqDef->isSubClassOf("SchedVar")) {
1222     Record *PredDef = VInfo.VarOrSeqDef->getValueAsDef("Predicate");
1223     Trans.PredTerm.push_back(PredCheck(IsRead, VInfo.RWIdx,PredDef));
1224     RecVec SelectedDefs = VInfo.VarOrSeqDef->getValueAsListOfDefs("Selected");
1225     SchedModels.findRWs(SelectedDefs, SelectedRWs, IsRead);
1226   }
1227   else {
1228     assert(VInfo.VarOrSeqDef->isSubClassOf("WriteSequence") &&
1229            "variant must be a SchedVariant or aliased WriteSequence");
1230     SelectedRWs.push_back(SchedModels.getSchedRWIdx(VInfo.VarOrSeqDef, IsRead));
1231   }
1232 
1233   const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(VInfo.RWIdx, IsRead);
1234 
1235   SmallVectorImpl<SmallVector<unsigned,4>> &RWSequences = IsRead
1236     ? Trans.ReadSequences : Trans.WriteSequences;
1237   if (SchedRW.IsVariadic) {
1238     unsigned OperIdx = RWSequences.size()-1;
1239     // Make N-1 copies of this transition's last sequence.
1240     for (unsigned i = 1, e = SelectedRWs.size(); i != e; ++i) {
1241       // Create a temporary copy the vector could reallocate.
1242       RWSequences.reserve(RWSequences.size() + 1);
1243       RWSequences.push_back(RWSequences[OperIdx]);
1244     }
1245     // Push each of the N elements of the SelectedRWs onto a copy of the last
1246     // sequence (split the current operand into N operands).
1247     // Note that write sequences should be expanded within this loop--the entire
1248     // sequence belongs to a single operand.
1249     for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
1250          RWI != RWE; ++RWI, ++OperIdx) {
1251       IdxVec ExpandedRWs;
1252       if (IsRead)
1253         ExpandedRWs.push_back(*RWI);
1254       else
1255         SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
1256       RWSequences[OperIdx].insert(RWSequences[OperIdx].end(),
1257                                   ExpandedRWs.begin(), ExpandedRWs.end());
1258     }
1259     assert(OperIdx == RWSequences.size() && "missed a sequence");
1260   }
1261   else {
1262     // Push this transition's expanded sequence onto this transition's last
1263     // sequence (add to the current operand's sequence).
1264     SmallVectorImpl<unsigned> &Seq = RWSequences.back();
1265     IdxVec ExpandedRWs;
1266     for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
1267          RWI != RWE; ++RWI) {
1268       if (IsRead)
1269         ExpandedRWs.push_back(*RWI);
1270       else
1271         SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
1272     }
1273     Seq.insert(Seq.end(), ExpandedRWs.begin(), ExpandedRWs.end());
1274   }
1275 }
1276 
1277 // RWSeq is a sequence of all Reads or all Writes for the next read or write
1278 // operand. StartIdx is an index into TransVec where partial results
1279 // starts. RWSeq must be applied to all transitions between StartIdx and the end
1280 // of TransVec.
1281 void PredTransitions::substituteVariantOperand(
1282   const SmallVectorImpl<unsigned> &RWSeq, bool IsRead, unsigned StartIdx) {
1283 
1284   // Visit each original RW within the current sequence.
1285   for (SmallVectorImpl<unsigned>::const_iterator
1286          RWI = RWSeq.begin(), RWE = RWSeq.end(); RWI != RWE; ++RWI) {
1287     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(*RWI, IsRead);
1288     // Push this RW on all partial PredTransitions or distribute variants.
1289     // New PredTransitions may be pushed within this loop which should not be
1290     // revisited (TransEnd must be loop invariant).
1291     for (unsigned TransIdx = StartIdx, TransEnd = TransVec.size();
1292          TransIdx != TransEnd; ++TransIdx) {
1293       // In the common case, push RW onto the current operand's sequence.
1294       if (!hasAliasedVariants(SchedRW, SchedModels)) {
1295         if (IsRead)
1296           TransVec[TransIdx].ReadSequences.back().push_back(*RWI);
1297         else
1298           TransVec[TransIdx].WriteSequences.back().push_back(*RWI);
1299         continue;
1300       }
1301       // Distribute this partial PredTransition across intersecting variants.
1302       // This will push a copies of TransVec[TransIdx] on the back of TransVec.
1303       std::vector<TransVariant> IntersectingVariants;
1304       getIntersectingVariants(SchedRW, TransIdx, IntersectingVariants);
1305       // Now expand each variant on top of its copy of the transition.
1306       for (std::vector<TransVariant>::const_iterator
1307              IVI = IntersectingVariants.begin(),
1308              IVE = IntersectingVariants.end();
1309            IVI != IVE; ++IVI) {
1310         pushVariant(*IVI, IsRead);
1311       }
1312     }
1313   }
1314 }
1315 
1316 // For each variant of a Read/Write in Trans, substitute the sequence of
1317 // Read/Writes guarded by the variant. This is exponential in the number of
1318 // variant Read/Writes, but in practice detection of mutually exclusive
1319 // predicates should result in linear growth in the total number variants.
1320 //
1321 // This is one step in a breadth-first search of nested variants.
1322 void PredTransitions::substituteVariants(const PredTransition &Trans) {
1323   // Build up a set of partial results starting at the back of
1324   // PredTransitions. Remember the first new transition.
1325   unsigned StartIdx = TransVec.size();
1326   TransVec.emplace_back();
1327   TransVec.back().PredTerm = Trans.PredTerm;
1328   TransVec.back().ProcIndices = Trans.ProcIndices;
1329 
1330   // Visit each original write sequence.
1331   for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
1332          WSI = Trans.WriteSequences.begin(), WSE = Trans.WriteSequences.end();
1333        WSI != WSE; ++WSI) {
1334     // Push a new (empty) write sequence onto all partial Transitions.
1335     for (std::vector<PredTransition>::iterator I =
1336            TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
1337       I->WriteSequences.emplace_back();
1338     }
1339     substituteVariantOperand(*WSI, /*IsRead=*/false, StartIdx);
1340   }
1341   // Visit each original read sequence.
1342   for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
1343          RSI = Trans.ReadSequences.begin(), RSE = Trans.ReadSequences.end();
1344        RSI != RSE; ++RSI) {
1345     // Push a new (empty) read sequence onto all partial Transitions.
1346     for (std::vector<PredTransition>::iterator I =
1347            TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
1348       I->ReadSequences.emplace_back();
1349     }
1350     substituteVariantOperand(*RSI, /*IsRead=*/true, StartIdx);
1351   }
1352 }
1353 
1354 // Create a new SchedClass for each variant found by inferFromRW. Pass
1355 static void inferFromTransitions(ArrayRef<PredTransition> LastTransitions,
1356                                  unsigned FromClassIdx,
1357                                  CodeGenSchedModels &SchedModels) {
1358   // For each PredTransition, create a new CodeGenSchedTransition, which usually
1359   // requires creating a new SchedClass.
1360   for (ArrayRef<PredTransition>::iterator
1361          I = LastTransitions.begin(), E = LastTransitions.end(); I != E; ++I) {
1362     IdxVec OperWritesVariant;
1363     transform(I->WriteSequences, std::back_inserter(OperWritesVariant),
1364               [&SchedModels](ArrayRef<unsigned> WS) {
1365                 return SchedModels.findOrInsertRW(WS, /*IsRead=*/false);
1366               });
1367     IdxVec OperReadsVariant;
1368     transform(I->ReadSequences, std::back_inserter(OperReadsVariant),
1369               [&SchedModels](ArrayRef<unsigned> RS) {
1370                 return SchedModels.findOrInsertRW(RS, /*IsRead=*/true);
1371               });
1372     CodeGenSchedTransition SCTrans;
1373     SCTrans.ToClassIdx =
1374       SchedModels.addSchedClass(/*ItinClassDef=*/nullptr, OperWritesVariant,
1375                                 OperReadsVariant, I->ProcIndices);
1376     SCTrans.ProcIndices.assign(I->ProcIndices.begin(), I->ProcIndices.end());
1377     // The final PredTerm is unique set of predicates guarding the transition.
1378     RecVec Preds;
1379     transform(I->PredTerm, std::back_inserter(Preds),
1380               [](const PredCheck &P) {
1381                 return P.Predicate;
1382               });
1383     Preds.erase(std::unique(Preds.begin(), Preds.end()), Preds.end());
1384     SCTrans.PredTerm = std::move(Preds);
1385     SchedModels.getSchedClass(FromClassIdx)
1386         .Transitions.push_back(std::move(SCTrans));
1387   }
1388 }
1389 
1390 // Create new SchedClasses for the given ReadWrite list. If any of the
1391 // ReadWrites refers to a SchedVariant, create a new SchedClass for each variant
1392 // of the ReadWrite list, following Aliases if necessary.
1393 void CodeGenSchedModels::inferFromRW(ArrayRef<unsigned> OperWrites,
1394                                      ArrayRef<unsigned> OperReads,
1395                                      unsigned FromClassIdx,
1396                                      ArrayRef<unsigned> ProcIndices) {
1397   DEBUG(dbgs() << "INFER RW proc("; dumpIdxVec(ProcIndices); dbgs() << ") ");
1398 
1399   // Create a seed transition with an empty PredTerm and the expanded sequences
1400   // of SchedWrites for the current SchedClass.
1401   std::vector<PredTransition> LastTransitions;
1402   LastTransitions.emplace_back();
1403   LastTransitions.back().ProcIndices.append(ProcIndices.begin(),
1404                                             ProcIndices.end());
1405 
1406   for (unsigned WriteIdx : OperWrites) {
1407     IdxVec WriteSeq;
1408     expandRWSequence(WriteIdx, WriteSeq, /*IsRead=*/false);
1409     LastTransitions[0].WriteSequences.emplace_back();
1410     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].WriteSequences.back();
1411     Seq.append(WriteSeq.begin(), WriteSeq.end());
1412     DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
1413   }
1414   DEBUG(dbgs() << " Reads: ");
1415   for (unsigned ReadIdx : OperReads) {
1416     IdxVec ReadSeq;
1417     expandRWSequence(ReadIdx, ReadSeq, /*IsRead=*/true);
1418     LastTransitions[0].ReadSequences.emplace_back();
1419     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].ReadSequences.back();
1420     Seq.append(ReadSeq.begin(), ReadSeq.end());
1421     DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
1422   }
1423   DEBUG(dbgs() << '\n');
1424 
1425   // Collect all PredTransitions for individual operands.
1426   // Iterate until no variant writes remain.
1427   while (hasVariant(LastTransitions, *this)) {
1428     PredTransitions Transitions(*this);
1429     for (const PredTransition &Trans : LastTransitions)
1430       Transitions.substituteVariants(Trans);
1431     DEBUG(Transitions.dump());
1432     LastTransitions.swap(Transitions.TransVec);
1433   }
1434   // If the first transition has no variants, nothing to do.
1435   if (LastTransitions[0].PredTerm.empty())
1436     return;
1437 
1438   // WARNING: We are about to mutate the SchedClasses vector. Do not refer to
1439   // OperWrites, OperReads, or ProcIndices after calling inferFromTransitions.
1440   inferFromTransitions(LastTransitions, FromClassIdx, *this);
1441 }
1442 
1443 // Check if any processor resource group contains all resource records in
1444 // SubUnits.
1445 bool CodeGenSchedModels::hasSuperGroup(RecVec &SubUnits, CodeGenProcModel &PM) {
1446   for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
1447     if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
1448       continue;
1449     RecVec SuperUnits =
1450       PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
1451     RecIter RI = SubUnits.begin(), RE = SubUnits.end();
1452     for ( ; RI != RE; ++RI) {
1453       if (!is_contained(SuperUnits, *RI)) {
1454         break;
1455       }
1456     }
1457     if (RI == RE)
1458       return true;
1459   }
1460   return false;
1461 }
1462 
1463 // Verify that overlapping groups have a common supergroup.
1464 void CodeGenSchedModels::verifyProcResourceGroups(CodeGenProcModel &PM) {
1465   for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
1466     if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
1467       continue;
1468     RecVec CheckUnits =
1469       PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
1470     for (unsigned j = i+1; j < e; ++j) {
1471       if (!PM.ProcResourceDefs[j]->isSubClassOf("ProcResGroup"))
1472         continue;
1473       RecVec OtherUnits =
1474         PM.ProcResourceDefs[j]->getValueAsListOfDefs("Resources");
1475       if (std::find_first_of(CheckUnits.begin(), CheckUnits.end(),
1476                              OtherUnits.begin(), OtherUnits.end())
1477           != CheckUnits.end()) {
1478         // CheckUnits and OtherUnits overlap
1479         OtherUnits.insert(OtherUnits.end(), CheckUnits.begin(),
1480                           CheckUnits.end());
1481         if (!hasSuperGroup(OtherUnits, PM)) {
1482           PrintFatalError((PM.ProcResourceDefs[i])->getLoc(),
1483                           "proc resource group overlaps with "
1484                           + PM.ProcResourceDefs[j]->getName()
1485                           + " but no supergroup contains both.");
1486         }
1487       }
1488     }
1489   }
1490 }
1491 
1492 // Collect all the RegisterFile definitions available in this target.
1493 void CodeGenSchedModels::collectRegisterFiles() {
1494   RecVec RegisterFileDefs = Records.getAllDerivedDefinitions("RegisterFile");
1495 
1496   // RegisterFiles is the vector of CodeGenRegisterFile.
1497   for (Record *RF : RegisterFileDefs) {
1498     // For each register file definition, construct a CodeGenRegisterFile object
1499     // and add it to the appropriate scheduling model.
1500     CodeGenProcModel &PM = getProcModel(RF->getValueAsDef("SchedModel"));
1501     PM.RegisterFiles.emplace_back(CodeGenRegisterFile(RF->getName(),RF));
1502     CodeGenRegisterFile &CGRF = PM.RegisterFiles.back();
1503 
1504     // Now set the number of physical registers as well as the cost of registers
1505     // in each register class.
1506     CGRF.NumPhysRegs = RF->getValueAsInt("NumPhysRegs");
1507     RecVec RegisterClasses = RF->getValueAsListOfDefs("RegClasses");
1508     std::vector<int64_t> RegisterCosts = RF->getValueAsListOfInts("RegCosts");
1509     for (unsigned I = 0, E = RegisterClasses.size(); I < E; ++I) {
1510       int Cost = RegisterCosts.size() > I ? RegisterCosts[I] : 1;
1511       CGRF.Costs.emplace_back(RegisterClasses[I], Cost);
1512     }
1513   }
1514 }
1515 
1516 // Collect and sort WriteRes, ReadAdvance, and ProcResources.
1517 void CodeGenSchedModels::collectProcResources() {
1518   ProcResourceDefs = Records.getAllDerivedDefinitions("ProcResourceUnits");
1519   ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
1520 
1521   // Add any subtarget-specific SchedReadWrites that are directly associated
1522   // with processor resources. Refer to the parent SchedClass's ProcIndices to
1523   // determine which processors they apply to.
1524   for (SchedClassIter SCI = schedClassBegin(), SCE = schedClassEnd();
1525        SCI != SCE; ++SCI) {
1526     if (SCI->ItinClassDef)
1527       collectItinProcResources(SCI->ItinClassDef);
1528     else {
1529       // This class may have a default ReadWrite list which can be overriden by
1530       // InstRW definitions.
1531       if (!SCI->InstRWs.empty()) {
1532         for (RecIter RWI = SCI->InstRWs.begin(), RWE = SCI->InstRWs.end();
1533              RWI != RWE; ++RWI) {
1534           Record *RWModelDef = (*RWI)->getValueAsDef("SchedModel");
1535           unsigned PIdx = getProcModel(RWModelDef).Index;
1536           IdxVec Writes, Reads;
1537           findRWs((*RWI)->getValueAsListOfDefs("OperandReadWrites"),
1538                   Writes, Reads);
1539           collectRWResources(Writes, Reads, PIdx);
1540         }
1541       }
1542       collectRWResources(SCI->Writes, SCI->Reads, SCI->ProcIndices);
1543     }
1544   }
1545   // Add resources separately defined by each subtarget.
1546   RecVec WRDefs = Records.getAllDerivedDefinitions("WriteRes");
1547   for (Record *WR : WRDefs) {
1548     Record *ModelDef = WR->getValueAsDef("SchedModel");
1549     addWriteRes(WR, getProcModel(ModelDef).Index);
1550   }
1551   RecVec SWRDefs = Records.getAllDerivedDefinitions("SchedWriteRes");
1552   for (Record *SWR : SWRDefs) {
1553     Record *ModelDef = SWR->getValueAsDef("SchedModel");
1554     addWriteRes(SWR, getProcModel(ModelDef).Index);
1555   }
1556   RecVec RADefs = Records.getAllDerivedDefinitions("ReadAdvance");
1557   for (Record *RA : RADefs) {
1558     Record *ModelDef = RA->getValueAsDef("SchedModel");
1559     addReadAdvance(RA, getProcModel(ModelDef).Index);
1560   }
1561   RecVec SRADefs = Records.getAllDerivedDefinitions("SchedReadAdvance");
1562   for (Record *SRA : SRADefs) {
1563     if (SRA->getValueInit("SchedModel")->isComplete()) {
1564       Record *ModelDef = SRA->getValueAsDef("SchedModel");
1565       addReadAdvance(SRA, getProcModel(ModelDef).Index);
1566     }
1567   }
1568   // Add ProcResGroups that are defined within this processor model, which may
1569   // not be directly referenced but may directly specify a buffer size.
1570   RecVec ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
1571   for (Record *PRG : ProcResGroups) {
1572     if (!PRG->getValueInit("SchedModel")->isComplete())
1573       continue;
1574     CodeGenProcModel &PM = getProcModel(PRG->getValueAsDef("SchedModel"));
1575     if (!is_contained(PM.ProcResourceDefs, PRG))
1576       PM.ProcResourceDefs.push_back(PRG);
1577   }
1578   // Add ProcResourceUnits unconditionally.
1579   for (Record *PRU : Records.getAllDerivedDefinitions("ProcResourceUnits")) {
1580     if (!PRU->getValueInit("SchedModel")->isComplete())
1581       continue;
1582     CodeGenProcModel &PM = getProcModel(PRU->getValueAsDef("SchedModel"));
1583     if (!is_contained(PM.ProcResourceDefs, PRU))
1584       PM.ProcResourceDefs.push_back(PRU);
1585   }
1586   // Finalize each ProcModel by sorting the record arrays.
1587   for (CodeGenProcModel &PM : ProcModels) {
1588     std::sort(PM.WriteResDefs.begin(), PM.WriteResDefs.end(),
1589               LessRecord());
1590     std::sort(PM.ReadAdvanceDefs.begin(), PM.ReadAdvanceDefs.end(),
1591               LessRecord());
1592     std::sort(PM.ProcResourceDefs.begin(), PM.ProcResourceDefs.end(),
1593               LessRecord());
1594     DEBUG(
1595       PM.dump();
1596       dbgs() << "WriteResDefs: ";
1597       for (RecIter RI = PM.WriteResDefs.begin(),
1598              RE = PM.WriteResDefs.end(); RI != RE; ++RI) {
1599         if ((*RI)->isSubClassOf("WriteRes"))
1600           dbgs() << (*RI)->getValueAsDef("WriteType")->getName() << " ";
1601         else
1602           dbgs() << (*RI)->getName() << " ";
1603       }
1604       dbgs() << "\nReadAdvanceDefs: ";
1605       for (RecIter RI = PM.ReadAdvanceDefs.begin(),
1606              RE = PM.ReadAdvanceDefs.end(); RI != RE; ++RI) {
1607         if ((*RI)->isSubClassOf("ReadAdvance"))
1608           dbgs() << (*RI)->getValueAsDef("ReadType")->getName() << " ";
1609         else
1610           dbgs() << (*RI)->getName() << " ";
1611       }
1612       dbgs() << "\nProcResourceDefs: ";
1613       for (RecIter RI = PM.ProcResourceDefs.begin(),
1614              RE = PM.ProcResourceDefs.end(); RI != RE; ++RI) {
1615         dbgs() << (*RI)->getName() << " ";
1616       }
1617       dbgs() << '\n');
1618     verifyProcResourceGroups(PM);
1619   }
1620 
1621   ProcResourceDefs.clear();
1622   ProcResGroups.clear();
1623 }
1624 
1625 void CodeGenSchedModels::checkCompleteness() {
1626   bool Complete = true;
1627   bool HadCompleteModel = false;
1628   for (const CodeGenProcModel &ProcModel : procModels()) {
1629     if (!ProcModel.ModelDef->getValueAsBit("CompleteModel"))
1630       continue;
1631     for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
1632       if (Inst->hasNoSchedulingInfo)
1633         continue;
1634       if (ProcModel.isUnsupported(*Inst))
1635         continue;
1636       unsigned SCIdx = getSchedClassIdx(*Inst);
1637       if (!SCIdx) {
1638         if (Inst->TheDef->isValueUnset("SchedRW") && !HadCompleteModel) {
1639           PrintError("No schedule information for instruction '"
1640                      + Inst->TheDef->getName() + "'");
1641           Complete = false;
1642         }
1643         continue;
1644       }
1645 
1646       const CodeGenSchedClass &SC = getSchedClass(SCIdx);
1647       if (!SC.Writes.empty())
1648         continue;
1649       if (SC.ItinClassDef != nullptr &&
1650           SC.ItinClassDef->getName() != "NoItinerary")
1651         continue;
1652 
1653       const RecVec &InstRWs = SC.InstRWs;
1654       auto I = find_if(InstRWs, [&ProcModel](const Record *R) {
1655         return R->getValueAsDef("SchedModel") == ProcModel.ModelDef;
1656       });
1657       if (I == InstRWs.end()) {
1658         PrintError("'" + ProcModel.ModelName + "' lacks information for '" +
1659                    Inst->TheDef->getName() + "'");
1660         Complete = false;
1661       }
1662     }
1663     HadCompleteModel = true;
1664   }
1665   if (!Complete) {
1666     errs() << "\n\nIncomplete schedule models found.\n"
1667       << "- Consider setting 'CompleteModel = 0' while developing new models.\n"
1668       << "- Pseudo instructions can be marked with 'hasNoSchedulingInfo = 1'.\n"
1669       << "- Instructions should usually have Sched<[...]> as a superclass, "
1670          "you may temporarily use an empty list.\n"
1671       << "- Instructions related to unsupported features can be excluded with "
1672          "list<Predicate> UnsupportedFeatures = [HasA,..,HasY]; in the "
1673          "processor model.\n\n";
1674     PrintFatalError("Incomplete schedule model");
1675   }
1676 }
1677 
1678 // Collect itinerary class resources for each processor.
1679 void CodeGenSchedModels::collectItinProcResources(Record *ItinClassDef) {
1680   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
1681     const CodeGenProcModel &PM = ProcModels[PIdx];
1682     // For all ItinRW entries.
1683     bool HasMatch = false;
1684     for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
1685          II != IE; ++II) {
1686       RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
1687       if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
1688         continue;
1689       if (HasMatch)
1690         PrintFatalError((*II)->getLoc(), "Duplicate itinerary class "
1691                         + ItinClassDef->getName()
1692                         + " in ItinResources for " + PM.ModelName);
1693       HasMatch = true;
1694       IdxVec Writes, Reads;
1695       findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1696       collectRWResources(Writes, Reads, PIdx);
1697     }
1698   }
1699 }
1700 
1701 void CodeGenSchedModels::collectRWResources(unsigned RWIdx, bool IsRead,
1702                                             ArrayRef<unsigned> ProcIndices) {
1703   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
1704   if (SchedRW.TheDef) {
1705     if (!IsRead && SchedRW.TheDef->isSubClassOf("SchedWriteRes")) {
1706       for (unsigned Idx : ProcIndices)
1707         addWriteRes(SchedRW.TheDef, Idx);
1708     }
1709     else if (IsRead && SchedRW.TheDef->isSubClassOf("SchedReadAdvance")) {
1710       for (unsigned Idx : ProcIndices)
1711         addReadAdvance(SchedRW.TheDef, Idx);
1712     }
1713   }
1714   for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
1715        AI != AE; ++AI) {
1716     IdxVec AliasProcIndices;
1717     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
1718       AliasProcIndices.push_back(
1719         getProcModel((*AI)->getValueAsDef("SchedModel")).Index);
1720     }
1721     else
1722       AliasProcIndices = ProcIndices;
1723     const CodeGenSchedRW &AliasRW = getSchedRW((*AI)->getValueAsDef("AliasRW"));
1724     assert(AliasRW.IsRead == IsRead && "cannot alias reads to writes");
1725 
1726     IdxVec ExpandedRWs;
1727     expandRWSequence(AliasRW.Index, ExpandedRWs, IsRead);
1728     for (IdxIter SI = ExpandedRWs.begin(), SE = ExpandedRWs.end();
1729          SI != SE; ++SI) {
1730       collectRWResources(*SI, IsRead, AliasProcIndices);
1731     }
1732   }
1733 }
1734 
1735 // Collect resources for a set of read/write types and processor indices.
1736 void CodeGenSchedModels::collectRWResources(ArrayRef<unsigned> Writes,
1737                                             ArrayRef<unsigned> Reads,
1738                                             ArrayRef<unsigned> ProcIndices) {
1739   for (unsigned Idx : Writes)
1740     collectRWResources(Idx, /*IsRead=*/false, ProcIndices);
1741 
1742   for (unsigned Idx : Reads)
1743     collectRWResources(Idx, /*IsRead=*/true, ProcIndices);
1744 }
1745 
1746 // Find the processor's resource units for this kind of resource.
1747 Record *CodeGenSchedModels::findProcResUnits(Record *ProcResKind,
1748                                              const CodeGenProcModel &PM,
1749                                              ArrayRef<SMLoc> Loc) const {
1750   if (ProcResKind->isSubClassOf("ProcResourceUnits"))
1751     return ProcResKind;
1752 
1753   Record *ProcUnitDef = nullptr;
1754   assert(!ProcResourceDefs.empty());
1755   assert(!ProcResGroups.empty());
1756 
1757   for (Record *ProcResDef : ProcResourceDefs) {
1758     if (ProcResDef->getValueAsDef("Kind") == ProcResKind
1759         && ProcResDef->getValueAsDef("SchedModel") == PM.ModelDef) {
1760       if (ProcUnitDef) {
1761         PrintFatalError(Loc,
1762                         "Multiple ProcessorResourceUnits associated with "
1763                         + ProcResKind->getName());
1764       }
1765       ProcUnitDef = ProcResDef;
1766     }
1767   }
1768   for (Record *ProcResGroup : ProcResGroups) {
1769     if (ProcResGroup == ProcResKind
1770         && ProcResGroup->getValueAsDef("SchedModel") == PM.ModelDef) {
1771       if (ProcUnitDef) {
1772         PrintFatalError(Loc,
1773                         "Multiple ProcessorResourceUnits associated with "
1774                         + ProcResKind->getName());
1775       }
1776       ProcUnitDef = ProcResGroup;
1777     }
1778   }
1779   if (!ProcUnitDef) {
1780     PrintFatalError(Loc,
1781                     "No ProcessorResources associated with "
1782                     + ProcResKind->getName());
1783   }
1784   return ProcUnitDef;
1785 }
1786 
1787 // Iteratively add a resource and its super resources.
1788 void CodeGenSchedModels::addProcResource(Record *ProcResKind,
1789                                          CodeGenProcModel &PM,
1790                                          ArrayRef<SMLoc> Loc) {
1791   while (true) {
1792     Record *ProcResUnits = findProcResUnits(ProcResKind, PM, Loc);
1793 
1794     // See if this ProcResource is already associated with this processor.
1795     if (is_contained(PM.ProcResourceDefs, ProcResUnits))
1796       return;
1797 
1798     PM.ProcResourceDefs.push_back(ProcResUnits);
1799     if (ProcResUnits->isSubClassOf("ProcResGroup"))
1800       return;
1801 
1802     if (!ProcResUnits->getValueInit("Super")->isComplete())
1803       return;
1804 
1805     ProcResKind = ProcResUnits->getValueAsDef("Super");
1806   }
1807 }
1808 
1809 // Add resources for a SchedWrite to this processor if they don't exist.
1810 void CodeGenSchedModels::addWriteRes(Record *ProcWriteResDef, unsigned PIdx) {
1811   assert(PIdx && "don't add resources to an invalid Processor model");
1812 
1813   RecVec &WRDefs = ProcModels[PIdx].WriteResDefs;
1814   if (is_contained(WRDefs, ProcWriteResDef))
1815     return;
1816   WRDefs.push_back(ProcWriteResDef);
1817 
1818   // Visit ProcResourceKinds referenced by the newly discovered WriteRes.
1819   RecVec ProcResDefs = ProcWriteResDef->getValueAsListOfDefs("ProcResources");
1820   for (RecIter WritePRI = ProcResDefs.begin(), WritePRE = ProcResDefs.end();
1821        WritePRI != WritePRE; ++WritePRI) {
1822     addProcResource(*WritePRI, ProcModels[PIdx], ProcWriteResDef->getLoc());
1823   }
1824 }
1825 
1826 // Add resources for a ReadAdvance to this processor if they don't exist.
1827 void CodeGenSchedModels::addReadAdvance(Record *ProcReadAdvanceDef,
1828                                         unsigned PIdx) {
1829   RecVec &RADefs = ProcModels[PIdx].ReadAdvanceDefs;
1830   if (is_contained(RADefs, ProcReadAdvanceDef))
1831     return;
1832   RADefs.push_back(ProcReadAdvanceDef);
1833 }
1834 
1835 unsigned CodeGenProcModel::getProcResourceIdx(Record *PRDef) const {
1836   RecIter PRPos = find(ProcResourceDefs, PRDef);
1837   if (PRPos == ProcResourceDefs.end())
1838     PrintFatalError(PRDef->getLoc(), "ProcResource def is not included in "
1839                     "the ProcResources list for " + ModelName);
1840   // Idx=0 is reserved for invalid.
1841   return 1 + (PRPos - ProcResourceDefs.begin());
1842 }
1843 
1844 bool CodeGenProcModel::isUnsupported(const CodeGenInstruction &Inst) const {
1845   for (const Record *TheDef : UnsupportedFeaturesDefs) {
1846     for (const Record *PredDef : Inst.TheDef->getValueAsListOfDefs("Predicates")) {
1847       if (TheDef->getName() == PredDef->getName())
1848         return true;
1849     }
1850   }
1851   return false;
1852 }
1853 
1854 #ifndef NDEBUG
1855 void CodeGenProcModel::dump() const {
1856   dbgs() << Index << ": " << ModelName << " "
1857          << (ModelDef ? ModelDef->getName() : "inferred") << " "
1858          << (ItinsDef ? ItinsDef->getName() : "no itinerary") << '\n';
1859 }
1860 
1861 void CodeGenSchedRW::dump() const {
1862   dbgs() << Name << (IsVariadic ? " (V) " : " ");
1863   if (IsSequence) {
1864     dbgs() << "(";
1865     dumpIdxVec(Sequence);
1866     dbgs() << ")";
1867   }
1868 }
1869 
1870 void CodeGenSchedClass::dump(const CodeGenSchedModels* SchedModels) const {
1871   dbgs() << "SCHEDCLASS " << Index << ":" << Name << '\n'
1872          << "  Writes: ";
1873   for (unsigned i = 0, N = Writes.size(); i < N; ++i) {
1874     SchedModels->getSchedWrite(Writes[i]).dump();
1875     if (i < N-1) {
1876       dbgs() << '\n';
1877       dbgs().indent(10);
1878     }
1879   }
1880   dbgs() << "\n  Reads: ";
1881   for (unsigned i = 0, N = Reads.size(); i < N; ++i) {
1882     SchedModels->getSchedRead(Reads[i]).dump();
1883     if (i < N-1) {
1884       dbgs() << '\n';
1885       dbgs().indent(10);
1886     }
1887   }
1888   dbgs() << "\n  ProcIdx: "; dumpIdxVec(ProcIndices); dbgs() << '\n';
1889   if (!Transitions.empty()) {
1890     dbgs() << "\n Transitions for Proc ";
1891     for (const CodeGenSchedTransition &Transition : Transitions) {
1892       dumpIdxVec(Transition.ProcIndices);
1893     }
1894   }
1895 }
1896 
1897 void PredTransitions::dump() const {
1898   dbgs() << "Expanded Variants:\n";
1899   for (std::vector<PredTransition>::const_iterator
1900          TI = TransVec.begin(), TE = TransVec.end(); TI != TE; ++TI) {
1901     dbgs() << "{";
1902     for (SmallVectorImpl<PredCheck>::const_iterator
1903            PCI = TI->PredTerm.begin(), PCE = TI->PredTerm.end();
1904          PCI != PCE; ++PCI) {
1905       if (PCI != TI->PredTerm.begin())
1906         dbgs() << ", ";
1907       dbgs() << SchedModels.getSchedRW(PCI->RWIdx, PCI->IsRead).Name
1908              << ":" << PCI->Predicate->getName();
1909     }
1910     dbgs() << "},\n  => {";
1911     for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
1912            WSI = TI->WriteSequences.begin(), WSE = TI->WriteSequences.end();
1913          WSI != WSE; ++WSI) {
1914       dbgs() << "(";
1915       for (SmallVectorImpl<unsigned>::const_iterator
1916              WI = WSI->begin(), WE = WSI->end(); WI != WE; ++WI) {
1917         if (WI != WSI->begin())
1918           dbgs() << ", ";
1919         dbgs() << SchedModels.getSchedWrite(*WI).Name;
1920       }
1921       dbgs() << "),";
1922     }
1923     dbgs() << "}\n";
1924   }
1925 }
1926 #endif // NDEBUG
1927