17ae0e2c9SDimitry Andric //===- CodeGenSchedule.cpp - Scheduling MachineModels ---------------------===//
27ae0e2c9SDimitry Andric //
37ae0e2c9SDimitry Andric //                     The LLVM Compiler Infrastructure
47ae0e2c9SDimitry Andric //
57ae0e2c9SDimitry Andric // This file is distributed under the University of Illinois Open Source
67ae0e2c9SDimitry Andric // License. See LICENSE.TXT for details.
77ae0e2c9SDimitry Andric //
87ae0e2c9SDimitry Andric //===----------------------------------------------------------------------===//
97ae0e2c9SDimitry Andric //
1091bc56edSDimitry Andric // This file defines structures to encapsulate the machine model as described in
117ae0e2c9SDimitry Andric // the target description.
127ae0e2c9SDimitry Andric //
137ae0e2c9SDimitry Andric //===----------------------------------------------------------------------===//
147ae0e2c9SDimitry Andric 
157ae0e2c9SDimitry Andric #include "CodeGenSchedule.h"
164ba319b5SDimitry Andric #include "CodeGenInstruction.h"
177ae0e2c9SDimitry Andric #include "CodeGenTarget.h"
184ba319b5SDimitry Andric #include "llvm/ADT/MapVector.h"
194ba319b5SDimitry Andric #include "llvm/ADT/STLExtras.h"
20d88c1a5aSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
21d88c1a5aSDimitry Andric #include "llvm/ADT/SmallSet.h"
22d88c1a5aSDimitry Andric #include "llvm/ADT/SmallVector.h"
23d88c1a5aSDimitry Andric #include "llvm/Support/Casting.h"
247ae0e2c9SDimitry Andric #include "llvm/Support/Debug.h"
253861d79fSDimitry Andric #include "llvm/Support/Regex.h"
264ba319b5SDimitry Andric #include "llvm/Support/raw_ostream.h"
27139f7f9bSDimitry Andric #include "llvm/TableGen/Error.h"
28d88c1a5aSDimitry Andric #include <algorithm>
29d88c1a5aSDimitry Andric #include <iterator>
30d88c1a5aSDimitry Andric #include <utility>
317ae0e2c9SDimitry Andric 
327ae0e2c9SDimitry Andric using namespace llvm;
337ae0e2c9SDimitry Andric 
3491bc56edSDimitry Andric #define DEBUG_TYPE "subtarget-emitter"
3591bc56edSDimitry Andric 
363861d79fSDimitry Andric #ifndef NDEBUG
dumpIdxVec(ArrayRef<unsigned> V)377d523365SDimitry Andric static void dumpIdxVec(ArrayRef<unsigned> V) {
387d523365SDimitry Andric   for (unsigned Idx : V)
397d523365SDimitry Andric     dbgs() << Idx << ", ";
403861d79fSDimitry Andric }
413861d79fSDimitry Andric #endif
423861d79fSDimitry Andric 
43f785676fSDimitry Andric namespace {
44d88c1a5aSDimitry Andric 
453861d79fSDimitry Andric // (instrs a, b, ...) Evaluate and union all arguments. Identical to AddOp.
463861d79fSDimitry Andric struct InstrsOp : public SetTheory::Operator {
apply__anonab391a420111::InstrsOp4791bc56edSDimitry Andric   void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
4891bc56edSDimitry Andric              ArrayRef<SMLoc> Loc) override {
493861d79fSDimitry Andric     ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts, Loc);
503861d79fSDimitry Andric   }
513861d79fSDimitry Andric };
523861d79fSDimitry Andric 
533861d79fSDimitry Andric // (instregex "OpcPat",...) Find all instructions matching an opcode pattern.
543861d79fSDimitry Andric struct InstRegexOp : public SetTheory::Operator {
553861d79fSDimitry Andric   const CodeGenTarget &Target;
InstRegexOp__anonab391a420111::InstRegexOp563861d79fSDimitry Andric   InstRegexOp(const CodeGenTarget &t): Target(t) {}
573861d79fSDimitry Andric 
584ba319b5SDimitry Andric   /// Remove any text inside of parentheses from S.
removeParens__anonab391a420111::InstRegexOp594ba319b5SDimitry Andric   static std::string removeParens(llvm::StringRef S) {
604ba319b5SDimitry Andric     std::string Result;
614ba319b5SDimitry Andric     unsigned Paren = 0;
624ba319b5SDimitry Andric     // NB: We don't care about escaped parens here.
634ba319b5SDimitry Andric     for (char C : S) {
644ba319b5SDimitry Andric       switch (C) {
654ba319b5SDimitry Andric       case '(':
664ba319b5SDimitry Andric         ++Paren;
674ba319b5SDimitry Andric         break;
684ba319b5SDimitry Andric       case ')':
694ba319b5SDimitry Andric         --Paren;
704ba319b5SDimitry Andric         break;
714ba319b5SDimitry Andric       default:
724ba319b5SDimitry Andric         if (Paren == 0)
734ba319b5SDimitry Andric           Result += C;
744ba319b5SDimitry Andric       }
754ba319b5SDimitry Andric     }
764ba319b5SDimitry Andric     return Result;
774ba319b5SDimitry Andric   }
784ba319b5SDimitry Andric 
apply__anonab391a420111::InstRegexOp793861d79fSDimitry Andric   void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
8091bc56edSDimitry Andric              ArrayRef<SMLoc> Loc) override {
814ba319b5SDimitry Andric     ArrayRef<const CodeGenInstruction *> Instructions =
824ba319b5SDimitry Andric         Target.getInstructionsByEnumValue();
834ba319b5SDimitry Andric 
844ba319b5SDimitry Andric     unsigned NumGeneric = Target.getNumFixedInstructions();
854ba319b5SDimitry Andric     unsigned NumPseudos = Target.getNumPseudoInstructions();
864ba319b5SDimitry Andric     auto Generics = Instructions.slice(0, NumGeneric);
874ba319b5SDimitry Andric     auto Pseudos = Instructions.slice(NumGeneric, NumPseudos);
884ba319b5SDimitry Andric     auto NonPseudos = Instructions.slice(NumGeneric + NumPseudos);
894ba319b5SDimitry Andric 
902cab237bSDimitry Andric     for (Init *Arg : make_range(Expr->arg_begin(), Expr->arg_end())) {
912cab237bSDimitry Andric       StringInit *SI = dyn_cast<StringInit>(Arg);
923861d79fSDimitry Andric       if (!SI)
934ba319b5SDimitry Andric         PrintFatalError(Loc, "instregex requires pattern string: " +
944ba319b5SDimitry Andric                                  Expr->getAsString());
954ba319b5SDimitry Andric       StringRef Original = SI->getValue();
964ba319b5SDimitry Andric 
974ba319b5SDimitry Andric       // Extract a prefix that we can binary search on.
984ba319b5SDimitry Andric       static const char RegexMetachars[] = "()^$|*+?.[]\\{}";
994ba319b5SDimitry Andric       auto FirstMeta = Original.find_first_of(RegexMetachars);
1004ba319b5SDimitry Andric 
1014ba319b5SDimitry Andric       // Look for top-level | or ?. We cannot optimize them to binary search.
1024ba319b5SDimitry Andric       if (removeParens(Original).find_first_of("|?") != std::string::npos)
1034ba319b5SDimitry Andric         FirstMeta = 0;
1044ba319b5SDimitry Andric 
1054ba319b5SDimitry Andric       Optional<Regex> Regexpr = None;
1064ba319b5SDimitry Andric       StringRef Prefix = Original.substr(0, FirstMeta);
1074ba319b5SDimitry Andric       StringRef PatStr = Original.substr(FirstMeta);
1084ba319b5SDimitry Andric       if (!PatStr.empty()) {
1094ba319b5SDimitry Andric         // For the rest use a python-style prefix match.
1104ba319b5SDimitry Andric         std::string pat = PatStr;
1113861d79fSDimitry Andric         if (pat[0] != '^') {
1123861d79fSDimitry Andric           pat.insert(0, "^(");
1133861d79fSDimitry Andric           pat.insert(pat.end(), ')');
1143861d79fSDimitry Andric         }
1154ba319b5SDimitry Andric         Regexpr = Regex(pat);
1163861d79fSDimitry Andric       }
1174ba319b5SDimitry Andric 
1184ba319b5SDimitry Andric       int NumMatches = 0;
1194ba319b5SDimitry Andric 
1204ba319b5SDimitry Andric       // The generic opcodes are unsorted, handle them manually.
1214ba319b5SDimitry Andric       for (auto *Inst : Generics) {
1224ba319b5SDimitry Andric         StringRef InstName = Inst->TheDef->getName();
1234ba319b5SDimitry Andric         if (InstName.startswith(Prefix) &&
1244ba319b5SDimitry Andric             (!Regexpr || Regexpr->match(InstName.substr(Prefix.size())))) {
12539d628a0SDimitry Andric           Elts.insert(Inst->TheDef);
1264ba319b5SDimitry Andric           NumMatches++;
1273861d79fSDimitry Andric         }
1283861d79fSDimitry Andric       }
1294ba319b5SDimitry Andric 
1304ba319b5SDimitry Andric       // Target instructions are split into two ranges: pseudo instructions
1314ba319b5SDimitry Andric       // first, than non-pseudos. Each range is in lexicographical order
1324ba319b5SDimitry Andric       // sorted by name. Find the sub-ranges that start with our prefix.
1334ba319b5SDimitry Andric       struct Comp {
1344ba319b5SDimitry Andric         bool operator()(const CodeGenInstruction *LHS, StringRef RHS) {
1354ba319b5SDimitry Andric           return LHS->TheDef->getName() < RHS;
1364ba319b5SDimitry Andric         }
1374ba319b5SDimitry Andric         bool operator()(StringRef LHS, const CodeGenInstruction *RHS) {
1384ba319b5SDimitry Andric           return LHS < RHS->TheDef->getName() &&
1394ba319b5SDimitry Andric                  !RHS->TheDef->getName().startswith(LHS);
1404ba319b5SDimitry Andric         }
1414ba319b5SDimitry Andric       };
1424ba319b5SDimitry Andric       auto Range1 =
1434ba319b5SDimitry Andric           std::equal_range(Pseudos.begin(), Pseudos.end(), Prefix, Comp());
1444ba319b5SDimitry Andric       auto Range2 = std::equal_range(NonPseudos.begin(), NonPseudos.end(),
1454ba319b5SDimitry Andric                                      Prefix, Comp());
1464ba319b5SDimitry Andric 
1474ba319b5SDimitry Andric       // For these ranges we know that instruction names start with the prefix.
1484ba319b5SDimitry Andric       // Check if there's a regex that needs to be checked.
1494ba319b5SDimitry Andric       const auto HandleNonGeneric = [&](const CodeGenInstruction *Inst) {
1504ba319b5SDimitry Andric         StringRef InstName = Inst->TheDef->getName();
1514ba319b5SDimitry Andric         if (!Regexpr || Regexpr->match(InstName.substr(Prefix.size()))) {
1524ba319b5SDimitry Andric           Elts.insert(Inst->TheDef);
1534ba319b5SDimitry Andric           NumMatches++;
1544ba319b5SDimitry Andric         }
1554ba319b5SDimitry Andric       };
1564ba319b5SDimitry Andric       std::for_each(Range1.first, Range1.second, HandleNonGeneric);
1574ba319b5SDimitry Andric       std::for_each(Range2.first, Range2.second, HandleNonGeneric);
1584ba319b5SDimitry Andric 
1594ba319b5SDimitry Andric       if (0 == NumMatches)
1604ba319b5SDimitry Andric         PrintFatalError(Loc, "instregex has no matches: " + Original);
1614ba319b5SDimitry Andric     }
1623861d79fSDimitry Andric   }
1633861d79fSDimitry Andric };
164d88c1a5aSDimitry Andric 
165f785676fSDimitry Andric } // end anonymous namespace
1663861d79fSDimitry Andric 
1673861d79fSDimitry Andric /// CodeGenModels ctor interprets machine model records and populates maps.
CodeGenSchedModels(RecordKeeper & RK,const CodeGenTarget & TGT)1687ae0e2c9SDimitry Andric CodeGenSchedModels::CodeGenSchedModels(RecordKeeper &RK,
1697ae0e2c9SDimitry Andric                                        const CodeGenTarget &TGT):
170139f7f9bSDimitry Andric   Records(RK), Target(TGT) {
1717ae0e2c9SDimitry Andric 
1723861d79fSDimitry Andric   Sets.addFieldExpander("InstRW", "Instrs");
1737ae0e2c9SDimitry Andric 
1743861d79fSDimitry Andric   // Allow Set evaluation to recognize the dags used in InstRW records:
1753861d79fSDimitry Andric   // (instrs Op1, Op1...)
176ff0cc061SDimitry Andric   Sets.addOperator("instrs", llvm::make_unique<InstrsOp>());
177ff0cc061SDimitry Andric   Sets.addOperator("instregex", llvm::make_unique<InstRegexOp>(Target));
1783861d79fSDimitry Andric 
1793861d79fSDimitry Andric   // Instantiate a CodeGenProcModel for each SchedMachineModel with the values
1803861d79fSDimitry Andric   // that are explicitly referenced in tablegen records. Resources associated
1813861d79fSDimitry Andric   // with each processor will be derived later. Populate ProcModelMap with the
1823861d79fSDimitry Andric   // CodeGenProcModel instances.
1833861d79fSDimitry Andric   collectProcModels();
1843861d79fSDimitry Andric 
1853861d79fSDimitry Andric   // Instantiate a CodeGenSchedRW for each SchedReadWrite record explicitly
1863861d79fSDimitry Andric   // defined, and populate SchedReads and SchedWrites vectors. Implicit
1873861d79fSDimitry Andric   // SchedReadWrites that represent sequences derived from expanded variant will
1883861d79fSDimitry Andric   // be inferred later.
1893861d79fSDimitry Andric   collectSchedRW();
1903861d79fSDimitry Andric 
1913861d79fSDimitry Andric   // Instantiate a CodeGenSchedClass for each unique SchedRW signature directly
1923861d79fSDimitry Andric   // required by an instruction definition, and populate SchedClassIdxMap. Set
1933861d79fSDimitry Andric   // NumItineraryClasses to the number of explicit itinerary classes referenced
1943861d79fSDimitry Andric   // by instructions. Set NumInstrSchedClasses to the number of itinerary
1953861d79fSDimitry Andric   // classes plus any classes implied by instructions that derive from class
1963861d79fSDimitry Andric   // Sched and provide SchedRW list. This does not infer any new classes from
1973861d79fSDimitry Andric   // SchedVariant.
1983861d79fSDimitry Andric   collectSchedClasses();
1993861d79fSDimitry Andric 
2003861d79fSDimitry Andric   // Find instruction itineraries for each processor. Sort and populate
2013861d79fSDimitry Andric   // CodeGenProcModel::ItinDefList. (Cycle-to-cycle itineraries). This requires
2023861d79fSDimitry Andric   // all itinerary classes to be discovered.
2033861d79fSDimitry Andric   collectProcItins();
2043861d79fSDimitry Andric 
2053861d79fSDimitry Andric   // Find ItinRW records for each processor and itinerary class.
2063861d79fSDimitry Andric   // (For per-operand resources mapped to itinerary classes).
2073861d79fSDimitry Andric   collectProcItinRW();
2083861d79fSDimitry Andric 
2093ca95b02SDimitry Andric   // Find UnsupportedFeatures records for each processor.
2103ca95b02SDimitry Andric   // (For per-operand resources mapped to itinerary classes).
2113ca95b02SDimitry Andric   collectProcUnsupportedFeatures();
2123ca95b02SDimitry Andric 
2133861d79fSDimitry Andric   // Infer new SchedClasses from SchedVariant.
2143861d79fSDimitry Andric   inferSchedClasses();
2153861d79fSDimitry Andric 
2163861d79fSDimitry Andric   // Populate each CodeGenProcModel's WriteResDefs, ReadAdvanceDefs, and
2173861d79fSDimitry Andric   // ProcResourceDefs.
2184ba319b5SDimitry Andric   LLVM_DEBUG(
2194ba319b5SDimitry Andric       dbgs() << "\n+++ RESOURCE DEFINITIONS (collectProcResources) +++\n");
2203861d79fSDimitry Andric   collectProcResources();
2213ca95b02SDimitry Andric 
2224ba319b5SDimitry Andric   // Collect optional processor description.
2234ba319b5SDimitry Andric   collectOptionalProcessorInfo();
2244ba319b5SDimitry Andric 
225*b5893f02SDimitry Andric   // Check MCInstPredicate definitions.
226*b5893f02SDimitry Andric   checkMCInstPredicates();
227*b5893f02SDimitry Andric 
228*b5893f02SDimitry Andric   // Check STIPredicate definitions.
229*b5893f02SDimitry Andric   checkSTIPredicates();
230*b5893f02SDimitry Andric 
231*b5893f02SDimitry Andric   // Find STIPredicate definitions for each processor model, and construct
232*b5893f02SDimitry Andric   // STIPredicateFunction objects.
233*b5893f02SDimitry Andric   collectSTIPredicates();
234*b5893f02SDimitry Andric 
2354ba319b5SDimitry Andric   checkCompleteness();
2364ba319b5SDimitry Andric }
2374ba319b5SDimitry Andric 
checkSTIPredicates() const238*b5893f02SDimitry Andric void CodeGenSchedModels::checkSTIPredicates() const {
239*b5893f02SDimitry Andric   DenseMap<StringRef, const Record *> Declarations;
240*b5893f02SDimitry Andric 
241*b5893f02SDimitry Andric   // There cannot be multiple declarations with the same name.
242*b5893f02SDimitry Andric   const RecVec Decls = Records.getAllDerivedDefinitions("STIPredicateDecl");
243*b5893f02SDimitry Andric   for (const Record *R : Decls) {
244*b5893f02SDimitry Andric     StringRef Name = R->getValueAsString("Name");
245*b5893f02SDimitry Andric     const auto It = Declarations.find(Name);
246*b5893f02SDimitry Andric     if (It == Declarations.end()) {
247*b5893f02SDimitry Andric       Declarations[Name] = R;
248*b5893f02SDimitry Andric       continue;
249*b5893f02SDimitry Andric     }
250*b5893f02SDimitry Andric 
251*b5893f02SDimitry Andric     PrintError(R->getLoc(), "STIPredicate " + Name + " multiply declared.");
252*b5893f02SDimitry Andric     PrintNote(It->second->getLoc(), "Previous declaration was here.");
253*b5893f02SDimitry Andric     PrintFatalError(R->getLoc(), "Invalid STIPredicateDecl found.");
254*b5893f02SDimitry Andric   }
255*b5893f02SDimitry Andric 
256*b5893f02SDimitry Andric   // Disallow InstructionEquivalenceClasses with an empty instruction list.
257*b5893f02SDimitry Andric   const RecVec Defs =
258*b5893f02SDimitry Andric       Records.getAllDerivedDefinitions("InstructionEquivalenceClass");
259*b5893f02SDimitry Andric   for (const Record *R : Defs) {
260*b5893f02SDimitry Andric     RecVec Opcodes = R->getValueAsListOfDefs("Opcodes");
261*b5893f02SDimitry Andric     if (Opcodes.empty()) {
262*b5893f02SDimitry Andric       PrintFatalError(R->getLoc(), "Invalid InstructionEquivalenceClass "
263*b5893f02SDimitry Andric                                    "defined with an empty opcode list.");
264*b5893f02SDimitry Andric     }
265*b5893f02SDimitry Andric   }
266*b5893f02SDimitry Andric }
267*b5893f02SDimitry Andric 
268*b5893f02SDimitry Andric // Used by function `processSTIPredicate` to construct a mask of machine
269*b5893f02SDimitry Andric // instruction operands.
constructOperandMask(ArrayRef<int64_t> Indices)270*b5893f02SDimitry Andric static APInt constructOperandMask(ArrayRef<int64_t> Indices) {
271*b5893f02SDimitry Andric   APInt OperandMask;
272*b5893f02SDimitry Andric   if (Indices.empty())
273*b5893f02SDimitry Andric     return OperandMask;
274*b5893f02SDimitry Andric 
275*b5893f02SDimitry Andric   int64_t MaxIndex = *std::max_element(Indices.begin(), Indices.end());
276*b5893f02SDimitry Andric   assert(MaxIndex >= 0 && "Invalid negative indices in input!");
277*b5893f02SDimitry Andric   OperandMask = OperandMask.zext(MaxIndex + 1);
278*b5893f02SDimitry Andric   for (const int64_t Index : Indices) {
279*b5893f02SDimitry Andric     assert(Index >= 0 && "Invalid negative indices!");
280*b5893f02SDimitry Andric     OperandMask.setBit(Index);
281*b5893f02SDimitry Andric   }
282*b5893f02SDimitry Andric 
283*b5893f02SDimitry Andric   return OperandMask;
284*b5893f02SDimitry Andric }
285*b5893f02SDimitry Andric 
286*b5893f02SDimitry Andric static void
processSTIPredicate(STIPredicateFunction & Fn,const DenseMap<Record *,unsigned> & ProcModelMap)287*b5893f02SDimitry Andric processSTIPredicate(STIPredicateFunction &Fn,
288*b5893f02SDimitry Andric                     const DenseMap<Record *, unsigned> &ProcModelMap) {
289*b5893f02SDimitry Andric   DenseMap<const Record *, unsigned> Opcode2Index;
290*b5893f02SDimitry Andric   using OpcodeMapPair = std::pair<const Record *, OpcodeInfo>;
291*b5893f02SDimitry Andric   std::vector<OpcodeMapPair> OpcodeMappings;
292*b5893f02SDimitry Andric   std::vector<std::pair<APInt, APInt>> OpcodeMasks;
293*b5893f02SDimitry Andric 
294*b5893f02SDimitry Andric   DenseMap<const Record *, unsigned> Predicate2Index;
295*b5893f02SDimitry Andric   unsigned NumUniquePredicates = 0;
296*b5893f02SDimitry Andric 
297*b5893f02SDimitry Andric   // Number unique predicates and opcodes used by InstructionEquivalenceClass
298*b5893f02SDimitry Andric   // definitions. Each unique opcode will be associated with an OpcodeInfo
299*b5893f02SDimitry Andric   // object.
300*b5893f02SDimitry Andric   for (const Record *Def : Fn.getDefinitions()) {
301*b5893f02SDimitry Andric     RecVec Classes = Def->getValueAsListOfDefs("Classes");
302*b5893f02SDimitry Andric     for (const Record *EC : Classes) {
303*b5893f02SDimitry Andric       const Record *Pred = EC->getValueAsDef("Predicate");
304*b5893f02SDimitry Andric       if (Predicate2Index.find(Pred) == Predicate2Index.end())
305*b5893f02SDimitry Andric         Predicate2Index[Pred] = NumUniquePredicates++;
306*b5893f02SDimitry Andric 
307*b5893f02SDimitry Andric       RecVec Opcodes = EC->getValueAsListOfDefs("Opcodes");
308*b5893f02SDimitry Andric       for (const Record *Opcode : Opcodes) {
309*b5893f02SDimitry Andric         if (Opcode2Index.find(Opcode) == Opcode2Index.end()) {
310*b5893f02SDimitry Andric           Opcode2Index[Opcode] = OpcodeMappings.size();
311*b5893f02SDimitry Andric           OpcodeMappings.emplace_back(Opcode, OpcodeInfo());
312*b5893f02SDimitry Andric         }
313*b5893f02SDimitry Andric       }
314*b5893f02SDimitry Andric     }
315*b5893f02SDimitry Andric   }
316*b5893f02SDimitry Andric 
317*b5893f02SDimitry Andric   // Initialize vector `OpcodeMasks` with default values.  We want to keep track
318*b5893f02SDimitry Andric   // of which processors "use" which opcodes.  We also want to be able to
319*b5893f02SDimitry Andric   // identify predicates that are used by different processors for a same
320*b5893f02SDimitry Andric   // opcode.
321*b5893f02SDimitry Andric   // This information is used later on by this algorithm to sort OpcodeMapping
322*b5893f02SDimitry Andric   // elements based on their processor and predicate sets.
323*b5893f02SDimitry Andric   OpcodeMasks.resize(OpcodeMappings.size());
324*b5893f02SDimitry Andric   APInt DefaultProcMask(ProcModelMap.size(), 0);
325*b5893f02SDimitry Andric   APInt DefaultPredMask(NumUniquePredicates, 0);
326*b5893f02SDimitry Andric   for (std::pair<APInt, APInt> &MaskPair : OpcodeMasks)
327*b5893f02SDimitry Andric     MaskPair = std::make_pair(DefaultProcMask, DefaultPredMask);
328*b5893f02SDimitry Andric 
329*b5893f02SDimitry Andric   // Construct a OpcodeInfo object for every unique opcode declared by an
330*b5893f02SDimitry Andric   // InstructionEquivalenceClass definition.
331*b5893f02SDimitry Andric   for (const Record *Def : Fn.getDefinitions()) {
332*b5893f02SDimitry Andric     RecVec Classes = Def->getValueAsListOfDefs("Classes");
333*b5893f02SDimitry Andric     const Record *SchedModel = Def->getValueAsDef("SchedModel");
334*b5893f02SDimitry Andric     unsigned ProcIndex = ProcModelMap.find(SchedModel)->second;
335*b5893f02SDimitry Andric     APInt ProcMask(ProcModelMap.size(), 0);
336*b5893f02SDimitry Andric     ProcMask.setBit(ProcIndex);
337*b5893f02SDimitry Andric 
338*b5893f02SDimitry Andric     for (const Record *EC : Classes) {
339*b5893f02SDimitry Andric       RecVec Opcodes = EC->getValueAsListOfDefs("Opcodes");
340*b5893f02SDimitry Andric 
341*b5893f02SDimitry Andric       std::vector<int64_t> OpIndices =
342*b5893f02SDimitry Andric           EC->getValueAsListOfInts("OperandIndices");
343*b5893f02SDimitry Andric       APInt OperandMask = constructOperandMask(OpIndices);
344*b5893f02SDimitry Andric 
345*b5893f02SDimitry Andric       const Record *Pred = EC->getValueAsDef("Predicate");
346*b5893f02SDimitry Andric       APInt PredMask(NumUniquePredicates, 0);
347*b5893f02SDimitry Andric       PredMask.setBit(Predicate2Index[Pred]);
348*b5893f02SDimitry Andric 
349*b5893f02SDimitry Andric       for (const Record *Opcode : Opcodes) {
350*b5893f02SDimitry Andric         unsigned OpcodeIdx = Opcode2Index[Opcode];
351*b5893f02SDimitry Andric         if (OpcodeMasks[OpcodeIdx].first[ProcIndex]) {
352*b5893f02SDimitry Andric           std::string Message =
353*b5893f02SDimitry Andric               "Opcode " + Opcode->getName().str() +
354*b5893f02SDimitry Andric               " used by multiple InstructionEquivalenceClass definitions.";
355*b5893f02SDimitry Andric           PrintFatalError(EC->getLoc(), Message);
356*b5893f02SDimitry Andric         }
357*b5893f02SDimitry Andric         OpcodeMasks[OpcodeIdx].first |= ProcMask;
358*b5893f02SDimitry Andric         OpcodeMasks[OpcodeIdx].second |= PredMask;
359*b5893f02SDimitry Andric         OpcodeInfo &OI = OpcodeMappings[OpcodeIdx].second;
360*b5893f02SDimitry Andric 
361*b5893f02SDimitry Andric         OI.addPredicateForProcModel(ProcMask, OperandMask, Pred);
362*b5893f02SDimitry Andric       }
363*b5893f02SDimitry Andric     }
364*b5893f02SDimitry Andric   }
365*b5893f02SDimitry Andric 
366*b5893f02SDimitry Andric   // Sort OpcodeMappings elements based on their CPU and predicate masks.
367*b5893f02SDimitry Andric   // As a last resort, order elements by opcode identifier.
368*b5893f02SDimitry Andric   llvm::sort(OpcodeMappings,
369*b5893f02SDimitry Andric              [&](const OpcodeMapPair &Lhs, const OpcodeMapPair &Rhs) {
370*b5893f02SDimitry Andric                unsigned LhsIdx = Opcode2Index[Lhs.first];
371*b5893f02SDimitry Andric                unsigned RhsIdx = Opcode2Index[Rhs.first];
372*b5893f02SDimitry Andric                std::pair<APInt, APInt> &LhsMasks = OpcodeMasks[LhsIdx];
373*b5893f02SDimitry Andric                std::pair<APInt, APInt> &RhsMasks = OpcodeMasks[RhsIdx];
374*b5893f02SDimitry Andric 
375*b5893f02SDimitry Andric                if (LhsMasks.first != RhsMasks.first) {
376*b5893f02SDimitry Andric                  if (LhsMasks.first.countPopulation() <
377*b5893f02SDimitry Andric                      RhsMasks.first.countPopulation())
378*b5893f02SDimitry Andric                    return true;
379*b5893f02SDimitry Andric                  return LhsMasks.first.countLeadingZeros() >
380*b5893f02SDimitry Andric                         RhsMasks.first.countLeadingZeros();
381*b5893f02SDimitry Andric                }
382*b5893f02SDimitry Andric 
383*b5893f02SDimitry Andric                if (LhsMasks.second != RhsMasks.second) {
384*b5893f02SDimitry Andric                  if (LhsMasks.second.countPopulation() <
385*b5893f02SDimitry Andric                      RhsMasks.second.countPopulation())
386*b5893f02SDimitry Andric                    return true;
387*b5893f02SDimitry Andric                  return LhsMasks.second.countLeadingZeros() >
388*b5893f02SDimitry Andric                         RhsMasks.second.countLeadingZeros();
389*b5893f02SDimitry Andric                }
390*b5893f02SDimitry Andric 
391*b5893f02SDimitry Andric                return LhsIdx < RhsIdx;
392*b5893f02SDimitry Andric              });
393*b5893f02SDimitry Andric 
394*b5893f02SDimitry Andric   // Now construct opcode groups. Groups are used by the SubtargetEmitter when
395*b5893f02SDimitry Andric   // expanding the body of a STIPredicate function. In particular, each opcode
396*b5893f02SDimitry Andric   // group is expanded into a sequence of labels in a switch statement.
397*b5893f02SDimitry Andric   // It identifies opcodes for which different processors define same predicates
398*b5893f02SDimitry Andric   // and same opcode masks.
399*b5893f02SDimitry Andric   for (OpcodeMapPair &Info : OpcodeMappings)
400*b5893f02SDimitry Andric     Fn.addOpcode(Info.first, std::move(Info.second));
401*b5893f02SDimitry Andric }
402*b5893f02SDimitry Andric 
collectSTIPredicates()403*b5893f02SDimitry Andric void CodeGenSchedModels::collectSTIPredicates() {
404*b5893f02SDimitry Andric   // Map STIPredicateDecl records to elements of vector
405*b5893f02SDimitry Andric   // CodeGenSchedModels::STIPredicates.
406*b5893f02SDimitry Andric   DenseMap<const Record *, unsigned> Decl2Index;
407*b5893f02SDimitry Andric 
408*b5893f02SDimitry Andric   RecVec RV = Records.getAllDerivedDefinitions("STIPredicate");
409*b5893f02SDimitry Andric   for (const Record *R : RV) {
410*b5893f02SDimitry Andric     const Record *Decl = R->getValueAsDef("Declaration");
411*b5893f02SDimitry Andric 
412*b5893f02SDimitry Andric     const auto It = Decl2Index.find(Decl);
413*b5893f02SDimitry Andric     if (It == Decl2Index.end()) {
414*b5893f02SDimitry Andric       Decl2Index[Decl] = STIPredicates.size();
415*b5893f02SDimitry Andric       STIPredicateFunction Predicate(Decl);
416*b5893f02SDimitry Andric       Predicate.addDefinition(R);
417*b5893f02SDimitry Andric       STIPredicates.emplace_back(std::move(Predicate));
418*b5893f02SDimitry Andric       continue;
419*b5893f02SDimitry Andric     }
420*b5893f02SDimitry Andric 
421*b5893f02SDimitry Andric     STIPredicateFunction &PreviousDef = STIPredicates[It->second];
422*b5893f02SDimitry Andric     PreviousDef.addDefinition(R);
423*b5893f02SDimitry Andric   }
424*b5893f02SDimitry Andric 
425*b5893f02SDimitry Andric   for (STIPredicateFunction &Fn : STIPredicates)
426*b5893f02SDimitry Andric     processSTIPredicate(Fn, ProcModelMap);
427*b5893f02SDimitry Andric }
428*b5893f02SDimitry Andric 
addPredicateForProcModel(const llvm::APInt & CpuMask,const llvm::APInt & OperandMask,const Record * Predicate)429*b5893f02SDimitry Andric void OpcodeInfo::addPredicateForProcModel(const llvm::APInt &CpuMask,
430*b5893f02SDimitry Andric                                           const llvm::APInt &OperandMask,
431*b5893f02SDimitry Andric                                           const Record *Predicate) {
432*b5893f02SDimitry Andric   auto It = llvm::find_if(
433*b5893f02SDimitry Andric       Predicates, [&OperandMask, &Predicate](const PredicateInfo &P) {
434*b5893f02SDimitry Andric         return P.Predicate == Predicate && P.OperandMask == OperandMask;
435*b5893f02SDimitry Andric       });
436*b5893f02SDimitry Andric   if (It == Predicates.end()) {
437*b5893f02SDimitry Andric     Predicates.emplace_back(CpuMask, OperandMask, Predicate);
438*b5893f02SDimitry Andric     return;
439*b5893f02SDimitry Andric   }
440*b5893f02SDimitry Andric   It->ProcModelMask |= CpuMask;
441*b5893f02SDimitry Andric }
442*b5893f02SDimitry Andric 
checkMCInstPredicates() const443*b5893f02SDimitry Andric void CodeGenSchedModels::checkMCInstPredicates() const {
444*b5893f02SDimitry Andric   RecVec MCPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
445*b5893f02SDimitry Andric   if (MCPredicates.empty())
446*b5893f02SDimitry Andric     return;
447*b5893f02SDimitry Andric 
448*b5893f02SDimitry Andric   // A target cannot have multiple TIIPredicate definitions with a same name.
449*b5893f02SDimitry Andric   llvm::StringMap<const Record *> TIIPredicates(MCPredicates.size());
450*b5893f02SDimitry Andric   for (const Record *TIIPred : MCPredicates) {
451*b5893f02SDimitry Andric     StringRef Name = TIIPred->getValueAsString("FunctionName");
452*b5893f02SDimitry Andric     StringMap<const Record *>::const_iterator It = TIIPredicates.find(Name);
453*b5893f02SDimitry Andric     if (It == TIIPredicates.end()) {
454*b5893f02SDimitry Andric       TIIPredicates[Name] = TIIPred;
455*b5893f02SDimitry Andric       continue;
456*b5893f02SDimitry Andric     }
457*b5893f02SDimitry Andric 
458*b5893f02SDimitry Andric     PrintError(TIIPred->getLoc(),
459*b5893f02SDimitry Andric                "TIIPredicate " + Name + " is multiply defined.");
460*b5893f02SDimitry Andric     PrintNote(It->second->getLoc(),
461*b5893f02SDimitry Andric               " Previous definition of " + Name + " was here.");
462*b5893f02SDimitry Andric     PrintFatalError(TIIPred->getLoc(),
463*b5893f02SDimitry Andric                     "Found conflicting definitions of TIIPredicate.");
464*b5893f02SDimitry Andric   }
465*b5893f02SDimitry Andric }
466*b5893f02SDimitry Andric 
collectRetireControlUnits()4674ba319b5SDimitry Andric void CodeGenSchedModels::collectRetireControlUnits() {
4684ba319b5SDimitry Andric   RecVec Units = Records.getAllDerivedDefinitions("RetireControlUnit");
4694ba319b5SDimitry Andric 
4704ba319b5SDimitry Andric   for (Record *RCU : Units) {
4714ba319b5SDimitry Andric     CodeGenProcModel &PM = getProcModel(RCU->getValueAsDef("SchedModel"));
4724ba319b5SDimitry Andric     if (PM.RetireControlUnit) {
4734ba319b5SDimitry Andric       PrintError(RCU->getLoc(),
4744ba319b5SDimitry Andric                  "Expected a single RetireControlUnit definition");
4754ba319b5SDimitry Andric       PrintNote(PM.RetireControlUnit->getLoc(),
4764ba319b5SDimitry Andric                 "Previous definition of RetireControlUnit was here");
4774ba319b5SDimitry Andric     }
4784ba319b5SDimitry Andric     PM.RetireControlUnit = RCU;
4794ba319b5SDimitry Andric   }
4804ba319b5SDimitry Andric }
4814ba319b5SDimitry Andric 
collectLoadStoreQueueInfo()482*b5893f02SDimitry Andric void CodeGenSchedModels::collectLoadStoreQueueInfo() {
483*b5893f02SDimitry Andric   RecVec Queues = Records.getAllDerivedDefinitions("MemoryQueue");
484*b5893f02SDimitry Andric 
485*b5893f02SDimitry Andric   for (Record *Queue : Queues) {
486*b5893f02SDimitry Andric     CodeGenProcModel &PM = getProcModel(Queue->getValueAsDef("SchedModel"));
487*b5893f02SDimitry Andric     if (Queue->isSubClassOf("LoadQueue")) {
488*b5893f02SDimitry Andric       if (PM.LoadQueue) {
489*b5893f02SDimitry Andric         PrintError(Queue->getLoc(),
490*b5893f02SDimitry Andric                    "Expected a single LoadQueue definition");
491*b5893f02SDimitry Andric         PrintNote(PM.LoadQueue->getLoc(),
492*b5893f02SDimitry Andric                   "Previous definition of LoadQueue was here");
493*b5893f02SDimitry Andric       }
494*b5893f02SDimitry Andric 
495*b5893f02SDimitry Andric       PM.LoadQueue = Queue;
496*b5893f02SDimitry Andric     }
497*b5893f02SDimitry Andric 
498*b5893f02SDimitry Andric     if (Queue->isSubClassOf("StoreQueue")) {
499*b5893f02SDimitry Andric       if (PM.StoreQueue) {
500*b5893f02SDimitry Andric         PrintError(Queue->getLoc(),
501*b5893f02SDimitry Andric                    "Expected a single StoreQueue definition");
502*b5893f02SDimitry Andric         PrintNote(PM.LoadQueue->getLoc(),
503*b5893f02SDimitry Andric                   "Previous definition of StoreQueue was here");
504*b5893f02SDimitry Andric       }
505*b5893f02SDimitry Andric 
506*b5893f02SDimitry Andric       PM.StoreQueue = Queue;
507*b5893f02SDimitry Andric     }
508*b5893f02SDimitry Andric   }
509*b5893f02SDimitry Andric }
510*b5893f02SDimitry Andric 
5114ba319b5SDimitry Andric /// Collect optional processor information.
collectOptionalProcessorInfo()5124ba319b5SDimitry Andric void CodeGenSchedModels::collectOptionalProcessorInfo() {
5134ba319b5SDimitry Andric   // Find register file definitions for each processor.
5144ba319b5SDimitry Andric   collectRegisterFiles();
5154ba319b5SDimitry Andric 
5164ba319b5SDimitry Andric   // Collect processor RetireControlUnit descriptors if available.
5174ba319b5SDimitry Andric   collectRetireControlUnits();
5184ba319b5SDimitry Andric 
519*b5893f02SDimitry Andric   // Collect information about load/store queues.
520*b5893f02SDimitry Andric   collectLoadStoreQueueInfo();
5214ba319b5SDimitry Andric 
5223ca95b02SDimitry Andric   checkCompleteness();
5237ae0e2c9SDimitry Andric }
5247ae0e2c9SDimitry Andric 
5253861d79fSDimitry Andric /// Gather all processor models.
collectProcModels()5263861d79fSDimitry Andric void CodeGenSchedModels::collectProcModels() {
5273861d79fSDimitry Andric   RecVec ProcRecords = Records.getAllDerivedDefinitions("Processor");
528*b5893f02SDimitry Andric   llvm::sort(ProcRecords, LessRecordFieldName());
5297ae0e2c9SDimitry Andric 
5303861d79fSDimitry Andric   // Reserve space because we can. Reallocation would be ok.
5313861d79fSDimitry Andric   ProcModels.reserve(ProcRecords.size()+1);
5323861d79fSDimitry Andric 
5333861d79fSDimitry Andric   // Use idx=0 for NoModel/NoItineraries.
5343861d79fSDimitry Andric   Record *NoModelDef = Records.getDef("NoSchedModel");
5353861d79fSDimitry Andric   Record *NoItinsDef = Records.getDef("NoItineraries");
53697bc6c73SDimitry Andric   ProcModels.emplace_back(0, "NoSchedModel", NoModelDef, NoItinsDef);
5373861d79fSDimitry Andric   ProcModelMap[NoModelDef] = 0;
5383861d79fSDimitry Andric 
5393861d79fSDimitry Andric   // For each processor, find a unique machine model.
5404ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "+++ PROCESSOR MODELs (addProcModel) +++\n");
5412cab237bSDimitry Andric   for (Record *ProcRecord : ProcRecords)
5422cab237bSDimitry Andric     addProcModel(ProcRecord);
5433861d79fSDimitry Andric }
5443861d79fSDimitry Andric 
5453861d79fSDimitry Andric /// Get a unique processor model based on the defined MachineModel and
5463861d79fSDimitry Andric /// ProcessorItineraries.
addProcModel(Record * ProcDef)5473861d79fSDimitry Andric void CodeGenSchedModels::addProcModel(Record *ProcDef) {
5483861d79fSDimitry Andric   Record *ModelKey = getModelOrItinDef(ProcDef);
5493861d79fSDimitry Andric   if (!ProcModelMap.insert(std::make_pair(ModelKey, ProcModels.size())).second)
5503861d79fSDimitry Andric     return;
5513861d79fSDimitry Andric 
5523861d79fSDimitry Andric   std::string Name = ModelKey->getName();
5533861d79fSDimitry Andric   if (ModelKey->isSubClassOf("SchedMachineModel")) {
5543861d79fSDimitry Andric     Record *ItinsDef = ModelKey->getValueAsDef("Itineraries");
55597bc6c73SDimitry Andric     ProcModels.emplace_back(ProcModels.size(), Name, ModelKey, ItinsDef);
5563861d79fSDimitry Andric   }
5573861d79fSDimitry Andric   else {
5583861d79fSDimitry Andric     // An itinerary is defined without a machine model. Infer a new model.
5593861d79fSDimitry Andric     if (!ModelKey->getValueAsListOfDefs("IID").empty())
5603861d79fSDimitry Andric       Name = Name + "Model";
56197bc6c73SDimitry Andric     ProcModels.emplace_back(ProcModels.size(), Name,
56297bc6c73SDimitry Andric                             ProcDef->getValueAsDef("SchedModel"), ModelKey);
5633861d79fSDimitry Andric   }
5644ba319b5SDimitry Andric   LLVM_DEBUG(ProcModels.back().dump());
5653861d79fSDimitry Andric }
5663861d79fSDimitry Andric 
5673861d79fSDimitry Andric // Recursively find all reachable SchedReadWrite records.
scanSchedRW(Record * RWDef,RecVec & RWDefs,SmallPtrSet<Record *,16> & RWSet)5683861d79fSDimitry Andric static void scanSchedRW(Record *RWDef, RecVec &RWDefs,
5693861d79fSDimitry Andric                         SmallPtrSet<Record*, 16> &RWSet) {
57039d628a0SDimitry Andric   if (!RWSet.insert(RWDef).second)
5713861d79fSDimitry Andric     return;
5723861d79fSDimitry Andric   RWDefs.push_back(RWDef);
5732cab237bSDimitry Andric   // Reads don't currently have sequence records, but it can be added later.
5743861d79fSDimitry Andric   if (RWDef->isSubClassOf("WriteSequence")) {
5753861d79fSDimitry Andric     RecVec Seq = RWDef->getValueAsListOfDefs("Writes");
5762cab237bSDimitry Andric     for (Record *WSRec : Seq)
5772cab237bSDimitry Andric       scanSchedRW(WSRec, RWDefs, RWSet);
5783861d79fSDimitry Andric   }
5793861d79fSDimitry Andric   else if (RWDef->isSubClassOf("SchedVariant")) {
5803861d79fSDimitry Andric     // Visit each variant (guarded by a different predicate).
5813861d79fSDimitry Andric     RecVec Vars = RWDef->getValueAsListOfDefs("Variants");
5822cab237bSDimitry Andric     for (Record *Variant : Vars) {
5833861d79fSDimitry Andric       // Visit each RW in the sequence selected by the current variant.
5842cab237bSDimitry Andric       RecVec Selected = Variant->getValueAsListOfDefs("Selected");
5852cab237bSDimitry Andric       for (Record *SelDef : Selected)
5862cab237bSDimitry Andric         scanSchedRW(SelDef, RWDefs, RWSet);
5873861d79fSDimitry Andric     }
5883861d79fSDimitry Andric   }
5893861d79fSDimitry Andric }
5903861d79fSDimitry Andric 
5913861d79fSDimitry Andric // Collect and sort all SchedReadWrites reachable via tablegen records.
5923861d79fSDimitry Andric // More may be inferred later when inferring new SchedClasses from variants.
collectSchedRW()5933861d79fSDimitry Andric void CodeGenSchedModels::collectSchedRW() {
5943861d79fSDimitry Andric   // Reserve idx=0 for invalid writes/reads.
5953861d79fSDimitry Andric   SchedWrites.resize(1);
5963861d79fSDimitry Andric   SchedReads.resize(1);
5973861d79fSDimitry Andric 
5983861d79fSDimitry Andric   SmallPtrSet<Record*, 16> RWSet;
5993861d79fSDimitry Andric 
6003861d79fSDimitry Andric   // Find all SchedReadWrites referenced by instruction defs.
6013861d79fSDimitry Andric   RecVec SWDefs, SRDefs;
6023ca95b02SDimitry Andric   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
60339d628a0SDimitry Andric     Record *SchedDef = Inst->TheDef;
604139f7f9bSDimitry Andric     if (SchedDef->isValueUnset("SchedRW"))
6053861d79fSDimitry Andric       continue;
6063861d79fSDimitry Andric     RecVec RWs = SchedDef->getValueAsListOfDefs("SchedRW");
6072cab237bSDimitry Andric     for (Record *RW : RWs) {
6082cab237bSDimitry Andric       if (RW->isSubClassOf("SchedWrite"))
6092cab237bSDimitry Andric         scanSchedRW(RW, SWDefs, RWSet);
6103861d79fSDimitry Andric       else {
6112cab237bSDimitry Andric         assert(RW->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
6122cab237bSDimitry Andric         scanSchedRW(RW, SRDefs, RWSet);
6133861d79fSDimitry Andric       }
6143861d79fSDimitry Andric     }
6153861d79fSDimitry Andric   }
6163861d79fSDimitry Andric   // Find all ReadWrites referenced by InstRW.
6173861d79fSDimitry Andric   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
6182cab237bSDimitry Andric   for (Record *InstRWDef : InstRWDefs) {
6193861d79fSDimitry Andric     // For all OperandReadWrites.
6202cab237bSDimitry Andric     RecVec RWDefs = InstRWDef->getValueAsListOfDefs("OperandReadWrites");
6212cab237bSDimitry Andric     for (Record *RWDef : RWDefs) {
6222cab237bSDimitry Andric       if (RWDef->isSubClassOf("SchedWrite"))
6232cab237bSDimitry Andric         scanSchedRW(RWDef, SWDefs, RWSet);
6243861d79fSDimitry Andric       else {
6252cab237bSDimitry Andric         assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
6262cab237bSDimitry Andric         scanSchedRW(RWDef, SRDefs, RWSet);
6273861d79fSDimitry Andric       }
6283861d79fSDimitry Andric     }
6293861d79fSDimitry Andric   }
6303861d79fSDimitry Andric   // Find all ReadWrites referenced by ItinRW.
6313861d79fSDimitry Andric   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
6322cab237bSDimitry Andric   for (Record *ItinRWDef : ItinRWDefs) {
6333861d79fSDimitry Andric     // For all OperandReadWrites.
6342cab237bSDimitry Andric     RecVec RWDefs = ItinRWDef->getValueAsListOfDefs("OperandReadWrites");
6352cab237bSDimitry Andric     for (Record *RWDef : RWDefs) {
6362cab237bSDimitry Andric       if (RWDef->isSubClassOf("SchedWrite"))
6372cab237bSDimitry Andric         scanSchedRW(RWDef, SWDefs, RWSet);
6383861d79fSDimitry Andric       else {
6392cab237bSDimitry Andric         assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
6402cab237bSDimitry Andric         scanSchedRW(RWDef, SRDefs, RWSet);
6413861d79fSDimitry Andric       }
6423861d79fSDimitry Andric     }
6433861d79fSDimitry Andric   }
6443861d79fSDimitry Andric   // Find all ReadWrites referenced by SchedAlias. AliasDefs needs to be sorted
6453861d79fSDimitry Andric   // for the loop below that initializes Alias vectors.
6463861d79fSDimitry Andric   RecVec AliasDefs = Records.getAllDerivedDefinitions("SchedAlias");
647*b5893f02SDimitry Andric   llvm::sort(AliasDefs, LessRecord());
6482cab237bSDimitry Andric   for (Record *ADef : AliasDefs) {
6492cab237bSDimitry Andric     Record *MatchDef = ADef->getValueAsDef("MatchRW");
6502cab237bSDimitry Andric     Record *AliasDef = ADef->getValueAsDef("AliasRW");
6513861d79fSDimitry Andric     if (MatchDef->isSubClassOf("SchedWrite")) {
6523861d79fSDimitry Andric       if (!AliasDef->isSubClassOf("SchedWrite"))
6532cab237bSDimitry Andric         PrintFatalError(ADef->getLoc(), "SchedWrite Alias must be SchedWrite");
6543861d79fSDimitry Andric       scanSchedRW(AliasDef, SWDefs, RWSet);
6553861d79fSDimitry Andric     }
6563861d79fSDimitry Andric     else {
6573861d79fSDimitry Andric       assert(MatchDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
6583861d79fSDimitry Andric       if (!AliasDef->isSubClassOf("SchedRead"))
6592cab237bSDimitry Andric         PrintFatalError(ADef->getLoc(), "SchedRead Alias must be SchedRead");
6603861d79fSDimitry Andric       scanSchedRW(AliasDef, SRDefs, RWSet);
6613861d79fSDimitry Andric     }
6623861d79fSDimitry Andric   }
6633861d79fSDimitry Andric   // Sort and add the SchedReadWrites directly referenced by instructions or
6643861d79fSDimitry Andric   // itinerary resources. Index reads and writes in separate domains.
665*b5893f02SDimitry Andric   llvm::sort(SWDefs, LessRecord());
6662cab237bSDimitry Andric   for (Record *SWDef : SWDefs) {
6672cab237bSDimitry Andric     assert(!getSchedRWIdx(SWDef, /*IsRead=*/false) && "duplicate SchedWrite");
6682cab237bSDimitry Andric     SchedWrites.emplace_back(SchedWrites.size(), SWDef);
6693861d79fSDimitry Andric   }
670*b5893f02SDimitry Andric   llvm::sort(SRDefs, LessRecord());
6712cab237bSDimitry Andric   for (Record *SRDef : SRDefs) {
6722cab237bSDimitry Andric     assert(!getSchedRWIdx(SRDef, /*IsRead-*/true) && "duplicate SchedWrite");
6732cab237bSDimitry Andric     SchedReads.emplace_back(SchedReads.size(), SRDef);
6743861d79fSDimitry Andric   }
6753861d79fSDimitry Andric   // Initialize WriteSequence vectors.
6762cab237bSDimitry Andric   for (CodeGenSchedRW &CGRW : SchedWrites) {
6772cab237bSDimitry Andric     if (!CGRW.IsSequence)
6783861d79fSDimitry Andric       continue;
6792cab237bSDimitry Andric     findRWs(CGRW.TheDef->getValueAsListOfDefs("Writes"), CGRW.Sequence,
6803861d79fSDimitry Andric             /*IsRead=*/false);
6813861d79fSDimitry Andric   }
6823861d79fSDimitry Andric   // Initialize Aliases vectors.
6832cab237bSDimitry Andric   for (Record *ADef : AliasDefs) {
6842cab237bSDimitry Andric     Record *AliasDef = ADef->getValueAsDef("AliasRW");
6853861d79fSDimitry Andric     getSchedRW(AliasDef).IsAlias = true;
6862cab237bSDimitry Andric     Record *MatchDef = ADef->getValueAsDef("MatchRW");
6873861d79fSDimitry Andric     CodeGenSchedRW &RW = getSchedRW(MatchDef);
6883861d79fSDimitry Andric     if (RW.IsAlias)
6892cab237bSDimitry Andric       PrintFatalError(ADef->getLoc(), "Cannot Alias an Alias");
6902cab237bSDimitry Andric     RW.Aliases.push_back(ADef);
6913861d79fSDimitry Andric   }
6924ba319b5SDimitry Andric   LLVM_DEBUG(
693a580b014SDimitry Andric       dbgs() << "\n+++ SCHED READS and WRITES (collectSchedRW) +++\n";
6943861d79fSDimitry Andric       for (unsigned WIdx = 0, WEnd = SchedWrites.size(); WIdx != WEnd; ++WIdx) {
6953861d79fSDimitry Andric         dbgs() << WIdx << ": ";
6963861d79fSDimitry Andric         SchedWrites[WIdx].dump();
6973861d79fSDimitry Andric         dbgs() << '\n';
6984ba319b5SDimitry Andric       } for (unsigned RIdx = 0, REnd = SchedReads.size(); RIdx != REnd;
6994ba319b5SDimitry Andric              ++RIdx) {
7003861d79fSDimitry Andric         dbgs() << RIdx << ": ";
7013861d79fSDimitry Andric         SchedReads[RIdx].dump();
7023861d79fSDimitry Andric         dbgs() << '\n';
7034ba319b5SDimitry Andric       } RecVec RWDefs = Records.getAllDerivedDefinitions("SchedReadWrite");
7044ba319b5SDimitry Andric       for (Record *RWDef
7054ba319b5SDimitry Andric            : RWDefs) {
7062cab237bSDimitry Andric         if (!getSchedRWIdx(RWDef, RWDef->isSubClassOf("SchedRead"))) {
7074ba319b5SDimitry Andric           StringRef Name = RWDef->getName();
7083861d79fSDimitry Andric           if (Name != "NoWrite" && Name != "ReadDefault")
7094ba319b5SDimitry Andric             dbgs() << "Unused SchedReadWrite " << Name << '\n';
7103861d79fSDimitry Andric         }
7113861d79fSDimitry Andric       });
7123861d79fSDimitry Andric }
7133861d79fSDimitry Andric 
7143861d79fSDimitry Andric /// Compute a SchedWrite name from a sequence of writes.
genRWName(ArrayRef<unsigned> Seq,bool IsRead)7157d523365SDimitry Andric std::string CodeGenSchedModels::genRWName(ArrayRef<unsigned> Seq, bool IsRead) {
7163861d79fSDimitry Andric   std::string Name("(");
7177d523365SDimitry Andric   for (auto I = Seq.begin(), E = Seq.end(); I != E; ++I) {
7183861d79fSDimitry Andric     if (I != Seq.begin())
7193861d79fSDimitry Andric       Name += '_';
7203861d79fSDimitry Andric     Name += getSchedRW(*I, IsRead).Name;
7213861d79fSDimitry Andric   }
7223861d79fSDimitry Andric   Name += ')';
7233861d79fSDimitry Andric   return Name;
7243861d79fSDimitry Andric }
7253861d79fSDimitry Andric 
getSchedRWIdx(const Record * Def,bool IsRead) const7264ba319b5SDimitry Andric unsigned CodeGenSchedModels::getSchedRWIdx(const Record *Def,
7274ba319b5SDimitry Andric                                            bool IsRead) const {
7283861d79fSDimitry Andric   const std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
7294ba319b5SDimitry Andric   const auto I = find_if(
7304ba319b5SDimitry Andric       RWVec, [Def](const CodeGenSchedRW &RW) { return RW.TheDef == Def; });
7314ba319b5SDimitry Andric   return I == RWVec.end() ? 0 : std::distance(RWVec.begin(), I);
7323861d79fSDimitry Andric }
7333861d79fSDimitry Andric 
hasReadOfWrite(Record * WriteDef) const7343861d79fSDimitry Andric bool CodeGenSchedModels::hasReadOfWrite(Record *WriteDef) const {
7352cab237bSDimitry Andric   for (const CodeGenSchedRW &Read : SchedReads) {
7362cab237bSDimitry Andric     Record *ReadDef = Read.TheDef;
7373861d79fSDimitry Andric     if (!ReadDef || !ReadDef->isSubClassOf("ProcReadAdvance"))
7383861d79fSDimitry Andric       continue;
7393861d79fSDimitry Andric 
7403861d79fSDimitry Andric     RecVec ValidWrites = ReadDef->getValueAsListOfDefs("ValidWrites");
741d88c1a5aSDimitry Andric     if (is_contained(ValidWrites, WriteDef)) {
7423861d79fSDimitry Andric       return true;
7433861d79fSDimitry Andric     }
7443861d79fSDimitry Andric   }
7453861d79fSDimitry Andric   return false;
7463861d79fSDimitry Andric }
7473861d79fSDimitry Andric 
splitSchedReadWrites(const RecVec & RWDefs,RecVec & WriteDefs,RecVec & ReadDefs)7484ba319b5SDimitry Andric static void splitSchedReadWrites(const RecVec &RWDefs,
7493861d79fSDimitry Andric                                  RecVec &WriteDefs, RecVec &ReadDefs) {
7502cab237bSDimitry Andric   for (Record *RWDef : RWDefs) {
7512cab237bSDimitry Andric     if (RWDef->isSubClassOf("SchedWrite"))
7522cab237bSDimitry Andric       WriteDefs.push_back(RWDef);
7533861d79fSDimitry Andric     else {
7542cab237bSDimitry Andric       assert(RWDef->isSubClassOf("SchedRead") && "unknown SchedReadWrite");
7552cab237bSDimitry Andric       ReadDefs.push_back(RWDef);
7563861d79fSDimitry Andric     }
7573861d79fSDimitry Andric   }
7583861d79fSDimitry Andric }
759d88c1a5aSDimitry Andric 
7603861d79fSDimitry Andric // Split the SchedReadWrites defs and call findRWs for each list.
findRWs(const RecVec & RWDefs,IdxVec & Writes,IdxVec & Reads) const7613861d79fSDimitry Andric void CodeGenSchedModels::findRWs(const RecVec &RWDefs,
7623861d79fSDimitry Andric                                  IdxVec &Writes, IdxVec &Reads) const {
7633861d79fSDimitry Andric   RecVec WriteDefs;
7643861d79fSDimitry Andric   RecVec ReadDefs;
7653861d79fSDimitry Andric   splitSchedReadWrites(RWDefs, WriteDefs, ReadDefs);
7663861d79fSDimitry Andric   findRWs(WriteDefs, Writes, false);
7673861d79fSDimitry Andric   findRWs(ReadDefs, Reads, true);
7683861d79fSDimitry Andric }
7693861d79fSDimitry Andric 
7703861d79fSDimitry Andric // Call getSchedRWIdx for all elements in a sequence of SchedRW defs.
findRWs(const RecVec & RWDefs,IdxVec & RWs,bool IsRead) const7713861d79fSDimitry Andric void CodeGenSchedModels::findRWs(const RecVec &RWDefs, IdxVec &RWs,
7723861d79fSDimitry Andric                                  bool IsRead) const {
7732cab237bSDimitry Andric   for (Record *RWDef : RWDefs) {
7742cab237bSDimitry Andric     unsigned Idx = getSchedRWIdx(RWDef, IsRead);
7753861d79fSDimitry Andric     assert(Idx && "failed to collect SchedReadWrite");
7763861d79fSDimitry Andric     RWs.push_back(Idx);
7773861d79fSDimitry Andric   }
7783861d79fSDimitry Andric }
7793861d79fSDimitry Andric 
expandRWSequence(unsigned RWIdx,IdxVec & RWSeq,bool IsRead) const7803861d79fSDimitry Andric void CodeGenSchedModels::expandRWSequence(unsigned RWIdx, IdxVec &RWSeq,
7813861d79fSDimitry Andric                                           bool IsRead) const {
7823861d79fSDimitry Andric   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
7833861d79fSDimitry Andric   if (!SchedRW.IsSequence) {
7843861d79fSDimitry Andric     RWSeq.push_back(RWIdx);
7853861d79fSDimitry Andric     return;
7863861d79fSDimitry Andric   }
7873861d79fSDimitry Andric   int Repeat =
7883861d79fSDimitry Andric     SchedRW.TheDef ? SchedRW.TheDef->getValueAsInt("Repeat") : 1;
7893861d79fSDimitry Andric   for (int i = 0; i < Repeat; ++i) {
7902cab237bSDimitry Andric     for (unsigned I : SchedRW.Sequence) {
7912cab237bSDimitry Andric       expandRWSequence(I, RWSeq, IsRead);
7923861d79fSDimitry Andric     }
7933861d79fSDimitry Andric   }
7943861d79fSDimitry Andric }
7953861d79fSDimitry Andric 
7963861d79fSDimitry Andric // Expand a SchedWrite as a sequence following any aliases that coincide with
7973861d79fSDimitry Andric // the given processor model.
expandRWSeqForProc(unsigned RWIdx,IdxVec & RWSeq,bool IsRead,const CodeGenProcModel & ProcModel) const7983861d79fSDimitry Andric void CodeGenSchedModels::expandRWSeqForProc(
7993861d79fSDimitry Andric   unsigned RWIdx, IdxVec &RWSeq, bool IsRead,
8003861d79fSDimitry Andric   const CodeGenProcModel &ProcModel) const {
8013861d79fSDimitry Andric 
8023861d79fSDimitry Andric   const CodeGenSchedRW &SchedWrite = getSchedRW(RWIdx, IsRead);
80391bc56edSDimitry Andric   Record *AliasDef = nullptr;
8044ba319b5SDimitry Andric   for (const Record *Rec : SchedWrite.Aliases) {
8054ba319b5SDimitry Andric     const CodeGenSchedRW &AliasRW = getSchedRW(Rec->getValueAsDef("AliasRW"));
8064ba319b5SDimitry Andric     if (Rec->getValueInit("SchedModel")->isComplete()) {
8074ba319b5SDimitry Andric       Record *ModelDef = Rec->getValueAsDef("SchedModel");
8083861d79fSDimitry Andric       if (&getProcModel(ModelDef) != &ProcModel)
8093861d79fSDimitry Andric         continue;
8103861d79fSDimitry Andric     }
8113861d79fSDimitry Andric     if (AliasDef)
8123861d79fSDimitry Andric       PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
8133861d79fSDimitry Andric                       "defined for processor " + ProcModel.ModelName +
8143861d79fSDimitry Andric                       " Ensure only one SchedAlias exists per RW.");
8153861d79fSDimitry Andric     AliasDef = AliasRW.TheDef;
8163861d79fSDimitry Andric   }
8173861d79fSDimitry Andric   if (AliasDef) {
8183861d79fSDimitry Andric     expandRWSeqForProc(getSchedRWIdx(AliasDef, IsRead),
8193861d79fSDimitry Andric                        RWSeq, IsRead,ProcModel);
8203861d79fSDimitry Andric     return;
8213861d79fSDimitry Andric   }
8223861d79fSDimitry Andric   if (!SchedWrite.IsSequence) {
8233861d79fSDimitry Andric     RWSeq.push_back(RWIdx);
8243861d79fSDimitry Andric     return;
8253861d79fSDimitry Andric   }
8263861d79fSDimitry Andric   int Repeat =
8273861d79fSDimitry Andric     SchedWrite.TheDef ? SchedWrite.TheDef->getValueAsInt("Repeat") : 1;
8284ba319b5SDimitry Andric   for (int I = 0, E = Repeat; I < E; ++I) {
8294ba319b5SDimitry Andric     for (unsigned Idx : SchedWrite.Sequence) {
8304ba319b5SDimitry Andric       expandRWSeqForProc(Idx, RWSeq, IsRead, ProcModel);
8313861d79fSDimitry Andric     }
8323861d79fSDimitry Andric   }
8333861d79fSDimitry Andric }
8343861d79fSDimitry Andric 
8353861d79fSDimitry Andric // Find the existing SchedWrite that models this sequence of writes.
findRWForSequence(ArrayRef<unsigned> Seq,bool IsRead)8367d523365SDimitry Andric unsigned CodeGenSchedModels::findRWForSequence(ArrayRef<unsigned> Seq,
8373861d79fSDimitry Andric                                                bool IsRead) {
8383861d79fSDimitry Andric   std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
8393861d79fSDimitry Andric 
8404ba319b5SDimitry Andric   auto I = find_if(RWVec, [Seq](CodeGenSchedRW &RW) {
8414ba319b5SDimitry Andric     return makeArrayRef(RW.Sequence) == Seq;
8424ba319b5SDimitry Andric   });
8433861d79fSDimitry Andric   // Index zero reserved for invalid RW.
8444ba319b5SDimitry Andric   return I == RWVec.end() ? 0 : std::distance(RWVec.begin(), I);
8453861d79fSDimitry Andric }
8463861d79fSDimitry Andric 
8473861d79fSDimitry Andric /// Add this ReadWrite if it doesn't already exist.
findOrInsertRW(ArrayRef<unsigned> Seq,bool IsRead)8483861d79fSDimitry Andric unsigned CodeGenSchedModels::findOrInsertRW(ArrayRef<unsigned> Seq,
8493861d79fSDimitry Andric                                             bool IsRead) {
8503861d79fSDimitry Andric   assert(!Seq.empty() && "cannot insert empty sequence");
8513861d79fSDimitry Andric   if (Seq.size() == 1)
8523861d79fSDimitry Andric     return Seq.back();
8533861d79fSDimitry Andric 
8543861d79fSDimitry Andric   unsigned Idx = findRWForSequence(Seq, IsRead);
8553861d79fSDimitry Andric   if (Idx)
8563861d79fSDimitry Andric     return Idx;
8573861d79fSDimitry Andric 
8584ba319b5SDimitry Andric   std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
8594ba319b5SDimitry Andric   unsigned RWIdx = RWVec.size();
8603861d79fSDimitry Andric   CodeGenSchedRW SchedRW(RWIdx, IsRead, Seq, genRWName(Seq, IsRead));
8614ba319b5SDimitry Andric   RWVec.push_back(SchedRW);
8623861d79fSDimitry Andric   return RWIdx;
8633861d79fSDimitry Andric }
8643861d79fSDimitry Andric 
8653861d79fSDimitry Andric /// Visit all the instruction definitions for this target to gather and
8663861d79fSDimitry Andric /// enumerate the itinerary classes. These are the explicitly specified
8673861d79fSDimitry Andric /// SchedClasses. More SchedClasses may be inferred.
collectSchedClasses()8683861d79fSDimitry Andric void CodeGenSchedModels::collectSchedClasses() {
8693861d79fSDimitry Andric 
8703861d79fSDimitry Andric   // NoItinerary is always the first class at Idx=0
8714ba319b5SDimitry Andric   assert(SchedClasses.empty() && "Expected empty sched class");
8724ba319b5SDimitry Andric   SchedClasses.emplace_back(0, "NoInstrModel",
8734ba319b5SDimitry Andric                             Records.getDef("NoItinerary"));
8743861d79fSDimitry Andric   SchedClasses.back().ProcIndices.push_back(0);
8757ae0e2c9SDimitry Andric 
876139f7f9bSDimitry Andric   // Create a SchedClass for each unique combination of itinerary class and
877139f7f9bSDimitry Andric   // SchedRW list.
8783ca95b02SDimitry Andric   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
87939d628a0SDimitry Andric     Record *ItinDef = Inst->TheDef->getValueAsDef("Itinerary");
8803861d79fSDimitry Andric     IdxVec Writes, Reads;
88139d628a0SDimitry Andric     if (!Inst->TheDef->isValueUnset("SchedRW"))
88239d628a0SDimitry Andric       findRWs(Inst->TheDef->getValueAsListOfDefs("SchedRW"), Writes, Reads);
883139f7f9bSDimitry Andric 
8843861d79fSDimitry Andric     // ProcIdx == 0 indicates the class applies to all processors.
8854ba319b5SDimitry Andric     unsigned SCIdx = addSchedClass(ItinDef, Writes, Reads, /*ProcIndices*/{0});
88639d628a0SDimitry Andric     InstrClassMap[Inst->TheDef] = SCIdx;
8877ae0e2c9SDimitry Andric   }
8883861d79fSDimitry Andric   // Create classes for InstRW defs.
8893861d79fSDimitry Andric   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
890*b5893f02SDimitry Andric   llvm::sort(InstRWDefs, LessRecord());
8914ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n+++ SCHED CLASSES (createInstRWClass) +++\n");
8922cab237bSDimitry Andric   for (Record *RWDef : InstRWDefs)
8932cab237bSDimitry Andric     createInstRWClass(RWDef);
8947ae0e2c9SDimitry Andric 
8953861d79fSDimitry Andric   NumInstrSchedClasses = SchedClasses.size();
8967ae0e2c9SDimitry Andric 
8973861d79fSDimitry Andric   bool EnableDump = false;
8984ba319b5SDimitry Andric   LLVM_DEBUG(EnableDump = true);
8993861d79fSDimitry Andric   if (!EnableDump)
9007ae0e2c9SDimitry Andric     return;
901139f7f9bSDimitry Andric 
9024ba319b5SDimitry Andric   LLVM_DEBUG(
9034ba319b5SDimitry Andric       dbgs()
9044ba319b5SDimitry Andric       << "\n+++ ITINERARIES and/or MACHINE MODELS (collectSchedClasses) +++\n");
9053ca95b02SDimitry Andric   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
906f9448bf3SDimitry Andric     StringRef InstName = Inst->TheDef->getName();
9074ba319b5SDimitry Andric     unsigned SCIdx = getSchedClassIdx(*Inst);
908139f7f9bSDimitry Andric     if (!SCIdx) {
9094ba319b5SDimitry Andric       LLVM_DEBUG({
9103ca95b02SDimitry Andric         if (!Inst->hasNoSchedulingInfo)
91139d628a0SDimitry Andric           dbgs() << "No machine model for " << Inst->TheDef->getName() << '\n';
9124ba319b5SDimitry Andric       });
913139f7f9bSDimitry Andric       continue;
914139f7f9bSDimitry Andric     }
915139f7f9bSDimitry Andric     CodeGenSchedClass &SC = getSchedClass(SCIdx);
916139f7f9bSDimitry Andric     if (SC.ProcIndices[0] != 0)
91739d628a0SDimitry Andric       PrintFatalError(Inst->TheDef->getLoc(), "Instruction's sched class "
918139f7f9bSDimitry Andric                       "must not be subtarget specific.");
919139f7f9bSDimitry Andric 
920139f7f9bSDimitry Andric     IdxVec ProcIndices;
921139f7f9bSDimitry Andric     if (SC.ItinClassDef->getName() != "NoItinerary") {
922139f7f9bSDimitry Andric       ProcIndices.push_back(0);
923139f7f9bSDimitry Andric       dbgs() << "Itinerary for " << InstName << ": "
924139f7f9bSDimitry Andric              << SC.ItinClassDef->getName() << '\n';
925139f7f9bSDimitry Andric     }
926139f7f9bSDimitry Andric     if (!SC.Writes.empty()) {
927139f7f9bSDimitry Andric       ProcIndices.push_back(0);
9284ba319b5SDimitry Andric       LLVM_DEBUG({
9293861d79fSDimitry Andric         dbgs() << "SchedRW machine model for " << InstName;
9304ba319b5SDimitry Andric         for (IdxIter WI = SC.Writes.begin(), WE = SC.Writes.end(); WI != WE;
9314ba319b5SDimitry Andric              ++WI)
9323861d79fSDimitry Andric           dbgs() << " " << SchedWrites[*WI].Name;
933139f7f9bSDimitry Andric         for (IdxIter RI = SC.Reads.begin(), RE = SC.Reads.end(); RI != RE; ++RI)
9343861d79fSDimitry Andric           dbgs() << " " << SchedReads[*RI].Name;
9353861d79fSDimitry Andric         dbgs() << '\n';
9364ba319b5SDimitry Andric       });
9373861d79fSDimitry Andric     }
9383861d79fSDimitry Andric     const RecVec &RWDefs = SchedClasses[SCIdx].InstRWs;
9392cab237bSDimitry Andric     for (Record *RWDef : RWDefs) {
9403861d79fSDimitry Andric       const CodeGenProcModel &ProcModel =
9412cab237bSDimitry Andric           getProcModel(RWDef->getValueAsDef("SchedModel"));
942139f7f9bSDimitry Andric       ProcIndices.push_back(ProcModel.Index);
9434ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "InstRW on " << ProcModel.ModelName << " for "
9444ba319b5SDimitry Andric                         << InstName);
9453861d79fSDimitry Andric       IdxVec Writes;
9463861d79fSDimitry Andric       IdxVec Reads;
9472cab237bSDimitry Andric       findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
9483861d79fSDimitry Andric               Writes, Reads);
9494ba319b5SDimitry Andric       LLVM_DEBUG({
9502cab237bSDimitry Andric         for (unsigned WIdx : Writes)
9512cab237bSDimitry Andric           dbgs() << " " << SchedWrites[WIdx].Name;
9522cab237bSDimitry Andric         for (unsigned RIdx : Reads)
9532cab237bSDimitry Andric           dbgs() << " " << SchedReads[RIdx].Name;
9543861d79fSDimitry Andric         dbgs() << '\n';
9554ba319b5SDimitry Andric       });
9563861d79fSDimitry Andric     }
957d88c1a5aSDimitry Andric     // If ProcIndices contains zero, the class applies to all processors.
9584ba319b5SDimitry Andric     LLVM_DEBUG({
959d88c1a5aSDimitry Andric       if (!std::count(ProcIndices.begin(), ProcIndices.end(), 0)) {
9602cab237bSDimitry Andric         for (const CodeGenProcModel &PM : ProcModels) {
9612cab237bSDimitry Andric           if (!std::count(ProcIndices.begin(), ProcIndices.end(), PM.Index))
96239d628a0SDimitry Andric             dbgs() << "No machine model for " << Inst->TheDef->getName()
9632cab237bSDimitry Andric                    << " on processor " << PM.ModelName << '\n';
9647ae0e2c9SDimitry Andric         }
9657ae0e2c9SDimitry Andric       }
9664ba319b5SDimitry Andric     });
9673861d79fSDimitry Andric   }
968d88c1a5aSDimitry Andric }
9693861d79fSDimitry Andric 
9703861d79fSDimitry Andric // Get the SchedClass index for an instruction.
9714ba319b5SDimitry Andric unsigned
getSchedClassIdx(const CodeGenInstruction & Inst) const9724ba319b5SDimitry Andric CodeGenSchedModels::getSchedClassIdx(const CodeGenInstruction &Inst) const {
973139f7f9bSDimitry Andric   return InstrClassMap.lookup(Inst.TheDef);
9743861d79fSDimitry Andric }
9753861d79fSDimitry Andric 
9767d523365SDimitry Andric std::string
createSchedClassName(Record * ItinClassDef,ArrayRef<unsigned> OperWrites,ArrayRef<unsigned> OperReads)9777d523365SDimitry Andric CodeGenSchedModels::createSchedClassName(Record *ItinClassDef,
9787d523365SDimitry Andric                                          ArrayRef<unsigned> OperWrites,
9797d523365SDimitry Andric                                          ArrayRef<unsigned> OperReads) {
9803861d79fSDimitry Andric 
9813861d79fSDimitry Andric   std::string Name;
982139f7f9bSDimitry Andric   if (ItinClassDef && ItinClassDef->getName() != "NoItinerary")
983139f7f9bSDimitry Andric     Name = ItinClassDef->getName();
9847d523365SDimitry Andric   for (unsigned Idx : OperWrites) {
985139f7f9bSDimitry Andric     if (!Name.empty())
9863861d79fSDimitry Andric       Name += '_';
9877d523365SDimitry Andric     Name += SchedWrites[Idx].Name;
9883861d79fSDimitry Andric   }
9897d523365SDimitry Andric   for (unsigned Idx : OperReads) {
9903861d79fSDimitry Andric     Name += '_';
9917d523365SDimitry Andric     Name += SchedReads[Idx].Name;
9923861d79fSDimitry Andric   }
9933861d79fSDimitry Andric   return Name;
9943861d79fSDimitry Andric }
9953861d79fSDimitry Andric 
createSchedClassName(const RecVec & InstDefs)9963861d79fSDimitry Andric std::string CodeGenSchedModels::createSchedClassName(const RecVec &InstDefs) {
9973861d79fSDimitry Andric 
9983861d79fSDimitry Andric   std::string Name;
9993861d79fSDimitry Andric   for (RecIter I = InstDefs.begin(), E = InstDefs.end(); I != E; ++I) {
10003861d79fSDimitry Andric     if (I != InstDefs.begin())
10013861d79fSDimitry Andric       Name += '_';
10023861d79fSDimitry Andric     Name += (*I)->getName();
10033861d79fSDimitry Andric   }
10043861d79fSDimitry Andric   return Name;
10053861d79fSDimitry Andric }
10063861d79fSDimitry Andric 
1007139f7f9bSDimitry Andric /// Add an inferred sched class from an itinerary class and per-operand list of
1008139f7f9bSDimitry Andric /// SchedWrites and SchedReads. ProcIndices contains the set of IDs of
1009139f7f9bSDimitry Andric /// processors that may utilize this class.
addSchedClass(Record * ItinClassDef,ArrayRef<unsigned> OperWrites,ArrayRef<unsigned> OperReads,ArrayRef<unsigned> ProcIndices)1010139f7f9bSDimitry Andric unsigned CodeGenSchedModels::addSchedClass(Record *ItinClassDef,
10117d523365SDimitry Andric                                            ArrayRef<unsigned> OperWrites,
10127d523365SDimitry Andric                                            ArrayRef<unsigned> OperReads,
10137d523365SDimitry Andric                                            ArrayRef<unsigned> ProcIndices) {
10143861d79fSDimitry Andric   assert(!ProcIndices.empty() && "expect at least one ProcIdx");
10153861d79fSDimitry Andric 
10164ba319b5SDimitry Andric   auto IsKeyEqual = [=](const CodeGenSchedClass &SC) {
10174ba319b5SDimitry Andric                      return SC.isKeyEqual(ItinClassDef, OperWrites, OperReads);
10184ba319b5SDimitry Andric                    };
10194ba319b5SDimitry Andric 
10204ba319b5SDimitry Andric   auto I = find_if(make_range(schedClassBegin(), schedClassEnd()), IsKeyEqual);
10214ba319b5SDimitry Andric   unsigned Idx = I == schedClassEnd() ? 0 : std::distance(schedClassBegin(), I);
1022139f7f9bSDimitry Andric   if (Idx || SchedClasses[0].isKeyEqual(ItinClassDef, OperWrites, OperReads)) {
10233861d79fSDimitry Andric     IdxVec PI;
10243861d79fSDimitry Andric     std::set_union(SchedClasses[Idx].ProcIndices.begin(),
10253861d79fSDimitry Andric                    SchedClasses[Idx].ProcIndices.end(),
10263861d79fSDimitry Andric                    ProcIndices.begin(), ProcIndices.end(),
10273861d79fSDimitry Andric                    std::back_inserter(PI));
10284ba319b5SDimitry Andric     SchedClasses[Idx].ProcIndices = std::move(PI);
10293861d79fSDimitry Andric     return Idx;
10303861d79fSDimitry Andric   }
10313861d79fSDimitry Andric   Idx = SchedClasses.size();
10324ba319b5SDimitry Andric   SchedClasses.emplace_back(Idx,
10334ba319b5SDimitry Andric                             createSchedClassName(ItinClassDef, OperWrites,
10344ba319b5SDimitry Andric                                                  OperReads),
10354ba319b5SDimitry Andric                             ItinClassDef);
10363861d79fSDimitry Andric   CodeGenSchedClass &SC = SchedClasses.back();
10373861d79fSDimitry Andric   SC.Writes = OperWrites;
10383861d79fSDimitry Andric   SC.Reads = OperReads;
10393861d79fSDimitry Andric   SC.ProcIndices = ProcIndices;
10403861d79fSDimitry Andric 
10413861d79fSDimitry Andric   return Idx;
10423861d79fSDimitry Andric }
10433861d79fSDimitry Andric 
10443861d79fSDimitry Andric // Create classes for each set of opcodes that are in the same InstReadWrite
10453861d79fSDimitry Andric // definition across all processors.
createInstRWClass(Record * InstRWDef)10463861d79fSDimitry Andric void CodeGenSchedModels::createInstRWClass(Record *InstRWDef) {
10473861d79fSDimitry Andric   // ClassInstrs will hold an entry for each subset of Instrs in InstRWDef that
10483861d79fSDimitry Andric   // intersects with an existing class via a previous InstRWDef. Instrs that do
10493861d79fSDimitry Andric   // not intersect with an existing class refer back to their former class as
10503861d79fSDimitry Andric   // determined from ItinDef or SchedRW.
10514ba319b5SDimitry Andric   SmallMapVector<unsigned, SmallVector<Record *, 8>, 4> ClassInstrs;
10523861d79fSDimitry Andric   // Sort Instrs into sets.
10533861d79fSDimitry Andric   const RecVec *InstDefs = Sets.expand(InstRWDef);
10543861d79fSDimitry Andric   if (InstDefs->empty())
10553861d79fSDimitry Andric     PrintFatalError(InstRWDef->getLoc(), "No matching instruction opcodes");
10563861d79fSDimitry Andric 
10574ba319b5SDimitry Andric   for (Record *InstDef : *InstDefs) {
10582cab237bSDimitry Andric     InstClassMapTy::const_iterator Pos = InstrClassMap.find(InstDef);
1059139f7f9bSDimitry Andric     if (Pos == InstrClassMap.end())
10602cab237bSDimitry Andric       PrintFatalError(InstDef->getLoc(), "No sched class for instruction.");
1061139f7f9bSDimitry Andric     unsigned SCIdx = Pos->second;
10624ba319b5SDimitry Andric     ClassInstrs[SCIdx].push_back(InstDef);
10633861d79fSDimitry Andric   }
10643861d79fSDimitry Andric   // For each set of Instrs, create a new class if necessary, and map or remap
10653861d79fSDimitry Andric   // the Instrs to it.
10664ba319b5SDimitry Andric   for (auto &Entry : ClassInstrs) {
10674ba319b5SDimitry Andric     unsigned OldSCIdx = Entry.first;
10684ba319b5SDimitry Andric     ArrayRef<Record*> InstDefs = Entry.second;
10693861d79fSDimitry Andric     // If the all instrs in the current class are accounted for, then leave
10703861d79fSDimitry Andric     // them mapped to their old class.
1071f785676fSDimitry Andric     if (OldSCIdx) {
1072f785676fSDimitry Andric       const RecVec &RWDefs = SchedClasses[OldSCIdx].InstRWs;
1073f785676fSDimitry Andric       if (!RWDefs.empty()) {
1074f785676fSDimitry Andric         const RecVec *OrigInstDefs = Sets.expand(RWDefs[0]);
10754ba319b5SDimitry Andric         unsigned OrigNumInstrs =
10764ba319b5SDimitry Andric           count_if(*OrigInstDefs, [&](Record *OIDef) {
10774ba319b5SDimitry Andric                      return InstrClassMap[OIDef] == OldSCIdx;
10784ba319b5SDimitry Andric                    });
1079f785676fSDimitry Andric         if (OrigNumInstrs == InstDefs.size()) {
10803861d79fSDimitry Andric           assert(SchedClasses[OldSCIdx].ProcIndices[0] == 0 &&
10813861d79fSDimitry Andric                  "expected a generic SchedClass");
10824ba319b5SDimitry Andric           Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
10834ba319b5SDimitry Andric           // Make sure we didn't already have a InstRW containing this
10844ba319b5SDimitry Andric           // instruction on this model.
10854ba319b5SDimitry Andric           for (Record *RWD : RWDefs) {
10864ba319b5SDimitry Andric             if (RWD->getValueAsDef("SchedModel") == RWModelDef &&
10874ba319b5SDimitry Andric                 RWModelDef->getValueAsBit("FullInstRWOverlapCheck")) {
10884ba319b5SDimitry Andric               for (Record *Inst : InstDefs) {
10894ba319b5SDimitry Andric                 PrintFatalError(InstRWDef->getLoc(), "Overlapping InstRW def " +
10904ba319b5SDimitry Andric                             Inst->getName() + " also matches " +
10914ba319b5SDimitry Andric                             RWD->getValue("Instrs")->getValue()->getAsString());
10924ba319b5SDimitry Andric               }
10934ba319b5SDimitry Andric             }
10944ba319b5SDimitry Andric           }
10954ba319b5SDimitry Andric           LLVM_DEBUG(dbgs() << "InstRW: Reuse SC " << OldSCIdx << ":"
1096f785676fSDimitry Andric                             << SchedClasses[OldSCIdx].Name << " on "
10974ba319b5SDimitry Andric                             << RWModelDef->getName() << "\n");
1098f785676fSDimitry Andric           SchedClasses[OldSCIdx].InstRWs.push_back(InstRWDef);
10993861d79fSDimitry Andric           continue;
11003861d79fSDimitry Andric         }
1101f785676fSDimitry Andric       }
1102f785676fSDimitry Andric     }
11033861d79fSDimitry Andric     unsigned SCIdx = SchedClasses.size();
11044ba319b5SDimitry Andric     SchedClasses.emplace_back(SCIdx, createSchedClassName(InstDefs), nullptr);
11053861d79fSDimitry Andric     CodeGenSchedClass &SC = SchedClasses.back();
11064ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "InstRW: New SC " << SCIdx << ":" << SC.Name << " on "
11074ba319b5SDimitry Andric                       << InstRWDef->getValueAsDef("SchedModel")->getName()
11084ba319b5SDimitry Andric                       << "\n");
1109f785676fSDimitry Andric 
11103861d79fSDimitry Andric     // Preserve ItinDef and Writes/Reads for processors without an InstRW entry.
11113861d79fSDimitry Andric     SC.ItinClassDef = SchedClasses[OldSCIdx].ItinClassDef;
11123861d79fSDimitry Andric     SC.Writes = SchedClasses[OldSCIdx].Writes;
11133861d79fSDimitry Andric     SC.Reads = SchedClasses[OldSCIdx].Reads;
11143861d79fSDimitry Andric     SC.ProcIndices.push_back(0);
11154ba319b5SDimitry Andric     // If we had an old class, copy it's InstRWs to this new class.
11164ba319b5SDimitry Andric     if (OldSCIdx) {
11173861d79fSDimitry Andric       Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
11184ba319b5SDimitry Andric       for (Record *OldRWDef : SchedClasses[OldSCIdx].InstRWs) {
11194ba319b5SDimitry Andric         if (OldRWDef->getValueAsDef("SchedModel") == RWModelDef) {
11204ba319b5SDimitry Andric           for (Record *InstDef : InstDefs) {
11214ba319b5SDimitry Andric             PrintFatalError(OldRWDef->getLoc(), "Overlapping InstRW def " +
11224ba319b5SDimitry Andric                        InstDef->getName() + " also matches " +
11234ba319b5SDimitry Andric                        OldRWDef->getValue("Instrs")->getValue()->getAsString());
11243861d79fSDimitry Andric           }
11253861d79fSDimitry Andric         }
11264ba319b5SDimitry Andric         assert(OldRWDef != InstRWDef &&
11274ba319b5SDimitry Andric                "SchedClass has duplicate InstRW def");
11284ba319b5SDimitry Andric         SC.InstRWs.push_back(OldRWDef);
11293861d79fSDimitry Andric       }
11304ba319b5SDimitry Andric     }
11314ba319b5SDimitry Andric     // Map each Instr to this new class.
11324ba319b5SDimitry Andric     for (Record *InstDef : InstDefs)
11334ba319b5SDimitry Andric       InstrClassMap[InstDef] = SCIdx;
11343861d79fSDimitry Andric     SC.InstRWs.push_back(InstRWDef);
11353861d79fSDimitry Andric   }
11367ae0e2c9SDimitry Andric }
11377ae0e2c9SDimitry Andric 
1138139f7f9bSDimitry Andric // True if collectProcItins found anything.
hasItineraries() const1139139f7f9bSDimitry Andric bool CodeGenSchedModels::hasItineraries() const {
11404ba319b5SDimitry Andric   for (const CodeGenProcModel &PM : make_range(procModelBegin(),procModelEnd()))
11412cab237bSDimitry Andric     if (PM.hasItineraries())
1142139f7f9bSDimitry Andric       return true;
1143139f7f9bSDimitry Andric   return false;
1144139f7f9bSDimitry Andric }
1145139f7f9bSDimitry Andric 
11467ae0e2c9SDimitry Andric // Gather the processor itineraries.
collectProcItins()11473861d79fSDimitry Andric void CodeGenSchedModels::collectProcItins() {
11484ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n+++ PROBLEM ITINERARIES (collectProcItins) +++\n");
114939d628a0SDimitry Andric   for (CodeGenProcModel &ProcModel : ProcModels) {
1150139f7f9bSDimitry Andric     if (!ProcModel.hasItineraries())
11513861d79fSDimitry Andric       continue;
11527ae0e2c9SDimitry Andric 
1153139f7f9bSDimitry Andric     RecVec ItinRecords = ProcModel.ItinsDef->getValueAsListOfDefs("IID");
1154139f7f9bSDimitry Andric     assert(!ItinRecords.empty() && "ProcModel.hasItineraries is incorrect");
1155139f7f9bSDimitry Andric 
1156139f7f9bSDimitry Andric     // Populate ItinDefList with Itinerary records.
1157139f7f9bSDimitry Andric     ProcModel.ItinDefList.resize(NumInstrSchedClasses);
11587ae0e2c9SDimitry Andric 
11597ae0e2c9SDimitry Andric     // Insert each itinerary data record in the correct position within
11607ae0e2c9SDimitry Andric     // the processor model's ItinDefList.
11612cab237bSDimitry Andric     for (Record *ItinData : ItinRecords) {
11624ba319b5SDimitry Andric       const Record *ItinDef = ItinData->getValueAsDef("TheClass");
1163139f7f9bSDimitry Andric       bool FoundClass = false;
11644ba319b5SDimitry Andric 
11654ba319b5SDimitry Andric       for (const CodeGenSchedClass &SC :
11664ba319b5SDimitry Andric            make_range(schedClassBegin(), schedClassEnd())) {
1167139f7f9bSDimitry Andric         // Multiple SchedClasses may share an itinerary. Update all of them.
11684ba319b5SDimitry Andric         if (SC.ItinClassDef == ItinDef) {
11694ba319b5SDimitry Andric           ProcModel.ItinDefList[SC.Index] = ItinData;
1170139f7f9bSDimitry Andric           FoundClass = true;
11717ae0e2c9SDimitry Andric         }
1172139f7f9bSDimitry Andric       }
1173139f7f9bSDimitry Andric       if (!FoundClass) {
11744ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << ProcModel.ItinsDef->getName()
11754ba319b5SDimitry Andric                           << " missing class for itinerary "
11764ba319b5SDimitry Andric                           << ItinDef->getName() << '\n');
1177139f7f9bSDimitry Andric       }
11787ae0e2c9SDimitry Andric     }
11797ae0e2c9SDimitry Andric     // Check for missing itinerary entries.
11807ae0e2c9SDimitry Andric     assert(!ProcModel.ItinDefList[0] && "NoItinerary class can't have rec");
11814ba319b5SDimitry Andric     LLVM_DEBUG(
11827ae0e2c9SDimitry Andric         for (unsigned i = 1, N = ProcModel.ItinDefList.size(); i < N; ++i) {
11837ae0e2c9SDimitry Andric           if (!ProcModel.ItinDefList[i])
11843861d79fSDimitry Andric             dbgs() << ProcModel.ItinsDef->getName()
11854ba319b5SDimitry Andric                    << " missing itinerary for class " << SchedClasses[i].Name
11864ba319b5SDimitry Andric                    << '\n';
11873861d79fSDimitry Andric         });
11887ae0e2c9SDimitry Andric   }
11893861d79fSDimitry Andric }
11903861d79fSDimitry Andric 
11913861d79fSDimitry Andric // Gather the read/write types for each itinerary class.
collectProcItinRW()11923861d79fSDimitry Andric void CodeGenSchedModels::collectProcItinRW() {
11933861d79fSDimitry Andric   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
1194*b5893f02SDimitry Andric   llvm::sort(ItinRWDefs, LessRecord());
11952cab237bSDimitry Andric   for (Record *RWDef  : ItinRWDefs) {
11962cab237bSDimitry Andric     if (!RWDef->getValueInit("SchedModel")->isComplete())
11972cab237bSDimitry Andric       PrintFatalError(RWDef->getLoc(), "SchedModel is undefined");
11982cab237bSDimitry Andric     Record *ModelDef = RWDef->getValueAsDef("SchedModel");
11993861d79fSDimitry Andric     ProcModelMapTy::const_iterator I = ProcModelMap.find(ModelDef);
12003861d79fSDimitry Andric     if (I == ProcModelMap.end()) {
12012cab237bSDimitry Andric       PrintFatalError(RWDef->getLoc(), "Undefined SchedMachineModel "
12023861d79fSDimitry Andric                     + ModelDef->getName());
12033861d79fSDimitry Andric     }
12042cab237bSDimitry Andric     ProcModels[I->second].ItinRWDefs.push_back(RWDef);
12053861d79fSDimitry Andric   }
12063861d79fSDimitry Andric }
12073861d79fSDimitry Andric 
12083ca95b02SDimitry Andric // Gather the unsupported features for processor models.
collectProcUnsupportedFeatures()12093ca95b02SDimitry Andric void CodeGenSchedModels::collectProcUnsupportedFeatures() {
12103ca95b02SDimitry Andric   for (CodeGenProcModel &ProcModel : ProcModels) {
12113ca95b02SDimitry Andric     for (Record *Pred : ProcModel.ModelDef->getValueAsListOfDefs("UnsupportedFeatures")) {
12123ca95b02SDimitry Andric        ProcModel.UnsupportedFeaturesDefs.push_back(Pred);
12133ca95b02SDimitry Andric     }
12143ca95b02SDimitry Andric   }
12153ca95b02SDimitry Andric }
12163ca95b02SDimitry Andric 
12173861d79fSDimitry Andric /// Infer new classes from existing classes. In the process, this may create new
12183861d79fSDimitry Andric /// SchedWrites from sequences of existing SchedWrites.
inferSchedClasses()12193861d79fSDimitry Andric void CodeGenSchedModels::inferSchedClasses() {
12204ba319b5SDimitry Andric   LLVM_DEBUG(
12214ba319b5SDimitry Andric       dbgs() << "\n+++ INFERRING SCHED CLASSES (inferSchedClasses) +++\n");
12224ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << NumInstrSchedClasses << " instr sched classes.\n");
1223139f7f9bSDimitry Andric 
12243861d79fSDimitry Andric   // Visit all existing classes and newly created classes.
12253861d79fSDimitry Andric   for (unsigned Idx = 0; Idx != SchedClasses.size(); ++Idx) {
1226139f7f9bSDimitry Andric     assert(SchedClasses[Idx].Index == Idx && "bad SCIdx");
1227139f7f9bSDimitry Andric 
12283861d79fSDimitry Andric     if (SchedClasses[Idx].ItinClassDef)
12293861d79fSDimitry Andric       inferFromItinClass(SchedClasses[Idx].ItinClassDef, Idx);
1230139f7f9bSDimitry Andric     if (!SchedClasses[Idx].InstRWs.empty())
12313861d79fSDimitry Andric       inferFromInstRWs(Idx);
1232139f7f9bSDimitry Andric     if (!SchedClasses[Idx].Writes.empty()) {
12333861d79fSDimitry Andric       inferFromRW(SchedClasses[Idx].Writes, SchedClasses[Idx].Reads,
12343861d79fSDimitry Andric                   Idx, SchedClasses[Idx].ProcIndices);
12353861d79fSDimitry Andric     }
12363861d79fSDimitry Andric     assert(SchedClasses.size() < (NumInstrSchedClasses*6) &&
12373861d79fSDimitry Andric            "too many SchedVariants");
12383861d79fSDimitry Andric   }
12393861d79fSDimitry Andric }
12403861d79fSDimitry Andric 
12413861d79fSDimitry Andric /// Infer classes from per-processor itinerary resources.
inferFromItinClass(Record * ItinClassDef,unsigned FromClassIdx)12423861d79fSDimitry Andric void CodeGenSchedModels::inferFromItinClass(Record *ItinClassDef,
12433861d79fSDimitry Andric                                             unsigned FromClassIdx) {
12443861d79fSDimitry Andric   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
12453861d79fSDimitry Andric     const CodeGenProcModel &PM = ProcModels[PIdx];
12463861d79fSDimitry Andric     // For all ItinRW entries.
12473861d79fSDimitry Andric     bool HasMatch = false;
12484ba319b5SDimitry Andric     for (const Record *Rec : PM.ItinRWDefs) {
12494ba319b5SDimitry Andric       RecVec Matched = Rec->getValueAsListOfDefs("MatchedItinClasses");
12503861d79fSDimitry Andric       if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
12513861d79fSDimitry Andric         continue;
12523861d79fSDimitry Andric       if (HasMatch)
12534ba319b5SDimitry Andric         PrintFatalError(Rec->getLoc(), "Duplicate itinerary class "
12543861d79fSDimitry Andric                       + ItinClassDef->getName()
12553861d79fSDimitry Andric                       + " in ItinResources for " + PM.ModelName);
12563861d79fSDimitry Andric       HasMatch = true;
12573861d79fSDimitry Andric       IdxVec Writes, Reads;
12584ba319b5SDimitry Andric       findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
12594ba319b5SDimitry Andric       inferFromRW(Writes, Reads, FromClassIdx, PIdx);
12603861d79fSDimitry Andric     }
12613861d79fSDimitry Andric   }
12623861d79fSDimitry Andric }
12633861d79fSDimitry Andric 
12643861d79fSDimitry Andric /// Infer classes from per-processor InstReadWrite definitions.
inferFromInstRWs(unsigned SCIdx)12653861d79fSDimitry Andric void CodeGenSchedModels::inferFromInstRWs(unsigned SCIdx) {
1266f785676fSDimitry Andric   for (unsigned I = 0, E = SchedClasses[SCIdx].InstRWs.size(); I != E; ++I) {
1267f785676fSDimitry Andric     assert(SchedClasses[SCIdx].InstRWs.size() == E && "InstrRWs was mutated!");
1268f785676fSDimitry Andric     Record *Rec = SchedClasses[SCIdx].InstRWs[I];
1269f785676fSDimitry Andric     const RecVec *InstDefs = Sets.expand(Rec);
12703861d79fSDimitry Andric     RecIter II = InstDefs->begin(), IE = InstDefs->end();
12713861d79fSDimitry Andric     for (; II != IE; ++II) {
12723861d79fSDimitry Andric       if (InstrClassMap[*II] == SCIdx)
12733861d79fSDimitry Andric         break;
12743861d79fSDimitry Andric     }
12753861d79fSDimitry Andric     // If this class no longer has any instructions mapped to it, it has become
12763861d79fSDimitry Andric     // irrelevant.
12773861d79fSDimitry Andric     if (II == IE)
12783861d79fSDimitry Andric       continue;
12793861d79fSDimitry Andric     IdxVec Writes, Reads;
1280f785676fSDimitry Andric     findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1281f785676fSDimitry Andric     unsigned PIdx = getProcModel(Rec->getValueAsDef("SchedModel")).Index;
12824ba319b5SDimitry Andric     inferFromRW(Writes, Reads, SCIdx, PIdx); // May mutate SchedClasses.
12833861d79fSDimitry Andric   }
12843861d79fSDimitry Andric }
12853861d79fSDimitry Andric 
12863861d79fSDimitry Andric namespace {
1287d88c1a5aSDimitry Andric 
12883861d79fSDimitry Andric // Helper for substituteVariantOperand.
12893861d79fSDimitry Andric struct TransVariant {
12903861d79fSDimitry Andric   Record *VarOrSeqDef;  // Variant or sequence.
12913861d79fSDimitry Andric   unsigned RWIdx;       // Index of this variant or sequence's matched type.
12923861d79fSDimitry Andric   unsigned ProcIdx;     // Processor model index or zero for any.
12933861d79fSDimitry Andric   unsigned TransVecIdx; // Index into PredTransitions::TransVec.
12943861d79fSDimitry Andric 
TransVariant__anonab391a420911::TransVariant12953861d79fSDimitry Andric   TransVariant(Record *def, unsigned rwi, unsigned pi, unsigned ti):
12963861d79fSDimitry Andric     VarOrSeqDef(def), RWIdx(rwi), ProcIdx(pi), TransVecIdx(ti) {}
12973861d79fSDimitry Andric };
12983861d79fSDimitry Andric 
12993861d79fSDimitry Andric // Associate a predicate with the SchedReadWrite that it guards.
13003861d79fSDimitry Andric // RWIdx is the index of the read/write variant.
13013861d79fSDimitry Andric struct PredCheck {
13023861d79fSDimitry Andric   bool IsRead;
13033861d79fSDimitry Andric   unsigned RWIdx;
13043861d79fSDimitry Andric   Record *Predicate;
13053861d79fSDimitry Andric 
PredCheck__anonab391a420911::PredCheck13063861d79fSDimitry Andric   PredCheck(bool r, unsigned w, Record *p): IsRead(r), RWIdx(w), Predicate(p) {}
13073861d79fSDimitry Andric };
13083861d79fSDimitry Andric 
13093861d79fSDimitry Andric // A Predicate transition is a list of RW sequences guarded by a PredTerm.
13103861d79fSDimitry Andric struct PredTransition {
13113861d79fSDimitry Andric   // A predicate term is a conjunction of PredChecks.
13123861d79fSDimitry Andric   SmallVector<PredCheck, 4> PredTerm;
13133861d79fSDimitry Andric   SmallVector<SmallVector<unsigned,4>, 16> WriteSequences;
13143861d79fSDimitry Andric   SmallVector<SmallVector<unsigned,4>, 16> ReadSequences;
13153861d79fSDimitry Andric   SmallVector<unsigned, 4> ProcIndices;
13163861d79fSDimitry Andric };
13173861d79fSDimitry Andric 
13183861d79fSDimitry Andric // Encapsulate a set of partially constructed transitions.
13193861d79fSDimitry Andric // The results are built by repeated calls to substituteVariants.
13203861d79fSDimitry Andric class PredTransitions {
13213861d79fSDimitry Andric   CodeGenSchedModels &SchedModels;
13223861d79fSDimitry Andric 
13233861d79fSDimitry Andric public:
13243861d79fSDimitry Andric   std::vector<PredTransition> TransVec;
13253861d79fSDimitry Andric 
PredTransitions(CodeGenSchedModels & sm)13263861d79fSDimitry Andric   PredTransitions(CodeGenSchedModels &sm): SchedModels(sm) {}
13273861d79fSDimitry Andric 
13283861d79fSDimitry Andric   void substituteVariantOperand(const SmallVectorImpl<unsigned> &RWSeq,
13293861d79fSDimitry Andric                                 bool IsRead, unsigned StartIdx);
13303861d79fSDimitry Andric 
13313861d79fSDimitry Andric   void substituteVariants(const PredTransition &Trans);
13323861d79fSDimitry Andric 
13333861d79fSDimitry Andric #ifndef NDEBUG
13343861d79fSDimitry Andric   void dump() const;
13357ae0e2c9SDimitry Andric #endif
13363861d79fSDimitry Andric 
13373861d79fSDimitry Andric private:
13383861d79fSDimitry Andric   bool mutuallyExclusive(Record *PredDef, ArrayRef<PredCheck> Term);
13393861d79fSDimitry Andric   void getIntersectingVariants(
13403861d79fSDimitry Andric     const CodeGenSchedRW &SchedRW, unsigned TransIdx,
13413861d79fSDimitry Andric     std::vector<TransVariant> &IntersectingVariants);
13423861d79fSDimitry Andric   void pushVariant(const TransVariant &VInfo, bool IsRead);
13433861d79fSDimitry Andric };
1344d88c1a5aSDimitry Andric 
1345d88c1a5aSDimitry Andric } // end anonymous namespace
13463861d79fSDimitry Andric 
13473861d79fSDimitry Andric // Return true if this predicate is mutually exclusive with a PredTerm. This
13483861d79fSDimitry Andric // degenerates into checking if the predicate is mutually exclusive with any
13493861d79fSDimitry Andric // predicate in the Term's conjunction.
13503861d79fSDimitry Andric //
13513861d79fSDimitry Andric // All predicates associated with a given SchedRW are considered mutually
13523861d79fSDimitry Andric // exclusive. This should work even if the conditions expressed by the
13533861d79fSDimitry Andric // predicates are not exclusive because the predicates for a given SchedWrite
13543861d79fSDimitry Andric // are always checked in the order they are defined in the .td file. Later
13553861d79fSDimitry Andric // conditions implicitly negate any prior condition.
mutuallyExclusive(Record * PredDef,ArrayRef<PredCheck> Term)13563861d79fSDimitry Andric bool PredTransitions::mutuallyExclusive(Record *PredDef,
13573861d79fSDimitry Andric                                         ArrayRef<PredCheck> Term) {
13582cab237bSDimitry Andric   for (const PredCheck &PC: Term) {
13592cab237bSDimitry Andric     if (PC.Predicate == PredDef)
13603861d79fSDimitry Andric       return false;
13613861d79fSDimitry Andric 
13622cab237bSDimitry Andric     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(PC.RWIdx, PC.IsRead);
13633861d79fSDimitry Andric     assert(SchedRW.HasVariants && "PredCheck must refer to a SchedVariant");
13643861d79fSDimitry Andric     RecVec Variants = SchedRW.TheDef->getValueAsListOfDefs("Variants");
13654ba319b5SDimitry Andric     if (any_of(Variants, [PredDef](const Record *R) {
13664ba319b5SDimitry Andric           return R->getValueAsDef("Predicate") == PredDef;
13674ba319b5SDimitry Andric         }))
13683861d79fSDimitry Andric       return true;
13697ae0e2c9SDimitry Andric   }
13703861d79fSDimitry Andric   return false;
13713861d79fSDimitry Andric }
13723861d79fSDimitry Andric 
hasAliasedVariants(const CodeGenSchedRW & RW,CodeGenSchedModels & SchedModels)13733861d79fSDimitry Andric static bool hasAliasedVariants(const CodeGenSchedRW &RW,
13743861d79fSDimitry Andric                                CodeGenSchedModels &SchedModels) {
13753861d79fSDimitry Andric   if (RW.HasVariants)
13763861d79fSDimitry Andric     return true;
13773861d79fSDimitry Andric 
13782cab237bSDimitry Andric   for (Record *Alias : RW.Aliases) {
13793861d79fSDimitry Andric     const CodeGenSchedRW &AliasRW =
13802cab237bSDimitry Andric       SchedModels.getSchedRW(Alias->getValueAsDef("AliasRW"));
13813861d79fSDimitry Andric     if (AliasRW.HasVariants)
13823861d79fSDimitry Andric       return true;
13833861d79fSDimitry Andric     if (AliasRW.IsSequence) {
13843861d79fSDimitry Andric       IdxVec ExpandedRWs;
13853861d79fSDimitry Andric       SchedModels.expandRWSequence(AliasRW.Index, ExpandedRWs, AliasRW.IsRead);
13864ba319b5SDimitry Andric       for (unsigned SI : ExpandedRWs) {
13874ba319b5SDimitry Andric         if (hasAliasedVariants(SchedModels.getSchedRW(SI, AliasRW.IsRead),
13884ba319b5SDimitry Andric                                SchedModels))
13893861d79fSDimitry Andric           return true;
13903861d79fSDimitry Andric       }
13913861d79fSDimitry Andric     }
13923861d79fSDimitry Andric   }
13933861d79fSDimitry Andric   return false;
13943861d79fSDimitry Andric }
13953861d79fSDimitry Andric 
hasVariant(ArrayRef<PredTransition> Transitions,CodeGenSchedModels & SchedModels)13963861d79fSDimitry Andric static bool hasVariant(ArrayRef<PredTransition> Transitions,
13973861d79fSDimitry Andric                        CodeGenSchedModels &SchedModels) {
13984ba319b5SDimitry Andric   for (const PredTransition &PTI : Transitions) {
13994ba319b5SDimitry Andric     for (const SmallVectorImpl<unsigned> &WSI : PTI.WriteSequences)
14004ba319b5SDimitry Andric       for (unsigned WI : WSI)
14014ba319b5SDimitry Andric         if (hasAliasedVariants(SchedModels.getSchedWrite(WI), SchedModels))
14023861d79fSDimitry Andric           return true;
14034ba319b5SDimitry Andric 
14044ba319b5SDimitry Andric     for (const SmallVectorImpl<unsigned> &RSI : PTI.ReadSequences)
14054ba319b5SDimitry Andric       for (unsigned RI : RSI)
14064ba319b5SDimitry Andric         if (hasAliasedVariants(SchedModels.getSchedRead(RI), SchedModels))
14073861d79fSDimitry Andric           return true;
14083861d79fSDimitry Andric   }
14093861d79fSDimitry Andric   return false;
14103861d79fSDimitry Andric }
14113861d79fSDimitry Andric 
14123861d79fSDimitry Andric // Populate IntersectingVariants with any variants or aliased sequences of the
14133861d79fSDimitry Andric // given SchedRW whose processor indices and predicates are not mutually
1414139f7f9bSDimitry Andric // exclusive with the given transition.
getIntersectingVariants(const CodeGenSchedRW & SchedRW,unsigned TransIdx,std::vector<TransVariant> & IntersectingVariants)14153861d79fSDimitry Andric void PredTransitions::getIntersectingVariants(
14163861d79fSDimitry Andric   const CodeGenSchedRW &SchedRW, unsigned TransIdx,
14173861d79fSDimitry Andric   std::vector<TransVariant> &IntersectingVariants) {
14183861d79fSDimitry Andric 
1419139f7f9bSDimitry Andric   bool GenericRW = false;
1420139f7f9bSDimitry Andric 
14213861d79fSDimitry Andric   std::vector<TransVariant> Variants;
14223861d79fSDimitry Andric   if (SchedRW.HasVariants) {
14233861d79fSDimitry Andric     unsigned VarProcIdx = 0;
14243861d79fSDimitry Andric     if (SchedRW.TheDef->getValueInit("SchedModel")->isComplete()) {
14253861d79fSDimitry Andric       Record *ModelDef = SchedRW.TheDef->getValueAsDef("SchedModel");
14263861d79fSDimitry Andric       VarProcIdx = SchedModels.getProcModel(ModelDef).Index;
14273861d79fSDimitry Andric     }
14283861d79fSDimitry Andric     // Push each variant. Assign TransVecIdx later.
14293861d79fSDimitry Andric     const RecVec VarDefs = SchedRW.TheDef->getValueAsListOfDefs("Variants");
14302cab237bSDimitry Andric     for (Record *VarDef : VarDefs)
14314ba319b5SDimitry Andric       Variants.emplace_back(VarDef, SchedRW.Index, VarProcIdx, 0);
1432139f7f9bSDimitry Andric     if (VarProcIdx == 0)
1433139f7f9bSDimitry Andric       GenericRW = true;
14343861d79fSDimitry Andric   }
14353861d79fSDimitry Andric   for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
14363861d79fSDimitry Andric        AI != AE; ++AI) {
14373861d79fSDimitry Andric     // If either the SchedAlias itself or the SchedReadWrite that it aliases
14383861d79fSDimitry Andric     // to is defined within a processor model, constrain all variants to
14393861d79fSDimitry Andric     // that processor.
14403861d79fSDimitry Andric     unsigned AliasProcIdx = 0;
14413861d79fSDimitry Andric     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
14423861d79fSDimitry Andric       Record *ModelDef = (*AI)->getValueAsDef("SchedModel");
14433861d79fSDimitry Andric       AliasProcIdx = SchedModels.getProcModel(ModelDef).Index;
14443861d79fSDimitry Andric     }
14453861d79fSDimitry Andric     const CodeGenSchedRW &AliasRW =
14463861d79fSDimitry Andric       SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
14473861d79fSDimitry Andric 
14483861d79fSDimitry Andric     if (AliasRW.HasVariants) {
14493861d79fSDimitry Andric       const RecVec VarDefs = AliasRW.TheDef->getValueAsListOfDefs("Variants");
14502cab237bSDimitry Andric       for (Record *VD : VarDefs)
14514ba319b5SDimitry Andric         Variants.emplace_back(VD, AliasRW.Index, AliasProcIdx, 0);
14523861d79fSDimitry Andric     }
14534ba319b5SDimitry Andric     if (AliasRW.IsSequence)
14544ba319b5SDimitry Andric       Variants.emplace_back(AliasRW.TheDef, SchedRW.Index, AliasProcIdx, 0);
1455139f7f9bSDimitry Andric     if (AliasProcIdx == 0)
1456139f7f9bSDimitry Andric       GenericRW = true;
14573861d79fSDimitry Andric   }
14582cab237bSDimitry Andric   for (TransVariant &Variant : Variants) {
14593861d79fSDimitry Andric     // Don't expand variants if the processor models don't intersect.
14603861d79fSDimitry Andric     // A zero processor index means any processor.
1461f785676fSDimitry Andric     SmallVectorImpl<unsigned> &ProcIndices = TransVec[TransIdx].ProcIndices;
14622cab237bSDimitry Andric     if (ProcIndices[0] && Variant.ProcIdx) {
14633861d79fSDimitry Andric       unsigned Cnt = std::count(ProcIndices.begin(), ProcIndices.end(),
14643861d79fSDimitry Andric                                 Variant.ProcIdx);
14653861d79fSDimitry Andric       if (!Cnt)
14663861d79fSDimitry Andric         continue;
14673861d79fSDimitry Andric       if (Cnt > 1) {
14683861d79fSDimitry Andric         const CodeGenProcModel &PM =
14693861d79fSDimitry Andric           *(SchedModels.procModelBegin() + Variant.ProcIdx);
14703861d79fSDimitry Andric         PrintFatalError(Variant.VarOrSeqDef->getLoc(),
14713861d79fSDimitry Andric                         "Multiple variants defined for processor " +
14723861d79fSDimitry Andric                         PM.ModelName +
14733861d79fSDimitry Andric                         " Ensure only one SchedAlias exists per RW.");
14743861d79fSDimitry Andric       }
14753861d79fSDimitry Andric     }
14763861d79fSDimitry Andric     if (Variant.VarOrSeqDef->isSubClassOf("SchedVar")) {
14773861d79fSDimitry Andric       Record *PredDef = Variant.VarOrSeqDef->getValueAsDef("Predicate");
14783861d79fSDimitry Andric       if (mutuallyExclusive(PredDef, TransVec[TransIdx].PredTerm))
14793861d79fSDimitry Andric         continue;
14803861d79fSDimitry Andric     }
14813861d79fSDimitry Andric     if (IntersectingVariants.empty()) {
14823861d79fSDimitry Andric       // The first variant builds on the existing transition.
14833861d79fSDimitry Andric       Variant.TransVecIdx = TransIdx;
14843861d79fSDimitry Andric       IntersectingVariants.push_back(Variant);
14853861d79fSDimitry Andric     }
14863861d79fSDimitry Andric     else {
14873861d79fSDimitry Andric       // Push another copy of the current transition for more variants.
14883861d79fSDimitry Andric       Variant.TransVecIdx = TransVec.size();
14893861d79fSDimitry Andric       IntersectingVariants.push_back(Variant);
14903861d79fSDimitry Andric       TransVec.push_back(TransVec[TransIdx]);
14913861d79fSDimitry Andric     }
14923861d79fSDimitry Andric   }
1493139f7f9bSDimitry Andric   if (GenericRW && IntersectingVariants.empty()) {
1494139f7f9bSDimitry Andric     PrintFatalError(SchedRW.TheDef->getLoc(), "No variant of this type has "
1495139f7f9bSDimitry Andric                     "a matching predicate on any processor");
1496139f7f9bSDimitry Andric   }
14973861d79fSDimitry Andric }
14983861d79fSDimitry Andric 
14993861d79fSDimitry Andric // Push the Reads/Writes selected by this variant onto the PredTransition
15003861d79fSDimitry Andric // specified by VInfo.
15013861d79fSDimitry Andric void PredTransitions::
pushVariant(const TransVariant & VInfo,bool IsRead)15023861d79fSDimitry Andric pushVariant(const TransVariant &VInfo, bool IsRead) {
15033861d79fSDimitry Andric   PredTransition &Trans = TransVec[VInfo.TransVecIdx];
15043861d79fSDimitry Andric 
15053861d79fSDimitry Andric   // If this operand transition is reached through a processor-specific alias,
15063861d79fSDimitry Andric   // then the whole transition is specific to this processor.
15073861d79fSDimitry Andric   if (VInfo.ProcIdx != 0)
15083861d79fSDimitry Andric     Trans.ProcIndices.assign(1, VInfo.ProcIdx);
15093861d79fSDimitry Andric 
15103861d79fSDimitry Andric   IdxVec SelectedRWs;
15113861d79fSDimitry Andric   if (VInfo.VarOrSeqDef->isSubClassOf("SchedVar")) {
15123861d79fSDimitry Andric     Record *PredDef = VInfo.VarOrSeqDef->getValueAsDef("Predicate");
15134ba319b5SDimitry Andric     Trans.PredTerm.emplace_back(IsRead, VInfo.RWIdx,PredDef);
15143861d79fSDimitry Andric     RecVec SelectedDefs = VInfo.VarOrSeqDef->getValueAsListOfDefs("Selected");
15153861d79fSDimitry Andric     SchedModels.findRWs(SelectedDefs, SelectedRWs, IsRead);
15163861d79fSDimitry Andric   }
15173861d79fSDimitry Andric   else {
15183861d79fSDimitry Andric     assert(VInfo.VarOrSeqDef->isSubClassOf("WriteSequence") &&
15193861d79fSDimitry Andric            "variant must be a SchedVariant or aliased WriteSequence");
15203861d79fSDimitry Andric     SelectedRWs.push_back(SchedModels.getSchedRWIdx(VInfo.VarOrSeqDef, IsRead));
15213861d79fSDimitry Andric   }
15223861d79fSDimitry Andric 
15233861d79fSDimitry Andric   const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(VInfo.RWIdx, IsRead);
15243861d79fSDimitry Andric 
15253861d79fSDimitry Andric   SmallVectorImpl<SmallVector<unsigned,4>> &RWSequences = IsRead
15263861d79fSDimitry Andric     ? Trans.ReadSequences : Trans.WriteSequences;
15273861d79fSDimitry Andric   if (SchedRW.IsVariadic) {
15283861d79fSDimitry Andric     unsigned OperIdx = RWSequences.size()-1;
15293861d79fSDimitry Andric     // Make N-1 copies of this transition's last sequence.
15304ba319b5SDimitry Andric     RWSequences.insert(RWSequences.end(), SelectedRWs.size() - 1,
15314ba319b5SDimitry Andric                        RWSequences[OperIdx]);
15323861d79fSDimitry Andric     // Push each of the N elements of the SelectedRWs onto a copy of the last
15333861d79fSDimitry Andric     // sequence (split the current operand into N operands).
15343861d79fSDimitry Andric     // Note that write sequences should be expanded within this loop--the entire
15353861d79fSDimitry Andric     // sequence belongs to a single operand.
15363861d79fSDimitry Andric     for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
15373861d79fSDimitry Andric          RWI != RWE; ++RWI, ++OperIdx) {
15383861d79fSDimitry Andric       IdxVec ExpandedRWs;
15393861d79fSDimitry Andric       if (IsRead)
15403861d79fSDimitry Andric         ExpandedRWs.push_back(*RWI);
15413861d79fSDimitry Andric       else
15423861d79fSDimitry Andric         SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
15433861d79fSDimitry Andric       RWSequences[OperIdx].insert(RWSequences[OperIdx].end(),
15443861d79fSDimitry Andric                                   ExpandedRWs.begin(), ExpandedRWs.end());
15453861d79fSDimitry Andric     }
15463861d79fSDimitry Andric     assert(OperIdx == RWSequences.size() && "missed a sequence");
15473861d79fSDimitry Andric   }
15483861d79fSDimitry Andric   else {
15493861d79fSDimitry Andric     // Push this transition's expanded sequence onto this transition's last
15503861d79fSDimitry Andric     // sequence (add to the current operand's sequence).
15513861d79fSDimitry Andric     SmallVectorImpl<unsigned> &Seq = RWSequences.back();
15523861d79fSDimitry Andric     IdxVec ExpandedRWs;
15533861d79fSDimitry Andric     for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
15543861d79fSDimitry Andric          RWI != RWE; ++RWI) {
15553861d79fSDimitry Andric       if (IsRead)
15563861d79fSDimitry Andric         ExpandedRWs.push_back(*RWI);
15573861d79fSDimitry Andric       else
15583861d79fSDimitry Andric         SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
15593861d79fSDimitry Andric     }
15603861d79fSDimitry Andric     Seq.insert(Seq.end(), ExpandedRWs.begin(), ExpandedRWs.end());
15613861d79fSDimitry Andric   }
15623861d79fSDimitry Andric }
15633861d79fSDimitry Andric 
15643861d79fSDimitry Andric // RWSeq is a sequence of all Reads or all Writes for the next read or write
15653861d79fSDimitry Andric // operand. StartIdx is an index into TransVec where partial results
15663861d79fSDimitry Andric // starts. RWSeq must be applied to all transitions between StartIdx and the end
15673861d79fSDimitry Andric // of TransVec.
substituteVariantOperand(const SmallVectorImpl<unsigned> & RWSeq,bool IsRead,unsigned StartIdx)15683861d79fSDimitry Andric void PredTransitions::substituteVariantOperand(
15693861d79fSDimitry Andric   const SmallVectorImpl<unsigned> &RWSeq, bool IsRead, unsigned StartIdx) {
15703861d79fSDimitry Andric 
15713861d79fSDimitry Andric   // Visit each original RW within the current sequence.
15723861d79fSDimitry Andric   for (SmallVectorImpl<unsigned>::const_iterator
15733861d79fSDimitry Andric          RWI = RWSeq.begin(), RWE = RWSeq.end(); RWI != RWE; ++RWI) {
15743861d79fSDimitry Andric     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(*RWI, IsRead);
15753861d79fSDimitry Andric     // Push this RW on all partial PredTransitions or distribute variants.
15763861d79fSDimitry Andric     // New PredTransitions may be pushed within this loop which should not be
15773861d79fSDimitry Andric     // revisited (TransEnd must be loop invariant).
15783861d79fSDimitry Andric     for (unsigned TransIdx = StartIdx, TransEnd = TransVec.size();
15793861d79fSDimitry Andric          TransIdx != TransEnd; ++TransIdx) {
15803861d79fSDimitry Andric       // In the common case, push RW onto the current operand's sequence.
15813861d79fSDimitry Andric       if (!hasAliasedVariants(SchedRW, SchedModels)) {
15823861d79fSDimitry Andric         if (IsRead)
15833861d79fSDimitry Andric           TransVec[TransIdx].ReadSequences.back().push_back(*RWI);
15843861d79fSDimitry Andric         else
15853861d79fSDimitry Andric           TransVec[TransIdx].WriteSequences.back().push_back(*RWI);
15863861d79fSDimitry Andric         continue;
15873861d79fSDimitry Andric       }
15883861d79fSDimitry Andric       // Distribute this partial PredTransition across intersecting variants.
15893861d79fSDimitry Andric       // This will push a copies of TransVec[TransIdx] on the back of TransVec.
15903861d79fSDimitry Andric       std::vector<TransVariant> IntersectingVariants;
15913861d79fSDimitry Andric       getIntersectingVariants(SchedRW, TransIdx, IntersectingVariants);
15923861d79fSDimitry Andric       // Now expand each variant on top of its copy of the transition.
15933861d79fSDimitry Andric       for (std::vector<TransVariant>::const_iterator
15943861d79fSDimitry Andric              IVI = IntersectingVariants.begin(),
15953861d79fSDimitry Andric              IVE = IntersectingVariants.end();
15963861d79fSDimitry Andric            IVI != IVE; ++IVI) {
15973861d79fSDimitry Andric         pushVariant(*IVI, IsRead);
15983861d79fSDimitry Andric       }
15993861d79fSDimitry Andric     }
16003861d79fSDimitry Andric   }
16013861d79fSDimitry Andric }
16023861d79fSDimitry Andric 
16033861d79fSDimitry Andric // For each variant of a Read/Write in Trans, substitute the sequence of
16043861d79fSDimitry Andric // Read/Writes guarded by the variant. This is exponential in the number of
16053861d79fSDimitry Andric // variant Read/Writes, but in practice detection of mutually exclusive
16063861d79fSDimitry Andric // predicates should result in linear growth in the total number variants.
16073861d79fSDimitry Andric //
16083861d79fSDimitry Andric // This is one step in a breadth-first search of nested variants.
substituteVariants(const PredTransition & Trans)16093861d79fSDimitry Andric void PredTransitions::substituteVariants(const PredTransition &Trans) {
16103861d79fSDimitry Andric   // Build up a set of partial results starting at the back of
16113861d79fSDimitry Andric   // PredTransitions. Remember the first new transition.
16123861d79fSDimitry Andric   unsigned StartIdx = TransVec.size();
16134ba319b5SDimitry Andric   TransVec.emplace_back();
16143861d79fSDimitry Andric   TransVec.back().PredTerm = Trans.PredTerm;
16153861d79fSDimitry Andric   TransVec.back().ProcIndices = Trans.ProcIndices;
16163861d79fSDimitry Andric 
16173861d79fSDimitry Andric   // Visit each original write sequence.
16183861d79fSDimitry Andric   for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
16193861d79fSDimitry Andric          WSI = Trans.WriteSequences.begin(), WSE = Trans.WriteSequences.end();
16203861d79fSDimitry Andric        WSI != WSE; ++WSI) {
16213861d79fSDimitry Andric     // Push a new (empty) write sequence onto all partial Transitions.
16223861d79fSDimitry Andric     for (std::vector<PredTransition>::iterator I =
16233861d79fSDimitry Andric            TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
16244ba319b5SDimitry Andric       I->WriteSequences.emplace_back();
16253861d79fSDimitry Andric     }
16263861d79fSDimitry Andric     substituteVariantOperand(*WSI, /*IsRead=*/false, StartIdx);
16273861d79fSDimitry Andric   }
16283861d79fSDimitry Andric   // Visit each original read sequence.
16293861d79fSDimitry Andric   for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
16303861d79fSDimitry Andric          RSI = Trans.ReadSequences.begin(), RSE = Trans.ReadSequences.end();
16313861d79fSDimitry Andric        RSI != RSE; ++RSI) {
16323861d79fSDimitry Andric     // Push a new (empty) read sequence onto all partial Transitions.
16333861d79fSDimitry Andric     for (std::vector<PredTransition>::iterator I =
16343861d79fSDimitry Andric            TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
16354ba319b5SDimitry Andric       I->ReadSequences.emplace_back();
16363861d79fSDimitry Andric     }
16373861d79fSDimitry Andric     substituteVariantOperand(*RSI, /*IsRead=*/true, StartIdx);
16383861d79fSDimitry Andric   }
16393861d79fSDimitry Andric }
16403861d79fSDimitry Andric 
16413861d79fSDimitry Andric // Create a new SchedClass for each variant found by inferFromRW. Pass
inferFromTransitions(ArrayRef<PredTransition> LastTransitions,unsigned FromClassIdx,CodeGenSchedModels & SchedModels)16423861d79fSDimitry Andric static void inferFromTransitions(ArrayRef<PredTransition> LastTransitions,
16433861d79fSDimitry Andric                                  unsigned FromClassIdx,
16443861d79fSDimitry Andric                                  CodeGenSchedModels &SchedModels) {
16453861d79fSDimitry Andric   // For each PredTransition, create a new CodeGenSchedTransition, which usually
16463861d79fSDimitry Andric   // requires creating a new SchedClass.
16473861d79fSDimitry Andric   for (ArrayRef<PredTransition>::iterator
16483861d79fSDimitry Andric          I = LastTransitions.begin(), E = LastTransitions.end(); I != E; ++I) {
16493861d79fSDimitry Andric     IdxVec OperWritesVariant;
16504ba319b5SDimitry Andric     transform(I->WriteSequences, std::back_inserter(OperWritesVariant),
16514ba319b5SDimitry Andric               [&SchedModels](ArrayRef<unsigned> WS) {
16524ba319b5SDimitry Andric                 return SchedModels.findOrInsertRW(WS, /*IsRead=*/false);
16534ba319b5SDimitry Andric               });
16543861d79fSDimitry Andric     IdxVec OperReadsVariant;
16554ba319b5SDimitry Andric     transform(I->ReadSequences, std::back_inserter(OperReadsVariant),
16564ba319b5SDimitry Andric               [&SchedModels](ArrayRef<unsigned> RS) {
16574ba319b5SDimitry Andric                 return SchedModels.findOrInsertRW(RS, /*IsRead=*/true);
16584ba319b5SDimitry Andric               });
16593861d79fSDimitry Andric     CodeGenSchedTransition SCTrans;
16603861d79fSDimitry Andric     SCTrans.ToClassIdx =
166191bc56edSDimitry Andric       SchedModels.addSchedClass(/*ItinClassDef=*/nullptr, OperWritesVariant,
16624ba319b5SDimitry Andric                                 OperReadsVariant, I->ProcIndices);
16634ba319b5SDimitry Andric     SCTrans.ProcIndices.assign(I->ProcIndices.begin(), I->ProcIndices.end());
16643861d79fSDimitry Andric     // The final PredTerm is unique set of predicates guarding the transition.
16653861d79fSDimitry Andric     RecVec Preds;
16664ba319b5SDimitry Andric     transform(I->PredTerm, std::back_inserter(Preds),
16674ba319b5SDimitry Andric               [](const PredCheck &P) {
16684ba319b5SDimitry Andric                 return P.Predicate;
16694ba319b5SDimitry Andric               });
16704ba319b5SDimitry Andric     Preds.erase(std::unique(Preds.begin(), Preds.end()), Preds.end());
16714ba319b5SDimitry Andric     SCTrans.PredTerm = std::move(Preds);
16724ba319b5SDimitry Andric     SchedModels.getSchedClass(FromClassIdx)
16734ba319b5SDimitry Andric         .Transitions.push_back(std::move(SCTrans));
16743861d79fSDimitry Andric   }
16753861d79fSDimitry Andric }
16763861d79fSDimitry Andric 
16773861d79fSDimitry Andric // Create new SchedClasses for the given ReadWrite list. If any of the
16783861d79fSDimitry Andric // ReadWrites refers to a SchedVariant, create a new SchedClass for each variant
16793861d79fSDimitry Andric // of the ReadWrite list, following Aliases if necessary.
inferFromRW(ArrayRef<unsigned> OperWrites,ArrayRef<unsigned> OperReads,unsigned FromClassIdx,ArrayRef<unsigned> ProcIndices)16807d523365SDimitry Andric void CodeGenSchedModels::inferFromRW(ArrayRef<unsigned> OperWrites,
16817d523365SDimitry Andric                                      ArrayRef<unsigned> OperReads,
16823861d79fSDimitry Andric                                      unsigned FromClassIdx,
16837d523365SDimitry Andric                                      ArrayRef<unsigned> ProcIndices) {
16844ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "INFER RW proc("; dumpIdxVec(ProcIndices);
16854ba319b5SDimitry Andric              dbgs() << ") ");
16863861d79fSDimitry Andric 
16873861d79fSDimitry Andric   // Create a seed transition with an empty PredTerm and the expanded sequences
16883861d79fSDimitry Andric   // of SchedWrites for the current SchedClass.
16893861d79fSDimitry Andric   std::vector<PredTransition> LastTransitions;
16904ba319b5SDimitry Andric   LastTransitions.emplace_back();
16913861d79fSDimitry Andric   LastTransitions.back().ProcIndices.append(ProcIndices.begin(),
16923861d79fSDimitry Andric                                             ProcIndices.end());
16933861d79fSDimitry Andric 
16947d523365SDimitry Andric   for (unsigned WriteIdx : OperWrites) {
16953861d79fSDimitry Andric     IdxVec WriteSeq;
16967d523365SDimitry Andric     expandRWSequence(WriteIdx, WriteSeq, /*IsRead=*/false);
16974ba319b5SDimitry Andric     LastTransitions[0].WriteSequences.emplace_back();
16984ba319b5SDimitry Andric     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].WriteSequences.back();
16994ba319b5SDimitry Andric     Seq.append(WriteSeq.begin(), WriteSeq.end());
17004ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
17013861d79fSDimitry Andric   }
17024ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << " Reads: ");
17037d523365SDimitry Andric   for (unsigned ReadIdx : OperReads) {
17043861d79fSDimitry Andric     IdxVec ReadSeq;
17057d523365SDimitry Andric     expandRWSequence(ReadIdx, ReadSeq, /*IsRead=*/true);
17064ba319b5SDimitry Andric     LastTransitions[0].ReadSequences.emplace_back();
17074ba319b5SDimitry Andric     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].ReadSequences.back();
17084ba319b5SDimitry Andric     Seq.append(ReadSeq.begin(), ReadSeq.end());
17094ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
17103861d79fSDimitry Andric   }
17114ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << '\n');
17123861d79fSDimitry Andric 
17133861d79fSDimitry Andric   // Collect all PredTransitions for individual operands.
17143861d79fSDimitry Andric   // Iterate until no variant writes remain.
17153861d79fSDimitry Andric   while (hasVariant(LastTransitions, *this)) {
17163861d79fSDimitry Andric     PredTransitions Transitions(*this);
17174ba319b5SDimitry Andric     for (const PredTransition &Trans : LastTransitions)
17184ba319b5SDimitry Andric       Transitions.substituteVariants(Trans);
17194ba319b5SDimitry Andric     LLVM_DEBUG(Transitions.dump());
17203861d79fSDimitry Andric     LastTransitions.swap(Transitions.TransVec);
17213861d79fSDimitry Andric   }
17223861d79fSDimitry Andric   // If the first transition has no variants, nothing to do.
17233861d79fSDimitry Andric   if (LastTransitions[0].PredTerm.empty())
17243861d79fSDimitry Andric     return;
17253861d79fSDimitry Andric 
17263861d79fSDimitry Andric   // WARNING: We are about to mutate the SchedClasses vector. Do not refer to
17273861d79fSDimitry Andric   // OperWrites, OperReads, or ProcIndices after calling inferFromTransitions.
17283861d79fSDimitry Andric   inferFromTransitions(LastTransitions, FromClassIdx, *this);
17293861d79fSDimitry Andric }
17303861d79fSDimitry Andric 
1731284c1978SDimitry Andric // Check if any processor resource group contains all resource records in
1732284c1978SDimitry Andric // SubUnits.
hasSuperGroup(RecVec & SubUnits,CodeGenProcModel & PM)1733284c1978SDimitry Andric bool CodeGenSchedModels::hasSuperGroup(RecVec &SubUnits, CodeGenProcModel &PM) {
1734284c1978SDimitry Andric   for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
1735284c1978SDimitry Andric     if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
1736284c1978SDimitry Andric       continue;
1737284c1978SDimitry Andric     RecVec SuperUnits =
1738284c1978SDimitry Andric       PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
1739284c1978SDimitry Andric     RecIter RI = SubUnits.begin(), RE = SubUnits.end();
1740284c1978SDimitry Andric     for ( ; RI != RE; ++RI) {
1741d88c1a5aSDimitry Andric       if (!is_contained(SuperUnits, *RI)) {
1742284c1978SDimitry Andric         break;
1743284c1978SDimitry Andric       }
1744284c1978SDimitry Andric     }
1745284c1978SDimitry Andric     if (RI == RE)
1746284c1978SDimitry Andric       return true;
1747284c1978SDimitry Andric   }
1748284c1978SDimitry Andric   return false;
1749284c1978SDimitry Andric }
1750284c1978SDimitry Andric 
1751284c1978SDimitry Andric // Verify that overlapping groups have a common supergroup.
verifyProcResourceGroups(CodeGenProcModel & PM)1752284c1978SDimitry Andric void CodeGenSchedModels::verifyProcResourceGroups(CodeGenProcModel &PM) {
1753284c1978SDimitry Andric   for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
1754284c1978SDimitry Andric     if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
1755284c1978SDimitry Andric       continue;
1756284c1978SDimitry Andric     RecVec CheckUnits =
1757284c1978SDimitry Andric       PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
1758284c1978SDimitry Andric     for (unsigned j = i+1; j < e; ++j) {
1759284c1978SDimitry Andric       if (!PM.ProcResourceDefs[j]->isSubClassOf("ProcResGroup"))
1760284c1978SDimitry Andric         continue;
1761284c1978SDimitry Andric       RecVec OtherUnits =
1762284c1978SDimitry Andric         PM.ProcResourceDefs[j]->getValueAsListOfDefs("Resources");
1763284c1978SDimitry Andric       if (std::find_first_of(CheckUnits.begin(), CheckUnits.end(),
1764284c1978SDimitry Andric                              OtherUnits.begin(), OtherUnits.end())
1765284c1978SDimitry Andric           != CheckUnits.end()) {
1766284c1978SDimitry Andric         // CheckUnits and OtherUnits overlap
1767284c1978SDimitry Andric         OtherUnits.insert(OtherUnits.end(), CheckUnits.begin(),
1768284c1978SDimitry Andric                           CheckUnits.end());
1769284c1978SDimitry Andric         if (!hasSuperGroup(OtherUnits, PM)) {
1770284c1978SDimitry Andric           PrintFatalError((PM.ProcResourceDefs[i])->getLoc(),
1771284c1978SDimitry Andric                           "proc resource group overlaps with "
1772284c1978SDimitry Andric                           + PM.ProcResourceDefs[j]->getName()
1773284c1978SDimitry Andric                           + " but no supergroup contains both.");
1774284c1978SDimitry Andric         }
1775284c1978SDimitry Andric       }
1776284c1978SDimitry Andric     }
1777284c1978SDimitry Andric   }
1778284c1978SDimitry Andric }
1779284c1978SDimitry Andric 
17804ba319b5SDimitry Andric // Collect all the RegisterFile definitions available in this target.
collectRegisterFiles()17814ba319b5SDimitry Andric void CodeGenSchedModels::collectRegisterFiles() {
17824ba319b5SDimitry Andric   RecVec RegisterFileDefs = Records.getAllDerivedDefinitions("RegisterFile");
17834ba319b5SDimitry Andric 
17844ba319b5SDimitry Andric   // RegisterFiles is the vector of CodeGenRegisterFile.
17854ba319b5SDimitry Andric   for (Record *RF : RegisterFileDefs) {
17864ba319b5SDimitry Andric     // For each register file definition, construct a CodeGenRegisterFile object
17874ba319b5SDimitry Andric     // and add it to the appropriate scheduling model.
17884ba319b5SDimitry Andric     CodeGenProcModel &PM = getProcModel(RF->getValueAsDef("SchedModel"));
17894ba319b5SDimitry Andric     PM.RegisterFiles.emplace_back(CodeGenRegisterFile(RF->getName(),RF));
17904ba319b5SDimitry Andric     CodeGenRegisterFile &CGRF = PM.RegisterFiles.back();
1791*b5893f02SDimitry Andric     CGRF.MaxMovesEliminatedPerCycle =
1792*b5893f02SDimitry Andric         RF->getValueAsInt("MaxMovesEliminatedPerCycle");
1793*b5893f02SDimitry Andric     CGRF.AllowZeroMoveEliminationOnly =
1794*b5893f02SDimitry Andric         RF->getValueAsBit("AllowZeroMoveEliminationOnly");
17954ba319b5SDimitry Andric 
17964ba319b5SDimitry Andric     // Now set the number of physical registers as well as the cost of registers
17974ba319b5SDimitry Andric     // in each register class.
17984ba319b5SDimitry Andric     CGRF.NumPhysRegs = RF->getValueAsInt("NumPhysRegs");
1799*b5893f02SDimitry Andric     if (!CGRF.NumPhysRegs) {
1800*b5893f02SDimitry Andric       PrintFatalError(RF->getLoc(),
1801*b5893f02SDimitry Andric                       "Invalid RegisterFile with zero physical registers");
18024ba319b5SDimitry Andric     }
18034ba319b5SDimitry Andric 
1804*b5893f02SDimitry Andric     RecVec RegisterClasses = RF->getValueAsListOfDefs("RegClasses");
1805*b5893f02SDimitry Andric     std::vector<int64_t> RegisterCosts = RF->getValueAsListOfInts("RegCosts");
1806*b5893f02SDimitry Andric     ListInit *MoveElimInfo = RF->getValueAsListInit("AllowMoveElimination");
1807*b5893f02SDimitry Andric     for (unsigned I = 0, E = RegisterClasses.size(); I < E; ++I) {
1808*b5893f02SDimitry Andric       int Cost = RegisterCosts.size() > I ? RegisterCosts[I] : 1;
1809*b5893f02SDimitry Andric 
1810*b5893f02SDimitry Andric       bool AllowMoveElim = false;
1811*b5893f02SDimitry Andric       if (MoveElimInfo->size() > I) {
1812*b5893f02SDimitry Andric         BitInit *Val = cast<BitInit>(MoveElimInfo->getElement(I));
1813*b5893f02SDimitry Andric         AllowMoveElim = Val->getValue();
18144ba319b5SDimitry Andric       }
1815*b5893f02SDimitry Andric 
1816*b5893f02SDimitry Andric       CGRF.Costs.emplace_back(RegisterClasses[I], Cost, AllowMoveElim);
18174ba319b5SDimitry Andric     }
18184ba319b5SDimitry Andric   }
18194ba319b5SDimitry Andric }
18204ba319b5SDimitry Andric 
18213861d79fSDimitry Andric // Collect and sort WriteRes, ReadAdvance, and ProcResources.
collectProcResources()18223861d79fSDimitry Andric void CodeGenSchedModels::collectProcResources() {
18233ca95b02SDimitry Andric   ProcResourceDefs = Records.getAllDerivedDefinitions("ProcResourceUnits");
18243ca95b02SDimitry Andric   ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
18253ca95b02SDimitry Andric 
18263861d79fSDimitry Andric   // Add any subtarget-specific SchedReadWrites that are directly associated
18273861d79fSDimitry Andric   // with processor resources. Refer to the parent SchedClass's ProcIndices to
18283861d79fSDimitry Andric   // determine which processors they apply to.
18294ba319b5SDimitry Andric   for (const CodeGenSchedClass &SC :
18304ba319b5SDimitry Andric        make_range(schedClassBegin(), schedClassEnd())) {
18314ba319b5SDimitry Andric     if (SC.ItinClassDef) {
18324ba319b5SDimitry Andric       collectItinProcResources(SC.ItinClassDef);
18334ba319b5SDimitry Andric       continue;
18344ba319b5SDimitry Andric     }
18354ba319b5SDimitry Andric 
1836139f7f9bSDimitry Andric     // This class may have a default ReadWrite list which can be overriden by
1837139f7f9bSDimitry Andric     // InstRW definitions.
18384ba319b5SDimitry Andric     for (Record *RW : SC.InstRWs) {
18394ba319b5SDimitry Andric       Record *RWModelDef = RW->getValueAsDef("SchedModel");
18404ba319b5SDimitry Andric       unsigned PIdx = getProcModel(RWModelDef).Index;
1841139f7f9bSDimitry Andric       IdxVec Writes, Reads;
18424ba319b5SDimitry Andric       findRWs(RW->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
18434ba319b5SDimitry Andric       collectRWResources(Writes, Reads, PIdx);
1844139f7f9bSDimitry Andric     }
18454ba319b5SDimitry Andric 
18464ba319b5SDimitry Andric     collectRWResources(SC.Writes, SC.Reads, SC.ProcIndices);
1847139f7f9bSDimitry Andric   }
18483861d79fSDimitry Andric   // Add resources separately defined by each subtarget.
18493861d79fSDimitry Andric   RecVec WRDefs = Records.getAllDerivedDefinitions("WriteRes");
18502cab237bSDimitry Andric   for (Record *WR : WRDefs) {
18512cab237bSDimitry Andric     Record *ModelDef = WR->getValueAsDef("SchedModel");
18522cab237bSDimitry Andric     addWriteRes(WR, getProcModel(ModelDef).Index);
18533861d79fSDimitry Andric   }
185491bc56edSDimitry Andric   RecVec SWRDefs = Records.getAllDerivedDefinitions("SchedWriteRes");
18552cab237bSDimitry Andric   for (Record *SWR : SWRDefs) {
18562cab237bSDimitry Andric     Record *ModelDef = SWR->getValueAsDef("SchedModel");
18572cab237bSDimitry Andric     addWriteRes(SWR, getProcModel(ModelDef).Index);
185891bc56edSDimitry Andric   }
18593861d79fSDimitry Andric   RecVec RADefs = Records.getAllDerivedDefinitions("ReadAdvance");
18602cab237bSDimitry Andric   for (Record *RA : RADefs) {
18612cab237bSDimitry Andric     Record *ModelDef = RA->getValueAsDef("SchedModel");
18622cab237bSDimitry Andric     addReadAdvance(RA, getProcModel(ModelDef).Index);
18633861d79fSDimitry Andric   }
186491bc56edSDimitry Andric   RecVec SRADefs = Records.getAllDerivedDefinitions("SchedReadAdvance");
18652cab237bSDimitry Andric   for (Record *SRA : SRADefs) {
18662cab237bSDimitry Andric     if (SRA->getValueInit("SchedModel")->isComplete()) {
18672cab237bSDimitry Andric       Record *ModelDef = SRA->getValueAsDef("SchedModel");
18682cab237bSDimitry Andric       addReadAdvance(SRA, getProcModel(ModelDef).Index);
186991bc56edSDimitry Andric     }
187091bc56edSDimitry Andric   }
1871f785676fSDimitry Andric   // Add ProcResGroups that are defined within this processor model, which may
1872f785676fSDimitry Andric   // not be directly referenced but may directly specify a buffer size.
1873f785676fSDimitry Andric   RecVec ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
18742cab237bSDimitry Andric   for (Record *PRG : ProcResGroups) {
18752cab237bSDimitry Andric     if (!PRG->getValueInit("SchedModel")->isComplete())
1876f785676fSDimitry Andric       continue;
18772cab237bSDimitry Andric     CodeGenProcModel &PM = getProcModel(PRG->getValueAsDef("SchedModel"));
18782cab237bSDimitry Andric     if (!is_contained(PM.ProcResourceDefs, PRG))
18792cab237bSDimitry Andric       PM.ProcResourceDefs.push_back(PRG);
1880f785676fSDimitry Andric   }
18814ba319b5SDimitry Andric   // Add ProcResourceUnits unconditionally.
18824ba319b5SDimitry Andric   for (Record *PRU : Records.getAllDerivedDefinitions("ProcResourceUnits")) {
18834ba319b5SDimitry Andric     if (!PRU->getValueInit("SchedModel")->isComplete())
18844ba319b5SDimitry Andric       continue;
18854ba319b5SDimitry Andric     CodeGenProcModel &PM = getProcModel(PRU->getValueAsDef("SchedModel"));
18864ba319b5SDimitry Andric     if (!is_contained(PM.ProcResourceDefs, PRU))
18874ba319b5SDimitry Andric       PM.ProcResourceDefs.push_back(PRU);
18884ba319b5SDimitry Andric   }
18893861d79fSDimitry Andric   // Finalize each ProcModel by sorting the record arrays.
189039d628a0SDimitry Andric   for (CodeGenProcModel &PM : ProcModels) {
1891*b5893f02SDimitry Andric     llvm::sort(PM.WriteResDefs, LessRecord());
1892*b5893f02SDimitry Andric     llvm::sort(PM.ReadAdvanceDefs, LessRecord());
1893*b5893f02SDimitry Andric     llvm::sort(PM.ProcResourceDefs, LessRecord());
18944ba319b5SDimitry Andric     LLVM_DEBUG(
18953861d79fSDimitry Andric         PM.dump();
18964ba319b5SDimitry Andric         dbgs() << "WriteResDefs: "; for (RecIter RI = PM.WriteResDefs.begin(),
18974ba319b5SDimitry Andric                                          RE = PM.WriteResDefs.end();
18984ba319b5SDimitry Andric                                          RI != RE; ++RI) {
18993861d79fSDimitry Andric           if ((*RI)->isSubClassOf("WriteRes"))
19003861d79fSDimitry Andric             dbgs() << (*RI)->getValueAsDef("WriteType")->getName() << " ";
19013861d79fSDimitry Andric           else
19023861d79fSDimitry Andric             dbgs() << (*RI)->getName() << " ";
19034ba319b5SDimitry Andric         } dbgs() << "\nReadAdvanceDefs: ";
19043861d79fSDimitry Andric         for (RecIter RI = PM.ReadAdvanceDefs.begin(),
19054ba319b5SDimitry Andric              RE = PM.ReadAdvanceDefs.end();
19064ba319b5SDimitry Andric              RI != RE; ++RI) {
19073861d79fSDimitry Andric           if ((*RI)->isSubClassOf("ReadAdvance"))
19083861d79fSDimitry Andric             dbgs() << (*RI)->getValueAsDef("ReadType")->getName() << " ";
19093861d79fSDimitry Andric           else
19103861d79fSDimitry Andric             dbgs() << (*RI)->getName() << " ";
19114ba319b5SDimitry Andric         } dbgs()
19124ba319b5SDimitry Andric         << "\nProcResourceDefs: ";
19133861d79fSDimitry Andric         for (RecIter RI = PM.ProcResourceDefs.begin(),
19144ba319b5SDimitry Andric              RE = PM.ProcResourceDefs.end();
19154ba319b5SDimitry Andric              RI != RE; ++RI) { dbgs() << (*RI)->getName() << " "; } dbgs()
19164ba319b5SDimitry Andric         << '\n');
1917284c1978SDimitry Andric     verifyProcResourceGroups(PM);
19183861d79fSDimitry Andric   }
19193ca95b02SDimitry Andric 
19203ca95b02SDimitry Andric   ProcResourceDefs.clear();
19213ca95b02SDimitry Andric   ProcResGroups.clear();
19223ca95b02SDimitry Andric }
19233ca95b02SDimitry Andric 
checkCompleteness()19243ca95b02SDimitry Andric void CodeGenSchedModels::checkCompleteness() {
19253ca95b02SDimitry Andric   bool Complete = true;
19263ca95b02SDimitry Andric   bool HadCompleteModel = false;
19273ca95b02SDimitry Andric   for (const CodeGenProcModel &ProcModel : procModels()) {
19284ba319b5SDimitry Andric     const bool HasItineraries = ProcModel.hasItineraries();
19293ca95b02SDimitry Andric     if (!ProcModel.ModelDef->getValueAsBit("CompleteModel"))
19303ca95b02SDimitry Andric       continue;
19313ca95b02SDimitry Andric     for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
19323ca95b02SDimitry Andric       if (Inst->hasNoSchedulingInfo)
19333ca95b02SDimitry Andric         continue;
19343ca95b02SDimitry Andric       if (ProcModel.isUnsupported(*Inst))
19353ca95b02SDimitry Andric         continue;
19363ca95b02SDimitry Andric       unsigned SCIdx = getSchedClassIdx(*Inst);
19373ca95b02SDimitry Andric       if (!SCIdx) {
19383ca95b02SDimitry Andric         if (Inst->TheDef->isValueUnset("SchedRW") && !HadCompleteModel) {
19393ca95b02SDimitry Andric           PrintError("No schedule information for instruction '"
19403ca95b02SDimitry Andric                      + Inst->TheDef->getName() + "'");
19413ca95b02SDimitry Andric           Complete = false;
19423ca95b02SDimitry Andric         }
19433ca95b02SDimitry Andric         continue;
19443ca95b02SDimitry Andric       }
19453ca95b02SDimitry Andric 
19463ca95b02SDimitry Andric       const CodeGenSchedClass &SC = getSchedClass(SCIdx);
19473ca95b02SDimitry Andric       if (!SC.Writes.empty())
19483ca95b02SDimitry Andric         continue;
19494ba319b5SDimitry Andric       if (HasItineraries && SC.ItinClassDef != nullptr &&
1950d88c1a5aSDimitry Andric           SC.ItinClassDef->getName() != "NoItinerary")
19513ca95b02SDimitry Andric         continue;
19523ca95b02SDimitry Andric 
19533ca95b02SDimitry Andric       const RecVec &InstRWs = SC.InstRWs;
1954d88c1a5aSDimitry Andric       auto I = find_if(InstRWs, [&ProcModel](const Record *R) {
1955d88c1a5aSDimitry Andric         return R->getValueAsDef("SchedModel") == ProcModel.ModelDef;
19563ca95b02SDimitry Andric       });
19573ca95b02SDimitry Andric       if (I == InstRWs.end()) {
19583ca95b02SDimitry Andric         PrintError("'" + ProcModel.ModelName + "' lacks information for '" +
19593ca95b02SDimitry Andric                    Inst->TheDef->getName() + "'");
19603ca95b02SDimitry Andric         Complete = false;
19613ca95b02SDimitry Andric       }
19623ca95b02SDimitry Andric     }
19633ca95b02SDimitry Andric     HadCompleteModel = true;
19643ca95b02SDimitry Andric   }
19653ca95b02SDimitry Andric   if (!Complete) {
19663ca95b02SDimitry Andric     errs() << "\n\nIncomplete schedule models found.\n"
19673ca95b02SDimitry Andric       << "- Consider setting 'CompleteModel = 0' while developing new models.\n"
19683ca95b02SDimitry Andric       << "- Pseudo instructions can be marked with 'hasNoSchedulingInfo = 1'.\n"
19693ca95b02SDimitry Andric       << "- Instructions should usually have Sched<[...]> as a superclass, "
19703ca95b02SDimitry Andric          "you may temporarily use an empty list.\n"
19713ca95b02SDimitry Andric       << "- Instructions related to unsupported features can be excluded with "
19723ca95b02SDimitry Andric          "list<Predicate> UnsupportedFeatures = [HasA,..,HasY]; in the "
19733ca95b02SDimitry Andric          "processor model.\n\n";
19743ca95b02SDimitry Andric     PrintFatalError("Incomplete schedule model");
19753ca95b02SDimitry Andric   }
19763861d79fSDimitry Andric }
19773861d79fSDimitry Andric 
19783861d79fSDimitry Andric // Collect itinerary class resources for each processor.
collectItinProcResources(Record * ItinClassDef)19793861d79fSDimitry Andric void CodeGenSchedModels::collectItinProcResources(Record *ItinClassDef) {
19803861d79fSDimitry Andric   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
19813861d79fSDimitry Andric     const CodeGenProcModel &PM = ProcModels[PIdx];
19823861d79fSDimitry Andric     // For all ItinRW entries.
19833861d79fSDimitry Andric     bool HasMatch = false;
19843861d79fSDimitry Andric     for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
19853861d79fSDimitry Andric          II != IE; ++II) {
19863861d79fSDimitry Andric       RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
19873861d79fSDimitry Andric       if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
19883861d79fSDimitry Andric         continue;
19893861d79fSDimitry Andric       if (HasMatch)
19903861d79fSDimitry Andric         PrintFatalError((*II)->getLoc(), "Duplicate itinerary class "
19913861d79fSDimitry Andric                         + ItinClassDef->getName()
19923861d79fSDimitry Andric                         + " in ItinResources for " + PM.ModelName);
19933861d79fSDimitry Andric       HasMatch = true;
19943861d79fSDimitry Andric       IdxVec Writes, Reads;
19953861d79fSDimitry Andric       findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
19964ba319b5SDimitry Andric       collectRWResources(Writes, Reads, PIdx);
19973861d79fSDimitry Andric     }
19983861d79fSDimitry Andric   }
19993861d79fSDimitry Andric }
20003861d79fSDimitry Andric 
collectRWResources(unsigned RWIdx,bool IsRead,ArrayRef<unsigned> ProcIndices)20013861d79fSDimitry Andric void CodeGenSchedModels::collectRWResources(unsigned RWIdx, bool IsRead,
20027d523365SDimitry Andric                                             ArrayRef<unsigned> ProcIndices) {
20033861d79fSDimitry Andric   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
20043861d79fSDimitry Andric   if (SchedRW.TheDef) {
20053861d79fSDimitry Andric     if (!IsRead && SchedRW.TheDef->isSubClassOf("SchedWriteRes")) {
20067d523365SDimitry Andric       for (unsigned Idx : ProcIndices)
20077d523365SDimitry Andric         addWriteRes(SchedRW.TheDef, Idx);
20083861d79fSDimitry Andric     }
20093861d79fSDimitry Andric     else if (IsRead && SchedRW.TheDef->isSubClassOf("SchedReadAdvance")) {
20107d523365SDimitry Andric       for (unsigned Idx : ProcIndices)
20117d523365SDimitry Andric         addReadAdvance(SchedRW.TheDef, Idx);
20123861d79fSDimitry Andric     }
20133861d79fSDimitry Andric   }
20143861d79fSDimitry Andric   for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
20153861d79fSDimitry Andric        AI != AE; ++AI) {
20163861d79fSDimitry Andric     IdxVec AliasProcIndices;
20173861d79fSDimitry Andric     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
20183861d79fSDimitry Andric       AliasProcIndices.push_back(
20193861d79fSDimitry Andric         getProcModel((*AI)->getValueAsDef("SchedModel")).Index);
20203861d79fSDimitry Andric     }
20213861d79fSDimitry Andric     else
20223861d79fSDimitry Andric       AliasProcIndices = ProcIndices;
20233861d79fSDimitry Andric     const CodeGenSchedRW &AliasRW = getSchedRW((*AI)->getValueAsDef("AliasRW"));
20243861d79fSDimitry Andric     assert(AliasRW.IsRead == IsRead && "cannot alias reads to writes");
20253861d79fSDimitry Andric 
20263861d79fSDimitry Andric     IdxVec ExpandedRWs;
20273861d79fSDimitry Andric     expandRWSequence(AliasRW.Index, ExpandedRWs, IsRead);
20283861d79fSDimitry Andric     for (IdxIter SI = ExpandedRWs.begin(), SE = ExpandedRWs.end();
20293861d79fSDimitry Andric          SI != SE; ++SI) {
20303861d79fSDimitry Andric       collectRWResources(*SI, IsRead, AliasProcIndices);
20313861d79fSDimitry Andric     }
20323861d79fSDimitry Andric   }
20333861d79fSDimitry Andric }
20343861d79fSDimitry Andric 
20353861d79fSDimitry Andric // Collect resources for a set of read/write types and processor indices.
collectRWResources(ArrayRef<unsigned> Writes,ArrayRef<unsigned> Reads,ArrayRef<unsigned> ProcIndices)20367d523365SDimitry Andric void CodeGenSchedModels::collectRWResources(ArrayRef<unsigned> Writes,
20377d523365SDimitry Andric                                             ArrayRef<unsigned> Reads,
20387d523365SDimitry Andric                                             ArrayRef<unsigned> ProcIndices) {
20397d523365SDimitry Andric   for (unsigned Idx : Writes)
20407d523365SDimitry Andric     collectRWResources(Idx, /*IsRead=*/false, ProcIndices);
20413861d79fSDimitry Andric 
20427d523365SDimitry Andric   for (unsigned Idx : Reads)
20437d523365SDimitry Andric     collectRWResources(Idx, /*IsRead=*/true, ProcIndices);
20443861d79fSDimitry Andric }
20453861d79fSDimitry Andric 
20463861d79fSDimitry Andric // Find the processor's resource units for this kind of resource.
findProcResUnits(Record * ProcResKind,const CodeGenProcModel & PM,ArrayRef<SMLoc> Loc) const20473861d79fSDimitry Andric Record *CodeGenSchedModels::findProcResUnits(Record *ProcResKind,
20482cab237bSDimitry Andric                                              const CodeGenProcModel &PM,
20492cab237bSDimitry Andric                                              ArrayRef<SMLoc> Loc) const {
20503861d79fSDimitry Andric   if (ProcResKind->isSubClassOf("ProcResourceUnits"))
20513861d79fSDimitry Andric     return ProcResKind;
20523861d79fSDimitry Andric 
205391bc56edSDimitry Andric   Record *ProcUnitDef = nullptr;
20543ca95b02SDimitry Andric   assert(!ProcResourceDefs.empty());
20553ca95b02SDimitry Andric   assert(!ProcResGroups.empty());
20563861d79fSDimitry Andric 
20572cab237bSDimitry Andric   for (Record *ProcResDef : ProcResourceDefs) {
20582cab237bSDimitry Andric     if (ProcResDef->getValueAsDef("Kind") == ProcResKind
20592cab237bSDimitry Andric         && ProcResDef->getValueAsDef("SchedModel") == PM.ModelDef) {
20603861d79fSDimitry Andric       if (ProcUnitDef) {
20612cab237bSDimitry Andric         PrintFatalError(Loc,
20623861d79fSDimitry Andric                         "Multiple ProcessorResourceUnits associated with "
20633861d79fSDimitry Andric                         + ProcResKind->getName());
20643861d79fSDimitry Andric       }
20652cab237bSDimitry Andric       ProcUnitDef = ProcResDef;
20663861d79fSDimitry Andric     }
20673861d79fSDimitry Andric   }
20682cab237bSDimitry Andric   for (Record *ProcResGroup : ProcResGroups) {
20692cab237bSDimitry Andric     if (ProcResGroup == ProcResKind
20702cab237bSDimitry Andric         && ProcResGroup->getValueAsDef("SchedModel") == PM.ModelDef) {
2071139f7f9bSDimitry Andric       if (ProcUnitDef) {
20722cab237bSDimitry Andric         PrintFatalError(Loc,
2073139f7f9bSDimitry Andric                         "Multiple ProcessorResourceUnits associated with "
2074139f7f9bSDimitry Andric                         + ProcResKind->getName());
2075139f7f9bSDimitry Andric       }
20762cab237bSDimitry Andric       ProcUnitDef = ProcResGroup;
2077139f7f9bSDimitry Andric     }
2078139f7f9bSDimitry Andric   }
20793861d79fSDimitry Andric   if (!ProcUnitDef) {
20802cab237bSDimitry Andric     PrintFatalError(Loc,
20813861d79fSDimitry Andric                     "No ProcessorResources associated with "
20823861d79fSDimitry Andric                     + ProcResKind->getName());
20833861d79fSDimitry Andric   }
20843861d79fSDimitry Andric   return ProcUnitDef;
20853861d79fSDimitry Andric }
20863861d79fSDimitry Andric 
20873861d79fSDimitry Andric // Iteratively add a resource and its super resources.
addProcResource(Record * ProcResKind,CodeGenProcModel & PM,ArrayRef<SMLoc> Loc)20883861d79fSDimitry Andric void CodeGenSchedModels::addProcResource(Record *ProcResKind,
20892cab237bSDimitry Andric                                          CodeGenProcModel &PM,
20902cab237bSDimitry Andric                                          ArrayRef<SMLoc> Loc) {
2091d88c1a5aSDimitry Andric   while (true) {
20922cab237bSDimitry Andric     Record *ProcResUnits = findProcResUnits(ProcResKind, PM, Loc);
20933861d79fSDimitry Andric 
20943861d79fSDimitry Andric     // See if this ProcResource is already associated with this processor.
2095d88c1a5aSDimitry Andric     if (is_contained(PM.ProcResourceDefs, ProcResUnits))
20963861d79fSDimitry Andric       return;
20973861d79fSDimitry Andric 
20983861d79fSDimitry Andric     PM.ProcResourceDefs.push_back(ProcResUnits);
2099139f7f9bSDimitry Andric     if (ProcResUnits->isSubClassOf("ProcResGroup"))
2100139f7f9bSDimitry Andric       return;
2101139f7f9bSDimitry Andric 
21023861d79fSDimitry Andric     if (!ProcResUnits->getValueInit("Super")->isComplete())
21033861d79fSDimitry Andric       return;
21043861d79fSDimitry Andric 
21053861d79fSDimitry Andric     ProcResKind = ProcResUnits->getValueAsDef("Super");
21063861d79fSDimitry Andric   }
21073861d79fSDimitry Andric }
21083861d79fSDimitry Andric 
21093861d79fSDimitry Andric // Add resources for a SchedWrite to this processor if they don't exist.
addWriteRes(Record * ProcWriteResDef,unsigned PIdx)21103861d79fSDimitry Andric void CodeGenSchedModels::addWriteRes(Record *ProcWriteResDef, unsigned PIdx) {
21113861d79fSDimitry Andric   assert(PIdx && "don't add resources to an invalid Processor model");
21123861d79fSDimitry Andric 
21133861d79fSDimitry Andric   RecVec &WRDefs = ProcModels[PIdx].WriteResDefs;
2114d88c1a5aSDimitry Andric   if (is_contained(WRDefs, ProcWriteResDef))
21153861d79fSDimitry Andric     return;
21163861d79fSDimitry Andric   WRDefs.push_back(ProcWriteResDef);
21173861d79fSDimitry Andric 
21183861d79fSDimitry Andric   // Visit ProcResourceKinds referenced by the newly discovered WriteRes.
21193861d79fSDimitry Andric   RecVec ProcResDefs = ProcWriteResDef->getValueAsListOfDefs("ProcResources");
21203861d79fSDimitry Andric   for (RecIter WritePRI = ProcResDefs.begin(), WritePRE = ProcResDefs.end();
21213861d79fSDimitry Andric        WritePRI != WritePRE; ++WritePRI) {
21222cab237bSDimitry Andric     addProcResource(*WritePRI, ProcModels[PIdx], ProcWriteResDef->getLoc());
21233861d79fSDimitry Andric   }
21243861d79fSDimitry Andric }
21253861d79fSDimitry Andric 
21263861d79fSDimitry Andric // Add resources for a ReadAdvance to this processor if they don't exist.
addReadAdvance(Record * ProcReadAdvanceDef,unsigned PIdx)21273861d79fSDimitry Andric void CodeGenSchedModels::addReadAdvance(Record *ProcReadAdvanceDef,
21283861d79fSDimitry Andric                                         unsigned PIdx) {
21293861d79fSDimitry Andric   RecVec &RADefs = ProcModels[PIdx].ReadAdvanceDefs;
2130d88c1a5aSDimitry Andric   if (is_contained(RADefs, ProcReadAdvanceDef))
21313861d79fSDimitry Andric     return;
21323861d79fSDimitry Andric   RADefs.push_back(ProcReadAdvanceDef);
21333861d79fSDimitry Andric }
21343861d79fSDimitry Andric 
getProcResourceIdx(Record * PRDef) const21353861d79fSDimitry Andric unsigned CodeGenProcModel::getProcResourceIdx(Record *PRDef) const {
2136d88c1a5aSDimitry Andric   RecIter PRPos = find(ProcResourceDefs, PRDef);
21373861d79fSDimitry Andric   if (PRPos == ProcResourceDefs.end())
21383861d79fSDimitry Andric     PrintFatalError(PRDef->getLoc(), "ProcResource def is not included in "
21393861d79fSDimitry Andric                     "the ProcResources list for " + ModelName);
21403861d79fSDimitry Andric   // Idx=0 is reserved for invalid.
21413861d79fSDimitry Andric   return 1 + (PRPos - ProcResourceDefs.begin());
21423861d79fSDimitry Andric }
21433861d79fSDimitry Andric 
isUnsupported(const CodeGenInstruction & Inst) const21443ca95b02SDimitry Andric bool CodeGenProcModel::isUnsupported(const CodeGenInstruction &Inst) const {
21453ca95b02SDimitry Andric   for (const Record *TheDef : UnsupportedFeaturesDefs) {
21463ca95b02SDimitry Andric     for (const Record *PredDef : Inst.TheDef->getValueAsListOfDefs("Predicates")) {
21473ca95b02SDimitry Andric       if (TheDef->getName() == PredDef->getName())
21483ca95b02SDimitry Andric         return true;
21493ca95b02SDimitry Andric     }
21503ca95b02SDimitry Andric   }
21513ca95b02SDimitry Andric   return false;
21523ca95b02SDimitry Andric }
21533ca95b02SDimitry Andric 
21543861d79fSDimitry Andric #ifndef NDEBUG
dump() const21553861d79fSDimitry Andric void CodeGenProcModel::dump() const {
21563861d79fSDimitry Andric   dbgs() << Index << ": " << ModelName << " "
21573861d79fSDimitry Andric          << (ModelDef ? ModelDef->getName() : "inferred") << " "
21583861d79fSDimitry Andric          << (ItinsDef ? ItinsDef->getName() : "no itinerary") << '\n';
21593861d79fSDimitry Andric }
21603861d79fSDimitry Andric 
dump() const21613861d79fSDimitry Andric void CodeGenSchedRW::dump() const {
21623861d79fSDimitry Andric   dbgs() << Name << (IsVariadic ? " (V) " : " ");
21633861d79fSDimitry Andric   if (IsSequence) {
21643861d79fSDimitry Andric     dbgs() << "(";
21653861d79fSDimitry Andric     dumpIdxVec(Sequence);
21663861d79fSDimitry Andric     dbgs() << ")";
21673861d79fSDimitry Andric   }
21683861d79fSDimitry Andric }
21693861d79fSDimitry Andric 
dump(const CodeGenSchedModels * SchedModels) const21703861d79fSDimitry Andric void CodeGenSchedClass::dump(const CodeGenSchedModels* SchedModels) const {
2171139f7f9bSDimitry Andric   dbgs() << "SCHEDCLASS " << Index << ":" << Name << '\n'
21723861d79fSDimitry Andric          << "  Writes: ";
21733861d79fSDimitry Andric   for (unsigned i = 0, N = Writes.size(); i < N; ++i) {
21743861d79fSDimitry Andric     SchedModels->getSchedWrite(Writes[i]).dump();
21753861d79fSDimitry Andric     if (i < N-1) {
21763861d79fSDimitry Andric       dbgs() << '\n';
21773861d79fSDimitry Andric       dbgs().indent(10);
21783861d79fSDimitry Andric     }
21793861d79fSDimitry Andric   }
21803861d79fSDimitry Andric   dbgs() << "\n  Reads: ";
21813861d79fSDimitry Andric   for (unsigned i = 0, N = Reads.size(); i < N; ++i) {
21823861d79fSDimitry Andric     SchedModels->getSchedRead(Reads[i]).dump();
21833861d79fSDimitry Andric     if (i < N-1) {
21843861d79fSDimitry Andric       dbgs() << '\n';
21853861d79fSDimitry Andric       dbgs().indent(10);
21863861d79fSDimitry Andric     }
21873861d79fSDimitry Andric   }
21883861d79fSDimitry Andric   dbgs() << "\n  ProcIdx: "; dumpIdxVec(ProcIndices); dbgs() << '\n';
2189139f7f9bSDimitry Andric   if (!Transitions.empty()) {
2190139f7f9bSDimitry Andric     dbgs() << "\n Transitions for Proc ";
21912cab237bSDimitry Andric     for (const CodeGenSchedTransition &Transition : Transitions) {
21922cab237bSDimitry Andric       dumpIdxVec(Transition.ProcIndices);
2193139f7f9bSDimitry Andric     }
2194139f7f9bSDimitry Andric   }
21953861d79fSDimitry Andric }
21963861d79fSDimitry Andric 
dump() const21973861d79fSDimitry Andric void PredTransitions::dump() const {
21983861d79fSDimitry Andric   dbgs() << "Expanded Variants:\n";
21993861d79fSDimitry Andric   for (std::vector<PredTransition>::const_iterator
22003861d79fSDimitry Andric          TI = TransVec.begin(), TE = TransVec.end(); TI != TE; ++TI) {
22013861d79fSDimitry Andric     dbgs() << "{";
22023861d79fSDimitry Andric     for (SmallVectorImpl<PredCheck>::const_iterator
22033861d79fSDimitry Andric            PCI = TI->PredTerm.begin(), PCE = TI->PredTerm.end();
22043861d79fSDimitry Andric          PCI != PCE; ++PCI) {
22053861d79fSDimitry Andric       if (PCI != TI->PredTerm.begin())
22063861d79fSDimitry Andric         dbgs() << ", ";
22073861d79fSDimitry Andric       dbgs() << SchedModels.getSchedRW(PCI->RWIdx, PCI->IsRead).Name
22083861d79fSDimitry Andric              << ":" << PCI->Predicate->getName();
22093861d79fSDimitry Andric     }
22103861d79fSDimitry Andric     dbgs() << "},\n  => {";
22113861d79fSDimitry Andric     for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
22123861d79fSDimitry Andric            WSI = TI->WriteSequences.begin(), WSE = TI->WriteSequences.end();
22133861d79fSDimitry Andric          WSI != WSE; ++WSI) {
22143861d79fSDimitry Andric       dbgs() << "(";
22153861d79fSDimitry Andric       for (SmallVectorImpl<unsigned>::const_iterator
22163861d79fSDimitry Andric              WI = WSI->begin(), WE = WSI->end(); WI != WE; ++WI) {
22173861d79fSDimitry Andric         if (WI != WSI->begin())
22183861d79fSDimitry Andric           dbgs() << ", ";
22193861d79fSDimitry Andric         dbgs() << SchedModels.getSchedWrite(*WI).Name;
22203861d79fSDimitry Andric       }
22213861d79fSDimitry Andric       dbgs() << "),";
22223861d79fSDimitry Andric     }
22233861d79fSDimitry Andric     dbgs() << "}\n";
22243861d79fSDimitry Andric   }
22253861d79fSDimitry Andric }
22263861d79fSDimitry Andric #endif // NDEBUG
2227