1 //===- Parser.cpp - MLIR Parser Implementation ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the parser for the MLIR textual form.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Parser.h"
14 #include "Lexer.h"
15 #include "mlir/Analysis/Verifier.h"
16 #include "mlir/IR/AffineExpr.h"
17 #include "mlir/IR/AffineMap.h"
18 #include "mlir/IR/Attributes.h"
19 #include "mlir/IR/Builders.h"
20 #include "mlir/IR/Dialect.h"
21 #include "mlir/IR/DialectImplementation.h"
22 #include "mlir/IR/IntegerSet.h"
23 #include "mlir/IR/Location.h"
24 #include "mlir/IR/MLIRContext.h"
25 #include "mlir/IR/Module.h"
26 #include "mlir/IR/OpImplementation.h"
27 #include "mlir/IR/StandardTypes.h"
28 #include "mlir/Support/STLExtras.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/StringSet.h"
33 #include "llvm/ADT/bit.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/SMLoc.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include <algorithm>
38 using namespace mlir;
39 using llvm::MemoryBuffer;
40 using llvm::SMLoc;
41 using llvm::SourceMgr;
42 
43 namespace {
44 class Parser;
45 
46 //===----------------------------------------------------------------------===//
47 // SymbolState
48 //===----------------------------------------------------------------------===//
49 
50 /// This class contains record of any parsed top-level symbols.
51 struct SymbolState {
52   // A map from attribute alias identifier to Attribute.
53   llvm::StringMap<Attribute> attributeAliasDefinitions;
54 
55   // A map from type alias identifier to Type.
56   llvm::StringMap<Type> typeAliasDefinitions;
57 
58   /// A set of locations into the main parser memory buffer for each of the
59   /// active nested parsers. Given that some nested parsers, i.e. custom dialect
60   /// parsers, operate on a temporary memory buffer, this provides an anchor
61   /// point for emitting diagnostics.
62   SmallVector<llvm::SMLoc, 1> nestedParserLocs;
63 
64   /// The top-level lexer that contains the original memory buffer provided by
65   /// the user. This is used by nested parsers to get a properly encoded source
66   /// location.
67   Lexer *topLevelLexer = nullptr;
68 };
69 
70 //===----------------------------------------------------------------------===//
71 // ParserState
72 //===----------------------------------------------------------------------===//
73 
74 /// This class refers to all of the state maintained globally by the parser,
75 /// such as the current lexer position etc.
76 struct ParserState {
77   ParserState(const llvm::SourceMgr &sourceMgr, MLIRContext *ctx,
78               SymbolState &symbols)
79       : context(ctx), lex(sourceMgr, ctx), curToken(lex.lexToken()),
80         symbols(symbols), parserDepth(symbols.nestedParserLocs.size()) {
81     // Set the top level lexer for the symbol state if one doesn't exist.
82     if (!symbols.topLevelLexer)
83       symbols.topLevelLexer = &lex;
84   }
85   ~ParserState() {
86     // Reset the top level lexer if it refers the lexer in our state.
87     if (symbols.topLevelLexer == &lex)
88       symbols.topLevelLexer = nullptr;
89   }
90   ParserState(const ParserState &) = delete;
91   void operator=(const ParserState &) = delete;
92 
93   /// The context we're parsing into.
94   MLIRContext *const context;
95 
96   /// The lexer for the source file we're parsing.
97   Lexer lex;
98 
99   /// This is the next token that hasn't been consumed yet.
100   Token curToken;
101 
102   /// The current state for symbol parsing.
103   SymbolState &symbols;
104 
105   /// The depth of this parser in the nested parsing stack.
106   size_t parserDepth;
107 };
108 
109 //===----------------------------------------------------------------------===//
110 // Parser
111 //===----------------------------------------------------------------------===//
112 
113 /// This class implement support for parsing global entities like types and
114 /// shared entities like SSA names.  It is intended to be subclassed by
115 /// specialized subparsers that include state, e.g. when a local symbol table.
116 class Parser {
117 public:
118   Builder builder;
119 
120   Parser(ParserState &state) : builder(state.context), state(state) {}
121 
122   // Helper methods to get stuff from the parser-global state.
123   ParserState &getState() const { return state; }
124   MLIRContext *getContext() const { return state.context; }
125   const llvm::SourceMgr &getSourceMgr() { return state.lex.getSourceMgr(); }
126 
127   /// Parse a comma-separated list of elements up until the specified end token.
128   ParseResult
129   parseCommaSeparatedListUntil(Token::Kind rightToken,
130                                const std::function<ParseResult()> &parseElement,
131                                bool allowEmptyList = true);
132 
133   /// Parse a comma separated list of elements that must have at least one entry
134   /// in it.
135   ParseResult
136   parseCommaSeparatedList(const std::function<ParseResult()> &parseElement);
137 
138   ParseResult parsePrettyDialectSymbolName(StringRef &prettyName);
139 
140   // We have two forms of parsing methods - those that return a non-null
141   // pointer on success, and those that return a ParseResult to indicate whether
142   // they returned a failure.  The second class fills in by-reference arguments
143   // as the results of their action.
144 
145   //===--------------------------------------------------------------------===//
146   // Error Handling
147   //===--------------------------------------------------------------------===//
148 
149   /// Emit an error and return failure.
150   InFlightDiagnostic emitError(const Twine &message = {}) {
151     return emitError(state.curToken.getLoc(), message);
152   }
153   InFlightDiagnostic emitError(SMLoc loc, const Twine &message = {});
154 
155   /// Encode the specified source location information into an attribute for
156   /// attachment to the IR.
157   Location getEncodedSourceLocation(llvm::SMLoc loc) {
158     // If there are no active nested parsers, we can get the encoded source
159     // location directly.
160     if (state.parserDepth == 0)
161       return state.lex.getEncodedSourceLocation(loc);
162     // Otherwise, we need to re-encode it to point to the top level buffer.
163     return state.symbols.topLevelLexer->getEncodedSourceLocation(
164         remapLocationToTopLevelBuffer(loc));
165   }
166 
167   /// Remaps the given SMLoc to the top level lexer of the parser. This is used
168   /// to adjust locations of potentially nested parsers to ensure that they can
169   /// be emitted properly as diagnostics.
170   llvm::SMLoc remapLocationToTopLevelBuffer(llvm::SMLoc loc) {
171     // If there are no active nested parsers, we can return location directly.
172     SymbolState &symbols = state.symbols;
173     if (state.parserDepth == 0)
174       return loc;
175     assert(symbols.topLevelLexer && "expected valid top-level lexer");
176 
177     // Otherwise, we need to remap the location to the main parser. This is
178     // simply offseting the location onto the location of the last nested
179     // parser.
180     size_t offset = loc.getPointer() - state.lex.getBufferBegin();
181     auto *rawLoc =
182         symbols.nestedParserLocs[state.parserDepth - 1].getPointer() + offset;
183     return llvm::SMLoc::getFromPointer(rawLoc);
184   }
185 
186   //===--------------------------------------------------------------------===//
187   // Token Parsing
188   //===--------------------------------------------------------------------===//
189 
190   /// Return the current token the parser is inspecting.
191   const Token &getToken() const { return state.curToken; }
192   StringRef getTokenSpelling() const { return state.curToken.getSpelling(); }
193 
194   /// If the current token has the specified kind, consume it and return true.
195   /// If not, return false.
196   bool consumeIf(Token::Kind kind) {
197     if (state.curToken.isNot(kind))
198       return false;
199     consumeToken(kind);
200     return true;
201   }
202 
203   /// Advance the current lexer onto the next token.
204   void consumeToken() {
205     assert(state.curToken.isNot(Token::eof, Token::error) &&
206            "shouldn't advance past EOF or errors");
207     state.curToken = state.lex.lexToken();
208   }
209 
210   /// Advance the current lexer onto the next token, asserting what the expected
211   /// current token is.  This is preferred to the above method because it leads
212   /// to more self-documenting code with better checking.
213   void consumeToken(Token::Kind kind) {
214     assert(state.curToken.is(kind) && "consumed an unexpected token");
215     consumeToken();
216   }
217 
218   /// Consume the specified token if present and return success.  On failure,
219   /// output a diagnostic and return failure.
220   ParseResult parseToken(Token::Kind expectedToken, const Twine &message);
221 
222   //===--------------------------------------------------------------------===//
223   // Type Parsing
224   //===--------------------------------------------------------------------===//
225 
226   ParseResult parseFunctionResultTypes(SmallVectorImpl<Type> &elements);
227   ParseResult parseTypeListNoParens(SmallVectorImpl<Type> &elements);
228   ParseResult parseTypeListParens(SmallVectorImpl<Type> &elements);
229 
230   /// Parse an arbitrary type.
231   Type parseType();
232 
233   /// Parse a complex type.
234   Type parseComplexType();
235 
236   /// Parse an extended type.
237   Type parseExtendedType();
238 
239   /// Parse a function type.
240   Type parseFunctionType();
241 
242   /// Parse a memref type.
243   Type parseMemRefType();
244 
245   /// Parse a non function type.
246   Type parseNonFunctionType();
247 
248   /// Parse a tensor type.
249   Type parseTensorType();
250 
251   /// Parse a tuple type.
252   Type parseTupleType();
253 
254   /// Parse a vector type.
255   VectorType parseVectorType();
256   ParseResult parseDimensionListRanked(SmallVectorImpl<int64_t> &dimensions,
257                                        bool allowDynamic = true);
258   ParseResult parseXInDimensionList();
259 
260   /// Parse strided layout specification.
261   ParseResult parseStridedLayout(int64_t &offset,
262                                  SmallVectorImpl<int64_t> &strides);
263 
264   // Parse a brace-delimiter list of comma-separated integers with `?` as an
265   // unknown marker.
266   ParseResult parseStrideList(SmallVectorImpl<int64_t> &dimensions);
267 
268   //===--------------------------------------------------------------------===//
269   // Attribute Parsing
270   //===--------------------------------------------------------------------===//
271 
272   /// Parse an arbitrary attribute with an optional type.
273   Attribute parseAttribute(Type type = {});
274 
275   /// Parse an attribute dictionary.
276   ParseResult parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes);
277 
278   /// Parse an extended attribute.
279   Attribute parseExtendedAttr(Type type);
280 
281   /// Parse a float attribute.
282   Attribute parseFloatAttr(Type type, bool isNegative);
283 
284   /// Parse a decimal or a hexadecimal literal, which can be either an integer
285   /// or a float attribute.
286   Attribute parseDecOrHexAttr(Type type, bool isNegative);
287 
288   /// Parse an opaque elements attribute.
289   Attribute parseOpaqueElementsAttr(Type attrType);
290 
291   /// Parse a dense elements attribute.
292   Attribute parseDenseElementsAttr(Type attrType);
293   ShapedType parseElementsLiteralType(Type type);
294 
295   /// Parse a sparse elements attribute.
296   Attribute parseSparseElementsAttr(Type attrType);
297 
298   //===--------------------------------------------------------------------===//
299   // Location Parsing
300   //===--------------------------------------------------------------------===//
301 
302   /// Parse an inline location.
303   ParseResult parseLocation(LocationAttr &loc);
304 
305   /// Parse a raw location instance.
306   ParseResult parseLocationInstance(LocationAttr &loc);
307 
308   /// Parse a callsite location instance.
309   ParseResult parseCallSiteLocation(LocationAttr &loc);
310 
311   /// Parse a fused location instance.
312   ParseResult parseFusedLocation(LocationAttr &loc);
313 
314   /// Parse a name or FileLineCol location instance.
315   ParseResult parseNameOrFileLineColLocation(LocationAttr &loc);
316 
317   /// Parse an optional trailing location.
318   ///
319   ///   trailing-location     ::= (`loc` `(` location `)`)?
320   ///
321   ParseResult parseOptionalTrailingLocation(Location &loc) {
322     // If there is a 'loc' we parse a trailing location.
323     if (!getToken().is(Token::kw_loc))
324       return success();
325 
326     // Parse the location.
327     LocationAttr directLoc;
328     if (parseLocation(directLoc))
329       return failure();
330     loc = directLoc;
331     return success();
332   }
333 
334   //===--------------------------------------------------------------------===//
335   // Affine Parsing
336   //===--------------------------------------------------------------------===//
337 
338   /// Parse a reference to either an affine map, or an integer set.
339   ParseResult parseAffineMapOrIntegerSetReference(AffineMap &map,
340                                                   IntegerSet &set);
341   ParseResult parseAffineMapReference(AffineMap &map);
342   ParseResult parseIntegerSetReference(IntegerSet &set);
343 
344   /// Parse an AffineMap where the dim and symbol identifiers are SSA ids.
345   ParseResult
346   parseAffineMapOfSSAIds(AffineMap &map,
347                          function_ref<ParseResult(bool)> parseElement,
348                          OpAsmParser::Delimiter delimiter);
349 
350 private:
351   /// The Parser is subclassed and reinstantiated.  Do not add additional
352   /// non-trivial state here, add it to the ParserState class.
353   ParserState &state;
354 };
355 } // end anonymous namespace
356 
357 //===----------------------------------------------------------------------===//
358 // Helper methods.
359 //===----------------------------------------------------------------------===//
360 
361 /// Parse a comma separated list of elements that must have at least one entry
362 /// in it.
363 ParseResult Parser::parseCommaSeparatedList(
364     const std::function<ParseResult()> &parseElement) {
365   // Non-empty case starts with an element.
366   if (parseElement())
367     return failure();
368 
369   // Otherwise we have a list of comma separated elements.
370   while (consumeIf(Token::comma)) {
371     if (parseElement())
372       return failure();
373   }
374   return success();
375 }
376 
377 /// Parse a comma-separated list of elements, terminated with an arbitrary
378 /// token.  This allows empty lists if allowEmptyList is true.
379 ///
380 ///   abstract-list ::= rightToken                  // if allowEmptyList == true
381 ///   abstract-list ::= element (',' element)* rightToken
382 ///
383 ParseResult Parser::parseCommaSeparatedListUntil(
384     Token::Kind rightToken, const std::function<ParseResult()> &parseElement,
385     bool allowEmptyList) {
386   // Handle the empty case.
387   if (getToken().is(rightToken)) {
388     if (!allowEmptyList)
389       return emitError("expected list element");
390     consumeToken(rightToken);
391     return success();
392   }
393 
394   if (parseCommaSeparatedList(parseElement) ||
395       parseToken(rightToken, "expected ',' or '" +
396                                  Token::getTokenSpelling(rightToken) + "'"))
397     return failure();
398 
399   return success();
400 }
401 
402 //===----------------------------------------------------------------------===//
403 // DialectAsmParser
404 //===----------------------------------------------------------------------===//
405 
406 namespace {
407 /// This class provides the main implementation of the DialectAsmParser that
408 /// allows for dialects to parse attributes and types. This allows for dialect
409 /// hooking into the main MLIR parsing logic.
410 class CustomDialectAsmParser : public DialectAsmParser {
411 public:
412   CustomDialectAsmParser(StringRef fullSpec, Parser &parser)
413       : fullSpec(fullSpec), nameLoc(parser.getToken().getLoc()),
414         parser(parser) {}
415   ~CustomDialectAsmParser() override {}
416 
417   /// Emit a diagnostic at the specified location and return failure.
418   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
419     return parser.emitError(loc, message);
420   }
421 
422   /// Return a builder which provides useful access to MLIRContext, global
423   /// objects like types and attributes.
424   Builder &getBuilder() const override { return parser.builder; }
425 
426   /// Get the location of the next token and store it into the argument.  This
427   /// always succeeds.
428   llvm::SMLoc getCurrentLocation() override {
429     return parser.getToken().getLoc();
430   }
431 
432   /// Return the location of the original name token.
433   llvm::SMLoc getNameLoc() const override { return nameLoc; }
434 
435   /// Re-encode the given source location as an MLIR location and return it.
436   Location getEncodedSourceLoc(llvm::SMLoc loc) override {
437     return parser.getEncodedSourceLocation(loc);
438   }
439 
440   /// Returns the full specification of the symbol being parsed. This allows
441   /// for using a separate parser if necessary.
442   StringRef getFullSymbolSpec() const override { return fullSpec; }
443 
444   /// Parse a floating point value from the stream.
445   ParseResult parseFloat(double &result) override {
446     bool negative = parser.consumeIf(Token::minus);
447     Token curTok = parser.getToken();
448 
449     // Check for a floating point value.
450     if (curTok.is(Token::floatliteral)) {
451       auto val = curTok.getFloatingPointValue();
452       if (!val.hasValue())
453         return emitError(curTok.getLoc(), "floating point value too large");
454       parser.consumeToken(Token::floatliteral);
455       result = negative ? -*val : *val;
456       return success();
457     }
458 
459     // TODO(riverriddle) support hex floating point values.
460     return emitError(getCurrentLocation(), "expected floating point literal");
461   }
462 
463   /// Parse an optional integer value from the stream.
464   OptionalParseResult parseOptionalInteger(uint64_t &result) override {
465     Token curToken = parser.getToken();
466     if (curToken.isNot(Token::integer, Token::minus))
467       return llvm::None;
468 
469     bool negative = parser.consumeIf(Token::minus);
470     Token curTok = parser.getToken();
471     if (parser.parseToken(Token::integer, "expected integer value"))
472       return failure();
473 
474     auto val = curTok.getUInt64IntegerValue();
475     if (!val)
476       return emitError(curTok.getLoc(), "integer value too large");
477     result = negative ? -*val : *val;
478     return success();
479   }
480 
481   //===--------------------------------------------------------------------===//
482   // Token Parsing
483   //===--------------------------------------------------------------------===//
484 
485   /// Parse a `->` token.
486   ParseResult parseArrow() override {
487     return parser.parseToken(Token::arrow, "expected '->'");
488   }
489 
490   /// Parses a `->` if present.
491   ParseResult parseOptionalArrow() override {
492     return success(parser.consumeIf(Token::arrow));
493   }
494 
495   /// Parse a '{' token.
496   ParseResult parseLBrace() override {
497     return parser.parseToken(Token::l_brace, "expected '{'");
498   }
499 
500   /// Parse a '{' token if present
501   ParseResult parseOptionalLBrace() override {
502     return success(parser.consumeIf(Token::l_brace));
503   }
504 
505   /// Parse a `}` token.
506   ParseResult parseRBrace() override {
507     return parser.parseToken(Token::r_brace, "expected '}'");
508   }
509 
510   /// Parse a `}` token if present
511   ParseResult parseOptionalRBrace() override {
512     return success(parser.consumeIf(Token::r_brace));
513   }
514 
515   /// Parse a `:` token.
516   ParseResult parseColon() override {
517     return parser.parseToken(Token::colon, "expected ':'");
518   }
519 
520   /// Parse a `:` token if present.
521   ParseResult parseOptionalColon() override {
522     return success(parser.consumeIf(Token::colon));
523   }
524 
525   /// Parse a `,` token.
526   ParseResult parseComma() override {
527     return parser.parseToken(Token::comma, "expected ','");
528   }
529 
530   /// Parse a `,` token if present.
531   ParseResult parseOptionalComma() override {
532     return success(parser.consumeIf(Token::comma));
533   }
534 
535   /// Parses a `...` if present.
536   ParseResult parseOptionalEllipsis() override {
537     return success(parser.consumeIf(Token::ellipsis));
538   }
539 
540   /// Parse a `=` token.
541   ParseResult parseEqual() override {
542     return parser.parseToken(Token::equal, "expected '='");
543   }
544 
545   /// Parse a '<' token.
546   ParseResult parseLess() override {
547     return parser.parseToken(Token::less, "expected '<'");
548   }
549 
550   /// Parse a `<` token if present.
551   ParseResult parseOptionalLess() override {
552     return success(parser.consumeIf(Token::less));
553   }
554 
555   /// Parse a '>' token.
556   ParseResult parseGreater() override {
557     return parser.parseToken(Token::greater, "expected '>'");
558   }
559 
560   /// Parse a `>` token if present.
561   ParseResult parseOptionalGreater() override {
562     return success(parser.consumeIf(Token::greater));
563   }
564 
565   /// Parse a `(` token.
566   ParseResult parseLParen() override {
567     return parser.parseToken(Token::l_paren, "expected '('");
568   }
569 
570   /// Parses a '(' if present.
571   ParseResult parseOptionalLParen() override {
572     return success(parser.consumeIf(Token::l_paren));
573   }
574 
575   /// Parse a `)` token.
576   ParseResult parseRParen() override {
577     return parser.parseToken(Token::r_paren, "expected ')'");
578   }
579 
580   /// Parses a ')' if present.
581   ParseResult parseOptionalRParen() override {
582     return success(parser.consumeIf(Token::r_paren));
583   }
584 
585   /// Parse a `[` token.
586   ParseResult parseLSquare() override {
587     return parser.parseToken(Token::l_square, "expected '['");
588   }
589 
590   /// Parses a '[' if present.
591   ParseResult parseOptionalLSquare() override {
592     return success(parser.consumeIf(Token::l_square));
593   }
594 
595   /// Parse a `]` token.
596   ParseResult parseRSquare() override {
597     return parser.parseToken(Token::r_square, "expected ']'");
598   }
599 
600   /// Parses a ']' if present.
601   ParseResult parseOptionalRSquare() override {
602     return success(parser.consumeIf(Token::r_square));
603   }
604 
605   /// Parses a '?' if present.
606   ParseResult parseOptionalQuestion() override {
607     return success(parser.consumeIf(Token::question));
608   }
609 
610   /// Parses a '*' if present.
611   ParseResult parseOptionalStar() override {
612     return success(parser.consumeIf(Token::star));
613   }
614 
615   /// Returns if the current token corresponds to a keyword.
616   bool isCurrentTokenAKeyword() const {
617     return parser.getToken().is(Token::bare_identifier) ||
618            parser.getToken().isKeyword();
619   }
620 
621   /// Parse the given keyword if present.
622   ParseResult parseOptionalKeyword(StringRef keyword) override {
623     // Check that the current token has the same spelling.
624     if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword)
625       return failure();
626     parser.consumeToken();
627     return success();
628   }
629 
630   /// Parse a keyword, if present, into 'keyword'.
631   ParseResult parseOptionalKeyword(StringRef *keyword) override {
632     // Check that the current token is a keyword.
633     if (!isCurrentTokenAKeyword())
634       return failure();
635 
636     *keyword = parser.getTokenSpelling();
637     parser.consumeToken();
638     return success();
639   }
640 
641   //===--------------------------------------------------------------------===//
642   // Attribute Parsing
643   //===--------------------------------------------------------------------===//
644 
645   /// Parse an arbitrary attribute and return it in result.
646   ParseResult parseAttribute(Attribute &result, Type type) override {
647     result = parser.parseAttribute(type);
648     return success(static_cast<bool>(result));
649   }
650 
651   /// Parse an affine map instance into 'map'.
652   ParseResult parseAffineMap(AffineMap &map) override {
653     return parser.parseAffineMapReference(map);
654   }
655 
656   /// Parse an integer set instance into 'set'.
657   ParseResult printIntegerSet(IntegerSet &set) override {
658     return parser.parseIntegerSetReference(set);
659   }
660 
661   //===--------------------------------------------------------------------===//
662   // Type Parsing
663   //===--------------------------------------------------------------------===//
664 
665   ParseResult parseType(Type &result) override {
666     result = parser.parseType();
667     return success(static_cast<bool>(result));
668   }
669 
670   ParseResult parseDimensionList(SmallVectorImpl<int64_t> &dimensions,
671                                  bool allowDynamic) override {
672     return parser.parseDimensionListRanked(dimensions, allowDynamic);
673   }
674 
675 private:
676   /// The full symbol specification.
677   StringRef fullSpec;
678 
679   /// The source location of the dialect symbol.
680   SMLoc nameLoc;
681 
682   /// The main parser.
683   Parser &parser;
684 };
685 } // namespace
686 
687 /// Parse the body of a pretty dialect symbol, which starts and ends with <>'s,
688 /// and may be recursive.  Return with the 'prettyName' StringRef encompassing
689 /// the entire pretty name.
690 ///
691 ///   pretty-dialect-sym-body ::= '<' pretty-dialect-sym-contents+ '>'
692 ///   pretty-dialect-sym-contents ::= pretty-dialect-sym-body
693 ///                                  | '(' pretty-dialect-sym-contents+ ')'
694 ///                                  | '[' pretty-dialect-sym-contents+ ']'
695 ///                                  | '{' pretty-dialect-sym-contents+ '}'
696 ///                                  | '[^[<({>\])}\0]+'
697 ///
698 ParseResult Parser::parsePrettyDialectSymbolName(StringRef &prettyName) {
699   // Pretty symbol names are a relatively unstructured format that contains a
700   // series of properly nested punctuation, with anything else in the middle.
701   // Scan ahead to find it and consume it if successful, otherwise emit an
702   // error.
703   auto *curPtr = getTokenSpelling().data();
704 
705   SmallVector<char, 8> nestedPunctuation;
706 
707   // Scan over the nested punctuation, bailing out on error and consuming until
708   // we find the end.  We know that we're currently looking at the '<', so we
709   // can go until we find the matching '>' character.
710   assert(*curPtr == '<');
711   do {
712     char c = *curPtr++;
713     switch (c) {
714     case '\0':
715       // This also handles the EOF case.
716       return emitError("unexpected nul or EOF in pretty dialect name");
717     case '<':
718     case '[':
719     case '(':
720     case '{':
721       nestedPunctuation.push_back(c);
722       continue;
723 
724     case '-':
725       // The sequence `->` is treated as special token.
726       if (*curPtr == '>')
727         ++curPtr;
728       continue;
729 
730     case '>':
731       if (nestedPunctuation.pop_back_val() != '<')
732         return emitError("unbalanced '>' character in pretty dialect name");
733       break;
734     case ']':
735       if (nestedPunctuation.pop_back_val() != '[')
736         return emitError("unbalanced ']' character in pretty dialect name");
737       break;
738     case ')':
739       if (nestedPunctuation.pop_back_val() != '(')
740         return emitError("unbalanced ')' character in pretty dialect name");
741       break;
742     case '}':
743       if (nestedPunctuation.pop_back_val() != '{')
744         return emitError("unbalanced '}' character in pretty dialect name");
745       break;
746 
747     default:
748       continue;
749     }
750   } while (!nestedPunctuation.empty());
751 
752   // Ok, we succeeded, remember where we stopped, reset the lexer to know it is
753   // consuming all this stuff, and return.
754   state.lex.resetPointer(curPtr);
755 
756   unsigned length = curPtr - prettyName.begin();
757   prettyName = StringRef(prettyName.begin(), length);
758   consumeToken();
759   return success();
760 }
761 
762 /// Parse an extended dialect symbol.
763 template <typename Symbol, typename SymbolAliasMap, typename CreateFn>
764 static Symbol parseExtendedSymbol(Parser &p, Token::Kind identifierTok,
765                                   SymbolAliasMap &aliases,
766                                   CreateFn &&createSymbol) {
767   // Parse the dialect namespace.
768   StringRef identifier = p.getTokenSpelling().drop_front();
769   auto loc = p.getToken().getLoc();
770   p.consumeToken(identifierTok);
771 
772   // If there is no '<' token following this, and if the typename contains no
773   // dot, then we are parsing a symbol alias.
774   if (p.getToken().isNot(Token::less) && !identifier.contains('.')) {
775     // Check for an alias for this type.
776     auto aliasIt = aliases.find(identifier);
777     if (aliasIt == aliases.end())
778       return (p.emitError("undefined symbol alias id '" + identifier + "'"),
779               nullptr);
780     return aliasIt->second;
781   }
782 
783   // Otherwise, we are parsing a dialect-specific symbol.  If the name contains
784   // a dot, then this is the "pretty" form.  If not, it is the verbose form that
785   // looks like <"...">.
786   std::string symbolData;
787   auto dialectName = identifier;
788 
789   // Handle the verbose form, where "identifier" is a simple dialect name.
790   if (!identifier.contains('.')) {
791     // Consume the '<'.
792     if (p.parseToken(Token::less, "expected '<' in dialect type"))
793       return nullptr;
794 
795     // Parse the symbol specific data.
796     if (p.getToken().isNot(Token::string))
797       return (p.emitError("expected string literal data in dialect symbol"),
798               nullptr);
799     symbolData = p.getToken().getStringValue();
800     loc = llvm::SMLoc::getFromPointer(p.getToken().getLoc().getPointer() + 1);
801     p.consumeToken(Token::string);
802 
803     // Consume the '>'.
804     if (p.parseToken(Token::greater, "expected '>' in dialect symbol"))
805       return nullptr;
806   } else {
807     // Ok, the dialect name is the part of the identifier before the dot, the
808     // part after the dot is the dialect's symbol, or the start thereof.
809     auto dotHalves = identifier.split('.');
810     dialectName = dotHalves.first;
811     auto prettyName = dotHalves.second;
812     loc = llvm::SMLoc::getFromPointer(prettyName.data());
813 
814     // If the dialect's symbol is followed immediately by a <, then lex the body
815     // of it into prettyName.
816     if (p.getToken().is(Token::less) &&
817         prettyName.bytes_end() == p.getTokenSpelling().bytes_begin()) {
818       if (p.parsePrettyDialectSymbolName(prettyName))
819         return nullptr;
820     }
821 
822     symbolData = prettyName.str();
823   }
824 
825   // Record the name location of the type remapped to the top level buffer.
826   llvm::SMLoc locInTopLevelBuffer = p.remapLocationToTopLevelBuffer(loc);
827   p.getState().symbols.nestedParserLocs.push_back(locInTopLevelBuffer);
828 
829   // Call into the provided symbol construction function.
830   Symbol sym = createSymbol(dialectName, symbolData, loc);
831 
832   // Pop the last parser location.
833   p.getState().symbols.nestedParserLocs.pop_back();
834   return sym;
835 }
836 
837 /// Parses a symbol, of type 'T', and returns it if parsing was successful. If
838 /// parsing failed, nullptr is returned. The number of bytes read from the input
839 /// string is returned in 'numRead'.
840 template <typename T, typename ParserFn>
841 static T parseSymbol(StringRef inputStr, MLIRContext *context,
842                      SymbolState &symbolState, ParserFn &&parserFn,
843                      size_t *numRead = nullptr) {
844   SourceMgr sourceMgr;
845   auto memBuffer = MemoryBuffer::getMemBuffer(
846       inputStr, /*BufferName=*/"<mlir_parser_buffer>",
847       /*RequiresNullTerminator=*/false);
848   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
849   ParserState state(sourceMgr, context, symbolState);
850   Parser parser(state);
851 
852   Token startTok = parser.getToken();
853   T symbol = parserFn(parser);
854   if (!symbol)
855     return T();
856 
857   // If 'numRead' is valid, then provide the number of bytes that were read.
858   Token endTok = parser.getToken();
859   if (numRead) {
860     *numRead = static_cast<size_t>(endTok.getLoc().getPointer() -
861                                    startTok.getLoc().getPointer());
862 
863     // Otherwise, ensure that all of the tokens were parsed.
864   } else if (startTok.getLoc() != endTok.getLoc() && endTok.isNot(Token::eof)) {
865     parser.emitError(endTok.getLoc(), "encountered unexpected token");
866     return T();
867   }
868   return symbol;
869 }
870 
871 //===----------------------------------------------------------------------===//
872 // Error Handling
873 //===----------------------------------------------------------------------===//
874 
875 InFlightDiagnostic Parser::emitError(SMLoc loc, const Twine &message) {
876   auto diag = mlir::emitError(getEncodedSourceLocation(loc), message);
877 
878   // If we hit a parse error in response to a lexer error, then the lexer
879   // already reported the error.
880   if (getToken().is(Token::error))
881     diag.abandon();
882   return diag;
883 }
884 
885 //===----------------------------------------------------------------------===//
886 // Token Parsing
887 //===----------------------------------------------------------------------===//
888 
889 /// Consume the specified token if present and return success.  On failure,
890 /// output a diagnostic and return failure.
891 ParseResult Parser::parseToken(Token::Kind expectedToken,
892                                const Twine &message) {
893   if (consumeIf(expectedToken))
894     return success();
895   return emitError(message);
896 }
897 
898 //===----------------------------------------------------------------------===//
899 // Type Parsing
900 //===----------------------------------------------------------------------===//
901 
902 /// Parse an arbitrary type.
903 ///
904 ///   type ::= function-type
905 ///          | non-function-type
906 ///
907 Type Parser::parseType() {
908   if (getToken().is(Token::l_paren))
909     return parseFunctionType();
910   return parseNonFunctionType();
911 }
912 
913 /// Parse a function result type.
914 ///
915 ///   function-result-type ::= type-list-parens
916 ///                          | non-function-type
917 ///
918 ParseResult Parser::parseFunctionResultTypes(SmallVectorImpl<Type> &elements) {
919   if (getToken().is(Token::l_paren))
920     return parseTypeListParens(elements);
921 
922   Type t = parseNonFunctionType();
923   if (!t)
924     return failure();
925   elements.push_back(t);
926   return success();
927 }
928 
929 /// Parse a list of types without an enclosing parenthesis.  The list must have
930 /// at least one member.
931 ///
932 ///   type-list-no-parens ::=  type (`,` type)*
933 ///
934 ParseResult Parser::parseTypeListNoParens(SmallVectorImpl<Type> &elements) {
935   auto parseElt = [&]() -> ParseResult {
936     auto elt = parseType();
937     elements.push_back(elt);
938     return elt ? success() : failure();
939   };
940 
941   return parseCommaSeparatedList(parseElt);
942 }
943 
944 /// Parse a parenthesized list of types.
945 ///
946 ///   type-list-parens ::= `(` `)`
947 ///                      | `(` type-list-no-parens `)`
948 ///
949 ParseResult Parser::parseTypeListParens(SmallVectorImpl<Type> &elements) {
950   if (parseToken(Token::l_paren, "expected '('"))
951     return failure();
952 
953   // Handle empty lists.
954   if (getToken().is(Token::r_paren))
955     return consumeToken(), success();
956 
957   if (parseTypeListNoParens(elements) ||
958       parseToken(Token::r_paren, "expected ')'"))
959     return failure();
960   return success();
961 }
962 
963 /// Parse a complex type.
964 ///
965 ///   complex-type ::= `complex` `<` type `>`
966 ///
967 Type Parser::parseComplexType() {
968   consumeToken(Token::kw_complex);
969 
970   // Parse the '<'.
971   if (parseToken(Token::less, "expected '<' in complex type"))
972     return nullptr;
973 
974   llvm::SMLoc elementTypeLoc = getToken().getLoc();
975   auto elementType = parseType();
976   if (!elementType ||
977       parseToken(Token::greater, "expected '>' in complex type"))
978     return nullptr;
979   if (!elementType.isa<FloatType>() && !elementType.isa<IntegerType>())
980     return emitError(elementTypeLoc, "invalid element type for complex"),
981            nullptr;
982 
983   return ComplexType::get(elementType);
984 }
985 
986 /// Parse an extended type.
987 ///
988 ///   extended-type ::= (dialect-type | type-alias)
989 ///   dialect-type  ::= `!` dialect-namespace `<` `"` type-data `"` `>`
990 ///   dialect-type  ::= `!` alias-name pretty-dialect-attribute-body?
991 ///   type-alias    ::= `!` alias-name
992 ///
993 Type Parser::parseExtendedType() {
994   return parseExtendedSymbol<Type>(
995       *this, Token::exclamation_identifier, state.symbols.typeAliasDefinitions,
996       [&](StringRef dialectName, StringRef symbolData,
997           llvm::SMLoc loc) -> Type {
998         // If we found a registered dialect, then ask it to parse the type.
999         if (auto *dialect = state.context->getRegisteredDialect(dialectName)) {
1000           return parseSymbol<Type>(
1001               symbolData, state.context, state.symbols, [&](Parser &parser) {
1002                 CustomDialectAsmParser customParser(symbolData, parser);
1003                 return dialect->parseType(customParser);
1004               });
1005         }
1006 
1007         // Otherwise, form a new opaque type.
1008         return OpaqueType::getChecked(
1009             Identifier::get(dialectName, state.context), symbolData,
1010             state.context, getEncodedSourceLocation(loc));
1011       });
1012 }
1013 
1014 /// Parse a function type.
1015 ///
1016 ///   function-type ::= type-list-parens `->` function-result-type
1017 ///
1018 Type Parser::parseFunctionType() {
1019   assert(getToken().is(Token::l_paren));
1020 
1021   SmallVector<Type, 4> arguments, results;
1022   if (parseTypeListParens(arguments) ||
1023       parseToken(Token::arrow, "expected '->' in function type") ||
1024       parseFunctionResultTypes(results))
1025     return nullptr;
1026 
1027   return builder.getFunctionType(arguments, results);
1028 }
1029 
1030 /// Parse the offset and strides from a strided layout specification.
1031 ///
1032 ///   strided-layout ::= `offset:` dimension `,` `strides: ` stride-list
1033 ///
1034 ParseResult Parser::parseStridedLayout(int64_t &offset,
1035                                        SmallVectorImpl<int64_t> &strides) {
1036   // Parse offset.
1037   consumeToken(Token::kw_offset);
1038   if (!consumeIf(Token::colon))
1039     return emitError("expected colon after `offset` keyword");
1040   auto maybeOffset = getToken().getUnsignedIntegerValue();
1041   bool question = getToken().is(Token::question);
1042   if (!maybeOffset && !question)
1043     return emitError("invalid offset");
1044   offset = maybeOffset ? static_cast<int64_t>(maybeOffset.getValue())
1045                        : MemRefType::getDynamicStrideOrOffset();
1046   consumeToken();
1047 
1048   if (!consumeIf(Token::comma))
1049     return emitError("expected comma after offset value");
1050 
1051   // Parse stride list.
1052   if (!consumeIf(Token::kw_strides))
1053     return emitError("expected `strides` keyword after offset specification");
1054   if (!consumeIf(Token::colon))
1055     return emitError("expected colon after `strides` keyword");
1056   if (failed(parseStrideList(strides)))
1057     return emitError("invalid braces-enclosed stride list");
1058   if (llvm::any_of(strides, [](int64_t st) { return st == 0; }))
1059     return emitError("invalid memref stride");
1060 
1061   return success();
1062 }
1063 
1064 /// Parse a memref type.
1065 ///
1066 ///   memref-type ::= ranked-memref-type | unranked-memref-type
1067 ///
1068 ///   ranked-memref-type ::= `memref` `<` dimension-list-ranked type
1069 ///                          (`,` semi-affine-map-composition)? (`,`
1070 ///                          memory-space)? `>`
1071 ///
1072 ///   unranked-memref-type ::= `memref` `<*x` type (`,` memory-space)? `>`
1073 ///
1074 ///   semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map
1075 ///   memory-space ::= integer-literal /* | TODO: address-space-id */
1076 ///
1077 Type Parser::parseMemRefType() {
1078   consumeToken(Token::kw_memref);
1079 
1080   if (parseToken(Token::less, "expected '<' in memref type"))
1081     return nullptr;
1082 
1083   bool isUnranked;
1084   SmallVector<int64_t, 4> dimensions;
1085 
1086   if (consumeIf(Token::star)) {
1087     // This is an unranked memref type.
1088     isUnranked = true;
1089     if (parseXInDimensionList())
1090       return nullptr;
1091 
1092   } else {
1093     isUnranked = false;
1094     if (parseDimensionListRanked(dimensions))
1095       return nullptr;
1096   }
1097 
1098   // Parse the element type.
1099   auto typeLoc = getToken().getLoc();
1100   auto elementType = parseType();
1101   if (!elementType)
1102     return nullptr;
1103 
1104   // Check that memref is formed from allowed types.
1105   if (!elementType.isIntOrFloat() && !elementType.isa<VectorType>() &&
1106       !elementType.isa<ComplexType>())
1107     return emitError(typeLoc, "invalid memref element type"), nullptr;
1108 
1109   // Parse semi-affine-map-composition.
1110   SmallVector<AffineMap, 2> affineMapComposition;
1111   Optional<unsigned> memorySpace;
1112   unsigned numDims = dimensions.size();
1113 
1114   auto parseElt = [&]() -> ParseResult {
1115     // Check for the memory space.
1116     if (getToken().is(Token::integer)) {
1117       if (memorySpace)
1118         return emitError("multiple memory spaces specified in memref type");
1119       memorySpace = getToken().getUnsignedIntegerValue();
1120       if (!memorySpace.hasValue())
1121         return emitError("invalid memory space in memref type");
1122       consumeToken(Token::integer);
1123       return success();
1124     }
1125     if (isUnranked)
1126       return emitError("cannot have affine map for unranked memref type");
1127     if (memorySpace)
1128       return emitError("expected memory space to be last in memref type");
1129 
1130     AffineMap map;
1131     llvm::SMLoc mapLoc = getToken().getLoc();
1132     if (getToken().is(Token::kw_offset)) {
1133       int64_t offset;
1134       SmallVector<int64_t, 4> strides;
1135       if (failed(parseStridedLayout(offset, strides)))
1136         return failure();
1137       // Construct strided affine map.
1138       map = makeStridedLinearLayoutMap(strides, offset, state.context);
1139     } else {
1140       // Parse an affine map attribute.
1141       auto affineMap = parseAttribute();
1142       if (!affineMap)
1143         return failure();
1144       auto affineMapAttr = affineMap.dyn_cast<AffineMapAttr>();
1145       if (!affineMapAttr)
1146         return emitError("expected affine map in memref type");
1147       map = affineMapAttr.getValue();
1148     }
1149 
1150     if (map.getNumDims() != numDims) {
1151       size_t i = affineMapComposition.size();
1152       return emitError(mapLoc, "memref affine map dimension mismatch between ")
1153              << (i == 0 ? Twine("memref rank") : "affine map " + Twine(i))
1154              << " and affine map" << i + 1 << ": " << numDims
1155              << " != " << map.getNumDims();
1156     }
1157     numDims = map.getNumResults();
1158     affineMapComposition.push_back(map);
1159     return success();
1160   };
1161 
1162   // Parse a list of mappings and address space if present.
1163   if (!consumeIf(Token::greater)) {
1164     // Parse comma separated list of affine maps, followed by memory space.
1165     if (parseToken(Token::comma, "expected ',' or '>' in memref type") ||
1166         parseCommaSeparatedListUntil(Token::greater, parseElt,
1167                                      /*allowEmptyList=*/false)) {
1168       return nullptr;
1169     }
1170   }
1171 
1172   if (isUnranked)
1173     return UnrankedMemRefType::get(elementType, memorySpace.getValueOr(0));
1174 
1175   return MemRefType::get(dimensions, elementType, affineMapComposition,
1176                          memorySpace.getValueOr(0));
1177 }
1178 
1179 /// Parse any type except the function type.
1180 ///
1181 ///   non-function-type ::= integer-type
1182 ///                       | index-type
1183 ///                       | float-type
1184 ///                       | extended-type
1185 ///                       | vector-type
1186 ///                       | tensor-type
1187 ///                       | memref-type
1188 ///                       | complex-type
1189 ///                       | tuple-type
1190 ///                       | none-type
1191 ///
1192 ///   index-type ::= `index`
1193 ///   float-type ::= `f16` | `bf16` | `f32` | `f64`
1194 ///   none-type ::= `none`
1195 ///
1196 Type Parser::parseNonFunctionType() {
1197   switch (getToken().getKind()) {
1198   default:
1199     return (emitError("expected non-function type"), nullptr);
1200   case Token::kw_memref:
1201     return parseMemRefType();
1202   case Token::kw_tensor:
1203     return parseTensorType();
1204   case Token::kw_complex:
1205     return parseComplexType();
1206   case Token::kw_tuple:
1207     return parseTupleType();
1208   case Token::kw_vector:
1209     return parseVectorType();
1210   // integer-type
1211   case Token::inttype: {
1212     auto width = getToken().getIntTypeBitwidth();
1213     if (!width.hasValue())
1214       return (emitError("invalid integer width"), nullptr);
1215     if (width.getValue() > IntegerType::kMaxWidth) {
1216       emitError(getToken().getLoc(), "integer bitwidth is limited to ")
1217           << IntegerType::kMaxWidth << " bits";
1218       return nullptr;
1219     }
1220 
1221     IntegerType::SignednessSemantics signSemantics = IntegerType::Signless;
1222     if (Optional<bool> signedness = getToken().getIntTypeSignedness())
1223       signSemantics = *signedness ? IntegerType::Signed : IntegerType::Unsigned;
1224 
1225     auto loc = getEncodedSourceLocation(getToken().getLoc());
1226     consumeToken(Token::inttype);
1227     return IntegerType::getChecked(width.getValue(), signSemantics, loc);
1228   }
1229 
1230   // float-type
1231   case Token::kw_bf16:
1232     consumeToken(Token::kw_bf16);
1233     return builder.getBF16Type();
1234   case Token::kw_f16:
1235     consumeToken(Token::kw_f16);
1236     return builder.getF16Type();
1237   case Token::kw_f32:
1238     consumeToken(Token::kw_f32);
1239     return builder.getF32Type();
1240   case Token::kw_f64:
1241     consumeToken(Token::kw_f64);
1242     return builder.getF64Type();
1243 
1244   // index-type
1245   case Token::kw_index:
1246     consumeToken(Token::kw_index);
1247     return builder.getIndexType();
1248 
1249   // none-type
1250   case Token::kw_none:
1251     consumeToken(Token::kw_none);
1252     return builder.getNoneType();
1253 
1254   // extended type
1255   case Token::exclamation_identifier:
1256     return parseExtendedType();
1257   }
1258 }
1259 
1260 /// Parse a tensor type.
1261 ///
1262 ///   tensor-type ::= `tensor` `<` dimension-list type `>`
1263 ///   dimension-list ::= dimension-list-ranked | `*x`
1264 ///
1265 Type Parser::parseTensorType() {
1266   consumeToken(Token::kw_tensor);
1267 
1268   if (parseToken(Token::less, "expected '<' in tensor type"))
1269     return nullptr;
1270 
1271   bool isUnranked;
1272   SmallVector<int64_t, 4> dimensions;
1273 
1274   if (consumeIf(Token::star)) {
1275     // This is an unranked tensor type.
1276     isUnranked = true;
1277 
1278     if (parseXInDimensionList())
1279       return nullptr;
1280 
1281   } else {
1282     isUnranked = false;
1283     if (parseDimensionListRanked(dimensions))
1284       return nullptr;
1285   }
1286 
1287   // Parse the element type.
1288   auto elementTypeLoc = getToken().getLoc();
1289   auto elementType = parseType();
1290   if (!elementType || parseToken(Token::greater, "expected '>' in tensor type"))
1291     return nullptr;
1292   if (!TensorType::isValidElementType(elementType))
1293     return emitError(elementTypeLoc, "invalid tensor element type"), nullptr;
1294 
1295   if (isUnranked)
1296     return UnrankedTensorType::get(elementType);
1297   return RankedTensorType::get(dimensions, elementType);
1298 }
1299 
1300 /// Parse a tuple type.
1301 ///
1302 ///   tuple-type ::= `tuple` `<` (type (`,` type)*)? `>`
1303 ///
1304 Type Parser::parseTupleType() {
1305   consumeToken(Token::kw_tuple);
1306 
1307   // Parse the '<'.
1308   if (parseToken(Token::less, "expected '<' in tuple type"))
1309     return nullptr;
1310 
1311   // Check for an empty tuple by directly parsing '>'.
1312   if (consumeIf(Token::greater))
1313     return TupleType::get(getContext());
1314 
1315   // Parse the element types and the '>'.
1316   SmallVector<Type, 4> types;
1317   if (parseTypeListNoParens(types) ||
1318       parseToken(Token::greater, "expected '>' in tuple type"))
1319     return nullptr;
1320 
1321   return TupleType::get(types, getContext());
1322 }
1323 
1324 /// Parse a vector type.
1325 ///
1326 ///   vector-type ::= `vector` `<` non-empty-static-dimension-list type `>`
1327 ///   non-empty-static-dimension-list ::= decimal-literal `x`
1328 ///                                       static-dimension-list
1329 ///   static-dimension-list ::= (decimal-literal `x`)*
1330 ///
1331 VectorType Parser::parseVectorType() {
1332   consumeToken(Token::kw_vector);
1333 
1334   if (parseToken(Token::less, "expected '<' in vector type"))
1335     return nullptr;
1336 
1337   SmallVector<int64_t, 4> dimensions;
1338   if (parseDimensionListRanked(dimensions, /*allowDynamic=*/false))
1339     return nullptr;
1340   if (dimensions.empty())
1341     return (emitError("expected dimension size in vector type"), nullptr);
1342   if (any_of(dimensions, [](int64_t i) { return i <= 0; }))
1343     return emitError(getToken().getLoc(),
1344                      "vector types must have positive constant sizes"),
1345            nullptr;
1346 
1347   // Parse the element type.
1348   auto typeLoc = getToken().getLoc();
1349   auto elementType = parseType();
1350   if (!elementType || parseToken(Token::greater, "expected '>' in vector type"))
1351     return nullptr;
1352   if (!VectorType::isValidElementType(elementType))
1353     return emitError(typeLoc, "vector elements must be int or float type"),
1354            nullptr;
1355 
1356   return VectorType::get(dimensions, elementType);
1357 }
1358 
1359 /// Parse a dimension list of a tensor or memref type.  This populates the
1360 /// dimension list, using -1 for the `?` dimensions if `allowDynamic` is set and
1361 /// errors out on `?` otherwise.
1362 ///
1363 ///   dimension-list-ranked ::= (dimension `x`)*
1364 ///   dimension ::= `?` | decimal-literal
1365 ///
1366 /// When `allowDynamic` is not set, this is used to parse:
1367 ///
1368 ///   static-dimension-list ::= (decimal-literal `x`)*
1369 ParseResult
1370 Parser::parseDimensionListRanked(SmallVectorImpl<int64_t> &dimensions,
1371                                  bool allowDynamic) {
1372   while (getToken().isAny(Token::integer, Token::question)) {
1373     if (consumeIf(Token::question)) {
1374       if (!allowDynamic)
1375         return emitError("expected static shape");
1376       dimensions.push_back(-1);
1377     } else {
1378       // Hexadecimal integer literals (starting with `0x`) are not allowed in
1379       // aggregate type declarations.  Therefore, `0xf32` should be processed as
1380       // a sequence of separate elements `0`, `x`, `f32`.
1381       if (getTokenSpelling().size() > 1 && getTokenSpelling()[1] == 'x') {
1382         // We can get here only if the token is an integer literal.  Hexadecimal
1383         // integer literals can only start with `0x` (`1x` wouldn't lex as a
1384         // literal, just `1` would, at which point we don't get into this
1385         // branch).
1386         assert(getTokenSpelling()[0] == '0' && "invalid integer literal");
1387         dimensions.push_back(0);
1388         state.lex.resetPointer(getTokenSpelling().data() + 1);
1389         consumeToken();
1390       } else {
1391         // Make sure this integer value is in bound and valid.
1392         auto dimension = getToken().getUnsignedIntegerValue();
1393         if (!dimension.hasValue())
1394           return emitError("invalid dimension");
1395         dimensions.push_back((int64_t)dimension.getValue());
1396         consumeToken(Token::integer);
1397       }
1398     }
1399 
1400     // Make sure we have an 'x' or something like 'xbf32'.
1401     if (parseXInDimensionList())
1402       return failure();
1403   }
1404 
1405   return success();
1406 }
1407 
1408 /// Parse an 'x' token in a dimension list, handling the case where the x is
1409 /// juxtaposed with an element type, as in "xf32", leaving the "f32" as the next
1410 /// token.
1411 ParseResult Parser::parseXInDimensionList() {
1412   if (getToken().isNot(Token::bare_identifier) || getTokenSpelling()[0] != 'x')
1413     return emitError("expected 'x' in dimension list");
1414 
1415   // If we had a prefix of 'x', lex the next token immediately after the 'x'.
1416   if (getTokenSpelling().size() != 1)
1417     state.lex.resetPointer(getTokenSpelling().data() + 1);
1418 
1419   // Consume the 'x'.
1420   consumeToken(Token::bare_identifier);
1421 
1422   return success();
1423 }
1424 
1425 // Parse a comma-separated list of dimensions, possibly empty:
1426 //   stride-list ::= `[` (dimension (`,` dimension)*)? `]`
1427 ParseResult Parser::parseStrideList(SmallVectorImpl<int64_t> &dimensions) {
1428   if (!consumeIf(Token::l_square))
1429     return failure();
1430   // Empty list early exit.
1431   if (consumeIf(Token::r_square))
1432     return success();
1433   while (true) {
1434     if (consumeIf(Token::question)) {
1435       dimensions.push_back(MemRefType::getDynamicStrideOrOffset());
1436     } else {
1437       // This must be an integer value.
1438       int64_t val;
1439       if (getToken().getSpelling().getAsInteger(10, val))
1440         return emitError("invalid integer value: ") << getToken().getSpelling();
1441       // Make sure it is not the one value for `?`.
1442       if (ShapedType::isDynamic(val))
1443         return emitError("invalid integer value: ")
1444                << getToken().getSpelling()
1445                << ", use `?` to specify a dynamic dimension";
1446       dimensions.push_back(val);
1447       consumeToken(Token::integer);
1448     }
1449     if (!consumeIf(Token::comma))
1450       break;
1451   }
1452   if (!consumeIf(Token::r_square))
1453     return failure();
1454   return success();
1455 }
1456 
1457 //===----------------------------------------------------------------------===//
1458 // Attribute parsing.
1459 //===----------------------------------------------------------------------===//
1460 
1461 /// Return the symbol reference referred to by the given token, that is known to
1462 /// be an @-identifier.
1463 static std::string extractSymbolReference(Token tok) {
1464   assert(tok.is(Token::at_identifier) && "expected valid @-identifier");
1465   StringRef nameStr = tok.getSpelling().drop_front();
1466 
1467   // Check to see if the reference is a string literal, or a bare identifier.
1468   if (nameStr.front() == '"')
1469     return tok.getStringValue();
1470   return std::string(nameStr);
1471 }
1472 
1473 /// Parse an arbitrary attribute.
1474 ///
1475 ///  attribute-value ::= `unit`
1476 ///                    | bool-literal
1477 ///                    | integer-literal (`:` (index-type | integer-type))?
1478 ///                    | float-literal (`:` float-type)?
1479 ///                    | string-literal (`:` type)?
1480 ///                    | type
1481 ///                    | `[` (attribute-value (`,` attribute-value)*)? `]`
1482 ///                    | `{` (attribute-entry (`,` attribute-entry)*)? `}`
1483 ///                    | symbol-ref-id (`::` symbol-ref-id)*
1484 ///                    | `dense` `<` attribute-value `>` `:`
1485 ///                      (tensor-type | vector-type)
1486 ///                    | `sparse` `<` attribute-value `,` attribute-value `>`
1487 ///                      `:` (tensor-type | vector-type)
1488 ///                    | `opaque` `<` dialect-namespace  `,` hex-string-literal
1489 ///                      `>` `:` (tensor-type | vector-type)
1490 ///                    | extended-attribute
1491 ///
1492 Attribute Parser::parseAttribute(Type type) {
1493   switch (getToken().getKind()) {
1494   // Parse an AffineMap or IntegerSet attribute.
1495   case Token::kw_affine_map: {
1496     consumeToken(Token::kw_affine_map);
1497 
1498     AffineMap map;
1499     if (parseToken(Token::less, "expected '<' in affine map") ||
1500         parseAffineMapReference(map) ||
1501         parseToken(Token::greater, "expected '>' in affine map"))
1502       return Attribute();
1503     return AffineMapAttr::get(map);
1504   }
1505   case Token::kw_affine_set: {
1506     consumeToken(Token::kw_affine_set);
1507 
1508     IntegerSet set;
1509     if (parseToken(Token::less, "expected '<' in integer set") ||
1510         parseIntegerSetReference(set) ||
1511         parseToken(Token::greater, "expected '>' in integer set"))
1512       return Attribute();
1513     return IntegerSetAttr::get(set);
1514   }
1515 
1516   // Parse an array attribute.
1517   case Token::l_square: {
1518     consumeToken(Token::l_square);
1519 
1520     SmallVector<Attribute, 4> elements;
1521     auto parseElt = [&]() -> ParseResult {
1522       elements.push_back(parseAttribute());
1523       return elements.back() ? success() : failure();
1524     };
1525 
1526     if (parseCommaSeparatedListUntil(Token::r_square, parseElt))
1527       return nullptr;
1528     return builder.getArrayAttr(elements);
1529   }
1530 
1531   // Parse a boolean attribute.
1532   case Token::kw_false:
1533     consumeToken(Token::kw_false);
1534     return builder.getBoolAttr(false);
1535   case Token::kw_true:
1536     consumeToken(Token::kw_true);
1537     return builder.getBoolAttr(true);
1538 
1539   // Parse a dense elements attribute.
1540   case Token::kw_dense:
1541     return parseDenseElementsAttr(type);
1542 
1543   // Parse a dictionary attribute.
1544   case Token::l_brace: {
1545     SmallVector<NamedAttribute, 4> elements;
1546     if (parseAttributeDict(elements))
1547       return nullptr;
1548     return builder.getDictionaryAttr(elements);
1549   }
1550 
1551   // Parse an extended attribute, i.e. alias or dialect attribute.
1552   case Token::hash_identifier:
1553     return parseExtendedAttr(type);
1554 
1555   // Parse floating point and integer attributes.
1556   case Token::floatliteral:
1557     return parseFloatAttr(type, /*isNegative=*/false);
1558   case Token::integer:
1559     return parseDecOrHexAttr(type, /*isNegative=*/false);
1560   case Token::minus: {
1561     consumeToken(Token::minus);
1562     if (getToken().is(Token::integer))
1563       return parseDecOrHexAttr(type, /*isNegative=*/true);
1564     if (getToken().is(Token::floatliteral))
1565       return parseFloatAttr(type, /*isNegative=*/true);
1566 
1567     return (emitError("expected constant integer or floating point value"),
1568             nullptr);
1569   }
1570 
1571   // Parse a location attribute.
1572   case Token::kw_loc: {
1573     LocationAttr attr;
1574     return failed(parseLocation(attr)) ? Attribute() : attr;
1575   }
1576 
1577   // Parse an opaque elements attribute.
1578   case Token::kw_opaque:
1579     return parseOpaqueElementsAttr(type);
1580 
1581   // Parse a sparse elements attribute.
1582   case Token::kw_sparse:
1583     return parseSparseElementsAttr(type);
1584 
1585   // Parse a string attribute.
1586   case Token::string: {
1587     auto val = getToken().getStringValue();
1588     consumeToken(Token::string);
1589     // Parse the optional trailing colon type if one wasn't explicitly provided.
1590     if (!type && consumeIf(Token::colon) && !(type = parseType()))
1591       return Attribute();
1592 
1593     return type ? StringAttr::get(val, type)
1594                 : StringAttr::get(val, getContext());
1595   }
1596 
1597   // Parse a symbol reference attribute.
1598   case Token::at_identifier: {
1599     std::string nameStr = extractSymbolReference(getToken());
1600     consumeToken(Token::at_identifier);
1601 
1602     // Parse any nested references.
1603     std::vector<FlatSymbolRefAttr> nestedRefs;
1604     while (getToken().is(Token::colon)) {
1605       // Check for the '::' prefix.
1606       const char *curPointer = getToken().getLoc().getPointer();
1607       consumeToken(Token::colon);
1608       if (!consumeIf(Token::colon)) {
1609         state.lex.resetPointer(curPointer);
1610         consumeToken();
1611         break;
1612       }
1613       // Parse the reference itself.
1614       auto curLoc = getToken().getLoc();
1615       if (getToken().isNot(Token::at_identifier)) {
1616         emitError(curLoc, "expected nested symbol reference identifier");
1617         return Attribute();
1618       }
1619 
1620       std::string nameStr = extractSymbolReference(getToken());
1621       consumeToken(Token::at_identifier);
1622       nestedRefs.push_back(SymbolRefAttr::get(nameStr, getContext()));
1623     }
1624 
1625     return builder.getSymbolRefAttr(nameStr, nestedRefs);
1626   }
1627 
1628   // Parse a 'unit' attribute.
1629   case Token::kw_unit:
1630     consumeToken(Token::kw_unit);
1631     return builder.getUnitAttr();
1632 
1633   default:
1634     // Parse a type attribute.
1635     if (Type type = parseType())
1636       return TypeAttr::get(type);
1637     return nullptr;
1638   }
1639 }
1640 
1641 /// Attribute dictionary.
1642 ///
1643 ///   attribute-dict ::= `{` `}`
1644 ///                    | `{` attribute-entry (`,` attribute-entry)* `}`
1645 ///   attribute-entry ::= bare-id `=` attribute-value
1646 ///
1647 ParseResult
1648 Parser::parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes) {
1649   if (parseToken(Token::l_brace, "expected '{' in attribute dictionary"))
1650     return failure();
1651 
1652   auto parseElt = [&]() -> ParseResult {
1653     // We allow keywords as attribute names.
1654     if (getToken().isNot(Token::bare_identifier, Token::inttype) &&
1655         !getToken().isKeyword())
1656       return emitError("expected attribute name");
1657     Identifier nameId = builder.getIdentifier(getTokenSpelling());
1658     consumeToken();
1659 
1660     // Try to parse the '=' for the attribute value.
1661     if (!consumeIf(Token::equal)) {
1662       // If there is no '=', we treat this as a unit attribute.
1663       attributes.push_back({nameId, builder.getUnitAttr()});
1664       return success();
1665     }
1666 
1667     auto attr = parseAttribute();
1668     if (!attr)
1669       return failure();
1670 
1671     attributes.push_back({nameId, attr});
1672     return success();
1673   };
1674 
1675   if (parseCommaSeparatedListUntil(Token::r_brace, parseElt))
1676     return failure();
1677 
1678   return success();
1679 }
1680 
1681 /// Parse an extended attribute.
1682 ///
1683 ///   extended-attribute ::= (dialect-attribute | attribute-alias)
1684 ///   dialect-attribute  ::= `#` dialect-namespace `<` `"` attr-data `"` `>`
1685 ///   dialect-attribute  ::= `#` alias-name pretty-dialect-sym-body?
1686 ///   attribute-alias    ::= `#` alias-name
1687 ///
1688 Attribute Parser::parseExtendedAttr(Type type) {
1689   Attribute attr = parseExtendedSymbol<Attribute>(
1690       *this, Token::hash_identifier, state.symbols.attributeAliasDefinitions,
1691       [&](StringRef dialectName, StringRef symbolData,
1692           llvm::SMLoc loc) -> Attribute {
1693         // Parse an optional trailing colon type.
1694         Type attrType = type;
1695         if (consumeIf(Token::colon) && !(attrType = parseType()))
1696           return Attribute();
1697 
1698         // If we found a registered dialect, then ask it to parse the attribute.
1699         if (auto *dialect = state.context->getRegisteredDialect(dialectName)) {
1700           return parseSymbol<Attribute>(
1701               symbolData, state.context, state.symbols, [&](Parser &parser) {
1702                 CustomDialectAsmParser customParser(symbolData, parser);
1703                 return dialect->parseAttribute(customParser, attrType);
1704               });
1705         }
1706 
1707         // Otherwise, form a new opaque attribute.
1708         return OpaqueAttr::getChecked(
1709             Identifier::get(dialectName, state.context), symbolData,
1710             attrType ? attrType : NoneType::get(state.context),
1711             getEncodedSourceLocation(loc));
1712       });
1713 
1714   // Ensure that the attribute has the same type as requested.
1715   if (attr && type && attr.getType() != type) {
1716     emitError("attribute type different than expected: expected ")
1717         << type << ", but got " << attr.getType();
1718     return nullptr;
1719   }
1720   return attr;
1721 }
1722 
1723 /// Parse a float attribute.
1724 Attribute Parser::parseFloatAttr(Type type, bool isNegative) {
1725   auto val = getToken().getFloatingPointValue();
1726   if (!val.hasValue())
1727     return (emitError("floating point value too large for attribute"), nullptr);
1728   consumeToken(Token::floatliteral);
1729   if (!type) {
1730     // Default to F64 when no type is specified.
1731     if (!consumeIf(Token::colon))
1732       type = builder.getF64Type();
1733     else if (!(type = parseType()))
1734       return nullptr;
1735   }
1736   if (!type.isa<FloatType>())
1737     return (emitError("floating point value not valid for specified type"),
1738             nullptr);
1739   return FloatAttr::get(type, isNegative ? -val.getValue() : val.getValue());
1740 }
1741 
1742 /// Construct a float attribute bitwise equivalent to the integer literal.
1743 static Optional<APFloat> buildHexadecimalFloatLiteral(Parser *p, FloatType type,
1744                                                       uint64_t value) {
1745   // FIXME: bfloat is currently stored as a double internally because it doesn't
1746   // have valid APFloat semantics.
1747   if (type.isF64() || type.isBF16())
1748     return APFloat(type.getFloatSemantics(), APInt(/*numBits=*/64, value));
1749 
1750   APInt apInt(type.getWidth(), value);
1751   if (apInt != value) {
1752     p->emitError("hexadecimal float constant out of range for type");
1753     return llvm::None;
1754   }
1755   return APFloat(type.getFloatSemantics(), apInt);
1756 }
1757 
1758 /// Parse a decimal or a hexadecimal literal, which can be either an integer
1759 /// or a float attribute.
1760 Attribute Parser::parseDecOrHexAttr(Type type, bool isNegative) {
1761   auto val = getToken().getUInt64IntegerValue();
1762   if (!val.hasValue())
1763     return (emitError("integer constant out of range for attribute"), nullptr);
1764 
1765   // Remember if the literal is hexadecimal.
1766   StringRef spelling = getToken().getSpelling();
1767   auto loc = state.curToken.getLoc();
1768   bool isHex = spelling.size() > 1 && spelling[1] == 'x';
1769 
1770   consumeToken(Token::integer);
1771   if (!type) {
1772     // Default to i64 if not type is specified.
1773     if (!consumeIf(Token::colon))
1774       type = builder.getIntegerType(64);
1775     else if (!(type = parseType()))
1776       return nullptr;
1777   }
1778 
1779   if (auto floatType = type.dyn_cast<FloatType>()) {
1780     if (isNegative)
1781       return emitError(
1782                  loc,
1783                  "hexadecimal float literal should not have a leading minus"),
1784              nullptr;
1785     if (!isHex) {
1786       emitError(loc, "unexpected decimal integer literal for a float attribute")
1787               .attachNote()
1788           << "add a trailing dot to make the literal a float";
1789       return nullptr;
1790     }
1791 
1792     // Construct a float attribute bitwise equivalent to the integer literal.
1793     Optional<APFloat> apVal =
1794         buildHexadecimalFloatLiteral(this, floatType, *val);
1795     return apVal ? FloatAttr::get(floatType, *apVal) : Attribute();
1796   }
1797 
1798   if (!type.isa<IntegerType>() && !type.isa<IndexType>())
1799     return emitError(loc, "integer literal not valid for specified type"),
1800            nullptr;
1801 
1802   if (isNegative && type.isUnsignedInteger()) {
1803     emitError(loc,
1804               "negative integer literal not valid for unsigned integer type");
1805     return nullptr;
1806   }
1807 
1808   // Parse the integer literal.
1809   int width = type.isIndex() ? 64 : type.getIntOrFloatBitWidth();
1810   APInt apInt(width, *val, isNegative);
1811   if (apInt != *val)
1812     return emitError(loc, "integer constant out of range for attribute"),
1813            nullptr;
1814 
1815   // Otherwise construct an integer attribute.
1816   if (isNegative ? (int64_t)-val.getValue() >= 0 : (int64_t)val.getValue() < 0)
1817     return emitError(loc, "integer constant out of range for attribute"),
1818            nullptr;
1819 
1820   return builder.getIntegerAttr(type, isNegative ? -apInt : apInt);
1821 }
1822 
1823 /// Parse elements values stored within a hex etring. On success, the values are
1824 /// stored into 'result'.
1825 static ParseResult parseElementAttrHexValues(Parser &parser, Token tok,
1826                                              std::string &result) {
1827   std::string val = tok.getStringValue();
1828   if (val.size() < 2 || val[0] != '0' || val[1] != 'x')
1829     return parser.emitError(tok.getLoc(),
1830                             "elements hex string should start with '0x'");
1831 
1832   StringRef hexValues = StringRef(val).drop_front(2);
1833   if (!llvm::all_of(hexValues, llvm::isHexDigit))
1834     return parser.emitError(tok.getLoc(),
1835                             "elements hex string only contains hex digits");
1836 
1837   result = llvm::fromHex(hexValues);
1838   return success();
1839 }
1840 
1841 /// Parse an opaque elements attribute.
1842 Attribute Parser::parseOpaqueElementsAttr(Type attrType) {
1843   consumeToken(Token::kw_opaque);
1844   if (parseToken(Token::less, "expected '<' after 'opaque'"))
1845     return nullptr;
1846 
1847   if (getToken().isNot(Token::string))
1848     return (emitError("expected dialect namespace"), nullptr);
1849 
1850   auto name = getToken().getStringValue();
1851   auto *dialect = builder.getContext()->getRegisteredDialect(name);
1852   // TODO(shpeisman): Allow for having an unknown dialect on an opaque
1853   // attribute. Otherwise, it can't be roundtripped without having the dialect
1854   // registered.
1855   if (!dialect)
1856     return (emitError("no registered dialect with namespace '" + name + "'"),
1857             nullptr);
1858   consumeToken(Token::string);
1859 
1860   if (parseToken(Token::comma, "expected ','"))
1861     return nullptr;
1862 
1863   Token hexTok = getToken();
1864   if (parseToken(Token::string, "elements hex string should start with '0x'") ||
1865       parseToken(Token::greater, "expected '>'"))
1866     return nullptr;
1867   auto type = parseElementsLiteralType(attrType);
1868   if (!type)
1869     return nullptr;
1870 
1871   std::string data;
1872   if (parseElementAttrHexValues(*this, hexTok, data))
1873     return nullptr;
1874   return OpaqueElementsAttr::get(dialect, type, data);
1875 }
1876 
1877 namespace {
1878 class TensorLiteralParser {
1879 public:
1880   TensorLiteralParser(Parser &p) : p(p) {}
1881 
1882   /// Parse the elements of a tensor literal. If 'allowHex' is true, the parser
1883   /// may also parse a tensor literal that is store as a hex string.
1884   ParseResult parse(bool allowHex);
1885 
1886   /// Build a dense attribute instance with the parsed elements and the given
1887   /// shaped type.
1888   DenseElementsAttr getAttr(llvm::SMLoc loc, ShapedType type);
1889 
1890   ArrayRef<int64_t> getShape() const { return shape; }
1891 
1892 private:
1893   enum class ElementKind { Boolean, Integer, Float };
1894 
1895   /// Return a string to represent the given element kind.
1896   const char *getElementKindStr(ElementKind kind) {
1897     switch (kind) {
1898     case ElementKind::Boolean:
1899       return "'boolean'";
1900     case ElementKind::Integer:
1901       return "'integer'";
1902     case ElementKind::Float:
1903       return "'float'";
1904     }
1905     llvm_unreachable("unknown element kind");
1906   }
1907 
1908   /// Build a Dense Integer attribute for the given type.
1909   DenseElementsAttr getIntAttr(llvm::SMLoc loc, ShapedType type,
1910                                IntegerType eltTy);
1911 
1912   /// Build a Dense Float attribute for the given type.
1913   DenseElementsAttr getFloatAttr(llvm::SMLoc loc, ShapedType type,
1914                                  FloatType eltTy);
1915 
1916   /// Build a Dense attribute with hex data for the given type.
1917   DenseElementsAttr getHexAttr(llvm::SMLoc loc, ShapedType type);
1918 
1919   /// Parse a single element, returning failure if it isn't a valid element
1920   /// literal. For example:
1921   /// parseElement(1) -> Success, 1
1922   /// parseElement([1]) -> Failure
1923   ParseResult parseElement();
1924 
1925   /// Parse a list of either lists or elements, returning the dimensions of the
1926   /// parsed sub-tensors in dims. For example:
1927   ///   parseList([1, 2, 3]) -> Success, [3]
1928   ///   parseList([[1, 2], [3, 4]]) -> Success, [2, 2]
1929   ///   parseList([[1, 2], 3]) -> Failure
1930   ///   parseList([[1, [2, 3]], [4, [5]]]) -> Failure
1931   ParseResult parseList(SmallVectorImpl<int64_t> &dims);
1932 
1933   /// Parse a literal that was printed as a hex string.
1934   ParseResult parseHexElements();
1935 
1936   Parser &p;
1937 
1938   /// The shape inferred from the parsed elements.
1939   SmallVector<int64_t, 4> shape;
1940 
1941   /// Storage used when parsing elements, this is a pair of <is_negated, token>.
1942   std::vector<std::pair<bool, Token>> storage;
1943 
1944   /// A flag that indicates the type of elements that have been parsed.
1945   Optional<ElementKind> knownEltKind;
1946 
1947   /// Storage used when parsing elements that were stored as hex values.
1948   Optional<Token> hexStorage;
1949 };
1950 } // namespace
1951 
1952 /// Parse the elements of a tensor literal. If 'allowHex' is true, the parser
1953 /// may also parse a tensor literal that is store as a hex string.
1954 ParseResult TensorLiteralParser::parse(bool allowHex) {
1955   // If hex is allowed, check for a string literal.
1956   if (allowHex && p.getToken().is(Token::string)) {
1957     hexStorage = p.getToken();
1958     p.consumeToken(Token::string);
1959     return success();
1960   }
1961   // Otherwise, parse a list or an individual element.
1962   if (p.getToken().is(Token::l_square))
1963     return parseList(shape);
1964   return parseElement();
1965 }
1966 
1967 /// Build a dense attribute instance with the parsed elements and the given
1968 /// shaped type.
1969 DenseElementsAttr TensorLiteralParser::getAttr(llvm::SMLoc loc,
1970                                                ShapedType type) {
1971   // Check to see if we parsed the literal from a hex string.
1972   if (hexStorage.hasValue())
1973     return getHexAttr(loc, type);
1974 
1975   // Check that the parsed storage size has the same number of elements to the
1976   // type, or is a known splat.
1977   if (!shape.empty() && getShape() != type.getShape()) {
1978     p.emitError(loc) << "inferred shape of elements literal ([" << getShape()
1979                      << "]) does not match type ([" << type.getShape() << "])";
1980     return nullptr;
1981   }
1982 
1983   // If the type is an integer, build a set of APInt values from the storage
1984   // with the correct bitwidth.
1985   if (auto intTy = type.getElementType().dyn_cast<IntegerType>())
1986     return getIntAttr(loc, type, intTy);
1987 
1988   // Otherwise, this must be a floating point type.
1989   auto floatTy = type.getElementType().dyn_cast<FloatType>();
1990   if (!floatTy) {
1991     p.emitError(loc) << "expected floating-point or integer element type, got "
1992                      << type.getElementType();
1993     return nullptr;
1994   }
1995   return getFloatAttr(loc, type, floatTy);
1996 }
1997 
1998 /// Build a Dense Integer attribute for the given type.
1999 DenseElementsAttr TensorLiteralParser::getIntAttr(llvm::SMLoc loc,
2000                                                   ShapedType type,
2001                                                   IntegerType eltTy) {
2002   std::vector<APInt> intElements;
2003   intElements.reserve(storage.size());
2004   auto isUintType = type.getElementType().isUnsignedInteger();
2005   for (const auto &signAndToken : storage) {
2006     bool isNegative = signAndToken.first;
2007     const Token &token = signAndToken.second;
2008     auto tokenLoc = token.getLoc();
2009 
2010     if (isNegative && isUintType) {
2011       p.emitError(tokenLoc)
2012           << "expected unsigned integer elements, but parsed negative value";
2013       return nullptr;
2014     }
2015 
2016     // Check to see if floating point values were parsed.
2017     if (token.is(Token::floatliteral)) {
2018       p.emitError(tokenLoc)
2019           << "expected integer elements, but parsed floating-point";
2020       return nullptr;
2021     }
2022 
2023     assert(token.isAny(Token::integer, Token::kw_true, Token::kw_false) &&
2024            "unexpected token type");
2025     if (token.isAny(Token::kw_true, Token::kw_false)) {
2026       if (!eltTy.isInteger(1))
2027         p.emitError(tokenLoc)
2028             << "expected i1 type for 'true' or 'false' values";
2029       APInt apInt(eltTy.getWidth(), token.is(Token::kw_true),
2030                   /*isSigned=*/false);
2031       intElements.push_back(apInt);
2032       continue;
2033     }
2034 
2035     // Create APInt values for each element with the correct bitwidth.
2036     auto val = token.getUInt64IntegerValue();
2037     if (!val.hasValue() || (isNegative ? (int64_t)-val.getValue() >= 0
2038                                        : (int64_t)val.getValue() < 0)) {
2039       p.emitError(tokenLoc, "integer constant out of range for attribute");
2040       return nullptr;
2041     }
2042     APInt apInt(eltTy.getWidth(), val.getValue(), isNegative);
2043     if (apInt != val.getValue())
2044       return (p.emitError(tokenLoc, "integer constant out of range for type"),
2045               nullptr);
2046     intElements.push_back(isNegative ? -apInt : apInt);
2047   }
2048 
2049   return DenseElementsAttr::get(type, intElements);
2050 }
2051 
2052 /// Build a Dense Float attribute for the given type.
2053 DenseElementsAttr TensorLiteralParser::getFloatAttr(llvm::SMLoc loc,
2054                                                     ShapedType type,
2055                                                     FloatType eltTy) {
2056   std::vector<APFloat> floatValues;
2057   floatValues.reserve(storage.size());
2058   for (const auto &signAndToken : storage) {
2059     bool isNegative = signAndToken.first;
2060     const Token &token = signAndToken.second;
2061 
2062     // Handle hexadecimal float literals.
2063     if (token.is(Token::integer) && token.getSpelling().startswith("0x")) {
2064       if (isNegative) {
2065         p.emitError(token.getLoc())
2066             << "hexadecimal float literal should not have a leading minus";
2067         return nullptr;
2068       }
2069       auto val = token.getUInt64IntegerValue();
2070       if (!val.hasValue()) {
2071         p.emitError("hexadecimal float constant out of range for attribute");
2072         return nullptr;
2073       }
2074       Optional<APFloat> apVal = buildHexadecimalFloatLiteral(&p, eltTy, *val);
2075       if (!apVal)
2076         return nullptr;
2077       floatValues.push_back(*apVal);
2078       continue;
2079     }
2080 
2081     // Check to see if any decimal integers or booleans were parsed.
2082     if (!token.is(Token::floatliteral)) {
2083       p.emitError() << "expected floating-point elements, but parsed integer";
2084       return nullptr;
2085     }
2086 
2087     // Build the float values from tokens.
2088     auto val = token.getFloatingPointValue();
2089     if (!val.hasValue()) {
2090       p.emitError("floating point value too large for attribute");
2091       return nullptr;
2092     }
2093     // Treat BF16 as double because it is not supported in LLVM's APFloat.
2094     APFloat apVal(isNegative ? -*val : *val);
2095     if (!eltTy.isBF16() && !eltTy.isF64()) {
2096       bool unused;
2097       apVal.convert(eltTy.getFloatSemantics(), APFloat::rmNearestTiesToEven,
2098                     &unused);
2099     }
2100     floatValues.push_back(apVal);
2101   }
2102 
2103   return DenseElementsAttr::get(type, floatValues);
2104 }
2105 
2106 /// Build a Dense attribute with hex data for the given type.
2107 DenseElementsAttr TensorLiteralParser::getHexAttr(llvm::SMLoc loc,
2108                                                   ShapedType type) {
2109   Type elementType = type.getElementType();
2110   if (!elementType.isa<FloatType>() && !elementType.isa<IntegerType>()) {
2111     p.emitError(loc) << "expected floating-point or integer element type, got "
2112                      << elementType;
2113     return nullptr;
2114   }
2115 
2116   std::string data;
2117   if (parseElementAttrHexValues(p, hexStorage.getValue(), data))
2118     return nullptr;
2119 
2120   // Check that the size of the hex data correpsonds to the size of the type, or
2121   // a splat of the type.
2122   // TODO: bf16 is currently stored as a double, this should be removed when
2123   // APFloat properly supports it.
2124   int64_t elementWidth =
2125       elementType.isBF16() ? 64 : elementType.getIntOrFloatBitWidth();
2126   if (static_cast<int64_t>(data.size() * CHAR_BIT) !=
2127       (type.getNumElements() * elementWidth)) {
2128     p.emitError(loc) << "elements hex data size is invalid for provided type: "
2129                      << type;
2130     return nullptr;
2131   }
2132 
2133   return DenseElementsAttr::getFromRawBuffer(
2134       type, ArrayRef<char>(data.data(), data.size()), /*isSplatBuffer=*/false);
2135 }
2136 
2137 ParseResult TensorLiteralParser::parseElement() {
2138   switch (p.getToken().getKind()) {
2139   // Parse a boolean element.
2140   case Token::kw_true:
2141   case Token::kw_false:
2142   case Token::floatliteral:
2143   case Token::integer:
2144     storage.emplace_back(/*isNegative=*/false, p.getToken());
2145     p.consumeToken();
2146     break;
2147 
2148   // Parse a signed integer or a negative floating-point element.
2149   case Token::minus:
2150     p.consumeToken(Token::minus);
2151     if (!p.getToken().isAny(Token::floatliteral, Token::integer))
2152       return p.emitError("expected integer or floating point literal");
2153     storage.emplace_back(/*isNegative=*/true, p.getToken());
2154     p.consumeToken();
2155     break;
2156 
2157   default:
2158     return p.emitError("expected element literal of primitive type");
2159   }
2160 
2161   return success();
2162 }
2163 
2164 /// Parse a list of either lists or elements, returning the dimensions of the
2165 /// parsed sub-tensors in dims. For example:
2166 ///   parseList([1, 2, 3]) -> Success, [3]
2167 ///   parseList([[1, 2], [3, 4]]) -> Success, [2, 2]
2168 ///   parseList([[1, 2], 3]) -> Failure
2169 ///   parseList([[1, [2, 3]], [4, [5]]]) -> Failure
2170 ParseResult TensorLiteralParser::parseList(SmallVectorImpl<int64_t> &dims) {
2171   p.consumeToken(Token::l_square);
2172 
2173   auto checkDims = [&](const SmallVectorImpl<int64_t> &prevDims,
2174                        const SmallVectorImpl<int64_t> &newDims) -> ParseResult {
2175     if (prevDims == newDims)
2176       return success();
2177     return p.emitError("tensor literal is invalid; ranks are not consistent "
2178                        "between elements");
2179   };
2180 
2181   bool first = true;
2182   SmallVector<int64_t, 4> newDims;
2183   unsigned size = 0;
2184   auto parseCommaSeparatedList = [&]() -> ParseResult {
2185     SmallVector<int64_t, 4> thisDims;
2186     if (p.getToken().getKind() == Token::l_square) {
2187       if (parseList(thisDims))
2188         return failure();
2189     } else if (parseElement()) {
2190       return failure();
2191     }
2192     ++size;
2193     if (!first)
2194       return checkDims(newDims, thisDims);
2195     newDims = thisDims;
2196     first = false;
2197     return success();
2198   };
2199   if (p.parseCommaSeparatedListUntil(Token::r_square, parseCommaSeparatedList))
2200     return failure();
2201 
2202   // Return the sublists' dimensions with 'size' prepended.
2203   dims.clear();
2204   dims.push_back(size);
2205   dims.append(newDims.begin(), newDims.end());
2206   return success();
2207 }
2208 
2209 /// Parse a dense elements attribute.
2210 Attribute Parser::parseDenseElementsAttr(Type attrType) {
2211   consumeToken(Token::kw_dense);
2212   if (parseToken(Token::less, "expected '<' after 'dense'"))
2213     return nullptr;
2214 
2215   // Parse the literal data.
2216   TensorLiteralParser literalParser(*this);
2217   if (literalParser.parse(/*allowHex=*/true))
2218     return nullptr;
2219 
2220   if (parseToken(Token::greater, "expected '>'"))
2221     return nullptr;
2222 
2223   auto typeLoc = getToken().getLoc();
2224   auto type = parseElementsLiteralType(attrType);
2225   if (!type)
2226     return nullptr;
2227   return literalParser.getAttr(typeLoc, type);
2228 }
2229 
2230 /// Shaped type for elements attribute.
2231 ///
2232 ///   elements-literal-type ::= vector-type | ranked-tensor-type
2233 ///
2234 /// This method also checks the type has static shape.
2235 ShapedType Parser::parseElementsLiteralType(Type type) {
2236   // If the user didn't provide a type, parse the colon type for the literal.
2237   if (!type) {
2238     if (parseToken(Token::colon, "expected ':'"))
2239       return nullptr;
2240     if (!(type = parseType()))
2241       return nullptr;
2242   }
2243 
2244   if (!type.isa<RankedTensorType>() && !type.isa<VectorType>()) {
2245     emitError("elements literal must be a ranked tensor or vector type");
2246     return nullptr;
2247   }
2248 
2249   auto sType = type.cast<ShapedType>();
2250   if (!sType.hasStaticShape())
2251     return (emitError("elements literal type must have static shape"), nullptr);
2252 
2253   return sType;
2254 }
2255 
2256 /// Parse a sparse elements attribute.
2257 Attribute Parser::parseSparseElementsAttr(Type attrType) {
2258   consumeToken(Token::kw_sparse);
2259   if (parseToken(Token::less, "Expected '<' after 'sparse'"))
2260     return nullptr;
2261 
2262   /// Parse the indices. We don't allow hex values here as we may need to use
2263   /// the inferred shape.
2264   auto indicesLoc = getToken().getLoc();
2265   TensorLiteralParser indiceParser(*this);
2266   if (indiceParser.parse(/*allowHex=*/false))
2267     return nullptr;
2268 
2269   if (parseToken(Token::comma, "expected ','"))
2270     return nullptr;
2271 
2272   /// Parse the values.
2273   auto valuesLoc = getToken().getLoc();
2274   TensorLiteralParser valuesParser(*this);
2275   if (valuesParser.parse(/*allowHex=*/true))
2276     return nullptr;
2277 
2278   if (parseToken(Token::greater, "expected '>'"))
2279     return nullptr;
2280 
2281   auto type = parseElementsLiteralType(attrType);
2282   if (!type)
2283     return nullptr;
2284 
2285   // If the indices are a splat, i.e. the literal parser parsed an element and
2286   // not a list, we set the shape explicitly. The indices are represented by a
2287   // 2-dimensional shape where the second dimension is the rank of the type.
2288   // Given that the parsed indices is a splat, we know that we only have one
2289   // indice and thus one for the first dimension.
2290   auto indiceEltType = builder.getIntegerType(64);
2291   ShapedType indicesType;
2292   if (indiceParser.getShape().empty()) {
2293     indicesType = RankedTensorType::get({1, type.getRank()}, indiceEltType);
2294   } else {
2295     // Otherwise, set the shape to the one parsed by the literal parser.
2296     indicesType = RankedTensorType::get(indiceParser.getShape(), indiceEltType);
2297   }
2298   auto indices = indiceParser.getAttr(indicesLoc, indicesType);
2299 
2300   // If the values are a splat, set the shape explicitly based on the number of
2301   // indices. The number of indices is encoded in the first dimension of the
2302   // indice shape type.
2303   auto valuesEltType = type.getElementType();
2304   ShapedType valuesType =
2305       valuesParser.getShape().empty()
2306           ? RankedTensorType::get({indicesType.getDimSize(0)}, valuesEltType)
2307           : RankedTensorType::get(valuesParser.getShape(), valuesEltType);
2308   auto values = valuesParser.getAttr(valuesLoc, valuesType);
2309 
2310   /// Sanity check.
2311   if (valuesType.getRank() != 1)
2312     return (emitError("expected 1-d tensor for values"), nullptr);
2313 
2314   auto sameShape = (indicesType.getRank() == 1) ||
2315                    (type.getRank() == indicesType.getDimSize(1));
2316   auto sameElementNum = indicesType.getDimSize(0) == valuesType.getDimSize(0);
2317   if (!sameShape || !sameElementNum) {
2318     emitError() << "expected shape ([" << type.getShape()
2319                 << "]); inferred shape of indices literal (["
2320                 << indicesType.getShape()
2321                 << "]); inferred shape of values literal (["
2322                 << valuesType.getShape() << "])";
2323     return nullptr;
2324   }
2325 
2326   // Build the sparse elements attribute by the indices and values.
2327   return SparseElementsAttr::get(type, indices, values);
2328 }
2329 
2330 //===----------------------------------------------------------------------===//
2331 // Location parsing.
2332 //===----------------------------------------------------------------------===//
2333 
2334 /// Parse a location.
2335 ///
2336 ///   location           ::= `loc` inline-location
2337 ///   inline-location    ::= '(' location-inst ')'
2338 ///
2339 ParseResult Parser::parseLocation(LocationAttr &loc) {
2340   // Check for 'loc' identifier.
2341   if (parseToken(Token::kw_loc, "expected 'loc' keyword"))
2342     return emitError();
2343 
2344   // Parse the inline-location.
2345   if (parseToken(Token::l_paren, "expected '(' in inline location") ||
2346       parseLocationInstance(loc) ||
2347       parseToken(Token::r_paren, "expected ')' in inline location"))
2348     return failure();
2349   return success();
2350 }
2351 
2352 /// Specific location instances.
2353 ///
2354 /// location-inst ::= filelinecol-location |
2355 ///                   name-location |
2356 ///                   callsite-location |
2357 ///                   fused-location |
2358 ///                   unknown-location
2359 /// filelinecol-location ::= string-literal ':' integer-literal
2360 ///                                         ':' integer-literal
2361 /// name-location ::= string-literal
2362 /// callsite-location ::= 'callsite' '(' location-inst 'at' location-inst ')'
2363 /// fused-location ::= fused ('<' attribute-value '>')?
2364 ///                    '[' location-inst (location-inst ',')* ']'
2365 /// unknown-location ::= 'unknown'
2366 ///
2367 ParseResult Parser::parseCallSiteLocation(LocationAttr &loc) {
2368   consumeToken(Token::bare_identifier);
2369 
2370   // Parse the '('.
2371   if (parseToken(Token::l_paren, "expected '(' in callsite location"))
2372     return failure();
2373 
2374   // Parse the callee location.
2375   LocationAttr calleeLoc;
2376   if (parseLocationInstance(calleeLoc))
2377     return failure();
2378 
2379   // Parse the 'at'.
2380   if (getToken().isNot(Token::bare_identifier) ||
2381       getToken().getSpelling() != "at")
2382     return emitError("expected 'at' in callsite location");
2383   consumeToken(Token::bare_identifier);
2384 
2385   // Parse the caller location.
2386   LocationAttr callerLoc;
2387   if (parseLocationInstance(callerLoc))
2388     return failure();
2389 
2390   // Parse the ')'.
2391   if (parseToken(Token::r_paren, "expected ')' in callsite location"))
2392     return failure();
2393 
2394   // Return the callsite location.
2395   loc = CallSiteLoc::get(calleeLoc, callerLoc);
2396   return success();
2397 }
2398 
2399 ParseResult Parser::parseFusedLocation(LocationAttr &loc) {
2400   consumeToken(Token::bare_identifier);
2401 
2402   // Try to parse the optional metadata.
2403   Attribute metadata;
2404   if (consumeIf(Token::less)) {
2405     metadata = parseAttribute();
2406     if (!metadata)
2407       return emitError("expected valid attribute metadata");
2408     // Parse the '>' token.
2409     if (parseToken(Token::greater,
2410                    "expected '>' after fused location metadata"))
2411       return failure();
2412   }
2413 
2414   SmallVector<Location, 4> locations;
2415   auto parseElt = [&] {
2416     LocationAttr newLoc;
2417     if (parseLocationInstance(newLoc))
2418       return failure();
2419     locations.push_back(newLoc);
2420     return success();
2421   };
2422 
2423   if (parseToken(Token::l_square, "expected '[' in fused location") ||
2424       parseCommaSeparatedList(parseElt) ||
2425       parseToken(Token::r_square, "expected ']' in fused location"))
2426     return failure();
2427 
2428   // Return the fused location.
2429   loc = FusedLoc::get(locations, metadata, getContext());
2430   return success();
2431 }
2432 
2433 ParseResult Parser::parseNameOrFileLineColLocation(LocationAttr &loc) {
2434   auto *ctx = getContext();
2435   auto str = getToken().getStringValue();
2436   consumeToken(Token::string);
2437 
2438   // If the next token is ':' this is a filelinecol location.
2439   if (consumeIf(Token::colon)) {
2440     // Parse the line number.
2441     if (getToken().isNot(Token::integer))
2442       return emitError("expected integer line number in FileLineColLoc");
2443     auto line = getToken().getUnsignedIntegerValue();
2444     if (!line.hasValue())
2445       return emitError("expected integer line number in FileLineColLoc");
2446     consumeToken(Token::integer);
2447 
2448     // Parse the ':'.
2449     if (parseToken(Token::colon, "expected ':' in FileLineColLoc"))
2450       return failure();
2451 
2452     // Parse the column number.
2453     if (getToken().isNot(Token::integer))
2454       return emitError("expected integer column number in FileLineColLoc");
2455     auto column = getToken().getUnsignedIntegerValue();
2456     if (!column.hasValue())
2457       return emitError("expected integer column number in FileLineColLoc");
2458     consumeToken(Token::integer);
2459 
2460     loc = FileLineColLoc::get(str, line.getValue(), column.getValue(), ctx);
2461     return success();
2462   }
2463 
2464   // Otherwise, this is a NameLoc.
2465 
2466   // Check for a child location.
2467   if (consumeIf(Token::l_paren)) {
2468     auto childSourceLoc = getToken().getLoc();
2469 
2470     // Parse the child location.
2471     LocationAttr childLoc;
2472     if (parseLocationInstance(childLoc))
2473       return failure();
2474 
2475     // The child must not be another NameLoc.
2476     if (childLoc.isa<NameLoc>())
2477       return emitError(childSourceLoc,
2478                        "child of NameLoc cannot be another NameLoc");
2479     loc = NameLoc::get(Identifier::get(str, ctx), childLoc);
2480 
2481     // Parse the closing ')'.
2482     if (parseToken(Token::r_paren,
2483                    "expected ')' after child location of NameLoc"))
2484       return failure();
2485   } else {
2486     loc = NameLoc::get(Identifier::get(str, ctx), ctx);
2487   }
2488 
2489   return success();
2490 }
2491 
2492 ParseResult Parser::parseLocationInstance(LocationAttr &loc) {
2493   // Handle either name or filelinecol locations.
2494   if (getToken().is(Token::string))
2495     return parseNameOrFileLineColLocation(loc);
2496 
2497   // Bare tokens required for other cases.
2498   if (!getToken().is(Token::bare_identifier))
2499     return emitError("expected location instance");
2500 
2501   // Check for the 'callsite' signifying a callsite location.
2502   if (getToken().getSpelling() == "callsite")
2503     return parseCallSiteLocation(loc);
2504 
2505   // If the token is 'fused', then this is a fused location.
2506   if (getToken().getSpelling() == "fused")
2507     return parseFusedLocation(loc);
2508 
2509   // Check for a 'unknown' for an unknown location.
2510   if (getToken().getSpelling() == "unknown") {
2511     consumeToken(Token::bare_identifier);
2512     loc = UnknownLoc::get(getContext());
2513     return success();
2514   }
2515 
2516   return emitError("expected location instance");
2517 }
2518 
2519 //===----------------------------------------------------------------------===//
2520 // Affine parsing.
2521 //===----------------------------------------------------------------------===//
2522 
2523 /// Lower precedence ops (all at the same precedence level). LNoOp is false in
2524 /// the boolean sense.
2525 enum AffineLowPrecOp {
2526   /// Null value.
2527   LNoOp,
2528   Add,
2529   Sub
2530 };
2531 
2532 /// Higher precedence ops - all at the same precedence level. HNoOp is false
2533 /// in the boolean sense.
2534 enum AffineHighPrecOp {
2535   /// Null value.
2536   HNoOp,
2537   Mul,
2538   FloorDiv,
2539   CeilDiv,
2540   Mod
2541 };
2542 
2543 namespace {
2544 /// This is a specialized parser for affine structures (affine maps, affine
2545 /// expressions, and integer sets), maintaining the state transient to their
2546 /// bodies.
2547 class AffineParser : public Parser {
2548 public:
2549   AffineParser(ParserState &state, bool allowParsingSSAIds = false,
2550                function_ref<ParseResult(bool)> parseElement = nullptr)
2551       : Parser(state), allowParsingSSAIds(allowParsingSSAIds),
2552         parseElement(parseElement), numDimOperands(0), numSymbolOperands(0) {}
2553 
2554   AffineMap parseAffineMapRange(unsigned numDims, unsigned numSymbols);
2555   ParseResult parseAffineMapOrIntegerSetInline(AffineMap &map, IntegerSet &set);
2556   IntegerSet parseIntegerSetConstraints(unsigned numDims, unsigned numSymbols);
2557   ParseResult parseAffineMapOfSSAIds(AffineMap &map,
2558                                      OpAsmParser::Delimiter delimiter);
2559   void getDimsAndSymbolSSAIds(SmallVectorImpl<StringRef> &dimAndSymbolSSAIds,
2560                               unsigned &numDims);
2561 
2562 private:
2563   // Binary affine op parsing.
2564   AffineLowPrecOp consumeIfLowPrecOp();
2565   AffineHighPrecOp consumeIfHighPrecOp();
2566 
2567   // Identifier lists for polyhedral structures.
2568   ParseResult parseDimIdList(unsigned &numDims);
2569   ParseResult parseSymbolIdList(unsigned &numSymbols);
2570   ParseResult parseDimAndOptionalSymbolIdList(unsigned &numDims,
2571                                               unsigned &numSymbols);
2572   ParseResult parseIdentifierDefinition(AffineExpr idExpr);
2573 
2574   AffineExpr parseAffineExpr();
2575   AffineExpr parseParentheticalExpr();
2576   AffineExpr parseNegateExpression(AffineExpr lhs);
2577   AffineExpr parseIntegerExpr();
2578   AffineExpr parseBareIdExpr();
2579   AffineExpr parseSSAIdExpr(bool isSymbol);
2580   AffineExpr parseSymbolSSAIdExpr();
2581 
2582   AffineExpr getAffineBinaryOpExpr(AffineHighPrecOp op, AffineExpr lhs,
2583                                    AffineExpr rhs, SMLoc opLoc);
2584   AffineExpr getAffineBinaryOpExpr(AffineLowPrecOp op, AffineExpr lhs,
2585                                    AffineExpr rhs);
2586   AffineExpr parseAffineOperandExpr(AffineExpr lhs);
2587   AffineExpr parseAffineLowPrecOpExpr(AffineExpr llhs, AffineLowPrecOp llhsOp);
2588   AffineExpr parseAffineHighPrecOpExpr(AffineExpr llhs, AffineHighPrecOp llhsOp,
2589                                        SMLoc llhsOpLoc);
2590   AffineExpr parseAffineConstraint(bool *isEq);
2591 
2592 private:
2593   bool allowParsingSSAIds;
2594   function_ref<ParseResult(bool)> parseElement;
2595   unsigned numDimOperands;
2596   unsigned numSymbolOperands;
2597   SmallVector<std::pair<StringRef, AffineExpr>, 4> dimsAndSymbols;
2598 };
2599 } // end anonymous namespace
2600 
2601 /// Create an affine binary high precedence op expression (mul's, div's, mod).
2602 /// opLoc is the location of the op token to be used to report errors
2603 /// for non-conforming expressions.
2604 AffineExpr AffineParser::getAffineBinaryOpExpr(AffineHighPrecOp op,
2605                                                AffineExpr lhs, AffineExpr rhs,
2606                                                SMLoc opLoc) {
2607   // TODO: make the error location info accurate.
2608   switch (op) {
2609   case Mul:
2610     if (!lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant()) {
2611       emitError(opLoc, "non-affine expression: at least one of the multiply "
2612                        "operands has to be either a constant or symbolic");
2613       return nullptr;
2614     }
2615     return lhs * rhs;
2616   case FloorDiv:
2617     if (!rhs.isSymbolicOrConstant()) {
2618       emitError(opLoc, "non-affine expression: right operand of floordiv "
2619                        "has to be either a constant or symbolic");
2620       return nullptr;
2621     }
2622     return lhs.floorDiv(rhs);
2623   case CeilDiv:
2624     if (!rhs.isSymbolicOrConstant()) {
2625       emitError(opLoc, "non-affine expression: right operand of ceildiv "
2626                        "has to be either a constant or symbolic");
2627       return nullptr;
2628     }
2629     return lhs.ceilDiv(rhs);
2630   case Mod:
2631     if (!rhs.isSymbolicOrConstant()) {
2632       emitError(opLoc, "non-affine expression: right operand of mod "
2633                        "has to be either a constant or symbolic");
2634       return nullptr;
2635     }
2636     return lhs % rhs;
2637   case HNoOp:
2638     llvm_unreachable("can't create affine expression for null high prec op");
2639     return nullptr;
2640   }
2641   llvm_unreachable("Unknown AffineHighPrecOp");
2642 }
2643 
2644 /// Create an affine binary low precedence op expression (add, sub).
2645 AffineExpr AffineParser::getAffineBinaryOpExpr(AffineLowPrecOp op,
2646                                                AffineExpr lhs, AffineExpr rhs) {
2647   switch (op) {
2648   case AffineLowPrecOp::Add:
2649     return lhs + rhs;
2650   case AffineLowPrecOp::Sub:
2651     return lhs - rhs;
2652   case AffineLowPrecOp::LNoOp:
2653     llvm_unreachable("can't create affine expression for null low prec op");
2654     return nullptr;
2655   }
2656   llvm_unreachable("Unknown AffineLowPrecOp");
2657 }
2658 
2659 /// Consume this token if it is a lower precedence affine op (there are only
2660 /// two precedence levels).
2661 AffineLowPrecOp AffineParser::consumeIfLowPrecOp() {
2662   switch (getToken().getKind()) {
2663   case Token::plus:
2664     consumeToken(Token::plus);
2665     return AffineLowPrecOp::Add;
2666   case Token::minus:
2667     consumeToken(Token::minus);
2668     return AffineLowPrecOp::Sub;
2669   default:
2670     return AffineLowPrecOp::LNoOp;
2671   }
2672 }
2673 
2674 /// Consume this token if it is a higher precedence affine op (there are only
2675 /// two precedence levels)
2676 AffineHighPrecOp AffineParser::consumeIfHighPrecOp() {
2677   switch (getToken().getKind()) {
2678   case Token::star:
2679     consumeToken(Token::star);
2680     return Mul;
2681   case Token::kw_floordiv:
2682     consumeToken(Token::kw_floordiv);
2683     return FloorDiv;
2684   case Token::kw_ceildiv:
2685     consumeToken(Token::kw_ceildiv);
2686     return CeilDiv;
2687   case Token::kw_mod:
2688     consumeToken(Token::kw_mod);
2689     return Mod;
2690   default:
2691     return HNoOp;
2692   }
2693 }
2694 
2695 /// Parse a high precedence op expression list: mul, div, and mod are high
2696 /// precedence binary ops, i.e., parse a
2697 ///   expr_1 op_1 expr_2 op_2 ... expr_n
2698 /// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
2699 /// All affine binary ops are left associative.
2700 /// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
2701 /// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
2702 /// null. llhsOpLoc is the location of the llhsOp token that will be used to
2703 /// report an error for non-conforming expressions.
2704 AffineExpr AffineParser::parseAffineHighPrecOpExpr(AffineExpr llhs,
2705                                                    AffineHighPrecOp llhsOp,
2706                                                    SMLoc llhsOpLoc) {
2707   AffineExpr lhs = parseAffineOperandExpr(llhs);
2708   if (!lhs)
2709     return nullptr;
2710 
2711   // Found an LHS. Parse the remaining expression.
2712   auto opLoc = getToken().getLoc();
2713   if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
2714     if (llhs) {
2715       AffineExpr expr = getAffineBinaryOpExpr(llhsOp, llhs, lhs, opLoc);
2716       if (!expr)
2717         return nullptr;
2718       return parseAffineHighPrecOpExpr(expr, op, opLoc);
2719     }
2720     // No LLHS, get RHS
2721     return parseAffineHighPrecOpExpr(lhs, op, opLoc);
2722   }
2723 
2724   // This is the last operand in this expression.
2725   if (llhs)
2726     return getAffineBinaryOpExpr(llhsOp, llhs, lhs, llhsOpLoc);
2727 
2728   // No llhs, 'lhs' itself is the expression.
2729   return lhs;
2730 }
2731 
2732 /// Parse an affine expression inside parentheses.
2733 ///
2734 ///   affine-expr ::= `(` affine-expr `)`
2735 AffineExpr AffineParser::parseParentheticalExpr() {
2736   if (parseToken(Token::l_paren, "expected '('"))
2737     return nullptr;
2738   if (getToken().is(Token::r_paren))
2739     return (emitError("no expression inside parentheses"), nullptr);
2740 
2741   auto expr = parseAffineExpr();
2742   if (!expr)
2743     return nullptr;
2744   if (parseToken(Token::r_paren, "expected ')'"))
2745     return nullptr;
2746 
2747   return expr;
2748 }
2749 
2750 /// Parse the negation expression.
2751 ///
2752 ///   affine-expr ::= `-` affine-expr
2753 AffineExpr AffineParser::parseNegateExpression(AffineExpr lhs) {
2754   if (parseToken(Token::minus, "expected '-'"))
2755     return nullptr;
2756 
2757   AffineExpr operand = parseAffineOperandExpr(lhs);
2758   // Since negation has the highest precedence of all ops (including high
2759   // precedence ops) but lower than parentheses, we are only going to use
2760   // parseAffineOperandExpr instead of parseAffineExpr here.
2761   if (!operand)
2762     // Extra error message although parseAffineOperandExpr would have
2763     // complained. Leads to a better diagnostic.
2764     return (emitError("missing operand of negation"), nullptr);
2765   return (-1) * operand;
2766 }
2767 
2768 /// Parse a bare id that may appear in an affine expression.
2769 ///
2770 ///   affine-expr ::= bare-id
2771 AffineExpr AffineParser::parseBareIdExpr() {
2772   if (getToken().isNot(Token::bare_identifier))
2773     return (emitError("expected bare identifier"), nullptr);
2774 
2775   StringRef sRef = getTokenSpelling();
2776   for (auto entry : dimsAndSymbols) {
2777     if (entry.first == sRef) {
2778       consumeToken(Token::bare_identifier);
2779       return entry.second;
2780     }
2781   }
2782 
2783   return (emitError("use of undeclared identifier"), nullptr);
2784 }
2785 
2786 /// Parse an SSA id which may appear in an affine expression.
2787 AffineExpr AffineParser::parseSSAIdExpr(bool isSymbol) {
2788   if (!allowParsingSSAIds)
2789     return (emitError("unexpected ssa identifier"), nullptr);
2790   if (getToken().isNot(Token::percent_identifier))
2791     return (emitError("expected ssa identifier"), nullptr);
2792   auto name = getTokenSpelling();
2793   // Check if we already parsed this SSA id.
2794   for (auto entry : dimsAndSymbols) {
2795     if (entry.first == name) {
2796       consumeToken(Token::percent_identifier);
2797       return entry.second;
2798     }
2799   }
2800   // Parse the SSA id and add an AffineDim/SymbolExpr to represent it.
2801   if (parseElement(isSymbol))
2802     return (emitError("failed to parse ssa identifier"), nullptr);
2803   auto idExpr = isSymbol
2804                     ? getAffineSymbolExpr(numSymbolOperands++, getContext())
2805                     : getAffineDimExpr(numDimOperands++, getContext());
2806   dimsAndSymbols.push_back({name, idExpr});
2807   return idExpr;
2808 }
2809 
2810 AffineExpr AffineParser::parseSymbolSSAIdExpr() {
2811   if (parseToken(Token::kw_symbol, "expected symbol keyword") ||
2812       parseToken(Token::l_paren, "expected '(' at start of SSA symbol"))
2813     return nullptr;
2814   AffineExpr symbolExpr = parseSSAIdExpr(/*isSymbol=*/true);
2815   if (!symbolExpr)
2816     return nullptr;
2817   if (parseToken(Token::r_paren, "expected ')' at end of SSA symbol"))
2818     return nullptr;
2819   return symbolExpr;
2820 }
2821 
2822 /// Parse a positive integral constant appearing in an affine expression.
2823 ///
2824 ///   affine-expr ::= integer-literal
2825 AffineExpr AffineParser::parseIntegerExpr() {
2826   auto val = getToken().getUInt64IntegerValue();
2827   if (!val.hasValue() || (int64_t)val.getValue() < 0)
2828     return (emitError("constant too large for index"), nullptr);
2829 
2830   consumeToken(Token::integer);
2831   return builder.getAffineConstantExpr((int64_t)val.getValue());
2832 }
2833 
2834 /// Parses an expression that can be a valid operand of an affine expression.
2835 /// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
2836 /// operator, the rhs of which is being parsed. This is used to determine
2837 /// whether an error should be emitted for a missing right operand.
2838 //  Eg: for an expression without parentheses (like i + j + k + l), each
2839 //  of the four identifiers is an operand. For i + j*k + l, j*k is not an
2840 //  operand expression, it's an op expression and will be parsed via
2841 //  parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and
2842 //  -l are valid operands that will be parsed by this function.
2843 AffineExpr AffineParser::parseAffineOperandExpr(AffineExpr lhs) {
2844   switch (getToken().getKind()) {
2845   case Token::bare_identifier:
2846     return parseBareIdExpr();
2847   case Token::kw_symbol:
2848     return parseSymbolSSAIdExpr();
2849   case Token::percent_identifier:
2850     return parseSSAIdExpr(/*isSymbol=*/false);
2851   case Token::integer:
2852     return parseIntegerExpr();
2853   case Token::l_paren:
2854     return parseParentheticalExpr();
2855   case Token::minus:
2856     return parseNegateExpression(lhs);
2857   case Token::kw_ceildiv:
2858   case Token::kw_floordiv:
2859   case Token::kw_mod:
2860   case Token::plus:
2861   case Token::star:
2862     if (lhs)
2863       emitError("missing right operand of binary operator");
2864     else
2865       emitError("missing left operand of binary operator");
2866     return nullptr;
2867   default:
2868     if (lhs)
2869       emitError("missing right operand of binary operator");
2870     else
2871       emitError("expected affine expression");
2872     return nullptr;
2873   }
2874 }
2875 
2876 /// Parse affine expressions that are bare-id's, integer constants,
2877 /// parenthetical affine expressions, and affine op expressions that are a
2878 /// composition of those.
2879 ///
2880 /// All binary op's associate from left to right.
2881 ///
2882 /// {add, sub} have lower precedence than {mul, div, and mod}.
2883 ///
2884 /// Add, sub'are themselves at the same precedence level. Mul, floordiv,
2885 /// ceildiv, and mod are at the same higher precedence level. Negation has
2886 /// higher precedence than any binary op.
2887 ///
2888 /// llhs: the affine expression appearing on the left of the one being parsed.
2889 /// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
2890 /// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned
2891 /// if llhs is non-null; otherwise lhs is returned. This is to deal with left
2892 /// associativity.
2893 ///
2894 /// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
2895 /// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where
2896 /// (e2*e3) will be parsed using parseAffineHighPrecOpExpr().
2897 AffineExpr AffineParser::parseAffineLowPrecOpExpr(AffineExpr llhs,
2898                                                   AffineLowPrecOp llhsOp) {
2899   AffineExpr lhs;
2900   if (!(lhs = parseAffineOperandExpr(llhs)))
2901     return nullptr;
2902 
2903   // Found an LHS. Deal with the ops.
2904   if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
2905     if (llhs) {
2906       AffineExpr sum = getAffineBinaryOpExpr(llhsOp, llhs, lhs);
2907       return parseAffineLowPrecOpExpr(sum, lOp);
2908     }
2909     // No LLHS, get RHS and form the expression.
2910     return parseAffineLowPrecOpExpr(lhs, lOp);
2911   }
2912   auto opLoc = getToken().getLoc();
2913   if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
2914     // We have a higher precedence op here. Get the rhs operand for the llhs
2915     // through parseAffineHighPrecOpExpr.
2916     AffineExpr highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc);
2917     if (!highRes)
2918       return nullptr;
2919 
2920     // If llhs is null, the product forms the first operand of the yet to be
2921     // found expression. If non-null, the op to associate with llhs is llhsOp.
2922     AffineExpr expr =
2923         llhs ? getAffineBinaryOpExpr(llhsOp, llhs, highRes) : highRes;
2924 
2925     // Recurse for subsequent low prec op's after the affine high prec op
2926     // expression.
2927     if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
2928       return parseAffineLowPrecOpExpr(expr, nextOp);
2929     return expr;
2930   }
2931   // Last operand in the expression list.
2932   if (llhs)
2933     return getAffineBinaryOpExpr(llhsOp, llhs, lhs);
2934   // No llhs, 'lhs' itself is the expression.
2935   return lhs;
2936 }
2937 
2938 /// Parse an affine expression.
2939 ///  affine-expr ::= `(` affine-expr `)`
2940 ///                | `-` affine-expr
2941 ///                | affine-expr `+` affine-expr
2942 ///                | affine-expr `-` affine-expr
2943 ///                | affine-expr `*` affine-expr
2944 ///                | affine-expr `floordiv` affine-expr
2945 ///                | affine-expr `ceildiv` affine-expr
2946 ///                | affine-expr `mod` affine-expr
2947 ///                | bare-id
2948 ///                | integer-literal
2949 ///
2950 /// Additional conditions are checked depending on the production. For eg.,
2951 /// one of the operands for `*` has to be either constant/symbolic; the second
2952 /// operand for floordiv, ceildiv, and mod has to be a positive integer.
2953 AffineExpr AffineParser::parseAffineExpr() {
2954   return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
2955 }
2956 
2957 /// Parse a dim or symbol from the lists appearing before the actual
2958 /// expressions of the affine map. Update our state to store the
2959 /// dimensional/symbolic identifier.
2960 ParseResult AffineParser::parseIdentifierDefinition(AffineExpr idExpr) {
2961   if (getToken().isNot(Token::bare_identifier))
2962     return emitError("expected bare identifier");
2963 
2964   auto name = getTokenSpelling();
2965   for (auto entry : dimsAndSymbols) {
2966     if (entry.first == name)
2967       return emitError("redefinition of identifier '" + name + "'");
2968   }
2969   consumeToken(Token::bare_identifier);
2970 
2971   dimsAndSymbols.push_back({name, idExpr});
2972   return success();
2973 }
2974 
2975 /// Parse the list of dimensional identifiers to an affine map.
2976 ParseResult AffineParser::parseDimIdList(unsigned &numDims) {
2977   if (parseToken(Token::l_paren,
2978                  "expected '(' at start of dimensional identifiers list")) {
2979     return failure();
2980   }
2981 
2982   auto parseElt = [&]() -> ParseResult {
2983     auto dimension = getAffineDimExpr(numDims++, getContext());
2984     return parseIdentifierDefinition(dimension);
2985   };
2986   return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
2987 }
2988 
2989 /// Parse the list of symbolic identifiers to an affine map.
2990 ParseResult AffineParser::parseSymbolIdList(unsigned &numSymbols) {
2991   consumeToken(Token::l_square);
2992   auto parseElt = [&]() -> ParseResult {
2993     auto symbol = getAffineSymbolExpr(numSymbols++, getContext());
2994     return parseIdentifierDefinition(symbol);
2995   };
2996   return parseCommaSeparatedListUntil(Token::r_square, parseElt);
2997 }
2998 
2999 /// Parse the list of symbolic identifiers to an affine map.
3000 ParseResult
3001 AffineParser::parseDimAndOptionalSymbolIdList(unsigned &numDims,
3002                                               unsigned &numSymbols) {
3003   if (parseDimIdList(numDims)) {
3004     return failure();
3005   }
3006   if (!getToken().is(Token::l_square)) {
3007     numSymbols = 0;
3008     return success();
3009   }
3010   return parseSymbolIdList(numSymbols);
3011 }
3012 
3013 /// Parses an ambiguous affine map or integer set definition inline.
3014 ParseResult AffineParser::parseAffineMapOrIntegerSetInline(AffineMap &map,
3015                                                            IntegerSet &set) {
3016   unsigned numDims = 0, numSymbols = 0;
3017 
3018   // List of dimensional and optional symbol identifiers.
3019   if (parseDimAndOptionalSymbolIdList(numDims, numSymbols)) {
3020     return failure();
3021   }
3022 
3023   // This is needed for parsing attributes as we wouldn't know whether we would
3024   // be parsing an integer set attribute or an affine map attribute.
3025   bool isArrow = getToken().is(Token::arrow);
3026   bool isColon = getToken().is(Token::colon);
3027   if (!isArrow && !isColon) {
3028     return emitError("expected '->' or ':'");
3029   } else if (isArrow) {
3030     parseToken(Token::arrow, "expected '->' or '['");
3031     map = parseAffineMapRange(numDims, numSymbols);
3032     return map ? success() : failure();
3033   } else if (parseToken(Token::colon, "expected ':' or '['")) {
3034     return failure();
3035   }
3036 
3037   if ((set = parseIntegerSetConstraints(numDims, numSymbols)))
3038     return success();
3039 
3040   return failure();
3041 }
3042 
3043 /// Parse an AffineMap where the dim and symbol identifiers are SSA ids.
3044 ParseResult
3045 AffineParser::parseAffineMapOfSSAIds(AffineMap &map,
3046                                      OpAsmParser::Delimiter delimiter) {
3047   Token::Kind rightToken;
3048   switch (delimiter) {
3049   case OpAsmParser::Delimiter::Square:
3050     if (parseToken(Token::l_square, "expected '['"))
3051       return failure();
3052     rightToken = Token::r_square;
3053     break;
3054   case OpAsmParser::Delimiter::Paren:
3055     if (parseToken(Token::l_paren, "expected '('"))
3056       return failure();
3057     rightToken = Token::r_paren;
3058     break;
3059   default:
3060     return emitError("unexpected delimiter");
3061   }
3062 
3063   SmallVector<AffineExpr, 4> exprs;
3064   auto parseElt = [&]() -> ParseResult {
3065     auto elt = parseAffineExpr();
3066     exprs.push_back(elt);
3067     return elt ? success() : failure();
3068   };
3069 
3070   // Parse a multi-dimensional affine expression (a comma-separated list of
3071   // 1-d affine expressions); the list can be empty. Grammar:
3072   // multi-dim-affine-expr ::= `(` `)`
3073   //                         | `(` affine-expr (`,` affine-expr)* `)`
3074   if (parseCommaSeparatedListUntil(rightToken, parseElt,
3075                                    /*allowEmptyList=*/true))
3076     return failure();
3077   // Parsed a valid affine map.
3078   if (exprs.empty())
3079     map = AffineMap::get(numDimOperands, dimsAndSymbols.size() - numDimOperands,
3080                          getContext());
3081   else
3082     map = AffineMap::get(numDimOperands, dimsAndSymbols.size() - numDimOperands,
3083                          exprs);
3084   return success();
3085 }
3086 
3087 /// Parse the range and sizes affine map definition inline.
3088 ///
3089 ///  affine-map ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
3090 ///
3091 ///  multi-dim-affine-expr ::= `(` `)`
3092 ///  multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)`
3093 AffineMap AffineParser::parseAffineMapRange(unsigned numDims,
3094                                             unsigned numSymbols) {
3095   parseToken(Token::l_paren, "expected '(' at start of affine map range");
3096 
3097   SmallVector<AffineExpr, 4> exprs;
3098   auto parseElt = [&]() -> ParseResult {
3099     auto elt = parseAffineExpr();
3100     ParseResult res = elt ? success() : failure();
3101     exprs.push_back(elt);
3102     return res;
3103   };
3104 
3105   // Parse a multi-dimensional affine expression (a comma-separated list of
3106   // 1-d affine expressions). Grammar:
3107   // multi-dim-affine-expr ::= `(` `)`
3108   //                         | `(` affine-expr (`,` affine-expr)* `)`
3109   if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true))
3110     return AffineMap();
3111 
3112   if (exprs.empty())
3113     return AffineMap::get(numDims, numSymbols, getContext());
3114 
3115   // Parsed a valid affine map.
3116   return AffineMap::get(numDims, numSymbols, exprs);
3117 }
3118 
3119 /// Parse an affine constraint.
3120 ///  affine-constraint ::= affine-expr `>=` `0`
3121 ///                      | affine-expr `==` `0`
3122 ///
3123 /// isEq is set to true if the parsed constraint is an equality, false if it
3124 /// is an inequality (greater than or equal).
3125 ///
3126 AffineExpr AffineParser::parseAffineConstraint(bool *isEq) {
3127   AffineExpr expr = parseAffineExpr();
3128   if (!expr)
3129     return nullptr;
3130 
3131   if (consumeIf(Token::greater) && consumeIf(Token::equal) &&
3132       getToken().is(Token::integer)) {
3133     auto dim = getToken().getUnsignedIntegerValue();
3134     if (dim.hasValue() && dim.getValue() == 0) {
3135       consumeToken(Token::integer);
3136       *isEq = false;
3137       return expr;
3138     }
3139     return (emitError("expected '0' after '>='"), nullptr);
3140   }
3141 
3142   if (consumeIf(Token::equal) && consumeIf(Token::equal) &&
3143       getToken().is(Token::integer)) {
3144     auto dim = getToken().getUnsignedIntegerValue();
3145     if (dim.hasValue() && dim.getValue() == 0) {
3146       consumeToken(Token::integer);
3147       *isEq = true;
3148       return expr;
3149     }
3150     return (emitError("expected '0' after '=='"), nullptr);
3151   }
3152 
3153   return (emitError("expected '== 0' or '>= 0' at end of affine constraint"),
3154           nullptr);
3155 }
3156 
3157 /// Parse the constraints that are part of an integer set definition.
3158 ///  integer-set-inline
3159 ///                ::= dim-and-symbol-id-lists `:`
3160 ///                '(' affine-constraint-conjunction? ')'
3161 ///  affine-constraint-conjunction ::= affine-constraint (`,`
3162 ///                                       affine-constraint)*
3163 ///
3164 IntegerSet AffineParser::parseIntegerSetConstraints(unsigned numDims,
3165                                                     unsigned numSymbols) {
3166   if (parseToken(Token::l_paren,
3167                  "expected '(' at start of integer set constraint list"))
3168     return IntegerSet();
3169 
3170   SmallVector<AffineExpr, 4> constraints;
3171   SmallVector<bool, 4> isEqs;
3172   auto parseElt = [&]() -> ParseResult {
3173     bool isEq;
3174     auto elt = parseAffineConstraint(&isEq);
3175     ParseResult res = elt ? success() : failure();
3176     if (elt) {
3177       constraints.push_back(elt);
3178       isEqs.push_back(isEq);
3179     }
3180     return res;
3181   };
3182 
3183   // Parse a list of affine constraints (comma-separated).
3184   if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true))
3185     return IntegerSet();
3186 
3187   // If no constraints were parsed, then treat this as a degenerate 'true' case.
3188   if (constraints.empty()) {
3189     /* 0 == 0 */
3190     auto zero = getAffineConstantExpr(0, getContext());
3191     return IntegerSet::get(numDims, numSymbols, zero, true);
3192   }
3193 
3194   // Parsed a valid integer set.
3195   return IntegerSet::get(numDims, numSymbols, constraints, isEqs);
3196 }
3197 
3198 /// Parse an ambiguous reference to either and affine map or an integer set.
3199 ParseResult Parser::parseAffineMapOrIntegerSetReference(AffineMap &map,
3200                                                         IntegerSet &set) {
3201   return AffineParser(state).parseAffineMapOrIntegerSetInline(map, set);
3202 }
3203 ParseResult Parser::parseAffineMapReference(AffineMap &map) {
3204   llvm::SMLoc curLoc = getToken().getLoc();
3205   IntegerSet set;
3206   if (parseAffineMapOrIntegerSetReference(map, set))
3207     return failure();
3208   if (set)
3209     return emitError(curLoc, "expected AffineMap, but got IntegerSet");
3210   return success();
3211 }
3212 ParseResult Parser::parseIntegerSetReference(IntegerSet &set) {
3213   llvm::SMLoc curLoc = getToken().getLoc();
3214   AffineMap map;
3215   if (parseAffineMapOrIntegerSetReference(map, set))
3216     return failure();
3217   if (map)
3218     return emitError(curLoc, "expected IntegerSet, but got AffineMap");
3219   return success();
3220 }
3221 
3222 /// Parse an AffineMap of SSA ids. The callback 'parseElement' is used to
3223 /// parse SSA value uses encountered while parsing affine expressions.
3224 ParseResult
3225 Parser::parseAffineMapOfSSAIds(AffineMap &map,
3226                                function_ref<ParseResult(bool)> parseElement,
3227                                OpAsmParser::Delimiter delimiter) {
3228   return AffineParser(state, /*allowParsingSSAIds=*/true, parseElement)
3229       .parseAffineMapOfSSAIds(map, delimiter);
3230 }
3231 
3232 //===----------------------------------------------------------------------===//
3233 // OperationParser
3234 //===----------------------------------------------------------------------===//
3235 
3236 namespace {
3237 /// This class provides support for parsing operations and regions of
3238 /// operations.
3239 class OperationParser : public Parser {
3240 public:
3241   OperationParser(ParserState &state, ModuleOp moduleOp)
3242       : Parser(state), opBuilder(moduleOp.getBodyRegion()), moduleOp(moduleOp) {
3243   }
3244 
3245   ~OperationParser();
3246 
3247   /// After parsing is finished, this function must be called to see if there
3248   /// are any remaining issues.
3249   ParseResult finalize();
3250 
3251   //===--------------------------------------------------------------------===//
3252   // SSA Value Handling
3253   //===--------------------------------------------------------------------===//
3254 
3255   /// This represents a use of an SSA value in the program.  The first two
3256   /// entries in the tuple are the name and result number of a reference.  The
3257   /// third is the location of the reference, which is used in case this ends
3258   /// up being a use of an undefined value.
3259   struct SSAUseInfo {
3260     StringRef name;  // Value name, e.g. %42 or %abc
3261     unsigned number; // Number, specified with #12
3262     SMLoc loc;       // Location of first definition or use.
3263   };
3264 
3265   /// Push a new SSA name scope to the parser.
3266   void pushSSANameScope(bool isIsolated);
3267 
3268   /// Pop the last SSA name scope from the parser.
3269   ParseResult popSSANameScope();
3270 
3271   /// Register a definition of a value with the symbol table.
3272   ParseResult addDefinition(SSAUseInfo useInfo, Value value);
3273 
3274   /// Parse an optional list of SSA uses into 'results'.
3275   ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
3276 
3277   /// Parse a single SSA use into 'result'.
3278   ParseResult parseSSAUse(SSAUseInfo &result);
3279 
3280   /// Given a reference to an SSA value and its type, return a reference. This
3281   /// returns null on failure.
3282   Value resolveSSAUse(SSAUseInfo useInfo, Type type);
3283 
3284   ParseResult parseSSADefOrUseAndType(
3285       const std::function<ParseResult(SSAUseInfo, Type)> &action);
3286 
3287   ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value> &results);
3288 
3289   /// Return the location of the value identified by its name and number if it
3290   /// has been already reference.
3291   Optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) {
3292     auto &values = isolatedNameScopes.back().values;
3293     if (!values.count(name) || number >= values[name].size())
3294       return {};
3295     if (values[name][number].first)
3296       return values[name][number].second;
3297     return {};
3298   }
3299 
3300   //===--------------------------------------------------------------------===//
3301   // Operation Parsing
3302   //===--------------------------------------------------------------------===//
3303 
3304   /// Parse an operation instance.
3305   ParseResult parseOperation();
3306 
3307   /// Parse a single operation successor.
3308   ParseResult parseSuccessor(Block *&dest);
3309 
3310   /// Parse a comma-separated list of operation successors in brackets.
3311   ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations);
3312 
3313   /// Parse an operation instance that is in the generic form.
3314   Operation *parseGenericOperation();
3315 
3316   /// Parse an operation instance that is in the generic form and insert it at
3317   /// the provided insertion point.
3318   Operation *parseGenericOperation(Block *insertBlock,
3319                                    Block::iterator insertPt);
3320 
3321   /// Parse an operation instance that is in the op-defined custom form.
3322   Operation *parseCustomOperation();
3323 
3324   //===--------------------------------------------------------------------===//
3325   // Region Parsing
3326   //===--------------------------------------------------------------------===//
3327 
3328   /// Parse a region into 'region' with the provided entry block arguments.
3329   /// 'isIsolatedNameScope' indicates if the naming scope of this region is
3330   /// isolated from those above.
3331   ParseResult parseRegion(Region &region,
3332                           ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments,
3333                           bool isIsolatedNameScope = false);
3334 
3335   /// Parse a region body into 'region'.
3336   ParseResult parseRegionBody(Region &region);
3337 
3338   //===--------------------------------------------------------------------===//
3339   // Block Parsing
3340   //===--------------------------------------------------------------------===//
3341 
3342   /// Parse a new block into 'block'.
3343   ParseResult parseBlock(Block *&block);
3344 
3345   /// Parse a list of operations into 'block'.
3346   ParseResult parseBlockBody(Block *block);
3347 
3348   /// Parse a (possibly empty) list of block arguments.
3349   ParseResult parseOptionalBlockArgList(SmallVectorImpl<BlockArgument> &results,
3350                                         Block *owner);
3351 
3352   /// Get the block with the specified name, creating it if it doesn't
3353   /// already exist.  The location specified is the point of use, which allows
3354   /// us to diagnose references to blocks that are not defined precisely.
3355   Block *getBlockNamed(StringRef name, SMLoc loc);
3356 
3357   /// Define the block with the specified name. Returns the Block* or nullptr in
3358   /// the case of redefinition.
3359   Block *defineBlockNamed(StringRef name, SMLoc loc, Block *existing);
3360 
3361 private:
3362   /// Returns the info for a block at the current scope for the given name.
3363   std::pair<Block *, SMLoc> &getBlockInfoByName(StringRef name) {
3364     return blocksByName.back()[name];
3365   }
3366 
3367   /// Insert a new forward reference to the given block.
3368   void insertForwardRef(Block *block, SMLoc loc) {
3369     forwardRef.back().try_emplace(block, loc);
3370   }
3371 
3372   /// Erase any forward reference to the given block.
3373   bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); }
3374 
3375   /// Record that a definition was added at the current scope.
3376   void recordDefinition(StringRef def);
3377 
3378   /// Get the value entry for the given SSA name.
3379   SmallVectorImpl<std::pair<Value, SMLoc>> &getSSAValueEntry(StringRef name);
3380 
3381   /// Create a forward reference placeholder value with the given location and
3382   /// result type.
3383   Value createForwardRefPlaceholder(SMLoc loc, Type type);
3384 
3385   /// Return true if this is a forward reference.
3386   bool isForwardRefPlaceholder(Value value) {
3387     return forwardRefPlaceholders.count(value);
3388   }
3389 
3390   /// This struct represents an isolated SSA name scope. This scope may contain
3391   /// other nested non-isolated scopes. These scopes are used for operations
3392   /// that are known to be isolated to allow for reusing names within their
3393   /// regions, even if those names are used above.
3394   struct IsolatedSSANameScope {
3395     /// Record that a definition was added at the current scope.
3396     void recordDefinition(StringRef def) {
3397       definitionsPerScope.back().insert(def);
3398     }
3399 
3400     /// Push a nested name scope.
3401     void pushSSANameScope() { definitionsPerScope.push_back({}); }
3402 
3403     /// Pop a nested name scope.
3404     void popSSANameScope() {
3405       for (auto &def : definitionsPerScope.pop_back_val())
3406         values.erase(def.getKey());
3407     }
3408 
3409     /// This keeps track of all of the SSA values we are tracking for each name
3410     /// scope, indexed by their name. This has one entry per result number.
3411     llvm::StringMap<SmallVector<std::pair<Value, SMLoc>, 1>> values;
3412 
3413     /// This keeps track of all of the values defined by a specific name scope.
3414     SmallVector<llvm::StringSet<>, 2> definitionsPerScope;
3415   };
3416 
3417   /// A list of isolated name scopes.
3418   SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes;
3419 
3420   /// This keeps track of the block names as well as the location of the first
3421   /// reference for each nested name scope. This is used to diagnose invalid
3422   /// block references and memorize them.
3423   SmallVector<DenseMap<StringRef, std::pair<Block *, SMLoc>>, 2> blocksByName;
3424   SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef;
3425 
3426   /// These are all of the placeholders we've made along with the location of
3427   /// their first reference, to allow checking for use of undefined values.
3428   DenseMap<Value, SMLoc> forwardRefPlaceholders;
3429 
3430   /// The builder used when creating parsed operation instances.
3431   OpBuilder opBuilder;
3432 
3433   /// The top level module operation.
3434   ModuleOp moduleOp;
3435 };
3436 } // end anonymous namespace
3437 
3438 OperationParser::~OperationParser() {
3439   for (auto &fwd : forwardRefPlaceholders) {
3440     // Drop all uses of undefined forward declared reference and destroy
3441     // defining operation.
3442     fwd.first.dropAllUses();
3443     fwd.first.getDefiningOp()->destroy();
3444   }
3445 }
3446 
3447 /// After parsing is finished, this function must be called to see if there are
3448 /// any remaining issues.
3449 ParseResult OperationParser::finalize() {
3450   // Check for any forward references that are left.  If we find any, error
3451   // out.
3452   if (!forwardRefPlaceholders.empty()) {
3453     SmallVector<std::pair<const char *, Value>, 4> errors;
3454     // Iteration over the map isn't deterministic, so sort by source location.
3455     for (auto entry : forwardRefPlaceholders)
3456       errors.push_back({entry.second.getPointer(), entry.first});
3457     llvm::array_pod_sort(errors.begin(), errors.end());
3458 
3459     for (auto entry : errors) {
3460       auto loc = SMLoc::getFromPointer(entry.first);
3461       emitError(loc, "use of undeclared SSA value name");
3462     }
3463     return failure();
3464   }
3465 
3466   return success();
3467 }
3468 
3469 //===----------------------------------------------------------------------===//
3470 // SSA Value Handling
3471 //===----------------------------------------------------------------------===//
3472 
3473 void OperationParser::pushSSANameScope(bool isIsolated) {
3474   blocksByName.push_back(DenseMap<StringRef, std::pair<Block *, SMLoc>>());
3475   forwardRef.push_back(DenseMap<Block *, SMLoc>());
3476 
3477   // Push back a new name definition scope.
3478   if (isIsolated)
3479     isolatedNameScopes.push_back({});
3480   isolatedNameScopes.back().pushSSANameScope();
3481 }
3482 
3483 ParseResult OperationParser::popSSANameScope() {
3484   auto forwardRefInCurrentScope = forwardRef.pop_back_val();
3485 
3486   // Verify that all referenced blocks were defined.
3487   if (!forwardRefInCurrentScope.empty()) {
3488     SmallVector<std::pair<const char *, Block *>, 4> errors;
3489     // Iteration over the map isn't deterministic, so sort by source location.
3490     for (auto entry : forwardRefInCurrentScope) {
3491       errors.push_back({entry.second.getPointer(), entry.first});
3492       // Add this block to the top-level region to allow for automatic cleanup.
3493       moduleOp.getOperation()->getRegion(0).push_back(entry.first);
3494     }
3495     llvm::array_pod_sort(errors.begin(), errors.end());
3496 
3497     for (auto entry : errors) {
3498       auto loc = SMLoc::getFromPointer(entry.first);
3499       emitError(loc, "reference to an undefined block");
3500     }
3501     return failure();
3502   }
3503 
3504   // Pop the next nested namescope. If there is only one internal namescope,
3505   // just pop the isolated scope.
3506   auto &currentNameScope = isolatedNameScopes.back();
3507   if (currentNameScope.definitionsPerScope.size() == 1)
3508     isolatedNameScopes.pop_back();
3509   else
3510     currentNameScope.popSSANameScope();
3511 
3512   blocksByName.pop_back();
3513   return success();
3514 }
3515 
3516 /// Register a definition of a value with the symbol table.
3517 ParseResult OperationParser::addDefinition(SSAUseInfo useInfo, Value value) {
3518   auto &entries = getSSAValueEntry(useInfo.name);
3519 
3520   // Make sure there is a slot for this value.
3521   if (entries.size() <= useInfo.number)
3522     entries.resize(useInfo.number + 1);
3523 
3524   // If we already have an entry for this, check to see if it was a definition
3525   // or a forward reference.
3526   if (auto existing = entries[useInfo.number].first) {
3527     if (!isForwardRefPlaceholder(existing)) {
3528       return emitError(useInfo.loc)
3529           .append("redefinition of SSA value '", useInfo.name, "'")
3530           .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3531           .append("previously defined here");
3532     }
3533 
3534     // If it was a forward reference, update everything that used it to use
3535     // the actual definition instead, delete the forward ref, and remove it
3536     // from our set of forward references we track.
3537     existing.replaceAllUsesWith(value);
3538     existing.getDefiningOp()->destroy();
3539     forwardRefPlaceholders.erase(existing);
3540   }
3541 
3542   /// Record this definition for the current scope.
3543   entries[useInfo.number] = {value, useInfo.loc};
3544   recordDefinition(useInfo.name);
3545   return success();
3546 }
3547 
3548 /// Parse a (possibly empty) list of SSA operands.
3549 ///
3550 ///   ssa-use-list ::= ssa-use (`,` ssa-use)*
3551 ///   ssa-use-list-opt ::= ssa-use-list?
3552 ///
3553 ParseResult
3554 OperationParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
3555   if (getToken().isNot(Token::percent_identifier))
3556     return success();
3557   return parseCommaSeparatedList([&]() -> ParseResult {
3558     SSAUseInfo result;
3559     if (parseSSAUse(result))
3560       return failure();
3561     results.push_back(result);
3562     return success();
3563   });
3564 }
3565 
3566 /// Parse a SSA operand for an operation.
3567 ///
3568 ///   ssa-use ::= ssa-id
3569 ///
3570 ParseResult OperationParser::parseSSAUse(SSAUseInfo &result) {
3571   result.name = getTokenSpelling();
3572   result.number = 0;
3573   result.loc = getToken().getLoc();
3574   if (parseToken(Token::percent_identifier, "expected SSA operand"))
3575     return failure();
3576 
3577   // If we have an attribute ID, it is a result number.
3578   if (getToken().is(Token::hash_identifier)) {
3579     if (auto value = getToken().getHashIdentifierNumber())
3580       result.number = value.getValue();
3581     else
3582       return emitError("invalid SSA value result number");
3583     consumeToken(Token::hash_identifier);
3584   }
3585 
3586   return success();
3587 }
3588 
3589 /// Given an unbound reference to an SSA value and its type, return the value
3590 /// it specifies.  This returns null on failure.
3591 Value OperationParser::resolveSSAUse(SSAUseInfo useInfo, Type type) {
3592   auto &entries = getSSAValueEntry(useInfo.name);
3593 
3594   // If we have already seen a value of this name, return it.
3595   if (useInfo.number < entries.size() && entries[useInfo.number].first) {
3596     auto result = entries[useInfo.number].first;
3597     // Check that the type matches the other uses.
3598     if (result.getType() == type)
3599       return result;
3600 
3601     emitError(useInfo.loc, "use of value '")
3602         .append(useInfo.name,
3603                 "' expects different type than prior uses: ", type, " vs ",
3604                 result.getType())
3605         .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3606         .append("prior use here");
3607     return nullptr;
3608   }
3609 
3610   // Make sure we have enough slots for this.
3611   if (entries.size() <= useInfo.number)
3612     entries.resize(useInfo.number + 1);
3613 
3614   // If the value has already been defined and this is an overly large result
3615   // number, diagnose that.
3616   if (entries[0].first && !isForwardRefPlaceholder(entries[0].first))
3617     return (emitError(useInfo.loc, "reference to invalid result number"),
3618             nullptr);
3619 
3620   // Otherwise, this is a forward reference.  Create a placeholder and remember
3621   // that we did so.
3622   auto result = createForwardRefPlaceholder(useInfo.loc, type);
3623   entries[useInfo.number].first = result;
3624   entries[useInfo.number].second = useInfo.loc;
3625   return result;
3626 }
3627 
3628 /// Parse an SSA use with an associated type.
3629 ///
3630 ///   ssa-use-and-type ::= ssa-use `:` type
3631 ParseResult OperationParser::parseSSADefOrUseAndType(
3632     const std::function<ParseResult(SSAUseInfo, Type)> &action) {
3633   SSAUseInfo useInfo;
3634   if (parseSSAUse(useInfo) ||
3635       parseToken(Token::colon, "expected ':' and type for SSA operand"))
3636     return failure();
3637 
3638   auto type = parseType();
3639   if (!type)
3640     return failure();
3641 
3642   return action(useInfo, type);
3643 }
3644 
3645 /// Parse a (possibly empty) list of SSA operands, followed by a colon, then
3646 /// followed by a type list.
3647 ///
3648 ///   ssa-use-and-type-list
3649 ///     ::= ssa-use-list ':' type-list-no-parens
3650 ///
3651 ParseResult OperationParser::parseOptionalSSAUseAndTypeList(
3652     SmallVectorImpl<Value> &results) {
3653   SmallVector<SSAUseInfo, 4> valueIDs;
3654   if (parseOptionalSSAUseList(valueIDs))
3655     return failure();
3656 
3657   // If there were no operands, then there is no colon or type lists.
3658   if (valueIDs.empty())
3659     return success();
3660 
3661   SmallVector<Type, 4> types;
3662   if (parseToken(Token::colon, "expected ':' in operand list") ||
3663       parseTypeListNoParens(types))
3664     return failure();
3665 
3666   if (valueIDs.size() != types.size())
3667     return emitError("expected ")
3668            << valueIDs.size() << " types to match operand list";
3669 
3670   results.reserve(valueIDs.size());
3671   for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
3672     if (auto value = resolveSSAUse(valueIDs[i], types[i]))
3673       results.push_back(value);
3674     else
3675       return failure();
3676   }
3677 
3678   return success();
3679 }
3680 
3681 /// Record that a definition was added at the current scope.
3682 void OperationParser::recordDefinition(StringRef def) {
3683   isolatedNameScopes.back().recordDefinition(def);
3684 }
3685 
3686 /// Get the value entry for the given SSA name.
3687 SmallVectorImpl<std::pair<Value, SMLoc>> &
3688 OperationParser::getSSAValueEntry(StringRef name) {
3689   return isolatedNameScopes.back().values[name];
3690 }
3691 
3692 /// Create and remember a new placeholder for a forward reference.
3693 Value OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) {
3694   // Forward references are always created as operations, because we just need
3695   // something with a def/use chain.
3696   //
3697   // We create these placeholders as having an empty name, which we know
3698   // cannot be created through normal user input, allowing us to distinguish
3699   // them.
3700   auto name = OperationName("placeholder", getContext());
3701   auto *op = Operation::create(
3702       getEncodedSourceLocation(loc), name, type, /*operands=*/{},
3703       /*attributes=*/llvm::None, /*successors=*/{}, /*numRegions=*/0,
3704       /*resizableOperandList=*/false);
3705   forwardRefPlaceholders[op->getResult(0)] = loc;
3706   return op->getResult(0);
3707 }
3708 
3709 //===----------------------------------------------------------------------===//
3710 // Operation Parsing
3711 //===----------------------------------------------------------------------===//
3712 
3713 /// Parse an operation.
3714 ///
3715 ///  operation         ::= op-result-list?
3716 ///                        (generic-operation | custom-operation)
3717 ///                        trailing-location?
3718 ///  generic-operation ::= string-literal `(` ssa-use-list? `)`
3719 ///                        successor-list? (`(` region-list `)`)?
3720 ///                        attribute-dict? `:` function-type
3721 ///  custom-operation  ::= bare-id custom-operation-format
3722 ///  op-result-list    ::= op-result (`,` op-result)* `=`
3723 ///  op-result         ::= ssa-id (`:` integer-literal)
3724 ///
3725 ParseResult OperationParser::parseOperation() {
3726   auto loc = getToken().getLoc();
3727   SmallVector<std::tuple<StringRef, unsigned, SMLoc>, 1> resultIDs;
3728   size_t numExpectedResults = 0;
3729   if (getToken().is(Token::percent_identifier)) {
3730     // Parse the group of result ids.
3731     auto parseNextResult = [&]() -> ParseResult {
3732       // Parse the next result id.
3733       if (!getToken().is(Token::percent_identifier))
3734         return emitError("expected valid ssa identifier");
3735 
3736       Token nameTok = getToken();
3737       consumeToken(Token::percent_identifier);
3738 
3739       // If the next token is a ':', we parse the expected result count.
3740       size_t expectedSubResults = 1;
3741       if (consumeIf(Token::colon)) {
3742         // Check that the next token is an integer.
3743         if (!getToken().is(Token::integer))
3744           return emitError("expected integer number of results");
3745 
3746         // Check that number of results is > 0.
3747         auto val = getToken().getUInt64IntegerValue();
3748         if (!val.hasValue() || val.getValue() < 1)
3749           return emitError("expected named operation to have atleast 1 result");
3750         consumeToken(Token::integer);
3751         expectedSubResults = *val;
3752       }
3753 
3754       resultIDs.emplace_back(nameTok.getSpelling(), expectedSubResults,
3755                              nameTok.getLoc());
3756       numExpectedResults += expectedSubResults;
3757       return success();
3758     };
3759     if (parseCommaSeparatedList(parseNextResult))
3760       return failure();
3761 
3762     if (parseToken(Token::equal, "expected '=' after SSA name"))
3763       return failure();
3764   }
3765 
3766   Operation *op;
3767   if (getToken().is(Token::bare_identifier) || getToken().isKeyword())
3768     op = parseCustomOperation();
3769   else if (getToken().is(Token::string))
3770     op = parseGenericOperation();
3771   else
3772     return emitError("expected operation name in quotes");
3773 
3774   // If parsing of the basic operation failed, then this whole thing fails.
3775   if (!op)
3776     return failure();
3777 
3778   // If the operation had a name, register it.
3779   if (!resultIDs.empty()) {
3780     if (op->getNumResults() == 0)
3781       return emitError(loc, "cannot name an operation with no results");
3782     if (numExpectedResults != op->getNumResults())
3783       return emitError(loc, "operation defines ")
3784              << op->getNumResults() << " results but was provided "
3785              << numExpectedResults << " to bind";
3786 
3787     // Add definitions for each of the result groups.
3788     unsigned opResI = 0;
3789     for (std::tuple<StringRef, unsigned, SMLoc> &resIt : resultIDs) {
3790       for (unsigned subRes : llvm::seq<unsigned>(0, std::get<1>(resIt))) {
3791         if (addDefinition({std::get<0>(resIt), subRes, std::get<2>(resIt)},
3792                           op->getResult(opResI++)))
3793           return failure();
3794       }
3795     }
3796   }
3797 
3798   return success();
3799 }
3800 
3801 /// Parse a single operation successor.
3802 ///
3803 ///   successor ::= block-id
3804 ///
3805 ParseResult OperationParser::parseSuccessor(Block *&dest) {
3806   // Verify branch is identifier and get the matching block.
3807   if (!getToken().is(Token::caret_identifier))
3808     return emitError("expected block name");
3809   dest = getBlockNamed(getTokenSpelling(), getToken().getLoc());
3810   consumeToken();
3811   return success();
3812 }
3813 
3814 /// Parse a comma-separated list of operation successors in brackets.
3815 ///
3816 ///   successor-list ::= `[` successor (`,` successor )* `]`
3817 ///
3818 ParseResult
3819 OperationParser::parseSuccessors(SmallVectorImpl<Block *> &destinations) {
3820   if (parseToken(Token::l_square, "expected '['"))
3821     return failure();
3822 
3823   auto parseElt = [this, &destinations] {
3824     Block *dest;
3825     ParseResult res = parseSuccessor(dest);
3826     destinations.push_back(dest);
3827     return res;
3828   };
3829   return parseCommaSeparatedListUntil(Token::r_square, parseElt,
3830                                       /*allowEmptyList=*/false);
3831 }
3832 
3833 namespace {
3834 // RAII-style guard for cleaning up the regions in the operation state before
3835 // deleting them.  Within the parser, regions may get deleted if parsing failed,
3836 // and other errors may be present, in particular undominated uses.  This makes
3837 // sure such uses are deleted.
3838 struct CleanupOpStateRegions {
3839   ~CleanupOpStateRegions() {
3840     SmallVector<Region *, 4> regionsToClean;
3841     regionsToClean.reserve(state.regions.size());
3842     for (auto &region : state.regions)
3843       if (region)
3844         for (auto &block : *region)
3845           block.dropAllDefinedValueUses();
3846   }
3847   OperationState &state;
3848 };
3849 } // namespace
3850 
3851 Operation *OperationParser::parseGenericOperation() {
3852   // Get location information for the operation.
3853   auto srcLocation = getEncodedSourceLocation(getToken().getLoc());
3854 
3855   auto name = getToken().getStringValue();
3856   if (name.empty())
3857     return (emitError("empty operation name is invalid"), nullptr);
3858   if (name.find('\0') != StringRef::npos)
3859     return (emitError("null character not allowed in operation name"), nullptr);
3860 
3861   consumeToken(Token::string);
3862 
3863   OperationState result(srcLocation, name);
3864 
3865   // Generic operations have a resizable operation list.
3866   result.setOperandListToResizable();
3867 
3868   // Parse the operand list.
3869   SmallVector<SSAUseInfo, 8> operandInfos;
3870   if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
3871       parseOptionalSSAUseList(operandInfos) ||
3872       parseToken(Token::r_paren, "expected ')' to end operand list")) {
3873     return nullptr;
3874   }
3875 
3876   // Parse the successor list.
3877   if (getToken().is(Token::l_square)) {
3878     // Check if the operation is a known terminator.
3879     const AbstractOperation *abstractOp = result.name.getAbstractOperation();
3880     if (abstractOp && !abstractOp->hasProperty(OperationProperty::Terminator))
3881       return emitError("successors in non-terminator"), nullptr;
3882 
3883     SmallVector<Block *, 2> successors;
3884     if (parseSuccessors(successors))
3885       return nullptr;
3886     result.addSuccessors(successors);
3887   }
3888 
3889   // Parse the region list.
3890   CleanupOpStateRegions guard{result};
3891   if (consumeIf(Token::l_paren)) {
3892     do {
3893       // Create temporary regions with the top level region as parent.
3894       result.regions.emplace_back(new Region(moduleOp));
3895       if (parseRegion(*result.regions.back(), /*entryArguments=*/{}))
3896         return nullptr;
3897     } while (consumeIf(Token::comma));
3898     if (parseToken(Token::r_paren, "expected ')' to end region list"))
3899       return nullptr;
3900   }
3901 
3902   if (getToken().is(Token::l_brace)) {
3903     if (parseAttributeDict(result.attributes))
3904       return nullptr;
3905   }
3906 
3907   if (parseToken(Token::colon, "expected ':' followed by operation type"))
3908     return nullptr;
3909 
3910   auto typeLoc = getToken().getLoc();
3911   auto type = parseType();
3912   if (!type)
3913     return nullptr;
3914   auto fnType = type.dyn_cast<FunctionType>();
3915   if (!fnType)
3916     return (emitError(typeLoc, "expected function type"), nullptr);
3917 
3918   result.addTypes(fnType.getResults());
3919 
3920   // Check that we have the right number of types for the operands.
3921   auto operandTypes = fnType.getInputs();
3922   if (operandTypes.size() != operandInfos.size()) {
3923     auto plural = "s"[operandInfos.size() == 1];
3924     return (emitError(typeLoc, "expected ")
3925                 << operandInfos.size() << " operand type" << plural
3926                 << " but had " << operandTypes.size(),
3927             nullptr);
3928   }
3929 
3930   // Resolve all of the operands.
3931   for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
3932     result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
3933     if (!result.operands.back())
3934       return nullptr;
3935   }
3936 
3937   // Parse a location if one is present.
3938   if (parseOptionalTrailingLocation(result.location))
3939     return nullptr;
3940 
3941   return opBuilder.createOperation(result);
3942 }
3943 
3944 Operation *OperationParser::parseGenericOperation(Block *insertBlock,
3945                                                   Block::iterator insertPt) {
3946   OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder);
3947   opBuilder.setInsertionPoint(insertBlock, insertPt);
3948   return parseGenericOperation();
3949 }
3950 
3951 namespace {
3952 class CustomOpAsmParser : public OpAsmParser {
3953 public:
3954   CustomOpAsmParser(SMLoc nameLoc, const AbstractOperation *opDefinition,
3955                     OperationParser &parser)
3956       : nameLoc(nameLoc), opDefinition(opDefinition), parser(parser) {}
3957 
3958   /// Parse an instance of the operation described by 'opDefinition' into the
3959   /// provided operation state.
3960   ParseResult parseOperation(OperationState &opState) {
3961     if (opDefinition->parseAssembly(*this, opState))
3962       return failure();
3963     return success();
3964   }
3965 
3966   Operation *parseGenericOperation(Block *insertBlock,
3967                                    Block::iterator insertPt) final {
3968     return parser.parseGenericOperation(insertBlock, insertPt);
3969   }
3970 
3971   //===--------------------------------------------------------------------===//
3972   // Utilities
3973   //===--------------------------------------------------------------------===//
3974 
3975   /// Return if any errors were emitted during parsing.
3976   bool didEmitError() const { return emittedError; }
3977 
3978   /// Emit a diagnostic at the specified location and return failure.
3979   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
3980     emittedError = true;
3981     return parser.emitError(loc, "custom op '" + opDefinition->name + "' " +
3982                                      message);
3983   }
3984 
3985   llvm::SMLoc getCurrentLocation() override {
3986     return parser.getToken().getLoc();
3987   }
3988 
3989   Builder &getBuilder() const override { return parser.builder; }
3990 
3991   llvm::SMLoc getNameLoc() const override { return nameLoc; }
3992 
3993   //===--------------------------------------------------------------------===//
3994   // Token Parsing
3995   //===--------------------------------------------------------------------===//
3996 
3997   /// Parse a `->` token.
3998   ParseResult parseArrow() override {
3999     return parser.parseToken(Token::arrow, "expected '->'");
4000   }
4001 
4002   /// Parses a `->` if present.
4003   ParseResult parseOptionalArrow() override {
4004     return success(parser.consumeIf(Token::arrow));
4005   }
4006 
4007   /// Parse a `:` token.
4008   ParseResult parseColon() override {
4009     return parser.parseToken(Token::colon, "expected ':'");
4010   }
4011 
4012   /// Parse a `:` token if present.
4013   ParseResult parseOptionalColon() override {
4014     return success(parser.consumeIf(Token::colon));
4015   }
4016 
4017   /// Parse a `,` token.
4018   ParseResult parseComma() override {
4019     return parser.parseToken(Token::comma, "expected ','");
4020   }
4021 
4022   /// Parse a `,` token if present.
4023   ParseResult parseOptionalComma() override {
4024     return success(parser.consumeIf(Token::comma));
4025   }
4026 
4027   /// Parses a `...` if present.
4028   ParseResult parseOptionalEllipsis() override {
4029     return success(parser.consumeIf(Token::ellipsis));
4030   }
4031 
4032   /// Parse a `=` token.
4033   ParseResult parseEqual() override {
4034     return parser.parseToken(Token::equal, "expected '='");
4035   }
4036 
4037   /// Parse a '<' token.
4038   ParseResult parseLess() override {
4039     return parser.parseToken(Token::less, "expected '<'");
4040   }
4041 
4042   /// Parse a '>' token.
4043   ParseResult parseGreater() override {
4044     return parser.parseToken(Token::greater, "expected '>'");
4045   }
4046 
4047   /// Parse a `(` token.
4048   ParseResult parseLParen() override {
4049     return parser.parseToken(Token::l_paren, "expected '('");
4050   }
4051 
4052   /// Parses a '(' if present.
4053   ParseResult parseOptionalLParen() override {
4054     return success(parser.consumeIf(Token::l_paren));
4055   }
4056 
4057   /// Parse a `)` token.
4058   ParseResult parseRParen() override {
4059     return parser.parseToken(Token::r_paren, "expected ')'");
4060   }
4061 
4062   /// Parses a ')' if present.
4063   ParseResult parseOptionalRParen() override {
4064     return success(parser.consumeIf(Token::r_paren));
4065   }
4066 
4067   /// Parse a `[` token.
4068   ParseResult parseLSquare() override {
4069     return parser.parseToken(Token::l_square, "expected '['");
4070   }
4071 
4072   /// Parses a '[' if present.
4073   ParseResult parseOptionalLSquare() override {
4074     return success(parser.consumeIf(Token::l_square));
4075   }
4076 
4077   /// Parse a `]` token.
4078   ParseResult parseRSquare() override {
4079     return parser.parseToken(Token::r_square, "expected ']'");
4080   }
4081 
4082   /// Parses a ']' if present.
4083   ParseResult parseOptionalRSquare() override {
4084     return success(parser.consumeIf(Token::r_square));
4085   }
4086 
4087   //===--------------------------------------------------------------------===//
4088   // Attribute Parsing
4089   //===--------------------------------------------------------------------===//
4090 
4091   /// Parse an arbitrary attribute of a given type and return it in result. This
4092   /// also adds the attribute to the specified attribute list with the specified
4093   /// name.
4094   ParseResult parseAttribute(Attribute &result, Type type, StringRef attrName,
4095                              SmallVectorImpl<NamedAttribute> &attrs) override {
4096     result = parser.parseAttribute(type);
4097     if (!result)
4098       return failure();
4099 
4100     attrs.push_back(parser.builder.getNamedAttr(attrName, result));
4101     return success();
4102   }
4103 
4104   /// Parse a named dictionary into 'result' if it is present.
4105   ParseResult
4106   parseOptionalAttrDict(SmallVectorImpl<NamedAttribute> &result) override {
4107     if (parser.getToken().isNot(Token::l_brace))
4108       return success();
4109     return parser.parseAttributeDict(result);
4110   }
4111 
4112   /// Parse a named dictionary into 'result' if the `attributes` keyword is
4113   /// present.
4114   ParseResult parseOptionalAttrDictWithKeyword(
4115       SmallVectorImpl<NamedAttribute> &result) override {
4116     if (failed(parseOptionalKeyword("attributes")))
4117       return success();
4118     return parser.parseAttributeDict(result);
4119   }
4120 
4121   /// Parse an affine map instance into 'map'.
4122   ParseResult parseAffineMap(AffineMap &map) override {
4123     return parser.parseAffineMapReference(map);
4124   }
4125 
4126   /// Parse an integer set instance into 'set'.
4127   ParseResult printIntegerSet(IntegerSet &set) override {
4128     return parser.parseIntegerSetReference(set);
4129   }
4130 
4131   //===--------------------------------------------------------------------===//
4132   // Identifier Parsing
4133   //===--------------------------------------------------------------------===//
4134 
4135   /// Returns if the current token corresponds to a keyword.
4136   bool isCurrentTokenAKeyword() const {
4137     return parser.getToken().is(Token::bare_identifier) ||
4138            parser.getToken().isKeyword();
4139   }
4140 
4141   /// Parse the given keyword if present.
4142   ParseResult parseOptionalKeyword(StringRef keyword) override {
4143     // Check that the current token has the same spelling.
4144     if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword)
4145       return failure();
4146     parser.consumeToken();
4147     return success();
4148   }
4149 
4150   /// Parse a keyword, if present, into 'keyword'.
4151   ParseResult parseOptionalKeyword(StringRef *keyword) override {
4152     // Check that the current token is a keyword.
4153     if (!isCurrentTokenAKeyword())
4154       return failure();
4155 
4156     *keyword = parser.getTokenSpelling();
4157     parser.consumeToken();
4158     return success();
4159   }
4160 
4161   /// Parse an optional @-identifier and store it (without the '@' symbol) in a
4162   /// string attribute named 'attrName'.
4163   ParseResult
4164   parseOptionalSymbolName(StringAttr &result, StringRef attrName,
4165                           SmallVectorImpl<NamedAttribute> &attrs) override {
4166     Token atToken = parser.getToken();
4167     if (atToken.isNot(Token::at_identifier))
4168       return failure();
4169 
4170     result = getBuilder().getStringAttr(extractSymbolReference(atToken));
4171     attrs.push_back(getBuilder().getNamedAttr(attrName, result));
4172     parser.consumeToken();
4173     return success();
4174   }
4175 
4176   //===--------------------------------------------------------------------===//
4177   // Operand Parsing
4178   //===--------------------------------------------------------------------===//
4179 
4180   /// Parse a single operand.
4181   ParseResult parseOperand(OperandType &result) override {
4182     OperationParser::SSAUseInfo useInfo;
4183     if (parser.parseSSAUse(useInfo))
4184       return failure();
4185 
4186     result = {useInfo.loc, useInfo.name, useInfo.number};
4187     return success();
4188   }
4189 
4190   /// Parse zero or more SSA comma-separated operand references with a specified
4191   /// surrounding delimiter, and an optional required operand count.
4192   ParseResult parseOperandList(SmallVectorImpl<OperandType> &result,
4193                                int requiredOperandCount = -1,
4194                                Delimiter delimiter = Delimiter::None) override {
4195     return parseOperandOrRegionArgList(result, /*isOperandList=*/true,
4196                                        requiredOperandCount, delimiter);
4197   }
4198 
4199   /// Parse zero or more SSA comma-separated operand or region arguments with
4200   ///  optional surrounding delimiter and required operand count.
4201   ParseResult
4202   parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result,
4203                               bool isOperandList, int requiredOperandCount = -1,
4204                               Delimiter delimiter = Delimiter::None) {
4205     auto startLoc = parser.getToken().getLoc();
4206 
4207     // Handle delimiters.
4208     switch (delimiter) {
4209     case Delimiter::None:
4210       // Don't check for the absence of a delimiter if the number of operands
4211       // is unknown (and hence the operand list could be empty).
4212       if (requiredOperandCount == -1)
4213         break;
4214       // Token already matches an identifier and so can't be a delimiter.
4215       if (parser.getToken().is(Token::percent_identifier))
4216         break;
4217       // Test against known delimiters.
4218       if (parser.getToken().is(Token::l_paren) ||
4219           parser.getToken().is(Token::l_square))
4220         return emitError(startLoc, "unexpected delimiter");
4221       return emitError(startLoc, "invalid operand");
4222     case Delimiter::OptionalParen:
4223       if (parser.getToken().isNot(Token::l_paren))
4224         return success();
4225       LLVM_FALLTHROUGH;
4226     case Delimiter::Paren:
4227       if (parser.parseToken(Token::l_paren, "expected '(' in operand list"))
4228         return failure();
4229       break;
4230     case Delimiter::OptionalSquare:
4231       if (parser.getToken().isNot(Token::l_square))
4232         return success();
4233       LLVM_FALLTHROUGH;
4234     case Delimiter::Square:
4235       if (parser.parseToken(Token::l_square, "expected '[' in operand list"))
4236         return failure();
4237       break;
4238     }
4239 
4240     // Check for zero operands.
4241     if (parser.getToken().is(Token::percent_identifier)) {
4242       do {
4243         OperandType operandOrArg;
4244         if (isOperandList ? parseOperand(operandOrArg)
4245                           : parseRegionArgument(operandOrArg))
4246           return failure();
4247         result.push_back(operandOrArg);
4248       } while (parser.consumeIf(Token::comma));
4249     }
4250 
4251     // Handle delimiters.   If we reach here, the optional delimiters were
4252     // present, so we need to parse their closing one.
4253     switch (delimiter) {
4254     case Delimiter::None:
4255       break;
4256     case Delimiter::OptionalParen:
4257     case Delimiter::Paren:
4258       if (parser.parseToken(Token::r_paren, "expected ')' in operand list"))
4259         return failure();
4260       break;
4261     case Delimiter::OptionalSquare:
4262     case Delimiter::Square:
4263       if (parser.parseToken(Token::r_square, "expected ']' in operand list"))
4264         return failure();
4265       break;
4266     }
4267 
4268     if (requiredOperandCount != -1 &&
4269         result.size() != static_cast<size_t>(requiredOperandCount))
4270       return emitError(startLoc, "expected ")
4271              << requiredOperandCount << " operands";
4272     return success();
4273   }
4274 
4275   /// Parse zero or more trailing SSA comma-separated trailing operand
4276   /// references with a specified surrounding delimiter, and an optional
4277   /// required operand count. A leading comma is expected before the operands.
4278   ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result,
4279                                        int requiredOperandCount,
4280                                        Delimiter delimiter) override {
4281     if (parser.getToken().is(Token::comma)) {
4282       parseComma();
4283       return parseOperandList(result, requiredOperandCount, delimiter);
4284     }
4285     if (requiredOperandCount != -1)
4286       return emitError(parser.getToken().getLoc(), "expected ")
4287              << requiredOperandCount << " operands";
4288     return success();
4289   }
4290 
4291   /// Resolve an operand to an SSA value, emitting an error on failure.
4292   ParseResult resolveOperand(const OperandType &operand, Type type,
4293                              SmallVectorImpl<Value> &result) override {
4294     OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
4295                                                operand.location};
4296     if (auto value = parser.resolveSSAUse(operandInfo, type)) {
4297       result.push_back(value);
4298       return success();
4299     }
4300     return failure();
4301   }
4302 
4303   /// Parse an AffineMap of SSA ids.
4304   ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands,
4305                                      Attribute &mapAttr, StringRef attrName,
4306                                      SmallVectorImpl<NamedAttribute> &attrs,
4307                                      Delimiter delimiter) override {
4308     SmallVector<OperandType, 2> dimOperands;
4309     SmallVector<OperandType, 1> symOperands;
4310 
4311     auto parseElement = [&](bool isSymbol) -> ParseResult {
4312       OperandType operand;
4313       if (parseOperand(operand))
4314         return failure();
4315       if (isSymbol)
4316         symOperands.push_back(operand);
4317       else
4318         dimOperands.push_back(operand);
4319       return success();
4320     };
4321 
4322     AffineMap map;
4323     if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter))
4324       return failure();
4325     // Add AffineMap attribute.
4326     if (map) {
4327       mapAttr = AffineMapAttr::get(map);
4328       attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr));
4329     }
4330 
4331     // Add dim operands before symbol operands in 'operands'.
4332     operands.assign(dimOperands.begin(), dimOperands.end());
4333     operands.append(symOperands.begin(), symOperands.end());
4334     return success();
4335   }
4336 
4337   //===--------------------------------------------------------------------===//
4338   // Region Parsing
4339   //===--------------------------------------------------------------------===//
4340 
4341   /// Parse a region that takes `arguments` of `argTypes` types.  This
4342   /// effectively defines the SSA values of `arguments` and assigns their type.
4343   ParseResult parseRegion(Region &region, ArrayRef<OperandType> arguments,
4344                           ArrayRef<Type> argTypes,
4345                           bool enableNameShadowing) override {
4346     assert(arguments.size() == argTypes.size() &&
4347            "mismatching number of arguments and types");
4348 
4349     SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2>
4350         regionArguments;
4351     for (auto pair : llvm::zip(arguments, argTypes)) {
4352       const OperandType &operand = std::get<0>(pair);
4353       Type type = std::get<1>(pair);
4354       OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
4355                                                  operand.location};
4356       regionArguments.emplace_back(operandInfo, type);
4357     }
4358 
4359     // Try to parse the region.
4360     assert((!enableNameShadowing ||
4361             opDefinition->hasProperty(OperationProperty::IsolatedFromAbove)) &&
4362            "name shadowing is only allowed on isolated regions");
4363     if (parser.parseRegion(region, regionArguments, enableNameShadowing))
4364       return failure();
4365     return success();
4366   }
4367 
4368   /// Parses a region if present.
4369   ParseResult parseOptionalRegion(Region &region,
4370                                   ArrayRef<OperandType> arguments,
4371                                   ArrayRef<Type> argTypes,
4372                                   bool enableNameShadowing) override {
4373     if (parser.getToken().isNot(Token::l_brace))
4374       return success();
4375     return parseRegion(region, arguments, argTypes, enableNameShadowing);
4376   }
4377 
4378   /// Parse a region argument. The type of the argument will be resolved later
4379   /// by a call to `parseRegion`.
4380   ParseResult parseRegionArgument(OperandType &argument) override {
4381     return parseOperand(argument);
4382   }
4383 
4384   /// Parse a region argument if present.
4385   ParseResult parseOptionalRegionArgument(OperandType &argument) override {
4386     if (parser.getToken().isNot(Token::percent_identifier))
4387       return success();
4388     return parseRegionArgument(argument);
4389   }
4390 
4391   ParseResult
4392   parseRegionArgumentList(SmallVectorImpl<OperandType> &result,
4393                           int requiredOperandCount = -1,
4394                           Delimiter delimiter = Delimiter::None) override {
4395     return parseOperandOrRegionArgList(result, /*isOperandList=*/false,
4396                                        requiredOperandCount, delimiter);
4397   }
4398 
4399   //===--------------------------------------------------------------------===//
4400   // Successor Parsing
4401   //===--------------------------------------------------------------------===//
4402 
4403   /// Parse a single operation successor.
4404   ParseResult parseSuccessor(Block *&dest) override {
4405     return parser.parseSuccessor(dest);
4406   }
4407 
4408   /// Parse an optional operation successor and its operand list.
4409   OptionalParseResult parseOptionalSuccessor(Block *&dest) override {
4410     if (parser.getToken().isNot(Token::caret_identifier))
4411       return llvm::None;
4412     return parseSuccessor(dest);
4413   }
4414 
4415   /// Parse a single operation successor and its operand list.
4416   ParseResult
4417   parseSuccessorAndUseList(Block *&dest,
4418                            SmallVectorImpl<Value> &operands) override {
4419     if (parseSuccessor(dest))
4420       return failure();
4421 
4422     // Handle optional arguments.
4423     if (succeeded(parseOptionalLParen()) &&
4424         (parser.parseOptionalSSAUseAndTypeList(operands) || parseRParen())) {
4425       return failure();
4426     }
4427     return success();
4428   }
4429 
4430   //===--------------------------------------------------------------------===//
4431   // Type Parsing
4432   //===--------------------------------------------------------------------===//
4433 
4434   /// Parse a type.
4435   ParseResult parseType(Type &result) override {
4436     return failure(!(result = parser.parseType()));
4437   }
4438 
4439   /// Parse an arrow followed by a type list.
4440   ParseResult parseArrowTypeList(SmallVectorImpl<Type> &result) override {
4441     if (parseArrow() || parser.parseFunctionResultTypes(result))
4442       return failure();
4443     return success();
4444   }
4445 
4446   /// Parse an optional arrow followed by a type list.
4447   ParseResult
4448   parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override {
4449     if (!parser.consumeIf(Token::arrow))
4450       return success();
4451     return parser.parseFunctionResultTypes(result);
4452   }
4453 
4454   /// Parse a colon followed by a type.
4455   ParseResult parseColonType(Type &result) override {
4456     return failure(parser.parseToken(Token::colon, "expected ':'") ||
4457                    !(result = parser.parseType()));
4458   }
4459 
4460   /// Parse a colon followed by a type list, which must have at least one type.
4461   ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override {
4462     if (parser.parseToken(Token::colon, "expected ':'"))
4463       return failure();
4464     return parser.parseTypeListNoParens(result);
4465   }
4466 
4467   /// Parse an optional colon followed by a type list, which if present must
4468   /// have at least one type.
4469   ParseResult
4470   parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override {
4471     if (!parser.consumeIf(Token::colon))
4472       return success();
4473     return parser.parseTypeListNoParens(result);
4474   }
4475 
4476   /// Parse a list of assignments of the form
4477   /// (%x1 = %y1 : type1, %x2 = %y2 : type2, ...).
4478   /// The list must contain at least one entry
4479   ParseResult parseAssignmentList(SmallVectorImpl<OperandType> &lhs,
4480                                   SmallVectorImpl<OperandType> &rhs) override {
4481     auto parseElt = [&]() -> ParseResult {
4482       OperandType regionArg, operand;
4483       if (parseRegionArgument(regionArg) || parseEqual() ||
4484           parseOperand(operand))
4485         return failure();
4486       lhs.push_back(regionArg);
4487       rhs.push_back(operand);
4488       return success();
4489     };
4490     if (parseLParen())
4491       return failure();
4492     return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
4493   }
4494 
4495 private:
4496   /// The source location of the operation name.
4497   SMLoc nameLoc;
4498 
4499   /// The abstract information of the operation.
4500   const AbstractOperation *opDefinition;
4501 
4502   /// The main operation parser.
4503   OperationParser &parser;
4504 
4505   /// A flag that indicates if any errors were emitted during parsing.
4506   bool emittedError = false;
4507 };
4508 } // end anonymous namespace.
4509 
4510 Operation *OperationParser::parseCustomOperation() {
4511   auto opLoc = getToken().getLoc();
4512   auto opName = getTokenSpelling();
4513 
4514   auto *opDefinition = AbstractOperation::lookup(opName, getContext());
4515   if (!opDefinition && !opName.contains('.')) {
4516     // If the operation name has no namespace prefix we treat it as a standard
4517     // operation and prefix it with "std".
4518     // TODO: Would it be better to just build a mapping of the registered
4519     // operations in the standard dialect?
4520     opDefinition =
4521         AbstractOperation::lookup(Twine("std." + opName).str(), getContext());
4522   }
4523 
4524   if (!opDefinition) {
4525     emitError(opLoc) << "custom op '" << opName << "' is unknown";
4526     return nullptr;
4527   }
4528 
4529   consumeToken();
4530 
4531   // If the custom op parser crashes, produce some indication to help
4532   // debugging.
4533   std::string opNameStr = opName.str();
4534   llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'",
4535                                    opNameStr.c_str());
4536 
4537   // Get location information for the operation.
4538   auto srcLocation = getEncodedSourceLocation(opLoc);
4539 
4540   // Have the op implementation take a crack and parsing this.
4541   OperationState opState(srcLocation, opDefinition->name);
4542   CleanupOpStateRegions guard{opState};
4543   CustomOpAsmParser opAsmParser(opLoc, opDefinition, *this);
4544   if (opAsmParser.parseOperation(opState))
4545     return nullptr;
4546 
4547   // If it emitted an error, we failed.
4548   if (opAsmParser.didEmitError())
4549     return nullptr;
4550 
4551   // Parse a location if one is present.
4552   if (parseOptionalTrailingLocation(opState.location))
4553     return nullptr;
4554 
4555   // Otherwise, we succeeded.  Use the state it parsed as our op information.
4556   return opBuilder.createOperation(opState);
4557 }
4558 
4559 //===----------------------------------------------------------------------===//
4560 // Region Parsing
4561 //===----------------------------------------------------------------------===//
4562 
4563 /// Region.
4564 ///
4565 ///   region ::= '{' region-body
4566 ///
4567 ParseResult OperationParser::parseRegion(
4568     Region &region,
4569     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
4570     bool isIsolatedNameScope) {
4571   // Parse the '{'.
4572   if (parseToken(Token::l_brace, "expected '{' to begin a region"))
4573     return failure();
4574 
4575   // Check for an empty region.
4576   if (entryArguments.empty() && consumeIf(Token::r_brace))
4577     return success();
4578   auto currentPt = opBuilder.saveInsertionPoint();
4579 
4580   // Push a new named value scope.
4581   pushSSANameScope(isIsolatedNameScope);
4582 
4583   // Parse the first block directly to allow for it to be unnamed.
4584   Block *block = new Block();
4585 
4586   // Add arguments to the entry block.
4587   if (!entryArguments.empty()) {
4588     for (auto &placeholderArgPair : entryArguments) {
4589       auto &argInfo = placeholderArgPair.first;
4590       // Ensure that the argument was not already defined.
4591       if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) {
4592         return emitError(argInfo.loc, "region entry argument '" + argInfo.name +
4593                                           "' is already in use")
4594                    .attachNote(getEncodedSourceLocation(*defLoc))
4595                << "previously referenced here";
4596       }
4597       if (addDefinition(placeholderArgPair.first,
4598                         block->addArgument(placeholderArgPair.second))) {
4599         delete block;
4600         return failure();
4601       }
4602     }
4603 
4604     // If we had named arguments, then don't allow a block name.
4605     if (getToken().is(Token::caret_identifier))
4606       return emitError("invalid block name in region with named arguments");
4607   }
4608 
4609   if (parseBlock(block)) {
4610     delete block;
4611     return failure();
4612   }
4613 
4614   // Verify that no other arguments were parsed.
4615   if (!entryArguments.empty() &&
4616       block->getNumArguments() > entryArguments.size()) {
4617     delete block;
4618     return emitError("entry block arguments were already defined");
4619   }
4620 
4621   // Parse the rest of the region.
4622   region.push_back(block);
4623   if (parseRegionBody(region))
4624     return failure();
4625 
4626   // Pop the SSA value scope for this region.
4627   if (popSSANameScope())
4628     return failure();
4629 
4630   // Reset the original insertion point.
4631   opBuilder.restoreInsertionPoint(currentPt);
4632   return success();
4633 }
4634 
4635 /// Region.
4636 ///
4637 ///   region-body ::= block* '}'
4638 ///
4639 ParseResult OperationParser::parseRegionBody(Region &region) {
4640   // Parse the list of blocks.
4641   while (!consumeIf(Token::r_brace)) {
4642     Block *newBlock = nullptr;
4643     if (parseBlock(newBlock))
4644       return failure();
4645     region.push_back(newBlock);
4646   }
4647   return success();
4648 }
4649 
4650 //===----------------------------------------------------------------------===//
4651 // Block Parsing
4652 //===----------------------------------------------------------------------===//
4653 
4654 /// Block declaration.
4655 ///
4656 ///   block ::= block-label? operation*
4657 ///   block-label    ::= block-id block-arg-list? `:`
4658 ///   block-id       ::= caret-id
4659 ///   block-arg-list ::= `(` ssa-id-and-type-list? `)`
4660 ///
4661 ParseResult OperationParser::parseBlock(Block *&block) {
4662   // The first block of a region may already exist, if it does the caret
4663   // identifier is optional.
4664   if (block && getToken().isNot(Token::caret_identifier))
4665     return parseBlockBody(block);
4666 
4667   SMLoc nameLoc = getToken().getLoc();
4668   auto name = getTokenSpelling();
4669   if (parseToken(Token::caret_identifier, "expected block name"))
4670     return failure();
4671 
4672   block = defineBlockNamed(name, nameLoc, block);
4673 
4674   // Fail if the block was already defined.
4675   if (!block)
4676     return emitError(nameLoc, "redefinition of block '") << name << "'";
4677 
4678   // If an argument list is present, parse it.
4679   if (consumeIf(Token::l_paren)) {
4680     SmallVector<BlockArgument, 8> bbArgs;
4681     if (parseOptionalBlockArgList(bbArgs, block) ||
4682         parseToken(Token::r_paren, "expected ')' to end argument list"))
4683       return failure();
4684   }
4685 
4686   if (parseToken(Token::colon, "expected ':' after block name"))
4687     return failure();
4688 
4689   return parseBlockBody(block);
4690 }
4691 
4692 ParseResult OperationParser::parseBlockBody(Block *block) {
4693   // Set the insertion point to the end of the block to parse.
4694   opBuilder.setInsertionPointToEnd(block);
4695 
4696   // Parse the list of operations that make up the body of the block.
4697   while (getToken().isNot(Token::caret_identifier, Token::r_brace))
4698     if (parseOperation())
4699       return failure();
4700 
4701   return success();
4702 }
4703 
4704 /// Get the block with the specified name, creating it if it doesn't already
4705 /// exist.  The location specified is the point of use, which allows
4706 /// us to diagnose references to blocks that are not defined precisely.
4707 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) {
4708   auto &blockAndLoc = getBlockInfoByName(name);
4709   if (!blockAndLoc.first) {
4710     blockAndLoc = {new Block(), loc};
4711     insertForwardRef(blockAndLoc.first, loc);
4712   }
4713 
4714   return blockAndLoc.first;
4715 }
4716 
4717 /// Define the block with the specified name. Returns the Block* or nullptr in
4718 /// the case of redefinition.
4719 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc,
4720                                          Block *existing) {
4721   auto &blockAndLoc = getBlockInfoByName(name);
4722   if (!blockAndLoc.first) {
4723     // If the caller provided a block, use it.  Otherwise create a new one.
4724     if (!existing)
4725       existing = new Block();
4726     blockAndLoc.first = existing;
4727     blockAndLoc.second = loc;
4728     return blockAndLoc.first;
4729   }
4730 
4731   // Forward declarations are removed once defined, so if we are defining a
4732   // existing block and it is not a forward declaration, then it is a
4733   // redeclaration.
4734   if (!eraseForwardRef(blockAndLoc.first))
4735     return nullptr;
4736   return blockAndLoc.first;
4737 }
4738 
4739 /// Parse a (possibly empty) list of SSA operands with types as block arguments.
4740 ///
4741 ///   ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
4742 ///
4743 ParseResult OperationParser::parseOptionalBlockArgList(
4744     SmallVectorImpl<BlockArgument> &results, Block *owner) {
4745   if (getToken().is(Token::r_brace))
4746     return success();
4747 
4748   // If the block already has arguments, then we're handling the entry block.
4749   // Parse and register the names for the arguments, but do not add them.
4750   bool definingExistingArgs = owner->getNumArguments() != 0;
4751   unsigned nextArgument = 0;
4752 
4753   return parseCommaSeparatedList([&]() -> ParseResult {
4754     return parseSSADefOrUseAndType(
4755         [&](SSAUseInfo useInfo, Type type) -> ParseResult {
4756           // If this block did not have existing arguments, define a new one.
4757           if (!definingExistingArgs)
4758             return addDefinition(useInfo, owner->addArgument(type));
4759 
4760           // Otherwise, ensure that this argument has already been created.
4761           if (nextArgument >= owner->getNumArguments())
4762             return emitError("too many arguments specified in argument list");
4763 
4764           // Finally, make sure the existing argument has the correct type.
4765           auto arg = owner->getArgument(nextArgument++);
4766           if (arg.getType() != type)
4767             return emitError("argument and block argument type mismatch");
4768           return addDefinition(useInfo, arg);
4769         });
4770   });
4771 }
4772 
4773 //===----------------------------------------------------------------------===//
4774 // Top-level entity parsing.
4775 //===----------------------------------------------------------------------===//
4776 
4777 namespace {
4778 /// This parser handles entities that are only valid at the top level of the
4779 /// file.
4780 class ModuleParser : public Parser {
4781 public:
4782   explicit ModuleParser(ParserState &state) : Parser(state) {}
4783 
4784   ParseResult parseModule(ModuleOp module);
4785 
4786 private:
4787   /// Parse an attribute alias declaration.
4788   ParseResult parseAttributeAliasDef();
4789 
4790   /// Parse an attribute alias declaration.
4791   ParseResult parseTypeAliasDef();
4792 };
4793 } // end anonymous namespace
4794 
4795 /// Parses an attribute alias declaration.
4796 ///
4797 ///   attribute-alias-def ::= '#' alias-name `=` attribute-value
4798 ///
4799 ParseResult ModuleParser::parseAttributeAliasDef() {
4800   assert(getToken().is(Token::hash_identifier));
4801   StringRef aliasName = getTokenSpelling().drop_front();
4802 
4803   // Check for redefinitions.
4804   if (getState().symbols.attributeAliasDefinitions.count(aliasName) > 0)
4805     return emitError("redefinition of attribute alias id '" + aliasName + "'");
4806 
4807   // Make sure this isn't invading the dialect attribute namespace.
4808   if (aliasName.contains('.'))
4809     return emitError("attribute names with a '.' are reserved for "
4810                      "dialect-defined names");
4811 
4812   consumeToken(Token::hash_identifier);
4813 
4814   // Parse the '='.
4815   if (parseToken(Token::equal, "expected '=' in attribute alias definition"))
4816     return failure();
4817 
4818   // Parse the attribute value.
4819   Attribute attr = parseAttribute();
4820   if (!attr)
4821     return failure();
4822 
4823   getState().symbols.attributeAliasDefinitions[aliasName] = attr;
4824   return success();
4825 }
4826 
4827 /// Parse a type alias declaration.
4828 ///
4829 ///   type-alias-def ::= '!' alias-name `=` 'type' type
4830 ///
4831 ParseResult ModuleParser::parseTypeAliasDef() {
4832   assert(getToken().is(Token::exclamation_identifier));
4833   StringRef aliasName = getTokenSpelling().drop_front();
4834 
4835   // Check for redefinitions.
4836   if (getState().symbols.typeAliasDefinitions.count(aliasName) > 0)
4837     return emitError("redefinition of type alias id '" + aliasName + "'");
4838 
4839   // Make sure this isn't invading the dialect type namespace.
4840   if (aliasName.contains('.'))
4841     return emitError("type names with a '.' are reserved for "
4842                      "dialect-defined names");
4843 
4844   consumeToken(Token::exclamation_identifier);
4845 
4846   // Parse the '=' and 'type'.
4847   if (parseToken(Token::equal, "expected '=' in type alias definition") ||
4848       parseToken(Token::kw_type, "expected 'type' in type alias definition"))
4849     return failure();
4850 
4851   // Parse the type.
4852   Type aliasedType = parseType();
4853   if (!aliasedType)
4854     return failure();
4855 
4856   // Register this alias with the parser state.
4857   getState().symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType);
4858   return success();
4859 }
4860 
4861 /// This is the top-level module parser.
4862 ParseResult ModuleParser::parseModule(ModuleOp module) {
4863   OperationParser opParser(getState(), module);
4864 
4865   // Module itself is a name scope.
4866   opParser.pushSSANameScope(/*isIsolated=*/true);
4867 
4868   while (true) {
4869     switch (getToken().getKind()) {
4870     default:
4871       // Parse a top-level operation.
4872       if (opParser.parseOperation())
4873         return failure();
4874       break;
4875 
4876     // If we got to the end of the file, then we're done.
4877     case Token::eof: {
4878       if (opParser.finalize())
4879         return failure();
4880 
4881       // Handle the case where the top level module was explicitly defined.
4882       auto &bodyBlocks = module.getBodyRegion().getBlocks();
4883       auto &operations = bodyBlocks.front().getOperations();
4884       assert(!operations.empty() && "expected a valid module terminator");
4885 
4886       // Check that the first operation is a module, and it is the only
4887       // non-terminator operation.
4888       ModuleOp nested = dyn_cast<ModuleOp>(operations.front());
4889       if (nested && std::next(operations.begin(), 2) == operations.end()) {
4890         // Merge the data of the nested module operation into 'module'.
4891         module.setLoc(nested.getLoc());
4892         module.setAttrs(nested.getOperation()->getAttrList());
4893         bodyBlocks.splice(bodyBlocks.end(), nested.getBodyRegion().getBlocks());
4894 
4895         // Erase the original module body.
4896         bodyBlocks.pop_front();
4897       }
4898 
4899       return opParser.popSSANameScope();
4900     }
4901 
4902     // If we got an error token, then the lexer already emitted an error, just
4903     // stop.  Someday we could introduce error recovery if there was demand
4904     // for it.
4905     case Token::error:
4906       return failure();
4907 
4908     // Parse an attribute alias.
4909     case Token::hash_identifier:
4910       if (parseAttributeAliasDef())
4911         return failure();
4912       break;
4913 
4914     // Parse a type alias.
4915     case Token::exclamation_identifier:
4916       if (parseTypeAliasDef())
4917         return failure();
4918       break;
4919     }
4920   }
4921 }
4922 
4923 //===----------------------------------------------------------------------===//
4924 
4925 /// This parses the file specified by the indicated SourceMgr and returns an
4926 /// MLIR module if it was valid.  If not, it emits diagnostics and returns
4927 /// null.
4928 OwningModuleRef mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr,
4929                                       MLIRContext *context) {
4930   auto sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
4931 
4932   // This is the result module we are parsing into.
4933   OwningModuleRef module(ModuleOp::create(FileLineColLoc::get(
4934       sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0, context)));
4935 
4936   SymbolState aliasState;
4937   ParserState state(sourceMgr, context, aliasState);
4938   if (ModuleParser(state).parseModule(*module))
4939     return nullptr;
4940 
4941   // Make sure the parse module has no other structural problems detected by
4942   // the verifier.
4943   if (failed(verify(*module)))
4944     return nullptr;
4945 
4946   return module;
4947 }
4948 
4949 /// This parses the file specified by the indicated filename and returns an
4950 /// MLIR module if it was valid.  If not, the error message is emitted through
4951 /// the error handler registered in the context, and a null pointer is returned.
4952 OwningModuleRef mlir::parseSourceFile(StringRef filename,
4953                                       MLIRContext *context) {
4954   llvm::SourceMgr sourceMgr;
4955   return parseSourceFile(filename, sourceMgr, context);
4956 }
4957 
4958 /// This parses the file specified by the indicated filename using the provided
4959 /// SourceMgr and returns an MLIR module if it was valid.  If not, the error
4960 /// message is emitted through the error handler registered in the context, and
4961 /// a null pointer is returned.
4962 OwningModuleRef mlir::parseSourceFile(StringRef filename,
4963                                       llvm::SourceMgr &sourceMgr,
4964                                       MLIRContext *context) {
4965   if (sourceMgr.getNumBuffers() != 0) {
4966     // TODO(b/136086478): Extend to support multiple buffers.
4967     emitError(mlir::UnknownLoc::get(context),
4968               "only main buffer parsed at the moment");
4969     return nullptr;
4970   }
4971   auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename);
4972   if (std::error_code error = file_or_err.getError()) {
4973     emitError(mlir::UnknownLoc::get(context),
4974               "could not open input file " + filename);
4975     return nullptr;
4976   }
4977 
4978   // Load the MLIR module.
4979   sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc());
4980   return parseSourceFile(sourceMgr, context);
4981 }
4982 
4983 /// This parses the program string to a MLIR module if it was valid. If not,
4984 /// it emits diagnostics and returns null.
4985 OwningModuleRef mlir::parseSourceString(StringRef moduleStr,
4986                                         MLIRContext *context) {
4987   auto memBuffer = MemoryBuffer::getMemBuffer(moduleStr);
4988   if (!memBuffer)
4989     return nullptr;
4990 
4991   SourceMgr sourceMgr;
4992   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
4993   return parseSourceFile(sourceMgr, context);
4994 }
4995 
4996 /// Parses a symbol, of type 'T', and returns it if parsing was successful. If
4997 /// parsing failed, nullptr is returned. The number of bytes read from the input
4998 /// string is returned in 'numRead'.
4999 template <typename T, typename ParserFn>
5000 static T parseSymbol(StringRef inputStr, MLIRContext *context, size_t &numRead,
5001                      ParserFn &&parserFn) {
5002   SymbolState aliasState;
5003   return parseSymbol<T>(
5004       inputStr, context, aliasState,
5005       [&](Parser &parser) {
5006         SourceMgrDiagnosticHandler handler(
5007             const_cast<llvm::SourceMgr &>(parser.getSourceMgr()),
5008             parser.getContext());
5009         return parserFn(parser);
5010       },
5011       &numRead);
5012 }
5013 
5014 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context) {
5015   size_t numRead = 0;
5016   return parseAttribute(attrStr, context, numRead);
5017 }
5018 Attribute mlir::parseAttribute(StringRef attrStr, Type type) {
5019   size_t numRead = 0;
5020   return parseAttribute(attrStr, type, numRead);
5021 }
5022 
5023 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context,
5024                                size_t &numRead) {
5025   return parseSymbol<Attribute>(attrStr, context, numRead, [](Parser &parser) {
5026     return parser.parseAttribute();
5027   });
5028 }
5029 Attribute mlir::parseAttribute(StringRef attrStr, Type type, size_t &numRead) {
5030   return parseSymbol<Attribute>(
5031       attrStr, type.getContext(), numRead,
5032       [type](Parser &parser) { return parser.parseAttribute(type); });
5033 }
5034 
5035 Type mlir::parseType(StringRef typeStr, MLIRContext *context) {
5036   size_t numRead = 0;
5037   return parseType(typeStr, context, numRead);
5038 }
5039 
5040 Type mlir::parseType(StringRef typeStr, MLIRContext *context, size_t &numRead) {
5041   return parseSymbol<Type>(typeStr, context, numRead,
5042                            [](Parser &parser) { return parser.parseType(); });
5043 }
5044