10b57cec5SDimitry Andric //===- CodeGenSchedule.cpp - Scheduling MachineModels ---------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines structures to encapsulate the machine model as described in
100b57cec5SDimitry Andric // the target description.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "CodeGenSchedule.h"
150b57cec5SDimitry Andric #include "CodeGenInstruction.h"
160b57cec5SDimitry Andric #include "CodeGenTarget.h"
170b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
180b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
230b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
240b57cec5SDimitry Andric #include "llvm/Support/Regex.h"
250b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
260b57cec5SDimitry Andric #include "llvm/TableGen/Error.h"
270b57cec5SDimitry Andric #include <algorithm>
280b57cec5SDimitry Andric #include <iterator>
290b57cec5SDimitry Andric #include <utility>
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric using namespace llvm;
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric #define DEBUG_TYPE "subtarget-emitter"
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric #ifndef NDEBUG
dumpIdxVec(ArrayRef<unsigned> V)360b57cec5SDimitry Andric static void dumpIdxVec(ArrayRef<unsigned> V) {
370b57cec5SDimitry Andric   for (unsigned Idx : V)
380b57cec5SDimitry Andric     dbgs() << Idx << ", ";
390b57cec5SDimitry Andric }
400b57cec5SDimitry Andric #endif
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric namespace {
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric // (instrs a, b, ...) Evaluate and union all arguments. Identical to AddOp.
450b57cec5SDimitry Andric struct InstrsOp : public SetTheory::Operator {
apply__anonfd00d8910111::InstrsOp460b57cec5SDimitry Andric   void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
470b57cec5SDimitry Andric              ArrayRef<SMLoc> Loc) override {
480b57cec5SDimitry Andric     ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts, Loc);
490b57cec5SDimitry Andric   }
500b57cec5SDimitry Andric };
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric // (instregex "OpcPat",...) Find all instructions matching an opcode pattern.
530b57cec5SDimitry Andric struct InstRegexOp : public SetTheory::Operator {
540b57cec5SDimitry Andric   const CodeGenTarget &Target;
InstRegexOp__anonfd00d8910111::InstRegexOp550b57cec5SDimitry Andric   InstRegexOp(const CodeGenTarget &t): Target(t) {}
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric   /// Remove any text inside of parentheses from S.
removeParens__anonfd00d8910111::InstRegexOp580b57cec5SDimitry Andric   static std::string removeParens(llvm::StringRef S) {
590b57cec5SDimitry Andric     std::string Result;
600b57cec5SDimitry Andric     unsigned Paren = 0;
610b57cec5SDimitry Andric     // NB: We don't care about escaped parens here.
620b57cec5SDimitry Andric     for (char C : S) {
630b57cec5SDimitry Andric       switch (C) {
640b57cec5SDimitry Andric       case '(':
650b57cec5SDimitry Andric         ++Paren;
660b57cec5SDimitry Andric         break;
670b57cec5SDimitry Andric       case ')':
680b57cec5SDimitry Andric         --Paren;
690b57cec5SDimitry Andric         break;
700b57cec5SDimitry Andric       default:
710b57cec5SDimitry Andric         if (Paren == 0)
720b57cec5SDimitry Andric           Result += C;
730b57cec5SDimitry Andric       }
740b57cec5SDimitry Andric     }
750b57cec5SDimitry Andric     return Result;
760b57cec5SDimitry Andric   }
770b57cec5SDimitry Andric 
apply__anonfd00d8910111::InstRegexOp780b57cec5SDimitry Andric   void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
790b57cec5SDimitry Andric              ArrayRef<SMLoc> Loc) override {
800b57cec5SDimitry Andric     ArrayRef<const CodeGenInstruction *> Instructions =
810b57cec5SDimitry Andric         Target.getInstructionsByEnumValue();
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric     unsigned NumGeneric = Target.getNumFixedInstructions();
840b57cec5SDimitry Andric     unsigned NumPseudos = Target.getNumPseudoInstructions();
850b57cec5SDimitry Andric     auto Generics = Instructions.slice(0, NumGeneric);
860b57cec5SDimitry Andric     auto Pseudos = Instructions.slice(NumGeneric, NumPseudos);
870b57cec5SDimitry Andric     auto NonPseudos = Instructions.slice(NumGeneric + NumPseudos);
880b57cec5SDimitry Andric 
89af732203SDimitry Andric     for (Init *Arg : Expr->getArgs()) {
900b57cec5SDimitry Andric       StringInit *SI = dyn_cast<StringInit>(Arg);
910b57cec5SDimitry Andric       if (!SI)
920b57cec5SDimitry Andric         PrintFatalError(Loc, "instregex requires pattern string: " +
930b57cec5SDimitry Andric                                  Expr->getAsString());
940b57cec5SDimitry Andric       StringRef Original = SI->getValue();
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric       // Extract a prefix that we can binary search on.
970b57cec5SDimitry Andric       static const char RegexMetachars[] = "()^$|*+?.[]\\{}";
980b57cec5SDimitry Andric       auto FirstMeta = Original.find_first_of(RegexMetachars);
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric       // Look for top-level | or ?. We cannot optimize them to binary search.
1010b57cec5SDimitry Andric       if (removeParens(Original).find_first_of("|?") != std::string::npos)
1020b57cec5SDimitry Andric         FirstMeta = 0;
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric       Optional<Regex> Regexpr = None;
1050b57cec5SDimitry Andric       StringRef Prefix = Original.substr(0, FirstMeta);
1060b57cec5SDimitry Andric       StringRef PatStr = Original.substr(FirstMeta);
1070b57cec5SDimitry Andric       if (!PatStr.empty()) {
1080b57cec5SDimitry Andric         // For the rest use a python-style prefix match.
1095ffd83dbSDimitry Andric         std::string pat = std::string(PatStr);
1100b57cec5SDimitry Andric         if (pat[0] != '^') {
1110b57cec5SDimitry Andric           pat.insert(0, "^(");
1120b57cec5SDimitry Andric           pat.insert(pat.end(), ')');
1130b57cec5SDimitry Andric         }
1140b57cec5SDimitry Andric         Regexpr = Regex(pat);
1150b57cec5SDimitry Andric       }
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric       int NumMatches = 0;
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric       // The generic opcodes are unsorted, handle them manually.
1200b57cec5SDimitry Andric       for (auto *Inst : Generics) {
1210b57cec5SDimitry Andric         StringRef InstName = Inst->TheDef->getName();
1220b57cec5SDimitry Andric         if (InstName.startswith(Prefix) &&
1230b57cec5SDimitry Andric             (!Regexpr || Regexpr->match(InstName.substr(Prefix.size())))) {
1240b57cec5SDimitry Andric           Elts.insert(Inst->TheDef);
1250b57cec5SDimitry Andric           NumMatches++;
1260b57cec5SDimitry Andric         }
1270b57cec5SDimitry Andric       }
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric       // Target instructions are split into two ranges: pseudo instructions
1300b57cec5SDimitry Andric       // first, than non-pseudos. Each range is in lexicographical order
1310b57cec5SDimitry Andric       // sorted by name. Find the sub-ranges that start with our prefix.
1320b57cec5SDimitry Andric       struct Comp {
1330b57cec5SDimitry Andric         bool operator()(const CodeGenInstruction *LHS, StringRef RHS) {
1340b57cec5SDimitry Andric           return LHS->TheDef->getName() < RHS;
1350b57cec5SDimitry Andric         }
1360b57cec5SDimitry Andric         bool operator()(StringRef LHS, const CodeGenInstruction *RHS) {
1370b57cec5SDimitry Andric           return LHS < RHS->TheDef->getName() &&
1380b57cec5SDimitry Andric                  !RHS->TheDef->getName().startswith(LHS);
1390b57cec5SDimitry Andric         }
1400b57cec5SDimitry Andric       };
1410b57cec5SDimitry Andric       auto Range1 =
1420b57cec5SDimitry Andric           std::equal_range(Pseudos.begin(), Pseudos.end(), Prefix, Comp());
1430b57cec5SDimitry Andric       auto Range2 = std::equal_range(NonPseudos.begin(), NonPseudos.end(),
1440b57cec5SDimitry Andric                                      Prefix, Comp());
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric       // For these ranges we know that instruction names start with the prefix.
1470b57cec5SDimitry Andric       // Check if there's a regex that needs to be checked.
1480b57cec5SDimitry Andric       const auto HandleNonGeneric = [&](const CodeGenInstruction *Inst) {
1490b57cec5SDimitry Andric         StringRef InstName = Inst->TheDef->getName();
1500b57cec5SDimitry Andric         if (!Regexpr || Regexpr->match(InstName.substr(Prefix.size()))) {
1510b57cec5SDimitry Andric           Elts.insert(Inst->TheDef);
1520b57cec5SDimitry Andric           NumMatches++;
1530b57cec5SDimitry Andric         }
1540b57cec5SDimitry Andric       };
1550b57cec5SDimitry Andric       std::for_each(Range1.first, Range1.second, HandleNonGeneric);
1560b57cec5SDimitry Andric       std::for_each(Range2.first, Range2.second, HandleNonGeneric);
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric       if (0 == NumMatches)
1590b57cec5SDimitry Andric         PrintFatalError(Loc, "instregex has no matches: " + Original);
1600b57cec5SDimitry Andric     }
1610b57cec5SDimitry Andric   }
1620b57cec5SDimitry Andric };
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric } // end anonymous namespace
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric /// CodeGenModels ctor interprets machine model records and populates maps.
CodeGenSchedModels(RecordKeeper & RK,const CodeGenTarget & TGT)1670b57cec5SDimitry Andric CodeGenSchedModels::CodeGenSchedModels(RecordKeeper &RK,
1680b57cec5SDimitry Andric                                        const CodeGenTarget &TGT):
1690b57cec5SDimitry Andric   Records(RK), Target(TGT) {
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   Sets.addFieldExpander("InstRW", "Instrs");
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   // Allow Set evaluation to recognize the dags used in InstRW records:
1740b57cec5SDimitry Andric   // (instrs Op1, Op1...)
1758bcb0991SDimitry Andric   Sets.addOperator("instrs", std::make_unique<InstrsOp>());
1768bcb0991SDimitry Andric   Sets.addOperator("instregex", std::make_unique<InstRegexOp>(Target));
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   // Instantiate a CodeGenProcModel for each SchedMachineModel with the values
1790b57cec5SDimitry Andric   // that are explicitly referenced in tablegen records. Resources associated
1800b57cec5SDimitry Andric   // with each processor will be derived later. Populate ProcModelMap with the
1810b57cec5SDimitry Andric   // CodeGenProcModel instances.
1820b57cec5SDimitry Andric   collectProcModels();
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   // Instantiate a CodeGenSchedRW for each SchedReadWrite record explicitly
1850b57cec5SDimitry Andric   // defined, and populate SchedReads and SchedWrites vectors. Implicit
1860b57cec5SDimitry Andric   // SchedReadWrites that represent sequences derived from expanded variant will
1870b57cec5SDimitry Andric   // be inferred later.
1880b57cec5SDimitry Andric   collectSchedRW();
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   // Instantiate a CodeGenSchedClass for each unique SchedRW signature directly
1910b57cec5SDimitry Andric   // required by an instruction definition, and populate SchedClassIdxMap. Set
1920b57cec5SDimitry Andric   // NumItineraryClasses to the number of explicit itinerary classes referenced
1930b57cec5SDimitry Andric   // by instructions. Set NumInstrSchedClasses to the number of itinerary
1940b57cec5SDimitry Andric   // classes plus any classes implied by instructions that derive from class
1950b57cec5SDimitry Andric   // Sched and provide SchedRW list. This does not infer any new classes from
1960b57cec5SDimitry Andric   // SchedVariant.
1970b57cec5SDimitry Andric   collectSchedClasses();
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   // Find instruction itineraries for each processor. Sort and populate
2000b57cec5SDimitry Andric   // CodeGenProcModel::ItinDefList. (Cycle-to-cycle itineraries). This requires
2010b57cec5SDimitry Andric   // all itinerary classes to be discovered.
2020b57cec5SDimitry Andric   collectProcItins();
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   // Find ItinRW records for each processor and itinerary class.
2050b57cec5SDimitry Andric   // (For per-operand resources mapped to itinerary classes).
2060b57cec5SDimitry Andric   collectProcItinRW();
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   // Find UnsupportedFeatures records for each processor.
2090b57cec5SDimitry Andric   // (For per-operand resources mapped to itinerary classes).
2100b57cec5SDimitry Andric   collectProcUnsupportedFeatures();
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric   // Infer new SchedClasses from SchedVariant.
2130b57cec5SDimitry Andric   inferSchedClasses();
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   // Populate each CodeGenProcModel's WriteResDefs, ReadAdvanceDefs, and
2160b57cec5SDimitry Andric   // ProcResourceDefs.
2170b57cec5SDimitry Andric   LLVM_DEBUG(
2180b57cec5SDimitry Andric       dbgs() << "\n+++ RESOURCE DEFINITIONS (collectProcResources) +++\n");
2190b57cec5SDimitry Andric   collectProcResources();
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   // Collect optional processor description.
2220b57cec5SDimitry Andric   collectOptionalProcessorInfo();
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   // Check MCInstPredicate definitions.
2250b57cec5SDimitry Andric   checkMCInstPredicates();
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   // Check STIPredicate definitions.
2280b57cec5SDimitry Andric   checkSTIPredicates();
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric   // Find STIPredicate definitions for each processor model, and construct
2310b57cec5SDimitry Andric   // STIPredicateFunction objects.
2320b57cec5SDimitry Andric   collectSTIPredicates();
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric   checkCompleteness();
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric 
checkSTIPredicates() const2370b57cec5SDimitry Andric void CodeGenSchedModels::checkSTIPredicates() const {
2380b57cec5SDimitry Andric   DenseMap<StringRef, const Record *> Declarations;
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   // There cannot be multiple declarations with the same name.
2410b57cec5SDimitry Andric   const RecVec Decls = Records.getAllDerivedDefinitions("STIPredicateDecl");
2420b57cec5SDimitry Andric   for (const Record *R : Decls) {
2430b57cec5SDimitry Andric     StringRef Name = R->getValueAsString("Name");
2440b57cec5SDimitry Andric     const auto It = Declarations.find(Name);
2450b57cec5SDimitry Andric     if (It == Declarations.end()) {
2460b57cec5SDimitry Andric       Declarations[Name] = R;
2470b57cec5SDimitry Andric       continue;
2480b57cec5SDimitry Andric     }
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric     PrintError(R->getLoc(), "STIPredicate " + Name + " multiply declared.");
251af732203SDimitry Andric     PrintFatalNote(It->second->getLoc(), "Previous declaration was here.");
2520b57cec5SDimitry Andric   }
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   // Disallow InstructionEquivalenceClasses with an empty instruction list.
2550b57cec5SDimitry Andric   const RecVec Defs =
2560b57cec5SDimitry Andric       Records.getAllDerivedDefinitions("InstructionEquivalenceClass");
2570b57cec5SDimitry Andric   for (const Record *R : Defs) {
2580b57cec5SDimitry Andric     RecVec Opcodes = R->getValueAsListOfDefs("Opcodes");
2590b57cec5SDimitry Andric     if (Opcodes.empty()) {
2600b57cec5SDimitry Andric       PrintFatalError(R->getLoc(), "Invalid InstructionEquivalenceClass "
2610b57cec5SDimitry Andric                                    "defined with an empty opcode list.");
2620b57cec5SDimitry Andric     }
2630b57cec5SDimitry Andric   }
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric // Used by function `processSTIPredicate` to construct a mask of machine
2670b57cec5SDimitry Andric // instruction operands.
constructOperandMask(ArrayRef<int64_t> Indices)2680b57cec5SDimitry Andric static APInt constructOperandMask(ArrayRef<int64_t> Indices) {
2690b57cec5SDimitry Andric   APInt OperandMask;
2700b57cec5SDimitry Andric   if (Indices.empty())
2710b57cec5SDimitry Andric     return OperandMask;
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   int64_t MaxIndex = *std::max_element(Indices.begin(), Indices.end());
2740b57cec5SDimitry Andric   assert(MaxIndex >= 0 && "Invalid negative indices in input!");
2750b57cec5SDimitry Andric   OperandMask = OperandMask.zext(MaxIndex + 1);
2760b57cec5SDimitry Andric   for (const int64_t Index : Indices) {
2770b57cec5SDimitry Andric     assert(Index >= 0 && "Invalid negative indices!");
2780b57cec5SDimitry Andric     OperandMask.setBit(Index);
2790b57cec5SDimitry Andric   }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   return OperandMask;
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric static void
processSTIPredicate(STIPredicateFunction & Fn,const ProcModelMapTy & ProcModelMap)2850b57cec5SDimitry Andric processSTIPredicate(STIPredicateFunction &Fn,
286af732203SDimitry Andric                     const ProcModelMapTy &ProcModelMap) {
2870b57cec5SDimitry Andric   DenseMap<const Record *, unsigned> Opcode2Index;
2880b57cec5SDimitry Andric   using OpcodeMapPair = std::pair<const Record *, OpcodeInfo>;
2890b57cec5SDimitry Andric   std::vector<OpcodeMapPair> OpcodeMappings;
2900b57cec5SDimitry Andric   std::vector<std::pair<APInt, APInt>> OpcodeMasks;
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric   DenseMap<const Record *, unsigned> Predicate2Index;
2930b57cec5SDimitry Andric   unsigned NumUniquePredicates = 0;
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric   // Number unique predicates and opcodes used by InstructionEquivalenceClass
2960b57cec5SDimitry Andric   // definitions. Each unique opcode will be associated with an OpcodeInfo
2970b57cec5SDimitry Andric   // object.
2980b57cec5SDimitry Andric   for (const Record *Def : Fn.getDefinitions()) {
2990b57cec5SDimitry Andric     RecVec Classes = Def->getValueAsListOfDefs("Classes");
3000b57cec5SDimitry Andric     for (const Record *EC : Classes) {
3010b57cec5SDimitry Andric       const Record *Pred = EC->getValueAsDef("Predicate");
3020b57cec5SDimitry Andric       if (Predicate2Index.find(Pred) == Predicate2Index.end())
3030b57cec5SDimitry Andric         Predicate2Index[Pred] = NumUniquePredicates++;
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric       RecVec Opcodes = EC->getValueAsListOfDefs("Opcodes");
3060b57cec5SDimitry Andric       for (const Record *Opcode : Opcodes) {
3070b57cec5SDimitry Andric         if (Opcode2Index.find(Opcode) == Opcode2Index.end()) {
3080b57cec5SDimitry Andric           Opcode2Index[Opcode] = OpcodeMappings.size();
3090b57cec5SDimitry Andric           OpcodeMappings.emplace_back(Opcode, OpcodeInfo());
3100b57cec5SDimitry Andric         }
3110b57cec5SDimitry Andric       }
3120b57cec5SDimitry Andric     }
3130b57cec5SDimitry Andric   }
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric   // Initialize vector `OpcodeMasks` with default values.  We want to keep track
3160b57cec5SDimitry Andric   // of which processors "use" which opcodes.  We also want to be able to
3170b57cec5SDimitry Andric   // identify predicates that are used by different processors for a same
3180b57cec5SDimitry Andric   // opcode.
3190b57cec5SDimitry Andric   // This information is used later on by this algorithm to sort OpcodeMapping
3200b57cec5SDimitry Andric   // elements based on their processor and predicate sets.
3210b57cec5SDimitry Andric   OpcodeMasks.resize(OpcodeMappings.size());
3220b57cec5SDimitry Andric   APInt DefaultProcMask(ProcModelMap.size(), 0);
3230b57cec5SDimitry Andric   APInt DefaultPredMask(NumUniquePredicates, 0);
3240b57cec5SDimitry Andric   for (std::pair<APInt, APInt> &MaskPair : OpcodeMasks)
3250b57cec5SDimitry Andric     MaskPair = std::make_pair(DefaultProcMask, DefaultPredMask);
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   // Construct a OpcodeInfo object for every unique opcode declared by an
3280b57cec5SDimitry Andric   // InstructionEquivalenceClass definition.
3290b57cec5SDimitry Andric   for (const Record *Def : Fn.getDefinitions()) {
3300b57cec5SDimitry Andric     RecVec Classes = Def->getValueAsListOfDefs("Classes");
3310b57cec5SDimitry Andric     const Record *SchedModel = Def->getValueAsDef("SchedModel");
3320b57cec5SDimitry Andric     unsigned ProcIndex = ProcModelMap.find(SchedModel)->second;
3330b57cec5SDimitry Andric     APInt ProcMask(ProcModelMap.size(), 0);
3340b57cec5SDimitry Andric     ProcMask.setBit(ProcIndex);
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric     for (const Record *EC : Classes) {
3370b57cec5SDimitry Andric       RecVec Opcodes = EC->getValueAsListOfDefs("Opcodes");
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric       std::vector<int64_t> OpIndices =
3400b57cec5SDimitry Andric           EC->getValueAsListOfInts("OperandIndices");
3410b57cec5SDimitry Andric       APInt OperandMask = constructOperandMask(OpIndices);
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric       const Record *Pred = EC->getValueAsDef("Predicate");
3440b57cec5SDimitry Andric       APInt PredMask(NumUniquePredicates, 0);
3450b57cec5SDimitry Andric       PredMask.setBit(Predicate2Index[Pred]);
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric       for (const Record *Opcode : Opcodes) {
3480b57cec5SDimitry Andric         unsigned OpcodeIdx = Opcode2Index[Opcode];
3490b57cec5SDimitry Andric         if (OpcodeMasks[OpcodeIdx].first[ProcIndex]) {
3500b57cec5SDimitry Andric           std::string Message =
3510b57cec5SDimitry Andric               "Opcode " + Opcode->getName().str() +
3520b57cec5SDimitry Andric               " used by multiple InstructionEquivalenceClass definitions.";
3530b57cec5SDimitry Andric           PrintFatalError(EC->getLoc(), Message);
3540b57cec5SDimitry Andric         }
3550b57cec5SDimitry Andric         OpcodeMasks[OpcodeIdx].first |= ProcMask;
3560b57cec5SDimitry Andric         OpcodeMasks[OpcodeIdx].second |= PredMask;
3570b57cec5SDimitry Andric         OpcodeInfo &OI = OpcodeMappings[OpcodeIdx].second;
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric         OI.addPredicateForProcModel(ProcMask, OperandMask, Pred);
3600b57cec5SDimitry Andric       }
3610b57cec5SDimitry Andric     }
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   // Sort OpcodeMappings elements based on their CPU and predicate masks.
3650b57cec5SDimitry Andric   // As a last resort, order elements by opcode identifier.
3660b57cec5SDimitry Andric   llvm::sort(OpcodeMappings,
3670b57cec5SDimitry Andric              [&](const OpcodeMapPair &Lhs, const OpcodeMapPair &Rhs) {
3680b57cec5SDimitry Andric                unsigned LhsIdx = Opcode2Index[Lhs.first];
3690b57cec5SDimitry Andric                unsigned RhsIdx = Opcode2Index[Rhs.first];
3700b57cec5SDimitry Andric                const std::pair<APInt, APInt> &LhsMasks = OpcodeMasks[LhsIdx];
3710b57cec5SDimitry Andric                const std::pair<APInt, APInt> &RhsMasks = OpcodeMasks[RhsIdx];
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric                auto LessThan = [](const APInt &Lhs, const APInt &Rhs) {
3740b57cec5SDimitry Andric                  unsigned LhsCountPopulation = Lhs.countPopulation();
3750b57cec5SDimitry Andric                  unsigned RhsCountPopulation = Rhs.countPopulation();
3760b57cec5SDimitry Andric                  return ((LhsCountPopulation < RhsCountPopulation) ||
3770b57cec5SDimitry Andric                          ((LhsCountPopulation == RhsCountPopulation) &&
3780b57cec5SDimitry Andric                           (Lhs.countLeadingZeros() > Rhs.countLeadingZeros())));
3790b57cec5SDimitry Andric                };
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric                if (LhsMasks.first != RhsMasks.first)
3820b57cec5SDimitry Andric                  return LessThan(LhsMasks.first, RhsMasks.first);
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric                if (LhsMasks.second != RhsMasks.second)
3850b57cec5SDimitry Andric                  return LessThan(LhsMasks.second, RhsMasks.second);
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric                return LhsIdx < RhsIdx;
3880b57cec5SDimitry Andric              });
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   // Now construct opcode groups. Groups are used by the SubtargetEmitter when
3910b57cec5SDimitry Andric   // expanding the body of a STIPredicate function. In particular, each opcode
3920b57cec5SDimitry Andric   // group is expanded into a sequence of labels in a switch statement.
3930b57cec5SDimitry Andric   // It identifies opcodes for which different processors define same predicates
3940b57cec5SDimitry Andric   // and same opcode masks.
3950b57cec5SDimitry Andric   for (OpcodeMapPair &Info : OpcodeMappings)
3960b57cec5SDimitry Andric     Fn.addOpcode(Info.first, std::move(Info.second));
3970b57cec5SDimitry Andric }
3980b57cec5SDimitry Andric 
collectSTIPredicates()3990b57cec5SDimitry Andric void CodeGenSchedModels::collectSTIPredicates() {
4000b57cec5SDimitry Andric   // Map STIPredicateDecl records to elements of vector
4010b57cec5SDimitry Andric   // CodeGenSchedModels::STIPredicates.
4020b57cec5SDimitry Andric   DenseMap<const Record *, unsigned> Decl2Index;
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric   RecVec RV = Records.getAllDerivedDefinitions("STIPredicate");
4050b57cec5SDimitry Andric   for (const Record *R : RV) {
4060b57cec5SDimitry Andric     const Record *Decl = R->getValueAsDef("Declaration");
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric     const auto It = Decl2Index.find(Decl);
4090b57cec5SDimitry Andric     if (It == Decl2Index.end()) {
4100b57cec5SDimitry Andric       Decl2Index[Decl] = STIPredicates.size();
4110b57cec5SDimitry Andric       STIPredicateFunction Predicate(Decl);
4120b57cec5SDimitry Andric       Predicate.addDefinition(R);
4130b57cec5SDimitry Andric       STIPredicates.emplace_back(std::move(Predicate));
4140b57cec5SDimitry Andric       continue;
4150b57cec5SDimitry Andric     }
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric     STIPredicateFunction &PreviousDef = STIPredicates[It->second];
4180b57cec5SDimitry Andric     PreviousDef.addDefinition(R);
4190b57cec5SDimitry Andric   }
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   for (STIPredicateFunction &Fn : STIPredicates)
4220b57cec5SDimitry Andric     processSTIPredicate(Fn, ProcModelMap);
4230b57cec5SDimitry Andric }
4240b57cec5SDimitry Andric 
addPredicateForProcModel(const llvm::APInt & CpuMask,const llvm::APInt & OperandMask,const Record * Predicate)4250b57cec5SDimitry Andric void OpcodeInfo::addPredicateForProcModel(const llvm::APInt &CpuMask,
4260b57cec5SDimitry Andric                                           const llvm::APInt &OperandMask,
4270b57cec5SDimitry Andric                                           const Record *Predicate) {
4280b57cec5SDimitry Andric   auto It = llvm::find_if(
4290b57cec5SDimitry Andric       Predicates, [&OperandMask, &Predicate](const PredicateInfo &P) {
4300b57cec5SDimitry Andric         return P.Predicate == Predicate && P.OperandMask == OperandMask;
4310b57cec5SDimitry Andric       });
4320b57cec5SDimitry Andric   if (It == Predicates.end()) {
4330b57cec5SDimitry Andric     Predicates.emplace_back(CpuMask, OperandMask, Predicate);
4340b57cec5SDimitry Andric     return;
4350b57cec5SDimitry Andric   }
4360b57cec5SDimitry Andric   It->ProcModelMask |= CpuMask;
4370b57cec5SDimitry Andric }
4380b57cec5SDimitry Andric 
checkMCInstPredicates() const4390b57cec5SDimitry Andric void CodeGenSchedModels::checkMCInstPredicates() const {
4400b57cec5SDimitry Andric   RecVec MCPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
4410b57cec5SDimitry Andric   if (MCPredicates.empty())
4420b57cec5SDimitry Andric     return;
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   // A target cannot have multiple TIIPredicate definitions with a same name.
4450b57cec5SDimitry Andric   llvm::StringMap<const Record *> TIIPredicates(MCPredicates.size());
4460b57cec5SDimitry Andric   for (const Record *TIIPred : MCPredicates) {
4470b57cec5SDimitry Andric     StringRef Name = TIIPred->getValueAsString("FunctionName");
4480b57cec5SDimitry Andric     StringMap<const Record *>::const_iterator It = TIIPredicates.find(Name);
4490b57cec5SDimitry Andric     if (It == TIIPredicates.end()) {
4500b57cec5SDimitry Andric       TIIPredicates[Name] = TIIPred;
4510b57cec5SDimitry Andric       continue;
4520b57cec5SDimitry Andric     }
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric     PrintError(TIIPred->getLoc(),
4550b57cec5SDimitry Andric                "TIIPredicate " + Name + " is multiply defined.");
456af732203SDimitry Andric     PrintFatalNote(It->second->getLoc(),
4570b57cec5SDimitry Andric                    " Previous definition of " + Name + " was here.");
4580b57cec5SDimitry Andric   }
4590b57cec5SDimitry Andric }
4600b57cec5SDimitry Andric 
collectRetireControlUnits()4610b57cec5SDimitry Andric void CodeGenSchedModels::collectRetireControlUnits() {
4620b57cec5SDimitry Andric   RecVec Units = Records.getAllDerivedDefinitions("RetireControlUnit");
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   for (Record *RCU : Units) {
4650b57cec5SDimitry Andric     CodeGenProcModel &PM = getProcModel(RCU->getValueAsDef("SchedModel"));
4660b57cec5SDimitry Andric     if (PM.RetireControlUnit) {
4670b57cec5SDimitry Andric       PrintError(RCU->getLoc(),
4680b57cec5SDimitry Andric                  "Expected a single RetireControlUnit definition");
4690b57cec5SDimitry Andric       PrintNote(PM.RetireControlUnit->getLoc(),
4700b57cec5SDimitry Andric                 "Previous definition of RetireControlUnit was here");
4710b57cec5SDimitry Andric     }
4720b57cec5SDimitry Andric     PM.RetireControlUnit = RCU;
4730b57cec5SDimitry Andric   }
4740b57cec5SDimitry Andric }
4750b57cec5SDimitry Andric 
collectLoadStoreQueueInfo()4760b57cec5SDimitry Andric void CodeGenSchedModels::collectLoadStoreQueueInfo() {
4770b57cec5SDimitry Andric   RecVec Queues = Records.getAllDerivedDefinitions("MemoryQueue");
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   for (Record *Queue : Queues) {
4800b57cec5SDimitry Andric     CodeGenProcModel &PM = getProcModel(Queue->getValueAsDef("SchedModel"));
4810b57cec5SDimitry Andric     if (Queue->isSubClassOf("LoadQueue")) {
4820b57cec5SDimitry Andric       if (PM.LoadQueue) {
4830b57cec5SDimitry Andric         PrintError(Queue->getLoc(),
4840b57cec5SDimitry Andric                    "Expected a single LoadQueue definition");
4850b57cec5SDimitry Andric         PrintNote(PM.LoadQueue->getLoc(),
4860b57cec5SDimitry Andric                   "Previous definition of LoadQueue was here");
4870b57cec5SDimitry Andric       }
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric       PM.LoadQueue = Queue;
4900b57cec5SDimitry Andric     }
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric     if (Queue->isSubClassOf("StoreQueue")) {
4930b57cec5SDimitry Andric       if (PM.StoreQueue) {
4940b57cec5SDimitry Andric         PrintError(Queue->getLoc(),
4950b57cec5SDimitry Andric                    "Expected a single StoreQueue definition");
4960b57cec5SDimitry Andric         PrintNote(PM.LoadQueue->getLoc(),
4970b57cec5SDimitry Andric                   "Previous definition of StoreQueue was here");
4980b57cec5SDimitry Andric       }
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric       PM.StoreQueue = Queue;
5010b57cec5SDimitry Andric     }
5020b57cec5SDimitry Andric   }
5030b57cec5SDimitry Andric }
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric /// Collect optional processor information.
collectOptionalProcessorInfo()5060b57cec5SDimitry Andric void CodeGenSchedModels::collectOptionalProcessorInfo() {
5070b57cec5SDimitry Andric   // Find register file definitions for each processor.
5080b57cec5SDimitry Andric   collectRegisterFiles();
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric   // Collect processor RetireControlUnit descriptors if available.
5110b57cec5SDimitry Andric   collectRetireControlUnits();
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric   // Collect information about load/store queues.
5140b57cec5SDimitry Andric   collectLoadStoreQueueInfo();
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   checkCompleteness();
5170b57cec5SDimitry Andric }
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric /// Gather all processor models.
collectProcModels()5200b57cec5SDimitry Andric void CodeGenSchedModels::collectProcModels() {
5210b57cec5SDimitry Andric   RecVec ProcRecords = Records.getAllDerivedDefinitions("Processor");
5220b57cec5SDimitry Andric   llvm::sort(ProcRecords, LessRecordFieldName());
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   // Reserve space because we can. Reallocation would be ok.
5250b57cec5SDimitry Andric   ProcModels.reserve(ProcRecords.size()+1);
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric   // Use idx=0 for NoModel/NoItineraries.
5280b57cec5SDimitry Andric   Record *NoModelDef = Records.getDef("NoSchedModel");
5290b57cec5SDimitry Andric   Record *NoItinsDef = Records.getDef("NoItineraries");
5300b57cec5SDimitry Andric   ProcModels.emplace_back(0, "NoSchedModel", NoModelDef, NoItinsDef);
5310b57cec5SDimitry Andric   ProcModelMap[NoModelDef] = 0;
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric   // For each processor, find a unique machine model.
5340b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "+++ PROCESSOR MODELs (addProcModel) +++\n");
5350b57cec5SDimitry Andric   for (Record *ProcRecord : ProcRecords)
5360b57cec5SDimitry Andric     addProcModel(ProcRecord);
5370b57cec5SDimitry Andric }
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric /// Get a unique processor model based on the defined MachineModel and
5400b57cec5SDimitry Andric /// ProcessorItineraries.
addProcModel(Record * ProcDef)5410b57cec5SDimitry Andric void CodeGenSchedModels::addProcModel(Record *ProcDef) {
5420b57cec5SDimitry Andric   Record *ModelKey = getModelOrItinDef(ProcDef);
5430b57cec5SDimitry Andric   if (!ProcModelMap.insert(std::make_pair(ModelKey, ProcModels.size())).second)
5440b57cec5SDimitry Andric     return;
5450b57cec5SDimitry Andric 
5465ffd83dbSDimitry Andric   std::string Name = std::string(ModelKey->getName());
5470b57cec5SDimitry Andric   if (ModelKey->isSubClassOf("SchedMachineModel")) {
5480b57cec5SDimitry Andric     Record *ItinsDef = ModelKey->getValueAsDef("Itineraries");
5490b57cec5SDimitry Andric     ProcModels.emplace_back(ProcModels.size(), Name, ModelKey, ItinsDef);
5500b57cec5SDimitry Andric   }
5510b57cec5SDimitry Andric   else {
5520b57cec5SDimitry Andric     // An itinerary is defined without a machine model. Infer a new model.
5530b57cec5SDimitry Andric     if (!ModelKey->getValueAsListOfDefs("IID").empty())
5540b57cec5SDimitry Andric       Name = Name + "Model";
5550b57cec5SDimitry Andric     ProcModels.emplace_back(ProcModels.size(), Name,
5560b57cec5SDimitry Andric                             ProcDef->getValueAsDef("SchedModel"), ModelKey);
5570b57cec5SDimitry Andric   }
5580b57cec5SDimitry Andric   LLVM_DEBUG(ProcModels.back().dump());
5590b57cec5SDimitry Andric }
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric // Recursively find all reachable SchedReadWrite records.
scanSchedRW(Record * RWDef,RecVec & RWDefs,SmallPtrSet<Record *,16> & RWSet)5620b57cec5SDimitry Andric static void scanSchedRW(Record *RWDef, RecVec &RWDefs,
5630b57cec5SDimitry Andric                         SmallPtrSet<Record*, 16> &RWSet) {
5640b57cec5SDimitry Andric   if (!RWSet.insert(RWDef).second)
5650b57cec5SDimitry Andric     return;
5660b57cec5SDimitry Andric   RWDefs.push_back(RWDef);
5670b57cec5SDimitry Andric   // Reads don't currently have sequence records, but it can be added later.
5680b57cec5SDimitry Andric   if (RWDef->isSubClassOf("WriteSequence")) {
5690b57cec5SDimitry Andric     RecVec Seq = RWDef->getValueAsListOfDefs("Writes");
5700b57cec5SDimitry Andric     for (Record *WSRec : Seq)
5710b57cec5SDimitry Andric       scanSchedRW(WSRec, RWDefs, RWSet);
5720b57cec5SDimitry Andric   }
5730b57cec5SDimitry Andric   else if (RWDef->isSubClassOf("SchedVariant")) {
5740b57cec5SDimitry Andric     // Visit each variant (guarded by a different predicate).
5750b57cec5SDimitry Andric     RecVec Vars = RWDef->getValueAsListOfDefs("Variants");
5760b57cec5SDimitry Andric     for (Record *Variant : Vars) {
5770b57cec5SDimitry Andric       // Visit each RW in the sequence selected by the current variant.
5780b57cec5SDimitry Andric       RecVec Selected = Variant->getValueAsListOfDefs("Selected");
5790b57cec5SDimitry Andric       for (Record *SelDef : Selected)
5800b57cec5SDimitry Andric         scanSchedRW(SelDef, RWDefs, RWSet);
5810b57cec5SDimitry Andric     }
5820b57cec5SDimitry Andric   }
5830b57cec5SDimitry Andric }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric // Collect and sort all SchedReadWrites reachable via tablegen records.
5860b57cec5SDimitry Andric // More may be inferred later when inferring new SchedClasses from variants.
collectSchedRW()5870b57cec5SDimitry Andric void CodeGenSchedModels::collectSchedRW() {
5880b57cec5SDimitry Andric   // Reserve idx=0 for invalid writes/reads.
5890b57cec5SDimitry Andric   SchedWrites.resize(1);
5900b57cec5SDimitry Andric   SchedReads.resize(1);
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric   SmallPtrSet<Record*, 16> RWSet;
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   // Find all SchedReadWrites referenced by instruction defs.
5950b57cec5SDimitry Andric   RecVec SWDefs, SRDefs;
5960b57cec5SDimitry Andric   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
5970b57cec5SDimitry Andric     Record *SchedDef = Inst->TheDef;
5980b57cec5SDimitry Andric     if (SchedDef->isValueUnset("SchedRW"))
5990b57cec5SDimitry Andric       continue;
6000b57cec5SDimitry Andric     RecVec RWs = SchedDef->getValueAsListOfDefs("SchedRW");
6010b57cec5SDimitry Andric     for (Record *RW : RWs) {
6020b57cec5SDimitry Andric       if (RW->isSubClassOf("SchedWrite"))
6030b57cec5SDimitry Andric         scanSchedRW(RW, SWDefs, RWSet);
6040b57cec5SDimitry Andric       else {
6050b57cec5SDimitry Andric         assert(RW->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
6060b57cec5SDimitry Andric         scanSchedRW(RW, SRDefs, RWSet);
6070b57cec5SDimitry Andric       }
6080b57cec5SDimitry Andric     }
6090b57cec5SDimitry Andric   }
6100b57cec5SDimitry Andric   // Find all ReadWrites referenced by InstRW.
6110b57cec5SDimitry Andric   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
6120b57cec5SDimitry Andric   for (Record *InstRWDef : InstRWDefs) {
6130b57cec5SDimitry Andric     // For all OperandReadWrites.
6140b57cec5SDimitry Andric     RecVec RWDefs = InstRWDef->getValueAsListOfDefs("OperandReadWrites");
6150b57cec5SDimitry Andric     for (Record *RWDef : RWDefs) {
6160b57cec5SDimitry Andric       if (RWDef->isSubClassOf("SchedWrite"))
6170b57cec5SDimitry Andric         scanSchedRW(RWDef, SWDefs, RWSet);
6180b57cec5SDimitry Andric       else {
6190b57cec5SDimitry Andric         assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
6200b57cec5SDimitry Andric         scanSchedRW(RWDef, SRDefs, RWSet);
6210b57cec5SDimitry Andric       }
6220b57cec5SDimitry Andric     }
6230b57cec5SDimitry Andric   }
6240b57cec5SDimitry Andric   // Find all ReadWrites referenced by ItinRW.
6250b57cec5SDimitry Andric   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
6260b57cec5SDimitry Andric   for (Record *ItinRWDef : ItinRWDefs) {
6270b57cec5SDimitry Andric     // For all OperandReadWrites.
6280b57cec5SDimitry Andric     RecVec RWDefs = ItinRWDef->getValueAsListOfDefs("OperandReadWrites");
6290b57cec5SDimitry Andric     for (Record *RWDef : RWDefs) {
6300b57cec5SDimitry Andric       if (RWDef->isSubClassOf("SchedWrite"))
6310b57cec5SDimitry Andric         scanSchedRW(RWDef, SWDefs, RWSet);
6320b57cec5SDimitry Andric       else {
6330b57cec5SDimitry Andric         assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
6340b57cec5SDimitry Andric         scanSchedRW(RWDef, SRDefs, RWSet);
6350b57cec5SDimitry Andric       }
6360b57cec5SDimitry Andric     }
6370b57cec5SDimitry Andric   }
6380b57cec5SDimitry Andric   // Find all ReadWrites referenced by SchedAlias. AliasDefs needs to be sorted
6390b57cec5SDimitry Andric   // for the loop below that initializes Alias vectors.
6400b57cec5SDimitry Andric   RecVec AliasDefs = Records.getAllDerivedDefinitions("SchedAlias");
6410b57cec5SDimitry Andric   llvm::sort(AliasDefs, LessRecord());
6420b57cec5SDimitry Andric   for (Record *ADef : AliasDefs) {
6430b57cec5SDimitry Andric     Record *MatchDef = ADef->getValueAsDef("MatchRW");
6440b57cec5SDimitry Andric     Record *AliasDef = ADef->getValueAsDef("AliasRW");
6450b57cec5SDimitry Andric     if (MatchDef->isSubClassOf("SchedWrite")) {
6460b57cec5SDimitry Andric       if (!AliasDef->isSubClassOf("SchedWrite"))
6470b57cec5SDimitry Andric         PrintFatalError(ADef->getLoc(), "SchedWrite Alias must be SchedWrite");
6480b57cec5SDimitry Andric       scanSchedRW(AliasDef, SWDefs, RWSet);
6490b57cec5SDimitry Andric     }
6500b57cec5SDimitry Andric     else {
6510b57cec5SDimitry Andric       assert(MatchDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
6520b57cec5SDimitry Andric       if (!AliasDef->isSubClassOf("SchedRead"))
6530b57cec5SDimitry Andric         PrintFatalError(ADef->getLoc(), "SchedRead Alias must be SchedRead");
6540b57cec5SDimitry Andric       scanSchedRW(AliasDef, SRDefs, RWSet);
6550b57cec5SDimitry Andric     }
6560b57cec5SDimitry Andric   }
6570b57cec5SDimitry Andric   // Sort and add the SchedReadWrites directly referenced by instructions or
6580b57cec5SDimitry Andric   // itinerary resources. Index reads and writes in separate domains.
6590b57cec5SDimitry Andric   llvm::sort(SWDefs, LessRecord());
6600b57cec5SDimitry Andric   for (Record *SWDef : SWDefs) {
6610b57cec5SDimitry Andric     assert(!getSchedRWIdx(SWDef, /*IsRead=*/false) && "duplicate SchedWrite");
6620b57cec5SDimitry Andric     SchedWrites.emplace_back(SchedWrites.size(), SWDef);
6630b57cec5SDimitry Andric   }
6640b57cec5SDimitry Andric   llvm::sort(SRDefs, LessRecord());
6650b57cec5SDimitry Andric   for (Record *SRDef : SRDefs) {
6660b57cec5SDimitry Andric     assert(!getSchedRWIdx(SRDef, /*IsRead-*/true) && "duplicate SchedWrite");
6670b57cec5SDimitry Andric     SchedReads.emplace_back(SchedReads.size(), SRDef);
6680b57cec5SDimitry Andric   }
6690b57cec5SDimitry Andric   // Initialize WriteSequence vectors.
6700b57cec5SDimitry Andric   for (CodeGenSchedRW &CGRW : SchedWrites) {
6710b57cec5SDimitry Andric     if (!CGRW.IsSequence)
6720b57cec5SDimitry Andric       continue;
6730b57cec5SDimitry Andric     findRWs(CGRW.TheDef->getValueAsListOfDefs("Writes"), CGRW.Sequence,
6740b57cec5SDimitry Andric             /*IsRead=*/false);
6750b57cec5SDimitry Andric   }
6760b57cec5SDimitry Andric   // Initialize Aliases vectors.
6770b57cec5SDimitry Andric   for (Record *ADef : AliasDefs) {
6780b57cec5SDimitry Andric     Record *AliasDef = ADef->getValueAsDef("AliasRW");
6790b57cec5SDimitry Andric     getSchedRW(AliasDef).IsAlias = true;
6800b57cec5SDimitry Andric     Record *MatchDef = ADef->getValueAsDef("MatchRW");
6810b57cec5SDimitry Andric     CodeGenSchedRW &RW = getSchedRW(MatchDef);
6820b57cec5SDimitry Andric     if (RW.IsAlias)
6830b57cec5SDimitry Andric       PrintFatalError(ADef->getLoc(), "Cannot Alias an Alias");
6840b57cec5SDimitry Andric     RW.Aliases.push_back(ADef);
6850b57cec5SDimitry Andric   }
6860b57cec5SDimitry Andric   LLVM_DEBUG(
6870b57cec5SDimitry Andric       dbgs() << "\n+++ SCHED READS and WRITES (collectSchedRW) +++\n";
6880b57cec5SDimitry Andric       for (unsigned WIdx = 0, WEnd = SchedWrites.size(); WIdx != WEnd; ++WIdx) {
6890b57cec5SDimitry Andric         dbgs() << WIdx << ": ";
6900b57cec5SDimitry Andric         SchedWrites[WIdx].dump();
6910b57cec5SDimitry Andric         dbgs() << '\n';
6920b57cec5SDimitry Andric       } for (unsigned RIdx = 0, REnd = SchedReads.size(); RIdx != REnd;
6930b57cec5SDimitry Andric              ++RIdx) {
6940b57cec5SDimitry Andric         dbgs() << RIdx << ": ";
6950b57cec5SDimitry Andric         SchedReads[RIdx].dump();
6960b57cec5SDimitry Andric         dbgs() << '\n';
6970b57cec5SDimitry Andric       } RecVec RWDefs = Records.getAllDerivedDefinitions("SchedReadWrite");
6980b57cec5SDimitry Andric       for (Record *RWDef
6990b57cec5SDimitry Andric            : RWDefs) {
7000b57cec5SDimitry Andric         if (!getSchedRWIdx(RWDef, RWDef->isSubClassOf("SchedRead"))) {
7010b57cec5SDimitry Andric           StringRef Name = RWDef->getName();
7020b57cec5SDimitry Andric           if (Name != "NoWrite" && Name != "ReadDefault")
7030b57cec5SDimitry Andric             dbgs() << "Unused SchedReadWrite " << Name << '\n';
7040b57cec5SDimitry Andric         }
7050b57cec5SDimitry Andric       });
7060b57cec5SDimitry Andric }
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric /// Compute a SchedWrite name from a sequence of writes.
genRWName(ArrayRef<unsigned> Seq,bool IsRead)7090b57cec5SDimitry Andric std::string CodeGenSchedModels::genRWName(ArrayRef<unsigned> Seq, bool IsRead) {
7100b57cec5SDimitry Andric   std::string Name("(");
711*5f7ddb14SDimitry Andric   ListSeparator LS("_");
712*5f7ddb14SDimitry Andric   for (unsigned I : Seq) {
713*5f7ddb14SDimitry Andric     Name += LS;
714*5f7ddb14SDimitry Andric     Name += getSchedRW(I, IsRead).Name;
7150b57cec5SDimitry Andric   }
7160b57cec5SDimitry Andric   Name += ')';
7170b57cec5SDimitry Andric   return Name;
7180b57cec5SDimitry Andric }
7190b57cec5SDimitry Andric 
getSchedRWIdx(const Record * Def,bool IsRead) const7200b57cec5SDimitry Andric unsigned CodeGenSchedModels::getSchedRWIdx(const Record *Def,
7210b57cec5SDimitry Andric                                            bool IsRead) const {
7220b57cec5SDimitry Andric   const std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
7230b57cec5SDimitry Andric   const auto I = find_if(
7240b57cec5SDimitry Andric       RWVec, [Def](const CodeGenSchedRW &RW) { return RW.TheDef == Def; });
7250b57cec5SDimitry Andric   return I == RWVec.end() ? 0 : std::distance(RWVec.begin(), I);
7260b57cec5SDimitry Andric }
7270b57cec5SDimitry Andric 
hasReadOfWrite(Record * WriteDef) const7280b57cec5SDimitry Andric bool CodeGenSchedModels::hasReadOfWrite(Record *WriteDef) const {
7290b57cec5SDimitry Andric   for (const CodeGenSchedRW &Read : SchedReads) {
7300b57cec5SDimitry Andric     Record *ReadDef = Read.TheDef;
7310b57cec5SDimitry Andric     if (!ReadDef || !ReadDef->isSubClassOf("ProcReadAdvance"))
7320b57cec5SDimitry Andric       continue;
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric     RecVec ValidWrites = ReadDef->getValueAsListOfDefs("ValidWrites");
7350b57cec5SDimitry Andric     if (is_contained(ValidWrites, WriteDef)) {
7360b57cec5SDimitry Andric       return true;
7370b57cec5SDimitry Andric     }
7380b57cec5SDimitry Andric   }
7390b57cec5SDimitry Andric   return false;
7400b57cec5SDimitry Andric }
7410b57cec5SDimitry Andric 
splitSchedReadWrites(const RecVec & RWDefs,RecVec & WriteDefs,RecVec & ReadDefs)7420b57cec5SDimitry Andric static void splitSchedReadWrites(const RecVec &RWDefs,
7430b57cec5SDimitry Andric                                  RecVec &WriteDefs, RecVec &ReadDefs) {
7440b57cec5SDimitry Andric   for (Record *RWDef : RWDefs) {
7450b57cec5SDimitry Andric     if (RWDef->isSubClassOf("SchedWrite"))
7460b57cec5SDimitry Andric       WriteDefs.push_back(RWDef);
7470b57cec5SDimitry Andric     else {
7480b57cec5SDimitry Andric       assert(RWDef->isSubClassOf("SchedRead") && "unknown SchedReadWrite");
7490b57cec5SDimitry Andric       ReadDefs.push_back(RWDef);
7500b57cec5SDimitry Andric     }
7510b57cec5SDimitry Andric   }
7520b57cec5SDimitry Andric }
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric // Split the SchedReadWrites defs and call findRWs for each list.
findRWs(const RecVec & RWDefs,IdxVec & Writes,IdxVec & Reads) const7550b57cec5SDimitry Andric void CodeGenSchedModels::findRWs(const RecVec &RWDefs,
7560b57cec5SDimitry Andric                                  IdxVec &Writes, IdxVec &Reads) const {
7570b57cec5SDimitry Andric   RecVec WriteDefs;
7580b57cec5SDimitry Andric   RecVec ReadDefs;
7590b57cec5SDimitry Andric   splitSchedReadWrites(RWDefs, WriteDefs, ReadDefs);
7600b57cec5SDimitry Andric   findRWs(WriteDefs, Writes, false);
7610b57cec5SDimitry Andric   findRWs(ReadDefs, Reads, true);
7620b57cec5SDimitry Andric }
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric // Call getSchedRWIdx for all elements in a sequence of SchedRW defs.
findRWs(const RecVec & RWDefs,IdxVec & RWs,bool IsRead) const7650b57cec5SDimitry Andric void CodeGenSchedModels::findRWs(const RecVec &RWDefs, IdxVec &RWs,
7660b57cec5SDimitry Andric                                  bool IsRead) const {
7670b57cec5SDimitry Andric   for (Record *RWDef : RWDefs) {
7680b57cec5SDimitry Andric     unsigned Idx = getSchedRWIdx(RWDef, IsRead);
7690b57cec5SDimitry Andric     assert(Idx && "failed to collect SchedReadWrite");
7700b57cec5SDimitry Andric     RWs.push_back(Idx);
7710b57cec5SDimitry Andric   }
7720b57cec5SDimitry Andric }
7730b57cec5SDimitry Andric 
expandRWSequence(unsigned RWIdx,IdxVec & RWSeq,bool IsRead) const7740b57cec5SDimitry Andric void CodeGenSchedModels::expandRWSequence(unsigned RWIdx, IdxVec &RWSeq,
7750b57cec5SDimitry Andric                                           bool IsRead) const {
7760b57cec5SDimitry Andric   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
7770b57cec5SDimitry Andric   if (!SchedRW.IsSequence) {
7780b57cec5SDimitry Andric     RWSeq.push_back(RWIdx);
7790b57cec5SDimitry Andric     return;
7800b57cec5SDimitry Andric   }
7810b57cec5SDimitry Andric   int Repeat =
7820b57cec5SDimitry Andric     SchedRW.TheDef ? SchedRW.TheDef->getValueAsInt("Repeat") : 1;
7830b57cec5SDimitry Andric   for (int i = 0; i < Repeat; ++i) {
7840b57cec5SDimitry Andric     for (unsigned I : SchedRW.Sequence) {
7850b57cec5SDimitry Andric       expandRWSequence(I, RWSeq, IsRead);
7860b57cec5SDimitry Andric     }
7870b57cec5SDimitry Andric   }
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric // Expand a SchedWrite as a sequence following any aliases that coincide with
7910b57cec5SDimitry Andric // the given processor model.
expandRWSeqForProc(unsigned RWIdx,IdxVec & RWSeq,bool IsRead,const CodeGenProcModel & ProcModel) const7920b57cec5SDimitry Andric void CodeGenSchedModels::expandRWSeqForProc(
7930b57cec5SDimitry Andric   unsigned RWIdx, IdxVec &RWSeq, bool IsRead,
7940b57cec5SDimitry Andric   const CodeGenProcModel &ProcModel) const {
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric   const CodeGenSchedRW &SchedWrite = getSchedRW(RWIdx, IsRead);
7970b57cec5SDimitry Andric   Record *AliasDef = nullptr;
7980b57cec5SDimitry Andric   for (const Record *Rec : SchedWrite.Aliases) {
7990b57cec5SDimitry Andric     const CodeGenSchedRW &AliasRW = getSchedRW(Rec->getValueAsDef("AliasRW"));
8000b57cec5SDimitry Andric     if (Rec->getValueInit("SchedModel")->isComplete()) {
8010b57cec5SDimitry Andric       Record *ModelDef = Rec->getValueAsDef("SchedModel");
8020b57cec5SDimitry Andric       if (&getProcModel(ModelDef) != &ProcModel)
8030b57cec5SDimitry Andric         continue;
8040b57cec5SDimitry Andric     }
8050b57cec5SDimitry Andric     if (AliasDef)
8060b57cec5SDimitry Andric       PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
8070b57cec5SDimitry Andric                       "defined for processor " + ProcModel.ModelName +
8080b57cec5SDimitry Andric                       " Ensure only one SchedAlias exists per RW.");
8090b57cec5SDimitry Andric     AliasDef = AliasRW.TheDef;
8100b57cec5SDimitry Andric   }
8110b57cec5SDimitry Andric   if (AliasDef) {
8120b57cec5SDimitry Andric     expandRWSeqForProc(getSchedRWIdx(AliasDef, IsRead),
8130b57cec5SDimitry Andric                        RWSeq, IsRead,ProcModel);
8140b57cec5SDimitry Andric     return;
8150b57cec5SDimitry Andric   }
8160b57cec5SDimitry Andric   if (!SchedWrite.IsSequence) {
8170b57cec5SDimitry Andric     RWSeq.push_back(RWIdx);
8180b57cec5SDimitry Andric     return;
8190b57cec5SDimitry Andric   }
8200b57cec5SDimitry Andric   int Repeat =
8210b57cec5SDimitry Andric     SchedWrite.TheDef ? SchedWrite.TheDef->getValueAsInt("Repeat") : 1;
8220b57cec5SDimitry Andric   for (int I = 0, E = Repeat; I < E; ++I) {
8230b57cec5SDimitry Andric     for (unsigned Idx : SchedWrite.Sequence) {
8240b57cec5SDimitry Andric       expandRWSeqForProc(Idx, RWSeq, IsRead, ProcModel);
8250b57cec5SDimitry Andric     }
8260b57cec5SDimitry Andric   }
8270b57cec5SDimitry Andric }
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric // Find the existing SchedWrite that models this sequence of writes.
findRWForSequence(ArrayRef<unsigned> Seq,bool IsRead)8300b57cec5SDimitry Andric unsigned CodeGenSchedModels::findRWForSequence(ArrayRef<unsigned> Seq,
8310b57cec5SDimitry Andric                                                bool IsRead) {
8320b57cec5SDimitry Andric   std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   auto I = find_if(RWVec, [Seq](CodeGenSchedRW &RW) {
8350b57cec5SDimitry Andric     return makeArrayRef(RW.Sequence) == Seq;
8360b57cec5SDimitry Andric   });
8370b57cec5SDimitry Andric   // Index zero reserved for invalid RW.
8380b57cec5SDimitry Andric   return I == RWVec.end() ? 0 : std::distance(RWVec.begin(), I);
8390b57cec5SDimitry Andric }
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric /// Add this ReadWrite if it doesn't already exist.
findOrInsertRW(ArrayRef<unsigned> Seq,bool IsRead)8420b57cec5SDimitry Andric unsigned CodeGenSchedModels::findOrInsertRW(ArrayRef<unsigned> Seq,
8430b57cec5SDimitry Andric                                             bool IsRead) {
8440b57cec5SDimitry Andric   assert(!Seq.empty() && "cannot insert empty sequence");
8450b57cec5SDimitry Andric   if (Seq.size() == 1)
8460b57cec5SDimitry Andric     return Seq.back();
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   unsigned Idx = findRWForSequence(Seq, IsRead);
8490b57cec5SDimitry Andric   if (Idx)
8500b57cec5SDimitry Andric     return Idx;
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric   std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
8530b57cec5SDimitry Andric   unsigned RWIdx = RWVec.size();
8540b57cec5SDimitry Andric   CodeGenSchedRW SchedRW(RWIdx, IsRead, Seq, genRWName(Seq, IsRead));
8550b57cec5SDimitry Andric   RWVec.push_back(SchedRW);
8560b57cec5SDimitry Andric   return RWIdx;
8570b57cec5SDimitry Andric }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric /// Visit all the instruction definitions for this target to gather and
8600b57cec5SDimitry Andric /// enumerate the itinerary classes. These are the explicitly specified
8610b57cec5SDimitry Andric /// SchedClasses. More SchedClasses may be inferred.
collectSchedClasses()8620b57cec5SDimitry Andric void CodeGenSchedModels::collectSchedClasses() {
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   // NoItinerary is always the first class at Idx=0
8650b57cec5SDimitry Andric   assert(SchedClasses.empty() && "Expected empty sched class");
8660b57cec5SDimitry Andric   SchedClasses.emplace_back(0, "NoInstrModel",
8670b57cec5SDimitry Andric                             Records.getDef("NoItinerary"));
8680b57cec5SDimitry Andric   SchedClasses.back().ProcIndices.push_back(0);
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric   // Create a SchedClass for each unique combination of itinerary class and
8710b57cec5SDimitry Andric   // SchedRW list.
8720b57cec5SDimitry Andric   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
8730b57cec5SDimitry Andric     Record *ItinDef = Inst->TheDef->getValueAsDef("Itinerary");
8740b57cec5SDimitry Andric     IdxVec Writes, Reads;
8750b57cec5SDimitry Andric     if (!Inst->TheDef->isValueUnset("SchedRW"))
8760b57cec5SDimitry Andric       findRWs(Inst->TheDef->getValueAsListOfDefs("SchedRW"), Writes, Reads);
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric     // ProcIdx == 0 indicates the class applies to all processors.
8790b57cec5SDimitry Andric     unsigned SCIdx = addSchedClass(ItinDef, Writes, Reads, /*ProcIndices*/{0});
8800b57cec5SDimitry Andric     InstrClassMap[Inst->TheDef] = SCIdx;
8810b57cec5SDimitry Andric   }
8820b57cec5SDimitry Andric   // Create classes for InstRW defs.
8830b57cec5SDimitry Andric   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
8840b57cec5SDimitry Andric   llvm::sort(InstRWDefs, LessRecord());
8850b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n+++ SCHED CLASSES (createInstRWClass) +++\n");
8860b57cec5SDimitry Andric   for (Record *RWDef : InstRWDefs)
8870b57cec5SDimitry Andric     createInstRWClass(RWDef);
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   NumInstrSchedClasses = SchedClasses.size();
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric   bool EnableDump = false;
8920b57cec5SDimitry Andric   LLVM_DEBUG(EnableDump = true);
8930b57cec5SDimitry Andric   if (!EnableDump)
8940b57cec5SDimitry Andric     return;
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric   LLVM_DEBUG(
8970b57cec5SDimitry Andric       dbgs()
8980b57cec5SDimitry Andric       << "\n+++ ITINERARIES and/or MACHINE MODELS (collectSchedClasses) +++\n");
8990b57cec5SDimitry Andric   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
9000b57cec5SDimitry Andric     StringRef InstName = Inst->TheDef->getName();
9010b57cec5SDimitry Andric     unsigned SCIdx = getSchedClassIdx(*Inst);
9020b57cec5SDimitry Andric     if (!SCIdx) {
9030b57cec5SDimitry Andric       LLVM_DEBUG({
9040b57cec5SDimitry Andric         if (!Inst->hasNoSchedulingInfo)
9050b57cec5SDimitry Andric           dbgs() << "No machine model for " << Inst->TheDef->getName() << '\n';
9060b57cec5SDimitry Andric       });
9070b57cec5SDimitry Andric       continue;
9080b57cec5SDimitry Andric     }
9090b57cec5SDimitry Andric     CodeGenSchedClass &SC = getSchedClass(SCIdx);
9100b57cec5SDimitry Andric     if (SC.ProcIndices[0] != 0)
9110b57cec5SDimitry Andric       PrintFatalError(Inst->TheDef->getLoc(), "Instruction's sched class "
9120b57cec5SDimitry Andric                       "must not be subtarget specific.");
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric     IdxVec ProcIndices;
9150b57cec5SDimitry Andric     if (SC.ItinClassDef->getName() != "NoItinerary") {
9160b57cec5SDimitry Andric       ProcIndices.push_back(0);
9170b57cec5SDimitry Andric       dbgs() << "Itinerary for " << InstName << ": "
9180b57cec5SDimitry Andric              << SC.ItinClassDef->getName() << '\n';
9190b57cec5SDimitry Andric     }
9200b57cec5SDimitry Andric     if (!SC.Writes.empty()) {
9210b57cec5SDimitry Andric       ProcIndices.push_back(0);
9220b57cec5SDimitry Andric       LLVM_DEBUG({
9230b57cec5SDimitry Andric         dbgs() << "SchedRW machine model for " << InstName;
924*5f7ddb14SDimitry Andric         for (unsigned int Write : SC.Writes)
925*5f7ddb14SDimitry Andric           dbgs() << " " << SchedWrites[Write].Name;
926*5f7ddb14SDimitry Andric         for (unsigned int Read : SC.Reads)
927*5f7ddb14SDimitry Andric           dbgs() << " " << SchedReads[Read].Name;
9280b57cec5SDimitry Andric         dbgs() << '\n';
9290b57cec5SDimitry Andric       });
9300b57cec5SDimitry Andric     }
9310b57cec5SDimitry Andric     const RecVec &RWDefs = SchedClasses[SCIdx].InstRWs;
9320b57cec5SDimitry Andric     for (Record *RWDef : RWDefs) {
9330b57cec5SDimitry Andric       const CodeGenProcModel &ProcModel =
9340b57cec5SDimitry Andric           getProcModel(RWDef->getValueAsDef("SchedModel"));
9350b57cec5SDimitry Andric       ProcIndices.push_back(ProcModel.Index);
9360b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "InstRW on " << ProcModel.ModelName << " for "
9370b57cec5SDimitry Andric                         << InstName);
9380b57cec5SDimitry Andric       IdxVec Writes;
9390b57cec5SDimitry Andric       IdxVec Reads;
9400b57cec5SDimitry Andric       findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
9410b57cec5SDimitry Andric               Writes, Reads);
9420b57cec5SDimitry Andric       LLVM_DEBUG({
9430b57cec5SDimitry Andric         for (unsigned WIdx : Writes)
9440b57cec5SDimitry Andric           dbgs() << " " << SchedWrites[WIdx].Name;
9450b57cec5SDimitry Andric         for (unsigned RIdx : Reads)
9460b57cec5SDimitry Andric           dbgs() << " " << SchedReads[RIdx].Name;
9470b57cec5SDimitry Andric         dbgs() << '\n';
9480b57cec5SDimitry Andric       });
9490b57cec5SDimitry Andric     }
9500b57cec5SDimitry Andric     // If ProcIndices contains zero, the class applies to all processors.
9510b57cec5SDimitry Andric     LLVM_DEBUG({
952af732203SDimitry Andric       if (!llvm::is_contained(ProcIndices, 0)) {
9530b57cec5SDimitry Andric         for (const CodeGenProcModel &PM : ProcModels) {
954af732203SDimitry Andric           if (!llvm::is_contained(ProcIndices, PM.Index))
9550b57cec5SDimitry Andric             dbgs() << "No machine model for " << Inst->TheDef->getName()
9560b57cec5SDimitry Andric                    << " on processor " << PM.ModelName << '\n';
9570b57cec5SDimitry Andric         }
9580b57cec5SDimitry Andric       }
9590b57cec5SDimitry Andric     });
9600b57cec5SDimitry Andric   }
9610b57cec5SDimitry Andric }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric // Get the SchedClass index for an instruction.
9640b57cec5SDimitry Andric unsigned
getSchedClassIdx(const CodeGenInstruction & Inst) const9650b57cec5SDimitry Andric CodeGenSchedModels::getSchedClassIdx(const CodeGenInstruction &Inst) const {
9660b57cec5SDimitry Andric   return InstrClassMap.lookup(Inst.TheDef);
9670b57cec5SDimitry Andric }
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric std::string
createSchedClassName(Record * ItinClassDef,ArrayRef<unsigned> OperWrites,ArrayRef<unsigned> OperReads)9700b57cec5SDimitry Andric CodeGenSchedModels::createSchedClassName(Record *ItinClassDef,
9710b57cec5SDimitry Andric                                          ArrayRef<unsigned> OperWrites,
9720b57cec5SDimitry Andric                                          ArrayRef<unsigned> OperReads) {
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric   std::string Name;
9750b57cec5SDimitry Andric   if (ItinClassDef && ItinClassDef->getName() != "NoItinerary")
9765ffd83dbSDimitry Andric     Name = std::string(ItinClassDef->getName());
9770b57cec5SDimitry Andric   for (unsigned Idx : OperWrites) {
9780b57cec5SDimitry Andric     if (!Name.empty())
9790b57cec5SDimitry Andric       Name += '_';
9800b57cec5SDimitry Andric     Name += SchedWrites[Idx].Name;
9810b57cec5SDimitry Andric   }
9820b57cec5SDimitry Andric   for (unsigned Idx : OperReads) {
9830b57cec5SDimitry Andric     Name += '_';
9840b57cec5SDimitry Andric     Name += SchedReads[Idx].Name;
9850b57cec5SDimitry Andric   }
9860b57cec5SDimitry Andric   return Name;
9870b57cec5SDimitry Andric }
9880b57cec5SDimitry Andric 
createSchedClassName(const RecVec & InstDefs)9890b57cec5SDimitry Andric std::string CodeGenSchedModels::createSchedClassName(const RecVec &InstDefs) {
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric   std::string Name;
992*5f7ddb14SDimitry Andric   ListSeparator LS("_");
993*5f7ddb14SDimitry Andric   for (const Record *InstDef : InstDefs) {
994*5f7ddb14SDimitry Andric     Name += LS;
995*5f7ddb14SDimitry Andric     Name += InstDef->getName();
9960b57cec5SDimitry Andric   }
9970b57cec5SDimitry Andric   return Name;
9980b57cec5SDimitry Andric }
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric /// Add an inferred sched class from an itinerary class and per-operand list of
10010b57cec5SDimitry Andric /// SchedWrites and SchedReads. ProcIndices contains the set of IDs of
10020b57cec5SDimitry Andric /// processors that may utilize this class.
addSchedClass(Record * ItinClassDef,ArrayRef<unsigned> OperWrites,ArrayRef<unsigned> OperReads,ArrayRef<unsigned> ProcIndices)10030b57cec5SDimitry Andric unsigned CodeGenSchedModels::addSchedClass(Record *ItinClassDef,
10040b57cec5SDimitry Andric                                            ArrayRef<unsigned> OperWrites,
10050b57cec5SDimitry Andric                                            ArrayRef<unsigned> OperReads,
10060b57cec5SDimitry Andric                                            ArrayRef<unsigned> ProcIndices) {
10070b57cec5SDimitry Andric   assert(!ProcIndices.empty() && "expect at least one ProcIdx");
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   auto IsKeyEqual = [=](const CodeGenSchedClass &SC) {
10100b57cec5SDimitry Andric                      return SC.isKeyEqual(ItinClassDef, OperWrites, OperReads);
10110b57cec5SDimitry Andric                    };
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric   auto I = find_if(make_range(schedClassBegin(), schedClassEnd()), IsKeyEqual);
10140b57cec5SDimitry Andric   unsigned Idx = I == schedClassEnd() ? 0 : std::distance(schedClassBegin(), I);
10150b57cec5SDimitry Andric   if (Idx || SchedClasses[0].isKeyEqual(ItinClassDef, OperWrites, OperReads)) {
10160b57cec5SDimitry Andric     IdxVec PI;
10170b57cec5SDimitry Andric     std::set_union(SchedClasses[Idx].ProcIndices.begin(),
10180b57cec5SDimitry Andric                    SchedClasses[Idx].ProcIndices.end(),
10190b57cec5SDimitry Andric                    ProcIndices.begin(), ProcIndices.end(),
10200b57cec5SDimitry Andric                    std::back_inserter(PI));
10210b57cec5SDimitry Andric     SchedClasses[Idx].ProcIndices = std::move(PI);
10220b57cec5SDimitry Andric     return Idx;
10230b57cec5SDimitry Andric   }
10240b57cec5SDimitry Andric   Idx = SchedClasses.size();
10250b57cec5SDimitry Andric   SchedClasses.emplace_back(Idx,
10260b57cec5SDimitry Andric                             createSchedClassName(ItinClassDef, OperWrites,
10270b57cec5SDimitry Andric                                                  OperReads),
10280b57cec5SDimitry Andric                             ItinClassDef);
10290b57cec5SDimitry Andric   CodeGenSchedClass &SC = SchedClasses.back();
10300b57cec5SDimitry Andric   SC.Writes = OperWrites;
10310b57cec5SDimitry Andric   SC.Reads = OperReads;
10320b57cec5SDimitry Andric   SC.ProcIndices = ProcIndices;
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric   return Idx;
10350b57cec5SDimitry Andric }
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric // Create classes for each set of opcodes that are in the same InstReadWrite
10380b57cec5SDimitry Andric // definition across all processors.
createInstRWClass(Record * InstRWDef)10390b57cec5SDimitry Andric void CodeGenSchedModels::createInstRWClass(Record *InstRWDef) {
10400b57cec5SDimitry Andric   // ClassInstrs will hold an entry for each subset of Instrs in InstRWDef that
10410b57cec5SDimitry Andric   // intersects with an existing class via a previous InstRWDef. Instrs that do
10420b57cec5SDimitry Andric   // not intersect with an existing class refer back to their former class as
10430b57cec5SDimitry Andric   // determined from ItinDef or SchedRW.
10440b57cec5SDimitry Andric   SmallMapVector<unsigned, SmallVector<Record *, 8>, 4> ClassInstrs;
10450b57cec5SDimitry Andric   // Sort Instrs into sets.
10460b57cec5SDimitry Andric   const RecVec *InstDefs = Sets.expand(InstRWDef);
10470b57cec5SDimitry Andric   if (InstDefs->empty())
10480b57cec5SDimitry Andric     PrintFatalError(InstRWDef->getLoc(), "No matching instruction opcodes");
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric   for (Record *InstDef : *InstDefs) {
10510b57cec5SDimitry Andric     InstClassMapTy::const_iterator Pos = InstrClassMap.find(InstDef);
10520b57cec5SDimitry Andric     if (Pos == InstrClassMap.end())
10530b57cec5SDimitry Andric       PrintFatalError(InstDef->getLoc(), "No sched class for instruction.");
10540b57cec5SDimitry Andric     unsigned SCIdx = Pos->second;
10550b57cec5SDimitry Andric     ClassInstrs[SCIdx].push_back(InstDef);
10560b57cec5SDimitry Andric   }
10570b57cec5SDimitry Andric   // For each set of Instrs, create a new class if necessary, and map or remap
10580b57cec5SDimitry Andric   // the Instrs to it.
10590b57cec5SDimitry Andric   for (auto &Entry : ClassInstrs) {
10600b57cec5SDimitry Andric     unsigned OldSCIdx = Entry.first;
10610b57cec5SDimitry Andric     ArrayRef<Record*> InstDefs = Entry.second;
10620b57cec5SDimitry Andric     // If the all instrs in the current class are accounted for, then leave
10630b57cec5SDimitry Andric     // them mapped to their old class.
10640b57cec5SDimitry Andric     if (OldSCIdx) {
10650b57cec5SDimitry Andric       const RecVec &RWDefs = SchedClasses[OldSCIdx].InstRWs;
10660b57cec5SDimitry Andric       if (!RWDefs.empty()) {
10670b57cec5SDimitry Andric         const RecVec *OrigInstDefs = Sets.expand(RWDefs[0]);
10680b57cec5SDimitry Andric         unsigned OrigNumInstrs =
10690b57cec5SDimitry Andric           count_if(*OrigInstDefs, [&](Record *OIDef) {
10700b57cec5SDimitry Andric                      return InstrClassMap[OIDef] == OldSCIdx;
10710b57cec5SDimitry Andric                    });
10720b57cec5SDimitry Andric         if (OrigNumInstrs == InstDefs.size()) {
10730b57cec5SDimitry Andric           assert(SchedClasses[OldSCIdx].ProcIndices[0] == 0 &&
10740b57cec5SDimitry Andric                  "expected a generic SchedClass");
10750b57cec5SDimitry Andric           Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
10760b57cec5SDimitry Andric           // Make sure we didn't already have a InstRW containing this
10770b57cec5SDimitry Andric           // instruction on this model.
10780b57cec5SDimitry Andric           for (Record *RWD : RWDefs) {
10790b57cec5SDimitry Andric             if (RWD->getValueAsDef("SchedModel") == RWModelDef &&
10800b57cec5SDimitry Andric                 RWModelDef->getValueAsBit("FullInstRWOverlapCheck")) {
10815ffd83dbSDimitry Andric               assert(!InstDefs.empty()); // Checked at function start.
1082af732203SDimitry Andric               PrintError(
1083af732203SDimitry Andric                   InstRWDef->getLoc(),
10848bcb0991SDimitry Andric                   "Overlapping InstRW definition for \"" +
10855ffd83dbSDimitry Andric                       InstDefs.front()->getName() +
10868bcb0991SDimitry Andric                       "\" also matches previous \"" +
10878bcb0991SDimitry Andric                       RWD->getValue("Instrs")->getValue()->getAsString() +
10888bcb0991SDimitry Andric                       "\".");
1089af732203SDimitry Andric               PrintFatalNote(RWD->getLoc(), "Previous match was here.");
10900b57cec5SDimitry Andric             }
10910b57cec5SDimitry Andric           }
10920b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "InstRW: Reuse SC " << OldSCIdx << ":"
10930b57cec5SDimitry Andric                             << SchedClasses[OldSCIdx].Name << " on "
10940b57cec5SDimitry Andric                             << RWModelDef->getName() << "\n");
10950b57cec5SDimitry Andric           SchedClasses[OldSCIdx].InstRWs.push_back(InstRWDef);
10960b57cec5SDimitry Andric           continue;
10970b57cec5SDimitry Andric         }
10980b57cec5SDimitry Andric       }
10990b57cec5SDimitry Andric     }
11000b57cec5SDimitry Andric     unsigned SCIdx = SchedClasses.size();
11010b57cec5SDimitry Andric     SchedClasses.emplace_back(SCIdx, createSchedClassName(InstDefs), nullptr);
11020b57cec5SDimitry Andric     CodeGenSchedClass &SC = SchedClasses.back();
11030b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "InstRW: New SC " << SCIdx << ":" << SC.Name << " on "
11040b57cec5SDimitry Andric                       << InstRWDef->getValueAsDef("SchedModel")->getName()
11050b57cec5SDimitry Andric                       << "\n");
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric     // Preserve ItinDef and Writes/Reads for processors without an InstRW entry.
11080b57cec5SDimitry Andric     SC.ItinClassDef = SchedClasses[OldSCIdx].ItinClassDef;
11090b57cec5SDimitry Andric     SC.Writes = SchedClasses[OldSCIdx].Writes;
11100b57cec5SDimitry Andric     SC.Reads = SchedClasses[OldSCIdx].Reads;
11110b57cec5SDimitry Andric     SC.ProcIndices.push_back(0);
11120b57cec5SDimitry Andric     // If we had an old class, copy it's InstRWs to this new class.
11130b57cec5SDimitry Andric     if (OldSCIdx) {
11140b57cec5SDimitry Andric       Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
11150b57cec5SDimitry Andric       for (Record *OldRWDef : SchedClasses[OldSCIdx].InstRWs) {
11160b57cec5SDimitry Andric         if (OldRWDef->getValueAsDef("SchedModel") == RWModelDef) {
11175ffd83dbSDimitry Andric           assert(!InstDefs.empty()); // Checked at function start.
1118af732203SDimitry Andric           PrintError(
1119af732203SDimitry Andric               InstRWDef->getLoc(),
11208bcb0991SDimitry Andric               "Overlapping InstRW definition for \"" +
1121af732203SDimitry Andric                   InstDefs.front()->getName() + "\" also matches previous \"" +
11228bcb0991SDimitry Andric                   OldRWDef->getValue("Instrs")->getValue()->getAsString() +
11238bcb0991SDimitry Andric                   "\".");
1124af732203SDimitry Andric           PrintFatalNote(OldRWDef->getLoc(), "Previous match was here.");
11250b57cec5SDimitry Andric         }
11260b57cec5SDimitry Andric         assert(OldRWDef != InstRWDef &&
11270b57cec5SDimitry Andric                "SchedClass has duplicate InstRW def");
11280b57cec5SDimitry Andric         SC.InstRWs.push_back(OldRWDef);
11290b57cec5SDimitry Andric       }
11300b57cec5SDimitry Andric     }
11310b57cec5SDimitry Andric     // Map each Instr to this new class.
11320b57cec5SDimitry Andric     for (Record *InstDef : InstDefs)
11330b57cec5SDimitry Andric       InstrClassMap[InstDef] = SCIdx;
11340b57cec5SDimitry Andric     SC.InstRWs.push_back(InstRWDef);
11350b57cec5SDimitry Andric   }
11360b57cec5SDimitry Andric }
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric // True if collectProcItins found anything.
hasItineraries() const11390b57cec5SDimitry Andric bool CodeGenSchedModels::hasItineraries() const {
11400b57cec5SDimitry Andric   for (const CodeGenProcModel &PM : make_range(procModelBegin(),procModelEnd()))
11410b57cec5SDimitry Andric     if (PM.hasItineraries())
11420b57cec5SDimitry Andric       return true;
11430b57cec5SDimitry Andric   return false;
11440b57cec5SDimitry Andric }
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric // Gather the processor itineraries.
collectProcItins()11470b57cec5SDimitry Andric void CodeGenSchedModels::collectProcItins() {
11480b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n+++ PROBLEM ITINERARIES (collectProcItins) +++\n");
11490b57cec5SDimitry Andric   for (CodeGenProcModel &ProcModel : ProcModels) {
11500b57cec5SDimitry Andric     if (!ProcModel.hasItineraries())
11510b57cec5SDimitry Andric       continue;
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric     RecVec ItinRecords = ProcModel.ItinsDef->getValueAsListOfDefs("IID");
11540b57cec5SDimitry Andric     assert(!ItinRecords.empty() && "ProcModel.hasItineraries is incorrect");
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric     // Populate ItinDefList with Itinerary records.
11570b57cec5SDimitry Andric     ProcModel.ItinDefList.resize(NumInstrSchedClasses);
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric     // Insert each itinerary data record in the correct position within
11600b57cec5SDimitry Andric     // the processor model's ItinDefList.
11610b57cec5SDimitry Andric     for (Record *ItinData : ItinRecords) {
11620b57cec5SDimitry Andric       const Record *ItinDef = ItinData->getValueAsDef("TheClass");
11630b57cec5SDimitry Andric       bool FoundClass = false;
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric       for (const CodeGenSchedClass &SC :
11660b57cec5SDimitry Andric            make_range(schedClassBegin(), schedClassEnd())) {
11670b57cec5SDimitry Andric         // Multiple SchedClasses may share an itinerary. Update all of them.
11680b57cec5SDimitry Andric         if (SC.ItinClassDef == ItinDef) {
11690b57cec5SDimitry Andric           ProcModel.ItinDefList[SC.Index] = ItinData;
11700b57cec5SDimitry Andric           FoundClass = true;
11710b57cec5SDimitry Andric         }
11720b57cec5SDimitry Andric       }
11730b57cec5SDimitry Andric       if (!FoundClass) {
11740b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << ProcModel.ItinsDef->getName()
11750b57cec5SDimitry Andric                           << " missing class for itinerary "
11760b57cec5SDimitry Andric                           << ItinDef->getName() << '\n');
11770b57cec5SDimitry Andric       }
11780b57cec5SDimitry Andric     }
11790b57cec5SDimitry Andric     // Check for missing itinerary entries.
11800b57cec5SDimitry Andric     assert(!ProcModel.ItinDefList[0] && "NoItinerary class can't have rec");
11810b57cec5SDimitry Andric     LLVM_DEBUG(
11820b57cec5SDimitry Andric         for (unsigned i = 1, N = ProcModel.ItinDefList.size(); i < N; ++i) {
11830b57cec5SDimitry Andric           if (!ProcModel.ItinDefList[i])
11840b57cec5SDimitry Andric             dbgs() << ProcModel.ItinsDef->getName()
11850b57cec5SDimitry Andric                    << " missing itinerary for class " << SchedClasses[i].Name
11860b57cec5SDimitry Andric                    << '\n';
11870b57cec5SDimitry Andric         });
11880b57cec5SDimitry Andric   }
11890b57cec5SDimitry Andric }
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric // Gather the read/write types for each itinerary class.
collectProcItinRW()11920b57cec5SDimitry Andric void CodeGenSchedModels::collectProcItinRW() {
11930b57cec5SDimitry Andric   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
11940b57cec5SDimitry Andric   llvm::sort(ItinRWDefs, LessRecord());
11950b57cec5SDimitry Andric   for (Record *RWDef  : ItinRWDefs) {
11960b57cec5SDimitry Andric     if (!RWDef->getValueInit("SchedModel")->isComplete())
11970b57cec5SDimitry Andric       PrintFatalError(RWDef->getLoc(), "SchedModel is undefined");
11980b57cec5SDimitry Andric     Record *ModelDef = RWDef->getValueAsDef("SchedModel");
11990b57cec5SDimitry Andric     ProcModelMapTy::const_iterator I = ProcModelMap.find(ModelDef);
12000b57cec5SDimitry Andric     if (I == ProcModelMap.end()) {
12010b57cec5SDimitry Andric       PrintFatalError(RWDef->getLoc(), "Undefined SchedMachineModel "
12020b57cec5SDimitry Andric                     + ModelDef->getName());
12030b57cec5SDimitry Andric     }
12040b57cec5SDimitry Andric     ProcModels[I->second].ItinRWDefs.push_back(RWDef);
12050b57cec5SDimitry Andric   }
12060b57cec5SDimitry Andric }
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric // Gather the unsupported features for processor models.
collectProcUnsupportedFeatures()12090b57cec5SDimitry Andric void CodeGenSchedModels::collectProcUnsupportedFeatures() {
1210af732203SDimitry Andric   for (CodeGenProcModel &ProcModel : ProcModels)
1211af732203SDimitry Andric     append_range(
1212af732203SDimitry Andric         ProcModel.UnsupportedFeaturesDefs,
1213af732203SDimitry Andric         ProcModel.ModelDef->getValueAsListOfDefs("UnsupportedFeatures"));
12140b57cec5SDimitry Andric }
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric /// Infer new classes from existing classes. In the process, this may create new
12170b57cec5SDimitry Andric /// SchedWrites from sequences of existing SchedWrites.
inferSchedClasses()12180b57cec5SDimitry Andric void CodeGenSchedModels::inferSchedClasses() {
12190b57cec5SDimitry Andric   LLVM_DEBUG(
12200b57cec5SDimitry Andric       dbgs() << "\n+++ INFERRING SCHED CLASSES (inferSchedClasses) +++\n");
12210b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << NumInstrSchedClasses << " instr sched classes.\n");
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   // Visit all existing classes and newly created classes.
12240b57cec5SDimitry Andric   for (unsigned Idx = 0; Idx != SchedClasses.size(); ++Idx) {
12250b57cec5SDimitry Andric     assert(SchedClasses[Idx].Index == Idx && "bad SCIdx");
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric     if (SchedClasses[Idx].ItinClassDef)
12280b57cec5SDimitry Andric       inferFromItinClass(SchedClasses[Idx].ItinClassDef, Idx);
12290b57cec5SDimitry Andric     if (!SchedClasses[Idx].InstRWs.empty())
12300b57cec5SDimitry Andric       inferFromInstRWs(Idx);
12310b57cec5SDimitry Andric     if (!SchedClasses[Idx].Writes.empty()) {
12320b57cec5SDimitry Andric       inferFromRW(SchedClasses[Idx].Writes, SchedClasses[Idx].Reads,
12330b57cec5SDimitry Andric                   Idx, SchedClasses[Idx].ProcIndices);
12340b57cec5SDimitry Andric     }
12350b57cec5SDimitry Andric     assert(SchedClasses.size() < (NumInstrSchedClasses*6) &&
12360b57cec5SDimitry Andric            "too many SchedVariants");
12370b57cec5SDimitry Andric   }
12380b57cec5SDimitry Andric }
12390b57cec5SDimitry Andric 
12400b57cec5SDimitry Andric /// Infer classes from per-processor itinerary resources.
inferFromItinClass(Record * ItinClassDef,unsigned FromClassIdx)12410b57cec5SDimitry Andric void CodeGenSchedModels::inferFromItinClass(Record *ItinClassDef,
12420b57cec5SDimitry Andric                                             unsigned FromClassIdx) {
12430b57cec5SDimitry Andric   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
12440b57cec5SDimitry Andric     const CodeGenProcModel &PM = ProcModels[PIdx];
12450b57cec5SDimitry Andric     // For all ItinRW entries.
12460b57cec5SDimitry Andric     bool HasMatch = false;
12470b57cec5SDimitry Andric     for (const Record *Rec : PM.ItinRWDefs) {
12480b57cec5SDimitry Andric       RecVec Matched = Rec->getValueAsListOfDefs("MatchedItinClasses");
1249af732203SDimitry Andric       if (!llvm::is_contained(Matched, ItinClassDef))
12500b57cec5SDimitry Andric         continue;
12510b57cec5SDimitry Andric       if (HasMatch)
12520b57cec5SDimitry Andric         PrintFatalError(Rec->getLoc(), "Duplicate itinerary class "
12530b57cec5SDimitry Andric                       + ItinClassDef->getName()
12540b57cec5SDimitry Andric                       + " in ItinResources for " + PM.ModelName);
12550b57cec5SDimitry Andric       HasMatch = true;
12560b57cec5SDimitry Andric       IdxVec Writes, Reads;
12570b57cec5SDimitry Andric       findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
12580b57cec5SDimitry Andric       inferFromRW(Writes, Reads, FromClassIdx, PIdx);
12590b57cec5SDimitry Andric     }
12600b57cec5SDimitry Andric   }
12610b57cec5SDimitry Andric }
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric /// Infer classes from per-processor InstReadWrite definitions.
inferFromInstRWs(unsigned SCIdx)12640b57cec5SDimitry Andric void CodeGenSchedModels::inferFromInstRWs(unsigned SCIdx) {
12650b57cec5SDimitry Andric   for (unsigned I = 0, E = SchedClasses[SCIdx].InstRWs.size(); I != E; ++I) {
12660b57cec5SDimitry Andric     assert(SchedClasses[SCIdx].InstRWs.size() == E && "InstrRWs was mutated!");
12670b57cec5SDimitry Andric     Record *Rec = SchedClasses[SCIdx].InstRWs[I];
12680b57cec5SDimitry Andric     const RecVec *InstDefs = Sets.expand(Rec);
12690b57cec5SDimitry Andric     RecIter II = InstDefs->begin(), IE = InstDefs->end();
12700b57cec5SDimitry Andric     for (; II != IE; ++II) {
12710b57cec5SDimitry Andric       if (InstrClassMap[*II] == SCIdx)
12720b57cec5SDimitry Andric         break;
12730b57cec5SDimitry Andric     }
12740b57cec5SDimitry Andric     // If this class no longer has any instructions mapped to it, it has become
12750b57cec5SDimitry Andric     // irrelevant.
12760b57cec5SDimitry Andric     if (II == IE)
12770b57cec5SDimitry Andric       continue;
12780b57cec5SDimitry Andric     IdxVec Writes, Reads;
12790b57cec5SDimitry Andric     findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
12800b57cec5SDimitry Andric     unsigned PIdx = getProcModel(Rec->getValueAsDef("SchedModel")).Index;
12810b57cec5SDimitry Andric     inferFromRW(Writes, Reads, SCIdx, PIdx); // May mutate SchedClasses.
1282af732203SDimitry Andric     SchedClasses[SCIdx].InstRWProcIndices.insert(PIdx);
12830b57cec5SDimitry Andric   }
12840b57cec5SDimitry Andric }
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric namespace {
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric // Helper for substituteVariantOperand.
12890b57cec5SDimitry Andric struct TransVariant {
12900b57cec5SDimitry Andric   Record *VarOrSeqDef;  // Variant or sequence.
12910b57cec5SDimitry Andric   unsigned RWIdx;       // Index of this variant or sequence's matched type.
12920b57cec5SDimitry Andric   unsigned ProcIdx;     // Processor model index or zero for any.
12930b57cec5SDimitry Andric   unsigned TransVecIdx; // Index into PredTransitions::TransVec.
12940b57cec5SDimitry Andric 
TransVariant__anonfd00d8910a11::TransVariant12950b57cec5SDimitry Andric   TransVariant(Record *def, unsigned rwi, unsigned pi, unsigned ti):
12960b57cec5SDimitry Andric     VarOrSeqDef(def), RWIdx(rwi), ProcIdx(pi), TransVecIdx(ti) {}
12970b57cec5SDimitry Andric };
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric // Associate a predicate with the SchedReadWrite that it guards.
13000b57cec5SDimitry Andric // RWIdx is the index of the read/write variant.
13010b57cec5SDimitry Andric struct PredCheck {
13020b57cec5SDimitry Andric   bool IsRead;
13030b57cec5SDimitry Andric   unsigned RWIdx;
13040b57cec5SDimitry Andric   Record *Predicate;
13050b57cec5SDimitry Andric 
PredCheck__anonfd00d8910a11::PredCheck13060b57cec5SDimitry Andric   PredCheck(bool r, unsigned w, Record *p): IsRead(r), RWIdx(w), Predicate(p) {}
13070b57cec5SDimitry Andric };
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric // A Predicate transition is a list of RW sequences guarded by a PredTerm.
13100b57cec5SDimitry Andric struct PredTransition {
13110b57cec5SDimitry Andric   // A predicate term is a conjunction of PredChecks.
13120b57cec5SDimitry Andric   SmallVector<PredCheck, 4> PredTerm;
13130b57cec5SDimitry Andric   SmallVector<SmallVector<unsigned,4>, 16> WriteSequences;
13140b57cec5SDimitry Andric   SmallVector<SmallVector<unsigned,4>, 16> ReadSequences;
1315af732203SDimitry Andric   unsigned ProcIndex = 0;
1316af732203SDimitry Andric 
1317af732203SDimitry Andric   PredTransition() = default;
PredTransition__anonfd00d8910a11::PredTransition1318af732203SDimitry Andric   PredTransition(ArrayRef<PredCheck> PT, unsigned ProcId) {
1319af732203SDimitry Andric     PredTerm.assign(PT.begin(), PT.end());
1320af732203SDimitry Andric     ProcIndex = ProcId;
1321af732203SDimitry Andric   }
13220b57cec5SDimitry Andric };
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric // Encapsulate a set of partially constructed transitions.
13250b57cec5SDimitry Andric // The results are built by repeated calls to substituteVariants.
13260b57cec5SDimitry Andric class PredTransitions {
13270b57cec5SDimitry Andric   CodeGenSchedModels &SchedModels;
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric public:
13300b57cec5SDimitry Andric   std::vector<PredTransition> TransVec;
13310b57cec5SDimitry Andric 
PredTransitions(CodeGenSchedModels & sm)13320b57cec5SDimitry Andric   PredTransitions(CodeGenSchedModels &sm): SchedModels(sm) {}
13330b57cec5SDimitry Andric 
1334af732203SDimitry Andric   bool substituteVariantOperand(const SmallVectorImpl<unsigned> &RWSeq,
13350b57cec5SDimitry Andric                                 bool IsRead, unsigned StartIdx);
13360b57cec5SDimitry Andric 
1337af732203SDimitry Andric   bool substituteVariants(const PredTransition &Trans);
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric #ifndef NDEBUG
13400b57cec5SDimitry Andric   void dump() const;
13410b57cec5SDimitry Andric #endif
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric private:
1344af732203SDimitry Andric   bool mutuallyExclusive(Record *PredDef, ArrayRef<Record *> Preds,
1345af732203SDimitry Andric                          ArrayRef<PredCheck> Term);
13460b57cec5SDimitry Andric   void getIntersectingVariants(
13470b57cec5SDimitry Andric     const CodeGenSchedRW &SchedRW, unsigned TransIdx,
13480b57cec5SDimitry Andric     std::vector<TransVariant> &IntersectingVariants);
13490b57cec5SDimitry Andric   void pushVariant(const TransVariant &VInfo, bool IsRead);
13500b57cec5SDimitry Andric };
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric } // end anonymous namespace
13530b57cec5SDimitry Andric 
13540b57cec5SDimitry Andric // Return true if this predicate is mutually exclusive with a PredTerm. This
13550b57cec5SDimitry Andric // degenerates into checking if the predicate is mutually exclusive with any
13560b57cec5SDimitry Andric // predicate in the Term's conjunction.
13570b57cec5SDimitry Andric //
13580b57cec5SDimitry Andric // All predicates associated with a given SchedRW are considered mutually
13590b57cec5SDimitry Andric // exclusive. This should work even if the conditions expressed by the
13600b57cec5SDimitry Andric // predicates are not exclusive because the predicates for a given SchedWrite
13610b57cec5SDimitry Andric // are always checked in the order they are defined in the .td file. Later
13620b57cec5SDimitry Andric // conditions implicitly negate any prior condition.
mutuallyExclusive(Record * PredDef,ArrayRef<Record * > Preds,ArrayRef<PredCheck> Term)13630b57cec5SDimitry Andric bool PredTransitions::mutuallyExclusive(Record *PredDef,
1364af732203SDimitry Andric                                         ArrayRef<Record *> Preds,
13650b57cec5SDimitry Andric                                         ArrayRef<PredCheck> Term) {
13660b57cec5SDimitry Andric   for (const PredCheck &PC: Term) {
13670b57cec5SDimitry Andric     if (PC.Predicate == PredDef)
13680b57cec5SDimitry Andric       return false;
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(PC.RWIdx, PC.IsRead);
13710b57cec5SDimitry Andric     assert(SchedRW.HasVariants && "PredCheck must refer to a SchedVariant");
13720b57cec5SDimitry Andric     RecVec Variants = SchedRW.TheDef->getValueAsListOfDefs("Variants");
13730b57cec5SDimitry Andric     if (any_of(Variants, [PredDef](const Record *R) {
13740b57cec5SDimitry Andric           return R->getValueAsDef("Predicate") == PredDef;
1375af732203SDimitry Andric         })) {
1376af732203SDimitry Andric       // To check if PredDef is mutually exclusive with PC we also need to
1377af732203SDimitry Andric       // check that PC.Predicate is exclusive with all predicates from variant
1378af732203SDimitry Andric       // we're expanding. Consider following RW sequence with two variants
1379af732203SDimitry Andric       // (1 & 2), where A, B and C are predicates from corresponding SchedVars:
1380af732203SDimitry Andric       //
1381af732203SDimitry Andric       // 1:A/B - 2:C/B
1382af732203SDimitry Andric       //
1383af732203SDimitry Andric       // Here C is not mutually exclusive with variant (1), because A doesn't
1384af732203SDimitry Andric       // exist in variant (2). This means we have possible transitions from A
1385af732203SDimitry Andric       // to C and from A to B, and fully expanded sequence would look like:
1386af732203SDimitry Andric       //
1387af732203SDimitry Andric       // if (A & C) return ...;
1388af732203SDimitry Andric       // if (A & B) return ...;
1389af732203SDimitry Andric       // if (B) return ...;
1390af732203SDimitry Andric       //
1391af732203SDimitry Andric       // Now let's consider another sequence:
1392af732203SDimitry Andric       //
1393af732203SDimitry Andric       // 1:A/B - 2:A/B
1394af732203SDimitry Andric       //
1395af732203SDimitry Andric       // Here A in variant (2) is mutually exclusive with variant (1), because
1396af732203SDimitry Andric       // A also exists in (2). This means A->B transition is impossible and
1397af732203SDimitry Andric       // expanded sequence would look like:
1398af732203SDimitry Andric       //
1399af732203SDimitry Andric       // if (A) return ...;
1400af732203SDimitry Andric       // if (B) return ...;
1401af732203SDimitry Andric       if (!count(Preds, PC.Predicate))
1402af732203SDimitry Andric         continue;
14030b57cec5SDimitry Andric       return true;
14040b57cec5SDimitry Andric     }
14050b57cec5SDimitry Andric   }
14060b57cec5SDimitry Andric   return false;
14070b57cec5SDimitry Andric }
14080b57cec5SDimitry Andric 
getAllPredicates(ArrayRef<TransVariant> Variants,unsigned ProcId)1409af732203SDimitry Andric static std::vector<Record *> getAllPredicates(ArrayRef<TransVariant> Variants,
1410af732203SDimitry Andric                                               unsigned ProcId) {
1411af732203SDimitry Andric   std::vector<Record *> Preds;
1412af732203SDimitry Andric   for (auto &Variant : Variants) {
1413af732203SDimitry Andric     if (!Variant.VarOrSeqDef->isSubClassOf("SchedVar"))
1414af732203SDimitry Andric       continue;
1415af732203SDimitry Andric     Preds.push_back(Variant.VarOrSeqDef->getValueAsDef("Predicate"));
14160b57cec5SDimitry Andric   }
1417af732203SDimitry Andric   return Preds;
14180b57cec5SDimitry Andric }
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric // Populate IntersectingVariants with any variants or aliased sequences of the
14210b57cec5SDimitry Andric // given SchedRW whose processor indices and predicates are not mutually
14220b57cec5SDimitry Andric // exclusive with the given transition.
getIntersectingVariants(const CodeGenSchedRW & SchedRW,unsigned TransIdx,std::vector<TransVariant> & IntersectingVariants)14230b57cec5SDimitry Andric void PredTransitions::getIntersectingVariants(
14240b57cec5SDimitry Andric   const CodeGenSchedRW &SchedRW, unsigned TransIdx,
14250b57cec5SDimitry Andric   std::vector<TransVariant> &IntersectingVariants) {
14260b57cec5SDimitry Andric 
14270b57cec5SDimitry Andric   bool GenericRW = false;
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric   std::vector<TransVariant> Variants;
14300b57cec5SDimitry Andric   if (SchedRW.HasVariants) {
14310b57cec5SDimitry Andric     unsigned VarProcIdx = 0;
14320b57cec5SDimitry Andric     if (SchedRW.TheDef->getValueInit("SchedModel")->isComplete()) {
14330b57cec5SDimitry Andric       Record *ModelDef = SchedRW.TheDef->getValueAsDef("SchedModel");
14340b57cec5SDimitry Andric       VarProcIdx = SchedModels.getProcModel(ModelDef).Index;
14350b57cec5SDimitry Andric     }
1436af732203SDimitry Andric     if (VarProcIdx == 0 || VarProcIdx == TransVec[TransIdx].ProcIndex) {
14370b57cec5SDimitry Andric       // Push each variant. Assign TransVecIdx later.
14380b57cec5SDimitry Andric       const RecVec VarDefs = SchedRW.TheDef->getValueAsListOfDefs("Variants");
14390b57cec5SDimitry Andric       for (Record *VarDef : VarDefs)
14400b57cec5SDimitry Andric         Variants.emplace_back(VarDef, SchedRW.Index, VarProcIdx, 0);
14410b57cec5SDimitry Andric       if (VarProcIdx == 0)
14420b57cec5SDimitry Andric         GenericRW = true;
14430b57cec5SDimitry Andric     }
1444af732203SDimitry Andric   }
14450b57cec5SDimitry Andric   for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
14460b57cec5SDimitry Andric        AI != AE; ++AI) {
14470b57cec5SDimitry Andric     // If either the SchedAlias itself or the SchedReadWrite that it aliases
14480b57cec5SDimitry Andric     // to is defined within a processor model, constrain all variants to
14490b57cec5SDimitry Andric     // that processor.
14500b57cec5SDimitry Andric     unsigned AliasProcIdx = 0;
14510b57cec5SDimitry Andric     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
14520b57cec5SDimitry Andric       Record *ModelDef = (*AI)->getValueAsDef("SchedModel");
14530b57cec5SDimitry Andric       AliasProcIdx = SchedModels.getProcModel(ModelDef).Index;
14540b57cec5SDimitry Andric     }
1455af732203SDimitry Andric     if (AliasProcIdx && AliasProcIdx != TransVec[TransIdx].ProcIndex)
1456af732203SDimitry Andric       continue;
1457af732203SDimitry Andric     if (!Variants.empty()) {
1458af732203SDimitry Andric       const CodeGenProcModel &PM =
1459af732203SDimitry Andric           *(SchedModels.procModelBegin() + AliasProcIdx);
1460af732203SDimitry Andric       PrintFatalError((*AI)->getLoc(),
1461af732203SDimitry Andric                       "Multiple variants defined for processor " +
1462af732203SDimitry Andric                           PM.ModelName +
1463af732203SDimitry Andric                           " Ensure only one SchedAlias exists per RW.");
1464af732203SDimitry Andric     }
1465af732203SDimitry Andric 
14660b57cec5SDimitry Andric     const CodeGenSchedRW &AliasRW =
14670b57cec5SDimitry Andric       SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric     if (AliasRW.HasVariants) {
14700b57cec5SDimitry Andric       const RecVec VarDefs = AliasRW.TheDef->getValueAsListOfDefs("Variants");
14710b57cec5SDimitry Andric       for (Record *VD : VarDefs)
14720b57cec5SDimitry Andric         Variants.emplace_back(VD, AliasRW.Index, AliasProcIdx, 0);
14730b57cec5SDimitry Andric     }
14740b57cec5SDimitry Andric     if (AliasRW.IsSequence)
14750b57cec5SDimitry Andric       Variants.emplace_back(AliasRW.TheDef, SchedRW.Index, AliasProcIdx, 0);
14760b57cec5SDimitry Andric     if (AliasProcIdx == 0)
14770b57cec5SDimitry Andric       GenericRW = true;
14780b57cec5SDimitry Andric   }
1479af732203SDimitry Andric   std::vector<Record *> AllPreds =
1480af732203SDimitry Andric       getAllPredicates(Variants, TransVec[TransIdx].ProcIndex);
14810b57cec5SDimitry Andric   for (TransVariant &Variant : Variants) {
14820b57cec5SDimitry Andric     // Don't expand variants if the processor models don't intersect.
14830b57cec5SDimitry Andric     // A zero processor index means any processor.
14840b57cec5SDimitry Andric     if (Variant.VarOrSeqDef->isSubClassOf("SchedVar")) {
14850b57cec5SDimitry Andric       Record *PredDef = Variant.VarOrSeqDef->getValueAsDef("Predicate");
1486af732203SDimitry Andric       if (mutuallyExclusive(PredDef, AllPreds, TransVec[TransIdx].PredTerm))
14870b57cec5SDimitry Andric         continue;
14880b57cec5SDimitry Andric     }
1489af732203SDimitry Andric 
14900b57cec5SDimitry Andric     if (IntersectingVariants.empty()) {
14910b57cec5SDimitry Andric       // The first variant builds on the existing transition.
14920b57cec5SDimitry Andric       Variant.TransVecIdx = TransIdx;
14930b57cec5SDimitry Andric       IntersectingVariants.push_back(Variant);
14940b57cec5SDimitry Andric     }
14950b57cec5SDimitry Andric     else {
14960b57cec5SDimitry Andric       // Push another copy of the current transition for more variants.
14970b57cec5SDimitry Andric       Variant.TransVecIdx = TransVec.size();
14980b57cec5SDimitry Andric       IntersectingVariants.push_back(Variant);
14990b57cec5SDimitry Andric       TransVec.push_back(TransVec[TransIdx]);
15000b57cec5SDimitry Andric     }
15010b57cec5SDimitry Andric   }
15020b57cec5SDimitry Andric   if (GenericRW && IntersectingVariants.empty()) {
15030b57cec5SDimitry Andric     PrintFatalError(SchedRW.TheDef->getLoc(), "No variant of this type has "
15040b57cec5SDimitry Andric                     "a matching predicate on any processor");
15050b57cec5SDimitry Andric   }
15060b57cec5SDimitry Andric }
15070b57cec5SDimitry Andric 
15080b57cec5SDimitry Andric // Push the Reads/Writes selected by this variant onto the PredTransition
15090b57cec5SDimitry Andric // specified by VInfo.
15100b57cec5SDimitry Andric void PredTransitions::
pushVariant(const TransVariant & VInfo,bool IsRead)15110b57cec5SDimitry Andric pushVariant(const TransVariant &VInfo, bool IsRead) {
15120b57cec5SDimitry Andric   PredTransition &Trans = TransVec[VInfo.TransVecIdx];
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric   // If this operand transition is reached through a processor-specific alias,
15150b57cec5SDimitry Andric   // then the whole transition is specific to this processor.
15160b57cec5SDimitry Andric   IdxVec SelectedRWs;
15170b57cec5SDimitry Andric   if (VInfo.VarOrSeqDef->isSubClassOf("SchedVar")) {
15180b57cec5SDimitry Andric     Record *PredDef = VInfo.VarOrSeqDef->getValueAsDef("Predicate");
15190b57cec5SDimitry Andric     Trans.PredTerm.emplace_back(IsRead, VInfo.RWIdx,PredDef);
15200b57cec5SDimitry Andric     RecVec SelectedDefs = VInfo.VarOrSeqDef->getValueAsListOfDefs("Selected");
15210b57cec5SDimitry Andric     SchedModels.findRWs(SelectedDefs, SelectedRWs, IsRead);
15220b57cec5SDimitry Andric   }
15230b57cec5SDimitry Andric   else {
15240b57cec5SDimitry Andric     assert(VInfo.VarOrSeqDef->isSubClassOf("WriteSequence") &&
15250b57cec5SDimitry Andric            "variant must be a SchedVariant or aliased WriteSequence");
15260b57cec5SDimitry Andric     SelectedRWs.push_back(SchedModels.getSchedRWIdx(VInfo.VarOrSeqDef, IsRead));
15270b57cec5SDimitry Andric   }
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric   const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(VInfo.RWIdx, IsRead);
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric   SmallVectorImpl<SmallVector<unsigned,4>> &RWSequences = IsRead
15320b57cec5SDimitry Andric     ? Trans.ReadSequences : Trans.WriteSequences;
15330b57cec5SDimitry Andric   if (SchedRW.IsVariadic) {
15340b57cec5SDimitry Andric     unsigned OperIdx = RWSequences.size()-1;
15350b57cec5SDimitry Andric     // Make N-1 copies of this transition's last sequence.
1536af732203SDimitry Andric     RWSequences.reserve(RWSequences.size() + SelectedRWs.size() - 1);
15370b57cec5SDimitry Andric     RWSequences.insert(RWSequences.end(), SelectedRWs.size() - 1,
15380b57cec5SDimitry Andric                        RWSequences[OperIdx]);
15390b57cec5SDimitry Andric     // Push each of the N elements of the SelectedRWs onto a copy of the last
15400b57cec5SDimitry Andric     // sequence (split the current operand into N operands).
15410b57cec5SDimitry Andric     // Note that write sequences should be expanded within this loop--the entire
15420b57cec5SDimitry Andric     // sequence belongs to a single operand.
15430b57cec5SDimitry Andric     for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
15440b57cec5SDimitry Andric          RWI != RWE; ++RWI, ++OperIdx) {
15450b57cec5SDimitry Andric       IdxVec ExpandedRWs;
15460b57cec5SDimitry Andric       if (IsRead)
15470b57cec5SDimitry Andric         ExpandedRWs.push_back(*RWI);
15480b57cec5SDimitry Andric       else
15490b57cec5SDimitry Andric         SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
1550af732203SDimitry Andric       llvm::append_range(RWSequences[OperIdx], ExpandedRWs);
15510b57cec5SDimitry Andric     }
15520b57cec5SDimitry Andric     assert(OperIdx == RWSequences.size() && "missed a sequence");
15530b57cec5SDimitry Andric   }
15540b57cec5SDimitry Andric   else {
15550b57cec5SDimitry Andric     // Push this transition's expanded sequence onto this transition's last
15560b57cec5SDimitry Andric     // sequence (add to the current operand's sequence).
15570b57cec5SDimitry Andric     SmallVectorImpl<unsigned> &Seq = RWSequences.back();
15580b57cec5SDimitry Andric     IdxVec ExpandedRWs;
1559*5f7ddb14SDimitry Andric     for (unsigned int SelectedRW : SelectedRWs) {
15600b57cec5SDimitry Andric       if (IsRead)
1561*5f7ddb14SDimitry Andric         ExpandedRWs.push_back(SelectedRW);
15620b57cec5SDimitry Andric       else
1563*5f7ddb14SDimitry Andric         SchedModels.expandRWSequence(SelectedRW, ExpandedRWs, IsRead);
15640b57cec5SDimitry Andric     }
1565af732203SDimitry Andric     llvm::append_range(Seq, ExpandedRWs);
15660b57cec5SDimitry Andric   }
15670b57cec5SDimitry Andric }
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric // RWSeq is a sequence of all Reads or all Writes for the next read or write
15700b57cec5SDimitry Andric // operand. StartIdx is an index into TransVec where partial results
15710b57cec5SDimitry Andric // starts. RWSeq must be applied to all transitions between StartIdx and the end
15720b57cec5SDimitry Andric // of TransVec.
substituteVariantOperand(const SmallVectorImpl<unsigned> & RWSeq,bool IsRead,unsigned StartIdx)1573af732203SDimitry Andric bool PredTransitions::substituteVariantOperand(
15740b57cec5SDimitry Andric     const SmallVectorImpl<unsigned> &RWSeq, bool IsRead, unsigned StartIdx) {
1575af732203SDimitry Andric   bool Subst = false;
15760b57cec5SDimitry Andric   // Visit each original RW within the current sequence.
1577*5f7ddb14SDimitry Andric   for (unsigned int RWI : RWSeq) {
1578*5f7ddb14SDimitry Andric     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(RWI, IsRead);
15790b57cec5SDimitry Andric     // Push this RW on all partial PredTransitions or distribute variants.
15800b57cec5SDimitry Andric     // New PredTransitions may be pushed within this loop which should not be
15810b57cec5SDimitry Andric     // revisited (TransEnd must be loop invariant).
15820b57cec5SDimitry Andric     for (unsigned TransIdx = StartIdx, TransEnd = TransVec.size();
15830b57cec5SDimitry Andric          TransIdx != TransEnd; ++TransIdx) {
15840b57cec5SDimitry Andric       // Distribute this partial PredTransition across intersecting variants.
15850b57cec5SDimitry Andric       // This will push a copies of TransVec[TransIdx] on the back of TransVec.
15860b57cec5SDimitry Andric       std::vector<TransVariant> IntersectingVariants;
15870b57cec5SDimitry Andric       getIntersectingVariants(SchedRW, TransIdx, IntersectingVariants);
15880b57cec5SDimitry Andric       // Now expand each variant on top of its copy of the transition.
1589af732203SDimitry Andric       for (const TransVariant &IV : IntersectingVariants)
1590af732203SDimitry Andric         pushVariant(IV, IsRead);
1591af732203SDimitry Andric       if (IntersectingVariants.empty()) {
1592af732203SDimitry Andric         if (IsRead)
1593*5f7ddb14SDimitry Andric           TransVec[TransIdx].ReadSequences.back().push_back(RWI);
1594af732203SDimitry Andric         else
1595*5f7ddb14SDimitry Andric           TransVec[TransIdx].WriteSequences.back().push_back(RWI);
1596af732203SDimitry Andric         continue;
1597af732203SDimitry Andric       } else {
1598af732203SDimitry Andric         Subst = true;
15990b57cec5SDimitry Andric       }
16000b57cec5SDimitry Andric     }
16010b57cec5SDimitry Andric   }
1602af732203SDimitry Andric   return Subst;
16030b57cec5SDimitry Andric }
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric // For each variant of a Read/Write in Trans, substitute the sequence of
16060b57cec5SDimitry Andric // Read/Writes guarded by the variant. This is exponential in the number of
16070b57cec5SDimitry Andric // variant Read/Writes, but in practice detection of mutually exclusive
16080b57cec5SDimitry Andric // predicates should result in linear growth in the total number variants.
16090b57cec5SDimitry Andric //
16100b57cec5SDimitry Andric // This is one step in a breadth-first search of nested variants.
substituteVariants(const PredTransition & Trans)1611af732203SDimitry Andric bool PredTransitions::substituteVariants(const PredTransition &Trans) {
16120b57cec5SDimitry Andric   // Build up a set of partial results starting at the back of
16130b57cec5SDimitry Andric   // PredTransitions. Remember the first new transition.
16140b57cec5SDimitry Andric   unsigned StartIdx = TransVec.size();
1615af732203SDimitry Andric   bool Subst = false;
1616af732203SDimitry Andric   assert(Trans.ProcIndex != 0);
1617af732203SDimitry Andric   TransVec.emplace_back(Trans.PredTerm, Trans.ProcIndex);
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric   // Visit each original write sequence.
1620*5f7ddb14SDimitry Andric   for (const auto &WriteSequence : Trans.WriteSequences) {
16210b57cec5SDimitry Andric     // Push a new (empty) write sequence onto all partial Transitions.
16220b57cec5SDimitry Andric     for (std::vector<PredTransition>::iterator I =
16230b57cec5SDimitry Andric            TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
16240b57cec5SDimitry Andric       I->WriteSequences.emplace_back();
16250b57cec5SDimitry Andric     }
1626*5f7ddb14SDimitry Andric     Subst |=
1627*5f7ddb14SDimitry Andric         substituteVariantOperand(WriteSequence, /*IsRead=*/false, StartIdx);
16280b57cec5SDimitry Andric   }
16290b57cec5SDimitry Andric   // Visit each original read sequence.
1630*5f7ddb14SDimitry Andric   for (const auto &ReadSequence : Trans.ReadSequences) {
16310b57cec5SDimitry Andric     // Push a new (empty) read sequence onto all partial Transitions.
16320b57cec5SDimitry Andric     for (std::vector<PredTransition>::iterator I =
16330b57cec5SDimitry Andric            TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
16340b57cec5SDimitry Andric       I->ReadSequences.emplace_back();
16350b57cec5SDimitry Andric     }
1636*5f7ddb14SDimitry Andric     Subst |= substituteVariantOperand(ReadSequence, /*IsRead=*/true, StartIdx);
16370b57cec5SDimitry Andric   }
1638af732203SDimitry Andric   return Subst;
16390b57cec5SDimitry Andric }
16400b57cec5SDimitry Andric 
addSequences(CodeGenSchedModels & SchedModels,const SmallVectorImpl<SmallVector<unsigned,4>> & Seqs,IdxVec & Result,bool IsRead)1641af732203SDimitry Andric static void addSequences(CodeGenSchedModels &SchedModels,
1642af732203SDimitry Andric                          const SmallVectorImpl<SmallVector<unsigned, 4>> &Seqs,
1643af732203SDimitry Andric                          IdxVec &Result, bool IsRead) {
1644af732203SDimitry Andric   for (const auto &S : Seqs)
1645af732203SDimitry Andric     if (!S.empty())
1646af732203SDimitry Andric       Result.push_back(SchedModels.findOrInsertRW(S, IsRead));
1647af732203SDimitry Andric }
1648af732203SDimitry Andric 
1649af732203SDimitry Andric #ifndef NDEBUG
dumpRecVec(const RecVec & RV)1650af732203SDimitry Andric static void dumpRecVec(const RecVec &RV) {
1651af732203SDimitry Andric   for (const Record *R : RV)
1652af732203SDimitry Andric     dbgs() << R->getName() << ", ";
1653af732203SDimitry Andric }
1654af732203SDimitry Andric #endif
1655af732203SDimitry Andric 
dumpTransition(const CodeGenSchedModels & SchedModels,const CodeGenSchedClass & FromSC,const CodeGenSchedTransition & SCTrans,const RecVec & Preds)1656af732203SDimitry Andric static void dumpTransition(const CodeGenSchedModels &SchedModels,
1657af732203SDimitry Andric                            const CodeGenSchedClass &FromSC,
1658af732203SDimitry Andric                            const CodeGenSchedTransition &SCTrans,
1659af732203SDimitry Andric                            const RecVec &Preds) {
1660af732203SDimitry Andric   LLVM_DEBUG(dbgs() << "Adding transition from " << FromSC.Name << "("
1661af732203SDimitry Andric                     << FromSC.Index << ") to "
1662af732203SDimitry Andric                     << SchedModels.getSchedClass(SCTrans.ToClassIdx).Name << "("
1663af732203SDimitry Andric                     << SCTrans.ToClassIdx << ") on pred term: (";
1664af732203SDimitry Andric              dumpRecVec(Preds);
1665af732203SDimitry Andric              dbgs() << ") on processor (" << SCTrans.ProcIndex << ")\n");
1666af732203SDimitry Andric }
16670b57cec5SDimitry Andric // Create a new SchedClass for each variant found by inferFromRW. Pass
inferFromTransitions(ArrayRef<PredTransition> LastTransitions,unsigned FromClassIdx,CodeGenSchedModels & SchedModels)16680b57cec5SDimitry Andric static void inferFromTransitions(ArrayRef<PredTransition> LastTransitions,
16690b57cec5SDimitry Andric                                  unsigned FromClassIdx,
16700b57cec5SDimitry Andric                                  CodeGenSchedModels &SchedModels) {
16710b57cec5SDimitry Andric   // For each PredTransition, create a new CodeGenSchedTransition, which usually
16720b57cec5SDimitry Andric   // requires creating a new SchedClass.
1673*5f7ddb14SDimitry Andric   for (const auto &LastTransition : LastTransitions) {
1674af732203SDimitry Andric     // Variant expansion (substituteVariants) may create unconditional
1675af732203SDimitry Andric     // transitions. We don't need to build sched classes for them.
1676*5f7ddb14SDimitry Andric     if (LastTransition.PredTerm.empty())
1677af732203SDimitry Andric       continue;
1678af732203SDimitry Andric     IdxVec OperWritesVariant, OperReadsVariant;
1679*5f7ddb14SDimitry Andric     addSequences(SchedModels, LastTransition.WriteSequences, OperWritesVariant,
1680*5f7ddb14SDimitry Andric                  false);
1681*5f7ddb14SDimitry Andric     addSequences(SchedModels, LastTransition.ReadSequences, OperReadsVariant,
1682*5f7ddb14SDimitry Andric                  true);
16830b57cec5SDimitry Andric     CodeGenSchedTransition SCTrans;
1684af732203SDimitry Andric 
1685af732203SDimitry Andric     // Transition should not contain processor indices already assigned to
1686af732203SDimitry Andric     // InstRWs in this scheduling class.
1687af732203SDimitry Andric     const CodeGenSchedClass &FromSC = SchedModels.getSchedClass(FromClassIdx);
1688*5f7ddb14SDimitry Andric     if (FromSC.InstRWProcIndices.count(LastTransition.ProcIndex))
1689af732203SDimitry Andric       continue;
1690*5f7ddb14SDimitry Andric     SCTrans.ProcIndex = LastTransition.ProcIndex;
16910b57cec5SDimitry Andric     SCTrans.ToClassIdx =
16920b57cec5SDimitry Andric         SchedModels.addSchedClass(/*ItinClassDef=*/nullptr, OperWritesVariant,
1693*5f7ddb14SDimitry Andric                                   OperReadsVariant, LastTransition.ProcIndex);
1694af732203SDimitry Andric 
16950b57cec5SDimitry Andric     // The final PredTerm is unique set of predicates guarding the transition.
16960b57cec5SDimitry Andric     RecVec Preds;
1697*5f7ddb14SDimitry Andric     transform(LastTransition.PredTerm, std::back_inserter(Preds),
1698*5f7ddb14SDimitry Andric               [](const PredCheck &P) { return P.Predicate; });
16990b57cec5SDimitry Andric     Preds.erase(std::unique(Preds.begin(), Preds.end()), Preds.end());
1700af732203SDimitry Andric     dumpTransition(SchedModels, FromSC, SCTrans, Preds);
17010b57cec5SDimitry Andric     SCTrans.PredTerm = std::move(Preds);
17020b57cec5SDimitry Andric     SchedModels.getSchedClass(FromClassIdx)
17030b57cec5SDimitry Andric         .Transitions.push_back(std::move(SCTrans));
17040b57cec5SDimitry Andric   }
17050b57cec5SDimitry Andric }
17060b57cec5SDimitry Andric 
getAllProcIndices() const1707af732203SDimitry Andric std::vector<unsigned> CodeGenSchedModels::getAllProcIndices() const {
1708af732203SDimitry Andric   std::vector<unsigned> ProcIdVec;
1709af732203SDimitry Andric   for (const auto &PM : ProcModelMap)
1710af732203SDimitry Andric     if (PM.second != 0)
1711af732203SDimitry Andric       ProcIdVec.push_back(PM.second);
1712af732203SDimitry Andric   // The order of the keys (Record pointers) of ProcModelMap are not stable.
1713af732203SDimitry Andric   // Sort to stabalize the values.
1714af732203SDimitry Andric   llvm::sort(ProcIdVec);
1715af732203SDimitry Andric   return ProcIdVec;
1716af732203SDimitry Andric }
1717af732203SDimitry Andric 
1718af732203SDimitry Andric static std::vector<PredTransition>
makePerProcessorTransitions(const PredTransition & Trans,ArrayRef<unsigned> ProcIndices)1719af732203SDimitry Andric makePerProcessorTransitions(const PredTransition &Trans,
1720af732203SDimitry Andric                             ArrayRef<unsigned> ProcIndices) {
1721af732203SDimitry Andric   std::vector<PredTransition> PerCpuTransVec;
1722af732203SDimitry Andric   for (unsigned ProcId : ProcIndices) {
1723af732203SDimitry Andric     assert(ProcId != 0);
1724af732203SDimitry Andric     PerCpuTransVec.push_back(Trans);
1725af732203SDimitry Andric     PerCpuTransVec.back().ProcIndex = ProcId;
1726af732203SDimitry Andric   }
1727af732203SDimitry Andric   return PerCpuTransVec;
1728af732203SDimitry Andric }
1729af732203SDimitry Andric 
17300b57cec5SDimitry Andric // Create new SchedClasses for the given ReadWrite list. If any of the
17310b57cec5SDimitry Andric // ReadWrites refers to a SchedVariant, create a new SchedClass for each variant
17320b57cec5SDimitry Andric // of the ReadWrite list, following Aliases if necessary.
inferFromRW(ArrayRef<unsigned> OperWrites,ArrayRef<unsigned> OperReads,unsigned FromClassIdx,ArrayRef<unsigned> ProcIndices)17330b57cec5SDimitry Andric void CodeGenSchedModels::inferFromRW(ArrayRef<unsigned> OperWrites,
17340b57cec5SDimitry Andric                                      ArrayRef<unsigned> OperReads,
17350b57cec5SDimitry Andric                                      unsigned FromClassIdx,
17360b57cec5SDimitry Andric                                      ArrayRef<unsigned> ProcIndices) {
17370b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "INFER RW proc("; dumpIdxVec(ProcIndices);
17380b57cec5SDimitry Andric              dbgs() << ") ");
17390b57cec5SDimitry Andric   // Create a seed transition with an empty PredTerm and the expanded sequences
17400b57cec5SDimitry Andric   // of SchedWrites for the current SchedClass.
17410b57cec5SDimitry Andric   std::vector<PredTransition> LastTransitions;
17420b57cec5SDimitry Andric   LastTransitions.emplace_back();
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric   for (unsigned WriteIdx : OperWrites) {
17450b57cec5SDimitry Andric     IdxVec WriteSeq;
17460b57cec5SDimitry Andric     expandRWSequence(WriteIdx, WriteSeq, /*IsRead=*/false);
17470b57cec5SDimitry Andric     LastTransitions[0].WriteSequences.emplace_back();
17480b57cec5SDimitry Andric     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].WriteSequences.back();
17490b57cec5SDimitry Andric     Seq.append(WriteSeq.begin(), WriteSeq.end());
17500b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
17510b57cec5SDimitry Andric   }
17520b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << " Reads: ");
17530b57cec5SDimitry Andric   for (unsigned ReadIdx : OperReads) {
17540b57cec5SDimitry Andric     IdxVec ReadSeq;
17550b57cec5SDimitry Andric     expandRWSequence(ReadIdx, ReadSeq, /*IsRead=*/true);
17560b57cec5SDimitry Andric     LastTransitions[0].ReadSequences.emplace_back();
17570b57cec5SDimitry Andric     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].ReadSequences.back();
17580b57cec5SDimitry Andric     Seq.append(ReadSeq.begin(), ReadSeq.end());
17590b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
17600b57cec5SDimitry Andric   }
17610b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << '\n');
17620b57cec5SDimitry Andric 
1763af732203SDimitry Andric   LastTransitions = makePerProcessorTransitions(
1764af732203SDimitry Andric       LastTransitions[0], llvm::is_contained(ProcIndices, 0)
1765af732203SDimitry Andric                               ? ArrayRef<unsigned>(getAllProcIndices())
1766af732203SDimitry Andric                               : ProcIndices);
17670b57cec5SDimitry Andric   // Collect all PredTransitions for individual operands.
17680b57cec5SDimitry Andric   // Iterate until no variant writes remain.
1769af732203SDimitry Andric   bool SubstitutedAny;
1770af732203SDimitry Andric   do {
1771af732203SDimitry Andric     SubstitutedAny = false;
17720b57cec5SDimitry Andric     PredTransitions Transitions(*this);
17730b57cec5SDimitry Andric     for (const PredTransition &Trans : LastTransitions)
1774af732203SDimitry Andric       SubstitutedAny |= Transitions.substituteVariants(Trans);
17750b57cec5SDimitry Andric     LLVM_DEBUG(Transitions.dump());
17760b57cec5SDimitry Andric     LastTransitions.swap(Transitions.TransVec);
1777af732203SDimitry Andric   } while (SubstitutedAny);
17780b57cec5SDimitry Andric 
17790b57cec5SDimitry Andric   // WARNING: We are about to mutate the SchedClasses vector. Do not refer to
17800b57cec5SDimitry Andric   // OperWrites, OperReads, or ProcIndices after calling inferFromTransitions.
17810b57cec5SDimitry Andric   inferFromTransitions(LastTransitions, FromClassIdx, *this);
17820b57cec5SDimitry Andric }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric // Check if any processor resource group contains all resource records in
17850b57cec5SDimitry Andric // SubUnits.
hasSuperGroup(RecVec & SubUnits,CodeGenProcModel & PM)17860b57cec5SDimitry Andric bool CodeGenSchedModels::hasSuperGroup(RecVec &SubUnits, CodeGenProcModel &PM) {
1787*5f7ddb14SDimitry Andric   for (Record *ProcResourceDef : PM.ProcResourceDefs) {
1788*5f7ddb14SDimitry Andric     if (!ProcResourceDef->isSubClassOf("ProcResGroup"))
17890b57cec5SDimitry Andric       continue;
1790*5f7ddb14SDimitry Andric     RecVec SuperUnits = ProcResourceDef->getValueAsListOfDefs("Resources");
17910b57cec5SDimitry Andric     RecIter RI = SubUnits.begin(), RE = SubUnits.end();
17920b57cec5SDimitry Andric     for ( ; RI != RE; ++RI) {
17930b57cec5SDimitry Andric       if (!is_contained(SuperUnits, *RI)) {
17940b57cec5SDimitry Andric         break;
17950b57cec5SDimitry Andric       }
17960b57cec5SDimitry Andric     }
17970b57cec5SDimitry Andric     if (RI == RE)
17980b57cec5SDimitry Andric       return true;
17990b57cec5SDimitry Andric   }
18000b57cec5SDimitry Andric   return false;
18010b57cec5SDimitry Andric }
18020b57cec5SDimitry Andric 
18030b57cec5SDimitry Andric // Verify that overlapping groups have a common supergroup.
verifyProcResourceGroups(CodeGenProcModel & PM)18040b57cec5SDimitry Andric void CodeGenSchedModels::verifyProcResourceGroups(CodeGenProcModel &PM) {
18050b57cec5SDimitry Andric   for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
18060b57cec5SDimitry Andric     if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
18070b57cec5SDimitry Andric       continue;
18080b57cec5SDimitry Andric     RecVec CheckUnits =
18090b57cec5SDimitry Andric       PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
18100b57cec5SDimitry Andric     for (unsigned j = i+1; j < e; ++j) {
18110b57cec5SDimitry Andric       if (!PM.ProcResourceDefs[j]->isSubClassOf("ProcResGroup"))
18120b57cec5SDimitry Andric         continue;
18130b57cec5SDimitry Andric       RecVec OtherUnits =
18140b57cec5SDimitry Andric         PM.ProcResourceDefs[j]->getValueAsListOfDefs("Resources");
18150b57cec5SDimitry Andric       if (std::find_first_of(CheckUnits.begin(), CheckUnits.end(),
18160b57cec5SDimitry Andric                              OtherUnits.begin(), OtherUnits.end())
18170b57cec5SDimitry Andric           != CheckUnits.end()) {
18180b57cec5SDimitry Andric         // CheckUnits and OtherUnits overlap
1819af732203SDimitry Andric         llvm::append_range(OtherUnits, CheckUnits);
18200b57cec5SDimitry Andric         if (!hasSuperGroup(OtherUnits, PM)) {
18210b57cec5SDimitry Andric           PrintFatalError((PM.ProcResourceDefs[i])->getLoc(),
18220b57cec5SDimitry Andric                           "proc resource group overlaps with "
18230b57cec5SDimitry Andric                           + PM.ProcResourceDefs[j]->getName()
18240b57cec5SDimitry Andric                           + " but no supergroup contains both.");
18250b57cec5SDimitry Andric         }
18260b57cec5SDimitry Andric       }
18270b57cec5SDimitry Andric     }
18280b57cec5SDimitry Andric   }
18290b57cec5SDimitry Andric }
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric // Collect all the RegisterFile definitions available in this target.
collectRegisterFiles()18320b57cec5SDimitry Andric void CodeGenSchedModels::collectRegisterFiles() {
18330b57cec5SDimitry Andric   RecVec RegisterFileDefs = Records.getAllDerivedDefinitions("RegisterFile");
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric   // RegisterFiles is the vector of CodeGenRegisterFile.
18360b57cec5SDimitry Andric   for (Record *RF : RegisterFileDefs) {
18370b57cec5SDimitry Andric     // For each register file definition, construct a CodeGenRegisterFile object
18380b57cec5SDimitry Andric     // and add it to the appropriate scheduling model.
18390b57cec5SDimitry Andric     CodeGenProcModel &PM = getProcModel(RF->getValueAsDef("SchedModel"));
18400b57cec5SDimitry Andric     PM.RegisterFiles.emplace_back(CodeGenRegisterFile(RF->getName(),RF));
18410b57cec5SDimitry Andric     CodeGenRegisterFile &CGRF = PM.RegisterFiles.back();
18420b57cec5SDimitry Andric     CGRF.MaxMovesEliminatedPerCycle =
18430b57cec5SDimitry Andric         RF->getValueAsInt("MaxMovesEliminatedPerCycle");
18440b57cec5SDimitry Andric     CGRF.AllowZeroMoveEliminationOnly =
18450b57cec5SDimitry Andric         RF->getValueAsBit("AllowZeroMoveEliminationOnly");
18460b57cec5SDimitry Andric 
18470b57cec5SDimitry Andric     // Now set the number of physical registers as well as the cost of registers
18480b57cec5SDimitry Andric     // in each register class.
18490b57cec5SDimitry Andric     CGRF.NumPhysRegs = RF->getValueAsInt("NumPhysRegs");
18500b57cec5SDimitry Andric     if (!CGRF.NumPhysRegs) {
18510b57cec5SDimitry Andric       PrintFatalError(RF->getLoc(),
18520b57cec5SDimitry Andric                       "Invalid RegisterFile with zero physical registers");
18530b57cec5SDimitry Andric     }
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric     RecVec RegisterClasses = RF->getValueAsListOfDefs("RegClasses");
18560b57cec5SDimitry Andric     std::vector<int64_t> RegisterCosts = RF->getValueAsListOfInts("RegCosts");
18570b57cec5SDimitry Andric     ListInit *MoveElimInfo = RF->getValueAsListInit("AllowMoveElimination");
18580b57cec5SDimitry Andric     for (unsigned I = 0, E = RegisterClasses.size(); I < E; ++I) {
18590b57cec5SDimitry Andric       int Cost = RegisterCosts.size() > I ? RegisterCosts[I] : 1;
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric       bool AllowMoveElim = false;
18620b57cec5SDimitry Andric       if (MoveElimInfo->size() > I) {
18630b57cec5SDimitry Andric         BitInit *Val = cast<BitInit>(MoveElimInfo->getElement(I));
18640b57cec5SDimitry Andric         AllowMoveElim = Val->getValue();
18650b57cec5SDimitry Andric       }
18660b57cec5SDimitry Andric 
18670b57cec5SDimitry Andric       CGRF.Costs.emplace_back(RegisterClasses[I], Cost, AllowMoveElim);
18680b57cec5SDimitry Andric     }
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric }
18710b57cec5SDimitry Andric 
18720b57cec5SDimitry Andric // Collect and sort WriteRes, ReadAdvance, and ProcResources.
collectProcResources()18730b57cec5SDimitry Andric void CodeGenSchedModels::collectProcResources() {
18740b57cec5SDimitry Andric   ProcResourceDefs = Records.getAllDerivedDefinitions("ProcResourceUnits");
18750b57cec5SDimitry Andric   ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric   // Add any subtarget-specific SchedReadWrites that are directly associated
18780b57cec5SDimitry Andric   // with processor resources. Refer to the parent SchedClass's ProcIndices to
18790b57cec5SDimitry Andric   // determine which processors they apply to.
18800b57cec5SDimitry Andric   for (const CodeGenSchedClass &SC :
18810b57cec5SDimitry Andric        make_range(schedClassBegin(), schedClassEnd())) {
18820b57cec5SDimitry Andric     if (SC.ItinClassDef) {
18830b57cec5SDimitry Andric       collectItinProcResources(SC.ItinClassDef);
18840b57cec5SDimitry Andric       continue;
18850b57cec5SDimitry Andric     }
18860b57cec5SDimitry Andric 
18870b57cec5SDimitry Andric     // This class may have a default ReadWrite list which can be overriden by
18880b57cec5SDimitry Andric     // InstRW definitions.
18890b57cec5SDimitry Andric     for (Record *RW : SC.InstRWs) {
18900b57cec5SDimitry Andric       Record *RWModelDef = RW->getValueAsDef("SchedModel");
18910b57cec5SDimitry Andric       unsigned PIdx = getProcModel(RWModelDef).Index;
18920b57cec5SDimitry Andric       IdxVec Writes, Reads;
18930b57cec5SDimitry Andric       findRWs(RW->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
18940b57cec5SDimitry Andric       collectRWResources(Writes, Reads, PIdx);
18950b57cec5SDimitry Andric     }
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric     collectRWResources(SC.Writes, SC.Reads, SC.ProcIndices);
18980b57cec5SDimitry Andric   }
18990b57cec5SDimitry Andric   // Add resources separately defined by each subtarget.
19000b57cec5SDimitry Andric   RecVec WRDefs = Records.getAllDerivedDefinitions("WriteRes");
19010b57cec5SDimitry Andric   for (Record *WR : WRDefs) {
19020b57cec5SDimitry Andric     Record *ModelDef = WR->getValueAsDef("SchedModel");
19030b57cec5SDimitry Andric     addWriteRes(WR, getProcModel(ModelDef).Index);
19040b57cec5SDimitry Andric   }
19050b57cec5SDimitry Andric   RecVec SWRDefs = Records.getAllDerivedDefinitions("SchedWriteRes");
19060b57cec5SDimitry Andric   for (Record *SWR : SWRDefs) {
19070b57cec5SDimitry Andric     Record *ModelDef = SWR->getValueAsDef("SchedModel");
19080b57cec5SDimitry Andric     addWriteRes(SWR, getProcModel(ModelDef).Index);
19090b57cec5SDimitry Andric   }
19100b57cec5SDimitry Andric   RecVec RADefs = Records.getAllDerivedDefinitions("ReadAdvance");
19110b57cec5SDimitry Andric   for (Record *RA : RADefs) {
19120b57cec5SDimitry Andric     Record *ModelDef = RA->getValueAsDef("SchedModel");
19130b57cec5SDimitry Andric     addReadAdvance(RA, getProcModel(ModelDef).Index);
19140b57cec5SDimitry Andric   }
19150b57cec5SDimitry Andric   RecVec SRADefs = Records.getAllDerivedDefinitions("SchedReadAdvance");
19160b57cec5SDimitry Andric   for (Record *SRA : SRADefs) {
19170b57cec5SDimitry Andric     if (SRA->getValueInit("SchedModel")->isComplete()) {
19180b57cec5SDimitry Andric       Record *ModelDef = SRA->getValueAsDef("SchedModel");
19190b57cec5SDimitry Andric       addReadAdvance(SRA, getProcModel(ModelDef).Index);
19200b57cec5SDimitry Andric     }
19210b57cec5SDimitry Andric   }
19220b57cec5SDimitry Andric   // Add ProcResGroups that are defined within this processor model, which may
19230b57cec5SDimitry Andric   // not be directly referenced but may directly specify a buffer size.
19240b57cec5SDimitry Andric   RecVec ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
19250b57cec5SDimitry Andric   for (Record *PRG : ProcResGroups) {
19260b57cec5SDimitry Andric     if (!PRG->getValueInit("SchedModel")->isComplete())
19270b57cec5SDimitry Andric       continue;
19280b57cec5SDimitry Andric     CodeGenProcModel &PM = getProcModel(PRG->getValueAsDef("SchedModel"));
19290b57cec5SDimitry Andric     if (!is_contained(PM.ProcResourceDefs, PRG))
19300b57cec5SDimitry Andric       PM.ProcResourceDefs.push_back(PRG);
19310b57cec5SDimitry Andric   }
19320b57cec5SDimitry Andric   // Add ProcResourceUnits unconditionally.
19330b57cec5SDimitry Andric   for (Record *PRU : Records.getAllDerivedDefinitions("ProcResourceUnits")) {
19340b57cec5SDimitry Andric     if (!PRU->getValueInit("SchedModel")->isComplete())
19350b57cec5SDimitry Andric       continue;
19360b57cec5SDimitry Andric     CodeGenProcModel &PM = getProcModel(PRU->getValueAsDef("SchedModel"));
19370b57cec5SDimitry Andric     if (!is_contained(PM.ProcResourceDefs, PRU))
19380b57cec5SDimitry Andric       PM.ProcResourceDefs.push_back(PRU);
19390b57cec5SDimitry Andric   }
19400b57cec5SDimitry Andric   // Finalize each ProcModel by sorting the record arrays.
19410b57cec5SDimitry Andric   for (CodeGenProcModel &PM : ProcModels) {
19420b57cec5SDimitry Andric     llvm::sort(PM.WriteResDefs, LessRecord());
19430b57cec5SDimitry Andric     llvm::sort(PM.ReadAdvanceDefs, LessRecord());
19440b57cec5SDimitry Andric     llvm::sort(PM.ProcResourceDefs, LessRecord());
19450b57cec5SDimitry Andric     LLVM_DEBUG(
1946*5f7ddb14SDimitry Andric         PM.dump(); dbgs() << "WriteResDefs: "; for (auto WriteResDef
1947*5f7ddb14SDimitry Andric                                                     : PM.WriteResDefs) {
1948*5f7ddb14SDimitry Andric           if (WriteResDef->isSubClassOf("WriteRes"))
1949*5f7ddb14SDimitry Andric             dbgs() << WriteResDef->getValueAsDef("WriteType")->getName() << " ";
19500b57cec5SDimitry Andric           else
1951*5f7ddb14SDimitry Andric             dbgs() << WriteResDef->getName() << " ";
19520b57cec5SDimitry Andric         } dbgs() << "\nReadAdvanceDefs: ";
1953*5f7ddb14SDimitry Andric         for (Record *ReadAdvanceDef
1954*5f7ddb14SDimitry Andric              : PM.ReadAdvanceDefs) {
1955*5f7ddb14SDimitry Andric           if (ReadAdvanceDef->isSubClassOf("ReadAdvance"))
1956*5f7ddb14SDimitry Andric             dbgs() << ReadAdvanceDef->getValueAsDef("ReadType")->getName()
1957*5f7ddb14SDimitry Andric                    << " ";
19580b57cec5SDimitry Andric           else
1959*5f7ddb14SDimitry Andric             dbgs() << ReadAdvanceDef->getName() << " ";
19600b57cec5SDimitry Andric         } dbgs()
19610b57cec5SDimitry Andric         << "\nProcResourceDefs: ";
1962*5f7ddb14SDimitry Andric         for (Record *ProcResourceDef
1963*5f7ddb14SDimitry Andric              : PM.ProcResourceDefs) {
1964*5f7ddb14SDimitry Andric           dbgs() << ProcResourceDef->getName() << " ";
1965*5f7ddb14SDimitry Andric         } dbgs()
19660b57cec5SDimitry Andric         << '\n');
19670b57cec5SDimitry Andric     verifyProcResourceGroups(PM);
19680b57cec5SDimitry Andric   }
19690b57cec5SDimitry Andric 
19700b57cec5SDimitry Andric   ProcResourceDefs.clear();
19710b57cec5SDimitry Andric   ProcResGroups.clear();
19720b57cec5SDimitry Andric }
19730b57cec5SDimitry Andric 
checkCompleteness()19740b57cec5SDimitry Andric void CodeGenSchedModels::checkCompleteness() {
19750b57cec5SDimitry Andric   bool Complete = true;
19760b57cec5SDimitry Andric   bool HadCompleteModel = false;
19770b57cec5SDimitry Andric   for (const CodeGenProcModel &ProcModel : procModels()) {
19780b57cec5SDimitry Andric     const bool HasItineraries = ProcModel.hasItineraries();
19790b57cec5SDimitry Andric     if (!ProcModel.ModelDef->getValueAsBit("CompleteModel"))
19800b57cec5SDimitry Andric       continue;
19810b57cec5SDimitry Andric     for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
19820b57cec5SDimitry Andric       if (Inst->hasNoSchedulingInfo)
19830b57cec5SDimitry Andric         continue;
19840b57cec5SDimitry Andric       if (ProcModel.isUnsupported(*Inst))
19850b57cec5SDimitry Andric         continue;
19860b57cec5SDimitry Andric       unsigned SCIdx = getSchedClassIdx(*Inst);
19870b57cec5SDimitry Andric       if (!SCIdx) {
19880b57cec5SDimitry Andric         if (Inst->TheDef->isValueUnset("SchedRW") && !HadCompleteModel) {
19890b57cec5SDimitry Andric           PrintError(Inst->TheDef->getLoc(),
19900b57cec5SDimitry Andric                      "No schedule information for instruction '" +
19910b57cec5SDimitry Andric                          Inst->TheDef->getName() + "' in SchedMachineModel '" +
19920b57cec5SDimitry Andric                      ProcModel.ModelDef->getName() + "'");
19930b57cec5SDimitry Andric           Complete = false;
19940b57cec5SDimitry Andric         }
19950b57cec5SDimitry Andric         continue;
19960b57cec5SDimitry Andric       }
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric       const CodeGenSchedClass &SC = getSchedClass(SCIdx);
19990b57cec5SDimitry Andric       if (!SC.Writes.empty())
20000b57cec5SDimitry Andric         continue;
20010b57cec5SDimitry Andric       if (HasItineraries && SC.ItinClassDef != nullptr &&
20020b57cec5SDimitry Andric           SC.ItinClassDef->getName() != "NoItinerary")
20030b57cec5SDimitry Andric         continue;
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric       const RecVec &InstRWs = SC.InstRWs;
20060b57cec5SDimitry Andric       auto I = find_if(InstRWs, [&ProcModel](const Record *R) {
20070b57cec5SDimitry Andric         return R->getValueAsDef("SchedModel") == ProcModel.ModelDef;
20080b57cec5SDimitry Andric       });
20090b57cec5SDimitry Andric       if (I == InstRWs.end()) {
20100b57cec5SDimitry Andric         PrintError(Inst->TheDef->getLoc(), "'" + ProcModel.ModelName +
20110b57cec5SDimitry Andric                                                "' lacks information for '" +
20120b57cec5SDimitry Andric                                                Inst->TheDef->getName() + "'");
20130b57cec5SDimitry Andric         Complete = false;
20140b57cec5SDimitry Andric       }
20150b57cec5SDimitry Andric     }
20160b57cec5SDimitry Andric     HadCompleteModel = true;
20170b57cec5SDimitry Andric   }
20180b57cec5SDimitry Andric   if (!Complete) {
20190b57cec5SDimitry Andric     errs() << "\n\nIncomplete schedule models found.\n"
20200b57cec5SDimitry Andric       << "- Consider setting 'CompleteModel = 0' while developing new models.\n"
20210b57cec5SDimitry Andric       << "- Pseudo instructions can be marked with 'hasNoSchedulingInfo = 1'.\n"
20220b57cec5SDimitry Andric       << "- Instructions should usually have Sched<[...]> as a superclass, "
20230b57cec5SDimitry Andric          "you may temporarily use an empty list.\n"
20240b57cec5SDimitry Andric       << "- Instructions related to unsupported features can be excluded with "
20250b57cec5SDimitry Andric          "list<Predicate> UnsupportedFeatures = [HasA,..,HasY]; in the "
20260b57cec5SDimitry Andric          "processor model.\n\n";
20270b57cec5SDimitry Andric     PrintFatalError("Incomplete schedule model");
20280b57cec5SDimitry Andric   }
20290b57cec5SDimitry Andric }
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric // Collect itinerary class resources for each processor.
collectItinProcResources(Record * ItinClassDef)20320b57cec5SDimitry Andric void CodeGenSchedModels::collectItinProcResources(Record *ItinClassDef) {
20330b57cec5SDimitry Andric   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
20340b57cec5SDimitry Andric     const CodeGenProcModel &PM = ProcModels[PIdx];
20350b57cec5SDimitry Andric     // For all ItinRW entries.
20360b57cec5SDimitry Andric     bool HasMatch = false;
20370b57cec5SDimitry Andric     for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
20380b57cec5SDimitry Andric          II != IE; ++II) {
20390b57cec5SDimitry Andric       RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
2040af732203SDimitry Andric       if (!llvm::is_contained(Matched, ItinClassDef))
20410b57cec5SDimitry Andric         continue;
20420b57cec5SDimitry Andric       if (HasMatch)
20430b57cec5SDimitry Andric         PrintFatalError((*II)->getLoc(), "Duplicate itinerary class "
20440b57cec5SDimitry Andric                         + ItinClassDef->getName()
20450b57cec5SDimitry Andric                         + " in ItinResources for " + PM.ModelName);
20460b57cec5SDimitry Andric       HasMatch = true;
20470b57cec5SDimitry Andric       IdxVec Writes, Reads;
20480b57cec5SDimitry Andric       findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
20490b57cec5SDimitry Andric       collectRWResources(Writes, Reads, PIdx);
20500b57cec5SDimitry Andric     }
20510b57cec5SDimitry Andric   }
20520b57cec5SDimitry Andric }
20530b57cec5SDimitry Andric 
collectRWResources(unsigned RWIdx,bool IsRead,ArrayRef<unsigned> ProcIndices)20540b57cec5SDimitry Andric void CodeGenSchedModels::collectRWResources(unsigned RWIdx, bool IsRead,
20550b57cec5SDimitry Andric                                             ArrayRef<unsigned> ProcIndices) {
20560b57cec5SDimitry Andric   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
20570b57cec5SDimitry Andric   if (SchedRW.TheDef) {
20580b57cec5SDimitry Andric     if (!IsRead && SchedRW.TheDef->isSubClassOf("SchedWriteRes")) {
20590b57cec5SDimitry Andric       for (unsigned Idx : ProcIndices)
20600b57cec5SDimitry Andric         addWriteRes(SchedRW.TheDef, Idx);
20610b57cec5SDimitry Andric     }
20620b57cec5SDimitry Andric     else if (IsRead && SchedRW.TheDef->isSubClassOf("SchedReadAdvance")) {
20630b57cec5SDimitry Andric       for (unsigned Idx : ProcIndices)
20640b57cec5SDimitry Andric         addReadAdvance(SchedRW.TheDef, Idx);
20650b57cec5SDimitry Andric     }
20660b57cec5SDimitry Andric   }
2067*5f7ddb14SDimitry Andric   for (auto *Alias : SchedRW.Aliases) {
20680b57cec5SDimitry Andric     IdxVec AliasProcIndices;
2069*5f7ddb14SDimitry Andric     if (Alias->getValueInit("SchedModel")->isComplete()) {
20700b57cec5SDimitry Andric       AliasProcIndices.push_back(
2071*5f7ddb14SDimitry Andric           getProcModel(Alias->getValueAsDef("SchedModel")).Index);
2072*5f7ddb14SDimitry Andric     } else
20730b57cec5SDimitry Andric       AliasProcIndices = ProcIndices;
2074*5f7ddb14SDimitry Andric     const CodeGenSchedRW &AliasRW = getSchedRW(Alias->getValueAsDef("AliasRW"));
20750b57cec5SDimitry Andric     assert(AliasRW.IsRead == IsRead && "cannot alias reads to writes");
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric     IdxVec ExpandedRWs;
20780b57cec5SDimitry Andric     expandRWSequence(AliasRW.Index, ExpandedRWs, IsRead);
2079*5f7ddb14SDimitry Andric     for (unsigned int ExpandedRW : ExpandedRWs) {
2080*5f7ddb14SDimitry Andric       collectRWResources(ExpandedRW, IsRead, AliasProcIndices);
20810b57cec5SDimitry Andric     }
20820b57cec5SDimitry Andric   }
20830b57cec5SDimitry Andric }
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric // Collect resources for a set of read/write types and processor indices.
collectRWResources(ArrayRef<unsigned> Writes,ArrayRef<unsigned> Reads,ArrayRef<unsigned> ProcIndices)20860b57cec5SDimitry Andric void CodeGenSchedModels::collectRWResources(ArrayRef<unsigned> Writes,
20870b57cec5SDimitry Andric                                             ArrayRef<unsigned> Reads,
20880b57cec5SDimitry Andric                                             ArrayRef<unsigned> ProcIndices) {
20890b57cec5SDimitry Andric   for (unsigned Idx : Writes)
20900b57cec5SDimitry Andric     collectRWResources(Idx, /*IsRead=*/false, ProcIndices);
20910b57cec5SDimitry Andric 
20920b57cec5SDimitry Andric   for (unsigned Idx : Reads)
20930b57cec5SDimitry Andric     collectRWResources(Idx, /*IsRead=*/true, ProcIndices);
20940b57cec5SDimitry Andric }
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric // Find the processor's resource units for this kind of resource.
findProcResUnits(Record * ProcResKind,const CodeGenProcModel & PM,ArrayRef<SMLoc> Loc) const20970b57cec5SDimitry Andric Record *CodeGenSchedModels::findProcResUnits(Record *ProcResKind,
20980b57cec5SDimitry Andric                                              const CodeGenProcModel &PM,
20990b57cec5SDimitry Andric                                              ArrayRef<SMLoc> Loc) const {
21000b57cec5SDimitry Andric   if (ProcResKind->isSubClassOf("ProcResourceUnits"))
21010b57cec5SDimitry Andric     return ProcResKind;
21020b57cec5SDimitry Andric 
21030b57cec5SDimitry Andric   Record *ProcUnitDef = nullptr;
21040b57cec5SDimitry Andric   assert(!ProcResourceDefs.empty());
21050b57cec5SDimitry Andric   assert(!ProcResGroups.empty());
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric   for (Record *ProcResDef : ProcResourceDefs) {
21080b57cec5SDimitry Andric     if (ProcResDef->getValueAsDef("Kind") == ProcResKind
21090b57cec5SDimitry Andric         && ProcResDef->getValueAsDef("SchedModel") == PM.ModelDef) {
21100b57cec5SDimitry Andric       if (ProcUnitDef) {
21110b57cec5SDimitry Andric         PrintFatalError(Loc,
21120b57cec5SDimitry Andric                         "Multiple ProcessorResourceUnits associated with "
21130b57cec5SDimitry Andric                         + ProcResKind->getName());
21140b57cec5SDimitry Andric       }
21150b57cec5SDimitry Andric       ProcUnitDef = ProcResDef;
21160b57cec5SDimitry Andric     }
21170b57cec5SDimitry Andric   }
21180b57cec5SDimitry Andric   for (Record *ProcResGroup : ProcResGroups) {
21190b57cec5SDimitry Andric     if (ProcResGroup == ProcResKind
21200b57cec5SDimitry Andric         && ProcResGroup->getValueAsDef("SchedModel") == PM.ModelDef) {
21210b57cec5SDimitry Andric       if (ProcUnitDef) {
21220b57cec5SDimitry Andric         PrintFatalError(Loc,
21230b57cec5SDimitry Andric                         "Multiple ProcessorResourceUnits associated with "
21240b57cec5SDimitry Andric                         + ProcResKind->getName());
21250b57cec5SDimitry Andric       }
21260b57cec5SDimitry Andric       ProcUnitDef = ProcResGroup;
21270b57cec5SDimitry Andric     }
21280b57cec5SDimitry Andric   }
21290b57cec5SDimitry Andric   if (!ProcUnitDef) {
21300b57cec5SDimitry Andric     PrintFatalError(Loc,
21310b57cec5SDimitry Andric                     "No ProcessorResources associated with "
21320b57cec5SDimitry Andric                     + ProcResKind->getName());
21330b57cec5SDimitry Andric   }
21340b57cec5SDimitry Andric   return ProcUnitDef;
21350b57cec5SDimitry Andric }
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric // Iteratively add a resource and its super resources.
addProcResource(Record * ProcResKind,CodeGenProcModel & PM,ArrayRef<SMLoc> Loc)21380b57cec5SDimitry Andric void CodeGenSchedModels::addProcResource(Record *ProcResKind,
21390b57cec5SDimitry Andric                                          CodeGenProcModel &PM,
21400b57cec5SDimitry Andric                                          ArrayRef<SMLoc> Loc) {
21410b57cec5SDimitry Andric   while (true) {
21420b57cec5SDimitry Andric     Record *ProcResUnits = findProcResUnits(ProcResKind, PM, Loc);
21430b57cec5SDimitry Andric 
21440b57cec5SDimitry Andric     // See if this ProcResource is already associated with this processor.
21450b57cec5SDimitry Andric     if (is_contained(PM.ProcResourceDefs, ProcResUnits))
21460b57cec5SDimitry Andric       return;
21470b57cec5SDimitry Andric 
21480b57cec5SDimitry Andric     PM.ProcResourceDefs.push_back(ProcResUnits);
21490b57cec5SDimitry Andric     if (ProcResUnits->isSubClassOf("ProcResGroup"))
21500b57cec5SDimitry Andric       return;
21510b57cec5SDimitry Andric 
21520b57cec5SDimitry Andric     if (!ProcResUnits->getValueInit("Super")->isComplete())
21530b57cec5SDimitry Andric       return;
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric     ProcResKind = ProcResUnits->getValueAsDef("Super");
21560b57cec5SDimitry Andric   }
21570b57cec5SDimitry Andric }
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric // Add resources for a SchedWrite to this processor if they don't exist.
addWriteRes(Record * ProcWriteResDef,unsigned PIdx)21600b57cec5SDimitry Andric void CodeGenSchedModels::addWriteRes(Record *ProcWriteResDef, unsigned PIdx) {
21610b57cec5SDimitry Andric   assert(PIdx && "don't add resources to an invalid Processor model");
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric   RecVec &WRDefs = ProcModels[PIdx].WriteResDefs;
21640b57cec5SDimitry Andric   if (is_contained(WRDefs, ProcWriteResDef))
21650b57cec5SDimitry Andric     return;
21660b57cec5SDimitry Andric   WRDefs.push_back(ProcWriteResDef);
21670b57cec5SDimitry Andric 
21680b57cec5SDimitry Andric   // Visit ProcResourceKinds referenced by the newly discovered WriteRes.
21690b57cec5SDimitry Andric   RecVec ProcResDefs = ProcWriteResDef->getValueAsListOfDefs("ProcResources");
2170*5f7ddb14SDimitry Andric   for (auto *ProcResDef : ProcResDefs) {
2171*5f7ddb14SDimitry Andric     addProcResource(ProcResDef, ProcModels[PIdx], ProcWriteResDef->getLoc());
21720b57cec5SDimitry Andric   }
21730b57cec5SDimitry Andric }
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric // Add resources for a ReadAdvance to this processor if they don't exist.
addReadAdvance(Record * ProcReadAdvanceDef,unsigned PIdx)21760b57cec5SDimitry Andric void CodeGenSchedModels::addReadAdvance(Record *ProcReadAdvanceDef,
21770b57cec5SDimitry Andric                                         unsigned PIdx) {
21780b57cec5SDimitry Andric   RecVec &RADefs = ProcModels[PIdx].ReadAdvanceDefs;
21790b57cec5SDimitry Andric   if (is_contained(RADefs, ProcReadAdvanceDef))
21800b57cec5SDimitry Andric     return;
21810b57cec5SDimitry Andric   RADefs.push_back(ProcReadAdvanceDef);
21820b57cec5SDimitry Andric }
21830b57cec5SDimitry Andric 
getProcResourceIdx(Record * PRDef) const21840b57cec5SDimitry Andric unsigned CodeGenProcModel::getProcResourceIdx(Record *PRDef) const {
21850b57cec5SDimitry Andric   RecIter PRPos = find(ProcResourceDefs, PRDef);
21860b57cec5SDimitry Andric   if (PRPos == ProcResourceDefs.end())
21870b57cec5SDimitry Andric     PrintFatalError(PRDef->getLoc(), "ProcResource def is not included in "
21880b57cec5SDimitry Andric                     "the ProcResources list for " + ModelName);
21890b57cec5SDimitry Andric   // Idx=0 is reserved for invalid.
21900b57cec5SDimitry Andric   return 1 + (PRPos - ProcResourceDefs.begin());
21910b57cec5SDimitry Andric }
21920b57cec5SDimitry Andric 
isUnsupported(const CodeGenInstruction & Inst) const21930b57cec5SDimitry Andric bool CodeGenProcModel::isUnsupported(const CodeGenInstruction &Inst) const {
21940b57cec5SDimitry Andric   for (const Record *TheDef : UnsupportedFeaturesDefs) {
21950b57cec5SDimitry Andric     for (const Record *PredDef : Inst.TheDef->getValueAsListOfDefs("Predicates")) {
21960b57cec5SDimitry Andric       if (TheDef->getName() == PredDef->getName())
21970b57cec5SDimitry Andric         return true;
21980b57cec5SDimitry Andric     }
21990b57cec5SDimitry Andric   }
22000b57cec5SDimitry Andric   return false;
22010b57cec5SDimitry Andric }
22020b57cec5SDimitry Andric 
22030b57cec5SDimitry Andric #ifndef NDEBUG
dump() const22040b57cec5SDimitry Andric void CodeGenProcModel::dump() const {
22050b57cec5SDimitry Andric   dbgs() << Index << ": " << ModelName << " "
22060b57cec5SDimitry Andric          << (ModelDef ? ModelDef->getName() : "inferred") << " "
22070b57cec5SDimitry Andric          << (ItinsDef ? ItinsDef->getName() : "no itinerary") << '\n';
22080b57cec5SDimitry Andric }
22090b57cec5SDimitry Andric 
dump() const22100b57cec5SDimitry Andric void CodeGenSchedRW::dump() const {
22110b57cec5SDimitry Andric   dbgs() << Name << (IsVariadic ? " (V) " : " ");
22120b57cec5SDimitry Andric   if (IsSequence) {
22130b57cec5SDimitry Andric     dbgs() << "(";
22140b57cec5SDimitry Andric     dumpIdxVec(Sequence);
22150b57cec5SDimitry Andric     dbgs() << ")";
22160b57cec5SDimitry Andric   }
22170b57cec5SDimitry Andric }
22180b57cec5SDimitry Andric 
dump(const CodeGenSchedModels * SchedModels) const22190b57cec5SDimitry Andric void CodeGenSchedClass::dump(const CodeGenSchedModels* SchedModels) const {
22200b57cec5SDimitry Andric   dbgs() << "SCHEDCLASS " << Index << ":" << Name << '\n'
22210b57cec5SDimitry Andric          << "  Writes: ";
22220b57cec5SDimitry Andric   for (unsigned i = 0, N = Writes.size(); i < N; ++i) {
22230b57cec5SDimitry Andric     SchedModels->getSchedWrite(Writes[i]).dump();
22240b57cec5SDimitry Andric     if (i < N-1) {
22250b57cec5SDimitry Andric       dbgs() << '\n';
22260b57cec5SDimitry Andric       dbgs().indent(10);
22270b57cec5SDimitry Andric     }
22280b57cec5SDimitry Andric   }
22290b57cec5SDimitry Andric   dbgs() << "\n  Reads: ";
22300b57cec5SDimitry Andric   for (unsigned i = 0, N = Reads.size(); i < N; ++i) {
22310b57cec5SDimitry Andric     SchedModels->getSchedRead(Reads[i]).dump();
22320b57cec5SDimitry Andric     if (i < N-1) {
22330b57cec5SDimitry Andric       dbgs() << '\n';
22340b57cec5SDimitry Andric       dbgs().indent(10);
22350b57cec5SDimitry Andric     }
22360b57cec5SDimitry Andric   }
2237af732203SDimitry Andric   dbgs() << "\n  ProcIdx: "; dumpIdxVec(ProcIndices);
22380b57cec5SDimitry Andric   if (!Transitions.empty()) {
22390b57cec5SDimitry Andric     dbgs() << "\n Transitions for Proc ";
22400b57cec5SDimitry Andric     for (const CodeGenSchedTransition &Transition : Transitions) {
2241af732203SDimitry Andric       dbgs() << Transition.ProcIndex << ", ";
22420b57cec5SDimitry Andric     }
22430b57cec5SDimitry Andric   }
2244af732203SDimitry Andric   dbgs() << '\n';
22450b57cec5SDimitry Andric }
22460b57cec5SDimitry Andric 
dump() const22470b57cec5SDimitry Andric void PredTransitions::dump() const {
22480b57cec5SDimitry Andric   dbgs() << "Expanded Variants:\n";
2249*5f7ddb14SDimitry Andric   for (const auto &TI : TransVec) {
22500b57cec5SDimitry Andric     dbgs() << "{";
2251*5f7ddb14SDimitry Andric     ListSeparator LS;
2252*5f7ddb14SDimitry Andric     for (const PredCheck &PC : TI.PredTerm)
2253*5f7ddb14SDimitry Andric       dbgs() << LS << SchedModels.getSchedRW(PC.RWIdx, PC.IsRead).Name << ":"
2254*5f7ddb14SDimitry Andric              << PC.Predicate->getName();
22550b57cec5SDimitry Andric     dbgs() << "},\n  => {";
22560b57cec5SDimitry Andric     for (SmallVectorImpl<SmallVector<unsigned, 4>>::const_iterator
2257*5f7ddb14SDimitry Andric              WSI = TI.WriteSequences.begin(),
2258*5f7ddb14SDimitry Andric              WSE = TI.WriteSequences.end();
22590b57cec5SDimitry Andric          WSI != WSE; ++WSI) {
22600b57cec5SDimitry Andric       dbgs() << "(";
2261*5f7ddb14SDimitry Andric       ListSeparator LS;
2262*5f7ddb14SDimitry Andric       for (unsigned N : *WSI)
2263*5f7ddb14SDimitry Andric         dbgs() << LS << SchedModels.getSchedWrite(N).Name;
22640b57cec5SDimitry Andric       dbgs() << "),";
22650b57cec5SDimitry Andric     }
22660b57cec5SDimitry Andric     dbgs() << "}\n";
22670b57cec5SDimitry Andric   }
22680b57cec5SDimitry Andric }
22690b57cec5SDimitry Andric #endif // NDEBUG
2270