13#include "llvm/ADT/TypeSwitch.h"
19#include "mlir/Dialect/PDL/IR/PDLOpsDialect.cpp.inc"
38 if (!llvm::isa_and_nonnull<PatternOp>(op->
getParentOp()))
43 "expected a bindable user when defined in the matcher body of a "
51 if (!isa<PatternOp>(op->
getParentOp()) || isa<RewriteOp>(op))
55 if (!visited.insert(op).second)
60 .Case([&visited](OperationOp operation) {
61 for (
Value operand : operation.getOperandValues())
62 visit(operand.getDefiningOp(), visited);
64 .Case<ResultOp, ResultsOp>([&visited](
auto result) {
77LogicalResult ApplyNativeConstraintOp::verify() {
78 if (getNumOperands() == 0)
79 return emitOpError(
"expected at least one argument");
81 return isa<OperationType>(
result.getType());
84 "returning an operation from a constraint is not supported");
93LogicalResult ApplyNativeRewriteOp::verify() {
94 if (getNumOperands() == 0 && getNumResults() == 0)
95 return emitOpError(
"expected at least one argument or result");
103LogicalResult AttributeOp::verify() {
105 std::optional<Attribute> attrValue = getValue();
108 if (isa<RewriteOp>((*this)->getParentOp()))
110 "expected constant value when specified within a `pdl.rewrite`");
114 return emitOpError(
"expected only one of [`type`, `value`] to be set");
141 auto parseOperands = [&]() {
147 attrNames.push_back(nameAttr);
148 attrOperands.push_back(operand);
161 if (attrNames.empty())
164 interleaveComma(llvm::seq<int>(0, attrNames.size()), p,
165 [&](
int i) { p << attrNames[i] <<
" = " << attrArgs[i]; });
174 Block *rewriterBlock = op->getBlock();
175 auto canInferTypeFromUse = [&](
OpOperand &use) {
178 ReplaceOp replOpUser = dyn_cast<ReplaceOp>(use.getOwner());
179 if (!replOpUser || use.getOperandNumber() == 0)
182 Operation *replacedOp = replOpUser.getOpValue().getDefiningOp();
183 return replacedOp->
getBlock() != rewriterBlock ||
189 if (llvm::any_of(op.getOp().getUses(), canInferTypeFromUse))
193 if (resultTypes.empty()) {
196 std::optional<StringRef> rawOpName = op.getOpName();
199 std::optional<RegisteredOperationName> opName =
208 bool expectedAtLeastOneResult =
211 if (expectedAtLeastOneResult) {
213 .emitOpError(
"must have inferable or constrained result types when "
214 "nested within `pdl.rewrite`")
216 .append(
"operation is created in a non-inferrable context, but '",
217 *opName,
"' does not implement InferTypeOpInterface");
223 for (
const auto &it : llvm::enumerate(resultTypes)) {
224 Operation *resultTypeOp = it.value().getDefiningOp();
225 assert(resultTypeOp &&
"expected valid result type operation");
229 if (isa<ApplyNativeRewriteOp>(resultTypeOp))
234 auto constrainsInput = [rewriterBlock](
Operation *user) {
235 return user->getBlock() != rewriterBlock &&
236 isa<OperandOp, OperandsOp, OperationOp>(user);
238 if (TypeOp typeOp = dyn_cast<TypeOp>(resultTypeOp)) {
239 if (typeOp.getConstantType() ||
240 llvm::any_of(typeOp->getUsers(), constrainsInput))
242 }
else if (TypesOp typeOp = dyn_cast<TypesOp>(resultTypeOp)) {
243 if (typeOp.getConstantTypes() ||
244 llvm::any_of(typeOp->getUsers(), constrainsInput))
249 .emitOpError(
"must have inferable or constrained result types when "
250 "nested within `pdl.rewrite`")
252 .append(
"result type #", it.index(),
" was not constrained");
257LogicalResult OperationOp::verify() {
258 bool isWithinRewrite = isa_and_nonnull<RewriteOp>((*this)->getParentOp());
259 if (isWithinRewrite && !getOpName())
260 return emitOpError(
"must have an operation name when nested within "
262 ArrayAttr attributeNames = getAttributeValueNamesAttr();
263 auto attributeValues = getAttributeValues();
264 if (attributeNames.size() != attributeValues.size()) {
266 <<
"expected the same number of attribute values and attribute "
268 << attributeNames.size() <<
" names and " << attributeValues.size()
274 if (isWithinRewrite && !mightHaveTypeInference()) {
282bool OperationOp::hasTypeInference() {
283 if (std::optional<StringRef> rawOpName = getOpName()) {
285 return opName.hasInterface<InferTypeOpInterface>();
290bool OperationOp::mightHaveTypeInference() {
291 if (std::optional<StringRef> rawOpName = getOpName()) {
293 return opName.mightHaveInterface<InferTypeOpInterface>();
302LogicalResult PatternOp::verifyRegions() {
303 Region &body = getBodyRegion();
305 auto rewriteOp = dyn_cast<RewriteOp>(term);
307 return emitOpError(
"expected body to terminate with `pdl.rewrite`")
308 .attachNote(term->
getLoc())
309 .append(
"see terminator defined here");
314 WalkResult
result = body.
walk([&](Operation *op) -> WalkResult {
315 if (!isa_and_nonnull<PDLDialect>(op->
getDialect())) {
316 emitOpError(
"expected only `pdl` operations within the pattern body")
318 .append(
"see non-`pdl` operation defined here");
323 if (
result.wasInterrupted())
328 return emitOpError(
"the pattern must contain at least one `pdl.operation`");
338 for (Operation &op : body.
front()) {
340 if (!isa<OperandOp, OperandsOp, ResultOp, ResultsOp, OperationOp>(op))
344 bool hasUserInRewrite =
false;
345 for (Operation *user : op.
getUsers()) {
346 Region *region = user->getParentRegion();
347 if (isa<RewriteOp>(user) ||
348 (region && isa<RewriteOp>(region->
getParentOp()))) {
349 hasUserInRewrite =
true;
355 if (!hasUserInRewrite)
362 }
else if (!visited.count(&op)) {
364 return emitOpError(
"the operations must form a connected component")
366 .append(
"see a disconnected value / operation here");
373void PatternOp::build(OpBuilder &builder, OperationState &state,
374 std::optional<uint16_t> benefit,
375 std::optional<StringRef> name) {
379 state.
regions[0]->emplaceBlock();
383RewriteOp PatternOp::getRewriter() {
384 return cast<RewriteOp>(getBodyRegion().front().getTerminator());
388StringRef PatternOp::getDefaultDialect() {
389 return PDLDialect::getDialectNamespace();
399 if (!argumentTypes.empty()) {
409 if (argumentTypes.empty())
410 p <<
": " << resultType;
413LogicalResult RangeOp::verify() {
414 Type elementType =
getType().getElementType();
415 for (Type operandType : getOperandTypes()) {
417 if (operandElementType != elementType) {
418 return emitOpError(
"expected operand to have element type ")
419 << elementType <<
", but got " << operandElementType;
429LogicalResult ReplaceOp::verify() {
430 if (getReplOperation() && !getReplValues().empty())
431 return emitOpError() <<
"expected no replacement values to be provided"
432 " when the replacement operation is present";
454 p <<
" -> " << resultType;
457LogicalResult ResultsOp::verify() {
459 return emitOpError() <<
"expected `pdl.range<value>` result type when "
460 "no index is specified, but got: "
470LogicalResult RewriteOp::verifyRegions() {
471 Region &rewriteRegion = getBodyRegion();
475 if (!rewriteRegion.
empty()) {
477 <<
"expected rewrite region to be empty when rewrite is external";
483 if (rewriteRegion.
empty()) {
484 return emitOpError() <<
"expected rewrite region to be non-empty if "
485 "external name is not specified";
489 if (!getExternalArgs().empty()) {
490 return emitOpError() <<
"expected no external arguments when the "
491 "rewrite is specified inline";
498StringRef RewriteOp::getDefaultDialect() {
499 return PDLDialect::getDialectNamespace();
506LogicalResult TypeOp::verify() {
507 if (!getConstantTypeAttr())
516LogicalResult TypesOp::verify() {
517 if (!getConstantTypesAttr())
526#define GET_OP_CLASSES
527#include "mlir/Dialect/PDL/IR/PDLOps.cpp.inc"
static ParseResult parseResultsValueType(OpAsmParser &p, IntegerAttr index, Type &resultType)
static LogicalResult verifyHasBindingUse(Operation *op)
Returns success if the given operation is not in the main matcher body or is used by a "binding" oper...
static void visit(Operation *op, DenseSet< Operation * > &visited)
Visits all the pdl.operand(s), pdl.result(s), and pdl.operation(s) connected to the given operation.
static LogicalResult verifyResultTypesAreInferrable(OperationOp op, OperandRange resultTypes)
Verifies that the result types of this operation, defined within a pdl.rewrite, can be inferred.
static void printRangeType(OpAsmPrinter &p, RangeOp op, TypeRange argumentTypes, Type resultType)
static ParseResult parseRangeType(OpAsmParser &p, TypeRange argumentTypes, Type &resultType)
static ParseResult parseOperationOpAttributes(OpAsmParser &p, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &attrOperands, ArrayAttr &attrNamesAttr)
static bool hasBindingUse(Operation *op)
Returns true if the given operation is used by a "binding" pdl operation.
static void printOperationOpAttributes(OpAsmPrinter &p, OperationOp op, OperandRange attrArgs, ArrayAttr attrNames)
static void printResultsValueType(OpAsmPrinter &p, ResultsOp op, IntegerAttr index, Type resultType)
static Type getValueType(Attribute attr)
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseRBrace()=0
Parse a } token.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual ParseResult parseArrow()=0
Parse a '->' token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual ParseResult parseOptionalLBrace()=0
Parse a { token if present.
Block represents an ordered list of Operations.
Operation * getTerminator()
Get the terminator operation of this block.
auto getOps()
Return an iterator range over the operations within this block that are of 'OpT'.
This class is a general helper class for creating context-global objects like types,...
IntegerAttr getI16IntegerAttr(int16_t value)
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
StringAttr getStringAttr(const Twine &bytes)
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
This class represents an operand of an operation.
This is a value defined by a result of an operation.
This class provides the API for ops which have an unknown number of results.
This class provides return value APIs for ops that are known to have zero results.
This class implements the operand iterators for the Operation class.
Operation is the basic unit of execution within MLIR.
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
Block * getBlock()
Returns the operation block that contains this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
user_range getUsers()
Returns a range of all users.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Operation * getParentOp()
Return the parent operation this region is attached to.
RetT walk(FnT &&callback)
Walk all nested operations, blocks or regions (including this region), depending on the type of callb...
static std::optional< RegisteredOperationName > lookup(StringRef name, MLIRContext *ctx)
Lookup the registered operation information for the given operation.
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
static WalkResult advance()
static WalkResult interrupt()
Type getRangeElementTypeOrSelf(Type type)
If the given type is a range, return its element type, otherwise return the type itself.
DynamicAPInt getIndex(const ConeV &cone)
Get the index of a cone, i.e., the volume of the parallelepiped spanned by its generators,...
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
llvm::TypeSwitch< T, ResultT > TypeSwitch
This is the representation of an operand reference.
SmallVector< std::unique_ptr< Region >, 1 > regions
Regions that the op will hold.