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