1 //===- PredicateTree.cpp - Predicate tree merging -------------------------===// 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 "PredicateTree.h" 10 #include "RootOrdering.h" 11 12 #include "mlir/Dialect/PDL/IR/PDL.h" 13 #include "mlir/Dialect/PDL/IR/PDLTypes.h" 14 #include "mlir/Dialect/PDLInterp/IR/PDLInterp.h" 15 #include "mlir/IR/BuiltinOps.h" 16 #include "mlir/Interfaces/InferTypeOpInterface.h" 17 #include "llvm/ADT/MapVector.h" 18 #include "llvm/ADT/TypeSwitch.h" 19 #include "llvm/Support/Debug.h" 20 #include <queue> 21 22 #define DEBUG_TYPE "pdl-predicate-tree" 23 24 using namespace mlir; 25 using namespace mlir::pdl_to_pdl_interp; 26 27 //===----------------------------------------------------------------------===// 28 // Predicate List Building 29 //===----------------------------------------------------------------------===// 30 31 static void getTreePredicates(std::vector<PositionalPredicate> &predList, 32 Value val, PredicateBuilder &builder, 33 DenseMap<Value, Position *> &inputs, 34 Position *pos); 35 36 /// Compares the depths of two positions. 37 static bool comparePosDepth(Position *lhs, Position *rhs) { 38 return lhs->getOperationDepth() < rhs->getOperationDepth(); 39 } 40 41 /// Returns the number of non-range elements within `values`. 42 static unsigned getNumNonRangeValues(ValueRange values) { 43 return llvm::count_if(values.getTypes(), 44 [](Type type) { return !type.isa<pdl::RangeType>(); }); 45 } 46 47 static void getTreePredicates(std::vector<PositionalPredicate> &predList, 48 Value val, PredicateBuilder &builder, 49 DenseMap<Value, Position *> &inputs, 50 AttributePosition *pos) { 51 assert(val.getType().isa<pdl::AttributeType>() && "expected attribute type"); 52 pdl::AttributeOp attr = cast<pdl::AttributeOp>(val.getDefiningOp()); 53 predList.emplace_back(pos, builder.getIsNotNull()); 54 55 // If the attribute has a type or value, add a constraint. 56 if (Value type = attr.type()) 57 getTreePredicates(predList, type, builder, inputs, builder.getType(pos)); 58 else if (Attribute value = attr.valueAttr()) 59 predList.emplace_back(pos, builder.getAttributeConstraint(value)); 60 } 61 62 /// Collect all of the predicates for the given operand position. 63 static void getOperandTreePredicates(std::vector<PositionalPredicate> &predList, 64 Value val, PredicateBuilder &builder, 65 DenseMap<Value, Position *> &inputs, 66 Position *pos) { 67 Type valueType = val.getType(); 68 bool isVariadic = valueType.isa<pdl::RangeType>(); 69 70 // If this is a typed operand, add a type constraint. 71 TypeSwitch<Operation *>(val.getDefiningOp()) 72 .Case<pdl::OperandOp, pdl::OperandsOp>([&](auto op) { 73 // Prevent traversal into a null value if the operand has a proper 74 // index. 75 if (std::is_same<pdl::OperandOp, decltype(op)>::value || 76 cast<OperandGroupPosition>(pos)->getOperandGroupNumber()) 77 predList.emplace_back(pos, builder.getIsNotNull()); 78 79 if (Value type = op.type()) 80 getTreePredicates(predList, type, builder, inputs, 81 builder.getType(pos)); 82 }) 83 .Case<pdl::ResultOp, pdl::ResultsOp>([&](auto op) { 84 Optional<unsigned> index = op.index(); 85 86 // Prevent traversal into a null value if the result has a proper index. 87 if (index) 88 predList.emplace_back(pos, builder.getIsNotNull()); 89 90 // Get the parent operation of this operand. 91 OperationPosition *parentPos = builder.getOperandDefiningOp(pos); 92 predList.emplace_back(parentPos, builder.getIsNotNull()); 93 94 // Ensure that the operands match the corresponding results of the 95 // parent operation. 96 Position *resultPos = nullptr; 97 if (std::is_same<pdl::ResultOp, decltype(op)>::value) 98 resultPos = builder.getResult(parentPos, *index); 99 else 100 resultPos = builder.getResultGroup(parentPos, index, isVariadic); 101 predList.emplace_back(resultPos, builder.getEqualTo(pos)); 102 103 // Collect the predicates of the parent operation. 104 getTreePredicates(predList, op.parent(), builder, inputs, 105 (Position *)parentPos); 106 }); 107 } 108 109 static void getTreePredicates(std::vector<PositionalPredicate> &predList, 110 Value val, PredicateBuilder &builder, 111 DenseMap<Value, Position *> &inputs, 112 OperationPosition *pos, 113 Optional<unsigned> ignoreOperand = llvm::None) { 114 assert(val.getType().isa<pdl::OperationType>() && "expected operation"); 115 pdl::OperationOp op = cast<pdl::OperationOp>(val.getDefiningOp()); 116 OperationPosition *opPos = cast<OperationPosition>(pos); 117 118 // Ensure getDefiningOp returns a non-null operation. 119 if (!opPos->isRoot()) 120 predList.emplace_back(pos, builder.getIsNotNull()); 121 122 // Check that this is the correct root operation. 123 if (Optional<StringRef> opName = op.name()) 124 predList.emplace_back(pos, builder.getOperationName(*opName)); 125 126 // Check that the operation has the proper number of operands. If there are 127 // any variable length operands, we check a minimum instead of an exact count. 128 OperandRange operands = op.operands(); 129 unsigned minOperands = getNumNonRangeValues(operands); 130 if (minOperands != operands.size()) { 131 if (minOperands) 132 predList.emplace_back(pos, builder.getOperandCountAtLeast(minOperands)); 133 } else { 134 predList.emplace_back(pos, builder.getOperandCount(minOperands)); 135 } 136 137 // Check that the operation has the proper number of results. If there are 138 // any variable length results, we check a minimum instead of an exact count. 139 OperandRange types = op.types(); 140 unsigned minResults = getNumNonRangeValues(types); 141 if (minResults == types.size()) 142 predList.emplace_back(pos, builder.getResultCount(types.size())); 143 else if (minResults) 144 predList.emplace_back(pos, builder.getResultCountAtLeast(minResults)); 145 146 // Recurse into any attributes, operands, or results. 147 for (auto it : llvm::zip(op.attributeNames(), op.attributes())) { 148 getTreePredicates( 149 predList, std::get<1>(it), builder, inputs, 150 builder.getAttribute(opPos, 151 std::get<0>(it).cast<StringAttr>().getValue())); 152 } 153 154 // Process the operands and results of the operation. For all values up to 155 // the first variable length value, we use the concrete operand/result 156 // number. After that, we use the "group" given that we can't know the 157 // concrete indices until runtime. If there is only one variadic operand 158 // group, we treat it as all of the operands/results of the operation. 159 /// Operands. 160 if (operands.size() == 1 && operands[0].getType().isa<pdl::RangeType>()) { 161 getTreePredicates(predList, operands.front(), builder, inputs, 162 builder.getAllOperands(opPos)); 163 } else { 164 bool foundVariableLength = false; 165 for (auto operandIt : llvm::enumerate(operands)) { 166 bool isVariadic = operandIt.value().getType().isa<pdl::RangeType>(); 167 foundVariableLength |= isVariadic; 168 169 // Ignore the specified operand, usually because this position was 170 // visited in an upward traversal via an iterative choice. 171 if (ignoreOperand && *ignoreOperand == operandIt.index()) 172 continue; 173 174 Position *pos = 175 foundVariableLength 176 ? builder.getOperandGroup(opPos, operandIt.index(), isVariadic) 177 : builder.getOperand(opPos, operandIt.index()); 178 getTreePredicates(predList, operandIt.value(), builder, inputs, pos); 179 } 180 } 181 /// Results. 182 if (types.size() == 1 && types[0].getType().isa<pdl::RangeType>()) { 183 getTreePredicates(predList, types.front(), builder, inputs, 184 builder.getType(builder.getAllResults(opPos))); 185 } else { 186 bool foundVariableLength = false; 187 for (auto &resultIt : llvm::enumerate(types)) { 188 bool isVariadic = resultIt.value().getType().isa<pdl::RangeType>(); 189 foundVariableLength |= isVariadic; 190 191 auto *resultPos = 192 foundVariableLength 193 ? builder.getResultGroup(pos, resultIt.index(), isVariadic) 194 : builder.getResult(pos, resultIt.index()); 195 predList.emplace_back(resultPos, builder.getIsNotNull()); 196 getTreePredicates(predList, resultIt.value(), builder, inputs, 197 builder.getType(resultPos)); 198 } 199 } 200 } 201 202 static void getTreePredicates(std::vector<PositionalPredicate> &predList, 203 Value val, PredicateBuilder &builder, 204 DenseMap<Value, Position *> &inputs, 205 TypePosition *pos) { 206 // Check for a constraint on a constant type. 207 if (pdl::TypeOp typeOp = val.getDefiningOp<pdl::TypeOp>()) { 208 if (Attribute type = typeOp.typeAttr()) 209 predList.emplace_back(pos, builder.getTypeConstraint(type)); 210 } else if (pdl::TypesOp typeOp = val.getDefiningOp<pdl::TypesOp>()) { 211 if (Attribute typeAttr = typeOp.typesAttr()) 212 predList.emplace_back(pos, builder.getTypeConstraint(typeAttr)); 213 } 214 } 215 216 /// Collect the tree predicates anchored at the given value. 217 static void getTreePredicates(std::vector<PositionalPredicate> &predList, 218 Value val, PredicateBuilder &builder, 219 DenseMap<Value, Position *> &inputs, 220 Position *pos) { 221 // Make sure this input value is accessible to the rewrite. 222 auto it = inputs.try_emplace(val, pos); 223 if (!it.second) { 224 // If this is an input value that has been visited in the tree, add a 225 // constraint to ensure that both instances refer to the same value. 226 if (isa<pdl::AttributeOp, pdl::OperandOp, pdl::OperandsOp, pdl::OperationOp, 227 pdl::TypeOp>(val.getDefiningOp())) { 228 auto minMaxPositions = 229 std::minmax(pos, it.first->second, comparePosDepth); 230 predList.emplace_back(minMaxPositions.second, 231 builder.getEqualTo(minMaxPositions.first)); 232 } 233 return; 234 } 235 236 TypeSwitch<Position *>(pos) 237 .Case<AttributePosition, OperationPosition, TypePosition>([&](auto *pos) { 238 getTreePredicates(predList, val, builder, inputs, pos); 239 }) 240 .Case<OperandPosition, OperandGroupPosition>([&](auto *pos) { 241 getOperandTreePredicates(predList, val, builder, inputs, pos); 242 }) 243 .Default([](auto *) { llvm_unreachable("unexpected position kind"); }); 244 } 245 246 static void getAttributePredicates(pdl::AttributeOp op, 247 std::vector<PositionalPredicate> &predList, 248 PredicateBuilder &builder, 249 DenseMap<Value, Position *> &inputs) { 250 Position *&attrPos = inputs[op]; 251 if (attrPos) 252 return; 253 Attribute value = op.valueAttr(); 254 assert(value && "expected non-tree `pdl.attribute` to contain a value"); 255 attrPos = builder.getAttributeLiteral(value); 256 } 257 258 static void getConstraintPredicates(pdl::ApplyNativeConstraintOp op, 259 std::vector<PositionalPredicate> &predList, 260 PredicateBuilder &builder, 261 DenseMap<Value, Position *> &inputs) { 262 OperandRange arguments = op.args(); 263 ArrayAttr parameters = op.constParamsAttr(); 264 265 std::vector<Position *> allPositions; 266 allPositions.reserve(arguments.size()); 267 for (Value arg : arguments) 268 allPositions.push_back(inputs.lookup(arg)); 269 270 // Push the constraint to the furthest position. 271 Position *pos = *std::max_element(allPositions.begin(), allPositions.end(), 272 comparePosDepth); 273 PredicateBuilder::Predicate pred = 274 builder.getConstraint(op.name(), std::move(allPositions), parameters); 275 predList.emplace_back(pos, pred); 276 } 277 278 static void getResultPredicates(pdl::ResultOp op, 279 std::vector<PositionalPredicate> &predList, 280 PredicateBuilder &builder, 281 DenseMap<Value, Position *> &inputs) { 282 Position *&resultPos = inputs[op]; 283 if (resultPos) 284 return; 285 286 // Ensure that the result isn't null. 287 auto *parentPos = cast<OperationPosition>(inputs.lookup(op.parent())); 288 resultPos = builder.getResult(parentPos, op.index()); 289 predList.emplace_back(resultPos, builder.getIsNotNull()); 290 } 291 292 static void getResultPredicates(pdl::ResultsOp op, 293 std::vector<PositionalPredicate> &predList, 294 PredicateBuilder &builder, 295 DenseMap<Value, Position *> &inputs) { 296 Position *&resultPos = inputs[op]; 297 if (resultPos) 298 return; 299 300 // Ensure that the result isn't null if the result has an index. 301 auto *parentPos = cast<OperationPosition>(inputs.lookup(op.parent())); 302 bool isVariadic = op.getType().isa<pdl::RangeType>(); 303 Optional<unsigned> index = op.index(); 304 resultPos = builder.getResultGroup(parentPos, index, isVariadic); 305 if (index) 306 predList.emplace_back(resultPos, builder.getIsNotNull()); 307 } 308 309 static void getTypePredicates(Value typeValue, 310 function_ref<Attribute()> typeAttrFn, 311 PredicateBuilder &builder, 312 DenseMap<Value, Position *> &inputs) { 313 Position *&typePos = inputs[typeValue]; 314 if (typePos) 315 return; 316 Attribute typeAttr = typeAttrFn(); 317 assert(typeAttr && 318 "expected non-tree `pdl.type`/`pdl.types` to contain a value"); 319 typePos = builder.getTypeLiteral(typeAttr); 320 } 321 322 /// Collect all of the predicates that cannot be determined via walking the 323 /// tree. 324 static void getNonTreePredicates(pdl::PatternOp pattern, 325 std::vector<PositionalPredicate> &predList, 326 PredicateBuilder &builder, 327 DenseMap<Value, Position *> &inputs) { 328 for (Operation &op : pattern.body().getOps()) { 329 TypeSwitch<Operation *>(&op) 330 .Case([&](pdl::AttributeOp attrOp) { 331 getAttributePredicates(attrOp, predList, builder, inputs); 332 }) 333 .Case<pdl::ApplyNativeConstraintOp>([&](auto constraintOp) { 334 getConstraintPredicates(constraintOp, predList, builder, inputs); 335 }) 336 .Case<pdl::ResultOp, pdl::ResultsOp>([&](auto resultOp) { 337 getResultPredicates(resultOp, predList, builder, inputs); 338 }) 339 .Case([&](pdl::TypeOp typeOp) { 340 getTypePredicates( 341 typeOp, [&] { return typeOp.typeAttr(); }, builder, inputs); 342 }) 343 .Case([&](pdl::TypesOp typeOp) { 344 getTypePredicates( 345 typeOp, [&] { return typeOp.typesAttr(); }, builder, inputs); 346 }); 347 } 348 } 349 350 namespace { 351 352 /// An op accepting a value at an optional index. 353 struct OpIndex { 354 Value parent; 355 Optional<unsigned> index; 356 }; 357 358 /// The parent and operand index of each operation for each root, stored 359 /// as a nested map [root][operation]. 360 using ParentMaps = DenseMap<Value, DenseMap<Value, OpIndex>>; 361 362 } // namespace 363 364 /// Given a pattern, determines the set of roots present in this pattern. 365 /// These are the operations whose results are not consumed by other operations. 366 static SmallVector<Value> detectRoots(pdl::PatternOp pattern) { 367 // First, collect all the operations that are used as operands 368 // to other operations. These are not roots by default. 369 DenseSet<Value> used; 370 for (auto operationOp : pattern.body().getOps<pdl::OperationOp>()) { 371 for (Value operand : operationOp.operands()) 372 TypeSwitch<Operation *>(operand.getDefiningOp()) 373 .Case<pdl::ResultOp, pdl::ResultsOp>( 374 [&used](auto resultOp) { used.insert(resultOp.parent()); }); 375 } 376 377 // Remove the specified root from the use set, so that we can 378 // always select it as a root, even if it is used by other operations. 379 if (Value root = pattern.getRewriter().root()) 380 used.erase(root); 381 382 // Finally, collect all the unused operations. 383 SmallVector<Value> roots; 384 for (Value operationOp : pattern.body().getOps<pdl::OperationOp>()) 385 if (!used.contains(operationOp)) 386 roots.push_back(operationOp); 387 388 return roots; 389 } 390 391 /// Given a list of candidate roots, builds the cost graph for connecting them. 392 /// The graph is formed by traversing the DAG of operations starting from each 393 /// root and marking the depth of each connector value (operand). Then we join 394 /// the candidate roots based on the common connector values, taking the one 395 /// with the minimum depth. Along the way, we compute, for each candidate root, 396 /// a mapping from each operation (in the DAG underneath this root) to its 397 /// parent operation and the corresponding operand index. 398 static void buildCostGraph(ArrayRef<Value> roots, RootOrderingGraph &graph, 399 ParentMaps &parentMaps) { 400 401 // The entry of a queue. The entry consists of the following items: 402 // * the value in the DAG underneath the root; 403 // * the parent of the value; 404 // * the operand index of the value in its parent; 405 // * the depth of the visited value. 406 struct Entry { 407 Entry(Value value, Value parent, Optional<unsigned> index, unsigned depth) 408 : value(value), parent(parent), index(index), depth(depth) {} 409 410 Value value; 411 Value parent; 412 Optional<unsigned> index; 413 unsigned depth; 414 }; 415 416 // A root of a value and its depth (distance from root to the value). 417 struct RootDepth { 418 Value root; 419 unsigned depth = 0; 420 }; 421 422 // Map from candidate connector values to their roots and depths. Using a 423 // small vector with 1 entry because most values belong to a single root. 424 llvm::MapVector<Value, SmallVector<RootDepth, 1>> connectorsRootsDepths; 425 426 // Perform a breadth-first traversal of the op DAG rooted at each root. 427 for (Value root : roots) { 428 // The queue of visited values. A value may be present multiple times in 429 // the queue, for multiple parents. We only accept the first occurrence, 430 // which is guaranteed to have the lowest depth. 431 std::queue<Entry> toVisit; 432 toVisit.emplace(root, Value(), 0, 0); 433 434 // The map from value to its parent for the current root. 435 DenseMap<Value, OpIndex> &parentMap = parentMaps[root]; 436 437 while (!toVisit.empty()) { 438 Entry entry = toVisit.front(); 439 toVisit.pop(); 440 // Skip if already visited. 441 if (!parentMap.insert({entry.value, {entry.parent, entry.index}}).second) 442 continue; 443 444 // Mark the root and depth of the value. 445 connectorsRootsDepths[entry.value].push_back({root, entry.depth}); 446 447 // Traverse the operands of an operation and result ops. 448 // We intentionally do not traverse attributes and types, because those 449 // are expensive to join on. 450 TypeSwitch<Operation *>(entry.value.getDefiningOp()) 451 .Case<pdl::OperationOp>([&](auto operationOp) { 452 OperandRange operands = operationOp.operands(); 453 // Special case when we pass all the operands in one range. 454 // For those, the index is empty. 455 if (operands.size() == 1 && 456 operands[0].getType().isa<pdl::RangeType>()) { 457 toVisit.emplace(operands[0], entry.value, llvm::None, 458 entry.depth + 1); 459 return; 460 } 461 462 // Default case: visit all the operands. 463 for (auto p : llvm::enumerate(operationOp.operands())) 464 toVisit.emplace(p.value(), entry.value, p.index(), 465 entry.depth + 1); 466 }) 467 .Case<pdl::ResultOp, pdl::ResultsOp>([&](auto resultOp) { 468 toVisit.emplace(resultOp.parent(), entry.value, resultOp.index(), 469 entry.depth); 470 }); 471 } 472 } 473 474 // Now build the cost graph. 475 // This is simply a minimum over all depths for the target root. 476 unsigned nextID = 0; 477 for (const auto &connectorRootsDepths : connectorsRootsDepths) { 478 Value value = connectorRootsDepths.first; 479 ArrayRef<RootDepth> rootsDepths = connectorRootsDepths.second; 480 // If there is only one root for this value, this will not trigger 481 // any edges in the cost graph (a perf optimization). 482 if (rootsDepths.size() == 1) 483 continue; 484 485 for (const RootDepth &p : rootsDepths) { 486 for (const RootDepth &q : rootsDepths) { 487 if (&p == &q) 488 continue; 489 // Insert or retrieve the property of edge from p to q. 490 RootOrderingEntry &entry = graph[q.root][p.root]; 491 if (!entry.connector /* new edge */ || entry.cost.first > q.depth) { 492 if (!entry.connector) 493 entry.cost.second = nextID++; 494 entry.cost.first = q.depth; 495 entry.connector = value; 496 } 497 } 498 } 499 } 500 501 assert((llvm::hasSingleElement(roots) || graph.size() == roots.size()) && 502 "the pattern contains a candidate root disconnected from the others"); 503 } 504 505 /// Visit a node during upward traversal. 506 void visitUpward(std::vector<PositionalPredicate> &predList, OpIndex opIndex, 507 PredicateBuilder &builder, 508 DenseMap<Value, Position *> &valueToPosition, Position *&pos, 509 bool &first) { 510 Value value = opIndex.parent; 511 TypeSwitch<Operation *>(value.getDefiningOp()) 512 .Case<pdl::OperationOp>([&](auto operationOp) { 513 LLVM_DEBUG(llvm::dbgs() << " * Value: " << value << "\n"); 514 OperationPosition *opPos = builder.getUsersOp(pos, opIndex.index); 515 516 // Guard against traversing back to where we came from. 517 if (first) { 518 Position *parent = pos->getParent(); 519 predList.emplace_back(opPos, builder.getNotEqualTo(parent)); 520 first = false; 521 } 522 523 // Guard against duplicate upward visits. These are not possible, 524 // because if this value was already visited, it would have been 525 // cheaper to start the traversal at this value rather than at the 526 // `connector`, violating the optimality of our spanning tree. 527 bool inserted = valueToPosition.try_emplace(value, opPos).second; 528 (void)inserted; 529 assert(inserted && "duplicate upward visit"); 530 531 // Obtain the tree predicates at the current value. 532 getTreePredicates(predList, value, builder, valueToPosition, opPos, 533 opIndex.index); 534 535 // Update the position 536 pos = opPos; 537 }) 538 .Case<pdl::ResultOp>([&](auto resultOp) { 539 // Traverse up an individual result. 540 auto *opPos = dyn_cast<OperationPosition>(pos); 541 assert(opPos && "operations and results must be interleaved"); 542 pos = builder.getResult(opPos, *opIndex.index); 543 }) 544 .Case<pdl::ResultsOp>([&](auto resultOp) { 545 // Traverse up a group of results. 546 auto *opPos = dyn_cast<OperationPosition>(pos); 547 assert(opPos && "operations and results must be interleaved"); 548 bool isVariadic = value.getType().isa<pdl::RangeType>(); 549 if (opIndex.index) 550 pos = builder.getResultGroup(opPos, opIndex.index, isVariadic); 551 else 552 pos = builder.getAllResults(opPos); 553 }); 554 } 555 556 /// Given a pattern operation, build the set of matcher predicates necessary to 557 /// match this pattern. 558 static Value buildPredicateList(pdl::PatternOp pattern, 559 PredicateBuilder &builder, 560 std::vector<PositionalPredicate> &predList, 561 DenseMap<Value, Position *> &valueToPosition) { 562 SmallVector<Value> roots = detectRoots(pattern); 563 564 // Build the root ordering graph and compute the parent maps. 565 RootOrderingGraph graph; 566 ParentMaps parentMaps; 567 buildCostGraph(roots, graph, parentMaps); 568 LLVM_DEBUG({ 569 llvm::dbgs() << "Graph:\n"; 570 for (auto &target : graph) { 571 llvm::dbgs() << " * " << target.first << "\n"; 572 for (auto &source : target.second) { 573 RootOrderingEntry &entry = source.second; 574 llvm::dbgs() << " <- " << source.first << ": " << entry.cost.first 575 << ":" << entry.cost.second << " via " 576 << entry.connector.getLoc() << "\n"; 577 } 578 } 579 }); 580 581 // Solve the optimal branching problem for each candidate root, or use the 582 // provided one. 583 Value bestRoot = pattern.getRewriter().root(); 584 OptimalBranching::EdgeList bestEdges; 585 if (!bestRoot) { 586 unsigned bestCost = 0; 587 LLVM_DEBUG(llvm::dbgs() << "Candidate roots:\n"); 588 for (Value root : roots) { 589 OptimalBranching solver(graph, root); 590 unsigned cost = solver.solve(); 591 LLVM_DEBUG(llvm::dbgs() << " * " << root << ": " << cost << "\n"); 592 if (!bestRoot || bestCost > cost) { 593 bestCost = cost; 594 bestRoot = root; 595 bestEdges = solver.preOrderTraversal(roots); 596 } 597 } 598 } else { 599 OptimalBranching solver(graph, bestRoot); 600 solver.solve(); 601 bestEdges = solver.preOrderTraversal(roots); 602 } 603 604 LLVM_DEBUG(llvm::dbgs() << "Calling key getTreePredicates:\n"); 605 LLVM_DEBUG(llvm::dbgs() << " * Value: " << bestRoot << "\n"); 606 607 // The best root is the starting point for the traversal. Get the tree 608 // predicates for the DAG rooted at bestRoot. 609 getTreePredicates(predList, bestRoot, builder, valueToPosition, 610 builder.getRoot()); 611 612 // Traverse the selected optimal branching. For all edges in order, traverse 613 // up starting from the connector, until the candidate root is reached, and 614 // call getTreePredicates at every node along the way. 615 for (const std::pair<Value, Value> &edge : bestEdges) { 616 Value target = edge.first; 617 Value source = edge.second; 618 619 // Check if we already visited the target root. This happens in two cases: 620 // 1) the initial root (bestRoot); 621 // 2) a root that is dominated by (contained in the subtree rooted at) an 622 // already visited root. 623 if (valueToPosition.count(target)) 624 continue; 625 626 // Determine the connector. 627 Value connector = graph[target][source].connector; 628 assert(connector && "invalid edge"); 629 LLVM_DEBUG(llvm::dbgs() << " * Connector: " << connector.getLoc() << "\n"); 630 DenseMap<Value, OpIndex> parentMap = parentMaps.lookup(target); 631 Position *pos = valueToPosition.lookup(connector); 632 assert(pos && "The value has not been traversed yet"); 633 bool first = true; 634 635 // Traverse from the connector upwards towards the target root. 636 for (Value value = connector; value != target;) { 637 OpIndex opIndex = parentMap.lookup(value); 638 assert(opIndex.parent && "missing parent"); 639 visitUpward(predList, opIndex, builder, valueToPosition, pos, first); 640 value = opIndex.parent; 641 } 642 } 643 644 getNonTreePredicates(pattern, predList, builder, valueToPosition); 645 646 return bestRoot; 647 } 648 649 //===----------------------------------------------------------------------===// 650 // Pattern Predicate Tree Merging 651 //===----------------------------------------------------------------------===// 652 653 namespace { 654 655 /// This class represents a specific predicate applied to a position, and 656 /// provides hashing and ordering operators. This class allows for computing a 657 /// frequence sum and ordering predicates based on a cost model. 658 struct OrderedPredicate { 659 OrderedPredicate(const std::pair<Position *, Qualifier *> &ip) 660 : position(ip.first), question(ip.second) {} 661 OrderedPredicate(const PositionalPredicate &ip) 662 : position(ip.position), question(ip.question) {} 663 664 /// The position this predicate is applied to. 665 Position *position; 666 667 /// The question that is applied by this predicate onto the position. 668 Qualifier *question; 669 670 /// The first and second order benefit sums. 671 /// The primary sum is the number of occurrences of this predicate among all 672 /// of the patterns. 673 unsigned primary = 0; 674 /// The secondary sum is a squared summation of the primary sum of all of the 675 /// predicates within each pattern that contains this predicate. This allows 676 /// for favoring predicates that are more commonly shared within a pattern, as 677 /// opposed to those shared across patterns. 678 unsigned secondary = 0; 679 680 /// A map between a pattern operation and the answer to the predicate question 681 /// within that pattern. 682 DenseMap<Operation *, Qualifier *> patternToAnswer; 683 684 /// Returns true if this predicate is ordered before `rhs`, based on the cost 685 /// model. 686 bool operator<(const OrderedPredicate &rhs) const { 687 // Sort by: 688 // * higher first and secondary order sums 689 // * lower depth 690 // * lower position dependency 691 // * lower predicate dependency 692 auto *rhsPos = rhs.position; 693 return std::make_tuple(primary, secondary, rhsPos->getOperationDepth(), 694 rhsPos->getKind(), rhs.question->getKind()) > 695 std::make_tuple(rhs.primary, rhs.secondary, 696 position->getOperationDepth(), position->getKind(), 697 question->getKind()); 698 } 699 }; 700 701 /// A DenseMapInfo for OrderedPredicate based solely on the position and 702 /// question. 703 struct OrderedPredicateDenseInfo { 704 using Base = DenseMapInfo<std::pair<Position *, Qualifier *>>; 705 706 static OrderedPredicate getEmptyKey() { return Base::getEmptyKey(); } 707 static OrderedPredicate getTombstoneKey() { return Base::getTombstoneKey(); } 708 static bool isEqual(const OrderedPredicate &lhs, 709 const OrderedPredicate &rhs) { 710 return lhs.position == rhs.position && lhs.question == rhs.question; 711 } 712 static unsigned getHashValue(const OrderedPredicate &p) { 713 return llvm::hash_combine(p.position, p.question); 714 } 715 }; 716 717 /// This class wraps a set of ordered predicates that are used within a specific 718 /// pattern operation. 719 struct OrderedPredicateList { 720 OrderedPredicateList(pdl::PatternOp pattern, Value root) 721 : pattern(pattern), root(root) {} 722 723 pdl::PatternOp pattern; 724 Value root; 725 DenseSet<OrderedPredicate *> predicates; 726 }; 727 } // namespace 728 729 /// Returns true if the given matcher refers to the same predicate as the given 730 /// ordered predicate. This means that the position and questions of the two 731 /// match. 732 static bool isSamePredicate(MatcherNode *node, OrderedPredicate *predicate) { 733 return node->getPosition() == predicate->position && 734 node->getQuestion() == predicate->question; 735 } 736 737 /// Get or insert a child matcher for the given parent switch node, given a 738 /// predicate and parent pattern. 739 std::unique_ptr<MatcherNode> &getOrCreateChild(SwitchNode *node, 740 OrderedPredicate *predicate, 741 pdl::PatternOp pattern) { 742 assert(isSamePredicate(node, predicate) && 743 "expected matcher to equal the given predicate"); 744 745 auto it = predicate->patternToAnswer.find(pattern); 746 assert(it != predicate->patternToAnswer.end() && 747 "expected pattern to exist in predicate"); 748 return node->getChildren().insert({it->second, nullptr}).first->second; 749 } 750 751 /// Build the matcher CFG by "pushing" patterns through by sorted predicate 752 /// order. A pattern will traverse as far as possible using common predicates 753 /// and then either diverge from the CFG or reach the end of a branch and start 754 /// creating new nodes. 755 static void propagatePattern(std::unique_ptr<MatcherNode> &node, 756 OrderedPredicateList &list, 757 std::vector<OrderedPredicate *>::iterator current, 758 std::vector<OrderedPredicate *>::iterator end) { 759 if (current == end) { 760 // We've hit the end of a pattern, so create a successful result node. 761 node = 762 std::make_unique<SuccessNode>(list.pattern, list.root, std::move(node)); 763 764 // If the pattern doesn't contain this predicate, ignore it. 765 } else if (list.predicates.find(*current) == list.predicates.end()) { 766 propagatePattern(node, list, std::next(current), end); 767 768 // If the current matcher node is invalid, create a new one for this 769 // position and continue propagation. 770 } else if (!node) { 771 // Create a new node at this position and continue 772 node = std::make_unique<SwitchNode>((*current)->position, 773 (*current)->question); 774 propagatePattern( 775 getOrCreateChild(cast<SwitchNode>(&*node), *current, list.pattern), 776 list, std::next(current), end); 777 778 // If the matcher has already been created, and it is for this predicate we 779 // continue propagation to the child. 780 } else if (isSamePredicate(node.get(), *current)) { 781 propagatePattern( 782 getOrCreateChild(cast<SwitchNode>(&*node), *current, list.pattern), 783 list, std::next(current), end); 784 785 // If the matcher doesn't match the current predicate, insert a branch as 786 // the common set of matchers has diverged. 787 } else { 788 propagatePattern(node->getFailureNode(), list, current, end); 789 } 790 } 791 792 /// Fold any switch nodes nested under `node` to boolean nodes when possible. 793 /// `node` is updated in-place if it is a switch. 794 static void foldSwitchToBool(std::unique_ptr<MatcherNode> &node) { 795 if (!node) 796 return; 797 798 if (SwitchNode *switchNode = dyn_cast<SwitchNode>(&*node)) { 799 SwitchNode::ChildMapT &children = switchNode->getChildren(); 800 for (auto &it : children) 801 foldSwitchToBool(it.second); 802 803 // If the node only contains one child, collapse it into a boolean predicate 804 // node. 805 if (children.size() == 1) { 806 auto childIt = children.begin(); 807 node = std::make_unique<BoolNode>( 808 node->getPosition(), node->getQuestion(), childIt->first, 809 std::move(childIt->second), std::move(node->getFailureNode())); 810 } 811 } else if (BoolNode *boolNode = dyn_cast<BoolNode>(&*node)) { 812 foldSwitchToBool(boolNode->getSuccessNode()); 813 } 814 815 foldSwitchToBool(node->getFailureNode()); 816 } 817 818 /// Insert an exit node at the end of the failure path of the `root`. 819 static void insertExitNode(std::unique_ptr<MatcherNode> *root) { 820 while (*root) 821 root = &(*root)->getFailureNode(); 822 *root = std::make_unique<ExitNode>(); 823 } 824 825 /// Given a module containing PDL pattern operations, generate a matcher tree 826 /// using the patterns within the given module and return the root matcher node. 827 std::unique_ptr<MatcherNode> 828 MatcherNode::generateMatcherTree(ModuleOp module, PredicateBuilder &builder, 829 DenseMap<Value, Position *> &valueToPosition) { 830 // The set of predicates contained within the pattern operations of the 831 // module. 832 struct PatternPredicates { 833 PatternPredicates(pdl::PatternOp pattern, Value root, 834 std::vector<PositionalPredicate> predicates) 835 : pattern(pattern), root(root), predicates(std::move(predicates)) {} 836 837 /// A pattern. 838 pdl::PatternOp pattern; 839 840 /// A root of the pattern chosen among the candidate roots in pdl.rewrite. 841 Value root; 842 843 /// The extracted predicates for this pattern and root. 844 std::vector<PositionalPredicate> predicates; 845 }; 846 847 SmallVector<PatternPredicates, 16> patternsAndPredicates; 848 for (pdl::PatternOp pattern : module.getOps<pdl::PatternOp>()) { 849 std::vector<PositionalPredicate> predicateList; 850 Value root = 851 buildPredicateList(pattern, builder, predicateList, valueToPosition); 852 patternsAndPredicates.emplace_back(pattern, root, std::move(predicateList)); 853 } 854 855 // Associate a pattern result with each unique predicate. 856 DenseSet<OrderedPredicate, OrderedPredicateDenseInfo> uniqued; 857 for (auto &patternAndPredList : patternsAndPredicates) { 858 for (auto &predicate : patternAndPredList.predicates) { 859 auto it = uniqued.insert(predicate); 860 it.first->patternToAnswer.try_emplace(patternAndPredList.pattern, 861 predicate.answer); 862 } 863 } 864 865 // Associate each pattern to a set of its ordered predicates for later lookup. 866 std::vector<OrderedPredicateList> lists; 867 lists.reserve(patternsAndPredicates.size()); 868 for (auto &patternAndPredList : patternsAndPredicates) { 869 OrderedPredicateList list(patternAndPredList.pattern, 870 patternAndPredList.root); 871 for (auto &predicate : patternAndPredList.predicates) { 872 OrderedPredicate *orderedPredicate = &*uniqued.find(predicate); 873 list.predicates.insert(orderedPredicate); 874 875 // Increment the primary sum for each reference to a particular predicate. 876 ++orderedPredicate->primary; 877 } 878 lists.push_back(std::move(list)); 879 } 880 881 // For a particular pattern, get the total primary sum and add it to the 882 // secondary sum of each predicate. Square the primary sums to emphasize 883 // shared predicates within rather than across patterns. 884 for (auto &list : lists) { 885 unsigned total = 0; 886 for (auto *predicate : list.predicates) 887 total += predicate->primary * predicate->primary; 888 for (auto *predicate : list.predicates) 889 predicate->secondary += total; 890 } 891 892 // Sort the set of predicates now that the cost primary and secondary sums 893 // have been computed. 894 std::vector<OrderedPredicate *> ordered; 895 ordered.reserve(uniqued.size()); 896 for (auto &ip : uniqued) 897 ordered.push_back(&ip); 898 std::stable_sort( 899 ordered.begin(), ordered.end(), 900 [](OrderedPredicate *lhs, OrderedPredicate *rhs) { return *lhs < *rhs; }); 901 902 // Build the matchers for each of the pattern predicate lists. 903 std::unique_ptr<MatcherNode> root; 904 for (OrderedPredicateList &list : lists) 905 propagatePattern(root, list, ordered.begin(), ordered.end()); 906 907 // Collapse the graph and insert the exit node. 908 foldSwitchToBool(root); 909 insertExitNode(&root); 910 return root; 911 } 912 913 //===----------------------------------------------------------------------===// 914 // MatcherNode 915 //===----------------------------------------------------------------------===// 916 917 MatcherNode::MatcherNode(TypeID matcherTypeID, Position *p, Qualifier *q, 918 std::unique_ptr<MatcherNode> failureNode) 919 : position(p), question(q), failureNode(std::move(failureNode)), 920 matcherTypeID(matcherTypeID) {} 921 922 //===----------------------------------------------------------------------===// 923 // BoolNode 924 //===----------------------------------------------------------------------===// 925 926 BoolNode::BoolNode(Position *position, Qualifier *question, Qualifier *answer, 927 std::unique_ptr<MatcherNode> successNode, 928 std::unique_ptr<MatcherNode> failureNode) 929 : MatcherNode(TypeID::get<BoolNode>(), position, question, 930 std::move(failureNode)), 931 answer(answer), successNode(std::move(successNode)) {} 932 933 //===----------------------------------------------------------------------===// 934 // SuccessNode 935 //===----------------------------------------------------------------------===// 936 937 SuccessNode::SuccessNode(pdl::PatternOp pattern, Value root, 938 std::unique_ptr<MatcherNode> failureNode) 939 : MatcherNode(TypeID::get<SuccessNode>(), /*position=*/nullptr, 940 /*question=*/nullptr, std::move(failureNode)), 941 pattern(pattern), root(root) {} 942 943 //===----------------------------------------------------------------------===// 944 // SwitchNode 945 //===----------------------------------------------------------------------===// 946 947 SwitchNode::SwitchNode(Position *position, Qualifier *question) 948 : MatcherNode(TypeID::get<SwitchNode>(), position, question) {} 949