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