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