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