#include "llvm/ADT/SmallString.h"
namespace mlir {
+
+namespace impl {
+/// Return the name of the attribute used for function types.
+inline StringRef getTypeAttrName() { return "type"; }
+
+/// Return the name of the attribute used for function arguments.
+inline StringRef getArgAttrName(unsigned arg, SmallVectorImpl<char> &out) {
+ out.clear();
+ return ("arg" + Twine(arg)).toStringRef(out);
+}
+
+/// Returns the dictionary attribute corresponding to the argument at 'index'.
+/// If there are no argument attributes at 'index', a null attribute is
+/// returned.
+inline DictionaryAttr getArgAttrDict(Operation *op, unsigned index) {
+ SmallString<8> nameOut;
+ return op->getAttrOfType<DictionaryAttr>(getArgAttrName(index, nameOut));
+}
+
+/// Return all of the attributes for the argument at 'index'.
+inline ArrayRef<NamedAttribute> getArgAttrs(Operation *op, unsigned index) {
+ auto argDict = getArgAttrDict(op, index);
+ return argDict ? argDict.getValue() : llvm::None;
+}
+
+/// Callback type for `parseFunctionLikeOp`, the callback should produce the
+/// type that will be associated with a function-like operation from lists of
+/// function arguments and results.
+using FuncTypeBuilder =
+ llvm::function_ref<Type(Builder &, ArrayRef<Type>, ArrayRef<Type>)>;
+
+/// Parser implementation for function-like operations. Uses
+/// `funcTypeBuilder` to construct the custom function type given lists of
+/// input and output types. If the builder returns a null type, `result` will
+/// not contain the `type` attribute. The caller can then either add the type
+/// or use op's verifier to report errors.
+ParseResult parseFunctionLikeOp(OpAsmParser *parser, OperationState *result,
+ FuncTypeBuilder funcTypeBuilder);
+
+/// Printer implementation for function-like operations. Accepts lists of
+/// argument and result types to use while printing.
+void printFunctionLikeOp(OpAsmPrinter *p, Operation *op,
+ ArrayRef<Type> argTypes, ArrayRef<Type> results);
+
+} // namespace impl
+
namespace OpTrait {
/// This trait provides APIs for Ops that behave like functions. In particular:
//===--------------------------------------------------------------------===//
/// Return the name of the attribute used for function types.
- static StringRef getTypeAttrName() { return "type"; }
+ static StringRef getTypeAttrName() { return ::mlir::impl::getTypeAttrName(); }
TypeAttr getTypeAttr() {
return this->getOperation()->template getAttrOfType<TypeAttr>(
/// Return all of the attributes for the argument at 'index'.
ArrayRef<NamedAttribute> getArgAttrs(unsigned index) {
- auto argDict = getArgAttrDict(index);
- return argDict ? argDict.getValue() : llvm::None;
+ return ::mlir::impl::getArgAttrs(this->getOperation(), index);
}
/// Return all argument attributes of this function.
protected:
/// Returns the attribute entry name for the set of argument attributes at
/// index 'arg'.
- static StringRef getArgAttrName(unsigned arg, SmallVectorImpl<char> &out);
+ static StringRef getArgAttrName(unsigned arg, SmallVectorImpl<char> &out) {
+ return ::mlir::impl::getArgAttrName(arg, out);
+ }
/// Returns the dictionary attribute corresponding to the argument at 'index'.
/// If there are no argument attributes at 'index', a null attribute is
/// returned.
DictionaryAttr getArgAttrDict(unsigned index) {
assert(index < getNumArguments() && "invalid argument number");
- SmallString<8> nameOut;
- return this->getOperation()->template getAttrOfType<DictionaryAttr>(
- getArgAttrName(index, nameOut));
+ return ::mlir::impl::getArgAttrDict(this->getOperation(), index);
}
/// Hook for concrete classes to verify that the type attribute respects
return result;
}
-/// Returns the attribute entry name for the set of argument attributes at index
-/// 'arg'.
-template <typename ConcreteType>
-StringRef
-FunctionLike<ConcreteType>::getArgAttrName(unsigned arg,
- SmallVectorImpl<char> &out) {
- out.clear();
- return ("arg" + Twine(arg)).toStringRef(out);
-}
-
} // end namespace OpTrait
} // end namespace mlir
}
/// Parsing/Printing methods.
-static ParseResult
-parseArgumentList(OpAsmParser *parser, SmallVectorImpl<Type> &argTypes,
- SmallVectorImpl<OpAsmParser::OperandType> &argNames,
- SmallVectorImpl<SmallVector<NamedAttribute, 2>> &argAttrs) {
- if (parser->parseLParen())
- return failure();
-
- // The argument list either has to consistently have ssa-id's followed by
- // types, or just be a type list. It isn't ok to sometimes have SSA ID's and
- // sometimes not.
- auto parseArgument = [&]() -> ParseResult {
- llvm::SMLoc loc = parser->getCurrentLocation();
-
- // Parse argument name if present.
- OpAsmParser::OperandType argument;
- Type argumentType;
- if (succeeded(parser->parseOptionalRegionArgument(argument)) &&
- !argument.name.empty()) {
- // Reject this if the preceding argument was missing a name.
- if (argNames.empty() && !argTypes.empty())
- return parser->emitError(loc,
- "expected type instead of SSA identifier");
- argNames.push_back(argument);
-
- if (parser->parseColonType(argumentType))
- return failure();
- } else if (!argNames.empty()) {
- // Reject this if the preceding argument had a name.
- return parser->emitError(loc, "expected SSA identifier");
- } else if (parser->parseType(argumentType)) {
- return failure();
- }
-
- // Add the argument type.
- argTypes.push_back(argumentType);
-
- // Parse any argument attributes.
- SmallVector<NamedAttribute, 2> attrs;
- if (parser->parseOptionalAttributeDict(attrs))
- return failure();
- argAttrs.push_back(attrs);
- return success();
- };
-
- // Parse the function arguments.
- if (parser->parseOptionalRParen()) {
- do {
- if (parseArgument())
- return failure();
- } while (succeeded(parser->parseOptionalComma()));
- parser->parseRParen();
- }
-
- return success();
-}
-
-/// Parse a function signature, starting with a name and including the
-/// parameter list.
-static ParseResult parseFunctionSignature(
- OpAsmParser *parser, FunctionType &type,
- SmallVectorImpl<OpAsmParser::OperandType> &argNames,
- SmallVectorImpl<SmallVector<NamedAttribute, 2>> &argAttrs) {
- SmallVector<Type, 4> argTypes;
- if (parseArgumentList(parser, argTypes, argNames, argAttrs))
- return failure();
-
- // Parse the return types if present.
- SmallVector<Type, 4> results;
- if (parser->parseOptionalArrowTypeList(results))
- return failure();
- type = parser->getBuilder().getFunctionType(argTypes, results);
- return success();
-}
ParseResult FuncOp::parse(OpAsmParser *parser, OperationState *result) {
- FunctionType type;
- SmallVector<OpAsmParser::OperandType, 4> entryArgs;
- SmallVector<SmallVector<NamedAttribute, 2>, 4> argAttrs;
- auto &builder = parser->getBuilder();
-
- // Parse the name as a symbol reference attribute.
- SymbolRefAttr nameAttr;
- if (parser->parseAttribute(nameAttr, SymbolTable::getSymbolAttrName(),
- result->attributes))
- return failure();
- // Convert the parsed function attr into a string attr.
- result->attributes.back().second = builder.getStringAttr(nameAttr.getValue());
-
- // Parse the function signature.
- if (parseFunctionSignature(parser, type, entryArgs, argAttrs))
- return failure();
- result->addAttribute(getTypeAttrName(), builder.getTypeAttr(type));
-
- // If function attributes are present, parse them.
- if (succeeded(parser->parseOptionalKeyword("attributes")))
- if (parser->parseOptionalAttributeDict(result->attributes))
- return failure();
-
- // Add the attributes to the function arguments.
- SmallString<8> argAttrName;
- for (unsigned i = 0, e = type.getNumInputs(); i != e; ++i)
- if (!argAttrs[i].empty())
- result->addAttribute(getArgAttrName(i, argAttrName),
- builder.getDictionaryAttr(argAttrs[i]));
-
- // Parse the optional function body.
- auto *body = result->addRegion();
- if (parser->parseOptionalRegion(
- *body, entryArgs, entryArgs.empty() ? llvm::None : type.getInputs()))
- return failure();
-
- return success();
-}
-
-static void printFunctionSignature(OpAsmPrinter *p, FuncOp op) {
- *p << '(';
-
- auto fnType = op.getType();
- bool isExternal = op.isExternal();
- for (unsigned i = 0, e = op.getNumArguments(); i != e; ++i) {
- if (i > 0)
- *p << ", ";
-
- // If this is an external function, don't print argument labels.
- if (!isExternal) {
- p->printOperand(op.getArgument(i));
- *p << ": ";
- }
-
- // Print the type followed by any argument attributes.
- p->printType(fnType.getInput(i));
- p->printOptionalAttrDict(op.getArgAttrs(i));
- }
- *p << ')';
- p->printOptionalArrowTypeList(fnType.getResults());
+ return impl::parseFunctionLikeOp(
+ parser, result,
+ [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results) {
+ return builder.getFunctionType(argTypes, results);
+ });
}
void FuncOp::print(OpAsmPrinter *p) {
- *p << "func @" << getName();
-
- // Print the signature.
- printFunctionSignature(p, *this);
-
- // Print out function attributes, if present.
- SmallVector<StringRef, 2> ignoredAttrs = {SymbolTable::getSymbolAttrName(),
- getTypeAttrName()};
-
- // Ignore any argument attributes.
- std::vector<SmallString<8>> argAttrStorage;
- SmallString<8> argAttrName;
- for (unsigned i = 0, e = getNumArguments(); i != e; ++i)
- if (getAttr(getArgAttrName(i, argAttrName)))
- argAttrStorage.emplace_back(argAttrName);
- ignoredAttrs.append(argAttrStorage.begin(), argAttrStorage.end());
-
- auto attrs = getAttrs();
- if (attrs.size() > ignoredAttrs.size()) {
- *p << "\n attributes ";
- p->printOptionalAttrDict(attrs, ignoredAttrs);
- }
-
- // Print the body if this is not an external function.
- if (!isExternal())
- p->printRegion(getBody(), /*printEntryBlockArgs=*/false,
- /*printBlockTerminators=*/true);
+ FunctionType fnType = getType();
+ impl::printFunctionLikeOp(p, *this, fnType.getInputs(), fnType.getResults());
}
LogicalResult FuncOp::verify() {
--- /dev/null
+//===- FunctionSupport.cpp - Utility types for function-like ops ----------===//
+//
+// Copyright 2019 The MLIR Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+// =============================================================================
+
+#include "mlir/IR/FunctionSupport.h"
+#include "mlir/IR/Builders.h"
+#include "mlir/IR/OpImplementation.h"
+
+using namespace mlir;
+
+static ParseResult
+parseArgumentList(OpAsmParser *parser, SmallVectorImpl<Type> &argTypes,
+ SmallVectorImpl<OpAsmParser::OperandType> &argNames,
+ SmallVectorImpl<SmallVector<NamedAttribute, 2>> &argAttrs) {
+ if (parser->parseLParen())
+ return failure();
+
+ // The argument list either has to consistently have ssa-id's followed by
+ // types, or just be a type list. It isn't ok to sometimes have SSA ID's and
+ // sometimes not.
+ auto parseArgument = [&]() -> ParseResult {
+ llvm::SMLoc loc = parser->getCurrentLocation();
+
+ // Parse argument name if present.
+ OpAsmParser::OperandType argument;
+ Type argumentType;
+ if (succeeded(parser->parseOptionalRegionArgument(argument)) &&
+ !argument.name.empty()) {
+ // Reject this if the preceding argument was missing a name.
+ if (argNames.empty() && !argTypes.empty())
+ return parser->emitError(loc,
+ "expected type instead of SSA identifier");
+ argNames.push_back(argument);
+
+ if (parser->parseColonType(argumentType))
+ return failure();
+ } else if (!argNames.empty()) {
+ // Reject this if the preceding argument had a name.
+ return parser->emitError(loc, "expected SSA identifier");
+ } else if (parser->parseType(argumentType)) {
+ return failure();
+ }
+
+ // Add the argument type.
+ argTypes.push_back(argumentType);
+
+ // Parse any argument attributes.
+ SmallVector<NamedAttribute, 2> attrs;
+ if (parser->parseOptionalAttributeDict(attrs))
+ return failure();
+ argAttrs.push_back(attrs);
+ return success();
+ };
+
+ // Parse the function arguments.
+ if (parser->parseOptionalRParen()) {
+ do {
+ if (parseArgument())
+ return failure();
+ } while (succeeded(parser->parseOptionalComma()));
+ parser->parseRParen();
+ }
+
+ return success();
+}
+
+/// Parse a function signature, starting with a name and including the
+/// parameter list.
+static ParseResult parseFunctionSignature(
+ OpAsmParser *parser, SmallVectorImpl<OpAsmParser::OperandType> &argNames,
+ SmallVectorImpl<Type> &argTypes,
+ SmallVectorImpl<SmallVector<NamedAttribute, 2>> &argAttrs,
+ SmallVectorImpl<Type> &results) {
+ if (parseArgumentList(parser, argTypes, argNames, argAttrs))
+ return failure();
+ // Parse the return types if present.
+ return parser->parseOptionalArrowTypeList(results);
+}
+
+/// Parser implementation for function-like operations. Uses `funcTypeBuilder`
+/// to construct the custom function type given lists of input and output types.
+ParseResult
+mlir::impl::parseFunctionLikeOp(OpAsmParser *parser, OperationState *result,
+ mlir::impl::FuncTypeBuilder funcTypeBuilder) {
+ SmallVector<OpAsmParser::OperandType, 4> entryArgs;
+ SmallVector<SmallVector<NamedAttribute, 2>, 4> argAttrs;
+ SmallVector<Type, 4> argTypes;
+ SmallVector<Type, 4> results;
+ auto &builder = parser->getBuilder();
+
+ // Parse the name as a symbol reference attribute.
+ SymbolRefAttr nameAttr;
+ if (parser->parseAttribute(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
+ result->attributes))
+ return failure();
+ // Convert the parsed function attr into a string attr.
+ result->attributes.back().second = builder.getStringAttr(nameAttr.getValue());
+
+ // Parse the function signature.
+ if (parseFunctionSignature(parser, entryArgs, argTypes, argAttrs, results))
+ return failure();
+
+ if (auto type = funcTypeBuilder(builder, argTypes, results))
+ result->addAttribute(getTypeAttrName(), builder.getTypeAttr(type));
+
+ // If function attributes are present, parse them.
+ if (succeeded(parser->parseOptionalKeyword("attributes")))
+ if (parser->parseOptionalAttributeDict(result->attributes))
+ return failure();
+
+ // Add the attributes to the function arguments.
+ SmallString<8> argAttrName;
+ for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
+ if (!argAttrs[i].empty())
+ result->addAttribute(getArgAttrName(i, argAttrName),
+ builder.getDictionaryAttr(argAttrs[i]));
+
+ // Parse the optional function body.
+ auto *body = result->addRegion();
+ if (parser->parseOptionalRegion(*body, entryArgs,
+ entryArgs.empty() ? llvm::ArrayRef<Type>()
+ : argTypes))
+ return failure();
+
+ return success();
+}
+
+/// Print the signature of the function-like operation `op`. Assumes `op` has
+/// the FunctionLike trait and passed the verification.
+static void printSignature(OpAsmPrinter *p, Operation *op,
+ ArrayRef<Type> argTypes, ArrayRef<Type> results) {
+ Region &body = op->getRegion(0);
+ bool isExternal = body.empty();
+
+ *p << '(';
+ for (unsigned i = 0, e = argTypes.size(); i < e; ++i) {
+ if (i > 0)
+ *p << ", ";
+
+ if (!isExternal) {
+ p->printOperand(body.front().getArgument(i));
+ *p << ": ";
+ }
+
+ p->printType(argTypes[i]);
+ p->printOptionalAttrDict(::mlir::impl::getArgAttrs(op, i));
+ }
+
+ *p << ')';
+ p->printOptionalArrowTypeList(results);
+}
+
+/// Printer implementation for function-like operations. Accepts lists of
+/// argument and result types to use while printing.
+void mlir::impl::printFunctionLikeOp(OpAsmPrinter *p, Operation *op,
+ ArrayRef<Type> argTypes,
+ ArrayRef<Type> results) {
+ // Print the operation and the function name.
+ auto funcName =
+ op->getAttrOfType<StringAttr>(::mlir::SymbolTable::getSymbolAttrName())
+ .getValue();
+ *p << op->getName() << " @" << funcName;
+
+ // Print the signature.
+ printSignature(p, op, argTypes, results);
+
+ // Print out function attributes, if present.
+ SmallVector<StringRef, 2> ignoredAttrs = {
+ ::mlir::SymbolTable::getSymbolAttrName(), getTypeAttrName()};
+
+ // Ignore any argument attributes.
+ std::vector<SmallString<8>> argAttrStorage;
+ SmallString<8> argAttrName;
+ for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
+ if (op->getAttr(getArgAttrName(i, argAttrName)))
+ argAttrStorage.emplace_back(argAttrName);
+ ignoredAttrs.append(argAttrStorage.begin(), argAttrStorage.end());
+
+ auto attrs = op->getAttrs();
+ if (attrs.size() > ignoredAttrs.size()) {
+ *p << "\n attributes ";
+ p->printOptionalAttrDict(attrs, ignoredAttrs);
+ }
+
+ // Print the body if this is not an external function.
+ Region &body = op->getRegion(0);
+ if (!body.empty())
+ p->printRegion(body, /*printEntryBlockArgs=*/false,
+ /*printBlockTerminators=*/true);
+}