blob: fe17b6c101980a6cc1702b2f5d9d11fd0b85682a [file] [log] [blame]
Chris Lattnere79379a2018-06-22 10:39:19 -07001//===- Parser.cpp - MLIR Parser Implementation ----------------------------===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17//
18// This file implements the parser for the MLIR textual form.
19//
20//===----------------------------------------------------------------------===//
21
22#include "mlir/Parser.h"
23#include "Lexer.h"
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070024#include "mlir/IR/AffineExpr.h"
MLIR Teamf85a6262018-06-27 11:03:08 -070025#include "mlir/IR/AffineMap.h"
Chris Lattner7121b802018-07-04 20:45:39 -070026#include "mlir/IR/Attributes.h"
Chris Lattner158e0a3e2018-07-08 20:51:38 -070027#include "mlir/IR/Builders.h"
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -070028#include "mlir/IR/MLFunction.h"
Chris Lattner21e67f62018-07-06 10:46:19 -070029#include "mlir/IR/Module.h"
30#include "mlir/IR/OperationSet.h"
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -070031#include "mlir/IR/Statements.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070032#include "mlir/IR/Types.h"
Chris Lattner6119d382018-07-20 18:41:34 -070033#include "llvm/ADT/DenseMap.h"
Chris Lattnere79379a2018-06-22 10:39:19 -070034#include "llvm/Support/SourceMgr.h"
35using namespace mlir;
Chris Lattner4c95a502018-06-23 16:03:42 -070036using llvm::SMLoc;
James Molloy0ff71542018-07-23 16:56:32 -070037using llvm::SourceMgr;
Chris Lattnere79379a2018-06-22 10:39:19 -070038
Chris Lattnerf7e22732018-06-22 22:03:48 -070039/// Simple enum to make code read better in cases that would otherwise return a
40/// bool value. Failure is "true" in a boolean context.
James Molloy0ff71542018-07-23 16:56:32 -070041enum ParseResult { ParseSuccess, ParseFailure };
Chris Lattnere79379a2018-06-22 10:39:19 -070042
Chris Lattner48af7d12018-07-09 19:05:38 -070043namespace {
44class Parser;
45
46/// This class refers to all of the state maintained globally by the parser,
47/// such as the current lexer position etc. The Parser base class provides
48/// methods to access this.
49class ParserState {
Chris Lattnered65a732018-06-28 20:45:33 -070050public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070051 ParserState(llvm::SourceMgr &sourceMgr, Module *module,
Chris Lattner48af7d12018-07-09 19:05:38 -070052 SMDiagnosticHandlerTy errorReporter)
Chris Lattner2e595eb2018-07-10 10:08:27 -070053 : context(module->getContext()), module(module),
54 lex(sourceMgr, errorReporter), curToken(lex.lexToken()),
Jacques Pienaard4c784e2018-07-11 00:07:36 -070055 errorReporter(errorReporter) {}
Chris Lattner2e595eb2018-07-10 10:08:27 -070056
57 // A map from affine map identifier to AffineMap.
58 llvm::StringMap<AffineMap *> affineMapDefinitions;
Chris Lattnere79379a2018-06-22 10:39:19 -070059
Chris Lattnere79379a2018-06-22 10:39:19 -070060private:
Chris Lattner48af7d12018-07-09 19:05:38 -070061 ParserState(const ParserState &) = delete;
62 void operator=(const ParserState &) = delete;
63
64 friend class Parser;
65
66 // The context we're parsing into.
Chris Lattner2e595eb2018-07-10 10:08:27 -070067 MLIRContext *const context;
68
69 // This is the module we are parsing into.
70 Module *const module;
Chris Lattnerf7e22732018-06-22 22:03:48 -070071
72 // The lexer for the source file we're parsing.
Chris Lattnere79379a2018-06-22 10:39:19 -070073 Lexer lex;
74
75 // This is the next token that hasn't been consumed yet.
76 Token curToken;
77
Jacques Pienaar9c411be2018-06-24 19:17:35 -070078 // The diagnostic error reporter.
Chris Lattner2e595eb2018-07-10 10:08:27 -070079 SMDiagnosticHandlerTy const errorReporter;
Chris Lattner48af7d12018-07-09 19:05:38 -070080};
81} // end anonymous namespace
MLIR Teamf85a6262018-06-27 11:03:08 -070082
Chris Lattner48af7d12018-07-09 19:05:38 -070083namespace {
84
Chris Lattner7f9cc272018-07-19 08:35:28 -070085typedef std::function<Operation *(Identifier, ArrayRef<SSAValue *>,
86 ArrayRef<Type *>, ArrayRef<NamedAttribute>)>
Tatiana Shpeisman565b9642018-07-16 11:47:09 -070087 CreateOperationFunction;
88
Chris Lattner48af7d12018-07-09 19:05:38 -070089/// This class implement support for parsing global entities like types and
90/// shared entities like SSA names. It is intended to be subclassed by
91/// specialized subparsers that include state, e.g. when a local symbol table.
92class Parser {
93public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070094 Builder builder;
Chris Lattner48af7d12018-07-09 19:05:38 -070095
Chris Lattner2e595eb2018-07-10 10:08:27 -070096 Parser(ParserState &state) : builder(state.context), state(state) {}
97
98 // Helper methods to get stuff from the parser-global state.
99 ParserState &getState() const { return state; }
Chris Lattner48af7d12018-07-09 19:05:38 -0700100 MLIRContext *getContext() const { return state.context; }
Chris Lattner2e595eb2018-07-10 10:08:27 -0700101 Module *getModule() { return state.module; }
Chris Lattner48af7d12018-07-09 19:05:38 -0700102
103 /// Return the current token the parser is inspecting.
104 const Token &getToken() const { return state.curToken; }
105 StringRef getTokenSpelling() const { return state.curToken.getSpelling(); }
Chris Lattnere79379a2018-06-22 10:39:19 -0700106
107 /// Emit an error and return failure.
Chris Lattner4c95a502018-06-23 16:03:42 -0700108 ParseResult emitError(const Twine &message) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700109 return emitError(state.curToken.getLoc(), message);
Chris Lattner4c95a502018-06-23 16:03:42 -0700110 }
111 ParseResult emitError(SMLoc loc, const Twine &message);
Chris Lattnere79379a2018-06-22 10:39:19 -0700112
113 /// Advance the current lexer onto the next token.
114 void consumeToken() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700115 assert(state.curToken.isNot(Token::eof, Token::error) &&
Chris Lattnere79379a2018-06-22 10:39:19 -0700116 "shouldn't advance past EOF or errors");
Chris Lattner48af7d12018-07-09 19:05:38 -0700117 state.curToken = state.lex.lexToken();
Chris Lattnere79379a2018-06-22 10:39:19 -0700118 }
119
120 /// Advance the current lexer onto the next token, asserting what the expected
121 /// current token is. This is preferred to the above method because it leads
122 /// to more self-documenting code with better checking.
Chris Lattner8da0c282018-06-29 11:15:56 -0700123 void consumeToken(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700124 assert(state.curToken.is(kind) && "consumed an unexpected token");
Chris Lattnere79379a2018-06-22 10:39:19 -0700125 consumeToken();
126 }
127
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700128 /// If the current token has the specified kind, consume it and return true.
129 /// If not, return false.
Chris Lattner8da0c282018-06-29 11:15:56 -0700130 bool consumeIf(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700131 if (state.curToken.isNot(kind))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700132 return false;
133 consumeToken(kind);
134 return true;
135 }
136
Chris Lattner40746442018-07-21 14:32:09 -0700137 /// Parse a comma-separated list of elements up until the specified end token.
138 ParseResult
139 parseCommaSeparatedListUntil(Token::Kind rightToken,
140 const std::function<ParseResult()> &parseElement,
141 bool allowEmptyList = true);
142
143 /// Parse a comma separated list of elements that must have at least one entry
144 /// in it.
145 ParseResult
146 parseCommaSeparatedList(const std::function<ParseResult()> &parseElement);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700147
Chris Lattnerf7e22732018-06-22 22:03:48 -0700148 // We have two forms of parsing methods - those that return a non-null
149 // pointer on success, and those that return a ParseResult to indicate whether
150 // they returned a failure. The second class fills in by-reference arguments
151 // as the results of their action.
152
Chris Lattnere79379a2018-06-22 10:39:19 -0700153 // Type parsing.
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700154 Type *parsePrimitiveType();
Chris Lattnerf7e22732018-06-22 22:03:48 -0700155 Type *parseElementType();
156 VectorType *parseVectorType();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700157 ParseResult parseDimensionListRanked(SmallVectorImpl<int> &dimensions);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700158 Type *parseTensorType();
159 Type *parseMemRefType();
160 Type *parseFunctionType();
161 Type *parseType();
Chris Lattner1604e472018-07-23 08:42:19 -0700162 ParseResult parseTypeListNoParens(SmallVectorImpl<Type *> &elements);
James Molloy0ff71542018-07-23 16:56:32 -0700163 ParseResult parseTypeList(SmallVectorImpl<Type *> &elements);
Chris Lattnere79379a2018-06-22 10:39:19 -0700164
Chris Lattner7121b802018-07-04 20:45:39 -0700165 // Attribute parsing.
166 Attribute *parseAttribute();
167 ParseResult parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes);
168
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700169 // Polyhedral structures.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700170 AffineMap *parseAffineMapInline();
MLIR Team718c82f2018-07-16 09:45:22 -0700171 AffineMap *parseAffineMapReference();
MLIR Teamf85a6262018-06-27 11:03:08 -0700172
Chris Lattner48af7d12018-07-09 19:05:38 -0700173private:
174 // The Parser is subclassed and reinstantiated. Do not add additional
175 // non-trivial state here, add it to the ParserState class.
176 ParserState &state;
Chris Lattnere79379a2018-06-22 10:39:19 -0700177};
178} // end anonymous namespace
179
180//===----------------------------------------------------------------------===//
181// Helper methods.
182//===----------------------------------------------------------------------===//
183
Chris Lattner4c95a502018-06-23 16:03:42 -0700184ParseResult Parser::emitError(SMLoc loc, const Twine &message) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700185 // If we hit a parse error in response to a lexer error, then the lexer
Jacques Pienaar9c411be2018-06-24 19:17:35 -0700186 // already reported the error.
Chris Lattner48af7d12018-07-09 19:05:38 -0700187 if (getToken().is(Token::error))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700188 return ParseFailure;
189
Chris Lattner48af7d12018-07-09 19:05:38 -0700190 auto &sourceMgr = state.lex.getSourceMgr();
191 state.errorReporter(sourceMgr.GetMessage(loc, SourceMgr::DK_Error, message));
Chris Lattnere79379a2018-06-22 10:39:19 -0700192 return ParseFailure;
193}
194
Chris Lattner40746442018-07-21 14:32:09 -0700195/// Parse a comma separated list of elements that must have at least one entry
196/// in it.
197ParseResult Parser::parseCommaSeparatedList(
198 const std::function<ParseResult()> &parseElement) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700199 // Non-empty case starts with an element.
200 if (parseElement())
201 return ParseFailure;
202
203 // Otherwise we have a list of comma separated elements.
204 while (consumeIf(Token::comma)) {
205 if (parseElement())
206 return ParseFailure;
207 }
Chris Lattner40746442018-07-21 14:32:09 -0700208 return ParseSuccess;
209}
210
211/// Parse a comma-separated list of elements, terminated with an arbitrary
212/// token. This allows empty lists if allowEmptyList is true.
213///
214/// abstract-list ::= rightToken // if allowEmptyList == true
215/// abstract-list ::= element (',' element)* rightToken
216///
217ParseResult Parser::parseCommaSeparatedListUntil(
218 Token::Kind rightToken, const std::function<ParseResult()> &parseElement,
219 bool allowEmptyList) {
220 // Handle the empty case.
221 if (getToken().is(rightToken)) {
222 if (!allowEmptyList)
223 return emitError("expected list element");
224 consumeToken(rightToken);
225 return ParseSuccess;
226 }
227
228 if (parseCommaSeparatedList(parseElement))
229 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700230
231 // Consume the end character.
232 if (!consumeIf(rightToken))
Chris Lattner8da0c282018-06-29 11:15:56 -0700233 return emitError("expected ',' or '" + Token::getTokenSpelling(rightToken) +
234 "'");
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700235
236 return ParseSuccess;
237}
Chris Lattnere79379a2018-06-22 10:39:19 -0700238
239//===----------------------------------------------------------------------===//
240// Type Parsing
241//===----------------------------------------------------------------------===//
242
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700243/// Parse the low-level fixed dtypes in the system.
244///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700245/// primitive-type ::= `f16` | `bf16` | `f32` | `f64`
246/// primitive-type ::= integer-type
247/// primitive-type ::= `affineint`
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700248///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700249Type *Parser::parsePrimitiveType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700250 switch (getToken().getKind()) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700251 default:
252 return (emitError("expected type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700253 case Token::kw_bf16:
254 consumeToken(Token::kw_bf16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700255 return builder.getBF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700256 case Token::kw_f16:
257 consumeToken(Token::kw_f16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700258 return builder.getF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700259 case Token::kw_f32:
260 consumeToken(Token::kw_f32);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700261 return builder.getF32Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700262 case Token::kw_f64:
263 consumeToken(Token::kw_f64);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700264 return builder.getF64Type();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700265 case Token::kw_affineint:
266 consumeToken(Token::kw_affineint);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700267 return builder.getAffineIntType();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700268 case Token::inttype: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700269 auto width = getToken().getIntTypeBitwidth();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700270 if (!width.hasValue())
271 return (emitError("invalid integer width"), nullptr);
272 consumeToken(Token::inttype);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700273 return builder.getIntegerType(width.getValue());
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700274 }
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700275 }
276}
277
278/// Parse the element type of a tensor or memref type.
279///
280/// element-type ::= primitive-type | vector-type
281///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700282Type *Parser::parseElementType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700283 if (getToken().is(Token::kw_vector))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700284 return parseVectorType();
285
286 return parsePrimitiveType();
287}
288
289/// Parse a vector type.
290///
291/// vector-type ::= `vector` `<` const-dimension-list primitive-type `>`
292/// const-dimension-list ::= (integer-literal `x`)+
293///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700294VectorType *Parser::parseVectorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700295 consumeToken(Token::kw_vector);
296
297 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700298 return (emitError("expected '<' in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700299
Chris Lattner48af7d12018-07-09 19:05:38 -0700300 if (getToken().isNot(Token::integer))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700301 return (emitError("expected dimension size in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700302
303 SmallVector<unsigned, 4> dimensions;
Chris Lattner48af7d12018-07-09 19:05:38 -0700304 while (getToken().is(Token::integer)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700305 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700306 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700307 if (!dimension.hasValue())
Chris Lattnerf7e22732018-06-22 22:03:48 -0700308 return (emitError("invalid dimension in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700309 dimensions.push_back(dimension.getValue());
310
311 consumeToken(Token::integer);
312
313 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700314 if (getToken().isNot(Token::bare_identifier) ||
315 getTokenSpelling()[0] != 'x')
Chris Lattnerf7e22732018-06-22 22:03:48 -0700316 return (emitError("expected 'x' in vector dimension list"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700317
318 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700319 if (getTokenSpelling().size() != 1)
320 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700321
322 // Consume the 'x'.
323 consumeToken(Token::bare_identifier);
324 }
325
326 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700327 auto *elementType = parsePrimitiveType();
328 if (!elementType)
329 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700330
331 if (!consumeIf(Token::greater))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700332 return (emitError("expected '>' in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700333
Chris Lattnerf7e22732018-06-22 22:03:48 -0700334 return VectorType::get(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700335}
336
337/// Parse a dimension list of a tensor or memref type. This populates the
338/// dimension list, returning -1 for the '?' dimensions.
339///
340/// dimension-list-ranked ::= (dimension `x`)*
341/// dimension ::= `?` | integer-literal
342///
343ParseResult Parser::parseDimensionListRanked(SmallVectorImpl<int> &dimensions) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700344 while (getToken().isAny(Token::integer, Token::question)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700345 if (consumeIf(Token::question)) {
346 dimensions.push_back(-1);
347 } else {
348 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700349 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700350 if (!dimension.hasValue() || (int)dimension.getValue() < 0)
351 return emitError("invalid dimension");
352 dimensions.push_back((int)dimension.getValue());
353 consumeToken(Token::integer);
354 }
355
356 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700357 if (getToken().isNot(Token::bare_identifier) ||
358 getTokenSpelling()[0] != 'x')
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700359 return emitError("expected 'x' in dimension list");
360
361 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700362 if (getTokenSpelling().size() != 1)
363 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700364
365 // Consume the 'x'.
366 consumeToken(Token::bare_identifier);
367 }
368
369 return ParseSuccess;
370}
371
372/// Parse a tensor type.
373///
374/// tensor-type ::= `tensor` `<` dimension-list element-type `>`
375/// dimension-list ::= dimension-list-ranked | `??`
376///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700377Type *Parser::parseTensorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700378 consumeToken(Token::kw_tensor);
379
380 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700381 return (emitError("expected '<' in tensor type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700382
383 bool isUnranked;
384 SmallVector<int, 4> dimensions;
385
386 if (consumeIf(Token::questionquestion)) {
387 isUnranked = true;
388 } else {
389 isUnranked = false;
390 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700391 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700392 }
393
394 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700395 auto elementType = parseElementType();
396 if (!elementType)
397 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700398
399 if (!consumeIf(Token::greater))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700400 return (emitError("expected '>' in tensor type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700401
MLIR Team355ec862018-06-23 18:09:09 -0700402 if (isUnranked)
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700403 return builder.getTensorType(elementType);
404 return builder.getTensorType(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700405}
406
407/// Parse a memref type.
408///
409/// memref-type ::= `memref` `<` dimension-list-ranked element-type
410/// (`,` semi-affine-map-composition)? (`,` memory-space)? `>`
411///
412/// semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map
413/// memory-space ::= integer-literal /* | TODO: address-space-id */
414///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700415Type *Parser::parseMemRefType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700416 consumeToken(Token::kw_memref);
417
418 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700419 return (emitError("expected '<' in memref type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700420
421 SmallVector<int, 4> dimensions;
422 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700423 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700424
425 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700426 auto elementType = parseElementType();
427 if (!elementType)
428 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700429
MLIR Team718c82f2018-07-16 09:45:22 -0700430 if (!consumeIf(Token::comma))
431 return (emitError("expected ',' in memref type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700432
MLIR Team718c82f2018-07-16 09:45:22 -0700433 // Parse semi-affine-map-composition.
James Molloy0ff71542018-07-23 16:56:32 -0700434 SmallVector<AffineMap *, 2> affineMapComposition;
MLIR Team718c82f2018-07-16 09:45:22 -0700435 unsigned memorySpace;
436 bool parsedMemorySpace = false;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700437
MLIR Team718c82f2018-07-16 09:45:22 -0700438 auto parseElt = [&]() -> ParseResult {
439 if (getToken().is(Token::integer)) {
440 // Parse memory space.
441 if (parsedMemorySpace)
442 return emitError("multiple memory spaces specified in memref type");
443 auto v = getToken().getUnsignedIntegerValue();
444 if (!v.hasValue())
445 return emitError("invalid memory space in memref type");
446 memorySpace = v.getValue();
447 consumeToken(Token::integer);
448 parsedMemorySpace = true;
449 } else {
450 // Parse affine map.
451 if (parsedMemorySpace)
452 return emitError("affine map after memory space in memref type");
James Molloy0ff71542018-07-23 16:56:32 -0700453 auto *affineMap = parseAffineMapReference();
MLIR Team718c82f2018-07-16 09:45:22 -0700454 if (affineMap == nullptr)
455 return ParseFailure;
456 affineMapComposition.push_back(affineMap);
457 }
458 return ParseSuccess;
459 };
460
461 // Parse comma separated list of affine maps, followed by memory space.
Chris Lattner40746442018-07-21 14:32:09 -0700462 if (parseCommaSeparatedListUntil(Token::greater, parseElt,
463 /*allowEmptyList=*/false)) {
MLIR Team718c82f2018-07-16 09:45:22 -0700464 return nullptr;
465 }
466 // Check that MemRef type specifies at least one affine map in composition.
467 if (affineMapComposition.empty())
468 return (emitError("expected semi-affine-map in memref type"), nullptr);
469 if (!parsedMemorySpace)
470 return (emitError("expected memory space in memref type"), nullptr);
471
472 return MemRefType::get(dimensions, elementType, affineMapComposition,
473 memorySpace);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700474}
475
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700476/// Parse a function type.
477///
478/// function-type ::= type-list-parens `->` type-list
479///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700480Type *Parser::parseFunctionType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700481 assert(getToken().is(Token::l_paren));
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700482
James Molloy0ff71542018-07-23 16:56:32 -0700483 SmallVector<Type *, 4> arguments;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700484 if (parseTypeList(arguments))
485 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700486
487 if (!consumeIf(Token::arrow))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700488 return (emitError("expected '->' in function type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700489
James Molloy0ff71542018-07-23 16:56:32 -0700490 SmallVector<Type *, 4> results;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700491 if (parseTypeList(results))
492 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700493
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700494 return builder.getFunctionType(arguments, results);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700495}
496
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700497/// Parse an arbitrary type.
498///
499/// type ::= primitive-type
500/// | vector-type
501/// | tensor-type
502/// | memref-type
503/// | function-type
504/// element-type ::= primitive-type | vector-type
505///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700506Type *Parser::parseType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700507 switch (getToken().getKind()) {
James Molloy0ff71542018-07-23 16:56:32 -0700508 case Token::kw_memref:
509 return parseMemRefType();
510 case Token::kw_tensor:
511 return parseTensorType();
512 case Token::kw_vector:
513 return parseVectorType();
514 case Token::l_paren:
515 return parseFunctionType();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700516 default:
517 return parsePrimitiveType();
518 }
519}
520
Chris Lattner1604e472018-07-23 08:42:19 -0700521/// Parse a list of types without an enclosing parenthesis. The list must have
522/// at least one member.
523///
524/// type-list-no-parens ::= type (`,` type)*
525///
526ParseResult Parser::parseTypeListNoParens(SmallVectorImpl<Type *> &elements) {
527 auto parseElt = [&]() -> ParseResult {
528 auto elt = parseType();
529 elements.push_back(elt);
530 return elt ? ParseSuccess : ParseFailure;
531 };
532
533 return parseCommaSeparatedList(parseElt);
534}
535
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700536/// Parse a "type list", which is a singular type, or a parenthesized list of
537/// types.
538///
539/// type-list ::= type-list-parens | type
540/// type-list-parens ::= `(` `)`
Chris Lattner1604e472018-07-23 08:42:19 -0700541/// | `(` type-list-no-parens `)`
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700542///
James Molloy0ff71542018-07-23 16:56:32 -0700543ParseResult Parser::parseTypeList(SmallVectorImpl<Type *> &elements) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700544 auto parseElt = [&]() -> ParseResult {
545 auto elt = parseType();
546 elements.push_back(elt);
547 return elt ? ParseSuccess : ParseFailure;
548 };
549
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700550 // If there is no parens, then it must be a singular type.
551 if (!consumeIf(Token::l_paren))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700552 return parseElt();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700553
Chris Lattner40746442018-07-21 14:32:09 -0700554 if (parseCommaSeparatedListUntil(Token::r_paren, parseElt))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700555 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700556
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700557 return ParseSuccess;
558}
559
Chris Lattner4c95a502018-06-23 16:03:42 -0700560//===----------------------------------------------------------------------===//
Chris Lattner7121b802018-07-04 20:45:39 -0700561// Attribute parsing.
562//===----------------------------------------------------------------------===//
563
Chris Lattner7121b802018-07-04 20:45:39 -0700564/// Attribute parsing.
565///
566/// attribute-value ::= bool-literal
567/// | integer-literal
568/// | float-literal
569/// | string-literal
570/// | `[` (attribute-value (`,` attribute-value)*)? `]`
571///
572Attribute *Parser::parseAttribute() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700573 switch (getToken().getKind()) {
Chris Lattner7121b802018-07-04 20:45:39 -0700574 case Token::kw_true:
575 consumeToken(Token::kw_true);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700576 return builder.getBoolAttr(true);
Chris Lattner7121b802018-07-04 20:45:39 -0700577 case Token::kw_false:
578 consumeToken(Token::kw_false);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700579 return builder.getBoolAttr(false);
Chris Lattner7121b802018-07-04 20:45:39 -0700580
581 case Token::integer: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700582 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700583 if (!val.hasValue() || (int64_t)val.getValue() < 0)
584 return (emitError("integer too large for attribute"), nullptr);
585 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700586 return builder.getIntegerAttr((int64_t)val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700587 }
588
589 case Token::minus: {
590 consumeToken(Token::minus);
Chris Lattner48af7d12018-07-09 19:05:38 -0700591 if (getToken().is(Token::integer)) {
592 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700593 if (!val.hasValue() || (int64_t)-val.getValue() >= 0)
594 return (emitError("integer too large for attribute"), nullptr);
595 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700596 return builder.getIntegerAttr((int64_t)-val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700597 }
598
599 return (emitError("expected constant integer or floating point value"),
600 nullptr);
601 }
602
603 case Token::string: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700604 auto val = getToken().getStringValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700605 consumeToken(Token::string);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700606 return builder.getStringAttr(val);
Chris Lattner7121b802018-07-04 20:45:39 -0700607 }
608
609 case Token::l_bracket: {
610 consumeToken(Token::l_bracket);
James Molloy0ff71542018-07-23 16:56:32 -0700611 SmallVector<Attribute *, 4> elements;
Chris Lattner7121b802018-07-04 20:45:39 -0700612
613 auto parseElt = [&]() -> ParseResult {
614 elements.push_back(parseAttribute());
615 return elements.back() ? ParseSuccess : ParseFailure;
616 };
617
Chris Lattner40746442018-07-21 14:32:09 -0700618 if (parseCommaSeparatedListUntil(Token::r_bracket, parseElt))
Chris Lattner7121b802018-07-04 20:45:39 -0700619 return nullptr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700620 return builder.getArrayAttr(elements);
Chris Lattner7121b802018-07-04 20:45:39 -0700621 }
622 default:
MLIR Teamb61885d2018-07-18 16:29:21 -0700623 // Try to parse affine map reference.
James Molloy0ff71542018-07-23 16:56:32 -0700624 auto *affineMap = parseAffineMapReference();
MLIR Teamb61885d2018-07-18 16:29:21 -0700625 if (affineMap != nullptr)
626 return builder.getAffineMapAttr(affineMap);
627
Chris Lattner7121b802018-07-04 20:45:39 -0700628 // TODO: Handle floating point.
629 return (emitError("expected constant attribute value"), nullptr);
630 }
631}
632
Chris Lattner7121b802018-07-04 20:45:39 -0700633/// Attribute dictionary.
634///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700635/// attribute-dict ::= `{` `}`
636/// | `{` attribute-entry (`,` attribute-entry)* `}`
637/// attribute-entry ::= bare-id `:` attribute-value
Chris Lattner7121b802018-07-04 20:45:39 -0700638///
James Molloy0ff71542018-07-23 16:56:32 -0700639ParseResult
640Parser::parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes) {
Chris Lattner7121b802018-07-04 20:45:39 -0700641 consumeToken(Token::l_brace);
642
643 auto parseElt = [&]() -> ParseResult {
644 // We allow keywords as attribute names.
Chris Lattner48af7d12018-07-09 19:05:38 -0700645 if (getToken().isNot(Token::bare_identifier, Token::inttype) &&
646 !getToken().isKeyword())
Chris Lattner7121b802018-07-04 20:45:39 -0700647 return emitError("expected attribute name");
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700648 auto nameId = builder.getIdentifier(getTokenSpelling());
Chris Lattner7121b802018-07-04 20:45:39 -0700649 consumeToken();
650
651 if (!consumeIf(Token::colon))
652 return emitError("expected ':' in attribute list");
653
654 auto attr = parseAttribute();
James Molloy0ff71542018-07-23 16:56:32 -0700655 if (!attr)
656 return ParseFailure;
Chris Lattner7121b802018-07-04 20:45:39 -0700657
658 attributes.push_back({nameId, attr});
659 return ParseSuccess;
660 };
661
Chris Lattner40746442018-07-21 14:32:09 -0700662 if (parseCommaSeparatedListUntil(Token::r_brace, parseElt))
Chris Lattner7121b802018-07-04 20:45:39 -0700663 return ParseFailure;
664
665 return ParseSuccess;
666}
667
668//===----------------------------------------------------------------------===//
MLIR Teamf85a6262018-06-27 11:03:08 -0700669// Polyhedral structures.
670//===----------------------------------------------------------------------===//
671
Chris Lattner2e595eb2018-07-10 10:08:27 -0700672/// Lower precedence ops (all at the same precedence level). LNoOp is false in
673/// the boolean sense.
674enum AffineLowPrecOp {
675 /// Null value.
676 LNoOp,
677 Add,
678 Sub
679};
MLIR Teamf85a6262018-06-27 11:03:08 -0700680
Chris Lattner2e595eb2018-07-10 10:08:27 -0700681/// Higher precedence ops - all at the same precedence level. HNoOp is false in
682/// the boolean sense.
683enum AffineHighPrecOp {
684 /// Null value.
685 HNoOp,
686 Mul,
687 FloorDiv,
688 CeilDiv,
689 Mod
690};
Chris Lattner7121b802018-07-04 20:45:39 -0700691
Chris Lattner2e595eb2018-07-10 10:08:27 -0700692namespace {
693/// This is a specialized parser for AffineMap's, maintaining the state
694/// transient to their bodies.
695class AffineMapParser : public Parser {
696public:
697 explicit AffineMapParser(ParserState &state) : Parser(state) {}
Chris Lattner7121b802018-07-04 20:45:39 -0700698
Chris Lattner2e595eb2018-07-10 10:08:27 -0700699 AffineMap *parseAffineMapInline();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700700
Chris Lattner2e595eb2018-07-10 10:08:27 -0700701private:
702 unsigned getNumDims() const { return dims.size(); }
703 unsigned getNumSymbols() const { return symbols.size(); }
MLIR Teamf85a6262018-06-27 11:03:08 -0700704
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700705 /// Returns true if the only identifiers the parser accepts in affine
706 /// expressions are symbolic identifiers.
707 bool isPureSymbolic() const { return pureSymbolic; }
708 void setSymbolicParsing(bool val) { pureSymbolic = val; }
709
Chris Lattner2e595eb2018-07-10 10:08:27 -0700710 // Binary affine op parsing.
711 AffineLowPrecOp consumeIfLowPrecOp();
712 AffineHighPrecOp consumeIfHighPrecOp();
MLIR Teamf85a6262018-06-27 11:03:08 -0700713
Chris Lattner2e595eb2018-07-10 10:08:27 -0700714 // Identifier lists for polyhedral structures.
715 ParseResult parseDimIdList();
716 ParseResult parseSymbolIdList();
717 ParseResult parseDimOrSymbolId(bool isDim);
718
719 AffineExpr *parseAffineExpr();
720 AffineExpr *parseParentheticalExpr();
721 AffineExpr *parseNegateExpression(AffineExpr *lhs);
722 AffineExpr *parseIntegerExpr();
723 AffineExpr *parseBareIdExpr();
724
725 AffineExpr *getBinaryAffineOpExpr(AffineHighPrecOp op, AffineExpr *lhs,
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700726 AffineExpr *rhs, SMLoc opLoc);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700727 AffineExpr *getBinaryAffineOpExpr(AffineLowPrecOp op, AffineExpr *lhs,
728 AffineExpr *rhs);
729 AffineExpr *parseAffineOperandExpr(AffineExpr *lhs);
730 AffineExpr *parseAffineLowPrecOpExpr(AffineExpr *llhs,
731 AffineLowPrecOp llhsOp);
732 AffineExpr *parseAffineHighPrecOpExpr(AffineExpr *llhs,
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700733 AffineHighPrecOp llhsOp,
734 SMLoc llhsOpLoc);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700735
736private:
737 // TODO(bondhugula): could just use an vector/ArrayRef and scan the numbers.
738 llvm::StringMap<unsigned> dims;
739 llvm::StringMap<unsigned> symbols;
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700740 /// True if the parser should allow only symbolic identifiers in affine
741 /// expressions.
742 bool pureSymbolic = false;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700743};
744} // end anonymous namespace
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700745
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700746/// Create an affine binary high precedence op expression (mul's, div's, mod).
747/// opLoc is the location of the op token to be used to report errors
748/// for non-conforming expressions.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700749AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineHighPrecOp op,
750 AffineExpr *lhs,
Chris Lattner40746442018-07-21 14:32:09 -0700751 AffineExpr *rhs,
752 SMLoc opLoc) {
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700753 // TODO: make the error location info accurate.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700754 switch (op) {
755 case Mul:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700756 if (!lhs->isSymbolicOrConstant() && !rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700757 emitError(opLoc, "non-affine expression: at least one of the multiply "
758 "operands has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700759 return nullptr;
760 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700761 return builder.getMulExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700762 case FloorDiv:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700763 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700764 emitError(opLoc, "non-affine expression: right operand of floordiv "
765 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700766 return nullptr;
767 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700768 return builder.getFloorDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700769 case CeilDiv:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700770 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700771 emitError(opLoc, "non-affine expression: right operand of ceildiv "
772 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700773 return nullptr;
774 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700775 return builder.getCeilDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700776 case Mod:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700777 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700778 emitError(opLoc, "non-affine expression: right operand of mod "
779 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700780 return nullptr;
781 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700782 return builder.getModExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700783 case HNoOp:
784 llvm_unreachable("can't create affine expression for null high prec op");
785 return nullptr;
786 }
787}
788
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700789/// Create an affine binary low precedence op expression (add, sub).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700790AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineLowPrecOp op,
791 AffineExpr *lhs,
792 AffineExpr *rhs) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700793 switch (op) {
794 case AffineLowPrecOp::Add:
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700795 return builder.getAddExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700796 case AffineLowPrecOp::Sub:
Uday Bondhugulac1faf662018-07-19 14:08:50 -0700797 return builder.getAddExpr(
798 lhs, builder.getMulExpr(rhs, builder.getConstantExpr(-1)));
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700799 case AffineLowPrecOp::LNoOp:
800 llvm_unreachable("can't create affine expression for null low prec op");
801 return nullptr;
802 }
803}
804
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700805/// Consume this token if it is a lower precedence affine op (there are only two
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700806/// precedence levels).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700807AffineLowPrecOp AffineMapParser::consumeIfLowPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700808 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700809 case Token::plus:
810 consumeToken(Token::plus);
811 return AffineLowPrecOp::Add;
812 case Token::minus:
813 consumeToken(Token::minus);
814 return AffineLowPrecOp::Sub;
815 default:
816 return AffineLowPrecOp::LNoOp;
817 }
818}
819
820/// Consume this token if it is a higher precedence affine op (there are only
821/// two precedence levels)
Chris Lattner2e595eb2018-07-10 10:08:27 -0700822AffineHighPrecOp AffineMapParser::consumeIfHighPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700823 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700824 case Token::star:
825 consumeToken(Token::star);
826 return Mul;
827 case Token::kw_floordiv:
828 consumeToken(Token::kw_floordiv);
829 return FloorDiv;
830 case Token::kw_ceildiv:
831 consumeToken(Token::kw_ceildiv);
832 return CeilDiv;
833 case Token::kw_mod:
834 consumeToken(Token::kw_mod);
835 return Mod;
836 default:
837 return HNoOp;
838 }
839}
840
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700841/// Parse a high precedence op expression list: mul, div, and mod are high
842/// precedence binary ops, i.e., parse a
843/// expr_1 op_1 expr_2 op_2 ... expr_n
844/// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
845/// All affine binary ops are left associative.
846/// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
847/// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700848/// null. llhsOpLoc is the location of the llhsOp token that will be used to
849/// report an error for non-conforming expressions.
850AffineExpr *AffineMapParser::parseAffineHighPrecOpExpr(AffineExpr *llhs,
851 AffineHighPrecOp llhsOp,
852 SMLoc llhsOpLoc) {
Chris Lattner2e595eb2018-07-10 10:08:27 -0700853 AffineExpr *lhs = parseAffineOperandExpr(llhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700854 if (!lhs)
855 return nullptr;
856
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700857 // Found an LHS. Parse the remaining expression.
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700858 auto opLoc = getToken().getLoc();
Chris Lattner2e595eb2018-07-10 10:08:27 -0700859 if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700860 if (llhs) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700861 AffineExpr *expr = getBinaryAffineOpExpr(llhsOp, llhs, lhs, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700862 if (!expr)
863 return nullptr;
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700864 return parseAffineHighPrecOpExpr(expr, op, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700865 }
866 // No LLHS, get RHS
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700867 return parseAffineHighPrecOpExpr(lhs, op, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700868 }
869
870 // This is the last operand in this expression.
871 if (llhs)
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700872 return getBinaryAffineOpExpr(llhsOp, llhs, lhs, llhsOpLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700873
874 // No llhs, 'lhs' itself is the expression.
875 return lhs;
876}
877
878/// Parse an affine expression inside parentheses.
879///
880/// affine-expr ::= `(` affine-expr `)`
Chris Lattner2e595eb2018-07-10 10:08:27 -0700881AffineExpr *AffineMapParser::parseParentheticalExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700882 if (!consumeIf(Token::l_paren))
883 return (emitError("expected '('"), nullptr);
Chris Lattner48af7d12018-07-09 19:05:38 -0700884 if (getToken().is(Token::r_paren))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700885 return (emitError("no expression inside parentheses"), nullptr);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700886 auto *expr = parseAffineExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700887 if (!expr)
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700888 return nullptr;
889 if (!consumeIf(Token::r_paren))
890 return (emitError("expected ')'"), nullptr);
891 return expr;
892}
893
894/// Parse the negation expression.
895///
896/// affine-expr ::= `-` affine-expr
Chris Lattner2e595eb2018-07-10 10:08:27 -0700897AffineExpr *AffineMapParser::parseNegateExpression(AffineExpr *lhs) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700898 if (!consumeIf(Token::minus))
899 return (emitError("expected '-'"), nullptr);
900
Chris Lattner2e595eb2018-07-10 10:08:27 -0700901 AffineExpr *operand = parseAffineOperandExpr(lhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700902 // Since negation has the highest precedence of all ops (including high
903 // precedence ops) but lower than parentheses, we are only going to use
904 // parseAffineOperandExpr instead of parseAffineExpr here.
905 if (!operand)
906 // Extra error message although parseAffineOperandExpr would have
907 // complained. Leads to a better diagnostic.
908 return (emitError("missing operand of negation"), nullptr);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700909 auto *minusOne = builder.getConstantExpr(-1);
910 return builder.getMulExpr(minusOne, operand);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700911}
912
913/// Parse a bare id that may appear in an affine expression.
914///
915/// affine-expr ::= bare-id
Chris Lattner2e595eb2018-07-10 10:08:27 -0700916AffineExpr *AffineMapParser::parseBareIdExpr() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700917 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700918 return (emitError("expected bare identifier"), nullptr);
919
Chris Lattner48af7d12018-07-09 19:05:38 -0700920 StringRef sRef = getTokenSpelling();
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700921 // dims, symbols are all pairwise distinct.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700922 if (dims.count(sRef)) {
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700923 if (isPureSymbolic())
924 return (emitError("identifier used is not a symbolic identifier"),
925 nullptr);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700926 consumeToken(Token::bare_identifier);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700927 return builder.getDimExpr(dims.lookup(sRef));
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700928 }
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700929
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700930 if (symbols.count(sRef)) {
931 consumeToken(Token::bare_identifier);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700932 return builder.getSymbolExpr(symbols.lookup(sRef));
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700933 }
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700934
935 return (emitError("use of undeclared identifier"), nullptr);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700936}
937
938/// Parse a positive integral constant appearing in an affine expression.
939///
940/// affine-expr ::= integer-literal
Chris Lattner2e595eb2018-07-10 10:08:27 -0700941AffineExpr *AffineMapParser::parseIntegerExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700942 // No need to handle negative numbers separately here. They are naturally
943 // handled via the unary negation operator, although (FIXME) MININT_64 still
944 // not correctly handled.
Chris Lattner48af7d12018-07-09 19:05:38 -0700945 if (getToken().isNot(Token::integer))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700946 return (emitError("expected integer"), nullptr);
947
Chris Lattner48af7d12018-07-09 19:05:38 -0700948 auto val = getToken().getUInt64IntegerValue();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700949 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
950 return (emitError("constant too large for affineint"), nullptr);
951 }
952 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700953 return builder.getConstantExpr((int64_t)val.getValue());
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700954}
955
956/// Parses an expression that can be a valid operand of an affine expression.
Uday Bondhugula76345202018-07-09 13:47:52 -0700957/// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
958/// operator, the rhs of which is being parsed. This is used to determine
959/// whether an error should be emitted for a missing right operand.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700960// Eg: for an expression without parentheses (like i + j + k + l), each
961// of the four identifiers is an operand. For i + j*k + l, j*k is not an
962// operand expression, it's an op expression and will be parsed via
963// parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and -l
964// are valid operands that will be parsed by this function.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700965AffineExpr *AffineMapParser::parseAffineOperandExpr(AffineExpr *lhs) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700966 switch (getToken().getKind()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700967 case Token::bare_identifier:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700968 return parseBareIdExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700969 case Token::integer:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700970 return parseIntegerExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700971 case Token::l_paren:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700972 return parseParentheticalExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700973 case Token::minus:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700974 return parseNegateExpression(lhs);
Uday Bondhugula76345202018-07-09 13:47:52 -0700975 case Token::kw_ceildiv:
976 case Token::kw_floordiv:
977 case Token::kw_mod:
978 case Token::plus:
979 case Token::star:
980 if (lhs)
981 emitError("missing right operand of binary operator");
982 else
983 emitError("missing left operand of binary operator");
984 return nullptr;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700985 default:
986 if (lhs)
Uday Bondhugula76345202018-07-09 13:47:52 -0700987 emitError("missing right operand of binary operator");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700988 else
989 emitError("expected affine expression");
990 return nullptr;
991 }
992}
993
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700994/// Parse affine expressions that are bare-id's, integer constants,
995/// parenthetical affine expressions, and affine op expressions that are a
996/// composition of those.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700997///
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700998/// All binary op's associate from left to right.
999///
1000/// {add, sub} have lower precedence than {mul, div, and mod}.
1001///
Uday Bondhugula76345202018-07-09 13:47:52 -07001002/// Add, sub'are themselves at the same precedence level. Mul, floordiv,
1003/// ceildiv, and mod are at the same higher precedence level. Negation has
1004/// higher precedence than any binary op.
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001005///
1006/// llhs: the affine expression appearing on the left of the one being parsed.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001007/// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
1008/// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned if
1009/// llhs is non-null; otherwise lhs is returned. This is to deal with left
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001010/// associativity.
1011///
1012/// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001013/// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where (e2*e3)
1014/// will be parsed using parseAffineHighPrecOpExpr().
Chris Lattner2e595eb2018-07-10 10:08:27 -07001015AffineExpr *AffineMapParser::parseAffineLowPrecOpExpr(AffineExpr *llhs,
1016 AffineLowPrecOp llhsOp) {
Uday Bondhugula76345202018-07-09 13:47:52 -07001017 AffineExpr *lhs;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001018 if (!(lhs = parseAffineOperandExpr(llhs)))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001019 return nullptr;
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001020
1021 // Found an LHS. Deal with the ops.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001022 if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001023 if (llhs) {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001024 AffineExpr *sum = getBinaryAffineOpExpr(llhsOp, llhs, lhs);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001025 return parseAffineLowPrecOpExpr(sum, lOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001026 }
1027 // No LLHS, get RHS and form the expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001028 return parseAffineLowPrecOpExpr(lhs, lOp);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001029 }
Uday Bondhugula851b8fd2018-07-20 14:57:21 -07001030 auto opLoc = getToken().getLoc();
Chris Lattner2e595eb2018-07-10 10:08:27 -07001031 if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001032 // We have a higher precedence op here. Get the rhs operand for the llhs
1033 // through parseAffineHighPrecOpExpr.
Uday Bondhugula851b8fd2018-07-20 14:57:21 -07001034 AffineExpr *highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001035 if (!highRes)
1036 return nullptr;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001037
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001038 // If llhs is null, the product forms the first operand of the yet to be
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001039 // found expression. If non-null, the op to associate with llhs is llhsOp.
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001040 AffineExpr *expr =
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001041 llhs ? getBinaryAffineOpExpr(llhsOp, llhs, highRes) : highRes;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001042
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001043 // Recurse for subsequent low prec op's after the affine high prec op
1044 // expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001045 if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
1046 return parseAffineLowPrecOpExpr(expr, nextOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001047 return expr;
1048 }
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001049 // Last operand in the expression list.
1050 if (llhs)
1051 return getBinaryAffineOpExpr(llhsOp, llhs, lhs);
1052 // No llhs, 'lhs' itself is the expression.
1053 return lhs;
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001054}
1055
1056/// Parse an affine expression.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001057/// affine-expr ::= `(` affine-expr `)`
1058/// | `-` affine-expr
1059/// | affine-expr `+` affine-expr
1060/// | affine-expr `-` affine-expr
1061/// | affine-expr `*` affine-expr
1062/// | affine-expr `floordiv` affine-expr
1063/// | affine-expr `ceildiv` affine-expr
1064/// | affine-expr `mod` affine-expr
1065/// | bare-id
1066/// | integer-literal
1067///
1068/// Additional conditions are checked depending on the production. For eg., one
1069/// of the operands for `*` has to be either constant/symbolic; the second
1070/// operand for floordiv, ceildiv, and mod has to be a positive integer.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001071AffineExpr *AffineMapParser::parseAffineExpr() {
1072 return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001073}
1074
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001075/// Parse a dim or symbol from the lists appearing before the actual expressions
Chris Lattner2e595eb2018-07-10 10:08:27 -07001076/// of the affine map. Update our state to store the dimensional/symbolic
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001077/// identifier. 'dim': whether it's the dim list or symbol list that is being
1078/// parsed.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001079ParseResult AffineMapParser::parseDimOrSymbolId(bool isDim) {
Chris Lattner48af7d12018-07-09 19:05:38 -07001080 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001081 return emitError("expected bare identifier");
Chris Lattner48af7d12018-07-09 19:05:38 -07001082 auto sRef = getTokenSpelling();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001083 consumeToken(Token::bare_identifier);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001084 if (dims.count(sRef))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001085 return emitError("dimensional identifier name reused");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001086 if (symbols.count(sRef))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001087 return emitError("symbolic identifier name reused");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001088 if (isDim)
1089 dims.insert({sRef, dims.size()});
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001090 else
Chris Lattner2e595eb2018-07-10 10:08:27 -07001091 symbols.insert({sRef, symbols.size()});
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001092 return ParseSuccess;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001093}
1094
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001095/// Parse the list of symbolic identifiers to an affine map.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001096ParseResult AffineMapParser::parseSymbolIdList() {
1097 if (!consumeIf(Token::l_bracket))
1098 return emitError("expected '['");
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001099
Chris Lattner2e595eb2018-07-10 10:08:27 -07001100 auto parseElt = [&]() -> ParseResult { return parseDimOrSymbolId(false); };
Chris Lattner40746442018-07-21 14:32:09 -07001101 return parseCommaSeparatedListUntil(Token::r_bracket, parseElt);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001102}
1103
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001104/// Parse the list of dimensional identifiers to an affine map.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001105ParseResult AffineMapParser::parseDimIdList() {
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001106 if (!consumeIf(Token::l_paren))
1107 return emitError("expected '(' at start of dimensional identifiers list");
1108
Chris Lattner2e595eb2018-07-10 10:08:27 -07001109 auto parseElt = [&]() -> ParseResult { return parseDimOrSymbolId(true); };
Chris Lattner40746442018-07-21 14:32:09 -07001110 return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001111}
1112
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001113/// Parse an affine map definition.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001114///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001115/// affine-map-inline ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
1116/// (`size` `(` dim-size (`,` dim-size)* `)`)?
1117/// dim-size ::= affine-expr | `min` `(` affine-expr ( `,` affine-expr)+ `)`
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001118///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001119/// multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
Chris Lattner2e595eb2018-07-10 10:08:27 -07001120AffineMap *AffineMapParser::parseAffineMapInline() {
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001121 // List of dimensional identifiers.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001122 if (parseDimIdList())
Chris Lattner7121b802018-07-04 20:45:39 -07001123 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001124
1125 // Symbols are optional.
Chris Lattner48af7d12018-07-09 19:05:38 -07001126 if (getToken().is(Token::l_bracket)) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001127 if (parseSymbolIdList())
Chris Lattner7121b802018-07-04 20:45:39 -07001128 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001129 }
1130 if (!consumeIf(Token::arrow)) {
Chris Lattner7121b802018-07-04 20:45:39 -07001131 return (emitError("expected '->' or '['"), nullptr);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001132 }
1133 if (!consumeIf(Token::l_paren)) {
1134 emitError("expected '(' at start of affine map range");
Chris Lattner7121b802018-07-04 20:45:39 -07001135 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001136 }
1137
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001138 SmallVector<AffineExpr *, 4> exprs;
1139 auto parseElt = [&]() -> ParseResult {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001140 auto *elt = parseAffineExpr();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001141 ParseResult res = elt ? ParseSuccess : ParseFailure;
1142 exprs.push_back(elt);
1143 return res;
1144 };
1145
1146 // Parse a multi-dimensional affine expression (a comma-separated list of 1-d
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001147 // affine expressions); the list cannot be empty.
1148 // Grammar: multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
Chris Lattner40746442018-07-21 14:32:09 -07001149 if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, false))
Chris Lattner7121b802018-07-04 20:45:39 -07001150 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001151
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001152 // Parse optional range sizes.
Uday Bondhugula1e500b42018-07-12 18:04:04 -07001153 // range-sizes ::= (`size` `(` dim-size (`,` dim-size)* `)`)?
1154 // dim-size ::= affine-expr | `min` `(` affine-expr (`,` affine-expr)+ `)`
1155 // TODO(bondhugula): support for min of several affine expressions.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001156 // TODO: check if sizes are non-negative whenever they are constant.
1157 SmallVector<AffineExpr *, 4> rangeSizes;
1158 if (consumeIf(Token::kw_size)) {
1159 // Location of the l_paren token (if it exists) for error reporting later.
1160 auto loc = getToken().getLoc();
1161 if (!consumeIf(Token::l_paren))
1162 return (emitError("expected '(' at start of affine map range"), nullptr);
1163
1164 auto parseRangeSize = [&]() -> ParseResult {
1165 auto *elt = parseAffineExpr();
1166 ParseResult res = elt ? ParseSuccess : ParseFailure;
1167 rangeSizes.push_back(elt);
1168 return res;
1169 };
1170
1171 setSymbolicParsing(true);
Chris Lattner40746442018-07-21 14:32:09 -07001172 if (parseCommaSeparatedListUntil(Token::r_paren, parseRangeSize, false))
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001173 return nullptr;
1174 if (exprs.size() > rangeSizes.size())
1175 return (emitError(loc, "fewer range sizes than range expressions"),
1176 nullptr);
1177 if (exprs.size() < rangeSizes.size())
1178 return (emitError(loc, "more range sizes than range expressions"),
1179 nullptr);
1180 }
1181
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001182 // Parsed a valid affine map.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001183 return builder.getAffineMap(dims.size(), symbols.size(), exprs, rangeSizes);
MLIR Teamf85a6262018-06-27 11:03:08 -07001184}
1185
Chris Lattner2e595eb2018-07-10 10:08:27 -07001186AffineMap *Parser::parseAffineMapInline() {
1187 return AffineMapParser(state).parseAffineMapInline();
1188}
1189
MLIR Team718c82f2018-07-16 09:45:22 -07001190AffineMap *Parser::parseAffineMapReference() {
1191 if (getToken().is(Token::hash_identifier)) {
1192 // Parse affine map identifier and verify that it exists.
1193 StringRef affineMapId = getTokenSpelling().drop_front();
1194 if (getState().affineMapDefinitions.count(affineMapId) == 0)
1195 return (emitError("undefined affine map id '" + affineMapId + "'"),
1196 nullptr);
1197 consumeToken(Token::hash_identifier);
1198 return getState().affineMapDefinitions[affineMapId];
1199 }
1200 // Try to parse inline affine map.
1201 return parseAffineMapInline();
1202}
1203
MLIR Teamf85a6262018-06-27 11:03:08 -07001204//===----------------------------------------------------------------------===//
Chris Lattner7f9cc272018-07-19 08:35:28 -07001205// FunctionParser
Chris Lattner4c95a502018-06-23 16:03:42 -07001206//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001207
Chris Lattner7f9cc272018-07-19 08:35:28 -07001208namespace {
1209/// This class contains parser state that is common across CFG and ML functions,
1210/// notably for dealing with operations and SSA values.
1211class FunctionParser : public Parser {
1212public:
1213 FunctionParser(ParserState &state) : Parser(state) {}
1214
Chris Lattner6119d382018-07-20 18:41:34 -07001215 /// After the function is finished parsing, this function checks to see if
1216 /// there are any remaining issues.
Chris Lattner40746442018-07-21 14:32:09 -07001217 ParseResult finalizeFunction(Function *func, SMLoc loc);
Chris Lattner6119d382018-07-20 18:41:34 -07001218
1219 /// This represents a use of an SSA value in the program. The first two
1220 /// entries in the tuple are the name and result number of a reference. The
1221 /// third is the location of the reference, which is used in case this ends up
1222 /// being a use of an undefined value.
1223 struct SSAUseInfo {
1224 StringRef name; // Value name, e.g. %42 or %abc
1225 unsigned number; // Number, specified with #12
1226 SMLoc loc; // Location of first definition or use.
1227 };
Chris Lattner7f9cc272018-07-19 08:35:28 -07001228
1229 /// Given a reference to an SSA value and its type, return a reference. This
1230 /// returns null on failure.
1231 SSAValue *resolveSSAUse(SSAUseInfo useInfo, Type *type);
1232
1233 /// Register a definition of a value with the symbol table.
1234 ParseResult addDefinition(SSAUseInfo useInfo, SSAValue *value);
1235
1236 // SSA parsing productions.
1237 ParseResult parseSSAUse(SSAUseInfo &result);
Chris Lattner40746442018-07-21 14:32:09 -07001238 ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
James Molloy61a656c2018-07-22 15:45:24 -07001239
1240 template <typename ResultType>
1241 ResultType parseSSADefOrUseAndType(
1242 const std::function<ResultType(SSAUseInfo, Type *)> &action);
1243
1244 SSAValue *parseSSAUseAndType() {
1245 return parseSSADefOrUseAndType<SSAValue *>(
1246 [&](SSAUseInfo useInfo, Type *type) -> SSAValue * {
1247 return resolveSSAUse(useInfo, type);
1248 });
1249 }
Chris Lattner40746442018-07-21 14:32:09 -07001250
1251 template <typename ValueTy>
Chris Lattner7f9cc272018-07-19 08:35:28 -07001252 ParseResult
Chris Lattner2c402672018-07-23 11:56:17 -07001253 parseOptionalSSAUseAndTypeList(SmallVectorImpl<ValueTy *> &results,
1254 bool isParenthesized);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001255
1256 // Operations
1257 ParseResult parseOperation(const CreateOperationFunction &createOpFunc);
1258
1259private:
1260 /// This keeps track of all of the SSA values we are tracking, indexed by
Chris Lattner6119d382018-07-20 18:41:34 -07001261 /// their name. This has one entry per result number.
1262 llvm::StringMap<SmallVector<std::pair<SSAValue *, SMLoc>, 1>> values;
1263
1264 /// These are all of the placeholders we've made along with the location of
1265 /// their first reference, to allow checking for use of undefined values.
1266 DenseMap<SSAValue *, SMLoc> forwardReferencePlaceholders;
1267
1268 SSAValue *createForwardReferencePlaceholder(SMLoc loc, Type *type);
1269
1270 /// Return true if this is a forward reference.
1271 bool isForwardReferencePlaceholder(SSAValue *value) {
1272 return forwardReferencePlaceholders.count(value);
1273 }
Chris Lattner7f9cc272018-07-19 08:35:28 -07001274};
1275} // end anonymous namespace
1276
Chris Lattner6119d382018-07-20 18:41:34 -07001277/// Create and remember a new placeholder for a forward reference.
1278SSAValue *FunctionParser::createForwardReferencePlaceholder(SMLoc loc,
1279 Type *type) {
1280 // Forward references are always created as instructions, even in ML
1281 // functions, because we just need something with a def/use chain.
1282 //
1283 // We create these placeholders as having an empty name, which we know cannot
1284 // be created through normal user input, allowing us to distinguish them.
1285 auto name = Identifier::get("placeholder", getContext());
1286 auto *inst = OperationInst::create(name, /*operands*/ {}, type, /*attrs*/ {},
1287 getContext());
1288 forwardReferencePlaceholders[inst->getResult(0)] = loc;
1289 return inst->getResult(0);
1290}
1291
Chris Lattner7f9cc272018-07-19 08:35:28 -07001292/// Given an unbound reference to an SSA value and its type, return a the value
1293/// it specifies. This returns null on failure.
1294SSAValue *FunctionParser::resolveSSAUse(SSAUseInfo useInfo, Type *type) {
Chris Lattner6119d382018-07-20 18:41:34 -07001295 auto &entries = values[useInfo.name];
1296
Chris Lattner7f9cc272018-07-19 08:35:28 -07001297 // If we have already seen a value of this name, return it.
Chris Lattner6119d382018-07-20 18:41:34 -07001298 if (useInfo.number < entries.size() && entries[useInfo.number].first) {
1299 auto *result = entries[useInfo.number].first;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001300 // Check that the type matches the other uses.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001301 if (result->getType() == type)
1302 return result;
1303
Chris Lattner6119d382018-07-20 18:41:34 -07001304 emitError(useInfo.loc, "use of value '" + useInfo.name.str() +
1305 "' expects different type than prior uses");
1306 emitError(entries[useInfo.number].second, "prior use here");
Chris Lattner7f9cc272018-07-19 08:35:28 -07001307 return nullptr;
1308 }
1309
Chris Lattner6119d382018-07-20 18:41:34 -07001310 // Make sure we have enough slots for this.
1311 if (entries.size() <= useInfo.number)
1312 entries.resize(useInfo.number + 1);
1313
1314 // If the value has already been defined and this is an overly large result
1315 // number, diagnose that.
1316 if (entries[0].first && !isForwardReferencePlaceholder(entries[0].first))
1317 return (emitError(useInfo.loc, "reference to invalid result number"),
1318 nullptr);
1319
1320 // Otherwise, this is a forward reference. Create a placeholder and remember
1321 // that we did so.
1322 auto *result = createForwardReferencePlaceholder(useInfo.loc, type);
1323 entries[useInfo.number].first = result;
1324 entries[useInfo.number].second = useInfo.loc;
1325 return result;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001326}
1327
1328/// Register a definition of a value with the symbol table.
1329ParseResult FunctionParser::addDefinition(SSAUseInfo useInfo, SSAValue *value) {
Chris Lattner6119d382018-07-20 18:41:34 -07001330 auto &entries = values[useInfo.name];
Chris Lattner7f9cc272018-07-19 08:35:28 -07001331
Chris Lattner6119d382018-07-20 18:41:34 -07001332 // Make sure there is a slot for this value.
1333 if (entries.size() <= useInfo.number)
1334 entries.resize(useInfo.number + 1);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001335
Chris Lattner6119d382018-07-20 18:41:34 -07001336 // If we already have an entry for this, check to see if it was a definition
1337 // or a forward reference.
1338 if (auto *existing = entries[useInfo.number].first) {
1339 if (!isForwardReferencePlaceholder(existing)) {
1340 emitError(useInfo.loc,
1341 "redefinition of SSA value '" + useInfo.name + "'");
1342 return emitError(entries[useInfo.number].second,
1343 "previously defined here");
1344 }
1345
1346 // If it was a forward reference, update everything that used it to use the
1347 // actual definition instead, delete the forward ref, and remove it from our
1348 // set of forward references we track.
1349 existing->replaceAllUsesWith(value);
1350 existing->getDefiningInst()->destroy();
1351 forwardReferencePlaceholders.erase(existing);
1352 }
1353
1354 entries[useInfo.number].first = value;
1355 entries[useInfo.number].second = useInfo.loc;
1356 return ParseSuccess;
1357}
1358
1359/// After the function is finished parsing, this function checks to see if
1360/// there are any remaining issues.
Chris Lattner40746442018-07-21 14:32:09 -07001361ParseResult FunctionParser::finalizeFunction(Function *func, SMLoc loc) {
Chris Lattner6119d382018-07-20 18:41:34 -07001362 // Check for any forward references that are left. If we find any, error out.
1363 if (!forwardReferencePlaceholders.empty()) {
1364 SmallVector<std::pair<const char *, SSAValue *>, 4> errors;
1365 // Iteration over the map isn't determinstic, so sort by source location.
1366 for (auto entry : forwardReferencePlaceholders)
1367 errors.push_back({entry.second.getPointer(), entry.first});
1368 llvm::array_pod_sort(errors.begin(), errors.end());
1369
1370 for (auto entry : errors)
1371 emitError(SMLoc::getFromPointer(entry.first),
1372 "use of undeclared SSA value name");
1373 return ParseFailure;
1374 }
1375
Chris Lattner40746442018-07-21 14:32:09 -07001376 // Run the verifier on this function. If an error is detected, report it.
1377 std::string errorString;
1378 if (func->verify(&errorString))
1379 return emitError(loc, errorString);
1380
Chris Lattner6119d382018-07-20 18:41:34 -07001381 return ParseSuccess;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001382}
1383
Chris Lattner78276e32018-07-07 15:48:26 -07001384/// Parse a SSA operand for an instruction or statement.
1385///
James Molloy61a656c2018-07-22 15:45:24 -07001386/// ssa-use ::= ssa-id
Chris Lattner78276e32018-07-07 15:48:26 -07001387///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001388ParseResult FunctionParser::parseSSAUse(SSAUseInfo &result) {
Chris Lattner6119d382018-07-20 18:41:34 -07001389 result.name = getTokenSpelling();
1390 result.number = 0;
1391 result.loc = getToken().getLoc();
Chris Lattner7f9cc272018-07-19 08:35:28 -07001392 if (!consumeIf(Token::percent_identifier))
1393 return emitError("expected SSA operand");
Chris Lattner6119d382018-07-20 18:41:34 -07001394
1395 // If we have an affine map ID, it is a result number.
1396 if (getToken().is(Token::hash_identifier)) {
1397 if (auto value = getToken().getHashIdentifierNumber())
1398 result.number = value.getValue();
1399 else
1400 return emitError("invalid SSA value result number");
1401 consumeToken(Token::hash_identifier);
1402 }
1403
Chris Lattner7f9cc272018-07-19 08:35:28 -07001404 return ParseSuccess;
Chris Lattner78276e32018-07-07 15:48:26 -07001405}
1406
1407/// Parse a (possibly empty) list of SSA operands.
1408///
1409/// ssa-use-list ::= ssa-use (`,` ssa-use)*
1410/// ssa-use-list-opt ::= ssa-use-list?
1411///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001412ParseResult
Chris Lattner40746442018-07-21 14:32:09 -07001413FunctionParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
1414 if (!getToken().is(Token::percent_identifier))
1415 return ParseSuccess;
1416 return parseCommaSeparatedList([&]() -> ParseResult {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001417 SSAUseInfo result;
1418 if (parseSSAUse(result))
1419 return ParseFailure;
1420 results.push_back(result);
1421 return ParseSuccess;
1422 });
Chris Lattner78276e32018-07-07 15:48:26 -07001423}
1424
1425/// Parse an SSA use with an associated type.
1426///
1427/// ssa-use-and-type ::= ssa-use `:` type
James Molloy61a656c2018-07-22 15:45:24 -07001428template <typename ResultType>
1429ResultType FunctionParser::parseSSADefOrUseAndType(
1430 const std::function<ResultType(SSAUseInfo, Type *)> &action) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001431 SSAUseInfo useInfo;
1432 if (parseSSAUse(useInfo))
1433 return nullptr;
Chris Lattner78276e32018-07-07 15:48:26 -07001434
1435 if (!consumeIf(Token::colon))
Chris Lattner7f9cc272018-07-19 08:35:28 -07001436 return (emitError("expected ':' and type for SSA operand"), nullptr);
Chris Lattner78276e32018-07-07 15:48:26 -07001437
Chris Lattner7f9cc272018-07-19 08:35:28 -07001438 auto *type = parseType();
1439 if (!type)
1440 return nullptr;
Chris Lattner78276e32018-07-07 15:48:26 -07001441
James Molloy61a656c2018-07-22 15:45:24 -07001442 return action(useInfo, type);
Chris Lattner78276e32018-07-07 15:48:26 -07001443}
1444
Chris Lattner2c402672018-07-23 11:56:17 -07001445/// Parse a (possibly empty) list of SSA operands, followed by a colon, then
1446/// followed by a type list. If hasParens is true, then the operands are
1447/// surrounded by parens.
Chris Lattner78276e32018-07-07 15:48:26 -07001448///
Chris Lattner2c402672018-07-23 11:56:17 -07001449/// ssa-use-and-type-list[parens]
1450/// ::= `(` ssa-use-list `)` ':' type-list-no-parens
1451///
1452/// ssa-use-and-type-list[!parens]
1453/// ::= ssa-use-list ':' type-list-no-parens
Chris Lattner78276e32018-07-07 15:48:26 -07001454///
Chris Lattner40746442018-07-21 14:32:09 -07001455template <typename ValueTy>
Chris Lattner7f9cc272018-07-19 08:35:28 -07001456ParseResult FunctionParser::parseOptionalSSAUseAndTypeList(
Chris Lattner2c402672018-07-23 11:56:17 -07001457 SmallVectorImpl<ValueTy *> &results, bool isParenthesized) {
1458
1459 // If we are in the parenthesized form and no paren exists, then we succeed
1460 // with an empty list.
1461 if (isParenthesized && !consumeIf(Token::l_paren))
Chris Lattner40746442018-07-21 14:32:09 -07001462 return ParseSuccess;
1463
Chris Lattner2c402672018-07-23 11:56:17 -07001464 SmallVector<SSAUseInfo, 4> valueIDs;
1465 if (parseOptionalSSAUseList(valueIDs))
Chris Lattner7f9cc272018-07-19 08:35:28 -07001466 return ParseFailure;
Chris Lattner2c402672018-07-23 11:56:17 -07001467
1468 if (isParenthesized && !consumeIf(Token::r_paren))
1469 return emitError("expected ')' in operand list");
1470
1471 // If there were no operands, then there is no colon or type lists.
1472 if (valueIDs.empty())
1473 return ParseSuccess;
1474
1475 if (!consumeIf(Token::colon))
1476 return emitError("expected ':' in operand list");
1477
1478 SmallVector<Type *, 4> types;
1479 if (parseTypeListNoParens(types))
1480 return ParseFailure;
1481
1482 if (valueIDs.size() != types.size())
1483 return emitError("expected " + Twine(valueIDs.size()) +
1484 " types to match operand list");
1485
1486 results.reserve(valueIDs.size());
1487 for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
1488 if (auto *value = resolveSSAUse(valueIDs[i], types[i]))
1489 results.push_back(cast<ValueTy>(value));
1490 else
1491 return ParseFailure;
1492 }
1493
1494 return ParseSuccess;
Chris Lattner78276e32018-07-07 15:48:26 -07001495}
1496
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001497/// Parse the CFG or MLFunc operation.
1498///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001499/// operation ::=
1500/// (ssa-id `=`)? string '(' ssa-use-list? ')' attribute-dict?
1501/// `:` function-type
1502///
1503ParseResult
Chris Lattner7f9cc272018-07-19 08:35:28 -07001504FunctionParser::parseOperation(const CreateOperationFunction &createOpFunc) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001505 auto loc = getToken().getLoc();
1506
1507 StringRef resultID;
1508 if (getToken().is(Token::percent_identifier)) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001509 resultID = getTokenSpelling();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001510 consumeToken(Token::percent_identifier);
1511 if (!consumeIf(Token::equal))
1512 return emitError("expected '=' after SSA name");
1513 }
1514
1515 if (getToken().isNot(Token::string))
1516 return emitError("expected operation name in quotes");
1517
1518 auto name = getToken().getStringValue();
1519 if (name.empty())
1520 return emitError("empty operation name is invalid");
1521
1522 consumeToken(Token::string);
1523
1524 if (!consumeIf(Token::l_paren))
1525 return emitError("expected '(' to start operand list");
1526
1527 // Parse the operand list.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001528 SmallVector<SSAUseInfo, 8> operandInfos;
Chris Lattner40746442018-07-21 14:32:09 -07001529 if (parseOptionalSSAUseList(operandInfos))
1530 return ParseFailure;
1531
1532 if (!consumeIf(Token::r_paren))
1533 return emitError("expected ')' to end operand list");
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001534
1535 SmallVector<NamedAttribute, 4> attributes;
1536 if (getToken().is(Token::l_brace)) {
1537 if (parseAttributeDict(attributes))
1538 return ParseFailure;
1539 }
1540
Chris Lattner3b2ef762018-07-18 15:31:25 -07001541 if (!consumeIf(Token::colon))
1542 return emitError("expected ':' followed by instruction type");
1543
1544 auto typeLoc = getToken().getLoc();
1545 auto type = parseType();
1546 if (!type)
1547 return ParseFailure;
1548 auto fnType = dyn_cast<FunctionType>(type);
1549 if (!fnType)
1550 return emitError(typeLoc, "expected function type");
1551
Chris Lattner7f9cc272018-07-19 08:35:28 -07001552 // Check that we have the right number of types for the operands.
1553 auto operandTypes = fnType->getInputs();
1554 if (operandTypes.size() != operandInfos.size()) {
1555 auto plural = "s"[operandInfos.size() == 1];
1556 return emitError(typeLoc, "expected " + llvm::utostr(operandInfos.size()) +
Chris Lattnerf8cce872018-07-20 09:28:54 -07001557 " operand type" + plural + " but had " +
Chris Lattner7f9cc272018-07-19 08:35:28 -07001558 llvm::utostr(operandTypes.size()));
1559 }
1560
1561 // Resolve all of the operands.
1562 SmallVector<SSAValue *, 8> operands;
1563 for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
1564 operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
1565 if (!operands.back())
1566 return ParseFailure;
1567 }
1568
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001569 auto nameId = builder.getIdentifier(name);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001570 auto op = createOpFunc(nameId, operands, fnType->getResults(), attributes);
1571 if (!op)
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001572 return ParseFailure;
1573
1574 // We just parsed an operation. If it is a recognized one, verify that it
1575 // is structurally as we expect. If not, produce an error with a reasonable
1576 // source location.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001577 if (auto *opInfo = op->getAbstractOperation(builder.getContext())) {
1578 if (auto error = opInfo->verifyInvariants(op))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001579 return emitError(loc, error);
1580 }
1581
Chris Lattner7f9cc272018-07-19 08:35:28 -07001582 // If the instruction had a name, register it.
1583 if (!resultID.empty()) {
1584 // FIXME: Add result infra to handle Stmt results as well to make this
1585 // generic.
1586 if (auto *inst = dyn_cast<OperationInst>(op)) {
Chris Lattnerf8cce872018-07-20 09:28:54 -07001587 if (inst->getNumResults() == 0)
Chris Lattner7f9cc272018-07-19 08:35:28 -07001588 return emitError(loc, "cannot name an operation with no results");
1589
Chris Lattner6119d382018-07-20 18:41:34 -07001590 for (unsigned i = 0, e = inst->getNumResults(); i != e; ++i)
1591 addDefinition({resultID, i, loc}, inst->getResult(i));
Chris Lattner7f9cc272018-07-19 08:35:28 -07001592 }
1593 }
1594
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001595 return ParseSuccess;
1596}
Chris Lattnere79379a2018-06-22 10:39:19 -07001597
Chris Lattner48af7d12018-07-09 19:05:38 -07001598//===----------------------------------------------------------------------===//
1599// CFG Functions
1600//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001601
Chris Lattner4c95a502018-06-23 16:03:42 -07001602namespace {
Chris Lattner48af7d12018-07-09 19:05:38 -07001603/// This is a specialized parser for CFGFunction's, maintaining the state
1604/// transient to their bodies.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001605class CFGFunctionParser : public FunctionParser {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001606public:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001607 CFGFunctionParser(ParserState &state, CFGFunction *function)
Chris Lattner7f9cc272018-07-19 08:35:28 -07001608 : FunctionParser(state), function(function), builder(function) {}
Chris Lattner2e595eb2018-07-10 10:08:27 -07001609
1610 ParseResult parseFunctionBody();
1611
1612private:
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001613 CFGFunction *function;
James Molloy0ff71542018-07-23 16:56:32 -07001614 llvm::StringMap<std::pair<BasicBlock *, SMLoc>> blocksByName;
Chris Lattner48af7d12018-07-09 19:05:38 -07001615
1616 /// This builder intentionally shadows the builder in the base class, with a
1617 /// more specific builder type.
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001618 CFGFuncBuilder builder;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001619
Chris Lattner4c95a502018-06-23 16:03:42 -07001620 /// Get the basic block with the specified name, creating it if it doesn't
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001621 /// already exist. The location specified is the point of use, which allows
1622 /// us to diagnose references to blocks that are not defined precisely.
1623 BasicBlock *getBlockNamed(StringRef name, SMLoc loc) {
1624 auto &blockAndLoc = blocksByName[name];
1625 if (!blockAndLoc.first) {
Chris Lattner3a467cc2018-07-01 20:28:00 -07001626 blockAndLoc.first = new BasicBlock();
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001627 blockAndLoc.second = loc;
Chris Lattner4c95a502018-06-23 16:03:42 -07001628 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001629 return blockAndLoc.first;
Chris Lattner4c95a502018-06-23 16:03:42 -07001630 }
Chris Lattner48af7d12018-07-09 19:05:38 -07001631
James Molloy61a656c2018-07-22 15:45:24 -07001632 ParseResult
1633 parseOptionalBasicBlockArgList(SmallVectorImpl<BBArgument *> &results,
1634 BasicBlock *owner);
1635
Chris Lattner48af7d12018-07-09 19:05:38 -07001636 ParseResult parseBasicBlock();
1637 OperationInst *parseCFGOperation();
1638 TerminatorInst *parseTerminator();
Chris Lattner4c95a502018-06-23 16:03:42 -07001639};
1640} // end anonymous namespace
1641
James Molloy61a656c2018-07-22 15:45:24 -07001642/// Parse a (possibly empty) list of SSA operands with types as basic block
Chris Lattner2c402672018-07-23 11:56:17 -07001643/// arguments.
James Molloy61a656c2018-07-22 15:45:24 -07001644///
1645/// ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
1646///
1647ParseResult CFGFunctionParser::parseOptionalBasicBlockArgList(
1648 SmallVectorImpl<BBArgument *> &results, BasicBlock *owner) {
1649 if (getToken().is(Token::r_brace))
1650 return ParseSuccess;
1651
1652 return parseCommaSeparatedList([&]() -> ParseResult {
1653 auto type = parseSSADefOrUseAndType<Type *>(
1654 [&](SSAUseInfo useInfo, Type *type) -> Type * {
1655 BBArgument *arg = owner->addArgument(type);
1656 if (addDefinition(useInfo, arg) == ParseFailure)
1657 return nullptr;
1658 return type;
1659 });
1660 return type ? ParseSuccess : ParseFailure;
1661 });
1662}
1663
Chris Lattner48af7d12018-07-09 19:05:38 -07001664ParseResult CFGFunctionParser::parseFunctionBody() {
Chris Lattner40746442018-07-21 14:32:09 -07001665 auto braceLoc = getToken().getLoc();
Chris Lattner48af7d12018-07-09 19:05:38 -07001666 if (!consumeIf(Token::l_brace))
1667 return emitError("expected '{' in CFG function");
1668
1669 // Make sure we have at least one block.
1670 if (getToken().is(Token::r_brace))
1671 return emitError("CFG functions must have at least one basic block");
Chris Lattner4c95a502018-06-23 16:03:42 -07001672
1673 // Parse the list of blocks.
1674 while (!consumeIf(Token::r_brace))
Chris Lattner48af7d12018-07-09 19:05:38 -07001675 if (parseBasicBlock())
Chris Lattner4c95a502018-06-23 16:03:42 -07001676 return ParseFailure;
1677
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001678 // Verify that all referenced blocks were defined. Iteration over a
1679 // StringMap isn't determinstic, but this is good enough for our purposes.
Chris Lattner48af7d12018-07-09 19:05:38 -07001680 for (auto &elt : blocksByName) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001681 auto *bb = elt.second.first;
Chris Lattner3a467cc2018-07-01 20:28:00 -07001682 if (!bb->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001683 return emitError(elt.second.second,
James Molloy0ff71542018-07-23 16:56:32 -07001684 "reference to an undefined basic block '" + elt.first() +
1685 "'");
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001686 }
1687
Chris Lattner48af7d12018-07-09 19:05:38 -07001688 getModule()->functionList.push_back(function);
Chris Lattner6119d382018-07-20 18:41:34 -07001689
Chris Lattner40746442018-07-21 14:32:09 -07001690 return finalizeFunction(function, braceLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001691}
1692
1693/// Basic block declaration.
1694///
1695/// basic-block ::= bb-label instruction* terminator-stmt
1696/// bb-label ::= bb-id bb-arg-list? `:`
1697/// bb-id ::= bare-id
1698/// bb-arg-list ::= `(` ssa-id-and-type-list? `)`
1699///
Chris Lattner48af7d12018-07-09 19:05:38 -07001700ParseResult CFGFunctionParser::parseBasicBlock() {
1701 SMLoc nameLoc = getToken().getLoc();
1702 auto name = getTokenSpelling();
Chris Lattner4c95a502018-06-23 16:03:42 -07001703 if (!consumeIf(Token::bare_identifier))
1704 return emitError("expected basic block name");
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001705
Chris Lattner48af7d12018-07-09 19:05:38 -07001706 auto *block = getBlockNamed(name, nameLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001707
1708 // If this block has already been parsed, then this is a redefinition with the
1709 // same block name.
Chris Lattner3a467cc2018-07-01 20:28:00 -07001710 if (block->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001711 return emitError(nameLoc, "redefinition of block '" + name.str() + "'");
1712
Chris Lattner78276e32018-07-07 15:48:26 -07001713 // If an argument list is present, parse it.
1714 if (consumeIf(Token::l_paren)) {
James Molloy61a656c2018-07-22 15:45:24 -07001715 SmallVector<BBArgument *, 8> bbArgs;
1716 if (parseOptionalBasicBlockArgList(bbArgs, block))
Chris Lattner78276e32018-07-07 15:48:26 -07001717 return ParseFailure;
Chris Lattner40746442018-07-21 14:32:09 -07001718 if (!consumeIf(Token::r_paren))
1719 return emitError("expected ')' to end argument list");
Chris Lattner78276e32018-07-07 15:48:26 -07001720 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001721
James Molloy61a656c2018-07-22 15:45:24 -07001722 // Add the block to the function.
1723 function->push_back(block);
1724
Chris Lattner4c95a502018-06-23 16:03:42 -07001725 if (!consumeIf(Token::colon))
1726 return emitError("expected ':' after basic block name");
1727
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001728 // Set the insertion point to the block we want to insert new operations into.
Chris Lattner48af7d12018-07-09 19:05:38 -07001729 builder.setInsertionPoint(block);
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001730
Chris Lattner7f9cc272018-07-19 08:35:28 -07001731 auto createOpFunc = [&](Identifier name, ArrayRef<SSAValue *> operands,
1732 ArrayRef<Type *> resultTypes,
1733 ArrayRef<NamedAttribute> attrs) -> Operation * {
1734 SmallVector<CFGValue *, 8> cfgOperands;
1735 cfgOperands.reserve(operands.size());
1736 for (auto *op : operands)
1737 cfgOperands.push_back(cast<CFGValue>(op));
1738 return builder.createOperation(name, cfgOperands, resultTypes, attrs);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001739 };
1740
Chris Lattnered65a732018-06-28 20:45:33 -07001741 // Parse the list of operations that make up the body of the block.
Chris Lattner48af7d12018-07-09 19:05:38 -07001742 while (getToken().isNot(Token::kw_return, Token::kw_br)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001743 if (parseOperation(createOpFunc))
Chris Lattnered65a732018-06-28 20:45:33 -07001744 return ParseFailure;
1745 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001746
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001747 if (!parseTerminator())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001748 return ParseFailure;
Chris Lattner4c95a502018-06-23 16:03:42 -07001749
1750 return ParseSuccess;
1751}
1752
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001753/// Parse the terminator instruction for a basic block.
1754///
1755/// terminator-stmt ::= `br` bb-id branch-use-list?
Chris Lattner1604e472018-07-23 08:42:19 -07001756/// branch-use-list ::= `(` ssa-use-list `)` ':' type-list-no-parens
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001757/// terminator-stmt ::=
1758/// `cond_br` ssa-use `,` bb-id branch-use-list? `,` bb-id branch-use-list?
1759/// terminator-stmt ::= `return` ssa-use-and-type-list?
1760///
Chris Lattner48af7d12018-07-09 19:05:38 -07001761TerminatorInst *CFGFunctionParser::parseTerminator() {
1762 switch (getToken().getKind()) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001763 default:
Chris Lattner3a467cc2018-07-01 20:28:00 -07001764 return (emitError("expected terminator at end of basic block"), nullptr);
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001765
Chris Lattner40746442018-07-21 14:32:09 -07001766 case Token::kw_return: {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001767 consumeToken(Token::kw_return);
Chris Lattner40746442018-07-21 14:32:09 -07001768
Chris Lattner2c402672018-07-23 11:56:17 -07001769 // Parse any operands.
1770 SmallVector<CFGValue *, 8> operands;
1771 if (parseOptionalSSAUseAndTypeList(operands, /*isParenthesized*/ false))
1772 return nullptr;
1773 return builder.createReturnInst(operands);
Chris Lattner40746442018-07-21 14:32:09 -07001774 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001775
1776 case Token::kw_br: {
1777 consumeToken(Token::kw_br);
Chris Lattner48af7d12018-07-09 19:05:38 -07001778 auto destBB = getBlockNamed(getTokenSpelling(), getToken().getLoc());
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001779 if (!consumeIf(Token::bare_identifier))
Chris Lattner3a467cc2018-07-01 20:28:00 -07001780 return (emitError("expected basic block name"), nullptr);
Chris Lattner1604e472018-07-23 08:42:19 -07001781 auto branch = builder.createBranchInst(destBB);
1782
Chris Lattner2c402672018-07-23 11:56:17 -07001783 SmallVector<CFGValue *, 8> operands;
1784 if (parseOptionalSSAUseAndTypeList(operands, /*isParenthesized*/ true))
Chris Lattner1604e472018-07-23 08:42:19 -07001785 return nullptr;
Chris Lattner2c402672018-07-23 11:56:17 -07001786 branch->addOperands(operands);
Chris Lattner1604e472018-07-23 08:42:19 -07001787 return branch;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001788 }
Chris Lattner78276e32018-07-07 15:48:26 -07001789 // TODO: cond_br.
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001790 }
1791}
1792
Chris Lattner48af7d12018-07-09 19:05:38 -07001793//===----------------------------------------------------------------------===//
1794// ML Functions
1795//===----------------------------------------------------------------------===//
1796
1797namespace {
1798/// Refined parser for MLFunction bodies.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001799class MLFunctionParser : public FunctionParser {
Chris Lattner48af7d12018-07-09 19:05:38 -07001800public:
Chris Lattner48af7d12018-07-09 19:05:38 -07001801 MLFunctionParser(ParserState &state, MLFunction *function)
Chris Lattner7f9cc272018-07-19 08:35:28 -07001802 : FunctionParser(state), function(function), builder(function) {}
Chris Lattner48af7d12018-07-09 19:05:38 -07001803
1804 ParseResult parseFunctionBody();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001805
1806private:
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001807 MLFunction *function;
1808
1809 /// This builder intentionally shadows the builder in the base class, with a
1810 /// more specific builder type.
1811 MLFuncBuilder builder;
1812
1813 ParseResult parseForStmt();
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001814 AffineConstantExpr *parseIntConstant();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001815 ParseResult parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001816 ParseResult parseElseClause(IfClause *elseClause);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001817 ParseResult parseStatements(StmtBlock *block);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001818 ParseResult parseStmtBlock(StmtBlock *block);
Chris Lattner48af7d12018-07-09 19:05:38 -07001819};
1820} // end anonymous namespace
1821
Chris Lattner48af7d12018-07-09 19:05:38 -07001822ParseResult MLFunctionParser::parseFunctionBody() {
Chris Lattner40746442018-07-21 14:32:09 -07001823 auto braceLoc = getToken().getLoc();
Chris Lattner48af7d12018-07-09 19:05:38 -07001824 if (!consumeIf(Token::l_brace))
1825 return emitError("expected '{' in ML function");
1826
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001827 // Parse statements in this function
1828 if (parseStatements(function))
1829 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001830
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001831 if (!consumeIf(Token::kw_return))
1832 emitError("ML function must end with return statement");
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001833
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001834 // TODO: store return operands in the IR.
1835 SmallVector<SSAUseInfo, 4> dummyUseInfo;
Chris Lattner40746442018-07-21 14:32:09 -07001836 if (parseOptionalSSAUseList(dummyUseInfo))
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001837 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001838
Chris Lattner40746442018-07-21 14:32:09 -07001839 if (!consumeIf(Token::r_brace))
1840 return emitError("expected '}' to end mlfunc");
1841
Chris Lattner48af7d12018-07-09 19:05:38 -07001842 getModule()->functionList.push_back(function);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001843
Chris Lattner40746442018-07-21 14:32:09 -07001844 return finalizeFunction(function, braceLoc);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001845}
1846
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001847/// For statement.
1848///
Chris Lattner48af7d12018-07-09 19:05:38 -07001849/// ml-for-stmt ::= `for` ssa-id `=` lower-bound `to` upper-bound
1850/// (`step` integer-literal)? `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001851///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001852ParseResult MLFunctionParser::parseForStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001853 consumeToken(Token::kw_for);
1854
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001855 // Parse induction variable
1856 if (getToken().isNot(Token::percent_identifier))
1857 return emitError("expected SSA identifier for the loop variable");
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001858
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001859 // TODO: create SSA value definition from name
1860 StringRef name = getTokenSpelling().drop_front();
1861 (void)name;
1862
1863 consumeToken(Token::percent_identifier);
1864
1865 if (!consumeIf(Token::equal))
1866 return emitError("expected =");
1867
1868 // Parse loop bounds
1869 AffineConstantExpr *lowerBound = parseIntConstant();
1870 if (!lowerBound)
1871 return ParseFailure;
1872
1873 if (!consumeIf(Token::kw_to))
1874 return emitError("expected 'to' between bounds");
1875
1876 AffineConstantExpr *upperBound = parseIntConstant();
1877 if (!upperBound)
1878 return ParseFailure;
1879
1880 // Parse step
1881 AffineConstantExpr *step = nullptr;
1882 if (consumeIf(Token::kw_step)) {
1883 step = parseIntConstant();
1884 if (!step)
1885 return ParseFailure;
1886 }
1887
1888 // Create for statement.
1889 ForStmt *stmt = builder.createFor(lowerBound, upperBound, step);
1890
1891 // If parsing of the for statement body fails,
1892 // MLIR contains for statement with those nested statements that have been
1893 // successfully parsed.
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001894 if (parseStmtBlock(static_cast<StmtBlock *>(stmt)))
1895 return ParseFailure;
1896
1897 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001898}
1899
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001900// This method is temporary workaround to parse simple loop bounds and
1901// step.
1902// TODO: remove this method once it's no longer used.
1903AffineConstantExpr *MLFunctionParser::parseIntConstant() {
1904 if (getToken().isNot(Token::integer))
1905 return (emitError("expected non-negative integer for now"), nullptr);
1906
1907 auto val = getToken().getUInt64IntegerValue();
1908 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
1909 return (emitError("constant too large for affineint"), nullptr);
1910 }
1911 consumeToken(Token::integer);
1912 return builder.getConstantExpr((int64_t)val.getValue());
1913}
1914
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001915/// If statement.
1916///
Chris Lattner48af7d12018-07-09 19:05:38 -07001917/// ml-if-head ::= `if` ml-if-cond `{` ml-stmt* `}`
1918/// | ml-if-head `else` `if` ml-if-cond `{` ml-stmt* `}`
1919/// ml-if-stmt ::= ml-if-head
1920/// | ml-if-head `else` `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001921///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001922ParseResult MLFunctionParser::parseIfStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001923 consumeToken(Token::kw_if);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001924 if (!consumeIf(Token::l_paren))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001925 return emitError("expected (");
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001926
James Molloy0ff71542018-07-23 16:56:32 -07001927 // TODO: parse condition
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001928
1929 if (!consumeIf(Token::r_paren))
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001930 return emitError("expected ')'");
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001931
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001932 IfStmt *ifStmt = builder.createIf();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001933 IfClause *thenClause = ifStmt->getThenClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001934
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001935 // When parsing of an if statement body fails, the IR contains
1936 // the if statement with the portion of the body that has been
1937 // successfully parsed.
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001938 if (parseStmtBlock(thenClause))
1939 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001940
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001941 if (consumeIf(Token::kw_else)) {
1942 IfClause *elseClause = ifStmt->createElseClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001943 if (parseElseClause(elseClause))
1944 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001945 }
1946
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001947 return ParseSuccess;
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001948}
1949
1950ParseResult MLFunctionParser::parseElseClause(IfClause *elseClause) {
1951 if (getToken().is(Token::kw_if)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001952 builder.setInsertionPoint(elseClause);
1953 return parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001954 }
1955
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001956 return parseStmtBlock(elseClause);
1957}
1958
1959///
1960/// Parse a list of statements ending with `return` or `}`
1961///
1962ParseResult MLFunctionParser::parseStatements(StmtBlock *block) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001963 auto createOpFunc = [&](Identifier name, ArrayRef<SSAValue *> operands,
1964 ArrayRef<Type *> resultTypes,
1965 ArrayRef<NamedAttribute> attrs) -> Operation * {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001966 return builder.createOperation(name, attrs);
1967 };
1968
1969 builder.setInsertionPoint(block);
1970
1971 while (getToken().isNot(Token::kw_return, Token::r_brace)) {
1972 switch (getToken().getKind()) {
1973 default:
1974 if (parseOperation(createOpFunc))
1975 return ParseFailure;
1976 break;
1977 case Token::kw_for:
1978 if (parseForStmt())
1979 return ParseFailure;
1980 break;
1981 case Token::kw_if:
1982 if (parseIfStmt())
1983 return ParseFailure;
1984 break;
1985 } // end switch
1986 }
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001987
1988 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001989}
1990
1991///
1992/// Parse `{` ml-stmt* `}`
1993///
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001994ParseResult MLFunctionParser::parseStmtBlock(StmtBlock *block) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001995 if (!consumeIf(Token::l_brace))
1996 return emitError("expected '{' before statement list");
1997
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001998 if (parseStatements(block))
1999 return ParseFailure;
2000
2001 if (!consumeIf(Token::r_brace))
2002 return emitError("expected '}' at the end of the statement block");
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002003
2004 return ParseSuccess;
2005}
2006
Chris Lattner4c95a502018-06-23 16:03:42 -07002007//===----------------------------------------------------------------------===//
2008// Top-level entity parsing.
2009//===----------------------------------------------------------------------===//
2010
Chris Lattner2e595eb2018-07-10 10:08:27 -07002011namespace {
2012/// This parser handles entities that are only valid at the top level of the
2013/// file.
2014class ModuleParser : public Parser {
2015public:
2016 explicit ModuleParser(ParserState &state) : Parser(state) {}
2017
2018 ParseResult parseModule();
2019
2020private:
2021 ParseResult parseAffineMapDef();
2022
2023 // Functions.
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002024 ParseResult parseMLArgumentList(SmallVectorImpl<Type *> &argTypes,
2025 SmallVectorImpl<StringRef> &argNames);
2026 ParseResult parseFunctionSignature(StringRef &name, FunctionType *&type,
2027 SmallVectorImpl<StringRef> *argNames);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002028 ParseResult parseExtFunc();
2029 ParseResult parseCFGFunc();
2030 ParseResult parseMLFunc();
2031};
2032} // end anonymous namespace
2033
2034/// Affine map declaration.
2035///
2036/// affine-map-def ::= affine-map-id `=` affine-map-inline
2037///
2038ParseResult ModuleParser::parseAffineMapDef() {
2039 assert(getToken().is(Token::hash_identifier));
2040
2041 StringRef affineMapId = getTokenSpelling().drop_front();
2042
2043 // Check for redefinitions.
2044 auto *&entry = getState().affineMapDefinitions[affineMapId];
2045 if (entry)
2046 return emitError("redefinition of affine map id '" + affineMapId + "'");
2047
2048 consumeToken(Token::hash_identifier);
2049
2050 // Parse the '='
2051 if (!consumeIf(Token::equal))
2052 return emitError("expected '=' in affine map outlined definition");
2053
2054 entry = parseAffineMapInline();
2055 if (!entry)
2056 return ParseFailure;
2057
Chris Lattner2e595eb2018-07-10 10:08:27 -07002058 return ParseSuccess;
2059}
2060
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002061/// Parse a (possibly empty) list of MLFunction arguments with types.
2062///
2063/// ml-argument ::= ssa-id `:` type
2064/// ml-argument-list ::= ml-argument (`,` ml-argument)* | /*empty*/
2065///
2066ParseResult
2067ModuleParser::parseMLArgumentList(SmallVectorImpl<Type *> &argTypes,
2068 SmallVectorImpl<StringRef> &argNames) {
2069 auto parseElt = [&]() -> ParseResult {
2070 // Parse argument name
2071 if (getToken().isNot(Token::percent_identifier))
2072 return emitError("expected SSA identifier");
2073
2074 StringRef name = getTokenSpelling().drop_front();
2075 consumeToken(Token::percent_identifier);
2076 argNames.push_back(name);
2077
2078 if (!consumeIf(Token::colon))
2079 return emitError("expected ':'");
2080
2081 // Parse argument type
2082 auto elt = parseType();
2083 if (!elt)
2084 return ParseFailure;
2085 argTypes.push_back(elt);
2086
2087 return ParseSuccess;
2088 };
2089
2090 if (!consumeIf(Token::l_paren))
2091 llvm_unreachable("expected '('");
2092
Chris Lattner40746442018-07-21 14:32:09 -07002093 return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002094}
2095
Chris Lattner2e595eb2018-07-10 10:08:27 -07002096/// Parse a function signature, starting with a name and including the parameter
2097/// list.
2098///
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002099/// argument-list ::= type (`,` type)* | /*empty*/ | ml-argument-list
Chris Lattner2e595eb2018-07-10 10:08:27 -07002100/// function-signature ::= function-id `(` argument-list `)` (`->` type-list)?
2101///
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002102ParseResult
2103ModuleParser::parseFunctionSignature(StringRef &name, FunctionType *&type,
2104 SmallVectorImpl<StringRef> *argNames) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07002105 if (getToken().isNot(Token::at_identifier))
2106 return emitError("expected a function identifier like '@foo'");
2107
2108 name = getTokenSpelling().drop_front();
2109 consumeToken(Token::at_identifier);
2110
2111 if (getToken().isNot(Token::l_paren))
2112 return emitError("expected '(' in function signature");
2113
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002114 SmallVector<Type *, 4> argTypes;
2115 ParseResult parseResult;
2116
2117 if (argNames)
2118 parseResult = parseMLArgumentList(argTypes, *argNames);
2119 else
2120 parseResult = parseTypeList(argTypes);
2121
2122 if (parseResult)
Chris Lattner2e595eb2018-07-10 10:08:27 -07002123 return ParseFailure;
2124
2125 // Parse the return type if present.
2126 SmallVector<Type *, 4> results;
2127 if (consumeIf(Token::arrow)) {
2128 if (parseTypeList(results))
2129 return ParseFailure;
2130 }
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002131 type = builder.getFunctionType(argTypes, results);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002132 return ParseSuccess;
2133}
2134
2135/// External function declarations.
2136///
2137/// ext-func ::= `extfunc` function-signature
2138///
2139ParseResult ModuleParser::parseExtFunc() {
2140 consumeToken(Token::kw_extfunc);
2141
2142 StringRef name;
2143 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002144 if (parseFunctionSignature(name, type, /*arguments*/ nullptr))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002145 return ParseFailure;
2146
2147 // Okay, the external function definition was parsed correctly.
2148 getModule()->functionList.push_back(new ExtFunction(name, type));
2149 return ParseSuccess;
2150}
2151
2152/// CFG function declarations.
2153///
2154/// cfg-func ::= `cfgfunc` function-signature `{` basic-block+ `}`
2155///
2156ParseResult ModuleParser::parseCFGFunc() {
2157 consumeToken(Token::kw_cfgfunc);
2158
2159 StringRef name;
2160 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002161 if (parseFunctionSignature(name, type, /*arguments*/ nullptr))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002162 return ParseFailure;
2163
2164 // Okay, the CFG function signature was parsed correctly, create the function.
2165 auto function = new CFGFunction(name, type);
2166
2167 return CFGFunctionParser(getState(), function).parseFunctionBody();
2168}
2169
2170/// ML function declarations.
2171///
2172/// ml-func ::= `mlfunc` ml-func-signature `{` ml-stmt* ml-return-stmt `}`
2173///
2174ParseResult ModuleParser::parseMLFunc() {
2175 consumeToken(Token::kw_mlfunc);
2176
2177 StringRef name;
2178 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002179 SmallVector<StringRef, 4> argNames;
Chris Lattner2e595eb2018-07-10 10:08:27 -07002180 // FIXME: Parse ML function signature (args + types)
2181 // by passing pointer to SmallVector<identifier> into parseFunctionSignature
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002182
2183 if (parseFunctionSignature(name, type, &argNames))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002184 return ParseFailure;
2185
2186 // Okay, the ML function signature was parsed correctly, create the function.
2187 auto function = new MLFunction(name, type);
2188
2189 return MLFunctionParser(getState(), function).parseFunctionBody();
2190}
2191
Chris Lattnere79379a2018-06-22 10:39:19 -07002192/// This is the top-level module parser.
Chris Lattner2e595eb2018-07-10 10:08:27 -07002193ParseResult ModuleParser::parseModule() {
Chris Lattnere79379a2018-06-22 10:39:19 -07002194 while (1) {
Chris Lattner48af7d12018-07-09 19:05:38 -07002195 switch (getToken().getKind()) {
Chris Lattnere79379a2018-06-22 10:39:19 -07002196 default:
2197 emitError("expected a top level entity");
Chris Lattner2e595eb2018-07-10 10:08:27 -07002198 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07002199
Uday Bondhugula015cbb12018-07-03 20:16:08 -07002200 // If we got to the end of the file, then we're done.
Chris Lattnere79379a2018-06-22 10:39:19 -07002201 case Token::eof:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002202 return ParseSuccess;
Chris Lattnere79379a2018-06-22 10:39:19 -07002203
2204 // If we got an error token, then the lexer already emitted an error, just
2205 // stop. Someday we could introduce error recovery if there was demand for
2206 // it.
2207 case Token::error:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002208 return ParseFailure;
2209
2210 case Token::hash_identifier:
2211 if (parseAffineMapDef())
2212 return ParseFailure;
2213 break;
Chris Lattnere79379a2018-06-22 10:39:19 -07002214
2215 case Token::kw_extfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002216 if (parseExtFunc())
2217 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07002218 break;
2219
Chris Lattner4c95a502018-06-23 16:03:42 -07002220 case Token::kw_cfgfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002221 if (parseCFGFunc())
2222 return ParseFailure;
MLIR Teamf85a6262018-06-27 11:03:08 -07002223 break;
Chris Lattner4c95a502018-06-23 16:03:42 -07002224
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002225 case Token::kw_mlfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002226 if (parseMLFunc())
2227 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002228 break;
2229
Uday Bondhugula015cbb12018-07-03 20:16:08 -07002230 // TODO: affine entity declarations, etc.
Chris Lattnere79379a2018-06-22 10:39:19 -07002231 }
2232 }
2233}
2234
2235//===----------------------------------------------------------------------===//
2236
Jacques Pienaar7b829702018-07-03 13:24:09 -07002237void mlir::defaultErrorReporter(const llvm::SMDiagnostic &error) {
2238 const auto &sourceMgr = *error.getSourceMgr();
2239 sourceMgr.PrintMessage(error.getLoc(), error.getKind(), error.getMessage());
2240}
2241
Chris Lattnere79379a2018-06-22 10:39:19 -07002242/// This parses the file specified by the indicated SourceMgr and returns an
2243/// MLIR module if it was valid. If not, it emits diagnostics and returns null.
Jacques Pienaar9c411be2018-06-24 19:17:35 -07002244Module *mlir::parseSourceFile(llvm::SourceMgr &sourceMgr, MLIRContext *context,
Jacques Pienaar7b829702018-07-03 13:24:09 -07002245 SMDiagnosticHandlerTy errorReporter) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07002246 // This is the result module we are parsing into.
2247 std::unique_ptr<Module> module(new Module(context));
2248
2249 ParserState state(sourceMgr, module.get(),
Jacques Pienaar0bffd862018-07-11 13:26:23 -07002250 errorReporter ? errorReporter : defaultErrorReporter);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002251 if (ModuleParser(state).parseModule())
2252 return nullptr;
Chris Lattner21e67f62018-07-06 10:46:19 -07002253
2254 // Make sure the parse module has no other structural problems detected by the
2255 // verifier.
Chris Lattner2e595eb2018-07-10 10:08:27 -07002256 module->verify();
2257 return module.release();
Chris Lattnere79379a2018-06-22 10:39:19 -07002258}