1 //===- Parser.cpp - MLIR Parser Implementation ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the parser for the MLIR textual form.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "Parser.h"
14 #include "mlir/IR/AffineMap.h"
15 #include "mlir/IR/Dialect.h"
16 #include "mlir/IR/Module.h"
17 #include "mlir/IR/Verifier.h"
18 #include "mlir/Parser.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/StringSet.h"
21 #include "llvm/ADT/bit.h"
22 #include "llvm/Support/PrettyStackTrace.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include <algorithm>
25 
26 using namespace mlir;
27 using namespace mlir::detail;
28 using llvm::MemoryBuffer;
29 using llvm::SMLoc;
30 using llvm::SourceMgr;
31 
32 //===----------------------------------------------------------------------===//
33 // Parser
34 //===----------------------------------------------------------------------===//
35 
36 /// Parse a comma separated list of elements that must have at least one entry
37 /// in it.
38 ParseResult
39 Parser::parseCommaSeparatedList(function_ref<ParseResult()> parseElement) {
40   // Non-empty case starts with an element.
41   if (parseElement())
42     return failure();
43 
44   // Otherwise we have a list of comma separated elements.
45   while (consumeIf(Token::comma)) {
46     if (parseElement())
47       return failure();
48   }
49   return success();
50 }
51 
52 /// Parse a comma-separated list of elements, terminated with an arbitrary
53 /// token.  This allows empty lists if allowEmptyList is true.
54 ///
55 ///   abstract-list ::= rightToken                  // if allowEmptyList == true
56 ///   abstract-list ::= element (',' element)* rightToken
57 ///
58 ParseResult
59 Parser::parseCommaSeparatedListUntil(Token::Kind rightToken,
60                                      function_ref<ParseResult()> parseElement,
61                                      bool allowEmptyList) {
62   // Handle the empty case.
63   if (getToken().is(rightToken)) {
64     if (!allowEmptyList)
65       return emitError("expected list element");
66     consumeToken(rightToken);
67     return success();
68   }
69 
70   if (parseCommaSeparatedList(parseElement) ||
71       parseToken(rightToken, "expected ',' or '" +
72                                  Token::getTokenSpelling(rightToken) + "'"))
73     return failure();
74 
75   return success();
76 }
77 
78 InFlightDiagnostic Parser::emitError(SMLoc loc, const Twine &message) {
79   auto diag = mlir::emitError(getEncodedSourceLocation(loc), message);
80 
81   // If we hit a parse error in response to a lexer error, then the lexer
82   // already reported the error.
83   if (getToken().is(Token::error))
84     diag.abandon();
85   return diag;
86 }
87 
88 /// Consume the specified token if present and return success.  On failure,
89 /// output a diagnostic and return failure.
90 ParseResult Parser::parseToken(Token::Kind expectedToken,
91                                const Twine &message) {
92   if (consumeIf(expectedToken))
93     return success();
94   return emitError(message);
95 }
96 
97 //===----------------------------------------------------------------------===//
98 // OperationParser
99 //===----------------------------------------------------------------------===//
100 
101 namespace {
102 /// This class provides support for parsing operations and regions of
103 /// operations.
104 class OperationParser : public Parser {
105 public:
106   OperationParser(ParserState &state, ModuleOp moduleOp)
107       : Parser(state), opBuilder(moduleOp.getBodyRegion()), moduleOp(moduleOp) {
108   }
109 
110   ~OperationParser();
111 
112   /// After parsing is finished, this function must be called to see if there
113   /// are any remaining issues.
114   ParseResult finalize();
115 
116   //===--------------------------------------------------------------------===//
117   // SSA Value Handling
118   //===--------------------------------------------------------------------===//
119 
120   /// This represents a use of an SSA value in the program.  The first two
121   /// entries in the tuple are the name and result number of a reference.  The
122   /// third is the location of the reference, which is used in case this ends
123   /// up being a use of an undefined value.
124   struct SSAUseInfo {
125     StringRef name;  // Value name, e.g. %42 or %abc
126     unsigned number; // Number, specified with #12
127     SMLoc loc;       // Location of first definition or use.
128   };
129 
130   /// Push a new SSA name scope to the parser.
131   void pushSSANameScope(bool isIsolated);
132 
133   /// Pop the last SSA name scope from the parser.
134   ParseResult popSSANameScope();
135 
136   /// Register a definition of a value with the symbol table.
137   ParseResult addDefinition(SSAUseInfo useInfo, Value value);
138 
139   /// Parse an optional list of SSA uses into 'results'.
140   ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
141 
142   /// Parse a single SSA use into 'result'.
143   ParseResult parseSSAUse(SSAUseInfo &result);
144 
145   /// Given a reference to an SSA value and its type, return a reference. This
146   /// returns null on failure.
147   Value resolveSSAUse(SSAUseInfo useInfo, Type type);
148 
149   ParseResult
150   parseSSADefOrUseAndType(function_ref<ParseResult(SSAUseInfo, Type)> action);
151 
152   ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value> &results);
153 
154   /// Return the location of the value identified by its name and number if it
155   /// has been already reference.
156   Optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) {
157     auto &values = isolatedNameScopes.back().values;
158     if (!values.count(name) || number >= values[name].size())
159       return {};
160     if (values[name][number].first)
161       return values[name][number].second;
162     return {};
163   }
164 
165   //===--------------------------------------------------------------------===//
166   // Operation Parsing
167   //===--------------------------------------------------------------------===//
168 
169   /// Parse an operation instance.
170   ParseResult parseOperation();
171 
172   /// Parse a single operation successor.
173   ParseResult parseSuccessor(Block *&dest);
174 
175   /// Parse a comma-separated list of operation successors in brackets.
176   ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations);
177 
178   /// Parse an operation instance that is in the generic form.
179   Operation *parseGenericOperation();
180 
181   /// Parse an operation instance that is in the generic form and insert it at
182   /// the provided insertion point.
183   Operation *parseGenericOperation(Block *insertBlock,
184                                    Block::iterator insertPt);
185 
186   /// This is the structure of a result specifier in the assembly syntax,
187   /// including the name, number of results, and location.
188   typedef std::tuple<StringRef, unsigned, SMLoc> ResultRecord;
189 
190   /// Parse an operation instance that is in the op-defined custom form.
191   /// resultInfo specifies information about the "%name =" specifiers.
192   Operation *parseCustomOperation(ArrayRef<ResultRecord> resultIDs);
193 
194   //===--------------------------------------------------------------------===//
195   // Region Parsing
196   //===--------------------------------------------------------------------===//
197 
198   /// Parse a region into 'region' with the provided entry block arguments.
199   /// 'isIsolatedNameScope' indicates if the naming scope of this region is
200   /// isolated from those above.
201   ParseResult parseRegion(Region &region,
202                           ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments,
203                           bool isIsolatedNameScope = false);
204 
205   /// Parse a region body into 'region'.
206   ParseResult parseRegionBody(Region &region);
207 
208   //===--------------------------------------------------------------------===//
209   // Block Parsing
210   //===--------------------------------------------------------------------===//
211 
212   /// Parse a new block into 'block'.
213   ParseResult parseBlock(Block *&block);
214 
215   /// Parse a list of operations into 'block'.
216   ParseResult parseBlockBody(Block *block);
217 
218   /// Parse a (possibly empty) list of block arguments.
219   ParseResult parseOptionalBlockArgList(SmallVectorImpl<BlockArgument> &results,
220                                         Block *owner);
221 
222   /// Get the block with the specified name, creating it if it doesn't
223   /// already exist.  The location specified is the point of use, which allows
224   /// us to diagnose references to blocks that are not defined precisely.
225   Block *getBlockNamed(StringRef name, SMLoc loc);
226 
227   /// Define the block with the specified name. Returns the Block* or nullptr in
228   /// the case of redefinition.
229   Block *defineBlockNamed(StringRef name, SMLoc loc, Block *existing);
230 
231 private:
232   /// Returns the info for a block at the current scope for the given name.
233   std::pair<Block *, SMLoc> &getBlockInfoByName(StringRef name) {
234     return blocksByName.back()[name];
235   }
236 
237   /// Insert a new forward reference to the given block.
238   void insertForwardRef(Block *block, SMLoc loc) {
239     forwardRef.back().try_emplace(block, loc);
240   }
241 
242   /// Erase any forward reference to the given block.
243   bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); }
244 
245   /// Record that a definition was added at the current scope.
246   void recordDefinition(StringRef def);
247 
248   /// Get the value entry for the given SSA name.
249   SmallVectorImpl<std::pair<Value, SMLoc>> &getSSAValueEntry(StringRef name);
250 
251   /// Create a forward reference placeholder value with the given location and
252   /// result type.
253   Value createForwardRefPlaceholder(SMLoc loc, Type type);
254 
255   /// Return true if this is a forward reference.
256   bool isForwardRefPlaceholder(Value value) {
257     return forwardRefPlaceholders.count(value);
258   }
259 
260   /// This struct represents an isolated SSA name scope. This scope may contain
261   /// other nested non-isolated scopes. These scopes are used for operations
262   /// that are known to be isolated to allow for reusing names within their
263   /// regions, even if those names are used above.
264   struct IsolatedSSANameScope {
265     /// Record that a definition was added at the current scope.
266     void recordDefinition(StringRef def) {
267       definitionsPerScope.back().insert(def);
268     }
269 
270     /// Push a nested name scope.
271     void pushSSANameScope() { definitionsPerScope.push_back({}); }
272 
273     /// Pop a nested name scope.
274     void popSSANameScope() {
275       for (auto &def : definitionsPerScope.pop_back_val())
276         values.erase(def.getKey());
277     }
278 
279     /// This keeps track of all of the SSA values we are tracking for each name
280     /// scope, indexed by their name. This has one entry per result number.
281     llvm::StringMap<SmallVector<std::pair<Value, SMLoc>, 1>> values;
282 
283     /// This keeps track of all of the values defined by a specific name scope.
284     SmallVector<llvm::StringSet<>, 2> definitionsPerScope;
285   };
286 
287   /// A list of isolated name scopes.
288   SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes;
289 
290   /// This keeps track of the block names as well as the location of the first
291   /// reference for each nested name scope. This is used to diagnose invalid
292   /// block references and memorize them.
293   SmallVector<DenseMap<StringRef, std::pair<Block *, SMLoc>>, 2> blocksByName;
294   SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef;
295 
296   /// These are all of the placeholders we've made along with the location of
297   /// their first reference, to allow checking for use of undefined values.
298   DenseMap<Value, SMLoc> forwardRefPlaceholders;
299 
300   /// The builder used when creating parsed operation instances.
301   OpBuilder opBuilder;
302 
303   /// The top level module operation.
304   ModuleOp moduleOp;
305 };
306 } // end anonymous namespace
307 
308 OperationParser::~OperationParser() {
309   for (auto &fwd : forwardRefPlaceholders) {
310     // Drop all uses of undefined forward declared reference and destroy
311     // defining operation.
312     fwd.first.dropAllUses();
313     fwd.first.getDefiningOp()->destroy();
314   }
315 }
316 
317 /// After parsing is finished, this function must be called to see if there are
318 /// any remaining issues.
319 ParseResult OperationParser::finalize() {
320   // Check for any forward references that are left.  If we find any, error
321   // out.
322   if (!forwardRefPlaceholders.empty()) {
323     SmallVector<const char *, 4> errors;
324     // Iteration over the map isn't deterministic, so sort by source location.
325     for (auto entry : forwardRefPlaceholders)
326       errors.push_back(entry.second.getPointer());
327     llvm::array_pod_sort(errors.begin(), errors.end());
328 
329     for (auto entry : errors) {
330       auto loc = SMLoc::getFromPointer(entry);
331       emitError(loc, "use of undeclared SSA value name");
332     }
333     return failure();
334   }
335 
336   return success();
337 }
338 
339 //===----------------------------------------------------------------------===//
340 // SSA Value Handling
341 //===----------------------------------------------------------------------===//
342 
343 void OperationParser::pushSSANameScope(bool isIsolated) {
344   blocksByName.push_back(DenseMap<StringRef, std::pair<Block *, SMLoc>>());
345   forwardRef.push_back(DenseMap<Block *, SMLoc>());
346 
347   // Push back a new name definition scope.
348   if (isIsolated)
349     isolatedNameScopes.push_back({});
350   isolatedNameScopes.back().pushSSANameScope();
351 }
352 
353 ParseResult OperationParser::popSSANameScope() {
354   auto forwardRefInCurrentScope = forwardRef.pop_back_val();
355 
356   // Verify that all referenced blocks were defined.
357   if (!forwardRefInCurrentScope.empty()) {
358     SmallVector<std::pair<const char *, Block *>, 4> errors;
359     // Iteration over the map isn't deterministic, so sort by source location.
360     for (auto entry : forwardRefInCurrentScope) {
361       errors.push_back({entry.second.getPointer(), entry.first});
362       // Add this block to the top-level region to allow for automatic cleanup.
363       moduleOp.getOperation()->getRegion(0).push_back(entry.first);
364     }
365     llvm::array_pod_sort(errors.begin(), errors.end());
366 
367     for (auto entry : errors) {
368       auto loc = SMLoc::getFromPointer(entry.first);
369       emitError(loc, "reference to an undefined block");
370     }
371     return failure();
372   }
373 
374   // Pop the next nested namescope. If there is only one internal namescope,
375   // just pop the isolated scope.
376   auto &currentNameScope = isolatedNameScopes.back();
377   if (currentNameScope.definitionsPerScope.size() == 1)
378     isolatedNameScopes.pop_back();
379   else
380     currentNameScope.popSSANameScope();
381 
382   blocksByName.pop_back();
383   return success();
384 }
385 
386 /// Register a definition of a value with the symbol table.
387 ParseResult OperationParser::addDefinition(SSAUseInfo useInfo, Value value) {
388   auto &entries = getSSAValueEntry(useInfo.name);
389 
390   // Make sure there is a slot for this value.
391   if (entries.size() <= useInfo.number)
392     entries.resize(useInfo.number + 1);
393 
394   // If we already have an entry for this, check to see if it was a definition
395   // or a forward reference.
396   if (auto existing = entries[useInfo.number].first) {
397     if (!isForwardRefPlaceholder(existing)) {
398       return emitError(useInfo.loc)
399           .append("redefinition of SSA value '", useInfo.name, "'")
400           .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
401           .append("previously defined here");
402     }
403 
404     if (existing.getType() != value.getType()) {
405       return emitError(useInfo.loc)
406           .append("definition of SSA value '", useInfo.name, "#",
407                   useInfo.number, "' has type ", value.getType())
408           .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
409           .append("previously used here with type ", existing.getType());
410     }
411 
412     // If it was a forward reference, update everything that used it to use
413     // the actual definition instead, delete the forward ref, and remove it
414     // from our set of forward references we track.
415     existing.replaceAllUsesWith(value);
416     existing.getDefiningOp()->destroy();
417     forwardRefPlaceholders.erase(existing);
418   }
419 
420   /// Record this definition for the current scope.
421   entries[useInfo.number] = {value, useInfo.loc};
422   recordDefinition(useInfo.name);
423   return success();
424 }
425 
426 /// Parse a (possibly empty) list of SSA operands.
427 ///
428 ///   ssa-use-list ::= ssa-use (`,` ssa-use)*
429 ///   ssa-use-list-opt ::= ssa-use-list?
430 ///
431 ParseResult
432 OperationParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
433   if (getToken().isNot(Token::percent_identifier))
434     return success();
435   return parseCommaSeparatedList([&]() -> ParseResult {
436     SSAUseInfo result;
437     if (parseSSAUse(result))
438       return failure();
439     results.push_back(result);
440     return success();
441   });
442 }
443 
444 /// Parse a SSA operand for an operation.
445 ///
446 ///   ssa-use ::= ssa-id
447 ///
448 ParseResult OperationParser::parseSSAUse(SSAUseInfo &result) {
449   result.name = getTokenSpelling();
450   result.number = 0;
451   result.loc = getToken().getLoc();
452   if (parseToken(Token::percent_identifier, "expected SSA operand"))
453     return failure();
454 
455   // If we have an attribute ID, it is a result number.
456   if (getToken().is(Token::hash_identifier)) {
457     if (auto value = getToken().getHashIdentifierNumber())
458       result.number = value.getValue();
459     else
460       return emitError("invalid SSA value result number");
461     consumeToken(Token::hash_identifier);
462   }
463 
464   return success();
465 }
466 
467 /// Given an unbound reference to an SSA value and its type, return the value
468 /// it specifies.  This returns null on failure.
469 Value OperationParser::resolveSSAUse(SSAUseInfo useInfo, Type type) {
470   auto &entries = getSSAValueEntry(useInfo.name);
471 
472   // If we have already seen a value of this name, return it.
473   if (useInfo.number < entries.size() && entries[useInfo.number].first) {
474     auto result = entries[useInfo.number].first;
475     // Check that the type matches the other uses.
476     if (result.getType() == type)
477       return result;
478 
479     emitError(useInfo.loc, "use of value '")
480         .append(useInfo.name,
481                 "' expects different type than prior uses: ", type, " vs ",
482                 result.getType())
483         .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
484         .append("prior use here");
485     return nullptr;
486   }
487 
488   // Make sure we have enough slots for this.
489   if (entries.size() <= useInfo.number)
490     entries.resize(useInfo.number + 1);
491 
492   // If the value has already been defined and this is an overly large result
493   // number, diagnose that.
494   if (entries[0].first && !isForwardRefPlaceholder(entries[0].first))
495     return (emitError(useInfo.loc, "reference to invalid result number"),
496             nullptr);
497 
498   // Otherwise, this is a forward reference.  Create a placeholder and remember
499   // that we did so.
500   auto result = createForwardRefPlaceholder(useInfo.loc, type);
501   entries[useInfo.number].first = result;
502   entries[useInfo.number].second = useInfo.loc;
503   return result;
504 }
505 
506 /// Parse an SSA use with an associated type.
507 ///
508 ///   ssa-use-and-type ::= ssa-use `:` type
509 ParseResult OperationParser::parseSSADefOrUseAndType(
510     function_ref<ParseResult(SSAUseInfo, Type)> action) {
511   SSAUseInfo useInfo;
512   if (parseSSAUse(useInfo) ||
513       parseToken(Token::colon, "expected ':' and type for SSA operand"))
514     return failure();
515 
516   auto type = parseType();
517   if (!type)
518     return failure();
519 
520   return action(useInfo, type);
521 }
522 
523 /// Parse a (possibly empty) list of SSA operands, followed by a colon, then
524 /// followed by a type list.
525 ///
526 ///   ssa-use-and-type-list
527 ///     ::= ssa-use-list ':' type-list-no-parens
528 ///
529 ParseResult OperationParser::parseOptionalSSAUseAndTypeList(
530     SmallVectorImpl<Value> &results) {
531   SmallVector<SSAUseInfo, 4> valueIDs;
532   if (parseOptionalSSAUseList(valueIDs))
533     return failure();
534 
535   // If there were no operands, then there is no colon or type lists.
536   if (valueIDs.empty())
537     return success();
538 
539   SmallVector<Type, 4> types;
540   if (parseToken(Token::colon, "expected ':' in operand list") ||
541       parseTypeListNoParens(types))
542     return failure();
543 
544   if (valueIDs.size() != types.size())
545     return emitError("expected ")
546            << valueIDs.size() << " types to match operand list";
547 
548   results.reserve(valueIDs.size());
549   for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
550     if (auto value = resolveSSAUse(valueIDs[i], types[i]))
551       results.push_back(value);
552     else
553       return failure();
554   }
555 
556   return success();
557 }
558 
559 /// Record that a definition was added at the current scope.
560 void OperationParser::recordDefinition(StringRef def) {
561   isolatedNameScopes.back().recordDefinition(def);
562 }
563 
564 /// Get the value entry for the given SSA name.
565 SmallVectorImpl<std::pair<Value, SMLoc>> &
566 OperationParser::getSSAValueEntry(StringRef name) {
567   return isolatedNameScopes.back().values[name];
568 }
569 
570 /// Create and remember a new placeholder for a forward reference.
571 Value OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) {
572   // Forward references are always created as operations, because we just need
573   // something with a def/use chain.
574   //
575   // We create these placeholders as having an empty name, which we know
576   // cannot be created through normal user input, allowing us to distinguish
577   // them.
578   auto name = OperationName("placeholder", getContext());
579   auto *op = Operation::create(
580       getEncodedSourceLocation(loc), name, type, /*operands=*/{},
581       /*attributes=*/llvm::None, /*successors=*/{}, /*numRegions=*/0);
582   forwardRefPlaceholders[op->getResult(0)] = loc;
583   return op->getResult(0);
584 }
585 
586 //===----------------------------------------------------------------------===//
587 // Operation Parsing
588 //===----------------------------------------------------------------------===//
589 
590 /// Parse an operation.
591 ///
592 ///  operation         ::= op-result-list?
593 ///                        (generic-operation | custom-operation)
594 ///                        trailing-location?
595 ///  generic-operation ::= string-literal `(` ssa-use-list? `)`
596 ///                        successor-list? (`(` region-list `)`)?
597 ///                        attribute-dict? `:` function-type
598 ///  custom-operation  ::= bare-id custom-operation-format
599 ///  op-result-list    ::= op-result (`,` op-result)* `=`
600 ///  op-result         ::= ssa-id (`:` integer-literal)
601 ///
602 ParseResult OperationParser::parseOperation() {
603   auto loc = getToken().getLoc();
604   SmallVector<ResultRecord, 1> resultIDs;
605   size_t numExpectedResults = 0;
606   if (getToken().is(Token::percent_identifier)) {
607     // Parse the group of result ids.
608     auto parseNextResult = [&]() -> ParseResult {
609       // Parse the next result id.
610       if (!getToken().is(Token::percent_identifier))
611         return emitError("expected valid ssa identifier");
612 
613       Token nameTok = getToken();
614       consumeToken(Token::percent_identifier);
615 
616       // If the next token is a ':', we parse the expected result count.
617       size_t expectedSubResults = 1;
618       if (consumeIf(Token::colon)) {
619         // Check that the next token is an integer.
620         if (!getToken().is(Token::integer))
621           return emitError("expected integer number of results");
622 
623         // Check that number of results is > 0.
624         auto val = getToken().getUInt64IntegerValue();
625         if (!val.hasValue() || val.getValue() < 1)
626           return emitError("expected named operation to have atleast 1 result");
627         consumeToken(Token::integer);
628         expectedSubResults = *val;
629       }
630 
631       resultIDs.emplace_back(nameTok.getSpelling(), expectedSubResults,
632                              nameTok.getLoc());
633       numExpectedResults += expectedSubResults;
634       return success();
635     };
636     if (parseCommaSeparatedList(parseNextResult))
637       return failure();
638 
639     if (parseToken(Token::equal, "expected '=' after SSA name"))
640       return failure();
641   }
642 
643   Operation *op;
644   if (getToken().is(Token::bare_identifier) || getToken().isKeyword())
645     op = parseCustomOperation(resultIDs);
646   else if (getToken().is(Token::string))
647     op = parseGenericOperation();
648   else
649     return emitError("expected operation name in quotes");
650 
651   // If parsing of the basic operation failed, then this whole thing fails.
652   if (!op)
653     return failure();
654 
655   // If the operation had a name, register it.
656   if (!resultIDs.empty()) {
657     if (op->getNumResults() == 0)
658       return emitError(loc, "cannot name an operation with no results");
659     if (numExpectedResults != op->getNumResults())
660       return emitError(loc, "operation defines ")
661              << op->getNumResults() << " results but was provided "
662              << numExpectedResults << " to bind";
663 
664     // Add definitions for each of the result groups.
665     unsigned opResI = 0;
666     for (ResultRecord &resIt : resultIDs) {
667       for (unsigned subRes : llvm::seq<unsigned>(0, std::get<1>(resIt))) {
668         if (addDefinition({std::get<0>(resIt), subRes, std::get<2>(resIt)},
669                           op->getResult(opResI++)))
670           return failure();
671       }
672     }
673   }
674 
675   return success();
676 }
677 
678 /// Parse a single operation successor.
679 ///
680 ///   successor ::= block-id
681 ///
682 ParseResult OperationParser::parseSuccessor(Block *&dest) {
683   // Verify branch is identifier and get the matching block.
684   if (!getToken().is(Token::caret_identifier))
685     return emitError("expected block name");
686   dest = getBlockNamed(getTokenSpelling(), getToken().getLoc());
687   consumeToken();
688   return success();
689 }
690 
691 /// Parse a comma-separated list of operation successors in brackets.
692 ///
693 ///   successor-list ::= `[` successor (`,` successor )* `]`
694 ///
695 ParseResult
696 OperationParser::parseSuccessors(SmallVectorImpl<Block *> &destinations) {
697   if (parseToken(Token::l_square, "expected '['"))
698     return failure();
699 
700   auto parseElt = [this, &destinations] {
701     Block *dest;
702     ParseResult res = parseSuccessor(dest);
703     destinations.push_back(dest);
704     return res;
705   };
706   return parseCommaSeparatedListUntil(Token::r_square, parseElt,
707                                       /*allowEmptyList=*/false);
708 }
709 
710 namespace {
711 // RAII-style guard for cleaning up the regions in the operation state before
712 // deleting them.  Within the parser, regions may get deleted if parsing failed,
713 // and other errors may be present, in particular undominated uses.  This makes
714 // sure such uses are deleted.
715 struct CleanupOpStateRegions {
716   ~CleanupOpStateRegions() {
717     SmallVector<Region *, 4> regionsToClean;
718     regionsToClean.reserve(state.regions.size());
719     for (auto &region : state.regions)
720       if (region)
721         for (auto &block : *region)
722           block.dropAllDefinedValueUses();
723   }
724   OperationState &state;
725 };
726 } // namespace
727 
728 Operation *OperationParser::parseGenericOperation() {
729   // Get location information for the operation.
730   auto srcLocation = getEncodedSourceLocation(getToken().getLoc());
731 
732   std::string name = getToken().getStringValue();
733   if (name.empty())
734     return (emitError("empty operation name is invalid"), nullptr);
735   if (name.find('\0') != StringRef::npos)
736     return (emitError("null character not allowed in operation name"), nullptr);
737 
738   consumeToken(Token::string);
739 
740   OperationState result(srcLocation, name);
741 
742   // Lazy load dialects in the context as needed.
743   if (!result.name.getAbstractOperation()) {
744     StringRef dialectName = StringRef(name).split('.').first;
745     if (!getContext()->getLoadedDialect(dialectName) &&
746         getContext()->getOrLoadDialect(dialectName)) {
747       result.name = OperationName(name, getContext());
748     }
749   }
750 
751   // Parse the operand list.
752   SmallVector<SSAUseInfo, 8> operandInfos;
753   if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
754       parseOptionalSSAUseList(operandInfos) ||
755       parseToken(Token::r_paren, "expected ')' to end operand list")) {
756     return nullptr;
757   }
758 
759   // Parse the successor list.
760   if (getToken().is(Token::l_square)) {
761     // Check if the operation is a known terminator.
762     const AbstractOperation *abstractOp = result.name.getAbstractOperation();
763     if (abstractOp && !abstractOp->hasProperty(OperationProperty::Terminator))
764       return emitError("successors in non-terminator"), nullptr;
765 
766     SmallVector<Block *, 2> successors;
767     if (parseSuccessors(successors))
768       return nullptr;
769     result.addSuccessors(successors);
770   }
771 
772   // Parse the region list.
773   CleanupOpStateRegions guard{result};
774   if (consumeIf(Token::l_paren)) {
775     do {
776       // Create temporary regions with the top level region as parent.
777       result.regions.emplace_back(new Region(moduleOp));
778       if (parseRegion(*result.regions.back(), /*entryArguments=*/{}))
779         return nullptr;
780     } while (consumeIf(Token::comma));
781     if (parseToken(Token::r_paren, "expected ')' to end region list"))
782       return nullptr;
783   }
784 
785   if (getToken().is(Token::l_brace)) {
786     if (parseAttributeDict(result.attributes))
787       return nullptr;
788   }
789 
790   if (parseToken(Token::colon, "expected ':' followed by operation type"))
791     return nullptr;
792 
793   auto typeLoc = getToken().getLoc();
794   auto type = parseType();
795   if (!type)
796     return nullptr;
797   auto fnType = type.dyn_cast<FunctionType>();
798   if (!fnType)
799     return (emitError(typeLoc, "expected function type"), nullptr);
800 
801   result.addTypes(fnType.getResults());
802 
803   // Check that we have the right number of types for the operands.
804   auto operandTypes = fnType.getInputs();
805   if (operandTypes.size() != operandInfos.size()) {
806     auto plural = "s"[operandInfos.size() == 1];
807     return (emitError(typeLoc, "expected ")
808                 << operandInfos.size() << " operand type" << plural
809                 << " but had " << operandTypes.size(),
810             nullptr);
811   }
812 
813   // Resolve all of the operands.
814   for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
815     result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
816     if (!result.operands.back())
817       return nullptr;
818   }
819 
820   // Parse a location if one is present.
821   if (parseOptionalTrailingLocation(result.location))
822     return nullptr;
823 
824   return opBuilder.createOperation(result);
825 }
826 
827 Operation *OperationParser::parseGenericOperation(Block *insertBlock,
828                                                   Block::iterator insertPt) {
829   OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder);
830   opBuilder.setInsertionPoint(insertBlock, insertPt);
831   return parseGenericOperation();
832 }
833 
834 namespace {
835 class CustomOpAsmParser : public OpAsmParser {
836 public:
837   CustomOpAsmParser(SMLoc nameLoc,
838                     ArrayRef<OperationParser::ResultRecord> resultIDs,
839                     const AbstractOperation *opDefinition,
840                     OperationParser &parser)
841       : nameLoc(nameLoc), resultIDs(resultIDs), opDefinition(opDefinition),
842         parser(parser) {}
843 
844   /// Parse an instance of the operation described by 'opDefinition' into the
845   /// provided operation state.
846   ParseResult parseOperation(OperationState &opState) {
847     if (opDefinition->parseAssembly(*this, opState))
848       return failure();
849     // Verify that the parsed attributes does not have duplicate attributes.
850     // This can happen if an attribute set during parsing is also specified in
851     // the attribute dictionary in the assembly, or the attribute is set
852     // multiple during parsing.
853     Optional<NamedAttribute> duplicate = opState.attributes.findDuplicate();
854     if (duplicate)
855       return emitError(getNameLoc(), "attribute '")
856              << duplicate->first
857              << "' occurs more than once in the attribute list";
858     return success();
859   }
860 
861   Operation *parseGenericOperation(Block *insertBlock,
862                                    Block::iterator insertPt) final {
863     return parser.parseGenericOperation(insertBlock, insertPt);
864   }
865 
866   //===--------------------------------------------------------------------===//
867   // Utilities
868   //===--------------------------------------------------------------------===//
869 
870   /// Return if any errors were emitted during parsing.
871   bool didEmitError() const { return emittedError; }
872 
873   /// Emit a diagnostic at the specified location and return failure.
874   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
875     emittedError = true;
876     return parser.emitError(loc, "custom op '" + opDefinition->name.strref() +
877                                      "' " + message);
878   }
879 
880   llvm::SMLoc getCurrentLocation() override {
881     return parser.getToken().getLoc();
882   }
883 
884   Builder &getBuilder() const override { return parser.builder; }
885 
886   /// Return the name of the specified result in the specified syntax, as well
887   /// as the subelement in the name.  For example, in this operation:
888   ///
889   ///  %x, %y:2, %z = foo.op
890   ///
891   ///    getResultName(0) == {"x", 0 }
892   ///    getResultName(1) == {"y", 0 }
893   ///    getResultName(2) == {"y", 1 }
894   ///    getResultName(3) == {"z", 0 }
895   std::pair<StringRef, unsigned>
896   getResultName(unsigned resultNo) const override {
897     // Scan for the resultID that contains this result number.
898     for (unsigned nameID = 0, e = resultIDs.size(); nameID != e; ++nameID) {
899       const auto &entry = resultIDs[nameID];
900       if (resultNo < std::get<1>(entry)) {
901         // Don't pass on the leading %.
902         StringRef name = std::get<0>(entry).drop_front();
903         return {name, resultNo};
904       }
905       resultNo -= std::get<1>(entry);
906     }
907 
908     // Invalid result number.
909     return {"", ~0U};
910   }
911 
912   /// Return the number of declared SSA results.  This returns 4 for the foo.op
913   /// example in the comment for getResultName.
914   size_t getNumResults() const override {
915     size_t count = 0;
916     for (auto &entry : resultIDs)
917       count += std::get<1>(entry);
918     return count;
919   }
920 
921   llvm::SMLoc getNameLoc() const override { return nameLoc; }
922 
923   //===--------------------------------------------------------------------===//
924   // Token Parsing
925   //===--------------------------------------------------------------------===//
926 
927   /// Parse a `->` token.
928   ParseResult parseArrow() override {
929     return parser.parseToken(Token::arrow, "expected '->'");
930   }
931 
932   /// Parses a `->` if present.
933   ParseResult parseOptionalArrow() override {
934     return success(parser.consumeIf(Token::arrow));
935   }
936 
937   /// Parse a '{' token.
938   ParseResult parseLBrace() override {
939     return parser.parseToken(Token::l_brace, "expected '{'");
940   }
941 
942   /// Parse a '{' token if present
943   ParseResult parseOptionalLBrace() override {
944     return success(parser.consumeIf(Token::l_brace));
945   }
946 
947   /// Parse a `}` token.
948   ParseResult parseRBrace() override {
949     return parser.parseToken(Token::r_brace, "expected '}'");
950   }
951 
952   /// Parse a `}` token if present
953   ParseResult parseOptionalRBrace() override {
954     return success(parser.consumeIf(Token::r_brace));
955   }
956 
957   /// Parse a `:` token.
958   ParseResult parseColon() override {
959     return parser.parseToken(Token::colon, "expected ':'");
960   }
961 
962   /// Parse a `:` token if present.
963   ParseResult parseOptionalColon() override {
964     return success(parser.consumeIf(Token::colon));
965   }
966 
967   /// Parse a `,` token.
968   ParseResult parseComma() override {
969     return parser.parseToken(Token::comma, "expected ','");
970   }
971 
972   /// Parse a `,` token if present.
973   ParseResult parseOptionalComma() override {
974     return success(parser.consumeIf(Token::comma));
975   }
976 
977   /// Parses a `...` if present.
978   ParseResult parseOptionalEllipsis() override {
979     return success(parser.consumeIf(Token::ellipsis));
980   }
981 
982   /// Parse a `=` token.
983   ParseResult parseEqual() override {
984     return parser.parseToken(Token::equal, "expected '='");
985   }
986 
987   /// Parse a `=` token if present.
988   ParseResult parseOptionalEqual() override {
989     return success(parser.consumeIf(Token::equal));
990   }
991 
992   /// Parse a '<' token.
993   ParseResult parseLess() override {
994     return parser.parseToken(Token::less, "expected '<'");
995   }
996 
997   /// Parse a '<' token if present.
998   ParseResult parseOptionalLess() override {
999     return success(parser.consumeIf(Token::less));
1000   }
1001 
1002   /// Parse a '>' token.
1003   ParseResult parseGreater() override {
1004     return parser.parseToken(Token::greater, "expected '>'");
1005   }
1006 
1007   /// Parse a '>' token if present.
1008   ParseResult parseOptionalGreater() override {
1009     return success(parser.consumeIf(Token::greater));
1010   }
1011 
1012   /// Parse a `(` token.
1013   ParseResult parseLParen() override {
1014     return parser.parseToken(Token::l_paren, "expected '('");
1015   }
1016 
1017   /// Parses a '(' if present.
1018   ParseResult parseOptionalLParen() override {
1019     return success(parser.consumeIf(Token::l_paren));
1020   }
1021 
1022   /// Parse a `)` token.
1023   ParseResult parseRParen() override {
1024     return parser.parseToken(Token::r_paren, "expected ')'");
1025   }
1026 
1027   /// Parses a ')' if present.
1028   ParseResult parseOptionalRParen() override {
1029     return success(parser.consumeIf(Token::r_paren));
1030   }
1031 
1032   /// Parse a `[` token.
1033   ParseResult parseLSquare() override {
1034     return parser.parseToken(Token::l_square, "expected '['");
1035   }
1036 
1037   /// Parses a '[' if present.
1038   ParseResult parseOptionalLSquare() override {
1039     return success(parser.consumeIf(Token::l_square));
1040   }
1041 
1042   /// Parse a `]` token.
1043   ParseResult parseRSquare() override {
1044     return parser.parseToken(Token::r_square, "expected ']'");
1045   }
1046 
1047   /// Parses a ']' if present.
1048   ParseResult parseOptionalRSquare() override {
1049     return success(parser.consumeIf(Token::r_square));
1050   }
1051 
1052   /// Parses a '?' token.
1053   ParseResult parseQuestion() override {
1054     return parser.parseToken(Token::question, "expected '?'");
1055   }
1056 
1057   /// Parses a '?' token if present.
1058   ParseResult parseOptionalQuestion() override {
1059     return success(parser.consumeIf(Token::question));
1060   }
1061 
1062   /// Parses a '+' token.
1063   ParseResult parsePlus() override {
1064     return parser.parseToken(Token::plus, "expected '+'");
1065   }
1066 
1067   /// Parses a '+' token if present.
1068   ParseResult parseOptionalPlus() override {
1069     return success(parser.consumeIf(Token::plus));
1070   }
1071 
1072   /// Parses a '*' token.
1073   ParseResult parseStar() override {
1074     return parser.parseToken(Token::star, "expected '*'");
1075   }
1076 
1077   /// Parses a '*' token if present.
1078   ParseResult parseOptionalStar() override {
1079     return success(parser.consumeIf(Token::star));
1080   }
1081 
1082   //===--------------------------------------------------------------------===//
1083   // Attribute Parsing
1084   //===--------------------------------------------------------------------===//
1085 
1086   /// Parse an arbitrary attribute of a given type and return it in result.
1087   ParseResult parseAttribute(Attribute &result, Type type) override {
1088     result = parser.parseAttribute(type);
1089     return success(static_cast<bool>(result));
1090   }
1091 
1092   /// Parse an optional attribute.
1093   template <typename AttrT>
1094   OptionalParseResult
1095   parseOptionalAttributeAndAddToList(AttrT &result, Type type,
1096                                      StringRef attrName, NamedAttrList &attrs) {
1097     OptionalParseResult parseResult =
1098         parser.parseOptionalAttribute(result, type);
1099     if (parseResult.hasValue() && succeeded(*parseResult))
1100       attrs.push_back(parser.builder.getNamedAttr(attrName, result));
1101     return parseResult;
1102   }
1103   OptionalParseResult parseOptionalAttribute(Attribute &result, Type type,
1104                                              StringRef attrName,
1105                                              NamedAttrList &attrs) override {
1106     return parseOptionalAttributeAndAddToList(result, type, attrName, attrs);
1107   }
1108   OptionalParseResult parseOptionalAttribute(ArrayAttr &result, Type type,
1109                                              StringRef attrName,
1110                                              NamedAttrList &attrs) override {
1111     return parseOptionalAttributeAndAddToList(result, type, attrName, attrs);
1112   }
1113   OptionalParseResult parseOptionalAttribute(StringAttr &result, Type type,
1114                                              StringRef attrName,
1115                                              NamedAttrList &attrs) override {
1116     return parseOptionalAttributeAndAddToList(result, type, attrName, attrs);
1117   }
1118 
1119   /// Parse a named dictionary into 'result' if it is present.
1120   ParseResult parseOptionalAttrDict(NamedAttrList &result) override {
1121     if (parser.getToken().isNot(Token::l_brace))
1122       return success();
1123     return parser.parseAttributeDict(result);
1124   }
1125 
1126   /// Parse a named dictionary into 'result' if the `attributes` keyword is
1127   /// present.
1128   ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result) override {
1129     if (failed(parseOptionalKeyword("attributes")))
1130       return success();
1131     return parser.parseAttributeDict(result);
1132   }
1133 
1134   /// Parse an affine map instance into 'map'.
1135   ParseResult parseAffineMap(AffineMap &map) override {
1136     return parser.parseAffineMapReference(map);
1137   }
1138 
1139   /// Parse an integer set instance into 'set'.
1140   ParseResult printIntegerSet(IntegerSet &set) override {
1141     return parser.parseIntegerSetReference(set);
1142   }
1143 
1144   //===--------------------------------------------------------------------===//
1145   // Identifier Parsing
1146   //===--------------------------------------------------------------------===//
1147 
1148   /// Returns true if the current token corresponds to a keyword.
1149   bool isCurrentTokenAKeyword() const {
1150     return parser.getToken().is(Token::bare_identifier) ||
1151            parser.getToken().isKeyword();
1152   }
1153 
1154   /// Parse the given keyword if present.
1155   ParseResult parseOptionalKeyword(StringRef keyword) override {
1156     // Check that the current token has the same spelling.
1157     if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword)
1158       return failure();
1159     parser.consumeToken();
1160     return success();
1161   }
1162 
1163   /// Parse a keyword, if present, into 'keyword'.
1164   ParseResult parseOptionalKeyword(StringRef *keyword) override {
1165     // Check that the current token is a keyword.
1166     if (!isCurrentTokenAKeyword())
1167       return failure();
1168 
1169     *keyword = parser.getTokenSpelling();
1170     parser.consumeToken();
1171     return success();
1172   }
1173 
1174   /// Parse a keyword if it is one of the 'allowedKeywords'.
1175   ParseResult
1176   parseOptionalKeyword(StringRef *keyword,
1177                        ArrayRef<StringRef> allowedKeywords) override {
1178     // Check that the current token is a keyword.
1179     if (!isCurrentTokenAKeyword())
1180       return failure();
1181 
1182     StringRef currentKeyword = parser.getTokenSpelling();
1183     if (llvm::is_contained(allowedKeywords, currentKeyword)) {
1184       *keyword = currentKeyword;
1185       parser.consumeToken();
1186       return success();
1187     }
1188 
1189     return failure();
1190   }
1191 
1192   /// Parse an optional @-identifier and store it (without the '@' symbol) in a
1193   /// string attribute named 'attrName'.
1194   ParseResult parseOptionalSymbolName(StringAttr &result, StringRef attrName,
1195                                       NamedAttrList &attrs) override {
1196     Token atToken = parser.getToken();
1197     if (atToken.isNot(Token::at_identifier))
1198       return failure();
1199 
1200     result = getBuilder().getStringAttr(atToken.getSymbolReference());
1201     attrs.push_back(getBuilder().getNamedAttr(attrName, result));
1202     parser.consumeToken();
1203     return success();
1204   }
1205 
1206   //===--------------------------------------------------------------------===//
1207   // Operand Parsing
1208   //===--------------------------------------------------------------------===//
1209 
1210   /// Parse a single operand.
1211   ParseResult parseOperand(OperandType &result) override {
1212     OperationParser::SSAUseInfo useInfo;
1213     if (parser.parseSSAUse(useInfo))
1214       return failure();
1215 
1216     result = {useInfo.loc, useInfo.name, useInfo.number};
1217     return success();
1218   }
1219 
1220   /// Parse a single operand if present.
1221   OptionalParseResult parseOptionalOperand(OperandType &result) override {
1222     if (parser.getToken().is(Token::percent_identifier))
1223       return parseOperand(result);
1224     return llvm::None;
1225   }
1226 
1227   /// Parse zero or more SSA comma-separated operand references with a specified
1228   /// surrounding delimiter, and an optional required operand count.
1229   ParseResult parseOperandList(SmallVectorImpl<OperandType> &result,
1230                                int requiredOperandCount = -1,
1231                                Delimiter delimiter = Delimiter::None) override {
1232     return parseOperandOrRegionArgList(result, /*isOperandList=*/true,
1233                                        requiredOperandCount, delimiter);
1234   }
1235 
1236   /// Parse zero or more SSA comma-separated operand or region arguments with
1237   ///  optional surrounding delimiter and required operand count.
1238   ParseResult
1239   parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result,
1240                               bool isOperandList, int requiredOperandCount = -1,
1241                               Delimiter delimiter = Delimiter::None) {
1242     auto startLoc = parser.getToken().getLoc();
1243 
1244     // Handle delimiters.
1245     switch (delimiter) {
1246     case Delimiter::None:
1247       // Don't check for the absence of a delimiter if the number of operands
1248       // is unknown (and hence the operand list could be empty).
1249       if (requiredOperandCount == -1)
1250         break;
1251       // Token already matches an identifier and so can't be a delimiter.
1252       if (parser.getToken().is(Token::percent_identifier))
1253         break;
1254       // Test against known delimiters.
1255       if (parser.getToken().is(Token::l_paren) ||
1256           parser.getToken().is(Token::l_square))
1257         return emitError(startLoc, "unexpected delimiter");
1258       return emitError(startLoc, "invalid operand");
1259     case Delimiter::OptionalParen:
1260       if (parser.getToken().isNot(Token::l_paren))
1261         return success();
1262       LLVM_FALLTHROUGH;
1263     case Delimiter::Paren:
1264       if (parser.parseToken(Token::l_paren, "expected '(' in operand list"))
1265         return failure();
1266       break;
1267     case Delimiter::OptionalSquare:
1268       if (parser.getToken().isNot(Token::l_square))
1269         return success();
1270       LLVM_FALLTHROUGH;
1271     case Delimiter::Square:
1272       if (parser.parseToken(Token::l_square, "expected '[' in operand list"))
1273         return failure();
1274       break;
1275     }
1276 
1277     // Check for zero operands.
1278     if (parser.getToken().is(Token::percent_identifier)) {
1279       do {
1280         OperandType operandOrArg;
1281         if (isOperandList ? parseOperand(operandOrArg)
1282                           : parseRegionArgument(operandOrArg))
1283           return failure();
1284         result.push_back(operandOrArg);
1285       } while (parser.consumeIf(Token::comma));
1286     }
1287 
1288     // Handle delimiters.   If we reach here, the optional delimiters were
1289     // present, so we need to parse their closing one.
1290     switch (delimiter) {
1291     case Delimiter::None:
1292       break;
1293     case Delimiter::OptionalParen:
1294     case Delimiter::Paren:
1295       if (parser.parseToken(Token::r_paren, "expected ')' in operand list"))
1296         return failure();
1297       break;
1298     case Delimiter::OptionalSquare:
1299     case Delimiter::Square:
1300       if (parser.parseToken(Token::r_square, "expected ']' in operand list"))
1301         return failure();
1302       break;
1303     }
1304 
1305     if (requiredOperandCount != -1 &&
1306         result.size() != static_cast<size_t>(requiredOperandCount))
1307       return emitError(startLoc, "expected ")
1308              << requiredOperandCount << " operands";
1309     return success();
1310   }
1311 
1312   /// Parse zero or more trailing SSA comma-separated trailing operand
1313   /// references with a specified surrounding delimiter, and an optional
1314   /// required operand count. A leading comma is expected before the operands.
1315   ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result,
1316                                        int requiredOperandCount,
1317                                        Delimiter delimiter) override {
1318     if (parser.getToken().is(Token::comma)) {
1319       parseComma();
1320       return parseOperandList(result, requiredOperandCount, delimiter);
1321     }
1322     if (requiredOperandCount != -1)
1323       return emitError(parser.getToken().getLoc(), "expected ")
1324              << requiredOperandCount << " operands";
1325     return success();
1326   }
1327 
1328   /// Resolve an operand to an SSA value, emitting an error on failure.
1329   ParseResult resolveOperand(const OperandType &operand, Type type,
1330                              SmallVectorImpl<Value> &result) override {
1331     OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1332                                                operand.location};
1333     if (auto value = parser.resolveSSAUse(operandInfo, type)) {
1334       result.push_back(value);
1335       return success();
1336     }
1337     return failure();
1338   }
1339 
1340   /// Parse an AffineMap of SSA ids.
1341   ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands,
1342                                      Attribute &mapAttr, StringRef attrName,
1343                                      NamedAttrList &attrs,
1344                                      Delimiter delimiter) override {
1345     SmallVector<OperandType, 2> dimOperands;
1346     SmallVector<OperandType, 1> symOperands;
1347 
1348     auto parseElement = [&](bool isSymbol) -> ParseResult {
1349       OperandType operand;
1350       if (parseOperand(operand))
1351         return failure();
1352       if (isSymbol)
1353         symOperands.push_back(operand);
1354       else
1355         dimOperands.push_back(operand);
1356       return success();
1357     };
1358 
1359     AffineMap map;
1360     if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter))
1361       return failure();
1362     // Add AffineMap attribute.
1363     if (map) {
1364       mapAttr = AffineMapAttr::get(map);
1365       attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr));
1366     }
1367 
1368     // Add dim operands before symbol operands in 'operands'.
1369     operands.assign(dimOperands.begin(), dimOperands.end());
1370     operands.append(symOperands.begin(), symOperands.end());
1371     return success();
1372   }
1373 
1374   //===--------------------------------------------------------------------===//
1375   // Region Parsing
1376   //===--------------------------------------------------------------------===//
1377 
1378   /// Parse a region that takes `arguments` of `argTypes` types.  This
1379   /// effectively defines the SSA values of `arguments` and assigns their type.
1380   ParseResult parseRegion(Region &region, ArrayRef<OperandType> arguments,
1381                           ArrayRef<Type> argTypes,
1382                           bool enableNameShadowing) override {
1383     assert(arguments.size() == argTypes.size() &&
1384            "mismatching number of arguments and types");
1385 
1386     SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2>
1387         regionArguments;
1388     for (auto pair : llvm::zip(arguments, argTypes)) {
1389       const OperandType &operand = std::get<0>(pair);
1390       Type type = std::get<1>(pair);
1391       OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1392                                                  operand.location};
1393       regionArguments.emplace_back(operandInfo, type);
1394     }
1395 
1396     // Try to parse the region.
1397     assert((!enableNameShadowing ||
1398             opDefinition->hasProperty(OperationProperty::IsolatedFromAbove)) &&
1399            "name shadowing is only allowed on isolated regions");
1400     if (parser.parseRegion(region, regionArguments, enableNameShadowing))
1401       return failure();
1402     return success();
1403   }
1404 
1405   /// Parses a region if present.
1406   ParseResult parseOptionalRegion(Region &region,
1407                                   ArrayRef<OperandType> arguments,
1408                                   ArrayRef<Type> argTypes,
1409                                   bool enableNameShadowing) override {
1410     if (parser.getToken().isNot(Token::l_brace))
1411       return success();
1412     return parseRegion(region, arguments, argTypes, enableNameShadowing);
1413   }
1414 
1415   /// Parses a region if present. If the region is present, a new region is
1416   /// allocated and placed in `region`. If no region is present, `region`
1417   /// remains untouched.
1418   OptionalParseResult
1419   parseOptionalRegion(std::unique_ptr<Region> &region,
1420                       ArrayRef<OperandType> arguments, ArrayRef<Type> argTypes,
1421                       bool enableNameShadowing = false) override {
1422     if (parser.getToken().isNot(Token::l_brace))
1423       return llvm::None;
1424     std::unique_ptr<Region> newRegion = std::make_unique<Region>();
1425     if (parseRegion(*newRegion, arguments, argTypes, enableNameShadowing))
1426       return failure();
1427 
1428     region = std::move(newRegion);
1429     return success();
1430   }
1431 
1432   /// Parse a region argument. The type of the argument will be resolved later
1433   /// by a call to `parseRegion`.
1434   ParseResult parseRegionArgument(OperandType &argument) override {
1435     return parseOperand(argument);
1436   }
1437 
1438   /// Parse a region argument if present.
1439   ParseResult parseOptionalRegionArgument(OperandType &argument) override {
1440     if (parser.getToken().isNot(Token::percent_identifier))
1441       return success();
1442     return parseRegionArgument(argument);
1443   }
1444 
1445   ParseResult
1446   parseRegionArgumentList(SmallVectorImpl<OperandType> &result,
1447                           int requiredOperandCount = -1,
1448                           Delimiter delimiter = Delimiter::None) override {
1449     return parseOperandOrRegionArgList(result, /*isOperandList=*/false,
1450                                        requiredOperandCount, delimiter);
1451   }
1452 
1453   //===--------------------------------------------------------------------===//
1454   // Successor Parsing
1455   //===--------------------------------------------------------------------===//
1456 
1457   /// Parse a single operation successor.
1458   ParseResult parseSuccessor(Block *&dest) override {
1459     return parser.parseSuccessor(dest);
1460   }
1461 
1462   /// Parse an optional operation successor and its operand list.
1463   OptionalParseResult parseOptionalSuccessor(Block *&dest) override {
1464     if (parser.getToken().isNot(Token::caret_identifier))
1465       return llvm::None;
1466     return parseSuccessor(dest);
1467   }
1468 
1469   /// Parse a single operation successor and its operand list.
1470   ParseResult
1471   parseSuccessorAndUseList(Block *&dest,
1472                            SmallVectorImpl<Value> &operands) override {
1473     if (parseSuccessor(dest))
1474       return failure();
1475 
1476     // Handle optional arguments.
1477     if (succeeded(parseOptionalLParen()) &&
1478         (parser.parseOptionalSSAUseAndTypeList(operands) || parseRParen())) {
1479       return failure();
1480     }
1481     return success();
1482   }
1483 
1484   //===--------------------------------------------------------------------===//
1485   // Type Parsing
1486   //===--------------------------------------------------------------------===//
1487 
1488   /// Parse a type.
1489   ParseResult parseType(Type &result) override {
1490     return failure(!(result = parser.parseType()));
1491   }
1492 
1493   /// Parse an optional type.
1494   OptionalParseResult parseOptionalType(Type &result) override {
1495     return parser.parseOptionalType(result);
1496   }
1497 
1498   /// Parse an arrow followed by a type list.
1499   ParseResult parseArrowTypeList(SmallVectorImpl<Type> &result) override {
1500     if (parseArrow() || parser.parseFunctionResultTypes(result))
1501       return failure();
1502     return success();
1503   }
1504 
1505   /// Parse an optional arrow followed by a type list.
1506   ParseResult
1507   parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override {
1508     if (!parser.consumeIf(Token::arrow))
1509       return success();
1510     return parser.parseFunctionResultTypes(result);
1511   }
1512 
1513   /// Parse a colon followed by a type.
1514   ParseResult parseColonType(Type &result) override {
1515     return failure(parser.parseToken(Token::colon, "expected ':'") ||
1516                    !(result = parser.parseType()));
1517   }
1518 
1519   /// Parse a colon followed by a type list, which must have at least one type.
1520   ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override {
1521     if (parser.parseToken(Token::colon, "expected ':'"))
1522       return failure();
1523     return parser.parseTypeListNoParens(result);
1524   }
1525 
1526   /// Parse an optional colon followed by a type list, which if present must
1527   /// have at least one type.
1528   ParseResult
1529   parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override {
1530     if (!parser.consumeIf(Token::colon))
1531       return success();
1532     return parser.parseTypeListNoParens(result);
1533   }
1534 
1535   /// Parse a list of assignments of the form
1536   ///   (%x1 = %y1, %x2 = %y2, ...).
1537   OptionalParseResult
1538   parseOptionalAssignmentList(SmallVectorImpl<OperandType> &lhs,
1539                               SmallVectorImpl<OperandType> &rhs) override {
1540     if (failed(parseOptionalLParen()))
1541       return llvm::None;
1542 
1543     auto parseElt = [&]() -> ParseResult {
1544       OperandType regionArg, operand;
1545       if (parseRegionArgument(regionArg) || parseEqual() ||
1546           parseOperand(operand))
1547         return failure();
1548       lhs.push_back(regionArg);
1549       rhs.push_back(operand);
1550       return success();
1551     };
1552     return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
1553   }
1554 
1555 private:
1556   /// The source location of the operation name.
1557   SMLoc nameLoc;
1558 
1559   /// Information about the result name specifiers.
1560   ArrayRef<OperationParser::ResultRecord> resultIDs;
1561 
1562   /// The abstract information of the operation.
1563   const AbstractOperation *opDefinition;
1564 
1565   /// The main operation parser.
1566   OperationParser &parser;
1567 
1568   /// A flag that indicates if any errors were emitted during parsing.
1569   bool emittedError = false;
1570 };
1571 } // end anonymous namespace.
1572 
1573 Operation *
1574 OperationParser::parseCustomOperation(ArrayRef<ResultRecord> resultIDs) {
1575   llvm::SMLoc opLoc = getToken().getLoc();
1576   StringRef opName = getTokenSpelling();
1577 
1578   auto *opDefinition = AbstractOperation::lookup(opName, getContext());
1579   if (!opDefinition) {
1580     if (opName.contains('.')) {
1581       // This op has a dialect, we try to check if we can register it in the
1582       // context on the fly.
1583       StringRef dialectName = opName.split('.').first;
1584       if (!getContext()->getLoadedDialect(dialectName) &&
1585           getContext()->getOrLoadDialect(dialectName)) {
1586         opDefinition = AbstractOperation::lookup(opName, getContext());
1587       }
1588     } else {
1589       // If the operation name has no namespace prefix we treat it as a standard
1590       // operation and prefix it with "std".
1591       // TODO: Would it be better to just build a mapping of the registered
1592       // operations in the standard dialect?
1593       if (getContext()->getOrLoadDialect("std"))
1594         opDefinition = AbstractOperation::lookup(Twine("std." + opName).str(),
1595                                                  getContext());
1596     }
1597   }
1598 
1599   if (!opDefinition) {
1600     emitError(opLoc) << "custom op '" << opName << "' is unknown";
1601     return nullptr;
1602   }
1603 
1604   consumeToken();
1605 
1606   // If the custom op parser crashes, produce some indication to help
1607   // debugging.
1608   std::string opNameStr = opName.str();
1609   llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'",
1610                                    opNameStr.c_str());
1611 
1612   // Get location information for the operation.
1613   auto srcLocation = getEncodedSourceLocation(opLoc);
1614 
1615   // Have the op implementation take a crack and parsing this.
1616   OperationState opState(srcLocation, opDefinition->name);
1617   CleanupOpStateRegions guard{opState};
1618   CustomOpAsmParser opAsmParser(opLoc, resultIDs, opDefinition, *this);
1619   if (opAsmParser.parseOperation(opState))
1620     return nullptr;
1621 
1622   // If it emitted an error, we failed.
1623   if (opAsmParser.didEmitError())
1624     return nullptr;
1625 
1626   // Parse a location if one is present.
1627   if (parseOptionalTrailingLocation(opState.location))
1628     return nullptr;
1629 
1630   // Otherwise, we succeeded.  Use the state it parsed as our op information.
1631   return opBuilder.createOperation(opState);
1632 }
1633 
1634 //===----------------------------------------------------------------------===//
1635 // Region Parsing
1636 //===----------------------------------------------------------------------===//
1637 
1638 /// Region.
1639 ///
1640 ///   region ::= '{' region-body
1641 ///
1642 ParseResult OperationParser::parseRegion(
1643     Region &region,
1644     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
1645     bool isIsolatedNameScope) {
1646   // Parse the '{'.
1647   if (parseToken(Token::l_brace, "expected '{' to begin a region"))
1648     return failure();
1649 
1650   // Check for an empty region.
1651   if (entryArguments.empty() && consumeIf(Token::r_brace))
1652     return success();
1653   auto currentPt = opBuilder.saveInsertionPoint();
1654 
1655   // Push a new named value scope.
1656   pushSSANameScope(isIsolatedNameScope);
1657 
1658   // Parse the first block directly to allow for it to be unnamed.
1659   auto owning_block = std::make_unique<Block>();
1660   Block *block = owning_block.get();
1661 
1662   // Add arguments to the entry block.
1663   if (!entryArguments.empty()) {
1664     for (auto &placeholderArgPair : entryArguments) {
1665       auto &argInfo = placeholderArgPair.first;
1666       // Ensure that the argument was not already defined.
1667       if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) {
1668         return emitError(argInfo.loc, "region entry argument '" + argInfo.name +
1669                                           "' is already in use")
1670                    .attachNote(getEncodedSourceLocation(*defLoc))
1671                << "previously referenced here";
1672       }
1673       if (addDefinition(placeholderArgPair.first,
1674                         block->addArgument(placeholderArgPair.second))) {
1675         return failure();
1676       }
1677     }
1678 
1679     // If we had named arguments, then don't allow a block name.
1680     if (getToken().is(Token::caret_identifier))
1681       return emitError("invalid block name in region with named arguments");
1682   }
1683 
1684   if (parseBlock(block)) {
1685     return failure();
1686   }
1687 
1688   // Verify that no other arguments were parsed.
1689   if (!entryArguments.empty() &&
1690       block->getNumArguments() > entryArguments.size()) {
1691     return emitError("entry block arguments were already defined");
1692   }
1693 
1694   // Parse the rest of the region.
1695   region.push_back(owning_block.release());
1696   if (parseRegionBody(region))
1697     return failure();
1698 
1699   // Pop the SSA value scope for this region.
1700   if (popSSANameScope())
1701     return failure();
1702 
1703   // Reset the original insertion point.
1704   opBuilder.restoreInsertionPoint(currentPt);
1705   return success();
1706 }
1707 
1708 /// Region.
1709 ///
1710 ///   region-body ::= block* '}'
1711 ///
1712 ParseResult OperationParser::parseRegionBody(Region &region) {
1713   // Parse the list of blocks.
1714   while (!consumeIf(Token::r_brace)) {
1715     Block *newBlock = nullptr;
1716     if (parseBlock(newBlock))
1717       return failure();
1718     region.push_back(newBlock);
1719   }
1720   return success();
1721 }
1722 
1723 //===----------------------------------------------------------------------===//
1724 // Block Parsing
1725 //===----------------------------------------------------------------------===//
1726 
1727 /// Block declaration.
1728 ///
1729 ///   block ::= block-label? operation*
1730 ///   block-label    ::= block-id block-arg-list? `:`
1731 ///   block-id       ::= caret-id
1732 ///   block-arg-list ::= `(` ssa-id-and-type-list? `)`
1733 ///
1734 ParseResult OperationParser::parseBlock(Block *&block) {
1735   // The first block of a region may already exist, if it does the caret
1736   // identifier is optional.
1737   if (block && getToken().isNot(Token::caret_identifier))
1738     return parseBlockBody(block);
1739 
1740   SMLoc nameLoc = getToken().getLoc();
1741   auto name = getTokenSpelling();
1742   if (parseToken(Token::caret_identifier, "expected block name"))
1743     return failure();
1744 
1745   block = defineBlockNamed(name, nameLoc, block);
1746 
1747   // Fail if the block was already defined.
1748   if (!block)
1749     return emitError(nameLoc, "redefinition of block '") << name << "'";
1750 
1751   // If an argument list is present, parse it.
1752   if (consumeIf(Token::l_paren)) {
1753     SmallVector<BlockArgument, 8> bbArgs;
1754     if (parseOptionalBlockArgList(bbArgs, block) ||
1755         parseToken(Token::r_paren, "expected ')' to end argument list"))
1756       return failure();
1757   }
1758 
1759   if (parseToken(Token::colon, "expected ':' after block name"))
1760     return failure();
1761 
1762   return parseBlockBody(block);
1763 }
1764 
1765 ParseResult OperationParser::parseBlockBody(Block *block) {
1766   // Set the insertion point to the end of the block to parse.
1767   opBuilder.setInsertionPointToEnd(block);
1768 
1769   // Parse the list of operations that make up the body of the block.
1770   while (getToken().isNot(Token::caret_identifier, Token::r_brace))
1771     if (parseOperation())
1772       return failure();
1773 
1774   return success();
1775 }
1776 
1777 /// Get the block with the specified name, creating it if it doesn't already
1778 /// exist.  The location specified is the point of use, which allows
1779 /// us to diagnose references to blocks that are not defined precisely.
1780 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) {
1781   auto &blockAndLoc = getBlockInfoByName(name);
1782   if (!blockAndLoc.first) {
1783     blockAndLoc = {new Block(), loc};
1784     insertForwardRef(blockAndLoc.first, loc);
1785   }
1786 
1787   return blockAndLoc.first;
1788 }
1789 
1790 /// Define the block with the specified name. Returns the Block* or nullptr in
1791 /// the case of redefinition.
1792 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc,
1793                                          Block *existing) {
1794   auto &blockAndLoc = getBlockInfoByName(name);
1795   if (!blockAndLoc.first) {
1796     // If the caller provided a block, use it.  Otherwise create a new one.
1797     if (!existing)
1798       existing = new Block();
1799     blockAndLoc.first = existing;
1800     blockAndLoc.second = loc;
1801     return blockAndLoc.first;
1802   }
1803 
1804   // Forward declarations are removed once defined, so if we are defining a
1805   // existing block and it is not a forward declaration, then it is a
1806   // redeclaration.
1807   if (!eraseForwardRef(blockAndLoc.first))
1808     return nullptr;
1809   return blockAndLoc.first;
1810 }
1811 
1812 /// Parse a (possibly empty) list of SSA operands with types as block arguments.
1813 ///
1814 ///   ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
1815 ///
1816 ParseResult OperationParser::parseOptionalBlockArgList(
1817     SmallVectorImpl<BlockArgument> &results, Block *owner) {
1818   if (getToken().is(Token::r_brace))
1819     return success();
1820 
1821   // If the block already has arguments, then we're handling the entry block.
1822   // Parse and register the names for the arguments, but do not add them.
1823   bool definingExistingArgs = owner->getNumArguments() != 0;
1824   unsigned nextArgument = 0;
1825 
1826   return parseCommaSeparatedList([&]() -> ParseResult {
1827     return parseSSADefOrUseAndType(
1828         [&](SSAUseInfo useInfo, Type type) -> ParseResult {
1829           // If this block did not have existing arguments, define a new one.
1830           if (!definingExistingArgs)
1831             return addDefinition(useInfo, owner->addArgument(type));
1832 
1833           // Otherwise, ensure that this argument has already been created.
1834           if (nextArgument >= owner->getNumArguments())
1835             return emitError("too many arguments specified in argument list");
1836 
1837           // Finally, make sure the existing argument has the correct type.
1838           auto arg = owner->getArgument(nextArgument++);
1839           if (arg.getType() != type)
1840             return emitError("argument and block argument type mismatch");
1841           return addDefinition(useInfo, arg);
1842         });
1843   });
1844 }
1845 
1846 //===----------------------------------------------------------------------===//
1847 // Top-level entity parsing.
1848 //===----------------------------------------------------------------------===//
1849 
1850 namespace {
1851 /// This parser handles entities that are only valid at the top level of the
1852 /// file.
1853 class ModuleParser : public Parser {
1854 public:
1855   explicit ModuleParser(ParserState &state) : Parser(state) {}
1856 
1857   ParseResult parseModule(ModuleOp module);
1858 
1859 private:
1860   /// Parse an attribute alias declaration.
1861   ParseResult parseAttributeAliasDef();
1862 
1863   /// Parse an attribute alias declaration.
1864   ParseResult parseTypeAliasDef();
1865 };
1866 } // end anonymous namespace
1867 
1868 /// Parses an attribute alias declaration.
1869 ///
1870 ///   attribute-alias-def ::= '#' alias-name `=` attribute-value
1871 ///
1872 ParseResult ModuleParser::parseAttributeAliasDef() {
1873   assert(getToken().is(Token::hash_identifier));
1874   StringRef aliasName = getTokenSpelling().drop_front();
1875 
1876   // Check for redefinitions.
1877   if (getState().symbols.attributeAliasDefinitions.count(aliasName) > 0)
1878     return emitError("redefinition of attribute alias id '" + aliasName + "'");
1879 
1880   // Make sure this isn't invading the dialect attribute namespace.
1881   if (aliasName.contains('.'))
1882     return emitError("attribute names with a '.' are reserved for "
1883                      "dialect-defined names");
1884 
1885   consumeToken(Token::hash_identifier);
1886 
1887   // Parse the '='.
1888   if (parseToken(Token::equal, "expected '=' in attribute alias definition"))
1889     return failure();
1890 
1891   // Parse the attribute value.
1892   Attribute attr = parseAttribute();
1893   if (!attr)
1894     return failure();
1895 
1896   getState().symbols.attributeAliasDefinitions[aliasName] = attr;
1897   return success();
1898 }
1899 
1900 /// Parse a type alias declaration.
1901 ///
1902 ///   type-alias-def ::= '!' alias-name `=` 'type' type
1903 ///
1904 ParseResult ModuleParser::parseTypeAliasDef() {
1905   assert(getToken().is(Token::exclamation_identifier));
1906   StringRef aliasName = getTokenSpelling().drop_front();
1907 
1908   // Check for redefinitions.
1909   if (getState().symbols.typeAliasDefinitions.count(aliasName) > 0)
1910     return emitError("redefinition of type alias id '" + aliasName + "'");
1911 
1912   // Make sure this isn't invading the dialect type namespace.
1913   if (aliasName.contains('.'))
1914     return emitError("type names with a '.' are reserved for "
1915                      "dialect-defined names");
1916 
1917   consumeToken(Token::exclamation_identifier);
1918 
1919   // Parse the '=' and 'type'.
1920   if (parseToken(Token::equal, "expected '=' in type alias definition") ||
1921       parseToken(Token::kw_type, "expected 'type' in type alias definition"))
1922     return failure();
1923 
1924   // Parse the type.
1925   Type aliasedType = parseType();
1926   if (!aliasedType)
1927     return failure();
1928 
1929   // Register this alias with the parser state.
1930   getState().symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType);
1931   return success();
1932 }
1933 
1934 /// This is the top-level module parser.
1935 ParseResult ModuleParser::parseModule(ModuleOp module) {
1936   OperationParser opParser(getState(), module);
1937 
1938   // Module itself is a name scope.
1939   opParser.pushSSANameScope(/*isIsolated=*/true);
1940 
1941   while (true) {
1942     switch (getToken().getKind()) {
1943     default:
1944       // Parse a top-level operation.
1945       if (opParser.parseOperation())
1946         return failure();
1947       break;
1948 
1949     // If we got to the end of the file, then we're done.
1950     case Token::eof: {
1951       if (opParser.finalize())
1952         return failure();
1953 
1954       // Handle the case where the top level module was explicitly defined.
1955       auto &bodyBlocks = module.getBodyRegion().getBlocks();
1956       auto &operations = bodyBlocks.front().getOperations();
1957       assert(!operations.empty() && "expected a valid module terminator");
1958 
1959       // Check that the first operation is a module, and it is the only
1960       // non-terminator operation.
1961       ModuleOp nested = dyn_cast<ModuleOp>(operations.front());
1962       if (nested && std::next(operations.begin(), 2) == operations.end()) {
1963         // Merge the data of the nested module operation into 'module'.
1964         module.setLoc(nested.getLoc());
1965         module.setAttrs(nested.getOperation()->getMutableAttrDict());
1966         bodyBlocks.splice(bodyBlocks.end(), nested.getBodyRegion().getBlocks());
1967 
1968         // Erase the original module body.
1969         bodyBlocks.pop_front();
1970       }
1971 
1972       return opParser.popSSANameScope();
1973     }
1974 
1975     // If we got an error token, then the lexer already emitted an error, just
1976     // stop.  Someday we could introduce error recovery if there was demand
1977     // for it.
1978     case Token::error:
1979       return failure();
1980 
1981     // Parse an attribute alias.
1982     case Token::hash_identifier:
1983       if (parseAttributeAliasDef())
1984         return failure();
1985       break;
1986 
1987     // Parse a type alias.
1988     case Token::exclamation_identifier:
1989       if (parseTypeAliasDef())
1990         return failure();
1991       break;
1992     }
1993   }
1994 }
1995 
1996 //===----------------------------------------------------------------------===//
1997 
1998 /// This parses the file specified by the indicated SourceMgr and returns an
1999 /// MLIR module if it was valid.  If not, it emits diagnostics and returns
2000 /// null.
2001 OwningModuleRef mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr,
2002                                       MLIRContext *context) {
2003   auto sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
2004 
2005   // This is the result module we are parsing into.
2006   OwningModuleRef module(ModuleOp::create(FileLineColLoc::get(
2007       sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0, context)));
2008 
2009   SymbolState aliasState;
2010   ParserState state(sourceMgr, context, aliasState);
2011   if (ModuleParser(state).parseModule(*module))
2012     return nullptr;
2013 
2014   // Make sure the parse module has no other structural problems detected by
2015   // the verifier.
2016   if (failed(verify(*module)))
2017     return nullptr;
2018 
2019   return module;
2020 }
2021 
2022 /// This parses the file specified by the indicated filename and returns an
2023 /// MLIR module if it was valid.  If not, the error message is emitted through
2024 /// the error handler registered in the context, and a null pointer is returned.
2025 OwningModuleRef mlir::parseSourceFile(StringRef filename,
2026                                       MLIRContext *context) {
2027   llvm::SourceMgr sourceMgr;
2028   return parseSourceFile(filename, sourceMgr, context);
2029 }
2030 
2031 /// This parses the file specified by the indicated filename using the provided
2032 /// SourceMgr and returns an MLIR module if it was valid.  If not, the error
2033 /// message is emitted through the error handler registered in the context, and
2034 /// a null pointer is returned.
2035 OwningModuleRef mlir::parseSourceFile(StringRef filename,
2036                                       llvm::SourceMgr &sourceMgr,
2037                                       MLIRContext *context) {
2038   if (sourceMgr.getNumBuffers() != 0) {
2039     // TODO: Extend to support multiple buffers.
2040     emitError(mlir::UnknownLoc::get(context),
2041               "only main buffer parsed at the moment");
2042     return nullptr;
2043   }
2044   auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename);
2045   if (std::error_code error = file_or_err.getError()) {
2046     emitError(mlir::UnknownLoc::get(context),
2047               "could not open input file " + filename);
2048     return nullptr;
2049   }
2050 
2051   // Load the MLIR module.
2052   sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc());
2053   return parseSourceFile(sourceMgr, context);
2054 }
2055 
2056 /// This parses the program string to a MLIR module if it was valid. If not,
2057 /// it emits diagnostics and returns null.
2058 OwningModuleRef mlir::parseSourceString(StringRef moduleStr,
2059                                         MLIRContext *context) {
2060   auto memBuffer = MemoryBuffer::getMemBuffer(moduleStr);
2061   if (!memBuffer)
2062     return nullptr;
2063 
2064   SourceMgr sourceMgr;
2065   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
2066   return parseSourceFile(sourceMgr, context);
2067 }
2068