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/IR/AffineExpr.h"
16 #include "mlir/IR/AffineMap.h"
17 #include "mlir/IR/Attributes.h"
18 #include "mlir/IR/Builders.h"
19 #include "mlir/IR/Dialect.h"
20 #include "mlir/IR/DialectImplementation.h"
21 #include "mlir/IR/IntegerSet.h"
22 #include "mlir/IR/Location.h"
23 #include "mlir/IR/MLIRContext.h"
24 #include "mlir/IR/Module.h"
25 #include "mlir/IR/OpImplementation.h"
26 #include "mlir/IR/StandardTypes.h"
27 #include "mlir/IR/Verifier.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(NamedAttrList &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     NamedAttrList elements;
1573     if (parseAttributeDict(elements))
1574       return nullptr;
1575     return elements.getDictionary(getContext());
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 Parser::parseAttributeDict(NamedAttrList &attributes) {
1675   if (parseToken(Token::l_brace, "expected '{' in attribute dictionary"))
1676     return failure();
1677 
1678   llvm::SmallDenseSet<Identifier> seenKeys;
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     if (!seenKeys.insert(*nameId).second)
1690       return emitError("duplicate key in dictionary attribute");
1691     consumeToken();
1692 
1693     // Try to parse the '=' for the attribute value.
1694     if (!consumeIf(Token::equal)) {
1695       // If there is no '=', we treat this as a unit attribute.
1696       attributes.push_back({*nameId, builder.getUnitAttr()});
1697       return success();
1698     }
1699 
1700     auto attr = parseAttribute();
1701     if (!attr)
1702       return failure();
1703     attributes.push_back({*nameId, attr});
1704     return success();
1705   };
1706 
1707   if (parseCommaSeparatedListUntil(Token::r_brace, parseElt))
1708     return failure();
1709 
1710   return success();
1711 }
1712 
1713 /// Parse an extended attribute.
1714 ///
1715 ///   extended-attribute ::= (dialect-attribute | attribute-alias)
1716 ///   dialect-attribute  ::= `#` dialect-namespace `<` `"` attr-data `"` `>`
1717 ///   dialect-attribute  ::= `#` alias-name pretty-dialect-sym-body?
1718 ///   attribute-alias    ::= `#` alias-name
1719 ///
1720 Attribute Parser::parseExtendedAttr(Type type) {
1721   Attribute attr = parseExtendedSymbol<Attribute>(
1722       *this, Token::hash_identifier, state.symbols.attributeAliasDefinitions,
1723       [&](StringRef dialectName, StringRef symbolData,
1724           llvm::SMLoc loc) -> Attribute {
1725         // Parse an optional trailing colon type.
1726         Type attrType = type;
1727         if (consumeIf(Token::colon) && !(attrType = parseType()))
1728           return Attribute();
1729 
1730         // If we found a registered dialect, then ask it to parse the attribute.
1731         if (auto *dialect = state.context->getRegisteredDialect(dialectName)) {
1732           return parseSymbol<Attribute>(
1733               symbolData, state.context, state.symbols, [&](Parser &parser) {
1734                 CustomDialectAsmParser customParser(symbolData, parser);
1735                 return dialect->parseAttribute(customParser, attrType);
1736               });
1737         }
1738 
1739         // Otherwise, form a new opaque attribute.
1740         return OpaqueAttr::getChecked(
1741             Identifier::get(dialectName, state.context), symbolData,
1742             attrType ? attrType : NoneType::get(state.context),
1743             getEncodedSourceLocation(loc));
1744       });
1745 
1746   // Ensure that the attribute has the same type as requested.
1747   if (attr && type && attr.getType() != type) {
1748     emitError("attribute type different than expected: expected ")
1749         << type << ", but got " << attr.getType();
1750     return nullptr;
1751   }
1752   return attr;
1753 }
1754 
1755 /// Parse a float attribute.
1756 Attribute Parser::parseFloatAttr(Type type, bool isNegative) {
1757   auto val = getToken().getFloatingPointValue();
1758   if (!val.hasValue())
1759     return (emitError("floating point value too large for attribute"), nullptr);
1760   consumeToken(Token::floatliteral);
1761   if (!type) {
1762     // Default to F64 when no type is specified.
1763     if (!consumeIf(Token::colon))
1764       type = builder.getF64Type();
1765     else if (!(type = parseType()))
1766       return nullptr;
1767   }
1768   if (!type.isa<FloatType>())
1769     return (emitError("floating point value not valid for specified type"),
1770             nullptr);
1771   return FloatAttr::get(type, isNegative ? -val.getValue() : val.getValue());
1772 }
1773 
1774 /// Construct a float attribute bitwise equivalent to the integer literal.
1775 static Optional<APFloat> buildHexadecimalFloatLiteral(Parser *p, FloatType type,
1776                                                       uint64_t value) {
1777   if (type.isF64())
1778     return APFloat(type.getFloatSemantics(), APInt(/*numBits=*/64, value));
1779 
1780   APInt apInt(type.getWidth(), value);
1781   if (apInt != value) {
1782     p->emitError("hexadecimal float constant out of range for type");
1783     return llvm::None;
1784   }
1785   return APFloat(type.getFloatSemantics(), apInt);
1786 }
1787 
1788 /// Construct an APint from a parsed value, a known attribute type and
1789 /// sign.
1790 static Optional<APInt> buildAttributeAPInt(Type type, bool isNegative,
1791                                            StringRef spelling) {
1792   // Parse the integer value into an APInt that is big enough to hold the value.
1793   APInt result;
1794   bool isHex = spelling.size() > 1 && spelling[1] == 'x';
1795   if (spelling.getAsInteger(isHex ? 0 : 10, result))
1796     return llvm::None;
1797 
1798   // Extend or truncate the bitwidth to the right size.
1799   unsigned width = type.isIndex() ? IndexType::kInternalStorageBitWidth
1800                                   : type.getIntOrFloatBitWidth();
1801   if (width > result.getBitWidth()) {
1802     result = result.zext(width);
1803   } else if (width < result.getBitWidth()) {
1804     // The parser can return an unnecessarily wide result with leading zeros.
1805     // This isn't a problem, but truncating off bits is bad.
1806     if (result.countLeadingZeros() < result.getBitWidth() - width)
1807       return llvm::None;
1808 
1809     result = result.trunc(width);
1810   }
1811 
1812   if (isNegative) {
1813     // The value is negative, we have an overflow if the sign bit is not set
1814     // in the negated apInt.
1815     result.negate();
1816     if (!result.isSignBitSet())
1817       return llvm::None;
1818   } else if ((type.isSignedInteger() || type.isIndex()) &&
1819              result.isSignBitSet()) {
1820     // The value is a positive signed integer or index,
1821     // we have an overflow if the sign bit is set.
1822     return llvm::None;
1823   }
1824 
1825   return result;
1826 }
1827 
1828 /// Parse a decimal or a hexadecimal literal, which can be either an integer
1829 /// or a float attribute.
1830 Attribute Parser::parseDecOrHexAttr(Type type, bool isNegative) {
1831   // Remember if the literal is hexadecimal.
1832   StringRef spelling = getToken().getSpelling();
1833   auto loc = state.curToken.getLoc();
1834   bool isHex = spelling.size() > 1 && spelling[1] == 'x';
1835 
1836   consumeToken(Token::integer);
1837   if (!type) {
1838     // Default to i64 if not type is specified.
1839     if (!consumeIf(Token::colon))
1840       type = builder.getIntegerType(64);
1841     else if (!(type = parseType()))
1842       return nullptr;
1843   }
1844 
1845   if (auto floatType = type.dyn_cast<FloatType>()) {
1846     if (isNegative)
1847       return emitError(
1848                  loc,
1849                  "hexadecimal float literal should not have a leading minus"),
1850              nullptr;
1851     if (!isHex) {
1852       emitError(loc, "unexpected decimal integer literal for a float attribute")
1853               .attachNote()
1854           << "add a trailing dot to make the literal a float";
1855       return nullptr;
1856     }
1857 
1858     auto val = Token::getUInt64IntegerValue(spelling);
1859     if (!val.hasValue())
1860       return emitError("integer constant out of range for attribute"), nullptr;
1861 
1862     // Construct a float attribute bitwise equivalent to the integer literal.
1863     Optional<APFloat> apVal =
1864         buildHexadecimalFloatLiteral(this, floatType, *val);
1865     return apVal ? FloatAttr::get(floatType, *apVal) : Attribute();
1866   }
1867 
1868   if (!type.isa<IntegerType>() && !type.isa<IndexType>())
1869     return emitError(loc, "integer literal not valid for specified type"),
1870            nullptr;
1871 
1872   if (isNegative && type.isUnsignedInteger()) {
1873     emitError(loc,
1874               "negative integer literal not valid for unsigned integer type");
1875     return nullptr;
1876   }
1877 
1878   Optional<APInt> apInt = buildAttributeAPInt(type, isNegative, spelling);
1879   if (!apInt)
1880     return emitError(loc, "integer constant out of range for attribute"),
1881            nullptr;
1882   return builder.getIntegerAttr(type, *apInt);
1883 }
1884 
1885 /// Parse elements values stored within a hex etring. On success, the values are
1886 /// stored into 'result'.
1887 static ParseResult parseElementAttrHexValues(Parser &parser, Token tok,
1888                                              std::string &result) {
1889   std::string val = tok.getStringValue();
1890   if (val.size() < 2 || val[0] != '0' || val[1] != 'x')
1891     return parser.emitError(tok.getLoc(),
1892                             "elements hex string should start with '0x'");
1893 
1894   StringRef hexValues = StringRef(val).drop_front(2);
1895   if (!llvm::all_of(hexValues, llvm::isHexDigit))
1896     return parser.emitError(tok.getLoc(),
1897                             "elements hex string only contains hex digits");
1898 
1899   result = llvm::fromHex(hexValues);
1900   return success();
1901 }
1902 
1903 /// Parse an opaque elements attribute.
1904 Attribute Parser::parseOpaqueElementsAttr(Type attrType) {
1905   consumeToken(Token::kw_opaque);
1906   if (parseToken(Token::less, "expected '<' after 'opaque'"))
1907     return nullptr;
1908 
1909   if (getToken().isNot(Token::string))
1910     return (emitError("expected dialect namespace"), nullptr);
1911 
1912   auto name = getToken().getStringValue();
1913   auto *dialect = builder.getContext()->getRegisteredDialect(name);
1914   // TODO(shpeisman): Allow for having an unknown dialect on an opaque
1915   // attribute. Otherwise, it can't be roundtripped without having the dialect
1916   // registered.
1917   if (!dialect)
1918     return (emitError("no registered dialect with namespace '" + name + "'"),
1919             nullptr);
1920   consumeToken(Token::string);
1921 
1922   if (parseToken(Token::comma, "expected ','"))
1923     return nullptr;
1924 
1925   Token hexTok = getToken();
1926   if (parseToken(Token::string, "elements hex string should start with '0x'") ||
1927       parseToken(Token::greater, "expected '>'"))
1928     return nullptr;
1929   auto type = parseElementsLiteralType(attrType);
1930   if (!type)
1931     return nullptr;
1932 
1933   std::string data;
1934   if (parseElementAttrHexValues(*this, hexTok, data))
1935     return nullptr;
1936   return OpaqueElementsAttr::get(dialect, type, data);
1937 }
1938 
1939 namespace {
1940 class TensorLiteralParser {
1941 public:
1942   TensorLiteralParser(Parser &p) : p(p) {}
1943 
1944   /// Parse the elements of a tensor literal. If 'allowHex' is true, the parser
1945   /// may also parse a tensor literal that is store as a hex string.
1946   ParseResult parse(bool allowHex);
1947 
1948   /// Build a dense attribute instance with the parsed elements and the given
1949   /// shaped type.
1950   DenseElementsAttr getAttr(llvm::SMLoc loc, ShapedType type);
1951 
1952   ArrayRef<int64_t> getShape() const { return shape; }
1953 
1954 private:
1955   /// Get the parsed elements for an integer attribute.
1956   ParseResult getIntAttrElements(llvm::SMLoc loc, Type eltTy,
1957                                  std::vector<APInt> &intValues);
1958 
1959   /// Get the parsed elements for a float attribute.
1960   ParseResult getFloatAttrElements(llvm::SMLoc loc, FloatType eltTy,
1961                                    std::vector<APFloat> &floatValues);
1962 
1963   /// Build a Dense String attribute for the given type.
1964   DenseElementsAttr getStringAttr(llvm::SMLoc loc, ShapedType type, Type eltTy);
1965 
1966   /// Build a Dense attribute with hex data for the given type.
1967   DenseElementsAttr getHexAttr(llvm::SMLoc loc, ShapedType type);
1968 
1969   /// Parse a single element, returning failure if it isn't a valid element
1970   /// literal. For example:
1971   /// parseElement(1) -> Success, 1
1972   /// parseElement([1]) -> Failure
1973   ParseResult parseElement();
1974 
1975   /// Parse a list of either lists or elements, returning the dimensions of the
1976   /// parsed sub-tensors in dims. For example:
1977   ///   parseList([1, 2, 3]) -> Success, [3]
1978   ///   parseList([[1, 2], [3, 4]]) -> Success, [2, 2]
1979   ///   parseList([[1, 2], 3]) -> Failure
1980   ///   parseList([[1, [2, 3]], [4, [5]]]) -> Failure
1981   ParseResult parseList(SmallVectorImpl<int64_t> &dims);
1982 
1983   /// Parse a literal that was printed as a hex string.
1984   ParseResult parseHexElements();
1985 
1986   Parser &p;
1987 
1988   /// The shape inferred from the parsed elements.
1989   SmallVector<int64_t, 4> shape;
1990 
1991   /// Storage used when parsing elements, this is a pair of <is_negated, token>.
1992   std::vector<std::pair<bool, Token>> storage;
1993 
1994   /// Storage used when parsing elements that were stored as hex values.
1995   Optional<Token> hexStorage;
1996 };
1997 } // namespace
1998 
1999 /// Parse the elements of a tensor literal. If 'allowHex' is true, the parser
2000 /// may also parse a tensor literal that is store as a hex string.
2001 ParseResult TensorLiteralParser::parse(bool allowHex) {
2002   // If hex is allowed, check for a string literal.
2003   if (allowHex && p.getToken().is(Token::string)) {
2004     hexStorage = p.getToken();
2005     p.consumeToken(Token::string);
2006     return success();
2007   }
2008   // Otherwise, parse a list or an individual element.
2009   if (p.getToken().is(Token::l_square))
2010     return parseList(shape);
2011   return parseElement();
2012 }
2013 
2014 /// Build a dense attribute instance with the parsed elements and the given
2015 /// shaped type.
2016 DenseElementsAttr TensorLiteralParser::getAttr(llvm::SMLoc loc,
2017                                                ShapedType type) {
2018   Type eltType = type.getElementType();
2019 
2020   // Check to see if we parse the literal from a hex string.
2021   if (hexStorage.hasValue() &&
2022       (eltType.isIntOrFloat() || eltType.isa<ComplexType>()))
2023     return getHexAttr(loc, type);
2024 
2025   // Check that the parsed storage size has the same number of elements to the
2026   // type, or is a known splat.
2027   if (!shape.empty() && getShape() != type.getShape()) {
2028     p.emitError(loc) << "inferred shape of elements literal ([" << getShape()
2029                      << "]) does not match type ([" << type.getShape() << "])";
2030     return nullptr;
2031   }
2032 
2033   // Handle complex types in the specific element type cases below.
2034   bool isComplex = false;
2035   if (ComplexType complexTy = eltType.dyn_cast<ComplexType>()) {
2036     eltType = complexTy.getElementType();
2037     isComplex = true;
2038   }
2039 
2040   // Handle integer and index types.
2041   if (eltType.isIntOrIndex()) {
2042     std::vector<APInt> intValues;
2043     if (failed(getIntAttrElements(loc, eltType, intValues)))
2044       return nullptr;
2045     if (isComplex) {
2046       // If this is a complex, treat the parsed values as complex values.
2047       auto complexData = llvm::makeArrayRef(
2048           reinterpret_cast<std::complex<APInt> *>(intValues.data()),
2049           intValues.size() / 2);
2050       return DenseElementsAttr::get(type, complexData);
2051     }
2052     return DenseElementsAttr::get(type, intValues);
2053   }
2054   // Handle floating point types.
2055   if (FloatType floatTy = eltType.dyn_cast<FloatType>()) {
2056     std::vector<APFloat> floatValues;
2057     if (failed(getFloatAttrElements(loc, floatTy, floatValues)))
2058       return nullptr;
2059     if (isComplex) {
2060       // If this is a complex, treat the parsed values as complex values.
2061       auto complexData = llvm::makeArrayRef(
2062           reinterpret_cast<std::complex<APFloat> *>(floatValues.data()),
2063           floatValues.size() / 2);
2064       return DenseElementsAttr::get(type, complexData);
2065     }
2066     return DenseElementsAttr::get(type, floatValues);
2067   }
2068 
2069   // Other types are assumed to be string representations.
2070   return getStringAttr(loc, type, type.getElementType());
2071 }
2072 
2073 /// Build a Dense Integer attribute for the given type.
2074 ParseResult
2075 TensorLiteralParser::getIntAttrElements(llvm::SMLoc loc, Type eltTy,
2076                                         std::vector<APInt> &intValues) {
2077   intValues.reserve(storage.size());
2078   bool isUintType = eltTy.isUnsignedInteger();
2079   for (const auto &signAndToken : storage) {
2080     bool isNegative = signAndToken.first;
2081     const Token &token = signAndToken.second;
2082     auto tokenLoc = token.getLoc();
2083 
2084     if (isNegative && isUintType) {
2085       return p.emitError(tokenLoc)
2086              << "expected unsigned integer elements, but parsed negative value";
2087     }
2088 
2089     // Check to see if floating point values were parsed.
2090     if (token.is(Token::floatliteral)) {
2091       return p.emitError(tokenLoc)
2092              << "expected integer elements, but parsed floating-point";
2093     }
2094 
2095     assert(token.isAny(Token::integer, Token::kw_true, Token::kw_false) &&
2096            "unexpected token type");
2097     if (token.isAny(Token::kw_true, Token::kw_false)) {
2098       if (!eltTy.isInteger(1)) {
2099         return p.emitError(tokenLoc)
2100                << "expected i1 type for 'true' or 'false' values";
2101       }
2102       APInt apInt(1, token.is(Token::kw_true), /*isSigned=*/false);
2103       intValues.push_back(apInt);
2104       continue;
2105     }
2106 
2107     // Create APInt values for each element with the correct bitwidth.
2108     Optional<APInt> apInt =
2109         buildAttributeAPInt(eltTy, isNegative, token.getSpelling());
2110     if (!apInt)
2111       return p.emitError(tokenLoc, "integer constant out of range for type");
2112     intValues.push_back(*apInt);
2113   }
2114   return success();
2115 }
2116 
2117 /// Build a Dense Float attribute for the given type.
2118 ParseResult
2119 TensorLiteralParser::getFloatAttrElements(llvm::SMLoc loc, 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         return p.emitError(token.getLoc())
2130                << "hexadecimal float literal should not have a leading minus";
2131       }
2132       auto val = token.getUInt64IntegerValue();
2133       if (!val.hasValue()) {
2134         return p.emitError(
2135             "hexadecimal float constant out of range for attribute");
2136       }
2137       Optional<APFloat> apVal = buildHexadecimalFloatLiteral(&p, eltTy, *val);
2138       if (!apVal)
2139         return failure();
2140       floatValues.push_back(*apVal);
2141       continue;
2142     }
2143 
2144     // Check to see if any decimal integers or booleans were parsed.
2145     if (!token.is(Token::floatliteral))
2146       return p.emitError()
2147              << "expected floating-point elements, but parsed integer";
2148 
2149     // Build the float values from tokens.
2150     auto val = token.getFloatingPointValue();
2151     if (!val.hasValue())
2152       return p.emitError("floating point value too large for attribute");
2153 
2154     APFloat apVal(isNegative ? -*val : *val);
2155     if (!eltTy.isF64()) {
2156       bool unused;
2157       apVal.convert(eltTy.getFloatSemantics(), APFloat::rmNearestTiesToEven,
2158                     &unused);
2159     }
2160     floatValues.push_back(apVal);
2161   }
2162   return success();
2163 }
2164 
2165 /// Build a Dense String attribute for the given type.
2166 DenseElementsAttr TensorLiteralParser::getStringAttr(llvm::SMLoc loc,
2167                                                      ShapedType type,
2168                                                      Type eltTy) {
2169   if (hexStorage.hasValue()) {
2170     auto stringValue = hexStorage.getValue().getStringValue();
2171     return DenseStringElementsAttr::get(type, {stringValue});
2172   }
2173 
2174   std::vector<std::string> stringValues;
2175   std::vector<StringRef> stringRefValues;
2176   stringValues.reserve(storage.size());
2177   stringRefValues.reserve(storage.size());
2178 
2179   for (auto val : storage) {
2180     stringValues.push_back(val.second.getStringValue());
2181     stringRefValues.push_back(stringValues.back());
2182   }
2183 
2184   return DenseStringElementsAttr::get(type, stringRefValues);
2185 }
2186 
2187 /// Build a Dense attribute with hex data for the given type.
2188 DenseElementsAttr TensorLiteralParser::getHexAttr(llvm::SMLoc loc,
2189                                                   ShapedType type) {
2190   Type elementType = type.getElementType();
2191   if (!elementType.isIntOrIndexOrFloat() && !elementType.isa<ComplexType>()) {
2192     p.emitError(loc)
2193         << "expected floating-point, integer, or complex element type, got "
2194         << elementType;
2195     return nullptr;
2196   }
2197 
2198   std::string data;
2199   if (parseElementAttrHexValues(p, hexStorage.getValue(), data))
2200     return nullptr;
2201 
2202   ArrayRef<char> rawData(data.data(), data.size());
2203   bool detectedSplat = false;
2204   if (!DenseElementsAttr::isValidRawBuffer(type, rawData, detectedSplat)) {
2205     p.emitError(loc) << "elements hex data size is invalid for provided type: "
2206                      << type;
2207     return nullptr;
2208   }
2209 
2210   return DenseElementsAttr::getFromRawBuffer(type, rawData, detectedSplat);
2211 }
2212 
2213 ParseResult TensorLiteralParser::parseElement() {
2214   switch (p.getToken().getKind()) {
2215   // Parse a boolean element.
2216   case Token::kw_true:
2217   case Token::kw_false:
2218   case Token::floatliteral:
2219   case Token::integer:
2220     storage.emplace_back(/*isNegative=*/false, p.getToken());
2221     p.consumeToken();
2222     break;
2223 
2224   // Parse a signed integer or a negative floating-point element.
2225   case Token::minus:
2226     p.consumeToken(Token::minus);
2227     if (!p.getToken().isAny(Token::floatliteral, Token::integer))
2228       return p.emitError("expected integer or floating point literal");
2229     storage.emplace_back(/*isNegative=*/true, p.getToken());
2230     p.consumeToken();
2231     break;
2232 
2233   case Token::string:
2234     storage.emplace_back(/*isNegative=*/ false, p.getToken());
2235     p.consumeToken();
2236     break;
2237 
2238   // Parse a complex element of the form '(' element ',' element ')'.
2239   case Token::l_paren:
2240     p.consumeToken(Token::l_paren);
2241     if (parseElement() ||
2242         p.parseToken(Token::comma, "expected ',' between complex elements") ||
2243         parseElement() ||
2244         p.parseToken(Token::r_paren, "expected ')' after complex elements"))
2245       return failure();
2246     break;
2247 
2248   default:
2249     return p.emitError("expected element literal of primitive type");
2250   }
2251 
2252   return success();
2253 }
2254 
2255 /// Parse a list of either lists or elements, returning the dimensions of the
2256 /// parsed sub-tensors in dims. For example:
2257 ///   parseList([1, 2, 3]) -> Success, [3]
2258 ///   parseList([[1, 2], [3, 4]]) -> Success, [2, 2]
2259 ///   parseList([[1, 2], 3]) -> Failure
2260 ///   parseList([[1, [2, 3]], [4, [5]]]) -> Failure
2261 ParseResult TensorLiteralParser::parseList(SmallVectorImpl<int64_t> &dims) {
2262   p.consumeToken(Token::l_square);
2263 
2264   auto checkDims = [&](const SmallVectorImpl<int64_t> &prevDims,
2265                        const SmallVectorImpl<int64_t> &newDims) -> ParseResult {
2266     if (prevDims == newDims)
2267       return success();
2268     return p.emitError("tensor literal is invalid; ranks are not consistent "
2269                        "between elements");
2270   };
2271 
2272   bool first = true;
2273   SmallVector<int64_t, 4> newDims;
2274   unsigned size = 0;
2275   auto parseCommaSeparatedList = [&]() -> ParseResult {
2276     SmallVector<int64_t, 4> thisDims;
2277     if (p.getToken().getKind() == Token::l_square) {
2278       if (parseList(thisDims))
2279         return failure();
2280     } else if (parseElement()) {
2281       return failure();
2282     }
2283     ++size;
2284     if (!first)
2285       return checkDims(newDims, thisDims);
2286     newDims = thisDims;
2287     first = false;
2288     return success();
2289   };
2290   if (p.parseCommaSeparatedListUntil(Token::r_square, parseCommaSeparatedList))
2291     return failure();
2292 
2293   // Return the sublists' dimensions with 'size' prepended.
2294   dims.clear();
2295   dims.push_back(size);
2296   dims.append(newDims.begin(), newDims.end());
2297   return success();
2298 }
2299 
2300 /// Parse a dense elements attribute.
2301 Attribute Parser::parseDenseElementsAttr(Type attrType) {
2302   consumeToken(Token::kw_dense);
2303   if (parseToken(Token::less, "expected '<' after 'dense'"))
2304     return nullptr;
2305 
2306   // Parse the literal data.
2307   TensorLiteralParser literalParser(*this);
2308   if (literalParser.parse(/*allowHex=*/true))
2309     return nullptr;
2310 
2311   if (parseToken(Token::greater, "expected '>'"))
2312     return nullptr;
2313 
2314   auto typeLoc = getToken().getLoc();
2315   auto type = parseElementsLiteralType(attrType);
2316   if (!type)
2317     return nullptr;
2318   return literalParser.getAttr(typeLoc, type);
2319 }
2320 
2321 /// Shaped type for elements attribute.
2322 ///
2323 ///   elements-literal-type ::= vector-type | ranked-tensor-type
2324 ///
2325 /// This method also checks the type has static shape.
2326 ShapedType Parser::parseElementsLiteralType(Type type) {
2327   // If the user didn't provide a type, parse the colon type for the literal.
2328   if (!type) {
2329     if (parseToken(Token::colon, "expected ':'"))
2330       return nullptr;
2331     if (!(type = parseType()))
2332       return nullptr;
2333   }
2334 
2335   if (!type.isa<RankedTensorType>() && !type.isa<VectorType>()) {
2336     emitError("elements literal must be a ranked tensor or vector type");
2337     return nullptr;
2338   }
2339 
2340   auto sType = type.cast<ShapedType>();
2341   if (!sType.hasStaticShape())
2342     return (emitError("elements literal type must have static shape"), nullptr);
2343 
2344   return sType;
2345 }
2346 
2347 /// Parse a sparse elements attribute.
2348 Attribute Parser::parseSparseElementsAttr(Type attrType) {
2349   consumeToken(Token::kw_sparse);
2350   if (parseToken(Token::less, "Expected '<' after 'sparse'"))
2351     return nullptr;
2352 
2353   /// Parse the indices. We don't allow hex values here as we may need to use
2354   /// the inferred shape.
2355   auto indicesLoc = getToken().getLoc();
2356   TensorLiteralParser indiceParser(*this);
2357   if (indiceParser.parse(/*allowHex=*/false))
2358     return nullptr;
2359 
2360   if (parseToken(Token::comma, "expected ','"))
2361     return nullptr;
2362 
2363   /// Parse the values.
2364   auto valuesLoc = getToken().getLoc();
2365   TensorLiteralParser valuesParser(*this);
2366   if (valuesParser.parse(/*allowHex=*/true))
2367     return nullptr;
2368 
2369   if (parseToken(Token::greater, "expected '>'"))
2370     return nullptr;
2371 
2372   auto type = parseElementsLiteralType(attrType);
2373   if (!type)
2374     return nullptr;
2375 
2376   // If the indices are a splat, i.e. the literal parser parsed an element and
2377   // not a list, we set the shape explicitly. The indices are represented by a
2378   // 2-dimensional shape where the second dimension is the rank of the type.
2379   // Given that the parsed indices is a splat, we know that we only have one
2380   // indice and thus one for the first dimension.
2381   auto indiceEltType = builder.getIntegerType(64);
2382   ShapedType indicesType;
2383   if (indiceParser.getShape().empty()) {
2384     indicesType = RankedTensorType::get({1, type.getRank()}, indiceEltType);
2385   } else {
2386     // Otherwise, set the shape to the one parsed by the literal parser.
2387     indicesType = RankedTensorType::get(indiceParser.getShape(), indiceEltType);
2388   }
2389   auto indices = indiceParser.getAttr(indicesLoc, indicesType);
2390 
2391   // If the values are a splat, set the shape explicitly based on the number of
2392   // indices. The number of indices is encoded in the first dimension of the
2393   // indice shape type.
2394   auto valuesEltType = type.getElementType();
2395   ShapedType valuesType =
2396       valuesParser.getShape().empty()
2397           ? RankedTensorType::get({indicesType.getDimSize(0)}, valuesEltType)
2398           : RankedTensorType::get(valuesParser.getShape(), valuesEltType);
2399   auto values = valuesParser.getAttr(valuesLoc, valuesType);
2400 
2401   /// Sanity check.
2402   if (valuesType.getRank() != 1)
2403     return (emitError("expected 1-d tensor for values"), nullptr);
2404 
2405   auto sameShape = (indicesType.getRank() == 1) ||
2406                    (type.getRank() == indicesType.getDimSize(1));
2407   auto sameElementNum = indicesType.getDimSize(0) == valuesType.getDimSize(0);
2408   if (!sameShape || !sameElementNum) {
2409     emitError() << "expected shape ([" << type.getShape()
2410                 << "]); inferred shape of indices literal (["
2411                 << indicesType.getShape()
2412                 << "]); inferred shape of values literal (["
2413                 << valuesType.getShape() << "])";
2414     return nullptr;
2415   }
2416 
2417   // Build the sparse elements attribute by the indices and values.
2418   return SparseElementsAttr::get(type, indices, values);
2419 }
2420 
2421 //===----------------------------------------------------------------------===//
2422 // Location parsing.
2423 //===----------------------------------------------------------------------===//
2424 
2425 /// Parse a location.
2426 ///
2427 ///   location           ::= `loc` inline-location
2428 ///   inline-location    ::= '(' location-inst ')'
2429 ///
2430 ParseResult Parser::parseLocation(LocationAttr &loc) {
2431   // Check for 'loc' identifier.
2432   if (parseToken(Token::kw_loc, "expected 'loc' keyword"))
2433     return emitError();
2434 
2435   // Parse the inline-location.
2436   if (parseToken(Token::l_paren, "expected '(' in inline location") ||
2437       parseLocationInstance(loc) ||
2438       parseToken(Token::r_paren, "expected ')' in inline location"))
2439     return failure();
2440   return success();
2441 }
2442 
2443 /// Specific location instances.
2444 ///
2445 /// location-inst ::= filelinecol-location |
2446 ///                   name-location |
2447 ///                   callsite-location |
2448 ///                   fused-location |
2449 ///                   unknown-location
2450 /// filelinecol-location ::= string-literal ':' integer-literal
2451 ///                                         ':' integer-literal
2452 /// name-location ::= string-literal
2453 /// callsite-location ::= 'callsite' '(' location-inst 'at' location-inst ')'
2454 /// fused-location ::= fused ('<' attribute-value '>')?
2455 ///                    '[' location-inst (location-inst ',')* ']'
2456 /// unknown-location ::= 'unknown'
2457 ///
2458 ParseResult Parser::parseCallSiteLocation(LocationAttr &loc) {
2459   consumeToken(Token::bare_identifier);
2460 
2461   // Parse the '('.
2462   if (parseToken(Token::l_paren, "expected '(' in callsite location"))
2463     return failure();
2464 
2465   // Parse the callee location.
2466   LocationAttr calleeLoc;
2467   if (parseLocationInstance(calleeLoc))
2468     return failure();
2469 
2470   // Parse the 'at'.
2471   if (getToken().isNot(Token::bare_identifier) ||
2472       getToken().getSpelling() != "at")
2473     return emitError("expected 'at' in callsite location");
2474   consumeToken(Token::bare_identifier);
2475 
2476   // Parse the caller location.
2477   LocationAttr callerLoc;
2478   if (parseLocationInstance(callerLoc))
2479     return failure();
2480 
2481   // Parse the ')'.
2482   if (parseToken(Token::r_paren, "expected ')' in callsite location"))
2483     return failure();
2484 
2485   // Return the callsite location.
2486   loc = CallSiteLoc::get(calleeLoc, callerLoc);
2487   return success();
2488 }
2489 
2490 ParseResult Parser::parseFusedLocation(LocationAttr &loc) {
2491   consumeToken(Token::bare_identifier);
2492 
2493   // Try to parse the optional metadata.
2494   Attribute metadata;
2495   if (consumeIf(Token::less)) {
2496     metadata = parseAttribute();
2497     if (!metadata)
2498       return emitError("expected valid attribute metadata");
2499     // Parse the '>' token.
2500     if (parseToken(Token::greater,
2501                    "expected '>' after fused location metadata"))
2502       return failure();
2503   }
2504 
2505   SmallVector<Location, 4> locations;
2506   auto parseElt = [&] {
2507     LocationAttr newLoc;
2508     if (parseLocationInstance(newLoc))
2509       return failure();
2510     locations.push_back(newLoc);
2511     return success();
2512   };
2513 
2514   if (parseToken(Token::l_square, "expected '[' in fused location") ||
2515       parseCommaSeparatedList(parseElt) ||
2516       parseToken(Token::r_square, "expected ']' in fused location"))
2517     return failure();
2518 
2519   // Return the fused location.
2520   loc = FusedLoc::get(locations, metadata, getContext());
2521   return success();
2522 }
2523 
2524 ParseResult Parser::parseNameOrFileLineColLocation(LocationAttr &loc) {
2525   auto *ctx = getContext();
2526   auto str = getToken().getStringValue();
2527   consumeToken(Token::string);
2528 
2529   // If the next token is ':' this is a filelinecol location.
2530   if (consumeIf(Token::colon)) {
2531     // Parse the line number.
2532     if (getToken().isNot(Token::integer))
2533       return emitError("expected integer line number in FileLineColLoc");
2534     auto line = getToken().getUnsignedIntegerValue();
2535     if (!line.hasValue())
2536       return emitError("expected integer line number in FileLineColLoc");
2537     consumeToken(Token::integer);
2538 
2539     // Parse the ':'.
2540     if (parseToken(Token::colon, "expected ':' in FileLineColLoc"))
2541       return failure();
2542 
2543     // Parse the column number.
2544     if (getToken().isNot(Token::integer))
2545       return emitError("expected integer column number in FileLineColLoc");
2546     auto column = getToken().getUnsignedIntegerValue();
2547     if (!column.hasValue())
2548       return emitError("expected integer column number in FileLineColLoc");
2549     consumeToken(Token::integer);
2550 
2551     loc = FileLineColLoc::get(str, line.getValue(), column.getValue(), ctx);
2552     return success();
2553   }
2554 
2555   // Otherwise, this is a NameLoc.
2556 
2557   // Check for a child location.
2558   if (consumeIf(Token::l_paren)) {
2559     auto childSourceLoc = getToken().getLoc();
2560 
2561     // Parse the child location.
2562     LocationAttr childLoc;
2563     if (parseLocationInstance(childLoc))
2564       return failure();
2565 
2566     // The child must not be another NameLoc.
2567     if (childLoc.isa<NameLoc>())
2568       return emitError(childSourceLoc,
2569                        "child of NameLoc cannot be another NameLoc");
2570     loc = NameLoc::get(Identifier::get(str, ctx), childLoc);
2571 
2572     // Parse the closing ')'.
2573     if (parseToken(Token::r_paren,
2574                    "expected ')' after child location of NameLoc"))
2575       return failure();
2576   } else {
2577     loc = NameLoc::get(Identifier::get(str, ctx), ctx);
2578   }
2579 
2580   return success();
2581 }
2582 
2583 ParseResult Parser::parseLocationInstance(LocationAttr &loc) {
2584   // Handle either name or filelinecol locations.
2585   if (getToken().is(Token::string))
2586     return parseNameOrFileLineColLocation(loc);
2587 
2588   // Bare tokens required for other cases.
2589   if (!getToken().is(Token::bare_identifier))
2590     return emitError("expected location instance");
2591 
2592   // Check for the 'callsite' signifying a callsite location.
2593   if (getToken().getSpelling() == "callsite")
2594     return parseCallSiteLocation(loc);
2595 
2596   // If the token is 'fused', then this is a fused location.
2597   if (getToken().getSpelling() == "fused")
2598     return parseFusedLocation(loc);
2599 
2600   // Check for a 'unknown' for an unknown location.
2601   if (getToken().getSpelling() == "unknown") {
2602     consumeToken(Token::bare_identifier);
2603     loc = UnknownLoc::get(getContext());
2604     return success();
2605   }
2606 
2607   return emitError("expected location instance");
2608 }
2609 
2610 //===----------------------------------------------------------------------===//
2611 // Affine parsing.
2612 //===----------------------------------------------------------------------===//
2613 
2614 /// Lower precedence ops (all at the same precedence level). LNoOp is false in
2615 /// the boolean sense.
2616 enum AffineLowPrecOp {
2617   /// Null value.
2618   LNoOp,
2619   Add,
2620   Sub
2621 };
2622 
2623 /// Higher precedence ops - all at the same precedence level. HNoOp is false
2624 /// in the boolean sense.
2625 enum AffineHighPrecOp {
2626   /// Null value.
2627   HNoOp,
2628   Mul,
2629   FloorDiv,
2630   CeilDiv,
2631   Mod
2632 };
2633 
2634 namespace {
2635 /// This is a specialized parser for affine structures (affine maps, affine
2636 /// expressions, and integer sets), maintaining the state transient to their
2637 /// bodies.
2638 class AffineParser : public Parser {
2639 public:
2640   AffineParser(ParserState &state, bool allowParsingSSAIds = false,
2641                function_ref<ParseResult(bool)> parseElement = nullptr)
2642       : Parser(state), allowParsingSSAIds(allowParsingSSAIds),
2643         parseElement(parseElement), numDimOperands(0), numSymbolOperands(0) {}
2644 
2645   AffineMap parseAffineMapRange(unsigned numDims, unsigned numSymbols);
2646   ParseResult parseAffineMapOrIntegerSetInline(AffineMap &map, IntegerSet &set);
2647   IntegerSet parseIntegerSetConstraints(unsigned numDims, unsigned numSymbols);
2648   ParseResult parseAffineMapOfSSAIds(AffineMap &map,
2649                                      OpAsmParser::Delimiter delimiter);
2650   void getDimsAndSymbolSSAIds(SmallVectorImpl<StringRef> &dimAndSymbolSSAIds,
2651                               unsigned &numDims);
2652 
2653 private:
2654   // Binary affine op parsing.
2655   AffineLowPrecOp consumeIfLowPrecOp();
2656   AffineHighPrecOp consumeIfHighPrecOp();
2657 
2658   // Identifier lists for polyhedral structures.
2659   ParseResult parseDimIdList(unsigned &numDims);
2660   ParseResult parseSymbolIdList(unsigned &numSymbols);
2661   ParseResult parseDimAndOptionalSymbolIdList(unsigned &numDims,
2662                                               unsigned &numSymbols);
2663   ParseResult parseIdentifierDefinition(AffineExpr idExpr);
2664 
2665   AffineExpr parseAffineExpr();
2666   AffineExpr parseParentheticalExpr();
2667   AffineExpr parseNegateExpression(AffineExpr lhs);
2668   AffineExpr parseIntegerExpr();
2669   AffineExpr parseBareIdExpr();
2670   AffineExpr parseSSAIdExpr(bool isSymbol);
2671   AffineExpr parseSymbolSSAIdExpr();
2672 
2673   AffineExpr getAffineBinaryOpExpr(AffineHighPrecOp op, AffineExpr lhs,
2674                                    AffineExpr rhs, SMLoc opLoc);
2675   AffineExpr getAffineBinaryOpExpr(AffineLowPrecOp op, AffineExpr lhs,
2676                                    AffineExpr rhs);
2677   AffineExpr parseAffineOperandExpr(AffineExpr lhs);
2678   AffineExpr parseAffineLowPrecOpExpr(AffineExpr llhs, AffineLowPrecOp llhsOp);
2679   AffineExpr parseAffineHighPrecOpExpr(AffineExpr llhs, AffineHighPrecOp llhsOp,
2680                                        SMLoc llhsOpLoc);
2681   AffineExpr parseAffineConstraint(bool *isEq);
2682 
2683 private:
2684   bool allowParsingSSAIds;
2685   function_ref<ParseResult(bool)> parseElement;
2686   unsigned numDimOperands;
2687   unsigned numSymbolOperands;
2688   SmallVector<std::pair<StringRef, AffineExpr>, 4> dimsAndSymbols;
2689 };
2690 } // end anonymous namespace
2691 
2692 /// Create an affine binary high precedence op expression (mul's, div's, mod).
2693 /// opLoc is the location of the op token to be used to report errors
2694 /// for non-conforming expressions.
2695 AffineExpr AffineParser::getAffineBinaryOpExpr(AffineHighPrecOp op,
2696                                                AffineExpr lhs, AffineExpr rhs,
2697                                                SMLoc opLoc) {
2698   // TODO: make the error location info accurate.
2699   switch (op) {
2700   case Mul:
2701     if (!lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant()) {
2702       emitError(opLoc, "non-affine expression: at least one of the multiply "
2703                        "operands has to be either a constant or symbolic");
2704       return nullptr;
2705     }
2706     return lhs * rhs;
2707   case FloorDiv:
2708     if (!rhs.isSymbolicOrConstant()) {
2709       emitError(opLoc, "non-affine expression: right operand of floordiv "
2710                        "has to be either a constant or symbolic");
2711       return nullptr;
2712     }
2713     return lhs.floorDiv(rhs);
2714   case CeilDiv:
2715     if (!rhs.isSymbolicOrConstant()) {
2716       emitError(opLoc, "non-affine expression: right operand of ceildiv "
2717                        "has to be either a constant or symbolic");
2718       return nullptr;
2719     }
2720     return lhs.ceilDiv(rhs);
2721   case Mod:
2722     if (!rhs.isSymbolicOrConstant()) {
2723       emitError(opLoc, "non-affine expression: right operand of mod "
2724                        "has to be either a constant or symbolic");
2725       return nullptr;
2726     }
2727     return lhs % rhs;
2728   case HNoOp:
2729     llvm_unreachable("can't create affine expression for null high prec op");
2730     return nullptr;
2731   }
2732   llvm_unreachable("Unknown AffineHighPrecOp");
2733 }
2734 
2735 /// Create an affine binary low precedence op expression (add, sub).
2736 AffineExpr AffineParser::getAffineBinaryOpExpr(AffineLowPrecOp op,
2737                                                AffineExpr lhs, AffineExpr rhs) {
2738   switch (op) {
2739   case AffineLowPrecOp::Add:
2740     return lhs + rhs;
2741   case AffineLowPrecOp::Sub:
2742     return lhs - rhs;
2743   case AffineLowPrecOp::LNoOp:
2744     llvm_unreachable("can't create affine expression for null low prec op");
2745     return nullptr;
2746   }
2747   llvm_unreachable("Unknown AffineLowPrecOp");
2748 }
2749 
2750 /// Consume this token if it is a lower precedence affine op (there are only
2751 /// two precedence levels).
2752 AffineLowPrecOp AffineParser::consumeIfLowPrecOp() {
2753   switch (getToken().getKind()) {
2754   case Token::plus:
2755     consumeToken(Token::plus);
2756     return AffineLowPrecOp::Add;
2757   case Token::minus:
2758     consumeToken(Token::minus);
2759     return AffineLowPrecOp::Sub;
2760   default:
2761     return AffineLowPrecOp::LNoOp;
2762   }
2763 }
2764 
2765 /// Consume this token if it is a higher precedence affine op (there are only
2766 /// two precedence levels)
2767 AffineHighPrecOp AffineParser::consumeIfHighPrecOp() {
2768   switch (getToken().getKind()) {
2769   case Token::star:
2770     consumeToken(Token::star);
2771     return Mul;
2772   case Token::kw_floordiv:
2773     consumeToken(Token::kw_floordiv);
2774     return FloorDiv;
2775   case Token::kw_ceildiv:
2776     consumeToken(Token::kw_ceildiv);
2777     return CeilDiv;
2778   case Token::kw_mod:
2779     consumeToken(Token::kw_mod);
2780     return Mod;
2781   default:
2782     return HNoOp;
2783   }
2784 }
2785 
2786 /// Parse a high precedence op expression list: mul, div, and mod are high
2787 /// precedence binary ops, i.e., parse a
2788 ///   expr_1 op_1 expr_2 op_2 ... expr_n
2789 /// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
2790 /// All affine binary ops are left associative.
2791 /// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
2792 /// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
2793 /// null. llhsOpLoc is the location of the llhsOp token that will be used to
2794 /// report an error for non-conforming expressions.
2795 AffineExpr AffineParser::parseAffineHighPrecOpExpr(AffineExpr llhs,
2796                                                    AffineHighPrecOp llhsOp,
2797                                                    SMLoc llhsOpLoc) {
2798   AffineExpr lhs = parseAffineOperandExpr(llhs);
2799   if (!lhs)
2800     return nullptr;
2801 
2802   // Found an LHS. Parse the remaining expression.
2803   auto opLoc = getToken().getLoc();
2804   if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
2805     if (llhs) {
2806       AffineExpr expr = getAffineBinaryOpExpr(llhsOp, llhs, lhs, opLoc);
2807       if (!expr)
2808         return nullptr;
2809       return parseAffineHighPrecOpExpr(expr, op, opLoc);
2810     }
2811     // No LLHS, get RHS
2812     return parseAffineHighPrecOpExpr(lhs, op, opLoc);
2813   }
2814 
2815   // This is the last operand in this expression.
2816   if (llhs)
2817     return getAffineBinaryOpExpr(llhsOp, llhs, lhs, llhsOpLoc);
2818 
2819   // No llhs, 'lhs' itself is the expression.
2820   return lhs;
2821 }
2822 
2823 /// Parse an affine expression inside parentheses.
2824 ///
2825 ///   affine-expr ::= `(` affine-expr `)`
2826 AffineExpr AffineParser::parseParentheticalExpr() {
2827   if (parseToken(Token::l_paren, "expected '('"))
2828     return nullptr;
2829   if (getToken().is(Token::r_paren))
2830     return (emitError("no expression inside parentheses"), nullptr);
2831 
2832   auto expr = parseAffineExpr();
2833   if (!expr)
2834     return nullptr;
2835   if (parseToken(Token::r_paren, "expected ')'"))
2836     return nullptr;
2837 
2838   return expr;
2839 }
2840 
2841 /// Parse the negation expression.
2842 ///
2843 ///   affine-expr ::= `-` affine-expr
2844 AffineExpr AffineParser::parseNegateExpression(AffineExpr lhs) {
2845   if (parseToken(Token::minus, "expected '-'"))
2846     return nullptr;
2847 
2848   AffineExpr operand = parseAffineOperandExpr(lhs);
2849   // Since negation has the highest precedence of all ops (including high
2850   // precedence ops) but lower than parentheses, we are only going to use
2851   // parseAffineOperandExpr instead of parseAffineExpr here.
2852   if (!operand)
2853     // Extra error message although parseAffineOperandExpr would have
2854     // complained. Leads to a better diagnostic.
2855     return (emitError("missing operand of negation"), nullptr);
2856   return (-1) * operand;
2857 }
2858 
2859 /// Parse a bare id that may appear in an affine expression.
2860 ///
2861 ///   affine-expr ::= bare-id
2862 AffineExpr AffineParser::parseBareIdExpr() {
2863   if (getToken().isNot(Token::bare_identifier))
2864     return (emitError("expected bare identifier"), nullptr);
2865 
2866   StringRef sRef = getTokenSpelling();
2867   for (auto entry : dimsAndSymbols) {
2868     if (entry.first == sRef) {
2869       consumeToken(Token::bare_identifier);
2870       return entry.second;
2871     }
2872   }
2873 
2874   return (emitError("use of undeclared identifier"), nullptr);
2875 }
2876 
2877 /// Parse an SSA id which may appear in an affine expression.
2878 AffineExpr AffineParser::parseSSAIdExpr(bool isSymbol) {
2879   if (!allowParsingSSAIds)
2880     return (emitError("unexpected ssa identifier"), nullptr);
2881   if (getToken().isNot(Token::percent_identifier))
2882     return (emitError("expected ssa identifier"), nullptr);
2883   auto name = getTokenSpelling();
2884   // Check if we already parsed this SSA id.
2885   for (auto entry : dimsAndSymbols) {
2886     if (entry.first == name) {
2887       consumeToken(Token::percent_identifier);
2888       return entry.second;
2889     }
2890   }
2891   // Parse the SSA id and add an AffineDim/SymbolExpr to represent it.
2892   if (parseElement(isSymbol))
2893     return (emitError("failed to parse ssa identifier"), nullptr);
2894   auto idExpr = isSymbol
2895                     ? getAffineSymbolExpr(numSymbolOperands++, getContext())
2896                     : getAffineDimExpr(numDimOperands++, getContext());
2897   dimsAndSymbols.push_back({name, idExpr});
2898   return idExpr;
2899 }
2900 
2901 AffineExpr AffineParser::parseSymbolSSAIdExpr() {
2902   if (parseToken(Token::kw_symbol, "expected symbol keyword") ||
2903       parseToken(Token::l_paren, "expected '(' at start of SSA symbol"))
2904     return nullptr;
2905   AffineExpr symbolExpr = parseSSAIdExpr(/*isSymbol=*/true);
2906   if (!symbolExpr)
2907     return nullptr;
2908   if (parseToken(Token::r_paren, "expected ')' at end of SSA symbol"))
2909     return nullptr;
2910   return symbolExpr;
2911 }
2912 
2913 /// Parse a positive integral constant appearing in an affine expression.
2914 ///
2915 ///   affine-expr ::= integer-literal
2916 AffineExpr AffineParser::parseIntegerExpr() {
2917   auto val = getToken().getUInt64IntegerValue();
2918   if (!val.hasValue() || (int64_t)val.getValue() < 0)
2919     return (emitError("constant too large for index"), nullptr);
2920 
2921   consumeToken(Token::integer);
2922   return builder.getAffineConstantExpr((int64_t)val.getValue());
2923 }
2924 
2925 /// Parses an expression that can be a valid operand of an affine expression.
2926 /// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
2927 /// operator, the rhs of which is being parsed. This is used to determine
2928 /// whether an error should be emitted for a missing right operand.
2929 //  Eg: for an expression without parentheses (like i + j + k + l), each
2930 //  of the four identifiers is an operand. For i + j*k + l, j*k is not an
2931 //  operand expression, it's an op expression and will be parsed via
2932 //  parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and
2933 //  -l are valid operands that will be parsed by this function.
2934 AffineExpr AffineParser::parseAffineOperandExpr(AffineExpr lhs) {
2935   switch (getToken().getKind()) {
2936   case Token::bare_identifier:
2937     return parseBareIdExpr();
2938   case Token::kw_symbol:
2939     return parseSymbolSSAIdExpr();
2940   case Token::percent_identifier:
2941     return parseSSAIdExpr(/*isSymbol=*/false);
2942   case Token::integer:
2943     return parseIntegerExpr();
2944   case Token::l_paren:
2945     return parseParentheticalExpr();
2946   case Token::minus:
2947     return parseNegateExpression(lhs);
2948   case Token::kw_ceildiv:
2949   case Token::kw_floordiv:
2950   case Token::kw_mod:
2951   case Token::plus:
2952   case Token::star:
2953     if (lhs)
2954       emitError("missing right operand of binary operator");
2955     else
2956       emitError("missing left operand of binary operator");
2957     return nullptr;
2958   default:
2959     if (lhs)
2960       emitError("missing right operand of binary operator");
2961     else
2962       emitError("expected affine expression");
2963     return nullptr;
2964   }
2965 }
2966 
2967 /// Parse affine expressions that are bare-id's, integer constants,
2968 /// parenthetical affine expressions, and affine op expressions that are a
2969 /// composition of those.
2970 ///
2971 /// All binary op's associate from left to right.
2972 ///
2973 /// {add, sub} have lower precedence than {mul, div, and mod}.
2974 ///
2975 /// Add, sub'are themselves at the same precedence level. Mul, floordiv,
2976 /// ceildiv, and mod are at the same higher precedence level. Negation has
2977 /// higher precedence than any binary op.
2978 ///
2979 /// llhs: the affine expression appearing on the left of the one being parsed.
2980 /// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
2981 /// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned
2982 /// if llhs is non-null; otherwise lhs is returned. This is to deal with left
2983 /// associativity.
2984 ///
2985 /// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
2986 /// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where
2987 /// (e2*e3) will be parsed using parseAffineHighPrecOpExpr().
2988 AffineExpr AffineParser::parseAffineLowPrecOpExpr(AffineExpr llhs,
2989                                                   AffineLowPrecOp llhsOp) {
2990   AffineExpr lhs;
2991   if (!(lhs = parseAffineOperandExpr(llhs)))
2992     return nullptr;
2993 
2994   // Found an LHS. Deal with the ops.
2995   if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
2996     if (llhs) {
2997       AffineExpr sum = getAffineBinaryOpExpr(llhsOp, llhs, lhs);
2998       return parseAffineLowPrecOpExpr(sum, lOp);
2999     }
3000     // No LLHS, get RHS and form the expression.
3001     return parseAffineLowPrecOpExpr(lhs, lOp);
3002   }
3003   auto opLoc = getToken().getLoc();
3004   if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
3005     // We have a higher precedence op here. Get the rhs operand for the llhs
3006     // through parseAffineHighPrecOpExpr.
3007     AffineExpr highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc);
3008     if (!highRes)
3009       return nullptr;
3010 
3011     // If llhs is null, the product forms the first operand of the yet to be
3012     // found expression. If non-null, the op to associate with llhs is llhsOp.
3013     AffineExpr expr =
3014         llhs ? getAffineBinaryOpExpr(llhsOp, llhs, highRes) : highRes;
3015 
3016     // Recurse for subsequent low prec op's after the affine high prec op
3017     // expression.
3018     if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
3019       return parseAffineLowPrecOpExpr(expr, nextOp);
3020     return expr;
3021   }
3022   // Last operand in the expression list.
3023   if (llhs)
3024     return getAffineBinaryOpExpr(llhsOp, llhs, lhs);
3025   // No llhs, 'lhs' itself is the expression.
3026   return lhs;
3027 }
3028 
3029 /// Parse an affine expression.
3030 ///  affine-expr ::= `(` affine-expr `)`
3031 ///                | `-` affine-expr
3032 ///                | affine-expr `+` affine-expr
3033 ///                | affine-expr `-` affine-expr
3034 ///                | affine-expr `*` affine-expr
3035 ///                | affine-expr `floordiv` affine-expr
3036 ///                | affine-expr `ceildiv` affine-expr
3037 ///                | affine-expr `mod` affine-expr
3038 ///                | bare-id
3039 ///                | integer-literal
3040 ///
3041 /// Additional conditions are checked depending on the production. For eg.,
3042 /// one of the operands for `*` has to be either constant/symbolic; the second
3043 /// operand for floordiv, ceildiv, and mod has to be a positive integer.
3044 AffineExpr AffineParser::parseAffineExpr() {
3045   return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
3046 }
3047 
3048 /// Parse a dim or symbol from the lists appearing before the actual
3049 /// expressions of the affine map. Update our state to store the
3050 /// dimensional/symbolic identifier.
3051 ParseResult AffineParser::parseIdentifierDefinition(AffineExpr idExpr) {
3052   if (getToken().isNot(Token::bare_identifier))
3053     return emitError("expected bare identifier");
3054 
3055   auto name = getTokenSpelling();
3056   for (auto entry : dimsAndSymbols) {
3057     if (entry.first == name)
3058       return emitError("redefinition of identifier '" + name + "'");
3059   }
3060   consumeToken(Token::bare_identifier);
3061 
3062   dimsAndSymbols.push_back({name, idExpr});
3063   return success();
3064 }
3065 
3066 /// Parse the list of dimensional identifiers to an affine map.
3067 ParseResult AffineParser::parseDimIdList(unsigned &numDims) {
3068   if (parseToken(Token::l_paren,
3069                  "expected '(' at start of dimensional identifiers list")) {
3070     return failure();
3071   }
3072 
3073   auto parseElt = [&]() -> ParseResult {
3074     auto dimension = getAffineDimExpr(numDims++, getContext());
3075     return parseIdentifierDefinition(dimension);
3076   };
3077   return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
3078 }
3079 
3080 /// Parse the list of symbolic identifiers to an affine map.
3081 ParseResult AffineParser::parseSymbolIdList(unsigned &numSymbols) {
3082   consumeToken(Token::l_square);
3083   auto parseElt = [&]() -> ParseResult {
3084     auto symbol = getAffineSymbolExpr(numSymbols++, getContext());
3085     return parseIdentifierDefinition(symbol);
3086   };
3087   return parseCommaSeparatedListUntil(Token::r_square, parseElt);
3088 }
3089 
3090 /// Parse the list of symbolic identifiers to an affine map.
3091 ParseResult
3092 AffineParser::parseDimAndOptionalSymbolIdList(unsigned &numDims,
3093                                               unsigned &numSymbols) {
3094   if (parseDimIdList(numDims)) {
3095     return failure();
3096   }
3097   if (!getToken().is(Token::l_square)) {
3098     numSymbols = 0;
3099     return success();
3100   }
3101   return parseSymbolIdList(numSymbols);
3102 }
3103 
3104 /// Parses an ambiguous affine map or integer set definition inline.
3105 ParseResult AffineParser::parseAffineMapOrIntegerSetInline(AffineMap &map,
3106                                                            IntegerSet &set) {
3107   unsigned numDims = 0, numSymbols = 0;
3108 
3109   // List of dimensional and optional symbol identifiers.
3110   if (parseDimAndOptionalSymbolIdList(numDims, numSymbols)) {
3111     return failure();
3112   }
3113 
3114   // This is needed for parsing attributes as we wouldn't know whether we would
3115   // be parsing an integer set attribute or an affine map attribute.
3116   bool isArrow = getToken().is(Token::arrow);
3117   bool isColon = getToken().is(Token::colon);
3118   if (!isArrow && !isColon) {
3119     return emitError("expected '->' or ':'");
3120   } else if (isArrow) {
3121     parseToken(Token::arrow, "expected '->' or '['");
3122     map = parseAffineMapRange(numDims, numSymbols);
3123     return map ? success() : failure();
3124   } else if (parseToken(Token::colon, "expected ':' or '['")) {
3125     return failure();
3126   }
3127 
3128   if ((set = parseIntegerSetConstraints(numDims, numSymbols)))
3129     return success();
3130 
3131   return failure();
3132 }
3133 
3134 /// Parse an AffineMap where the dim and symbol identifiers are SSA ids.
3135 ParseResult
3136 AffineParser::parseAffineMapOfSSAIds(AffineMap &map,
3137                                      OpAsmParser::Delimiter delimiter) {
3138   Token::Kind rightToken;
3139   switch (delimiter) {
3140   case OpAsmParser::Delimiter::Square:
3141     if (parseToken(Token::l_square, "expected '['"))
3142       return failure();
3143     rightToken = Token::r_square;
3144     break;
3145   case OpAsmParser::Delimiter::Paren:
3146     if (parseToken(Token::l_paren, "expected '('"))
3147       return failure();
3148     rightToken = Token::r_paren;
3149     break;
3150   default:
3151     return emitError("unexpected delimiter");
3152   }
3153 
3154   SmallVector<AffineExpr, 4> exprs;
3155   auto parseElt = [&]() -> ParseResult {
3156     auto elt = parseAffineExpr();
3157     exprs.push_back(elt);
3158     return elt ? success() : failure();
3159   };
3160 
3161   // Parse a multi-dimensional affine expression (a comma-separated list of
3162   // 1-d affine expressions); the list can be empty. Grammar:
3163   // multi-dim-affine-expr ::= `(` `)`
3164   //                         | `(` affine-expr (`,` affine-expr)* `)`
3165   if (parseCommaSeparatedListUntil(rightToken, parseElt,
3166                                    /*allowEmptyList=*/true))
3167     return failure();
3168   // Parsed a valid affine map.
3169   map = AffineMap::get(numDimOperands, dimsAndSymbols.size() - numDimOperands,
3170                        exprs, getContext());
3171   return success();
3172 }
3173 
3174 /// Parse the range and sizes affine map definition inline.
3175 ///
3176 ///  affine-map ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
3177 ///
3178 ///  multi-dim-affine-expr ::= `(` `)`
3179 ///  multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)`
3180 AffineMap AffineParser::parseAffineMapRange(unsigned numDims,
3181                                             unsigned numSymbols) {
3182   parseToken(Token::l_paren, "expected '(' at start of affine map range");
3183 
3184   SmallVector<AffineExpr, 4> exprs;
3185   auto parseElt = [&]() -> ParseResult {
3186     auto elt = parseAffineExpr();
3187     ParseResult res = elt ? success() : failure();
3188     exprs.push_back(elt);
3189     return res;
3190   };
3191 
3192   // Parse a multi-dimensional affine expression (a comma-separated list of
3193   // 1-d affine expressions). Grammar:
3194   // multi-dim-affine-expr ::= `(` `)`
3195   //                         | `(` affine-expr (`,` affine-expr)* `)`
3196   if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true))
3197     return AffineMap();
3198 
3199   // Parsed a valid affine map.
3200   return AffineMap::get(numDims, numSymbols, exprs, getContext());
3201 }
3202 
3203 /// Parse an affine constraint.
3204 ///  affine-constraint ::= affine-expr `>=` `0`
3205 ///                      | affine-expr `==` `0`
3206 ///
3207 /// isEq is set to true if the parsed constraint is an equality, false if it
3208 /// is an inequality (greater than or equal).
3209 ///
3210 AffineExpr AffineParser::parseAffineConstraint(bool *isEq) {
3211   AffineExpr expr = parseAffineExpr();
3212   if (!expr)
3213     return nullptr;
3214 
3215   if (consumeIf(Token::greater) && consumeIf(Token::equal) &&
3216       getToken().is(Token::integer)) {
3217     auto dim = getToken().getUnsignedIntegerValue();
3218     if (dim.hasValue() && dim.getValue() == 0) {
3219       consumeToken(Token::integer);
3220       *isEq = false;
3221       return expr;
3222     }
3223     return (emitError("expected '0' after '>='"), nullptr);
3224   }
3225 
3226   if (consumeIf(Token::equal) && consumeIf(Token::equal) &&
3227       getToken().is(Token::integer)) {
3228     auto dim = getToken().getUnsignedIntegerValue();
3229     if (dim.hasValue() && dim.getValue() == 0) {
3230       consumeToken(Token::integer);
3231       *isEq = true;
3232       return expr;
3233     }
3234     return (emitError("expected '0' after '=='"), nullptr);
3235   }
3236 
3237   return (emitError("expected '== 0' or '>= 0' at end of affine constraint"),
3238           nullptr);
3239 }
3240 
3241 /// Parse the constraints that are part of an integer set definition.
3242 ///  integer-set-inline
3243 ///                ::= dim-and-symbol-id-lists `:`
3244 ///                '(' affine-constraint-conjunction? ')'
3245 ///  affine-constraint-conjunction ::= affine-constraint (`,`
3246 ///                                       affine-constraint)*
3247 ///
3248 IntegerSet AffineParser::parseIntegerSetConstraints(unsigned numDims,
3249                                                     unsigned numSymbols) {
3250   if (parseToken(Token::l_paren,
3251                  "expected '(' at start of integer set constraint list"))
3252     return IntegerSet();
3253 
3254   SmallVector<AffineExpr, 4> constraints;
3255   SmallVector<bool, 4> isEqs;
3256   auto parseElt = [&]() -> ParseResult {
3257     bool isEq;
3258     auto elt = parseAffineConstraint(&isEq);
3259     ParseResult res = elt ? success() : failure();
3260     if (elt) {
3261       constraints.push_back(elt);
3262       isEqs.push_back(isEq);
3263     }
3264     return res;
3265   };
3266 
3267   // Parse a list of affine constraints (comma-separated).
3268   if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true))
3269     return IntegerSet();
3270 
3271   // If no constraints were parsed, then treat this as a degenerate 'true' case.
3272   if (constraints.empty()) {
3273     /* 0 == 0 */
3274     auto zero = getAffineConstantExpr(0, getContext());
3275     return IntegerSet::get(numDims, numSymbols, zero, true);
3276   }
3277 
3278   // Parsed a valid integer set.
3279   return IntegerSet::get(numDims, numSymbols, constraints, isEqs);
3280 }
3281 
3282 /// Parse an ambiguous reference to either and affine map or an integer set.
3283 ParseResult Parser::parseAffineMapOrIntegerSetReference(AffineMap &map,
3284                                                         IntegerSet &set) {
3285   return AffineParser(state).parseAffineMapOrIntegerSetInline(map, set);
3286 }
3287 ParseResult Parser::parseAffineMapReference(AffineMap &map) {
3288   llvm::SMLoc curLoc = getToken().getLoc();
3289   IntegerSet set;
3290   if (parseAffineMapOrIntegerSetReference(map, set))
3291     return failure();
3292   if (set)
3293     return emitError(curLoc, "expected AffineMap, but got IntegerSet");
3294   return success();
3295 }
3296 ParseResult Parser::parseIntegerSetReference(IntegerSet &set) {
3297   llvm::SMLoc curLoc = getToken().getLoc();
3298   AffineMap map;
3299   if (parseAffineMapOrIntegerSetReference(map, set))
3300     return failure();
3301   if (map)
3302     return emitError(curLoc, "expected IntegerSet, but got AffineMap");
3303   return success();
3304 }
3305 
3306 /// Parse an AffineMap of SSA ids. The callback 'parseElement' is used to
3307 /// parse SSA value uses encountered while parsing affine expressions.
3308 ParseResult
3309 Parser::parseAffineMapOfSSAIds(AffineMap &map,
3310                                function_ref<ParseResult(bool)> parseElement,
3311                                OpAsmParser::Delimiter delimiter) {
3312   return AffineParser(state, /*allowParsingSSAIds=*/true, parseElement)
3313       .parseAffineMapOfSSAIds(map, delimiter);
3314 }
3315 
3316 //===----------------------------------------------------------------------===//
3317 // OperationParser
3318 //===----------------------------------------------------------------------===//
3319 
3320 namespace {
3321 /// This class provides support for parsing operations and regions of
3322 /// operations.
3323 class OperationParser : public Parser {
3324 public:
3325   OperationParser(ParserState &state, ModuleOp moduleOp)
3326       : Parser(state), opBuilder(moduleOp.getBodyRegion()), moduleOp(moduleOp) {
3327   }
3328 
3329   ~OperationParser();
3330 
3331   /// After parsing is finished, this function must be called to see if there
3332   /// are any remaining issues.
3333   ParseResult finalize();
3334 
3335   //===--------------------------------------------------------------------===//
3336   // SSA Value Handling
3337   //===--------------------------------------------------------------------===//
3338 
3339   /// This represents a use of an SSA value in the program.  The first two
3340   /// entries in the tuple are the name and result number of a reference.  The
3341   /// third is the location of the reference, which is used in case this ends
3342   /// up being a use of an undefined value.
3343   struct SSAUseInfo {
3344     StringRef name;  // Value name, e.g. %42 or %abc
3345     unsigned number; // Number, specified with #12
3346     SMLoc loc;       // Location of first definition or use.
3347   };
3348 
3349   /// Push a new SSA name scope to the parser.
3350   void pushSSANameScope(bool isIsolated);
3351 
3352   /// Pop the last SSA name scope from the parser.
3353   ParseResult popSSANameScope();
3354 
3355   /// Register a definition of a value with the symbol table.
3356   ParseResult addDefinition(SSAUseInfo useInfo, Value value);
3357 
3358   /// Parse an optional list of SSA uses into 'results'.
3359   ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
3360 
3361   /// Parse a single SSA use into 'result'.
3362   ParseResult parseSSAUse(SSAUseInfo &result);
3363 
3364   /// Given a reference to an SSA value and its type, return a reference. This
3365   /// returns null on failure.
3366   Value resolveSSAUse(SSAUseInfo useInfo, Type type);
3367 
3368   ParseResult parseSSADefOrUseAndType(
3369       const std::function<ParseResult(SSAUseInfo, Type)> &action);
3370 
3371   ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value> &results);
3372 
3373   /// Return the location of the value identified by its name and number if it
3374   /// has been already reference.
3375   Optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) {
3376     auto &values = isolatedNameScopes.back().values;
3377     if (!values.count(name) || number >= values[name].size())
3378       return {};
3379     if (values[name][number].first)
3380       return values[name][number].second;
3381     return {};
3382   }
3383 
3384   //===--------------------------------------------------------------------===//
3385   // Operation Parsing
3386   //===--------------------------------------------------------------------===//
3387 
3388   /// Parse an operation instance.
3389   ParseResult parseOperation();
3390 
3391   /// Parse a single operation successor.
3392   ParseResult parseSuccessor(Block *&dest);
3393 
3394   /// Parse a comma-separated list of operation successors in brackets.
3395   ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations);
3396 
3397   /// Parse an operation instance that is in the generic form.
3398   Operation *parseGenericOperation();
3399 
3400   /// Parse an operation instance that is in the generic form and insert it at
3401   /// the provided insertion point.
3402   Operation *parseGenericOperation(Block *insertBlock,
3403                                    Block::iterator insertPt);
3404 
3405   /// This is the structure of a result specifier in the assembly syntax,
3406   /// including the name, number of results, and location.
3407   typedef std::tuple<StringRef, unsigned, SMLoc> ResultRecord;
3408 
3409   /// Parse an operation instance that is in the op-defined custom form.
3410   /// resultInfo specifies information about the "%name =" specifiers.
3411   Operation *parseCustomOperation(ArrayRef<ResultRecord> resultInfo);
3412 
3413   //===--------------------------------------------------------------------===//
3414   // Region Parsing
3415   //===--------------------------------------------------------------------===//
3416 
3417   /// Parse a region into 'region' with the provided entry block arguments.
3418   /// 'isIsolatedNameScope' indicates if the naming scope of this region is
3419   /// isolated from those above.
3420   ParseResult parseRegion(Region &region,
3421                           ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments,
3422                           bool isIsolatedNameScope = false);
3423 
3424   /// Parse a region body into 'region'.
3425   ParseResult parseRegionBody(Region &region);
3426 
3427   //===--------------------------------------------------------------------===//
3428   // Block Parsing
3429   //===--------------------------------------------------------------------===//
3430 
3431   /// Parse a new block into 'block'.
3432   ParseResult parseBlock(Block *&block);
3433 
3434   /// Parse a list of operations into 'block'.
3435   ParseResult parseBlockBody(Block *block);
3436 
3437   /// Parse a (possibly empty) list of block arguments.
3438   ParseResult parseOptionalBlockArgList(SmallVectorImpl<BlockArgument> &results,
3439                                         Block *owner);
3440 
3441   /// Get the block with the specified name, creating it if it doesn't
3442   /// already exist.  The location specified is the point of use, which allows
3443   /// us to diagnose references to blocks that are not defined precisely.
3444   Block *getBlockNamed(StringRef name, SMLoc loc);
3445 
3446   /// Define the block with the specified name. Returns the Block* or nullptr in
3447   /// the case of redefinition.
3448   Block *defineBlockNamed(StringRef name, SMLoc loc, Block *existing);
3449 
3450 private:
3451   /// Returns the info for a block at the current scope for the given name.
3452   std::pair<Block *, SMLoc> &getBlockInfoByName(StringRef name) {
3453     return blocksByName.back()[name];
3454   }
3455 
3456   /// Insert a new forward reference to the given block.
3457   void insertForwardRef(Block *block, SMLoc loc) {
3458     forwardRef.back().try_emplace(block, loc);
3459   }
3460 
3461   /// Erase any forward reference to the given block.
3462   bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); }
3463 
3464   /// Record that a definition was added at the current scope.
3465   void recordDefinition(StringRef def);
3466 
3467   /// Get the value entry for the given SSA name.
3468   SmallVectorImpl<std::pair<Value, SMLoc>> &getSSAValueEntry(StringRef name);
3469 
3470   /// Create a forward reference placeholder value with the given location and
3471   /// result type.
3472   Value createForwardRefPlaceholder(SMLoc loc, Type type);
3473 
3474   /// Return true if this is a forward reference.
3475   bool isForwardRefPlaceholder(Value value) {
3476     return forwardRefPlaceholders.count(value);
3477   }
3478 
3479   /// This struct represents an isolated SSA name scope. This scope may contain
3480   /// other nested non-isolated scopes. These scopes are used for operations
3481   /// that are known to be isolated to allow for reusing names within their
3482   /// regions, even if those names are used above.
3483   struct IsolatedSSANameScope {
3484     /// Record that a definition was added at the current scope.
3485     void recordDefinition(StringRef def) {
3486       definitionsPerScope.back().insert(def);
3487     }
3488 
3489     /// Push a nested name scope.
3490     void pushSSANameScope() { definitionsPerScope.push_back({}); }
3491 
3492     /// Pop a nested name scope.
3493     void popSSANameScope() {
3494       for (auto &def : definitionsPerScope.pop_back_val())
3495         values.erase(def.getKey());
3496     }
3497 
3498     /// This keeps track of all of the SSA values we are tracking for each name
3499     /// scope, indexed by their name. This has one entry per result number.
3500     llvm::StringMap<SmallVector<std::pair<Value, SMLoc>, 1>> values;
3501 
3502     /// This keeps track of all of the values defined by a specific name scope.
3503     SmallVector<llvm::StringSet<>, 2> definitionsPerScope;
3504   };
3505 
3506   /// A list of isolated name scopes.
3507   SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes;
3508 
3509   /// This keeps track of the block names as well as the location of the first
3510   /// reference for each nested name scope. This is used to diagnose invalid
3511   /// block references and memorize them.
3512   SmallVector<DenseMap<StringRef, std::pair<Block *, SMLoc>>, 2> blocksByName;
3513   SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef;
3514 
3515   /// These are all of the placeholders we've made along with the location of
3516   /// their first reference, to allow checking for use of undefined values.
3517   DenseMap<Value, SMLoc> forwardRefPlaceholders;
3518 
3519   /// The builder used when creating parsed operation instances.
3520   OpBuilder opBuilder;
3521 
3522   /// The top level module operation.
3523   ModuleOp moduleOp;
3524 };
3525 } // end anonymous namespace
3526 
3527 OperationParser::~OperationParser() {
3528   for (auto &fwd : forwardRefPlaceholders) {
3529     // Drop all uses of undefined forward declared reference and destroy
3530     // defining operation.
3531     fwd.first.dropAllUses();
3532     fwd.first.getDefiningOp()->destroy();
3533   }
3534 }
3535 
3536 /// After parsing is finished, this function must be called to see if there are
3537 /// any remaining issues.
3538 ParseResult OperationParser::finalize() {
3539   // Check for any forward references that are left.  If we find any, error
3540   // out.
3541   if (!forwardRefPlaceholders.empty()) {
3542     SmallVector<const char *, 4> errors;
3543     // Iteration over the map isn't deterministic, so sort by source location.
3544     for (auto entry : forwardRefPlaceholders)
3545       errors.push_back(entry.second.getPointer());
3546     llvm::array_pod_sort(errors.begin(), errors.end());
3547 
3548     for (auto entry : errors) {
3549       auto loc = SMLoc::getFromPointer(entry);
3550       emitError(loc, "use of undeclared SSA value name");
3551     }
3552     return failure();
3553   }
3554 
3555   return success();
3556 }
3557 
3558 //===----------------------------------------------------------------------===//
3559 // SSA Value Handling
3560 //===----------------------------------------------------------------------===//
3561 
3562 void OperationParser::pushSSANameScope(bool isIsolated) {
3563   blocksByName.push_back(DenseMap<StringRef, std::pair<Block *, SMLoc>>());
3564   forwardRef.push_back(DenseMap<Block *, SMLoc>());
3565 
3566   // Push back a new name definition scope.
3567   if (isIsolated)
3568     isolatedNameScopes.push_back({});
3569   isolatedNameScopes.back().pushSSANameScope();
3570 }
3571 
3572 ParseResult OperationParser::popSSANameScope() {
3573   auto forwardRefInCurrentScope = forwardRef.pop_back_val();
3574 
3575   // Verify that all referenced blocks were defined.
3576   if (!forwardRefInCurrentScope.empty()) {
3577     SmallVector<std::pair<const char *, Block *>, 4> errors;
3578     // Iteration over the map isn't deterministic, so sort by source location.
3579     for (auto entry : forwardRefInCurrentScope) {
3580       errors.push_back({entry.second.getPointer(), entry.first});
3581       // Add this block to the top-level region to allow for automatic cleanup.
3582       moduleOp.getOperation()->getRegion(0).push_back(entry.first);
3583     }
3584     llvm::array_pod_sort(errors.begin(), errors.end());
3585 
3586     for (auto entry : errors) {
3587       auto loc = SMLoc::getFromPointer(entry.first);
3588       emitError(loc, "reference to an undefined block");
3589     }
3590     return failure();
3591   }
3592 
3593   // Pop the next nested namescope. If there is only one internal namescope,
3594   // just pop the isolated scope.
3595   auto &currentNameScope = isolatedNameScopes.back();
3596   if (currentNameScope.definitionsPerScope.size() == 1)
3597     isolatedNameScopes.pop_back();
3598   else
3599     currentNameScope.popSSANameScope();
3600 
3601   blocksByName.pop_back();
3602   return success();
3603 }
3604 
3605 /// Register a definition of a value with the symbol table.
3606 ParseResult OperationParser::addDefinition(SSAUseInfo useInfo, Value value) {
3607   auto &entries = getSSAValueEntry(useInfo.name);
3608 
3609   // Make sure there is a slot for this value.
3610   if (entries.size() <= useInfo.number)
3611     entries.resize(useInfo.number + 1);
3612 
3613   // If we already have an entry for this, check to see if it was a definition
3614   // or a forward reference.
3615   if (auto existing = entries[useInfo.number].first) {
3616     if (!isForwardRefPlaceholder(existing)) {
3617       return emitError(useInfo.loc)
3618           .append("redefinition of SSA value '", useInfo.name, "'")
3619           .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3620           .append("previously defined here");
3621     }
3622 
3623     if (existing.getType() != value.getType()) {
3624       return emitError(useInfo.loc)
3625           .append("definition of SSA value '", useInfo.name, "#",
3626                   useInfo.number, "' has type ", value.getType())
3627           .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3628           .append("previously used here with type ", existing.getType());
3629     }
3630 
3631     // If it was a forward reference, update everything that used it to use
3632     // the actual definition instead, delete the forward ref, and remove it
3633     // from our set of forward references we track.
3634     existing.replaceAllUsesWith(value);
3635     existing.getDefiningOp()->destroy();
3636     forwardRefPlaceholders.erase(existing);
3637   }
3638 
3639   /// Record this definition for the current scope.
3640   entries[useInfo.number] = {value, useInfo.loc};
3641   recordDefinition(useInfo.name);
3642   return success();
3643 }
3644 
3645 /// Parse a (possibly empty) list of SSA operands.
3646 ///
3647 ///   ssa-use-list ::= ssa-use (`,` ssa-use)*
3648 ///   ssa-use-list-opt ::= ssa-use-list?
3649 ///
3650 ParseResult
3651 OperationParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
3652   if (getToken().isNot(Token::percent_identifier))
3653     return success();
3654   return parseCommaSeparatedList([&]() -> ParseResult {
3655     SSAUseInfo result;
3656     if (parseSSAUse(result))
3657       return failure();
3658     results.push_back(result);
3659     return success();
3660   });
3661 }
3662 
3663 /// Parse a SSA operand for an operation.
3664 ///
3665 ///   ssa-use ::= ssa-id
3666 ///
3667 ParseResult OperationParser::parseSSAUse(SSAUseInfo &result) {
3668   result.name = getTokenSpelling();
3669   result.number = 0;
3670   result.loc = getToken().getLoc();
3671   if (parseToken(Token::percent_identifier, "expected SSA operand"))
3672     return failure();
3673 
3674   // If we have an attribute ID, it is a result number.
3675   if (getToken().is(Token::hash_identifier)) {
3676     if (auto value = getToken().getHashIdentifierNumber())
3677       result.number = value.getValue();
3678     else
3679       return emitError("invalid SSA value result number");
3680     consumeToken(Token::hash_identifier);
3681   }
3682 
3683   return success();
3684 }
3685 
3686 /// Given an unbound reference to an SSA value and its type, return the value
3687 /// it specifies.  This returns null on failure.
3688 Value OperationParser::resolveSSAUse(SSAUseInfo useInfo, Type type) {
3689   auto &entries = getSSAValueEntry(useInfo.name);
3690 
3691   // If we have already seen a value of this name, return it.
3692   if (useInfo.number < entries.size() && entries[useInfo.number].first) {
3693     auto result = entries[useInfo.number].first;
3694     // Check that the type matches the other uses.
3695     if (result.getType() == type)
3696       return result;
3697 
3698     emitError(useInfo.loc, "use of value '")
3699         .append(useInfo.name,
3700                 "' expects different type than prior uses: ", type, " vs ",
3701                 result.getType())
3702         .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3703         .append("prior use here");
3704     return nullptr;
3705   }
3706 
3707   // Make sure we have enough slots for this.
3708   if (entries.size() <= useInfo.number)
3709     entries.resize(useInfo.number + 1);
3710 
3711   // If the value has already been defined and this is an overly large result
3712   // number, diagnose that.
3713   if (entries[0].first && !isForwardRefPlaceholder(entries[0].first))
3714     return (emitError(useInfo.loc, "reference to invalid result number"),
3715             nullptr);
3716 
3717   // Otherwise, this is a forward reference.  Create a placeholder and remember
3718   // that we did so.
3719   auto result = createForwardRefPlaceholder(useInfo.loc, type);
3720   entries[useInfo.number].first = result;
3721   entries[useInfo.number].second = useInfo.loc;
3722   return result;
3723 }
3724 
3725 /// Parse an SSA use with an associated type.
3726 ///
3727 ///   ssa-use-and-type ::= ssa-use `:` type
3728 ParseResult OperationParser::parseSSADefOrUseAndType(
3729     const std::function<ParseResult(SSAUseInfo, Type)> &action) {
3730   SSAUseInfo useInfo;
3731   if (parseSSAUse(useInfo) ||
3732       parseToken(Token::colon, "expected ':' and type for SSA operand"))
3733     return failure();
3734 
3735   auto type = parseType();
3736   if (!type)
3737     return failure();
3738 
3739   return action(useInfo, type);
3740 }
3741 
3742 /// Parse a (possibly empty) list of SSA operands, followed by a colon, then
3743 /// followed by a type list.
3744 ///
3745 ///   ssa-use-and-type-list
3746 ///     ::= ssa-use-list ':' type-list-no-parens
3747 ///
3748 ParseResult OperationParser::parseOptionalSSAUseAndTypeList(
3749     SmallVectorImpl<Value> &results) {
3750   SmallVector<SSAUseInfo, 4> valueIDs;
3751   if (parseOptionalSSAUseList(valueIDs))
3752     return failure();
3753 
3754   // If there were no operands, then there is no colon or type lists.
3755   if (valueIDs.empty())
3756     return success();
3757 
3758   SmallVector<Type, 4> types;
3759   if (parseToken(Token::colon, "expected ':' in operand list") ||
3760       parseTypeListNoParens(types))
3761     return failure();
3762 
3763   if (valueIDs.size() != types.size())
3764     return emitError("expected ")
3765            << valueIDs.size() << " types to match operand list";
3766 
3767   results.reserve(valueIDs.size());
3768   for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
3769     if (auto value = resolveSSAUse(valueIDs[i], types[i]))
3770       results.push_back(value);
3771     else
3772       return failure();
3773   }
3774 
3775   return success();
3776 }
3777 
3778 /// Record that a definition was added at the current scope.
3779 void OperationParser::recordDefinition(StringRef def) {
3780   isolatedNameScopes.back().recordDefinition(def);
3781 }
3782 
3783 /// Get the value entry for the given SSA name.
3784 SmallVectorImpl<std::pair<Value, SMLoc>> &
3785 OperationParser::getSSAValueEntry(StringRef name) {
3786   return isolatedNameScopes.back().values[name];
3787 }
3788 
3789 /// Create and remember a new placeholder for a forward reference.
3790 Value OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) {
3791   // Forward references are always created as operations, because we just need
3792   // something with a def/use chain.
3793   //
3794   // We create these placeholders as having an empty name, which we know
3795   // cannot be created through normal user input, allowing us to distinguish
3796   // them.
3797   auto name = OperationName("placeholder", getContext());
3798   auto *op = Operation::create(
3799       getEncodedSourceLocation(loc), name, type, /*operands=*/{},
3800       /*attributes=*/llvm::None, /*successors=*/{}, /*numRegions=*/0);
3801   forwardRefPlaceholders[op->getResult(0)] = loc;
3802   return op->getResult(0);
3803 }
3804 
3805 //===----------------------------------------------------------------------===//
3806 // Operation Parsing
3807 //===----------------------------------------------------------------------===//
3808 
3809 /// Parse an operation.
3810 ///
3811 ///  operation         ::= op-result-list?
3812 ///                        (generic-operation | custom-operation)
3813 ///                        trailing-location?
3814 ///  generic-operation ::= string-literal `(` ssa-use-list? `)`
3815 ///                        successor-list? (`(` region-list `)`)?
3816 ///                        attribute-dict? `:` function-type
3817 ///  custom-operation  ::= bare-id custom-operation-format
3818 ///  op-result-list    ::= op-result (`,` op-result)* `=`
3819 ///  op-result         ::= ssa-id (`:` integer-literal)
3820 ///
3821 ParseResult OperationParser::parseOperation() {
3822   auto loc = getToken().getLoc();
3823   SmallVector<ResultRecord, 1> resultIDs;
3824   size_t numExpectedResults = 0;
3825   if (getToken().is(Token::percent_identifier)) {
3826     // Parse the group of result ids.
3827     auto parseNextResult = [&]() -> ParseResult {
3828       // Parse the next result id.
3829       if (!getToken().is(Token::percent_identifier))
3830         return emitError("expected valid ssa identifier");
3831 
3832       Token nameTok = getToken();
3833       consumeToken(Token::percent_identifier);
3834 
3835       // If the next token is a ':', we parse the expected result count.
3836       size_t expectedSubResults = 1;
3837       if (consumeIf(Token::colon)) {
3838         // Check that the next token is an integer.
3839         if (!getToken().is(Token::integer))
3840           return emitError("expected integer number of results");
3841 
3842         // Check that number of results is > 0.
3843         auto val = getToken().getUInt64IntegerValue();
3844         if (!val.hasValue() || val.getValue() < 1)
3845           return emitError("expected named operation to have atleast 1 result");
3846         consumeToken(Token::integer);
3847         expectedSubResults = *val;
3848       }
3849 
3850       resultIDs.emplace_back(nameTok.getSpelling(), expectedSubResults,
3851                              nameTok.getLoc());
3852       numExpectedResults += expectedSubResults;
3853       return success();
3854     };
3855     if (parseCommaSeparatedList(parseNextResult))
3856       return failure();
3857 
3858     if (parseToken(Token::equal, "expected '=' after SSA name"))
3859       return failure();
3860   }
3861 
3862   Operation *op;
3863   if (getToken().is(Token::bare_identifier) || getToken().isKeyword())
3864     op = parseCustomOperation(resultIDs);
3865   else if (getToken().is(Token::string))
3866     op = parseGenericOperation();
3867   else
3868     return emitError("expected operation name in quotes");
3869 
3870   // If parsing of the basic operation failed, then this whole thing fails.
3871   if (!op)
3872     return failure();
3873 
3874   // If the operation had a name, register it.
3875   if (!resultIDs.empty()) {
3876     if (op->getNumResults() == 0)
3877       return emitError(loc, "cannot name an operation with no results");
3878     if (numExpectedResults != op->getNumResults())
3879       return emitError(loc, "operation defines ")
3880              << op->getNumResults() << " results but was provided "
3881              << numExpectedResults << " to bind";
3882 
3883     // Add definitions for each of the result groups.
3884     unsigned opResI = 0;
3885     for (ResultRecord &resIt : resultIDs) {
3886       for (unsigned subRes : llvm::seq<unsigned>(0, std::get<1>(resIt))) {
3887         if (addDefinition({std::get<0>(resIt), subRes, std::get<2>(resIt)},
3888                           op->getResult(opResI++)))
3889           return failure();
3890       }
3891     }
3892   }
3893 
3894   return success();
3895 }
3896 
3897 /// Parse a single operation successor.
3898 ///
3899 ///   successor ::= block-id
3900 ///
3901 ParseResult OperationParser::parseSuccessor(Block *&dest) {
3902   // Verify branch is identifier and get the matching block.
3903   if (!getToken().is(Token::caret_identifier))
3904     return emitError("expected block name");
3905   dest = getBlockNamed(getTokenSpelling(), getToken().getLoc());
3906   consumeToken();
3907   return success();
3908 }
3909 
3910 /// Parse a comma-separated list of operation successors in brackets.
3911 ///
3912 ///   successor-list ::= `[` successor (`,` successor )* `]`
3913 ///
3914 ParseResult
3915 OperationParser::parseSuccessors(SmallVectorImpl<Block *> &destinations) {
3916   if (parseToken(Token::l_square, "expected '['"))
3917     return failure();
3918 
3919   auto parseElt = [this, &destinations] {
3920     Block *dest;
3921     ParseResult res = parseSuccessor(dest);
3922     destinations.push_back(dest);
3923     return res;
3924   };
3925   return parseCommaSeparatedListUntil(Token::r_square, parseElt,
3926                                       /*allowEmptyList=*/false);
3927 }
3928 
3929 namespace {
3930 // RAII-style guard for cleaning up the regions in the operation state before
3931 // deleting them.  Within the parser, regions may get deleted if parsing failed,
3932 // and other errors may be present, in particular undominated uses.  This makes
3933 // sure such uses are deleted.
3934 struct CleanupOpStateRegions {
3935   ~CleanupOpStateRegions() {
3936     SmallVector<Region *, 4> regionsToClean;
3937     regionsToClean.reserve(state.regions.size());
3938     for (auto &region : state.regions)
3939       if (region)
3940         for (auto &block : *region)
3941           block.dropAllDefinedValueUses();
3942   }
3943   OperationState &state;
3944 };
3945 } // namespace
3946 
3947 Operation *OperationParser::parseGenericOperation() {
3948   // Get location information for the operation.
3949   auto srcLocation = getEncodedSourceLocation(getToken().getLoc());
3950 
3951   auto name = getToken().getStringValue();
3952   if (name.empty())
3953     return (emitError("empty operation name is invalid"), nullptr);
3954   if (name.find('\0') != StringRef::npos)
3955     return (emitError("null character not allowed in operation name"), nullptr);
3956 
3957   consumeToken(Token::string);
3958 
3959   OperationState result(srcLocation, name);
3960 
3961   // Parse the operand list.
3962   SmallVector<SSAUseInfo, 8> operandInfos;
3963   if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
3964       parseOptionalSSAUseList(operandInfos) ||
3965       parseToken(Token::r_paren, "expected ')' to end operand list")) {
3966     return nullptr;
3967   }
3968 
3969   // Parse the successor list.
3970   if (getToken().is(Token::l_square)) {
3971     // Check if the operation is a known terminator.
3972     const AbstractOperation *abstractOp = result.name.getAbstractOperation();
3973     if (abstractOp && !abstractOp->hasProperty(OperationProperty::Terminator))
3974       return emitError("successors in non-terminator"), nullptr;
3975 
3976     SmallVector<Block *, 2> successors;
3977     if (parseSuccessors(successors))
3978       return nullptr;
3979     result.addSuccessors(successors);
3980   }
3981 
3982   // Parse the region list.
3983   CleanupOpStateRegions guard{result};
3984   if (consumeIf(Token::l_paren)) {
3985     do {
3986       // Create temporary regions with the top level region as parent.
3987       result.regions.emplace_back(new Region(moduleOp));
3988       if (parseRegion(*result.regions.back(), /*entryArguments=*/{}))
3989         return nullptr;
3990     } while (consumeIf(Token::comma));
3991     if (parseToken(Token::r_paren, "expected ')' to end region list"))
3992       return nullptr;
3993   }
3994 
3995   if (getToken().is(Token::l_brace)) {
3996     if (parseAttributeDict(result.attributes))
3997       return nullptr;
3998   }
3999 
4000   if (parseToken(Token::colon, "expected ':' followed by operation type"))
4001     return nullptr;
4002 
4003   auto typeLoc = getToken().getLoc();
4004   auto type = parseType();
4005   if (!type)
4006     return nullptr;
4007   auto fnType = type.dyn_cast<FunctionType>();
4008   if (!fnType)
4009     return (emitError(typeLoc, "expected function type"), nullptr);
4010 
4011   result.addTypes(fnType.getResults());
4012 
4013   // Check that we have the right number of types for the operands.
4014   auto operandTypes = fnType.getInputs();
4015   if (operandTypes.size() != operandInfos.size()) {
4016     auto plural = "s"[operandInfos.size() == 1];
4017     return (emitError(typeLoc, "expected ")
4018                 << operandInfos.size() << " operand type" << plural
4019                 << " but had " << operandTypes.size(),
4020             nullptr);
4021   }
4022 
4023   // Resolve all of the operands.
4024   for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
4025     result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
4026     if (!result.operands.back())
4027       return nullptr;
4028   }
4029 
4030   // Parse a location if one is present.
4031   if (parseOptionalTrailingLocation(result.location))
4032     return nullptr;
4033 
4034   return opBuilder.createOperation(result);
4035 }
4036 
4037 Operation *OperationParser::parseGenericOperation(Block *insertBlock,
4038                                                   Block::iterator insertPt) {
4039   OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder);
4040   opBuilder.setInsertionPoint(insertBlock, insertPt);
4041   return parseGenericOperation();
4042 }
4043 
4044 namespace {
4045 class CustomOpAsmParser : public OpAsmParser {
4046 public:
4047   CustomOpAsmParser(SMLoc nameLoc,
4048                     ArrayRef<OperationParser::ResultRecord> resultIDs,
4049                     const AbstractOperation *opDefinition,
4050                     OperationParser &parser)
4051       : nameLoc(nameLoc), resultIDs(resultIDs), opDefinition(opDefinition),
4052         parser(parser) {}
4053 
4054   /// Parse an instance of the operation described by 'opDefinition' into the
4055   /// provided operation state.
4056   ParseResult parseOperation(OperationState &opState) {
4057     if (opDefinition->parseAssembly(*this, opState))
4058       return failure();
4059     return success();
4060   }
4061 
4062   Operation *parseGenericOperation(Block *insertBlock,
4063                                    Block::iterator insertPt) final {
4064     return parser.parseGenericOperation(insertBlock, insertPt);
4065   }
4066 
4067   //===--------------------------------------------------------------------===//
4068   // Utilities
4069   //===--------------------------------------------------------------------===//
4070 
4071   /// Return if any errors were emitted during parsing.
4072   bool didEmitError() const { return emittedError; }
4073 
4074   /// Emit a diagnostic at the specified location and return failure.
4075   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
4076     emittedError = true;
4077     return parser.emitError(loc, "custom op '" + opDefinition->name + "' " +
4078                                      message);
4079   }
4080 
4081   llvm::SMLoc getCurrentLocation() override {
4082     return parser.getToken().getLoc();
4083   }
4084 
4085   Builder &getBuilder() const override { return parser.builder; }
4086 
4087   /// Return the name of the specified result in the specified syntax, as well
4088   /// as the subelement in the name.  For example, in this operation:
4089   ///
4090   ///  %x, %y:2, %z = foo.op
4091   ///
4092   ///    getResultName(0) == {"x", 0 }
4093   ///    getResultName(1) == {"y", 0 }
4094   ///    getResultName(2) == {"y", 1 }
4095   ///    getResultName(3) == {"z", 0 }
4096   std::pair<StringRef, unsigned>
4097   getResultName(unsigned resultNo) const override {
4098     // Scan for the resultID that contains this result number.
4099     for (unsigned nameID = 0, e = resultIDs.size(); nameID != e; ++nameID) {
4100       const auto &entry = resultIDs[nameID];
4101       if (resultNo < std::get<1>(entry)) {
4102         // Don't pass on the leading %.
4103         StringRef name = std::get<0>(entry).drop_front();
4104         return {name, resultNo};
4105       }
4106       resultNo -= std::get<1>(entry);
4107     }
4108 
4109     // Invalid result number.
4110     return {"", ~0U};
4111   }
4112 
4113   /// Return the number of declared SSA results.  This returns 4 for the foo.op
4114   /// example in the comment for getResultName.
4115   size_t getNumResults() const override {
4116     size_t count = 0;
4117     for (auto &entry : resultIDs)
4118       count += std::get<1>(entry);
4119     return count;
4120   }
4121 
4122   llvm::SMLoc getNameLoc() const override { return nameLoc; }
4123 
4124   //===--------------------------------------------------------------------===//
4125   // Token Parsing
4126   //===--------------------------------------------------------------------===//
4127 
4128   /// Parse a `->` token.
4129   ParseResult parseArrow() override {
4130     return parser.parseToken(Token::arrow, "expected '->'");
4131   }
4132 
4133   /// Parses a `->` if present.
4134   ParseResult parseOptionalArrow() override {
4135     return success(parser.consumeIf(Token::arrow));
4136   }
4137 
4138   /// Parse a `:` token.
4139   ParseResult parseColon() override {
4140     return parser.parseToken(Token::colon, "expected ':'");
4141   }
4142 
4143   /// Parse a `:` token if present.
4144   ParseResult parseOptionalColon() override {
4145     return success(parser.consumeIf(Token::colon));
4146   }
4147 
4148   /// Parse a `,` token.
4149   ParseResult parseComma() override {
4150     return parser.parseToken(Token::comma, "expected ','");
4151   }
4152 
4153   /// Parse a `,` token if present.
4154   ParseResult parseOptionalComma() override {
4155     return success(parser.consumeIf(Token::comma));
4156   }
4157 
4158   /// Parses a `...` if present.
4159   ParseResult parseOptionalEllipsis() override {
4160     return success(parser.consumeIf(Token::ellipsis));
4161   }
4162 
4163   /// Parse a `=` token.
4164   ParseResult parseEqual() override {
4165     return parser.parseToken(Token::equal, "expected '='");
4166   }
4167 
4168   /// Parse a '<' token.
4169   ParseResult parseLess() override {
4170     return parser.parseToken(Token::less, "expected '<'");
4171   }
4172 
4173   /// Parse a '>' token.
4174   ParseResult parseGreater() override {
4175     return parser.parseToken(Token::greater, "expected '>'");
4176   }
4177 
4178   /// Parse a `(` token.
4179   ParseResult parseLParen() override {
4180     return parser.parseToken(Token::l_paren, "expected '('");
4181   }
4182 
4183   /// Parses a '(' if present.
4184   ParseResult parseOptionalLParen() override {
4185     return success(parser.consumeIf(Token::l_paren));
4186   }
4187 
4188   /// Parse a `)` token.
4189   ParseResult parseRParen() override {
4190     return parser.parseToken(Token::r_paren, "expected ')'");
4191   }
4192 
4193   /// Parses a ')' if present.
4194   ParseResult parseOptionalRParen() override {
4195     return success(parser.consumeIf(Token::r_paren));
4196   }
4197 
4198   /// Parse a `[` token.
4199   ParseResult parseLSquare() override {
4200     return parser.parseToken(Token::l_square, "expected '['");
4201   }
4202 
4203   /// Parses a '[' if present.
4204   ParseResult parseOptionalLSquare() override {
4205     return success(parser.consumeIf(Token::l_square));
4206   }
4207 
4208   /// Parse a `]` token.
4209   ParseResult parseRSquare() override {
4210     return parser.parseToken(Token::r_square, "expected ']'");
4211   }
4212 
4213   /// Parses a ']' if present.
4214   ParseResult parseOptionalRSquare() override {
4215     return success(parser.consumeIf(Token::r_square));
4216   }
4217 
4218   //===--------------------------------------------------------------------===//
4219   // Attribute Parsing
4220   //===--------------------------------------------------------------------===//
4221 
4222   /// Parse an arbitrary attribute of a given type and return it in result. This
4223   /// also adds the attribute to the specified attribute list with the specified
4224   /// name.
4225   ParseResult parseAttribute(Attribute &result, Type type, StringRef attrName,
4226                              NamedAttrList &attrs) override {
4227     result = parser.parseAttribute(type);
4228     if (!result)
4229       return failure();
4230 
4231     attrs.push_back(parser.builder.getNamedAttr(attrName, result));
4232     return success();
4233   }
4234 
4235   /// Parse a named dictionary into 'result' if it is present.
4236   ParseResult parseOptionalAttrDict(NamedAttrList &result) override {
4237     if (parser.getToken().isNot(Token::l_brace))
4238       return success();
4239     return parser.parseAttributeDict(result);
4240   }
4241 
4242   /// Parse a named dictionary into 'result' if the `attributes` keyword is
4243   /// present.
4244   ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result) override {
4245     if (failed(parseOptionalKeyword("attributes")))
4246       return success();
4247     return parser.parseAttributeDict(result);
4248   }
4249 
4250   /// Parse an affine map instance into 'map'.
4251   ParseResult parseAffineMap(AffineMap &map) override {
4252     return parser.parseAffineMapReference(map);
4253   }
4254 
4255   /// Parse an integer set instance into 'set'.
4256   ParseResult printIntegerSet(IntegerSet &set) override {
4257     return parser.parseIntegerSetReference(set);
4258   }
4259 
4260   //===--------------------------------------------------------------------===//
4261   // Identifier Parsing
4262   //===--------------------------------------------------------------------===//
4263 
4264   /// Returns if the current token corresponds to a keyword.
4265   bool isCurrentTokenAKeyword() const {
4266     return parser.getToken().is(Token::bare_identifier) ||
4267            parser.getToken().isKeyword();
4268   }
4269 
4270   /// Parse the given keyword if present.
4271   ParseResult parseOptionalKeyword(StringRef keyword) override {
4272     // Check that the current token has the same spelling.
4273     if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword)
4274       return failure();
4275     parser.consumeToken();
4276     return success();
4277   }
4278 
4279   /// Parse a keyword, if present, into 'keyword'.
4280   ParseResult parseOptionalKeyword(StringRef *keyword) override {
4281     // Check that the current token is a keyword.
4282     if (!isCurrentTokenAKeyword())
4283       return failure();
4284 
4285     *keyword = parser.getTokenSpelling();
4286     parser.consumeToken();
4287     return success();
4288   }
4289 
4290   /// Parse an optional @-identifier and store it (without the '@' symbol) in a
4291   /// string attribute named 'attrName'.
4292   ParseResult parseOptionalSymbolName(StringAttr &result, StringRef attrName,
4293                                       NamedAttrList &attrs) override {
4294     Token atToken = parser.getToken();
4295     if (atToken.isNot(Token::at_identifier))
4296       return failure();
4297 
4298     result = getBuilder().getStringAttr(extractSymbolReference(atToken));
4299     attrs.push_back(getBuilder().getNamedAttr(attrName, result));
4300     parser.consumeToken();
4301     return success();
4302   }
4303 
4304   //===--------------------------------------------------------------------===//
4305   // Operand Parsing
4306   //===--------------------------------------------------------------------===//
4307 
4308   /// Parse a single operand.
4309   ParseResult parseOperand(OperandType &result) override {
4310     OperationParser::SSAUseInfo useInfo;
4311     if (parser.parseSSAUse(useInfo))
4312       return failure();
4313 
4314     result = {useInfo.loc, useInfo.name, useInfo.number};
4315     return success();
4316   }
4317 
4318   /// Parse a single operand if present.
4319   OptionalParseResult parseOptionalOperand(OperandType &result) override {
4320     if (parser.getToken().is(Token::percent_identifier))
4321       return parseOperand(result);
4322     return llvm::None;
4323   }
4324 
4325   /// Parse zero or more SSA comma-separated operand references with a specified
4326   /// surrounding delimiter, and an optional required operand count.
4327   ParseResult parseOperandList(SmallVectorImpl<OperandType> &result,
4328                                int requiredOperandCount = -1,
4329                                Delimiter delimiter = Delimiter::None) override {
4330     return parseOperandOrRegionArgList(result, /*isOperandList=*/true,
4331                                        requiredOperandCount, delimiter);
4332   }
4333 
4334   /// Parse zero or more SSA comma-separated operand or region arguments with
4335   ///  optional surrounding delimiter and required operand count.
4336   ParseResult
4337   parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result,
4338                               bool isOperandList, int requiredOperandCount = -1,
4339                               Delimiter delimiter = Delimiter::None) {
4340     auto startLoc = parser.getToken().getLoc();
4341 
4342     // Handle delimiters.
4343     switch (delimiter) {
4344     case Delimiter::None:
4345       // Don't check for the absence of a delimiter if the number of operands
4346       // is unknown (and hence the operand list could be empty).
4347       if (requiredOperandCount == -1)
4348         break;
4349       // Token already matches an identifier and so can't be a delimiter.
4350       if (parser.getToken().is(Token::percent_identifier))
4351         break;
4352       // Test against known delimiters.
4353       if (parser.getToken().is(Token::l_paren) ||
4354           parser.getToken().is(Token::l_square))
4355         return emitError(startLoc, "unexpected delimiter");
4356       return emitError(startLoc, "invalid operand");
4357     case Delimiter::OptionalParen:
4358       if (parser.getToken().isNot(Token::l_paren))
4359         return success();
4360       LLVM_FALLTHROUGH;
4361     case Delimiter::Paren:
4362       if (parser.parseToken(Token::l_paren, "expected '(' in operand list"))
4363         return failure();
4364       break;
4365     case Delimiter::OptionalSquare:
4366       if (parser.getToken().isNot(Token::l_square))
4367         return success();
4368       LLVM_FALLTHROUGH;
4369     case Delimiter::Square:
4370       if (parser.parseToken(Token::l_square, "expected '[' in operand list"))
4371         return failure();
4372       break;
4373     }
4374 
4375     // Check for zero operands.
4376     if (parser.getToken().is(Token::percent_identifier)) {
4377       do {
4378         OperandType operandOrArg;
4379         if (isOperandList ? parseOperand(operandOrArg)
4380                           : parseRegionArgument(operandOrArg))
4381           return failure();
4382         result.push_back(operandOrArg);
4383       } while (parser.consumeIf(Token::comma));
4384     }
4385 
4386     // Handle delimiters.   If we reach here, the optional delimiters were
4387     // present, so we need to parse their closing one.
4388     switch (delimiter) {
4389     case Delimiter::None:
4390       break;
4391     case Delimiter::OptionalParen:
4392     case Delimiter::Paren:
4393       if (parser.parseToken(Token::r_paren, "expected ')' in operand list"))
4394         return failure();
4395       break;
4396     case Delimiter::OptionalSquare:
4397     case Delimiter::Square:
4398       if (parser.parseToken(Token::r_square, "expected ']' in operand list"))
4399         return failure();
4400       break;
4401     }
4402 
4403     if (requiredOperandCount != -1 &&
4404         result.size() != static_cast<size_t>(requiredOperandCount))
4405       return emitError(startLoc, "expected ")
4406              << requiredOperandCount << " operands";
4407     return success();
4408   }
4409 
4410   /// Parse zero or more trailing SSA comma-separated trailing operand
4411   /// references with a specified surrounding delimiter, and an optional
4412   /// required operand count. A leading comma is expected before the operands.
4413   ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result,
4414                                        int requiredOperandCount,
4415                                        Delimiter delimiter) override {
4416     if (parser.getToken().is(Token::comma)) {
4417       parseComma();
4418       return parseOperandList(result, requiredOperandCount, delimiter);
4419     }
4420     if (requiredOperandCount != -1)
4421       return emitError(parser.getToken().getLoc(), "expected ")
4422              << requiredOperandCount << " operands";
4423     return success();
4424   }
4425 
4426   /// Resolve an operand to an SSA value, emitting an error on failure.
4427   ParseResult resolveOperand(const OperandType &operand, Type type,
4428                              SmallVectorImpl<Value> &result) override {
4429     OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
4430                                                operand.location};
4431     if (auto value = parser.resolveSSAUse(operandInfo, type)) {
4432       result.push_back(value);
4433       return success();
4434     }
4435     return failure();
4436   }
4437 
4438   /// Parse an AffineMap of SSA ids.
4439   ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands,
4440                                      Attribute &mapAttr, StringRef attrName,
4441                                      NamedAttrList &attrs,
4442                                      Delimiter delimiter) override {
4443     SmallVector<OperandType, 2> dimOperands;
4444     SmallVector<OperandType, 1> symOperands;
4445 
4446     auto parseElement = [&](bool isSymbol) -> ParseResult {
4447       OperandType operand;
4448       if (parseOperand(operand))
4449         return failure();
4450       if (isSymbol)
4451         symOperands.push_back(operand);
4452       else
4453         dimOperands.push_back(operand);
4454       return success();
4455     };
4456 
4457     AffineMap map;
4458     if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter))
4459       return failure();
4460     // Add AffineMap attribute.
4461     if (map) {
4462       mapAttr = AffineMapAttr::get(map);
4463       attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr));
4464     }
4465 
4466     // Add dim operands before symbol operands in 'operands'.
4467     operands.assign(dimOperands.begin(), dimOperands.end());
4468     operands.append(symOperands.begin(), symOperands.end());
4469     return success();
4470   }
4471 
4472   //===--------------------------------------------------------------------===//
4473   // Region Parsing
4474   //===--------------------------------------------------------------------===//
4475 
4476   /// Parse a region that takes `arguments` of `argTypes` types.  This
4477   /// effectively defines the SSA values of `arguments` and assigns their type.
4478   ParseResult parseRegion(Region &region, ArrayRef<OperandType> arguments,
4479                           ArrayRef<Type> argTypes,
4480                           bool enableNameShadowing) override {
4481     assert(arguments.size() == argTypes.size() &&
4482            "mismatching number of arguments and types");
4483 
4484     SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2>
4485         regionArguments;
4486     for (auto pair : llvm::zip(arguments, argTypes)) {
4487       const OperandType &operand = std::get<0>(pair);
4488       Type type = std::get<1>(pair);
4489       OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
4490                                                  operand.location};
4491       regionArguments.emplace_back(operandInfo, type);
4492     }
4493 
4494     // Try to parse the region.
4495     assert((!enableNameShadowing ||
4496             opDefinition->hasProperty(OperationProperty::IsolatedFromAbove)) &&
4497            "name shadowing is only allowed on isolated regions");
4498     if (parser.parseRegion(region, regionArguments, enableNameShadowing))
4499       return failure();
4500     return success();
4501   }
4502 
4503   /// Parses a region if present.
4504   ParseResult parseOptionalRegion(Region &region,
4505                                   ArrayRef<OperandType> arguments,
4506                                   ArrayRef<Type> argTypes,
4507                                   bool enableNameShadowing) override {
4508     if (parser.getToken().isNot(Token::l_brace))
4509       return success();
4510     return parseRegion(region, arguments, argTypes, enableNameShadowing);
4511   }
4512 
4513   /// Parse a region argument. The type of the argument will be resolved later
4514   /// by a call to `parseRegion`.
4515   ParseResult parseRegionArgument(OperandType &argument) override {
4516     return parseOperand(argument);
4517   }
4518 
4519   /// Parse a region argument if present.
4520   ParseResult parseOptionalRegionArgument(OperandType &argument) override {
4521     if (parser.getToken().isNot(Token::percent_identifier))
4522       return success();
4523     return parseRegionArgument(argument);
4524   }
4525 
4526   ParseResult
4527   parseRegionArgumentList(SmallVectorImpl<OperandType> &result,
4528                           int requiredOperandCount = -1,
4529                           Delimiter delimiter = Delimiter::None) override {
4530     return parseOperandOrRegionArgList(result, /*isOperandList=*/false,
4531                                        requiredOperandCount, delimiter);
4532   }
4533 
4534   //===--------------------------------------------------------------------===//
4535   // Successor Parsing
4536   //===--------------------------------------------------------------------===//
4537 
4538   /// Parse a single operation successor.
4539   ParseResult parseSuccessor(Block *&dest) override {
4540     return parser.parseSuccessor(dest);
4541   }
4542 
4543   /// Parse an optional operation successor and its operand list.
4544   OptionalParseResult parseOptionalSuccessor(Block *&dest) override {
4545     if (parser.getToken().isNot(Token::caret_identifier))
4546       return llvm::None;
4547     return parseSuccessor(dest);
4548   }
4549 
4550   /// Parse a single operation successor and its operand list.
4551   ParseResult
4552   parseSuccessorAndUseList(Block *&dest,
4553                            SmallVectorImpl<Value> &operands) override {
4554     if (parseSuccessor(dest))
4555       return failure();
4556 
4557     // Handle optional arguments.
4558     if (succeeded(parseOptionalLParen()) &&
4559         (parser.parseOptionalSSAUseAndTypeList(operands) || parseRParen())) {
4560       return failure();
4561     }
4562     return success();
4563   }
4564 
4565   //===--------------------------------------------------------------------===//
4566   // Type Parsing
4567   //===--------------------------------------------------------------------===//
4568 
4569   /// Parse a type.
4570   ParseResult parseType(Type &result) override {
4571     return failure(!(result = parser.parseType()));
4572   }
4573 
4574   /// Parse an optional type.
4575   OptionalParseResult parseOptionalType(Type &result) override {
4576     return parser.parseOptionalType(result);
4577   }
4578 
4579   /// Parse an arrow followed by a type list.
4580   ParseResult parseArrowTypeList(SmallVectorImpl<Type> &result) override {
4581     if (parseArrow() || parser.parseFunctionResultTypes(result))
4582       return failure();
4583     return success();
4584   }
4585 
4586   /// Parse an optional arrow followed by a type list.
4587   ParseResult
4588   parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override {
4589     if (!parser.consumeIf(Token::arrow))
4590       return success();
4591     return parser.parseFunctionResultTypes(result);
4592   }
4593 
4594   /// Parse a colon followed by a type.
4595   ParseResult parseColonType(Type &result) override {
4596     return failure(parser.parseToken(Token::colon, "expected ':'") ||
4597                    !(result = parser.parseType()));
4598   }
4599 
4600   /// Parse a colon followed by a type list, which must have at least one type.
4601   ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override {
4602     if (parser.parseToken(Token::colon, "expected ':'"))
4603       return failure();
4604     return parser.parseTypeListNoParens(result);
4605   }
4606 
4607   /// Parse an optional colon followed by a type list, which if present must
4608   /// have at least one type.
4609   ParseResult
4610   parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override {
4611     if (!parser.consumeIf(Token::colon))
4612       return success();
4613     return parser.parseTypeListNoParens(result);
4614   }
4615 
4616   /// Parse a list of assignments of the form
4617   /// (%x1 = %y1 : type1, %x2 = %y2 : type2, ...).
4618   /// The list must contain at least one entry
4619   ParseResult parseAssignmentList(SmallVectorImpl<OperandType> &lhs,
4620                                   SmallVectorImpl<OperandType> &rhs) override {
4621     auto parseElt = [&]() -> ParseResult {
4622       OperandType regionArg, operand;
4623       if (parseRegionArgument(regionArg) || parseEqual() ||
4624           parseOperand(operand))
4625         return failure();
4626       lhs.push_back(regionArg);
4627       rhs.push_back(operand);
4628       return success();
4629     };
4630     if (parseLParen())
4631       return failure();
4632     return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
4633   }
4634 
4635 private:
4636   /// The source location of the operation name.
4637   SMLoc nameLoc;
4638 
4639   /// Information about the result name specifiers.
4640   ArrayRef<OperationParser::ResultRecord> resultIDs;
4641 
4642   /// The abstract information of the operation.
4643   const AbstractOperation *opDefinition;
4644 
4645   /// The main operation parser.
4646   OperationParser &parser;
4647 
4648   /// A flag that indicates if any errors were emitted during parsing.
4649   bool emittedError = false;
4650 };
4651 } // end anonymous namespace.
4652 
4653 Operation *
4654 OperationParser::parseCustomOperation(ArrayRef<ResultRecord> resultIDs) {
4655   auto opLoc = getToken().getLoc();
4656   auto opName = getTokenSpelling();
4657 
4658   auto *opDefinition = AbstractOperation::lookup(opName, getContext());
4659   if (!opDefinition && !opName.contains('.')) {
4660     // If the operation name has no namespace prefix we treat it as a standard
4661     // operation and prefix it with "std".
4662     // TODO: Would it be better to just build a mapping of the registered
4663     // operations in the standard dialect?
4664     opDefinition =
4665         AbstractOperation::lookup(Twine("std." + opName).str(), getContext());
4666   }
4667 
4668   if (!opDefinition) {
4669     emitError(opLoc) << "custom op '" << opName << "' is unknown";
4670     return nullptr;
4671   }
4672 
4673   consumeToken();
4674 
4675   // If the custom op parser crashes, produce some indication to help
4676   // debugging.
4677   std::string opNameStr = opName.str();
4678   llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'",
4679                                    opNameStr.c_str());
4680 
4681   // Get location information for the operation.
4682   auto srcLocation = getEncodedSourceLocation(opLoc);
4683 
4684   // Have the op implementation take a crack and parsing this.
4685   OperationState opState(srcLocation, opDefinition->name);
4686   CleanupOpStateRegions guard{opState};
4687   CustomOpAsmParser opAsmParser(opLoc, resultIDs, opDefinition, *this);
4688   if (opAsmParser.parseOperation(opState))
4689     return nullptr;
4690 
4691   // If it emitted an error, we failed.
4692   if (opAsmParser.didEmitError())
4693     return nullptr;
4694 
4695   // Parse a location if one is present.
4696   if (parseOptionalTrailingLocation(opState.location))
4697     return nullptr;
4698 
4699   // Otherwise, we succeeded.  Use the state it parsed as our op information.
4700   return opBuilder.createOperation(opState);
4701 }
4702 
4703 //===----------------------------------------------------------------------===//
4704 // Region Parsing
4705 //===----------------------------------------------------------------------===//
4706 
4707 /// Region.
4708 ///
4709 ///   region ::= '{' region-body
4710 ///
4711 ParseResult OperationParser::parseRegion(
4712     Region &region,
4713     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
4714     bool isIsolatedNameScope) {
4715   // Parse the '{'.
4716   if (parseToken(Token::l_brace, "expected '{' to begin a region"))
4717     return failure();
4718 
4719   // Check for an empty region.
4720   if (entryArguments.empty() && consumeIf(Token::r_brace))
4721     return success();
4722   auto currentPt = opBuilder.saveInsertionPoint();
4723 
4724   // Push a new named value scope.
4725   pushSSANameScope(isIsolatedNameScope);
4726 
4727   // Parse the first block directly to allow for it to be unnamed.
4728   Block *block = new Block();
4729 
4730   // Add arguments to the entry block.
4731   if (!entryArguments.empty()) {
4732     for (auto &placeholderArgPair : entryArguments) {
4733       auto &argInfo = placeholderArgPair.first;
4734       // Ensure that the argument was not already defined.
4735       if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) {
4736         return emitError(argInfo.loc, "region entry argument '" + argInfo.name +
4737                                           "' is already in use")
4738                    .attachNote(getEncodedSourceLocation(*defLoc))
4739                << "previously referenced here";
4740       }
4741       if (addDefinition(placeholderArgPair.first,
4742                         block->addArgument(placeholderArgPair.second))) {
4743         delete block;
4744         return failure();
4745       }
4746     }
4747 
4748     // If we had named arguments, then don't allow a block name.
4749     if (getToken().is(Token::caret_identifier))
4750       return emitError("invalid block name in region with named arguments");
4751   }
4752 
4753   if (parseBlock(block)) {
4754     delete block;
4755     return failure();
4756   }
4757 
4758   // Verify that no other arguments were parsed.
4759   if (!entryArguments.empty() &&
4760       block->getNumArguments() > entryArguments.size()) {
4761     delete block;
4762     return emitError("entry block arguments were already defined");
4763   }
4764 
4765   // Parse the rest of the region.
4766   region.push_back(block);
4767   if (parseRegionBody(region))
4768     return failure();
4769 
4770   // Pop the SSA value scope for this region.
4771   if (popSSANameScope())
4772     return failure();
4773 
4774   // Reset the original insertion point.
4775   opBuilder.restoreInsertionPoint(currentPt);
4776   return success();
4777 }
4778 
4779 /// Region.
4780 ///
4781 ///   region-body ::= block* '}'
4782 ///
4783 ParseResult OperationParser::parseRegionBody(Region &region) {
4784   // Parse the list of blocks.
4785   while (!consumeIf(Token::r_brace)) {
4786     Block *newBlock = nullptr;
4787     if (parseBlock(newBlock))
4788       return failure();
4789     region.push_back(newBlock);
4790   }
4791   return success();
4792 }
4793 
4794 //===----------------------------------------------------------------------===//
4795 // Block Parsing
4796 //===----------------------------------------------------------------------===//
4797 
4798 /// Block declaration.
4799 ///
4800 ///   block ::= block-label? operation*
4801 ///   block-label    ::= block-id block-arg-list? `:`
4802 ///   block-id       ::= caret-id
4803 ///   block-arg-list ::= `(` ssa-id-and-type-list? `)`
4804 ///
4805 ParseResult OperationParser::parseBlock(Block *&block) {
4806   // The first block of a region may already exist, if it does the caret
4807   // identifier is optional.
4808   if (block && getToken().isNot(Token::caret_identifier))
4809     return parseBlockBody(block);
4810 
4811   SMLoc nameLoc = getToken().getLoc();
4812   auto name = getTokenSpelling();
4813   if (parseToken(Token::caret_identifier, "expected block name"))
4814     return failure();
4815 
4816   block = defineBlockNamed(name, nameLoc, block);
4817 
4818   // Fail if the block was already defined.
4819   if (!block)
4820     return emitError(nameLoc, "redefinition of block '") << name << "'";
4821 
4822   // If an argument list is present, parse it.
4823   if (consumeIf(Token::l_paren)) {
4824     SmallVector<BlockArgument, 8> bbArgs;
4825     if (parseOptionalBlockArgList(bbArgs, block) ||
4826         parseToken(Token::r_paren, "expected ')' to end argument list"))
4827       return failure();
4828   }
4829 
4830   if (parseToken(Token::colon, "expected ':' after block name"))
4831     return failure();
4832 
4833   return parseBlockBody(block);
4834 }
4835 
4836 ParseResult OperationParser::parseBlockBody(Block *block) {
4837   // Set the insertion point to the end of the block to parse.
4838   opBuilder.setInsertionPointToEnd(block);
4839 
4840   // Parse the list of operations that make up the body of the block.
4841   while (getToken().isNot(Token::caret_identifier, Token::r_brace))
4842     if (parseOperation())
4843       return failure();
4844 
4845   return success();
4846 }
4847 
4848 /// Get the block with the specified name, creating it if it doesn't already
4849 /// exist.  The location specified is the point of use, which allows
4850 /// us to diagnose references to blocks that are not defined precisely.
4851 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) {
4852   auto &blockAndLoc = getBlockInfoByName(name);
4853   if (!blockAndLoc.first) {
4854     blockAndLoc = {new Block(), loc};
4855     insertForwardRef(blockAndLoc.first, loc);
4856   }
4857 
4858   return blockAndLoc.first;
4859 }
4860 
4861 /// Define the block with the specified name. Returns the Block* or nullptr in
4862 /// the case of redefinition.
4863 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc,
4864                                          Block *existing) {
4865   auto &blockAndLoc = getBlockInfoByName(name);
4866   if (!blockAndLoc.first) {
4867     // If the caller provided a block, use it.  Otherwise create a new one.
4868     if (!existing)
4869       existing = new Block();
4870     blockAndLoc.first = existing;
4871     blockAndLoc.second = loc;
4872     return blockAndLoc.first;
4873   }
4874 
4875   // Forward declarations are removed once defined, so if we are defining a
4876   // existing block and it is not a forward declaration, then it is a
4877   // redeclaration.
4878   if (!eraseForwardRef(blockAndLoc.first))
4879     return nullptr;
4880   return blockAndLoc.first;
4881 }
4882 
4883 /// Parse a (possibly empty) list of SSA operands with types as block arguments.
4884 ///
4885 ///   ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
4886 ///
4887 ParseResult OperationParser::parseOptionalBlockArgList(
4888     SmallVectorImpl<BlockArgument> &results, Block *owner) {
4889   if (getToken().is(Token::r_brace))
4890     return success();
4891 
4892   // If the block already has arguments, then we're handling the entry block.
4893   // Parse and register the names for the arguments, but do not add them.
4894   bool definingExistingArgs = owner->getNumArguments() != 0;
4895   unsigned nextArgument = 0;
4896 
4897   return parseCommaSeparatedList([&]() -> ParseResult {
4898     return parseSSADefOrUseAndType(
4899         [&](SSAUseInfo useInfo, Type type) -> ParseResult {
4900           // If this block did not have existing arguments, define a new one.
4901           if (!definingExistingArgs)
4902             return addDefinition(useInfo, owner->addArgument(type));
4903 
4904           // Otherwise, ensure that this argument has already been created.
4905           if (nextArgument >= owner->getNumArguments())
4906             return emitError("too many arguments specified in argument list");
4907 
4908           // Finally, make sure the existing argument has the correct type.
4909           auto arg = owner->getArgument(nextArgument++);
4910           if (arg.getType() != type)
4911             return emitError("argument and block argument type mismatch");
4912           return addDefinition(useInfo, arg);
4913         });
4914   });
4915 }
4916 
4917 //===----------------------------------------------------------------------===//
4918 // Top-level entity parsing.
4919 //===----------------------------------------------------------------------===//
4920 
4921 namespace {
4922 /// This parser handles entities that are only valid at the top level of the
4923 /// file.
4924 class ModuleParser : public Parser {
4925 public:
4926   explicit ModuleParser(ParserState &state) : Parser(state) {}
4927 
4928   ParseResult parseModule(ModuleOp module);
4929 
4930 private:
4931   /// Parse an attribute alias declaration.
4932   ParseResult parseAttributeAliasDef();
4933 
4934   /// Parse an attribute alias declaration.
4935   ParseResult parseTypeAliasDef();
4936 };
4937 } // end anonymous namespace
4938 
4939 /// Parses an attribute alias declaration.
4940 ///
4941 ///   attribute-alias-def ::= '#' alias-name `=` attribute-value
4942 ///
4943 ParseResult ModuleParser::parseAttributeAliasDef() {
4944   assert(getToken().is(Token::hash_identifier));
4945   StringRef aliasName = getTokenSpelling().drop_front();
4946 
4947   // Check for redefinitions.
4948   if (getState().symbols.attributeAliasDefinitions.count(aliasName) > 0)
4949     return emitError("redefinition of attribute alias id '" + aliasName + "'");
4950 
4951   // Make sure this isn't invading the dialect attribute namespace.
4952   if (aliasName.contains('.'))
4953     return emitError("attribute names with a '.' are reserved for "
4954                      "dialect-defined names");
4955 
4956   consumeToken(Token::hash_identifier);
4957 
4958   // Parse the '='.
4959   if (parseToken(Token::equal, "expected '=' in attribute alias definition"))
4960     return failure();
4961 
4962   // Parse the attribute value.
4963   Attribute attr = parseAttribute();
4964   if (!attr)
4965     return failure();
4966 
4967   getState().symbols.attributeAliasDefinitions[aliasName] = attr;
4968   return success();
4969 }
4970 
4971 /// Parse a type alias declaration.
4972 ///
4973 ///   type-alias-def ::= '!' alias-name `=` 'type' type
4974 ///
4975 ParseResult ModuleParser::parseTypeAliasDef() {
4976   assert(getToken().is(Token::exclamation_identifier));
4977   StringRef aliasName = getTokenSpelling().drop_front();
4978 
4979   // Check for redefinitions.
4980   if (getState().symbols.typeAliasDefinitions.count(aliasName) > 0)
4981     return emitError("redefinition of type alias id '" + aliasName + "'");
4982 
4983   // Make sure this isn't invading the dialect type namespace.
4984   if (aliasName.contains('.'))
4985     return emitError("type names with a '.' are reserved for "
4986                      "dialect-defined names");
4987 
4988   consumeToken(Token::exclamation_identifier);
4989 
4990   // Parse the '=' and 'type'.
4991   if (parseToken(Token::equal, "expected '=' in type alias definition") ||
4992       parseToken(Token::kw_type, "expected 'type' in type alias definition"))
4993     return failure();
4994 
4995   // Parse the type.
4996   Type aliasedType = parseType();
4997   if (!aliasedType)
4998     return failure();
4999 
5000   // Register this alias with the parser state.
5001   getState().symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType);
5002   return success();
5003 }
5004 
5005 /// This is the top-level module parser.
5006 ParseResult ModuleParser::parseModule(ModuleOp module) {
5007   OperationParser opParser(getState(), module);
5008 
5009   // Module itself is a name scope.
5010   opParser.pushSSANameScope(/*isIsolated=*/true);
5011 
5012   while (true) {
5013     switch (getToken().getKind()) {
5014     default:
5015       // Parse a top-level operation.
5016       if (opParser.parseOperation())
5017         return failure();
5018       break;
5019 
5020     // If we got to the end of the file, then we're done.
5021     case Token::eof: {
5022       if (opParser.finalize())
5023         return failure();
5024 
5025       // Handle the case where the top level module was explicitly defined.
5026       auto &bodyBlocks = module.getBodyRegion().getBlocks();
5027       auto &operations = bodyBlocks.front().getOperations();
5028       assert(!operations.empty() && "expected a valid module terminator");
5029 
5030       // Check that the first operation is a module, and it is the only
5031       // non-terminator operation.
5032       ModuleOp nested = dyn_cast<ModuleOp>(operations.front());
5033       if (nested && std::next(operations.begin(), 2) == operations.end()) {
5034         // Merge the data of the nested module operation into 'module'.
5035         module.setLoc(nested.getLoc());
5036         module.setAttrs(nested.getOperation()->getMutableAttrDict());
5037         bodyBlocks.splice(bodyBlocks.end(), nested.getBodyRegion().getBlocks());
5038 
5039         // Erase the original module body.
5040         bodyBlocks.pop_front();
5041       }
5042 
5043       return opParser.popSSANameScope();
5044     }
5045 
5046     // If we got an error token, then the lexer already emitted an error, just
5047     // stop.  Someday we could introduce error recovery if there was demand
5048     // for it.
5049     case Token::error:
5050       return failure();
5051 
5052     // Parse an attribute alias.
5053     case Token::hash_identifier:
5054       if (parseAttributeAliasDef())
5055         return failure();
5056       break;
5057 
5058     // Parse a type alias.
5059     case Token::exclamation_identifier:
5060       if (parseTypeAliasDef())
5061         return failure();
5062       break;
5063     }
5064   }
5065 }
5066 
5067 //===----------------------------------------------------------------------===//
5068 
5069 /// This parses the file specified by the indicated SourceMgr and returns an
5070 /// MLIR module if it was valid.  If not, it emits diagnostics and returns
5071 /// null.
5072 OwningModuleRef mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr,
5073                                       MLIRContext *context) {
5074   auto sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
5075 
5076   // This is the result module we are parsing into.
5077   OwningModuleRef module(ModuleOp::create(FileLineColLoc::get(
5078       sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0, context)));
5079 
5080   SymbolState aliasState;
5081   ParserState state(sourceMgr, context, aliasState);
5082   if (ModuleParser(state).parseModule(*module))
5083     return nullptr;
5084 
5085   // Make sure the parse module has no other structural problems detected by
5086   // the verifier.
5087   if (failed(verify(*module)))
5088     return nullptr;
5089 
5090   return module;
5091 }
5092 
5093 /// This parses the file specified by the indicated filename and returns an
5094 /// MLIR module if it was valid.  If not, the error message is emitted through
5095 /// the error handler registered in the context, and a null pointer is returned.
5096 OwningModuleRef mlir::parseSourceFile(StringRef filename,
5097                                       MLIRContext *context) {
5098   llvm::SourceMgr sourceMgr;
5099   return parseSourceFile(filename, sourceMgr, context);
5100 }
5101 
5102 /// This parses the file specified by the indicated filename using the provided
5103 /// SourceMgr and returns an MLIR module if it was valid.  If not, the error
5104 /// message is emitted through the error handler registered in the context, and
5105 /// a null pointer is returned.
5106 OwningModuleRef mlir::parseSourceFile(StringRef filename,
5107                                       llvm::SourceMgr &sourceMgr,
5108                                       MLIRContext *context) {
5109   if (sourceMgr.getNumBuffers() != 0) {
5110     // TODO(b/136086478): Extend to support multiple buffers.
5111     emitError(mlir::UnknownLoc::get(context),
5112               "only main buffer parsed at the moment");
5113     return nullptr;
5114   }
5115   auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename);
5116   if (std::error_code error = file_or_err.getError()) {
5117     emitError(mlir::UnknownLoc::get(context),
5118               "could not open input file " + filename);
5119     return nullptr;
5120   }
5121 
5122   // Load the MLIR module.
5123   sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc());
5124   return parseSourceFile(sourceMgr, context);
5125 }
5126 
5127 /// This parses the program string to a MLIR module if it was valid. If not,
5128 /// it emits diagnostics and returns null.
5129 OwningModuleRef mlir::parseSourceString(StringRef moduleStr,
5130                                         MLIRContext *context) {
5131   auto memBuffer = MemoryBuffer::getMemBuffer(moduleStr);
5132   if (!memBuffer)
5133     return nullptr;
5134 
5135   SourceMgr sourceMgr;
5136   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
5137   return parseSourceFile(sourceMgr, context);
5138 }
5139 
5140 /// Parses a symbol, of type 'T', and returns it if parsing was successful. If
5141 /// parsing failed, nullptr is returned. The number of bytes read from the input
5142 /// string is returned in 'numRead'.
5143 template <typename T, typename ParserFn>
5144 static T parseSymbol(StringRef inputStr, MLIRContext *context, size_t &numRead,
5145                      ParserFn &&parserFn) {
5146   SymbolState aliasState;
5147   return parseSymbol<T>(
5148       inputStr, context, aliasState,
5149       [&](Parser &parser) {
5150         SourceMgrDiagnosticHandler handler(
5151             const_cast<llvm::SourceMgr &>(parser.getSourceMgr()),
5152             parser.getContext());
5153         return parserFn(parser);
5154       },
5155       &numRead);
5156 }
5157 
5158 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context) {
5159   size_t numRead = 0;
5160   return parseAttribute(attrStr, context, numRead);
5161 }
5162 Attribute mlir::parseAttribute(StringRef attrStr, Type type) {
5163   size_t numRead = 0;
5164   return parseAttribute(attrStr, type, numRead);
5165 }
5166 
5167 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context,
5168                                size_t &numRead) {
5169   return parseSymbol<Attribute>(attrStr, context, numRead, [](Parser &parser) {
5170     return parser.parseAttribute();
5171   });
5172 }
5173 Attribute mlir::parseAttribute(StringRef attrStr, Type type, size_t &numRead) {
5174   return parseSymbol<Attribute>(
5175       attrStr, type.getContext(), numRead,
5176       [type](Parser &parser) { return parser.parseAttribute(type); });
5177 }
5178 
5179 Type mlir::parseType(StringRef typeStr, MLIRContext *context) {
5180   size_t numRead = 0;
5181   return parseType(typeStr, context, numRead);
5182 }
5183 
5184 Type mlir::parseType(StringRef typeStr, MLIRContext *context, size_t &numRead) {
5185   return parseSymbol<Type>(typeStr, context, numRead,
5186                            [](Parser &parser) { return parser.parseType(); });
5187 }
5188