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 
parseFunctionArgumentList(OpAsmParser & parser,bool allowAttributes,bool allowVariadic,SmallVectorImpl<OpAsmParser::OperandType> & argNames,SmallVectorImpl<Type> & argTypes,SmallVectorImpl<NamedAttrList> & argAttrs,bool & isVariadic)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
parseFunctionResultList(OpAsmParser & parser,SmallVectorImpl<Type> & resultTypes,SmallVectorImpl<NamedAttrList> & resultAttrs)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.
parseFunctionSignature(OpAsmParser & parser,bool allowVariadic,SmallVectorImpl<OpAsmParser::OperandType> & argNames,SmallVectorImpl<Type> & argTypes,SmallVectorImpl<NamedAttrList> & argAttrs,bool & isVariadic,SmallVectorImpl<Type> & resultTypes,SmallVectorImpl<NamedAttrList> & resultAttrs)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 
addArgAndResultAttrs(Builder & builder,OperationState & result,ArrayRef<NamedAttrList> argAttrs,ArrayRef<NamedAttrList> resultAttrs)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
parseFunctionLikeOp(OpAsmParser & parser,OperationState & result,bool allowVariadic,mlir::impl::FuncTypeBuilder funcTypeBuilder)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 visibility.
174   impl::parseOptionalVisibilityKeyword(parser, result.attributes);
175 
176   // Parse the name as a symbol.
177   StringAttr nameAttr;
178   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
179                              result.attributes))
180     return failure();
181 
182   // Parse the function signature.
183   llvm::SMLoc signatureLocation = parser.getCurrentLocation();
184   bool isVariadic = false;
185   if (parseFunctionSignature(parser, allowVariadic, entryArgs, argTypes,
186                              argAttrs, isVariadic, resultTypes, resultAttrs))
187     return failure();
188 
189   std::string errorMessage;
190   if (auto type = funcTypeBuilder(builder, argTypes, resultTypes,
191                                   impl::VariadicFlag(isVariadic), errorMessage))
192     result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
193   else
194     return parser.emitError(signatureLocation)
195            << "failed to construct function type"
196            << (errorMessage.empty() ? "" : ": ") << errorMessage;
197 
198   // If function attributes are present, parse them.
199   NamedAttrList parsedAttributes;
200   llvm::SMLoc attributeDictLocation = parser.getCurrentLocation();
201   if (parser.parseOptionalAttrDictWithKeyword(parsedAttributes))
202     return failure();
203 
204   // Disallow attributes that are inferred from elsewhere in the attribute
205   // dictionary.
206   for (StringRef disallowed :
207        {SymbolTable::getVisibilityAttrName(), SymbolTable::getSymbolAttrName(),
208         getTypeAttrName()}) {
209     if (parsedAttributes.get(disallowed))
210       return parser.emitError(attributeDictLocation, "'")
211              << disallowed
212              << "' is an inferred attribute and should not be specified in the "
213                 "explicit attribute dictionary";
214   }
215   result.attributes.append(parsedAttributes);
216 
217   // Add the attributes to the function arguments.
218   assert(argAttrs.size() == argTypes.size());
219   assert(resultAttrs.size() == resultTypes.size());
220   addArgAndResultAttrs(builder, result, argAttrs, resultAttrs);
221 
222   // Parse the optional function body. The printer will not print the body if
223   // its empty, so disallow parsing of empty body in the parser.
224   auto *body = result.addRegion();
225   llvm::SMLoc loc = parser.getCurrentLocation();
226   OptionalParseResult parseResult = parser.parseOptionalRegion(
227       *body, entryArgs, entryArgs.empty() ? ArrayRef<Type>() : argTypes,
228       /*enableNameShadowing=*/false);
229   if (parseResult.hasValue()) {
230     if (failed(*parseResult))
231       return failure();
232     // Function body was parsed, make sure its not empty.
233     if (body->empty())
234       return parser.emitError(loc, "expected non-empty function body");
235   }
236   return success();
237 }
238 
239 // Print a function result list.
printFunctionResultList(OpAsmPrinter & p,ArrayRef<Type> types,ArrayRef<ArrayRef<NamedAttribute>> attrs)240 static void printFunctionResultList(OpAsmPrinter &p, ArrayRef<Type> types,
241                                     ArrayRef<ArrayRef<NamedAttribute>> attrs) {
242   assert(!types.empty() && "Should not be called for empty result list.");
243   auto &os = p.getStream();
244   bool needsParens =
245       types.size() > 1 || types[0].isa<FunctionType>() || !attrs[0].empty();
246   if (needsParens)
247     os << '(';
248   llvm::interleaveComma(
249       llvm::zip(types, attrs), os,
250       [&](const std::tuple<Type, ArrayRef<NamedAttribute>> &t) {
251         p.printType(std::get<0>(t));
252         p.printOptionalAttrDict(std::get<1>(t));
253       });
254   if (needsParens)
255     os << ')';
256 }
257 
258 /// Print the signature of the function-like operation `op`.  Assumes `op` has
259 /// the FunctionLike trait and passed the verification.
printFunctionSignature(OpAsmPrinter & p,Operation * op,ArrayRef<Type> argTypes,bool isVariadic,ArrayRef<Type> resultTypes)260 void mlir::impl::printFunctionSignature(OpAsmPrinter &p, Operation *op,
261                                         ArrayRef<Type> argTypes,
262                                         bool isVariadic,
263                                         ArrayRef<Type> resultTypes) {
264   Region &body = op->getRegion(0);
265   bool isExternal = body.empty();
266 
267   p << '(';
268   for (unsigned i = 0, e = argTypes.size(); i < e; ++i) {
269     if (i > 0)
270       p << ", ";
271 
272     if (!isExternal) {
273       p.printOperand(body.getArgument(i));
274       p << ": ";
275     }
276 
277     p.printType(argTypes[i]);
278     p.printOptionalAttrDict(::mlir::impl::getArgAttrs(op, i));
279   }
280 
281   if (isVariadic) {
282     if (!argTypes.empty())
283       p << ", ";
284     p << "...";
285   }
286 
287   p << ')';
288 
289   if (!resultTypes.empty()) {
290     p.getStream() << " -> ";
291     SmallVector<ArrayRef<NamedAttribute>, 4> resultAttrs;
292     for (int i = 0, e = resultTypes.size(); i < e; ++i)
293       resultAttrs.push_back(::mlir::impl::getResultAttrs(op, i));
294     printFunctionResultList(p, resultTypes, resultAttrs);
295   }
296 }
297 
298 /// Prints the list of function prefixed with the "attributes" keyword. The
299 /// attributes with names listed in "elided" as well as those used by the
300 /// function-like operation internally are not printed. Nothing is printed
301 /// if all attributes are elided. Assumes `op` has the `FunctionLike` trait and
302 /// passed the verification.
printFunctionAttributes(OpAsmPrinter & p,Operation * op,unsigned numInputs,unsigned numResults,ArrayRef<StringRef> elided)303 void mlir::impl::printFunctionAttributes(OpAsmPrinter &p, Operation *op,
304                                          unsigned numInputs,
305                                          unsigned numResults,
306                                          ArrayRef<StringRef> elided) {
307   // Print out function attributes, if present.
308   SmallVector<StringRef, 2> ignoredAttrs = {
309       ::mlir::SymbolTable::getSymbolAttrName(), getTypeAttrName()};
310   ignoredAttrs.append(elided.begin(), elided.end());
311 
312   SmallString<8> attrNameBuf;
313 
314   // Ignore any argument attributes.
315   std::vector<SmallString<8>> argAttrStorage;
316   for (unsigned i = 0; i != numInputs; ++i)
317     if (op->getAttr(getArgAttrName(i, attrNameBuf)))
318       argAttrStorage.emplace_back(attrNameBuf);
319   ignoredAttrs.append(argAttrStorage.begin(), argAttrStorage.end());
320 
321   // Ignore any result attributes.
322   std::vector<SmallString<8>> resultAttrStorage;
323   for (unsigned i = 0; i != numResults; ++i)
324     if (op->getAttr(getResultAttrName(i, attrNameBuf)))
325       resultAttrStorage.emplace_back(attrNameBuf);
326   ignoredAttrs.append(resultAttrStorage.begin(), resultAttrStorage.end());
327 
328   p.printOptionalAttrDictWithKeyword(op->getAttrs(), ignoredAttrs);
329 }
330 
331 /// Printer implementation for function-like operations.  Accepts lists of
332 /// argument and result types to use while printing.
printFunctionLikeOp(OpAsmPrinter & p,Operation * op,ArrayRef<Type> argTypes,bool isVariadic,ArrayRef<Type> resultTypes)333 void mlir::impl::printFunctionLikeOp(OpAsmPrinter &p, Operation *op,
334                                      ArrayRef<Type> argTypes, bool isVariadic,
335                                      ArrayRef<Type> resultTypes) {
336   // Print the operation and the function name.
337   auto funcName =
338       op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())
339           .getValue();
340   p << op->getName() << ' ';
341 
342   StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
343   if (auto visibility = op->getAttrOfType<StringAttr>(visibilityAttrName))
344     p << visibility.getValue() << ' ';
345   p.printSymbolName(funcName);
346 
347   printFunctionSignature(p, op, argTypes, isVariadic, resultTypes);
348   printFunctionAttributes(p, op, argTypes.size(), resultTypes.size(),
349                           {visibilityAttrName});
350   // Print the body if this is not an external function.
351   Region &body = op->getRegion(0);
352   if (!body.empty())
353     p.printRegion(body, /*printEntryBlockArgs=*/false,
354                   /*printBlockTerminators=*/true);
355 }
356