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