1 //===- FunctionImplementation.cpp - Utilities for function-like ops -------===// 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 "mlir/IR/FunctionImplementation.h" 10 #include "mlir/IR/Builders.h" 11 #include "mlir/IR/FunctionSupport.h" 12 #include "mlir/IR/SymbolTable.h" 13 14 using namespace mlir; 15 16 ParseResult mlir::impl::parseFunctionArgumentList( 17 OpAsmParser &parser, bool allowAttributes, bool allowVariadic, 18 SmallVectorImpl<OpAsmParser::OperandType> &argNames, 19 SmallVectorImpl<Type> &argTypes, SmallVectorImpl<NamedAttrList> &argAttrs, 20 bool &isVariadic) { 21 if (parser.parseLParen()) 22 return failure(); 23 24 // The argument list either has to consistently have ssa-id's followed by 25 // types, or just be a type list. It isn't ok to sometimes have SSA ID's and 26 // sometimes not. 27 auto parseArgument = [&]() -> ParseResult { 28 llvm::SMLoc loc = parser.getCurrentLocation(); 29 30 // Parse argument name if present. 31 OpAsmParser::OperandType argument; 32 Type argumentType; 33 if (succeeded(parser.parseOptionalRegionArgument(argument)) && 34 !argument.name.empty()) { 35 // Reject this if the preceding argument was missing a name. 36 if (argNames.empty() && !argTypes.empty()) 37 return parser.emitError(loc, "expected type instead of SSA identifier"); 38 argNames.push_back(argument); 39 40 if (parser.parseColonType(argumentType)) 41 return failure(); 42 } else if (allowVariadic && succeeded(parser.parseOptionalEllipsis())) { 43 isVariadic = true; 44 return success(); 45 } else if (!argNames.empty()) { 46 // Reject this if the preceding argument had a name. 47 return parser.emitError(loc, "expected SSA identifier"); 48 } else if (parser.parseType(argumentType)) { 49 return failure(); 50 } 51 52 // Add the argument type. 53 argTypes.push_back(argumentType); 54 55 // Parse any argument attributes. 56 NamedAttrList attrs; 57 if (parser.parseOptionalAttrDict(attrs)) 58 return failure(); 59 if (!allowAttributes && !attrs.empty()) 60 return parser.emitError(loc, "expected arguments without attributes"); 61 argAttrs.push_back(attrs); 62 return success(); 63 }; 64 65 // Parse the function arguments. 66 isVariadic = false; 67 if (failed(parser.parseOptionalRParen())) { 68 do { 69 unsigned numTypedArguments = argTypes.size(); 70 if (parseArgument()) 71 return failure(); 72 73 llvm::SMLoc loc = parser.getCurrentLocation(); 74 if (argTypes.size() == numTypedArguments && 75 succeeded(parser.parseOptionalComma())) 76 return parser.emitError( 77 loc, "variadic arguments must be in the end of the argument list"); 78 } while (succeeded(parser.parseOptionalComma())); 79 parser.parseRParen(); 80 } 81 82 return success(); 83 } 84 85 /// Parse a function result list. 86 /// 87 /// function-result-list ::= function-result-list-parens 88 /// | non-function-type 89 /// function-result-list-parens ::= `(` `)` 90 /// | `(` function-result-list-no-parens `)` 91 /// function-result-list-no-parens ::= function-result (`,` function-result)* 92 /// function-result ::= type attribute-dict? 93 /// 94 static ParseResult 95 parseFunctionResultList(OpAsmParser &parser, SmallVectorImpl<Type> &resultTypes, 96 SmallVectorImpl<NamedAttrList> &resultAttrs) { 97 if (failed(parser.parseOptionalLParen())) { 98 // We already know that there is no `(`, so parse a type. 99 // Because there is no `(`, it cannot be a function type. 100 Type ty; 101 if (parser.parseType(ty)) 102 return failure(); 103 resultTypes.push_back(ty); 104 resultAttrs.emplace_back(); 105 return success(); 106 } 107 108 // Special case for an empty set of parens. 109 if (succeeded(parser.parseOptionalRParen())) 110 return success(); 111 112 // Parse individual function results. 113 do { 114 resultTypes.emplace_back(); 115 resultAttrs.emplace_back(); 116 if (parser.parseType(resultTypes.back()) || 117 parser.parseOptionalAttrDict(resultAttrs.back())) { 118 return failure(); 119 } 120 } while (succeeded(parser.parseOptionalComma())); 121 return parser.parseRParen(); 122 } 123 124 /// Parses a function signature using `parser`. The `allowVariadic` argument 125 /// indicates whether functions with variadic arguments are supported. The 126 /// trailing arguments are populated by this function with names, types and 127 /// attributes of the arguments and those of the results. 128 ParseResult mlir::impl::parseFunctionSignature( 129 OpAsmParser &parser, bool allowVariadic, 130 SmallVectorImpl<OpAsmParser::OperandType> &argNames, 131 SmallVectorImpl<Type> &argTypes, SmallVectorImpl<NamedAttrList> &argAttrs, 132 bool &isVariadic, SmallVectorImpl<Type> &resultTypes, 133 SmallVectorImpl<NamedAttrList> &resultAttrs) { 134 bool allowArgAttrs = true; 135 if (parseFunctionArgumentList(parser, allowArgAttrs, allowVariadic, argNames, 136 argTypes, argAttrs, isVariadic)) 137 return failure(); 138 if (succeeded(parser.parseOptionalArrow())) 139 return parseFunctionResultList(parser, resultTypes, resultAttrs); 140 return success(); 141 } 142 143 void mlir::impl::addArgAndResultAttrs(Builder &builder, OperationState &result, 144 ArrayRef<NamedAttrList> argAttrs, 145 ArrayRef<NamedAttrList> resultAttrs) { 146 // Add the attributes to the function arguments. 147 SmallString<8> attrNameBuf; 148 for (unsigned i = 0, e = argAttrs.size(); i != e; ++i) 149 if (!argAttrs[i].empty()) 150 result.addAttribute(getArgAttrName(i, attrNameBuf), 151 builder.getDictionaryAttr(argAttrs[i])); 152 153 // Add the attributes to the function results. 154 for (unsigned i = 0, e = resultAttrs.size(); i != e; ++i) 155 if (!resultAttrs[i].empty()) 156 result.addAttribute(getResultAttrName(i, attrNameBuf), 157 builder.getDictionaryAttr(resultAttrs[i])); 158 } 159 160 /// Parser implementation for function-like operations. Uses `funcTypeBuilder` 161 /// to construct the custom function type given lists of input and output types. 162 ParseResult 163 mlir::impl::parseFunctionLikeOp(OpAsmParser &parser, OperationState &result, 164 bool allowVariadic, 165 mlir::impl::FuncTypeBuilder funcTypeBuilder) { 166 SmallVector<OpAsmParser::OperandType, 4> entryArgs; 167 SmallVector<NamedAttrList, 4> argAttrs; 168 SmallVector<NamedAttrList, 4> resultAttrs; 169 SmallVector<Type, 4> argTypes; 170 SmallVector<Type, 4> resultTypes; 171 auto &builder = parser.getBuilder(); 172 173 // Parse the name as a symbol. 174 StringAttr nameAttr; 175 if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(), 176 result.attributes)) 177 return failure(); 178 179 // Parse the function signature. 180 auto signatureLocation = parser.getCurrentLocation(); 181 bool isVariadic = false; 182 if (parseFunctionSignature(parser, allowVariadic, entryArgs, argTypes, 183 argAttrs, isVariadic, resultTypes, resultAttrs)) 184 return failure(); 185 186 std::string errorMessage; 187 if (auto type = funcTypeBuilder(builder, argTypes, resultTypes, 188 impl::VariadicFlag(isVariadic), errorMessage)) 189 result.addAttribute(getTypeAttrName(), TypeAttr::get(type)); 190 else 191 return parser.emitError(signatureLocation) 192 << "failed to construct function type" 193 << (errorMessage.empty() ? "" : ": ") << errorMessage; 194 195 // If function attributes are present, parse them. 196 if (parser.parseOptionalAttrDictWithKeyword(result.attributes)) 197 return failure(); 198 199 // Add the attributes to the function arguments. 200 assert(argAttrs.size() == argTypes.size()); 201 assert(resultAttrs.size() == resultTypes.size()); 202 addArgAndResultAttrs(builder, result, argAttrs, resultAttrs); 203 204 // Parse the optional function body. 205 auto *body = result.addRegion(); 206 return parser.parseOptionalRegion( 207 *body, entryArgs, entryArgs.empty() ? ArrayRef<Type>() : argTypes); 208 } 209 210 // Print a function result list. 211 static void printFunctionResultList(OpAsmPrinter &p, ArrayRef<Type> types, 212 ArrayRef<ArrayRef<NamedAttribute>> attrs) { 213 assert(!types.empty() && "Should not be called for empty result list."); 214 auto &os = p.getStream(); 215 bool needsParens = 216 types.size() > 1 || types[0].isa<FunctionType>() || !attrs[0].empty(); 217 if (needsParens) 218 os << '('; 219 llvm::interleaveComma( 220 llvm::zip(types, attrs), os, 221 [&](const std::tuple<Type, ArrayRef<NamedAttribute>> &t) { 222 p.printType(std::get<0>(t)); 223 p.printOptionalAttrDict(std::get<1>(t)); 224 }); 225 if (needsParens) 226 os << ')'; 227 } 228 229 /// Print the signature of the function-like operation `op`. Assumes `op` has 230 /// the FunctionLike trait and passed the verification. 231 void mlir::impl::printFunctionSignature(OpAsmPrinter &p, Operation *op, 232 ArrayRef<Type> argTypes, 233 bool isVariadic, 234 ArrayRef<Type> resultTypes) { 235 Region &body = op->getRegion(0); 236 bool isExternal = body.empty(); 237 238 p << '('; 239 for (unsigned i = 0, e = argTypes.size(); i < e; ++i) { 240 if (i > 0) 241 p << ", "; 242 243 if (!isExternal) { 244 p.printOperand(body.getArgument(i)); 245 p << ": "; 246 } 247 248 p.printType(argTypes[i]); 249 p.printOptionalAttrDict(::mlir::impl::getArgAttrs(op, i)); 250 } 251 252 if (isVariadic) { 253 if (!argTypes.empty()) 254 p << ", "; 255 p << "..."; 256 } 257 258 p << ')'; 259 260 if (!resultTypes.empty()) { 261 p.getStream() << " -> "; 262 SmallVector<ArrayRef<NamedAttribute>, 4> resultAttrs; 263 for (int i = 0, e = resultTypes.size(); i < e; ++i) 264 resultAttrs.push_back(::mlir::impl::getResultAttrs(op, i)); 265 printFunctionResultList(p, resultTypes, resultAttrs); 266 } 267 } 268 269 /// Prints the list of function prefixed with the "attributes" keyword. The 270 /// attributes with names listed in "elided" as well as those used by the 271 /// function-like operation internally are not printed. Nothing is printed 272 /// if all attributes are elided. Assumes `op` has the `FunctionLike` trait and 273 /// passed the verification. 274 void mlir::impl::printFunctionAttributes(OpAsmPrinter &p, Operation *op, 275 unsigned numInputs, 276 unsigned numResults, 277 ArrayRef<StringRef> elided) { 278 // Print out function attributes, if present. 279 SmallVector<StringRef, 2> ignoredAttrs = { 280 ::mlir::SymbolTable::getSymbolAttrName(), getTypeAttrName()}; 281 ignoredAttrs.append(elided.begin(), elided.end()); 282 283 SmallString<8> attrNameBuf; 284 285 // Ignore any argument attributes. 286 std::vector<SmallString<8>> argAttrStorage; 287 for (unsigned i = 0; i != numInputs; ++i) 288 if (op->getAttr(getArgAttrName(i, attrNameBuf))) 289 argAttrStorage.emplace_back(attrNameBuf); 290 ignoredAttrs.append(argAttrStorage.begin(), argAttrStorage.end()); 291 292 // Ignore any result attributes. 293 std::vector<SmallString<8>> resultAttrStorage; 294 for (unsigned i = 0; i != numResults; ++i) 295 if (op->getAttr(getResultAttrName(i, attrNameBuf))) 296 resultAttrStorage.emplace_back(attrNameBuf); 297 ignoredAttrs.append(resultAttrStorage.begin(), resultAttrStorage.end()); 298 299 p.printOptionalAttrDictWithKeyword(op->getAttrs(), ignoredAttrs); 300 } 301 302 /// Printer implementation for function-like operations. Accepts lists of 303 /// argument and result types to use while printing. 304 void mlir::impl::printFunctionLikeOp(OpAsmPrinter &p, Operation *op, 305 ArrayRef<Type> argTypes, bool isVariadic, 306 ArrayRef<Type> resultTypes) { 307 // Print the operation and the function name. 308 auto funcName = 309 op->getAttrOfType<StringAttr>(::mlir::SymbolTable::getSymbolAttrName()) 310 .getValue(); 311 p << op->getName() << ' '; 312 p.printSymbolName(funcName); 313 314 printFunctionSignature(p, op, argTypes, isVariadic, resultTypes); 315 printFunctionAttributes(p, op, argTypes.size(), resultTypes.size()); 316 317 // Print the body if this is not an external function. 318 Region &body = op->getRegion(0); 319 if (!body.empty()) 320 p.printRegion(body, /*printEntryBlockArgs=*/false, 321 /*printBlockTerminators=*/true); 322 } 323