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