• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   auto 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   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
200     return failure();
201 
202   // Add the attributes to the function arguments.
203   assert(argAttrs.size() == argTypes.size());
204   assert(resultAttrs.size() == resultTypes.size());
205   addArgAndResultAttrs(builder, result, argAttrs, resultAttrs);
206 
207   // Parse the optional function body. The printer will not print the body if
208   // its empty, so disallow parsing of empty body in the parser.
209   auto *body = result.addRegion();
210   llvm::SMLoc loc = parser.getCurrentLocation();
211   OptionalParseResult parseResult = parser.parseOptionalRegion(
212       *body, entryArgs, entryArgs.empty() ? ArrayRef<Type>() : argTypes,
213       /*enableNameShadowing=*/false);
214   if (parseResult.hasValue()) {
215     if (failed(*parseResult))
216       return failure();
217     // Function body was parsed, make sure its not empty.
218     if (body->empty())
219       return parser.emitError(loc, "expected non-empty function body");
220   }
221   return success();
222 }
223 
224 // Print a function result list.
printFunctionResultList(OpAsmPrinter & p,ArrayRef<Type> types,ArrayRef<ArrayRef<NamedAttribute>> attrs)225 static void printFunctionResultList(OpAsmPrinter &p, ArrayRef<Type> types,
226                                     ArrayRef<ArrayRef<NamedAttribute>> attrs) {
227   assert(!types.empty() && "Should not be called for empty result list.");
228   auto &os = p.getStream();
229   bool needsParens =
230       types.size() > 1 || types[0].isa<FunctionType>() || !attrs[0].empty();
231   if (needsParens)
232     os << '(';
233   llvm::interleaveComma(
234       llvm::zip(types, attrs), os,
235       [&](const std::tuple<Type, ArrayRef<NamedAttribute>> &t) {
236         p.printType(std::get<0>(t));
237         p.printOptionalAttrDict(std::get<1>(t));
238       });
239   if (needsParens)
240     os << ')';
241 }
242 
243 /// Print the signature of the function-like operation `op`.  Assumes `op` has
244 /// the FunctionLike trait and passed the verification.
printFunctionSignature(OpAsmPrinter & p,Operation * op,ArrayRef<Type> argTypes,bool isVariadic,ArrayRef<Type> resultTypes)245 void mlir::impl::printFunctionSignature(OpAsmPrinter &p, Operation *op,
246                                         ArrayRef<Type> argTypes,
247                                         bool isVariadic,
248                                         ArrayRef<Type> resultTypes) {
249   Region &body = op->getRegion(0);
250   bool isExternal = body.empty();
251 
252   p << '(';
253   for (unsigned i = 0, e = argTypes.size(); i < e; ++i) {
254     if (i > 0)
255       p << ", ";
256 
257     if (!isExternal) {
258       p.printOperand(body.getArgument(i));
259       p << ": ";
260     }
261 
262     p.printType(argTypes[i]);
263     p.printOptionalAttrDict(::mlir::impl::getArgAttrs(op, i));
264   }
265 
266   if (isVariadic) {
267     if (!argTypes.empty())
268       p << ", ";
269     p << "...";
270   }
271 
272   p << ')';
273 
274   if (!resultTypes.empty()) {
275     p.getStream() << " -> ";
276     SmallVector<ArrayRef<NamedAttribute>, 4> resultAttrs;
277     for (int i = 0, e = resultTypes.size(); i < e; ++i)
278       resultAttrs.push_back(::mlir::impl::getResultAttrs(op, i));
279     printFunctionResultList(p, resultTypes, resultAttrs);
280   }
281 }
282 
283 /// Prints the list of function prefixed with the "attributes" keyword. The
284 /// attributes with names listed in "elided" as well as those used by the
285 /// function-like operation internally are not printed. Nothing is printed
286 /// if all attributes are elided. Assumes `op` has the `FunctionLike` trait and
287 /// passed the verification.
printFunctionAttributes(OpAsmPrinter & p,Operation * op,unsigned numInputs,unsigned numResults,ArrayRef<StringRef> elided)288 void mlir::impl::printFunctionAttributes(OpAsmPrinter &p, Operation *op,
289                                          unsigned numInputs,
290                                          unsigned numResults,
291                                          ArrayRef<StringRef> elided) {
292   // Print out function attributes, if present.
293   SmallVector<StringRef, 2> ignoredAttrs = {
294       ::mlir::SymbolTable::getSymbolAttrName(), getTypeAttrName()};
295   ignoredAttrs.append(elided.begin(), elided.end());
296 
297   SmallString<8> attrNameBuf;
298 
299   // Ignore any argument attributes.
300   std::vector<SmallString<8>> argAttrStorage;
301   for (unsigned i = 0; i != numInputs; ++i)
302     if (op->getAttr(getArgAttrName(i, attrNameBuf)))
303       argAttrStorage.emplace_back(attrNameBuf);
304   ignoredAttrs.append(argAttrStorage.begin(), argAttrStorage.end());
305 
306   // Ignore any result attributes.
307   std::vector<SmallString<8>> resultAttrStorage;
308   for (unsigned i = 0; i != numResults; ++i)
309     if (op->getAttr(getResultAttrName(i, attrNameBuf)))
310       resultAttrStorage.emplace_back(attrNameBuf);
311   ignoredAttrs.append(resultAttrStorage.begin(), resultAttrStorage.end());
312 
313   p.printOptionalAttrDictWithKeyword(op->getAttrs(), ignoredAttrs);
314 }
315 
316 /// Printer implementation for function-like operations.  Accepts lists of
317 /// argument and result types to use while printing.
printFunctionLikeOp(OpAsmPrinter & p,Operation * op,ArrayRef<Type> argTypes,bool isVariadic,ArrayRef<Type> resultTypes)318 void mlir::impl::printFunctionLikeOp(OpAsmPrinter &p, Operation *op,
319                                      ArrayRef<Type> argTypes, bool isVariadic,
320                                      ArrayRef<Type> resultTypes) {
321   // Print the operation and the function name.
322   auto funcName =
323       op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())
324           .getValue();
325   p << op->getName() << ' ';
326 
327   StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
328   if (auto visibility = op->getAttrOfType<StringAttr>(visibilityAttrName))
329     p << visibility.getValue() << ' ';
330   p.printSymbolName(funcName);
331 
332   printFunctionSignature(p, op, argTypes, isVariadic, resultTypes);
333   printFunctionAttributes(p, op, argTypes.size(), resultTypes.size(),
334                           {visibilityAttrName});
335   // Print the body if this is not an external function.
336   Region &body = op->getRegion(0);
337   if (!body.empty())
338     p.printRegion(body, /*printEntryBlockArgs=*/false,
339                   /*printBlockTerminators=*/true);
340 }
341