MLIR 24.0.0git
PDLInterp.cpp
Go to the documentation of this file.
1//===- PDLInterp.cpp - PDL Interpreter Dialect ------------------*- C++ -*-===//
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
13
14using namespace mlir;
15using namespace mlir::pdl_interp;
16
17#include "mlir/Dialect/PDLInterp/IR/PDLInterpOpsDialect.cpp.inc"
18
19//===----------------------------------------------------------------------===//
20// PDLInterp Dialect
21//===----------------------------------------------------------------------===//
22
23template <typename OpT>
24static LogicalResult verifySwitchOp(OpT op) {
25 // Verify that the number of case destinations matches the number of case
26 // values.
27 size_t numDests = op.getCases().size();
28 size_t numValues = op.getCaseValues().size();
29 if (numDests != numValues) {
30 return op.emitOpError(
31 "expected number of cases to match the number of case "
32 "values, got ")
33 << numDests << " but expected " << numValues;
34 }
35 return success();
36}
37
38//===----------------------------------------------------------------------===//
39// pdl_interp::CreateOperationOp
40//===----------------------------------------------------------------------===//
41
42LogicalResult CreateOperationOp::verify() {
43 if (!getInferredResultTypes())
44 return success();
45 if (!getInputResultTypes().empty()) {
46 return emitOpError("with inferred results cannot also have "
47 "explicit result types");
48 }
49 OperationName opName(getName(), getContext());
50 if (!opName.hasInterface<InferTypeOpInterface>()) {
51 return emitOpError()
52 << "has inferred results, but the created operation '" << opName
53 << "' does not support result type inference (or is not "
54 "registered)";
55 }
56 return success();
57}
58
60 OpAsmParser &p,
62 ArrayAttr &attrNamesAttr) {
63 Builder &builder = p.getBuilder();
65 if (succeeded(p.parseOptionalLBrace())) {
66 auto parseOperands = [&]() {
67 StringAttr nameAttr;
69 if (p.parseAttribute(nameAttr) || p.parseEqual() ||
70 p.parseOperand(operand))
71 return failure();
72 attrNames.push_back(nameAttr);
73 attrOperands.push_back(operand);
74 return success();
75 };
76 if (p.parseCommaSeparatedList(parseOperands) || p.parseRBrace())
77 return failure();
78 }
79 attrNamesAttr = builder.getArrayAttr(attrNames);
80 return success();
81}
82
84 CreateOperationOp op,
85 OperandRange attrArgs,
86 ArrayAttr attrNames) {
87 if (attrNames.empty())
88 return;
89 p << " {";
90 interleaveComma(llvm::seq<int>(0, attrNames.size()), p,
91 [&](int i) { p << attrNames[i] << " = " << attrArgs[i]; });
92 p << '}';
93}
94
96 OpAsmParser &p,
98 SmallVectorImpl<Type> &resultTypes, UnitAttr &inferredResultTypes) {
99 if (failed(p.parseOptionalArrow()))
100 return success();
101
102 // Handle the case of inferred results.
103 if (succeeded(p.parseOptionalLess())) {
104 if (p.parseKeyword("inferred") || p.parseGreater())
105 return failure();
106 inferredResultTypes = p.getBuilder().getUnitAttr();
107 return success();
108 }
109
110 // Otherwise, parse the explicit results.
111 return failure(p.parseLParen() || p.parseOperandList(resultOperands) ||
112 p.parseColonTypeList(resultTypes) || p.parseRParen());
113}
114
115static void printCreateOperationOpResults(OpAsmPrinter &p, CreateOperationOp op,
116 OperandRange resultOperands,
117 TypeRange resultTypes,
118 UnitAttr inferredResultTypes) {
119 // Handle the case of inferred results.
120 if (inferredResultTypes) {
121 p << " -> <inferred>";
122 return;
123 }
124
125 // Otherwise, handle the explicit results.
126 if (!resultTypes.empty())
127 p << " -> (" << resultOperands << " : " << resultTypes << ")";
128}
129
130//===----------------------------------------------------------------------===//
131// pdl_interp::ForEachOp
132//===----------------------------------------------------------------------===//
133
134void ForEachOp::build(::mlir::OpBuilder &builder, ::mlir::OperationState &state,
135 Value range, Block *successor, bool initLoop) {
136 build(builder, state, range, successor);
137 if (initLoop) {
138 // Create the block and the loop variable.
139 // FIXME: Allow passing in a proper location for the loop variable.
140 auto rangeType = llvm::cast<pdl::RangeType>(range.getType());
141 state.regions.front()->emplaceBlock();
142 state.regions.front()->addArgument(rangeType.getElementType(),
143 state.location);
144 }
145}
146
147ParseResult ForEachOp::parse(OpAsmParser &parser, OperationState &result) {
148 // Parse the loop variable followed by type.
149 OpAsmParser::Argument loopVariable;
151 if (parser.parseArgument(loopVariable, /*allowType=*/true) ||
152 parser.parseKeyword("in", " after loop variable") ||
153 // Parse the operand (value range).
154 parser.parseOperand(operandInfo))
155 return failure();
156
157 // Resolve the operand.
158 Type rangeType = pdl::RangeType::get(loopVariable.type);
159 if (parser.resolveOperand(operandInfo, rangeType, result.operands))
160 return failure();
161
162 // Parse the body region.
163 Region *body = result.addRegion();
164 Block *successor;
165 if (parser.parseRegion(*body, loopVariable) ||
166 parser.parseOptionalAttrDict(result.attributes) ||
167 // Parse the successor.
168 parser.parseArrow() || parser.parseSuccessor(successor))
169 return failure();
170
171 result.addSuccessors(successor);
172 return success();
173}
174
175void ForEachOp::print(OpAsmPrinter &p) {
176 BlockArgument arg = getLoopVariable();
177 p << ' ' << arg << " : " << arg.getType() << " in " << getValues() << ' ';
178 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
179 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
180 p << " -> ";
181 p.printSuccessor(getSuccessor());
182}
183
184LogicalResult ForEachOp::verify() {
185 // Verify that the operation has exactly one argument.
186 if (getRegion().getNumArguments() != 1)
187 return emitOpError("requires exactly one argument");
188
189 // Verify that the loop variable and the operand (value range)
190 // have compatible types.
191 BlockArgument arg = getLoopVariable();
192 Type rangeType = pdl::RangeType::get(arg.getType());
193 if (rangeType != getValues().getType())
194 return emitOpError("operand must be a range of loop variable type");
195
196 return success();
197}
198
199//===----------------------------------------------------------------------===//
200// pdl_interp::FuncOp
201//===----------------------------------------------------------------------===//
202
203void FuncOp::build(OpBuilder &builder, OperationState &state, StringRef name,
204 FunctionType type, ArrayRef<NamedAttribute> attrs) {
205 buildWithEntryBlock(builder, state, name, type, attrs, type.getInputs());
206}
207
208ParseResult FuncOp::parse(OpAsmParser &parser, OperationState &result) {
209 auto buildFuncType =
210 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
212 std::string &) { return builder.getFunctionType(argTypes, results); };
213
215 parser, result, /*allowVariadic=*/false,
216 getFunctionTypeAttrName(result.name), buildFuncType,
217 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
218}
219
220void FuncOp::print(OpAsmPrinter &p) {
222 p, *this, /*isVariadic=*/false, getFunctionTypeAttrName(),
223 getArgAttrsAttrName(), getResAttrsAttrName());
224}
225
226//===----------------------------------------------------------------------===//
227// pdl_interp::GetValueTypeOp
228//===----------------------------------------------------------------------===//
229
230/// Given the result type of a `GetValueTypeOp`, return the expected input type.
232 Type valueTy = pdl::ValueType::get(type.getContext());
233 return llvm::isa<pdl::RangeType>(type) ? pdl::RangeType::get(valueTy)
234 : valueTy;
235}
236
237//===----------------------------------------------------------------------===//
238// pdl::CreateRangeOp
239//===----------------------------------------------------------------------===//
240
241static ParseResult parseRangeType(OpAsmParser &p, TypeRange argumentTypes,
242 Type &resultType) {
243 // If arguments were provided, infer the result type from the argument list.
244 if (!argumentTypes.empty()) {
245 resultType =
246 pdl::RangeType::get(pdl::getRangeElementTypeOrSelf(argumentTypes[0]));
247 return success();
248 }
249 // Otherwise, parse the type as a trailing type.
250 return p.parseColonType(resultType);
251}
252
253static void printRangeType(OpAsmPrinter &p, CreateRangeOp op,
254 TypeRange argumentTypes, Type resultType) {
255 if (argumentTypes.empty())
256 p << ": " << resultType;
257}
258
259LogicalResult CreateRangeOp::verify() {
260 Type elementType = getType().getElementType();
261 for (Type operandType : getOperandTypes()) {
262 Type operandElementType = pdl::getRangeElementTypeOrSelf(operandType);
263 if (operandElementType != elementType) {
264 return emitOpError("expected operand to have element type ")
265 << elementType << ", but got " << operandElementType;
266 }
267 }
268 return success();
269}
270
271//===----------------------------------------------------------------------===//
272// pdl_interp::SwitchAttributeOp
273//===----------------------------------------------------------------------===//
274
275LogicalResult SwitchAttributeOp::verify() { return verifySwitchOp(*this); }
276
277//===----------------------------------------------------------------------===//
278// pdl_interp::SwitchOperandCountOp
279//===----------------------------------------------------------------------===//
280
281LogicalResult SwitchOperandCountOp::verify() { return verifySwitchOp(*this); }
282
283//===----------------------------------------------------------------------===//
284// pdl_interp::SwitchOperationNameOp
285//===----------------------------------------------------------------------===//
286
287LogicalResult SwitchOperationNameOp::verify() { return verifySwitchOp(*this); }
288
289//===----------------------------------------------------------------------===//
290// pdl_interp::SwitchResultCountOp
291//===----------------------------------------------------------------------===//
292
293LogicalResult SwitchResultCountOp::verify() { return verifySwitchOp(*this); }
294
295//===----------------------------------------------------------------------===//
296// pdl_interp::SwitchTypeOp
297//===----------------------------------------------------------------------===//
298
299LogicalResult SwitchTypeOp::verify() { return verifySwitchOp(*this); }
300
301//===----------------------------------------------------------------------===//
302// pdl_interp::SwitchTypesOp
303//===----------------------------------------------------------------------===//
304
305LogicalResult SwitchTypesOp::verify() { return verifySwitchOp(*this); }
306
307//===----------------------------------------------------------------------===//
308// TableGen Auto-Generated Op and Interface Definitions
309//===----------------------------------------------------------------------===//
310
311#define GET_OP_CLASSES
312#include "mlir/Dialect/PDLInterp/IR/PDLInterpOps.cpp.inc"
return success()
static void printRangeType(OpAsmPrinter &p, CreateRangeOp op, TypeRange argumentTypes, Type resultType)
static void printCreateOperationOpResults(OpAsmPrinter &p, CreateOperationOp op, OperandRange resultOperands, TypeRange resultTypes, UnitAttr inferredResultTypes)
static Type getGetValueTypeOpValueType(Type type)
Given the result type of a GetValueTypeOp, return the expected input type.
static ParseResult parseCreateOperationOpResults(OpAsmParser &p, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &resultOperands, SmallVectorImpl< Type > &resultTypes, UnitAttr &inferredResultTypes)
Definition PDLInterp.cpp:95
static ParseResult parseCreateOperationOpAttributes(OpAsmParser &p, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &attrOperands, ArrayAttr &attrNamesAttr)
Definition PDLInterp.cpp:59
static LogicalResult verifySwitchOp(OpT op)
Definition PDLInterp.cpp:24
static ParseResult parseRangeType(OpAsmParser &p, TypeRange argumentTypes, Type &resultType)
static void printCreateOperationOpAttributes(OpAsmPrinter &p, CreateOperationOp op, OperandRange attrArgs, ArrayAttr attrNames)
Definition PDLInterp.cpp:83
ArrayAttr()
b getContext())
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
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 parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual ParseResult parseOptionalArrow()=0
Parse a '->' token if present.
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 parseOptionalLess()=0
Parse a '<' token if present.
virtual ParseResult parseArrow()=0
Parse a '->' token.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
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.
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
UnitAttr getUnitAttr()
Definition Builders.cpp:106
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition Builders.cpp:84
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult parseSuccessor(Block *&dest)=0
Parse a single operation successor.
virtual ParseResult parseArgument(Argument &result, bool allowType=false, bool allowAttrs=false)=0
Parse a single argument with the following syntax:
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
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.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printSuccessor(Block *successor)=0
Print the given successor.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
This class helps build Operations.
Definition Builders.h:210
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
A named class for passing around the variadic flag.
void printFunctionOp(OpAsmPrinter &p, FunctionOpInterface op, bool isVariadic, StringRef typeAttrName, StringAttr argAttrsName, StringAttr resAttrsName)
Printer implementation for function-like operations.
ParseResult parseFunctionOp(OpAsmParser &parser, OperationState &result, bool allowVariadic, StringAttr typeAttrName, FuncTypeBuilder funcTypeBuilder, StringAttr argAttrsName, StringAttr resAttrsName)
Parser implementation for function-like operations.
Type getRangeElementTypeOrSelf(Type type)
If the given type is a range, return its element type, otherwise return the type itself.
Definition PDLTypes.cpp:48
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
This is the representation of an operand reference.
This represents an operation in an abstracted form, suitable for use with the builder APIs.
SmallVector< std::unique_ptr< Region >, 1 > regions
Regions that the op will hold.