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     return success();
850   }
851 
852   Operation *parseGenericOperation(Block *insertBlock,
853                                    Block::iterator insertPt) final {
854     return parser.parseGenericOperation(insertBlock, insertPt);
855   }
856 
857   //===--------------------------------------------------------------------===//
858   // Utilities
859   //===--------------------------------------------------------------------===//
860 
861   /// Return if any errors were emitted during parsing.
862   bool didEmitError() const { return emittedError; }
863 
864   /// Emit a diagnostic at the specified location and return failure.
865   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
866     emittedError = true;
867     return parser.emitError(loc, "custom op '" + opDefinition->name.strref() +
868                                      "' " + message);
869   }
870 
871   llvm::SMLoc getCurrentLocation() override {
872     return parser.getToken().getLoc();
873   }
874 
875   Builder &getBuilder() const override { return parser.builder; }
876 
877   /// Return the name of the specified result in the specified syntax, as well
878   /// as the subelement in the name.  For example, in this operation:
879   ///
880   ///  %x, %y:2, %z = foo.op
881   ///
882   ///    getResultName(0) == {"x", 0 }
883   ///    getResultName(1) == {"y", 0 }
884   ///    getResultName(2) == {"y", 1 }
885   ///    getResultName(3) == {"z", 0 }
886   std::pair<StringRef, unsigned>
887   getResultName(unsigned resultNo) const override {
888     // Scan for the resultID that contains this result number.
889     for (unsigned nameID = 0, e = resultIDs.size(); nameID != e; ++nameID) {
890       const auto &entry = resultIDs[nameID];
891       if (resultNo < std::get<1>(entry)) {
892         // Don't pass on the leading %.
893         StringRef name = std::get<0>(entry).drop_front();
894         return {name, resultNo};
895       }
896       resultNo -= std::get<1>(entry);
897     }
898 
899     // Invalid result number.
900     return {"", ~0U};
901   }
902 
903   /// Return the number of declared SSA results.  This returns 4 for the foo.op
904   /// example in the comment for getResultName.
905   size_t getNumResults() const override {
906     size_t count = 0;
907     for (auto &entry : resultIDs)
908       count += std::get<1>(entry);
909     return count;
910   }
911 
912   llvm::SMLoc getNameLoc() const override { return nameLoc; }
913 
914   //===--------------------------------------------------------------------===//
915   // Token Parsing
916   //===--------------------------------------------------------------------===//
917 
918   /// Parse a `->` token.
919   ParseResult parseArrow() override {
920     return parser.parseToken(Token::arrow, "expected '->'");
921   }
922 
923   /// Parses a `->` if present.
924   ParseResult parseOptionalArrow() override {
925     return success(parser.consumeIf(Token::arrow));
926   }
927 
928   /// Parse a '{' token.
929   ParseResult parseLBrace() override {
930     return parser.parseToken(Token::l_brace, "expected '{'");
931   }
932 
933   /// Parse a '{' token if present
934   ParseResult parseOptionalLBrace() override {
935     return success(parser.consumeIf(Token::l_brace));
936   }
937 
938   /// Parse a `}` token.
939   ParseResult parseRBrace() override {
940     return parser.parseToken(Token::r_brace, "expected '}'");
941   }
942 
943   /// Parse a `}` token if present
944   ParseResult parseOptionalRBrace() override {
945     return success(parser.consumeIf(Token::r_brace));
946   }
947 
948   /// Parse a `:` token.
949   ParseResult parseColon() override {
950     return parser.parseToken(Token::colon, "expected ':'");
951   }
952 
953   /// Parse a `:` token if present.
954   ParseResult parseOptionalColon() override {
955     return success(parser.consumeIf(Token::colon));
956   }
957 
958   /// Parse a `,` token.
959   ParseResult parseComma() override {
960     return parser.parseToken(Token::comma, "expected ','");
961   }
962 
963   /// Parse a `,` token if present.
964   ParseResult parseOptionalComma() override {
965     return success(parser.consumeIf(Token::comma));
966   }
967 
968   /// Parses a `...` if present.
969   ParseResult parseOptionalEllipsis() override {
970     return success(parser.consumeIf(Token::ellipsis));
971   }
972 
973   /// Parse a `=` token.
974   ParseResult parseEqual() override {
975     return parser.parseToken(Token::equal, "expected '='");
976   }
977 
978   /// Parse a `=` token if present.
979   ParseResult parseOptionalEqual() override {
980     return success(parser.consumeIf(Token::equal));
981   }
982 
983   /// Parse a '<' token.
984   ParseResult parseLess() override {
985     return parser.parseToken(Token::less, "expected '<'");
986   }
987 
988   /// Parse a '>' token.
989   ParseResult parseGreater() override {
990     return parser.parseToken(Token::greater, "expected '>'");
991   }
992 
993   /// Parse a `(` token.
994   ParseResult parseLParen() override {
995     return parser.parseToken(Token::l_paren, "expected '('");
996   }
997 
998   /// Parses a '(' if present.
999   ParseResult parseOptionalLParen() override {
1000     return success(parser.consumeIf(Token::l_paren));
1001   }
1002 
1003   /// Parse a `)` token.
1004   ParseResult parseRParen() override {
1005     return parser.parseToken(Token::r_paren, "expected ')'");
1006   }
1007 
1008   /// Parses a ')' if present.
1009   ParseResult parseOptionalRParen() override {
1010     return success(parser.consumeIf(Token::r_paren));
1011   }
1012 
1013   /// Parses a '?' if present.
1014   ParseResult parseOptionalQuestion() override {
1015     return success(parser.consumeIf(Token::question));
1016   }
1017 
1018   /// Parse a `[` token.
1019   ParseResult parseLSquare() override {
1020     return parser.parseToken(Token::l_square, "expected '['");
1021   }
1022 
1023   /// Parses a '[' if present.
1024   ParseResult parseOptionalLSquare() override {
1025     return success(parser.consumeIf(Token::l_square));
1026   }
1027 
1028   /// Parse a `]` token.
1029   ParseResult parseRSquare() override {
1030     return parser.parseToken(Token::r_square, "expected ']'");
1031   }
1032 
1033   /// Parses a ']' if present.
1034   ParseResult parseOptionalRSquare() override {
1035     return success(parser.consumeIf(Token::r_square));
1036   }
1037 
1038   //===--------------------------------------------------------------------===//
1039   // Attribute Parsing
1040   //===--------------------------------------------------------------------===//
1041 
1042   /// Parse an arbitrary attribute of a given type and return it in result.
1043   ParseResult parseAttribute(Attribute &result, Type type) override {
1044     result = parser.parseAttribute(type);
1045     return success(static_cast<bool>(result));
1046   }
1047 
1048   /// Parse an optional attribute.
1049   template <typename AttrT>
1050   OptionalParseResult
1051   parseOptionalAttributeAndAddToList(AttrT &result, Type type,
1052                                      StringRef attrName, NamedAttrList &attrs) {
1053     OptionalParseResult parseResult =
1054         parser.parseOptionalAttribute(result, type);
1055     if (parseResult.hasValue() && succeeded(*parseResult))
1056       attrs.push_back(parser.builder.getNamedAttr(attrName, result));
1057     return parseResult;
1058   }
1059   OptionalParseResult parseOptionalAttribute(Attribute &result, Type type,
1060                                              StringRef attrName,
1061                                              NamedAttrList &attrs) override {
1062     return parseOptionalAttributeAndAddToList(result, type, attrName, attrs);
1063   }
1064   OptionalParseResult parseOptionalAttribute(ArrayAttr &result, Type type,
1065                                              StringRef attrName,
1066                                              NamedAttrList &attrs) override {
1067     return parseOptionalAttributeAndAddToList(result, type, attrName, attrs);
1068   }
1069   OptionalParseResult parseOptionalAttribute(StringAttr &result, Type type,
1070                                              StringRef attrName,
1071                                              NamedAttrList &attrs) override {
1072     return parseOptionalAttributeAndAddToList(result, type, attrName, attrs);
1073   }
1074 
1075   /// Parse a named dictionary into 'result' if it is present.
1076   ParseResult parseOptionalAttrDict(NamedAttrList &result) override {
1077     if (parser.getToken().isNot(Token::l_brace))
1078       return success();
1079     return parser.parseAttributeDict(result);
1080   }
1081 
1082   /// Parse a named dictionary into 'result' if the `attributes` keyword is
1083   /// present.
1084   ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result) override {
1085     if (failed(parseOptionalKeyword("attributes")))
1086       return success();
1087     return parser.parseAttributeDict(result);
1088   }
1089 
1090   /// Parse an affine map instance into 'map'.
1091   ParseResult parseAffineMap(AffineMap &map) override {
1092     return parser.parseAffineMapReference(map);
1093   }
1094 
1095   /// Parse an integer set instance into 'set'.
1096   ParseResult printIntegerSet(IntegerSet &set) override {
1097     return parser.parseIntegerSetReference(set);
1098   }
1099 
1100   //===--------------------------------------------------------------------===//
1101   // Identifier Parsing
1102   //===--------------------------------------------------------------------===//
1103 
1104   /// Returns true if the current token corresponds to a keyword.
1105   bool isCurrentTokenAKeyword() const {
1106     return parser.getToken().is(Token::bare_identifier) ||
1107            parser.getToken().isKeyword();
1108   }
1109 
1110   /// Parse the given keyword if present.
1111   ParseResult parseOptionalKeyword(StringRef keyword) override {
1112     // Check that the current token has the same spelling.
1113     if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword)
1114       return failure();
1115     parser.consumeToken();
1116     return success();
1117   }
1118 
1119   /// Parse a keyword, if present, into 'keyword'.
1120   ParseResult parseOptionalKeyword(StringRef *keyword) override {
1121     // Check that the current token is a keyword.
1122     if (!isCurrentTokenAKeyword())
1123       return failure();
1124 
1125     *keyword = parser.getTokenSpelling();
1126     parser.consumeToken();
1127     return success();
1128   }
1129 
1130   /// Parse an optional @-identifier and store it (without the '@' symbol) in a
1131   /// string attribute named 'attrName'.
1132   ParseResult parseOptionalSymbolName(StringAttr &result, StringRef attrName,
1133                                       NamedAttrList &attrs) override {
1134     Token atToken = parser.getToken();
1135     if (atToken.isNot(Token::at_identifier))
1136       return failure();
1137 
1138     result = getBuilder().getStringAttr(atToken.getSymbolReference());
1139     attrs.push_back(getBuilder().getNamedAttr(attrName, result));
1140     parser.consumeToken();
1141     return success();
1142   }
1143 
1144   //===--------------------------------------------------------------------===//
1145   // Operand Parsing
1146   //===--------------------------------------------------------------------===//
1147 
1148   /// Parse a single operand.
1149   ParseResult parseOperand(OperandType &result) override {
1150     OperationParser::SSAUseInfo useInfo;
1151     if (parser.parseSSAUse(useInfo))
1152       return failure();
1153 
1154     result = {useInfo.loc, useInfo.name, useInfo.number};
1155     return success();
1156   }
1157 
1158   /// Parse a single operand if present.
1159   OptionalParseResult parseOptionalOperand(OperandType &result) override {
1160     if (parser.getToken().is(Token::percent_identifier))
1161       return parseOperand(result);
1162     return llvm::None;
1163   }
1164 
1165   /// Parse zero or more SSA comma-separated operand references with a specified
1166   /// surrounding delimiter, and an optional required operand count.
1167   ParseResult parseOperandList(SmallVectorImpl<OperandType> &result,
1168                                int requiredOperandCount = -1,
1169                                Delimiter delimiter = Delimiter::None) override {
1170     return parseOperandOrRegionArgList(result, /*isOperandList=*/true,
1171                                        requiredOperandCount, delimiter);
1172   }
1173 
1174   /// Parse zero or more SSA comma-separated operand or region arguments with
1175   ///  optional surrounding delimiter and required operand count.
1176   ParseResult
1177   parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result,
1178                               bool isOperandList, int requiredOperandCount = -1,
1179                               Delimiter delimiter = Delimiter::None) {
1180     auto startLoc = parser.getToken().getLoc();
1181 
1182     // Handle delimiters.
1183     switch (delimiter) {
1184     case Delimiter::None:
1185       // Don't check for the absence of a delimiter if the number of operands
1186       // is unknown (and hence the operand list could be empty).
1187       if (requiredOperandCount == -1)
1188         break;
1189       // Token already matches an identifier and so can't be a delimiter.
1190       if (parser.getToken().is(Token::percent_identifier))
1191         break;
1192       // Test against known delimiters.
1193       if (parser.getToken().is(Token::l_paren) ||
1194           parser.getToken().is(Token::l_square))
1195         return emitError(startLoc, "unexpected delimiter");
1196       return emitError(startLoc, "invalid operand");
1197     case Delimiter::OptionalParen:
1198       if (parser.getToken().isNot(Token::l_paren))
1199         return success();
1200       LLVM_FALLTHROUGH;
1201     case Delimiter::Paren:
1202       if (parser.parseToken(Token::l_paren, "expected '(' in operand list"))
1203         return failure();
1204       break;
1205     case Delimiter::OptionalSquare:
1206       if (parser.getToken().isNot(Token::l_square))
1207         return success();
1208       LLVM_FALLTHROUGH;
1209     case Delimiter::Square:
1210       if (parser.parseToken(Token::l_square, "expected '[' in operand list"))
1211         return failure();
1212       break;
1213     }
1214 
1215     // Check for zero operands.
1216     if (parser.getToken().is(Token::percent_identifier)) {
1217       do {
1218         OperandType operandOrArg;
1219         if (isOperandList ? parseOperand(operandOrArg)
1220                           : parseRegionArgument(operandOrArg))
1221           return failure();
1222         result.push_back(operandOrArg);
1223       } while (parser.consumeIf(Token::comma));
1224     }
1225 
1226     // Handle delimiters.   If we reach here, the optional delimiters were
1227     // present, so we need to parse their closing one.
1228     switch (delimiter) {
1229     case Delimiter::None:
1230       break;
1231     case Delimiter::OptionalParen:
1232     case Delimiter::Paren:
1233       if (parser.parseToken(Token::r_paren, "expected ')' in operand list"))
1234         return failure();
1235       break;
1236     case Delimiter::OptionalSquare:
1237     case Delimiter::Square:
1238       if (parser.parseToken(Token::r_square, "expected ']' in operand list"))
1239         return failure();
1240       break;
1241     }
1242 
1243     if (requiredOperandCount != -1 &&
1244         result.size() != static_cast<size_t>(requiredOperandCount))
1245       return emitError(startLoc, "expected ")
1246              << requiredOperandCount << " operands";
1247     return success();
1248   }
1249 
1250   /// Parse zero or more trailing SSA comma-separated trailing operand
1251   /// references with a specified surrounding delimiter, and an optional
1252   /// required operand count. A leading comma is expected before the operands.
1253   ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result,
1254                                        int requiredOperandCount,
1255                                        Delimiter delimiter) override {
1256     if (parser.getToken().is(Token::comma)) {
1257       parseComma();
1258       return parseOperandList(result, requiredOperandCount, delimiter);
1259     }
1260     if (requiredOperandCount != -1)
1261       return emitError(parser.getToken().getLoc(), "expected ")
1262              << requiredOperandCount << " operands";
1263     return success();
1264   }
1265 
1266   /// Resolve an operand to an SSA value, emitting an error on failure.
1267   ParseResult resolveOperand(const OperandType &operand, Type type,
1268                              SmallVectorImpl<Value> &result) override {
1269     OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1270                                                operand.location};
1271     if (auto value = parser.resolveSSAUse(operandInfo, type)) {
1272       result.push_back(value);
1273       return success();
1274     }
1275     return failure();
1276   }
1277 
1278   /// Parse an AffineMap of SSA ids.
1279   ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands,
1280                                      Attribute &mapAttr, StringRef attrName,
1281                                      NamedAttrList &attrs,
1282                                      Delimiter delimiter) override {
1283     SmallVector<OperandType, 2> dimOperands;
1284     SmallVector<OperandType, 1> symOperands;
1285 
1286     auto parseElement = [&](bool isSymbol) -> ParseResult {
1287       OperandType operand;
1288       if (parseOperand(operand))
1289         return failure();
1290       if (isSymbol)
1291         symOperands.push_back(operand);
1292       else
1293         dimOperands.push_back(operand);
1294       return success();
1295     };
1296 
1297     AffineMap map;
1298     if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter))
1299       return failure();
1300     // Add AffineMap attribute.
1301     if (map) {
1302       mapAttr = AffineMapAttr::get(map);
1303       attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr));
1304     }
1305 
1306     // Add dim operands before symbol operands in 'operands'.
1307     operands.assign(dimOperands.begin(), dimOperands.end());
1308     operands.append(symOperands.begin(), symOperands.end());
1309     return success();
1310   }
1311 
1312   //===--------------------------------------------------------------------===//
1313   // Region Parsing
1314   //===--------------------------------------------------------------------===//
1315 
1316   /// Parse a region that takes `arguments` of `argTypes` types.  This
1317   /// effectively defines the SSA values of `arguments` and assigns their type.
1318   ParseResult parseRegion(Region &region, ArrayRef<OperandType> arguments,
1319                           ArrayRef<Type> argTypes,
1320                           bool enableNameShadowing) override {
1321     assert(arguments.size() == argTypes.size() &&
1322            "mismatching number of arguments and types");
1323 
1324     SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2>
1325         regionArguments;
1326     for (auto pair : llvm::zip(arguments, argTypes)) {
1327       const OperandType &operand = std::get<0>(pair);
1328       Type type = std::get<1>(pair);
1329       OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1330                                                  operand.location};
1331       regionArguments.emplace_back(operandInfo, type);
1332     }
1333 
1334     // Try to parse the region.
1335     assert((!enableNameShadowing ||
1336             opDefinition->hasProperty(OperationProperty::IsolatedFromAbove)) &&
1337            "name shadowing is only allowed on isolated regions");
1338     if (parser.parseRegion(region, regionArguments, enableNameShadowing))
1339       return failure();
1340     return success();
1341   }
1342 
1343   /// Parses a region if present.
1344   ParseResult parseOptionalRegion(Region &region,
1345                                   ArrayRef<OperandType> arguments,
1346                                   ArrayRef<Type> argTypes,
1347                                   bool enableNameShadowing) override {
1348     if (parser.getToken().isNot(Token::l_brace))
1349       return success();
1350     return parseRegion(region, arguments, argTypes, enableNameShadowing);
1351   }
1352 
1353   /// Parses a region if present. If the region is present, a new region is
1354   /// allocated and placed in `region`. If no region is present, `region`
1355   /// remains untouched.
1356   OptionalParseResult
1357   parseOptionalRegion(std::unique_ptr<Region> &region,
1358                       ArrayRef<OperandType> arguments, ArrayRef<Type> argTypes,
1359                       bool enableNameShadowing = false) override {
1360     if (parser.getToken().isNot(Token::l_brace))
1361       return llvm::None;
1362     std::unique_ptr<Region> newRegion = std::make_unique<Region>();
1363     if (parseRegion(*newRegion, arguments, argTypes, enableNameShadowing))
1364       return failure();
1365 
1366     region = std::move(newRegion);
1367     return success();
1368   }
1369 
1370   /// Parse a region argument. The type of the argument will be resolved later
1371   /// by a call to `parseRegion`.
1372   ParseResult parseRegionArgument(OperandType &argument) override {
1373     return parseOperand(argument);
1374   }
1375 
1376   /// Parse a region argument if present.
1377   ParseResult parseOptionalRegionArgument(OperandType &argument) override {
1378     if (parser.getToken().isNot(Token::percent_identifier))
1379       return success();
1380     return parseRegionArgument(argument);
1381   }
1382 
1383   ParseResult
1384   parseRegionArgumentList(SmallVectorImpl<OperandType> &result,
1385                           int requiredOperandCount = -1,
1386                           Delimiter delimiter = Delimiter::None) override {
1387     return parseOperandOrRegionArgList(result, /*isOperandList=*/false,
1388                                        requiredOperandCount, delimiter);
1389   }
1390 
1391   //===--------------------------------------------------------------------===//
1392   // Successor Parsing
1393   //===--------------------------------------------------------------------===//
1394 
1395   /// Parse a single operation successor.
1396   ParseResult parseSuccessor(Block *&dest) override {
1397     return parser.parseSuccessor(dest);
1398   }
1399 
1400   /// Parse an optional operation successor and its operand list.
1401   OptionalParseResult parseOptionalSuccessor(Block *&dest) override {
1402     if (parser.getToken().isNot(Token::caret_identifier))
1403       return llvm::None;
1404     return parseSuccessor(dest);
1405   }
1406 
1407   /// Parse a single operation successor and its operand list.
1408   ParseResult
1409   parseSuccessorAndUseList(Block *&dest,
1410                            SmallVectorImpl<Value> &operands) override {
1411     if (parseSuccessor(dest))
1412       return failure();
1413 
1414     // Handle optional arguments.
1415     if (succeeded(parseOptionalLParen()) &&
1416         (parser.parseOptionalSSAUseAndTypeList(operands) || parseRParen())) {
1417       return failure();
1418     }
1419     return success();
1420   }
1421 
1422   //===--------------------------------------------------------------------===//
1423   // Type Parsing
1424   //===--------------------------------------------------------------------===//
1425 
1426   /// Parse a type.
1427   ParseResult parseType(Type &result) override {
1428     return failure(!(result = parser.parseType()));
1429   }
1430 
1431   /// Parse an optional type.
1432   OptionalParseResult parseOptionalType(Type &result) override {
1433     return parser.parseOptionalType(result);
1434   }
1435 
1436   /// Parse an arrow followed by a type list.
1437   ParseResult parseArrowTypeList(SmallVectorImpl<Type> &result) override {
1438     if (parseArrow() || parser.parseFunctionResultTypes(result))
1439       return failure();
1440     return success();
1441   }
1442 
1443   /// Parse an optional arrow followed by a type list.
1444   ParseResult
1445   parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override {
1446     if (!parser.consumeIf(Token::arrow))
1447       return success();
1448     return parser.parseFunctionResultTypes(result);
1449   }
1450 
1451   /// Parse a colon followed by a type.
1452   ParseResult parseColonType(Type &result) override {
1453     return failure(parser.parseToken(Token::colon, "expected ':'") ||
1454                    !(result = parser.parseType()));
1455   }
1456 
1457   /// Parse a colon followed by a type list, which must have at least one type.
1458   ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override {
1459     if (parser.parseToken(Token::colon, "expected ':'"))
1460       return failure();
1461     return parser.parseTypeListNoParens(result);
1462   }
1463 
1464   /// Parse an optional colon followed by a type list, which if present must
1465   /// have at least one type.
1466   ParseResult
1467   parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override {
1468     if (!parser.consumeIf(Token::colon))
1469       return success();
1470     return parser.parseTypeListNoParens(result);
1471   }
1472 
1473   /// Parse a list of assignments of the form
1474   /// (%x1 = %y1 : type1, %x2 = %y2 : type2, ...).
1475   /// The list must contain at least one entry
1476   ParseResult parseAssignmentList(SmallVectorImpl<OperandType> &lhs,
1477                                   SmallVectorImpl<OperandType> &rhs) override {
1478     auto parseElt = [&]() -> ParseResult {
1479       OperandType regionArg, operand;
1480       if (parseRegionArgument(regionArg) || parseEqual() ||
1481           parseOperand(operand))
1482         return failure();
1483       lhs.push_back(regionArg);
1484       rhs.push_back(operand);
1485       return success();
1486     };
1487     if (parseLParen())
1488       return failure();
1489     return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
1490   }
1491 
1492 private:
1493   /// The source location of the operation name.
1494   SMLoc nameLoc;
1495 
1496   /// Information about the result name specifiers.
1497   ArrayRef<OperationParser::ResultRecord> resultIDs;
1498 
1499   /// The abstract information of the operation.
1500   const AbstractOperation *opDefinition;
1501 
1502   /// The main operation parser.
1503   OperationParser &parser;
1504 
1505   /// A flag that indicates if any errors were emitted during parsing.
1506   bool emittedError = false;
1507 };
1508 } // end anonymous namespace.
1509 
1510 Operation *
1511 OperationParser::parseCustomOperation(ArrayRef<ResultRecord> resultIDs) {
1512   llvm::SMLoc opLoc = getToken().getLoc();
1513   StringRef opName = getTokenSpelling();
1514 
1515   auto *opDefinition = AbstractOperation::lookup(opName, getContext());
1516   if (!opDefinition) {
1517     if (opName.contains('.')) {
1518       // This op has a dialect, we try to check if we can register it in the
1519       // context on the fly.
1520       StringRef dialectName = opName.split('.').first;
1521       if (!getContext()->getLoadedDialect(dialectName) &&
1522           getContext()->getOrLoadDialect(dialectName)) {
1523         opDefinition = AbstractOperation::lookup(opName, getContext());
1524       }
1525     } else {
1526       // If the operation name has no namespace prefix we treat it as a standard
1527       // operation and prefix it with "std".
1528       // TODO: Would it be better to just build a mapping of the registered
1529       // operations in the standard dialect?
1530       if (getContext()->getOrLoadDialect("std"))
1531         opDefinition = AbstractOperation::lookup(Twine("std." + opName).str(),
1532                                                  getContext());
1533     }
1534   }
1535 
1536   if (!opDefinition) {
1537     emitError(opLoc) << "custom op '" << opName << "' is unknown";
1538     return nullptr;
1539   }
1540 
1541   consumeToken();
1542 
1543   // If the custom op parser crashes, produce some indication to help
1544   // debugging.
1545   std::string opNameStr = opName.str();
1546   llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'",
1547                                    opNameStr.c_str());
1548 
1549   // Get location information for the operation.
1550   auto srcLocation = getEncodedSourceLocation(opLoc);
1551 
1552   // Have the op implementation take a crack and parsing this.
1553   OperationState opState(srcLocation, opDefinition->name);
1554   CleanupOpStateRegions guard{opState};
1555   CustomOpAsmParser opAsmParser(opLoc, resultIDs, opDefinition, *this);
1556   if (opAsmParser.parseOperation(opState))
1557     return nullptr;
1558 
1559   // If it emitted an error, we failed.
1560   if (opAsmParser.didEmitError())
1561     return nullptr;
1562 
1563   // Parse a location if one is present.
1564   if (parseOptionalTrailingLocation(opState.location))
1565     return nullptr;
1566 
1567   // Otherwise, we succeeded.  Use the state it parsed as our op information.
1568   return opBuilder.createOperation(opState);
1569 }
1570 
1571 //===----------------------------------------------------------------------===//
1572 // Region Parsing
1573 //===----------------------------------------------------------------------===//
1574 
1575 /// Region.
1576 ///
1577 ///   region ::= '{' region-body
1578 ///
1579 ParseResult OperationParser::parseRegion(
1580     Region &region,
1581     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
1582     bool isIsolatedNameScope) {
1583   // Parse the '{'.
1584   if (parseToken(Token::l_brace, "expected '{' to begin a region"))
1585     return failure();
1586 
1587   // Check for an empty region.
1588   if (entryArguments.empty() && consumeIf(Token::r_brace))
1589     return success();
1590   auto currentPt = opBuilder.saveInsertionPoint();
1591 
1592   // Push a new named value scope.
1593   pushSSANameScope(isIsolatedNameScope);
1594 
1595   // Parse the first block directly to allow for it to be unnamed.
1596   auto owning_block = std::make_unique<Block>();
1597   Block *block = owning_block.get();
1598 
1599   // Add arguments to the entry block.
1600   if (!entryArguments.empty()) {
1601     for (auto &placeholderArgPair : entryArguments) {
1602       auto &argInfo = placeholderArgPair.first;
1603       // Ensure that the argument was not already defined.
1604       if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) {
1605         return emitError(argInfo.loc, "region entry argument '" + argInfo.name +
1606                                           "' is already in use")
1607                    .attachNote(getEncodedSourceLocation(*defLoc))
1608                << "previously referenced here";
1609       }
1610       if (addDefinition(placeholderArgPair.first,
1611                         block->addArgument(placeholderArgPair.second))) {
1612         return failure();
1613       }
1614     }
1615 
1616     // If we had named arguments, then don't allow a block name.
1617     if (getToken().is(Token::caret_identifier))
1618       return emitError("invalid block name in region with named arguments");
1619   }
1620 
1621   if (parseBlock(block)) {
1622     return failure();
1623   }
1624 
1625   // Verify that no other arguments were parsed.
1626   if (!entryArguments.empty() &&
1627       block->getNumArguments() > entryArguments.size()) {
1628     return emitError("entry block arguments were already defined");
1629   }
1630 
1631   // Parse the rest of the region.
1632   region.push_back(owning_block.release());
1633   if (parseRegionBody(region))
1634     return failure();
1635 
1636   // Pop the SSA value scope for this region.
1637   if (popSSANameScope())
1638     return failure();
1639 
1640   // Reset the original insertion point.
1641   opBuilder.restoreInsertionPoint(currentPt);
1642   return success();
1643 }
1644 
1645 /// Region.
1646 ///
1647 ///   region-body ::= block* '}'
1648 ///
1649 ParseResult OperationParser::parseRegionBody(Region &region) {
1650   // Parse the list of blocks.
1651   while (!consumeIf(Token::r_brace)) {
1652     Block *newBlock = nullptr;
1653     if (parseBlock(newBlock))
1654       return failure();
1655     region.push_back(newBlock);
1656   }
1657   return success();
1658 }
1659 
1660 //===----------------------------------------------------------------------===//
1661 // Block Parsing
1662 //===----------------------------------------------------------------------===//
1663 
1664 /// Block declaration.
1665 ///
1666 ///   block ::= block-label? operation*
1667 ///   block-label    ::= block-id block-arg-list? `:`
1668 ///   block-id       ::= caret-id
1669 ///   block-arg-list ::= `(` ssa-id-and-type-list? `)`
1670 ///
1671 ParseResult OperationParser::parseBlock(Block *&block) {
1672   // The first block of a region may already exist, if it does the caret
1673   // identifier is optional.
1674   if (block && getToken().isNot(Token::caret_identifier))
1675     return parseBlockBody(block);
1676 
1677   SMLoc nameLoc = getToken().getLoc();
1678   auto name = getTokenSpelling();
1679   if (parseToken(Token::caret_identifier, "expected block name"))
1680     return failure();
1681 
1682   block = defineBlockNamed(name, nameLoc, block);
1683 
1684   // Fail if the block was already defined.
1685   if (!block)
1686     return emitError(nameLoc, "redefinition of block '") << name << "'";
1687 
1688   // If an argument list is present, parse it.
1689   if (consumeIf(Token::l_paren)) {
1690     SmallVector<BlockArgument, 8> bbArgs;
1691     if (parseOptionalBlockArgList(bbArgs, block) ||
1692         parseToken(Token::r_paren, "expected ')' to end argument list"))
1693       return failure();
1694   }
1695 
1696   if (parseToken(Token::colon, "expected ':' after block name"))
1697     return failure();
1698 
1699   return parseBlockBody(block);
1700 }
1701 
1702 ParseResult OperationParser::parseBlockBody(Block *block) {
1703   // Set the insertion point to the end of the block to parse.
1704   opBuilder.setInsertionPointToEnd(block);
1705 
1706   // Parse the list of operations that make up the body of the block.
1707   while (getToken().isNot(Token::caret_identifier, Token::r_brace))
1708     if (parseOperation())
1709       return failure();
1710 
1711   return success();
1712 }
1713 
1714 /// Get the block with the specified name, creating it if it doesn't already
1715 /// exist.  The location specified is the point of use, which allows
1716 /// us to diagnose references to blocks that are not defined precisely.
1717 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) {
1718   auto &blockAndLoc = getBlockInfoByName(name);
1719   if (!blockAndLoc.first) {
1720     blockAndLoc = {new Block(), loc};
1721     insertForwardRef(blockAndLoc.first, loc);
1722   }
1723 
1724   return blockAndLoc.first;
1725 }
1726 
1727 /// Define the block with the specified name. Returns the Block* or nullptr in
1728 /// the case of redefinition.
1729 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc,
1730                                          Block *existing) {
1731   auto &blockAndLoc = getBlockInfoByName(name);
1732   if (!blockAndLoc.first) {
1733     // If the caller provided a block, use it.  Otherwise create a new one.
1734     if (!existing)
1735       existing = new Block();
1736     blockAndLoc.first = existing;
1737     blockAndLoc.second = loc;
1738     return blockAndLoc.first;
1739   }
1740 
1741   // Forward declarations are removed once defined, so if we are defining a
1742   // existing block and it is not a forward declaration, then it is a
1743   // redeclaration.
1744   if (!eraseForwardRef(blockAndLoc.first))
1745     return nullptr;
1746   return blockAndLoc.first;
1747 }
1748 
1749 /// Parse a (possibly empty) list of SSA operands with types as block arguments.
1750 ///
1751 ///   ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
1752 ///
1753 ParseResult OperationParser::parseOptionalBlockArgList(
1754     SmallVectorImpl<BlockArgument> &results, Block *owner) {
1755   if (getToken().is(Token::r_brace))
1756     return success();
1757 
1758   // If the block already has arguments, then we're handling the entry block.
1759   // Parse and register the names for the arguments, but do not add them.
1760   bool definingExistingArgs = owner->getNumArguments() != 0;
1761   unsigned nextArgument = 0;
1762 
1763   return parseCommaSeparatedList([&]() -> ParseResult {
1764     return parseSSADefOrUseAndType(
1765         [&](SSAUseInfo useInfo, Type type) -> ParseResult {
1766           // If this block did not have existing arguments, define a new one.
1767           if (!definingExistingArgs)
1768             return addDefinition(useInfo, owner->addArgument(type));
1769 
1770           // Otherwise, ensure that this argument has already been created.
1771           if (nextArgument >= owner->getNumArguments())
1772             return emitError("too many arguments specified in argument list");
1773 
1774           // Finally, make sure the existing argument has the correct type.
1775           auto arg = owner->getArgument(nextArgument++);
1776           if (arg.getType() != type)
1777             return emitError("argument and block argument type mismatch");
1778           return addDefinition(useInfo, arg);
1779         });
1780   });
1781 }
1782 
1783 //===----------------------------------------------------------------------===//
1784 // Top-level entity parsing.
1785 //===----------------------------------------------------------------------===//
1786 
1787 namespace {
1788 /// This parser handles entities that are only valid at the top level of the
1789 /// file.
1790 class ModuleParser : public Parser {
1791 public:
1792   explicit ModuleParser(ParserState &state) : Parser(state) {}
1793 
1794   ParseResult parseModule(ModuleOp module);
1795 
1796 private:
1797   /// Parse an attribute alias declaration.
1798   ParseResult parseAttributeAliasDef();
1799 
1800   /// Parse an attribute alias declaration.
1801   ParseResult parseTypeAliasDef();
1802 };
1803 } // end anonymous namespace
1804 
1805 /// Parses an attribute alias declaration.
1806 ///
1807 ///   attribute-alias-def ::= '#' alias-name `=` attribute-value
1808 ///
1809 ParseResult ModuleParser::parseAttributeAliasDef() {
1810   assert(getToken().is(Token::hash_identifier));
1811   StringRef aliasName = getTokenSpelling().drop_front();
1812 
1813   // Check for redefinitions.
1814   if (getState().symbols.attributeAliasDefinitions.count(aliasName) > 0)
1815     return emitError("redefinition of attribute alias id '" + aliasName + "'");
1816 
1817   // Make sure this isn't invading the dialect attribute namespace.
1818   if (aliasName.contains('.'))
1819     return emitError("attribute names with a '.' are reserved for "
1820                      "dialect-defined names");
1821 
1822   consumeToken(Token::hash_identifier);
1823 
1824   // Parse the '='.
1825   if (parseToken(Token::equal, "expected '=' in attribute alias definition"))
1826     return failure();
1827 
1828   // Parse the attribute value.
1829   Attribute attr = parseAttribute();
1830   if (!attr)
1831     return failure();
1832 
1833   getState().symbols.attributeAliasDefinitions[aliasName] = attr;
1834   return success();
1835 }
1836 
1837 /// Parse a type alias declaration.
1838 ///
1839 ///   type-alias-def ::= '!' alias-name `=` 'type' type
1840 ///
1841 ParseResult ModuleParser::parseTypeAliasDef() {
1842   assert(getToken().is(Token::exclamation_identifier));
1843   StringRef aliasName = getTokenSpelling().drop_front();
1844 
1845   // Check for redefinitions.
1846   if (getState().symbols.typeAliasDefinitions.count(aliasName) > 0)
1847     return emitError("redefinition of type alias id '" + aliasName + "'");
1848 
1849   // Make sure this isn't invading the dialect type namespace.
1850   if (aliasName.contains('.'))
1851     return emitError("type names with a '.' are reserved for "
1852                      "dialect-defined names");
1853 
1854   consumeToken(Token::exclamation_identifier);
1855 
1856   // Parse the '=' and 'type'.
1857   if (parseToken(Token::equal, "expected '=' in type alias definition") ||
1858       parseToken(Token::kw_type, "expected 'type' in type alias definition"))
1859     return failure();
1860 
1861   // Parse the type.
1862   Type aliasedType = parseType();
1863   if (!aliasedType)
1864     return failure();
1865 
1866   // Register this alias with the parser state.
1867   getState().symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType);
1868   return success();
1869 }
1870 
1871 /// This is the top-level module parser.
1872 ParseResult ModuleParser::parseModule(ModuleOp module) {
1873   OperationParser opParser(getState(), module);
1874 
1875   // Module itself is a name scope.
1876   opParser.pushSSANameScope(/*isIsolated=*/true);
1877 
1878   while (true) {
1879     switch (getToken().getKind()) {
1880     default:
1881       // Parse a top-level operation.
1882       if (opParser.parseOperation())
1883         return failure();
1884       break;
1885 
1886     // If we got to the end of the file, then we're done.
1887     case Token::eof: {
1888       if (opParser.finalize())
1889         return failure();
1890 
1891       // Handle the case where the top level module was explicitly defined.
1892       auto &bodyBlocks = module.getBodyRegion().getBlocks();
1893       auto &operations = bodyBlocks.front().getOperations();
1894       assert(!operations.empty() && "expected a valid module terminator");
1895 
1896       // Check that the first operation is a module, and it is the only
1897       // non-terminator operation.
1898       ModuleOp nested = dyn_cast<ModuleOp>(operations.front());
1899       if (nested && std::next(operations.begin(), 2) == operations.end()) {
1900         // Merge the data of the nested module operation into 'module'.
1901         module.setLoc(nested.getLoc());
1902         module.setAttrs(nested.getOperation()->getMutableAttrDict());
1903         bodyBlocks.splice(bodyBlocks.end(), nested.getBodyRegion().getBlocks());
1904 
1905         // Erase the original module body.
1906         bodyBlocks.pop_front();
1907       }
1908 
1909       return opParser.popSSANameScope();
1910     }
1911 
1912     // If we got an error token, then the lexer already emitted an error, just
1913     // stop.  Someday we could introduce error recovery if there was demand
1914     // for it.
1915     case Token::error:
1916       return failure();
1917 
1918     // Parse an attribute alias.
1919     case Token::hash_identifier:
1920       if (parseAttributeAliasDef())
1921         return failure();
1922       break;
1923 
1924     // Parse a type alias.
1925     case Token::exclamation_identifier:
1926       if (parseTypeAliasDef())
1927         return failure();
1928       break;
1929     }
1930   }
1931 }
1932 
1933 //===----------------------------------------------------------------------===//
1934 
1935 /// This parses the file specified by the indicated SourceMgr and returns an
1936 /// MLIR module if it was valid.  If not, it emits diagnostics and returns
1937 /// null.
1938 OwningModuleRef mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr,
1939                                       MLIRContext *context) {
1940   auto sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
1941 
1942   // This is the result module we are parsing into.
1943   OwningModuleRef module(ModuleOp::create(FileLineColLoc::get(
1944       sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0, context)));
1945 
1946   SymbolState aliasState;
1947   ParserState state(sourceMgr, context, aliasState);
1948   if (ModuleParser(state).parseModule(*module))
1949     return nullptr;
1950 
1951   // Make sure the parse module has no other structural problems detected by
1952   // the verifier.
1953   if (failed(verify(*module)))
1954     return nullptr;
1955 
1956   return module;
1957 }
1958 
1959 /// This parses the file specified by the indicated filename and returns an
1960 /// MLIR module if it was valid.  If not, the error message is emitted through
1961 /// the error handler registered in the context, and a null pointer is returned.
1962 OwningModuleRef mlir::parseSourceFile(StringRef filename,
1963                                       MLIRContext *context) {
1964   llvm::SourceMgr sourceMgr;
1965   return parseSourceFile(filename, sourceMgr, context);
1966 }
1967 
1968 /// This parses the file specified by the indicated filename using the provided
1969 /// SourceMgr and returns an MLIR module if it was valid.  If not, the error
1970 /// message is emitted through the error handler registered in the context, and
1971 /// a null pointer is returned.
1972 OwningModuleRef mlir::parseSourceFile(StringRef filename,
1973                                       llvm::SourceMgr &sourceMgr,
1974                                       MLIRContext *context) {
1975   if (sourceMgr.getNumBuffers() != 0) {
1976     // TODO: Extend to support multiple buffers.
1977     emitError(mlir::UnknownLoc::get(context),
1978               "only main buffer parsed at the moment");
1979     return nullptr;
1980   }
1981   auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename);
1982   if (std::error_code error = file_or_err.getError()) {
1983     emitError(mlir::UnknownLoc::get(context),
1984               "could not open input file " + filename);
1985     return nullptr;
1986   }
1987 
1988   // Load the MLIR module.
1989   sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc());
1990   return parseSourceFile(sourceMgr, context);
1991 }
1992 
1993 /// This parses the program string to a MLIR module if it was valid. If not,
1994 /// it emits diagnostics and returns null.
1995 OwningModuleRef mlir::parseSourceString(StringRef moduleStr,
1996                                         MLIRContext *context) {
1997   auto memBuffer = MemoryBuffer::getMemBuffer(moduleStr);
1998   if (!memBuffer)
1999     return nullptr;
2000 
2001   SourceMgr sourceMgr;
2002   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
2003   return parseSourceFile(sourceMgr, context);
2004 }
2005