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