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