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 cannot be empty. Grammar:
3072   // multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
3073   if (parseCommaSeparatedListUntil(rightToken, parseElt,
3074                                    /*allowEmptyList=*/true))
3075     return failure();
3076   // Parsed a valid affine map.
3077   if (exprs.empty())
3078     map = AffineMap::get(getContext());
3079   else
3080     map = AffineMap::get(numDimOperands, dimsAndSymbols.size() - numDimOperands,
3081                          exprs);
3082   return success();
3083 }
3084 
3085 /// Parse the range and sizes affine map definition inline.
3086 ///
3087 ///  affine-map ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
3088 ///
3089 ///  multi-dim-affine-expr ::= `(` `)`
3090 ///  multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)`
3091 AffineMap AffineParser::parseAffineMapRange(unsigned numDims,
3092                                             unsigned numSymbols) {
3093   parseToken(Token::l_paren, "expected '(' at start of affine map range");
3094 
3095   SmallVector<AffineExpr, 4> exprs;
3096   auto parseElt = [&]() -> ParseResult {
3097     auto elt = parseAffineExpr();
3098     ParseResult res = elt ? success() : failure();
3099     exprs.push_back(elt);
3100     return res;
3101   };
3102 
3103   // Parse a multi-dimensional affine expression (a comma-separated list of
3104   // 1-d affine expressions); the list cannot be empty. Grammar:
3105   // multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
3106   if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true))
3107     return AffineMap();
3108 
3109   if (exprs.empty())
3110     return AffineMap::get(getContext());
3111 
3112   // Parsed a valid affine map.
3113   return AffineMap::get(numDims, numSymbols, exprs);
3114 }
3115 
3116 /// Parse an affine constraint.
3117 ///  affine-constraint ::= affine-expr `>=` `0`
3118 ///                      | affine-expr `==` `0`
3119 ///
3120 /// isEq is set to true if the parsed constraint is an equality, false if it
3121 /// is an inequality (greater than or equal).
3122 ///
3123 AffineExpr AffineParser::parseAffineConstraint(bool *isEq) {
3124   AffineExpr expr = parseAffineExpr();
3125   if (!expr)
3126     return nullptr;
3127 
3128   if (consumeIf(Token::greater) && consumeIf(Token::equal) &&
3129       getToken().is(Token::integer)) {
3130     auto dim = getToken().getUnsignedIntegerValue();
3131     if (dim.hasValue() && dim.getValue() == 0) {
3132       consumeToken(Token::integer);
3133       *isEq = false;
3134       return expr;
3135     }
3136     return (emitError("expected '0' after '>='"), nullptr);
3137   }
3138 
3139   if (consumeIf(Token::equal) && consumeIf(Token::equal) &&
3140       getToken().is(Token::integer)) {
3141     auto dim = getToken().getUnsignedIntegerValue();
3142     if (dim.hasValue() && dim.getValue() == 0) {
3143       consumeToken(Token::integer);
3144       *isEq = true;
3145       return expr;
3146     }
3147     return (emitError("expected '0' after '=='"), nullptr);
3148   }
3149 
3150   return (emitError("expected '== 0' or '>= 0' at end of affine constraint"),
3151           nullptr);
3152 }
3153 
3154 /// Parse the constraints that are part of an integer set definition.
3155 ///  integer-set-inline
3156 ///                ::= dim-and-symbol-id-lists `:`
3157 ///                '(' affine-constraint-conjunction? ')'
3158 ///  affine-constraint-conjunction ::= affine-constraint (`,`
3159 ///                                       affine-constraint)*
3160 ///
3161 IntegerSet AffineParser::parseIntegerSetConstraints(unsigned numDims,
3162                                                     unsigned numSymbols) {
3163   if (parseToken(Token::l_paren,
3164                  "expected '(' at start of integer set constraint list"))
3165     return IntegerSet();
3166 
3167   SmallVector<AffineExpr, 4> constraints;
3168   SmallVector<bool, 4> isEqs;
3169   auto parseElt = [&]() -> ParseResult {
3170     bool isEq;
3171     auto elt = parseAffineConstraint(&isEq);
3172     ParseResult res = elt ? success() : failure();
3173     if (elt) {
3174       constraints.push_back(elt);
3175       isEqs.push_back(isEq);
3176     }
3177     return res;
3178   };
3179 
3180   // Parse a list of affine constraints (comma-separated).
3181   if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true))
3182     return IntegerSet();
3183 
3184   // If no constraints were parsed, then treat this as a degenerate 'true' case.
3185   if (constraints.empty()) {
3186     /* 0 == 0 */
3187     auto zero = getAffineConstantExpr(0, getContext());
3188     return IntegerSet::get(numDims, numSymbols, zero, true);
3189   }
3190 
3191   // Parsed a valid integer set.
3192   return IntegerSet::get(numDims, numSymbols, constraints, isEqs);
3193 }
3194 
3195 /// Parse an ambiguous reference to either and affine map or an integer set.
3196 ParseResult Parser::parseAffineMapOrIntegerSetReference(AffineMap &map,
3197                                                         IntegerSet &set) {
3198   return AffineParser(state).parseAffineMapOrIntegerSetInline(map, set);
3199 }
3200 ParseResult Parser::parseAffineMapReference(AffineMap &map) {
3201   llvm::SMLoc curLoc = getToken().getLoc();
3202   IntegerSet set;
3203   if (parseAffineMapOrIntegerSetReference(map, set))
3204     return failure();
3205   if (set)
3206     return emitError(curLoc, "expected AffineMap, but got IntegerSet");
3207   return success();
3208 }
3209 ParseResult Parser::parseIntegerSetReference(IntegerSet &set) {
3210   llvm::SMLoc curLoc = getToken().getLoc();
3211   AffineMap map;
3212   if (parseAffineMapOrIntegerSetReference(map, set))
3213     return failure();
3214   if (map)
3215     return emitError(curLoc, "expected IntegerSet, but got AffineMap");
3216   return success();
3217 }
3218 
3219 /// Parse an AffineMap of SSA ids. The callback 'parseElement' is used to
3220 /// parse SSA value uses encountered while parsing affine expressions.
3221 ParseResult
3222 Parser::parseAffineMapOfSSAIds(AffineMap &map,
3223                                function_ref<ParseResult(bool)> parseElement,
3224                                OpAsmParser::Delimiter delimiter) {
3225   return AffineParser(state, /*allowParsingSSAIds=*/true, parseElement)
3226       .parseAffineMapOfSSAIds(map, delimiter);
3227 }
3228 
3229 //===----------------------------------------------------------------------===//
3230 // OperationParser
3231 //===----------------------------------------------------------------------===//
3232 
3233 namespace {
3234 /// This class provides support for parsing operations and regions of
3235 /// operations.
3236 class OperationParser : public Parser {
3237 public:
3238   OperationParser(ParserState &state, ModuleOp moduleOp)
3239       : Parser(state), opBuilder(moduleOp.getBodyRegion()), moduleOp(moduleOp) {
3240   }
3241 
3242   ~OperationParser();
3243 
3244   /// After parsing is finished, this function must be called to see if there
3245   /// are any remaining issues.
3246   ParseResult finalize();
3247 
3248   //===--------------------------------------------------------------------===//
3249   // SSA Value Handling
3250   //===--------------------------------------------------------------------===//
3251 
3252   /// This represents a use of an SSA value in the program.  The first two
3253   /// entries in the tuple are the name and result number of a reference.  The
3254   /// third is the location of the reference, which is used in case this ends
3255   /// up being a use of an undefined value.
3256   struct SSAUseInfo {
3257     StringRef name;  // Value name, e.g. %42 or %abc
3258     unsigned number; // Number, specified with #12
3259     SMLoc loc;       // Location of first definition or use.
3260   };
3261 
3262   /// Push a new SSA name scope to the parser.
3263   void pushSSANameScope(bool isIsolated);
3264 
3265   /// Pop the last SSA name scope from the parser.
3266   ParseResult popSSANameScope();
3267 
3268   /// Register a definition of a value with the symbol table.
3269   ParseResult addDefinition(SSAUseInfo useInfo, Value value);
3270 
3271   /// Parse an optional list of SSA uses into 'results'.
3272   ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
3273 
3274   /// Parse a single SSA use into 'result'.
3275   ParseResult parseSSAUse(SSAUseInfo &result);
3276 
3277   /// Given a reference to an SSA value and its type, return a reference. This
3278   /// returns null on failure.
3279   Value resolveSSAUse(SSAUseInfo useInfo, Type type);
3280 
3281   ParseResult parseSSADefOrUseAndType(
3282       const std::function<ParseResult(SSAUseInfo, Type)> &action);
3283 
3284   ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value> &results);
3285 
3286   /// Return the location of the value identified by its name and number if it
3287   /// has been already reference.
3288   Optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) {
3289     auto &values = isolatedNameScopes.back().values;
3290     if (!values.count(name) || number >= values[name].size())
3291       return {};
3292     if (values[name][number].first)
3293       return values[name][number].second;
3294     return {};
3295   }
3296 
3297   //===--------------------------------------------------------------------===//
3298   // Operation Parsing
3299   //===--------------------------------------------------------------------===//
3300 
3301   /// Parse an operation instance.
3302   ParseResult parseOperation();
3303 
3304   /// Parse a single operation successor and its operand list.
3305   ParseResult parseSuccessorAndUseList(Block *&dest,
3306                                        SmallVectorImpl<Value> &operands);
3307 
3308   /// Parse a comma-separated list of operation successors in brackets.
3309   ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations,
3310                               SmallVectorImpl<SmallVector<Value, 4>> &operands);
3311 
3312   /// Parse an operation instance that is in the generic form.
3313   Operation *parseGenericOperation();
3314 
3315   /// Parse an operation instance that is in the generic form and insert it at
3316   /// the provided insertion point.
3317   Operation *parseGenericOperation(Block *insertBlock,
3318                                    Block::iterator insertPt);
3319 
3320   /// Parse an operation instance that is in the op-defined custom form.
3321   Operation *parseCustomOperation();
3322 
3323   //===--------------------------------------------------------------------===//
3324   // Region Parsing
3325   //===--------------------------------------------------------------------===//
3326 
3327   /// Parse a region into 'region' with the provided entry block arguments.
3328   /// 'isIsolatedNameScope' indicates if the naming scope of this region is
3329   /// isolated from those above.
3330   ParseResult parseRegion(Region &region,
3331                           ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments,
3332                           bool isIsolatedNameScope = false);
3333 
3334   /// Parse a region body into 'region'.
3335   ParseResult parseRegionBody(Region &region);
3336 
3337   //===--------------------------------------------------------------------===//
3338   // Block Parsing
3339   //===--------------------------------------------------------------------===//
3340 
3341   /// Parse a new block into 'block'.
3342   ParseResult parseBlock(Block *&block);
3343 
3344   /// Parse a list of operations into 'block'.
3345   ParseResult parseBlockBody(Block *block);
3346 
3347   /// Parse a (possibly empty) list of block arguments.
3348   ParseResult parseOptionalBlockArgList(SmallVectorImpl<BlockArgument> &results,
3349                                         Block *owner);
3350 
3351   /// Get the block with the specified name, creating it if it doesn't
3352   /// already exist.  The location specified is the point of use, which allows
3353   /// us to diagnose references to blocks that are not defined precisely.
3354   Block *getBlockNamed(StringRef name, SMLoc loc);
3355 
3356   /// Define the block with the specified name. Returns the Block* or nullptr in
3357   /// the case of redefinition.
3358   Block *defineBlockNamed(StringRef name, SMLoc loc, Block *existing);
3359 
3360 private:
3361   /// Returns the info for a block at the current scope for the given name.
3362   std::pair<Block *, SMLoc> &getBlockInfoByName(StringRef name) {
3363     return blocksByName.back()[name];
3364   }
3365 
3366   /// Insert a new forward reference to the given block.
3367   void insertForwardRef(Block *block, SMLoc loc) {
3368     forwardRef.back().try_emplace(block, loc);
3369   }
3370 
3371   /// Erase any forward reference to the given block.
3372   bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); }
3373 
3374   /// Record that a definition was added at the current scope.
3375   void recordDefinition(StringRef def);
3376 
3377   /// Get the value entry for the given SSA name.
3378   SmallVectorImpl<std::pair<Value, SMLoc>> &getSSAValueEntry(StringRef name);
3379 
3380   /// Create a forward reference placeholder value with the given location and
3381   /// result type.
3382   Value createForwardRefPlaceholder(SMLoc loc, Type type);
3383 
3384   /// Return true if this is a forward reference.
3385   bool isForwardRefPlaceholder(Value value) {
3386     return forwardRefPlaceholders.count(value);
3387   }
3388 
3389   /// This struct represents an isolated SSA name scope. This scope may contain
3390   /// other nested non-isolated scopes. These scopes are used for operations
3391   /// that are known to be isolated to allow for reusing names within their
3392   /// regions, even if those names are used above.
3393   struct IsolatedSSANameScope {
3394     /// Record that a definition was added at the current scope.
3395     void recordDefinition(StringRef def) {
3396       definitionsPerScope.back().insert(def);
3397     }
3398 
3399     /// Push a nested name scope.
3400     void pushSSANameScope() { definitionsPerScope.push_back({}); }
3401 
3402     /// Pop a nested name scope.
3403     void popSSANameScope() {
3404       for (auto &def : definitionsPerScope.pop_back_val())
3405         values.erase(def.getKey());
3406     }
3407 
3408     /// This keeps track of all of the SSA values we are tracking for each name
3409     /// scope, indexed by their name. This has one entry per result number.
3410     llvm::StringMap<SmallVector<std::pair<Value, SMLoc>, 1>> values;
3411 
3412     /// This keeps track of all of the values defined by a specific name scope.
3413     SmallVector<llvm::StringSet<>, 2> definitionsPerScope;
3414   };
3415 
3416   /// A list of isolated name scopes.
3417   SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes;
3418 
3419   /// This keeps track of the block names as well as the location of the first
3420   /// reference for each nested name scope. This is used to diagnose invalid
3421   /// block references and memorize them.
3422   SmallVector<DenseMap<StringRef, std::pair<Block *, SMLoc>>, 2> blocksByName;
3423   SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef;
3424 
3425   /// These are all of the placeholders we've made along with the location of
3426   /// their first reference, to allow checking for use of undefined values.
3427   DenseMap<Value, SMLoc> forwardRefPlaceholders;
3428 
3429   /// The builder used when creating parsed operation instances.
3430   OpBuilder opBuilder;
3431 
3432   /// The top level module operation.
3433   ModuleOp moduleOp;
3434 };
3435 } // end anonymous namespace
3436 
3437 OperationParser::~OperationParser() {
3438   for (auto &fwd : forwardRefPlaceholders) {
3439     // Drop all uses of undefined forward declared reference and destroy
3440     // defining operation.
3441     fwd.first.dropAllUses();
3442     fwd.first.getDefiningOp()->destroy();
3443   }
3444 }
3445 
3446 /// After parsing is finished, this function must be called to see if there are
3447 /// any remaining issues.
3448 ParseResult OperationParser::finalize() {
3449   // Check for any forward references that are left.  If we find any, error
3450   // out.
3451   if (!forwardRefPlaceholders.empty()) {
3452     SmallVector<std::pair<const char *, Value>, 4> errors;
3453     // Iteration over the map isn't deterministic, so sort by source location.
3454     for (auto entry : forwardRefPlaceholders)
3455       errors.push_back({entry.second.getPointer(), entry.first});
3456     llvm::array_pod_sort(errors.begin(), errors.end());
3457 
3458     for (auto entry : errors) {
3459       auto loc = SMLoc::getFromPointer(entry.first);
3460       emitError(loc, "use of undeclared SSA value name");
3461     }
3462     return failure();
3463   }
3464 
3465   return success();
3466 }
3467 
3468 //===----------------------------------------------------------------------===//
3469 // SSA Value Handling
3470 //===----------------------------------------------------------------------===//
3471 
3472 void OperationParser::pushSSANameScope(bool isIsolated) {
3473   blocksByName.push_back(DenseMap<StringRef, std::pair<Block *, SMLoc>>());
3474   forwardRef.push_back(DenseMap<Block *, SMLoc>());
3475 
3476   // Push back a new name definition scope.
3477   if (isIsolated)
3478     isolatedNameScopes.push_back({});
3479   isolatedNameScopes.back().pushSSANameScope();
3480 }
3481 
3482 ParseResult OperationParser::popSSANameScope() {
3483   auto forwardRefInCurrentScope = forwardRef.pop_back_val();
3484 
3485   // Verify that all referenced blocks were defined.
3486   if (!forwardRefInCurrentScope.empty()) {
3487     SmallVector<std::pair<const char *, Block *>, 4> errors;
3488     // Iteration over the map isn't deterministic, so sort by source location.
3489     for (auto entry : forwardRefInCurrentScope) {
3490       errors.push_back({entry.second.getPointer(), entry.first});
3491       // Add this block to the top-level region to allow for automatic cleanup.
3492       moduleOp.getOperation()->getRegion(0).push_back(entry.first);
3493     }
3494     llvm::array_pod_sort(errors.begin(), errors.end());
3495 
3496     for (auto entry : errors) {
3497       auto loc = SMLoc::getFromPointer(entry.first);
3498       emitError(loc, "reference to an undefined block");
3499     }
3500     return failure();
3501   }
3502 
3503   // Pop the next nested namescope. If there is only one internal namescope,
3504   // just pop the isolated scope.
3505   auto &currentNameScope = isolatedNameScopes.back();
3506   if (currentNameScope.definitionsPerScope.size() == 1)
3507     isolatedNameScopes.pop_back();
3508   else
3509     currentNameScope.popSSANameScope();
3510 
3511   blocksByName.pop_back();
3512   return success();
3513 }
3514 
3515 /// Register a definition of a value with the symbol table.
3516 ParseResult OperationParser::addDefinition(SSAUseInfo useInfo, Value value) {
3517   auto &entries = getSSAValueEntry(useInfo.name);
3518 
3519   // Make sure there is a slot for this value.
3520   if (entries.size() <= useInfo.number)
3521     entries.resize(useInfo.number + 1);
3522 
3523   // If we already have an entry for this, check to see if it was a definition
3524   // or a forward reference.
3525   if (auto existing = entries[useInfo.number].first) {
3526     if (!isForwardRefPlaceholder(existing)) {
3527       return emitError(useInfo.loc)
3528           .append("redefinition of SSA value '", useInfo.name, "'")
3529           .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3530           .append("previously defined here");
3531     }
3532 
3533     // If it was a forward reference, update everything that used it to use
3534     // the actual definition instead, delete the forward ref, and remove it
3535     // from our set of forward references we track.
3536     existing.replaceAllUsesWith(value);
3537     existing.getDefiningOp()->destroy();
3538     forwardRefPlaceholders.erase(existing);
3539   }
3540 
3541   /// Record this definition for the current scope.
3542   entries[useInfo.number] = {value, useInfo.loc};
3543   recordDefinition(useInfo.name);
3544   return success();
3545 }
3546 
3547 /// Parse a (possibly empty) list of SSA operands.
3548 ///
3549 ///   ssa-use-list ::= ssa-use (`,` ssa-use)*
3550 ///   ssa-use-list-opt ::= ssa-use-list?
3551 ///
3552 ParseResult
3553 OperationParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
3554   if (getToken().isNot(Token::percent_identifier))
3555     return success();
3556   return parseCommaSeparatedList([&]() -> ParseResult {
3557     SSAUseInfo result;
3558     if (parseSSAUse(result))
3559       return failure();
3560     results.push_back(result);
3561     return success();
3562   });
3563 }
3564 
3565 /// Parse a SSA operand for an operation.
3566 ///
3567 ///   ssa-use ::= ssa-id
3568 ///
3569 ParseResult OperationParser::parseSSAUse(SSAUseInfo &result) {
3570   result.name = getTokenSpelling();
3571   result.number = 0;
3572   result.loc = getToken().getLoc();
3573   if (parseToken(Token::percent_identifier, "expected SSA operand"))
3574     return failure();
3575 
3576   // If we have an attribute ID, it is a result number.
3577   if (getToken().is(Token::hash_identifier)) {
3578     if (auto value = getToken().getHashIdentifierNumber())
3579       result.number = value.getValue();
3580     else
3581       return emitError("invalid SSA value result number");
3582     consumeToken(Token::hash_identifier);
3583   }
3584 
3585   return success();
3586 }
3587 
3588 /// Given an unbound reference to an SSA value and its type, return the value
3589 /// it specifies.  This returns null on failure.
3590 Value OperationParser::resolveSSAUse(SSAUseInfo useInfo, Type type) {
3591   auto &entries = getSSAValueEntry(useInfo.name);
3592 
3593   // If we have already seen a value of this name, return it.
3594   if (useInfo.number < entries.size() && entries[useInfo.number].first) {
3595     auto result = entries[useInfo.number].first;
3596     // Check that the type matches the other uses.
3597     if (result.getType() == type)
3598       return result;
3599 
3600     emitError(useInfo.loc, "use of value '")
3601         .append(useInfo.name,
3602                 "' expects different type than prior uses: ", type, " vs ",
3603                 result.getType())
3604         .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3605         .append("prior use here");
3606     return nullptr;
3607   }
3608 
3609   // Make sure we have enough slots for this.
3610   if (entries.size() <= useInfo.number)
3611     entries.resize(useInfo.number + 1);
3612 
3613   // If the value has already been defined and this is an overly large result
3614   // number, diagnose that.
3615   if (entries[0].first && !isForwardRefPlaceholder(entries[0].first))
3616     return (emitError(useInfo.loc, "reference to invalid result number"),
3617             nullptr);
3618 
3619   // Otherwise, this is a forward reference.  Create a placeholder and remember
3620   // that we did so.
3621   auto result = createForwardRefPlaceholder(useInfo.loc, type);
3622   entries[useInfo.number].first = result;
3623   entries[useInfo.number].second = useInfo.loc;
3624   return result;
3625 }
3626 
3627 /// Parse an SSA use with an associated type.
3628 ///
3629 ///   ssa-use-and-type ::= ssa-use `:` type
3630 ParseResult OperationParser::parseSSADefOrUseAndType(
3631     const std::function<ParseResult(SSAUseInfo, Type)> &action) {
3632   SSAUseInfo useInfo;
3633   if (parseSSAUse(useInfo) ||
3634       parseToken(Token::colon, "expected ':' and type for SSA operand"))
3635     return failure();
3636 
3637   auto type = parseType();
3638   if (!type)
3639     return failure();
3640 
3641   return action(useInfo, type);
3642 }
3643 
3644 /// Parse a (possibly empty) list of SSA operands, followed by a colon, then
3645 /// followed by a type list.
3646 ///
3647 ///   ssa-use-and-type-list
3648 ///     ::= ssa-use-list ':' type-list-no-parens
3649 ///
3650 ParseResult OperationParser::parseOptionalSSAUseAndTypeList(
3651     SmallVectorImpl<Value> &results) {
3652   SmallVector<SSAUseInfo, 4> valueIDs;
3653   if (parseOptionalSSAUseList(valueIDs))
3654     return failure();
3655 
3656   // If there were no operands, then there is no colon or type lists.
3657   if (valueIDs.empty())
3658     return success();
3659 
3660   SmallVector<Type, 4> types;
3661   if (parseToken(Token::colon, "expected ':' in operand list") ||
3662       parseTypeListNoParens(types))
3663     return failure();
3664 
3665   if (valueIDs.size() != types.size())
3666     return emitError("expected ")
3667            << valueIDs.size() << " types to match operand list";
3668 
3669   results.reserve(valueIDs.size());
3670   for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
3671     if (auto value = resolveSSAUse(valueIDs[i], types[i]))
3672       results.push_back(value);
3673     else
3674       return failure();
3675   }
3676 
3677   return success();
3678 }
3679 
3680 /// Record that a definition was added at the current scope.
3681 void OperationParser::recordDefinition(StringRef def) {
3682   isolatedNameScopes.back().recordDefinition(def);
3683 }
3684 
3685 /// Get the value entry for the given SSA name.
3686 SmallVectorImpl<std::pair<Value, SMLoc>> &
3687 OperationParser::getSSAValueEntry(StringRef name) {
3688   return isolatedNameScopes.back().values[name];
3689 }
3690 
3691 /// Create and remember a new placeholder for a forward reference.
3692 Value OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) {
3693   // Forward references are always created as operations, because we just need
3694   // something with a def/use chain.
3695   //
3696   // We create these placeholders as having an empty name, which we know
3697   // cannot be created through normal user input, allowing us to distinguish
3698   // them.
3699   auto name = OperationName("placeholder", getContext());
3700   auto *op = Operation::create(
3701       getEncodedSourceLocation(loc), name, type, /*operands=*/{},
3702       /*attributes=*/llvm::None, /*successors=*/{}, /*numRegions=*/0,
3703       /*resizableOperandList=*/false);
3704   forwardRefPlaceholders[op->getResult(0)] = loc;
3705   return op->getResult(0);
3706 }
3707 
3708 //===----------------------------------------------------------------------===//
3709 // Operation Parsing
3710 //===----------------------------------------------------------------------===//
3711 
3712 /// Parse an operation.
3713 ///
3714 ///  operation         ::= op-result-list?
3715 ///                        (generic-operation | custom-operation)
3716 ///                        trailing-location?
3717 ///  generic-operation ::= string-literal `(` ssa-use-list? `)`
3718 ///                        successor-list? (`(` region-list `)`)?
3719 ///                        attribute-dict? `:` function-type
3720 ///  custom-operation  ::= bare-id custom-operation-format
3721 ///  op-result-list    ::= op-result (`,` op-result)* `=`
3722 ///  op-result         ::= ssa-id (`:` integer-literal)
3723 ///
3724 ParseResult OperationParser::parseOperation() {
3725   auto loc = getToken().getLoc();
3726   SmallVector<std::tuple<StringRef, unsigned, SMLoc>, 1> resultIDs;
3727   size_t numExpectedResults = 0;
3728   if (getToken().is(Token::percent_identifier)) {
3729     // Parse the group of result ids.
3730     auto parseNextResult = [&]() -> ParseResult {
3731       // Parse the next result id.
3732       if (!getToken().is(Token::percent_identifier))
3733         return emitError("expected valid ssa identifier");
3734 
3735       Token nameTok = getToken();
3736       consumeToken(Token::percent_identifier);
3737 
3738       // If the next token is a ':', we parse the expected result count.
3739       size_t expectedSubResults = 1;
3740       if (consumeIf(Token::colon)) {
3741         // Check that the next token is an integer.
3742         if (!getToken().is(Token::integer))
3743           return emitError("expected integer number of results");
3744 
3745         // Check that number of results is > 0.
3746         auto val = getToken().getUInt64IntegerValue();
3747         if (!val.hasValue() || val.getValue() < 1)
3748           return emitError("expected named operation to have atleast 1 result");
3749         consumeToken(Token::integer);
3750         expectedSubResults = *val;
3751       }
3752 
3753       resultIDs.emplace_back(nameTok.getSpelling(), expectedSubResults,
3754                              nameTok.getLoc());
3755       numExpectedResults += expectedSubResults;
3756       return success();
3757     };
3758     if (parseCommaSeparatedList(parseNextResult))
3759       return failure();
3760 
3761     if (parseToken(Token::equal, "expected '=' after SSA name"))
3762       return failure();
3763   }
3764 
3765   Operation *op;
3766   if (getToken().is(Token::bare_identifier) || getToken().isKeyword())
3767     op = parseCustomOperation();
3768   else if (getToken().is(Token::string))
3769     op = parseGenericOperation();
3770   else
3771     return emitError("expected operation name in quotes");
3772 
3773   // If parsing of the basic operation failed, then this whole thing fails.
3774   if (!op)
3775     return failure();
3776 
3777   // If the operation had a name, register it.
3778   if (!resultIDs.empty()) {
3779     if (op->getNumResults() == 0)
3780       return emitError(loc, "cannot name an operation with no results");
3781     if (numExpectedResults != op->getNumResults())
3782       return emitError(loc, "operation defines ")
3783              << op->getNumResults() << " results but was provided "
3784              << numExpectedResults << " to bind";
3785 
3786     // Add definitions for each of the result groups.
3787     unsigned opResI = 0;
3788     for (std::tuple<StringRef, unsigned, SMLoc> &resIt : resultIDs) {
3789       for (unsigned subRes : llvm::seq<unsigned>(0, std::get<1>(resIt))) {
3790         if (addDefinition({std::get<0>(resIt), subRes, std::get<2>(resIt)},
3791                           op->getResult(opResI++)))
3792           return failure();
3793       }
3794     }
3795   }
3796 
3797   return success();
3798 }
3799 
3800 /// Parse a single operation successor and its operand list.
3801 ///
3802 ///   successor ::= block-id branch-use-list?
3803 ///   branch-use-list ::= `(` ssa-use-list ':' type-list-no-parens `)`
3804 ///
3805 ParseResult
3806 OperationParser::parseSuccessorAndUseList(Block *&dest,
3807                                           SmallVectorImpl<Value> &operands) {
3808   // Verify branch is identifier and get the matching block.
3809   if (!getToken().is(Token::caret_identifier))
3810     return emitError("expected block name");
3811   dest = getBlockNamed(getTokenSpelling(), getToken().getLoc());
3812   consumeToken();
3813 
3814   // Handle optional arguments.
3815   if (consumeIf(Token::l_paren) &&
3816       (parseOptionalSSAUseAndTypeList(operands) ||
3817        parseToken(Token::r_paren, "expected ')' to close argument list"))) {
3818     return failure();
3819   }
3820 
3821   return success();
3822 }
3823 
3824 /// Parse a comma-separated list of operation successors in brackets.
3825 ///
3826 ///   successor-list ::= `[` successor (`,` successor )* `]`
3827 ///
3828 ParseResult OperationParser::parseSuccessors(
3829     SmallVectorImpl<Block *> &destinations,
3830     SmallVectorImpl<SmallVector<Value, 4>> &operands) {
3831   if (parseToken(Token::l_square, "expected '['"))
3832     return failure();
3833 
3834   auto parseElt = [this, &destinations, &operands]() {
3835     Block *dest;
3836     SmallVector<Value, 4> destOperands;
3837     auto res = parseSuccessorAndUseList(dest, destOperands);
3838     destinations.push_back(dest);
3839     operands.push_back(destOperands);
3840     return res;
3841   };
3842   return parseCommaSeparatedListUntil(Token::r_square, parseElt,
3843                                       /*allowEmptyList=*/false);
3844 }
3845 
3846 namespace {
3847 // RAII-style guard for cleaning up the regions in the operation state before
3848 // deleting them.  Within the parser, regions may get deleted if parsing failed,
3849 // and other errors may be present, in particular undominated uses.  This makes
3850 // sure such uses are deleted.
3851 struct CleanupOpStateRegions {
3852   ~CleanupOpStateRegions() {
3853     SmallVector<Region *, 4> regionsToClean;
3854     regionsToClean.reserve(state.regions.size());
3855     for (auto &region : state.regions)
3856       if (region)
3857         for (auto &block : *region)
3858           block.dropAllDefinedValueUses();
3859   }
3860   OperationState &state;
3861 };
3862 } // namespace
3863 
3864 Operation *OperationParser::parseGenericOperation() {
3865   // Get location information for the operation.
3866   auto srcLocation = getEncodedSourceLocation(getToken().getLoc());
3867 
3868   auto name = getToken().getStringValue();
3869   if (name.empty())
3870     return (emitError("empty operation name is invalid"), nullptr);
3871   if (name.find('\0') != StringRef::npos)
3872     return (emitError("null character not allowed in operation name"), nullptr);
3873 
3874   consumeToken(Token::string);
3875 
3876   OperationState result(srcLocation, name);
3877 
3878   // Generic operations have a resizable operation list.
3879   result.setOperandListToResizable();
3880 
3881   // Parse the operand list.
3882   SmallVector<SSAUseInfo, 8> operandInfos;
3883 
3884   if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
3885       parseOptionalSSAUseList(operandInfos) ||
3886       parseToken(Token::r_paren, "expected ')' to end operand list")) {
3887     return nullptr;
3888   }
3889 
3890   // Parse the successor list but don't add successors to the result yet to
3891   // avoid messing up with the argument order.
3892   SmallVector<Block *, 2> successors;
3893   SmallVector<SmallVector<Value, 4>, 2> successorOperands;
3894   if (getToken().is(Token::l_square)) {
3895     // Check if the operation is a known terminator.
3896     const AbstractOperation *abstractOp = result.name.getAbstractOperation();
3897     if (abstractOp && !abstractOp->hasProperty(OperationProperty::Terminator))
3898       return emitError("successors in non-terminator"), nullptr;
3899     if (parseSuccessors(successors, successorOperands))
3900       return nullptr;
3901   }
3902 
3903   // Parse the region list.
3904   CleanupOpStateRegions guard{result};
3905   if (consumeIf(Token::l_paren)) {
3906     do {
3907       // Create temporary regions with the top level region as parent.
3908       result.regions.emplace_back(new Region(moduleOp));
3909       if (parseRegion(*result.regions.back(), /*entryArguments=*/{}))
3910         return nullptr;
3911     } while (consumeIf(Token::comma));
3912     if (parseToken(Token::r_paren, "expected ')' to end region list"))
3913       return nullptr;
3914   }
3915 
3916   if (getToken().is(Token::l_brace)) {
3917     if (parseAttributeDict(result.attributes))
3918       return nullptr;
3919   }
3920 
3921   if (parseToken(Token::colon, "expected ':' followed by operation type"))
3922     return nullptr;
3923 
3924   auto typeLoc = getToken().getLoc();
3925   auto type = parseType();
3926   if (!type)
3927     return nullptr;
3928   auto fnType = type.dyn_cast<FunctionType>();
3929   if (!fnType)
3930     return (emitError(typeLoc, "expected function type"), nullptr);
3931 
3932   result.addTypes(fnType.getResults());
3933 
3934   // Check that we have the right number of types for the operands.
3935   auto operandTypes = fnType.getInputs();
3936   if (operandTypes.size() != operandInfos.size()) {
3937     auto plural = "s"[operandInfos.size() == 1];
3938     return (emitError(typeLoc, "expected ")
3939                 << operandInfos.size() << " operand type" << plural
3940                 << " but had " << operandTypes.size(),
3941             nullptr);
3942   }
3943 
3944   // Resolve all of the operands.
3945   for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
3946     result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
3947     if (!result.operands.back())
3948       return nullptr;
3949   }
3950 
3951   // Add the successors, and their operands after the proper operands.
3952   for (auto succ : llvm::zip(successors, successorOperands)) {
3953     Block *successor = std::get<0>(succ);
3954     const SmallVector<Value, 4> &operands = std::get<1>(succ);
3955     result.addSuccessor(successor, operands);
3956   }
3957 
3958   // Parse a location if one is present.
3959   if (parseOptionalTrailingLocation(result.location))
3960     return nullptr;
3961 
3962   return opBuilder.createOperation(result);
3963 }
3964 
3965 Operation *OperationParser::parseGenericOperation(Block *insertBlock,
3966                                                   Block::iterator insertPt) {
3967   OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder);
3968   opBuilder.setInsertionPoint(insertBlock, insertPt);
3969   return parseGenericOperation();
3970 }
3971 
3972 namespace {
3973 class CustomOpAsmParser : public OpAsmParser {
3974 public:
3975   CustomOpAsmParser(SMLoc nameLoc, const AbstractOperation *opDefinition,
3976                     OperationParser &parser)
3977       : nameLoc(nameLoc), opDefinition(opDefinition), parser(parser) {}
3978 
3979   /// Parse an instance of the operation described by 'opDefinition' into the
3980   /// provided operation state.
3981   ParseResult parseOperation(OperationState &opState) {
3982     if (opDefinition->parseAssembly(*this, opState))
3983       return failure();
3984     return success();
3985   }
3986 
3987   Operation *parseGenericOperation(Block *insertBlock,
3988                                    Block::iterator insertPt) final {
3989     return parser.parseGenericOperation(insertBlock, insertPt);
3990   }
3991 
3992   //===--------------------------------------------------------------------===//
3993   // Utilities
3994   //===--------------------------------------------------------------------===//
3995 
3996   /// Return if any errors were emitted during parsing.
3997   bool didEmitError() const { return emittedError; }
3998 
3999   /// Emit a diagnostic at the specified location and return failure.
4000   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
4001     emittedError = true;
4002     return parser.emitError(loc, "custom op '" + opDefinition->name + "' " +
4003                                      message);
4004   }
4005 
4006   llvm::SMLoc getCurrentLocation() override {
4007     return parser.getToken().getLoc();
4008   }
4009 
4010   Builder &getBuilder() const override { return parser.builder; }
4011 
4012   llvm::SMLoc getNameLoc() const override { return nameLoc; }
4013 
4014   //===--------------------------------------------------------------------===//
4015   // Token Parsing
4016   //===--------------------------------------------------------------------===//
4017 
4018   /// Parse a `->` token.
4019   ParseResult parseArrow() override {
4020     return parser.parseToken(Token::arrow, "expected '->'");
4021   }
4022 
4023   /// Parses a `->` if present.
4024   ParseResult parseOptionalArrow() override {
4025     return success(parser.consumeIf(Token::arrow));
4026   }
4027 
4028   /// Parse a `:` token.
4029   ParseResult parseColon() override {
4030     return parser.parseToken(Token::colon, "expected ':'");
4031   }
4032 
4033   /// Parse a `:` token if present.
4034   ParseResult parseOptionalColon() override {
4035     return success(parser.consumeIf(Token::colon));
4036   }
4037 
4038   /// Parse a `,` token.
4039   ParseResult parseComma() override {
4040     return parser.parseToken(Token::comma, "expected ','");
4041   }
4042 
4043   /// Parse a `,` token if present.
4044   ParseResult parseOptionalComma() override {
4045     return success(parser.consumeIf(Token::comma));
4046   }
4047 
4048   /// Parses a `...` if present.
4049   ParseResult parseOptionalEllipsis() override {
4050     return success(parser.consumeIf(Token::ellipsis));
4051   }
4052 
4053   /// Parse a `=` token.
4054   ParseResult parseEqual() override {
4055     return parser.parseToken(Token::equal, "expected '='");
4056   }
4057 
4058   /// Parse a '<' token.
4059   ParseResult parseLess() override {
4060     return parser.parseToken(Token::less, "expected '<'");
4061   }
4062 
4063   /// Parse a '>' token.
4064   ParseResult parseGreater() override {
4065     return parser.parseToken(Token::greater, "expected '>'");
4066   }
4067 
4068   /// Parse a `(` token.
4069   ParseResult parseLParen() override {
4070     return parser.parseToken(Token::l_paren, "expected '('");
4071   }
4072 
4073   /// Parses a '(' if present.
4074   ParseResult parseOptionalLParen() override {
4075     return success(parser.consumeIf(Token::l_paren));
4076   }
4077 
4078   /// Parse a `)` token.
4079   ParseResult parseRParen() override {
4080     return parser.parseToken(Token::r_paren, "expected ')'");
4081   }
4082 
4083   /// Parses a ')' if present.
4084   ParseResult parseOptionalRParen() override {
4085     return success(parser.consumeIf(Token::r_paren));
4086   }
4087 
4088   /// Parse a `[` token.
4089   ParseResult parseLSquare() override {
4090     return parser.parseToken(Token::l_square, "expected '['");
4091   }
4092 
4093   /// Parses a '[' if present.
4094   ParseResult parseOptionalLSquare() override {
4095     return success(parser.consumeIf(Token::l_square));
4096   }
4097 
4098   /// Parse a `]` token.
4099   ParseResult parseRSquare() override {
4100     return parser.parseToken(Token::r_square, "expected ']'");
4101   }
4102 
4103   /// Parses a ']' if present.
4104   ParseResult parseOptionalRSquare() override {
4105     return success(parser.consumeIf(Token::r_square));
4106   }
4107 
4108   //===--------------------------------------------------------------------===//
4109   // Attribute Parsing
4110   //===--------------------------------------------------------------------===//
4111 
4112   /// Parse an arbitrary attribute of a given type and return it in result. This
4113   /// also adds the attribute to the specified attribute list with the specified
4114   /// name.
4115   ParseResult parseAttribute(Attribute &result, Type type, StringRef attrName,
4116                              SmallVectorImpl<NamedAttribute> &attrs) override {
4117     result = parser.parseAttribute(type);
4118     if (!result)
4119       return failure();
4120 
4121     attrs.push_back(parser.builder.getNamedAttr(attrName, result));
4122     return success();
4123   }
4124 
4125   /// Parse a named dictionary into 'result' if it is present.
4126   ParseResult
4127   parseOptionalAttrDict(SmallVectorImpl<NamedAttribute> &result) override {
4128     if (parser.getToken().isNot(Token::l_brace))
4129       return success();
4130     return parser.parseAttributeDict(result);
4131   }
4132 
4133   /// Parse a named dictionary into 'result' if the `attributes` keyword is
4134   /// present.
4135   ParseResult parseOptionalAttrDictWithKeyword(
4136       SmallVectorImpl<NamedAttribute> &result) override {
4137     if (failed(parseOptionalKeyword("attributes")))
4138       return success();
4139     return parser.parseAttributeDict(result);
4140   }
4141 
4142   /// Parse an affine map instance into 'map'.
4143   ParseResult parseAffineMap(AffineMap &map) override {
4144     return parser.parseAffineMapReference(map);
4145   }
4146 
4147   /// Parse an integer set instance into 'set'.
4148   ParseResult printIntegerSet(IntegerSet &set) override {
4149     return parser.parseIntegerSetReference(set);
4150   }
4151 
4152   //===--------------------------------------------------------------------===//
4153   // Identifier Parsing
4154   //===--------------------------------------------------------------------===//
4155 
4156   /// Returns if the current token corresponds to a keyword.
4157   bool isCurrentTokenAKeyword() const {
4158     return parser.getToken().is(Token::bare_identifier) ||
4159            parser.getToken().isKeyword();
4160   }
4161 
4162   /// Parse the given keyword if present.
4163   ParseResult parseOptionalKeyword(StringRef keyword) override {
4164     // Check that the current token has the same spelling.
4165     if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword)
4166       return failure();
4167     parser.consumeToken();
4168     return success();
4169   }
4170 
4171   /// Parse a keyword, if present, into 'keyword'.
4172   ParseResult parseOptionalKeyword(StringRef *keyword) override {
4173     // Check that the current token is a keyword.
4174     if (!isCurrentTokenAKeyword())
4175       return failure();
4176 
4177     *keyword = parser.getTokenSpelling();
4178     parser.consumeToken();
4179     return success();
4180   }
4181 
4182   /// Parse an optional @-identifier and store it (without the '@' symbol) in a
4183   /// string attribute named 'attrName'.
4184   ParseResult
4185   parseOptionalSymbolName(StringAttr &result, StringRef attrName,
4186                           SmallVectorImpl<NamedAttribute> &attrs) override {
4187     Token atToken = parser.getToken();
4188     if (atToken.isNot(Token::at_identifier))
4189       return failure();
4190 
4191     result = getBuilder().getStringAttr(extractSymbolReference(atToken));
4192     attrs.push_back(getBuilder().getNamedAttr(attrName, result));
4193     parser.consumeToken();
4194     return success();
4195   }
4196 
4197   //===--------------------------------------------------------------------===//
4198   // Operand Parsing
4199   //===--------------------------------------------------------------------===//
4200 
4201   /// Parse a single operand.
4202   ParseResult parseOperand(OperandType &result) override {
4203     OperationParser::SSAUseInfo useInfo;
4204     if (parser.parseSSAUse(useInfo))
4205       return failure();
4206 
4207     result = {useInfo.loc, useInfo.name, useInfo.number};
4208     return success();
4209   }
4210 
4211   /// Parse zero or more SSA comma-separated operand references with a specified
4212   /// surrounding delimiter, and an optional required operand count.
4213   ParseResult parseOperandList(SmallVectorImpl<OperandType> &result,
4214                                int requiredOperandCount = -1,
4215                                Delimiter delimiter = Delimiter::None) override {
4216     return parseOperandOrRegionArgList(result, /*isOperandList=*/true,
4217                                        requiredOperandCount, delimiter);
4218   }
4219 
4220   /// Parse zero or more SSA comma-separated operand or region arguments with
4221   ///  optional surrounding delimiter and required operand count.
4222   ParseResult
4223   parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result,
4224                               bool isOperandList, int requiredOperandCount = -1,
4225                               Delimiter delimiter = Delimiter::None) {
4226     auto startLoc = parser.getToken().getLoc();
4227 
4228     // Handle delimiters.
4229     switch (delimiter) {
4230     case Delimiter::None:
4231       // Don't check for the absence of a delimiter if the number of operands
4232       // is unknown (and hence the operand list could be empty).
4233       if (requiredOperandCount == -1)
4234         break;
4235       // Token already matches an identifier and so can't be a delimiter.
4236       if (parser.getToken().is(Token::percent_identifier))
4237         break;
4238       // Test against known delimiters.
4239       if (parser.getToken().is(Token::l_paren) ||
4240           parser.getToken().is(Token::l_square))
4241         return emitError(startLoc, "unexpected delimiter");
4242       return emitError(startLoc, "invalid operand");
4243     case Delimiter::OptionalParen:
4244       if (parser.getToken().isNot(Token::l_paren))
4245         return success();
4246       LLVM_FALLTHROUGH;
4247     case Delimiter::Paren:
4248       if (parser.parseToken(Token::l_paren, "expected '(' in operand list"))
4249         return failure();
4250       break;
4251     case Delimiter::OptionalSquare:
4252       if (parser.getToken().isNot(Token::l_square))
4253         return success();
4254       LLVM_FALLTHROUGH;
4255     case Delimiter::Square:
4256       if (parser.parseToken(Token::l_square, "expected '[' in operand list"))
4257         return failure();
4258       break;
4259     }
4260 
4261     // Check for zero operands.
4262     if (parser.getToken().is(Token::percent_identifier)) {
4263       do {
4264         OperandType operandOrArg;
4265         if (isOperandList ? parseOperand(operandOrArg)
4266                           : parseRegionArgument(operandOrArg))
4267           return failure();
4268         result.push_back(operandOrArg);
4269       } while (parser.consumeIf(Token::comma));
4270     }
4271 
4272     // Handle delimiters.   If we reach here, the optional delimiters were
4273     // present, so we need to parse their closing one.
4274     switch (delimiter) {
4275     case Delimiter::None:
4276       break;
4277     case Delimiter::OptionalParen:
4278     case Delimiter::Paren:
4279       if (parser.parseToken(Token::r_paren, "expected ')' in operand list"))
4280         return failure();
4281       break;
4282     case Delimiter::OptionalSquare:
4283     case Delimiter::Square:
4284       if (parser.parseToken(Token::r_square, "expected ']' in operand list"))
4285         return failure();
4286       break;
4287     }
4288 
4289     if (requiredOperandCount != -1 &&
4290         result.size() != static_cast<size_t>(requiredOperandCount))
4291       return emitError(startLoc, "expected ")
4292              << requiredOperandCount << " operands";
4293     return success();
4294   }
4295 
4296   /// Parse zero or more trailing SSA comma-separated trailing operand
4297   /// references with a specified surrounding delimiter, and an optional
4298   /// required operand count. A leading comma is expected before the operands.
4299   ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result,
4300                                        int requiredOperandCount,
4301                                        Delimiter delimiter) override {
4302     if (parser.getToken().is(Token::comma)) {
4303       parseComma();
4304       return parseOperandList(result, requiredOperandCount, delimiter);
4305     }
4306     if (requiredOperandCount != -1)
4307       return emitError(parser.getToken().getLoc(), "expected ")
4308              << requiredOperandCount << " operands";
4309     return success();
4310   }
4311 
4312   /// Resolve an operand to an SSA value, emitting an error on failure.
4313   ParseResult resolveOperand(const OperandType &operand, Type type,
4314                              SmallVectorImpl<Value> &result) override {
4315     OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
4316                                                operand.location};
4317     if (auto value = parser.resolveSSAUse(operandInfo, type)) {
4318       result.push_back(value);
4319       return success();
4320     }
4321     return failure();
4322   }
4323 
4324   /// Parse an AffineMap of SSA ids.
4325   ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands,
4326                                      Attribute &mapAttr, StringRef attrName,
4327                                      SmallVectorImpl<NamedAttribute> &attrs,
4328                                      Delimiter delimiter) override {
4329     SmallVector<OperandType, 2> dimOperands;
4330     SmallVector<OperandType, 1> symOperands;
4331 
4332     auto parseElement = [&](bool isSymbol) -> ParseResult {
4333       OperandType operand;
4334       if (parseOperand(operand))
4335         return failure();
4336       if (isSymbol)
4337         symOperands.push_back(operand);
4338       else
4339         dimOperands.push_back(operand);
4340       return success();
4341     };
4342 
4343     AffineMap map;
4344     if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter))
4345       return failure();
4346     // Add AffineMap attribute.
4347     if (map) {
4348       mapAttr = AffineMapAttr::get(map);
4349       attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr));
4350     }
4351 
4352     // Add dim operands before symbol operands in 'operands'.
4353     operands.assign(dimOperands.begin(), dimOperands.end());
4354     operands.append(symOperands.begin(), symOperands.end());
4355     return success();
4356   }
4357 
4358   //===--------------------------------------------------------------------===//
4359   // Region Parsing
4360   //===--------------------------------------------------------------------===//
4361 
4362   /// Parse a region that takes `arguments` of `argTypes` types.  This
4363   /// effectively defines the SSA values of `arguments` and assigns their type.
4364   ParseResult parseRegion(Region &region, ArrayRef<OperandType> arguments,
4365                           ArrayRef<Type> argTypes,
4366                           bool enableNameShadowing) override {
4367     assert(arguments.size() == argTypes.size() &&
4368            "mismatching number of arguments and types");
4369 
4370     SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2>
4371         regionArguments;
4372     for (auto pair : llvm::zip(arguments, argTypes)) {
4373       const OperandType &operand = std::get<0>(pair);
4374       Type type = std::get<1>(pair);
4375       OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
4376                                                  operand.location};
4377       regionArguments.emplace_back(operandInfo, type);
4378     }
4379 
4380     // Try to parse the region.
4381     assert((!enableNameShadowing ||
4382             opDefinition->hasProperty(OperationProperty::IsolatedFromAbove)) &&
4383            "name shadowing is only allowed on isolated regions");
4384     if (parser.parseRegion(region, regionArguments, enableNameShadowing))
4385       return failure();
4386     return success();
4387   }
4388 
4389   /// Parses a region if present.
4390   ParseResult parseOptionalRegion(Region &region,
4391                                   ArrayRef<OperandType> arguments,
4392                                   ArrayRef<Type> argTypes,
4393                                   bool enableNameShadowing) override {
4394     if (parser.getToken().isNot(Token::l_brace))
4395       return success();
4396     return parseRegion(region, arguments, argTypes, enableNameShadowing);
4397   }
4398 
4399   /// Parse a region argument. The type of the argument will be resolved later
4400   /// by a call to `parseRegion`.
4401   ParseResult parseRegionArgument(OperandType &argument) override {
4402     return parseOperand(argument);
4403   }
4404 
4405   /// Parse a region argument if present.
4406   ParseResult parseOptionalRegionArgument(OperandType &argument) override {
4407     if (parser.getToken().isNot(Token::percent_identifier))
4408       return success();
4409     return parseRegionArgument(argument);
4410   }
4411 
4412   ParseResult
4413   parseRegionArgumentList(SmallVectorImpl<OperandType> &result,
4414                           int requiredOperandCount = -1,
4415                           Delimiter delimiter = Delimiter::None) override {
4416     return parseOperandOrRegionArgList(result, /*isOperandList=*/false,
4417                                        requiredOperandCount, delimiter);
4418   }
4419 
4420   //===--------------------------------------------------------------------===//
4421   // Successor Parsing
4422   //===--------------------------------------------------------------------===//
4423 
4424   /// Parse a single operation successor and its operand list.
4425   ParseResult
4426   parseSuccessorAndUseList(Block *&dest,
4427                            SmallVectorImpl<Value> &operands) override {
4428     return parser.parseSuccessorAndUseList(dest, operands);
4429   }
4430 
4431   /// Parse an optional operation successor and its operand list.
4432   OptionalParseResult
4433   parseOptionalSuccessorAndUseList(Block *&dest,
4434                                    SmallVectorImpl<Value> &operands) override {
4435     if (parser.getToken().isNot(Token::caret_identifier))
4436       return llvm::None;
4437     return parseSuccessorAndUseList(dest, operands);
4438   }
4439 
4440   //===--------------------------------------------------------------------===//
4441   // Type Parsing
4442   //===--------------------------------------------------------------------===//
4443 
4444   /// Parse a type.
4445   ParseResult parseType(Type &result) override {
4446     return failure(!(result = parser.parseType()));
4447   }
4448 
4449   /// Parse an arrow followed by a type list.
4450   ParseResult parseArrowTypeList(SmallVectorImpl<Type> &result) override {
4451     if (parseArrow() || parser.parseFunctionResultTypes(result))
4452       return failure();
4453     return success();
4454   }
4455 
4456   /// Parse an optional arrow followed by a type list.
4457   ParseResult
4458   parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override {
4459     if (!parser.consumeIf(Token::arrow))
4460       return success();
4461     return parser.parseFunctionResultTypes(result);
4462   }
4463 
4464   /// Parse a colon followed by a type.
4465   ParseResult parseColonType(Type &result) override {
4466     return failure(parser.parseToken(Token::colon, "expected ':'") ||
4467                    !(result = parser.parseType()));
4468   }
4469 
4470   /// Parse a colon followed by a type list, which must have at least one type.
4471   ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override {
4472     if (parser.parseToken(Token::colon, "expected ':'"))
4473       return failure();
4474     return parser.parseTypeListNoParens(result);
4475   }
4476 
4477   /// Parse an optional colon followed by a type list, which if present must
4478   /// have at least one type.
4479   ParseResult
4480   parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override {
4481     if (!parser.consumeIf(Token::colon))
4482       return success();
4483     return parser.parseTypeListNoParens(result);
4484   }
4485 
4486   /// Parse a list of assignments of the form
4487   /// (%x1 = %y1 : type1, %x2 = %y2 : type2, ...).
4488   /// The list must contain at least one entry
4489   ParseResult parseAssignmentList(SmallVectorImpl<OperandType> &lhs,
4490                                   SmallVectorImpl<OperandType> &rhs) override {
4491     auto parseElt = [&]() -> ParseResult {
4492       OperandType regionArg, operand;
4493       if (parseRegionArgument(regionArg) || parseEqual() ||
4494           parseOperand(operand))
4495         return failure();
4496       lhs.push_back(regionArg);
4497       rhs.push_back(operand);
4498       return success();
4499     };
4500     if (parseLParen())
4501       return failure();
4502     return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
4503   }
4504 
4505 private:
4506   /// The source location of the operation name.
4507   SMLoc nameLoc;
4508 
4509   /// The abstract information of the operation.
4510   const AbstractOperation *opDefinition;
4511 
4512   /// The main operation parser.
4513   OperationParser &parser;
4514 
4515   /// A flag that indicates if any errors were emitted during parsing.
4516   bool emittedError = false;
4517 };
4518 } // end anonymous namespace.
4519 
4520 Operation *OperationParser::parseCustomOperation() {
4521   auto opLoc = getToken().getLoc();
4522   auto opName = getTokenSpelling();
4523 
4524   auto *opDefinition = AbstractOperation::lookup(opName, getContext());
4525   if (!opDefinition && !opName.contains('.')) {
4526     // If the operation name has no namespace prefix we treat it as a standard
4527     // operation and prefix it with "std".
4528     // TODO: Would it be better to just build a mapping of the registered
4529     // operations in the standard dialect?
4530     opDefinition =
4531         AbstractOperation::lookup(Twine("std." + opName).str(), getContext());
4532   }
4533 
4534   if (!opDefinition) {
4535     emitError(opLoc) << "custom op '" << opName << "' is unknown";
4536     return nullptr;
4537   }
4538 
4539   consumeToken();
4540 
4541   // If the custom op parser crashes, produce some indication to help
4542   // debugging.
4543   std::string opNameStr = opName.str();
4544   llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'",
4545                                    opNameStr.c_str());
4546 
4547   // Get location information for the operation.
4548   auto srcLocation = getEncodedSourceLocation(opLoc);
4549 
4550   // Have the op implementation take a crack and parsing this.
4551   OperationState opState(srcLocation, opDefinition->name);
4552   CleanupOpStateRegions guard{opState};
4553   CustomOpAsmParser opAsmParser(opLoc, opDefinition, *this);
4554   if (opAsmParser.parseOperation(opState))
4555     return nullptr;
4556 
4557   // If it emitted an error, we failed.
4558   if (opAsmParser.didEmitError())
4559     return nullptr;
4560 
4561   // Parse a location if one is present.
4562   if (parseOptionalTrailingLocation(opState.location))
4563     return nullptr;
4564 
4565   // Otherwise, we succeeded.  Use the state it parsed as our op information.
4566   return opBuilder.createOperation(opState);
4567 }
4568 
4569 //===----------------------------------------------------------------------===//
4570 // Region Parsing
4571 //===----------------------------------------------------------------------===//
4572 
4573 /// Region.
4574 ///
4575 ///   region ::= '{' region-body
4576 ///
4577 ParseResult OperationParser::parseRegion(
4578     Region &region,
4579     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
4580     bool isIsolatedNameScope) {
4581   // Parse the '{'.
4582   if (parseToken(Token::l_brace, "expected '{' to begin a region"))
4583     return failure();
4584 
4585   // Check for an empty region.
4586   if (entryArguments.empty() && consumeIf(Token::r_brace))
4587     return success();
4588   auto currentPt = opBuilder.saveInsertionPoint();
4589 
4590   // Push a new named value scope.
4591   pushSSANameScope(isIsolatedNameScope);
4592 
4593   // Parse the first block directly to allow for it to be unnamed.
4594   Block *block = new Block();
4595 
4596   // Add arguments to the entry block.
4597   if (!entryArguments.empty()) {
4598     for (auto &placeholderArgPair : entryArguments) {
4599       auto &argInfo = placeholderArgPair.first;
4600       // Ensure that the argument was not already defined.
4601       if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) {
4602         return emitError(argInfo.loc, "region entry argument '" + argInfo.name +
4603                                           "' is already in use")
4604                    .attachNote(getEncodedSourceLocation(*defLoc))
4605                << "previously referenced here";
4606       }
4607       if (addDefinition(placeholderArgPair.first,
4608                         block->addArgument(placeholderArgPair.second))) {
4609         delete block;
4610         return failure();
4611       }
4612     }
4613 
4614     // If we had named arguments, then don't allow a block name.
4615     if (getToken().is(Token::caret_identifier))
4616       return emitError("invalid block name in region with named arguments");
4617   }
4618 
4619   if (parseBlock(block)) {
4620     delete block;
4621     return failure();
4622   }
4623 
4624   // Verify that no other arguments were parsed.
4625   if (!entryArguments.empty() &&
4626       block->getNumArguments() > entryArguments.size()) {
4627     delete block;
4628     return emitError("entry block arguments were already defined");
4629   }
4630 
4631   // Parse the rest of the region.
4632   region.push_back(block);
4633   if (parseRegionBody(region))
4634     return failure();
4635 
4636   // Pop the SSA value scope for this region.
4637   if (popSSANameScope())
4638     return failure();
4639 
4640   // Reset the original insertion point.
4641   opBuilder.restoreInsertionPoint(currentPt);
4642   return success();
4643 }
4644 
4645 /// Region.
4646 ///
4647 ///   region-body ::= block* '}'
4648 ///
4649 ParseResult OperationParser::parseRegionBody(Region &region) {
4650   // Parse the list of blocks.
4651   while (!consumeIf(Token::r_brace)) {
4652     Block *newBlock = nullptr;
4653     if (parseBlock(newBlock))
4654       return failure();
4655     region.push_back(newBlock);
4656   }
4657   return success();
4658 }
4659 
4660 //===----------------------------------------------------------------------===//
4661 // Block Parsing
4662 //===----------------------------------------------------------------------===//
4663 
4664 /// Block declaration.
4665 ///
4666 ///   block ::= block-label? operation*
4667 ///   block-label    ::= block-id block-arg-list? `:`
4668 ///   block-id       ::= caret-id
4669 ///   block-arg-list ::= `(` ssa-id-and-type-list? `)`
4670 ///
4671 ParseResult OperationParser::parseBlock(Block *&block) {
4672   // The first block of a region may already exist, if it does the caret
4673   // identifier is optional.
4674   if (block && getToken().isNot(Token::caret_identifier))
4675     return parseBlockBody(block);
4676 
4677   SMLoc nameLoc = getToken().getLoc();
4678   auto name = getTokenSpelling();
4679   if (parseToken(Token::caret_identifier, "expected block name"))
4680     return failure();
4681 
4682   block = defineBlockNamed(name, nameLoc, block);
4683 
4684   // Fail if the block was already defined.
4685   if (!block)
4686     return emitError(nameLoc, "redefinition of block '") << name << "'";
4687 
4688   // If an argument list is present, parse it.
4689   if (consumeIf(Token::l_paren)) {
4690     SmallVector<BlockArgument, 8> bbArgs;
4691     if (parseOptionalBlockArgList(bbArgs, block) ||
4692         parseToken(Token::r_paren, "expected ')' to end argument list"))
4693       return failure();
4694   }
4695 
4696   if (parseToken(Token::colon, "expected ':' after block name"))
4697     return failure();
4698 
4699   return parseBlockBody(block);
4700 }
4701 
4702 ParseResult OperationParser::parseBlockBody(Block *block) {
4703   // Set the insertion point to the end of the block to parse.
4704   opBuilder.setInsertionPointToEnd(block);
4705 
4706   // Parse the list of operations that make up the body of the block.
4707   while (getToken().isNot(Token::caret_identifier, Token::r_brace))
4708     if (parseOperation())
4709       return failure();
4710 
4711   return success();
4712 }
4713 
4714 /// Get the block with the specified name, creating it if it doesn't already
4715 /// exist.  The location specified is the point of use, which allows
4716 /// us to diagnose references to blocks that are not defined precisely.
4717 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) {
4718   auto &blockAndLoc = getBlockInfoByName(name);
4719   if (!blockAndLoc.first) {
4720     blockAndLoc = {new Block(), loc};
4721     insertForwardRef(blockAndLoc.first, loc);
4722   }
4723 
4724   return blockAndLoc.first;
4725 }
4726 
4727 /// Define the block with the specified name. Returns the Block* or nullptr in
4728 /// the case of redefinition.
4729 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc,
4730                                          Block *existing) {
4731   auto &blockAndLoc = getBlockInfoByName(name);
4732   if (!blockAndLoc.first) {
4733     // If the caller provided a block, use it.  Otherwise create a new one.
4734     if (!existing)
4735       existing = new Block();
4736     blockAndLoc.first = existing;
4737     blockAndLoc.second = loc;
4738     return blockAndLoc.first;
4739   }
4740 
4741   // Forward declarations are removed once defined, so if we are defining a
4742   // existing block and it is not a forward declaration, then it is a
4743   // redeclaration.
4744   if (!eraseForwardRef(blockAndLoc.first))
4745     return nullptr;
4746   return blockAndLoc.first;
4747 }
4748 
4749 /// Parse a (possibly empty) list of SSA operands with types as block arguments.
4750 ///
4751 ///   ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
4752 ///
4753 ParseResult OperationParser::parseOptionalBlockArgList(
4754     SmallVectorImpl<BlockArgument> &results, Block *owner) {
4755   if (getToken().is(Token::r_brace))
4756     return success();
4757 
4758   // If the block already has arguments, then we're handling the entry block.
4759   // Parse and register the names for the arguments, but do not add them.
4760   bool definingExistingArgs = owner->getNumArguments() != 0;
4761   unsigned nextArgument = 0;
4762 
4763   return parseCommaSeparatedList([&]() -> ParseResult {
4764     return parseSSADefOrUseAndType(
4765         [&](SSAUseInfo useInfo, Type type) -> ParseResult {
4766           // If this block did not have existing arguments, define a new one.
4767           if (!definingExistingArgs)
4768             return addDefinition(useInfo, owner->addArgument(type));
4769 
4770           // Otherwise, ensure that this argument has already been created.
4771           if (nextArgument >= owner->getNumArguments())
4772             return emitError("too many arguments specified in argument list");
4773 
4774           // Finally, make sure the existing argument has the correct type.
4775           auto arg = owner->getArgument(nextArgument++);
4776           if (arg.getType() != type)
4777             return emitError("argument and block argument type mismatch");
4778           return addDefinition(useInfo, arg);
4779         });
4780   });
4781 }
4782 
4783 //===----------------------------------------------------------------------===//
4784 // Top-level entity parsing.
4785 //===----------------------------------------------------------------------===//
4786 
4787 namespace {
4788 /// This parser handles entities that are only valid at the top level of the
4789 /// file.
4790 class ModuleParser : public Parser {
4791 public:
4792   explicit ModuleParser(ParserState &state) : Parser(state) {}
4793 
4794   ParseResult parseModule(ModuleOp module);
4795 
4796 private:
4797   /// Parse an attribute alias declaration.
4798   ParseResult parseAttributeAliasDef();
4799 
4800   /// Parse an attribute alias declaration.
4801   ParseResult parseTypeAliasDef();
4802 };
4803 } // end anonymous namespace
4804 
4805 /// Parses an attribute alias declaration.
4806 ///
4807 ///   attribute-alias-def ::= '#' alias-name `=` attribute-value
4808 ///
4809 ParseResult ModuleParser::parseAttributeAliasDef() {
4810   assert(getToken().is(Token::hash_identifier));
4811   StringRef aliasName = getTokenSpelling().drop_front();
4812 
4813   // Check for redefinitions.
4814   if (getState().symbols.attributeAliasDefinitions.count(aliasName) > 0)
4815     return emitError("redefinition of attribute alias id '" + aliasName + "'");
4816 
4817   // Make sure this isn't invading the dialect attribute namespace.
4818   if (aliasName.contains('.'))
4819     return emitError("attribute names with a '.' are reserved for "
4820                      "dialect-defined names");
4821 
4822   consumeToken(Token::hash_identifier);
4823 
4824   // Parse the '='.
4825   if (parseToken(Token::equal, "expected '=' in attribute alias definition"))
4826     return failure();
4827 
4828   // Parse the attribute value.
4829   Attribute attr = parseAttribute();
4830   if (!attr)
4831     return failure();
4832 
4833   getState().symbols.attributeAliasDefinitions[aliasName] = attr;
4834   return success();
4835 }
4836 
4837 /// Parse a type alias declaration.
4838 ///
4839 ///   type-alias-def ::= '!' alias-name `=` 'type' type
4840 ///
4841 ParseResult ModuleParser::parseTypeAliasDef() {
4842   assert(getToken().is(Token::exclamation_identifier));
4843   StringRef aliasName = getTokenSpelling().drop_front();
4844 
4845   // Check for redefinitions.
4846   if (getState().symbols.typeAliasDefinitions.count(aliasName) > 0)
4847     return emitError("redefinition of type alias id '" + aliasName + "'");
4848 
4849   // Make sure this isn't invading the dialect type namespace.
4850   if (aliasName.contains('.'))
4851     return emitError("type names with a '.' are reserved for "
4852                      "dialect-defined names");
4853 
4854   consumeToken(Token::exclamation_identifier);
4855 
4856   // Parse the '=' and 'type'.
4857   if (parseToken(Token::equal, "expected '=' in type alias definition") ||
4858       parseToken(Token::kw_type, "expected 'type' in type alias definition"))
4859     return failure();
4860 
4861   // Parse the type.
4862   Type aliasedType = parseType();
4863   if (!aliasedType)
4864     return failure();
4865 
4866   // Register this alias with the parser state.
4867   getState().symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType);
4868   return success();
4869 }
4870 
4871 /// This is the top-level module parser.
4872 ParseResult ModuleParser::parseModule(ModuleOp module) {
4873   OperationParser opParser(getState(), module);
4874 
4875   // Module itself is a name scope.
4876   opParser.pushSSANameScope(/*isIsolated=*/true);
4877 
4878   while (true) {
4879     switch (getToken().getKind()) {
4880     default:
4881       // Parse a top-level operation.
4882       if (opParser.parseOperation())
4883         return failure();
4884       break;
4885 
4886     // If we got to the end of the file, then we're done.
4887     case Token::eof: {
4888       if (opParser.finalize())
4889         return failure();
4890 
4891       // Handle the case where the top level module was explicitly defined.
4892       auto &bodyBlocks = module.getBodyRegion().getBlocks();
4893       auto &operations = bodyBlocks.front().getOperations();
4894       assert(!operations.empty() && "expected a valid module terminator");
4895 
4896       // Check that the first operation is a module, and it is the only
4897       // non-terminator operation.
4898       ModuleOp nested = dyn_cast<ModuleOp>(operations.front());
4899       if (nested && std::next(operations.begin(), 2) == operations.end()) {
4900         // Merge the data of the nested module operation into 'module'.
4901         module.setLoc(nested.getLoc());
4902         module.setAttrs(nested.getOperation()->getAttrList());
4903         bodyBlocks.splice(bodyBlocks.end(), nested.getBodyRegion().getBlocks());
4904 
4905         // Erase the original module body.
4906         bodyBlocks.pop_front();
4907       }
4908 
4909       return opParser.popSSANameScope();
4910     }
4911 
4912     // If we got an error token, then the lexer already emitted an error, just
4913     // stop.  Someday we could introduce error recovery if there was demand
4914     // for it.
4915     case Token::error:
4916       return failure();
4917 
4918     // Parse an attribute alias.
4919     case Token::hash_identifier:
4920       if (parseAttributeAliasDef())
4921         return failure();
4922       break;
4923 
4924     // Parse a type alias.
4925     case Token::exclamation_identifier:
4926       if (parseTypeAliasDef())
4927         return failure();
4928       break;
4929     }
4930   }
4931 }
4932 
4933 //===----------------------------------------------------------------------===//
4934 
4935 /// This parses the file specified by the indicated SourceMgr and returns an
4936 /// MLIR module if it was valid.  If not, it emits diagnostics and returns
4937 /// null.
4938 OwningModuleRef mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr,
4939                                       MLIRContext *context) {
4940   auto sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
4941 
4942   // This is the result module we are parsing into.
4943   OwningModuleRef module(ModuleOp::create(FileLineColLoc::get(
4944       sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0, context)));
4945 
4946   SymbolState aliasState;
4947   ParserState state(sourceMgr, context, aliasState);
4948   if (ModuleParser(state).parseModule(*module))
4949     return nullptr;
4950 
4951   // Make sure the parse module has no other structural problems detected by
4952   // the verifier.
4953   if (failed(verify(*module)))
4954     return nullptr;
4955 
4956   return module;
4957 }
4958 
4959 /// This parses the file specified by the indicated filename and returns an
4960 /// MLIR module if it was valid.  If not, the error message is emitted through
4961 /// the error handler registered in the context, and a null pointer is returned.
4962 OwningModuleRef mlir::parseSourceFile(StringRef filename,
4963                                       MLIRContext *context) {
4964   llvm::SourceMgr sourceMgr;
4965   return parseSourceFile(filename, sourceMgr, context);
4966 }
4967 
4968 /// This parses the file specified by the indicated filename using the provided
4969 /// SourceMgr and returns an MLIR module if it was valid.  If not, the error
4970 /// message is emitted through the error handler registered in the context, and
4971 /// a null pointer is returned.
4972 OwningModuleRef mlir::parseSourceFile(StringRef filename,
4973                                       llvm::SourceMgr &sourceMgr,
4974                                       MLIRContext *context) {
4975   if (sourceMgr.getNumBuffers() != 0) {
4976     // TODO(b/136086478): Extend to support multiple buffers.
4977     emitError(mlir::UnknownLoc::get(context),
4978               "only main buffer parsed at the moment");
4979     return nullptr;
4980   }
4981   auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename);
4982   if (std::error_code error = file_or_err.getError()) {
4983     emitError(mlir::UnknownLoc::get(context),
4984               "could not open input file " + filename);
4985     return nullptr;
4986   }
4987 
4988   // Load the MLIR module.
4989   sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc());
4990   return parseSourceFile(sourceMgr, context);
4991 }
4992 
4993 /// This parses the program string to a MLIR module if it was valid. If not,
4994 /// it emits diagnostics and returns null.
4995 OwningModuleRef mlir::parseSourceString(StringRef moduleStr,
4996                                         MLIRContext *context) {
4997   auto memBuffer = MemoryBuffer::getMemBuffer(moduleStr);
4998   if (!memBuffer)
4999     return nullptr;
5000 
5001   SourceMgr sourceMgr;
5002   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
5003   return parseSourceFile(sourceMgr, context);
5004 }
5005 
5006 /// Parses a symbol, of type 'T', and returns it if parsing was successful. If
5007 /// parsing failed, nullptr is returned. The number of bytes read from the input
5008 /// string is returned in 'numRead'.
5009 template <typename T, typename ParserFn>
5010 static T parseSymbol(StringRef inputStr, MLIRContext *context, size_t &numRead,
5011                      ParserFn &&parserFn) {
5012   SymbolState aliasState;
5013   return parseSymbol<T>(
5014       inputStr, context, aliasState,
5015       [&](Parser &parser) {
5016         SourceMgrDiagnosticHandler handler(
5017             const_cast<llvm::SourceMgr &>(parser.getSourceMgr()),
5018             parser.getContext());
5019         return parserFn(parser);
5020       },
5021       &numRead);
5022 }
5023 
5024 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context) {
5025   size_t numRead = 0;
5026   return parseAttribute(attrStr, context, numRead);
5027 }
5028 Attribute mlir::parseAttribute(StringRef attrStr, Type type) {
5029   size_t numRead = 0;
5030   return parseAttribute(attrStr, type, numRead);
5031 }
5032 
5033 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context,
5034                                size_t &numRead) {
5035   return parseSymbol<Attribute>(attrStr, context, numRead, [](Parser &parser) {
5036     return parser.parseAttribute();
5037   });
5038 }
5039 Attribute mlir::parseAttribute(StringRef attrStr, Type type, size_t &numRead) {
5040   return parseSymbol<Attribute>(
5041       attrStr, type.getContext(), numRead,
5042       [type](Parser &parser) { return parser.parseAttribute(type); });
5043 }
5044 
5045 Type mlir::parseType(StringRef typeStr, MLIRContext *context) {
5046   size_t numRead = 0;
5047   return parseType(typeStr, context, numRead);
5048 }
5049 
5050 Type mlir::parseType(StringRef typeStr, MLIRContext *context, size_t &numRead) {
5051   return parseSymbol<Type>(typeStr, context, numRead,
5052                            [](Parser &parser) { return parser.parseType(); });
5053 }
5054