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