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