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