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