blob: a468c9e5c8947471dc0aab17a01fa8d5852bb00e [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"
Jacques Pienaar84491092018-07-31 17:15:15 -070024#include "llvm/ADT/DenseMap.h"
25#include "llvm/Support/SourceMgr.h"
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070026#include "mlir/IR/AffineExpr.h"
MLIR Teamf85a6262018-06-27 11:03:08 -070027#include "mlir/IR/AffineMap.h"
Chris Lattner7121b802018-07-04 20:45:39 -070028#include "mlir/IR/Attributes.h"
Chris Lattner158e0a3e2018-07-08 20:51:38 -070029#include "mlir/IR/Builders.h"
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -070030#include "mlir/IR/MLFunction.h"
Chris Lattner21e67f62018-07-06 10:46:19 -070031#include "mlir/IR/Module.h"
Chris Lattner85ee1512018-07-25 11:15:20 -070032#include "mlir/IR/OpImplementation.h"
Chris Lattner21e67f62018-07-06 10:46:19 -070033#include "mlir/IR/OperationSet.h"
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -070034#include "mlir/IR/Statements.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070035#include "mlir/IR/Types.h"
Chris Lattnere79379a2018-06-22 10:39:19 -070036using namespace mlir;
Chris Lattner4c95a502018-06-23 16:03:42 -070037using llvm::SMLoc;
James Molloy0ff71542018-07-23 16:56:32 -070038using llvm::SourceMgr;
Chris Lattnere79379a2018-06-22 10:39:19 -070039
Chris Lattnerf7e22732018-06-22 22:03:48 -070040/// Simple enum to make code read better in cases that would otherwise return a
41/// bool value. Failure is "true" in a boolean context.
James Molloy0ff71542018-07-23 16:56:32 -070042enum ParseResult { ParseSuccess, ParseFailure };
Chris Lattnere79379a2018-06-22 10:39:19 -070043
Chris Lattner48af7d12018-07-09 19:05:38 -070044namespace {
45class Parser;
46
47/// This class refers to all of the state maintained globally by the parser,
48/// such as the current lexer position etc. The Parser base class provides
49/// methods to access this.
50class ParserState {
Chris Lattnered65a732018-06-28 20:45:33 -070051public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070052 ParserState(llvm::SourceMgr &sourceMgr, Module *module,
Chris Lattner48af7d12018-07-09 19:05:38 -070053 SMDiagnosticHandlerTy errorReporter)
Chris Lattner2e595eb2018-07-10 10:08:27 -070054 : context(module->getContext()), module(module),
55 lex(sourceMgr, errorReporter), curToken(lex.lexToken()),
Chris Lattner85ee1512018-07-25 11:15:20 -070056 errorReporter(errorReporter), operationSet(OperationSet::get(context)) {
57 }
Chris Lattner2e595eb2018-07-10 10:08:27 -070058
59 // A map from affine map identifier to AffineMap.
60 llvm::StringMap<AffineMap *> affineMapDefinitions;
Chris Lattnere79379a2018-06-22 10:39:19 -070061
Chris Lattnere79379a2018-06-22 10:39:19 -070062private:
Chris Lattner48af7d12018-07-09 19:05:38 -070063 ParserState(const ParserState &) = delete;
64 void operator=(const ParserState &) = delete;
65
66 friend class Parser;
67
68 // The context we're parsing into.
Chris Lattner2e595eb2018-07-10 10:08:27 -070069 MLIRContext *const context;
70
71 // This is the module we are parsing into.
72 Module *const module;
Chris Lattnerf7e22732018-06-22 22:03:48 -070073
74 // The lexer for the source file we're parsing.
Chris Lattnere79379a2018-06-22 10:39:19 -070075 Lexer lex;
76
77 // This is the next token that hasn't been consumed yet.
78 Token curToken;
79
Jacques Pienaar9c411be2018-06-24 19:17:35 -070080 // The diagnostic error reporter.
Chris Lattner2e595eb2018-07-10 10:08:27 -070081 SMDiagnosticHandlerTy const errorReporter;
Chris Lattner85ee1512018-07-25 11:15:20 -070082
83 // The active OperationSet we're parsing with.
84 OperationSet &operationSet;
Chris Lattner48af7d12018-07-09 19:05:38 -070085};
86} // end anonymous namespace
MLIR Teamf85a6262018-06-27 11:03:08 -070087
Chris Lattner48af7d12018-07-09 19:05:38 -070088namespace {
89
Chris Lattner7f9cc272018-07-19 08:35:28 -070090typedef std::function<Operation *(Identifier, ArrayRef<SSAValue *>,
91 ArrayRef<Type *>, ArrayRef<NamedAttribute>)>
Tatiana Shpeisman565b9642018-07-16 11:47:09 -070092 CreateOperationFunction;
93
Chris Lattner48af7d12018-07-09 19:05:38 -070094/// This class implement support for parsing global entities like types and
95/// shared entities like SSA names. It is intended to be subclassed by
96/// specialized subparsers that include state, e.g. when a local symbol table.
97class Parser {
98public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070099 Builder builder;
Chris Lattner48af7d12018-07-09 19:05:38 -0700100
Chris Lattner2e595eb2018-07-10 10:08:27 -0700101 Parser(ParserState &state) : builder(state.context), state(state) {}
102
103 // Helper methods to get stuff from the parser-global state.
104 ParserState &getState() const { return state; }
Chris Lattner48af7d12018-07-09 19:05:38 -0700105 MLIRContext *getContext() const { return state.context; }
Chris Lattner2e595eb2018-07-10 10:08:27 -0700106 Module *getModule() { return state.module; }
Chris Lattner85ee1512018-07-25 11:15:20 -0700107 OperationSet &getOperationSet() const { return state.operationSet; }
Chris Lattner48af7d12018-07-09 19:05:38 -0700108
109 /// Return the current token the parser is inspecting.
110 const Token &getToken() const { return state.curToken; }
111 StringRef getTokenSpelling() const { return state.curToken.getSpelling(); }
Chris Lattnere79379a2018-06-22 10:39:19 -0700112
113 /// Emit an error and return failure.
Chris Lattner4c95a502018-06-23 16:03:42 -0700114 ParseResult emitError(const Twine &message) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700115 return emitError(state.curToken.getLoc(), message);
Chris Lattner4c95a502018-06-23 16:03:42 -0700116 }
117 ParseResult emitError(SMLoc loc, const Twine &message);
Chris Lattnere79379a2018-06-22 10:39:19 -0700118
119 /// Advance the current lexer onto the next token.
120 void consumeToken() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700121 assert(state.curToken.isNot(Token::eof, Token::error) &&
Chris Lattnere79379a2018-06-22 10:39:19 -0700122 "shouldn't advance past EOF or errors");
Chris Lattner48af7d12018-07-09 19:05:38 -0700123 state.curToken = state.lex.lexToken();
Chris Lattnere79379a2018-06-22 10:39:19 -0700124 }
125
126 /// Advance the current lexer onto the next token, asserting what the expected
127 /// current token is. This is preferred to the above method because it leads
128 /// to more self-documenting code with better checking.
Chris Lattner8da0c282018-06-29 11:15:56 -0700129 void consumeToken(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700130 assert(state.curToken.is(kind) && "consumed an unexpected token");
Chris Lattnere79379a2018-06-22 10:39:19 -0700131 consumeToken();
132 }
133
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700134 /// If the current token has the specified kind, consume it and return true.
135 /// If not, return false.
Chris Lattner8da0c282018-06-29 11:15:56 -0700136 bool consumeIf(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700137 if (state.curToken.isNot(kind))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700138 return false;
139 consumeToken(kind);
140 return true;
141 }
142
Chris Lattnerf7702a62018-07-23 17:30:01 -0700143 /// Consume the specified token if present and return success. On failure,
144 /// output a diagnostic and return failure.
145 ParseResult parseToken(Token::Kind expectedToken, const Twine &message);
146
Chris Lattner40746442018-07-21 14:32:09 -0700147 /// Parse a comma-separated list of elements up until the specified end token.
148 ParseResult
149 parseCommaSeparatedListUntil(Token::Kind rightToken,
150 const std::function<ParseResult()> &parseElement,
151 bool allowEmptyList = true);
152
153 /// Parse a comma separated list of elements that must have at least one entry
154 /// in it.
155 ParseResult
156 parseCommaSeparatedList(const std::function<ParseResult()> &parseElement);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700157
Chris Lattnerf7e22732018-06-22 22:03:48 -0700158 // We have two forms of parsing methods - those that return a non-null
159 // pointer on success, and those that return a ParseResult to indicate whether
160 // they returned a failure. The second class fills in by-reference arguments
161 // as the results of their action.
162
Chris Lattnere79379a2018-06-22 10:39:19 -0700163 // Type parsing.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700164 VectorType *parseVectorType();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700165 ParseResult parseDimensionListRanked(SmallVectorImpl<int> &dimensions);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700166 Type *parseTensorType();
167 Type *parseMemRefType();
168 Type *parseFunctionType();
169 Type *parseType();
Chris Lattner1604e472018-07-23 08:42:19 -0700170 ParseResult parseTypeListNoParens(SmallVectorImpl<Type *> &elements);
James Molloy0ff71542018-07-23 16:56:32 -0700171 ParseResult parseTypeList(SmallVectorImpl<Type *> &elements);
Chris Lattnere79379a2018-06-22 10:39:19 -0700172
Chris Lattner7121b802018-07-04 20:45:39 -0700173 // Attribute parsing.
174 Attribute *parseAttribute();
175 ParseResult parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes);
176
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700177 // Polyhedral structures.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700178 AffineMap *parseAffineMapInline();
MLIR Team718c82f2018-07-16 09:45:22 -0700179 AffineMap *parseAffineMapReference();
MLIR Teamf85a6262018-06-27 11:03:08 -0700180
Chris Lattner48af7d12018-07-09 19:05:38 -0700181private:
182 // The Parser is subclassed and reinstantiated. Do not add additional
183 // non-trivial state here, add it to the ParserState class.
184 ParserState &state;
Chris Lattnere79379a2018-06-22 10:39:19 -0700185};
186} // end anonymous namespace
187
188//===----------------------------------------------------------------------===//
189// Helper methods.
190//===----------------------------------------------------------------------===//
191
Chris Lattner4c95a502018-06-23 16:03:42 -0700192ParseResult Parser::emitError(SMLoc loc, const Twine &message) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700193 // If we hit a parse error in response to a lexer error, then the lexer
Jacques Pienaar9c411be2018-06-24 19:17:35 -0700194 // already reported the error.
Chris Lattner48af7d12018-07-09 19:05:38 -0700195 if (getToken().is(Token::error))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700196 return ParseFailure;
197
Chris Lattner48af7d12018-07-09 19:05:38 -0700198 auto &sourceMgr = state.lex.getSourceMgr();
199 state.errorReporter(sourceMgr.GetMessage(loc, SourceMgr::DK_Error, message));
Chris Lattnere79379a2018-06-22 10:39:19 -0700200 return ParseFailure;
201}
202
Chris Lattnerf7702a62018-07-23 17:30:01 -0700203/// Consume the specified token if present and return success. On failure,
204/// output a diagnostic and return failure.
205ParseResult Parser::parseToken(Token::Kind expectedToken,
206 const Twine &message) {
207 if (consumeIf(expectedToken))
208 return ParseSuccess;
209 return emitError(message);
210}
211
Chris Lattner40746442018-07-21 14:32:09 -0700212/// Parse a comma separated list of elements that must have at least one entry
213/// in it.
214ParseResult Parser::parseCommaSeparatedList(
215 const std::function<ParseResult()> &parseElement) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700216 // Non-empty case starts with an element.
217 if (parseElement())
218 return ParseFailure;
219
220 // Otherwise we have a list of comma separated elements.
221 while (consumeIf(Token::comma)) {
222 if (parseElement())
223 return ParseFailure;
224 }
Chris Lattner40746442018-07-21 14:32:09 -0700225 return ParseSuccess;
226}
227
228/// Parse a comma-separated list of elements, terminated with an arbitrary
229/// token. This allows empty lists if allowEmptyList is true.
230///
231/// abstract-list ::= rightToken // if allowEmptyList == true
232/// abstract-list ::= element (',' element)* rightToken
233///
234ParseResult Parser::parseCommaSeparatedListUntil(
235 Token::Kind rightToken, const std::function<ParseResult()> &parseElement,
236 bool allowEmptyList) {
237 // Handle the empty case.
238 if (getToken().is(rightToken)) {
239 if (!allowEmptyList)
240 return emitError("expected list element");
241 consumeToken(rightToken);
242 return ParseSuccess;
243 }
244
Chris Lattnerf7702a62018-07-23 17:30:01 -0700245 if (parseCommaSeparatedList(parseElement) ||
246 parseToken(rightToken, "expected ',' or '" +
247 Token::getTokenSpelling(rightToken) + "'"))
Chris Lattner40746442018-07-21 14:32:09 -0700248 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700249
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700250 return ParseSuccess;
251}
Chris Lattnere79379a2018-06-22 10:39:19 -0700252
253//===----------------------------------------------------------------------===//
254// Type Parsing
255//===----------------------------------------------------------------------===//
256
Chris Lattnerc3251192018-07-27 13:09:58 -0700257/// Parse an arbitrary type.
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700258///
Chris Lattnerc3251192018-07-27 13:09:58 -0700259/// type ::= integer-type
260/// | float-type
261/// | other-type
262/// | vector-type
263/// | tensor-type
264/// | memref-type
265/// | function-type
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700266///
Chris Lattnerc3251192018-07-27 13:09:58 -0700267/// float-type ::= `f16` | `bf16` | `f32` | `f64`
268/// other-type ::= `affineint` | `tf_control`
269///
270Type *Parser::parseType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700271 switch (getToken().getKind()) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700272 default:
273 return (emitError("expected type"), nullptr);
Chris Lattnerc3251192018-07-27 13:09:58 -0700274 case Token::kw_memref:
275 return parseMemRefType();
276 case Token::kw_tensor:
277 return parseTensorType();
278 case Token::kw_vector:
279 return parseVectorType();
280 case Token::l_paren:
281 return parseFunctionType();
282 // integer-type
283 case Token::inttype: {
284 auto width = getToken().getIntTypeBitwidth();
285 if (!width.hasValue())
286 return (emitError("invalid integer width"), nullptr);
287 consumeToken(Token::inttype);
288 return builder.getIntegerType(width.getValue());
289 }
290
291 // float-type
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700292 case Token::kw_bf16:
293 consumeToken(Token::kw_bf16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700294 return builder.getBF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700295 case Token::kw_f16:
296 consumeToken(Token::kw_f16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700297 return builder.getF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700298 case Token::kw_f32:
299 consumeToken(Token::kw_f32);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700300 return builder.getF32Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700301 case Token::kw_f64:
302 consumeToken(Token::kw_f64);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700303 return builder.getF64Type();
Chris Lattnerc3251192018-07-27 13:09:58 -0700304
305 // other-type
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700306 case Token::kw_affineint:
307 consumeToken(Token::kw_affineint);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700308 return builder.getAffineIntType();
Jacques Pienaarc0d69302018-07-27 11:07:12 -0700309 case Token::kw_tf_control:
310 consumeToken(Token::kw_tf_control);
311 return builder.getTFControlType();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700312 }
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700313}
314
315/// Parse a vector type.
316///
317/// vector-type ::= `vector` `<` const-dimension-list primitive-type `>`
318/// const-dimension-list ::= (integer-literal `x`)+
319///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700320VectorType *Parser::parseVectorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700321 consumeToken(Token::kw_vector);
322
Chris Lattnerf7702a62018-07-23 17:30:01 -0700323 if (parseToken(Token::less, "expected '<' in vector type"))
324 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700325
Chris Lattner48af7d12018-07-09 19:05:38 -0700326 if (getToken().isNot(Token::integer))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700327 return (emitError("expected dimension size in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700328
329 SmallVector<unsigned, 4> dimensions;
Chris Lattner48af7d12018-07-09 19:05:38 -0700330 while (getToken().is(Token::integer)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700331 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700332 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700333 if (!dimension.hasValue())
Chris Lattnerf7e22732018-06-22 22:03:48 -0700334 return (emitError("invalid dimension in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700335 dimensions.push_back(dimension.getValue());
336
337 consumeToken(Token::integer);
338
339 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700340 if (getToken().isNot(Token::bare_identifier) ||
341 getTokenSpelling()[0] != 'x')
Chris Lattnerf7e22732018-06-22 22:03:48 -0700342 return (emitError("expected 'x' in vector dimension list"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700343
344 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700345 if (getTokenSpelling().size() != 1)
346 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700347
348 // Consume the 'x'.
349 consumeToken(Token::bare_identifier);
350 }
351
352 // Parse the element type.
Chris Lattnerc3251192018-07-27 13:09:58 -0700353 auto typeLoc = getToken().getLoc();
354 auto *elementType = parseType();
355 if (!elementType || parseToken(Token::greater, "expected '>' in vector type"))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700356 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700357
Chris Lattnerc3251192018-07-27 13:09:58 -0700358 if (!isa<FloatType>(elementType) && !isa<IntegerType>(elementType))
359 return (emitError(typeLoc, "invalid vector element type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700360
Chris Lattnerf7e22732018-06-22 22:03:48 -0700361 return VectorType::get(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700362}
363
364/// Parse a dimension list of a tensor or memref type. This populates the
365/// dimension list, returning -1 for the '?' dimensions.
366///
367/// dimension-list-ranked ::= (dimension `x`)*
368/// dimension ::= `?` | integer-literal
369///
370ParseResult Parser::parseDimensionListRanked(SmallVectorImpl<int> &dimensions) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700371 while (getToken().isAny(Token::integer, Token::question)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700372 if (consumeIf(Token::question)) {
373 dimensions.push_back(-1);
374 } else {
375 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700376 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700377 if (!dimension.hasValue() || (int)dimension.getValue() < 0)
378 return emitError("invalid dimension");
379 dimensions.push_back((int)dimension.getValue());
380 consumeToken(Token::integer);
381 }
382
383 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700384 if (getToken().isNot(Token::bare_identifier) ||
385 getTokenSpelling()[0] != 'x')
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700386 return emitError("expected 'x' in dimension list");
387
388 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700389 if (getTokenSpelling().size() != 1)
390 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700391
392 // Consume the 'x'.
393 consumeToken(Token::bare_identifier);
394 }
395
396 return ParseSuccess;
397}
398
399/// Parse a tensor type.
400///
401/// tensor-type ::= `tensor` `<` dimension-list element-type `>`
402/// dimension-list ::= dimension-list-ranked | `??`
403///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700404Type *Parser::parseTensorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700405 consumeToken(Token::kw_tensor);
406
Chris Lattnerf7702a62018-07-23 17:30:01 -0700407 if (parseToken(Token::less, "expected '<' in tensor type"))
408 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700409
410 bool isUnranked;
411 SmallVector<int, 4> dimensions;
412
413 if (consumeIf(Token::questionquestion)) {
414 isUnranked = true;
415 } else {
416 isUnranked = false;
417 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700418 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700419 }
420
421 // Parse the element type.
Chris Lattnerc3251192018-07-27 13:09:58 -0700422 auto typeLoc = getToken().getLoc();
423 auto *elementType = parseType();
424 if (!elementType || parseToken(Token::greater, "expected '>' in tensor type"))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700425 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700426
Chris Lattnerc3251192018-07-27 13:09:58 -0700427 if (!isa<IntegerType>(elementType) && !isa<FloatType>(elementType) &&
428 !isa<VectorType>(elementType))
429 return (emitError(typeLoc, "invalid tensor element type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700430
MLIR Team355ec862018-06-23 18:09:09 -0700431 if (isUnranked)
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700432 return builder.getTensorType(elementType);
433 return builder.getTensorType(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700434}
435
436/// Parse a memref type.
437///
438/// memref-type ::= `memref` `<` dimension-list-ranked element-type
439/// (`,` semi-affine-map-composition)? (`,` memory-space)? `>`
440///
441/// semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map
442/// memory-space ::= integer-literal /* | TODO: address-space-id */
443///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700444Type *Parser::parseMemRefType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700445 consumeToken(Token::kw_memref);
446
Chris Lattnerf7702a62018-07-23 17:30:01 -0700447 if (parseToken(Token::less, "expected '<' in memref type"))
448 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700449
450 SmallVector<int, 4> dimensions;
451 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700452 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700453
454 // Parse the element type.
Chris Lattnerc3251192018-07-27 13:09:58 -0700455 auto typeLoc = getToken().getLoc();
456 auto *elementType = parseType();
Chris Lattnerf7e22732018-06-22 22:03:48 -0700457 if (!elementType)
458 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700459
Chris Lattnerc3251192018-07-27 13:09:58 -0700460 if (!isa<IntegerType>(elementType) && !isa<FloatType>(elementType) &&
461 !isa<VectorType>(elementType))
462 return (emitError(typeLoc, "invalid memref element type"), nullptr);
463
MLIR Team718c82f2018-07-16 09:45:22 -0700464 // Parse semi-affine-map-composition.
James Molloy0ff71542018-07-23 16:56:32 -0700465 SmallVector<AffineMap *, 2> affineMapComposition;
Chris Lattner413db6a2018-07-25 12:55:50 -0700466 unsigned memorySpace = 0;
MLIR Team718c82f2018-07-16 09:45:22 -0700467 bool parsedMemorySpace = false;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700468
MLIR Team718c82f2018-07-16 09:45:22 -0700469 auto parseElt = [&]() -> ParseResult {
470 if (getToken().is(Token::integer)) {
471 // Parse memory space.
472 if (parsedMemorySpace)
473 return emitError("multiple memory spaces specified in memref type");
474 auto v = getToken().getUnsignedIntegerValue();
475 if (!v.hasValue())
476 return emitError("invalid memory space in memref type");
477 memorySpace = v.getValue();
478 consumeToken(Token::integer);
479 parsedMemorySpace = true;
480 } else {
481 // Parse affine map.
482 if (parsedMemorySpace)
483 return emitError("affine map after memory space in memref type");
James Molloy0ff71542018-07-23 16:56:32 -0700484 auto *affineMap = parseAffineMapReference();
MLIR Team718c82f2018-07-16 09:45:22 -0700485 if (affineMap == nullptr)
486 return ParseFailure;
487 affineMapComposition.push_back(affineMap);
488 }
489 return ParseSuccess;
490 };
491
Chris Lattner413db6a2018-07-25 12:55:50 -0700492 // Parse a list of mappings and address space if present.
493 if (consumeIf(Token::comma)) {
494 // Parse comma separated list of affine maps, followed by memory space.
495 if (parseCommaSeparatedListUntil(Token::greater, parseElt,
496 /*allowEmptyList=*/false)) {
497 return nullptr;
498 }
499 } else {
500 if (parseToken(Token::greater, "expected ',' or '>' in memref type"))
501 return nullptr;
MLIR Team718c82f2018-07-16 09:45:22 -0700502 }
MLIR Team718c82f2018-07-16 09:45:22 -0700503
504 return MemRefType::get(dimensions, elementType, affineMapComposition,
505 memorySpace);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700506}
507
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700508/// Parse a function type.
509///
510/// function-type ::= type-list-parens `->` type-list
511///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700512Type *Parser::parseFunctionType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700513 assert(getToken().is(Token::l_paren));
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700514
Chris Lattnerf7702a62018-07-23 17:30:01 -0700515 SmallVector<Type *, 4> arguments, results;
516 if (parseTypeList(arguments) ||
517 parseToken(Token::arrow, "expected '->' in function type") ||
518 parseTypeList(results))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700519 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700520
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700521 return builder.getFunctionType(arguments, results);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700522}
523
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700524
Chris Lattner1604e472018-07-23 08:42:19 -0700525/// Parse a list of types without an enclosing parenthesis. The list must have
526/// at least one member.
527///
528/// type-list-no-parens ::= type (`,` type)*
529///
530ParseResult Parser::parseTypeListNoParens(SmallVectorImpl<Type *> &elements) {
531 auto parseElt = [&]() -> ParseResult {
532 auto elt = parseType();
533 elements.push_back(elt);
534 return elt ? ParseSuccess : ParseFailure;
535 };
536
537 return parseCommaSeparatedList(parseElt);
538}
539
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700540/// Parse a "type list", which is a singular type, or a parenthesized list of
541/// types.
542///
543/// type-list ::= type-list-parens | type
544/// type-list-parens ::= `(` `)`
Chris Lattner1604e472018-07-23 08:42:19 -0700545/// | `(` type-list-no-parens `)`
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700546///
James Molloy0ff71542018-07-23 16:56:32 -0700547ParseResult Parser::parseTypeList(SmallVectorImpl<Type *> &elements) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700548 auto parseElt = [&]() -> ParseResult {
549 auto elt = parseType();
550 elements.push_back(elt);
551 return elt ? ParseSuccess : ParseFailure;
552 };
553
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700554 // If there is no parens, then it must be a singular type.
555 if (!consumeIf(Token::l_paren))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700556 return parseElt();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700557
Chris Lattner40746442018-07-21 14:32:09 -0700558 if (parseCommaSeparatedListUntil(Token::r_paren, parseElt))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700559 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700560
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700561 return ParseSuccess;
562}
563
Chris Lattner4c95a502018-06-23 16:03:42 -0700564//===----------------------------------------------------------------------===//
Chris Lattner7121b802018-07-04 20:45:39 -0700565// Attribute parsing.
566//===----------------------------------------------------------------------===//
567
Chris Lattner7121b802018-07-04 20:45:39 -0700568/// Attribute parsing.
569///
570/// attribute-value ::= bool-literal
571/// | integer-literal
572/// | float-literal
573/// | string-literal
574/// | `[` (attribute-value (`,` attribute-value)*)? `]`
575///
576Attribute *Parser::parseAttribute() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700577 switch (getToken().getKind()) {
Chris Lattner7121b802018-07-04 20:45:39 -0700578 case Token::kw_true:
579 consumeToken(Token::kw_true);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700580 return builder.getBoolAttr(true);
Chris Lattner7121b802018-07-04 20:45:39 -0700581 case Token::kw_false:
582 consumeToken(Token::kw_false);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700583 return builder.getBoolAttr(false);
Chris Lattner7121b802018-07-04 20:45:39 -0700584
Jacques Pienaar84491092018-07-31 17:15:15 -0700585 case Token::floatliteral: {
586 auto val = getToken().getFloatingPointValue();
587 if (!val.hasValue())
588 return (emitError("floating point value too large for attribute"),
589 nullptr);
590 consumeToken(Token::floatliteral);
591 return builder.getFloatAttr(val.getValue());
592 }
Chris Lattner7121b802018-07-04 20:45:39 -0700593 case Token::integer: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700594 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700595 if (!val.hasValue() || (int64_t)val.getValue() < 0)
596 return (emitError("integer too large for attribute"), nullptr);
597 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700598 return builder.getIntegerAttr((int64_t)val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700599 }
600
601 case Token::minus: {
602 consumeToken(Token::minus);
Chris Lattner48af7d12018-07-09 19:05:38 -0700603 if (getToken().is(Token::integer)) {
604 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700605 if (!val.hasValue() || (int64_t)-val.getValue() >= 0)
606 return (emitError("integer too large for attribute"), nullptr);
607 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700608 return builder.getIntegerAttr((int64_t)-val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700609 }
Jacques Pienaar84491092018-07-31 17:15:15 -0700610 if (getToken().is(Token::floatliteral)) {
611 auto val = getToken().getFloatingPointValue();
612 if (!val.hasValue())
613 return (emitError("floating point value too large for attribute"),
614 nullptr);
615 consumeToken(Token::floatliteral);
616 return builder.getFloatAttr(-val.getValue());
617 }
Chris Lattner7121b802018-07-04 20:45:39 -0700618
619 return (emitError("expected constant integer or floating point value"),
620 nullptr);
621 }
622
623 case Token::string: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700624 auto val = getToken().getStringValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700625 consumeToken(Token::string);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700626 return builder.getStringAttr(val);
Chris Lattner7121b802018-07-04 20:45:39 -0700627 }
628
Chris Lattner85ee1512018-07-25 11:15:20 -0700629 case Token::l_square: {
630 consumeToken(Token::l_square);
James Molloy0ff71542018-07-23 16:56:32 -0700631 SmallVector<Attribute *, 4> elements;
Chris Lattner7121b802018-07-04 20:45:39 -0700632
633 auto parseElt = [&]() -> ParseResult {
634 elements.push_back(parseAttribute());
635 return elements.back() ? ParseSuccess : ParseFailure;
636 };
637
Chris Lattner85ee1512018-07-25 11:15:20 -0700638 if (parseCommaSeparatedListUntil(Token::r_square, parseElt))
Chris Lattner7121b802018-07-04 20:45:39 -0700639 return nullptr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700640 return builder.getArrayAttr(elements);
Chris Lattner7121b802018-07-04 20:45:39 -0700641 }
642 default:
MLIR Teamb61885d2018-07-18 16:29:21 -0700643 // Try to parse affine map reference.
James Molloy0ff71542018-07-23 16:56:32 -0700644 auto *affineMap = parseAffineMapReference();
MLIR Teamb61885d2018-07-18 16:29:21 -0700645 if (affineMap != nullptr)
646 return builder.getAffineMapAttr(affineMap);
647
Chris Lattner7121b802018-07-04 20:45:39 -0700648 return (emitError("expected constant attribute value"), nullptr);
649 }
650}
651
Chris Lattner7121b802018-07-04 20:45:39 -0700652/// Attribute dictionary.
653///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700654/// attribute-dict ::= `{` `}`
655/// | `{` attribute-entry (`,` attribute-entry)* `}`
656/// attribute-entry ::= bare-id `:` attribute-value
Chris Lattner7121b802018-07-04 20:45:39 -0700657///
James Molloy0ff71542018-07-23 16:56:32 -0700658ParseResult
659Parser::parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes) {
Chris Lattner7121b802018-07-04 20:45:39 -0700660 consumeToken(Token::l_brace);
661
662 auto parseElt = [&]() -> ParseResult {
663 // We allow keywords as attribute names.
Chris Lattner48af7d12018-07-09 19:05:38 -0700664 if (getToken().isNot(Token::bare_identifier, Token::inttype) &&
665 !getToken().isKeyword())
Chris Lattner7121b802018-07-04 20:45:39 -0700666 return emitError("expected attribute name");
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700667 auto nameId = builder.getIdentifier(getTokenSpelling());
Chris Lattner7121b802018-07-04 20:45:39 -0700668 consumeToken();
669
Chris Lattnerf7702a62018-07-23 17:30:01 -0700670 if (parseToken(Token::colon, "expected ':' in attribute list"))
671 return ParseFailure;
Chris Lattner7121b802018-07-04 20:45:39 -0700672
673 auto attr = parseAttribute();
James Molloy0ff71542018-07-23 16:56:32 -0700674 if (!attr)
675 return ParseFailure;
Chris Lattner7121b802018-07-04 20:45:39 -0700676
677 attributes.push_back({nameId, attr});
678 return ParseSuccess;
679 };
680
Chris Lattner40746442018-07-21 14:32:09 -0700681 if (parseCommaSeparatedListUntil(Token::r_brace, parseElt))
Chris Lattner7121b802018-07-04 20:45:39 -0700682 return ParseFailure;
683
684 return ParseSuccess;
685}
686
687//===----------------------------------------------------------------------===//
MLIR Teamf85a6262018-06-27 11:03:08 -0700688// Polyhedral structures.
689//===----------------------------------------------------------------------===//
690
Chris Lattner2e595eb2018-07-10 10:08:27 -0700691/// Lower precedence ops (all at the same precedence level). LNoOp is false in
692/// the boolean sense.
693enum AffineLowPrecOp {
694 /// Null value.
695 LNoOp,
696 Add,
697 Sub
698};
MLIR Teamf85a6262018-06-27 11:03:08 -0700699
Chris Lattner2e595eb2018-07-10 10:08:27 -0700700/// Higher precedence ops - all at the same precedence level. HNoOp is false in
701/// the boolean sense.
702enum AffineHighPrecOp {
703 /// Null value.
704 HNoOp,
705 Mul,
706 FloorDiv,
707 CeilDiv,
708 Mod
709};
Chris Lattner7121b802018-07-04 20:45:39 -0700710
Chris Lattner2e595eb2018-07-10 10:08:27 -0700711namespace {
712/// This is a specialized parser for AffineMap's, maintaining the state
713/// transient to their bodies.
714class AffineMapParser : public Parser {
715public:
716 explicit AffineMapParser(ParserState &state) : Parser(state) {}
Chris Lattner7121b802018-07-04 20:45:39 -0700717
Chris Lattner2e595eb2018-07-10 10:08:27 -0700718 AffineMap *parseAffineMapInline();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700719
Chris Lattner2e595eb2018-07-10 10:08:27 -0700720private:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700721 // Binary affine op parsing.
722 AffineLowPrecOp consumeIfLowPrecOp();
723 AffineHighPrecOp consumeIfHighPrecOp();
MLIR Teamf85a6262018-06-27 11:03:08 -0700724
Chris Lattner2e595eb2018-07-10 10:08:27 -0700725 // Identifier lists for polyhedral structures.
Chris Lattner413db6a2018-07-25 12:55:50 -0700726 ParseResult parseDimIdList(unsigned &numDims);
727 ParseResult parseSymbolIdList(unsigned &numSymbols);
728 ParseResult parseIdentifierDefinition(AffineExpr *idExpr);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700729
730 AffineExpr *parseAffineExpr();
731 AffineExpr *parseParentheticalExpr();
732 AffineExpr *parseNegateExpression(AffineExpr *lhs);
733 AffineExpr *parseIntegerExpr();
734 AffineExpr *parseBareIdExpr();
735
736 AffineExpr *getBinaryAffineOpExpr(AffineHighPrecOp op, AffineExpr *lhs,
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700737 AffineExpr *rhs, SMLoc opLoc);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700738 AffineExpr *getBinaryAffineOpExpr(AffineLowPrecOp op, AffineExpr *lhs,
739 AffineExpr *rhs);
740 AffineExpr *parseAffineOperandExpr(AffineExpr *lhs);
741 AffineExpr *parseAffineLowPrecOpExpr(AffineExpr *llhs,
742 AffineLowPrecOp llhsOp);
743 AffineExpr *parseAffineHighPrecOpExpr(AffineExpr *llhs,
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700744 AffineHighPrecOp llhsOp,
745 SMLoc llhsOpLoc);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700746
747private:
Chris Lattner413db6a2018-07-25 12:55:50 -0700748 SmallVector<std::pair<StringRef, AffineExpr *>, 4> dimsAndSymbols;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700749};
750} // end anonymous namespace
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700751
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700752/// Create an affine binary high precedence op expression (mul's, div's, mod).
753/// opLoc is the location of the op token to be used to report errors
754/// for non-conforming expressions.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700755AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineHighPrecOp op,
756 AffineExpr *lhs,
Chris Lattner40746442018-07-21 14:32:09 -0700757 AffineExpr *rhs,
758 SMLoc opLoc) {
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700759 // TODO: make the error location info accurate.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700760 switch (op) {
761 case Mul:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700762 if (!lhs->isSymbolicOrConstant() && !rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700763 emitError(opLoc, "non-affine expression: at least one of the multiply "
764 "operands has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700765 return nullptr;
766 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700767 return builder.getMulExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700768 case FloorDiv:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700769 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700770 emitError(opLoc, "non-affine expression: right operand of floordiv "
771 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700772 return nullptr;
773 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700774 return builder.getFloorDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700775 case CeilDiv:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700776 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700777 emitError(opLoc, "non-affine expression: right operand of ceildiv "
778 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700779 return nullptr;
780 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700781 return builder.getCeilDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700782 case Mod:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700783 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700784 emitError(opLoc, "non-affine expression: right operand of mod "
785 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700786 return nullptr;
787 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700788 return builder.getModExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700789 case HNoOp:
790 llvm_unreachable("can't create affine expression for null high prec op");
791 return nullptr;
792 }
793}
794
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700795/// Create an affine binary low precedence op expression (add, sub).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700796AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineLowPrecOp op,
797 AffineExpr *lhs,
798 AffineExpr *rhs) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700799 switch (op) {
800 case AffineLowPrecOp::Add:
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700801 return builder.getAddExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700802 case AffineLowPrecOp::Sub:
Uday Bondhugulac1faf662018-07-19 14:08:50 -0700803 return builder.getAddExpr(
804 lhs, builder.getMulExpr(rhs, builder.getConstantExpr(-1)));
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700805 case AffineLowPrecOp::LNoOp:
806 llvm_unreachable("can't create affine expression for null low prec op");
807 return nullptr;
808 }
809}
810
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700811/// Consume this token if it is a lower precedence affine op (there are only two
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700812/// precedence levels).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700813AffineLowPrecOp AffineMapParser::consumeIfLowPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700814 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700815 case Token::plus:
816 consumeToken(Token::plus);
817 return AffineLowPrecOp::Add;
818 case Token::minus:
819 consumeToken(Token::minus);
820 return AffineLowPrecOp::Sub;
821 default:
822 return AffineLowPrecOp::LNoOp;
823 }
824}
825
826/// Consume this token if it is a higher precedence affine op (there are only
827/// two precedence levels)
Chris Lattner2e595eb2018-07-10 10:08:27 -0700828AffineHighPrecOp AffineMapParser::consumeIfHighPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700829 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700830 case Token::star:
831 consumeToken(Token::star);
832 return Mul;
833 case Token::kw_floordiv:
834 consumeToken(Token::kw_floordiv);
835 return FloorDiv;
836 case Token::kw_ceildiv:
837 consumeToken(Token::kw_ceildiv);
838 return CeilDiv;
839 case Token::kw_mod:
840 consumeToken(Token::kw_mod);
841 return Mod;
842 default:
843 return HNoOp;
844 }
845}
846
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700847/// Parse a high precedence op expression list: mul, div, and mod are high
848/// precedence binary ops, i.e., parse a
849/// expr_1 op_1 expr_2 op_2 ... expr_n
850/// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
851/// All affine binary ops are left associative.
852/// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
853/// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700854/// null. llhsOpLoc is the location of the llhsOp token that will be used to
855/// report an error for non-conforming expressions.
856AffineExpr *AffineMapParser::parseAffineHighPrecOpExpr(AffineExpr *llhs,
857 AffineHighPrecOp llhsOp,
858 SMLoc llhsOpLoc) {
Chris Lattner2e595eb2018-07-10 10:08:27 -0700859 AffineExpr *lhs = parseAffineOperandExpr(llhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700860 if (!lhs)
861 return nullptr;
862
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700863 // Found an LHS. Parse the remaining expression.
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700864 auto opLoc = getToken().getLoc();
Chris Lattner2e595eb2018-07-10 10:08:27 -0700865 if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700866 if (llhs) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700867 AffineExpr *expr = getBinaryAffineOpExpr(llhsOp, llhs, lhs, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700868 if (!expr)
869 return nullptr;
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700870 return parseAffineHighPrecOpExpr(expr, op, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700871 }
872 // No LLHS, get RHS
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700873 return parseAffineHighPrecOpExpr(lhs, op, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700874 }
875
876 // This is the last operand in this expression.
877 if (llhs)
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700878 return getBinaryAffineOpExpr(llhsOp, llhs, lhs, llhsOpLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700879
880 // No llhs, 'lhs' itself is the expression.
881 return lhs;
882}
883
884/// Parse an affine expression inside parentheses.
885///
886/// affine-expr ::= `(` affine-expr `)`
Chris Lattner2e595eb2018-07-10 10:08:27 -0700887AffineExpr *AffineMapParser::parseParentheticalExpr() {
Chris Lattnerf7702a62018-07-23 17:30:01 -0700888 if (parseToken(Token::l_paren, "expected '('"))
889 return nullptr;
Chris Lattner48af7d12018-07-09 19:05:38 -0700890 if (getToken().is(Token::r_paren))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700891 return (emitError("no expression inside parentheses"), nullptr);
Chris Lattnerf7702a62018-07-23 17:30:01 -0700892
Chris Lattner2e595eb2018-07-10 10:08:27 -0700893 auto *expr = parseAffineExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700894 if (!expr)
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700895 return nullptr;
Chris Lattnerf7702a62018-07-23 17:30:01 -0700896 if (parseToken(Token::r_paren, "expected ')'"))
897 return nullptr;
898
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700899 return expr;
900}
901
902/// Parse the negation expression.
903///
904/// affine-expr ::= `-` affine-expr
Chris Lattner2e595eb2018-07-10 10:08:27 -0700905AffineExpr *AffineMapParser::parseNegateExpression(AffineExpr *lhs) {
Chris Lattnerf7702a62018-07-23 17:30:01 -0700906 if (parseToken(Token::minus, "expected '-'"))
907 return nullptr;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700908
Chris Lattner2e595eb2018-07-10 10:08:27 -0700909 AffineExpr *operand = parseAffineOperandExpr(lhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700910 // Since negation has the highest precedence of all ops (including high
911 // precedence ops) but lower than parentheses, we are only going to use
912 // parseAffineOperandExpr instead of parseAffineExpr here.
913 if (!operand)
914 // Extra error message although parseAffineOperandExpr would have
915 // complained. Leads to a better diagnostic.
916 return (emitError("missing operand of negation"), nullptr);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700917 auto *minusOne = builder.getConstantExpr(-1);
918 return builder.getMulExpr(minusOne, operand);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700919}
920
921/// Parse a bare id that may appear in an affine expression.
922///
923/// affine-expr ::= bare-id
Chris Lattner2e595eb2018-07-10 10:08:27 -0700924AffineExpr *AffineMapParser::parseBareIdExpr() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700925 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700926 return (emitError("expected bare identifier"), nullptr);
927
Chris Lattner48af7d12018-07-09 19:05:38 -0700928 StringRef sRef = getTokenSpelling();
Chris Lattner413db6a2018-07-25 12:55:50 -0700929 for (auto entry : dimsAndSymbols) {
Chris Lattnera8e47672018-07-25 14:08:16 -0700930 if (entry.first == sRef) {
931 consumeToken(Token::bare_identifier);
932 return entry.second;
933 }
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700934 }
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700935
936 return (emitError("use of undeclared identifier"), nullptr);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700937}
938
939/// Parse a positive integral constant appearing in an affine expression.
940///
941/// affine-expr ::= integer-literal
Chris Lattner2e595eb2018-07-10 10:08:27 -0700942AffineExpr *AffineMapParser::parseIntegerExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700943 // No need to handle negative numbers separately here. They are naturally
944 // handled via the unary negation operator, although (FIXME) MININT_64 still
945 // not correctly handled.
Chris Lattner48af7d12018-07-09 19:05:38 -0700946 if (getToken().isNot(Token::integer))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700947 return (emitError("expected integer"), nullptr);
948
Chris Lattner48af7d12018-07-09 19:05:38 -0700949 auto val = getToken().getUInt64IntegerValue();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700950 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
951 return (emitError("constant too large for affineint"), nullptr);
952 }
953 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700954 return builder.getConstantExpr((int64_t)val.getValue());
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700955}
956
957/// Parses an expression that can be a valid operand of an affine expression.
Uday Bondhugula76345202018-07-09 13:47:52 -0700958/// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
959/// operator, the rhs of which is being parsed. This is used to determine
960/// whether an error should be emitted for a missing right operand.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700961// Eg: for an expression without parentheses (like i + j + k + l), each
962// of the four identifiers is an operand. For i + j*k + l, j*k is not an
963// operand expression, it's an op expression and will be parsed via
964// parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and -l
965// are valid operands that will be parsed by this function.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700966AffineExpr *AffineMapParser::parseAffineOperandExpr(AffineExpr *lhs) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700967 switch (getToken().getKind()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700968 case Token::bare_identifier:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700969 return parseBareIdExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700970 case Token::integer:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700971 return parseIntegerExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700972 case Token::l_paren:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700973 return parseParentheticalExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700974 case Token::minus:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700975 return parseNegateExpression(lhs);
Uday Bondhugula76345202018-07-09 13:47:52 -0700976 case Token::kw_ceildiv:
977 case Token::kw_floordiv:
978 case Token::kw_mod:
979 case Token::plus:
980 case Token::star:
981 if (lhs)
982 emitError("missing right operand of binary operator");
983 else
984 emitError("missing left operand of binary operator");
985 return nullptr;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700986 default:
987 if (lhs)
Uday Bondhugula76345202018-07-09 13:47:52 -0700988 emitError("missing right operand of binary operator");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700989 else
990 emitError("expected affine expression");
991 return nullptr;
992 }
993}
994
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700995/// Parse affine expressions that are bare-id's, integer constants,
996/// parenthetical affine expressions, and affine op expressions that are a
997/// composition of those.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700998///
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700999/// All binary op's associate from left to right.
1000///
1001/// {add, sub} have lower precedence than {mul, div, and mod}.
1002///
Uday Bondhugula76345202018-07-09 13:47:52 -07001003/// Add, sub'are themselves at the same precedence level. Mul, floordiv,
1004/// ceildiv, and mod are at the same higher precedence level. Negation has
1005/// higher precedence than any binary op.
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001006///
1007/// llhs: the affine expression appearing on the left of the one being parsed.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001008/// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
1009/// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned if
1010/// llhs is non-null; otherwise lhs is returned. This is to deal with left
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001011/// associativity.
1012///
1013/// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001014/// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where (e2*e3)
1015/// will be parsed using parseAffineHighPrecOpExpr().
Chris Lattner2e595eb2018-07-10 10:08:27 -07001016AffineExpr *AffineMapParser::parseAffineLowPrecOpExpr(AffineExpr *llhs,
1017 AffineLowPrecOp llhsOp) {
Uday Bondhugula76345202018-07-09 13:47:52 -07001018 AffineExpr *lhs;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001019 if (!(lhs = parseAffineOperandExpr(llhs)))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001020 return nullptr;
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001021
1022 // Found an LHS. Deal with the ops.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001023 if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001024 if (llhs) {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001025 AffineExpr *sum = getBinaryAffineOpExpr(llhsOp, llhs, lhs);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001026 return parseAffineLowPrecOpExpr(sum, lOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001027 }
1028 // No LLHS, get RHS and form the expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001029 return parseAffineLowPrecOpExpr(lhs, lOp);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001030 }
Uday Bondhugula851b8fd2018-07-20 14:57:21 -07001031 auto opLoc = getToken().getLoc();
Chris Lattner2e595eb2018-07-10 10:08:27 -07001032 if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001033 // We have a higher precedence op here. Get the rhs operand for the llhs
1034 // through parseAffineHighPrecOpExpr.
Uday Bondhugula851b8fd2018-07-20 14:57:21 -07001035 AffineExpr *highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001036 if (!highRes)
1037 return nullptr;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001038
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001039 // If llhs is null, the product forms the first operand of the yet to be
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001040 // found expression. If non-null, the op to associate with llhs is llhsOp.
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001041 AffineExpr *expr =
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001042 llhs ? getBinaryAffineOpExpr(llhsOp, llhs, highRes) : highRes;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001043
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001044 // Recurse for subsequent low prec op's after the affine high prec op
1045 // expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001046 if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
1047 return parseAffineLowPrecOpExpr(expr, nextOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001048 return expr;
1049 }
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001050 // Last operand in the expression list.
1051 if (llhs)
1052 return getBinaryAffineOpExpr(llhsOp, llhs, lhs);
1053 // No llhs, 'lhs' itself is the expression.
1054 return lhs;
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001055}
1056
1057/// Parse an affine expression.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001058/// affine-expr ::= `(` affine-expr `)`
1059/// | `-` affine-expr
1060/// | affine-expr `+` affine-expr
1061/// | affine-expr `-` affine-expr
1062/// | affine-expr `*` affine-expr
1063/// | affine-expr `floordiv` affine-expr
1064/// | affine-expr `ceildiv` affine-expr
1065/// | affine-expr `mod` affine-expr
1066/// | bare-id
1067/// | integer-literal
1068///
1069/// Additional conditions are checked depending on the production. For eg., one
1070/// of the operands for `*` has to be either constant/symbolic; the second
1071/// operand for floordiv, ceildiv, and mod has to be a positive integer.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001072AffineExpr *AffineMapParser::parseAffineExpr() {
1073 return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001074}
1075
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001076/// Parse a dim or symbol from the lists appearing before the actual expressions
Chris Lattner2e595eb2018-07-10 10:08:27 -07001077/// of the affine map. Update our state to store the dimensional/symbolic
Chris Lattner413db6a2018-07-25 12:55:50 -07001078/// identifier.
1079ParseResult AffineMapParser::parseIdentifierDefinition(AffineExpr *idExpr) {
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 Lattner413db6a2018-07-25 12:55:50 -07001082
1083 auto name = getTokenSpelling();
1084 for (auto entry : dimsAndSymbols) {
1085 if (entry.first == name)
1086 return emitError("redefinition of identifier '" + Twine(name) + "'");
1087 }
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001088 consumeToken(Token::bare_identifier);
Chris Lattner413db6a2018-07-25 12:55:50 -07001089
1090 dimsAndSymbols.push_back({name, idExpr});
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001091 return ParseSuccess;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001092}
1093
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001094/// Parse the list of symbolic identifiers to an affine map.
Chris Lattner413db6a2018-07-25 12:55:50 -07001095ParseResult AffineMapParser::parseSymbolIdList(unsigned &numSymbols) {
1096 consumeToken(Token::l_square);
1097 auto parseElt = [&]() -> ParseResult {
1098 auto *symbol = AffineSymbolExpr::get(numSymbols++, getContext());
1099 return parseIdentifierDefinition(symbol);
1100 };
Chris Lattner85ee1512018-07-25 11:15:20 -07001101 return parseCommaSeparatedListUntil(Token::r_square, 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 Lattner413db6a2018-07-25 12:55:50 -07001105ParseResult AffineMapParser::parseDimIdList(unsigned &numDims) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07001106 if (parseToken(Token::l_paren,
1107 "expected '(' at start of dimensional identifiers list"))
1108 return ParseFailure;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001109
Chris Lattner413db6a2018-07-25 12:55:50 -07001110 auto parseElt = [&]() -> ParseResult {
1111 auto *dimension = AffineDimExpr::get(numDims++, getContext());
1112 return parseIdentifierDefinition(dimension);
1113 };
Chris Lattner40746442018-07-21 14:32:09 -07001114 return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001115}
1116
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001117/// Parse an affine map definition.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001118///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001119/// affine-map-inline ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
1120/// (`size` `(` dim-size (`,` dim-size)* `)`)?
1121/// dim-size ::= affine-expr | `min` `(` affine-expr ( `,` affine-expr)+ `)`
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001122///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001123/// multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
Chris Lattner2e595eb2018-07-10 10:08:27 -07001124AffineMap *AffineMapParser::parseAffineMapInline() {
Chris Lattner413db6a2018-07-25 12:55:50 -07001125 unsigned numDims = 0, numSymbols = 0;
1126
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001127 // List of dimensional identifiers.
Chris Lattner413db6a2018-07-25 12:55:50 -07001128 if (parseDimIdList(numDims))
Chris Lattner7121b802018-07-04 20:45:39 -07001129 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001130
1131 // Symbols are optional.
Chris Lattner85ee1512018-07-25 11:15:20 -07001132 if (getToken().is(Token::l_square)) {
Chris Lattner413db6a2018-07-25 12:55:50 -07001133 if (parseSymbolIdList(numSymbols))
Chris Lattner7121b802018-07-04 20:45:39 -07001134 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001135 }
Chris Lattnerf7702a62018-07-23 17:30:01 -07001136
1137 if (parseToken(Token::arrow, "expected '->' or '['") ||
1138 parseToken(Token::l_paren, "expected '(' at start of affine map range"))
Chris Lattner7121b802018-07-04 20:45:39 -07001139 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001140
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001141 SmallVector<AffineExpr *, 4> exprs;
1142 auto parseElt = [&]() -> ParseResult {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001143 auto *elt = parseAffineExpr();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001144 ParseResult res = elt ? ParseSuccess : ParseFailure;
1145 exprs.push_back(elt);
1146 return res;
1147 };
1148
1149 // Parse a multi-dimensional affine expression (a comma-separated list of 1-d
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001150 // affine expressions); the list cannot be empty.
1151 // Grammar: multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
Chris Lattner40746442018-07-21 14:32:09 -07001152 if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, false))
Chris Lattner7121b802018-07-04 20:45:39 -07001153 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001154
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001155 // Parse optional range sizes.
Uday Bondhugula1e500b42018-07-12 18:04:04 -07001156 // range-sizes ::= (`size` `(` dim-size (`,` dim-size)* `)`)?
1157 // dim-size ::= affine-expr | `min` `(` affine-expr (`,` affine-expr)+ `)`
1158 // TODO(bondhugula): support for min of several affine expressions.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001159 // TODO: check if sizes are non-negative whenever they are constant.
1160 SmallVector<AffineExpr *, 4> rangeSizes;
1161 if (consumeIf(Token::kw_size)) {
1162 // Location of the l_paren token (if it exists) for error reporting later.
1163 auto loc = getToken().getLoc();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001164 if (parseToken(Token::l_paren, "expected '(' at start of affine map range"))
1165 return nullptr;
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001166
1167 auto parseRangeSize = [&]() -> ParseResult {
Chris Lattner413db6a2018-07-25 12:55:50 -07001168 auto loc = getToken().getLoc();
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001169 auto *elt = parseAffineExpr();
Chris Lattner413db6a2018-07-25 12:55:50 -07001170 if (!elt)
1171 return ParseFailure;
1172
1173 if (!elt->isSymbolicOrConstant())
1174 return emitError(loc,
1175 "size expressions cannot refer to dimension values");
1176
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001177 rangeSizes.push_back(elt);
Chris Lattner413db6a2018-07-25 12:55:50 -07001178 return ParseSuccess;
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001179 };
1180
Chris Lattner40746442018-07-21 14:32:09 -07001181 if (parseCommaSeparatedListUntil(Token::r_paren, parseRangeSize, false))
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001182 return nullptr;
1183 if (exprs.size() > rangeSizes.size())
1184 return (emitError(loc, "fewer range sizes than range expressions"),
1185 nullptr);
1186 if (exprs.size() < rangeSizes.size())
1187 return (emitError(loc, "more range sizes than range expressions"),
1188 nullptr);
1189 }
1190
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001191 // Parsed a valid affine map.
Chris Lattner413db6a2018-07-25 12:55:50 -07001192 return builder.getAffineMap(numDims, numSymbols, exprs, rangeSizes);
MLIR Teamf85a6262018-06-27 11:03:08 -07001193}
1194
Chris Lattner2e595eb2018-07-10 10:08:27 -07001195AffineMap *Parser::parseAffineMapInline() {
1196 return AffineMapParser(state).parseAffineMapInline();
1197}
1198
MLIR Team718c82f2018-07-16 09:45:22 -07001199AffineMap *Parser::parseAffineMapReference() {
1200 if (getToken().is(Token::hash_identifier)) {
1201 // Parse affine map identifier and verify that it exists.
1202 StringRef affineMapId = getTokenSpelling().drop_front();
1203 if (getState().affineMapDefinitions.count(affineMapId) == 0)
1204 return (emitError("undefined affine map id '" + affineMapId + "'"),
1205 nullptr);
1206 consumeToken(Token::hash_identifier);
1207 return getState().affineMapDefinitions[affineMapId];
1208 }
1209 // Try to parse inline affine map.
1210 return parseAffineMapInline();
1211}
1212
MLIR Teamf85a6262018-06-27 11:03:08 -07001213//===----------------------------------------------------------------------===//
Chris Lattner7f9cc272018-07-19 08:35:28 -07001214// FunctionParser
Chris Lattner4c95a502018-06-23 16:03:42 -07001215//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001216
Chris Lattner7f9cc272018-07-19 08:35:28 -07001217namespace {
1218/// This class contains parser state that is common across CFG and ML functions,
1219/// notably for dealing with operations and SSA values.
1220class FunctionParser : public Parser {
1221public:
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001222 enum class Kind { CFGFunc, MLFunc };
1223
1224 Kind getKind() const { return kind; }
Chris Lattner7f9cc272018-07-19 08:35:28 -07001225
Chris Lattner6119d382018-07-20 18:41:34 -07001226 /// After the function is finished parsing, this function checks to see if
1227 /// there are any remaining issues.
Chris Lattner40746442018-07-21 14:32:09 -07001228 ParseResult finalizeFunction(Function *func, SMLoc loc);
Chris Lattner6119d382018-07-20 18:41:34 -07001229
1230 /// This represents a use of an SSA value in the program. The first two
1231 /// entries in the tuple are the name and result number of a reference. The
1232 /// third is the location of the reference, which is used in case this ends up
1233 /// being a use of an undefined value.
1234 struct SSAUseInfo {
1235 StringRef name; // Value name, e.g. %42 or %abc
1236 unsigned number; // Number, specified with #12
1237 SMLoc loc; // Location of first definition or use.
1238 };
Chris Lattner7f9cc272018-07-19 08:35:28 -07001239
1240 /// Given a reference to an SSA value and its type, return a reference. This
1241 /// returns null on failure.
1242 SSAValue *resolveSSAUse(SSAUseInfo useInfo, Type *type);
1243
1244 /// Register a definition of a value with the symbol table.
1245 ParseResult addDefinition(SSAUseInfo useInfo, SSAValue *value);
1246
1247 // SSA parsing productions.
1248 ParseResult parseSSAUse(SSAUseInfo &result);
Chris Lattner40746442018-07-21 14:32:09 -07001249 ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
James Molloy61a656c2018-07-22 15:45:24 -07001250
1251 template <typename ResultType>
1252 ResultType parseSSADefOrUseAndType(
1253 const std::function<ResultType(SSAUseInfo, Type *)> &action);
1254
1255 SSAValue *parseSSAUseAndType() {
1256 return parseSSADefOrUseAndType<SSAValue *>(
1257 [&](SSAUseInfo useInfo, Type *type) -> SSAValue * {
1258 return resolveSSAUse(useInfo, type);
1259 });
1260 }
Chris Lattner40746442018-07-21 14:32:09 -07001261
1262 template <typename ValueTy>
Chris Lattner7f9cc272018-07-19 08:35:28 -07001263 ParseResult
Chris Lattner2c402672018-07-23 11:56:17 -07001264 parseOptionalSSAUseAndTypeList(SmallVectorImpl<ValueTy *> &results,
1265 bool isParenthesized);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001266
1267 // Operations
1268 ParseResult parseOperation(const CreateOperationFunction &createOpFunc);
Chris Lattner85ee1512018-07-25 11:15:20 -07001269 Operation *parseVerboseOperation(const CreateOperationFunction &createOpFunc);
1270 Operation *parseCustomOperation(const CreateOperationFunction &createOpFunc);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001271
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001272protected:
1273 FunctionParser(ParserState &state, Kind kind) : Parser(state), kind(kind) {}
1274
Chris Lattner7f9cc272018-07-19 08:35:28 -07001275private:
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001276 /// Kind indicates if this is CFG or ML function parser.
1277 Kind kind;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001278 /// This keeps track of all of the SSA values we are tracking, indexed by
Chris Lattner6119d382018-07-20 18:41:34 -07001279 /// their name. This has one entry per result number.
1280 llvm::StringMap<SmallVector<std::pair<SSAValue *, SMLoc>, 1>> values;
1281
1282 /// These are all of the placeholders we've made along with the location of
1283 /// their first reference, to allow checking for use of undefined values.
1284 DenseMap<SSAValue *, SMLoc> forwardReferencePlaceholders;
1285
1286 SSAValue *createForwardReferencePlaceholder(SMLoc loc, Type *type);
1287
1288 /// Return true if this is a forward reference.
1289 bool isForwardReferencePlaceholder(SSAValue *value) {
1290 return forwardReferencePlaceholders.count(value);
1291 }
Chris Lattner7f9cc272018-07-19 08:35:28 -07001292};
1293} // end anonymous namespace
1294
Chris Lattner6119d382018-07-20 18:41:34 -07001295/// Create and remember a new placeholder for a forward reference.
1296SSAValue *FunctionParser::createForwardReferencePlaceholder(SMLoc loc,
1297 Type *type) {
1298 // Forward references are always created as instructions, even in ML
1299 // functions, because we just need something with a def/use chain.
1300 //
1301 // We create these placeholders as having an empty name, which we know cannot
1302 // be created through normal user input, allowing us to distinguish them.
1303 auto name = Identifier::get("placeholder", getContext());
1304 auto *inst = OperationInst::create(name, /*operands*/ {}, type, /*attrs*/ {},
1305 getContext());
1306 forwardReferencePlaceholders[inst->getResult(0)] = loc;
1307 return inst->getResult(0);
1308}
1309
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001310/// Given an unbound reference to an SSA value and its type, return the value
Chris Lattner7f9cc272018-07-19 08:35:28 -07001311/// it specifies. This returns null on failure.
1312SSAValue *FunctionParser::resolveSSAUse(SSAUseInfo useInfo, Type *type) {
Chris Lattner6119d382018-07-20 18:41:34 -07001313 auto &entries = values[useInfo.name];
1314
Chris Lattner7f9cc272018-07-19 08:35:28 -07001315 // If we have already seen a value of this name, return it.
Chris Lattner6119d382018-07-20 18:41:34 -07001316 if (useInfo.number < entries.size() && entries[useInfo.number].first) {
1317 auto *result = entries[useInfo.number].first;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001318 // Check that the type matches the other uses.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001319 if (result->getType() == type)
1320 return result;
1321
Chris Lattner6119d382018-07-20 18:41:34 -07001322 emitError(useInfo.loc, "use of value '" + useInfo.name.str() +
1323 "' expects different type than prior uses");
1324 emitError(entries[useInfo.number].second, "prior use here");
Chris Lattner7f9cc272018-07-19 08:35:28 -07001325 return nullptr;
1326 }
1327
Chris Lattner6119d382018-07-20 18:41:34 -07001328 // Make sure we have enough slots for this.
1329 if (entries.size() <= useInfo.number)
1330 entries.resize(useInfo.number + 1);
1331
1332 // If the value has already been defined and this is an overly large result
1333 // number, diagnose that.
1334 if (entries[0].first && !isForwardReferencePlaceholder(entries[0].first))
1335 return (emitError(useInfo.loc, "reference to invalid result number"),
1336 nullptr);
1337
Tatiana Shpeismand880b352018-07-31 23:14:16 -07001338 // Otherwise, this is a forward reference. If we are in ML function return
1339 // an error. In CFG function, create a placeholder and remember
1340 // that we did so.
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001341 if (getKind() == Kind::MLFunc)
1342 return (
1343 emitError(useInfo.loc, "use of undefined SSA value " + useInfo.name),
1344 nullptr);
1345
Chris Lattner6119d382018-07-20 18:41:34 -07001346 auto *result = createForwardReferencePlaceholder(useInfo.loc, type);
1347 entries[useInfo.number].first = result;
1348 entries[useInfo.number].second = useInfo.loc;
1349 return result;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001350}
1351
1352/// Register a definition of a value with the symbol table.
1353ParseResult FunctionParser::addDefinition(SSAUseInfo useInfo, SSAValue *value) {
Chris Lattner6119d382018-07-20 18:41:34 -07001354 auto &entries = values[useInfo.name];
Chris Lattner7f9cc272018-07-19 08:35:28 -07001355
Chris Lattner6119d382018-07-20 18:41:34 -07001356 // Make sure there is a slot for this value.
1357 if (entries.size() <= useInfo.number)
1358 entries.resize(useInfo.number + 1);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001359
Chris Lattner6119d382018-07-20 18:41:34 -07001360 // If we already have an entry for this, check to see if it was a definition
1361 // or a forward reference.
1362 if (auto *existing = entries[useInfo.number].first) {
1363 if (!isForwardReferencePlaceholder(existing)) {
1364 emitError(useInfo.loc,
1365 "redefinition of SSA value '" + useInfo.name + "'");
1366 return emitError(entries[useInfo.number].second,
1367 "previously defined here");
1368 }
1369
1370 // If it was a forward reference, update everything that used it to use the
1371 // actual definition instead, delete the forward ref, and remove it from our
1372 // set of forward references we track.
1373 existing->replaceAllUsesWith(value);
1374 existing->getDefiningInst()->destroy();
1375 forwardReferencePlaceholders.erase(existing);
1376 }
1377
1378 entries[useInfo.number].first = value;
1379 entries[useInfo.number].second = useInfo.loc;
1380 return ParseSuccess;
1381}
1382
1383/// After the function is finished parsing, this function checks to see if
1384/// there are any remaining issues.
Chris Lattner40746442018-07-21 14:32:09 -07001385ParseResult FunctionParser::finalizeFunction(Function *func, SMLoc loc) {
Chris Lattner6119d382018-07-20 18:41:34 -07001386 // Check for any forward references that are left. If we find any, error out.
1387 if (!forwardReferencePlaceholders.empty()) {
1388 SmallVector<std::pair<const char *, SSAValue *>, 4> errors;
1389 // Iteration over the map isn't determinstic, so sort by source location.
1390 for (auto entry : forwardReferencePlaceholders)
1391 errors.push_back({entry.second.getPointer(), entry.first});
1392 llvm::array_pod_sort(errors.begin(), errors.end());
1393
1394 for (auto entry : errors)
1395 emitError(SMLoc::getFromPointer(entry.first),
1396 "use of undeclared SSA value name");
1397 return ParseFailure;
1398 }
1399
Chris Lattner40746442018-07-21 14:32:09 -07001400 // Run the verifier on this function. If an error is detected, report it.
1401 std::string errorString;
1402 if (func->verify(&errorString))
1403 return emitError(loc, errorString);
1404
Chris Lattner6119d382018-07-20 18:41:34 -07001405 return ParseSuccess;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001406}
1407
Chris Lattner78276e32018-07-07 15:48:26 -07001408/// Parse a SSA operand for an instruction or statement.
1409///
James Molloy61a656c2018-07-22 15:45:24 -07001410/// ssa-use ::= ssa-id
Chris Lattner78276e32018-07-07 15:48:26 -07001411///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001412ParseResult FunctionParser::parseSSAUse(SSAUseInfo &result) {
Chris Lattner6119d382018-07-20 18:41:34 -07001413 result.name = getTokenSpelling();
1414 result.number = 0;
1415 result.loc = getToken().getLoc();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001416 if (parseToken(Token::percent_identifier, "expected SSA operand"))
1417 return ParseFailure;
Chris Lattner6119d382018-07-20 18:41:34 -07001418
1419 // If we have an affine map ID, it is a result number.
1420 if (getToken().is(Token::hash_identifier)) {
1421 if (auto value = getToken().getHashIdentifierNumber())
1422 result.number = value.getValue();
1423 else
1424 return emitError("invalid SSA value result number");
1425 consumeToken(Token::hash_identifier);
1426 }
1427
Chris Lattner7f9cc272018-07-19 08:35:28 -07001428 return ParseSuccess;
Chris Lattner78276e32018-07-07 15:48:26 -07001429}
1430
1431/// Parse a (possibly empty) list of SSA operands.
1432///
1433/// ssa-use-list ::= ssa-use (`,` ssa-use)*
1434/// ssa-use-list-opt ::= ssa-use-list?
1435///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001436ParseResult
Chris Lattner40746442018-07-21 14:32:09 -07001437FunctionParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
Chris Lattner85ee1512018-07-25 11:15:20 -07001438 if (getToken().isNot(Token::percent_identifier))
Chris Lattner40746442018-07-21 14:32:09 -07001439 return ParseSuccess;
1440 return parseCommaSeparatedList([&]() -> ParseResult {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001441 SSAUseInfo result;
1442 if (parseSSAUse(result))
1443 return ParseFailure;
1444 results.push_back(result);
1445 return ParseSuccess;
1446 });
Chris Lattner78276e32018-07-07 15:48:26 -07001447}
1448
1449/// Parse an SSA use with an associated type.
1450///
1451/// ssa-use-and-type ::= ssa-use `:` type
James Molloy61a656c2018-07-22 15:45:24 -07001452template <typename ResultType>
1453ResultType FunctionParser::parseSSADefOrUseAndType(
1454 const std::function<ResultType(SSAUseInfo, Type *)> &action) {
Chris Lattner78276e32018-07-07 15:48:26 -07001455
Chris Lattnerf7702a62018-07-23 17:30:01 -07001456 SSAUseInfo useInfo;
1457 if (parseSSAUse(useInfo) ||
1458 parseToken(Token::colon, "expected ':' and type for SSA operand"))
1459 return nullptr;
Chris Lattner78276e32018-07-07 15:48:26 -07001460
Chris Lattner7f9cc272018-07-19 08:35:28 -07001461 auto *type = parseType();
1462 if (!type)
1463 return nullptr;
Chris Lattner78276e32018-07-07 15:48:26 -07001464
James Molloy61a656c2018-07-22 15:45:24 -07001465 return action(useInfo, type);
Chris Lattner78276e32018-07-07 15:48:26 -07001466}
1467
Chris Lattner2c402672018-07-23 11:56:17 -07001468/// Parse a (possibly empty) list of SSA operands, followed by a colon, then
1469/// followed by a type list. If hasParens is true, then the operands are
1470/// surrounded by parens.
Chris Lattner78276e32018-07-07 15:48:26 -07001471///
Chris Lattner2c402672018-07-23 11:56:17 -07001472/// ssa-use-and-type-list[parens]
1473/// ::= `(` ssa-use-list `)` ':' type-list-no-parens
1474///
1475/// ssa-use-and-type-list[!parens]
1476/// ::= ssa-use-list ':' type-list-no-parens
Chris Lattner78276e32018-07-07 15:48:26 -07001477///
Chris Lattner40746442018-07-21 14:32:09 -07001478template <typename ValueTy>
Chris Lattner7f9cc272018-07-19 08:35:28 -07001479ParseResult FunctionParser::parseOptionalSSAUseAndTypeList(
Chris Lattner2c402672018-07-23 11:56:17 -07001480 SmallVectorImpl<ValueTy *> &results, bool isParenthesized) {
1481
1482 // If we are in the parenthesized form and no paren exists, then we succeed
1483 // with an empty list.
1484 if (isParenthesized && !consumeIf(Token::l_paren))
Chris Lattner40746442018-07-21 14:32:09 -07001485 return ParseSuccess;
1486
Chris Lattner2c402672018-07-23 11:56:17 -07001487 SmallVector<SSAUseInfo, 4> valueIDs;
1488 if (parseOptionalSSAUseList(valueIDs))
Chris Lattner7f9cc272018-07-19 08:35:28 -07001489 return ParseFailure;
Chris Lattner2c402672018-07-23 11:56:17 -07001490
1491 if (isParenthesized && !consumeIf(Token::r_paren))
1492 return emitError("expected ')' in operand list");
1493
1494 // If there were no operands, then there is no colon or type lists.
1495 if (valueIDs.empty())
1496 return ParseSuccess;
1497
Chris Lattner2c402672018-07-23 11:56:17 -07001498 SmallVector<Type *, 4> types;
Chris Lattnerf7702a62018-07-23 17:30:01 -07001499 if (parseToken(Token::colon, "expected ':' in operand list") ||
1500 parseTypeListNoParens(types))
Chris Lattner2c402672018-07-23 11:56:17 -07001501 return ParseFailure;
1502
1503 if (valueIDs.size() != types.size())
1504 return emitError("expected " + Twine(valueIDs.size()) +
1505 " types to match operand list");
1506
1507 results.reserve(valueIDs.size());
1508 for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
1509 if (auto *value = resolveSSAUse(valueIDs[i], types[i]))
1510 results.push_back(cast<ValueTy>(value));
1511 else
1512 return ParseFailure;
1513 }
1514
1515 return ParseSuccess;
Chris Lattner78276e32018-07-07 15:48:26 -07001516}
1517
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001518/// Parse the CFG or MLFunc operation.
1519///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001520/// operation ::=
1521/// (ssa-id `=`)? string '(' ssa-use-list? ')' attribute-dict?
1522/// `:` function-type
1523///
1524ParseResult
Chris Lattner7f9cc272018-07-19 08:35:28 -07001525FunctionParser::parseOperation(const CreateOperationFunction &createOpFunc) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001526 auto loc = getToken().getLoc();
1527
1528 StringRef resultID;
1529 if (getToken().is(Token::percent_identifier)) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001530 resultID = getTokenSpelling();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001531 consumeToken(Token::percent_identifier);
Chris Lattnerf7702a62018-07-23 17:30:01 -07001532 if (parseToken(Token::equal, "expected '=' after SSA name"))
1533 return ParseFailure;
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001534 }
1535
Chris Lattner85ee1512018-07-25 11:15:20 -07001536 Operation *op;
1537 if (getToken().is(Token::bare_identifier) || getToken().isKeyword())
1538 op = parseCustomOperation(createOpFunc);
1539 else if (getToken().is(Token::string))
1540 op = parseVerboseOperation(createOpFunc);
1541 else
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001542 return emitError("expected operation name in quotes");
1543
Chris Lattner85ee1512018-07-25 11:15:20 -07001544 // If parsing of the basic operation failed, then this whole thing fails.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001545 if (!op)
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001546 return ParseFailure;
1547
1548 // We just parsed an operation. If it is a recognized one, verify that it
1549 // is structurally as we expect. If not, produce an error with a reasonable
1550 // source location.
Chris Lattner95865062018-08-01 10:18:59 -07001551 if (auto *opInfo = op->getAbstractOperation()) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001552 if (auto error = opInfo->verifyInvariants(op))
Chris Lattner9361fb32018-07-24 08:34:58 -07001553 return emitError(loc, Twine("'") + op->getName().str() + "' op " + error);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001554 }
1555
Chris Lattner7f9cc272018-07-19 08:35:28 -07001556 // If the instruction had a name, register it.
1557 if (!resultID.empty()) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001558 if (op->getNumResults() == 0)
1559 return emitError(loc, "cannot name an operation with no results");
Chris Lattner7f9cc272018-07-19 08:35:28 -07001560
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001561 for (unsigned i = 0, e = op->getNumResults(); i != e; ++i)
1562 addDefinition({resultID, i, loc}, op->getResult(i));
Chris Lattner7f9cc272018-07-19 08:35:28 -07001563 }
1564
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001565 return ParseSuccess;
1566}
Chris Lattnere79379a2018-06-22 10:39:19 -07001567
Chris Lattner85ee1512018-07-25 11:15:20 -07001568Operation *FunctionParser::parseVerboseOperation(
1569 const CreateOperationFunction &createOpFunc) {
1570 auto name = getToken().getStringValue();
1571 if (name.empty())
1572 return (emitError("empty operation name is invalid"), nullptr);
1573
1574 consumeToken(Token::string);
1575
1576 // Parse the operand list.
1577 SmallVector<SSAUseInfo, 8> operandInfos;
1578
1579 if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
1580 parseOptionalSSAUseList(operandInfos) ||
1581 parseToken(Token::r_paren, "expected ')' to end operand list")) {
1582 return nullptr;
1583 }
1584
1585 SmallVector<NamedAttribute, 4> attributes;
1586 if (getToken().is(Token::l_brace)) {
1587 if (parseAttributeDict(attributes))
1588 return nullptr;
1589 }
1590
1591 if (parseToken(Token::colon, "expected ':' followed by instruction type"))
1592 return nullptr;
1593
1594 auto typeLoc = getToken().getLoc();
1595 auto type = parseType();
1596 if (!type)
1597 return nullptr;
1598 auto fnType = dyn_cast<FunctionType>(type);
1599 if (!fnType)
1600 return (emitError(typeLoc, "expected function type"), nullptr);
1601
1602 // Check that we have the right number of types for the operands.
1603 auto operandTypes = fnType->getInputs();
1604 if (operandTypes.size() != operandInfos.size()) {
1605 auto plural = "s"[operandInfos.size() == 1];
1606 return (emitError(typeLoc, "expected " + llvm::utostr(operandInfos.size()) +
1607 " operand type" + plural + " but had " +
1608 llvm::utostr(operandTypes.size())),
1609 nullptr);
1610 }
1611
1612 // Resolve all of the operands.
1613 SmallVector<SSAValue *, 8> operands;
1614 for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
1615 operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
1616 if (!operands.back())
1617 return nullptr;
1618 }
1619
1620 auto nameId = builder.getIdentifier(name);
1621 return createOpFunc(nameId, operands, fnType->getResults(), attributes);
1622}
1623
1624namespace {
1625class CustomOpAsmParser : public OpAsmParser {
1626public:
1627 CustomOpAsmParser(SMLoc nameLoc, StringRef opName, FunctionParser &parser)
1628 : nameLoc(nameLoc), opName(opName), parser(parser) {}
1629
1630 /// This is an internal helper to parser a colon, we don't want to expose
1631 /// this to clients.
1632 bool internalParseColon(llvm::SMLoc *loc) {
1633 if (loc)
1634 *loc = parser.getToken().getLoc();
1635 return parser.parseToken(Token::colon, "expected ':'");
1636 }
1637
1638 //===--------------------------------------------------------------------===//
1639 // High level parsing methods.
1640 //===--------------------------------------------------------------------===//
1641
1642 bool parseComma(llvm::SMLoc *loc = nullptr) override {
1643 if (loc)
1644 *loc = parser.getToken().getLoc();
1645 return parser.parseToken(Token::comma, "expected ','");
1646 }
1647
1648 bool parseColonType(Type *&result, llvm::SMLoc *loc = nullptr) override {
1649 return internalParseColon(loc) || !(result = parser.parseType());
1650 }
1651
1652 bool parseColonTypeList(SmallVectorImpl<Type *> &result,
1653 llvm::SMLoc *loc = nullptr) override {
1654 if (internalParseColon(loc))
1655 return true;
1656
1657 do {
1658 if (auto *type = parser.parseType())
1659 result.push_back(type);
1660 else
1661 return true;
1662
1663 } while (parser.consumeIf(Token::comma));
1664 return false;
1665 }
1666
1667 bool parseAttribute(Attribute *&result, llvm::SMLoc *loc = nullptr) override {
1668 if (loc)
1669 *loc = parser.getToken().getLoc();
1670 result = parser.parseAttribute();
1671 return result == nullptr;
1672 }
1673
1674 bool parseOperand(OperandType &result) override {
1675 FunctionParser::SSAUseInfo useInfo;
1676 if (parser.parseSSAUse(useInfo))
1677 return true;
1678
1679 result = {useInfo.loc, useInfo.name, useInfo.number};
1680 return false;
1681 }
1682
1683 bool parseOperandList(SmallVectorImpl<OperandType> &result,
1684 int requiredOperandCount = -1,
1685 Delimeter delimeter = Delimeter::NoDelimeter) override {
1686 auto startLoc = parser.getToken().getLoc();
1687
1688 // Handle delimeters.
1689 switch (delimeter) {
1690 case Delimeter::NoDelimeter:
1691 break;
Chris Lattner3164ae62018-07-28 09:36:25 -07001692 case Delimeter::OptionalParenDelimeter:
1693 if (parser.getToken().isNot(Token::l_paren))
1694 return false;
1695 LLVM_FALLTHROUGH;
Chris Lattner85ee1512018-07-25 11:15:20 -07001696 case Delimeter::ParenDelimeter:
1697 if (parser.parseToken(Token::l_paren, "expected '(' in operand list"))
1698 return true;
1699 break;
Chris Lattner3164ae62018-07-28 09:36:25 -07001700 case Delimeter::OptionalSquareDelimeter:
1701 if (parser.getToken().isNot(Token::l_square))
1702 return false;
1703 LLVM_FALLTHROUGH;
Chris Lattner85ee1512018-07-25 11:15:20 -07001704 case Delimeter::SquareDelimeter:
1705 if (parser.parseToken(Token::l_square, "expected '[' in operand list"))
1706 return true;
1707 break;
1708 }
1709
1710 // Check for zero operands.
1711 if (parser.getToken().is(Token::percent_identifier)) {
1712 do {
1713 OperandType operand;
1714 if (parseOperand(operand))
1715 return true;
1716 result.push_back(operand);
1717 } while (parser.consumeIf(Token::comma));
1718 }
1719
Chris Lattner3164ae62018-07-28 09:36:25 -07001720 // Handle delimeters. If we reach here, the optional delimiters were
1721 // present, so we need to parse their closing one.
Chris Lattner85ee1512018-07-25 11:15:20 -07001722 switch (delimeter) {
1723 case Delimeter::NoDelimeter:
1724 break;
Chris Lattner3164ae62018-07-28 09:36:25 -07001725 case Delimeter::OptionalParenDelimeter:
Chris Lattner85ee1512018-07-25 11:15:20 -07001726 case Delimeter::ParenDelimeter:
1727 if (parser.parseToken(Token::r_paren, "expected ')' in operand list"))
1728 return true;
1729 break;
Chris Lattner3164ae62018-07-28 09:36:25 -07001730 case Delimeter::OptionalSquareDelimeter:
Chris Lattner85ee1512018-07-25 11:15:20 -07001731 case Delimeter::SquareDelimeter:
1732 if (parser.parseToken(Token::r_square, "expected ']' in operand list"))
1733 return true;
1734 break;
1735 }
1736
1737 if (requiredOperandCount != -1 && result.size() != requiredOperandCount)
1738 emitError(startLoc,
1739 "expected " + Twine(requiredOperandCount) + " operands");
1740 return false;
1741 }
1742
1743 //===--------------------------------------------------------------------===//
1744 // Methods for interacting with the parser
1745 //===--------------------------------------------------------------------===//
1746
1747 Builder &getBuilder() const override { return parser.builder; }
1748
1749 llvm::SMLoc getNameLoc() const override { return nameLoc; }
1750
1751 bool resolveOperand(OperandType operand, Type *type,
1752 SSAValue *&result) override {
1753 FunctionParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1754 operand.location};
1755 result = parser.resolveSSAUse(operandInfo, type);
1756 return result == nullptr;
1757 }
1758
1759 /// Emit a diagnostic at the specified location.
1760 void emitError(llvm::SMLoc loc, const Twine &message) override {
1761 parser.emitError(loc, "custom op '" + Twine(opName) + "' " + message);
1762 emittedError = true;
1763 }
1764
1765 bool didEmitError() const { return emittedError; }
1766
1767private:
1768 SMLoc nameLoc;
1769 StringRef opName;
1770 FunctionParser &parser;
1771 bool emittedError = false;
1772};
1773} // end anonymous namespace.
1774
1775Operation *FunctionParser::parseCustomOperation(
1776 const CreateOperationFunction &createOpFunc) {
1777 auto opLoc = getToken().getLoc();
1778 auto opName = getTokenSpelling();
1779 CustomOpAsmParser opAsmParser(opLoc, opName, *this);
1780
1781 auto *opDefinition = getOperationSet().lookup(opName);
1782 if (!opDefinition) {
1783 opAsmParser.emitError(opLoc, "is unknown");
1784 return nullptr;
1785 }
1786
1787 consumeToken();
1788
1789 // Have the op implementation take a crack and parsing this.
1790 auto result = opDefinition->parseAssembly(&opAsmParser);
1791
1792 // If it emitted an error, we failed.
1793 if (opAsmParser.didEmitError())
1794 return nullptr;
1795
1796 // Otherwise, we succeeded. Use the state it parsed as our op information.
1797 auto nameId = builder.getIdentifier(opName);
1798 return createOpFunc(nameId, result.operands, result.types, result.attributes);
1799}
1800
Chris Lattner48af7d12018-07-09 19:05:38 -07001801//===----------------------------------------------------------------------===//
1802// CFG Functions
1803//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001804
Chris Lattner4c95a502018-06-23 16:03:42 -07001805namespace {
Chris Lattner48af7d12018-07-09 19:05:38 -07001806/// This is a specialized parser for CFGFunction's, maintaining the state
1807/// transient to their bodies.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001808class CFGFunctionParser : public FunctionParser {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001809public:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001810 CFGFunctionParser(ParserState &state, CFGFunction *function)
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001811 : FunctionParser(state, Kind::CFGFunc), function(function),
1812 builder(function) {}
Chris Lattner2e595eb2018-07-10 10:08:27 -07001813
1814 ParseResult parseFunctionBody();
1815
1816private:
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001817 CFGFunction *function;
James Molloy0ff71542018-07-23 16:56:32 -07001818 llvm::StringMap<std::pair<BasicBlock *, SMLoc>> blocksByName;
Chris Lattner48af7d12018-07-09 19:05:38 -07001819
1820 /// This builder intentionally shadows the builder in the base class, with a
1821 /// more specific builder type.
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001822 CFGFuncBuilder builder;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001823
Chris Lattner4c95a502018-06-23 16:03:42 -07001824 /// Get the basic block with the specified name, creating it if it doesn't
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001825 /// already exist. The location specified is the point of use, which allows
1826 /// us to diagnose references to blocks that are not defined precisely.
1827 BasicBlock *getBlockNamed(StringRef name, SMLoc loc) {
1828 auto &blockAndLoc = blocksByName[name];
1829 if (!blockAndLoc.first) {
Chris Lattner3a467cc2018-07-01 20:28:00 -07001830 blockAndLoc.first = new BasicBlock();
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001831 blockAndLoc.second = loc;
Chris Lattner4c95a502018-06-23 16:03:42 -07001832 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001833 return blockAndLoc.first;
Chris Lattner4c95a502018-06-23 16:03:42 -07001834 }
Chris Lattner48af7d12018-07-09 19:05:38 -07001835
James Molloy61a656c2018-07-22 15:45:24 -07001836 ParseResult
1837 parseOptionalBasicBlockArgList(SmallVectorImpl<BBArgument *> &results,
1838 BasicBlock *owner);
James Molloy4f788372018-07-24 15:01:27 -07001839 ParseResult parseBranchBlockAndUseList(BasicBlock *&block,
1840 SmallVectorImpl<CFGValue *> &values);
James Molloy61a656c2018-07-22 15:45:24 -07001841
Chris Lattner48af7d12018-07-09 19:05:38 -07001842 ParseResult parseBasicBlock();
1843 OperationInst *parseCFGOperation();
1844 TerminatorInst *parseTerminator();
Chris Lattner4c95a502018-06-23 16:03:42 -07001845};
1846} // end anonymous namespace
1847
James Molloy61a656c2018-07-22 15:45:24 -07001848/// Parse a (possibly empty) list of SSA operands with types as basic block
Chris Lattner2c402672018-07-23 11:56:17 -07001849/// arguments.
James Molloy61a656c2018-07-22 15:45:24 -07001850///
1851/// ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
1852///
1853ParseResult CFGFunctionParser::parseOptionalBasicBlockArgList(
1854 SmallVectorImpl<BBArgument *> &results, BasicBlock *owner) {
1855 if (getToken().is(Token::r_brace))
1856 return ParseSuccess;
1857
1858 return parseCommaSeparatedList([&]() -> ParseResult {
1859 auto type = parseSSADefOrUseAndType<Type *>(
1860 [&](SSAUseInfo useInfo, Type *type) -> Type * {
1861 BBArgument *arg = owner->addArgument(type);
1862 if (addDefinition(useInfo, arg) == ParseFailure)
1863 return nullptr;
1864 return type;
1865 });
1866 return type ? ParseSuccess : ParseFailure;
1867 });
1868}
1869
Chris Lattner48af7d12018-07-09 19:05:38 -07001870ParseResult CFGFunctionParser::parseFunctionBody() {
Chris Lattner40746442018-07-21 14:32:09 -07001871 auto braceLoc = getToken().getLoc();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001872 if (parseToken(Token::l_brace, "expected '{' in CFG function"))
1873 return ParseFailure;
Chris Lattner48af7d12018-07-09 19:05:38 -07001874
1875 // Make sure we have at least one block.
1876 if (getToken().is(Token::r_brace))
1877 return emitError("CFG functions must have at least one basic block");
Chris Lattner4c95a502018-06-23 16:03:42 -07001878
1879 // Parse the list of blocks.
1880 while (!consumeIf(Token::r_brace))
Chris Lattner48af7d12018-07-09 19:05:38 -07001881 if (parseBasicBlock())
Chris Lattner4c95a502018-06-23 16:03:42 -07001882 return ParseFailure;
1883
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001884 // Verify that all referenced blocks were defined. Iteration over a
1885 // StringMap isn't determinstic, but this is good enough for our purposes.
Chris Lattner48af7d12018-07-09 19:05:38 -07001886 for (auto &elt : blocksByName) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001887 auto *bb = elt.second.first;
Chris Lattner3a467cc2018-07-01 20:28:00 -07001888 if (!bb->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001889 return emitError(elt.second.second,
James Molloy0ff71542018-07-23 16:56:32 -07001890 "reference to an undefined basic block '" + elt.first() +
1891 "'");
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001892 }
1893
Chris Lattnera8e47672018-07-25 14:08:16 -07001894 getModule()->getFunctions().push_back(function);
Chris Lattner6119d382018-07-20 18:41:34 -07001895
Chris Lattner40746442018-07-21 14:32:09 -07001896 return finalizeFunction(function, braceLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001897}
1898
1899/// Basic block declaration.
1900///
1901/// basic-block ::= bb-label instruction* terminator-stmt
1902/// bb-label ::= bb-id bb-arg-list? `:`
1903/// bb-id ::= bare-id
1904/// bb-arg-list ::= `(` ssa-id-and-type-list? `)`
1905///
Chris Lattner48af7d12018-07-09 19:05:38 -07001906ParseResult CFGFunctionParser::parseBasicBlock() {
1907 SMLoc nameLoc = getToken().getLoc();
1908 auto name = getTokenSpelling();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001909 if (parseToken(Token::bare_identifier, "expected basic block name"))
1910 return ParseFailure;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001911
Chris Lattner48af7d12018-07-09 19:05:38 -07001912 auto *block = getBlockNamed(name, nameLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001913
1914 // If this block has already been parsed, then this is a redefinition with the
1915 // same block name.
Chris Lattner3a467cc2018-07-01 20:28:00 -07001916 if (block->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001917 return emitError(nameLoc, "redefinition of block '" + name.str() + "'");
1918
Chris Lattner78276e32018-07-07 15:48:26 -07001919 // If an argument list is present, parse it.
1920 if (consumeIf(Token::l_paren)) {
James Molloy61a656c2018-07-22 15:45:24 -07001921 SmallVector<BBArgument *, 8> bbArgs;
Chris Lattnerf7702a62018-07-23 17:30:01 -07001922 if (parseOptionalBasicBlockArgList(bbArgs, block) ||
1923 parseToken(Token::r_paren, "expected ')' to end argument list"))
Chris Lattner78276e32018-07-07 15:48:26 -07001924 return ParseFailure;
Chris Lattner78276e32018-07-07 15:48:26 -07001925 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001926
James Molloy61a656c2018-07-22 15:45:24 -07001927 // Add the block to the function.
1928 function->push_back(block);
1929
Chris Lattnerf7702a62018-07-23 17:30:01 -07001930 if (parseToken(Token::colon, "expected ':' after basic block name"))
1931 return ParseFailure;
Chris Lattner4c95a502018-06-23 16:03:42 -07001932
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001933 // Set the insertion point to the block we want to insert new operations into.
Chris Lattner48af7d12018-07-09 19:05:38 -07001934 builder.setInsertionPoint(block);
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001935
Chris Lattner7f9cc272018-07-19 08:35:28 -07001936 auto createOpFunc = [&](Identifier name, ArrayRef<SSAValue *> operands,
1937 ArrayRef<Type *> resultTypes,
1938 ArrayRef<NamedAttribute> attrs) -> Operation * {
1939 SmallVector<CFGValue *, 8> cfgOperands;
1940 cfgOperands.reserve(operands.size());
1941 for (auto *op : operands)
1942 cfgOperands.push_back(cast<CFGValue>(op));
1943 return builder.createOperation(name, cfgOperands, resultTypes, attrs);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001944 };
1945
Chris Lattnered65a732018-06-28 20:45:33 -07001946 // Parse the list of operations that make up the body of the block.
James Molloy4f788372018-07-24 15:01:27 -07001947 while (getToken().isNot(Token::kw_return, Token::kw_br, Token::kw_cond_br)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001948 if (parseOperation(createOpFunc))
Chris Lattnered65a732018-06-28 20:45:33 -07001949 return ParseFailure;
1950 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001951
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001952 if (!parseTerminator())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001953 return ParseFailure;
Chris Lattner4c95a502018-06-23 16:03:42 -07001954
1955 return ParseSuccess;
1956}
1957
James Molloy4f788372018-07-24 15:01:27 -07001958ParseResult CFGFunctionParser::parseBranchBlockAndUseList(
1959 BasicBlock *&block, SmallVectorImpl<CFGValue *> &values) {
1960 block = getBlockNamed(getTokenSpelling(), getToken().getLoc());
1961 if (parseToken(Token::bare_identifier, "expected basic block name"))
1962 return ParseFailure;
1963
1964 if (!consumeIf(Token::l_paren))
1965 return ParseSuccess;
1966 if (parseOptionalSSAUseAndTypeList(values, /*isParenthesized*/ false) ||
1967 parseToken(Token::r_paren, "expected ')' to close argument list"))
1968 return ParseFailure;
1969 return ParseSuccess;
1970}
1971
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001972/// Parse the terminator instruction for a basic block.
1973///
1974/// terminator-stmt ::= `br` bb-id branch-use-list?
Chris Lattner1604e472018-07-23 08:42:19 -07001975/// branch-use-list ::= `(` ssa-use-list `)` ':' type-list-no-parens
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001976/// terminator-stmt ::=
1977/// `cond_br` ssa-use `,` bb-id branch-use-list? `,` bb-id branch-use-list?
1978/// terminator-stmt ::= `return` ssa-use-and-type-list?
1979///
Chris Lattner48af7d12018-07-09 19:05:38 -07001980TerminatorInst *CFGFunctionParser::parseTerminator() {
1981 switch (getToken().getKind()) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001982 default:
Chris Lattner3a467cc2018-07-01 20:28:00 -07001983 return (emitError("expected terminator at end of basic block"), nullptr);
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001984
Chris Lattner40746442018-07-21 14:32:09 -07001985 case Token::kw_return: {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001986 consumeToken(Token::kw_return);
Chris Lattner40746442018-07-21 14:32:09 -07001987
Chris Lattner2c402672018-07-23 11:56:17 -07001988 // Parse any operands.
1989 SmallVector<CFGValue *, 8> operands;
1990 if (parseOptionalSSAUseAndTypeList(operands, /*isParenthesized*/ false))
1991 return nullptr;
1992 return builder.createReturnInst(operands);
Chris Lattner40746442018-07-21 14:32:09 -07001993 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001994
1995 case Token::kw_br: {
1996 consumeToken(Token::kw_br);
James Molloy4f788372018-07-24 15:01:27 -07001997 BasicBlock *destBB;
1998 SmallVector<CFGValue *, 4> values;
1999 if (parseBranchBlockAndUseList(destBB, values))
Chris Lattnerf7702a62018-07-23 17:30:01 -07002000 return nullptr;
Chris Lattner1604e472018-07-23 08:42:19 -07002001 auto branch = builder.createBranchInst(destBB);
James Molloy4f788372018-07-24 15:01:27 -07002002 branch->addOperands(values);
Chris Lattner1604e472018-07-23 08:42:19 -07002003 return branch;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07002004 }
James Molloy4f788372018-07-24 15:01:27 -07002005
2006 case Token::kw_cond_br: {
2007 consumeToken(Token::kw_cond_br);
2008 SSAUseInfo ssaUse;
2009 if (parseSSAUse(ssaUse))
2010 return nullptr;
2011 auto *cond = resolveSSAUse(ssaUse, builder.getIntegerType(1));
2012 if (!cond)
2013 return (emitError("expected type was boolean (i1)"), nullptr);
2014 if (parseToken(Token::comma, "expected ',' in conditional branch"))
2015 return nullptr;
2016
2017 BasicBlock *trueBlock;
2018 SmallVector<CFGValue *, 4> trueOperands;
2019 if (parseBranchBlockAndUseList(trueBlock, trueOperands))
2020 return nullptr;
2021
2022 if (parseToken(Token::comma, "expected ',' in conditional branch"))
2023 return nullptr;
2024
2025 BasicBlock *falseBlock;
2026 SmallVector<CFGValue *, 4> falseOperands;
2027 if (parseBranchBlockAndUseList(falseBlock, falseOperands))
2028 return nullptr;
2029
2030 auto branch = builder.createCondBranchInst(cast<CFGValue>(cond), trueBlock,
2031 falseBlock);
2032 branch->addTrueOperands(trueOperands);
2033 branch->addFalseOperands(falseOperands);
2034 return branch;
2035 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07002036 }
2037}
2038
Chris Lattner48af7d12018-07-09 19:05:38 -07002039//===----------------------------------------------------------------------===//
2040// ML Functions
2041//===----------------------------------------------------------------------===//
2042
2043namespace {
2044/// Refined parser for MLFunction bodies.
Chris Lattner7f9cc272018-07-19 08:35:28 -07002045class MLFunctionParser : public FunctionParser {
Chris Lattner48af7d12018-07-09 19:05:38 -07002046public:
Chris Lattner48af7d12018-07-09 19:05:38 -07002047 MLFunctionParser(ParserState &state, MLFunction *function)
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07002048 : FunctionParser(state, Kind::MLFunc), function(function),
2049 builder(function) {}
Chris Lattner48af7d12018-07-09 19:05:38 -07002050
2051 ParseResult parseFunctionBody();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002052
2053private:
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002054 MLFunction *function;
2055
2056 /// This builder intentionally shadows the builder in the base class, with a
2057 /// more specific builder type.
2058 MLFuncBuilder builder;
2059
2060 ParseResult parseForStmt();
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002061 AffineConstantExpr *parseIntConstant();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002062 ParseResult parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002063 ParseResult parseElseClause(IfClause *elseClause);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002064 ParseResult parseStatements(StmtBlock *block);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002065 ParseResult parseStmtBlock(StmtBlock *block);
Chris Lattner48af7d12018-07-09 19:05:38 -07002066};
2067} // end anonymous namespace
2068
Chris Lattner48af7d12018-07-09 19:05:38 -07002069ParseResult MLFunctionParser::parseFunctionBody() {
Chris Lattner40746442018-07-21 14:32:09 -07002070 auto braceLoc = getToken().getLoc();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002071 // Parse statements in this function
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002072
Chris Lattnerf7702a62018-07-23 17:30:01 -07002073 if (parseToken(Token::l_brace, "expected '{' in ML function") ||
2074 parseStatements(function)) {
2075 return ParseFailure;
2076 }
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002077
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002078 // TODO: store return operands in the IR.
2079 SmallVector<SSAUseInfo, 4> dummyUseInfo;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002080
Chris Lattnerf7702a62018-07-23 17:30:01 -07002081 if (parseToken(Token::kw_return,
2082 "ML function must end with return statement") ||
2083 parseOptionalSSAUseList(dummyUseInfo) ||
2084 parseToken(Token::r_brace, "expected '}' to end mlfunc"))
2085 return ParseFailure;
Chris Lattner40746442018-07-21 14:32:09 -07002086
Chris Lattnera8e47672018-07-25 14:08:16 -07002087 getModule()->getFunctions().push_back(function);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002088
Chris Lattner40746442018-07-21 14:32:09 -07002089 return finalizeFunction(function, braceLoc);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002090}
2091
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002092/// For statement.
2093///
Chris Lattner48af7d12018-07-09 19:05:38 -07002094/// ml-for-stmt ::= `for` ssa-id `=` lower-bound `to` upper-bound
2095/// (`step` integer-literal)? `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002096///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002097ParseResult MLFunctionParser::parseForStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002098 consumeToken(Token::kw_for);
2099
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002100 // Parse induction variable
2101 if (getToken().isNot(Token::percent_identifier))
2102 return emitError("expected SSA identifier for the loop variable");
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002103
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07002104 auto loc = getToken().getLoc();
Tatiana Shpeismand880b352018-07-31 23:14:16 -07002105 StringRef inductionVariableName = getTokenSpelling();
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002106 consumeToken(Token::percent_identifier);
2107
Chris Lattnerf7702a62018-07-23 17:30:01 -07002108 if (parseToken(Token::equal, "expected ="))
2109 return ParseFailure;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002110
2111 // Parse loop bounds
2112 AffineConstantExpr *lowerBound = parseIntConstant();
2113 if (!lowerBound)
2114 return ParseFailure;
2115
Chris Lattnerf7702a62018-07-23 17:30:01 -07002116 if (parseToken(Token::kw_to, "expected 'to' between bounds"))
2117 return ParseFailure;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002118
2119 AffineConstantExpr *upperBound = parseIntConstant();
2120 if (!upperBound)
2121 return ParseFailure;
2122
2123 // Parse step
2124 AffineConstantExpr *step = nullptr;
2125 if (consumeIf(Token::kw_step)) {
2126 step = parseIntConstant();
2127 if (!step)
2128 return ParseFailure;
2129 }
2130
2131 // Create for statement.
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07002132 ForStmt *forStmt = builder.createFor(lowerBound, upperBound, step);
2133
2134 // Create SSA value definition for the induction variable.
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -07002135 addDefinition({inductionVariableName, 0, loc}, forStmt);
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002136
2137 // If parsing of the for statement body fails,
2138 // MLIR contains for statement with those nested statements that have been
2139 // successfully parsed.
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07002140 if (parseStmtBlock(forStmt))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002141 return ParseFailure;
2142
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07002143 // Reset insertion point to the current block.
2144 builder.setInsertionPoint(forStmt->getBlock());
2145
Tatiana Shpeismand880b352018-07-31 23:14:16 -07002146 // TODO: remove definition of the induction variable.
2147
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002148 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002149}
2150
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002151// This method is temporary workaround to parse simple loop bounds and
2152// step.
2153// TODO: remove this method once it's no longer used.
2154AffineConstantExpr *MLFunctionParser::parseIntConstant() {
2155 if (getToken().isNot(Token::integer))
2156 return (emitError("expected non-negative integer for now"), nullptr);
2157
2158 auto val = getToken().getUInt64IntegerValue();
2159 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
2160 return (emitError("constant too large for affineint"), nullptr);
2161 }
2162 consumeToken(Token::integer);
2163 return builder.getConstantExpr((int64_t)val.getValue());
2164}
2165
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002166/// If statement.
2167///
Chris Lattner48af7d12018-07-09 19:05:38 -07002168/// ml-if-head ::= `if` ml-if-cond `{` ml-stmt* `}`
2169/// | ml-if-head `else` `if` ml-if-cond `{` ml-stmt* `}`
2170/// ml-if-stmt ::= ml-if-head
2171/// | ml-if-head `else` `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002172///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002173ParseResult MLFunctionParser::parseIfStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002174 consumeToken(Token::kw_if);
Chris Lattnerf7702a62018-07-23 17:30:01 -07002175 if (parseToken(Token::l_paren, "expected ("))
2176 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002177
James Molloy0ff71542018-07-23 16:56:32 -07002178 // TODO: parse condition
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002179
Chris Lattnerf7702a62018-07-23 17:30:01 -07002180 if (parseToken(Token::r_paren, "expected )"))
2181 return ParseFailure;
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002182
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002183 IfStmt *ifStmt = builder.createIf();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002184 IfClause *thenClause = ifStmt->getThenClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002185
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002186 // When parsing of an if statement body fails, the IR contains
2187 // the if statement with the portion of the body that has been
2188 // successfully parsed.
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002189 if (parseStmtBlock(thenClause))
2190 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002191
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002192 if (consumeIf(Token::kw_else)) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07002193 auto *elseClause = ifStmt->createElseClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002194 if (parseElseClause(elseClause))
2195 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002196 }
2197
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07002198 // Reset insertion point to the current block.
2199 builder.setInsertionPoint(ifStmt->getBlock());
2200
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002201 return ParseSuccess;
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002202}
2203
2204ParseResult MLFunctionParser::parseElseClause(IfClause *elseClause) {
2205 if (getToken().is(Token::kw_if)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002206 builder.setInsertionPoint(elseClause);
2207 return parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002208 }
2209
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002210 return parseStmtBlock(elseClause);
2211}
2212
2213///
2214/// Parse a list of statements ending with `return` or `}`
2215///
2216ParseResult MLFunctionParser::parseStatements(StmtBlock *block) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07002217 auto createOpFunc = [&](Identifier name, ArrayRef<SSAValue *> operands,
2218 ArrayRef<Type *> resultTypes,
2219 ArrayRef<NamedAttribute> attrs) -> Operation * {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07002220 SmallVector<MLValue *, 8> stmtOperands;
2221 stmtOperands.reserve(operands.size());
2222 for (auto *op : operands)
2223 stmtOperands.push_back(cast<MLValue>(op));
2224 return builder.createOperation(name, stmtOperands, resultTypes, attrs);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002225 };
2226
2227 builder.setInsertionPoint(block);
2228
2229 while (getToken().isNot(Token::kw_return, Token::r_brace)) {
2230 switch (getToken().getKind()) {
2231 default:
2232 if (parseOperation(createOpFunc))
2233 return ParseFailure;
2234 break;
2235 case Token::kw_for:
2236 if (parseForStmt())
2237 return ParseFailure;
2238 break;
2239 case Token::kw_if:
2240 if (parseIfStmt())
2241 return ParseFailure;
2242 break;
2243 } // end switch
2244 }
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002245
2246 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002247}
2248
2249///
2250/// Parse `{` ml-stmt* `}`
2251///
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002252ParseResult MLFunctionParser::parseStmtBlock(StmtBlock *block) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07002253 if (parseToken(Token::l_brace, "expected '{' before statement list") ||
2254 parseStatements(block) ||
2255 parseToken(Token::r_brace,
2256 "expected '}' at the end of the statement block"))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002257 return ParseFailure;
2258
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002259 return ParseSuccess;
2260}
2261
Chris Lattner4c95a502018-06-23 16:03:42 -07002262//===----------------------------------------------------------------------===//
2263// Top-level entity parsing.
2264//===----------------------------------------------------------------------===//
2265
Chris Lattner2e595eb2018-07-10 10:08:27 -07002266namespace {
2267/// This parser handles entities that are only valid at the top level of the
2268/// file.
2269class ModuleParser : public Parser {
2270public:
2271 explicit ModuleParser(ParserState &state) : Parser(state) {}
2272
2273 ParseResult parseModule();
2274
2275private:
2276 ParseResult parseAffineMapDef();
2277
2278 // Functions.
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002279 ParseResult parseMLArgumentList(SmallVectorImpl<Type *> &argTypes,
2280 SmallVectorImpl<StringRef> &argNames);
2281 ParseResult parseFunctionSignature(StringRef &name, FunctionType *&type,
2282 SmallVectorImpl<StringRef> *argNames);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002283 ParseResult parseExtFunc();
2284 ParseResult parseCFGFunc();
2285 ParseResult parseMLFunc();
2286};
2287} // end anonymous namespace
2288
2289/// Affine map declaration.
2290///
2291/// affine-map-def ::= affine-map-id `=` affine-map-inline
2292///
2293ParseResult ModuleParser::parseAffineMapDef() {
2294 assert(getToken().is(Token::hash_identifier));
2295
2296 StringRef affineMapId = getTokenSpelling().drop_front();
2297
2298 // Check for redefinitions.
2299 auto *&entry = getState().affineMapDefinitions[affineMapId];
2300 if (entry)
2301 return emitError("redefinition of affine map id '" + affineMapId + "'");
2302
2303 consumeToken(Token::hash_identifier);
2304
2305 // Parse the '='
Chris Lattnerf7702a62018-07-23 17:30:01 -07002306 if (parseToken(Token::equal,
2307 "expected '=' in affine map outlined definition"))
2308 return ParseFailure;
Chris Lattner2e595eb2018-07-10 10:08:27 -07002309
2310 entry = parseAffineMapInline();
2311 if (!entry)
2312 return ParseFailure;
2313
Chris Lattner2e595eb2018-07-10 10:08:27 -07002314 return ParseSuccess;
2315}
2316
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002317/// Parse a (possibly empty) list of MLFunction arguments with types.
2318///
2319/// ml-argument ::= ssa-id `:` type
2320/// ml-argument-list ::= ml-argument (`,` ml-argument)* | /*empty*/
2321///
2322ParseResult
2323ModuleParser::parseMLArgumentList(SmallVectorImpl<Type *> &argTypes,
2324 SmallVectorImpl<StringRef> &argNames) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07002325 consumeToken(Token::l_paren);
2326
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002327 auto parseElt = [&]() -> ParseResult {
2328 // Parse argument name
2329 if (getToken().isNot(Token::percent_identifier))
2330 return emitError("expected SSA identifier");
2331
2332 StringRef name = getTokenSpelling().drop_front();
2333 consumeToken(Token::percent_identifier);
2334 argNames.push_back(name);
2335
Chris Lattnerf7702a62018-07-23 17:30:01 -07002336 if (parseToken(Token::colon, "expected ':'"))
2337 return ParseFailure;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002338
2339 // Parse argument type
2340 auto elt = parseType();
2341 if (!elt)
2342 return ParseFailure;
2343 argTypes.push_back(elt);
2344
2345 return ParseSuccess;
2346 };
2347
Chris Lattner40746442018-07-21 14:32:09 -07002348 return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002349}
2350
Chris Lattner2e595eb2018-07-10 10:08:27 -07002351/// Parse a function signature, starting with a name and including the parameter
2352/// list.
2353///
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002354/// argument-list ::= type (`,` type)* | /*empty*/ | ml-argument-list
Chris Lattner2e595eb2018-07-10 10:08:27 -07002355/// function-signature ::= function-id `(` argument-list `)` (`->` type-list)?
2356///
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002357ParseResult
2358ModuleParser::parseFunctionSignature(StringRef &name, FunctionType *&type,
2359 SmallVectorImpl<StringRef> *argNames) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07002360 if (getToken().isNot(Token::at_identifier))
2361 return emitError("expected a function identifier like '@foo'");
2362
2363 name = getTokenSpelling().drop_front();
2364 consumeToken(Token::at_identifier);
2365
2366 if (getToken().isNot(Token::l_paren))
2367 return emitError("expected '(' in function signature");
2368
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002369 SmallVector<Type *, 4> argTypes;
2370 ParseResult parseResult;
2371
2372 if (argNames)
2373 parseResult = parseMLArgumentList(argTypes, *argNames);
2374 else
2375 parseResult = parseTypeList(argTypes);
2376
2377 if (parseResult)
Chris Lattner2e595eb2018-07-10 10:08:27 -07002378 return ParseFailure;
2379
2380 // Parse the return type if present.
2381 SmallVector<Type *, 4> results;
2382 if (consumeIf(Token::arrow)) {
2383 if (parseTypeList(results))
2384 return ParseFailure;
2385 }
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002386 type = builder.getFunctionType(argTypes, results);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002387 return ParseSuccess;
2388}
2389
2390/// External function declarations.
2391///
2392/// ext-func ::= `extfunc` function-signature
2393///
2394ParseResult ModuleParser::parseExtFunc() {
2395 consumeToken(Token::kw_extfunc);
2396
2397 StringRef name;
2398 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002399 if (parseFunctionSignature(name, type, /*arguments*/ nullptr))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002400 return ParseFailure;
2401
2402 // Okay, the external function definition was parsed correctly.
Chris Lattnera8e47672018-07-25 14:08:16 -07002403 getModule()->getFunctions().push_back(new ExtFunction(name, type));
Chris Lattner2e595eb2018-07-10 10:08:27 -07002404 return ParseSuccess;
2405}
2406
2407/// CFG function declarations.
2408///
2409/// cfg-func ::= `cfgfunc` function-signature `{` basic-block+ `}`
2410///
2411ParseResult ModuleParser::parseCFGFunc() {
2412 consumeToken(Token::kw_cfgfunc);
2413
2414 StringRef name;
2415 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002416 if (parseFunctionSignature(name, type, /*arguments*/ nullptr))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002417 return ParseFailure;
2418
2419 // Okay, the CFG function signature was parsed correctly, create the function.
2420 auto function = new CFGFunction(name, type);
2421
2422 return CFGFunctionParser(getState(), function).parseFunctionBody();
2423}
2424
2425/// ML function declarations.
2426///
2427/// ml-func ::= `mlfunc` ml-func-signature `{` ml-stmt* ml-return-stmt `}`
2428///
2429ParseResult ModuleParser::parseMLFunc() {
2430 consumeToken(Token::kw_mlfunc);
2431
2432 StringRef name;
2433 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002434 SmallVector<StringRef, 4> argNames;
Chris Lattner2e595eb2018-07-10 10:08:27 -07002435 // FIXME: Parse ML function signature (args + types)
2436 // by passing pointer to SmallVector<identifier> into parseFunctionSignature
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002437
2438 if (parseFunctionSignature(name, type, &argNames))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002439 return ParseFailure;
2440
2441 // Okay, the ML function signature was parsed correctly, create the function.
2442 auto function = new MLFunction(name, type);
2443
2444 return MLFunctionParser(getState(), function).parseFunctionBody();
2445}
2446
Chris Lattnere79379a2018-06-22 10:39:19 -07002447/// This is the top-level module parser.
Chris Lattner2e595eb2018-07-10 10:08:27 -07002448ParseResult ModuleParser::parseModule() {
Chris Lattnere79379a2018-06-22 10:39:19 -07002449 while (1) {
Chris Lattner48af7d12018-07-09 19:05:38 -07002450 switch (getToken().getKind()) {
Chris Lattnere79379a2018-06-22 10:39:19 -07002451 default:
2452 emitError("expected a top level entity");
Chris Lattner2e595eb2018-07-10 10:08:27 -07002453 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07002454
Uday Bondhugula015cbb12018-07-03 20:16:08 -07002455 // If we got to the end of the file, then we're done.
Chris Lattnere79379a2018-06-22 10:39:19 -07002456 case Token::eof:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002457 return ParseSuccess;
Chris Lattnere79379a2018-06-22 10:39:19 -07002458
2459 // If we got an error token, then the lexer already emitted an error, just
2460 // stop. Someday we could introduce error recovery if there was demand for
2461 // it.
2462 case Token::error:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002463 return ParseFailure;
2464
2465 case Token::hash_identifier:
2466 if (parseAffineMapDef())
2467 return ParseFailure;
2468 break;
Chris Lattnere79379a2018-06-22 10:39:19 -07002469
2470 case Token::kw_extfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002471 if (parseExtFunc())
2472 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07002473 break;
2474
Chris Lattner4c95a502018-06-23 16:03:42 -07002475 case Token::kw_cfgfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002476 if (parseCFGFunc())
2477 return ParseFailure;
MLIR Teamf85a6262018-06-27 11:03:08 -07002478 break;
Chris Lattner4c95a502018-06-23 16:03:42 -07002479
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002480 case Token::kw_mlfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002481 if (parseMLFunc())
2482 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002483 break;
Chris Lattnere79379a2018-06-22 10:39:19 -07002484 }
2485 }
2486}
2487
2488//===----------------------------------------------------------------------===//
2489
Jacques Pienaar7b829702018-07-03 13:24:09 -07002490void mlir::defaultErrorReporter(const llvm::SMDiagnostic &error) {
2491 const auto &sourceMgr = *error.getSourceMgr();
2492 sourceMgr.PrintMessage(error.getLoc(), error.getKind(), error.getMessage());
2493}
2494
Chris Lattnere79379a2018-06-22 10:39:19 -07002495/// This parses the file specified by the indicated SourceMgr and returns an
2496/// MLIR module if it was valid. If not, it emits diagnostics and returns null.
Jacques Pienaar9c411be2018-06-24 19:17:35 -07002497Module *mlir::parseSourceFile(llvm::SourceMgr &sourceMgr, MLIRContext *context,
Jacques Pienaar7b829702018-07-03 13:24:09 -07002498 SMDiagnosticHandlerTy errorReporter) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07002499 // This is the result module we are parsing into.
2500 std::unique_ptr<Module> module(new Module(context));
2501
2502 ParserState state(sourceMgr, module.get(),
Jacques Pienaar0bffd862018-07-11 13:26:23 -07002503 errorReporter ? errorReporter : defaultErrorReporter);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002504 if (ModuleParser(state).parseModule())
2505 return nullptr;
Chris Lattner21e67f62018-07-06 10:46:19 -07002506
2507 // Make sure the parse module has no other structural problems detected by the
2508 // verifier.
Chris Lattner2e595eb2018-07-10 10:08:27 -07002509 module->verify();
2510 return module.release();
Chris Lattnere79379a2018-06-22 10:39:19 -07002511}