1 //===- GIMatchTree.cpp - A decision tree to match GIMatchDag's ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "GIMatchTree.h" 10 11 #include "../CodeGenInstruction.h" 12 13 #include "llvm/Support/Debug.h" 14 #include "llvm/Support/Format.h" 15 #include "llvm/Support/ScopedPrinter.h" 16 #include "llvm/Support/raw_ostream.h" 17 #include "llvm/TableGen/Error.h" 18 #include "llvm/TableGen/Record.h" 19 20 #define DEBUG_TYPE "gimatchtree" 21 22 using namespace llvm; 23 24 void GIMatchTree::writeDOTGraph(raw_ostream &OS) const { 25 OS << "digraph \"matchtree\" {\n"; 26 writeDOTGraphNode(OS); 27 OS << "}\n"; 28 } 29 30 void GIMatchTree::writeDOTGraphNode(raw_ostream &OS) const { 31 OS << format(" Node%p", this) << " [shape=record,label=\"{"; 32 if (Partitioner) { 33 Partitioner->emitDescription(OS); 34 OS << "|" << Partitioner->getNumPartitions() << " partitions|"; 35 } else 36 OS << "No partitioner|"; 37 bool IsFullyTraversed = true; 38 bool IsFullyTested = true; 39 StringRef Separator = ""; 40 for (const auto &Leaf : PossibleLeaves) { 41 OS << Separator << Leaf.getName(); 42 Separator = ","; 43 if (!Leaf.isFullyTraversed()) 44 IsFullyTraversed = false; 45 if (!Leaf.isFullyTested()) 46 IsFullyTested = false; 47 } 48 if (!Partitioner && !IsFullyTraversed) 49 OS << "|Not fully traversed"; 50 if (!Partitioner && !IsFullyTested) { 51 OS << "|Not fully tested"; 52 if (IsFullyTraversed) { 53 for (const GIMatchTreeLeafInfo &Leaf : PossibleLeaves) { 54 if (Leaf.isFullyTested()) 55 continue; 56 OS << "\\n" << Leaf.getName() << ": " << &Leaf; 57 for (const GIMatchDagPredicate *P : Leaf.untested_predicates()) 58 OS << *P; 59 } 60 } 61 } 62 OS << "}\""; 63 if (!Partitioner && 64 (!IsFullyTraversed || !IsFullyTested || PossibleLeaves.size() > 1)) 65 OS << ",color=red"; 66 OS << "]\n"; 67 for (const auto &C : Children) 68 C.writeDOTGraphNode(OS); 69 writeDOTGraphEdges(OS); 70 } 71 72 void GIMatchTree::writeDOTGraphEdges(raw_ostream &OS) const { 73 for (const auto &Child : enumerate(Children)) { 74 OS << format(" Node%p", this) << " -> " << format("Node%p", &Child.value()) 75 << " [label=\"#" << Child.index() << " "; 76 Partitioner->emitPartitionName(OS, Child.index()); 77 OS << "\"]\n"; 78 } 79 } 80 81 GIMatchTreeBuilderLeafInfo::GIMatchTreeBuilderLeafInfo( 82 GIMatchTreeBuilder &Builder, StringRef Name, unsigned RootIdx, 83 const GIMatchDag &MatchDag, void *Data) 84 : Builder(Builder), Info(Name, RootIdx, Data), MatchDag(MatchDag), 85 InstrNodeToInfo(), 86 RemainingInstrNodes(BitVector(MatchDag.getNumInstrNodes(), true)), 87 RemainingEdges(BitVector(MatchDag.getNumEdges(), true)), 88 RemainingPredicates(BitVector(MatchDag.getNumPredicates(), true)), 89 TraversableEdges(MatchDag.getNumEdges()), 90 TestablePredicates(MatchDag.getNumPredicates()) { 91 // Number all the predicates in this DAG 92 for (auto &P : enumerate(MatchDag.predicates())) { 93 PredicateIDs.insert(std::make_pair(P.value(), P.index())); 94 } 95 96 // Number all the predicate dependencies in this DAG and set up a bitvector 97 // for each predicate indicating the unsatisfied dependencies. 98 for (auto &Dep : enumerate(MatchDag.predicate_edges())) { 99 PredicateDepIDs.insert(std::make_pair(Dep.value(), Dep.index())); 100 } 101 UnsatisfiedPredDepsForPred.resize(MatchDag.getNumPredicates(), 102 BitVector(PredicateDepIDs.size())); 103 for (auto &Dep : enumerate(MatchDag.predicate_edges())) { 104 unsigned ID = PredicateIDs.lookup(Dep.value()->getPredicate()); 105 UnsatisfiedPredDepsForPred[ID].set(Dep.index()); 106 } 107 } 108 109 void GIMatchTreeBuilderLeafInfo::declareInstr(const GIMatchDagInstr *Instr, unsigned ID) { 110 // Record the assignment of this instr to the given ID. 111 auto InfoI = InstrNodeToInfo.insert(std::make_pair( 112 Instr, GIMatchTreeInstrInfo(ID, Instr))); 113 InstrIDToInfo.insert(std::make_pair(ID, &InfoI.first->second)); 114 115 if (Instr == nullptr) 116 return; 117 118 if (!Instr->getUserAssignedName().empty()) 119 Info.bindInstrVariable(Instr->getUserAssignedName(), ID); 120 for (const auto &VarBinding : Instr->user_assigned_operand_names()) 121 Info.bindOperandVariable(VarBinding.second, ID, VarBinding.first); 122 123 // Clear the bit indicating we haven't visited this instr. 124 const auto &NodeI = find(MatchDag.instr_nodes(), Instr); 125 assert(NodeI != MatchDag.instr_nodes_end() && "Instr isn't in this DAG"); 126 unsigned InstrIdx = MatchDag.getInstrNodeIdx(NodeI); 127 RemainingInstrNodes.reset(InstrIdx); 128 129 // When we declare an instruction, we don't expose any traversable edges just 130 // yet. A partitioner has to check they exist and are registers before they 131 // are traversable. 132 133 // When we declare an instruction, we potentially activate some predicates. 134 // Mark the dependencies that are now satisfied as a result of this 135 // instruction and mark any predicates whose dependencies are fully 136 // satisfied. 137 for (auto &Dep : enumerate(MatchDag.predicate_edges())) { 138 if (Dep.value()->getRequiredMI() == Instr && 139 Dep.value()->getRequiredMO() == nullptr) { 140 for (auto &DepsFor : enumerate(UnsatisfiedPredDepsForPred)) { 141 DepsFor.value().reset(Dep.index()); 142 if (DepsFor.value().none()) 143 TestablePredicates.set(DepsFor.index()); 144 } 145 } 146 } 147 } 148 149 void GIMatchTreeBuilderLeafInfo::declareOperand(unsigned InstrID, 150 unsigned OpIdx) { 151 const GIMatchDagInstr *Instr = InstrIDToInfo.lookup(InstrID)->getInstrNode(); 152 153 OperandIDToInfo.insert(std::make_pair( 154 std::make_pair(InstrID, OpIdx), 155 GIMatchTreeOperandInfo(Instr, OpIdx))); 156 157 // When an operand becomes reachable, we potentially activate some traversals. 158 // Record the edges that can now be followed as a result of this 159 // instruction. 160 for (auto &E : enumerate(MatchDag.edges())) { 161 if (E.value()->getFromMI() == Instr && 162 E.value()->getFromMO()->getIdx() == OpIdx) { 163 TraversableEdges.set(E.index()); 164 } 165 } 166 167 // When an operand becomes reachable, we potentially activate some predicates. 168 // Clear the dependencies that are now satisfied as a result of this 169 // operand and activate any predicates whose dependencies are fully 170 // satisfied. 171 for (auto &Dep : enumerate(MatchDag.predicate_edges())) { 172 if (Dep.value()->getRequiredMI() == Instr && Dep.value()->getRequiredMO() && 173 Dep.value()->getRequiredMO()->getIdx() == OpIdx) { 174 for (auto &DepsFor : enumerate(UnsatisfiedPredDepsForPred)) { 175 DepsFor.value().reset(Dep.index()); 176 if (DepsFor.value().none()) 177 TestablePredicates.set(DepsFor.index()); 178 } 179 } 180 } 181 } 182 183 void GIMatchTreeBuilder::addPartitionersForInstr(unsigned InstrIdx) { 184 // Find the partitioners that can be used now that this node is 185 // uncovered. Our choices are: 186 // - Test the opcode 187 addPartitioner(std::make_unique<GIMatchTreeOpcodePartitioner>(InstrIdx)); 188 } 189 190 void GIMatchTreeBuilder::addPartitionersForOperand(unsigned InstrID, 191 unsigned OpIdx) { 192 LLVM_DEBUG(dbgs() << "Add partitioners for Instrs[" << InstrID 193 << "].getOperand(" << OpIdx << ")\n"); 194 addPartitioner( 195 std::make_unique<GIMatchTreeVRegDefPartitioner>(InstrID, OpIdx)); 196 } 197 198 void GIMatchTreeBuilder::filterRedundantPartitioners() { 199 // TODO: Filter partitioners for facts that are already known 200 // - If we know the opcode, we can elide the num operand check so long as 201 // the instruction has a fixed number of operands. 202 // - If we know an exact number of operands then we can elide further number 203 // of operand checks. 204 // - If the current min number of operands exceeds the one we want to check 205 // then we can elide it. 206 } 207 208 void GIMatchTreeBuilder::evaluatePartitioners() { 209 // Determine the partitioning the partitioner would produce 210 for (auto &Partitioner : Partitioners) { 211 LLVM_DEBUG(dbgs() << " Weighing up "; 212 Partitioner->emitDescription(dbgs()); dbgs() << "\n"); 213 Partitioner->repartition(Leaves); 214 LLVM_DEBUG(Partitioner->emitPartitionResults(dbgs())); 215 } 216 } 217 218 void GIMatchTreeBuilder::runStep() { 219 LLVM_DEBUG(dbgs() << "Building match tree node for " << TreeNode << "\n"); 220 LLVM_DEBUG(dbgs() << " Rules reachable at this node:\n"); 221 for (const auto &Leaf : Leaves) { 222 LLVM_DEBUG(dbgs() << " " << Leaf.getName() << " (" << &Leaf.getInfo() << "\n"); 223 TreeNode->addPossibleLeaf(Leaf.getInfo(), Leaf.isFullyTraversed(), 224 Leaf.isFullyTested()); 225 } 226 227 LLVM_DEBUG(dbgs() << " Partitioners available at this node:\n"); 228 #ifndef NDEBUG 229 for (const auto &Partitioner : Partitioners) 230 LLVM_DEBUG(dbgs() << " "; Partitioner->emitDescription(dbgs()); 231 dbgs() << "\n"); 232 #endif // ifndef NDEBUG 233 234 // Check for unreachable rules. Rules are unreachable if they are preceeded by 235 // a fully tested rule. 236 // Note: This is only true for the current algorithm, if we allow the 237 // algorithm to compare equally valid rules then they will become 238 // reachable. 239 { 240 auto FullyTestedLeafI = Leaves.end(); 241 for (auto LeafI = Leaves.begin(), LeafE = Leaves.end(); 242 LeafI != LeafE; ++LeafI) { 243 if (LeafI->isFullyTraversed() && LeafI->isFullyTested()) 244 FullyTestedLeafI = LeafI; 245 else if (FullyTestedLeafI != Leaves.end()) { 246 PrintError("Leaf " + LeafI->getName() + " is unreachable"); 247 PrintNote("Leaf " + FullyTestedLeafI->getName() + 248 " will have already matched"); 249 } 250 } 251 } 252 253 LLVM_DEBUG(dbgs() << " Eliminating redundant partitioners:\n"); 254 filterRedundantPartitioners(); 255 LLVM_DEBUG(dbgs() << " Partitioners remaining:\n"); 256 #ifndef NDEBUG 257 for (const auto &Partitioner : Partitioners) 258 LLVM_DEBUG(dbgs() << " "; Partitioner->emitDescription(dbgs()); 259 dbgs() << "\n"); 260 #endif // ifndef NDEBUG 261 262 if (Partitioners.empty()) { 263 // Nothing left to do but check we really did identify a single rule. 264 if (Leaves.size() > 1) { 265 LLVM_DEBUG(dbgs() << "Leaf contains multiple rules, drop after the first " 266 "fully tested rule\n"); 267 auto FirstFullyTested = 268 llvm::find_if(Leaves, [](const GIMatchTreeBuilderLeafInfo &X) { 269 return X.isFullyTraversed() && X.isFullyTested() && 270 !X.getMatchDag().hasPostMatchPredicate(); 271 }); 272 if (FirstFullyTested != Leaves.end()) 273 FirstFullyTested++; 274 275 #ifndef NDEBUG 276 for (auto &Leaf : make_range(Leaves.begin(), FirstFullyTested)) 277 LLVM_DEBUG(dbgs() << " Kept " << Leaf.getName() << "\n"); 278 for (const auto &Leaf : make_range(FirstFullyTested, Leaves.end())) 279 LLVM_DEBUG(dbgs() << " Dropped " << Leaf.getName() << "\n"); 280 #endif // ifndef NDEBUG 281 TreeNode->dropLeavesAfter( 282 std::distance(Leaves.begin(), FirstFullyTested)); 283 } 284 for (const auto &Leaf : Leaves) { 285 if (!Leaf.isFullyTraversed()) { 286 PrintError("Leaf " + Leaf.getName() + " is not fully traversed"); 287 PrintNote("This indicates a missing partitioner within tblgen"); 288 Leaf.dump(errs()); 289 for (unsigned InstrIdx : Leaf.untested_instrs()) 290 PrintNote("Instr " + llvm::to_string(*Leaf.getInstr(InstrIdx))); 291 for (unsigned EdgeIdx : Leaf.untested_edges()) 292 PrintNote("Edge " + llvm::to_string(*Leaf.getEdge(EdgeIdx))); 293 } 294 } 295 296 // Copy out information about untested predicates so the user of the tree 297 // can deal with them. 298 for (auto LeafPair : zip(Leaves, TreeNode->possible_leaves())) { 299 const GIMatchTreeBuilderLeafInfo &BuilderLeaf = std::get<0>(LeafPair); 300 GIMatchTreeLeafInfo &TreeLeaf = std::get<1>(LeafPair); 301 if (!BuilderLeaf.isFullyTested()) 302 for (unsigned PredicateIdx : BuilderLeaf.untested_predicates()) 303 TreeLeaf.addUntestedPredicate(BuilderLeaf.getPredicate(PredicateIdx)); 304 } 305 return; 306 } 307 308 LLVM_DEBUG(dbgs() << " Weighing up partitioners:\n"); 309 evaluatePartitioners(); 310 311 // Select the best partitioner by its ability to partition 312 // - Prefer partitioners that don't distinguish between partitions. This 313 // is to fail early on decisions that must go a single way. 314 auto PartitionerI = std::max_element( 315 Partitioners.begin(), Partitioners.end(), 316 [](const std::unique_ptr<GIMatchTreePartitioner> &A, 317 const std::unique_ptr<GIMatchTreePartitioner> &B) { 318 // We generally want partitioners that subdivide the 319 // ruleset as much as possible since these take fewer 320 // checks to converge on a particular rule. However, 321 // it's important to note that one leaf can end up in 322 // multiple partitions if the check isn't mutually 323 // exclusive (e.g. getVRegDef() vs isReg()). 324 // We therefore minimize average leaves per partition. 325 return (double)A->getNumLeavesWithDupes() / A->getNumPartitions() > 326 (double)B->getNumLeavesWithDupes() / B->getNumPartitions(); 327 }); 328 329 // Select a partitioner and partition the ruleset 330 // Note that it's possible for a single rule to end up in multiple 331 // partitions. For example, an opcode test on a rule without an opcode 332 // predicate will result in it being passed to all partitions. 333 std::unique_ptr<GIMatchTreePartitioner> Partitioner = std::move(*PartitionerI); 334 Partitioners.erase(PartitionerI); 335 LLVM_DEBUG(dbgs() << " Selected partitioner: "; 336 Partitioner->emitDescription(dbgs()); dbgs() << "\n"); 337 338 assert(Partitioner->getNumPartitions() > 0 && 339 "Must always partition into at least one partition"); 340 341 TreeNode->setNumChildren(Partitioner->getNumPartitions()); 342 for (auto &C : enumerate(TreeNode->children())) { 343 SubtreeBuilders.emplace_back(&C.value(), NextInstrID); 344 Partitioner->applyForPartition(C.index(), *this, SubtreeBuilders.back()); 345 } 346 347 TreeNode->setPartitioner(std::move(Partitioner)); 348 349 // Recurse into the subtree builders. Each one must get a copy of the 350 // remaining partitioners as each path has to check everything. 351 for (auto &SubtreeBuilder : SubtreeBuilders) { 352 for (const auto &Partitioner : Partitioners) 353 SubtreeBuilder.addPartitioner(Partitioner->clone()); 354 SubtreeBuilder.runStep(); 355 } 356 } 357 358 std::unique_ptr<GIMatchTree> GIMatchTreeBuilder::run() { 359 unsigned NewInstrID = allocInstrID(); 360 // Start by recording the root instruction as instr #0 and set up the initial 361 // partitioners. 362 for (auto &Leaf : Leaves) { 363 LLVM_DEBUG(Leaf.getMatchDag().writeDOTGraph(dbgs(), Leaf.getName())); 364 GIMatchDagInstr *Root = 365 *(Leaf.getMatchDag().roots().begin() + Leaf.getRootIdx()); 366 Leaf.declareInstr(Root, NewInstrID); 367 } 368 369 addPartitionersForInstr(NewInstrID); 370 371 std::unique_ptr<GIMatchTree> TreeRoot = std::make_unique<GIMatchTree>(); 372 TreeNode = TreeRoot.get(); 373 runStep(); 374 375 return TreeRoot; 376 } 377 378 void GIMatchTreeOpcodePartitioner::emitPartitionName(raw_ostream &OS, unsigned Idx) const { 379 if (PartitionToInstr[Idx] == nullptr) { 380 OS << "* or nullptr"; 381 return; 382 } 383 OS << PartitionToInstr[Idx]->Namespace 384 << "::" << PartitionToInstr[Idx]->TheDef->getName(); 385 } 386 387 void GIMatchTreeOpcodePartitioner::repartition( 388 GIMatchTreeBuilder::LeafVec &Leaves) { 389 Partitions.clear(); 390 InstrToPartition.clear(); 391 PartitionToInstr.clear(); 392 TestedPredicates.clear(); 393 394 for (const auto &Leaf : enumerate(Leaves)) { 395 bool AllOpcodes = true; 396 GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID); 397 BitVector TestedPredicatesForLeaf( 398 Leaf.value().getMatchDag().getNumPredicates()); 399 400 // If the instruction isn't declared then we don't care about it. Ignore 401 // it for now and add it to all partitions later once we know what 402 // partitions we have. 403 if (!InstrInfo) { 404 LLVM_DEBUG(dbgs() << " " << Leaf.value().getName() 405 << " doesn't care about Instr[" << InstrID << "]\n"); 406 assert(TestedPredicatesForLeaf.size() == Leaf.value().getMatchDag().getNumPredicates()); 407 TestedPredicates.push_back(TestedPredicatesForLeaf); 408 continue; 409 } 410 411 // If the opcode is available to test then any opcode predicates will have 412 // been enabled too. 413 for (unsigned PIdx : Leaf.value().TestablePredicates.set_bits()) { 414 const auto &P = Leaf.value().getPredicate(PIdx); 415 SmallVector<const CodeGenInstruction *, 1> OpcodesForThisPredicate; 416 if (const auto *OpcodeP = dyn_cast<const GIMatchDagOpcodePredicate>(P)) { 417 // We've found _an_ opcode predicate, but we don't know if it's 418 // checking this instruction yet. 419 bool IsThisPredicate = false; 420 for (const auto &PDep : Leaf.value().getMatchDag().predicate_edges()) { 421 if (PDep->getRequiredMI() == InstrInfo->getInstrNode() && 422 PDep->getRequiredMO() == nullptr && PDep->getPredicate() == P) { 423 IsThisPredicate = true; 424 break; 425 } 426 } 427 if (!IsThisPredicate) 428 continue; 429 430 // If we get here twice then we've somehow ended up with two opcode 431 // predicates for one instruction in the same DAG. That should be 432 // impossible. 433 assert(AllOpcodes && "Conflicting opcode predicates"); 434 const CodeGenInstruction *Expected = OpcodeP->getInstr(); 435 OpcodesForThisPredicate.push_back(Expected); 436 } 437 438 if (const auto *OpcodeP = 439 dyn_cast<const GIMatchDagOneOfOpcodesPredicate>(P)) { 440 // We've found _an_ oneof(opcodes) predicate, but we don't know if it's 441 // checking this instruction yet. 442 bool IsThisPredicate = false; 443 for (const auto &PDep : Leaf.value().getMatchDag().predicate_edges()) { 444 if (PDep->getRequiredMI() == InstrInfo->getInstrNode() && 445 PDep->getRequiredMO() == nullptr && PDep->getPredicate() == P) { 446 IsThisPredicate = true; 447 break; 448 } 449 } 450 if (!IsThisPredicate) 451 continue; 452 453 // If we get here twice then we've somehow ended up with two opcode 454 // predicates for one instruction in the same DAG. That should be 455 // impossible. 456 assert(AllOpcodes && "Conflicting opcode predicates"); 457 for (const CodeGenInstruction *Expected : OpcodeP->getInstrs()) 458 OpcodesForThisPredicate.push_back(Expected); 459 } 460 461 for (const CodeGenInstruction *Expected : OpcodesForThisPredicate) { 462 // Mark this predicate as one we're testing. 463 TestedPredicatesForLeaf.set(PIdx); 464 465 // Partitions must be numbered 0, 1, .., N but instructions don't meet 466 // that requirement. Assign a partition number to each opcode if we 467 // lack one ... 468 auto Partition = InstrToPartition.find(Expected); 469 if (Partition == InstrToPartition.end()) { 470 BitVector Contents(Leaves.size()); 471 Partition = InstrToPartition 472 .insert(std::make_pair(Expected, Partitions.size())) 473 .first; 474 PartitionToInstr.push_back(Expected); 475 Partitions.insert(std::make_pair(Partitions.size(), Contents)); 476 } 477 // ... and mark this leaf as being in that partition. 478 Partitions.find(Partition->second)->second.set(Leaf.index()); 479 AllOpcodes = false; 480 LLVM_DEBUG(dbgs() << " " << Leaf.value().getName() 481 << " is in partition " << Partition->second << "\n"); 482 } 483 484 // TODO: This is where we would handle multiple choices of opcode 485 // the end result will be that this leaf ends up in multiple 486 // partitions similarly to AllOpcodes. 487 } 488 489 // If we never check the opcode, add it to every partition. 490 if (AllOpcodes) { 491 // Add a partition for the default case if we don't already have one. 492 if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) { 493 PartitionToInstr.push_back(nullptr); 494 BitVector Contents(Leaves.size()); 495 Partitions.insert(std::make_pair(Partitions.size(), Contents)); 496 } 497 LLVM_DEBUG(dbgs() << " " << Leaf.value().getName() 498 << " is in all partitions (opcode not checked)\n"); 499 for (auto &Partition : Partitions) 500 Partition.second.set(Leaf.index()); 501 } 502 503 assert(TestedPredicatesForLeaf.size() == Leaf.value().getMatchDag().getNumPredicates()); 504 TestedPredicates.push_back(TestedPredicatesForLeaf); 505 } 506 507 if (Partitions.size() == 0) { 508 // Add a partition for the default case if we don't already have one. 509 if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) { 510 PartitionToInstr.push_back(nullptr); 511 BitVector Contents(Leaves.size()); 512 Partitions.insert(std::make_pair(Partitions.size(), Contents)); 513 } 514 } 515 516 // Add any leaves that don't care about this instruction to all partitions. 517 for (const auto &Leaf : enumerate(Leaves)) { 518 GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID); 519 if (!InstrInfo) { 520 // Add a partition for the default case if we don't already have one. 521 if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) { 522 PartitionToInstr.push_back(nullptr); 523 BitVector Contents(Leaves.size()); 524 Partitions.insert(std::make_pair(Partitions.size(), Contents)); 525 } 526 for (auto &Partition : Partitions) 527 Partition.second.set(Leaf.index()); 528 } 529 } 530 531 } 532 533 void GIMatchTreeOpcodePartitioner::applyForPartition( 534 unsigned PartitionIdx, GIMatchTreeBuilder &Builder, GIMatchTreeBuilder &SubBuilder) { 535 LLVM_DEBUG(dbgs() << " Making partition " << PartitionIdx << "\n"); 536 const CodeGenInstruction *CGI = PartitionToInstr[PartitionIdx]; 537 538 BitVector PossibleLeaves = getPossibleLeavesForPartition(PartitionIdx); 539 // Consume any predicates we handled. 540 for (auto &EnumeratedLeaf : enumerate(Builder.getPossibleLeaves())) { 541 if (!PossibleLeaves[EnumeratedLeaf.index()]) 542 continue; 543 544 auto &Leaf = EnumeratedLeaf.value(); 545 const auto &TestedPredicatesForLeaf = 546 TestedPredicates[EnumeratedLeaf.index()]; 547 548 for (unsigned PredIdx : TestedPredicatesForLeaf.set_bits()) { 549 LLVM_DEBUG(dbgs() << " " << Leaf.getName() << " tested predicate #" 550 << PredIdx << " of " << TestedPredicatesForLeaf.size() 551 << " " << *Leaf.getPredicate(PredIdx) << "\n"); 552 Leaf.RemainingPredicates.reset(PredIdx); 553 Leaf.TestablePredicates.reset(PredIdx); 554 } 555 SubBuilder.addLeaf(Leaf); 556 } 557 558 // Nothing to do, we don't know anything about this instruction as a result 559 // of this partitioner. 560 if (CGI == nullptr) 561 return; 562 563 GIMatchTreeBuilder::LeafVec &NewLeaves = SubBuilder.getPossibleLeaves(); 564 // Find all the operands we know to exist and are referenced. This will 565 // usually be all the referenced operands but there are some cases where 566 // instructions are variadic. Such operands must be handled by partitioners 567 // that check the number of operands. 568 BitVector ReferencedOperands(1); 569 for (auto &Leaf : NewLeaves) { 570 GIMatchTreeInstrInfo *InstrInfo = Leaf.getInstrInfo(InstrID); 571 // Skip any leaves that don't care about this instruction. 572 if (!InstrInfo) 573 continue; 574 const GIMatchDagInstr *Instr = InstrInfo->getInstrNode(); 575 for (auto &E : enumerate(Leaf.getMatchDag().edges())) { 576 if (E.value()->getFromMI() == Instr && 577 E.value()->getFromMO()->getIdx() < CGI->Operands.size()) { 578 ReferencedOperands.resize(E.value()->getFromMO()->getIdx() + 1); 579 ReferencedOperands.set(E.value()->getFromMO()->getIdx()); 580 } 581 } 582 } 583 for (auto &Leaf : NewLeaves) { 584 for (unsigned OpIdx : ReferencedOperands.set_bits()) { 585 Leaf.declareOperand(InstrID, OpIdx); 586 } 587 } 588 for (unsigned OpIdx : ReferencedOperands.set_bits()) { 589 SubBuilder.addPartitionersForOperand(InstrID, OpIdx); 590 } 591 } 592 593 void GIMatchTreeOpcodePartitioner::emitPartitionResults( 594 raw_ostream &OS) const { 595 OS << "Partitioning by opcode would produce " << Partitions.size() 596 << " partitions\n"; 597 for (const auto &Partition : InstrToPartition) { 598 if (Partition.first == nullptr) 599 OS << "Default: "; 600 else 601 OS << Partition.first->TheDef->getName() << ": "; 602 StringRef Separator = ""; 603 for (unsigned I : Partitions.find(Partition.second)->second.set_bits()) { 604 OS << Separator << I; 605 Separator = ", "; 606 } 607 OS << "\n"; 608 } 609 } 610 611 void GIMatchTreeOpcodePartitioner::generatePartitionSelectorCode( 612 raw_ostream &OS, StringRef Indent) const { 613 // Make sure not to emit empty switch or switch with just default 614 if (PartitionToInstr.size() == 1 && PartitionToInstr[0] == nullptr) { 615 OS << Indent << "Partition = 0;\n"; 616 } else if (PartitionToInstr.size()) { 617 OS << Indent << "Partition = -1;\n" 618 << Indent << "switch (MIs[" << InstrID << "]->getOpcode()) {\n"; 619 for (const auto &EnumInstr : enumerate(PartitionToInstr)) { 620 if (EnumInstr.value() == nullptr) 621 OS << Indent << "default:"; 622 else 623 OS << Indent << "case " << EnumInstr.value()->Namespace 624 << "::" << EnumInstr.value()->TheDef->getName() << ":"; 625 OS << " Partition = " << EnumInstr.index() << "; break;\n"; 626 } 627 OS << Indent << "}\n"; 628 } 629 OS << Indent 630 << "// Default case but without conflicting with potential default case " 631 "in selection.\n" 632 << Indent << "if (Partition == -1) return false;\n"; 633 } 634 635 void GIMatchTreeVRegDefPartitioner::addToPartition(bool Result, 636 unsigned LeafIdx) { 637 auto I = ResultToPartition.find(Result); 638 if (I == ResultToPartition.end()) { 639 ResultToPartition.insert(std::make_pair(Result, PartitionToResult.size())); 640 PartitionToResult.push_back(Result); 641 } 642 I = ResultToPartition.find(Result); 643 auto P = Partitions.find(I->second); 644 if (P == Partitions.end()) 645 P = Partitions.insert(std::make_pair(I->second, BitVector())).first; 646 P->second.resize(LeafIdx + 1); 647 P->second.set(LeafIdx); 648 } 649 650 void GIMatchTreeVRegDefPartitioner::repartition( 651 GIMatchTreeBuilder::LeafVec &Leaves) { 652 Partitions.clear(); 653 654 for (const auto &Leaf : enumerate(Leaves)) { 655 GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID); 656 BitVector TraversedEdgesForLeaf(Leaf.value().getMatchDag().getNumEdges()); 657 658 // If the instruction isn't declared then we don't care about it. Ignore 659 // it for now and add it to all partitions later once we know what 660 // partitions we have. 661 if (!InstrInfo) { 662 TraversedEdges.push_back(TraversedEdgesForLeaf); 663 continue; 664 } 665 666 // If this node has an use -> def edge from this operand then this 667 // instruction must be in partition 1 (isVRegDef()). 668 bool WantsEdge = false; 669 for (unsigned EIdx : Leaf.value().TraversableEdges.set_bits()) { 670 const auto &E = Leaf.value().getEdge(EIdx); 671 if (E->getFromMI() != InstrInfo->getInstrNode() || 672 E->getFromMO()->getIdx() != OpIdx || E->isDefToUse()) 673 continue; 674 675 // We're looking at the right edge. This leaf wants a vreg def so we'll 676 // put it in partition 1. 677 addToPartition(true, Leaf.index()); 678 TraversedEdgesForLeaf.set(EIdx); 679 WantsEdge = true; 680 } 681 682 bool isNotReg = false; 683 if (!WantsEdge && isNotReg) { 684 // If this leaf doesn't have an edge and we _don't_ want a register, 685 // then add it to partition 0. 686 addToPartition(false, Leaf.index()); 687 } else if (!WantsEdge) { 688 // If this leaf doesn't have an edge and we don't know what we want, 689 // then add it to partition 0 and 1. 690 addToPartition(false, Leaf.index()); 691 addToPartition(true, Leaf.index()); 692 } 693 694 TraversedEdges.push_back(TraversedEdgesForLeaf); 695 } 696 697 // Add any leaves that don't care about this instruction to all partitions. 698 for (const auto &Leaf : enumerate(Leaves)) { 699 GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID); 700 if (!InstrInfo) 701 for (auto &Partition : Partitions) 702 Partition.second.set(Leaf.index()); 703 } 704 } 705 706 void GIMatchTreeVRegDefPartitioner::applyForPartition( 707 unsigned PartitionIdx, GIMatchTreeBuilder &Builder, 708 GIMatchTreeBuilder &SubBuilder) { 709 BitVector PossibleLeaves = getPossibleLeavesForPartition(PartitionIdx); 710 711 std::vector<BitVector> TraversedEdgesByNewLeaves; 712 // Consume any edges we handled. 713 for (auto &EnumeratedLeaf : enumerate(Builder.getPossibleLeaves())) { 714 if (!PossibleLeaves[EnumeratedLeaf.index()]) 715 continue; 716 717 auto &Leaf = EnumeratedLeaf.value(); 718 const auto &TraversedEdgesForLeaf = TraversedEdges[EnumeratedLeaf.index()]; 719 TraversedEdgesByNewLeaves.push_back(TraversedEdgesForLeaf); 720 Leaf.RemainingEdges.reset(TraversedEdgesForLeaf); 721 Leaf.TraversableEdges.reset(TraversedEdgesForLeaf); 722 SubBuilder.addLeaf(Leaf); 723 } 724 725 // Nothing to do. The only thing we know is that it isn't a vreg-def. 726 if (PartitionToResult[PartitionIdx] == false) 727 return; 728 729 NewInstrID = SubBuilder.allocInstrID(); 730 731 GIMatchTreeBuilder::LeafVec &NewLeaves = SubBuilder.getPossibleLeaves(); 732 for (const auto I : zip(NewLeaves, TraversedEdgesByNewLeaves)) { 733 auto &Leaf = std::get<0>(I); 734 auto &TraversedEdgesForLeaf = std::get<1>(I); 735 GIMatchTreeInstrInfo *InstrInfo = Leaf.getInstrInfo(InstrID); 736 // Skip any leaves that don't care about this instruction. 737 if (!InstrInfo) 738 continue; 739 for (unsigned EIdx : TraversedEdgesForLeaf.set_bits()) { 740 const GIMatchDagEdge *E = Leaf.getEdge(EIdx); 741 Leaf.declareInstr(E->getToMI(), NewInstrID); 742 } 743 } 744 SubBuilder.addPartitionersForInstr(NewInstrID); 745 } 746 747 void GIMatchTreeVRegDefPartitioner::emitPartitionResults( 748 raw_ostream &OS) const { 749 OS << "Partitioning by vreg-def would produce " << Partitions.size() 750 << " partitions\n"; 751 for (const auto &Partition : Partitions) { 752 OS << Partition.first << " ("; 753 emitPartitionName(OS, Partition.first); 754 OS << "): "; 755 StringRef Separator = ""; 756 for (unsigned I : Partition.second.set_bits()) { 757 OS << Separator << I; 758 Separator = ", "; 759 } 760 OS << "\n"; 761 } 762 } 763 764 void GIMatchTreeVRegDefPartitioner::generatePartitionSelectorCode( 765 raw_ostream &OS, StringRef Indent) const { 766 OS << Indent << "Partition = -1\n" 767 << Indent << "if (MIs.size() <= NewInstrID) MIs.resize(NewInstrID + 1);\n" 768 << Indent << "MIs[" << NewInstrID << "] = nullptr;\n" 769 << Indent << "if (MIs[" << InstrID << "].getOperand(" << OpIdx 770 << ").isReg()))\n" 771 << Indent << " MIs[" << NewInstrID << "] = MRI.getVRegDef(MIs[" << InstrID 772 << "].getOperand(" << OpIdx << ").getReg()));\n"; 773 774 for (const auto &Pair : ResultToPartition) 775 OS << Indent << "if (MIs[" << NewInstrID << "] " 776 << (Pair.first ? "==" : "!=") 777 << " nullptr) Partition = " << Pair.second << ";\n"; 778 779 OS << Indent << "if (Partition == -1) return false;\n"; 780 } 781